react-reason-editor 1.0.165 → 1.0.167

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.
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./rolldown-runtime-BeavJI0R.cjs"),t=require("./dist-2-kjLBhJ.cjs"),n=require("./tooltip-DSRLxJD_.cjs"),r=require("./editorConfig-BJeXCimT.cjs"),i=require("./reason-toolbar-skin-CGqwfyDi.cjs"),s=require("./dropdown-menu-By9VjdjW.cjs"),o=require("./Transcribe.cjs"),a=require("./dist-CN633rTi.cjs");let c=require("react"),l=e.__toESM(c,1);c=e.__toESM(c);let d=require("@tiptap/core"),h=require("@tiptap/pm/state"),u=require("react/jsx-runtime"),f=require("lucide-react"),g=require("use-sync-external-store/shim");require("use-sync-external-store/shim/with-selector");let p=require("use-voice-control/client");var m=class extends a.Observable{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const e=a.getUnixTime();null!==this.getLocalState()&&15e3<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&3e4<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&y(this,t,"timeout")},a.floor(3e3)),e.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){const t=this.clientID,n=this.meta.get(t),r=void 0===n?0:n.clock+1,i=this.states.get(t);null===e?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:r,lastUpdated:a.getUnixTime()});const s=[],o=[],c=[],l=[];null===e?l.push(t):null==i?null!=e&&s.push(t):(o.push(t),a.equalityDeep(i,e)||c.push(t)),(s.length>0||c.length>0||l.length>0)&&this.emit("change",[{added:s,updated:c,removed:l},"local"]),this.emit("update",[{added:s,updated:o,removed:l},"local"])}setLocalStateField(e,t){const n=this.getLocalState();null!==n&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}},y=(e,t,n)=>{const r=[];for(let i=0;i<t.length;i++){const n=t[i];if(e.states.has(n)){if(e.states.delete(n),n===e.clientID){const t=e.meta.get(n);e.meta.set(n,{clock:t.clock+1,lastUpdated:a.getUnixTime()})}r.push(n)}}r.length>0&&(e.emit("change",[{added:[],updated:[],removed:r},n]),e.emit("update",[{added:[],updated:[],removed:r},n]))},w=(e,t,n=e.states)=>{const r=t.length,i=a.createEncoder();a.writeVarUint(i,r);for(let s=0;s<r;s++){const r=t[s],o=n.get(r)||null,c=e.meta.get(r).clock;a.writeVarUint(i,r),a.writeVarUint(i,c),a.writeVarString(i,JSON.stringify(o))}return a.toUint8Array(i)};function b(e){return{engine:e,execute(){},isActive:()=>!1,isEnabled:()=>!1,getValue(){},subscribe:()=>()=>{}}}var v=[{kind:"button",id:"undo",label:"Undo",icon:f.Undo2,shortcut:"⌘Z"},{kind:"button",id:"redo",label:"Redo",icon:f.Redo2,shortcut:"⇧⌘Z"},{kind:"separator",id:"history-divider"},{kind:"button",id:"bold",label:"Bold",icon:f.Bold,shortcut:"⌘B"},{kind:"button",id:"italic",label:"Italic",icon:f.Italic,shortcut:"⌘I"},{kind:"button",id:"underline",label:"Underline",icon:f.Underline,shortcut:"⌘U"},{kind:"button",id:"highlight",label:"Highlight",icon:f.Highlighter,shortcut:"⌘⇧H"},{kind:"separator",id:"marks-divider"},{kind:"menu",id:"block-format",label:"Block Format",icon:f.Rows3,children:[{kind:"button",id:"paragraph",label:"Paragraph",icon:f.Pilcrow},{kind:"button",id:"heading-1",label:"Heading 1",icon:f.Heading1,shortcut:"Ctrl+Alt+1"},{kind:"button",id:"heading-2",label:"Heading 2",icon:f.Heading2,shortcut:"Ctrl+Alt+2"},{kind:"button",id:"heading-3",label:"Heading 3",icon:f.Heading3,shortcut:"Ctrl+Alt+3"},{kind:"button",id:"heading-4",label:"Heading 4",icon:f.Heading4,shortcut:"Ctrl+Alt+4"},{kind:"button",id:"heading-5",label:"Heading 5",icon:f.Heading5,shortcut:"Ctrl+Alt+5"},{kind:"button",id:"heading-6",label:"Heading 6",icon:f.Heading6,shortcut:"Ctrl+Alt+6"},{kind:"separator",id:"block-format-lists-divider"},{kind:"button",id:"bullet-list",label:"Bullet List",icon:f.List,shortcut:"Ctrl+Shift+8"},{kind:"button",id:"ordered-list",label:"Ordered List",icon:f.ListOrdered,shortcut:"Ctrl+Shift+7"},{kind:"button",id:"task-list",label:"Check List",icon:f.ListChecks,shortcut:"Ctrl+Shift+9"},{kind:"separator",id:"block-format-quote-divider"},{kind:"button",id:"blockquote",label:"Blockquote",icon:f.Quote,shortcut:"Ctrl+Shift+B"},{kind:"button",id:"code-block",label:"Code Block",icon:f.Code2,shortcut:"Ctrl+Alt+C"},{kind:"separator",id:"block-format-clear-divider"},{kind:"button",id:"clear-formatting",label:"Clear Format",icon:f.Eraser}]},{kind:"menu",id:"text-styles",label:"Text Styles",icon:f.Type,children:[{kind:"group-label",id:"text-styles-label",label:"Text Styles"},{kind:"button",id:"strike",label:"Strikethrough",icon:f.Strikethrough,shortcut:"Ctrl+Shift+S"},{kind:"button",id:"code",label:"Inline Code",icon:f.Code,shortcut:"Ctrl+E"},{kind:"button",id:"text-color",label:"Text Color",icon:f.Baseline,shortcut:"Alt+Shift+C"},{kind:"button",id:"superscript",label:"Superscript",icon:f.Superscript,shortcut:"Ctrl+."},{kind:"button",id:"subscript",label:"Subscript",icon:f.Subscript,shortcut:"Ctrl+,"},{kind:"separator",id:"text-styles-indent-divider"},{kind:"button",id:"indent",label:"Indent",icon:f.IndentIncrease},{kind:"button",id:"outdent",label:"Outdent",icon:f.IndentDecrease},{kind:"menu",id:"alignment",label:"Alignment",icon:f.AlignLeft,children:[{kind:"button",id:"align-left",label:"Align Left",icon:f.AlignLeft},{kind:"button",id:"align-center",label:"Align Center",icon:f.AlignCenter},{kind:"button",id:"align-right",label:"Align Right",icon:f.AlignRight},{kind:"button",id:"align-justify",label:"Justify",icon:f.AlignJustify}]}]},{kind:"menu",id:"insert",label:"Insert",icon:f.Plus,children:[{kind:"group-label",id:"insert-label",label:"Insert"},{kind:"button",id:"link",label:"Link",icon:f.Link2},{kind:"button",id:"emoji",label:"Emoji",icon:f.Smile},{kind:"button",id:"table",label:"Table",icon:f.Table2},{kind:"button",id:"image",label:"Image",icon:f.Image},{kind:"button",id:"columns",label:"Columns",icon:f.Columns2,shortcut:"Ctrl+Alt+G"},{kind:"button",id:"callout",label:"Callout",icon:f.Info},{kind:"button",id:"horizontal-rule",label:"Divider",icon:f.Minus,shortcut:"Ctrl+Alt+S"},{kind:"button",id:"video",label:"Video",icon:f.Video},{kind:"button",id:"math",label:"Math",icon:f.Sigma}]},{kind:"separator",id:"voice-divider"},{kind:"button",id:"transcribe",label:"Dictate",icon:f.Mic,shortcut:"Ctrl+Shift+D"},{kind:"menu",id:"table-tools",label:"Table",icon:f.Table2,visibleWhenActive:"table",children:[{kind:"group-label",id:"table-rows-label",label:"Rows"},{kind:"button",id:"table.add-row-before",label:"Insert Row Above",icon:f.Rows3},{kind:"button",id:"table.add-row-after",label:"Insert Row Below",icon:f.Rows3},{kind:"button",id:"table.delete-row",label:"Delete Row",icon:f.Trash2},{kind:"separator",id:"table-columns-divider"},{kind:"group-label",id:"table-columns-label",label:"Columns"},{kind:"button",id:"table.add-column-before",label:"Insert Column Left",icon:f.Columns2},{kind:"button",id:"table.add-column-after",label:"Insert Column Right",icon:f.Columns2},{kind:"button",id:"table.delete-column",label:"Delete Column",icon:f.Trash2},{kind:"separator",id:"table-cells-divider"},{kind:"group-label",id:"table-cells-label",label:"Cells"},{kind:"button",id:"table.merge-cells",label:"Merge Cells",icon:f.Braces},{kind:"button",id:"table.split-cell",label:"Split Cell",icon:f.Braces},{kind:"button",id:"table.toggle-header-row",label:"Toggle Header Row",icon:f.Rows3},{kind:"separator",id:"table-delete-divider"},{kind:"button",id:"table.delete",label:"Delete Table",icon:f.Trash2}]}];var _="flex items-center justify-center rounded p-1.5 text-gray-600 transition-colors dark:text-gray-300 disabled:cursor-not-allowed disabled:opacity-40 hover:enabled:bg-gray-100 dark:hover:enabled:bg-slate-800",S="bg-gray-200 text-gray-900 dark:bg-slate-700 dark:text-white",k="flex w-full cursor-pointer items-center gap-2 text-xs data-disabled:cursor-not-allowed data-disabled:opacity-40";function C({shortcut:e}){return e?(0,u.jsx)("span",{className:"ml-auto pl-4 text-[10px] tracking-widest text-gray-400 dark:text-gray-500",children:e}):null}function E({items:e,adapter:n}){return(0,u.jsx)(u.Fragment,{children:e.map(e=>{if("separator"===e.kind)return(0,u.jsx)(s.DropdownMenuSeparator,{},e.id);if("group-label"===e.kind)return(0,u.jsx)(s.DropdownMenuLabel,{className:"px-2 py-1 text-[10px] font-semibold uppercase tracking-wide text-gray-400",children:e.label},e.id);if("menu"===e.kind){const t=e.icon;return(0,u.jsxs)(s.DropdownMenuSub,{children:[(0,u.jsxs)(s.DropdownMenuSubTrigger,{className:k,children:[(0,u.jsx)(t,{className:"size-3.5 shrink-0 text-gray-500 dark:text-gray-400"}),e.label]}),(0,u.jsx)(s.DropdownMenuPortal,{children:(0,u.jsx)(s.DropdownMenuSubContent,{className:"min-w-[200px]",children:(0,u.jsx)(E,{items:e.children,adapter:n})})})]},e.id)}const r=e.icon,i=n.isActive(e.id);return(0,u.jsxs)(s.DropdownMenuItem,{"aria-pressed":i,className:t.cn(k,i&&S),"data-command":e.id,"data-state":i?"active":"inactive",disabled:!n.isEnabled(e.id),onSelect:()=>{n.execute(e.id)},children:[(0,u.jsx)(r,{className:"size-3.5 shrink-0 text-gray-500 dark:text-gray-400"}),(0,u.jsx)("span",{className:"truncate",children:e.label}),(0,u.jsx)(C,{shortcut:e.shortcut})]},e.id)})})}function A({item:e,adapter:r}){if("separator"===e.kind)return(0,u.jsx)("div",{className:"mx-1 h-5 w-px bg-gray-200 dark:bg-slate-700"});if("group-label"===e.kind)return(0,u.jsx)("span",{className:"px-1 text-[10px] font-semibold uppercase tracking-wide text-gray-400",children:e.label});if("menu"===e.kind){if(e.visibleWhenActive&&!r.isActive(e.visibleWhenActive))return null;const i=e.icon;return(0,u.jsxs)(s.DropdownMenu,{children:[(0,u.jsxs)(n.Tooltip,{children:[(0,u.jsx)(n.TooltipTrigger,{asChild:!0,children:(0,u.jsx)(s.DropdownMenuTrigger,{"aria-label":e.label,className:t.cn(_,"data-[state=open]:bg-gray-200 dark:data-[state=open]:bg-slate-700"),"data-menu":e.id,children:(0,u.jsx)(i,{className:"size-4"})})}),(0,u.jsx)(n.TooltipContent,{side:"bottom",children:e.label})]}),(0,u.jsx)(s.DropdownMenuContent,{align:"start",className:"min-w-[240px]",children:(0,u.jsx)(E,{items:e.children,adapter:r})})]})}const i=e.icon,o=r.isActive(e.id),a=r.isEnabled(e.id);return(0,u.jsxs)(n.Tooltip,{children:[(0,u.jsx)(n.TooltipTrigger,{asChild:!0,children:(0,u.jsx)("button",{"aria-label":e.label,"aria-pressed":o,className:t.cn(_,o&&S),"data-command":e.id,"data-state":o?"active":"inactive",disabled:!a,onClick:()=>{r.execute(e.id)},type:"button",children:(0,u.jsx)(i,{className:"size-4"})})}),(0,u.jsxs)(n.TooltipContent,{side:"bottom",children:[e.label,e.shortcut?(0,u.jsx)("span",{className:"ml-2 text-[10px] tracking-widest opacity-70",children:e.shortcut}):null]})]})}function x({adapter:e,items:r=v,className:i,children:s}){return function(e){const[t,n]=l.useState(0);l.useEffect(()=>{if(e.subscribe)return e.subscribe(()=>n(e=>e+1))},[e])}(e),(0,u.jsx)(n.TooltipProvider,{delayDuration:300,children:(0,u.jsxs)("div",{className:t.cn("flex flex-wrap items-center gap-0.5 border-b border-gray-200 px-2 py-1 dark:border-slate-700",i),"data-engine":e.engine,role:"toolbar",children:[r.map(t=>(0,u.jsx)(A,{adapter:e,item:t},(t.kind,t.id))),s?(0,u.jsx)("div",{className:"ml-auto flex items-center gap-1",children:s}):null]})})}var T="REASON-documents",R="reason-documents-changed";function D(){if("undefined"==typeof window)return[];try{const e=window.localStorage.getItem(T);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function O(e){"undefined"!=typeof window&&(window.localStorage.setItem(T,JSON.stringify(e)),window.dispatchEvent(new Event(R)))}function U(e){return{id:e.id,title:e.title?.trim()||"Untitled Document"}}function P(){return D().filter(e=>!e.isFolder&&!e.isDeleted&&!e.parentId).map(U)}function L(e="Untitled Document"){const t={id:`doc-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,title:e,content:"",parentId:null};return O([...D(),t]),U(t)}function M(e,t){const n=t.trim()||"Untitled Document";O(D().map(t=>t.id===e?{...t,title:n}:t))}function I(e){O(D().map(t=>t.id===e?{...t,isDeleted:!0}:t))}function N(e){if("undefined"==typeof window)return()=>{};const t=t=>{"REASON-documents"===t.key&&e()};return window.addEventListener(R,e),window.addEventListener("storage",t),()=>{window.removeEventListener(R,e),window.removeEventListener("storage",t)}}var j=function(e){return e[e.Token=0]="Token",e[e.PermissionDenied=1]="PermissionDenied",e[e.Authenticated=2]="Authenticated",e}({}),V=(e,t)=>{a.writeVarUint(e,j.Token),a.writeVarString(e,t)},F=(e,t,n,r)=>{switch(a.readVarUint(e)){case j.Token:t();break;case j.PermissionDenied:n(a.readVarString(e));break;case j.Authenticated:r(a.readVarString(e))}},B=e=>Array.from(e.entries()).map(([e,t])=>({clientId:e,...t}));function H(e,t){return e+"\0"+t}function W(e){const t=e.indexOf("\0");return-1===t?{documentName:e,sessionId:null}:{documentName:e.substring(0,t),sessionId:e.substring(t+1)}}var Y=function(e){return e[e.Connecting=0]="Connecting",e[e.Open=1]="Open",e[e.Closing=2]="Closing",e[e.Closed=3]="Closed",e}({});async function q(e){return new Promise(t=>setTimeout(t,e))}function K(e,t){let n=t.delay;if(0===n)return 0;if(t.factor&&(n*=Math.pow(t.factor,e.attemptNum-1),0!==t.maxDelay&&(n=Math.min(n,t.maxDelay))),t.jitter){const e=Math.ceil(t.minDelay);n=Math.floor(Math.random()*(Math.floor(n)-e+1))+e}return Math.round(n)}async function z(e,t){const n=function(e){return e||(e={}),{delay:void 0===e.delay?200:e.delay,initialDelay:void 0===e.initialDelay?0:e.initialDelay,minDelay:void 0===e.minDelay?0:e.minDelay,maxDelay:void 0===e.maxDelay?0:e.maxDelay,factor:void 0===e.factor?0:e.factor,maxAttempts:void 0===e.maxAttempts?3:e.maxAttempts,timeout:void 0===e.timeout?0:e.timeout,jitter:!0===e.jitter,initialJitter:!0===e.initialJitter,handleError:void 0===e.handleError?null:e.handleError,handleTimeout:void 0===e.handleTimeout?null:e.handleTimeout,beforeAttempt:void 0===e.beforeAttempt?null:e.beforeAttempt,calculateDelay:void 0===e.calculateDelay?null:e.calculateDelay}}(t);for(const o of["delay","initialDelay","minDelay","maxDelay","maxAttempts","timeout"]){const e=n[o];if(!Number.isInteger(e)||e<0)throw new Error(`Value for ${o} must be an integer greater than or equal to 0`)}if(n.factor.constructor!==Number||n.factor<0)throw new Error("Value for factor must be a number greater than or equal to 0");if(n.delay<n.minDelay)throw new Error(`delay cannot be less than minDelay (delay: ${n.delay}, minDelay: ${n.minDelay}`);const r={attemptNum:0,attemptsRemaining:n.maxAttempts?n.maxAttempts:-1,aborted:!1,abort(){r.aborted=!0}},i=n.calculateDelay||K;const s=n.calculateDelay?n.calculateDelay(r,n):n.initialDelay;if(s&&await q(s),r.attemptNum<1&&n.initialJitter){const e=i(r,n);e&&await q(e)}return async function t(){if(n.beforeAttempt&&n.beforeAttempt(r,n),r.aborted){const e=new Error("Attempt aborted");throw e.code="ATTEMPT_ABORTED",e}const s=async e=>{if(n.handleError&&await n.handleError(e,r,n),r.aborted||0===r.attemptsRemaining)throw e;r.attemptNum++;const s=i(r,n);return s&&await q(s),t()};return r.attemptsRemaining>0&&r.attemptsRemaining--,n.timeout?new Promise((t,i)=>{const o=setTimeout(()=>{if(n.handleTimeout)try{t(n.handleTimeout(r,n))}catch(e){i(e)}else{const e=new Error(`Retry timeout (attemptNum: ${r.attemptNum}, timeout: ${n.timeout})`);e.code="ATTEMPT_TIMEOUT",i(e)}},n.timeout);e(r,n).then(e=>{clearTimeout(o),t(e)}).catch(e=>{clearTimeout(o),s(e).then(t).catch(i)})}):e(r,n).catch(s)}()}var $=(e,t,n)=>((e,t,n)=>{a.writeVarUint(e,1),a.writeVarUint8Array(e,a.encodeStateAsUpdate(t,n))})(t,n,a.readVarUint8Array(e)),J=(e,t,n,r)=>{try{a.applyUpdate(t,a.readVarUint8Array(e),n)}catch(i){null!=r&&r(i)}},Q=J,G=class{constructor(){this.callbacks={}}on(e,t){return this.callbacks[e]||(this.callbacks[e]=[]),this.callbacks[e].push(t),this}emit(e,...t){const n=this.callbacks[e];return n&&n.forEach(e=>e.apply(this,t)),this}off(e,t){const n=this.callbacks[e];return n&&(t?this.callbacks[e]=n.filter(e=>e!==t):delete this.callbacks[e]),this}removeAllListeners(){this.callbacks={}}},X=class{constructor(e){this.data=e,this.encoder=a.createEncoder(),this.decoder=a.createDecoder(new Uint8Array(this.data))}peekVarString(){return a.peekVarString(this.decoder)}readVarUint(){return a.readVarUint(this.decoder)}readVarString(){return a.readVarString(this.decoder)}readVarUint8Array(){return a.readVarUint8Array(this.decoder)}writeVarUint(e){return a.writeVarUint(this.encoder,e)}writeVarString(e){return a.writeVarString(this.encoder,e)}writeVarUint8Array(e){return a.writeVarUint8Array(this.encoder,e)}length(){return a.length(this.encoder)}},Z=function(e){return e[e.Sync=0]="Sync",e[e.Awareness=1]="Awareness",e[e.Auth=2]="Auth",e[e.QueryAwareness=3]="QueryAwareness",e[e.Stateless=5]="Stateless",e[e.CLOSE=7]="CLOSE",e[e.SyncStatus=8]="SyncStatus",e[e.Ping=9]="Ping",e[e.Pong=10]="Pong",e}({}),ee=function(e){return e.Connecting="connecting",e.Connected="connected",e.Disconnected="disconnected",e}({}),te=class{constructor(){this.encoder=a.createEncoder()}get(e){return e.encoder}toUint8Array(){return a.toUint8Array(this.encoder)}},ne=class extends te{constructor(...e){super(...e),this.type=Z.CLOSE,this.description="Ask the server to close the connection"}get(e){return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),this.encoder}},re=class e extends G{static{this.DEDUPLICATABLE_TYPES=new Set([Z.Awareness,Z.QueryAwareness])}constructor(e){super(),this.messageQueue=[],this.configuration={url:"",autoConnect:!0,preserveTrailingSlash:!1,document:void 0,WebSocketPolyfill:void 0,messageReconnectTimeout:3e4,delay:1e3,initialDelay:0,factor:2,maxAttempts:0,minDelay:1e3,maxDelay:3e4,jitter:!0,timeout:0,onOpen:()=>null,onConnect:()=>null,onMessage:()=>null,onOutgoingMessage:()=>null,onStatus:()=>null,onDisconnect:()=>null,onClose:()=>null,onDestroy:()=>null,onAwarenessUpdate:()=>null,onAwarenessChange:()=>null,handleTimeout:null,providerMap:new Map},this.webSocket=null,this.webSocketHandlers={},this.shouldConnect=!0,this.status=ee.Disconnected,this.lastMessageReceived=0,this.identifier=0,this.intervals={connectionChecker:null},this.connectionAttempt=null,this.receivedOnOpenPayload=void 0,this.closeTries=0,this.setConfiguration(e),this.configuration.WebSocketPolyfill=e.WebSocketPolyfill?e.WebSocketPolyfill:WebSocket,this.on("open",this.configuration.onOpen),this.on("open",this.onOpen.bind(this)),this.on("connect",this.configuration.onConnect),this.on("message",this.configuration.onMessage),this.on("outgoingMessage",this.configuration.onOutgoingMessage),this.on("status",this.configuration.onStatus),this.on("disconnect",this.configuration.onDisconnect),this.on("close",this.configuration.onClose),this.on("destroy",this.configuration.onDestroy),this.on("awarenessUpdate",this.configuration.onAwarenessUpdate),this.on("awarenessChange",this.configuration.onAwarenessChange),this.on("close",this.onClose.bind(this)),this.on("message",this.onMessage.bind(this)),this.intervals.connectionChecker=setInterval(this.checkConnection.bind(this),this.configuration.messageReconnectTimeout/10),this.shouldConnect&&this.connect()}async onOpen(e){this.status=ee.Connected,this.emit("status",{status:ee.Connected}),this.cancelWebsocketRetry=void 0,this.receivedOnOpenPayload=e}attach(e){const t=e.effectiveName,n=this.configuration.providerMap.get(t);if(n&&n!==e&&n.isAuthenticated)throw new Error(`Cannot attach two providers with the same effective name "${t}". Use sessionAwareness: true to multiplex providers with the same document name.`);this.configuration.providerMap.set(t,e),this.status===ee.Disconnected&&this.shouldConnect&&this.connect(),this.receivedOnOpenPayload&&this.status===ee.Connected&&e.onOpen(this.receivedOnOpenPayload)}detach(e){const t=e.effectiveName;this.configuration.providerMap.has(t)&&(e.send(ne,{documentName:t}),this.configuration.providerMap.delete(t))}setConfiguration(e={}){this.configuration={...this.configuration,...e},this.configuration.autoConnect||(this.shouldConnect=!1)}async connect(){if(this.status===ee.Connected)return;this.cancelWebsocketRetry&&(this.cancelWebsocketRetry(),this.cancelWebsocketRetry=void 0),this.receivedOnOpenPayload=void 0,this.shouldConnect=!0;const{retryPromise:e,cancelFunc:t}=(()=>{let e=!1;return{retryPromise:z(this.createWebSocketConnection.bind(this),{delay:this.configuration.delay,initialDelay:this.configuration.initialDelay,factor:this.configuration.factor,maxAttempts:this.configuration.maxAttempts,minDelay:this.configuration.minDelay,maxDelay:this.configuration.maxDelay,jitter:this.configuration.jitter,timeout:this.configuration.timeout,handleTimeout:this.configuration.handleTimeout,beforeAttempt:t=>{this.shouldConnect&&!e||t.abort()}}).catch(e=>{if(e&&"ATTEMPT_ABORTED"!==e.code)throw e}),cancelFunc:()=>{e=!0}}})();return this.cancelWebsocketRetry=t,e}attachWebSocketListeners(e,t){const{identifier:n}=e;this.webSocketHandlers[n]={message:e=>this.emit("message",e),close:e=>this.emit("close",{event:e}),open:e=>this.emit("open",e),error:e=>{t(e)}};const r=this.webSocketHandlers[e.identifier];Object.keys(r).forEach(t=>{e.addEventListener(t,r[t])})}cleanupWebSocket(){if(!this.webSocket)return;const{identifier:e}=this.webSocket,t=this.webSocketHandlers[e];Object.keys(t).forEach(n=>{this.webSocket?.removeEventListener(n,t[n]),delete this.webSocketHandlers[e]}),this.webSocket.close(),this.webSocket=null}createWebSocketConnection(){return new Promise((e,t)=>{this.webSocket&&(this.messageQueue=[],this.cleanupWebSocket()),this.lastMessageReceived=0,this.identifier+=1;const n=new this.configuration.WebSocketPolyfill(this.url);n.binaryType="arraybuffer",n.identifier=this.identifier,this.attachWebSocketListeners(n,t),this.webSocket=n,this.status=ee.Connecting,this.emit("status",{status:ee.Connecting}),this.connectionAttempt={resolve:e,reject:t}})}onMessage(e){this.resolveConnectionAttempt(),this.lastMessageReceived=a.getUnixTime();const t=new Uint8Array(e.data);if(1===t.length&&t[0]===Z.Ping)return void this.sendPong();const n=new X(t).peekVarString();this.configuration.providerMap.get(n)?.onMessage(e)}sendPong(){const e=a.createEncoder();a.writeVarUint(e,Z.Pong),this.send(a.toUint8Array(e))}resolveConnectionAttempt(){this.connectionAttempt&&(this.connectionAttempt.resolve(),this.connectionAttempt=null,this.status=ee.Connected,this.emit("status",{status:ee.Connected}),this.emit("connect"),this.messageQueue.forEach(e=>this.send(e)),this.messageQueue=[])}stopConnectionAttempt(){this.connectionAttempt=null}rejectConnectionAttempt(){this.connectionAttempt?.reject(),this.connectionAttempt=null}checkConnection(){this.status===ee.Connected&&this.lastMessageReceived&&(this.configuration.messageReconnectTimeout>=a.getUnixTime()-this.lastMessageReceived||(this.closeTries+=1,this.closeTries>2?(this.onClose({event:{code:4408,reason:"forced"}}),this.closeTries=0):(this.webSocket?.close(),this.messageQueue=[])))}get serverUrl(){if(this.configuration.preserveTrailingSlash)return this.configuration.url;let e=this.configuration.url;for(;"/"===e[e.length-1];)e=e.slice(0,e.length-1);return e}get url(){return this.serverUrl}disconnect(){if(this.shouldConnect=!1,null!==this.webSocket)try{this.webSocket.close(),this.messageQueue=[]}catch(e){}}parseQueuedMessage(e){try{const t=a.createDecoder(e);return{documentName:a.readVarString(t),messageType:a.readVarUint(t)}}catch{return null}}addToQueue(t){if(t instanceof Uint8Array){const n=this.parseQueuedMessage(t);n&&e.DEDUPLICATABLE_TYPES.has(n.messageType)&&(this.messageQueue=this.messageQueue.filter(e=>{if(!(e instanceof Uint8Array))return!0;const t=this.parseQueuedMessage(e);return!t||!(t.documentName===n.documentName&&t.messageType===n.messageType)}))}this.messageQueue.push(t)}send(e){this.webSocket?.readyState===Y.Open?this.webSocket.send(e):this.addToQueue(e)}onClose({event:e}){this.closeTries=0,this.cleanupWebSocket(),this.connectionAttempt&&this.rejectConnectionAttempt(),this.status=ee.Disconnected,this.emit("status",{status:ee.Disconnected}),this.emit("disconnect",{event:e}),!this.cancelWebsocketRetry&&this.shouldConnect&&setTimeout(()=>{this.connect()},this.configuration.delay)}destroy(){this.emit("destroy"),clearInterval(this.intervals.connectionChecker),this.stopConnectionAttempt(),this.disconnect(),this.removeAllListeners(),this.cleanupWebSocket()}},ie=class{constructor(e){this.message=e}apply(e,t){const{message:n}=this,r=n.readVarUint(),i=n.length();switch(r){case Z.Sync:this.applySyncMessage(e,t);break;case Z.Awareness:this.applyAwarenessMessage(e);break;case Z.Auth:this.applyAuthMessage(e);break;case Z.QueryAwareness:this.applyQueryAwarenessMessage(e);break;case Z.Stateless:e.receiveStateless(a.readVarString(n.decoder));break;case Z.SyncStatus:this.applySyncStatusMessage(e,1===a.readVarInt(n.decoder));break;case Z.CLOSE:{const t={code:1e3,reason:a.readVarString(n.decoder)};e.onClose(),e.configuration.onClose({event:t}),e.forwardClose({event:t});break}}n.length()>i+1&&e.send(te,{encoder:n.encoder})}applySyncMessage(e,t){const{message:n}=this;n.writeVarUint(Z.Sync);const r=((e,t,n,r,i)=>{const s=a.readVarUint(e);switch(s){case 0:$(e,t,n);break;case 1:J(e,n,r,i);break;case 2:Q(e,n,r,i);break;default:throw new Error("Unknown message type")}return s})(n.decoder,n.encoder,e.document,e);t&&1===r&&(e.synced=!0)}applySyncStatusMessage(e,t){t&&e.decrementUnsyncedChanges()}applyAwarenessMessage(e){if(!e.awareness)return;const{message:t}=this;((e,t,n)=>{const r=a.createDecoder(t),i=a.getUnixTime(),s=[],o=[],c=[],l=[],d=a.readVarUint(r);for(let h=0;h<d;h++){const t=a.readVarUint(r);let n=a.readVarUint(r);const d=JSON.parse(a.readVarString(r)),h=e.meta.get(t),u=e.states.get(t),f=void 0===h?0:h.clock;(f<n||f===n&&null===d&&e.states.has(t))&&(null===d?t===e.clientID&&null!=e.getLocalState()?n++:e.states.delete(t):e.states.set(t,d),e.meta.set(t,{clock:n,lastUpdated:i}),void 0===h&&null!==d?s.push(t):void 0!==h&&null===d?l.push(t):null!==d&&(a.equalityDeep(d,u)||c.push(t),o.push(t)))}(s.length>0||c.length>0||l.length>0)&&e.emit("change",[{added:s,updated:c,removed:l},n]),(s.length>0||o.length>0||l.length>0)&&e.emit("update",[{added:s,updated:o,removed:l},n])})(e.awareness,t.readVarUint8Array(),e)}applyAuthMessage(e){const{message:t}=this;F(t.decoder,e.sendToken.bind(e),e.permissionDeniedHandler.bind(e),e.authenticatedHandler.bind(e))}applyQueryAwarenessMessage(e){if(!e.awareness)return;const{message:t}=this;t.writeVarUint(Z.Awareness),t.writeVarUint8Array(w(e.awareness,Array.from(e.awareness.getStates().keys())))}},se=class{constructor(e,t={}){this.message=new e,this.encoder=this.message.get(t)}create(){return a.toUint8Array(this.encoder)}send(e){e?.send(this.create())}},oe=class extends te{constructor(...e){super(...e),this.type=Z.Auth,this.description="Authentication"}get(e){if(void 0===e.token)throw new Error("The authentication message requires `token` as an argument.");return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),V(this.encoder,e.token),a.writeVarString(this.encoder,"4.6.0"),this.encoder}},ae=class extends te{constructor(...e){super(...e),this.type=Z.Awareness,this.description="Awareness states update"}get(e){if(void 0===e.awareness)throw new Error("The awareness message requires awareness as an argument");if(void 0===e.clients)throw new Error("The awareness message requires clients as an argument");let t;return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),t=void 0===e.states?w(e.awareness,e.clients):w(e.awareness,e.clients,e.states),a.writeVarUint8Array(this.encoder,t),this.encoder}},ce=class extends te{constructor(...e){super(...e),this.type=Z.Stateless,this.description="A stateless message"}get(e){return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),a.writeVarString(this.encoder,e.payload??""),this.encoder}},le=class extends te{constructor(...e){super(...e),this.type=Z.Sync,this.description="First sync step"}get(e){if(void 0===e.document)throw new Error("The sync step one message requires document as an argument");return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),((e,t)=>{a.writeVarUint(e,0);const n=a.encodeStateVector(t);a.writeVarUint8Array(e,n)})(this.encoder,e.document),this.encoder}},de=class extends te{constructor(...e){super(...e),this.type=Z.Sync,this.description="A document update"}get(e){var t,n;return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),t=this.encoder,n=e.update,a.writeVarUint(t,2),a.writeVarUint8Array(t,n),this.encoder}},he=class extends Error{constructor(...e){super(...e),this.code=1001}},ue=class extends G{get effectiveName(){return this.configuration.sessionAwareness?H(this.configuration.name,this.sessionId):this.configuration.name}constructor(e){super(),this.configuration={name:"",document:void 0,awareness:void 0,token:null,sessionAwareness:!1,forceSyncInterval:!1,flushDelay:!1,onAuthenticated:()=>null,onAuthenticationFailed:()=>null,onOpen:()=>null,onConnect:()=>null,onMessage:()=>null,onOutgoingMessage:()=>null,onSynced:()=>null,onStatus:()=>null,onDisconnect:()=>null,onClose:()=>null,onDestroy:()=>null,onAwarenessUpdate:()=>null,onAwarenessChange:()=>null,onStateless:()=>null,onUnsyncedChanges:()=>null},this.isSynced=!1,this.unsyncedChanges=0,this.isAuthenticated=!1,this.authorizedScope=void 0,this.manageSocket=!1,this._isAttached=!1,this.pendingUpdates=[],this.pendingAwarenessClients=new Set,this.flushTimeout=null,this.sessionId=Math.random().toString(36).slice(2),this.intervals={forceSync:null},this.boundDocumentUpdateHandler=this.documentUpdateHandler.bind(this),this.boundAwarenessUpdateHandler=this.awarenessUpdateHandler.bind(this),this.boundPageHide=this.pageHide.bind(this),this.boundOnOpen=this.onOpen.bind(this),this.boundOnClose=this.onClose.bind(this),this.forwardConnect=()=>this.emit("connect"),this.forwardStatus=e=>this.emit("status",e),this.forwardClose=e=>this.emit("close",e),this.forwardDisconnect=e=>this.emit("disconnect",e),this.forwardDestroy=()=>this.emit("destroy"),this.setConfiguration(e),this.configuration.document=e.document?e.document:new a.Doc,this.configuration.awareness=void 0!==e.awareness?e.awareness:new m(this.document),this.on("open",this.configuration.onOpen),this.on("message",this.configuration.onMessage),this.on("outgoingMessage",this.configuration.onOutgoingMessage),this.on("synced",this.configuration.onSynced),this.on("destroy",this.configuration.onDestroy),this.on("awarenessUpdate",this.configuration.onAwarenessUpdate),this.on("awarenessChange",this.configuration.onAwarenessChange),this.on("stateless",this.configuration.onStateless),this.on("unsyncedChanges",this.configuration.onUnsyncedChanges),this.on("authenticated",this.configuration.onAuthenticated),this.on("authenticationFailed",this.configuration.onAuthenticationFailed),this.awareness?.on("update",()=>{this.emit("awarenessUpdate",{states:B(this.awareness.getStates())})}),this.awareness?.on("change",()=>{this.emit("awarenessChange",{states:B(this.awareness.getStates())})}),this.document.on("update",this.boundDocumentUpdateHandler),this.awareness?.on("update",this.boundAwarenessUpdateHandler),this.registerEventListeners(),this.configuration.forceSyncInterval&&"number"==typeof this.configuration.forceSyncInterval&&(this.intervals.forceSync=setInterval(this.forceSync.bind(this),this.configuration.forceSyncInterval)),this.manageSocket&&this.attach()}setConfiguration(e={}){e.websocketProvider||(this.manageSocket=!0,this.configuration.websocketProvider=new re(e)),this.configuration={...this.configuration,...e}}get document(){return this.configuration.document}get isAttached(){return this._isAttached}get awareness(){return this.configuration.awareness}get hasUnsyncedChanges(){return this.unsyncedChanges>0}resetUnsyncedChanges(){this.unsyncedChanges=1,this.emit("unsyncedChanges",{number:this.unsyncedChanges})}incrementUnsyncedChanges(){this.unsyncedChanges+=1,this.emit("unsyncedChanges",{number:this.unsyncedChanges})}decrementUnsyncedChanges(){this.unsyncedChanges>0&&(this.unsyncedChanges-=1),0===this.unsyncedChanges&&(this.synced=!0),this.emit("unsyncedChanges",{number:this.unsyncedChanges})}forceSync(){this.resetUnsyncedChanges(),this.send(le,{document:this.document,documentName:this.effectiveName})}pageHide(){this.awareness&&y(this.awareness,[this.document.clientID],"page hide")}registerEventListeners(){"undefined"!=typeof window&&"addEventListener"in window&&window.addEventListener("pagehide",this.boundPageHide)}sendStateless(e){this.send(ce,{documentName:this.effectiveName,payload:e})}async sendToken(){let e;try{e=await this.getToken()}catch(t){return void this.permissionDeniedHandler(`Failed to get token during sendToken(): ${t}`)}this.send(oe,{token:e??"",documentName:this.effectiveName})}get batchingEnabled(){return!!this.configuration.flushDelay&&"number"==typeof this.configuration.flushDelay}documentUpdateHandler(e,t){if(t!==this){if(!this.batchingEnabled)return this.incrementUnsyncedChanges(),void this.send(de,{update:e,documentName:this.effectiveName});0===this.pendingUpdates.length&&this.incrementUnsyncedChanges(),this.pendingUpdates.push(e),this.scheduleFlush()}}awarenessUpdateHandler({added:e,updated:t,removed:n},r){if(r===this)return;const i=e.concat(t).concat(n);if(this.batchingEnabled){for(const e of i)this.pendingAwarenessClients.add(e);this.scheduleFlush()}else this.send(ae,{awareness:this.awareness,clients:i,documentName:this.effectiveName})}scheduleFlush(){null===this.flushTimeout&&(this.flushTimeout=setTimeout(()=>{this.flushTimeout=null,this.flushPendingUpdates()},this.configuration.flushDelay))}flushPendingUpdates(){if(null!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.pendingUpdates.length>0){const e=1===this.pendingUpdates.length?this.pendingUpdates[0]:a.mergeUpdates(this.pendingUpdates);this.pendingUpdates=[],this.send(de,{update:e,documentName:this.effectiveName})}if(this.pendingAwarenessClients.size>0){const e=Array.from(this.pendingAwarenessClients);this.pendingAwarenessClients.clear(),this.send(ae,{awareness:this.awareness,clients:e,documentName:this.effectiveName})}}get synced(){return this.isSynced}set synced(e){this.isSynced!==e&&(this.isSynced=e,e&&this.emit("synced",{state:e}))}receiveStateless(e){this.emit("stateless",{payload:e})}async connect(){if(this.manageSocket)return this.configuration.websocketProvider.connect()}disconnect(){if(this.manageSocket)return this.configuration.websocketProvider.disconnect()}async onOpen(e){this.isAuthenticated=!1,this.emit("open",{event:e}),await this.sendToken(),this.startSync()}async getToken(){return"function"==typeof this.configuration.token?await this.configuration.token():this.configuration.token}startSync(){this.resetUnsyncedChanges(),this.send(le,{document:this.document,documentName:this.effectiveName}),this.awareness&&null!==this.awareness.getLocalState()&&this.send(ae,{awareness:this.awareness,clients:[this.document.clientID],documentName:this.effectiveName})}send(e,t){if(!this._isAttached)return;const n=new se(e,t);this.emit("outgoingMessage",{message:n.message}),n.send(this.configuration.websocketProvider)}onMessage(e){const t=new X(e.data),{documentName:n}=W(t.readVarString());t.writeVarString(this.effectiveName),this.emit("message",{event:e,message:new X(e.data)}),new ie(t).apply(this,!0)}onClose(){this.isAuthenticated=!1,this.synced=!1,null!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.pendingUpdates=[],this.pendingAwarenessClients.clear(),this.awareness&&y(this.awareness,Array.from(this.awareness.getStates().keys()).filter(e=>e!==this.document.clientID),this)}destroy(){this.emit("destroy"),this.intervals.forceSync&&clearInterval(this.intervals.forceSync),this.awareness&&(y(this.awareness,[this.document.clientID],"provider destroy"),this.awareness.off("update",this.boundAwarenessUpdateHandler),this.awareness.destroy()),this.flushPendingUpdates(),this.document.off("update",this.boundDocumentUpdateHandler),this.removeAllListeners(),this.detach(),this.manageSocket&&this.configuration.websocketProvider.destroy(),"undefined"!=typeof window&&"removeEventListener"in window&&window.removeEventListener("pagehide",this.boundPageHide)}detach(){this.configuration.websocketProvider.off("connect",this.configuration.onConnect),this.configuration.websocketProvider.off("connect",this.forwardConnect),this.configuration.websocketProvider.off("status",this.forwardStatus),this.configuration.websocketProvider.off("status",this.configuration.onStatus),this.configuration.websocketProvider.off("open",this.boundOnOpen),this.configuration.websocketProvider.off("close",this.boundOnClose),this.configuration.websocketProvider.off("close",this.configuration.onClose),this.configuration.websocketProvider.off("close",this.forwardClose),this.configuration.websocketProvider.off("disconnect",this.configuration.onDisconnect),this.configuration.websocketProvider.off("disconnect",this.forwardDisconnect),this.configuration.websocketProvider.off("destroy",this.configuration.onDestroy),this.configuration.websocketProvider.off("destroy",this.forwardDestroy),this.configuration.websocketProvider.detach(this),this._isAttached=!1}attach(){this._isAttached||(this.configuration.websocketProvider.on("connect",this.configuration.onConnect),this.configuration.websocketProvider.on("connect",this.forwardConnect),this.configuration.websocketProvider.on("status",this.configuration.onStatus),this.configuration.websocketProvider.on("status",this.forwardStatus),this.configuration.websocketProvider.on("open",this.boundOnOpen),this.configuration.websocketProvider.on("close",this.boundOnClose),this.configuration.websocketProvider.on("close",this.configuration.onClose),this.configuration.websocketProvider.on("close",this.forwardClose),this.configuration.websocketProvider.on("disconnect",this.configuration.onDisconnect),this.configuration.websocketProvider.on("disconnect",this.forwardDisconnect),this.configuration.websocketProvider.on("destroy",this.configuration.onDestroy),this.configuration.websocketProvider.on("destroy",this.forwardDestroy),this.configuration.websocketProvider.attach(this),this._isAttached=!0)}permissionDeniedHandler(e){this.emit("authenticationFailed",{reason:e}),this.isAuthenticated=!1}authenticatedHandler(e){this.isAuthenticated=!0,this.authorizedScope=e,this.emit("authenticated",{scope:e})}setAwarenessField(e,t){if(!this.awareness)throw new he(`Cannot set awareness field "${e}" to ${JSON.stringify(t)}. You have disabled Awareness for this provider by explicitly passing awareness: null in the provider configuration.`);this.awareness.setLocalStateField(e,t)}},fe="reason-editor";function ge(e,t){if(!t)throw new Error("collaborationRoom: documentId is required");return`${fe}:${e}:${t}`}function pe(){return"undefined"!=typeof process&&(process.env.NEXT_PUBLIC_HOCUSPOCUS_URL??process.env.VITE_HOCUSPOCUS_URL)||"ws://127.0.0.1:1234"}function me({engine:e,documentId:t,token:n,url:r=pe(),onSynced:i}){const s=ge(e,t),o=new a.Doc,c=new ue({document:o,name:s,token:n,url:r,onSynced:()=>i?.(!0)});return{room:s,ydoc:o,provider:c,destroy(){c.destroy(),o.destroy()}}}function ye({documentId:e,token:t,url:n=pe()}){const r=ge("plate",e);return[{type:"hocuspocus",options:{name:r,token:t,url:n}},{type:"indexeddb",options:{docName:r}}]}var we=["#e11d48","#0891b2","#7c3aed","#ea580c","#16a34a","#2563eb","#db2777","#ca8a04"];function be(e){let t=0;for(let n=0;n<e.length;n++)t=31*t+e.charCodeAt(n)|0;return we[Math.abs(t)%we.length]}var ve={bold:"bold",italic:"italic",underline:"underline",strike:"strike",code:"code",superscript:"superscript",subscript:"subscript",highlight:"highlight","text-color":"textStyle"},_e={paragraph:{name:"paragraph"},"heading-1":{name:"heading",attrs:{level:1}},"heading-2":{name:"heading",attrs:{level:2}},"heading-3":{name:"heading",attrs:{level:3}},"heading-4":{name:"heading",attrs:{level:4}},"heading-5":{name:"heading",attrs:{level:5}},"heading-6":{name:"heading",attrs:{level:6}},blockquote:{name:"blockquote"},"code-block":{name:"codeBlock"},"bullet-list":{name:"bulletList"},"ordered-list":{name:"orderedList"},"task-list":{name:"taskList"},table:{name:"table"},callout:{name:"callout"},columns:{name:"columns"}},Se={"align-left":"left","align-center":"center","align-right":"right","align-justify":"justify"},ke={"table.add-row-before":"addRowBefore","table.add-row-after":"addRowAfter","table.delete-row":"deleteRow","table.add-column-before":"addColumnBefore","table.add-column-after":"addColumnAfter","table.delete-column":"deleteColumn","table.merge-cells":"mergeCells","table.split-cell":"splitCell","table.toggle-header-row":"toggleHeaderRow","table.delete":"deleteTable"};function Ce(e,t){return e?.value?e.value:"undefined"!=typeof window?window.prompt(t)??void 0:void 0}function Ee(e){return{engine:"tiptap",execute(t,n){!function(e,t,n){const r=()=>e.chain().focus(),i=e.commands,s=ke[t];if(s)return void r()[s]?.().run();const o=Se[t];if(o)r().setTextAlign?.(o).run();else switch(t){case"undo":return void i.undo?.();case"redo":return void i.redo?.();case"bold":return void r().toggleBold().run();case"italic":return void r().toggleItalic().run();case"underline":return void r().toggleUnderline?.().run();case"strike":return void r().toggleStrike().run();case"code":return void r().toggleCode().run();case"superscript":return void r().toggleSuperscript?.().run();case"subscript":return void r().toggleSubscript?.().run();case"text-color":{const t=n?.value??"#ef4444";return void(e.isActive("textStyle",{color:t})?r().unsetColor?.().run():r().setColor?.(t).run())}case"highlight":{const t=n?.value??"#fde047";return void(e.isActive("highlight")?r().unsetHighlight?.().run():r().setHighlight?.({color:t}).run())}case"clear-formatting":return void r().clearNodes().unsetAllMarks().run();case"paragraph":return void r().setParagraph().run();case"heading-1":case"heading-2":case"heading-3":case"heading-4":case"heading-5":case"heading-6":{const e=Number(t.slice(8));return void r().toggleHeading({level:e}).run()}case"blockquote":return void r().toggleBlockquote().run();case"code-block":return void r().toggleCodeBlock().run();case"bullet-list":return void r().toggleBulletList().run();case"ordered-list":return void r().toggleOrderedList().run();case"task-list":return void r().toggleTaskList?.().run();case"indent":return void r().indent?.().run();case"outdent":return void r().outdent?.().run();case"link":{const e=Ce(n,"Link URL");if(!e)return;return void r().extendMarkRange("link").setLink({href:e}).run()}case"image":{const e=Ce(n,"Image URL");if(!e)return;const t=r();return void("function"==typeof t.setImageInline?t.setImageInline({src:e}).run():t.setImage?.({src:e}).run())}case"video":{const e=Ce(n,"Video URL");if(!e)return;return void r().setVideo?.({src:e}).run()}case"table":return void r().insertTable?.({rows:3,cols:3,withHeaderRow:!0}).run();case"horizontal-rule":return void r().setHorizontalRule().run();case"emoji":return void r().insertContent(":").run();case"math":return void r().setKatex?.({text:n?.value??""}).run();case"callout":return void r().setCallout?.({type:"note",title:"",body:""}).run();case"columns":return void r().insertColumns?.({cols:2}).run();case"transcribe":return void i.toggleTranscribe?.();default:;}}(e,t,n)},isActive:t=>function(e,t){const n=Se[t];if(n)return e.isActive({textAlign:n});const r=_e[t];if(r)return e.isActive(r.name,r.attrs);const i=ve[t];return i?"text-color"===t?!!e.getAttributes("textStyle").color:e.isActive(i):"link"===t?e.isActive("link"):"transcribe"===t&&!!o.getTranscribeStorage(e)?.listening}(e,t),isEnabled:t=>function(e,t){const n=function(e){switch(e){case"highlight":return"highlight";case"text-color":return"color";case"superscript":return"superscript";case"subscript":return"subscript";case"task-list":return"taskList";case"link":return"link";case"image":return"image";case"video":return"video";case"table":return"table";case"emoji":return"emoji";case"math":return"katex";case"callout":return"callout";case"columns":return"columns";case"transcribe":return"transcribe";case"indent":case"outdent":return"indent";case"align-left":case"align-center":case"align-right":case"align-justify":return"textAlign";default:return}}(t);if(n&&!function(e,t){return e.extensionManager.extensions.some(e=>e.name===t)}(e,n))return!1;if("undo"===t)return e.can().undo();if("redo"===t)return e.can().redo();if("transcribe"===t)return(0,p.isTranscriptionSupported)();const r=ke[t];return r?!!e.isActive("table")&&Boolean(e.can()[r]?.()):e.isEditable}(e,t),getValue:t=>function(e,t){return"text-color"===t?e.getAttributes("textStyle").color:"highlight"===t?e.getAttributes("highlight").color:"link"===t?e.getAttributes("link").href:void 0}(e,t),subscribe(t){e.on("transaction",t),e.on("selectionUpdate",t);const n=o.subscribeTranscribe(e,t);return()=>{e.off("transaction",t),e.off("selectionUpdate",t),n()}}}}function Ae(e){return"string"==typeof e&&/^#[0-9a-fA-F]{6}$/.test(e)}var xe=e=>Array.from(e.entries()).map(([e,t])=>t&&t.user?{clientId:e,...t.user}:{clientId:e}),Te=()=>null,Re=e=>({...e,color:Ae(e.color)?e.color:"transparent"}),De=d.Extension.create({name:"collaborationCaret",priority:999,addOptions:()=>({provider:null,user:{name:null,color:null},render:e=>{const t=document.createElement("span"),{color:n}=Re(e);t.classList.add("collaboration-carets__caret"),t.style.borderColor=n;const r=document.createElement("div");return r.classList.add("collaboration-carets__label"),r.style.backgroundColor=n,r.insertBefore(document.createTextNode(e.name),null),t.insertBefore(r,null),t},selectionRender:e=>Ae(e.color)?a.defaultSelectionBuilder(e):{},onUpdate:Te}),onCreate(){if(this.options.onUpdate,!this.options.provider)throw new Error('The "provider" option is required for the CollaborationCaret extension')},addStorage:()=>({users:[]}),addCommands(){return{updateUser:e=>()=>(this.options.provider.awareness.setLocalStateField("user",e),!0),user:e=>({editor:t})=>t.commands.updateUser(e)}},addProseMirrorPlugins(){const{provider:e}=this.options,t=this.storage,n=this.options.user;return[new h.Plugin({key:new h.PluginKey("collaborationCaretAwarenessListener"),view:()=>{const r=()=>{t.users=xe(e.awareness.states)};return e.awareness.setLocalStateField("user",n),t.users=xe(e.awareness.states),e.awareness.on("update",r),{destroy:()=>{e.awareness.off("update",r),t.users=[]}}}}),a.yCursorPlugin(e.awareness,{cursorBuilder:e=>this.options.render(Re(e)),selectionBuilder:e=>this.options.selectionRender(Re(e))})]}});var Oe={bold:i.KEYS.bold,italic:i.KEYS.italic,underline:i.KEYS.underline,strike:i.KEYS.strikethrough,code:i.KEYS.code,superscript:i.KEYS.sup,subscript:i.KEYS.sub,highlight:i.KEYS.highlight,"text-color":i.KEYS.color},Ue={superscript:i.KEYS.sub,subscript:i.KEYS.sup},Pe={paragraph:i.KEYS.p,"heading-1":i.KEYS.h1,"heading-2":i.KEYS.h2,"heading-3":i.KEYS.h3,"heading-4":i.KEYS.h4,"heading-5":i.KEYS.h5,"heading-6":i.KEYS.h6,blockquote:i.KEYS.blockquote},Le={"bullet-list":i.ListStyleType.Disc,"ordered-list":i.ListStyleType.Decimal,"task-list":i.KEYS.listTodo},Me={"bullet-list":[i.ListStyleType.Disc,i.ListStyleType.Circle,i.ListStyleType.Square],"ordered-list":[i.ListStyleType.Decimal,i.ListStyleType.LowerAlpha,i.ListStyleType.UpperAlpha,i.ListStyleType.LowerRoman,i.ListStyleType.UpperRoman],"task-list":[i.KEYS.listTodo]},Ie={"align-left":"left","align-center":"center","align-right":"right","align-justify":"justify"},Ne=new Set(["table.add-row-before","table.add-row-after","table.delete-row","table.add-column-before","table.add-column-after","table.delete-column","table.merge-cells","table.split-cell","table.toggle-header-row","table.delete"]);function je(e){return!!e.selection&&Boolean(i.getTableAbove(e))}function Ve(e){if(!je(e))return{canMerge:!1,canSplit:!1};const t=i.getSelectedCellEntries(e);if(!t?.length)return{canMerge:!1,canSplit:!1};const n=t.map(([e])=>e);if(n.length>1){const{maxCol:t,maxRow:r,minCol:s,minRow:o}=i.getSelectedCellsBoundingBox(e,n),a=n.reduce((e,t)=>e+i.getColSpan(t)*i.getRowSpan(t),0)===(t-s+1)*(r-o+1);return{canMerge:e.api.isExpanded()&&a,canSplit:!1}}const[r]=n;return{canMerge:!1,canSplit:i.getColSpan(r)>1||i.getRowSpan(r)>1}}function Fe(e,t){return e?.value?e.value:"undefined"!=typeof window?window.prompt(t)??void 0:void 0}function Be(e,t){const n=function(e){if(Ne.has(e)||"table"===e)return i.KEYS.table;switch(e){case"highlight":return i.KEYS.highlight;case"text-color":return i.KEYS.color;case"link":return i.KEYS.link;case"image":return i.KEYS.img;case"video":return i.KEYS.video;case"math":return i.KEYS.equation;case"callout":return i.KEYS.callout;case"columns":return i.KEYS.columnGroup;case"transcribe":return"transcribe";case"emoji":return i.KEYS.emoji;case"code-block":return i.KEYS.codeBlock;case"bullet-list":case"ordered-list":case"task-list":return i.KEYS.list;case"indent":case"outdent":return i.KEYS.indent;case"align-left":case"align-center":case"align-right":case"align-justify":return i.KEYS.textAlign;default:return}}(t);return!(n&&!function(e,t){return Boolean(e.plugins?.[t])}(e,n))&&("undo"===t?e.history.undos.length>0:"redo"===t?e.history.redos.length>0:"transcribe"===t?(0,p.isTranscriptionSupported)()&&!e.api.isReadOnly?.():"table.merge-cells"===t?Ve(e).canMerge:"table.split-cell"===t?Ve(e).canSplit:Ne.has(t)?je(e):!e.api.isReadOnly?.())}function He(e){return{engine:"plate",execute(t,n){!function(e,t,n){e.tf.focus();const r=Oe[t];if(r&&"text-color"!==t&&"highlight"!==t)return void e.tf.toggleMark(r,{remove:Ue[t]});const s=Pe[t];if(s)return void e.tf.toggleBlock(s,s===i.KEYS.blockquote?{wrap:!0}:void 0);const o=Le[t];if(o)return void i.toggleList(e,{listStyleType:o});const a=Ie[t];if(a)e.getTransforms(i.TextAlignPlugin).textAlign.setNodes(a);else switch(t){case"undo":return void e.tf.undo();case"redo":return void e.tf.redo();case"text-color":{const t=n?.value??"#ef4444";return void(e.api.marks()?.[i.KEYS.color]===t?e.tf.removeMarks(i.KEYS.color):e.tf.addMarks({[i.KEYS.color]:t}))}case"highlight":return void(e.api.marks()?.[i.KEYS.highlight]?e.tf.removeMarks(i.KEYS.highlight):e.tf.addMarks({[i.KEYS.highlight]:n?.value??"#fde047"}));case"clear-formatting":return e.tf.removeMarks(Object.values(Oe)),void e.tf.toggleBlock(i.KEYS.p);case"code-block":return void i.toggleCodeBlock(e);case"link":return void(n?.value?i.upsertLink(e,{url:n.value}):i.triggerFloatingLink(e,{focused:!0}));case"image":{const t=Fe(n,"Image URL");if(!t)return;return void i.insertImage(e,t)}case"video":{const t=Fe(n,"Video URL");if(!t)return;return void i.insertMedia(e,{select:!0,type:i.KEYS.video,url:t})}case"table":return void i.insertTable(e,{colCount:3,rowCount:3},{select:!0});case"horizontal-rule":return void e.tf.insertNodes({children:[{text:""}],type:i.KEYS.hr});case"emoji":return void e.tf.insertText(":");case"math":return void i.insertEquation(e,{select:!0});case"callout":return void i.insertCallout(e,{select:!0});case"columns":return void i.insertColumnGroup(e,{columns:2,select:!0});case"transcribe":return void i.getTranscribeController(e).toggle();case"indent":return void i.indent(e);case"outdent":return void i.outdent(e);case"table.add-row-before":return void i.insertTableRow(e,{before:!0});case"table.add-row-after":return void i.insertTableRow(e);case"table.delete-row":return void i.deleteRow(e);case"table.add-column-before":return void i.insertTableColumn(e,{before:!0});case"table.add-column-after":return void i.insertTableColumn(e);case"table.delete-column":return void i.deleteColumn(e);case"table.merge-cells":return void i.mergeTableCells(e);case"table.split-cell":return void i.splitTableCell(e);case"table.toggle-header-row":{const t=i.getTableAbove(e);if(!t)return;const[n,r]=t;return void e.tf.setNodes({headerRow:!n.headerRow},{at:r})}case"table.delete":return void i.deleteTable(e);default:;}}(e,t,n)},isActive(t){if("transcribe"===t)return i.getTranscribeController(e).getState().listening;if(!e.selection)return!1;try{return function(e,t){if("task-list"===t)return i.someTodoList(e);const n=Me[t];if(n)return i.someList(e,n);const r=Oe[t];if(r)return Boolean(e.api.marks()?.[r]);const s=Pe[t];if(s)return e.api.some({match:{type:s}});if("code-block"===t)return e.api.some({match:{type:i.KEYS.codeBlock}});if("table"===t)return je(e);if("callout"===t)return e.api.some({match:{type:i.KEYS.callout}});if("columns"===t)return e.api.some({match:{type:i.KEYS.column}});if("link"===t)return e.api.some({match:{type:i.KEYS.link}});if("transcribe"===t)return i.getTranscribeController(e).getState().listening;const o=Ie[t];return!!o&&e.api.some({match:e=>e[i.KEYS.textAlign]===o})}(e,t)}catch{return!1}},isEnabled(t){try{return Be(e,t)}catch{return!1}},getValue(t){if(e.selection)try{return function(e,t){const n=e.api.marks();return"text-color"===t?n?.[i.KEYS.color]:"highlight"===t?n?.[i.KEYS.highlight]:void 0}(e,t)}catch{return}},subscribe(t){const n=e.apply;let r=!1;e.apply=i=>{n.call(e,i),r||(r=!0,queueMicrotask(()=>{r=!1,t()}))};const s=i.getTranscribeController(e).subscribe(t);return()=>{e.apply=n,s()}}}}var We,Ye=class{constructor(e,t){this.clock=e,this.len=t}},qe=class{constructor(){this.clients=new Map}},Ke=(e,t,n)=>t.clients.forEach((t,r)=>{const i=e.doc.store.clients.get(r);if(null!=i){const r=i[i.length-1],s=r.id.clock+r.length;for(let o=0,a=t[o];o<t.length&&a.clock<s;a=t[++o])Xt(e,i,a.clock,a.len,n)}}),ze=(e,t)=>{const n=e.clients.get(t.client);return void 0!==n&&null!==((e,t)=>{let n=0,r=e.length-1;for(;n<=r;){const i=a.floor((n+r)/2),s=e[i],o=s.clock;if(o<=t){if(t<o+s.len)return i;n=i+1}else r=i-1}return null})(n,t.clock)},$e=e=>{e.clients.forEach(e=>{let t,n;for(e.sort((e,t)=>e.clock-t.clock),t=1,n=1;t<e.length;t++){const r=e[n-1],i=e[t];r.clock+r.len>=i.clock?e[n-1]=new Ye(r.clock,a.max(r.len,i.clock+i.len-r.clock)):(n<t&&(e[n]=i),n++)}e.length=n})},Je=e=>{const t=new qe;for(let n=0;n<e.length;n++)e[n].clients.forEach((r,i)=>{if(!t.clients.has(i)){const s=r.slice();for(let t=n+1;t<e.length;t++)a.appendTo(s,e[t].clients.get(i)||[]);t.clients.set(i,s)}});return $e(t),t},Qe=(e,t,n,r)=>{a.setIfUndefined(e.clients,t,()=>[]).push(new Ye(n,r))},Ge=()=>new qe,Xe=(e,t)=>{a.writeVarUint(e.restEncoder,t.clients.size),a.from(t.clients.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{e.resetDsCurVal(),a.writeVarUint(e.restEncoder,t);const r=n.length;a.writeVarUint(e.restEncoder,r);for(let i=0;i<r;i++){const t=n[i];e.writeDsClock(t.clock),e.writeDsLen(t.len)}})},Ze=e=>{const t=new qe,n=a.readVarUint(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();const n=a.readVarUint(e.restDecoder),r=a.readVarUint(e.restDecoder);if(r>0){const i=a.setIfUndefined(t.clients,n,()=>[]);for(let t=0;t<r;t++)i.push(new Ye(e.readDsClock(),e.readDsLen()))}}return t},et=(e,t,n)=>{const r=new qe,i=a.readVarUint(e.restDecoder);for(let s=0;s<i;s++){e.resetDsCurVal();const i=a.readVarUint(e.restDecoder),s=a.readVarUint(e.restDecoder),o=n.clients.get(i)||[],c=qt(n,i);for(let n=0;n<s;n++){const n=e.readDsClock(),s=n+e.readDsLen();if(n<c){c<s&&Qe(r,i,c,s-c);let e=zt(o,n),a=o[e];for(!a.deleted&&a.id.clock<n&&(o.splice(e+1,0,Hr(t,a,n-a.id.clock)),e++);e<o.length&&(a=o[e++],a.id.clock<s);)a.deleted||(s<a.id.clock+a.length&&o.splice(e,0,Hr(t,a,s-a.id.clock)),a.delete(t))}else Qe(r,i,n,s-n)}}if(r.clients.size>0){const e=new dt;return a.writeVarUint(e.restEncoder,0),Xe(e,r),e.toUint8Array()}return null},tt=a.uint32,nt=class e extends a.ObservableV2{constructor({guid:e=a.uuidv4(),collectionid:t=null,gc:n=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:s=!1,shouldLoad:o=!0}={}){super(),this.gc=n,this.gcFilter=r,this.clientID=tt(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new Wt,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=o,this.autoLoad=s,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=a.create(e=>{this.on("load",()=>{this.isLoaded=!0,e(this)})});const c=()=>a.create(e=>{const t=n=>{void 0!==n&&!0!==n||(this.off("sync",t),e())};this.on("sync",t)});this.on("sync",e=>{!1===e&&this.isSynced&&(this.whenSynced=c()),this.isSynced=void 0===e||!0===e,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const e=this._item;null===e||this.shouldLoad||sn(e.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(a.from(this.subdocs).map(e=>e.guid))}transact(e,t=null){return sn(this,e,t)}get(e,t=Dn){const n=a.setIfUndefined(this.share,e,()=>{const e=new t;return e._integrate(this,null),e}),r=n.constructor;if(t!==Dn&&r!==t){if(r===Dn){const r=new t;r._map=n._map,n._map.forEach(e=>{for(;null!==e;e=e.left)e.parent=r}),r._start=n._start;for(let e=r._start;null!==e;e=e.right)e.parent=r;return r._length=n._length,this.share.set(e,r),r._integrate(this,null),r}throw new Error(`Type with the name ${e} has already been defined with a different constructor`)}return n}getArray(e=""){return this.get(e,$n)}getText(e=""){return this.get(e,ur)}getMap(e=""){return this.get(e,Qn)}getXmlElement(e=""){return this.get(e,pr)}getXmlFragment(e=""){return this.get(e,gr)}toJSON(){const e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,a.from(this.subdocs).forEach(e=>e.destroy());const t=this._item;if(null!==t){this._item=null;const n=t.content;n.doc=new e({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,sn(t.parent.doc,e=>{const r=n.doc;t.deleted||e.subdocsAdded.add(r),e.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}},rt=class{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return a.readVarUint(this.restDecoder)}readDsLen(){return a.readVarUint(this.restDecoder)}},it=class extends rt{readLeftID(){return xt(a.readVarUint(this.restDecoder),a.readVarUint(this.restDecoder))}readRightID(){return xt(a.readVarUint(this.restDecoder),a.readVarUint(this.restDecoder))}readClient(){return a.readVarUint(this.restDecoder)}readInfo(){return a.readUint8(this.restDecoder)}readString(){return a.readVarString(this.restDecoder)}readParentInfo(){return 1===a.readVarUint(this.restDecoder)}readTypeRef(){return a.readVarUint(this.restDecoder)}readLen(){return a.readVarUint(this.restDecoder)}readAny(){return a.readAny(this.restDecoder)}readBuf(){return a.copyUint8Array(a.readVarUint8Array(this.restDecoder))}readJSON(){return JSON.parse(a.readVarString(this.restDecoder))}readKey(){return a.readVarString(this.restDecoder)}},st=class{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=a.readVarUint(this.restDecoder),this.dsCurrVal}readDsLen(){const e=a.readVarUint(this.restDecoder)+1;return this.dsCurrVal+=e,e}},ot=class extends st{constructor(e){super(e),this.keys=[],a.readVarUint(e),this.keyClockDecoder=new a.IntDiffOptRleDecoder(a.readVarUint8Array(e)),this.clientDecoder=new a.UintOptRleDecoder(a.readVarUint8Array(e)),this.leftClockDecoder=new a.IntDiffOptRleDecoder(a.readVarUint8Array(e)),this.rightClockDecoder=new a.IntDiffOptRleDecoder(a.readVarUint8Array(e)),this.infoDecoder=new a.RleDecoder(a.readVarUint8Array(e),a.readUint8),this.stringDecoder=new a.StringDecoder(a.readVarUint8Array(e)),this.parentInfoDecoder=new a.RleDecoder(a.readVarUint8Array(e),a.readUint8),this.typeRefDecoder=new a.UintOptRleDecoder(a.readVarUint8Array(e)),this.lenDecoder=new a.UintOptRleDecoder(a.readVarUint8Array(e))}readLeftID(){return new Et(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new Et(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return 1===this.parentInfoDecoder.read()}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return a.readAny(this.restDecoder)}readBuf(){return a.readVarUint8Array(this.restDecoder)}readJSON(){return a.readAny(this.restDecoder)}readKey(){const e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{const e=this.stringDecoder.read();return this.keys.push(e),e}}},at=class{constructor(){this.restEncoder=a.createEncoder()}toUint8Array(){return a.toUint8Array(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){a.writeVarUint(this.restEncoder,e)}writeDsLen(e){a.writeVarUint(this.restEncoder,e)}},ct=class extends at{writeLeftID(e){a.writeVarUint(this.restEncoder,e.client),a.writeVarUint(this.restEncoder,e.clock)}writeRightID(e){a.writeVarUint(this.restEncoder,e.client),a.writeVarUint(this.restEncoder,e.clock)}writeClient(e){a.writeVarUint(this.restEncoder,e)}writeInfo(e){a.writeUint8(this.restEncoder,e)}writeString(e){a.writeVarString(this.restEncoder,e)}writeParentInfo(e){a.writeVarUint(this.restEncoder,e?1:0)}writeTypeRef(e){a.writeVarUint(this.restEncoder,e)}writeLen(e){a.writeVarUint(this.restEncoder,e)}writeAny(e){a.writeAny(this.restEncoder,e)}writeBuf(e){a.writeVarUint8Array(this.restEncoder,e)}writeJSON(e){a.writeVarString(this.restEncoder,JSON.stringify(e))}writeKey(e){a.writeVarString(this.restEncoder,e)}},lt=class{constructor(){this.restEncoder=a.createEncoder(),this.dsCurrVal=0}toUint8Array(){return a.toUint8Array(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const t=e-this.dsCurrVal;this.dsCurrVal=e,a.writeVarUint(this.restEncoder,t)}writeDsLen(e){0===e&&a.unexpectedCase(),a.writeVarUint(this.restEncoder,e-1),this.dsCurrVal+=e}},dt=class extends lt{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new a.IntDiffOptRleEncoder,this.clientEncoder=new a.UintOptRleEncoder,this.leftClockEncoder=new a.IntDiffOptRleEncoder,this.rightClockEncoder=new a.IntDiffOptRleEncoder,this.infoEncoder=new a.RleEncoder(a.writeUint8),this.stringEncoder=new a.StringEncoder,this.parentInfoEncoder=new a.RleEncoder(a.writeUint8),this.typeRefEncoder=new a.UintOptRleEncoder,this.lenEncoder=new a.UintOptRleEncoder}toUint8Array(){const e=a.createEncoder();return a.writeVarUint(e,0),a.writeVarUint8Array(e,this.keyClockEncoder.toUint8Array()),a.writeVarUint8Array(e,this.clientEncoder.toUint8Array()),a.writeVarUint8Array(e,this.leftClockEncoder.toUint8Array()),a.writeVarUint8Array(e,this.rightClockEncoder.toUint8Array()),a.writeVarUint8Array(e,a.toUint8Array(this.infoEncoder)),a.writeVarUint8Array(e,this.stringEncoder.toUint8Array()),a.writeVarUint8Array(e,a.toUint8Array(this.parentInfoEncoder)),a.writeVarUint8Array(e,this.typeRefEncoder.toUint8Array()),a.writeVarUint8Array(e,this.lenEncoder.toUint8Array()),a.writeUint8Array(e,a.toUint8Array(this.restEncoder)),a.toUint8Array(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(e?1:0)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){a.writeAny(this.restEncoder,e)}writeBuf(e){a.writeVarUint8Array(this.restEncoder,e)}writeJSON(e){a.writeAny(this.restEncoder,e)}writeKey(e){const t=this.keyMap.get(e);void 0===t?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t)}},ht=(e,t,n)=>{const r=new Map;n.forEach((e,n)=>{qt(t,n)>e&&r.set(n,e)}),Yt(t).forEach((e,t)=>{n.has(t)||r.set(t,0)}),a.writeVarUint(e.restEncoder,r.size),a.from(r.entries()).sort((e,t)=>t[0]-e[0]).forEach(([n,r])=>{((e,t,n,r)=>{r=a.max(r,t[0].id.clock);const i=zt(t,r);a.writeVarUint(e.restEncoder,t.length-i),e.writeClient(n),a.writeVarUint(e.restEncoder,r);const s=t[i];s.write(e,r-s.id.clock);for(let o=i+1;o<t.length;o++)t[o].write(e,0)})(e,t.clients.get(n),n,r)})},ut=(e,t,n,r=new ot(e))=>sn(t,e=>{e.local=!1;let t=!1;const n=e.doc,i=n.store,s=((e,t)=>{const n=a.create$3(),r=a.readVarUint(e.restDecoder);for(let i=0;i<r;i++){const r=a.readVarUint(e.restDecoder),i=new Array(r),s=e.readClient();let o=a.readVarUint(e.restDecoder);n.set(s,{i:0,refs:i});for(let n=0;n<r;n++){const r=e.readInfo();switch(31&r){case 0:{const t=e.readLen();i[n]=new vr(xt(s,o),t),o+=t;break}case 10:{const t=a.readVarUint(e.restDecoder);i[n]=new $r(xt(s,o),t),o+=t;break}default:{const a=!(192&r),c=new qr(xt(s,o),null,128&~r?null:e.readLeftID(),null,64&~r?null:e.readRightID(),a?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,!a||32&~r?null:e.readString(),Kr(e,r));i[n]=c,o+=c.length}}}}return n})(r,n),o=((e,t,n)=>{const r=[];let i=a.from(n.keys()).sort((e,t)=>e-t);if(0===i.length)return null;const s=()=>{if(0===i.length)return null;let e=n.get(i[i.length-1]);for(;e.refs.length===e.i;){if(i.pop(),!(i.length>0))return null;e=n.get(i[i.length-1])}return e};let o=s();if(null===o)return null;const c=new Wt,l=new Map,d=(e,t)=>{const n=l.get(e);(null==n||n>t)&&l.set(e,t)};let h=o.refs[o.i++];const u=new Map,f=()=>{for(const e of r){const t=e.id.client,r=n.get(t);r?(r.i--,c.clients.set(t,r.refs.slice(r.i)),n.delete(t),r.i=0,r.refs=[]):c.clients.set(t,[e]),i=i.filter(e=>e!==t)}r.length=0};for(;;){if(h.constructor!==$r){const i=a.setIfUndefined(u,h.id.client,()=>qt(t,h.id.client))-h.id.clock;if(i<0)r.push(h),d(h.id.client,h.id.clock-1),f();else{const s=h.getMissing(e,t);if(null!==s){r.push(h);const e=n.get(s)||{refs:[],i:0};if(e.refs.length!==e.i){h=e.refs[e.i++];continue}d(s,qt(t,s)),f()}else(0===i||i<h.length)&&(h.integrate(e,i),u.set(h.id.client,h.id.clock+h.length))}}if(r.length>0)h=r.pop();else if(null!==o&&o.i<o.refs.length)h=o.refs[o.i++];else{if(o=s(),null===o)break;h=o.refs[o.i++]}}if(c.clients.size>0){const e=new dt;return ht(e,c,new Map),a.writeVarUint(e.restEncoder,0),{missing:l,update:e.toUint8Array()}}return null})(e,i,s),c=i.pendingStructs;if(c){for(const[e,n]of c.missing)if(n<qt(i,e)){t=!0;break}if(o){for(const[e,t]of o.missing){const n=c.missing.get(e);(null==n||n>t)&&c.missing.set(e,t)}c.update=gn([c.update,o.update])}}else i.pendingStructs=o;const l=et(r,e,i);if(i.pendingDs){const t=new ot(a.createDecoder(i.pendingDs));a.readVarUint(t.restDecoder);const n=et(t,e,i);i.pendingDs=l&&n?gn([l,n]):l||n}else i.pendingDs=l;if(t){const t=i.pendingStructs.update;i.pendingStructs=null,ft(e.doc,t)}},n,!1),ft=(e,t,n,r=ot)=>{const i=a.createDecoder(t);ut(i,e,n,new r(i))},gt=(e,t,n)=>ft(e,t,n,it),pt=(e,t,n=new Map)=>{ht(e,t.store,n),Xe(e,(e=>{const t=Ge();return e.clients.forEach((e,n)=>{const r=[];for(let t=0;t<e.length;t++){const n=e[t];if(n.deleted){const i=n.id.clock;let s=n.length;if(t+1<e.length)for(let n=e[t+1];t+1<e.length&&n.deleted;n=e[1+ ++t])s+=n.length;r.push(new Ye(i,s))}}r.length>0&&t.clients.set(n,r)}),t})(t.store))},mt=(e,t)=>((e,t=new Uint8Array([0]),n=new dt)=>{const r=yt(t);pt(n,e,r);const i=[n.toUint8Array()];if(e.store.pendingDs&&i.push(e.store.pendingDs),e.store.pendingStructs&&i.push(pn(e.store.pendingStructs.update,t)),i.length>1){if(n.constructor===ct)return un(i.map((e,t)=>0===t?e:bn(e)));if(n.constructor===dt)return gn(i)}return i[0]})(e,t,new ct),yt=e=>(e=>{const t=new Map,n=a.readVarUint(e.restDecoder);for(let r=0;r<n;r++){const n=a.readVarUint(e.restDecoder),r=a.readVarUint(e.restDecoder);t.set(n,r)}return t})(new rt(a.createDecoder(e))),wt=(e,t)=>(a.writeVarUint(e.restEncoder,t.size),a.from(t.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{a.writeVarUint(e.restEncoder,t),a.writeVarUint(e.restEncoder,n)}),e),bt=(e,t=new lt)=>(e instanceof Map?wt(t,e):((e,t)=>{wt(e,Yt(t.store))})(t,e),t.toUint8Array()),vt=class{constructor(){this.l=[]}},_t=()=>new vt,St=(e,t)=>e.l.push(t),kt=(e,t)=>{const n=e.l;n.length;e.l=n.filter(e=>t!==e),e.l.length},Ct=(e,t,n)=>a.callAll(e.l,[t,n]),Et=class{constructor(e,t){this.client=e,this.clock=t}},At=(e,t)=>e===t||null!==e&&null!==t&&e.client===t.client&&e.clock===t.clock,xt=(e,t)=>new Et(e,t),Tt=(e,t)=>{a.writeVarUint(e,t.client),a.writeVarUint(e,t.clock)},Rt=e=>xt(a.readVarUint(e),a.readVarUint(e)),Dt=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw a.unexpectedCase()},Ot=(e,t)=>{for(;null!==t;){if(t.parent===e)return!0;t=t.parent._item}return!1},Ut=class{constructor(e,t,n,r=0){this.type=e,this.tname=t,this.item=n,this.assoc=r}},Pt=class{constructor(e,t,n=0){this.type=e,this.index=t,this.assoc=n}},Lt=(e,t,n)=>{let r=null,i=null;return null===e._item?i=Dt(e):r=xt(e._item.id.client,e._item.id.clock),new Ut(r,i,t,n)},Mt=(e,t,n=0)=>{let r=e._start;if(n<0){if(0===t)return Lt(e,null,n);t--}for(;null!==r;){if(!r.deleted&&r.countable){if(r.length>t)return Lt(e,xt(r.id.client,r.id.clock+t),n);t-=r.length}if(null===r.right&&n<0)return Lt(e,r.lastId,n);r=r.right}return Lt(e,null,n)},It=e=>{const t=a.createEncoder();return((e,t)=>{const{type:n,tname:r,item:i,assoc:s}=t;if(null!==i)a.writeVarUint(e,0),Tt(e,i);else if(null!==r)a.writeUint8(e,1),a.writeVarString(e,r);else{if(null===n)throw a.unexpectedCase();a.writeUint8(e,2),Tt(e,n)}a.writeVarInt(e,s)})(t,e),a.toUint8Array(t)},Nt=e=>(e=>{let t=null,n=null,r=null;switch(a.readVarUint(e)){case 0:r=Rt(e);break;case 1:n=a.readVarString(e);break;case 2:t=Rt(e)}const i=a.hasContent(e)?a.readVarInt(e):0;return new Ut(t,n,r,i)})(a.createDecoder(e)),jt=(e,t,n=!0)=>{const r=t.store,i=e.item,s=e.type,o=e.tname,c=e.assoc;let l=null,d=0;if(null!==i){if(qt(r,i.client)<=i.clock)return null;const e=n?Fr(r,i):((e,t)=>{const n=$t(e,t);return{item:n,diff:t.clock-n.id.clock}})(r,i),t=e.item;if(!(t instanceof qr))return null;if(l=t.parent,null===l._item||!l._item.deleted){d=t.deleted||!t.countable?0:e.diff+(c>=0?0:1);let n=t.left;for(;null!==n;)!n.deleted&&n.countable&&(d+=n.length),n=n.left}}else{if(null!==o)l=t.get(o);else{if(null===s)throw a.unexpectedCase();{if(qt(r,s.client)<=s.clock)return null;const{item:e}=n?Fr(r,s):{item:$t(r,s)};if(!(e instanceof qr&&e.content instanceof Vr))return null;l=e.content.type}}d=c>=0?l._length:0}return((e,t,n=0)=>new Pt(e,t,n))(l,d,e.assoc)},Vt=(e,t)=>e===t||null!==e&&null!==t&&e.tname===t.tname&&At(e.item,t.item)&&At(e.type,t.type)&&e.assoc===t.assoc,Ft=class{constructor(e,t){this.ds=e,this.sv=t}},Bt=(We=Ge(),new Ft(We,new Map),(e,t)=>void 0===t?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!ze(t.ds,e.id)),Ht=(e,t)=>{const n=a.setIfUndefined(e.meta,Ht,a.create$2),r=e.doc.store;n.has(t)||(t.sv.forEach((t,n)=>{t<qt(r,n)&&Qt(e,xt(n,t))}),Ke(e,t.ds,e=>{}),n.add(t))},Wt=class{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}},Yt=e=>{const t=new Map;return e.clients.forEach((e,n)=>{const r=e[e.length-1];t.set(n,r.id.clock+r.length)}),t},qt=(e,t)=>{const n=e.clients.get(t);if(void 0===n)return 0;const r=n[n.length-1];return r.id.clock+r.length},Kt=(e,t)=>{let n=e.clients.get(t.id.client);if(void 0===n)n=[],e.clients.set(t.id.client,n);else{const e=n[n.length-1];if(e.id.clock+e.length!==t.id.clock)throw a.unexpectedCase()}n.push(t)},zt=(e,t)=>{let n=0,r=e.length-1,i=e[r],s=i.id.clock;if(s===t)return r;let o=a.floor(t/(s+i.length-1)*r);for(;n<=r;){if(i=e[o],s=i.id.clock,s<=t){if(t<s+i.length)return o;n=o+1}else r=o-1;o=a.floor((n+r)/2)}throw a.unexpectedCase()},$t=(e,t)=>{const n=e.clients.get(t.client);return n[zt(n,t.clock)]},Jt=(e,t,n)=>{const r=zt(t,n),i=t[r];return i.id.clock<n&&i instanceof qr?(t.splice(r+1,0,Hr(e,i,n-i.id.clock)),r+1):r},Qt=(e,t)=>{const n=e.doc.store.clients.get(t.client);return n[Jt(e,n,t.clock)]},Gt=(e,t,n)=>{const r=t.clients.get(n.client),i=zt(r,n.clock),s=r[i];return n.clock!==s.id.clock+s.length-1&&s.constructor!==vr&&r.splice(i+1,0,Hr(e,s,n.clock-s.id.clock+1)),s},Xt=(e,t,n,r,i)=>{if(0===r)return;const s=n+r;let o,a=Jt(e,t,n);do{o=t[a++],s<o.id.clock+o.length&&Jt(e,t,s),i(o)}while(a<t.length&&t[a].id.clock<s)},Zt=class{constructor(e,t,n){this.doc=e,this.deleteSet=new qe,this.beforeState=Yt(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=t,this.meta=new Map,this.local=n,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}},en=(e,t)=>!(0===t.deleteSet.clients.size&&!a.any(t.afterState,(e,n)=>t.beforeState.get(n)!==e))&&($e(t.deleteSet),((e,t)=>{ht(e,t.doc.store,t.beforeState)})(e,t),Xe(e,t.deleteSet),!0),tn=(e,t,n)=>{const r=t._item;(null===r||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&a.setIfUndefined(e.changed,t,a.create$2).add(n)},nn=(e,t)=>{let n=e[t],r=e[t-1],i=t;for(;i>0&&(r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n));n=r,r=e[--i-1])n instanceof qr&&null!==n.parentSub&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);const s=t-i;return s&&e.splice(t+1-s,s),s},rn=(e,t)=>{if(t<e.length){const n=e[t],r=n.doc,i=r.store,s=n.deleteSet,o=n._mergeStructs;try{$e(s),n.afterState=Yt(n.doc.store),r.emit("beforeObserverCalls",[n,r]);const e=[];n.changed.forEach((t,r)=>e.push(()=>{null!==r._item&&r._item.deleted||r._callObserver(n,t)})),e.push(()=>{n.changedParentTypes.forEach((t,r)=>{r._dEH.l.length>0&&(null===r._item||!r._item.deleted)&&((t=t.filter(e=>null===e.target._item||!e.target._item.deleted)).forEach(e=>{e.currentTarget=r,e._path=null}),t.sort((e,t)=>e.path.length-t.path.length),e.push(()=>{Ct(r._dEH,t,n)}))}),e.push(()=>r.emit("afterTransaction",[n,r])),e.push(()=>{n._needFormattingCleanup&&lr(n)})}),a.callAll(e,[])}finally{r.gc&&((e,t,n)=>{for(const[r,i]of e.clients.entries()){const e=t.clients.get(r);for(let r=i.length-1;r>=0;r--){const s=i[r],o=s.clock+s.len;for(let r=zt(e,s.clock),i=e[r];r<e.length&&i.id.clock<o;i=e[++r]){const i=e[r];if(s.clock+s.len<=i.id.clock)break;i instanceof qr&&i.deleted&&!i.keep&&n(i)&&i.gc(t,!1)}}}})(s,i,r.gcFilter),((e,t)=>{e.clients.forEach((e,n)=>{const r=t.clients.get(n);for(let t=e.length-1;t>=0;t--){const n=e[t];for(let e=a.min(r.length-1,1+zt(r,n.clock+n.len-1)),t=r[e];e>0&&t.id.clock>=n.clock;t=r[e])e-=1+nn(r,e)}})})(s,i),n.afterState.forEach((e,t)=>{const r=n.beforeState.get(t)||0;if(r!==e){const e=i.clients.get(t),n=a.max(zt(e,r),1);for(let t=e.length-1;t>=n;)t-=1+nn(e,t)}});for(let e=o.length-1;e>=0;e--){const{client:t,clock:n}=o[e].id,r=i.clients.get(t),s=zt(r,n);s+1<r.length&&nn(r,s+1)>1||s>0&&nn(r,s)}if(n.local||n.afterState.get(r.clientID)===n.beforeState.get(r.clientID)||(a.print(a.ORANGE,a.BOLD,"[yjs] ",a.UNBOLD,a.RED,"Changed the client-id because another client seems to be using it."),r.clientID=tt()),r.emit("afterTransactionCleanup",[n,r]),r._observers.has("update")){const e=new ct;en(e,n)&&r.emit("update",[e.toUint8Array(),n.origin,r,n])}if(r._observers.has("updateV2")){const e=new dt;en(e,n)&&r.emit("updateV2",[e.toUint8Array(),n.origin,r,n])}const{subdocsAdded:c,subdocsLoaded:l,subdocsRemoved:d}=n;(c.size>0||d.size>0||l.size>0)&&(c.forEach(e=>{e.clientID=r.clientID,null==e.collectionid&&(e.collectionid=r.collectionid),r.subdocs.add(e)}),d.forEach(e=>r.subdocs.delete(e)),r.emit("subdocs",[{loaded:l,added:c,removed:d},r,n]),d.forEach(e=>e.destroy())),e.length<=t+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,e])):rn(e,t+1)}}},sn=(e,t,n=null,r=!0)=>{const i=e._transactionCleanups;let s=!1,o=null;null===e._transaction&&(s=!0,e._transaction=new Zt(e,n,r),i.push(e._transaction),1===i.length&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(s){const t=e._transaction===i[0];e._transaction=null,t&&rn(i,0)}}return o},on=class{constructor(e,t){this.insertions=t,this.deletions=e,this.meta=new Map}},an=(e,t,n)=>{Ke(e,n.deletions,n=>{n instanceof qr&&t.scope.some(t=>t===e.doc||Ot(t,n))&&Br(n,!1)})},cn=(e,t,n)=>{let r=null;const i=e.doc,s=e.scope;sn(i,n=>{for(;t.length>0&&null===e.currStackItem;){const r=i.store,o=t.pop(),a=new Set,c=[];let l=!1;Ke(n,o.insertions,e=>{if(e instanceof qr){if(null!==e.redone){let{item:t,diff:i}=Fr(r,e.id);i>0&&(t=Qt(n,xt(t.id.client,t.id.clock+i))),e=t}!e.deleted&&s.some(t=>t===n.doc||Ot(t,e))&&c.push(e)}}),Ke(n,o.deletions,e=>{e instanceof qr&&s.some(t=>t===n.doc||Ot(t,e))&&!ze(o.insertions,e.id)&&a.add(e)}),a.forEach(t=>{l=null!==Yr(n,t,a,o.insertions,e.ignoreRemoteMapChanges,e)||l});for(let t=c.length-1;t>=0;t--){const r=c[t];e.deleteFilter(r)&&(r.delete(n),l=!0)}e.currStackItem=l?o:null}n.changed.forEach((e,t)=>{e.has(null)&&t._searchMarker&&(t._searchMarker.length=0)}),r=n},e);const o=e.currStackItem;if(null!=o){const t=r.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:t,origin:e},e]),e.currStackItem=null}return o},ln=class extends a.ObservableV2{constructor(e,{captureTimeout:t=500,captureTransaction:n=e=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:s=!1,doc:o=(a.isArray(e)?e[0].doc:e instanceof nt?e:e.doc)}={}){super(),this.scope=[],this.doc=o,this.addToScope(e),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=n,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=s,this.captureTimeout=t,this.afterTransactionHandler=e=>{if(!(this.captureTransaction(e)&&this.scope.some(t=>e.changedParentTypes.has(t)||t===this.doc)&&(this.trackedOrigins.has(e.origin)||e.origin&&this.trackedOrigins.has(e.origin.constructor))))return;const t=this.undoing,n=this.redoing,r=t?this.redoStack:this.undoStack;t?this.stopCapturing():n||this.clear(!1,!0);const i=new qe;e.afterState.forEach((t,n)=>{const r=e.beforeState.get(n)||0,s=t-r;s>0&&Qe(i,n,r,s)});const s=a.getUnixTime();let o=!1;if(this.lastChange>0&&s-this.lastChange<this.captureTimeout&&r.length>0&&!t&&!n){const t=r[r.length-1];t.deletions=Je([t.deletions,e.deleteSet]),t.insertions=Je([t.insertions,i])}else r.push(new on(e.deleteSet,i)),o=!0;t||n||(this.lastChange=s),Ke(e,e.deleteSet,t=>{t instanceof qr&&this.scope.some(n=>n===e.doc||Ot(n,t))&&Br(t,!0)});const c=[{stackItem:r[r.length-1],origin:e.origin,type:t?"redo":"undo",changedParentTypes:e.changedParentTypes},this];o?this.emit("stack-item-added",c):this.emit("stack-item-updated",c)},this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",()=>{this.destroy()})}addToScope(e){const t=new Set(this.scope);(e=a.isArray(e)?e:[e]).forEach(e=>{t.has(e)||(t.add(e),(e instanceof Dn?e.doc!==this.doc:e!==this.doc)&&a.warn("[yjs#509] Not same Y.Doc"),this.scope.push(e))})}addTrackedOrigin(e){this.trackedOrigins.add(e)}removeTrackedOrigin(e){this.trackedOrigins.delete(e)}clear(e=!0,t=!0){(e&&this.canUndo()||t&&this.canRedo())&&this.doc.transact(n=>{e&&(this.undoStack.forEach(e=>an(n,this,e)),this.undoStack=[]),t&&(this.redoStack.forEach(e=>an(n,this,e)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:e,redoStackCleared:t}])})}stopCapturing(){this.lastChange=0}undo(){let e;this.undoing=!0;try{e=cn(this,this.undoStack,"undo")}finally{this.undoing=!1}return e}redo(){let e;this.redoing=!0;try{e=cn(this,this.redoStack,"redo")}finally{this.redoing=!1}return e}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),super.destroy()}};var dn=class{constructor(e,t){this.gen=function*(e){const t=a.readVarUint(e.restDecoder);for(let n=0;n<t;n++){const t=a.readVarUint(e.restDecoder),n=e.readClient();let r=a.readVarUint(e.restDecoder);for(let i=0;i<t;i++){const t=e.readInfo();if(10===t){const t=a.readVarUint(e.restDecoder);yield new $r(xt(n,r),t),r+=t}else if(31&t){const i=!(192&t),s=new qr(xt(n,r),null,128&~t?null:e.readLeftID(),null,64&~t?null:e.readRightID(),i?e.readParentInfo()?e.readString():e.readLeftID():null,!i||32&~t?null:e.readString(),Kr(e,t));yield s,r+=s.length}else{const t=e.readLen();yield new vr(xt(n,r),t),r+=t}}}}(e),this.curr=null,this.done=!1,this.filterSkips=t,this.next()}next(){do{this.curr=this.gen.next().value||null}while(this.filterSkips&&null!==this.curr&&this.curr.constructor===$r);return this.curr}},hn=class{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}},un=e=>gn(e,it,ct),fn=(e,t)=>{if(e.constructor===vr){const{client:n,clock:r}=e.id;return new vr(xt(n,r+t),e.length-t)}if(e.constructor===$r){const{client:n,clock:r}=e.id;return new $r(xt(n,r+t),e.length-t)}{const n=e,{client:r,clock:i}=n.id;return new qr(xt(r,i+t),null,xt(r,i+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},gn=(e,t=ot,n=dt)=>{if(1===e.length)return e[0];const r=e.map(e=>new t(a.createDecoder(e)));let i=r.map(e=>new dn(e,!0)),s=null;const o=new n,c=new hn(o);for(;i=i.filter(e=>null!==e.curr),i.sort((e,t)=>{if(e.curr.id.client===t.curr.id.client){const n=e.curr.id.clock-t.curr.id.clock;return 0===n?e.curr.constructor===t.curr.constructor?0:e.curr.constructor===$r?1:-1:n}return t.curr.id.client-e.curr.id.client}),0!==i.length;){const e=i[0],t=e.curr.id.client;if(null!==s){let n=e.curr,r=!1;for(;null!==n&&n.id.clock+n.length<=s.struct.id.clock+s.struct.length&&n.id.client>=s.struct.id.client;)n=e.next(),r=!0;if(null===n||n.id.client!==t||r&&n.id.clock>s.struct.id.clock+s.struct.length)continue;if(t!==s.struct.id.client)yn(c,s.struct,s.offset),s={struct:n,offset:0},e.next();else if(s.struct.id.clock+s.struct.length<n.id.clock)if(s.struct.constructor===$r)s.struct.length=n.id.clock+n.length-s.struct.id.clock;else{yn(c,s.struct,s.offset);const e=n.id.clock-s.struct.id.clock-s.struct.length;s={struct:new $r(xt(t,s.struct.id.clock+s.struct.length),e),offset:0}}else{const t=s.struct.id.clock+s.struct.length-n.id.clock;t>0&&(s.struct.constructor===$r?s.struct.length-=t:n=fn(n,t)),s.struct.mergeWith(n)||(yn(c,s.struct,s.offset),s={struct:n,offset:0},e.next())}}else s={struct:e.curr,offset:0},e.next();for(let n=e.curr;null!==n&&n.id.client===t&&n.id.clock===s.struct.id.clock+s.struct.length&&n.constructor!==$r;n=e.next())yn(c,s.struct,s.offset),s={struct:n,offset:0}}null!==s&&(yn(c,s.struct,s.offset),s=null),wn(c);const l=r.map(e=>Ze(e)),d=Je(l);return Xe(o,d),o.toUint8Array()},pn=(e,t,n=ot,r=dt)=>{const i=yt(t),s=new r,o=new hn(s),c=new n(a.createDecoder(e)),l=new dn(c,!1);for(;l.curr;){const e=l.curr,t=e.id.client,n=i.get(t)||0;if(l.curr.constructor!==$r)if(e.id.clock+e.length>n)for(yn(o,e,a.max(n-e.id.clock,0)),l.next();l.curr&&l.curr.id.client===t;)yn(o,l.curr,0),l.next();else for(;l.curr&&l.curr.id.client===t&&l.curr.id.clock+l.curr.length<=n;)l.next();else l.next()}wn(o);const d=Ze(c);return Xe(s,d),s.toUint8Array()},mn=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:a.toUint8Array(e.encoder.restEncoder)}),e.encoder.restEncoder=a.createEncoder(),e.written=0)},yn=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&mn(e),0===e.written&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),a.writeVarUint(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},wn=e=>{mn(e);const t=e.encoder.restEncoder;a.writeVarUint(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){const r=e.clientStructs[n];a.writeVarUint(t,r.written),a.writeUint8Array(t,r.restEncoder)}},bn=e=>((e,t,n,r)=>{const i=new n(a.createDecoder(e)),s=new dn(i,!1),o=new r,c=new hn(o);for(let a=s.curr;null!==a;a=s.next())yn(c,t(a),0);wn(c);const l=Ze(i);return Xe(o,l),o.toUint8Array()})(e,a.id,ot,ct),vn="You must not compute changes after the event-handler fired.",_n=class{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Sn(this.currentTarget,this.target))}deletes(e){return ze(this.transaction.deleteSet,e.id)}get keys(){if(null===this._keys){if(0===this.transaction.doc._transactionCleanups.length)throw a.create$1(vn);const e=new Map,t=this.target;this.transaction.changed.get(t).forEach(n=>{if(null!==n){const r=t._map.get(n);let i,s;if(this.adds(r)){let e=r.left;for(;null!==e&&this.adds(e);)e=e.left;if(this.deletes(r)){if(null===e||!this.deletes(e))return;i="delete",s=a.last(e.content.getContent())}else null!==e&&this.deletes(e)?(i="update",s=a.last(e.content.getContent())):(i="add",s=void 0)}else{if(!this.deletes(r))return;i="delete",s=a.last(r.content.getContent())}e.set(n,{action:i,oldValue:s})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(null===e){if(0===this.transaction.doc._transactionCleanups.length)throw a.create$1(vn);const t=this.target,n=a.create$2(),r=a.create$2(),i=[];if(e={added:n,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(t).has(null)){let e=null;const s=()=>{e&&i.push(e)};for(let i=t._start;null!==i;i=i.right)i.deleted?this.deletes(i)&&!this.adds(i)&&(null!==e&&void 0!==e.delete||(s(),e={delete:0}),e.delete+=i.length,r.add(i)):this.adds(i)?(null!==e&&void 0!==e.insert||(s(),e={insert:[]}),e.insert=e.insert.concat(i.content.getContent()),n.add(i)):(null!==e&&void 0!==e.retain||(s(),e={retain:0}),e.retain+=i.length);null!==e&&void 0===e.retain&&s()}this._changes=e}return e}},Sn=(e,t)=>{const n=[];for(;null!==t._item&&t!==e;){if(null!==t._item.parentSub)n.unshift(t._item.parentSub);else{let e=0,r=t._item.parent._start;for(;r!==t._item&&null!==r;)!r.deleted&&r.countable&&(e+=r.length),r=r.right;n.unshift(e)}t=t._item.parent}return n},kn=()=>{a.warn("Invalid access: Add Yjs type to a document before reading data.")},Cn=0,En=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=Cn++}},An=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=Cn++},xn=(e,t)=>{if(null===e._start||0===t||null===e._searchMarker)return null;const n=0===e._searchMarker.length?null:e._searchMarker.reduce((e,n)=>a.abs(t-e.index)<a.abs(t-n.index)?e:n);let r=e._start,i=0;for(null!==n&&(r=n.p,i=n.index,(e=>{e.timestamp=Cn++})(n));null!==r.right&&i<t;){if(!r.deleted&&r.countable){if(t<i+r.length)break;i+=r.length}r=r.right}for(;null!==r.left&&i>t;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;null!==r.left&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return null!==n&&a.abs(n.index-i)<r.parent.length/80?(An(n,r,i),n):((e,t,n)=>{if(e.length>=80){const r=e.reduce((e,t)=>e.timestamp<t.timestamp?e:t);return An(r,t,n),r}{const r=new En(t,n);return e.push(r),r}})(e._searchMarker,r,i)},Tn=(e,t,n)=>{for(let r=e.length-1;r>=0;r--){const i=e[r];if(n>0){let t=i.p;for(t.marker=!1;t&&(t.deleted||!t.countable);)t=t.left,t&&!t.deleted&&t.countable&&(i.index-=t.length);if(null===t||!0===t.marker){e.splice(r,1);continue}i.p=t,t.marker=!0}(t<i.index||n>0&&t===i.index)&&(i.index=a.max(t,i.index+n))}},Rn=(e,t,n)=>{const r=e,i=t.changedParentTypes;for(;a.setIfUndefined(i,e,()=>[]).push(n),null!==e._item;)e=e._item.parent;Ct(r._eH,n,t)},Dn=class{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=_t(),this._dEH=_t(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw a.methodUnimplemented()}clone(){throw a.methodUnimplemented()}_write(e){}get _first(){let e=this._start;for(;null!==e&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){St(this._eH,e)}observeDeep(e){St(this._dEH,e)}unobserve(e){kt(this._eH,e)}unobserveDeep(e){kt(this._dEH,e)}toJSON(){}},On=(e,t,n)=>{e.doc??kn(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let r=n-t;const i=[];let s=e._start;for(;null!==s&&r>0;){if(s.countable&&!s.deleted){const e=s.content.getContent();if(e.length<=t)t-=e.length;else{for(let n=t;n<e.length&&r>0;n++)i.push(e[n]),r--;t=0}}s=s.right}return i},Un=e=>{e.doc??kn();const t=[];let n=e._start;for(;null!==n;){if(n.countable&&!n.deleted){const e=n.content.getContent();for(let n=0;n<e.length;n++)t.push(e[n])}n=n.right}return t},Pn=(e,t)=>{let n=0,r=e._start;for(e.doc??kn();null!==r;){if(r.countable&&!r.deleted){const i=r.content.getContent();for(let r=0;r<i.length;r++)t(i[r],n++,e)}r=r.right}},Ln=(e,t)=>{const n=[];return Pn(e,(r,i)=>{n.push(t(r,i,e))}),n},Mn=e=>{let t=e._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(null===n){for(;null!==t&&t.deleted;)t=t.right;if(null===t)return{done:!0,value:void 0};n=t.content.getContent(),r=0,t=t.right}const e=n[r++];return n.length<=r&&(n=null),{done:!1,value:e}}}},In=(e,t)=>{e.doc??kn();const n=xn(e,t);let r=e._start;for(null!==n&&(r=n.p,t-=n.index);null!==r;r=r.right)if(!r.deleted&&r.countable){if(t<r.length)return r.content.getContent()[t];t-=r.length}},Nn=(e,t,n,r)=>{let i=n;const s=e.doc,o=s.clientID,a=s.store,c=null===n?t._start:n.right;let l=[];const d=()=>{l.length>0&&(i=new qr(xt(o,qt(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Rr(l)),i.integrate(e,0),l=[])};r.forEach(n=>{if(null===n)l.push(n);else switch(n.constructor){case Number:case Object:case Boolean:case Array:case String:l.push(n);break;default:switch(d(),n.constructor){case Uint8Array:case ArrayBuffer:i=new qr(xt(o,qt(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new _r(new Uint8Array(n))),i.integrate(e,0);break;case nt:i=new qr(xt(o,qt(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Cr(n)),i.integrate(e,0);break;default:if(!(n instanceof Dn))throw new Error("Unexpected content type in insert operation");i=new qr(xt(o,qt(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Vr(n)),i.integrate(e,0)}}}),d()},jn=()=>a.create$1("Length exceeded!"),Vn=(e,t,n,r)=>{if(n>t._length)throw jn();if(0===n)return t._searchMarker&&Tn(t._searchMarker,n,r.length),Nn(e,t,null,r);const i=n,s=xn(t,n);let o=t._start;for(null!==s&&(o=s.p,0===(n-=s.index)&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));null!==o;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n<o.length&&Qt(e,xt(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&Tn(t._searchMarker,i,r.length),Nn(e,t,o,r)},Fn=(e,t,n,r)=>{if(0===r)return;const i=n,s=r,o=xn(t,n);let a=t._start;for(null!==o&&(a=o.p,n-=o.index);null!==a&&n>0;a=a.right)!a.deleted&&a.countable&&(n<a.length&&Qt(e,xt(a.id.client,a.id.clock+n)),n-=a.length);for(;r>0&&null!==a;)a.deleted||(r<a.length&&Qt(e,xt(a.id.client,a.id.clock+r)),a.delete(e),r-=a.length),a=a.right;if(r>0)throw jn();t._searchMarker&&Tn(t._searchMarker,i,-s+r)},Bn=(e,t,n)=>{const r=t._map.get(n);void 0!==r&&r.delete(e)},Hn=(e,t,n,r)=>{const i=t._map.get(n)||null,s=e.doc,o=s.clientID;let a;if(null==r)a=new Rr([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:a=new Rr([r]);break;case Uint8Array:a=new _r(r);break;case nt:a=new Cr(r);break;default:if(!(r instanceof Dn))throw new Error("Unexpected content type");a=new Vr(r)}new qr(xt(o,qt(s.store,o)),i,i&&i.lastId,null,null,t,n,a).integrate(e,0)},Wn=(e,t)=>{e.doc??kn();const n=e._map.get(t);return void 0===n||n.deleted?void 0:n.content.getContent()[n.length-1]},Yn=e=>{const t={};return e.doc??kn(),e._map.forEach((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])}),t},qn=(e,t)=>{e.doc??kn();const n=e._map.get(t);return void 0!==n&&!n.deleted},Kn=e=>(e.doc??kn(),a.iteratorFilter(e._map.entries(),e=>!e[1].deleted)),zn=class extends _n{},$n=class e extends Dn{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new e;return n.push(t),n}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){const t=new e;return t.insert(0,this.toArray().map(e=>e instanceof Dn?e.clone():e)),t}get length(){return this.doc??kn(),this._length}_callObserver(e,t){super._callObserver(e,t),Rn(this,e,new zn(this,e))}insert(e,t){null!==this.doc?sn(this.doc,n=>{Vn(n,this,e,t)}):this._prelimContent.splice(e,0,...t)}push(e){null!==this.doc?sn(this.doc,t=>{((e,t,n)=>{let r=(t._searchMarker||[]).reduce((e,t)=>t.index>e.index?t:e,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;Nn(e,t,r,n)})(t,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,t=1){null!==this.doc?sn(this.doc,n=>{Fn(n,this,e,t)}):this._prelimContent.splice(e,t)}get(e){return In(this,e)}toArray(){return Un(this)}slice(e=0,t=this.length){return On(this,e,t)}toJSON(){return this.map(e=>e instanceof Dn?e.toJSON():e)}map(e){return Ln(this,e)}forEach(e){Pn(this,e)}[Symbol.iterator](){return Mn(this)}_write(e){e.writeTypeRef(Ur)}},Jn=class extends _n{constructor(e,t,n){super(e,t),this.keysChanged=n}},Qn=class e extends Dn{constructor(e){super(),this._prelimContent=null,this._prelimContent=void 0===e?new Map:new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach((e,t)=>{this.set(t,e)}),this._prelimContent=null}_copy(){return new e}clone(){const t=new e;return this.forEach((e,n)=>{t.set(n,e instanceof Dn?e.clone():e)}),t}_callObserver(e,t){Rn(this,e,new Jn(this,e,t))}toJSON(){this.doc??kn();const e={};return this._map.forEach((t,n)=>{if(!t.deleted){const r=t.content.getContent()[t.length-1];e[n]=r instanceof Dn?r.toJSON():r}}),e}get size(){return[...Kn(this)].length}keys(){return a.iteratorMap(Kn(this),e=>e[0])}values(){return a.iteratorMap(Kn(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return a.iteratorMap(Kn(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??kn(),this._map.forEach((t,n)=>{t.deleted||e(t.content.getContent()[t.length-1],n,this)})}[Symbol.iterator](){return this.entries()}delete(e){null!==this.doc?sn(this.doc,t=>{Bn(t,this,e)}):this._prelimContent.delete(e)}set(e,t){return null!==this.doc?sn(this.doc,n=>{Hn(n,this,e,t)}):this._prelimContent.set(e,t),t}get(e){return Wn(this,e)}has(e){return qn(this,e)}clear(){null!==this.doc?sn(this.doc,e=>{this.forEach(function(t,n,r){Bn(e,r,n)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(Pr)}},Gn=(e,t)=>e===t||"object"==typeof e&&"object"==typeof t&&e&&t&&a.equalFlat(e,t),Xn=class{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){if(null===this.right&&a.unexpectedCase(),this.right.content.constructor===Ar)this.right.deleted||nr(this.currentAttributes,this.right.content);else this.right.deleted||(this.index+=this.right.length);this.left=this.right,this.right=this.right.right}},Zn=(e,t,n)=>{for(;null!==t.right&&n>0;){if(t.right.content.constructor===Ar)t.right.deleted||nr(t.currentAttributes,t.right.content);else t.right.deleted||(n<t.right.length&&Qt(e,xt(t.right.id.client,t.right.id.clock+n)),t.index+=t.right.length,n-=t.right.length);t.left=t.right,t.right=t.right.right}return t},er=(e,t,n,r)=>{const i=new Map,s=r?xn(t,n):null;if(s){const t=new Xn(s.p.left,s.p,s.index,i);return Zn(e,t,n-s.index)}{const r=new Xn(null,t._start,0,i);return Zn(e,r,n)}},tr=(e,t,n,r)=>{for(;null!==n.right&&(!0===n.right.deleted||n.right.content.constructor===Ar&&Gn(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();const i=e.doc,s=i.clientID;r.forEach((r,o)=>{const a=n.left,c=n.right,l=new qr(xt(s,qt(i.store,s)),a,a&&a.lastId,c,c&&c.id,t,null,new Ar(o,r));l.integrate(e,0),n.right=l,n.forward()})},nr=(e,t)=>{const{key:n,value:r}=t;null===r?e.delete(n):e.set(n,r)},rr=(e,t)=>{for(;null!==e.right&&(e.right.deleted||e.right.content.constructor===Ar&&Gn(t[e.right.content.key]??null,e.right.content.value));)e.forward()},ir=(e,t,n,r)=>{const i=e.doc,s=i.clientID,o=new Map;for(const a in r){const c=r[a],l=n.currentAttributes.get(a)??null;if(!Gn(l,c)){o.set(a,l);const{left:r,right:d}=n;n.right=new qr(xt(s,qt(i.store,s)),r,r&&r.lastId,d,d&&d.id,t,null,new Ar(a,c)),n.right.integrate(e,0),n.forward()}}return o},sr=(e,t,n,r,i)=>{n.currentAttributes.forEach((e,t)=>{void 0===i[t]&&(i[t]=null)});const s=e.doc,o=s.clientID;rr(n,i);const a=ir(e,t,n,i),c=r.constructor===String?new Dr(r):r instanceof Dn?new Vr(r):new Er(r);let{left:l,right:d,index:h}=n;t._searchMarker&&Tn(t._searchMarker,n.index,c.getLength()),d=new qr(xt(o,qt(s.store,o)),l,l&&l.lastId,d,d&&d.id,t,null,c),d.integrate(e,0),n.right=d,n.index=h,n.forward(),tr(e,t,n,a)},or=(e,t,n,r,i)=>{const s=e.doc,o=s.clientID;rr(n,i);const a=ir(e,t,n,i);e:for(;null!==n.right&&(r>0||a.size>0&&(n.right.deleted||n.right.content.constructor===Ar));){if(!n.right.deleted)switch(n.right.content.constructor){case Ar:{const{key:t,value:s}=n.right.content,o=i[t];if(void 0!==o){if(Gn(o,s))a.delete(t);else{if(0===r)break e;a.set(t,s)}n.right.delete(e)}else n.currentAttributes.set(t,s);break}default:r<n.right.length&&Qt(e,xt(n.right.id.client,n.right.id.clock+r)),r-=n.right.length}n.forward()}if(r>0){let i="";for(;r>0;r--)i+="\n";n.right=new qr(xt(o,qt(s.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Dr(i)),n.right.integrate(e,0),n.forward()}tr(e,t,n,a)},ar=(e,t,n,r,i)=>{let s=t;const o=a.create$3();for(;s&&(!s.countable||s.deleted);){if(!s.deleted&&s.content.constructor===Ar){const e=s.content;o.set(e.key,e)}s=s.right}let c=0,l=!1;for(;t!==s;){if(n===t&&(l=!0),!t.deleted){const n=t.content;switch(n.constructor){case Ar:{const{key:s,value:a}=n,d=r.get(s)??null;o.get(s)===n&&d!==a||(t.delete(e),c++,l||(i.get(s)??null)!==a||d===a||(null===d?i.delete(s):i.set(s,d))),l||t.deleted||nr(i,n);break}}}t=t.right}return c},cr=e=>{let t=0;return sn(e.doc,n=>{let r=e._start,i=e._start,s=a.create$3();const o=a.copy(s);for(;i;){if(!1===i.deleted)if(i.content.constructor===Ar)nr(o,i.content);else t+=ar(n,r,i,s,o),s=a.copy(o),r=i;i=i.right}}),t},lr=e=>{const t=new Set,n=e.doc;for(const[r,i]of e.afterState.entries()){const s=e.beforeState.get(r)||0;i!==s&&Xt(e,n.store.clients.get(r),s,i,e=>{e.deleted||e.content.constructor!==Ar||e.constructor===vr||t.add(e.parent)})}sn(n,n=>{Ke(e,e.deleteSet,e=>{if(e instanceof vr||!e.parent._hasFormatting||t.has(e.parent))return;const r=e.parent;e.content.constructor===Ar?t.add(r):((e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===Ar){const r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}})(n,e)});for(const e of t)cr(e)})},dr=(e,t,n)=>{const r=n,i=a.copy(t.currentAttributes),s=t.right;for(;n>0&&null!==t.right;){if(!1===t.right.deleted)switch(t.right.content.constructor){case Vr:case Er:case Dr:n<t.right.length&&Qt(e,xt(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e)}t.forward()}s&&ar(e,s,t.right,i,t.currentAttributes);const o=(t.left||t.right).parent;return o._searchMarker&&Tn(o._searchMarker,t.index,-r+n),t},hr=class extends _n{constructor(e,t,n){super(e,t),this.childListChanged=!1,this.keysChanged=new Set,n.forEach(e=>{null===e?this.childListChanged=!0:this.keysChanged.add(e)})}get changes(){if(null===this._changes){const e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(null===this._delta){const e=this.target.doc,t=[];sn(e,e=>{const n=new Map,r=new Map;let i=this.target._start,s=null;const o={};let c="",l=0,d=0;const h=()=>{if(null!==s){let e=null;switch(s){case"delete":d>0&&(e={delete:d}),d=0;break;case"insert":("object"==typeof c||c.length>0)&&(e={insert:c},n.size>0&&(e.attributes={},n.forEach((t,n)=>{null!==t&&(e.attributes[n]=t)}))),c="";break;case"retain":l>0&&(e={retain:l},a.isEmpty(o)||(e.attributes=a.assign({},o))),l=0}e&&t.push(e),s=null}};for(;null!==i;){switch(i.content.constructor){case Vr:case Er:this.adds(i)?this.deletes(i)||(h(),s="insert",c=i.content.getContent()[0],h()):this.deletes(i)?("delete"!==s&&(h(),s="delete"),d+=1):i.deleted||("retain"!==s&&(h(),s="retain"),l+=1);break;case Dr:this.adds(i)?this.deletes(i)||("insert"!==s&&(h(),s="insert"),c+=i.content.str):this.deletes(i)?("delete"!==s&&(h(),s="delete"),d+=i.length):i.deleted||("retain"!==s&&(h(),s="retain"),l+=i.length);break;case Ar:{const{key:t,value:a}=i.content;if(this.adds(i)){if(!this.deletes(i)){const c=n.get(t)??null;Gn(c,a)?null!==a&&i.delete(e):("retain"===s&&h(),Gn(a,r.get(t)??null)?delete o[t]:o[t]=a)}}else if(this.deletes(i)){r.set(t,a);const e=n.get(t)??null;Gn(e,a)||("retain"===s&&h(),o[t]=e)}else if(!i.deleted){r.set(t,a);const n=o[t];void 0!==n&&(Gn(n,a)?null!==n&&i.delete(e):("retain"===s&&h(),null===a?delete o[t]:o[t]=a))}i.deleted||("insert"===s&&h(),nr(n,i.content));break}}i=i.right}for(h();t.length>0;){const e=t[t.length-1];if(void 0===e.retain||void 0!==e.attributes)break;t.pop()}}),this._delta=t}return this._delta}},ur=class e extends Dn{constructor(e){super(),this._pending=void 0!==e?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??kn(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(e=>e())}catch(n){}this._pending=null}_copy(){return new e}clone(){const t=new e;return t.applyDelta(this.toDelta()),t}_callObserver(e,t){super._callObserver(e,t);const n=new hr(this,e,t);Rn(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??kn();let e="",t=this._start;for(;null!==t;)!t.deleted&&t.countable&&t.content.constructor===Dr&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){null!==this.doc?sn(this.doc,n=>{const r=new Xn(null,this._start,0,new Map);for(let i=0;i<e.length;i++){const s=e[i];if(void 0!==s.insert){const o=t||"string"!=typeof s.insert||i!==e.length-1||null!==r.right||"\n"!==s.insert.slice(-1)?s.insert:s.insert.slice(0,-1);("string"!=typeof o||o.length>0)&&sr(n,this,r,o,s.attributes||{})}else void 0!==s.retain?or(n,this,r,s.retain,s.attributes||{}):void 0!==s.delete&&dr(n,r,s.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,t,n){this.doc??kn();const r=[],i=new Map,s=this.doc;let o="",a=this._start;function c(){if(o.length>0){const e={};let t=!1;i.forEach((n,r)=>{t=!0,e[r]=n});const n={insert:o};t&&(n.attributes=e),r.push(n),o=""}}const l=()=>{for(;null!==a;){if(Bt(a,e)||void 0!==t&&Bt(a,t))switch(a.content.constructor){case Dr:{const r=i.get("ychange");void 0===e||Bt(a,e)?void 0===t||Bt(a,t)?void 0!==r&&(c(),i.delete("ychange")):void 0!==r&&r.user===a.id.client&&"added"===r.type||(c(),i.set("ychange",n?n("added",a.id):{type:"added"})):void 0!==r&&r.user===a.id.client&&"removed"===r.type||(c(),i.set("ychange",n?n("removed",a.id):{type:"removed"})),o+=a.content.str;break}case Vr:case Er:{c();const e={insert:a.content.getContent()[0]};if(i.size>0){const t={};e.attributes=t,i.forEach((e,n)=>{t[n]=e})}r.push(e);break}case Ar:Bt(a,e)&&(c(),nr(i,a.content))}a=a.right}c()};return e||t?sn(s,n=>{e&&Ht(n,e),t&&Ht(n,t),l()},"cleanup"):l(),r}insert(e,t,n){if(t.length<=0)return;const r=this.doc;null!==r?sn(r,r=>{const i=er(r,this,e,!n);n||(n={},i.currentAttributes.forEach((e,t)=>{n[t]=e})),sr(r,this,i,t,n)}):this._pending.push(()=>this.insert(e,t,n))}insertEmbed(e,t,n){const r=this.doc;null!==r?sn(r,r=>{const i=er(r,this,e,!n);sr(r,this,i,t,n||{})}):this._pending.push(()=>this.insertEmbed(e,t,n||{}))}delete(e,t){if(0===t)return;const n=this.doc;null!==n?sn(n,n=>{dr(n,er(n,this,e,!0),t)}):this._pending.push(()=>this.delete(e,t))}format(e,t,n){if(0===t)return;const r=this.doc;null!==r?sn(r,r=>{const i=er(r,this,e,!1);null!==i.right&&or(r,this,i,t,n)}):this._pending.push(()=>this.format(e,t,n))}removeAttribute(e){null!==this.doc?sn(this.doc,t=>{Bn(t,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,t){null!==this.doc?sn(this.doc,n=>{Hn(n,this,e,t)}):this._pending.push(()=>this.setAttribute(e,t))}getAttribute(e){return Wn(this,e)}getAttributes(){return Yn(this)}_write(e){e.writeTypeRef(Lr)}},fr=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??kn()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(null!==e&&(!this._firstCall||e.deleted||!this._filter(t)))do{if(t=e.content.type,e.deleted||t.constructor!==pr&&t.constructor!==gr||null===t._start)for(;null!==e;){const t=e.next;if(null!==t){e=t;break}e=e.parent===this._root?null:e.parent._item}else e=t._start}while(null!==e&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,null===e?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}},gr=class e extends Dn{constructor(){super(),this._prelimContent=[]}get firstChild(){const e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){const t=new e;return t.insert(0,this.toArray().map(e=>e instanceof Dn?e.clone():e)),t}get length(){return this.doc??kn(),null===this._prelimContent?this._length:this._prelimContent.length}createTreeWalker(e){return new fr(this,e)}querySelector(e){e=e.toUpperCase();const t=new fr(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),a.from(new fr(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){Rn(this,e,new mr(this,t,e))}toString(){return Ln(this,e=>e.toString()).join("")}toJSON(){return this.toString()}toDOM(e=document,t={},n){const r=e.createDocumentFragment();return void 0!==n&&n._createAssociation(r,this),Pn(this,i=>{r.insertBefore(i.toDOM(e,t,n),null)}),r}insert(e,t){null!==this.doc?sn(this.doc,n=>{Vn(n,this,e,t)}):this._prelimContent.splice(e,0,...t)}insertAfter(e,t){if(null!==this.doc)sn(this.doc,n=>{const r=e&&e instanceof Dn?e._item:e;Nn(n,this,r,t)});else{const n=this._prelimContent,r=null===e?0:n.findIndex(t=>t===e)+1;if(0===r&&null!==e)throw a.create$1("Reference item not found");n.splice(r,0,...t)}}delete(e,t=1){null!==this.doc?sn(this.doc,n=>{Fn(n,this,e,t)}):this._prelimContent.splice(e,t)}toArray(){return Un(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return In(this,e)}slice(e=0,t=this.length){return On(this,e,t)}forEach(e){Pn(this,e)}_write(e){e.writeTypeRef(Ir)}},pr=class e extends gr{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((e,t)=>{this.setAttribute(t,e)}),this._prelimAttrs=null}_copy(){return new e(this.nodeName)}clone(){const t=new e(this.nodeName),n=this.getAttributes();return a.forEach(n,(e,n)=>{t.setAttribute(n,e)}),t.insert(0,this.toArray().map(e=>e instanceof Dn?e.clone():e)),t}toString(){const e=this.getAttributes(),t=[],n=[];for(const s in e)n.push(s);n.sort();const r=n.length;for(let s=0;s<r;s++){const r=n[s];t.push(r+'="'+e[r]+'"')}const i=this.nodeName.toLocaleLowerCase();return`<${i}${t.length>0?" "+t.join(" "):""}>${super.toString()}</${i}>`}removeAttribute(e){null!==this.doc?sn(this.doc,t=>{Bn(t,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,t){null!==this.doc?sn(this.doc,n=>{Hn(n,this,e,t)}):this._prelimAttrs.set(e,t)}getAttribute(e){return Wn(this,e)}hasAttribute(e){return qn(this,e)}getAttributes(e){return e?((e,t)=>{const n={};return e._map.forEach((e,r)=>{let i=e;for(;null!==i&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;null!==i&&Bt(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n})(this,e):Yn(this)}toDOM(e=document,t={},n){const r=e.createElement(this.nodeName),i=this.getAttributes();for(const s in i){const e=i[s];"string"==typeof e&&r.setAttribute(s,e)}return Pn(this,i=>{r.appendChild(i.toDOM(e,t,n))}),void 0!==n&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(Mr),e.writeKey(this.nodeName)}},mr=class extends _n{constructor(e,t,n){super(e,n),this.childListChanged=!1,this.attributesChanged=new Set,t.forEach(e=>{null===e?this.childListChanged=!0:this.attributesChanged.add(e)})}},yr=class e extends Qn{constructor(e){super(),this.hookName=e}_copy(){return new e(this.hookName)}clone(){const t=new e(this.hookName);return this.forEach((e,n)=>{t.set(n,e)}),t}toDOM(e=document,t={},n){const r=t[this.hookName];let i;return i=void 0!==r?r.createDom(this):document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),void 0!==n&&n._createAssociation(i,this),i}_write(e){e.writeTypeRef(Nr),e.writeKey(this.hookName)}},wr=class e extends ur{get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new e}clone(){const t=new e;return t.applyDelta(this.toDelta()),t}toDOM(e=document,t,n){const r=e.createTextNode(this.toString());return void 0!==n&&n._createAssociation(r,this),r}toString(){return this.toDelta().map(e=>{const t=[];for(const r in e.attributes){const n=[];for(const t in e.attributes[r])n.push({key:t,value:e.attributes[r][t]});n.sort((e,t)=>e.key<t.key?-1:1),t.push({nodeName:r,attrs:n})}t.sort((e,t)=>e.nodeName<t.nodeName?-1:1);let n="";for(let r=0;r<t.length;r++){const e=t[r];n+=`<${e.nodeName}`;for(let t=0;t<e.attrs.length;t++){const r=e.attrs[t];n+=` ${r.key}="${r.value}"`}n+=">"}n+=e.insert;for(let r=t.length-1;r>=0;r--)n+=`</${t[r].nodeName}>`;return n}).join("")}toJSON(){return this.toString()}_write(e){e.writeTypeRef(jr)}},br=class{constructor(e,t){this.id=e,this.length=t}get deleted(){throw a.methodUnimplemented()}mergeWith(e){return!1}write(e,t,n){throw a.methodUnimplemented()}integrate(e,t){throw a.methodUnimplemented()}},vr=class extends br{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){t>0&&(this.id.clock+=t,this.length-=t),Kt(e.doc.store,this)}write(e,t){e.writeInfo(0),e.writeLen(this.length-t)}getMissing(e,t){return null}},_r=class e{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new e(this.content)}splice(e){throw a.methodUnimplemented()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}},Sr=class e{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.len)}splice(t){const n=new e(this.len-t);return this.len=t,n}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){Qe(e.deleteSet,t.id.client,t.id.clock,this.len),t.markDeleted()}delete(e){}gc(e){}write(e,t){e.writeLen(this.len-t)}getRef(){return 1}},kr=(e,t)=>new nt({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1}),Cr=class e{constructor(e){e._item,this.doc=e;const t={};this.opts=t,e.gc||(t.gc=!1),e.autoLoad&&(t.autoLoad=!0),null!==e.meta&&(t.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new e(kr(this.doc.guid,this.opts))}splice(e){throw a.methodUnimplemented()}mergeWith(e){return!1}integrate(e,t){this.doc._item=t,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,t){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}},Er=class e{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new e(this.embed)}splice(e){throw a.methodUnimplemented()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}},Ar=class e{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.key,this.value)}splice(e){throw a.methodUnimplemented()}mergeWith(e){return!1}integrate(e,t){const n=t.parent;n._searchMarker=null,n._hasFormatting=!0}delete(e){}gc(e){}write(e,t){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}},xr=class e{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){const n=new e(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){const n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){const t=this.arr[r];e.writeString(void 0===t?"undefined":JSON.stringify(t))}}getRef(){return 2}},Tr="development"===a.getVariable("node_env"),Rr=class e{constructor(e){this.arr=e,Tr&&a.deepFreeze(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){const n=new e(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){const n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){const t=this.arr[r];e.writeAny(t)}}getRef(){return 8}},Dr=class e{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new e(this.str)}splice(t){const n=new e(this.str.slice(t));this.str=this.str.slice(0,t);const r=this.str.charCodeAt(t-1);return r>=55296&&r<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(e){return this.str+=e.str,!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeString(0===t?this.str:this.str.slice(t))}getRef(){return 4}},Or=[e=>new $n,e=>new Qn,e=>new ur,e=>new pr(e.readKey()),e=>new gr,e=>new yr(e.readKey()),e=>new wr],Ur=0,Pr=1,Lr=2,Mr=3,Ir=4,Nr=5,jr=6,Vr=class e{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new e(this.type._copy())}splice(e){throw a.methodUnimplemented()}mergeWith(e){return!1}integrate(e,t){this.type._integrate(e.doc,t)}delete(e){let t=this.type._start;for(;null!==t;)t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e),t=t.right;this.type._map.forEach(t=>{t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e)}),e.changed.delete(this.type)}gc(e){let t=this.type._start;for(;null!==t;)t.gc(e,!0),t=t.right;this.type._start=null,this.type._map.forEach(t=>{for(;null!==t;)t.gc(e,!0),t=t.left}),this.type._map=new Map}write(e,t){this.type._write(e)}getRef(){return 7}},Fr=(e,t)=>{let n,r=t,i=0;do{i>0&&(r=xt(r.client,r.clock+i)),n=$t(e,r),i=r.clock-n.id.clock,r=n.redone}while(null!==r&&n instanceof qr);return{item:n,diff:i}},Br=(e,t)=>{for(;null!==e&&e.keep!==t;)e.keep=t,e=e.parent._item},Hr=(e,t,n)=>{const{client:r,clock:i}=t.id,s=new qr(xt(r,i+n),t,xt(r,i+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&s.markDeleted(),t.keep&&(s.keep=!0),null!==t.redone&&(s.redone=xt(t.redone.client,t.redone.clock+n)),t.right=s,null!==s.right&&(s.right.left=s),e._mergeStructs.push(s),null!==s.parentSub&&null===s.right&&s.parent._map.set(s.parentSub,s),t.length=n,s},Wr=(e,t)=>a.some(e,e=>ze(e.deletions,t)),Yr=(e,t,n,r,i,s)=>{const o=e.doc,a=o.store,c=o.clientID,l=t.redone;if(null!==l)return Qt(e,l);let d,h=t.parent._item,u=null;if(null!==h&&!0===h.deleted){if(null===h.redone&&(!n.has(h)||null===Yr(e,h,n,r,i,s)))return null;for(;null!==h.redone;)h=Qt(e,h.redone)}const f=null===h?t.parent:h.content.type;if(null===t.parentSub){for(u=t.left,d=t;null!==u;){let t=u;for(;null!==t&&t.parent._item!==h;)t=null===t.redone?null:Qt(e,t.redone);if(null!==t&&t.parent._item===h){u=t;break}u=u.left}for(;null!==d;){let t=d;for(;null!==t&&t.parent._item!==h;)t=null===t.redone?null:Qt(e,t.redone);if(null!==t&&t.parent._item===h){d=t;break}d=d.right}}else{if(d=null,t.right&&!i){for(u=t;null!==u&&null!==u.right&&(u.right.redone||ze(r,u.right.id)||Wr(s.undoStack,u.right.id)||Wr(s.redoStack,u.right.id));)for(u=u.right;u.redone;)u=Qt(e,u.redone);if(u&&null!==u.right)return null}else u=f._map.get(t.parentSub)||null;null!==u&&u.parent._item!==h&&(u=f._map.get(t.parentSub)||null)}const g=qt(a,c),p=xt(c,g),m=new qr(p,u,u&&u.lastId,d,d&&d.id,f,t.parentSub,t.content.copy());return t.redone=p,Br(m,!0),m.integrate(e,0),m},qr=class e extends br{constructor(e,t,n,r,i,s,o,a){super(e,a.getLength()),this.origin=n,this.left=t,this.right=r,this.rightOrigin=i,this.parent=s,this.parentSub=o,this.redone=null,this.content=a,this.info=this.content.isCountable()?2:0}set marker(e){(8&this.info)>0!==e&&(this.info^=8)}get marker(){return(8&this.info)>0}get keep(){return(1&this.info)>0}set keep(e){this.keep!==e&&(this.info^=1)}get countable(){return(2&this.info)>0}get deleted(){return(4&this.info)>0}set deleted(e){this.deleted!==e&&(this.info^=4)}markDeleted(){this.info|=4}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=qt(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=qt(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Et&&this.id.client!==this.parent.client&&this.parent.clock>=qt(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Gt(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=Qt(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===vr||this.right&&this.right.constructor===vr)this.parent=null;else if(this.parent){if(this.parent.constructor===Et){const e=$t(n,this.parent);e.constructor===vr?this.parent=null:this.parent=e.content.type}}else this.left&&this.left.constructor===e?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===e&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=Gt(e,e.doc.store,xt(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(t),this.length-=t),this.parent){if(!this.left&&(!this.right||null!==this.right.left)||this.left&&this.left.right!==this.right){let t,n=this.left;if(null!==n)t=n.right;else if(null!==this.parentSub)for(t=this.parent._map.get(this.parentSub)||null;null!==t&&null!==t.left;)t=t.left;else t=this.parent._start;const r=new Set,i=new Set;for(;null!==t&&t!==this.right;){if(i.add(t),r.add(t),At(this.origin,t.origin)){if(t.id.client<this.id.client)n=t,r.clear();else if(At(this.rightOrigin,t.rightOrigin))break}else{if(null===t.origin||!i.has($t(e.doc.store,t.origin)))break;r.has($t(e.doc.store,t.origin))||(n=t,r.clear())}t=t.right}this.left=n}if(null!==this.left){const e=this.left.right;this.right=e,this.left.right=this}else{let e;if(null!==this.parentSub)for(e=this.parent._map.get(this.parentSub)||null;null!==e&&null!==e.left;)e=e.left;else e=this.parent._start,this.parent._start=this;this.right=e}null!==this.right?this.right.left=this:null!==this.parentSub&&(this.parent._map.set(this.parentSub,this),null!==this.left&&this.left.delete(e)),null===this.parentSub&&this.countable&&!this.deleted&&(this.parent._length+=this.length),Kt(e.doc.store,this),this.content.integrate(e,this),tn(e,this.parent,this.parentSub),(null!==this.parent._item&&this.parent._item.deleted||null!==this.parentSub&&null!==this.right)&&this.delete(e)}else new vr(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;null!==e&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;null!==e&&e.deleted;)e=e.left;return e}get lastId(){return 1===this.length?this.id:xt(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&At(e.origin,this.lastId)&&this.right===e&&At(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&null===this.redone&&null===e.redone&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){const t=this.parent._searchMarker;return t&&t.forEach(t=>{t.p===e&&(t.p=this,!this.deleted&&this.countable&&(t.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,null!==this.right&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){const t=this.parent;this.countable&&null===this.parentSub&&(t._length-=this.length),this.markDeleted(),Qe(e.deleteSet,this.id.client,this.id.clock,this.length),tn(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw a.unexpectedCase();this.content.gc(e),t?((e,t,n)=>{const r=e.clients.get(t.id.client);r[zt(r,t.id.clock)]=n})(e,this,new vr(this.id,this.length)):this.content=new Sr(this.length)}write(e,t){const n=t>0?xt(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,i=this.parentSub,s=31&this.content.getRef()|(null===n?0:128)|(null===r?0:64)|(null===i?0:32);if(e.writeInfo(s),null!==n&&e.writeLeftID(n),null!==r&&e.writeRightID(r),null===n&&null===r){const t=this.parent;if(void 0!==t._item){const n=t._item;if(null===n){const n=Dt(t);e.writeParentInfo(!0),e.writeString(n)}else e.writeParentInfo(!1),e.writeLeftID(n.id)}else t.constructor===String?(e.writeParentInfo(!0),e.writeString(t)):t.constructor===Et?(e.writeParentInfo(!1),e.writeLeftID(t)):a.unexpectedCase();null!==i&&e.writeString(i)}this.content.write(e,t)}},Kr=(e,t)=>zr[31&t](e),zr=[()=>{a.unexpectedCase()},e=>new Sr(e.readLen()),e=>{const t=e.readLen(),n=[];for(let r=0;r<t;r++){const t=e.readString();"undefined"===t?n.push(void 0):n.push(JSON.parse(t))}return new xr(n)},e=>new _r(e.readBuf()),e=>new Dr(e.readString()),e=>new Er(e.readJSON()),e=>new Ar(e.readKey(),e.readJSON()),e=>new Vr(Or[e.readTypeRef()](e)),e=>{const t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new Rr(n)},e=>new Cr(kr(e.readString(),e.readAny())),()=>{a.unexpectedCase()}],$r=class extends br{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){a.unexpectedCase()}write(e,t){e.writeInfo(10),a.writeVarUint(e.restEncoder,this.length-t)}getMissing(e,t){return null}},Jr="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},Qr="__ $YJS$ __";Jr[Qr],Jr[Qr]=!0;var Gr=Object.defineProperty,Xr=Object.defineProperties,Zr=Object.getOwnPropertyDescriptors,ei=Object.getOwnPropertySymbols,ti=Object.prototype.hasOwnProperty,ni=Object.prototype.propertyIsEnumerable,ri=(e,t,n)=>t in e?Gr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ii=(e,t)=>{for(var n in t||(t={}))ti.call(t,n)&&ri(e,n,t[n]);if(ei)for(var n of ei(t))ni.call(t,n)&&ri(e,n,t[n]);return e},si=(e,t)=>Xr(e,Zr(t)),oi=(e,t)=>{var n={};for(var r in e)ti.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&ei)for(var r of ei(e))t.indexOf(r)<0&&ni.call(e,r)&&(n[r]=e[r]);return n};function ai(e){return"[object Object]"===Object.prototype.toString.call(e)}function ci(e){if(!ai(e))return!1;const t=e.constructor;if(void 0===t)return!0;const n=t.prototype;return!1!==ai(n)&&!1!==n.hasOwnProperty("isPrototypeOf")}function li(e,t){for(const n in e){const r=e[n],i=t[n];if(ci(r)&&ci(i)){if(!li(r,i))return!1}else if(Array.isArray(r)&&Array.isArray(i)){if(r.length!==i.length)return!1;for(let e=0;e<r.length;e++)if(r[e]!==i[e])return!1}else if(r!==i)return!1}for(const n in t)if(void 0===e[n]&&void 0!==t[n])return!1;return!0}function di(e,...t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e)))}function hi(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>null!==e))}function ui(e){return function(e){var t,n;const r=[];for(const i of e){if("string"==typeof i.insert&&0===i.insert.length)continue;const e=r[r.length-1];e&&"string"==typeof e.insert&&"string"==typeof i.insert&&(e.attributes===i.attributes||!e.attributes==!i.attributes&&li(null!=(t=e.attributes)?t:{},null!=(n=i.attributes)?n:{}))?e.insert+=i.insert:r.push(i)}return r}(e.toDelta())}function fi({insert:e}){return"string"==typeof e?e.length:1}function gi(e){return e.reduce((e,t)=>e+fi(t),0)}function pi(e,t,n){if(n<1)return[];let r=0;const i=[],s=t+n;for(let o=0;o<e.length&&!(r>=s);o++){const n=e[o],a=fi(n);if(r+a<=t){r+=a;continue}if("string"!=typeof n.insert){r+=a,i.push(n);continue}const c=Math.max(0,t-r),l=Math.min(a,a-(r+a-s));i.push(si(ii({},n),{insert:n.insert.slice(c,l)})),r+=a}return i}function mi(e){return function(e,...t){return Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e)))}(e,i.Text.isText(e)?"text":"children")}function yi(e){const t=ui(e),n=t.length>0?t.map(wi):[{text:""}];return si(ii({},e.getAttributes()),{children:n})}function wi(e){return"string"==typeof e.insert?si(ii({},e.attributes),{text:e.insert}):yi(e.insert)}function bi(e){return e.map(e=>i.Text.isText(e)?{insert:e.text,attributes:mi(e)}:{insert:vi(e)})}function vi(e){var t=e,{children:n}=t,r=oi(t,["children"]);const i=new wr;return Object.entries(r).forEach(([e,t])=>{i.setAttribute(e,t)}),i.applyDelta(bi(n),{sanitize:!1}),i}function _i(e){return e?i.Text.isText(e)?e.text.length:1:0}function Si(e,t,n){var r;if(0===n.length)throw new Error("Path has to a have a length >= 1");if(i.Text.isText(t))throw new Error("Cannot descent into slate text");const[s,...o]=n,a=function(e,t){return e.children.slice(0,t).reduce((e,t)=>e+_i(t),0)}(t,s),c=t.children[s],l=ui(e),d=_i(c),h=pi(l,a,d);if(h.length>1)throw new Error("Path doesn't match yText, yTarget spans multiple nodes");const u=null==(r=h[0])?void 0:r.insert;if(o.length>0){if(!(u instanceof wr))throw new Error("Path doesn't match yText, cannot descent into non-yText");return Si(u,c,o)}return{yParent:e,textRange:{start:a,end:a+d},yTarget:u instanceof wr?u:void 0,slateParent:t,slateTarget:c,targetDelta:h}}function ki(e,t,n={}){const{assoc:r=0,insert:s=!1}=n;let o=0,a=0;for(let l=0;l<e.children.length;l++){const n=e.children[l],s=i.Text.isText(n)?n.text.length:1;s>0&&(a=l);const c=o+s;if(s>0&&(r>=0?c>t:c>=t))return[l,t-o];o+=s}if(t>o+(s?1:0))throw new Error("yOffset out of bounds");if(s)return[e.children.length,0];const c=e.children[a];return[a,i.Text.isText(c)?c.text.length:1]}function Ci(e,t,n){const r=[n];for(;r[0]!==e;){const{parent:e}=r[0];if(!e)throw new Error("yText isn't a descendant of root element");if(!(e instanceof wr))throw new Error("Unexpected y parent type");r.unshift(e)}if(r.length<2)return[];let s=t;return r.reduce((e,t,n)=>{const o=r[n+1];if(!o)return e;let a=0;const c=ui(t);for(const r of c){if(r.insert===o)break;a+="string"==typeof r.insert?r.insert.length:1}if(i.Text.isText(s))throw new Error("Cannot descent into slate text");const[l]=ki(s,a);return s=s.children[l],e.concat(l)},[])}function Ei(e,t,n){const{target:r,changes:s}=n,o=n.delta;if(!(r instanceof wr))throw new Error("Unexpected target node type");const a=[],c=Ci(e,t,r),l=i.Node.get(t,c);if(i.Text.isText(l))throw new Error("Cannot apply yTextEvent to text node");const d=Array.from(s.keys.entries());if(c.length>0&&d.length>0){const e=Object.fromEntries(d.map(([e,t])=>[e,"delete"===t.action?null:r.getAttribute(e)])),t=Object.fromEntries(d.map(([e])=>[e,l[e]]));a.push({type:"set_node",newProperties:e,properties:t,path:c})}return o.length>0&&a.push(...function(e,t,n){const r=[];let s=n.reduce((e,t)=>"retain"in t?e+t.retain:"delete"in t?e+t.delete:e,0);return n.reverse().forEach(n=>{var o;if("attributes"in n&&"retain"in n){const[o,a]=ki(e,s-n.retain),[c,l]=ki(e,s,{assoc:-1});for(let s=c;s>=o;s--){const d=e.children[s],h=[...t,s];if(!i.Text.isText(d))continue;const u=n.attributes,f=di(e,...Object.keys(n.attributes));if(s===o||s===c){const e=s===o?a:0,t=s===c?l:d.text.length;if(t!==d.text.length&&r.push({type:"split_node",path:h,position:t,properties:mi(d)}),0!==e){r.push({type:"split_node",path:h,position:e,properties:hi(ii(ii({},mi(d)),u))});continue}}r.push({type:"set_node",newProperties:u,path:h,properties:f})}}if("retain"in n&&(s-=n.retain),"delete"in n){const[o,a]=ki(e,s-n.delete),[c,l]=ki(e,s,{assoc:-1});for(let n=0===l?c-1:c;n>=o;n--){const d=e.children[n],h=[...t,n];if(i.Text.isText(d)&&(n===o||n===c)){const e=n===o?a:0,t=n===c?l:d.text.length;r.push({type:"remove_text",offset:e,text:d.text.slice(e,t),path:h}),s-=t-e;continue}r.push({type:"remove_node",node:d,path:h}),s-=_i(d)}return}if("insert"in n){const[a,c]=ki(e,s,{insert:!0}),l=e.children[a],d=[...t,a];if(i.Text.isText(l)){const e=r[r.length-1],t=null!=e&&"insert_node"===e.type?e.node:mi(l);let s=[];if(null==e||"insert_node"!==e.type&&"insert_text"!==e.type&&"split_node"!==e.type&&"set_node"!==e.type||(s=e.path),"string"==typeof n.insert&&li(null!=(o=n.attributes)?o:{},t)&&i.Path.equals(d,s))return r.push({type:"insert_text",offset:c,text:n.insert,path:d});const a=wi(n);return 0===c?r.push({type:"insert_node",path:d,node:a}):(c<l.text.length&&r.push({type:"split_node",path:d,position:c,properties:mi(l)}),r.push({type:"insert_node",path:i.Path.next(d),node:a}))}return r.push({type:"insert_node",path:d,node:wi(n)})}}),r}(l,c,o)),a}function Ai(e,t,n){i.Editor$1.withoutNormalizing(t,()=>{n.forEach(n=>{(function(e,t,n){if(n instanceof hr)return Ei(e,t,n);throw new Error("Unexpected Y event type")})(e,t,n).forEach(e=>{t.apply(e)})})})}function xi(e){return e.map(e=>"string"==typeof e.insert?e:si(ii({},e),{insert:Ti(e.insert)}))}function Ti(e){const t=new wr,n=e.getAttributes();return Object.entries(n).forEach(([e,n])=>{t.setAttribute(e,n)}),t.applyDelta(xi(ui(e)),{sanitize:!1}),t}function Ri(e){if(!e.doc)throw new Error("shared type isn't attached to a document")}var Di="__slateYjsStoredPosition_";function Oi(e,t,n){const{yTarget:r,yParent:i,textRange:s}=Si(e,t,n.path);if(r)throw new Error("Slate point points to a non-text element inside sharedRoot");const o=s.start+n.offset;return Mt(i,o,o===s.end?-1:0)}function Ui(e,t,n){if(!e.doc)throw new Error("sharedRoot isn't attach to a yDoc");const r=jt(n,e.doc);return r&&function(e,t,{type:n,index:r,assoc:s}){if(!(n instanceof wr))throw new Error("Absolute position points to a non-XMLText");const o=Ci(e,t,n),a=i.Node.get(t,o);if(i.Text.isText(a))throw new Error("Absolute position doesn't match slateRoot, cannot descent into text");const[c,l]=ki(a,r,{assoc:s}),d=a.children[c];return i.Text.isText(d)?{path:[...o,c],offset:l}:null}(e,t,r)}function Pi(e,t,n){e.setAttribute(Di+t,It(n))}function Li(e,t,n){return Object.fromEntries(Object.entries(e).filter(([,e])=>e.type===t&&(!n||(e.assoc>=0?e.index>=n.start&&e.index<n.end:e.index>n.start&&e.index>=n.end))))}function Mi(e,t,n=""){const r={[n]:Li(e,t)};return ui(t).forEach(({insert:t},i)=>{t instanceof wr&&Object.assign(r,Mi(e,t,n?`${n}.${i}`:i.toString()))}),r}function Ii(e,t,n,r=0){const i=function(e){return Ri(e),Object.fromEntries(Object.entries(e.getAttributes()).filter(([e])=>e.startsWith(Di)).map(([t,n])=>[t.slice(25),jt(Nt(n),e.doc)]).filter(([,e])=>e))}(e),s={"":Li(i,t,{start:r,end:r+gi(n)})};return n.forEach(({insert:e},t)=>{e instanceof wr&&Object.assign(s,Mi(i,e,t.toString()))}),s}function Ni(e,t,n,r,i=0,s=0,o=""){const a=n[o];a&&Object.entries(a).forEach(([n,r])=>{Pi(e,n,Mt(t,r.index-s+i,r.assoc))}),r.forEach(({insert:t},r)=>{t instanceof wr&&Ni(e,t,n,ui(t),0,0,o?`${o}.${r}`:r.toString())})}function ji(e,t,n){return{anchor:Oi(e,t,n.anchor),focus:Oi(e,t,n.focus)}}var Vi={insert_node:function(e,t,n){const{yParent:r,textRange:s}=Si(e,t,n.path);if(i.Text.isText(n.node))return r.insert(s.start,n.node.text,mi(n.node));r.insertEmbed(s.start,vi(n.node))},remove_node:function(e,t,n){const{yParent:r,textRange:i}=Si(e,t,n.path);r.delete(i.start,i.end-i.start)},set_node:function(e,t,n){const{yTarget:r,textRange:i,yParent:s}=Si(e,t,n.path);if(r)return Object.entries(n.newProperties).forEach(([e,t])=>{if(null===t)return r.removeAttribute(e);r.setAttribute(e,t)}),Object.entries(n.properties).forEach(([e])=>{n.newProperties.hasOwnProperty(e)||r.removeAttribute(e)});const o=ii(ii({},Object.fromEntries(Object.keys(n.properties).map(e=>[e,null]))),n.newProperties);s.format(i.start,i.end-i.start,o)},merge_node:function(e,t,n){const r=Si(e,t,n.path),s=Si(r.yParent,r.slateParent,i.Path.previous(n.path.slice(-1)));if(!r.yTarget!=!s.yTarget)throw new Error("Cannot merge y text with y element");if(!s.yTarget||!r.yTarget){const{yParent:e,textRange:s,slateTarget:o}=r;if(!o)throw new Error("Expected Slate target node for merge op.");const a=i.Node.get(t,i.Path.previous(n.path));if(!i.Text.isText(a))throw new Error("Path points to Y.Text but not a Slate text node.");const c=mi(o),l=mi(a),d=Object.keys(c).reduce((e,t)=>t in l?e:si(ii({},e),{[t]:null}),{});return e.format(s.start,s.end-s.start,ii(ii({},d),l))}const o=s.yTarget.length,a=ui(r.yTarget),c=xi(a),l=Ii(e,r.yTarget,a,o),d=[{retain:o},...c];s.yTarget.applyDelta(d,{sanitize:!1}),r.yParent.delete(r.textRange.start,r.textRange.end-r.textRange.start),Ni(e,s.yTarget,l,c,o)},move_node:function(e,t,n){const r=i.Path.parent(n.newPath),s=n.newPath[n.newPath.length-1],o=i.Node.get(t,r);if(i.Text.isText(o))throw new Error("Cannot move slate node into text element");const a=[...r,Math.min(s,o.children.length)],c=Si(e,t,n.path),l=Si(e,t,a),d=xi(c.targetDelta),h=Ii(e,c.yParent,c.targetDelta);c.yParent.delete(c.textRange.start,c.textRange.end-c.textRange.start);const u=gi(ui(l.yParent)),f=Math.min(l.textRange.start,u),g=[{retain:f},...d];l.yParent.applyDelta(g,{sanitize:!1}),Ni(e,l.yParent,h,d,f,c.textRange.start)},split_node:function(e,t,n){const r=Si(e,t,n.path);if(!r.slateTarget)throw new Error("Y target without corresponding slate node");if(!r.yTarget){if(!i.Text.isText(r.slateTarget))throw new Error("Mismatch node type between y target and slate node");const e={};return r.targetDelta.forEach(t=>{t.attributes&&Object.keys(t.attributes).forEach(t=>{e[t]=null})}),r.yParent.format(r.textRange.start,r.textRange.end-r.textRange.start,ii(ii({},e),n.properties))}if(i.Text.isText(r.slateTarget))throw new Error("Mismatch node type between y target and slate node");const s=Si(r.yTarget,r.slateTarget,[n.position]),o=r.slateTarget.children.slice(0,n.position).reduce((e,t)=>e+_i(t),0),a=r.slateTarget.children.reduce((e,t)=>e+_i(t),0),c=pi(ui(r.yTarget),o,a-o),l=xi(c),d=Ii(e,r.yTarget,c,o),h=new wr;h.applyDelta(l,{sanitize:!1}),Object.entries(n.properties).forEach(([e,t])=>{h.setAttribute(e,t)}),r.yTarget.delete(s.textRange.start,r.yTarget.length-s.textRange.start),r.yParent.insertEmbed(r.textRange.end,h),Ni(e,h,d,l,0,o)}};var Fi=si(ii(ii({},{insert_text:function(e,t,n){const{yParent:r,textRange:s}=Si(e,t,n.path),o=i.Node.get(t,n.path);if(!i.Text.isText(o))throw new Error("Cannot insert text into non-text node");r.insert(s.start+n.offset,n.text,mi(o))},remove_text:function(e,t,n){const{yParent:r,textRange:i}=Si(e,t,n.path);r.delete(i.start+n.offset,n.text.length)}}),Vi),{set_selection:()=>{}});var Bi=Symbol("slate-yjs-operation"),Hi=Symbol("slate-yjs-position-storage"),Wi=new WeakMap,Yi=new WeakMap,qi=new WeakSet,Ki={isYjsEditor:e=>i.Editor$1.isEditor(e)&&e.sharedRoot instanceof wr&&"localOrigin"in e&&"positionStorageOrigin"in e&&"function"==typeof e.applyRemoteEvents&&"function"==typeof e.storeLocalChange&&"function"==typeof e.flushLocalChanges&&"function"==typeof e.isLocalOrigin&&"function"==typeof e.connect&&"function"==typeof e.disconnect,localChanges(e){var t;return null!=(t=Yi.get(e))?t:[]},applyRemoteEvents(e,t,n){e.applyRemoteEvents(t,n)},storeLocalChange(e,t){e.storeLocalChange(t)},flushLocalChanges(e){e.flushLocalChanges()},connected:e=>qi.has(e),connect(e){e.connect()},disconnect(e){e.disconnect()},isLocal:e=>e.isLocalOrigin(Ki.origin(e)),origin(e){const t=Wi.get(e);return void 0!==t?t:e.localOrigin},withOrigin(e,t,n){const r=Ki.origin(e);Wi.set(e,t),n(),Wi.set(e,r)},storePosition(e,t,n){const{sharedRoot:r,positionStorageOrigin:i}=e;Ri(r);const s=Oi(r,e,n);r.doc.transact(()=>{Pi(r,t,s)},i)},removeStoredPosition(e,t){const{sharedRoot:n,positionStorageOrigin:r}=e;Ri(n),n.doc.transact(()=>{!function(e,t){e.removeAttribute(Di+t)}(n,t)},r)},position(e,t){const n=function(e,t){const n=e.getAttribute(Di+t);return n?Nt(n):null}(e.sharedRoot,t);if(n)return Ui(e.sharedRoot,e,n)},storedPositionsRelative(e){return t=e.sharedRoot,Object.fromEntries(Object.entries(t.getAttributes()).filter(([e])=>e.startsWith(Di)).map(([e,t])=>{return[e.slice(25),(n=t,new Ut(null==n.type?null:xt(n.type.client,n.type.clock),n.tname??null,null==n.item?null:xt(n.item.client,n.item.clock),null==n.assoc?0:n.assoc))];var n}));var t}};function zi(e,t,{localOrigin:n,positionStorageOrigin:r,autoConnect:s=!1}={}){const o=e;o.sharedRoot=t,o.localOrigin=null!=n?n:Bi,o.positionStorageOrigin=null!=r?r:Hi,o.applyRemoteEvents=(e,t)=>{Ki.flushLocalChanges(o),i.Editor$1.withoutNormalizing(o,()=>{Ki.withOrigin(o,t,()=>{Ai(o.sharedRoot,o,e)})})},o.isLocalOrigin=e=>e===o.localOrigin;const a=(e,t)=>{o.isLocalOrigin(t.origin)||Ki.applyRemoteEvents(o,e,t.origin)};let c=null;s&&(c=setTimeout(()=>{c=null,Ki.connect(o)})),o.connect=()=>{if(Ki.connected(o))throw new Error("already connected");o.sharedRoot.observeDeep(a);const t=yi(o.sharedRoot);o.children=t.children,qi.add(o),i.Editor$1.normalize(e,{force:!0}),e.operations.length||e.onChange()},o.disconnect=()=>{c&&clearTimeout(c),Ki.flushLocalChanges(o),o.sharedRoot.unobserveDeep(a),qi.delete(o)},o.storeLocalChange=t=>{Yi.set(o,[...Ki.localChanges(o),{op:t,doc:e.children,origin:Ki.origin(o)}])},o.flushLocalChanges=()=>{Ri(o.sharedRoot);const e=Ki.localChanges(o);Yi.delete(o);const t=[];e.forEach(e=>{const n=t[t.length-1];if(n&&n[0].origin===e.origin)return n.push(e);t.push([e])}),t.forEach(e=>{Ri(o.sharedRoot),o.sharedRoot.doc.transact(()=>{e.forEach(e=>{Ri(o.sharedRoot),function(e,t,n){const r=Fi[n.type];if(!r)throw new Error(`Unknown operation: ${n.type}`);r(e,t,n)}(o.sharedRoot,{children:e.doc},e.op)})},e[0].origin)})};const{apply:l,onChange:d}=o;return o.apply=e=>{Ki.connected(o)&&Ki.isLocal(o)&&Ki.storeLocalChange(o,e),l(e)},o.onChange=()=>{Ki.connected(o)&&Ki.flushLocalChanges(o),d()},o}var $i=new WeakMap,Ji=Symbol("slate-yjs-history-without-saving");function Qi(e,t={}){var n=t,{withoutSavingOrigin:r=Ji,trackedOrigins:s=new Set([e.localOrigin])}=n,o=oi(n,["withoutSavingOrigin","trackedOrigins"]);const a=e;a.undoManager=new ln(a.sharedRoot,ii({trackedOrigins:s},o)),a.withoutSavingOrigin=r;const{onChange:c,isLocalOrigin:l}=a;a.onChange=()=>{c(),$i.set(a,a.selection&&ji(a.sharedRoot,a,a.selection))},a.isLocalOrigin=e=>e===a.withoutSavingOrigin||l(e);const d=({stackItem:e})=>{e.meta.set("selection",a.selection&&ji(a.sharedRoot,a,a.selection)),e.meta.set("selectionBefore",$i.get(a))},h=({stackItem:e})=>{e.meta.set("selection",a.selection&&ji(a.sharedRoot,a,a.selection))},u=({stackItem:e,type:t})=>{const n="undo"===t?a.undoManager.redoStack:a.undoManager.undoStack,r=n[n.length-1];r&&(r.meta.set("selection",e.meta.get("selectionBefore")),r.meta.set("selectionBefore",e.meta.get("selection")));const s=e.meta.get("selectionBefore");if(!s)return;const o=function(e,t,n){const r=Ui(e,t,n.anchor);if(!r)return null;const i=Ui(e,t,n.focus);return i?{anchor:r,focus:i}:null}(a.sharedRoot,a,s);o&&i.Transforms.select(a,o)},{connect:f,disconnect:g}=a;return a.connect=()=>{f(),a.undoManager.on("stack-item-added",d),a.undoManager.on("stack-item-popped",u),a.undoManager.on("stack-item-updated",h)},a.disconnect=()=>{a.undoManager.off("stack-item-added",d),a.undoManager.off("stack-item-popped",u),a.undoManager.off("stack-item-updated",h),g()},a.undo=()=>{Ki.connected(a)&&(Ki.flushLocalChanges(a),a.undoManager.undo())},a.redo=()=>{Ki.connected(a)&&(Ki.flushLocalChanges(a),a.undoManager.redo())},a}var Gi=new WeakMap,Xi={isCursorEditor:e=>Ki.isYjsEditor(e)&&e.awareness&&"string"==typeof e.cursorDataField&&"string"==typeof e.selectionStateField&&"function"==typeof e.sendCursorPosition&&"function"==typeof e.sendCursorData,sendCursorPosition(e,t=e.selection){e.sendCursorPosition(t)},sendCursorData(e,t){e.sendCursorData(t)},on(e,t,n){var r;if("change"!==t)return;const i=null!=(r=Gi.get(e))?r:new Set;i.add(n),Gi.set(e,i)},off(e,t,n){if("change"!==t)return;const r=Gi.get(e);r&&r.delete(n)},cursorState(e,t){var n;if(t===e.awareness.clientID||!Ki.connected(e))return null;const r=e.awareness.getStates().get(t);return r?{relativeSelection:null!=(n=r[e.selectionStateField])?n:null,data:r[e.cursorDataField],clientId:t}:null},cursorStates:e=>Ki.connected(e)?Object.fromEntries(Array.from(e.awareness.getStates().entries(),([t,n])=>t!==e.awareness.clientID&&n?[t,{relativeSelection:n[e.selectionStateField],data:n[e.cursorDataField]}]:null).filter(Array.isArray)):{}};var Zi=class extends a.Observable{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const e=a.getUnixTime();null!==this.getLocalState()&&15e3<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&3e4<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&es(this,t,"timeout")},a.floor(3e3)),e.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){const t=this.clientID,n=this.meta.get(t),r=void 0===n?0:n.clock+1,i=this.states.get(t);null===e?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:r,lastUpdated:a.getUnixTime()});const s=[],o=[],c=[],l=[];null===e?l.push(t):null==i?null!=e&&s.push(t):(o.push(t),a.equalityDeep(i,e)||c.push(t)),(s.length>0||c.length>0||l.length>0)&&this.emit("change",[{added:s,updated:c,removed:l},"local"]),this.emit("update",[{added:s,updated:o,removed:l},"local"])}setLocalStateField(e,t){const n=this.getLocalState();null!==n&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}},es=(e,t,n)=>{const r=[];for(let i=0;i<t.length;i++){const n=t[i];if(e.states.has(n)){if(e.states.delete(n),n===e.clientID){const t=e.meta.get(n);e.meta.set(n,{clock:t.clock+1,lastUpdated:a.getUnixTime()})}r.push(n)}}r.length>0&&(e.emit("change",[{added:[],updated:[],removed:r},n]),e.emit("update",[{added:[],updated:[],removed:r},n]))},ts=(e,t,n=e.states)=>{const r=t.length,i=a.createEncoder();a.writeVarUint(i,r);for(let s=0;s<r;s++){const r=t[s],o=n.get(r)||null,c=e.meta.get(r).clock;a.writeVarUint(i,r),a.writeVarUint(i,c),a.writeVarString(i,JSON.stringify(o))}return a.toUint8Array(i)},ns=(e,t,n)=>{const r=a.createDecoder(t),i=a.getUnixTime(),s=[],o=[],c=[],l=[],d=a.readVarUint(r);for(let h=0;h<d;h++){const t=a.readVarUint(r);let n=a.readVarUint(r);const d=JSON.parse(a.readVarString(r)),h=e.meta.get(t),u=e.states.get(t),f=void 0===h?0:h.clock;(f<n||f===n&&null===d&&e.states.has(t))&&(null===d?t===e.clientID&&null!=e.getLocalState()?n++:e.states.delete(t):e.states.set(t,d),e.meta.set(t,{clock:n,lastUpdated:i}),void 0===h&&null!==d?s.push(t):void 0!==h&&null===d?l.push(t):null!==d&&(a.equalityDeep(d,u)||c.push(t),o.push(t)))}(s.length>0||c.length>0||l.length>0)&&e.emit("change",[{added:s,updated:c,removed:l},n]),(s.length>0||o.length>0||l.length>0)&&e.emit("update",[{added:s,updated:o,removed:l},n])},rs=(e,t)=>{a.writeVarUint(e,0);const n=(e=>bt(e,new at))(t);a.writeVarUint8Array(e,n)},is=(e,t,n)=>{a.writeVarUint(e,1),a.writeVarUint8Array(e,mt(t,n))},ss=(e,t,n,r)=>{try{gt(t,a.readVarUint8Array(e),n)}catch(i){null!=r&&r(i)}},os=(e,t)=>{a.writeVarUint(e,2),a.writeVarUint8Array(e,t)},as=ss,cs=(e,t,n,r,i)=>{const s=a.readVarUint(e);switch(s){case 0:((e,t,n)=>{is(t,n,a.readVarUint8Array(e))})(e,t,n);break;case 1:ss(e,n,r,i);break;case 2:as(e,n,r,i);break;default:throw new Error("Unknown message type")}return s},ls=class{constructor(){this.callbacks={}}on(e,t){return this.callbacks[e]||(this.callbacks[e]=[]),this.callbacks[e].push(t),this}emit(e,...t){const n=this.callbacks[e];return n&&n.forEach(e=>e.apply(this,t)),this}off(e,t){const n=this.callbacks[e];return n&&(t?this.callbacks[e]=n.filter(e=>e!==t):delete this.callbacks[e]),this}removeAllListeners(){this.callbacks={}}},ds=class{constructor(e){this.data=e,this.encoder=a.createEncoder(),this.decoder=a.createDecoder(new Uint8Array(this.data))}peekVarString(){return a.peekVarString(this.decoder)}readVarUint(){return a.readVarUint(this.decoder)}readVarString(){return a.readVarString(this.decoder)}readVarUint8Array(){return a.readVarUint8Array(this.decoder)}writeVarUint(e){return a.writeVarUint(this.encoder,e)}writeVarString(e){return a.writeVarString(this.encoder,e)}writeVarUint8Array(e){return a.writeVarUint8Array(this.encoder,e)}length(){return a.length(this.encoder)}},hs=function(e){return e[e.Sync=0]="Sync",e[e.Awareness=1]="Awareness",e[e.Auth=2]="Auth",e[e.QueryAwareness=3]="QueryAwareness",e[e.Stateless=5]="Stateless",e[e.CLOSE=7]="CLOSE",e[e.SyncStatus=8]="SyncStatus",e[e.Ping=9]="Ping",e[e.Pong=10]="Pong",e}({}),us=function(e){return e.Connecting="connecting",e.Connected="connected",e.Disconnected="disconnected",e}({}),fs=class{constructor(){this.encoder=a.createEncoder()}get(e){return e.encoder}toUint8Array(){return a.toUint8Array(this.encoder)}},gs=class extends fs{constructor(...e){super(...e),this.type=hs.CLOSE,this.description="Ask the server to close the connection"}get(e){return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),this.encoder}},ps=class e extends ls{static{this.DEDUPLICATABLE_TYPES=new Set([hs.Awareness,hs.QueryAwareness])}constructor(e){super(),this.messageQueue=[],this.configuration={url:"",autoConnect:!0,preserveTrailingSlash:!1,document:void 0,WebSocketPolyfill:void 0,messageReconnectTimeout:3e4,delay:1e3,initialDelay:0,factor:2,maxAttempts:0,minDelay:1e3,maxDelay:3e4,jitter:!0,timeout:0,onOpen:()=>null,onConnect:()=>null,onMessage:()=>null,onOutgoingMessage:()=>null,onStatus:()=>null,onDisconnect:()=>null,onClose:()=>null,onDestroy:()=>null,onAwarenessUpdate:()=>null,onAwarenessChange:()=>null,handleTimeout:null,providerMap:new Map},this.webSocket=null,this.webSocketHandlers={},this.shouldConnect=!0,this.status=us.Disconnected,this.lastMessageReceived=0,this.identifier=0,this.intervals={connectionChecker:null},this.connectionAttempt=null,this.receivedOnOpenPayload=void 0,this.closeTries=0,this.setConfiguration(e),this.configuration.WebSocketPolyfill=e.WebSocketPolyfill?e.WebSocketPolyfill:WebSocket,this.on("open",this.configuration.onOpen),this.on("open",this.onOpen.bind(this)),this.on("connect",this.configuration.onConnect),this.on("message",this.configuration.onMessage),this.on("outgoingMessage",this.configuration.onOutgoingMessage),this.on("status",this.configuration.onStatus),this.on("disconnect",this.configuration.onDisconnect),this.on("close",this.configuration.onClose),this.on("destroy",this.configuration.onDestroy),this.on("awarenessUpdate",this.configuration.onAwarenessUpdate),this.on("awarenessChange",this.configuration.onAwarenessChange),this.on("close",this.onClose.bind(this)),this.on("message",this.onMessage.bind(this)),this.intervals.connectionChecker=setInterval(this.checkConnection.bind(this),this.configuration.messageReconnectTimeout/10),this.shouldConnect&&this.connect()}async onOpen(e){this.status=us.Connected,this.emit("status",{status:us.Connected}),this.cancelWebsocketRetry=void 0,this.receivedOnOpenPayload=e}attach(e){const t=e.effectiveName,n=this.configuration.providerMap.get(t);if(n&&n!==e&&n.isAuthenticated)throw new Error(`Cannot attach two providers with the same effective name "${t}". Use sessionAwareness: true to multiplex providers with the same document name.`);this.configuration.providerMap.set(t,e),this.status===us.Disconnected&&this.shouldConnect&&this.connect(),this.receivedOnOpenPayload&&this.status===us.Connected&&e.onOpen(this.receivedOnOpenPayload)}detach(e){const t=e.effectiveName;this.configuration.providerMap.has(t)&&(e.send(gs,{documentName:t}),this.configuration.providerMap.delete(t))}setConfiguration(e={}){this.configuration={...this.configuration,...e},this.configuration.autoConnect||(this.shouldConnect=!1)}async connect(){if(this.status===us.Connected)return;this.cancelWebsocketRetry&&(this.cancelWebsocketRetry(),this.cancelWebsocketRetry=void 0),this.receivedOnOpenPayload=void 0,this.shouldConnect=!0;const{retryPromise:e,cancelFunc:t}=(()=>{let e=!1;return{retryPromise:z(this.createWebSocketConnection.bind(this),{delay:this.configuration.delay,initialDelay:this.configuration.initialDelay,factor:this.configuration.factor,maxAttempts:this.configuration.maxAttempts,minDelay:this.configuration.minDelay,maxDelay:this.configuration.maxDelay,jitter:this.configuration.jitter,timeout:this.configuration.timeout,handleTimeout:this.configuration.handleTimeout,beforeAttempt:t=>{this.shouldConnect&&!e||t.abort()}}).catch(e=>{if(e&&"ATTEMPT_ABORTED"!==e.code)throw e}),cancelFunc:()=>{e=!0}}})();return this.cancelWebsocketRetry=t,e}attachWebSocketListeners(e,t){const{identifier:n}=e;this.webSocketHandlers[n]={message:e=>this.emit("message",e),close:e=>this.emit("close",{event:e}),open:e=>this.emit("open",e),error:e=>{t(e)}};const r=this.webSocketHandlers[e.identifier];Object.keys(r).forEach(t=>{e.addEventListener(t,r[t])})}cleanupWebSocket(){if(!this.webSocket)return;const{identifier:e}=this.webSocket,t=this.webSocketHandlers[e];Object.keys(t).forEach(n=>{this.webSocket?.removeEventListener(n,t[n]),delete this.webSocketHandlers[e]}),this.webSocket.close(),this.webSocket=null}createWebSocketConnection(){return new Promise((e,t)=>{this.webSocket&&(this.messageQueue=[],this.cleanupWebSocket()),this.lastMessageReceived=0,this.identifier+=1;const n=new this.configuration.WebSocketPolyfill(this.url);n.binaryType="arraybuffer",n.identifier=this.identifier,this.attachWebSocketListeners(n,t),this.webSocket=n,this.status=us.Connecting,this.emit("status",{status:us.Connecting}),this.connectionAttempt={resolve:e,reject:t}})}onMessage(e){this.resolveConnectionAttempt(),this.lastMessageReceived=a.getUnixTime();const t=new Uint8Array(e.data);if(1===t.length&&t[0]===hs.Ping)return void this.sendPong();const n=new ds(t).peekVarString();this.configuration.providerMap.get(n)?.onMessage(e)}sendPong(){const e=a.createEncoder();a.writeVarUint(e,hs.Pong),this.send(a.toUint8Array(e))}resolveConnectionAttempt(){this.connectionAttempt&&(this.connectionAttempt.resolve(),this.connectionAttempt=null,this.status=us.Connected,this.emit("status",{status:us.Connected}),this.emit("connect"),this.messageQueue.forEach(e=>this.send(e)),this.messageQueue=[])}stopConnectionAttempt(){this.connectionAttempt=null}rejectConnectionAttempt(){this.connectionAttempt?.reject(),this.connectionAttempt=null}checkConnection(){this.status===us.Connected&&this.lastMessageReceived&&(this.configuration.messageReconnectTimeout>=a.getUnixTime()-this.lastMessageReceived||(this.closeTries+=1,this.closeTries>2?(this.onClose({event:{code:4408,reason:"forced"}}),this.closeTries=0):(this.webSocket?.close(),this.messageQueue=[])))}get serverUrl(){if(this.configuration.preserveTrailingSlash)return this.configuration.url;let e=this.configuration.url;for(;"/"===e[e.length-1];)e=e.slice(0,e.length-1);return e}get url(){return this.serverUrl}disconnect(){if(this.shouldConnect=!1,null!==this.webSocket)try{this.webSocket.close(),this.messageQueue=[]}catch(e){}}parseQueuedMessage(e){try{const t=a.createDecoder(e);return{documentName:a.readVarString(t),messageType:a.readVarUint(t)}}catch{return null}}addToQueue(t){if(t instanceof Uint8Array){const n=this.parseQueuedMessage(t);n&&e.DEDUPLICATABLE_TYPES.has(n.messageType)&&(this.messageQueue=this.messageQueue.filter(e=>{if(!(e instanceof Uint8Array))return!0;const t=this.parseQueuedMessage(e);return!t||!(t.documentName===n.documentName&&t.messageType===n.messageType)}))}this.messageQueue.push(t)}send(e){this.webSocket?.readyState===Y.Open?this.webSocket.send(e):this.addToQueue(e)}onClose({event:e}){this.closeTries=0,this.cleanupWebSocket(),this.connectionAttempt&&this.rejectConnectionAttempt(),this.status=us.Disconnected,this.emit("status",{status:us.Disconnected}),this.emit("disconnect",{event:e}),!this.cancelWebsocketRetry&&this.shouldConnect&&setTimeout(()=>{this.connect()},this.configuration.delay)}destroy(){this.emit("destroy"),clearInterval(this.intervals.connectionChecker),this.stopConnectionAttempt(),this.disconnect(),this.removeAllListeners(),this.cleanupWebSocket()}},ms=class{constructor(e){this.message=e}apply(e,t){const{message:n}=this,r=n.readVarUint(),i=n.length();switch(r){case hs.Sync:this.applySyncMessage(e,t);break;case hs.Awareness:this.applyAwarenessMessage(e);break;case hs.Auth:this.applyAuthMessage(e);break;case hs.QueryAwareness:this.applyQueryAwarenessMessage(e);break;case hs.Stateless:e.receiveStateless(a.readVarString(n.decoder));break;case hs.SyncStatus:this.applySyncStatusMessage(e,1===a.readVarInt(n.decoder));break;case hs.CLOSE:{const t={code:1e3,reason:a.readVarString(n.decoder)};e.onClose(),e.configuration.onClose({event:t}),e.forwardClose({event:t});break}}n.length()>i+1&&e.send(fs,{encoder:n.encoder})}applySyncMessage(e,t){const{message:n}=this;n.writeVarUint(hs.Sync);const r=cs(n.decoder,n.encoder,e.document,e);t&&1===r&&(e.synced=!0)}applySyncStatusMessage(e,t){t&&e.decrementUnsyncedChanges()}applyAwarenessMessage(e){if(!e.awareness)return;const{message:t}=this;ns(e.awareness,t.readVarUint8Array(),e)}applyAuthMessage(e){const{message:t}=this;F(t.decoder,e.sendToken.bind(e),e.permissionDeniedHandler.bind(e),e.authenticatedHandler.bind(e))}applyQueryAwarenessMessage(e){if(!e.awareness)return;const{message:t}=this;t.writeVarUint(hs.Awareness),t.writeVarUint8Array(ts(e.awareness,Array.from(e.awareness.getStates().keys())))}},ys=class{constructor(e,t={}){this.message=new e,this.encoder=this.message.get(t)}create(){return a.toUint8Array(this.encoder)}send(e){e?.send(this.create())}},ws=class extends fs{constructor(...e){super(...e),this.type=hs.Auth,this.description="Authentication"}get(e){if(void 0===e.token)throw new Error("The authentication message requires `token` as an argument.");return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),V(this.encoder,e.token),a.writeVarString(this.encoder,"4.6.0"),this.encoder}},bs=class extends fs{constructor(...e){super(...e),this.type=hs.Awareness,this.description="Awareness states update"}get(e){if(void 0===e.awareness)throw new Error("The awareness message requires awareness as an argument");if(void 0===e.clients)throw new Error("The awareness message requires clients as an argument");let t;return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),t=void 0===e.states?ts(e.awareness,e.clients):ts(e.awareness,e.clients,e.states),a.writeVarUint8Array(this.encoder,t),this.encoder}},vs=class extends fs{constructor(...e){super(...e),this.type=hs.Stateless,this.description="A stateless message"}get(e){return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),a.writeVarString(this.encoder,e.payload??""),this.encoder}},_s=class extends fs{constructor(...e){super(...e),this.type=hs.Sync,this.description="First sync step"}get(e){if(void 0===e.document)throw new Error("The sync step one message requires document as an argument");return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),rs(this.encoder,e.document),this.encoder}},Ss=class extends fs{constructor(...e){super(...e),this.type=hs.Sync,this.description="A document update"}get(e){return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),os(this.encoder,e.update),this.encoder}},ks=class extends Error{constructor(...e){super(...e),this.code=1001}},Cs=class extends ls{get effectiveName(){return this.configuration.sessionAwareness?H(this.configuration.name,this.sessionId):this.configuration.name}constructor(e){super(),this.configuration={name:"",document:void 0,awareness:void 0,token:null,sessionAwareness:!1,forceSyncInterval:!1,flushDelay:!1,onAuthenticated:()=>null,onAuthenticationFailed:()=>null,onOpen:()=>null,onConnect:()=>null,onMessage:()=>null,onOutgoingMessage:()=>null,onSynced:()=>null,onStatus:()=>null,onDisconnect:()=>null,onClose:()=>null,onDestroy:()=>null,onAwarenessUpdate:()=>null,onAwarenessChange:()=>null,onStateless:()=>null,onUnsyncedChanges:()=>null},this.isSynced=!1,this.unsyncedChanges=0,this.isAuthenticated=!1,this.authorizedScope=void 0,this.manageSocket=!1,this._isAttached=!1,this.pendingUpdates=[],this.pendingAwarenessClients=new Set,this.flushTimeout=null,this.sessionId=Math.random().toString(36).slice(2),this.intervals={forceSync:null},this.boundDocumentUpdateHandler=this.documentUpdateHandler.bind(this),this.boundAwarenessUpdateHandler=this.awarenessUpdateHandler.bind(this),this.boundPageHide=this.pageHide.bind(this),this.boundOnOpen=this.onOpen.bind(this),this.boundOnClose=this.onClose.bind(this),this.forwardConnect=()=>this.emit("connect"),this.forwardStatus=e=>this.emit("status",e),this.forwardClose=e=>this.emit("close",e),this.forwardDisconnect=e=>this.emit("disconnect",e),this.forwardDestroy=()=>this.emit("destroy"),this.setConfiguration(e),this.configuration.document=e.document?e.document:new nt,this.configuration.awareness=void 0!==e.awareness?e.awareness:new Zi(this.document),this.on("open",this.configuration.onOpen),this.on("message",this.configuration.onMessage),this.on("outgoingMessage",this.configuration.onOutgoingMessage),this.on("synced",this.configuration.onSynced),this.on("destroy",this.configuration.onDestroy),this.on("awarenessUpdate",this.configuration.onAwarenessUpdate),this.on("awarenessChange",this.configuration.onAwarenessChange),this.on("stateless",this.configuration.onStateless),this.on("unsyncedChanges",this.configuration.onUnsyncedChanges),this.on("authenticated",this.configuration.onAuthenticated),this.on("authenticationFailed",this.configuration.onAuthenticationFailed),this.awareness?.on("update",()=>{this.emit("awarenessUpdate",{states:B(this.awareness.getStates())})}),this.awareness?.on("change",()=>{this.emit("awarenessChange",{states:B(this.awareness.getStates())})}),this.document.on("update",this.boundDocumentUpdateHandler),this.awareness?.on("update",this.boundAwarenessUpdateHandler),this.registerEventListeners(),this.configuration.forceSyncInterval&&"number"==typeof this.configuration.forceSyncInterval&&(this.intervals.forceSync=setInterval(this.forceSync.bind(this),this.configuration.forceSyncInterval)),this.manageSocket&&this.attach()}setConfiguration(e={}){e.websocketProvider||(this.manageSocket=!0,this.configuration.websocketProvider=new ps(e)),this.configuration={...this.configuration,...e}}get document(){return this.configuration.document}get isAttached(){return this._isAttached}get awareness(){return this.configuration.awareness}get hasUnsyncedChanges(){return this.unsyncedChanges>0}resetUnsyncedChanges(){this.unsyncedChanges=1,this.emit("unsyncedChanges",{number:this.unsyncedChanges})}incrementUnsyncedChanges(){this.unsyncedChanges+=1,this.emit("unsyncedChanges",{number:this.unsyncedChanges})}decrementUnsyncedChanges(){this.unsyncedChanges>0&&(this.unsyncedChanges-=1),0===this.unsyncedChanges&&(this.synced=!0),this.emit("unsyncedChanges",{number:this.unsyncedChanges})}forceSync(){this.resetUnsyncedChanges(),this.send(_s,{document:this.document,documentName:this.effectiveName})}pageHide(){this.awareness&&es(this.awareness,[this.document.clientID],"page hide")}registerEventListeners(){"undefined"!=typeof window&&"addEventListener"in window&&window.addEventListener("pagehide",this.boundPageHide)}sendStateless(e){this.send(vs,{documentName:this.effectiveName,payload:e})}async sendToken(){let e;try{e=await this.getToken()}catch(t){return void this.permissionDeniedHandler(`Failed to get token during sendToken(): ${t}`)}this.send(ws,{token:e??"",documentName:this.effectiveName})}get batchingEnabled(){return!!this.configuration.flushDelay&&"number"==typeof this.configuration.flushDelay}documentUpdateHandler(e,t){if(t!==this){if(!this.batchingEnabled)return this.incrementUnsyncedChanges(),void this.send(Ss,{update:e,documentName:this.effectiveName});0===this.pendingUpdates.length&&this.incrementUnsyncedChanges(),this.pendingUpdates.push(e),this.scheduleFlush()}}awarenessUpdateHandler({added:e,updated:t,removed:n},r){if(r===this)return;const i=e.concat(t).concat(n);if(this.batchingEnabled){for(const e of i)this.pendingAwarenessClients.add(e);this.scheduleFlush()}else this.send(bs,{awareness:this.awareness,clients:i,documentName:this.effectiveName})}scheduleFlush(){null===this.flushTimeout&&(this.flushTimeout=setTimeout(()=>{this.flushTimeout=null,this.flushPendingUpdates()},this.configuration.flushDelay))}flushPendingUpdates(){if(null!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.pendingUpdates.length>0){const e=1===this.pendingUpdates.length?this.pendingUpdates[0]:un(this.pendingUpdates);this.pendingUpdates=[],this.send(Ss,{update:e,documentName:this.effectiveName})}if(this.pendingAwarenessClients.size>0){const e=Array.from(this.pendingAwarenessClients);this.pendingAwarenessClients.clear(),this.send(bs,{awareness:this.awareness,clients:e,documentName:this.effectiveName})}}get synced(){return this.isSynced}set synced(e){this.isSynced!==e&&(this.isSynced=e,e&&this.emit("synced",{state:e}))}receiveStateless(e){this.emit("stateless",{payload:e})}async connect(){if(this.manageSocket)return this.configuration.websocketProvider.connect()}disconnect(){if(this.manageSocket)return this.configuration.websocketProvider.disconnect()}async onOpen(e){this.isAuthenticated=!1,this.emit("open",{event:e}),await this.sendToken(),this.startSync()}async getToken(){return"function"==typeof this.configuration.token?await this.configuration.token():this.configuration.token}startSync(){this.resetUnsyncedChanges(),this.send(_s,{document:this.document,documentName:this.effectiveName}),this.awareness&&null!==this.awareness.getLocalState()&&this.send(bs,{awareness:this.awareness,clients:[this.document.clientID],documentName:this.effectiveName})}send(e,t){if(!this._isAttached)return;const n=new ys(e,t);this.emit("outgoingMessage",{message:n.message}),n.send(this.configuration.websocketProvider)}onMessage(e){const t=new ds(e.data),{documentName:n}=W(t.readVarString());t.writeVarString(this.effectiveName),this.emit("message",{event:e,message:new ds(e.data)}),new ms(t).apply(this,!0)}onClose(){this.isAuthenticated=!1,this.synced=!1,null!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.pendingUpdates=[],this.pendingAwarenessClients.clear(),this.awareness&&es(this.awareness,Array.from(this.awareness.getStates().keys()).filter(e=>e!==this.document.clientID),this)}destroy(){this.emit("destroy"),this.intervals.forceSync&&clearInterval(this.intervals.forceSync),this.awareness&&(es(this.awareness,[this.document.clientID],"provider destroy"),this.awareness.off("update",this.boundAwarenessUpdateHandler),this.awareness.destroy()),this.flushPendingUpdates(),this.document.off("update",this.boundDocumentUpdateHandler),this.removeAllListeners(),this.detach(),this.manageSocket&&this.configuration.websocketProvider.destroy(),"undefined"!=typeof window&&"removeEventListener"in window&&window.removeEventListener("pagehide",this.boundPageHide)}detach(){this.configuration.websocketProvider.off("connect",this.configuration.onConnect),this.configuration.websocketProvider.off("connect",this.forwardConnect),this.configuration.websocketProvider.off("status",this.forwardStatus),this.configuration.websocketProvider.off("status",this.configuration.onStatus),this.configuration.websocketProvider.off("open",this.boundOnOpen),this.configuration.websocketProvider.off("close",this.boundOnClose),this.configuration.websocketProvider.off("close",this.configuration.onClose),this.configuration.websocketProvider.off("close",this.forwardClose),this.configuration.websocketProvider.off("disconnect",this.configuration.onDisconnect),this.configuration.websocketProvider.off("disconnect",this.forwardDisconnect),this.configuration.websocketProvider.off("destroy",this.configuration.onDestroy),this.configuration.websocketProvider.off("destroy",this.forwardDestroy),this.configuration.websocketProvider.detach(this),this._isAttached=!1}attach(){this._isAttached||(this.configuration.websocketProvider.on("connect",this.configuration.onConnect),this.configuration.websocketProvider.on("connect",this.forwardConnect),this.configuration.websocketProvider.on("status",this.configuration.onStatus),this.configuration.websocketProvider.on("status",this.forwardStatus),this.configuration.websocketProvider.on("open",this.boundOnOpen),this.configuration.websocketProvider.on("close",this.boundOnClose),this.configuration.websocketProvider.on("close",this.configuration.onClose),this.configuration.websocketProvider.on("close",this.forwardClose),this.configuration.websocketProvider.on("disconnect",this.configuration.onDisconnect),this.configuration.websocketProvider.on("disconnect",this.forwardDisconnect),this.configuration.websocketProvider.on("destroy",this.configuration.onDestroy),this.configuration.websocketProvider.on("destroy",this.forwardDestroy),this.configuration.websocketProvider.attach(this),this._isAttached=!0)}permissionDeniedHandler(e){this.emit("authenticationFailed",{reason:e}),this.isAuthenticated=!1}authenticatedHandler(e){this.isAuthenticated=!0,this.authorizedScope=e,this.emit("authenticated",{scope:e})}setAwarenessField(e,t){if(!this.awareness)throw new ks(`Cannot set awareness field "${e}" to ${JSON.stringify(t)}. You have disabled Awareness for this provider by explicitly passing awareness: null in the provider configuration.`);this.awareness.setLocalStateField(e,t)}},Es=e=>a.create((t,n)=>{e.onerror=e=>n(new Error(e.target.error)),e.onsuccess=e=>t(e.target.result)}),As=(e,t,n="readwrite")=>{const r=e.transaction(t,n);return t.map(e=>Us(r,e))},xs=(e,t)=>Es(e.count(t)),Ts=(e,t)=>Es(e.delete(t)),Rs=(e,t)=>Es(e.add(t)),Ds=(e,t=null)=>((e,t,n)=>{let r=null;return Os(e,t,e=>(r=e,!1),n).then(()=>r)})(e,t,"prev"),Os=(e,t,n,r="next")=>((e,t)=>a.create((n,r)=>{e.onerror=r,e.onsuccess=async e=>{const r=e.target.result;if(null===r||!1===await t(r))return n();r.continue()}}))(e.openKeyCursor(t,r),e=>n(e.key)),Us=(e,t)=>e.objectStore(t),Ps="custom",Ls="updates",Ms=(e,t=()=>{},n=()=>{})=>{const[r]=As(e.db,[Ls]);return(i=r,a=e._dbref,c=!1,s=IDBKeyRange.lowerBound(a,c),Es(i.getAll(s,o))).then(i=>{e._destroyed||(t(r),sn(e.doc,()=>{i.forEach(t=>gt(e.doc,t))},e,!1),n(r))}).then(()=>Ds(r).then(t=>{e._dbref=t+1})).then(()=>xs(r).then(t=>{e._dbsize=t})).then(()=>r);var i,s,o,a,c},Is=(e,t=!0)=>Ms(e).then(n=>{(t||e._dbsize>=500)&&Rs(n,mt(e.doc)).then(()=>{return Ts(n,(t=e._dbref,r=!0,IDBKeyRange.upperBound(t,r)));var t,r}).then(()=>xs(n).then(t=>{e._dbsize=t}))}),Ns=class extends a.Observable{constructor(e,t){super(),this.doc=t,this.name=e,this._dbref=0,this._dbsize=0,this._destroyed=!1,this.db=null,this.synced=!1,this._db=((e,t)=>a.create((n,r)=>{const i=indexedDB.open(e);i.onupgradeneeded=e=>t(e.target.result),i.onerror=e=>r(a.create$1(e.target.error)),i.onsuccess=e=>{const t=e.target.result;t.onversionchange=()=>{t.close()},n(t)}}))(e,e=>((e,t)=>t.forEach(t=>e.createObjectStore.apply(e,t)))(e,[["updates",{autoIncrement:!0}],["custom"]])),this.whenSynced=a.create(e=>this.on("synced",()=>e(this))),this._db.then(e=>{this.db=e;Ms(this,e=>Rs(e,mt(t)),()=>{if(this._destroyed)return this;this.synced=!0,this.emit("synced",[this])})}),this._storeTimeout=1e3,this._storeTimeoutId=null,this._storeUpdate=(e,t)=>{if(this.db&&t!==this){const[t]=As(this.db,[Ls]);Rs(t,e),++this._dbsize>=500&&(null!==this._storeTimeoutId&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{Is(this,!1),this._storeTimeoutId=null},this._storeTimeout))}},t.on("update",this._storeUpdate),this.destroy=this.destroy.bind(this),t.on("destroy",this.destroy)}destroy(){return this._storeTimeoutId&&clearTimeout(this._storeTimeoutId),this.doc.off("update",this._storeUpdate),this.doc.off("destroy",this.destroy),this._destroyed=!0,this._db.then(e=>{e.close()})}clearData(){return this.destroy().then(()=>{var e;e=this.name,Es(indexedDB.deleteDatabase(e))})}get(e){return this._db.then(t=>{const[n]=As(t,[Ps],"readonly");return((e,t)=>Es(e.get(t)))(n,e)})}set(e,t){return this._db.then(n=>{const[r]=As(n,[Ps]);return((e,t,n)=>Es(e.put(t,n)))(r,t,e)})}del(e){return this._db.then(t=>{const[n]=As(t,[Ps]);return Ts(n,e)})}},js=3e4,Vs=e=>{if(e.shouldConnect&&null===e.ws){const t=new WebSocket(e.url),n=e.binaryType;let r=null;n&&(t.binaryType=n),e.ws=t,e.connecting=!0,e.connected=!1,t.onmessage=t=>{e.lastMessageReceived=a.getUnixTime();const n=t.data,i="string"==typeof n?JSON.parse(n):n;i&&"pong"===i.type&&(clearTimeout(r),r=setTimeout(s,15e3)),e.emit("message",[i,e])};const i=t=>{null!==e.ws&&(e.ws=null,e.connecting=!1,e.connected?(e.connected=!1,e.emit("disconnect",[{type:"disconnect",error:t},e])):e.unsuccessfulReconnects++,setTimeout(Vs,a.min(1200*a.log10(e.unsuccessfulReconnects+1),2500),e)),clearTimeout(r)},s=()=>{e.ws===t&&e.send({type:"ping"})};t.onclose=()=>i(null),t.onerror=e=>i(e),t.onopen=()=>{e.lastMessageReceived=a.getUnixTime(),e.connecting=!1,e.connected=!0,e.unsuccessfulReconnects=0,e.emit("connect",[{type:"connect"},e]),r=setTimeout(s,15e3)}}},Fs=class extends a.Observable{constructor(e,{binaryType:t}={}){super(),this.url=e,this.ws=null,this.binaryType=t||null,this.connected=!1,this.connecting=!1,this.unsuccessfulReconnects=0,this.lastMessageReceived=0,this.shouldConnect=!0,this._checkInterval=setInterval(()=>{this.connected&&js<a.getUnixTime()-this.lastMessageReceived&&this.ws.close()},15e3),Vs(this)}send(e){this.ws&&this.ws.send(JSON.stringify(e))}destroy(){clearInterval(this._checkInterval),this.disconnect(),super.destroy()}disconnect(){this.shouldConnect=!1,null!==this.ws&&this.ws.close()}connect(){this.shouldConnect=!0,this.connected||null!==this.ws||Vs(this)}},Bs=new Map,Hs="undefined"==typeof BroadcastChannel?class{constructor(e){this.room=e,this.onmessage=null,this._onChange=t=>t.key===e&&null!==this.onmessage&&this.onmessage({data:a.fromBase64(t.newValue||"")}),a.onChange(this._onChange)}postMessage(e){a.varStorage.setItem(this.room,a.toBase64(a.createUint8ArrayFromArrayBuffer(e)))}close(){a.offChange(this._onChange)}}:BroadcastChannel,Ws=e=>a.setIfUndefined(Bs,e,()=>{const t=a.create$2(),n=new Hs(e);return n.onmessage=e=>t.forEach(t=>t(e.data,"broadcastchannel")),{bc:n,subs:t}}),Ys=e.__commonJSMin((e,t)=>{!function(n){if("object"==typeof e&&void 0!==t)t.exports=n();else if("function"==typeof define&&define.amd)define([],n);else{("undefined"==typeof window?"undefined"==typeof global?"undefined"==typeof self?this:self:global:window).SimplePeer=n()}}(function(){var e=Math.floor,t=Math.abs,n=Math.pow;return function e(t,n,r){function i(o,a){if(!n[o]){if(!t[o]){var c="function"==typeof require&&require;if(!a&&c)return c(o,!0);if(s)return s(o,!0);var l=new Error("Cannot find module '"+o+"'");throw l.code="MODULE_NOT_FOUND",l}var d=n[o]={exports:{}};t[o][0].call(d.exports,function(e){return i(t[o][1][e]||e)},d,d.exports,e,t,n,r)}return n[o].exports}for(var s="function"==typeof require&&require,o=0;o<r.length;o++)i(r[o]);return i}({1:[function(e,t,n){"use strict";function r(e){var t=e.length;if(0<t%4)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function i(e){return o[63&e>>18]+o[63&e>>12]+o[63&e>>6]+o[63&e]}function s(e,t,n){for(var r,s=[],o=t;o<n;o+=3)r=(16711680&e[o]<<16)+(65280&e[o+1]<<8)+(255&e[o+2]),s.push(i(r));return s.join("")}n.byteLength=function(e){var t=r(e),n=t[0],i=t[1];return 3*(n+i)/4-i},n.toByteArray=function(e){var t,n,i=r(e),s=i[0],o=i[1],l=new c(function(e,t,n){return 3*(t+n)/4-n}(0,s,o)),d=0,h=0<o?s-4:s;for(n=0;n<h;n+=4)t=a[e.charCodeAt(n)]<<18|a[e.charCodeAt(n+1)]<<12|a[e.charCodeAt(n+2)]<<6|a[e.charCodeAt(n+3)],l[d++]=255&t>>16,l[d++]=255&t>>8,l[d++]=255&t;return 2===o&&(t=a[e.charCodeAt(n)]<<2|a[e.charCodeAt(n+1)]>>4,l[d++]=255&t),1===o&&(t=a[e.charCodeAt(n)]<<10|a[e.charCodeAt(n+1)]<<4|a[e.charCodeAt(n+2)]>>2,l[d++]=255&t>>8,l[d++]=255&t),l},n.fromByteArray=function(e){for(var t,n=e.length,r=n%3,i=[],a=16383,c=0,l=n-r;c<l;c+=a)i.push(s(e,c,c+a>l?l:c+a));return 1===r?(t=e[n-1],i.push(o[t>>2]+o[63&t<<4]+"==")):2===r&&(t=(e[n-2]<<8)+e[n-1],i.push(o[t>>10]+o[63&t>>4]+o[63&t<<2]+"=")),i.join("")};for(var o=[],a=[],c="undefined"==typeof Uint8Array?Array:Uint8Array,l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",d=0;d<64;++d)o[d]=l[d],a[l.charCodeAt(d)]=d;a[45]=62,a[95]=63},{}],2:[function(){},{}],3:[function(e,t,r){(function(){(function(){"use strict";var t=String.fromCharCode,i=Math.min;function s(e){if(2147483647<e)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=o.prototype,t}function o(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return l(e)}return a(e,t,n)}function a(e,t,n){if("string"==typeof e)return function(e,t){if(("string"!=typeof t||""===t)&&(t="utf8"),!o.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var n=0|u(e,t),r=s(n),i=r.write(e,t);return i!==n&&(r=r.slice(0,i)),r}(e,t);if(ArrayBuffer.isView(e))return d(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(V(e,ArrayBuffer)||e&&V(e.buffer,ArrayBuffer))return function(e,t,n){if(0>t||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');var r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n);return r.__proto__=o.prototype,r}(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return o.from(r,t,n);var i=function(e){if(o.isBuffer(e)){var t=0|h(e.length),n=s(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0===e.length?"Buffer"===e.type&&Array.isArray(e.data)?d(e.data):void 0:"number"!=typeof e.length||F(e.length)?s(0):d(e)}(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return o.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function c(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(0>e)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function l(e){return c(e),s(0>e?0:0|h(e))}function d(e){for(var t=0>e.length?0:0|h(e.length),n=s(t),r=0;r<t;r+=1)n[r]=255&e[r];return n}function h(e){if(e>=2147483647)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+2147483647..toString(16)+" bytes");return 0|e}function u(e,t){if(o.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||V(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var n=e.length,r=2<arguments.length&&!0===arguments[2];if(!r&&0===n)return 0;for(var i=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return I(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return N(e).length;default:if(i)return r?-1:I(e).length;t=(""+t).toLowerCase(),i=!0}}function f(e,t,n){var r=!1;if((void 0===t||0>t)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),0>=n)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return T(this,t,n);case"utf8":case"utf-8":return C(this,t,n);case"ascii":return A(this,t,n);case"latin1":case"binary":return x(this,t,n);case"base64":return k(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function g(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function p(e,t,n,r,i){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):2147483647<n?n=2147483647:-2147483648>n&&(n=-2147483648),F(n=+n)&&(n=i?0:e.length-1),0>n&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(0>n){if(!i)return-1;n=0}if("string"==typeof t&&(t=o.from(t,r)),o.isBuffer(t))return 0===t.length?-1:m(e,t,n,r,i);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):m(e,[t],n,r,i);throw new TypeError("val must be string, number or Buffer")}function m(e,t,n,r,i){function s(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}var o,a=1,c=e.length,l=t.length;if(void 0!==r&&("ucs2"===(r=(r+"").toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(2>e.length||2>t.length)return-1;a=2,c/=2,l/=2,n/=2}if(i){var d=-1;for(o=n;o<c;o++)if(s(e,o)!==s(t,-1===d?0:o-d))-1!==d&&(o-=o-d),d=-1;else if(-1===d&&(d=o),o-d+1===l)return d*a}else for(n+l>c&&(n=c-l),o=n;0<=o;o--){for(var h=!0,u=0;u<l;u++)if(s(e,o+u)!==s(t,u)){h=!1;break}if(h)return o}return-1}function y(e,t,n,r){n=+n||0;var i=e.length-n;r?(r=+r)>i&&(r=i):r=i;var s=t.length;r>s/2&&(r=s/2);for(var o,a=0;a<r;++a){if(F(o=parseInt(t.substr(2*a,2),16)))return a;e[n+a]=o}return a}function w(e,t,n,r){return j(I(t,e.length-n),e,n,r)}function b(e,t,n,r){return j(function(e){for(var t=[],n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function v(e,t,n,r){return b(e,t,n,r)}function _(e,t,n,r){return j(N(t),e,n,r)}function S(e,t,n,r){return j(function(e,t){for(var n,r,i,s=[],o=0;o<e.length&&!(0>(t-=2));++o)n=e.charCodeAt(o),r=n>>8,i=n%256,s.push(i),s.push(r);return s}(t,e.length-n),e,n,r)}function k(e,t,n){return 0===t&&n===e.length?B.fromByteArray(e):B.fromByteArray(e.slice(t,n))}function C(e,t,n){n=i(e.length,n);for(var r=[],s=t;s<n;){var o,a,c,l,d=e[s],h=null,u=239<d?4:223<d?3:191<d?2:1;if(s+u<=n)1===u?128>d&&(h=d):2===u?128==(192&(o=e[s+1]))&&(127<(l=(31&d)<<6|63&o)&&(h=l)):3===u?(o=e[s+1],a=e[s+2],128==(192&o)&&128==(192&a)&&(2047<(l=(15&d)<<12|(63&o)<<6|63&a)&&(55296>l||57343<l)&&(h=l))):4===u&&(o=e[s+1],a=e[s+2],c=e[s+3],128==(192&o)&&128==(192&a)&&128==(192&c)&&(65535<(l=(15&d)<<18|(63&o)<<12|(63&a)<<6|63&c)&&1114112>l&&(h=l)));null===h?(h=65533,u=1):65535<h&&(h-=65536,r.push(55296|1023&h>>>10),h=56320|1023&h),r.push(h),s+=u}return E(r)}function E(e){var n=e.length;if(n<=4096)return t.apply(String,e);for(var r="",i=0;i<n;)r+=t.apply(String,e.slice(i,i+=4096));return r}function A(e,n,r){var s="";r=i(e.length,r);for(var o=n;o<r;++o)s+=t(127&e[o]);return s}function x(e,n,r){var s="";r=i(e.length,r);for(var o=n;o<r;++o)s+=t(e[o]);return s}function T(e,t,n){var r=e.length;(!t||0>t)&&(t=0),(!n||0>n||n>r)&&(n=r);for(var i="",s=t;s<n;++s)i+=M(e[s]);return i}function R(e,n,r){for(var i=e.slice(n,r),s="",o=0;o<i.length;o+=2)s+=t(i[o]+256*i[o+1]);return s}function D(e,t,n){if(0!=e%1||0>e)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function O(e,t,n,r,i,s){if(!o.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<s)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function U(e,t,n,r){if(n+r>e.length)throw new RangeError("Index out of range");if(0>n)throw new RangeError("Index out of range")}function P(e,t,n,r,i){return t=+t,n>>>=0,i||U(e,0,n,4),H.write(e,t,n,r,23,4),n+4}function L(e,t,n,r,i){return t=+t,n>>>=0,i||U(e,0,n,8),H.write(e,t,n,r,52,8),n+8}function M(e){return 16>e?"0"+e.toString(16):e.toString(16)}function I(e,t){t=t||1/0;for(var n,r=e.length,i=null,s=[],o=0;o<r;++o){if(55295<(n=e.charCodeAt(o))&&57344>n){if(!i){if(56319<n){-1<(t-=3)&&s.push(239,191,189);continue}if(o+1===r){-1<(t-=3)&&s.push(239,191,189);continue}i=n;continue}if(56320>n){-1<(t-=3)&&s.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&-1<(t-=3)&&s.push(239,191,189);if(i=null,128>n){if(0>(t-=1))break;s.push(n)}else if(2048>n){if(0>(t-=2))break;s.push(192|n>>6,128|63&n)}else if(65536>n){if(0>(t-=3))break;s.push(224|n>>12,128|63&n>>6,128|63&n)}else{if(!(1114112>n))throw new Error("Invalid code point");if(0>(t-=4))break;s.push(240|n>>18,128|63&n>>12,128|63&n>>6,128|63&n)}}return s}function N(e){return B.toByteArray(function(e){if(2>(e=(e=e.split("=")[0]).trim().replace(W,"")).length)return"";for(;0!=e.length%4;)e+="=";return e}(e))}function j(e,t,n,r){for(var i=0;i<r&&!(i+n>=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function V(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function F(e){return e!=e}var B=e("base64-js"),H=e("ieee754");r.Buffer=o,r.SlowBuffer=function(e){return+e!=e&&(e=0),o.alloc(+e)},r.INSPECT_MAX_BYTES=50,r.kMaxLength=2147483647,o.TYPED_ARRAY_SUPPORT=function(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(t){return!1}}(),o.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||console.error,Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){return o.isBuffer(this)?this.buffer:void 0}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){return o.isBuffer(this)?this.byteOffset:void 0}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&o[Symbol.species]===o&&Object.defineProperty(o,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),o.poolSize=8192,o.from=function(e,t,n){return a(e,t,n)},o.prototype.__proto__=Uint8Array.prototype,o.__proto__=Uint8Array,o.alloc=function(e,t,n){return function(e,t,n){return c(e),0>=e||void 0===t?s(e):"string"==typeof n?s(e).fill(t,n):s(e).fill(t)}(e,t,n)},o.allocUnsafe=function(e){return l(e)},o.allocUnsafeSlow=function(e){return l(e)},o.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==o.prototype},o.compare=function(e,t){if(V(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),V(t,Uint8Array)&&(t=o.from(t,t.offset,t.byteLength)),!o.isBuffer(e)||!o.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var n=e.length,r=t.length,s=0,a=i(n,r);s<a;++s)if(e[s]!==t[s]){n=e[s],r=t[s];break}return n<r?-1:r<n?1:0},o.isEncoding=function(e){switch((e+"").toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},o.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return o.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=o.allocUnsafe(t),i=0;for(n=0;n<e.length;++n){var s=e[n];if(V(s,Uint8Array)&&(s=o.from(s)),!o.isBuffer(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(r,i),i+=s.length}return r},o.byteLength=u,o.prototype._isBuffer=!0,o.prototype.swap16=function(){var e=this.length;if(0!=e%2)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)g(this,t,t+1);return this},o.prototype.swap32=function(){var e=this.length;if(0!=e%4)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)g(this,t,t+3),g(this,t+1,t+2);return this},o.prototype.swap64=function(){var e=this.length;if(0!=e%8)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)g(this,t,t+7),g(this,t+1,t+6),g(this,t+2,t+5),g(this,t+3,t+4);return this},o.prototype.toString=function(){var e=this.length;return 0===e?"":0===arguments.length?C(this,0,e):f.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(e){if(!o.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===o.compare(this,e)},o.prototype.inspect=function(){var e="",t=r.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),"<Buffer "+e+">"},o.prototype.compare=function(e,t,n,r,s){if(V(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),!o.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===s&&(s=this.length),0>t||n>e.length||0>r||s>this.length)throw new RangeError("out of range index");if(r>=s&&t>=n)return 0;if(r>=s)return-1;if(t>=n)return 1;if(this===e)return 0;for(var a=(s>>>=0)-(r>>>=0),c=(n>>>=0)-(t>>>=0),l=i(a,c),d=this.slice(r,s),h=e.slice(t,n),u=0;u<l;++u)if(d[u]!==h[u]){a=d[u],c=h[u];break}return a<c?-1:c<a?1:0},o.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},o.prototype.indexOf=function(e,t,n){return p(this,e,t,n,!0)},o.prototype.lastIndexOf=function(e,t,n){return p(this,e,t,n,!1)},o.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var i=this.length-t;if((void 0===n||n>i)&&(n=i),0<e.length&&(0>n||0>t)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var s=!1;;)switch(r){case"hex":return y(this,e,t,n);case"utf8":case"utf-8":return w(this,e,t,n);case"ascii":return b(this,e,t,n);case"latin1":case"binary":return v(this,e,t,n);case"base64":return _(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},o.prototype.slice=function(e,t){var n=this.length;0>(e=~~e)?0>(e+=n)&&(e=0):e>n&&(e=n),0>(t=void 0===t?n:~~t)?0>(t+=n)&&(t=0):t>n&&(t=n),t<e&&(t=e);var r=this.subarray(e,t);return r.__proto__=o.prototype,r},o.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||D(e,t,this.length);for(var r=this[e],i=1,s=0;++s<t&&(i*=256);)r+=this[e+s]*i;return r},o.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||D(e,t,this.length);for(var r=this[e+--t],i=1;0<t&&(i*=256);)r+=this[e+--t]*i;return r},o.prototype.readUInt8=function(e,t){return e>>>=0,t||D(e,1,this.length),this[e]},o.prototype.readUInt16LE=function(e,t){return e>>>=0,t||D(e,2,this.length),this[e]|this[e+1]<<8},o.prototype.readUInt16BE=function(e,t){return e>>>=0,t||D(e,2,this.length),this[e]<<8|this[e+1]},o.prototype.readUInt32LE=function(e,t){return e>>>=0,t||D(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},o.prototype.readUInt32BE=function(e,t){return e>>>=0,t||D(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},o.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||D(e,t,this.length);for(var i=this[e],s=1,o=0;++o<t&&(s*=256);)i+=this[e+o]*s;return i>=(s*=128)&&(i-=n(2,8*t)),i},o.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||D(e,t,this.length);for(var i=t,s=1,o=this[e+--i];0<i&&(s*=256);)o+=this[e+--i]*s;return o>=(s*=128)&&(o-=n(2,8*t)),o},o.prototype.readInt8=function(e,t){return e>>>=0,t||D(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},o.prototype.readInt16LE=function(e,t){e>>>=0,t||D(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},o.prototype.readInt16BE=function(e,t){e>>>=0,t||D(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},o.prototype.readInt32LE=function(e,t){return e>>>=0,t||D(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},o.prototype.readInt32BE=function(e,t){return e>>>=0,t||D(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},o.prototype.readFloatLE=function(e,t){return e>>>=0,t||D(e,4,this.length),H.read(this,e,!0,23,4)},o.prototype.readFloatBE=function(e,t){return e>>>=0,t||D(e,4,this.length),H.read(this,e,!1,23,4)},o.prototype.readDoubleLE=function(e,t){return e>>>=0,t||D(e,8,this.length),H.read(this,e,!0,52,8)},o.prototype.readDoubleBE=function(e,t){return e>>>=0,t||D(e,8,this.length),H.read(this,e,!1,52,8)},o.prototype.writeUIntLE=function(e,t,r,i){(e=+e,t>>>=0,r>>>=0,i)||O(this,e,t,r,n(2,8*r)-1,0);var s=1,o=0;for(this[t]=255&e;++o<r&&(s*=256);)this[t+o]=255&e/s;return t+r},o.prototype.writeUIntBE=function(e,t,r,i){(e=+e,t>>>=0,r>>>=0,i)||O(this,e,t,r,n(2,8*r)-1,0);var s=r-1,o=1;for(this[t+s]=255&e;0<=--s&&(o*=256);)this[t+s]=255&e/o;return t+r},o.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,1,255,0),this[t]=255&e,t+1},o.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},o.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},o.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},o.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},o.prototype.writeIntLE=function(e,t,r,i){if(e=+e,t>>>=0,!i){var s=n(2,8*r-1);O(this,e,t,r,s-1,-s)}var o=0,a=1,c=0;for(this[t]=255&e;++o<r&&(a*=256);)0>e&&0===c&&0!==this[t+o-1]&&(c=1),this[t+o]=255&(e/a|0)-c;return t+r},o.prototype.writeIntBE=function(e,t,r,i){if(e=+e,t>>>=0,!i){var s=n(2,8*r-1);O(this,e,t,r,s-1,-s)}var o=r-1,a=1,c=0;for(this[t+o]=255&e;0<=--o&&(a*=256);)0>e&&0===c&&0!==this[t+o+1]&&(c=1),this[t+o]=255&(e/a|0)-c;return t+r},o.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,1,127,-128),0>e&&(e=255+e+1),this[t]=255&e,t+1},o.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},o.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},o.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},o.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,2147483647,-2147483648),0>e&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},o.prototype.writeFloatLE=function(e,t,n){return P(this,e,t,!0,n)},o.prototype.writeFloatBE=function(e,t,n){return P(this,e,t,!1,n)},o.prototype.writeDoubleLE=function(e,t,n){return L(this,e,t,!0,n)},o.prototype.writeDoubleBE=function(e,t,n){return L(this,e,t,!1,n)},o.prototype.copy=function(e,t,n,r){if(!o.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),0<r&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(0>t)throw new RangeError("targetStart out of bounds");if(0>n||n>=this.length)throw new RangeError("Index out of range");if(0>r)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);var i=r-n;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,n,r);else if(this===e&&n<t&&t<r)for(var s=i-1;0<=s;--s)e[s+t]=this[s+n];else Uint8Array.prototype.set.call(e,this.subarray(n,r),t);return i},o.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!o.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){var i=e.charCodeAt(0);("utf8"===r&&128>i||"latin1"===r)&&(e=i)}}else"number"==typeof e&&(e&=255);if(0>t||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;var s;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(s=t;s<n;++s)this[s]=e;else{var a=o.isBuffer(e)?e:o.from(e,r),c=a.length;if(0===c)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(s=0;s<n-t;++s)this[s+t]=a[s%c]}return this};var W=/[^+/0-9A-Za-z-_]/g}).call(this)}).call(this,e("buffer").Buffer)},{"base64-js":1,buffer:3,ieee754:9}],4:[function(e,t,n){(function(r){(function(){n.formatArgs=function(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;e.splice(1,0,n,"color: inherit");let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{"%%"===e||(r++,"%c"===e&&(i=r))}),e.splice(i,0,n)},n.save=function(e){try{e?n.storage.setItem("debug",e):n.storage.removeItem("debug")}catch(e){}},n.load=function(){let e;try{e=n.storage.getItem("debug")}catch(e){}return!e&&void 0!==r&&"env"in r&&(e=r.env.DEBUG),e},n.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||!("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&31<=parseInt(RegExp.$1,10)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},n.storage=function(){try{return localStorage}catch(e){}}(),n.destroy=(()=>{let e=!1;return()=>{e||(e=!0)}})(),n.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],n.log=console.debug||console.log||(()=>{}),t.exports=e("./common")(n);const{formatters:i}=t.exports;i.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}).call(this)}).call(this,e("_process"))},{"./common":5,_process:12}],5:[function(e,n){n.exports=function(n){function r(e){function t(...e){if(!t.enabled)return;const i=t,s=+new Date;i.diff=s-(n||s),i.prev=n,i.curr=s,n=s,e[0]=r.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,n)=>{if("%%"===t)return"%";o++;const s=r.formatters[n];if("function"==typeof s){const n=e[o];t=s.call(i,n),e.splice(o,1),o--}return t}),r.formatArgs.call(i,e),(i.log||r.log).apply(i,e)}let n,s=null;return t.namespace=e,t.useColors=r.useColors(),t.color=r.selectColor(e),t.extend=i,t.destroy=r.destroy,Object.defineProperty(t,"enabled",{enumerable:!0,configurable:!1,get:()=>null===s?r.enabled(e):s,set:e=>{s=e}}),"function"==typeof r.init&&r.init(t),t}function i(e,t){const n=r(this.namespace+(void 0===t?":":t)+e);return n.log=this.log,n}function s(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return r.debug=r,r.default=r,r.coerce=function(e){return e instanceof Error?e.stack||e.message:e},r.disable=function(){const e=[...r.names.map(s),...r.skips.map(s).map(e=>"-"+e)].join(",");return r.enable(""),e},r.enable=function(e){let t;r.save(e),r.names=[],r.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),i=n.length;for(t=0;t<i;t++)n[t]&&("-"===(e=n[t].replace(/\*/g,".*?"))[0]?r.skips.push(new RegExp("^"+e.substr(1)+"$")):r.names.push(new RegExp("^"+e+"$")))},r.enabled=function(e){if("*"===e[e.length-1])return!0;let t,n;for(t=0,n=r.skips.length;t<n;t++)if(r.skips[t].test(e))return!1;for(t=0,n=r.names.length;t<n;t++)if(r.names[t].test(e))return!0;return!1},r.humanize=e("ms"),r.destroy=function(){},Object.keys(n).forEach(e=>{r[e]=n[e]}),r.names=[],r.skips=[],r.formatters={},r.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return r.colors[t(n)%r.colors.length]},r.enable(r.load()),r}},{ms:11}],6:[function(e,t){"use strict";function n(e,t){for(const n in t)Object.defineProperty(e,n,{value:t[n],enumerable:!0,configurable:!0});return e}t.exports=function(e,t,r){if(!e||"string"==typeof e)throw new TypeError("Please pass an Error to err-code");r||(r={}),"object"==typeof t&&(r=t,t=""),t&&(r.code=t);try{return n(e,r)}catch(t){r.message=e.message,r.stack=e.stack;const i=function(){};return i.prototype=Object.create(Object.getPrototypeOf(e)),n(new i,r)}}},{}],7:[function(e,t){"use strict";function n(){n.init.call(this)}function r(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function i(e){return void 0===e._maxListeners?n.defaultMaxListeners:e._maxListeners}function s(e,t,n,s){var o,a,c;if(r(n),void 0===(a=e._events)?(a=e._events=Object.create(null),e._eventsCount=0):(void 0!==a.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),a=e._events),c=a[t]),void 0===c)c=a[t]=n,++e._eventsCount;else if("function"==typeof c?c=a[t]=s?[n,c]:[c,n]:s?c.unshift(n):c.push(n),0<(o=i(e))&&c.length>o&&!c.warned){c.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=c.length,console&&console.warn}return e}function o(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function a(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=o.bind(r);return i.listener=n,r.wrapFn=i,i}function c(e,t,n){var r=e._events;if(void 0===r)return[];var i=r[t];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]:n?function(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(i):d(i,i.length)}function l(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function d(e,t){for(var n=Array(t),r=0;r<t;++r)n[r]=e[r];return n}function h(e,t,n,r){if("function"==typeof e.on)r.once?e.once(t,n):e.on(t,n);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,function i(s){r.once&&e.removeEventListener(t,i),n(s)})}}var u,f="object"==typeof Reflect?Reflect:null,g=f&&"function"==typeof f.apply?f.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};u=f&&"function"==typeof f.ownKeys?f.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var p=Number.isNaN||function(e){return e!=e};t.exports=n,t.exports.once=function(e,t){return new Promise(function(n,r){function i(n){e.removeListener(t,s),r(n)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",i),n([].slice.call(arguments))}h(e,t,s,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&h(e,"error",t,n)}(e,i,{once:!0})})},n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var m=10;Object.defineProperty(n,"defaultMaxListeners",{enumerable:!0,get:function(){return m},set:function(e){if("number"!=typeof e||0>e||p(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");m=e}}),n.init=function(){(void 0===this._events||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},n.prototype.setMaxListeners=function(e){if("number"!=typeof e||0>e||p(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},n.prototype.getMaxListeners=function(){return i(this)},n.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var r="error"===e,i=this._events;if(void 0!==i)r=r&&void 0===i.error;else if(!r)return!1;if(r){var s;if(0<t.length&&(s=t[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var a=i[e];if(void 0===a)return!1;if("function"==typeof a)g(a,this,t);else{var c=a.length,l=d(a,c);for(n=0;n<c;++n)g(l[n],this,t)}return!0},n.prototype.addListener=function(e,t){return s(this,e,t,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(e,t){return s(this,e,t,!0)},n.prototype.once=function(e,t){return r(t),this.on(e,a(this,e,t)),this},n.prototype.prependOnceListener=function(e,t){return r(t),this.prependListener(e,a(this,e,t)),this},n.prototype.removeListener=function(e,t){var n,i,s,o,a;if(r(t),void 0===(i=this._events))return this;if(void 0===(n=i[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(s=-1,o=n.length-1;0<=o;o--)if(n[o]===t||n[o].listener===t){a=n[o].listener,s=o;break}if(0>s)return this;0===s?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,s),1===n.length&&(i[e]=n[0]),void 0!==i.removeListener&&this.emit("removeListener",e,a||t)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(e){var t,n,r=this._events;if(void 0===r)return this;if(void 0===r.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==r[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete r[e]),this;if(0===arguments.length){var i,s=Object.keys(r);for(n=0;n<s.length;++n)"removeListener"!==(i=s[n])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;0<=n;n--)this.removeListener(e,t[n]);return this},n.prototype.listeners=function(e){return c(this,e,!0)},n.prototype.rawListeners=function(e){return c(this,e,!1)},n.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):l.call(e,t)},n.prototype.listenerCount=l,n.prototype.eventNames=function(){return 0<this._eventsCount?u(this._events):[]}},{}],8:[function(e,t){t.exports=function(){if("undefined"==typeof globalThis)return null;var e={RTCPeerConnection:globalThis.RTCPeerConnection||globalThis.mozRTCPeerConnection||globalThis.webkitRTCPeerConnection,RTCSessionDescription:globalThis.RTCSessionDescription||globalThis.mozRTCSessionDescription||globalThis.webkitRTCSessionDescription,RTCIceCandidate:globalThis.RTCIceCandidate||globalThis.mozRTCIceCandidate||globalThis.webkitRTCIceCandidate};return e.RTCPeerConnection?e:null}},{}],9:[function(r,i,s){s.read=function(e,t,r,i,s){var o,a,c=8*s-i-1,l=(1<<c)-1,d=l>>1,h=-7,u=r?s-1:0,f=r?-1:1,g=e[t+u];for(u+=f,o=g&(1<<-h)-1,g>>=-h,h+=c;0<h;o=256*o+e[t+u],u+=f,h-=8);for(a=o&(1<<-h)-1,o>>=-h,h+=i;0<h;a=256*a+e[t+u],u+=f,h-=8);if(0===o)o=1-d;else{if(o===l)return a?NaN:1/0*(g?-1:1);a+=n(2,i),o-=d}return(g?-1:1)*a*n(2,o-i)},s.write=function(r,i,s,o,a,c){var l,d,h,u=Math.LN2,f=Math.log,g=8*c-a-1,p=(1<<g)-1,m=p>>1,y=23===a?n(2,-24)-n(2,-77):0,w=o?0:c-1,b=o?1:-1,v=0>i||0===i&&0>1/i?1:0;for(i=t(i),isNaN(i)||i===1/0?(d=isNaN(i)?1:0,l=p):(l=e(f(i)/u),1>i*(h=n(2,-l))&&(l--,h*=2),2<=(i+=1<=l+m?y/h:y*n(2,1-m))*h&&(l++,h/=2),l+m>=p?(d=0,l=p):1<=l+m?(d=(i*h-1)*n(2,a),l+=m):(d=i*n(2,m-1)*n(2,a),l=0));8<=a;r[s+w]=255&d,w+=b,d/=256,a-=8);for(l=l<<a|d,g+=a;0<g;r[s+w]=255&l,w+=b,l/=256,g-=8);r[s+w-b]|=128*v}},{}],10:[function(e,t){t.exports="function"==typeof Object.create?function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}},{}],11:[function(e,n){var r=Math.round;function i(e){var n=t(e);return 864e5<=n?r(e/864e5)+"d":36e5<=n?r(e/36e5)+"h":6e4<=n?r(e/6e4)+"m":1e3<=n?r(e/1e3)+"s":e+"ms"}function s(e){var n=t(e);return 864e5<=n?o(e,n,864e5,"day"):36e5<=n?o(e,n,36e5,"hour"):6e4<=n?o(e,n,6e4,"minute"):1e3<=n?o(e,n,1e3,"second"):e+" ms"}function o(e,t,n,i){return r(e/n)+" "+i+(t>=1.5*n?"s":"")}n.exports=function(e,t){t=t||{};var n=typeof e;if("string"==n&&0<e.length)return function(e){if(!(100<(e+="").length)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]),r=(t[2]||"ms").toLowerCase();return"years"===r||"year"===r||"yrs"===r||"yr"===r||"y"===r?315576e5*n:"weeks"===r||"week"===r||"w"===r?6048e5*n:"days"===r||"day"===r||"d"===r?864e5*n:"hours"===r||"hour"===r||"hrs"===r||"hr"===r||"h"===r?36e5*n:"minutes"===r||"minute"===r||"mins"===r||"min"===r||"m"===r?6e4*n:"seconds"===r||"second"===r||"secs"===r||"sec"===r||"s"===r?1e3*n:"milliseconds"===r||"millisecond"===r||"msecs"===r||"msec"===r||"ms"===r?n:void 0}}}(e);if("number"===n&&isFinite(e))return t.long?s(e):i(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},{}],12:[function(e,t){function n(){throw new Error("setTimeout has not been defined")}function r(){throw new Error("clearTimeout has not been defined")}function i(e){if(l===setTimeout)return setTimeout(e,0);if((l===n||!l)&&setTimeout)return l=setTimeout,setTimeout(e,0);try{return l(e,0)}catch(n){try{return l.call(null,e,0)}catch(n){return l.call(this,e,0)}}}function s(){g&&u&&(g=!1,u.length?f=u.concat(f):p=-1,f.length&&o())}function o(){if(!g){var e=i(s);g=!0;for(var t=f.length;t;){for(u=f,f=[];++p<t;)u&&u[p].run();p=-1,t=f.length}u=null,g=!1,function(e){if(d===clearTimeout)return clearTimeout(e);if((d===r||!d)&&clearTimeout)return d=clearTimeout,clearTimeout(e);try{return d(e)}catch(n){try{return d.call(null,e)}catch(n){return d.call(this,e)}}}(e)}}function a(e,t){this.fun=e,this.array=t}function c(){}var l,d,h=t.exports={};!function(){try{l="function"==typeof setTimeout?setTimeout:n}catch(t){l=n}try{d="function"==typeof clearTimeout?clearTimeout:r}catch(t){d=r}}();var u,f=[],g=!1,p=-1;h.nextTick=function(e){var t=Array(arguments.length-1);if(1<arguments.length)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];f.push(new a(e,t)),1!==f.length||g||i(o)},a.prototype.run=function(){this.fun.apply(null,this.array)},h.title="browser",h.browser=!0,h.env={},h.argv=[],h.version="",h.versions={},h.on=c,h.addListener=c,h.once=c,h.off=c,h.removeListener=c,h.removeAllListeners=c,h.emit=c,h.prependListener=c,h.prependOnceListener=c,h.listeners=function(){return[]},h.binding=function(){throw new Error("process.binding is not supported")},h.cwd=function(){return"/"},h.chdir=function(){throw new Error("process.chdir is not supported")},h.umask=function(){return 0}},{}],13:[function(e,t){(function(e){(function(){let n;t.exports="function"==typeof queueMicrotask?queueMicrotask.bind("undefined"==typeof window?e:window):e=>(n||(n=Promise.resolve())).then(e).catch(e=>setTimeout(()=>{throw e},0))}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{}],14:[function(e,t){(function(n,r){(function(){"use strict";var i=e("safe-buffer").Buffer,s=r.crypto||r.msCrypto;t.exports=s&&s.getRandomValues?function(e,t){if(e>4294967295)throw new RangeError("requested too many random bytes");var r=i.allocUnsafe(e);if(0<e)if(65536<e)for(var o=0;o<e;o+=65536)s.getRandomValues(r.slice(o,o+65536));else s.getRandomValues(r);return"function"==typeof t?n.nextTick(function(){t(null,r)}):r}:function(){throw new Error("Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11")}}).call(this)}).call(this,e("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{_process:12,"safe-buffer":30}],15:[function(e,t){"use strict";function n(e,t,n){function r(e,n,r){return"string"==typeof t?t:t(e,n,r)}n||(n=Error);var s=function(e){function t(t,n,i){return e.call(this,r(t,n,i))||this}return function(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}(t,e),t}(n);s.prototype.name=n.name,s.prototype.code=e,i[e]=s}function r(e,t){if(Array.isArray(e)){var n=e.length;return e=e.map(function(e){return e+""}),2<n?"one of ".concat(t," ").concat(e.slice(0,n-1).join(", "),", or ")+e[n-1]:2===n?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(e+"")}var i={};n("ERR_INVALID_OPT_VALUE",function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'},TypeError),n("ERR_INVALID_ARG_TYPE",function(e,t,n){var i,s;if("string"==typeof t&&function(e,t,n){return e.substr(!n||0>n?0:+n,t.length)===t}(t,"not ")?(i="must not be",t=t.replace(/^not /,"")):i="must be",function(e,t,n){return(void 0===n||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}(e," argument"))s="The ".concat(e," ").concat(i," ").concat(r(t,"type"));else{var o=function(e,t,n){return"number"!=typeof n&&(n=0),!(n+t.length>e.length)&&-1!==e.indexOf(t,n)}(e,".")?"property":"argument";s='The "'.concat(e,'" ').concat(o," ").concat(i," ").concat(r(t,"type"))}return s+=". Received type ".concat(typeof n)},TypeError),n("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),n("ERR_METHOD_NOT_IMPLEMENTED",function(e){return"The "+e+" method is not implemented"}),n("ERR_STREAM_PREMATURE_CLOSE","Premature close"),n("ERR_STREAM_DESTROYED",function(e){return"Cannot call "+e+" after a stream was destroyed"}),n("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),n("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),n("ERR_STREAM_WRITE_AFTER_END","write after end"),n("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),n("ERR_UNKNOWN_ENCODING",function(e){return"Unknown encoding: "+e},TypeError),n("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),t.exports.codes=i},{}],16:[function(e,t){(function(n){(function(){"use strict";function r(e){return this instanceof r?(a.call(this,e),c.call(this,e),this.allowHalfOpen=!0,void(e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",i))))):new r(e)}function i(){this._writableState.ended||n.nextTick(s,this)}function s(e){e.end()}var o=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=r;var a=e("./_stream_readable"),c=e("./_stream_writable");e("inherits")(r,a);for(var l,d=o(c.prototype),h=0;h<d.length;h++)l=d[h],r.prototype[l]||(r.prototype[l]=c.prototype[l]);Object.defineProperty(r.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(r.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(r.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(r.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&this._readableState.destroyed&&this._writableState.destroyed},set:function(e){void 0===this._readableState||void 0===this._writableState||(this._readableState.destroyed=e,this._writableState.destroyed=e)}})}).call(this)}).call(this,e("_process"))},{"./_stream_readable":18,"./_stream_writable":20,_process:12,inherits:10}],17:[function(e,t){"use strict";function n(e){return this instanceof n?void r.call(this,e):new n(e)}t.exports=n;var r=e("./_stream_transform");e("inherits")(n,r),n.prototype._transform=function(e,t,n){n(null,e)}},{"./_stream_transform":19,inherits:10}],18:[function(e,t){(function(n,r){(function(){"use strict";function i(t,n,r){S=S||e("./_stream_duplex"),t=t||{},"boolean"!=typeof r&&(r=n instanceof S),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=L(this,t,"readableHighWaterMark",r),this.buffer=new U,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(!R&&(R=e("string_decoder/").StringDecoder),this.decoder=new R(t.encoding),this.encoding=t.encoding)}function s(t){if(S=S||e("./_stream_duplex"),!(this instanceof s))return new s(t);var n=this instanceof S;this._readableState=new i(t,this,n),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),E.call(this)}function o(e,t,n,r,i){k("readableAddChunk",t);var s,o=e._readableState;if(null===t)o.reading=!1,function(e,t){if(k("onEofChunk"),!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?d(e):(t.needReadable=!1,!t.emittedReadable&&(t.emittedReadable=!0,h(e)))}}(e,o);else if(i||(s=c(o,t)),s)F(e,s);else if(o.objectMode||t&&0<t.length)if("string"==typeof t||o.objectMode||Object.getPrototypeOf(t)===A.prototype||(t=function(e){return A.from(e)}(t)),r)o.endEmitted?F(e,new V):a(e,o,t,!0);else if(o.ended)F(e,new N);else{if(o.destroyed)return!1;o.reading=!1,o.decoder&&!n?(t=o.decoder.write(t),o.objectMode||0!==t.length?a(e,o,t,!1):u(e,o)):a(e,o,t,!1)}else r||(o.reading=!1,u(e,o));return!o.ended&&(o.length<o.highWaterMark||0===o.length)}function a(e,t,n,r){t.flowing&&0===t.length&&!t.sync?(t.awaitDrain=0,e.emit("data",n)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&d(e)),u(e,t)}function c(e,t){var n;return function(e){return A.isBuffer(e)||e instanceof x}(t)||"string"==typeof t||void 0===t||e.objectMode||(n=new I("chunk",["string","Buffer","Uint8Array"],t)),n}function l(e,t){return 0>=e||0===t.length&&t.ended?0:t.objectMode?1:e==e?(e>t.highWaterMark&&(t.highWaterMark=function(e){return 1073741824<=e?e=1073741824:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0)):t.flowing&&t.length?t.buffer.head.data.length:t.length}function d(e){var t=e._readableState;k("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(k("emitReadable",t.flowing),t.emittedReadable=!0,n.nextTick(h,e))}function h(e){var t=e._readableState;k("emitReadable_",t.destroyed,t.length,t.ended),!t.destroyed&&(t.length||t.ended)&&(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,y(e)}function u(e,t){t.readingMore||(t.readingMore=!0,n.nextTick(f,e,t))}function f(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&0===t.length);){var n=t.length;if(k("maybeReadMore read 0"),e.read(0),n===t.length)break}t.readingMore=!1}function g(e){var t=e._readableState;t.readableListening=0<e.listenerCount("readable"),t.resumeScheduled&&!t.paused?t.flowing=!0:0<e.listenerCount("data")&&e.resume()}function p(e){k("readable nexttick read 0"),e.read(0)}function m(e,t){k("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),y(e),t.flowing&&!t.reading&&e.read(0)}function y(e){var t=e._readableState;for(k("flow",t.flowing);t.flowing&&null!==e.read(););}function w(e,t){return 0===t.length?null:(t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n);var n}function b(e){var t=e._readableState;k("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,n.nextTick(v,t,e))}function v(e,t){if(k("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}function _(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}var S,k;t.exports=s,s.ReadableState=i,e("events").EventEmitter;var C=function(e,t){return e.listeners(t).length},E=e("./internal/streams/stream"),A=e("buffer").Buffer,x=r.Uint8Array||function(){},T=e("util");k=T&&T.debuglog?T.debuglog("stream"):function(){};var R,D,O,U=e("./internal/streams/buffer_list"),P=e("./internal/streams/destroy"),L=e("./internal/streams/state").getHighWaterMark,M=e("../errors").codes,I=M.ERR_INVALID_ARG_TYPE,N=M.ERR_STREAM_PUSH_AFTER_EOF,j=M.ERR_METHOD_NOT_IMPLEMENTED,V=M.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;e("inherits")(s,E);var F=P.errorOrDestroy,B=["error","close","destroy","pause","resume"];Object.defineProperty(s.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),s.prototype.destroy=P.destroy,s.prototype._undestroy=P.undestroy,s.prototype._destroy=function(e,t){t(e)},s.prototype.push=function(e,t){var n,r=this._readableState;return r.objectMode?n=!0:"string"==typeof e&&((t=t||r.defaultEncoding)!==r.encoding&&(e=A.from(e,t),t=""),n=!0),o(this,e,t,!1,n)},s.prototype.unshift=function(e){return o(this,e,null,!0,!1)},s.prototype.isPaused=function(){return!1===this._readableState.flowing},s.prototype.setEncoding=function(t){R||(R=e("string_decoder/").StringDecoder);var n=new R(t);this._readableState.decoder=n,this._readableState.encoding=this._readableState.decoder.encoding;for(var r=this._readableState.buffer.head,i="";null!==r;)i+=n.write(r.data),r=r.next;return this._readableState.buffer.clear(),""!==i&&this._readableState.buffer.push(i),this._readableState.length=i.length,this},s.prototype.read=function(e){k("read",e),e=parseInt(e,10);var t=this._readableState,n=e;if(0!==e&&(t.emittedReadable=!1),0===e&&t.needReadable&&((0===t.highWaterMark?0<t.length:t.length>=t.highWaterMark)||t.ended))return k("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?b(this):d(this),null;if(0===(e=l(e,t))&&t.ended)return 0===t.length&&b(this),null;var r=t.needReadable;k("need readable",r),(0===t.length||t.length-e<t.highWaterMark)&&k("length less than watermark",r=!0),t.ended||t.reading?k("reading or ended",r=!1):r&&(k("do read"),t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,!t.reading&&(e=l(n,t)));var i=0<e?w(e,t):null;return null===i?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(!t.ended&&(t.needReadable=!0),n!==e&&t.ended&&b(this)),null!==i&&this.emit("data",i),i},s.prototype._read=function(){F(this,new j("_read()"))},s.prototype.pipe=function(e,t){function r(e,t){k("onunpipe"),e===h&&t&&!1===t.hasUnpiped&&(t.hasUnpiped=!0,s())}function i(){k("onend"),e.end()}function s(){k("cleanup"),e.removeListener("close",c),e.removeListener("finish",l),e.removeListener("drain",g),e.removeListener("error",a),e.removeListener("unpipe",r),h.removeListener("end",i),h.removeListener("end",d),h.removeListener("data",o),p=!0,u.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&g()}function o(t){k("ondata");var n=e.write(t);k("dest.write",n),!1===n&&((1===u.pipesCount&&u.pipes===e||1<u.pipesCount&&-1!==_(u.pipes,e))&&!p&&(k("false write response, pause",u.awaitDrain),u.awaitDrain++),h.pause())}function a(t){k("onerror",t),d(),e.removeListener("error",a),0===C(e,"error")&&F(e,t)}function c(){e.removeListener("finish",l),d()}function l(){k("onfinish"),e.removeListener("close",c),d()}function d(){k("unpipe"),h.unpipe(e)}var h=this,u=this._readableState;switch(u.pipesCount){case 0:u.pipes=e;break;case 1:u.pipes=[u.pipes,e];break;default:u.pipes.push(e)}u.pipesCount+=1,k("pipe count=%d opts=%j",u.pipesCount,t);var f=t&&!1===t.end||e===n.stdout||e===n.stderr?d:i;u.endEmitted?n.nextTick(f):h.once("end",f),e.on("unpipe",r);var g=function(e){return function(){var t=e._readableState;k("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&C(e,"data")&&(t.flowing=!0,y(e))}}(h);e.on("drain",g);var p=!1;return h.on("data",o),function(e,t,n){"function"==typeof e.prependListener?e.prependListener(t,n):e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n)}(e,"error",a),e.once("close",c),e.once("finish",l),e.emit("pipe",h),u.flowing||(k("pipe resume"),h.resume()),e},s.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n)),this;if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var s=0;s<i;s++)r[s].emit("unpipe",this,{hasUnpiped:!1});return this}var o=_(t.pipes,e);return-1===o||(t.pipes.splice(o,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,n)),this},s.prototype.on=function(e,t){var r=E.prototype.on.call(this,e,t),i=this._readableState;return"data"===e?(i.readableListening=0<this.listenerCount("readable"),!1!==i.flowing&&this.resume()):"readable"==e&&!i.endEmitted&&!i.readableListening&&(i.readableListening=i.needReadable=!0,i.flowing=!1,i.emittedReadable=!1,k("on readable",i.length,i.reading),i.length?d(this):!i.reading&&n.nextTick(p,this)),r},s.prototype.addListener=s.prototype.on,s.prototype.removeListener=function(e,t){var r=E.prototype.removeListener.call(this,e,t);return"readable"===e&&n.nextTick(g,this),r},s.prototype.removeAllListeners=function(e){var t=E.prototype.removeAllListeners.apply(this,arguments);return("readable"===e||void 0===e)&&n.nextTick(g,this),t},s.prototype.resume=function(){var e=this._readableState;return e.flowing||(k("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,n.nextTick(m,e,t))}(this,e)),e.paused=!1,this},s.prototype.pause=function(){return k("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(k("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},s.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var i in e.on("end",function(){if(k("wrapped end"),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)}),e.on("data",function(i){k("wrapped data"),n.decoder&&(i=n.decoder.write(i)),n.objectMode&&null==i||!(n.objectMode||i&&i.length)||t.push(i)||(r=!0,e.pause())}),e)void 0===this[i]&&"function"==typeof e[i]&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));for(var s=0;s<B.length;s++)e.on(B[s],this.emit.bind(this,B[s]));return this._read=function(t){k("wrapped _read",t),r&&(r=!1,e.resume())},this},"function"==typeof Symbol&&(s.prototype[Symbol.asyncIterator]=function(){return void 0===D&&(D=e("./internal/streams/async_iterator")),D(this)}),Object.defineProperty(s.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(s.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(s.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),s._fromList=w,Object.defineProperty(s.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(s.from=function(t,n){return void 0===O&&(O=e("./internal/streams/from")),O(s,t,n)})}).call(this)}).call(this,e("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"../errors":15,"./_stream_duplex":16,"./internal/streams/async_iterator":21,"./internal/streams/buffer_list":22,"./internal/streams/destroy":23,"./internal/streams/from":25,"./internal/streams/state":27,"./internal/streams/stream":28,_process:12,buffer:3,events:7,inherits:10,"string_decoder/":31,util:2}],19:[function(e,t){"use strict";function n(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(null===r)return this.emit("error",new c);n.writechunk=null,n.writecb=null,null!=t&&this.push(t),r(e);var i=this._readableState;i.reading=!1,(i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}function r(e){return this instanceof r?(h.call(this,e),this._transformState={afterTransform:n.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),void this.on("prefinish",i)):new r(e)}function i(){var e=this;"function"!=typeof this._flush||this._readableState.destroyed?s(this,null,null):this._flush(function(t,n){s(e,t,n)})}function s(e,t,n){if(t)return e.emit("error",t);if(null!=n&&e.push(n),e._writableState.length)throw new d;if(e._transformState.transforming)throw new l;return e.push(null)}t.exports=r;var o=e("../errors").codes,a=o.ERR_METHOD_NOT_IMPLEMENTED,c=o.ERR_MULTIPLE_CALLBACK,l=o.ERR_TRANSFORM_ALREADY_TRANSFORMING,d=o.ERR_TRANSFORM_WITH_LENGTH_0,h=e("./_stream_duplex");e("inherits")(r,h),r.prototype.push=function(e,t){return this._transformState.needTransform=!1,h.prototype.push.call(this,e,t)},r.prototype._transform=function(e,t,n){n(new a("_transform()"))},r.prototype._write=function(e,t,n){var r=this._transformState;if(r.writecb=n,r.writechunk=e,r.writeencoding=t,!r.transforming){var i=this._readableState;(r.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}},r.prototype._read=function(){var e=this._transformState;null===e.writechunk||e.transforming?e.needTransform=!0:(e.transforming=!0,this._transform(e.writechunk,e.writeencoding,e.afterTransform))},r.prototype._destroy=function(e,t){h.prototype._destroy.call(this,e,function(e){t(e)})}},{"../errors":15,"./_stream_duplex":16,inherits:10}],20:[function(e,t){(function(n,r){(function(){"use strict";function i(e){var t=this;this.next=null,this.entry=null,this.finish=function(){!function(e,t,n){var r=e.entry;for(e.entry=null;r;){var i=r.callback;t.pendingcb--,i(n),r=r.next}t.corkedRequestsFree.next=e}(t,e)}}function s(){}function o(t,n,r){v=v||e("./_stream_duplex"),t=t||{},"boolean"!=typeof r&&(r=n instanceof v),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=x(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var s=!1===t.decodeStrings;this.decodeStrings=!s,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){u(n,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new i(this)}function a(t){var n=this instanceof(v=v||e("./_stream_duplex"));return n||_.call(a,this)?(this._writableState=new o(t,this,n),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),void k.call(this)):new a(t)}function c(e,t){var r=new M;N(e,r),n.nextTick(t,r)}function l(e,t,r,i){var s;return null===r?s=new L:"string"!=typeof r&&!t.objectMode&&(s=new R("chunk",["string","Buffer"],r)),!s||(N(e,s),n.nextTick(i,s),!1)}function d(e,t,n,r,i,s){if(!n){var o=function(e,t,n){return e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=C.from(t,n)),t}(t,r,i);r!==o&&(n=!0,i="buffer",r=o)}var a=t.objectMode?1:r.length;t.length+=a;var c=t.length<t.highWaterMark;if(c||(t.needDrain=!0),t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:i,isBuf:n,callback:s,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else h(e,t,!1,a,r,i,s);return c}function h(e,t,n,r,i,s,o){t.writelen=r,t.writecb=o,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new P("write")):n?e._writev(i,t.onwrite):e._write(i,s,t.onwrite),t.sync=!1}function u(e,t){var r=e._writableState,i=r.sync,s=r.writecb;if("function"!=typeof s)throw new O;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(r),t)!function(e,t,r,i,s){--t.pendingcb,r?(n.nextTick(s,i),n.nextTick(w,e,t),e._writableState.errorEmitted=!0,N(e,i)):(s(i),e._writableState.errorEmitted=!0,N(e,i),w(e,t))}(e,r,i,t,s);else{var o=p(r)||e.destroyed;o||r.corked||r.bufferProcessing||!r.bufferedRequest||g(e,r),i?n.nextTick(f,e,r,o,s):f(e,r,o,s)}}function f(e,t,n,r){n||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,r(),w(e,t)}function g(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var r=t.bufferedRequestCount,s=Array(r),o=t.corkedRequestsFree;o.entry=n;for(var a=0,c=!0;n;)s[a]=n,n.isBuf||(c=!1),n=n.next,a+=1;s.allBuffers=c,h(e,t,!0,t.length,s,"",o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new i(t),t.bufferedRequestCount=0}else{for(;n;){var l=n.chunk,d=n.encoding,u=n.callback;if(h(e,t,!1,t.objectMode?1:l.length,l,d,u),n=n.next,t.bufferedRequestCount--,t.writing)break}null===n&&(t.lastBufferedRequest=null)}t.bufferedRequest=n,t.bufferProcessing=!1}function p(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function m(e,t){e._final(function(n){t.pendingcb--,n&&N(e,n),t.prefinished=!0,e.emit("prefinish"),w(e,t)})}function y(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.pendingcb++,t.finalCalled=!0,n.nextTick(m,e,t)))}function w(e,t){var n=p(t);if(n&&(y(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"),t.autoDestroy))){var r=e._readableState;(!r||r.autoDestroy&&r.endEmitted)&&e.destroy()}return n}function b(e,t,r){t.ending=!0,w(e,t),r&&(t.finished?n.nextTick(r):e.once("finish",r)),t.ended=!0,e.writable=!1}var v;t.exports=a,a.WritableState=o;var _,S={deprecate:e("util-deprecate")},k=e("./internal/streams/stream"),C=e("buffer").Buffer,E=r.Uint8Array||function(){},A=e("./internal/streams/destroy"),x=e("./internal/streams/state").getHighWaterMark,T=e("../errors").codes,R=T.ERR_INVALID_ARG_TYPE,D=T.ERR_METHOD_NOT_IMPLEMENTED,O=T.ERR_MULTIPLE_CALLBACK,U=T.ERR_STREAM_CANNOT_PIPE,P=T.ERR_STREAM_DESTROYED,L=T.ERR_STREAM_NULL_VALUES,M=T.ERR_STREAM_WRITE_AFTER_END,I=T.ERR_UNKNOWN_ENCODING,N=A.errorOrDestroy;e("inherits")(a,k),o.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(o.prototype,"buffer",{get:S.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(_=Function.prototype[Symbol.hasInstance],Object.defineProperty(a,Symbol.hasInstance,{value:function(e){return!!_.call(this,e)||!(this!==a)&&e&&e._writableState instanceof o}})):_=function(e){return e instanceof this},a.prototype.pipe=function(){N(this,new U)},a.prototype.write=function(e,t,n){var r=this._writableState,i=!1,o=!r.objectMode&&function(e){return C.isBuffer(e)||e instanceof E}(e);return o&&!C.isBuffer(e)&&(e=function(e){return C.from(e)}(e)),"function"==typeof t&&(n=t,t=null),o?t="buffer":!t&&(t=r.defaultEncoding),"function"!=typeof n&&(n=s),r.ending?c(this,n):(o||l(this,r,e,n))&&(r.pendingcb++,i=d(this,r,o,e,t,n)),i},a.prototype.cork=function(){this._writableState.corked++},a.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest&&g(this,e))},a.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(-1<["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())))throw new I(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(a.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(a.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),a.prototype._write=function(e,t,n){n(new D("_write()"))},a.prototype._writev=null,a.prototype.end=function(e,t,n){var r=this._writableState;return"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||b(this,r,n),this},Object.defineProperty(a.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(a.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),a.prototype.destroy=A.destroy,a.prototype._undestroy=A.undestroy,a.prototype._destroy=function(e,t){t(e)}}).call(this)}).call(this,e("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"../errors":15,"./_stream_duplex":16,"./internal/streams/destroy":23,"./internal/streams/state":27,"./internal/streams/stream":28,_process:12,buffer:3,inherits:10,"util-deprecate":32}],21:[function(e,t){(function(n){(function(){"use strict";function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){return{value:e,done:t}}function s(e){var t=e[l];if(null!==t){var n=e[p].read();null!==n&&(e[f]=null,e[l]=null,e[d]=null,t(i(n,!1)))}}function o(e){n.nextTick(s,e)}var a,c=e("./end-of-stream"),l=Symbol("lastResolve"),d=Symbol("lastReject"),h=Symbol("error"),u=Symbol("ended"),f=Symbol("lastPromise"),g=Symbol("handlePromise"),p=Symbol("stream"),m=Object.getPrototypeOf(function(){}),y=Object.setPrototypeOf((a={get stream(){return this[p]},next:function(){var e=this,t=this[h];if(null!==t)return Promise.reject(t);if(this[u])return Promise.resolve(i(void 0,!0));if(this[p].destroyed)return new Promise(function(t,r){n.nextTick(function(){e[h]?r(e[h]):t(i(void 0,!0))})});var r,s=this[f];if(s)r=new Promise(function(e,t){return function(n,r){e.then(function(){t[u]?n(i(void 0,!0)):t[g](n,r)},r)}}(s,this));else{var o=this[p].read();if(null!==o)return Promise.resolve(i(o,!1));r=new Promise(this[g])}return this[f]=r,r}},r(a,Symbol.asyncIterator,function(){return this}),r(a,"return",function(){var e=this;return new Promise(function(t,n){e[p].destroy(null,function(e){e?n(e):t(i(void 0,!0))})})}),a),m);t.exports=function(e){var t,n=Object.create(y,(r(t={},p,{value:e,writable:!0}),r(t,l,{value:null,writable:!0}),r(t,d,{value:null,writable:!0}),r(t,h,{value:null,writable:!0}),r(t,u,{value:e._readableState.endEmitted,writable:!0}),r(t,g,{value:function(e,t){var r=n[p].read();r?(n[f]=null,n[l]=null,n[d]=null,e(i(r,!1))):(n[l]=e,n[d]=t)},writable:!0}),t));return n[f]=null,c(e,function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=n[d];return null!==t&&(n[f]=null,n[l]=null,n[d]=null,t(e)),void(n[h]=e)}var r=n[l];null!==r&&(n[f]=null,n[l]=null,n[d]=null,r(i(void 0,!0))),n[u]=!0}),e.on("readable",o.bind(null,n)),n}}).call(this)}).call(this,e("_process"))},{"./end-of-stream":24,_process:12}],22:[function(e,t){"use strict";function n(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){for(var n,r=0;r<t.length;r++)(n=t[r]).enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}function s(e,t,n){o.prototype.copy.call(e,t,n)}var o=e("buffer").Buffer,a=e("util").inspect,c=a&&a.custom||"inspect";t.exports=function(){function e(){(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),this.head=null,this.tail=null,this.length=0}return function(e,t,n){t&&i(e.prototype,t),n&&i(e,n)}(e,[{key:"push",value:function(e){var t={data:e,next:null};0<this.length?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:"unshift",value:function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}},{key:"shift",value:function(){if(0!==this.length){var e=this.head.data;return this.head=1===this.length?this.tail=null:this.head.next,--this.length,e}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n}},{key:"concat",value:function(e){if(0===this.length)return o.alloc(0);for(var t=o.allocUnsafe(e>>>0),n=this.head,r=0;n;)s(n.data,t,r),r+=n.data.length,n=n.next;return t}},{key:"consume",value:function(e,t){var n;return e<this.head.data.length?(n=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):n=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),n}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(e){var t=this.head,n=1,r=t.data;for(e-=r.length;t=t.next;){var i=t.data,s=e>i.length?i.length:e;if(r+=s===i.length?i:i.slice(0,e),0===(e-=s)){s===i.length?(++n,this.head=t.next?t.next:this.tail=null):(this.head=t,t.data=i.slice(s));break}++n}return this.length-=n,r}},{key:"_getBuffer",value:function(e){var t=o.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var i=n.data,s=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,s),0===(e-=s)){s===i.length?(++r,this.head=n.next?n.next:this.tail=null):(this.head=n,n.data=i.slice(s));break}++r}return this.length-=r,t}},{key:c,value:function(e,t){return a(this,function(e){for(var t,i=1;i<arguments.length;i++)t=null==arguments[i]?{}:arguments[i],i%2?n(Object(t),!0).forEach(function(n){r(e,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):n(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))});return e}({},t,{depth:0,customInspect:!1}))}}]),e}()},{buffer:3,util:2}],23:[function(e,t){(function(e){(function(){"use strict";function n(e,t){i(e,t),r(e)}function r(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function i(e,t){e.emit("error",t)}t.exports={destroy:function(t,s){var o=this,a=this._readableState&&this._readableState.destroyed,c=this._writableState&&this._writableState.destroyed;return a||c?(s?s(t):t&&(this._writableState?!this._writableState.errorEmitted&&(this._writableState.errorEmitted=!0,e.nextTick(i,this,t)):e.nextTick(i,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,function(t){!s&&t?o._writableState?o._writableState.errorEmitted?e.nextTick(r,o):(o._writableState.errorEmitted=!0,e.nextTick(n,o,t)):e.nextTick(n,o,t):s?(e.nextTick(r,o),s(t)):e.nextTick(r,o)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit("error",t)}}}).call(this)}).call(this,e("_process"))},{_process:12}],24:[function(e,t){"use strict";function n(){}var r=e("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;t.exports=function e(t,i,s){if("function"==typeof i)return e(t,null,i);i||(i={}),s=function(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=Array(n),i=0;i<n;i++)r[i]=arguments[i];e.apply(this,r)}}}(s||n);var o=i.readable||!1!==i.readable&&t.readable,a=i.writable||!1!==i.writable&&t.writable,c=function(){t.writable||d()},l=t._writableState&&t._writableState.finished,d=function(){a=!1,l=!0,o||s.call(t)},h=t._readableState&&t._readableState.endEmitted,u=function(){o=!1,h=!0,a||s.call(t)},f=function(e){s.call(t,e)},g=function(){var e;return o&&!h?(t._readableState&&t._readableState.ended||(e=new r),s.call(t,e)):a&&!l?(t._writableState&&t._writableState.ended||(e=new r),s.call(t,e)):void 0},p=function(){t.req.on("finish",d)};return function(e){return e.setHeader&&"function"==typeof e.abort}(t)?(t.on("complete",d),t.on("abort",g),t.req?p():t.on("request",p)):a&&!t._writableState&&(t.on("end",c),t.on("close",c)),t.on("end",u),t.on("finish",d),!1!==i.error&&t.on("error",f),t.on("close",g),function(){t.removeListener("complete",d),t.removeListener("abort",g),t.removeListener("request",p),t.req&&t.req.removeListener("finish",d),t.removeListener("end",c),t.removeListener("close",c),t.removeListener("finish",d),t.removeListener("end",u),t.removeListener("error",f),t.removeListener("close",g)}}},{"../../../errors":15}],25:[function(e,t){t.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],26:[function(e,t){"use strict";function n(e){if(e)throw e}function r(t,n,r,i){i=function(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}(i);var s=!1;t.on("close",function(){s=!0}),void 0===a&&(a=e("./end-of-stream")),a(t,{readable:n,writable:r},function(e){return e?i(e):(s=!0,void i())});var o=!1;return function(e){if(!s)return o?void 0:(o=!0,function(e){return e.setHeader&&"function"==typeof e.abort}(t)?t.abort():"function"==typeof t.destroy?t.destroy():void i(e||new d("pipe")))}}function i(e){e()}function s(e,t){return e.pipe(t)}function o(e){return e.length&&"function"==typeof e[e.length-1]?e.pop():n}var a,c=e("../../../errors").codes,l=c.ERR_MISSING_ARGS,d=c.ERR_STREAM_DESTROYED;t.exports=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var a=o(t);if(Array.isArray(t[0])&&(t=t[0]),2>t.length)throw new l("streams");var c,d=t.map(function(e,n){var s=n<t.length-1;return r(e,s,0<n,function(e){c||(c=e),e&&d.forEach(i),s||(d.forEach(i),a(c))})});return t.reduce(s)}},{"../../../errors":15,"./end-of-stream":24}],27:[function(t,n){"use strict";var r=t("../../../errors").codes.ERR_INVALID_OPT_VALUE;n.exports={getHighWaterMark:function(t,n,i,s){var o=function(e,t,n){return null==e.highWaterMark?t?e[n]:null:e.highWaterMark}(n,s,i);if(null!=o){if(!isFinite(o)||e(o)!==o||0>o)throw new r(s?i:"highWaterMark",o);return e(o)}return t.objectMode?16:16384}}},{"../../../errors":15}],28:[function(e,t){t.exports=e("events").EventEmitter},{events:7}],29:[function(e,t,n){(n=t.exports=e("./lib/_stream_readable.js")).Stream=n,n.Readable=n,n.Writable=e("./lib/_stream_writable.js"),n.Duplex=e("./lib/_stream_duplex.js"),n.Transform=e("./lib/_stream_transform.js"),n.PassThrough=e("./lib/_stream_passthrough.js"),n.finished=e("./lib/internal/streams/end-of-stream.js"),n.pipeline=e("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":16,"./lib/_stream_passthrough.js":17,"./lib/_stream_readable.js":18,"./lib/_stream_transform.js":19,"./lib/_stream_writable.js":20,"./lib/internal/streams/end-of-stream.js":24,"./lib/internal/streams/pipeline.js":26}],30:[function(e,t,n){function r(e,t){for(var n in e)t[n]=e[n]}function i(e,t,n){return o(e,t,n)}var s=e("buffer"),o=s.Buffer;o.from&&o.alloc&&o.allocUnsafe&&o.allocUnsafeSlow?t.exports=s:(r(s,n),n.Buffer=i),i.prototype=Object.create(o.prototype),r(o,i),i.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return o(e,t,n)},i.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=o(e);return void 0===t?r.fill(0):"string"==typeof n?r.fill(t,n):r.fill(t),r},i.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return o(e)},i.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return s.SlowBuffer(e)}},{buffer:3}],31:[function(e,t,n){"use strict";function r(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(u.isEncoding===f||!f(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=o,this.end=a,t=4;break;case"utf8":this.fillLast=s,t=4;break;case"base64":this.text=c,this.end=l,t=3;break;default:return this.write=d,void(this.end=h)}this.lastNeed=0,this.lastTotal=0,this.lastChar=u.allocUnsafe(t)}function i(e){return 127>=e?0:6==e>>5?2:14==e>>4?3:30==e>>3?4:2==e>>6?-1:-2}function s(e){var t=this.lastTotal-this.lastNeed,n=function(e,t){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(1<e.lastNeed&&1<t.length){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(2<e.lastNeed&&2<t.length&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0===n?this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length)):n}function o(e,t){if(0==(e.length-t)%2){var n=e.toString("utf16le",t);if(n){var r=n.charCodeAt(n.length-1);if(55296<=r&&56319>=r)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function a(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function c(e,t){var n=(e.length-t)%3;return 0==n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1==n?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-n))}function l(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function d(e){return e.toString(this.encoding)}function h(e){return e&&e.length?this.write(e):""}var u=e("safe-buffer").Buffer,f=u.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};n.StringDecoder=r,r.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n<e.length?t?t+this.text(e,n):this.text(e,n):t||""},r.prototype.end=function(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t},r.prototype.text=function(e,t){var n=function(e,t,n){var r=t.length-1;if(r<n)return 0;var s=i(t[r]);return 0<=s?(0<s&&(e.lastNeed=s-1),s):--r<n||-2===s?0:0<=(s=i(t[r]))?(0<s&&(e.lastNeed=s-2),s):--r<n||-2===s?0:0<=(s=i(t[r]))?(0<s&&(2===s?s=0:e.lastNeed=s-3),s):0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString("utf8",t,r)},r.prototype.fillLast=function(e){return this.lastNeed<=e.length?(e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),void(this.lastNeed-=e.length))}},{"safe-buffer":30}],32:[function(e,t){(function(e){(function(){function n(t){try{if(!e.localStorage)return!1}catch(e){return!1}var n=e.localStorage[t];return null!=n&&"true"===(n+"").toLowerCase()}t.exports=function(e,t){if(n("noDeprecation"))return e;var r=!1;return function(){if(!r){if(n("throwDeprecation"))throw new Error(t);n("traceDeprecation"),r=!0}return e.apply(this,arguments)}}}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{}],"/":[function(e,t){function n(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}const r=e("debug")("simple-peer"),i=e("get-browser-rtc"),s=e("randombytes"),o=e("readable-stream"),a=e("queue-microtask"),c=e("err-code"),{Buffer:l}=e("buffer"),d=65536;class h extends o.Duplex{constructor(e){if(super(e=Object.assign({allowHalfOpen:!1},e)),this._id=s(4).toString("hex").slice(0,7),this._debug("new peer %o",e),this.channelName=e.initiator?e.channelName||s(20).toString("hex"):null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||h.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},h.config,e.config),this.offerOptions=e.offerOptions||{},this.answerOptions=e.answerOptions||{},this.sdpTransform=e.sdpTransform||(e=>e),this.streams=e.streams||(e.stream?[e.stream]:[]),this.trickle=void 0===e.trickle||e.trickle,this.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,this.iceCompleteTimeout=e.iceCompleteTimeout||5e3,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=e.wrtc&&"object"==typeof e.wrtc?e.wrtc:i(),!this._wrtc)throw"undefined"==typeof window?c(new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"),"ERR_WEBRTC_SUPPORT"):c(new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(e){return void this.destroy(c(e,"ERR_PC_CONSTRUCTOR"))}this._isReactNativeWebrtc="number"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=e=>{this._onIceCandidate(e)},"object"==typeof this._pc.peerIdentity&&this._pc.peerIdentity.catch(e=>{this.destroy(c(e,"ERR_PC_PEER_IDENTITY"))}),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this.streams&&this.streams.forEach(e=>{this.addStream(e)}),this._pc.ontrack=e=>{this._onTrack(e)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(e){if(!this.destroying){if(this.destroyed)throw c(new Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if("string"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}this._debug("signal()"),e.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),e.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(e.transceiverRequest.kind,e.transceiverRequest.init)),e.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(e.candidate):this._pendingCandidates.push(e.candidate)),e.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(e)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(e=>{this._addIceCandidate(e)}),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())}).catch(e=>{this.destroy(c(e,"ERR_SET_REMOTE_DESCRIPTION"))}),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.destroy(c(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(e){const t=new this._wrtc.RTCIceCandidate(e);this._pc.addIceCandidate(t).catch(e=>{!t.address||t.address.endsWith(".local")||this.destroy(c(e,"ERR_ADD_ICE_CANDIDATE"))})}send(e){if(!this.destroying){if(this.destroyed)throw c(new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(e)}}addTransceiver(e,t){if(!this.destroying){if(this.destroyed)throw c(new Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(e,t),this._needsNegotiation()}catch(e){this.destroy(c(e,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:e,init:t}})}}addStream(e){if(!this.destroying){if(this.destroyed)throw c(new Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),e.getTracks().forEach(t=>{this.addTrack(t,e)})}}addTrack(e,t){if(this.destroying)return;if(this.destroyed)throw c(new Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const n=this._senderMap.get(e)||new Map;let r=n.get(t);if(r)throw r.removed?c(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):c(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED");r=this._pc.addTrack(e,t),n.set(t,r),this._senderMap.set(e,n),this._needsNegotiation()}replaceTrack(e,t,n){if(this.destroying)return;if(this.destroyed)throw c(new Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const r=this._senderMap.get(e),i=r?r.get(n):null;if(!i)throw c(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");t&&this._senderMap.set(t,r),null==i.replaceTrack?this.destroy(c(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK")):i.replaceTrack(t)}removeTrack(e,t){if(this.destroying)return;if(this.destroyed)throw c(new Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const n=this._senderMap.get(e),r=n?n.get(t):null;if(!r)throw c(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{r.removed=!0,this._pc.removeTrack(r)}catch(e){"NS_ERROR_UNEXPECTED"===e.name?this._sendersAwaitingStable.push(r):this.destroy(c(e,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(e){if(!this.destroying){if(this.destroyed)throw c(new Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),e.getTracks().forEach(t=>{this.removeTrack(t,e)})}}_needsNegotiation(){this._debug("_needsNegotiation"),this._batchedNegotiation||(this._batchedNegotiation=!0,a(()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1}))}negotiate(){if(!this.destroying){if(this.destroyed)throw c(new Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}destroy(e){this._destroy(e,()=>{})}_destroy(e,t){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",e&&(e.message||e)),a(()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",e&&(e.message||e)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch(e){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(e){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,e&&this.emit("error",e),this.emit("close"),t()}))}_setupData(e){if(!e.channel)return this.destroy(c(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=e.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=d),this.channelName=this._channel.label,this._channel.onmessage=e=>{this._onChannelMessage(e)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=e=>{const t=e.error instanceof Error?e.error:new Error(`Datachannel error: ${e.message} ${e.filename}:${e.lineno}:${e.colno}`);this.destroy(c(t,"ERR_DATA_CHANNEL"))};let t=!1;this._closingInterval=setInterval(()=>{this._channel&&"closing"===this._channel.readyState?(t&&this._onChannelClose(),t=!0):t=!1},5e3)}_read(){}_write(e,t,n){if(this.destroyed)return n(c(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(e)}catch(e){return this.destroy(c(e,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>d?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=n):n(null)}else this._debug("write before connect"),this._chunk=e,this._cb=n}_onFinish(){if(!this.destroyed){const e=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?e():this.once("connect",e)}}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=n(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(!this.destroyed){const t=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:t.type,sdp:t.sdp})}};this._pc.setLocalDescription(e).then(()=>{this._debug("createOffer success"),this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))}).catch(e=>{this.destroy(c(e,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(e=>{this.destroy(c(e,"ERR_CREATE_OFFER"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(e=>{e.mid||!e.sender.track||e.requested||(e.requested=!0,this.addTransceiver(e.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=n(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(!this.destroyed){const t=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:t.type,sdp:t.sdp}),this.initiator||this._requestMissingTransceivers()}};this._pc.setLocalDescription(e).then(()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))}).catch(e=>{this.destroy(c(e,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(e=>{this.destroy(c(e,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(c(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",e,t),this.emit("iceStateChange",e,t),("connected"===e||"completed"===e)&&(this._pcReady=!0,this._maybeReady()),"failed"===e&&this.destroy(c(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),"closed"===e&&this.destroy(c(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(e){const t=e=>("[object Array]"===Object.prototype.toString.call(e.values)&&e.values.forEach(t=>{Object.assign(e,t)}),e);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then(n=>{const r=[];n.forEach(e=>{r.push(t(e))}),e(null,r)},t=>e(t)):0<this._pc.getStats.length?this._pc.getStats(n=>{if(this.destroyed)return;const r=[];n.result().forEach(e=>{const n={};e.names().forEach(t=>{n[t]=e.stat(t)}),n.id=e.id,n.type=e.type,n.timestamp=e.timestamp,r.push(t(n))}),e(null,r)},t=>e(t)):e(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this.getStats((t,n)=>{if(this.destroyed)return;t&&(n=[]);const r={},i={},s={};let o=!1;n.forEach(e=>{("remotecandidate"===e.type||"remote-candidate"===e.type)&&(r[e.id]=e),("localcandidate"===e.type||"local-candidate"===e.type)&&(i[e.id]=e),("candidatepair"===e.type||"candidate-pair"===e.type)&&(s[e.id]=e)});const a=e=>{o=!0;let t=i[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=+t.port):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=+t.portNumber):"string"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(":"),this.localAddress=t[0],this.localPort=+t[1]),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let n=r[e.remoteCandidateId];n&&(n.ip||n.address)?(this.remoteAddress=n.ip||n.address,this.remotePort=+n.port):n&&n.ipAddress?(this.remoteAddress=n.ipAddress,this.remotePort=+n.portNumber):"string"==typeof e.googRemoteAddress&&(n=e.googRemoteAddress.split(":"),this.remoteAddress=n[0],this.remotePort=+n[1]),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(n.forEach(e=>{"transport"===e.type&&e.selectedCandidatePairId&&a(s[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&a(e)}),o||Object.keys(s).length&&!Object.keys(i).length){if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(e){return this.destroy(c(e,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');const t=this._cb;this._cb=null,t(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}else setTimeout(e,100)})};e()}_onInterval(){this._cb&&this._channel&&!(this._channel.bufferedAmount>d)&&this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(e=>{this._pc.removeTrack(e),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(e){this.destroyed||(e.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):!e.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit("_iceComplete")),e.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(e){if(this.destroyed)return;let t=e.data;t instanceof ArrayBuffer&&(t=l.from(t)),this.push(t)}_onChannelBufferedAmountLow(){if(!this.destroyed&&this._cb){this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const e=this._cb;this._cb=null,e(null)}}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(e){this.destroyed||e.streams.forEach(t=>{this._debug("on track"),this.emit("track",e.track,t),this._remoteTracks.push({track:e.track,stream:t}),this._remoteStreams.some(e=>e.id===t.id)||(this._remoteStreams.push(t),a(()=>{this._debug("on stream"),this.emit("stream",t)}))})}_debug(){const e=[].slice.call(arguments);e[0]="["+this._id+"] "+e[0],r.apply(null,e)}}h.WEBRTC_SUPPORT=!!i(),h.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},h.channelConfig={},t.exports=h},{buffer:3,debug:4,"err-code":6,"get-browser-rtc":8,"queue-microtask":13,randombytes:14,"readable-stream":29}]},{},[])("/")})}),qs=e.__toESM(Ys(),1),Ks=(e,t)=>{if(!t)return a.resolve(e);const n=crypto.getRandomValues(new Uint8Array(12));return crypto.subtle.encrypt({name:"AES-GCM",iv:n},t,e).then(e=>{const t=a.createEncoder();return a.writeVarString(t,"AES-GCM"),a.writeVarUint8Array(t,n),a.writeVarUint8Array(t,new Uint8Array(e)),a.toUint8Array(t)})},zs=(e,t)=>{if(!t)return a.resolve(e);const n=a.createDecoder(e);"AES-GCM"!==a.readVarString(n)&&a.reject(a.create$1("Unknown encryption algorithm"));const r=a.readVarUint8Array(n),i=a.readVarUint8Array(n);return crypto.subtle.decrypt({name:"AES-GCM",iv:r},t,i).then(e=>new Uint8Array(e))},$s=a.createModuleLogger("y-webrtc"),Js=new Map,Qs=new Map,Gs=e=>{let t=!0;e.webrtcConns.forEach(e=>{e.synced||(t=!1)}),(!t&&e.synced||t&&!e.synced)&&(e.synced=t,e.provider.emit("synced",[{synced:t}]),$s("synced ",a.BOLD,e.name,a.UNBOLD," with all peers"))},Xs=(e,t,n)=>{const r=a.createDecoder(t),i=a.createEncoder(),s=a.readVarUint(r);if(void 0===e)return null;const o=e.awareness,c=e.doc;let l=!1;switch(s){case 0:{a.writeVarUint(i,0);const t=cs(r,i,c,e);1!==t||e.synced||n(),0===t&&(l=!0);break}case 3:a.writeVarUint(i,1),a.writeVarUint8Array(i,ts(o,Array.from(o.getStates().keys()))),l=!0;break;case 1:ns(o,a.readVarUint8Array(r),e);break;case 4:{const t=1===a.readUint8(r),n=a.readVarString(r);if(n!==e.peerId&&(e.bcConns.has(n)&&!t||!e.bcConns.has(n)&&t)){const r=[],i=[];t?(e.bcConns.add(n),i.push(n)):(e.bcConns.delete(n),r.push(n)),e.provider.emit("peers",[{added:i,removed:r,webrtcPeers:Array.from(e.webrtcConns.keys()),bcPeers:Array.from(e.bcConns)}]),io(e)}break}default:return i}return l?i:null},Zs=(e,t)=>{$s("send message to ",a.BOLD,e.remotePeerId,a.UNBOLD,a.GREY," (",e.room.name,")",a.UNCOLOR);try{e.peer.send(a.toUint8Array(t))}catch(n){}},eo=class{constructor(e,t,n,r){$s("establishing connection to ",a.BOLD,n),this.room=r,this.remotePeerId=n,this.glareToken=void 0,this.closed=!1,this.connected=!1,this.synced=!1,this.peer=new qs.default({initiator:t,...r.provider.peerOpts}),this.peer.on("signal",t=>{void 0===this.glareToken&&(this.glareToken=Date.now()+Math.random()),oo(e,r,{to:n,from:r.peerId,type:"signal",token:this.glareToken,signal:t})}),this.peer.on("connect",()=>{$s("connected to ",a.BOLD,n),this.connected=!0;const e=r.provider.doc,t=r.awareness,i=a.createEncoder();a.writeVarUint(i,0),rs(i,e),Zs(this,i);const s=t.getStates();if(s.size>0){const e=a.createEncoder();a.writeVarUint(e,1),a.writeVarUint8Array(e,ts(t,Array.from(s.keys()))),Zs(this,e)}}),this.peer.on("close",()=>{this.connected=!1,this.closed=!0,r.webrtcConns.has(this.remotePeerId)&&(r.webrtcConns.delete(this.remotePeerId),r.provider.emit("peers",[{removed:[this.remotePeerId],added:[],webrtcPeers:Array.from(r.webrtcConns.keys()),bcPeers:Array.from(r.bcConns)}])),Gs(r),this.peer.destroy(),$s("closed connection to ",a.BOLD,n),ro(r)}),this.peer.on("error",e=>{$s("Error in connection to ",a.BOLD,n,": ",e),ro(r)}),this.peer.on("data",e=>{const t=((e,t)=>{const n=e.room;return $s("received message from ",a.BOLD,e.remotePeerId,a.GREY," (",n.name,")",a.UNBOLD,a.UNCOLOR),Xs(n,t,()=>{e.synced=!0,$s("synced ",a.BOLD,n.name,a.UNBOLD," with ",a.BOLD,e.remotePeerId),Gs(n)})})(this,e);null!==t&&Zs(this,t)})}destroy(){this.peer.destroy()}},to=(e,t)=>Ks(t,e.key).then(t=>e.mux(()=>((e,t,n=null)=>{const r=Ws(e);r.bc.postMessage(t),r.subs.forEach(e=>e(t,n))})(e.name,t))),no=(e,t)=>{e.bcconnected&&to(e,t),((e,t)=>{$s("broadcast message in ",a.BOLD,e.name,a.UNBOLD),e.webrtcConns.forEach(e=>{try{e.peer.send(t)}catch(n){}})})(e,t)},ro=e=>{Js.forEach(t=>{t.connected&&(t.send({type:"subscribe",topics:[e.name]}),e.webrtcConns.size<e.provider.maxConns&&oo(t,e,{type:"announce",from:e.peerId}))})},io=e=>{if(e.provider.filterBcConns){const t=a.createEncoder();a.writeVarUint(t,4),a.writeUint8(t,1),a.writeVarString(t,e.peerId),to(e,a.toUint8Array(t))}},so=class{constructor(e,t,n,r){this.peerId=a.uuidv4(),this.doc=e,this.awareness=t.awareness,this.provider=t,this.synced=!1,this.name=n,this.key=r,this.webrtcConns=new Map,this.bcConns=new Set,this.mux=a.createMutex(),this.bcconnected=!1,this._bcSubscriber=e=>zs(new Uint8Array(e),r).then(e=>this.mux(()=>{const t=Xs(this,e,()=>{});t&&to(this,a.toUint8Array(t))})),this._docUpdateHandler=(e,t)=>{const n=a.createEncoder();a.writeVarUint(n,0),os(n,e),no(this,a.toUint8Array(n))},this._awarenessUpdateHandler=({added:e,updated:t,removed:n},r)=>{const i=e.concat(t).concat(n),s=a.createEncoder();a.writeVarUint(s,1),a.writeVarUint8Array(s,ts(this.awareness,i)),no(this,a.toUint8Array(s))},this._beforeUnloadHandler=()=>{es(this.awareness,[e.clientID],"window unload"),Qs.forEach(e=>{e.disconnect()})},"undefined"!=typeof window?window.addEventListener("beforeunload",this._beforeUnloadHandler):"undefined"!=typeof process&&process.on("exit",this._beforeUnloadHandler)}connect(){this.doc.on("update",this._docUpdateHandler),this.awareness.on("update",this._awarenessUpdateHandler),ro(this);const e=this.name;var t,n;t=e,n=this._bcSubscriber,Ws(t).subs.add(n),this.bcconnected=!0,io(this);const r=a.createEncoder();a.writeVarUint(r,0),rs(r,this.doc),to(this,a.toUint8Array(r));const i=a.createEncoder();a.writeVarUint(i,0),is(i,this.doc),to(this,a.toUint8Array(i));const s=a.createEncoder();a.writeVarUint(s,3),to(this,a.toUint8Array(s));const o=a.createEncoder();a.writeVarUint(o,1),a.writeVarUint8Array(o,ts(this.awareness,[this.doc.clientID])),to(this,a.toUint8Array(o))}disconnect(){Js.forEach(e=>{e.connected&&e.send({type:"unsubscribe",topics:[this.name]})}),es(this.awareness,[this.doc.clientID],"disconnect");const e=a.createEncoder();a.writeVarUint(e,4),a.writeUint8(e,0),a.writeVarString(e,this.peerId),to(this,a.toUint8Array(e)),((e,t)=>{const n=Ws(e),r=n.subs.delete(t);r&&0===n.subs.size&&(n.bc.close(),Bs.delete(e))})(this.name,this._bcSubscriber),this.bcconnected=!1,this.doc.off("update",this._docUpdateHandler),this.awareness.off("update",this._awarenessUpdateHandler),this.webrtcConns.forEach(e=>e.destroy())}destroy(){this.disconnect(),"undefined"!=typeof window?window.removeEventListener("beforeunload",this._beforeUnloadHandler):"undefined"!=typeof process&&process.off("exit",this._beforeUnloadHandler)}},oo=(e,t,n)=>{t.key?((e,t)=>{const n=a.createEncoder();return a.writeAny(n,e),Ks(a.toUint8Array(n),t)})(n,t.key).then(n=>{e.send({type:"publish",topic:t.name,data:a.toBase64(n)})}):e.send({type:"publish",topic:t.name,data:n})},ao=class extends Fs{constructor(e){super(e),this.providers=new Set,this.on("connect",()=>{$s(`connected (${e})`);const t=Array.from(Qs.keys());this.send({type:"subscribe",topics:t}),Qs.forEach(e=>oo(this,e,{type:"announce",from:e.peerId}))}),this.on("message",e=>{if("publish"===e.type){const r=e.topic,i=Qs.get(r);if(null==i||"string"!=typeof r)return;const s=e=>{const t=i.webrtcConns,n=i.peerId;if(null==e||e.from===n||void 0!==e.to&&e.to!==n||i.bcConns.has(e.from))return;const r=t.has(e.from)?()=>{}:()=>i.provider.emit("peers",[{removed:[],added:[e.from],webrtcPeers:Array.from(i.webrtcConns.keys()),bcPeers:Array.from(i.bcConns)}]);switch(e.type){case"announce":t.size<i.provider.maxConns&&(a.setIfUndefined(t,e.from,()=>new eo(this,!0,e.from,i)),r());break;case"signal":if("offer"===e.signal.type){const n=t.get(e.from);if(n){const t=e.token,r=n.glareToken;if(r&&r>t)return void $s("offer rejected: ",e.from);n.glareToken=void 0}}if("answer"===e.signal.type){$s("offer answered by: ",e.from);t.get(e.from).glareToken=void 0}e.to===n&&(a.setIfUndefined(t,e.from,()=>new eo(this,!1,e.from,i)).peer.signal(e.signal),r())}};i.key?"string"==typeof e.data&&(t=a.fromBase64(e.data),n=i.key,zs(t,n).then(e=>a.readAny(a.createDecoder(new Uint8Array(e))))).then(s):s(e.data)}var t,n}),this.on("disconnect",()=>$s(`disconnect (${e})`))}},co=e=>{e.emit("status",[{connected:e.connected}])},lo=class extends a.ObservableV2{constructor(e,t,{signaling:n=["wss://y-webrtc-eu.fly.dev"],password:r=null,awareness:i=new Zi(t),maxConns:s=20+a.floor(15*a.rand()),filterBcConns:o=!0,peerOpts:c={}}={}){super(),this.roomName=e,this.doc=t,this.filterBcConns=o,this.awareness=i,this.shouldConnect=!1,this.signalingUrls=n,this.signalingConns=[],this.maxConns=s,this.peerOpts=c,this.key=r?((e,t)=>{const n=a.encodeUtf8(e).buffer,r=a.encodeUtf8(t).buffer;return crypto.subtle.importKey("raw",n,"PBKDF2",!1,["deriveKey"]).then(e=>crypto.subtle.deriveKey({name:"PBKDF2",salt:r,iterations:1e5,hash:"SHA-256"},e,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]))})(r,e):a.resolve(null),this.room=null,this.key.then(n=>{this.room=((e,t,n,r)=>{if(Qs.has(n))throw a.create$1(`A Yjs Doc connected to room "${n}" already exists!`);const i=new so(e,t,n,r);return Qs.set(n,i),i})(t,this,e,n),this.shouldConnect?this.room.connect():this.room.disconnect(),co(this)}),this.connect(),this.destroy=this.destroy.bind(this),t.on("destroy",this.destroy)}get connected(){return null!==this.room&&this.shouldConnect}connect(){this.shouldConnect=!0,this.signalingUrls.forEach(e=>{const t=a.setIfUndefined(Js,e,()=>new ao(e));this.signalingConns.push(t),t.providers.add(this)}),this.room&&(this.room.connect(),co(this))}disconnect(){this.shouldConnect=!1,this.signalingConns.forEach(e=>{e.providers.delete(this),0===e.providers.size&&(e.destroy(),Js.delete(e.url))}),this.room&&(this.room.disconnect(),co(this))}destroy(){this.doc.off("destroy",this.destroy),this.key.then(()=>{this.room.destroy(),Qs.delete(this.roomName)}),super.destroy()}};async function ho(e,t){const n=await async function(e,t){const n=`${e}-${JSON.stringify(t)}`,r=(new TextEncoder).encode(n),i=globalThis.crypto?.subtle??globalThis.window?.crypto?.subtle;if(!i)throw new Error("Web Crypto API subtle.digest is unavailable");return function(e){const t=new DataView(e).getInt32(0,!1);return Math.abs(t)%2147483647+1}(await i.digest("SHA-256",r))}(e,t),r=new nt({guid:e});r.clientID=n;const i=bi(t);r.get("content",wr).applyDelta(i);const s=mt(r);return r.destroy(),s}var uo={hocuspocus:class{_isConnected=!1;_isSynced=!1;onConnect;onDisconnect;onError;onSyncChange;destroy=()=>{this._isConnected&&this.provider.disconnect()};disconnect=()=>{this._isConnected&&(this.provider.disconnect(),this._isConnected=!1,this._isSynced&&(this._isSynced=!1,this?.onSyncChange?.(!1)))};provider;type="hocuspocus";constructor({awareness:e,doc:t,options:n,wsOptions:r,onConnect:i,onDisconnect:s,onError:o,onSyncChange:a}){this.onConnect=i,this.onDisconnect=s,this.onSyncChange=a,this.onError=o;const c={...n,...t&&{document:t},...e&&{awareness:e},...r&&(()=>{try{return{websocketProvider:new ps(r)}}catch(e){return this.onError?.(e instanceof Error?e:new Error(String(e))),{}}})(),onAwarenessChange:n.onAwarenessChange||(()=>{}),onConnect:()=>{this._isConnected=!0,this.onConnect?.(),n.onConnect?.()},onDisconnect:e=>{this._isConnected=!1,this._isSynced&&(this._isSynced=!1,this.onSyncChange?.(!1)),this.onDisconnect?.(),n.onDisconnect?.(e)},onSynced:e=>{const t=this._isSynced;this._isSynced=!0,t||this.onSyncChange?.(!0),n.onSynced?.(e)}};try{this.provider=new Cs(c)}catch(l){this.provider=new Cs({...c,connect:!1}),this.onError?.(l instanceof Error?l:new Error(String(l)))}}connect(){try{this.provider.connect()}catch(e){this._isConnected=!1}}get awareness(){return this.provider.awareness}get document(){return this.provider.document}get isConnected(){return this._isConnected}get isSynced(){return this._isSynced}},indexeddb:class{_isConnected=!1;_isDestroyed=!1;_isSynced=!1;onConnect;onDisconnect;onError;onSyncChange;providerOptions;_provider=null;awareness;document;isLocalPersistence=!0;type="indexeddb";constructor({awareness:e,doc:t,options:n,onConnect:r,onDisconnect:i,onError:s,onSyncChange:o}){this.document=t??new nt,this.awareness=e??new Zi(this.document),this.providerOptions=n,this.onConnect=r,this.onDisconnect=i,this.onError=s,this.onSyncChange=o}connect=()=>{if(!this._isDestroyed){if(!this._provider)try{const e=new Ns(this.providerOptions.docName,this.document);this._provider=e,e._db.then(()=>{this._provider!==e||this._isDestroyed||this.setConnected(!0)}).catch(t=>{this._provider!==e||this._isDestroyed||(this._provider=null,this.destroyProvider(e,!1),this.handleError(t),this.setSynced(!1),this.setConnected(!1))}),e.whenSynced.then(()=>{this._provider===e&&this._isConnected&&!this._isDestroyed&&this.setSynced(!0)}).catch(e=>{this.handleError(e)})}catch(e){return this.handleError(e),this.setConnected(!1),void this.setSynced(!1)}this._provider.synced&&(this.setConnected(!0),this.setSynced(!0))}};destroy=()=>{this._isDestroyed||(this._isDestroyed=!0,this.disconnect())};disconnect=()=>{const e=this._provider;(e||this._isConnected||this._isSynced)&&(this._provider=null,this.setSynced(!1),this.setConnected(!1),e&&this.destroyProvider(e))};get isConnected(){return this._isConnected}get isConnectionPending(){return!!this._provider&&!this._isConnected&&!this._isDestroyed}get isSyncPending(){return!!this._provider&&!this._isSynced&&!this._isDestroyed}get isSynced(){return this._isSynced}get provider(){return this._provider}destroyProvider(e,t=!0){try{e.destroy().catch(e=>{t&&this.handleError(e)})}catch(n){t&&this.handleError(n)}}handleError(e){this.onError?.(e instanceof Error?e:new Error(String(e)))}setConnected(e){this._isConnected!==e&&(this._isConnected=e,e?this.onConnect?.():this.onDisconnect?.())}setSynced(e){this._isSynced!==e&&(this._isSynced=e,this.onSyncChange?.(e))}},webrtc:class{_isConnected=!1;_isSynced=!1;doc;onSyncChange;provider=null;connect=()=>{if(this.provider)try{this.provider.connect()}catch(e){}};destroy=()=>{if(this.provider)try{this.provider.destroy()}catch(e){}};disconnect=()=>{if(this.provider)try{this.provider.disconnect();const e=this._isSynced;this._isConnected=!1,this._isSynced=!1,e&&this.onSyncChange?.(!1)}catch(e){}};type="webrtc";constructor({awareness:e,doc:t,options:n,onConnect:r,onDisconnect:i,onError:s,onSyncChange:o}){this.onSyncChange=o,this.doc=t||new nt;try{this.provider=new lo(n.roomName,this.doc,{awareness:e,filterBcConns:n.filterBcConns,maxConns:n.maxConns,password:n.password,peerOpts:n.peerOpts,signaling:n.signaling}),this.provider.on("status",e=>{const t=this._isConnected;this._isConnected=e.connected,e.connected?(t||r?.(),this._isSynced||(this._isSynced=!0,o?.(!0))):t&&(i?.(),this._isSynced&&(this._isSynced=!1,o?.(!1)))})}catch(a){s?.(a instanceof Error?a:new Error(String(a)))}}get awareness(){return this.provider.awareness}get document(){return this.doc}get isConnected(){return this._isConnected}get isSynced(){return this._isSynced}}},fo=({type:e,...t})=>{const n=(e=>uo[e])(e);if(!n)throw new Error(`Provider type "${e}" not found in registry`);return new n(t)},go=(e,t,n)=>function(e,t,{cursorStateField:n="selection",cursorDataField:r="data",autoSend:i=!0,data:s}={}){const o=e;o.awareness=t,o.cursorDataField=r,o.selectionStateField=n,o.sendCursorData=e=>{o.awareness.setLocalStateField(o.cursorDataField,e)},o.sendCursorPosition=e=>{const t=o.awareness.getLocalState(),r=null==t?void 0:t[n];if(!e)return void(r&&o.awareness.setLocalStateField(o.selectionStateField,null));const{anchor:i,focus:s}=ji(o.sharedRoot,o,e);r&&Vt(i,r)&&Vt(s,r)||o.awareness.setLocalStateField(o.selectionStateField,{anchor:i,focus:s})};const a=e=>{const t=Gi.get(o);if(!t)return;const n=o.awareness.clientID,r={added:e.added.filter(e=>e!==n),removed:e.removed.filter(e=>e!==n),updated:e.updated.filter(e=>e!==n)};(r.added.length>0||r.removed.length>0||r.updated.length>0)&&t.forEach(e=>e(r))},{connect:c,disconnect:l}=o;return o.connect=()=>{if(c(),o.awareness.on("change",a),a({removed:[],added:Array.from(o.awareness.getStates().keys()),updated:[]}),i){s&&Xi.sendCursorData(o,s);const{onChange:e}=o;o.onChange=()=>{e(),Ki.connected(o)&&Xi.sendCursorPosition(o)}}},o.disconnect=()=>{o.awareness.off("change",a),a({removed:Array.from(o.awareness.getStates().keys()),added:[],updated:[]}),l()},o}(e,t,n),po=e=>"object"==typeof e&&null!==e&&"type"in e&&"options"in e,mo=i.createTSlatePlugin({key:i.KEYS.yjs,extendEditor:({editor:e,getOptions:t})=>{let n=e;const{awareness:r,cursors:i,localOrigin:s,positionStorageOrigin:o,sharedType:a,ydoc:c}=t();if(n=((e,t,n)=>zi(e,t,n))(n,a??c.get("content",wr),{autoConnect:!1,localOrigin:s,positionStorageOrigin:o}),i)if(r){let e=!0;!1===i.autoSend&&(e=!1),n=go(n,r,{...i,autoSend:e})}else n.api.debug.error("Yjs plugin: Internal shared awareness (awareness) is missing but cursors are enabled.");return((e,t)=>Qi(e,t))(n)},options:{_isConnected:!1,_isSynced:!1,userId:null,_providers:[],awareness:null,cursors:{},localOrigin:null,positionStorageOrigin:null,providers:[],sharedType:null,ydoc:null,onConnect:()=>{},onDisconnect:()=>{},onError:()=>{},onSyncChange:()=>{}}}).extend(({getOptions:e})=>{const{localOrigin:t,positionStorageOrigin:n,...r}=e();let{awareness:i,ydoc:s}=r;return s||(s=new nt),i||(i=new Zi(s)),{options:{awareness:i,localOrigin:t??void 0,positionStorageOrigin:n??void 0,ydoc:s}}}).extendApi(e=>({connect:t=>{const{getOptions:n}=e,{_providers:r}=n(),i=t?Array.isArray(t)?t:[t]:null;r.forEach(e=>{if(!i||i.includes(e.type))try{e.connect()}catch(t){n().onError?.({error:t instanceof Error?t:new Error(String(t)),type:e.type})}})},destroy:()=>{const{editor:t,getOptions:n}=e,{_providers:r}=n();for(const e of[...r].reverse())try{(e.isConnected||e.isConnectionPending)&&e.destroy()}catch(i){}try{Ki.disconnect(t)}catch{}},disconnect:t=>{const{editor:n,getOptions:r}=e,{_providers:i}=r(),s=t?Array.isArray(t)?t:[t]:null;for(const e of[...i].reverse())try{!e.isConnected&&!e.isConnectionPending||null!==s&&!s.includes(e.type)||e.disconnect()}catch(o){}},init:async({id:t,autoConnect:n=!0,autoSelect:r,selection:i,value:s,onReady:o}={})=>{const{editor:a,getOptions:c,setOption:l}=e,{awareness:d,providers:h=[],sharedType:u,ydoc:f}=c(),g=()=>{return(e=u??f.get("content",wr)).length>0||null!=e._start;var e};if(0===h.length)throw new Error("No providers specified. Please provide provider configurations or instances in the `providers` array.");const p=[];let m=null;const y=new Promise(e=>{m=e});for(const e of h)if(po(e)){const{options:t,type:n}=e;let r=null;if(!t)continue;try{const e=fo({awareness:d,doc:f,options:t,type:n,onConnect:()=>{c().onConnect?.({type:n}),l("_isConnected",!0)},onDisconnect:()=>{c().onDisconnect?.({type:n});const{_providers:e}=c();e.some(e=>e.isConnected)||l("_isConnected",!1)},onError:e=>{c().onError?.({error:e,type:n})},onSyncChange:e=>{c().onSyncChange?.({isSynced:e,type:n}),l("_isSynced",e);const t=p.some(e=>!e.isLocalPersistence),i=!r?.isLocalPersistence||!t||g();e&&m&&i&&(m(),m=null)}});r=e,p.push(e)}catch{}}else p.push(e);if(l("_providers",p),n&&p.length>0){p.forEach(e=>{try{e.connect()}catch(t){c().onError?.({error:t instanceof Error?t:new Error(String(t)),type:e.type})}});const e=5e3;await Promise.race([y,new Promise(t=>{setTimeout(()=>{m=null,t()},e)})])}if(!g()&&!p.some(e=>e.isLocalPersistence&&(e.isConnectionPending||e.isSyncPending))&&null!==s){let e=s;if("string"==typeof s?e=a.api.html.deserialize({element:s}):"function"==typeof s?e=await s(a):s&&(e=s),e&&0!==e?.length||(e=a.api.create.value()),u){const t=bi(e);f.transact(()=>{u.applyDelta(t)})}else{const n=await ho(t??a.id,e);f.transact(()=>{gt(f,n)})}}Ki.connect(a),a.tf.init({autoSelect:r,selection:i,shouldNormalizeEditor:!1,value:null}),a.api.onChange(),o?.({editor:a,isAsync:!0,value:a.children})}})),yo=i.toPlatePlugin(mo),wo=Object.defineProperty,bo=Object.defineProperties,vo=Object.getOwnPropertyDescriptors,_o=Object.getOwnPropertySymbols,So=Object.prototype.hasOwnProperty,ko=Object.prototype.propertyIsEnumerable,Co=(e,t,n)=>t in e?wo(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Eo=(e,t)=>{for(var n in t||(t={}))So.call(t,n)&&Co(e,n,t[n]);if(_o)for(var n of _o(t))ko.call(t,n)&&Co(e,n,t[n]);return e},Ao=(e,t)=>bo(e,vo(t));function xo(e){return"[object Object]"===Object.prototype.toString.call(e)}function To(e){if(!xo(e))return!1;const t=e.constructor;if(void 0===t)return!0;const n=t.prototype;return!1!==xo(n)&&!1!==n.hasOwnProperty("isPrototypeOf")}function Ro(e,t){for(const n in e){const r=e[n],i=t[n];if(To(r)&&To(i)){if(!Ro(r,i))return!1}else if(Array.isArray(r)&&Array.isArray(i)){if(r.length!==i.length)return!1;for(let e=0;e<r.length;e++)if(r[e]!==i[e])return!1}else if(r!==i)return!1}for(const n in t)if(void 0===e[n]&&void 0!==t[n])return!1;return!0}function Do(e){return function(e){var t,n;const r=[];for(const i of e){if("string"==typeof i.insert&&0===i.insert.length)continue;const e=r[r.length-1];e&&"string"==typeof e.insert&&"string"==typeof i.insert&&(e.attributes===i.attributes||!e.attributes==!i.attributes&&Ro(null!=(t=e.attributes)?t:{},null!=(n=i.attributes)?n:{}))?e.insert+=i.insert:r.push(i)}return r}(e.toDelta())}function Oo({insert:e}){return"string"==typeof e?e.length:1}function Uo(e){return e.reduce((e,t)=>e+Oo(t),0)}function Po(e,t,n){if(n<1)return[];let r=0;const i=[],s=t+n;for(let o=0;o<e.length&&!(r>=s);o++){const n=e[o],a=Oo(n);if(r+a<=t){r+=a;continue}if("string"!=typeof n.insert){r+=a,i.push(n);continue}const c=Math.max(0,t-r),l=Math.min(a,a-(r+a-s));i.push(Ao(Eo({},n),{insert:n.insert.slice(c,l)})),r+=a}return i}function Lo(e){return function(e,...t){return Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e)))}(e,i.Text.isText(e)?"text":"children")}function Mo(e){var t=e,{children:n}=t,r=((e,t)=>{var n={};for(var r in e)So.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&_o)for(var r of _o(e))t.indexOf(r)<0&&ko.call(e,r)&&(n[r]=e[r]);return n})(t,["children"]);const s=new a.YXmlText;return Object.entries(r).forEach(([e,t])=>{s.setAttribute(e,t)}),s.applyDelta(n.map(e=>i.Text.isText(e)?{insert:e.text,attributes:Lo(e)}:{insert:Mo(e)}),{sanitize:!1}),s}function Io(e){return e?i.Text.isText(e)?e.text.length:1:0}function No(e,t,n){var r;if(0===n.length)throw new Error("Path has to a have a length >= 1");if(i.Text.isText(t))throw new Error("Cannot descent into slate text");const[s,...o]=n,c=function(e,t){return e.children.slice(0,t).reduce((e,t)=>e+Io(t),0)}(t,s),l=t.children[s],d=Do(e),h=Io(l),u=Po(d,c,h);if(u.length>1)throw new Error("Path doesn't match yText, yTarget spans multiple nodes");const f=null==(r=u[0])?void 0:r.insert;if(o.length>0){if(!(f instanceof a.YXmlText))throw new Error("Path doesn't match yText, cannot descent into non-yText");return No(f,l,o)}return{yParent:e,textRange:{start:c,end:c+h},yTarget:f instanceof a.YXmlText?f:void 0,slateParent:t,slateTarget:l,targetDelta:u}}function jo(e,t,n={}){const{assoc:r=0,insert:s=!1}=n;let o=0,a=0;for(let l=0;l<e.children.length;l++){const n=e.children[l],s=i.Text.isText(n)?n.text.length:1;s>0&&(a=l);const c=o+s;if(s>0&&(r>=0?c>t:c>=t))return[l,t-o];o+=s}if(t>o+(s?1:0))throw new Error("yOffset out of bounds");if(s)return[e.children.length,0];const c=e.children[a];return[a,i.Text.isText(c)?c.text.length:1]}function Vo(e){return e.map(e=>"string"==typeof e.insert?e:Ao(Eo({},e),{insert:Fo(e.insert)}))}function Fo(e){const t=new a.YXmlText,n=e.getAttributes();return Object.entries(n).forEach(([e,n])=>{t.setAttribute(e,n)}),t.applyDelta(Vo(Do(e)),{sanitize:!1}),t}function Bo(e){if(!e.doc)throw new Error("shared type isn't attached to a document")}var Ho="__slateYjsStoredPosition_";function Wo(e,t,{type:n,index:r,assoc:s}){if(!(n instanceof a.YXmlText))throw new Error("Absolute position points to a non-XMLText");const o=function(e,t,n){const r=[n];for(;r[0]!==e;){const{parent:e}=r[0];if(!e)throw new Error("yText isn't a descendant of root element");if(!(e instanceof a.YXmlText))throw new Error("Unexpected y parent type");r.unshift(e)}if(r.length<2)return[];let s=t;return r.reduce((e,t,n)=>{const o=r[n+1];if(!o)return e;let a=0;const c=Do(t);for(const r of c){if(r.insert===o)break;a+="string"==typeof r.insert?r.insert.length:1}if(i.Text.isText(s))throw new Error("Cannot descent into slate text");const[l]=jo(s,a);return s=s.children[l],e.concat(l)},[])}(e,t,n),c=i.Node.get(t,o);if(i.Text.isText(c))throw new Error("Absolute position doesn't match slateRoot, cannot descent into text");const[l,d]=jo(c,r,{assoc:s}),h=c.children[l];return i.Text.isText(h)?{path:[...o,l],offset:d}:null}function Yo(e,t,n){if(!e.doc)throw new Error("sharedRoot isn't attach to a yDoc");const r=a.createAbsolutePositionFromRelativePosition(n,e.doc);return r&&Wo(e,t,r)}function qo(e,t,n){e.setAttribute(Ho+t,a.encodeRelativePosition(n))}function Ko(e,t,n){return Object.fromEntries(Object.entries(e).filter(([,e])=>e.type===t&&(!n||(e.assoc>=0?e.index>=n.start&&e.index<n.end:e.index>n.start&&e.index>=n.end))))}function zo(e,t,n=""){const r={[n]:Ko(e,t)};return Do(t).forEach(({insert:t},i)=>{t instanceof a.YXmlText&&Object.assign(r,zo(e,t,n?`${n}.${i}`:i.toString()))}),r}function $o(e,t,n,r=0){const i=function(e){return Bo(e),Object.fromEntries(Object.entries(e.getAttributes()).filter(([e])=>e.startsWith(Ho)).map(([t,n])=>[t.slice(25),a.createAbsolutePositionFromRelativePosition(a.decodeRelativePosition(n),e.doc)]).filter(([,e])=>e))}(e),s={"":Ko(i,t,{start:r,end:r+Uo(n)})};return n.forEach(({insert:e},t)=>{e instanceof a.YXmlText&&Object.assign(s,zo(i,e,t.toString()))}),s}function Jo(e,t,n,r,i=0,s=0,o=""){const c=n[o];c&&Object.entries(c).forEach(([n,r])=>{qo(e,n,a.createRelativePositionFromTypeIndex(t,r.index-s+i,r.assoc))}),r.forEach(({insert:t},r)=>{t instanceof a.YXmlText&&Jo(e,t,n,Do(t),0,0,o?`${o}.${r}`:r.toString())})}var Qo={insert_node:function(e,t,n){const{yParent:r,textRange:s}=No(e,t,n.path);if(i.Text.isText(n.node))return r.insert(s.start,n.node.text,Lo(n.node));r.insertEmbed(s.start,Mo(n.node))},remove_node:function(e,t,n){const{yParent:r,textRange:i}=No(e,t,n.path);r.delete(i.start,i.end-i.start)},set_node:function(e,t,n){const{yTarget:r,textRange:i,yParent:s}=No(e,t,n.path);if(r)return Object.entries(n.newProperties).forEach(([e,t])=>{if(null===t)return r.removeAttribute(e);r.setAttribute(e,t)}),Object.entries(n.properties).forEach(([e])=>{n.newProperties.hasOwnProperty(e)||r.removeAttribute(e)});const o=Eo(Eo({},Object.fromEntries(Object.keys(n.properties).map(e=>[e,null]))),n.newProperties);s.format(i.start,i.end-i.start,o)},merge_node:function(e,t,n){const r=No(e,t,n.path),s=No(r.yParent,r.slateParent,i.Path.previous(n.path.slice(-1)));if(!r.yTarget!=!s.yTarget)throw new Error("Cannot merge y text with y element");if(!s.yTarget||!r.yTarget){const{yParent:e,textRange:s,slateTarget:o}=r;if(!o)throw new Error("Expected Slate target node for merge op.");const a=i.Node.get(t,i.Path.previous(n.path));if(!i.Text.isText(a))throw new Error("Path points to Y.Text but not a Slate text node.");const c=Lo(o),l=Lo(a),d=Object.keys(c).reduce((e,t)=>t in l?e:Ao(Eo({},e),{[t]:null}),{});return e.format(s.start,s.end-s.start,Eo(Eo({},d),l))}const o=s.yTarget.length,a=Do(r.yTarget),c=Vo(a),l=$o(e,r.yTarget,a,o),d=[{retain:o},...c];s.yTarget.applyDelta(d,{sanitize:!1}),r.yParent.delete(r.textRange.start,r.textRange.end-r.textRange.start),Jo(e,s.yTarget,l,c,o)},move_node:function(e,t,n){const r=i.Path.parent(n.newPath),s=n.newPath[n.newPath.length-1],o=i.Node.get(t,r);if(i.Text.isText(o))throw new Error("Cannot move slate node into text element");const a=[...r,Math.min(s,o.children.length)],c=No(e,t,n.path),l=No(e,t,a),d=Vo(c.targetDelta),h=$o(e,c.yParent,c.targetDelta);c.yParent.delete(c.textRange.start,c.textRange.end-c.textRange.start);const u=Uo(Do(l.yParent)),f=Math.min(l.textRange.start,u),g=[{retain:f},...d];l.yParent.applyDelta(g,{sanitize:!1}),Jo(e,l.yParent,h,d,f,c.textRange.start)},split_node:function(e,t,n){const r=No(e,t,n.path);if(!r.slateTarget)throw new Error("Y target without corresponding slate node");if(!r.yTarget){if(!i.Text.isText(r.slateTarget))throw new Error("Mismatch node type between y target and slate node");const e={};return r.targetDelta.forEach(t=>{t.attributes&&Object.keys(t.attributes).forEach(t=>{e[t]=null})}),r.yParent.format(r.textRange.start,r.textRange.end-r.textRange.start,Eo(Eo({},e),n.properties))}if(i.Text.isText(r.slateTarget))throw new Error("Mismatch node type between y target and slate node");const s=No(r.yTarget,r.slateTarget,[n.position]),o=r.slateTarget.children.slice(0,n.position).reduce((e,t)=>e+Io(t),0),c=r.slateTarget.children.reduce((e,t)=>e+Io(t),0),l=Po(Do(r.yTarget),o,c-o),d=Vo(l),h=$o(e,r.yTarget,l,o),u=new a.YXmlText;u.applyDelta(d,{sanitize:!1}),Object.entries(n.properties).forEach(([e,t])=>{u.setAttribute(e,t)}),r.yTarget.delete(s.textRange.start,r.yTarget.length-s.textRange.start),r.yParent.insertEmbed(r.textRange.end,u),Jo(e,u,h,d,0,o)}};Ao(Eo(Eo({},{insert_text:function(e,t,n){const{yParent:r,textRange:s}=No(e,t,n.path),o=i.Node.get(t,n.path);if(!i.Text.isText(o))throw new Error("Cannot insert text into non-text node");r.insert(s.start+n.offset,n.text,Lo(o))},remove_text:function(e,t,n){const{yParent:r,textRange:i}=No(e,t,n.path);r.delete(i.start+n.offset,n.text.length)}}),Qo),{set_selection:()=>{}});var Go=new WeakMap,Xo=new WeakMap,Zo=new WeakSet,ea={isYjsEditor:e=>i.Editor$1.isEditor(e)&&e.sharedRoot instanceof a.YXmlText&&"localOrigin"in e&&"positionStorageOrigin"in e&&"function"==typeof e.applyRemoteEvents&&"function"==typeof e.storeLocalChange&&"function"==typeof e.flushLocalChanges&&"function"==typeof e.isLocalOrigin&&"function"==typeof e.connect&&"function"==typeof e.disconnect,localChanges(e){var t;return null!=(t=Xo.get(e))?t:[]},applyRemoteEvents(e,t,n){e.applyRemoteEvents(t,n)},storeLocalChange(e,t){e.storeLocalChange(t)},flushLocalChanges(e){e.flushLocalChanges()},connected:e=>Zo.has(e),connect(e){e.connect()},disconnect(e){e.disconnect()},isLocal:e=>e.isLocalOrigin(ea.origin(e)),origin(e){const t=Go.get(e);return void 0!==t?t:e.localOrigin},withOrigin(e,t,n){const r=ea.origin(e);Go.set(e,t),n(),Go.set(e,r)},storePosition(e,t,n){const{sharedRoot:r,positionStorageOrigin:i}=e;Bo(r);const s=function(e,t,n){const{yTarget:r,yParent:i,textRange:s}=No(e,t,n.path);if(r)throw new Error("Slate point points to a non-text element inside sharedRoot");const o=s.start+n.offset;return a.createRelativePositionFromTypeIndex(i,o,o===s.end?-1:0)}(r,e,n);r.doc.transact(()=>{qo(r,t,s)},i)},removeStoredPosition(e,t){const{sharedRoot:n,positionStorageOrigin:r}=e;Bo(n),n.doc.transact(()=>{!function(e,t){e.removeAttribute(Ho+t)}(n,t)},r)},position(e,t){const n=function(e,t){const n=e.getAttribute(Ho+t);return n?a.decodeRelativePosition(n):null}(e.sharedRoot,t);if(n)return Yo(e.sharedRoot,e,n)},storedPositionsRelative(e){return t=e.sharedRoot,Object.fromEntries(Object.entries(t.getAttributes()).filter(([e])=>e.startsWith(Ho)).map(([e,t])=>[e.slice(25),a.createRelativePositionFromJSON(t)]));var t}},ta=new WeakMap,na={isCursorEditor:e=>ea.isYjsEditor(e)&&e.awareness&&"string"==typeof e.cursorDataField&&"string"==typeof e.selectionStateField&&"function"==typeof e.sendCursorPosition&&"function"==typeof e.sendCursorData,sendCursorPosition(e,t=e.selection){e.sendCursorPosition(t)},sendCursorData(e,t){e.sendCursorData(t)},on(e,t,n){var r;if("change"!==t)return;const i=null!=(r=ta.get(e))?r:new Set;i.add(n),ta.set(e,i)},off(e,t,n){if("change"!==t)return;const r=ta.get(e);r&&r.delete(n)},cursorState(e,t){var n;if(t===e.awareness.clientID||!ea.connected(e))return null;const r=e.awareness.getStates().get(t);return r?{relativeSelection:null!=(n=r[e.selectionStateField])?n:null,data:r[e.cursorDataField],clientId:t}:null},cursorStates:e=>ea.connected(e)?Object.fromEntries(Array.from(e.awareness.getStates().entries(),([t,n])=>t!==e.awareness.clientID&&n?[t,{relativeSelection:n[e.selectionStateField],data:n[e.cursorDataField]}]:null).filter(Array.isArray)):{}},ra=Object.defineProperty,ia=Object.defineProperties,sa=Object.getOwnPropertyDescriptors,oa=Object.getOwnPropertySymbols,aa=Object.prototype.hasOwnProperty,ca=Object.prototype.propertyIsEnumerable,la=(e,t,n)=>t in e?ra(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,da=(e,t)=>{for(var n in t||(t={}))aa.call(t,n)&&la(e,n,t[n]);if(oa)for(var n of oa(t))ca.call(t,n)&&la(e,n,t[n]);return e},ha=new WeakMap;function ua(e,t){if(!t.relativeSelection)return null;let n=ha.get(e.children);n||(n=new WeakMap,ha.set(e.children,n));let r=n.get(t);if(void 0===r)try{r=function(e,t,n){const r=Yo(e,t,n.anchor);if(!r)return null;const i=Yo(e,t,n.focus);return i?{anchor:r,focus:i}:null}(e.sharedRoot,e,t.relativeSelection),n.set(t,r)}catch(i){return null}return r}function fa(){const e=i.useSlateStatic();if(!na.isCursorEditor(e))throw new Error("Cannot use useSyncExternalStore outside the context of a RemoteCursorEditor");return e}var ga=new WeakMap;function pa(e){const t=ga.get(e);if(t)return t;const n=function(e){let t={};const n=new Set,r=n.add.bind(n),i=new Set;let s=null;return[t=>(i.add(t),s||(s=e=>{e.added.forEach(r),e.removed.forEach(r),e.updated.forEach(r),i.forEach(e=>e())},na.on(e,"change",s)),()=>{i.delete(t),s&&0===i.size&&(na.off(e,"change",s),s=null)}),()=>(0===n.size||(n.forEach(n=>{const r=na.cursorState(e,n);null!==r?t[n]=r:delete t[n.toString()]}),n.clear(),t=da({},t)),t)]}(e);return ga.set(e,n),n}function ma(){const[e,t]=pa(fa());return(0,g.useSyncExternalStore)(e,t)}function ya(e,t,{yOffset:n,xOffset:r,shouldGenerateOverlay:s}){const[o,a]=i.Range.edges(t),c=function(e,t){try{return i.ReactEditor.toDOMRange(e,t)}catch(n){return null}}(e,t);if(!c)return{caretPosition:null,selectionRects:[]};const l=[],d=i.Editor$1.nodes(e,{at:t,match:(e,t)=>i.Text.isText(e)&&(!s||s(e,t))});let h=null;const u=i.Range.isBackward(t);for(const[f,g]of d){const s=i.ReactEditor.toDOMNode(e,f),d=i.Path.equals(g,o.path),p=i.Path.equals(g,a.path);let m=null;if(d||p){const e=document.createRange();e.selectNode(s),d&&e.setStart(c.startContainer,c.startOffset),p&&e.setEnd(c.endContainer,c.endOffset),m=e.getClientRects()}else m=s.getClientRects();const y=u?d:p;for(let e=0;e<m.length;e++){const s=m.item(e);if(!s)continue;const o=y&&(u?0===e:e===m.length-1),a=s.top-n,c=s.left-r;o&&(h={height:s.height,top:a,left:c+(u||i.Range.isCollapsed(t)?0:s.width)}),l.push({width:s.width,height:s.height,top:a,left:c})}}return{selectionRects:l,caretPosition:h}}var wa=Object.freeze([]);function ba(e={}){var t,n=e,{containerRef:r,shouldGenerateOverlay:i}=n,s=((e,t)=>{var n={};for(var r in e)aa.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&oa)for(var r of oa(e))t.indexOf(r)<0&&ca.call(e,r)&&(n[r]=e[r]);return n})(n,["containerRef","shouldGenerateOverlay"]);const o=fa(),a=ma(),c=function(){const[,e]=(0,l.useReducer)(e=>e+1,0),t=(0,l.useRef)(null),n=()=>{t.current&&(cancelAnimationFrame(t.current),t.current=0)};return(0,l.useEffect)(n),(0,l.useEffect)(()=>n,[]),(0,l.useCallback)((n=!1)=>{n?e():t.current||(t.current=requestAnimationFrame(e))},[])}(),d=(0,l.useRef)(new WeakMap),[h,u]=(0,l.useState)({}),f=!("refreshOnResize"in s)||(null==(t=s.refreshOnResize)||t);return function(e,t){const n=(0,l.useRef)(t);n.current=t;const[r]=(0,l.useState)(()=>new ResizeObserver(()=>{n.current()}));(0,l.useEffect)(()=>{if(!(null==e?void 0:e.current))return;const{current:t}=e;return r.observe(t),()=>r.unobserve(t)},[r,e])}(f?r:void 0,()=>{d.current=new WeakMap,c("debounced"!==f)}),(0,l.useLayoutEffect)(()=>{var e,t,n;if(r&&!r.current)return;const s=null==(e=null==r?void 0:r.current)?void 0:e.getBoundingClientRect(),c=null!=(t=null==s?void 0:s.x)?t:0,l=null!=(n=null==s?void 0:s.y)?n:0;let f=Object.keys(h).length!==Object.keys(a).length;const g=Object.fromEntries(Object.entries(a).map(([e,t])=>{const n=t.relativeSelection&&ua(o,t);if(!n)return[e,wa];const r=d.current.get(n);if(r)return[e,r];const s=ya(o,n,{xOffset:c,yOffset:l,shouldGenerateOverlay:i});return f=!0,d.current.set(n,s),[e,s]}));f&&u(g)}),[(0,l.useMemo)(()=>Object.entries(a).map(([e,t])=>{var n,r;const i=t.relativeSelection&&ua(o,t),s=h[e];return a=da({},t),c={range:i,caretPosition:null!=(n=null==s?void 0:s.caretPosition)?n:null,selectionRects:null!=(r=null==s?void 0:s.selectionRects)?r:wa},ia(a,sa(c));var a,c}),[a,o,h]),(0,l.useCallback)(()=>{d.current=new WeakMap,c(!0)},[c])]}function va(){return i.usePluginOption(yo,"_isSynced")?(0,u.jsx)(_a,{}):null}function _a(){const e=i.useEditorContainerRef(),[t]=ba({containerRef:e});return(0,u.jsx)(u.Fragment,{children:t.map(e=>(0,u.jsx)(Sa,{...e},e.clientId))})}function Sa({caretPosition:e,data:t,selectionRects:n}){if(!t)return null;const r={backgroundColor:(i=t.color,s=.5,i+Math.round(255*Math.min(Math.max(s,0),1)).toString(16).padStart(2,"0").toUpperCase())};var i,s;return(0,u.jsxs)(u.Fragment,{children:[n.map((e,t)=>(0,u.jsx)("div",{className:"pointer-events-none absolute",style:{...r,...e}},t)),e&&(0,u.jsx)(Ea,{data:t,caretPosition:e})]})}var ka=.7,Ca=1;function Ea({caretPosition:e,data:t}){const[n,r]=l.useState(!1),i={...e,background:t?.color,opacity:ka,transition:"opacity 0.2s"},s={...i,opacity:Ca},o={background:t?.color,opacity:ka,transform:"translateY(-100%)",transition:"opacity 0.2s"},a={...o,opacity:Ca};return(0,u.jsx)("div",{className:"absolute w-0.5",style:n?s:i,children:(0,u.jsx)("div",{className:"absolute top-0 whitespace-nowrap rounded rounded-bl-none px-1.5 py-0.5 text-white text-xs",style:n?a:o,onMouseEnter:()=>{r(!0)},onMouseLeave:()=>{r(!1)},children:t?.name})})}function Aa({documentId:e,initialValue:t=i.EMPTY_PLATE_VALUE,user:n,authToken:r,className:s,renderToolbar:o,overlays:a}){const c=ge("plate",e),d=n.color??be(n.id),h=Boolean(r),f=i.usePlateEditor({plugins:h?[...i.platePlugins,yo.configure({options:{cursors:{data:{color:d,name:n.name}},providers:ye({documentId:e,token:r})},render:{afterEditable:va}})]:i.platePlugins,skipInitialization:h,value:h?void 0:t},[c,h]);l.useEffect(()=>{if(h)return f.getApi(yo).yjs.init({id:c,value:t}),()=>{f.getApi(yo).yjs.destroy()}},[h,f,c]);const[,g]=l.useReducer(e=>e+1,0),p=l.useMemo(()=>f?He(f):b("plate"),[f]);return l.useEffect(()=>{g()},[f]),(0,u.jsx)("div",{className:`flex h-full min-h-0 w-full flex-col ${s??""}`,"data-room":c,children:(0,u.jsxs)(i.Plate,{editor:f,children:[o?o(p):(0,u.jsx)(x,{adapter:p}),(0,u.jsxs)(i.EditorContainer,{className:"relative min-h-0 flex-1",children:[(0,u.jsx)(i.Editor,{placeholder:"Start writing…",variant:"default"}),a]})]})})}exports.AIMenu=i.AIMenu,exports.AIToolbarButton=i.AIToolbarButton,exports.AiKit=i.AiKit,exports.AiPlugin=i.AiPlugin,exports.DEFAULT_PLATE_AI_OPTIONS=i.DEFAULT_PLATE_AI_OPTIONS,exports.EMPTY_PLATE_VALUE=i.EMPTY_PLATE_VALUE,exports.FixedToolbar=i.FixedToolbar,exports.FixedToolbarButtons=i.FixedToolbarButtons,exports.FloatingToolbar=i.FloatingToolbar,exports.FloatingToolbarButtons=i.FloatingToolbarButtons,exports.MediaKit=i.MediaKit,exports.REASON_TOOLBAR=v,exports.REASON_TOOLBAR_SKIN=i.REASON_TOOLBAR_SKIN,exports.ROOM_PREFIX=fe,exports.ReasonPlateEditor=Aa,exports.ReasonPlaygroundEditor=function(e){return(0,u.jsx)(Aa,{...e,overlays:(0,u.jsx)(i.FloatingToolbar,{children:(0,u.jsx)(i.FloatingToolbarButtons,{})}),renderToolbar:()=>(0,u.jsx)(i.FixedToolbar,{className:i.REASON_TOOLBAR_SKIN,children:(0,u.jsx)(i.FixedToolbarButtons,{})})})},exports.ReasonSidebar=function({activeDocumentId:e,linkForDocument:n,onNavigate:r,className:i}){const[s,o]=l.useState([]),[a,c]=l.useState(null),[d,h]=l.useState(""),g=l.useCallback(()=>{o(P())},[]);l.useEffect(()=>(g(),N(g)),[g]);const p=()=>{a&&M(a,d),c(null)};return(0,u.jsxs)("nav",{"aria-label":"Documents",className:t.cn("flex w-56 shrink-0 flex-col gap-0.5 overflow-y-auto border-r border-gray-200 bg-gray-50 p-2 dark:border-slate-700 dark:bg-slate-900",i),"data-testid":"reason-sidebar",children:[(0,u.jsxs)("div",{className:"flex items-center justify-between px-1 pb-2",children:[(0,u.jsx)("span",{className:"text-[11px] font-semibold uppercase tracking-wide text-gray-400",children:"Documents"}),(0,u.jsx)("button",{"aria-label":"New document",className:"rounded p-1 text-gray-500 hover:bg-gray-200 dark:text-gray-400 dark:hover:bg-slate-800",onClick:()=>{r(L().id)},type:"button",children:(0,u.jsx)(f.Plus,{className:"size-3.5"})})]}),s.map(i=>{const o=i.id===e,l=a===i.id;return(0,u.jsxs)("div",{className:t.cn("group flex items-center gap-1.5 rounded px-1.5 py-1 text-sm",o?"bg-gray-200 text-gray-900 dark:bg-slate-700 dark:text-white":"text-gray-600 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-slate-800"),"data-document-id":i.id,children:[(0,u.jsx)(f.FileText,{className:"size-3.5 shrink-0 opacity-60"}),l?(0,u.jsx)("input",{autoFocus:!0,className:"min-w-0 flex-1 rounded border border-gray-300 bg-white px-1 py-0.5 text-sm dark:border-slate-600 dark:bg-slate-800",onBlur:p,onChange:e=>h(e.target.value),onKeyDown:e=>{"Enter"===e.key&&p(),"Escape"===e.key&&c(null)},value:d}):(0,u.jsx)("a",{className:"min-w-0 flex-1 truncate",href:n(i.id),children:i.title}),!l&&(0,u.jsxs)("div",{className:"hidden shrink-0 items-center gap-0.5 group-hover:flex",children:[(0,u.jsx)("button",{"aria-label":`Rename ${i.title}`,className:"rounded p-0.5 text-gray-400 hover:bg-gray-200 dark:hover:bg-slate-700",onClick:()=>(e=>{c(e.id),h(e.title)})(i),type:"button",children:(0,u.jsx)(f.Pencil,{className:"size-3"})}),(0,u.jsx)("button",{"aria-label":`Delete ${i.title}`,className:"rounded p-0.5 text-gray-400 hover:bg-gray-200 dark:hover:bg-slate-700",onClick:()=>(t=>{if("undefined"!=typeof window&&!window.confirm(`Delete "${t.title}"?`))return;if(I(t.id),t.id!==e)return;const n=s.find(e=>e.id!==t.id);r(n?n.id:L().id)})(i),type:"button",children:(0,u.jsx)(f.Trash2,{className:"size-3"})})]})]},i.id)}),0===s.length&&(0,u.jsx)("p",{className:"px-1.5 py-2 text-xs text-gray-400",children:"No documents yet."})]})},exports.ReasonTiptapEditor=function({documentId:e,initialContent:t="",user:n,authToken:i,className:s}){const[o,c]=l.useState(null),[d,h]=l.useState(null),f=ge("tiptap",e),g=n.color??be(n.id);l.useEffect(()=>{if(!i)return;const t=me({engine:"tiptap",documentId:e,token:i});return h(t),()=>{h(null),t.destroy()}},[i,e]);const p=l.useMemo(()=>{const e=r.buildExtensions(r.createDefaultConfig());return d?function(e,t,n){return[...e.filter(e=>"undoRedo"!==e?.name),a.Collaboration.configure({document:t.ydoc}),De.configure({provider:t.provider,user:n})]}(e,d,{name:n.name,color:g}):e},[d,n.name,g]),m=l.useMemo(()=>o?Ee(o):b("tiptap"),[o]);return(0,u.jsx)("div",{className:`flex h-full min-h-0 w-full flex-col ${s??""}`,"data-room":f,children:(0,u.jsx)(r.NovelEditor,{className:"flex min-h-0 flex-1 flex-col",extensions:p,immediatelyRender:!1,initialContent:d?void 0:t,onEditor:c,rebuildKey:d?`collab:${f}`:"local",textDirection:"auto",children:({EditorSurface:e})=>(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)(x,{adapter:m}),(0,u.jsx)("div",{className:"relative min-h-0 flex-1 overflow-auto",children:(0,u.jsx)(e,{className:"h-full"})})]})})})},exports.ReasonToolbar=x,exports.SIDEBAR_DOCUMENTS_STORAGE_KEY=T,exports.collaborationRoom=ge,exports.collectToolbarCommands=function e(t=v){const n=[];for(const r of t)"button"===r.kind&&n.push(r.id),"menu"===r.kind&&n.push(...e(r.children));return n},exports.createAiKit=i.createAiKit,exports.createCollaborationSession=me,exports.createNullAdapter=b,exports.createPlateAdapter=He,exports.createSidebarDocument=L,exports.createTiptapAdapter=Ee,exports.cursorColorFor=be,exports.deleteSidebarDocument=I,exports.getPlateAiController=i.getPlateAiController,exports.hocuspocusUrl=pe,exports.htmlToPlateValue=i.htmlToPlateValue,exports.listSidebarDocuments=P,exports.parseCollaborationRoom=function(e){const[t,n,...r]=e.split(":"),i=r.join(":");return"reason-editor"!==t||"tiptap"!==n&&"plate"!==n?null:i?{engine:n,documentId:i}:null},exports.plateBasePlugins=i.plateBasePlugins,exports.platePlugins=i.platePlugins,exports.plateValueToHtml=i.plateValueToHtml,exports.plateYjsProviders=ye,exports.renameSidebarDocument=M,exports.subscribeSidebarDocuments=N;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./rolldown-runtime-BeavJI0R.cjs"),t=require("./dist-2-kjLBhJ.cjs"),n=require("./tooltip-DSRLxJD_.cjs"),r=require("./editorConfig-Nlnbb5zI.cjs"),i=require("./reason-toolbar-skin-CBgQqHPn.cjs"),s=require("./dropdown-menu-By9VjdjW.cjs"),o=require("./Transcribe.cjs"),a=require("./dist-CN633rTi.cjs");let c=require("react"),l=e.__toESM(c,1);c=e.__toESM(c);let d=require("@tiptap/core"),h=require("@tiptap/pm/state"),u=require("react/jsx-runtime"),f=require("lucide-react"),g=require("use-sync-external-store/shim");require("use-sync-external-store/shim/with-selector");let p=require("use-voice-control/client");var m=class extends a.Observable{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const e=a.getUnixTime();null!==this.getLocalState()&&15e3<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&3e4<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&y(this,t,"timeout")},a.floor(3e3)),e.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){const t=this.clientID,n=this.meta.get(t),r=void 0===n?0:n.clock+1,i=this.states.get(t);null===e?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:r,lastUpdated:a.getUnixTime()});const s=[],o=[],c=[],l=[];null===e?l.push(t):null==i?null!=e&&s.push(t):(o.push(t),a.equalityDeep(i,e)||c.push(t)),(s.length>0||c.length>0||l.length>0)&&this.emit("change",[{added:s,updated:c,removed:l},"local"]),this.emit("update",[{added:s,updated:o,removed:l},"local"])}setLocalStateField(e,t){const n=this.getLocalState();null!==n&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}},y=(e,t,n)=>{const r=[];for(let i=0;i<t.length;i++){const n=t[i];if(e.states.has(n)){if(e.states.delete(n),n===e.clientID){const t=e.meta.get(n);e.meta.set(n,{clock:t.clock+1,lastUpdated:a.getUnixTime()})}r.push(n)}}r.length>0&&(e.emit("change",[{added:[],updated:[],removed:r},n]),e.emit("update",[{added:[],updated:[],removed:r},n]))},w=(e,t,n=e.states)=>{const r=t.length,i=a.createEncoder();a.writeVarUint(i,r);for(let s=0;s<r;s++){const r=t[s],o=n.get(r)||null,c=e.meta.get(r).clock;a.writeVarUint(i,r),a.writeVarUint(i,c),a.writeVarString(i,JSON.stringify(o))}return a.toUint8Array(i)};function b(e){return{engine:e,execute(){},isActive:()=>!1,isEnabled:()=>!1,getValue(){},subscribe:()=>()=>{}}}var v=[{kind:"button",id:"undo",label:"Undo",icon:f.Undo2,shortcut:"⌘Z"},{kind:"button",id:"redo",label:"Redo",icon:f.Redo2,shortcut:"⇧⌘Z"},{kind:"separator",id:"history-divider"},{kind:"button",id:"bold",label:"Bold",icon:f.Bold,shortcut:"⌘B"},{kind:"button",id:"italic",label:"Italic",icon:f.Italic,shortcut:"⌘I"},{kind:"button",id:"underline",label:"Underline",icon:f.Underline,shortcut:"⌘U"},{kind:"button",id:"highlight",label:"Highlight",icon:f.Highlighter,shortcut:"⌘⇧H"},{kind:"separator",id:"marks-divider"},{kind:"menu",id:"block-format",label:"Block Format",icon:f.Rows3,children:[{kind:"button",id:"paragraph",label:"Paragraph",icon:f.Pilcrow},{kind:"button",id:"heading-1",label:"Heading 1",icon:f.Heading1,shortcut:"Ctrl+Alt+1"},{kind:"button",id:"heading-2",label:"Heading 2",icon:f.Heading2,shortcut:"Ctrl+Alt+2"},{kind:"button",id:"heading-3",label:"Heading 3",icon:f.Heading3,shortcut:"Ctrl+Alt+3"},{kind:"button",id:"heading-4",label:"Heading 4",icon:f.Heading4,shortcut:"Ctrl+Alt+4"},{kind:"button",id:"heading-5",label:"Heading 5",icon:f.Heading5,shortcut:"Ctrl+Alt+5"},{kind:"button",id:"heading-6",label:"Heading 6",icon:f.Heading6,shortcut:"Ctrl+Alt+6"},{kind:"separator",id:"block-format-lists-divider"},{kind:"button",id:"bullet-list",label:"Bullet List",icon:f.List,shortcut:"Ctrl+Shift+8"},{kind:"button",id:"ordered-list",label:"Ordered List",icon:f.ListOrdered,shortcut:"Ctrl+Shift+7"},{kind:"button",id:"task-list",label:"Check List",icon:f.ListChecks,shortcut:"Ctrl+Shift+9"},{kind:"separator",id:"block-format-quote-divider"},{kind:"button",id:"blockquote",label:"Blockquote",icon:f.Quote,shortcut:"Ctrl+Shift+B"},{kind:"button",id:"code-block",label:"Code Block",icon:f.Code2,shortcut:"Ctrl+Alt+C"},{kind:"separator",id:"block-format-clear-divider"},{kind:"button",id:"clear-formatting",label:"Clear Format",icon:f.Eraser}]},{kind:"menu",id:"text-styles",label:"Text Styles",icon:f.Type,children:[{kind:"group-label",id:"text-styles-label",label:"Text Styles"},{kind:"button",id:"strike",label:"Strikethrough",icon:f.Strikethrough,shortcut:"Ctrl+Shift+S"},{kind:"button",id:"code",label:"Inline Code",icon:f.Code,shortcut:"Ctrl+E"},{kind:"button",id:"text-color",label:"Text Color",icon:f.Baseline,shortcut:"Alt+Shift+C"},{kind:"button",id:"superscript",label:"Superscript",icon:f.Superscript,shortcut:"Ctrl+."},{kind:"button",id:"subscript",label:"Subscript",icon:f.Subscript,shortcut:"Ctrl+,"},{kind:"separator",id:"text-styles-indent-divider"},{kind:"button",id:"indent",label:"Indent",icon:f.IndentIncrease},{kind:"button",id:"outdent",label:"Outdent",icon:f.IndentDecrease},{kind:"menu",id:"alignment",label:"Alignment",icon:f.AlignLeft,children:[{kind:"button",id:"align-left",label:"Align Left",icon:f.AlignLeft},{kind:"button",id:"align-center",label:"Align Center",icon:f.AlignCenter},{kind:"button",id:"align-right",label:"Align Right",icon:f.AlignRight},{kind:"button",id:"align-justify",label:"Justify",icon:f.AlignJustify}]}]},{kind:"menu",id:"insert",label:"Insert",icon:f.Plus,children:[{kind:"group-label",id:"insert-label",label:"Insert"},{kind:"button",id:"link",label:"Link",icon:f.Link2},{kind:"button",id:"emoji",label:"Emoji",icon:f.Smile},{kind:"button",id:"table",label:"Table",icon:f.Table2},{kind:"button",id:"image",label:"Image",icon:f.Image},{kind:"button",id:"columns",label:"Columns",icon:f.Columns2,shortcut:"Ctrl+Alt+G"},{kind:"button",id:"callout",label:"Callout",icon:f.Info},{kind:"button",id:"horizontal-rule",label:"Divider",icon:f.Minus,shortcut:"Ctrl+Alt+S"},{kind:"button",id:"video",label:"Video",icon:f.Video},{kind:"button",id:"math",label:"Math",icon:f.Sigma}]},{kind:"separator",id:"voice-divider"},{kind:"button",id:"transcribe",label:"Dictate",icon:f.Mic,shortcut:"Ctrl+Shift+D"},{kind:"menu",id:"table-tools",label:"Table",icon:f.Table2,visibleWhenActive:"table",children:[{kind:"group-label",id:"table-rows-label",label:"Rows"},{kind:"button",id:"table.add-row-before",label:"Insert Row Above",icon:f.Rows3},{kind:"button",id:"table.add-row-after",label:"Insert Row Below",icon:f.Rows3},{kind:"button",id:"table.delete-row",label:"Delete Row",icon:f.Trash2},{kind:"separator",id:"table-columns-divider"},{kind:"group-label",id:"table-columns-label",label:"Columns"},{kind:"button",id:"table.add-column-before",label:"Insert Column Left",icon:f.Columns2},{kind:"button",id:"table.add-column-after",label:"Insert Column Right",icon:f.Columns2},{kind:"button",id:"table.delete-column",label:"Delete Column",icon:f.Trash2},{kind:"separator",id:"table-cells-divider"},{kind:"group-label",id:"table-cells-label",label:"Cells"},{kind:"button",id:"table.merge-cells",label:"Merge Cells",icon:f.Braces},{kind:"button",id:"table.split-cell",label:"Split Cell",icon:f.Braces},{kind:"button",id:"table.toggle-header-row",label:"Toggle Header Row",icon:f.Rows3},{kind:"separator",id:"table-delete-divider"},{kind:"button",id:"table.delete",label:"Delete Table",icon:f.Trash2}]}];var _="flex items-center justify-center rounded p-1.5 text-gray-600 transition-colors dark:text-gray-300 disabled:cursor-not-allowed disabled:opacity-40 hover:enabled:bg-gray-100 dark:hover:enabled:bg-slate-800",S="bg-gray-200 text-gray-900 dark:bg-slate-700 dark:text-white",k="flex w-full cursor-pointer items-center gap-2 text-xs data-disabled:cursor-not-allowed data-disabled:opacity-40";function C({shortcut:e}){return e?(0,u.jsx)("span",{className:"ml-auto pl-4 text-[10px] tracking-widest text-gray-400 dark:text-gray-500",children:e}):null}function E({items:e,adapter:n}){return(0,u.jsx)(u.Fragment,{children:e.map(e=>{if("separator"===e.kind)return(0,u.jsx)(s.DropdownMenuSeparator,{},e.id);if("group-label"===e.kind)return(0,u.jsx)(s.DropdownMenuLabel,{className:"px-2 py-1 text-[10px] font-semibold uppercase tracking-wide text-gray-400",children:e.label},e.id);if("menu"===e.kind){const t=e.icon;return(0,u.jsxs)(s.DropdownMenuSub,{children:[(0,u.jsxs)(s.DropdownMenuSubTrigger,{className:k,children:[(0,u.jsx)(t,{className:"size-3.5 shrink-0 text-gray-500 dark:text-gray-400"}),e.label]}),(0,u.jsx)(s.DropdownMenuPortal,{children:(0,u.jsx)(s.DropdownMenuSubContent,{className:"min-w-[200px]",children:(0,u.jsx)(E,{items:e.children,adapter:n})})})]},e.id)}const r=e.icon,i=n.isActive(e.id);return(0,u.jsxs)(s.DropdownMenuItem,{"aria-pressed":i,className:t.cn(k,i&&S),"data-command":e.id,"data-state":i?"active":"inactive",disabled:!n.isEnabled(e.id),onSelect:()=>{n.execute(e.id)},children:[(0,u.jsx)(r,{className:"size-3.5 shrink-0 text-gray-500 dark:text-gray-400"}),(0,u.jsx)("span",{className:"truncate",children:e.label}),(0,u.jsx)(C,{shortcut:e.shortcut})]},e.id)})})}function A({item:e,adapter:r}){if("separator"===e.kind)return(0,u.jsx)("div",{className:"mx-1 h-5 w-px bg-gray-200 dark:bg-slate-700"});if("group-label"===e.kind)return(0,u.jsx)("span",{className:"px-1 text-[10px] font-semibold uppercase tracking-wide text-gray-400",children:e.label});if("menu"===e.kind){if(e.visibleWhenActive&&!r.isActive(e.visibleWhenActive))return null;const i=e.icon;return(0,u.jsxs)(s.DropdownMenu,{children:[(0,u.jsxs)(n.Tooltip,{children:[(0,u.jsx)(n.TooltipTrigger,{asChild:!0,children:(0,u.jsx)(s.DropdownMenuTrigger,{"aria-label":e.label,className:t.cn(_,"data-[state=open]:bg-gray-200 dark:data-[state=open]:bg-slate-700"),"data-menu":e.id,children:(0,u.jsx)(i,{className:"size-4"})})}),(0,u.jsx)(n.TooltipContent,{side:"bottom",children:e.label})]}),(0,u.jsx)(s.DropdownMenuContent,{align:"start",className:"min-w-[240px]",children:(0,u.jsx)(E,{items:e.children,adapter:r})})]})}const i=e.icon,o=r.isActive(e.id),a=r.isEnabled(e.id);return(0,u.jsxs)(n.Tooltip,{children:[(0,u.jsx)(n.TooltipTrigger,{asChild:!0,children:(0,u.jsx)("button",{"aria-label":e.label,"aria-pressed":o,className:t.cn(_,o&&S),"data-command":e.id,"data-state":o?"active":"inactive",disabled:!a,onClick:()=>{r.execute(e.id)},type:"button",children:(0,u.jsx)(i,{className:"size-4"})})}),(0,u.jsxs)(n.TooltipContent,{side:"bottom",children:[e.label,e.shortcut?(0,u.jsx)("span",{className:"ml-2 text-[10px] tracking-widest opacity-70",children:e.shortcut}):null]})]})}function x({adapter:e,items:r=v,className:i,children:s}){return function(e){const[t,n]=l.useState(0);l.useEffect(()=>{if(e.subscribe)return e.subscribe(()=>n(e=>e+1))},[e])}(e),(0,u.jsx)(n.TooltipProvider,{delayDuration:300,children:(0,u.jsxs)("div",{className:t.cn("flex flex-wrap items-center gap-0.5 border-b border-gray-200 px-2 py-1 dark:border-slate-700",i),"data-engine":e.engine,role:"toolbar",children:[r.map(t=>(0,u.jsx)(A,{adapter:e,item:t},(t.kind,t.id))),s?(0,u.jsx)("div",{className:"ml-auto flex items-center gap-1",children:s}):null]})})}var T="REASON-documents",R="reason-documents-changed";function D(){if("undefined"==typeof window)return[];try{const e=window.localStorage.getItem(T);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function O(e){"undefined"!=typeof window&&(window.localStorage.setItem(T,JSON.stringify(e)),window.dispatchEvent(new Event(R)))}function U(e){return{id:e.id,title:e.title?.trim()||"Untitled Document"}}function P(){return D().filter(e=>!e.isFolder&&!e.isDeleted&&!e.parentId).map(U)}function L(e="Untitled Document"){const t={id:`doc-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,title:e,content:"",parentId:null};return O([...D(),t]),U(t)}function M(e,t){const n=t.trim()||"Untitled Document";O(D().map(t=>t.id===e?{...t,title:n}:t))}function I(e){O(D().map(t=>t.id===e?{...t,isDeleted:!0}:t))}function N(e){if("undefined"==typeof window)return()=>{};const t=t=>{"REASON-documents"===t.key&&e()};return window.addEventListener(R,e),window.addEventListener("storage",t),()=>{window.removeEventListener(R,e),window.removeEventListener("storage",t)}}var j=function(e){return e[e.Token=0]="Token",e[e.PermissionDenied=1]="PermissionDenied",e[e.Authenticated=2]="Authenticated",e}({}),V=(e,t)=>{a.writeVarUint(e,j.Token),a.writeVarString(e,t)},F=(e,t,n,r)=>{switch(a.readVarUint(e)){case j.Token:t();break;case j.PermissionDenied:n(a.readVarString(e));break;case j.Authenticated:r(a.readVarString(e))}},B=e=>Array.from(e.entries()).map(([e,t])=>({clientId:e,...t}));function H(e,t){return e+"\0"+t}function W(e){const t=e.indexOf("\0");return-1===t?{documentName:e,sessionId:null}:{documentName:e.substring(0,t),sessionId:e.substring(t+1)}}var Y=function(e){return e[e.Connecting=0]="Connecting",e[e.Open=1]="Open",e[e.Closing=2]="Closing",e[e.Closed=3]="Closed",e}({});async function q(e){return new Promise(t=>setTimeout(t,e))}function K(e,t){let n=t.delay;if(0===n)return 0;if(t.factor&&(n*=Math.pow(t.factor,e.attemptNum-1),0!==t.maxDelay&&(n=Math.min(n,t.maxDelay))),t.jitter){const e=Math.ceil(t.minDelay);n=Math.floor(Math.random()*(Math.floor(n)-e+1))+e}return Math.round(n)}async function z(e,t){const n=function(e){return e||(e={}),{delay:void 0===e.delay?200:e.delay,initialDelay:void 0===e.initialDelay?0:e.initialDelay,minDelay:void 0===e.minDelay?0:e.minDelay,maxDelay:void 0===e.maxDelay?0:e.maxDelay,factor:void 0===e.factor?0:e.factor,maxAttempts:void 0===e.maxAttempts?3:e.maxAttempts,timeout:void 0===e.timeout?0:e.timeout,jitter:!0===e.jitter,initialJitter:!0===e.initialJitter,handleError:void 0===e.handleError?null:e.handleError,handleTimeout:void 0===e.handleTimeout?null:e.handleTimeout,beforeAttempt:void 0===e.beforeAttempt?null:e.beforeAttempt,calculateDelay:void 0===e.calculateDelay?null:e.calculateDelay}}(t);for(const o of["delay","initialDelay","minDelay","maxDelay","maxAttempts","timeout"]){const e=n[o];if(!Number.isInteger(e)||e<0)throw new Error(`Value for ${o} must be an integer greater than or equal to 0`)}if(n.factor.constructor!==Number||n.factor<0)throw new Error("Value for factor must be a number greater than or equal to 0");if(n.delay<n.minDelay)throw new Error(`delay cannot be less than minDelay (delay: ${n.delay}, minDelay: ${n.minDelay}`);const r={attemptNum:0,attemptsRemaining:n.maxAttempts?n.maxAttempts:-1,aborted:!1,abort(){r.aborted=!0}},i=n.calculateDelay||K;const s=n.calculateDelay?n.calculateDelay(r,n):n.initialDelay;if(s&&await q(s),r.attemptNum<1&&n.initialJitter){const e=i(r,n);e&&await q(e)}return async function t(){if(n.beforeAttempt&&n.beforeAttempt(r,n),r.aborted){const e=new Error("Attempt aborted");throw e.code="ATTEMPT_ABORTED",e}const s=async e=>{if(n.handleError&&await n.handleError(e,r,n),r.aborted||0===r.attemptsRemaining)throw e;r.attemptNum++;const s=i(r,n);return s&&await q(s),t()};return r.attemptsRemaining>0&&r.attemptsRemaining--,n.timeout?new Promise((t,i)=>{const o=setTimeout(()=>{if(n.handleTimeout)try{t(n.handleTimeout(r,n))}catch(e){i(e)}else{const e=new Error(`Retry timeout (attemptNum: ${r.attemptNum}, timeout: ${n.timeout})`);e.code="ATTEMPT_TIMEOUT",i(e)}},n.timeout);e(r,n).then(e=>{clearTimeout(o),t(e)}).catch(e=>{clearTimeout(o),s(e).then(t).catch(i)})}):e(r,n).catch(s)}()}var $=(e,t,n)=>((e,t,n)=>{a.writeVarUint(e,1),a.writeVarUint8Array(e,a.encodeStateAsUpdate(t,n))})(t,n,a.readVarUint8Array(e)),J=(e,t,n,r)=>{try{a.applyUpdate(t,a.readVarUint8Array(e),n)}catch(i){null!=r&&r(i)}},Q=J,G=class{constructor(){this.callbacks={}}on(e,t){return this.callbacks[e]||(this.callbacks[e]=[]),this.callbacks[e].push(t),this}emit(e,...t){const n=this.callbacks[e];return n&&n.forEach(e=>e.apply(this,t)),this}off(e,t){const n=this.callbacks[e];return n&&(t?this.callbacks[e]=n.filter(e=>e!==t):delete this.callbacks[e]),this}removeAllListeners(){this.callbacks={}}},X=class{constructor(e){this.data=e,this.encoder=a.createEncoder(),this.decoder=a.createDecoder(new Uint8Array(this.data))}peekVarString(){return a.peekVarString(this.decoder)}readVarUint(){return a.readVarUint(this.decoder)}readVarString(){return a.readVarString(this.decoder)}readVarUint8Array(){return a.readVarUint8Array(this.decoder)}writeVarUint(e){return a.writeVarUint(this.encoder,e)}writeVarString(e){return a.writeVarString(this.encoder,e)}writeVarUint8Array(e){return a.writeVarUint8Array(this.encoder,e)}length(){return a.length(this.encoder)}},Z=function(e){return e[e.Sync=0]="Sync",e[e.Awareness=1]="Awareness",e[e.Auth=2]="Auth",e[e.QueryAwareness=3]="QueryAwareness",e[e.Stateless=5]="Stateless",e[e.CLOSE=7]="CLOSE",e[e.SyncStatus=8]="SyncStatus",e[e.Ping=9]="Ping",e[e.Pong=10]="Pong",e}({}),ee=function(e){return e.Connecting="connecting",e.Connected="connected",e.Disconnected="disconnected",e}({}),te=class{constructor(){this.encoder=a.createEncoder()}get(e){return e.encoder}toUint8Array(){return a.toUint8Array(this.encoder)}},ne=class extends te{constructor(...e){super(...e),this.type=Z.CLOSE,this.description="Ask the server to close the connection"}get(e){return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),this.encoder}},re=class e extends G{static{this.DEDUPLICATABLE_TYPES=new Set([Z.Awareness,Z.QueryAwareness])}constructor(e){super(),this.messageQueue=[],this.configuration={url:"",autoConnect:!0,preserveTrailingSlash:!1,document:void 0,WebSocketPolyfill:void 0,messageReconnectTimeout:3e4,delay:1e3,initialDelay:0,factor:2,maxAttempts:0,minDelay:1e3,maxDelay:3e4,jitter:!0,timeout:0,onOpen:()=>null,onConnect:()=>null,onMessage:()=>null,onOutgoingMessage:()=>null,onStatus:()=>null,onDisconnect:()=>null,onClose:()=>null,onDestroy:()=>null,onAwarenessUpdate:()=>null,onAwarenessChange:()=>null,handleTimeout:null,providerMap:new Map},this.webSocket=null,this.webSocketHandlers={},this.shouldConnect=!0,this.status=ee.Disconnected,this.lastMessageReceived=0,this.identifier=0,this.intervals={connectionChecker:null},this.connectionAttempt=null,this.receivedOnOpenPayload=void 0,this.closeTries=0,this.setConfiguration(e),this.configuration.WebSocketPolyfill=e.WebSocketPolyfill?e.WebSocketPolyfill:WebSocket,this.on("open",this.configuration.onOpen),this.on("open",this.onOpen.bind(this)),this.on("connect",this.configuration.onConnect),this.on("message",this.configuration.onMessage),this.on("outgoingMessage",this.configuration.onOutgoingMessage),this.on("status",this.configuration.onStatus),this.on("disconnect",this.configuration.onDisconnect),this.on("close",this.configuration.onClose),this.on("destroy",this.configuration.onDestroy),this.on("awarenessUpdate",this.configuration.onAwarenessUpdate),this.on("awarenessChange",this.configuration.onAwarenessChange),this.on("close",this.onClose.bind(this)),this.on("message",this.onMessage.bind(this)),this.intervals.connectionChecker=setInterval(this.checkConnection.bind(this),this.configuration.messageReconnectTimeout/10),this.shouldConnect&&this.connect()}async onOpen(e){this.status=ee.Connected,this.emit("status",{status:ee.Connected}),this.cancelWebsocketRetry=void 0,this.receivedOnOpenPayload=e}attach(e){const t=e.effectiveName,n=this.configuration.providerMap.get(t);if(n&&n!==e&&n.isAuthenticated)throw new Error(`Cannot attach two providers with the same effective name "${t}". Use sessionAwareness: true to multiplex providers with the same document name.`);this.configuration.providerMap.set(t,e),this.status===ee.Disconnected&&this.shouldConnect&&this.connect(),this.receivedOnOpenPayload&&this.status===ee.Connected&&e.onOpen(this.receivedOnOpenPayload)}detach(e){const t=e.effectiveName;this.configuration.providerMap.has(t)&&(e.send(ne,{documentName:t}),this.configuration.providerMap.delete(t))}setConfiguration(e={}){this.configuration={...this.configuration,...e},this.configuration.autoConnect||(this.shouldConnect=!1)}async connect(){if(this.status===ee.Connected)return;this.cancelWebsocketRetry&&(this.cancelWebsocketRetry(),this.cancelWebsocketRetry=void 0),this.receivedOnOpenPayload=void 0,this.shouldConnect=!0;const{retryPromise:e,cancelFunc:t}=(()=>{let e=!1;return{retryPromise:z(this.createWebSocketConnection.bind(this),{delay:this.configuration.delay,initialDelay:this.configuration.initialDelay,factor:this.configuration.factor,maxAttempts:this.configuration.maxAttempts,minDelay:this.configuration.minDelay,maxDelay:this.configuration.maxDelay,jitter:this.configuration.jitter,timeout:this.configuration.timeout,handleTimeout:this.configuration.handleTimeout,beforeAttempt:t=>{this.shouldConnect&&!e||t.abort()}}).catch(e=>{if(e&&"ATTEMPT_ABORTED"!==e.code)throw e}),cancelFunc:()=>{e=!0}}})();return this.cancelWebsocketRetry=t,e}attachWebSocketListeners(e,t){const{identifier:n}=e;this.webSocketHandlers[n]={message:e=>this.emit("message",e),close:e=>this.emit("close",{event:e}),open:e=>this.emit("open",e),error:e=>{t(e)}};const r=this.webSocketHandlers[e.identifier];Object.keys(r).forEach(t=>{e.addEventListener(t,r[t])})}cleanupWebSocket(){if(!this.webSocket)return;const{identifier:e}=this.webSocket,t=this.webSocketHandlers[e];Object.keys(t).forEach(n=>{this.webSocket?.removeEventListener(n,t[n]),delete this.webSocketHandlers[e]}),this.webSocket.close(),this.webSocket=null}createWebSocketConnection(){return new Promise((e,t)=>{this.webSocket&&(this.messageQueue=[],this.cleanupWebSocket()),this.lastMessageReceived=0,this.identifier+=1;const n=new this.configuration.WebSocketPolyfill(this.url);n.binaryType="arraybuffer",n.identifier=this.identifier,this.attachWebSocketListeners(n,t),this.webSocket=n,this.status=ee.Connecting,this.emit("status",{status:ee.Connecting}),this.connectionAttempt={resolve:e,reject:t}})}onMessage(e){this.resolveConnectionAttempt(),this.lastMessageReceived=a.getUnixTime();const t=new Uint8Array(e.data);if(1===t.length&&t[0]===Z.Ping)return void this.sendPong();const n=new X(t).peekVarString();this.configuration.providerMap.get(n)?.onMessage(e)}sendPong(){const e=a.createEncoder();a.writeVarUint(e,Z.Pong),this.send(a.toUint8Array(e))}resolveConnectionAttempt(){this.connectionAttempt&&(this.connectionAttempt.resolve(),this.connectionAttempt=null,this.status=ee.Connected,this.emit("status",{status:ee.Connected}),this.emit("connect"),this.messageQueue.forEach(e=>this.send(e)),this.messageQueue=[])}stopConnectionAttempt(){this.connectionAttempt=null}rejectConnectionAttempt(){this.connectionAttempt?.reject(),this.connectionAttempt=null}checkConnection(){this.status===ee.Connected&&this.lastMessageReceived&&(this.configuration.messageReconnectTimeout>=a.getUnixTime()-this.lastMessageReceived||(this.closeTries+=1,this.closeTries>2?(this.onClose({event:{code:4408,reason:"forced"}}),this.closeTries=0):(this.webSocket?.close(),this.messageQueue=[])))}get serverUrl(){if(this.configuration.preserveTrailingSlash)return this.configuration.url;let e=this.configuration.url;for(;"/"===e[e.length-1];)e=e.slice(0,e.length-1);return e}get url(){return this.serverUrl}disconnect(){if(this.shouldConnect=!1,null!==this.webSocket)try{this.webSocket.close(),this.messageQueue=[]}catch(e){}}parseQueuedMessage(e){try{const t=a.createDecoder(e);return{documentName:a.readVarString(t),messageType:a.readVarUint(t)}}catch{return null}}addToQueue(t){if(t instanceof Uint8Array){const n=this.parseQueuedMessage(t);n&&e.DEDUPLICATABLE_TYPES.has(n.messageType)&&(this.messageQueue=this.messageQueue.filter(e=>{if(!(e instanceof Uint8Array))return!0;const t=this.parseQueuedMessage(e);return!t||!(t.documentName===n.documentName&&t.messageType===n.messageType)}))}this.messageQueue.push(t)}send(e){this.webSocket?.readyState===Y.Open?this.webSocket.send(e):this.addToQueue(e)}onClose({event:e}){this.closeTries=0,this.cleanupWebSocket(),this.connectionAttempt&&this.rejectConnectionAttempt(),this.status=ee.Disconnected,this.emit("status",{status:ee.Disconnected}),this.emit("disconnect",{event:e}),!this.cancelWebsocketRetry&&this.shouldConnect&&setTimeout(()=>{this.connect()},this.configuration.delay)}destroy(){this.emit("destroy"),clearInterval(this.intervals.connectionChecker),this.stopConnectionAttempt(),this.disconnect(),this.removeAllListeners(),this.cleanupWebSocket()}},ie=class{constructor(e){this.message=e}apply(e,t){const{message:n}=this,r=n.readVarUint(),i=n.length();switch(r){case Z.Sync:this.applySyncMessage(e,t);break;case Z.Awareness:this.applyAwarenessMessage(e);break;case Z.Auth:this.applyAuthMessage(e);break;case Z.QueryAwareness:this.applyQueryAwarenessMessage(e);break;case Z.Stateless:e.receiveStateless(a.readVarString(n.decoder));break;case Z.SyncStatus:this.applySyncStatusMessage(e,1===a.readVarInt(n.decoder));break;case Z.CLOSE:{const t={code:1e3,reason:a.readVarString(n.decoder)};e.onClose(),e.configuration.onClose({event:t}),e.forwardClose({event:t});break}}n.length()>i+1&&e.send(te,{encoder:n.encoder})}applySyncMessage(e,t){const{message:n}=this;n.writeVarUint(Z.Sync);const r=((e,t,n,r,i)=>{const s=a.readVarUint(e);switch(s){case 0:$(e,t,n);break;case 1:J(e,n,r,i);break;case 2:Q(e,n,r,i);break;default:throw new Error("Unknown message type")}return s})(n.decoder,n.encoder,e.document,e);t&&1===r&&(e.synced=!0)}applySyncStatusMessage(e,t){t&&e.decrementUnsyncedChanges()}applyAwarenessMessage(e){if(!e.awareness)return;const{message:t}=this;((e,t,n)=>{const r=a.createDecoder(t),i=a.getUnixTime(),s=[],o=[],c=[],l=[],d=a.readVarUint(r);for(let h=0;h<d;h++){const t=a.readVarUint(r);let n=a.readVarUint(r);const d=JSON.parse(a.readVarString(r)),h=e.meta.get(t),u=e.states.get(t),f=void 0===h?0:h.clock;(f<n||f===n&&null===d&&e.states.has(t))&&(null===d?t===e.clientID&&null!=e.getLocalState()?n++:e.states.delete(t):e.states.set(t,d),e.meta.set(t,{clock:n,lastUpdated:i}),void 0===h&&null!==d?s.push(t):void 0!==h&&null===d?l.push(t):null!==d&&(a.equalityDeep(d,u)||c.push(t),o.push(t)))}(s.length>0||c.length>0||l.length>0)&&e.emit("change",[{added:s,updated:c,removed:l},n]),(s.length>0||o.length>0||l.length>0)&&e.emit("update",[{added:s,updated:o,removed:l},n])})(e.awareness,t.readVarUint8Array(),e)}applyAuthMessage(e){const{message:t}=this;F(t.decoder,e.sendToken.bind(e),e.permissionDeniedHandler.bind(e),e.authenticatedHandler.bind(e))}applyQueryAwarenessMessage(e){if(!e.awareness)return;const{message:t}=this;t.writeVarUint(Z.Awareness),t.writeVarUint8Array(w(e.awareness,Array.from(e.awareness.getStates().keys())))}},se=class{constructor(e,t={}){this.message=new e,this.encoder=this.message.get(t)}create(){return a.toUint8Array(this.encoder)}send(e){e?.send(this.create())}},oe=class extends te{constructor(...e){super(...e),this.type=Z.Auth,this.description="Authentication"}get(e){if(void 0===e.token)throw new Error("The authentication message requires `token` as an argument.");return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),V(this.encoder,e.token),a.writeVarString(this.encoder,"4.6.0"),this.encoder}},ae=class extends te{constructor(...e){super(...e),this.type=Z.Awareness,this.description="Awareness states update"}get(e){if(void 0===e.awareness)throw new Error("The awareness message requires awareness as an argument");if(void 0===e.clients)throw new Error("The awareness message requires clients as an argument");let t;return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),t=void 0===e.states?w(e.awareness,e.clients):w(e.awareness,e.clients,e.states),a.writeVarUint8Array(this.encoder,t),this.encoder}},ce=class extends te{constructor(...e){super(...e),this.type=Z.Stateless,this.description="A stateless message"}get(e){return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),a.writeVarString(this.encoder,e.payload??""),this.encoder}},le=class extends te{constructor(...e){super(...e),this.type=Z.Sync,this.description="First sync step"}get(e){if(void 0===e.document)throw new Error("The sync step one message requires document as an argument");return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),((e,t)=>{a.writeVarUint(e,0);const n=a.encodeStateVector(t);a.writeVarUint8Array(e,n)})(this.encoder,e.document),this.encoder}},de=class extends te{constructor(...e){super(...e),this.type=Z.Sync,this.description="A document update"}get(e){var t,n;return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),t=this.encoder,n=e.update,a.writeVarUint(t,2),a.writeVarUint8Array(t,n),this.encoder}},he=class extends Error{constructor(...e){super(...e),this.code=1001}},ue=class extends G{get effectiveName(){return this.configuration.sessionAwareness?H(this.configuration.name,this.sessionId):this.configuration.name}constructor(e){super(),this.configuration={name:"",document:void 0,awareness:void 0,token:null,sessionAwareness:!1,forceSyncInterval:!1,flushDelay:!1,onAuthenticated:()=>null,onAuthenticationFailed:()=>null,onOpen:()=>null,onConnect:()=>null,onMessage:()=>null,onOutgoingMessage:()=>null,onSynced:()=>null,onStatus:()=>null,onDisconnect:()=>null,onClose:()=>null,onDestroy:()=>null,onAwarenessUpdate:()=>null,onAwarenessChange:()=>null,onStateless:()=>null,onUnsyncedChanges:()=>null},this.isSynced=!1,this.unsyncedChanges=0,this.isAuthenticated=!1,this.authorizedScope=void 0,this.manageSocket=!1,this._isAttached=!1,this.pendingUpdates=[],this.pendingAwarenessClients=new Set,this.flushTimeout=null,this.sessionId=Math.random().toString(36).slice(2),this.intervals={forceSync:null},this.boundDocumentUpdateHandler=this.documentUpdateHandler.bind(this),this.boundAwarenessUpdateHandler=this.awarenessUpdateHandler.bind(this),this.boundPageHide=this.pageHide.bind(this),this.boundOnOpen=this.onOpen.bind(this),this.boundOnClose=this.onClose.bind(this),this.forwardConnect=()=>this.emit("connect"),this.forwardStatus=e=>this.emit("status",e),this.forwardClose=e=>this.emit("close",e),this.forwardDisconnect=e=>this.emit("disconnect",e),this.forwardDestroy=()=>this.emit("destroy"),this.setConfiguration(e),this.configuration.document=e.document?e.document:new a.Doc,this.configuration.awareness=void 0!==e.awareness?e.awareness:new m(this.document),this.on("open",this.configuration.onOpen),this.on("message",this.configuration.onMessage),this.on("outgoingMessage",this.configuration.onOutgoingMessage),this.on("synced",this.configuration.onSynced),this.on("destroy",this.configuration.onDestroy),this.on("awarenessUpdate",this.configuration.onAwarenessUpdate),this.on("awarenessChange",this.configuration.onAwarenessChange),this.on("stateless",this.configuration.onStateless),this.on("unsyncedChanges",this.configuration.onUnsyncedChanges),this.on("authenticated",this.configuration.onAuthenticated),this.on("authenticationFailed",this.configuration.onAuthenticationFailed),this.awareness?.on("update",()=>{this.emit("awarenessUpdate",{states:B(this.awareness.getStates())})}),this.awareness?.on("change",()=>{this.emit("awarenessChange",{states:B(this.awareness.getStates())})}),this.document.on("update",this.boundDocumentUpdateHandler),this.awareness?.on("update",this.boundAwarenessUpdateHandler),this.registerEventListeners(),this.configuration.forceSyncInterval&&"number"==typeof this.configuration.forceSyncInterval&&(this.intervals.forceSync=setInterval(this.forceSync.bind(this),this.configuration.forceSyncInterval)),this.manageSocket&&this.attach()}setConfiguration(e={}){e.websocketProvider||(this.manageSocket=!0,this.configuration.websocketProvider=new re(e)),this.configuration={...this.configuration,...e}}get document(){return this.configuration.document}get isAttached(){return this._isAttached}get awareness(){return this.configuration.awareness}get hasUnsyncedChanges(){return this.unsyncedChanges>0}resetUnsyncedChanges(){this.unsyncedChanges=1,this.emit("unsyncedChanges",{number:this.unsyncedChanges})}incrementUnsyncedChanges(){this.unsyncedChanges+=1,this.emit("unsyncedChanges",{number:this.unsyncedChanges})}decrementUnsyncedChanges(){this.unsyncedChanges>0&&(this.unsyncedChanges-=1),0===this.unsyncedChanges&&(this.synced=!0),this.emit("unsyncedChanges",{number:this.unsyncedChanges})}forceSync(){this.resetUnsyncedChanges(),this.send(le,{document:this.document,documentName:this.effectiveName})}pageHide(){this.awareness&&y(this.awareness,[this.document.clientID],"page hide")}registerEventListeners(){"undefined"!=typeof window&&"addEventListener"in window&&window.addEventListener("pagehide",this.boundPageHide)}sendStateless(e){this.send(ce,{documentName:this.effectiveName,payload:e})}async sendToken(){let e;try{e=await this.getToken()}catch(t){return void this.permissionDeniedHandler(`Failed to get token during sendToken(): ${t}`)}this.send(oe,{token:e??"",documentName:this.effectiveName})}get batchingEnabled(){return!!this.configuration.flushDelay&&"number"==typeof this.configuration.flushDelay}documentUpdateHandler(e,t){if(t!==this){if(!this.batchingEnabled)return this.incrementUnsyncedChanges(),void this.send(de,{update:e,documentName:this.effectiveName});0===this.pendingUpdates.length&&this.incrementUnsyncedChanges(),this.pendingUpdates.push(e),this.scheduleFlush()}}awarenessUpdateHandler({added:e,updated:t,removed:n},r){if(r===this)return;const i=e.concat(t).concat(n);if(this.batchingEnabled){for(const e of i)this.pendingAwarenessClients.add(e);this.scheduleFlush()}else this.send(ae,{awareness:this.awareness,clients:i,documentName:this.effectiveName})}scheduleFlush(){null===this.flushTimeout&&(this.flushTimeout=setTimeout(()=>{this.flushTimeout=null,this.flushPendingUpdates()},this.configuration.flushDelay))}flushPendingUpdates(){if(null!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.pendingUpdates.length>0){const e=1===this.pendingUpdates.length?this.pendingUpdates[0]:a.mergeUpdates(this.pendingUpdates);this.pendingUpdates=[],this.send(de,{update:e,documentName:this.effectiveName})}if(this.pendingAwarenessClients.size>0){const e=Array.from(this.pendingAwarenessClients);this.pendingAwarenessClients.clear(),this.send(ae,{awareness:this.awareness,clients:e,documentName:this.effectiveName})}}get synced(){return this.isSynced}set synced(e){this.isSynced!==e&&(this.isSynced=e,e&&this.emit("synced",{state:e}))}receiveStateless(e){this.emit("stateless",{payload:e})}async connect(){if(this.manageSocket)return this.configuration.websocketProvider.connect()}disconnect(){if(this.manageSocket)return this.configuration.websocketProvider.disconnect()}async onOpen(e){this.isAuthenticated=!1,this.emit("open",{event:e}),await this.sendToken(),this.startSync()}async getToken(){return"function"==typeof this.configuration.token?await this.configuration.token():this.configuration.token}startSync(){this.resetUnsyncedChanges(),this.send(le,{document:this.document,documentName:this.effectiveName}),this.awareness&&null!==this.awareness.getLocalState()&&this.send(ae,{awareness:this.awareness,clients:[this.document.clientID],documentName:this.effectiveName})}send(e,t){if(!this._isAttached)return;const n=new se(e,t);this.emit("outgoingMessage",{message:n.message}),n.send(this.configuration.websocketProvider)}onMessage(e){const t=new X(e.data),{documentName:n}=W(t.readVarString());t.writeVarString(this.effectiveName),this.emit("message",{event:e,message:new X(e.data)}),new ie(t).apply(this,!0)}onClose(){this.isAuthenticated=!1,this.synced=!1,null!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.pendingUpdates=[],this.pendingAwarenessClients.clear(),this.awareness&&y(this.awareness,Array.from(this.awareness.getStates().keys()).filter(e=>e!==this.document.clientID),this)}destroy(){this.emit("destroy"),this.intervals.forceSync&&clearInterval(this.intervals.forceSync),this.awareness&&(y(this.awareness,[this.document.clientID],"provider destroy"),this.awareness.off("update",this.boundAwarenessUpdateHandler),this.awareness.destroy()),this.flushPendingUpdates(),this.document.off("update",this.boundDocumentUpdateHandler),this.removeAllListeners(),this.detach(),this.manageSocket&&this.configuration.websocketProvider.destroy(),"undefined"!=typeof window&&"removeEventListener"in window&&window.removeEventListener("pagehide",this.boundPageHide)}detach(){this.configuration.websocketProvider.off("connect",this.configuration.onConnect),this.configuration.websocketProvider.off("connect",this.forwardConnect),this.configuration.websocketProvider.off("status",this.forwardStatus),this.configuration.websocketProvider.off("status",this.configuration.onStatus),this.configuration.websocketProvider.off("open",this.boundOnOpen),this.configuration.websocketProvider.off("close",this.boundOnClose),this.configuration.websocketProvider.off("close",this.configuration.onClose),this.configuration.websocketProvider.off("close",this.forwardClose),this.configuration.websocketProvider.off("disconnect",this.configuration.onDisconnect),this.configuration.websocketProvider.off("disconnect",this.forwardDisconnect),this.configuration.websocketProvider.off("destroy",this.configuration.onDestroy),this.configuration.websocketProvider.off("destroy",this.forwardDestroy),this.configuration.websocketProvider.detach(this),this._isAttached=!1}attach(){this._isAttached||(this.configuration.websocketProvider.on("connect",this.configuration.onConnect),this.configuration.websocketProvider.on("connect",this.forwardConnect),this.configuration.websocketProvider.on("status",this.configuration.onStatus),this.configuration.websocketProvider.on("status",this.forwardStatus),this.configuration.websocketProvider.on("open",this.boundOnOpen),this.configuration.websocketProvider.on("close",this.boundOnClose),this.configuration.websocketProvider.on("close",this.configuration.onClose),this.configuration.websocketProvider.on("close",this.forwardClose),this.configuration.websocketProvider.on("disconnect",this.configuration.onDisconnect),this.configuration.websocketProvider.on("disconnect",this.forwardDisconnect),this.configuration.websocketProvider.on("destroy",this.configuration.onDestroy),this.configuration.websocketProvider.on("destroy",this.forwardDestroy),this.configuration.websocketProvider.attach(this),this._isAttached=!0)}permissionDeniedHandler(e){this.emit("authenticationFailed",{reason:e}),this.isAuthenticated=!1}authenticatedHandler(e){this.isAuthenticated=!0,this.authorizedScope=e,this.emit("authenticated",{scope:e})}setAwarenessField(e,t){if(!this.awareness)throw new he(`Cannot set awareness field "${e}" to ${JSON.stringify(t)}. You have disabled Awareness for this provider by explicitly passing awareness: null in the provider configuration.`);this.awareness.setLocalStateField(e,t)}},fe="reason-editor";function ge(e,t){if(!t)throw new Error("collaborationRoom: documentId is required");return`${fe}:${e}:${t}`}function pe(){return"undefined"!=typeof process&&(process.env.NEXT_PUBLIC_HOCUSPOCUS_URL??process.env.VITE_HOCUSPOCUS_URL)||"ws://127.0.0.1:1234"}function me({engine:e,documentId:t,token:n,url:r=pe(),onSynced:i}){const s=ge(e,t),o=new a.Doc,c=new ue({document:o,name:s,token:n,url:r,onSynced:()=>i?.(!0)});return{room:s,ydoc:o,provider:c,destroy(){c.destroy(),o.destroy()}}}function ye({documentId:e,token:t,url:n=pe()}){const r=ge("plate",e);return[{type:"hocuspocus",options:{name:r,token:t,url:n}},{type:"indexeddb",options:{docName:r}}]}var we=["#e11d48","#0891b2","#7c3aed","#ea580c","#16a34a","#2563eb","#db2777","#ca8a04"];function be(e){let t=0;for(let n=0;n<e.length;n++)t=31*t+e.charCodeAt(n)|0;return we[Math.abs(t)%we.length]}var ve={bold:"bold",italic:"italic",underline:"underline",strike:"strike",code:"code",superscript:"superscript",subscript:"subscript",highlight:"highlight","text-color":"textStyle"},_e={paragraph:{name:"paragraph"},"heading-1":{name:"heading",attrs:{level:1}},"heading-2":{name:"heading",attrs:{level:2}},"heading-3":{name:"heading",attrs:{level:3}},"heading-4":{name:"heading",attrs:{level:4}},"heading-5":{name:"heading",attrs:{level:5}},"heading-6":{name:"heading",attrs:{level:6}},blockquote:{name:"blockquote"},"code-block":{name:"codeBlock"},"bullet-list":{name:"bulletList"},"ordered-list":{name:"orderedList"},"task-list":{name:"taskList"},table:{name:"table"},callout:{name:"callout"},columns:{name:"columns"}},Se={"align-left":"left","align-center":"center","align-right":"right","align-justify":"justify"},ke={"table.add-row-before":"addRowBefore","table.add-row-after":"addRowAfter","table.delete-row":"deleteRow","table.add-column-before":"addColumnBefore","table.add-column-after":"addColumnAfter","table.delete-column":"deleteColumn","table.merge-cells":"mergeCells","table.split-cell":"splitCell","table.toggle-header-row":"toggleHeaderRow","table.delete":"deleteTable"};function Ce(e,t){return e?.value?e.value:"undefined"!=typeof window?window.prompt(t)??void 0:void 0}function Ee(e){return{engine:"tiptap",execute(t,n){!function(e,t,n){const r=()=>e.chain().focus(),i=e.commands,s=ke[t];if(s)return void r()[s]?.().run();const o=Se[t];if(o)r().setTextAlign?.(o).run();else switch(t){case"undo":return void i.undo?.();case"redo":return void i.redo?.();case"bold":return void r().toggleBold().run();case"italic":return void r().toggleItalic().run();case"underline":return void r().toggleUnderline?.().run();case"strike":return void r().toggleStrike().run();case"code":return void r().toggleCode().run();case"superscript":return void r().toggleSuperscript?.().run();case"subscript":return void r().toggleSubscript?.().run();case"text-color":{const t=n?.value??"#ef4444";return void(e.isActive("textStyle",{color:t})?r().unsetColor?.().run():r().setColor?.(t).run())}case"highlight":{const t=n?.value??"#fde047";return void(e.isActive("highlight")?r().unsetHighlight?.().run():r().setHighlight?.({color:t}).run())}case"clear-formatting":return void r().clearNodes().unsetAllMarks().run();case"paragraph":return void r().setParagraph().run();case"heading-1":case"heading-2":case"heading-3":case"heading-4":case"heading-5":case"heading-6":{const e=Number(t.slice(8));return void r().toggleHeading({level:e}).run()}case"blockquote":return void r().toggleBlockquote().run();case"code-block":return void r().toggleCodeBlock().run();case"bullet-list":return void r().toggleBulletList().run();case"ordered-list":return void r().toggleOrderedList().run();case"task-list":return void r().toggleTaskList?.().run();case"indent":return void r().indent?.().run();case"outdent":return void r().outdent?.().run();case"link":{const e=Ce(n,"Link URL");if(!e)return;return void r().extendMarkRange("link").setLink({href:e}).run()}case"image":{const e=Ce(n,"Image URL");if(!e)return;const t=r();return void("function"==typeof t.setImageInline?t.setImageInline({src:e}).run():t.setImage?.({src:e}).run())}case"video":{const e=Ce(n,"Video URL");if(!e)return;return void r().setVideo?.({src:e}).run()}case"table":return void r().insertTable?.({rows:3,cols:3,withHeaderRow:!0}).run();case"horizontal-rule":return void r().setHorizontalRule().run();case"emoji":return void r().insertContent(":").run();case"math":return void r().setKatex?.({text:n?.value??""}).run();case"callout":return void r().setCallout?.({type:"note",title:"",body:""}).run();case"columns":return void r().insertColumns?.({cols:2}).run();case"transcribe":return void i.toggleTranscribe?.();default:;}}(e,t,n)},isActive:t=>function(e,t){const n=Se[t];if(n)return e.isActive({textAlign:n});const r=_e[t];if(r)return e.isActive(r.name,r.attrs);const i=ve[t];return i?"text-color"===t?!!e.getAttributes("textStyle").color:e.isActive(i):"link"===t?e.isActive("link"):"transcribe"===t&&!!o.getTranscribeStorage(e)?.listening}(e,t),isEnabled:t=>function(e,t){const n=function(e){switch(e){case"highlight":return"highlight";case"text-color":return"color";case"superscript":return"superscript";case"subscript":return"subscript";case"task-list":return"taskList";case"link":return"link";case"image":return"image";case"video":return"video";case"table":return"table";case"emoji":return"emoji";case"math":return"katex";case"callout":return"callout";case"columns":return"columns";case"transcribe":return"transcribe";case"indent":case"outdent":return"indent";case"align-left":case"align-center":case"align-right":case"align-justify":return"textAlign";default:return}}(t);if(n&&!function(e,t){return e.extensionManager.extensions.some(e=>e.name===t)}(e,n))return!1;if("undo"===t)return e.can().undo();if("redo"===t)return e.can().redo();if("transcribe"===t)return(0,p.isTranscriptionSupported)();const r=ke[t];return r?!!e.isActive("table")&&Boolean(e.can()[r]?.()):e.isEditable}(e,t),getValue:t=>function(e,t){return"text-color"===t?e.getAttributes("textStyle").color:"highlight"===t?e.getAttributes("highlight").color:"link"===t?e.getAttributes("link").href:void 0}(e,t),subscribe(t){e.on("transaction",t),e.on("selectionUpdate",t);const n=o.subscribeTranscribe(e,t);return()=>{e.off("transaction",t),e.off("selectionUpdate",t),n()}}}}function Ae(e){return"string"==typeof e&&/^#[0-9a-fA-F]{6}$/.test(e)}var xe=e=>Array.from(e.entries()).map(([e,t])=>t&&t.user?{clientId:e,...t.user}:{clientId:e}),Te=()=>null,Re=e=>({...e,color:Ae(e.color)?e.color:"transparent"}),De=d.Extension.create({name:"collaborationCaret",priority:999,addOptions:()=>({provider:null,user:{name:null,color:null},render:e=>{const t=document.createElement("span"),{color:n}=Re(e);t.classList.add("collaboration-carets__caret"),t.style.borderColor=n;const r=document.createElement("div");return r.classList.add("collaboration-carets__label"),r.style.backgroundColor=n,r.insertBefore(document.createTextNode(e.name),null),t.insertBefore(r,null),t},selectionRender:e=>Ae(e.color)?a.defaultSelectionBuilder(e):{},onUpdate:Te}),onCreate(){if(this.options.onUpdate,!this.options.provider)throw new Error('The "provider" option is required for the CollaborationCaret extension')},addStorage:()=>({users:[]}),addCommands(){return{updateUser:e=>()=>(this.options.provider.awareness.setLocalStateField("user",e),!0),user:e=>({editor:t})=>t.commands.updateUser(e)}},addProseMirrorPlugins(){const{provider:e}=this.options,t=this.storage,n=this.options.user;return[new h.Plugin({key:new h.PluginKey("collaborationCaretAwarenessListener"),view:()=>{const r=()=>{t.users=xe(e.awareness.states)};return e.awareness.setLocalStateField("user",n),t.users=xe(e.awareness.states),e.awareness.on("update",r),{destroy:()=>{e.awareness.off("update",r),t.users=[]}}}}),a.yCursorPlugin(e.awareness,{cursorBuilder:e=>this.options.render(Re(e)),selectionBuilder:e=>this.options.selectionRender(Re(e))})]}});var Oe={bold:i.KEYS.bold,italic:i.KEYS.italic,underline:i.KEYS.underline,strike:i.KEYS.strikethrough,code:i.KEYS.code,superscript:i.KEYS.sup,subscript:i.KEYS.sub,highlight:i.KEYS.highlight,"text-color":i.KEYS.color},Ue={superscript:i.KEYS.sub,subscript:i.KEYS.sup},Pe={paragraph:i.KEYS.p,"heading-1":i.KEYS.h1,"heading-2":i.KEYS.h2,"heading-3":i.KEYS.h3,"heading-4":i.KEYS.h4,"heading-5":i.KEYS.h5,"heading-6":i.KEYS.h6,blockquote:i.KEYS.blockquote},Le={"bullet-list":i.ListStyleType.Disc,"ordered-list":i.ListStyleType.Decimal,"task-list":i.KEYS.listTodo},Me={"bullet-list":[i.ListStyleType.Disc,i.ListStyleType.Circle,i.ListStyleType.Square],"ordered-list":[i.ListStyleType.Decimal,i.ListStyleType.LowerAlpha,i.ListStyleType.UpperAlpha,i.ListStyleType.LowerRoman,i.ListStyleType.UpperRoman],"task-list":[i.KEYS.listTodo]},Ie={"align-left":"left","align-center":"center","align-right":"right","align-justify":"justify"},Ne=new Set(["table.add-row-before","table.add-row-after","table.delete-row","table.add-column-before","table.add-column-after","table.delete-column","table.merge-cells","table.split-cell","table.toggle-header-row","table.delete"]);function je(e){return!!e.selection&&Boolean(i.getTableAbove(e))}function Ve(e){if(!je(e))return{canMerge:!1,canSplit:!1};const t=i.getSelectedCellEntries(e);if(!t?.length)return{canMerge:!1,canSplit:!1};const n=t.map(([e])=>e);if(n.length>1){const{maxCol:t,maxRow:r,minCol:s,minRow:o}=i.getSelectedCellsBoundingBox(e,n),a=n.reduce((e,t)=>e+i.getColSpan(t)*i.getRowSpan(t),0)===(t-s+1)*(r-o+1);return{canMerge:e.api.isExpanded()&&a,canSplit:!1}}const[r]=n;return{canMerge:!1,canSplit:i.getColSpan(r)>1||i.getRowSpan(r)>1}}function Fe(e,t){return e?.value?e.value:"undefined"!=typeof window?window.prompt(t)??void 0:void 0}function Be(e,t){const n=function(e){if(Ne.has(e)||"table"===e)return i.KEYS.table;switch(e){case"highlight":return i.KEYS.highlight;case"text-color":return i.KEYS.color;case"link":return i.KEYS.link;case"image":return i.KEYS.img;case"video":return i.KEYS.video;case"math":return i.KEYS.equation;case"callout":return i.KEYS.callout;case"columns":return i.KEYS.columnGroup;case"transcribe":return"transcribe";case"emoji":return i.KEYS.emoji;case"code-block":return i.KEYS.codeBlock;case"bullet-list":case"ordered-list":case"task-list":return i.KEYS.list;case"indent":case"outdent":return i.KEYS.indent;case"align-left":case"align-center":case"align-right":case"align-justify":return i.KEYS.textAlign;default:return}}(t);return!(n&&!function(e,t){return Boolean(e.plugins?.[t])}(e,n))&&("undo"===t?e.history.undos.length>0:"redo"===t?e.history.redos.length>0:"transcribe"===t?(0,p.isTranscriptionSupported)()&&!e.api.isReadOnly?.():"table.merge-cells"===t?Ve(e).canMerge:"table.split-cell"===t?Ve(e).canSplit:Ne.has(t)?je(e):!e.api.isReadOnly?.())}function He(e){return{engine:"plate",execute(t,n){!function(e,t,n){e.tf.focus();const r=Oe[t];if(r&&"text-color"!==t&&"highlight"!==t)return void e.tf.toggleMark(r,{remove:Ue[t]});const s=Pe[t];if(s)return void e.tf.toggleBlock(s,s===i.KEYS.blockquote?{wrap:!0}:void 0);const o=Le[t];if(o)return void i.toggleList(e,{listStyleType:o});const a=Ie[t];if(a)e.getTransforms(i.TextAlignPlugin).textAlign.setNodes(a);else switch(t){case"undo":return void e.tf.undo();case"redo":return void e.tf.redo();case"text-color":{const t=n?.value??"#ef4444";return void(e.api.marks()?.[i.KEYS.color]===t?e.tf.removeMarks(i.KEYS.color):e.tf.addMarks({[i.KEYS.color]:t}))}case"highlight":return void(e.api.marks()?.[i.KEYS.highlight]?e.tf.removeMarks(i.KEYS.highlight):e.tf.addMarks({[i.KEYS.highlight]:n?.value??"#fde047"}));case"clear-formatting":return e.tf.removeMarks(Object.values(Oe)),void e.tf.toggleBlock(i.KEYS.p);case"code-block":return void i.toggleCodeBlock(e);case"link":return void(n?.value?i.upsertLink(e,{url:n.value}):i.triggerFloatingLink(e,{focused:!0}));case"image":{const t=Fe(n,"Image URL");if(!t)return;return void i.insertImage(e,t)}case"video":{const t=Fe(n,"Video URL");if(!t)return;return void i.insertMedia(e,{select:!0,type:i.KEYS.video,url:t})}case"table":return void i.insertTable(e,{colCount:3,rowCount:3},{select:!0});case"horizontal-rule":return void e.tf.insertNodes({children:[{text:""}],type:i.KEYS.hr});case"emoji":return void e.tf.insertText(":");case"math":return void i.insertEquation(e,{select:!0});case"callout":return void i.insertCallout(e,{select:!0});case"columns":return void i.insertColumnGroup(e,{columns:2,select:!0});case"transcribe":return void i.getTranscribeController(e).toggle();case"indent":return void i.indent(e);case"outdent":return void i.outdent(e);case"table.add-row-before":return void i.insertTableRow(e,{before:!0});case"table.add-row-after":return void i.insertTableRow(e);case"table.delete-row":return void i.deleteRow(e);case"table.add-column-before":return void i.insertTableColumn(e,{before:!0});case"table.add-column-after":return void i.insertTableColumn(e);case"table.delete-column":return void i.deleteColumn(e);case"table.merge-cells":return void i.mergeTableCells(e);case"table.split-cell":return void i.splitTableCell(e);case"table.toggle-header-row":{const t=i.getTableAbove(e);if(!t)return;const[n,r]=t;return void e.tf.setNodes({headerRow:!n.headerRow},{at:r})}case"table.delete":return void i.deleteTable(e);default:;}}(e,t,n)},isActive(t){if("transcribe"===t)return i.getTranscribeController(e).getState().listening;if(!e.selection)return!1;try{return function(e,t){if("task-list"===t)return i.someTodoList(e);const n=Me[t];if(n)return i.someList(e,n);const r=Oe[t];if(r)return Boolean(e.api.marks()?.[r]);const s=Pe[t];if(s)return e.api.some({match:{type:s}});if("code-block"===t)return e.api.some({match:{type:i.KEYS.codeBlock}});if("table"===t)return je(e);if("callout"===t)return e.api.some({match:{type:i.KEYS.callout}});if("columns"===t)return e.api.some({match:{type:i.KEYS.column}});if("link"===t)return e.api.some({match:{type:i.KEYS.link}});if("transcribe"===t)return i.getTranscribeController(e).getState().listening;const o=Ie[t];return!!o&&e.api.some({match:e=>e[i.KEYS.textAlign]===o})}(e,t)}catch{return!1}},isEnabled(t){try{return Be(e,t)}catch{return!1}},getValue(t){if(e.selection)try{return function(e,t){const n=e.api.marks();return"text-color"===t?n?.[i.KEYS.color]:"highlight"===t?n?.[i.KEYS.highlight]:void 0}(e,t)}catch{return}},subscribe(t){const n=e.apply;let r=!1;e.apply=i=>{n.call(e,i),r||(r=!0,queueMicrotask(()=>{r=!1,t()}))};const s=i.getTranscribeController(e).subscribe(t);return()=>{e.apply=n,s()}}}}var We,Ye=class{constructor(e,t){this.clock=e,this.len=t}},qe=class{constructor(){this.clients=new Map}},Ke=(e,t,n)=>t.clients.forEach((t,r)=>{const i=e.doc.store.clients.get(r);if(null!=i){const r=i[i.length-1],s=r.id.clock+r.length;for(let o=0,a=t[o];o<t.length&&a.clock<s;a=t[++o])Xt(e,i,a.clock,a.len,n)}}),ze=(e,t)=>{const n=e.clients.get(t.client);return void 0!==n&&null!==((e,t)=>{let n=0,r=e.length-1;for(;n<=r;){const i=a.floor((n+r)/2),s=e[i],o=s.clock;if(o<=t){if(t<o+s.len)return i;n=i+1}else r=i-1}return null})(n,t.clock)},$e=e=>{e.clients.forEach(e=>{let t,n;for(e.sort((e,t)=>e.clock-t.clock),t=1,n=1;t<e.length;t++){const r=e[n-1],i=e[t];r.clock+r.len>=i.clock?e[n-1]=new Ye(r.clock,a.max(r.len,i.clock+i.len-r.clock)):(n<t&&(e[n]=i),n++)}e.length=n})},Je=e=>{const t=new qe;for(let n=0;n<e.length;n++)e[n].clients.forEach((r,i)=>{if(!t.clients.has(i)){const s=r.slice();for(let t=n+1;t<e.length;t++)a.appendTo(s,e[t].clients.get(i)||[]);t.clients.set(i,s)}});return $e(t),t},Qe=(e,t,n,r)=>{a.setIfUndefined(e.clients,t,()=>[]).push(new Ye(n,r))},Ge=()=>new qe,Xe=(e,t)=>{a.writeVarUint(e.restEncoder,t.clients.size),a.from(t.clients.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{e.resetDsCurVal(),a.writeVarUint(e.restEncoder,t);const r=n.length;a.writeVarUint(e.restEncoder,r);for(let i=0;i<r;i++){const t=n[i];e.writeDsClock(t.clock),e.writeDsLen(t.len)}})},Ze=e=>{const t=new qe,n=a.readVarUint(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();const n=a.readVarUint(e.restDecoder),r=a.readVarUint(e.restDecoder);if(r>0){const i=a.setIfUndefined(t.clients,n,()=>[]);for(let t=0;t<r;t++)i.push(new Ye(e.readDsClock(),e.readDsLen()))}}return t},et=(e,t,n)=>{const r=new qe,i=a.readVarUint(e.restDecoder);for(let s=0;s<i;s++){e.resetDsCurVal();const i=a.readVarUint(e.restDecoder),s=a.readVarUint(e.restDecoder),o=n.clients.get(i)||[],c=qt(n,i);for(let n=0;n<s;n++){const n=e.readDsClock(),s=n+e.readDsLen();if(n<c){c<s&&Qe(r,i,c,s-c);let e=zt(o,n),a=o[e];for(!a.deleted&&a.id.clock<n&&(o.splice(e+1,0,Hr(t,a,n-a.id.clock)),e++);e<o.length&&(a=o[e++],a.id.clock<s);)a.deleted||(s<a.id.clock+a.length&&o.splice(e,0,Hr(t,a,s-a.id.clock)),a.delete(t))}else Qe(r,i,n,s-n)}}if(r.clients.size>0){const e=new dt;return a.writeVarUint(e.restEncoder,0),Xe(e,r),e.toUint8Array()}return null},tt=a.uint32,nt=class e extends a.ObservableV2{constructor({guid:e=a.uuidv4(),collectionid:t=null,gc:n=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:s=!1,shouldLoad:o=!0}={}){super(),this.gc=n,this.gcFilter=r,this.clientID=tt(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new Wt,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=o,this.autoLoad=s,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=a.create(e=>{this.on("load",()=>{this.isLoaded=!0,e(this)})});const c=()=>a.create(e=>{const t=n=>{void 0!==n&&!0!==n||(this.off("sync",t),e())};this.on("sync",t)});this.on("sync",e=>{!1===e&&this.isSynced&&(this.whenSynced=c()),this.isSynced=void 0===e||!0===e,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const e=this._item;null===e||this.shouldLoad||sn(e.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(a.from(this.subdocs).map(e=>e.guid))}transact(e,t=null){return sn(this,e,t)}get(e,t=Dn){const n=a.setIfUndefined(this.share,e,()=>{const e=new t;return e._integrate(this,null),e}),r=n.constructor;if(t!==Dn&&r!==t){if(r===Dn){const r=new t;r._map=n._map,n._map.forEach(e=>{for(;null!==e;e=e.left)e.parent=r}),r._start=n._start;for(let e=r._start;null!==e;e=e.right)e.parent=r;return r._length=n._length,this.share.set(e,r),r._integrate(this,null),r}throw new Error(`Type with the name ${e} has already been defined with a different constructor`)}return n}getArray(e=""){return this.get(e,$n)}getText(e=""){return this.get(e,ur)}getMap(e=""){return this.get(e,Qn)}getXmlElement(e=""){return this.get(e,pr)}getXmlFragment(e=""){return this.get(e,gr)}toJSON(){const e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,a.from(this.subdocs).forEach(e=>e.destroy());const t=this._item;if(null!==t){this._item=null;const n=t.content;n.doc=new e({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,sn(t.parent.doc,e=>{const r=n.doc;t.deleted||e.subdocsAdded.add(r),e.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}},rt=class{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return a.readVarUint(this.restDecoder)}readDsLen(){return a.readVarUint(this.restDecoder)}},it=class extends rt{readLeftID(){return xt(a.readVarUint(this.restDecoder),a.readVarUint(this.restDecoder))}readRightID(){return xt(a.readVarUint(this.restDecoder),a.readVarUint(this.restDecoder))}readClient(){return a.readVarUint(this.restDecoder)}readInfo(){return a.readUint8(this.restDecoder)}readString(){return a.readVarString(this.restDecoder)}readParentInfo(){return 1===a.readVarUint(this.restDecoder)}readTypeRef(){return a.readVarUint(this.restDecoder)}readLen(){return a.readVarUint(this.restDecoder)}readAny(){return a.readAny(this.restDecoder)}readBuf(){return a.copyUint8Array(a.readVarUint8Array(this.restDecoder))}readJSON(){return JSON.parse(a.readVarString(this.restDecoder))}readKey(){return a.readVarString(this.restDecoder)}},st=class{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=a.readVarUint(this.restDecoder),this.dsCurrVal}readDsLen(){const e=a.readVarUint(this.restDecoder)+1;return this.dsCurrVal+=e,e}},ot=class extends st{constructor(e){super(e),this.keys=[],a.readVarUint(e),this.keyClockDecoder=new a.IntDiffOptRleDecoder(a.readVarUint8Array(e)),this.clientDecoder=new a.UintOptRleDecoder(a.readVarUint8Array(e)),this.leftClockDecoder=new a.IntDiffOptRleDecoder(a.readVarUint8Array(e)),this.rightClockDecoder=new a.IntDiffOptRleDecoder(a.readVarUint8Array(e)),this.infoDecoder=new a.RleDecoder(a.readVarUint8Array(e),a.readUint8),this.stringDecoder=new a.StringDecoder(a.readVarUint8Array(e)),this.parentInfoDecoder=new a.RleDecoder(a.readVarUint8Array(e),a.readUint8),this.typeRefDecoder=new a.UintOptRleDecoder(a.readVarUint8Array(e)),this.lenDecoder=new a.UintOptRleDecoder(a.readVarUint8Array(e))}readLeftID(){return new Et(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new Et(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return 1===this.parentInfoDecoder.read()}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return a.readAny(this.restDecoder)}readBuf(){return a.readVarUint8Array(this.restDecoder)}readJSON(){return a.readAny(this.restDecoder)}readKey(){const e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{const e=this.stringDecoder.read();return this.keys.push(e),e}}},at=class{constructor(){this.restEncoder=a.createEncoder()}toUint8Array(){return a.toUint8Array(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){a.writeVarUint(this.restEncoder,e)}writeDsLen(e){a.writeVarUint(this.restEncoder,e)}},ct=class extends at{writeLeftID(e){a.writeVarUint(this.restEncoder,e.client),a.writeVarUint(this.restEncoder,e.clock)}writeRightID(e){a.writeVarUint(this.restEncoder,e.client),a.writeVarUint(this.restEncoder,e.clock)}writeClient(e){a.writeVarUint(this.restEncoder,e)}writeInfo(e){a.writeUint8(this.restEncoder,e)}writeString(e){a.writeVarString(this.restEncoder,e)}writeParentInfo(e){a.writeVarUint(this.restEncoder,e?1:0)}writeTypeRef(e){a.writeVarUint(this.restEncoder,e)}writeLen(e){a.writeVarUint(this.restEncoder,e)}writeAny(e){a.writeAny(this.restEncoder,e)}writeBuf(e){a.writeVarUint8Array(this.restEncoder,e)}writeJSON(e){a.writeVarString(this.restEncoder,JSON.stringify(e))}writeKey(e){a.writeVarString(this.restEncoder,e)}},lt=class{constructor(){this.restEncoder=a.createEncoder(),this.dsCurrVal=0}toUint8Array(){return a.toUint8Array(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const t=e-this.dsCurrVal;this.dsCurrVal=e,a.writeVarUint(this.restEncoder,t)}writeDsLen(e){0===e&&a.unexpectedCase(),a.writeVarUint(this.restEncoder,e-1),this.dsCurrVal+=e}},dt=class extends lt{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new a.IntDiffOptRleEncoder,this.clientEncoder=new a.UintOptRleEncoder,this.leftClockEncoder=new a.IntDiffOptRleEncoder,this.rightClockEncoder=new a.IntDiffOptRleEncoder,this.infoEncoder=new a.RleEncoder(a.writeUint8),this.stringEncoder=new a.StringEncoder,this.parentInfoEncoder=new a.RleEncoder(a.writeUint8),this.typeRefEncoder=new a.UintOptRleEncoder,this.lenEncoder=new a.UintOptRleEncoder}toUint8Array(){const e=a.createEncoder();return a.writeVarUint(e,0),a.writeVarUint8Array(e,this.keyClockEncoder.toUint8Array()),a.writeVarUint8Array(e,this.clientEncoder.toUint8Array()),a.writeVarUint8Array(e,this.leftClockEncoder.toUint8Array()),a.writeVarUint8Array(e,this.rightClockEncoder.toUint8Array()),a.writeVarUint8Array(e,a.toUint8Array(this.infoEncoder)),a.writeVarUint8Array(e,this.stringEncoder.toUint8Array()),a.writeVarUint8Array(e,a.toUint8Array(this.parentInfoEncoder)),a.writeVarUint8Array(e,this.typeRefEncoder.toUint8Array()),a.writeVarUint8Array(e,this.lenEncoder.toUint8Array()),a.writeUint8Array(e,a.toUint8Array(this.restEncoder)),a.toUint8Array(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(e?1:0)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){a.writeAny(this.restEncoder,e)}writeBuf(e){a.writeVarUint8Array(this.restEncoder,e)}writeJSON(e){a.writeAny(this.restEncoder,e)}writeKey(e){const t=this.keyMap.get(e);void 0===t?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t)}},ht=(e,t,n)=>{const r=new Map;n.forEach((e,n)=>{qt(t,n)>e&&r.set(n,e)}),Yt(t).forEach((e,t)=>{n.has(t)||r.set(t,0)}),a.writeVarUint(e.restEncoder,r.size),a.from(r.entries()).sort((e,t)=>t[0]-e[0]).forEach(([n,r])=>{((e,t,n,r)=>{r=a.max(r,t[0].id.clock);const i=zt(t,r);a.writeVarUint(e.restEncoder,t.length-i),e.writeClient(n),a.writeVarUint(e.restEncoder,r);const s=t[i];s.write(e,r-s.id.clock);for(let o=i+1;o<t.length;o++)t[o].write(e,0)})(e,t.clients.get(n),n,r)})},ut=(e,t,n,r=new ot(e))=>sn(t,e=>{e.local=!1;let t=!1;const n=e.doc,i=n.store,s=((e,t)=>{const n=a.create$3(),r=a.readVarUint(e.restDecoder);for(let i=0;i<r;i++){const r=a.readVarUint(e.restDecoder),i=new Array(r),s=e.readClient();let o=a.readVarUint(e.restDecoder);n.set(s,{i:0,refs:i});for(let n=0;n<r;n++){const r=e.readInfo();switch(31&r){case 0:{const t=e.readLen();i[n]=new vr(xt(s,o),t),o+=t;break}case 10:{const t=a.readVarUint(e.restDecoder);i[n]=new $r(xt(s,o),t),o+=t;break}default:{const a=!(192&r),c=new qr(xt(s,o),null,128&~r?null:e.readLeftID(),null,64&~r?null:e.readRightID(),a?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,!a||32&~r?null:e.readString(),Kr(e,r));i[n]=c,o+=c.length}}}}return n})(r,n),o=((e,t,n)=>{const r=[];let i=a.from(n.keys()).sort((e,t)=>e-t);if(0===i.length)return null;const s=()=>{if(0===i.length)return null;let e=n.get(i[i.length-1]);for(;e.refs.length===e.i;){if(i.pop(),!(i.length>0))return null;e=n.get(i[i.length-1])}return e};let o=s();if(null===o)return null;const c=new Wt,l=new Map,d=(e,t)=>{const n=l.get(e);(null==n||n>t)&&l.set(e,t)};let h=o.refs[o.i++];const u=new Map,f=()=>{for(const e of r){const t=e.id.client,r=n.get(t);r?(r.i--,c.clients.set(t,r.refs.slice(r.i)),n.delete(t),r.i=0,r.refs=[]):c.clients.set(t,[e]),i=i.filter(e=>e!==t)}r.length=0};for(;;){if(h.constructor!==$r){const i=a.setIfUndefined(u,h.id.client,()=>qt(t,h.id.client))-h.id.clock;if(i<0)r.push(h),d(h.id.client,h.id.clock-1),f();else{const s=h.getMissing(e,t);if(null!==s){r.push(h);const e=n.get(s)||{refs:[],i:0};if(e.refs.length!==e.i){h=e.refs[e.i++];continue}d(s,qt(t,s)),f()}else(0===i||i<h.length)&&(h.integrate(e,i),u.set(h.id.client,h.id.clock+h.length))}}if(r.length>0)h=r.pop();else if(null!==o&&o.i<o.refs.length)h=o.refs[o.i++];else{if(o=s(),null===o)break;h=o.refs[o.i++]}}if(c.clients.size>0){const e=new dt;return ht(e,c,new Map),a.writeVarUint(e.restEncoder,0),{missing:l,update:e.toUint8Array()}}return null})(e,i,s),c=i.pendingStructs;if(c){for(const[e,n]of c.missing)if(n<qt(i,e)){t=!0;break}if(o){for(const[e,t]of o.missing){const n=c.missing.get(e);(null==n||n>t)&&c.missing.set(e,t)}c.update=gn([c.update,o.update])}}else i.pendingStructs=o;const l=et(r,e,i);if(i.pendingDs){const t=new ot(a.createDecoder(i.pendingDs));a.readVarUint(t.restDecoder);const n=et(t,e,i);i.pendingDs=l&&n?gn([l,n]):l||n}else i.pendingDs=l;if(t){const t=i.pendingStructs.update;i.pendingStructs=null,ft(e.doc,t)}},n,!1),ft=(e,t,n,r=ot)=>{const i=a.createDecoder(t);ut(i,e,n,new r(i))},gt=(e,t,n)=>ft(e,t,n,it),pt=(e,t,n=new Map)=>{ht(e,t.store,n),Xe(e,(e=>{const t=Ge();return e.clients.forEach((e,n)=>{const r=[];for(let t=0;t<e.length;t++){const n=e[t];if(n.deleted){const i=n.id.clock;let s=n.length;if(t+1<e.length)for(let n=e[t+1];t+1<e.length&&n.deleted;n=e[1+ ++t])s+=n.length;r.push(new Ye(i,s))}}r.length>0&&t.clients.set(n,r)}),t})(t.store))},mt=(e,t)=>((e,t=new Uint8Array([0]),n=new dt)=>{const r=yt(t);pt(n,e,r);const i=[n.toUint8Array()];if(e.store.pendingDs&&i.push(e.store.pendingDs),e.store.pendingStructs&&i.push(pn(e.store.pendingStructs.update,t)),i.length>1){if(n.constructor===ct)return un(i.map((e,t)=>0===t?e:bn(e)));if(n.constructor===dt)return gn(i)}return i[0]})(e,t,new ct),yt=e=>(e=>{const t=new Map,n=a.readVarUint(e.restDecoder);for(let r=0;r<n;r++){const n=a.readVarUint(e.restDecoder),r=a.readVarUint(e.restDecoder);t.set(n,r)}return t})(new rt(a.createDecoder(e))),wt=(e,t)=>(a.writeVarUint(e.restEncoder,t.size),a.from(t.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{a.writeVarUint(e.restEncoder,t),a.writeVarUint(e.restEncoder,n)}),e),bt=(e,t=new lt)=>(e instanceof Map?wt(t,e):((e,t)=>{wt(e,Yt(t.store))})(t,e),t.toUint8Array()),vt=class{constructor(){this.l=[]}},_t=()=>new vt,St=(e,t)=>e.l.push(t),kt=(e,t)=>{const n=e.l;n.length;e.l=n.filter(e=>t!==e),e.l.length},Ct=(e,t,n)=>a.callAll(e.l,[t,n]),Et=class{constructor(e,t){this.client=e,this.clock=t}},At=(e,t)=>e===t||null!==e&&null!==t&&e.client===t.client&&e.clock===t.clock,xt=(e,t)=>new Et(e,t),Tt=(e,t)=>{a.writeVarUint(e,t.client),a.writeVarUint(e,t.clock)},Rt=e=>xt(a.readVarUint(e),a.readVarUint(e)),Dt=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw a.unexpectedCase()},Ot=(e,t)=>{for(;null!==t;){if(t.parent===e)return!0;t=t.parent._item}return!1},Ut=class{constructor(e,t,n,r=0){this.type=e,this.tname=t,this.item=n,this.assoc=r}},Pt=class{constructor(e,t,n=0){this.type=e,this.index=t,this.assoc=n}},Lt=(e,t,n)=>{let r=null,i=null;return null===e._item?i=Dt(e):r=xt(e._item.id.client,e._item.id.clock),new Ut(r,i,t,n)},Mt=(e,t,n=0)=>{let r=e._start;if(n<0){if(0===t)return Lt(e,null,n);t--}for(;null!==r;){if(!r.deleted&&r.countable){if(r.length>t)return Lt(e,xt(r.id.client,r.id.clock+t),n);t-=r.length}if(null===r.right&&n<0)return Lt(e,r.lastId,n);r=r.right}return Lt(e,null,n)},It=e=>{const t=a.createEncoder();return((e,t)=>{const{type:n,tname:r,item:i,assoc:s}=t;if(null!==i)a.writeVarUint(e,0),Tt(e,i);else if(null!==r)a.writeUint8(e,1),a.writeVarString(e,r);else{if(null===n)throw a.unexpectedCase();a.writeUint8(e,2),Tt(e,n)}a.writeVarInt(e,s)})(t,e),a.toUint8Array(t)},Nt=e=>(e=>{let t=null,n=null,r=null;switch(a.readVarUint(e)){case 0:r=Rt(e);break;case 1:n=a.readVarString(e);break;case 2:t=Rt(e)}const i=a.hasContent(e)?a.readVarInt(e):0;return new Ut(t,n,r,i)})(a.createDecoder(e)),jt=(e,t,n=!0)=>{const r=t.store,i=e.item,s=e.type,o=e.tname,c=e.assoc;let l=null,d=0;if(null!==i){if(qt(r,i.client)<=i.clock)return null;const e=n?Fr(r,i):((e,t)=>{const n=$t(e,t);return{item:n,diff:t.clock-n.id.clock}})(r,i),t=e.item;if(!(t instanceof qr))return null;if(l=t.parent,null===l._item||!l._item.deleted){d=t.deleted||!t.countable?0:e.diff+(c>=0?0:1);let n=t.left;for(;null!==n;)!n.deleted&&n.countable&&(d+=n.length),n=n.left}}else{if(null!==o)l=t.get(o);else{if(null===s)throw a.unexpectedCase();{if(qt(r,s.client)<=s.clock)return null;const{item:e}=n?Fr(r,s):{item:$t(r,s)};if(!(e instanceof qr&&e.content instanceof Vr))return null;l=e.content.type}}d=c>=0?l._length:0}return((e,t,n=0)=>new Pt(e,t,n))(l,d,e.assoc)},Vt=(e,t)=>e===t||null!==e&&null!==t&&e.tname===t.tname&&At(e.item,t.item)&&At(e.type,t.type)&&e.assoc===t.assoc,Ft=class{constructor(e,t){this.ds=e,this.sv=t}},Bt=(We=Ge(),new Ft(We,new Map),(e,t)=>void 0===t?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!ze(t.ds,e.id)),Ht=(e,t)=>{const n=a.setIfUndefined(e.meta,Ht,a.create$2),r=e.doc.store;n.has(t)||(t.sv.forEach((t,n)=>{t<qt(r,n)&&Qt(e,xt(n,t))}),Ke(e,t.ds,e=>{}),n.add(t))},Wt=class{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}},Yt=e=>{const t=new Map;return e.clients.forEach((e,n)=>{const r=e[e.length-1];t.set(n,r.id.clock+r.length)}),t},qt=(e,t)=>{const n=e.clients.get(t);if(void 0===n)return 0;const r=n[n.length-1];return r.id.clock+r.length},Kt=(e,t)=>{let n=e.clients.get(t.id.client);if(void 0===n)n=[],e.clients.set(t.id.client,n);else{const e=n[n.length-1];if(e.id.clock+e.length!==t.id.clock)throw a.unexpectedCase()}n.push(t)},zt=(e,t)=>{let n=0,r=e.length-1,i=e[r],s=i.id.clock;if(s===t)return r;let o=a.floor(t/(s+i.length-1)*r);for(;n<=r;){if(i=e[o],s=i.id.clock,s<=t){if(t<s+i.length)return o;n=o+1}else r=o-1;o=a.floor((n+r)/2)}throw a.unexpectedCase()},$t=(e,t)=>{const n=e.clients.get(t.client);return n[zt(n,t.clock)]},Jt=(e,t,n)=>{const r=zt(t,n),i=t[r];return i.id.clock<n&&i instanceof qr?(t.splice(r+1,0,Hr(e,i,n-i.id.clock)),r+1):r},Qt=(e,t)=>{const n=e.doc.store.clients.get(t.client);return n[Jt(e,n,t.clock)]},Gt=(e,t,n)=>{const r=t.clients.get(n.client),i=zt(r,n.clock),s=r[i];return n.clock!==s.id.clock+s.length-1&&s.constructor!==vr&&r.splice(i+1,0,Hr(e,s,n.clock-s.id.clock+1)),s},Xt=(e,t,n,r,i)=>{if(0===r)return;const s=n+r;let o,a=Jt(e,t,n);do{o=t[a++],s<o.id.clock+o.length&&Jt(e,t,s),i(o)}while(a<t.length&&t[a].id.clock<s)},Zt=class{constructor(e,t,n){this.doc=e,this.deleteSet=new qe,this.beforeState=Yt(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=t,this.meta=new Map,this.local=n,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}},en=(e,t)=>!(0===t.deleteSet.clients.size&&!a.any(t.afterState,(e,n)=>t.beforeState.get(n)!==e))&&($e(t.deleteSet),((e,t)=>{ht(e,t.doc.store,t.beforeState)})(e,t),Xe(e,t.deleteSet),!0),tn=(e,t,n)=>{const r=t._item;(null===r||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&a.setIfUndefined(e.changed,t,a.create$2).add(n)},nn=(e,t)=>{let n=e[t],r=e[t-1],i=t;for(;i>0&&(r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n));n=r,r=e[--i-1])n instanceof qr&&null!==n.parentSub&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);const s=t-i;return s&&e.splice(t+1-s,s),s},rn=(e,t)=>{if(t<e.length){const n=e[t],r=n.doc,i=r.store,s=n.deleteSet,o=n._mergeStructs;try{$e(s),n.afterState=Yt(n.doc.store),r.emit("beforeObserverCalls",[n,r]);const e=[];n.changed.forEach((t,r)=>e.push(()=>{null!==r._item&&r._item.deleted||r._callObserver(n,t)})),e.push(()=>{n.changedParentTypes.forEach((t,r)=>{r._dEH.l.length>0&&(null===r._item||!r._item.deleted)&&((t=t.filter(e=>null===e.target._item||!e.target._item.deleted)).forEach(e=>{e.currentTarget=r,e._path=null}),t.sort((e,t)=>e.path.length-t.path.length),e.push(()=>{Ct(r._dEH,t,n)}))}),e.push(()=>r.emit("afterTransaction",[n,r])),e.push(()=>{n._needFormattingCleanup&&lr(n)})}),a.callAll(e,[])}finally{r.gc&&((e,t,n)=>{for(const[r,i]of e.clients.entries()){const e=t.clients.get(r);for(let r=i.length-1;r>=0;r--){const s=i[r],o=s.clock+s.len;for(let r=zt(e,s.clock),i=e[r];r<e.length&&i.id.clock<o;i=e[++r]){const i=e[r];if(s.clock+s.len<=i.id.clock)break;i instanceof qr&&i.deleted&&!i.keep&&n(i)&&i.gc(t,!1)}}}})(s,i,r.gcFilter),((e,t)=>{e.clients.forEach((e,n)=>{const r=t.clients.get(n);for(let t=e.length-1;t>=0;t--){const n=e[t];for(let e=a.min(r.length-1,1+zt(r,n.clock+n.len-1)),t=r[e];e>0&&t.id.clock>=n.clock;t=r[e])e-=1+nn(r,e)}})})(s,i),n.afterState.forEach((e,t)=>{const r=n.beforeState.get(t)||0;if(r!==e){const e=i.clients.get(t),n=a.max(zt(e,r),1);for(let t=e.length-1;t>=n;)t-=1+nn(e,t)}});for(let e=o.length-1;e>=0;e--){const{client:t,clock:n}=o[e].id,r=i.clients.get(t),s=zt(r,n);s+1<r.length&&nn(r,s+1)>1||s>0&&nn(r,s)}if(n.local||n.afterState.get(r.clientID)===n.beforeState.get(r.clientID)||(a.print(a.ORANGE,a.BOLD,"[yjs] ",a.UNBOLD,a.RED,"Changed the client-id because another client seems to be using it."),r.clientID=tt()),r.emit("afterTransactionCleanup",[n,r]),r._observers.has("update")){const e=new ct;en(e,n)&&r.emit("update",[e.toUint8Array(),n.origin,r,n])}if(r._observers.has("updateV2")){const e=new dt;en(e,n)&&r.emit("updateV2",[e.toUint8Array(),n.origin,r,n])}const{subdocsAdded:c,subdocsLoaded:l,subdocsRemoved:d}=n;(c.size>0||d.size>0||l.size>0)&&(c.forEach(e=>{e.clientID=r.clientID,null==e.collectionid&&(e.collectionid=r.collectionid),r.subdocs.add(e)}),d.forEach(e=>r.subdocs.delete(e)),r.emit("subdocs",[{loaded:l,added:c,removed:d},r,n]),d.forEach(e=>e.destroy())),e.length<=t+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,e])):rn(e,t+1)}}},sn=(e,t,n=null,r=!0)=>{const i=e._transactionCleanups;let s=!1,o=null;null===e._transaction&&(s=!0,e._transaction=new Zt(e,n,r),i.push(e._transaction),1===i.length&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(s){const t=e._transaction===i[0];e._transaction=null,t&&rn(i,0)}}return o},on=class{constructor(e,t){this.insertions=t,this.deletions=e,this.meta=new Map}},an=(e,t,n)=>{Ke(e,n.deletions,n=>{n instanceof qr&&t.scope.some(t=>t===e.doc||Ot(t,n))&&Br(n,!1)})},cn=(e,t,n)=>{let r=null;const i=e.doc,s=e.scope;sn(i,n=>{for(;t.length>0&&null===e.currStackItem;){const r=i.store,o=t.pop(),a=new Set,c=[];let l=!1;Ke(n,o.insertions,e=>{if(e instanceof qr){if(null!==e.redone){let{item:t,diff:i}=Fr(r,e.id);i>0&&(t=Qt(n,xt(t.id.client,t.id.clock+i))),e=t}!e.deleted&&s.some(t=>t===n.doc||Ot(t,e))&&c.push(e)}}),Ke(n,o.deletions,e=>{e instanceof qr&&s.some(t=>t===n.doc||Ot(t,e))&&!ze(o.insertions,e.id)&&a.add(e)}),a.forEach(t=>{l=null!==Yr(n,t,a,o.insertions,e.ignoreRemoteMapChanges,e)||l});for(let t=c.length-1;t>=0;t--){const r=c[t];e.deleteFilter(r)&&(r.delete(n),l=!0)}e.currStackItem=l?o:null}n.changed.forEach((e,t)=>{e.has(null)&&t._searchMarker&&(t._searchMarker.length=0)}),r=n},e);const o=e.currStackItem;if(null!=o){const t=r.changedParentTypes;e.emit("stack-item-popped",[{stackItem:o,type:n,changedParentTypes:t,origin:e},e]),e.currStackItem=null}return o},ln=class extends a.ObservableV2{constructor(e,{captureTimeout:t=500,captureTransaction:n=e=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:s=!1,doc:o=(a.isArray(e)?e[0].doc:e instanceof nt?e:e.doc)}={}){super(),this.scope=[],this.doc=o,this.addToScope(e),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=n,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=s,this.captureTimeout=t,this.afterTransactionHandler=e=>{if(!(this.captureTransaction(e)&&this.scope.some(t=>e.changedParentTypes.has(t)||t===this.doc)&&(this.trackedOrigins.has(e.origin)||e.origin&&this.trackedOrigins.has(e.origin.constructor))))return;const t=this.undoing,n=this.redoing,r=t?this.redoStack:this.undoStack;t?this.stopCapturing():n||this.clear(!1,!0);const i=new qe;e.afterState.forEach((t,n)=>{const r=e.beforeState.get(n)||0,s=t-r;s>0&&Qe(i,n,r,s)});const s=a.getUnixTime();let o=!1;if(this.lastChange>0&&s-this.lastChange<this.captureTimeout&&r.length>0&&!t&&!n){const t=r[r.length-1];t.deletions=Je([t.deletions,e.deleteSet]),t.insertions=Je([t.insertions,i])}else r.push(new on(e.deleteSet,i)),o=!0;t||n||(this.lastChange=s),Ke(e,e.deleteSet,t=>{t instanceof qr&&this.scope.some(n=>n===e.doc||Ot(n,t))&&Br(t,!0)});const c=[{stackItem:r[r.length-1],origin:e.origin,type:t?"redo":"undo",changedParentTypes:e.changedParentTypes},this];o?this.emit("stack-item-added",c):this.emit("stack-item-updated",c)},this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",()=>{this.destroy()})}addToScope(e){const t=new Set(this.scope);(e=a.isArray(e)?e:[e]).forEach(e=>{t.has(e)||(t.add(e),(e instanceof Dn?e.doc!==this.doc:e!==this.doc)&&a.warn("[yjs#509] Not same Y.Doc"),this.scope.push(e))})}addTrackedOrigin(e){this.trackedOrigins.add(e)}removeTrackedOrigin(e){this.trackedOrigins.delete(e)}clear(e=!0,t=!0){(e&&this.canUndo()||t&&this.canRedo())&&this.doc.transact(n=>{e&&(this.undoStack.forEach(e=>an(n,this,e)),this.undoStack=[]),t&&(this.redoStack.forEach(e=>an(n,this,e)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:e,redoStackCleared:t}])})}stopCapturing(){this.lastChange=0}undo(){let e;this.undoing=!0;try{e=cn(this,this.undoStack,"undo")}finally{this.undoing=!1}return e}redo(){let e;this.redoing=!0;try{e=cn(this,this.redoStack,"redo")}finally{this.redoing=!1}return e}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),super.destroy()}};var dn=class{constructor(e,t){this.gen=function*(e){const t=a.readVarUint(e.restDecoder);for(let n=0;n<t;n++){const t=a.readVarUint(e.restDecoder),n=e.readClient();let r=a.readVarUint(e.restDecoder);for(let i=0;i<t;i++){const t=e.readInfo();if(10===t){const t=a.readVarUint(e.restDecoder);yield new $r(xt(n,r),t),r+=t}else if(31&t){const i=!(192&t),s=new qr(xt(n,r),null,128&~t?null:e.readLeftID(),null,64&~t?null:e.readRightID(),i?e.readParentInfo()?e.readString():e.readLeftID():null,!i||32&~t?null:e.readString(),Kr(e,t));yield s,r+=s.length}else{const t=e.readLen();yield new vr(xt(n,r),t),r+=t}}}}(e),this.curr=null,this.done=!1,this.filterSkips=t,this.next()}next(){do{this.curr=this.gen.next().value||null}while(this.filterSkips&&null!==this.curr&&this.curr.constructor===$r);return this.curr}},hn=class{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}},un=e=>gn(e,it,ct),fn=(e,t)=>{if(e.constructor===vr){const{client:n,clock:r}=e.id;return new vr(xt(n,r+t),e.length-t)}if(e.constructor===$r){const{client:n,clock:r}=e.id;return new $r(xt(n,r+t),e.length-t)}{const n=e,{client:r,clock:i}=n.id;return new qr(xt(r,i+t),null,xt(r,i+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},gn=(e,t=ot,n=dt)=>{if(1===e.length)return e[0];const r=e.map(e=>new t(a.createDecoder(e)));let i=r.map(e=>new dn(e,!0)),s=null;const o=new n,c=new hn(o);for(;i=i.filter(e=>null!==e.curr),i.sort((e,t)=>{if(e.curr.id.client===t.curr.id.client){const n=e.curr.id.clock-t.curr.id.clock;return 0===n?e.curr.constructor===t.curr.constructor?0:e.curr.constructor===$r?1:-1:n}return t.curr.id.client-e.curr.id.client}),0!==i.length;){const e=i[0],t=e.curr.id.client;if(null!==s){let n=e.curr,r=!1;for(;null!==n&&n.id.clock+n.length<=s.struct.id.clock+s.struct.length&&n.id.client>=s.struct.id.client;)n=e.next(),r=!0;if(null===n||n.id.client!==t||r&&n.id.clock>s.struct.id.clock+s.struct.length)continue;if(t!==s.struct.id.client)yn(c,s.struct,s.offset),s={struct:n,offset:0},e.next();else if(s.struct.id.clock+s.struct.length<n.id.clock)if(s.struct.constructor===$r)s.struct.length=n.id.clock+n.length-s.struct.id.clock;else{yn(c,s.struct,s.offset);const e=n.id.clock-s.struct.id.clock-s.struct.length;s={struct:new $r(xt(t,s.struct.id.clock+s.struct.length),e),offset:0}}else{const t=s.struct.id.clock+s.struct.length-n.id.clock;t>0&&(s.struct.constructor===$r?s.struct.length-=t:n=fn(n,t)),s.struct.mergeWith(n)||(yn(c,s.struct,s.offset),s={struct:n,offset:0},e.next())}}else s={struct:e.curr,offset:0},e.next();for(let n=e.curr;null!==n&&n.id.client===t&&n.id.clock===s.struct.id.clock+s.struct.length&&n.constructor!==$r;n=e.next())yn(c,s.struct,s.offset),s={struct:n,offset:0}}null!==s&&(yn(c,s.struct,s.offset),s=null),wn(c);const l=r.map(e=>Ze(e)),d=Je(l);return Xe(o,d),o.toUint8Array()},pn=(e,t,n=ot,r=dt)=>{const i=yt(t),s=new r,o=new hn(s),c=new n(a.createDecoder(e)),l=new dn(c,!1);for(;l.curr;){const e=l.curr,t=e.id.client,n=i.get(t)||0;if(l.curr.constructor!==$r)if(e.id.clock+e.length>n)for(yn(o,e,a.max(n-e.id.clock,0)),l.next();l.curr&&l.curr.id.client===t;)yn(o,l.curr,0),l.next();else for(;l.curr&&l.curr.id.client===t&&l.curr.id.clock+l.curr.length<=n;)l.next();else l.next()}wn(o);const d=Ze(c);return Xe(s,d),s.toUint8Array()},mn=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:a.toUint8Array(e.encoder.restEncoder)}),e.encoder.restEncoder=a.createEncoder(),e.written=0)},yn=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&mn(e),0===e.written&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),a.writeVarUint(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},wn=e=>{mn(e);const t=e.encoder.restEncoder;a.writeVarUint(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){const r=e.clientStructs[n];a.writeVarUint(t,r.written),a.writeUint8Array(t,r.restEncoder)}},bn=e=>((e,t,n,r)=>{const i=new n(a.createDecoder(e)),s=new dn(i,!1),o=new r,c=new hn(o);for(let a=s.curr;null!==a;a=s.next())yn(c,t(a),0);wn(c);const l=Ze(i);return Xe(o,l),o.toUint8Array()})(e,a.id,ot,ct),vn="You must not compute changes after the event-handler fired.",_n=class{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Sn(this.currentTarget,this.target))}deletes(e){return ze(this.transaction.deleteSet,e.id)}get keys(){if(null===this._keys){if(0===this.transaction.doc._transactionCleanups.length)throw a.create$1(vn);const e=new Map,t=this.target;this.transaction.changed.get(t).forEach(n=>{if(null!==n){const r=t._map.get(n);let i,s;if(this.adds(r)){let e=r.left;for(;null!==e&&this.adds(e);)e=e.left;if(this.deletes(r)){if(null===e||!this.deletes(e))return;i="delete",s=a.last(e.content.getContent())}else null!==e&&this.deletes(e)?(i="update",s=a.last(e.content.getContent())):(i="add",s=void 0)}else{if(!this.deletes(r))return;i="delete",s=a.last(r.content.getContent())}e.set(n,{action:i,oldValue:s})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(null===e){if(0===this.transaction.doc._transactionCleanups.length)throw a.create$1(vn);const t=this.target,n=a.create$2(),r=a.create$2(),i=[];if(e={added:n,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(t).has(null)){let e=null;const s=()=>{e&&i.push(e)};for(let i=t._start;null!==i;i=i.right)i.deleted?this.deletes(i)&&!this.adds(i)&&(null!==e&&void 0!==e.delete||(s(),e={delete:0}),e.delete+=i.length,r.add(i)):this.adds(i)?(null!==e&&void 0!==e.insert||(s(),e={insert:[]}),e.insert=e.insert.concat(i.content.getContent()),n.add(i)):(null!==e&&void 0!==e.retain||(s(),e={retain:0}),e.retain+=i.length);null!==e&&void 0===e.retain&&s()}this._changes=e}return e}},Sn=(e,t)=>{const n=[];for(;null!==t._item&&t!==e;){if(null!==t._item.parentSub)n.unshift(t._item.parentSub);else{let e=0,r=t._item.parent._start;for(;r!==t._item&&null!==r;)!r.deleted&&r.countable&&(e+=r.length),r=r.right;n.unshift(e)}t=t._item.parent}return n},kn=()=>{a.warn("Invalid access: Add Yjs type to a document before reading data.")},Cn=0,En=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=Cn++}},An=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=Cn++},xn=(e,t)=>{if(null===e._start||0===t||null===e._searchMarker)return null;const n=0===e._searchMarker.length?null:e._searchMarker.reduce((e,n)=>a.abs(t-e.index)<a.abs(t-n.index)?e:n);let r=e._start,i=0;for(null!==n&&(r=n.p,i=n.index,(e=>{e.timestamp=Cn++})(n));null!==r.right&&i<t;){if(!r.deleted&&r.countable){if(t<i+r.length)break;i+=r.length}r=r.right}for(;null!==r.left&&i>t;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;null!==r.left&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return null!==n&&a.abs(n.index-i)<r.parent.length/80?(An(n,r,i),n):((e,t,n)=>{if(e.length>=80){const r=e.reduce((e,t)=>e.timestamp<t.timestamp?e:t);return An(r,t,n),r}{const r=new En(t,n);return e.push(r),r}})(e._searchMarker,r,i)},Tn=(e,t,n)=>{for(let r=e.length-1;r>=0;r--){const i=e[r];if(n>0){let t=i.p;for(t.marker=!1;t&&(t.deleted||!t.countable);)t=t.left,t&&!t.deleted&&t.countable&&(i.index-=t.length);if(null===t||!0===t.marker){e.splice(r,1);continue}i.p=t,t.marker=!0}(t<i.index||n>0&&t===i.index)&&(i.index=a.max(t,i.index+n))}},Rn=(e,t,n)=>{const r=e,i=t.changedParentTypes;for(;a.setIfUndefined(i,e,()=>[]).push(n),null!==e._item;)e=e._item.parent;Ct(r._eH,n,t)},Dn=class{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=_t(),this._dEH=_t(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw a.methodUnimplemented()}clone(){throw a.methodUnimplemented()}_write(e){}get _first(){let e=this._start;for(;null!==e&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){St(this._eH,e)}observeDeep(e){St(this._dEH,e)}unobserve(e){kt(this._eH,e)}unobserveDeep(e){kt(this._dEH,e)}toJSON(){}},On=(e,t,n)=>{e.doc??kn(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let r=n-t;const i=[];let s=e._start;for(;null!==s&&r>0;){if(s.countable&&!s.deleted){const e=s.content.getContent();if(e.length<=t)t-=e.length;else{for(let n=t;n<e.length&&r>0;n++)i.push(e[n]),r--;t=0}}s=s.right}return i},Un=e=>{e.doc??kn();const t=[];let n=e._start;for(;null!==n;){if(n.countable&&!n.deleted){const e=n.content.getContent();for(let n=0;n<e.length;n++)t.push(e[n])}n=n.right}return t},Pn=(e,t)=>{let n=0,r=e._start;for(e.doc??kn();null!==r;){if(r.countable&&!r.deleted){const i=r.content.getContent();for(let r=0;r<i.length;r++)t(i[r],n++,e)}r=r.right}},Ln=(e,t)=>{const n=[];return Pn(e,(r,i)=>{n.push(t(r,i,e))}),n},Mn=e=>{let t=e._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(null===n){for(;null!==t&&t.deleted;)t=t.right;if(null===t)return{done:!0,value:void 0};n=t.content.getContent(),r=0,t=t.right}const e=n[r++];return n.length<=r&&(n=null),{done:!1,value:e}}}},In=(e,t)=>{e.doc??kn();const n=xn(e,t);let r=e._start;for(null!==n&&(r=n.p,t-=n.index);null!==r;r=r.right)if(!r.deleted&&r.countable){if(t<r.length)return r.content.getContent()[t];t-=r.length}},Nn=(e,t,n,r)=>{let i=n;const s=e.doc,o=s.clientID,a=s.store,c=null===n?t._start:n.right;let l=[];const d=()=>{l.length>0&&(i=new qr(xt(o,qt(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Rr(l)),i.integrate(e,0),l=[])};r.forEach(n=>{if(null===n)l.push(n);else switch(n.constructor){case Number:case Object:case Boolean:case Array:case String:l.push(n);break;default:switch(d(),n.constructor){case Uint8Array:case ArrayBuffer:i=new qr(xt(o,qt(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new _r(new Uint8Array(n))),i.integrate(e,0);break;case nt:i=new qr(xt(o,qt(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Cr(n)),i.integrate(e,0);break;default:if(!(n instanceof Dn))throw new Error("Unexpected content type in insert operation");i=new qr(xt(o,qt(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Vr(n)),i.integrate(e,0)}}}),d()},jn=()=>a.create$1("Length exceeded!"),Vn=(e,t,n,r)=>{if(n>t._length)throw jn();if(0===n)return t._searchMarker&&Tn(t._searchMarker,n,r.length),Nn(e,t,null,r);const i=n,s=xn(t,n);let o=t._start;for(null!==s&&(o=s.p,0===(n-=s.index)&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));null!==o;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n<o.length&&Qt(e,xt(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&Tn(t._searchMarker,i,r.length),Nn(e,t,o,r)},Fn=(e,t,n,r)=>{if(0===r)return;const i=n,s=r,o=xn(t,n);let a=t._start;for(null!==o&&(a=o.p,n-=o.index);null!==a&&n>0;a=a.right)!a.deleted&&a.countable&&(n<a.length&&Qt(e,xt(a.id.client,a.id.clock+n)),n-=a.length);for(;r>0&&null!==a;)a.deleted||(r<a.length&&Qt(e,xt(a.id.client,a.id.clock+r)),a.delete(e),r-=a.length),a=a.right;if(r>0)throw jn();t._searchMarker&&Tn(t._searchMarker,i,-s+r)},Bn=(e,t,n)=>{const r=t._map.get(n);void 0!==r&&r.delete(e)},Hn=(e,t,n,r)=>{const i=t._map.get(n)||null,s=e.doc,o=s.clientID;let a;if(null==r)a=new Rr([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:a=new Rr([r]);break;case Uint8Array:a=new _r(r);break;case nt:a=new Cr(r);break;default:if(!(r instanceof Dn))throw new Error("Unexpected content type");a=new Vr(r)}new qr(xt(o,qt(s.store,o)),i,i&&i.lastId,null,null,t,n,a).integrate(e,0)},Wn=(e,t)=>{e.doc??kn();const n=e._map.get(t);return void 0===n||n.deleted?void 0:n.content.getContent()[n.length-1]},Yn=e=>{const t={};return e.doc??kn(),e._map.forEach((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])}),t},qn=(e,t)=>{e.doc??kn();const n=e._map.get(t);return void 0!==n&&!n.deleted},Kn=e=>(e.doc??kn(),a.iteratorFilter(e._map.entries(),e=>!e[1].deleted)),zn=class extends _n{},$n=class e extends Dn{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new e;return n.push(t),n}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){const t=new e;return t.insert(0,this.toArray().map(e=>e instanceof Dn?e.clone():e)),t}get length(){return this.doc??kn(),this._length}_callObserver(e,t){super._callObserver(e,t),Rn(this,e,new zn(this,e))}insert(e,t){null!==this.doc?sn(this.doc,n=>{Vn(n,this,e,t)}):this._prelimContent.splice(e,0,...t)}push(e){null!==this.doc?sn(this.doc,t=>{((e,t,n)=>{let r=(t._searchMarker||[]).reduce((e,t)=>t.index>e.index?t:e,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;Nn(e,t,r,n)})(t,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,t=1){null!==this.doc?sn(this.doc,n=>{Fn(n,this,e,t)}):this._prelimContent.splice(e,t)}get(e){return In(this,e)}toArray(){return Un(this)}slice(e=0,t=this.length){return On(this,e,t)}toJSON(){return this.map(e=>e instanceof Dn?e.toJSON():e)}map(e){return Ln(this,e)}forEach(e){Pn(this,e)}[Symbol.iterator](){return Mn(this)}_write(e){e.writeTypeRef(Ur)}},Jn=class extends _n{constructor(e,t,n){super(e,t),this.keysChanged=n}},Qn=class e extends Dn{constructor(e){super(),this._prelimContent=null,this._prelimContent=void 0===e?new Map:new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach((e,t)=>{this.set(t,e)}),this._prelimContent=null}_copy(){return new e}clone(){const t=new e;return this.forEach((e,n)=>{t.set(n,e instanceof Dn?e.clone():e)}),t}_callObserver(e,t){Rn(this,e,new Jn(this,e,t))}toJSON(){this.doc??kn();const e={};return this._map.forEach((t,n)=>{if(!t.deleted){const r=t.content.getContent()[t.length-1];e[n]=r instanceof Dn?r.toJSON():r}}),e}get size(){return[...Kn(this)].length}keys(){return a.iteratorMap(Kn(this),e=>e[0])}values(){return a.iteratorMap(Kn(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return a.iteratorMap(Kn(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??kn(),this._map.forEach((t,n)=>{t.deleted||e(t.content.getContent()[t.length-1],n,this)})}[Symbol.iterator](){return this.entries()}delete(e){null!==this.doc?sn(this.doc,t=>{Bn(t,this,e)}):this._prelimContent.delete(e)}set(e,t){return null!==this.doc?sn(this.doc,n=>{Hn(n,this,e,t)}):this._prelimContent.set(e,t),t}get(e){return Wn(this,e)}has(e){return qn(this,e)}clear(){null!==this.doc?sn(this.doc,e=>{this.forEach(function(t,n,r){Bn(e,r,n)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(Pr)}},Gn=(e,t)=>e===t||"object"==typeof e&&"object"==typeof t&&e&&t&&a.equalFlat(e,t),Xn=class{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){if(null===this.right&&a.unexpectedCase(),this.right.content.constructor===Ar)this.right.deleted||nr(this.currentAttributes,this.right.content);else this.right.deleted||(this.index+=this.right.length);this.left=this.right,this.right=this.right.right}},Zn=(e,t,n)=>{for(;null!==t.right&&n>0;){if(t.right.content.constructor===Ar)t.right.deleted||nr(t.currentAttributes,t.right.content);else t.right.deleted||(n<t.right.length&&Qt(e,xt(t.right.id.client,t.right.id.clock+n)),t.index+=t.right.length,n-=t.right.length);t.left=t.right,t.right=t.right.right}return t},er=(e,t,n,r)=>{const i=new Map,s=r?xn(t,n):null;if(s){const t=new Xn(s.p.left,s.p,s.index,i);return Zn(e,t,n-s.index)}{const r=new Xn(null,t._start,0,i);return Zn(e,r,n)}},tr=(e,t,n,r)=>{for(;null!==n.right&&(!0===n.right.deleted||n.right.content.constructor===Ar&&Gn(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();const i=e.doc,s=i.clientID;r.forEach((r,o)=>{const a=n.left,c=n.right,l=new qr(xt(s,qt(i.store,s)),a,a&&a.lastId,c,c&&c.id,t,null,new Ar(o,r));l.integrate(e,0),n.right=l,n.forward()})},nr=(e,t)=>{const{key:n,value:r}=t;null===r?e.delete(n):e.set(n,r)},rr=(e,t)=>{for(;null!==e.right&&(e.right.deleted||e.right.content.constructor===Ar&&Gn(t[e.right.content.key]??null,e.right.content.value));)e.forward()},ir=(e,t,n,r)=>{const i=e.doc,s=i.clientID,o=new Map;for(const a in r){const c=r[a],l=n.currentAttributes.get(a)??null;if(!Gn(l,c)){o.set(a,l);const{left:r,right:d}=n;n.right=new qr(xt(s,qt(i.store,s)),r,r&&r.lastId,d,d&&d.id,t,null,new Ar(a,c)),n.right.integrate(e,0),n.forward()}}return o},sr=(e,t,n,r,i)=>{n.currentAttributes.forEach((e,t)=>{void 0===i[t]&&(i[t]=null)});const s=e.doc,o=s.clientID;rr(n,i);const a=ir(e,t,n,i),c=r.constructor===String?new Dr(r):r instanceof Dn?new Vr(r):new Er(r);let{left:l,right:d,index:h}=n;t._searchMarker&&Tn(t._searchMarker,n.index,c.getLength()),d=new qr(xt(o,qt(s.store,o)),l,l&&l.lastId,d,d&&d.id,t,null,c),d.integrate(e,0),n.right=d,n.index=h,n.forward(),tr(e,t,n,a)},or=(e,t,n,r,i)=>{const s=e.doc,o=s.clientID;rr(n,i);const a=ir(e,t,n,i);e:for(;null!==n.right&&(r>0||a.size>0&&(n.right.deleted||n.right.content.constructor===Ar));){if(!n.right.deleted)switch(n.right.content.constructor){case Ar:{const{key:t,value:s}=n.right.content,o=i[t];if(void 0!==o){if(Gn(o,s))a.delete(t);else{if(0===r)break e;a.set(t,s)}n.right.delete(e)}else n.currentAttributes.set(t,s);break}default:r<n.right.length&&Qt(e,xt(n.right.id.client,n.right.id.clock+r)),r-=n.right.length}n.forward()}if(r>0){let i="";for(;r>0;r--)i+="\n";n.right=new qr(xt(o,qt(s.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Dr(i)),n.right.integrate(e,0),n.forward()}tr(e,t,n,a)},ar=(e,t,n,r,i)=>{let s=t;const o=a.create$3();for(;s&&(!s.countable||s.deleted);){if(!s.deleted&&s.content.constructor===Ar){const e=s.content;o.set(e.key,e)}s=s.right}let c=0,l=!1;for(;t!==s;){if(n===t&&(l=!0),!t.deleted){const n=t.content;switch(n.constructor){case Ar:{const{key:s,value:a}=n,d=r.get(s)??null;o.get(s)===n&&d!==a||(t.delete(e),c++,l||(i.get(s)??null)!==a||d===a||(null===d?i.delete(s):i.set(s,d))),l||t.deleted||nr(i,n);break}}}t=t.right}return c},cr=e=>{let t=0;return sn(e.doc,n=>{let r=e._start,i=e._start,s=a.create$3();const o=a.copy(s);for(;i;){if(!1===i.deleted)if(i.content.constructor===Ar)nr(o,i.content);else t+=ar(n,r,i,s,o),s=a.copy(o),r=i;i=i.right}}),t},lr=e=>{const t=new Set,n=e.doc;for(const[r,i]of e.afterState.entries()){const s=e.beforeState.get(r)||0;i!==s&&Xt(e,n.store.clients.get(r),s,i,e=>{e.deleted||e.content.constructor!==Ar||e.constructor===vr||t.add(e.parent)})}sn(n,n=>{Ke(e,e.deleteSet,e=>{if(e instanceof vr||!e.parent._hasFormatting||t.has(e.parent))return;const r=e.parent;e.content.constructor===Ar?t.add(r):((e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===Ar){const r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}})(n,e)});for(const e of t)cr(e)})},dr=(e,t,n)=>{const r=n,i=a.copy(t.currentAttributes),s=t.right;for(;n>0&&null!==t.right;){if(!1===t.right.deleted)switch(t.right.content.constructor){case Vr:case Er:case Dr:n<t.right.length&&Qt(e,xt(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e)}t.forward()}s&&ar(e,s,t.right,i,t.currentAttributes);const o=(t.left||t.right).parent;return o._searchMarker&&Tn(o._searchMarker,t.index,-r+n),t},hr=class extends _n{constructor(e,t,n){super(e,t),this.childListChanged=!1,this.keysChanged=new Set,n.forEach(e=>{null===e?this.childListChanged=!0:this.keysChanged.add(e)})}get changes(){if(null===this._changes){const e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(null===this._delta){const e=this.target.doc,t=[];sn(e,e=>{const n=new Map,r=new Map;let i=this.target._start,s=null;const o={};let c="",l=0,d=0;const h=()=>{if(null!==s){let e=null;switch(s){case"delete":d>0&&(e={delete:d}),d=0;break;case"insert":("object"==typeof c||c.length>0)&&(e={insert:c},n.size>0&&(e.attributes={},n.forEach((t,n)=>{null!==t&&(e.attributes[n]=t)}))),c="";break;case"retain":l>0&&(e={retain:l},a.isEmpty(o)||(e.attributes=a.assign({},o))),l=0}e&&t.push(e),s=null}};for(;null!==i;){switch(i.content.constructor){case Vr:case Er:this.adds(i)?this.deletes(i)||(h(),s="insert",c=i.content.getContent()[0],h()):this.deletes(i)?("delete"!==s&&(h(),s="delete"),d+=1):i.deleted||("retain"!==s&&(h(),s="retain"),l+=1);break;case Dr:this.adds(i)?this.deletes(i)||("insert"!==s&&(h(),s="insert"),c+=i.content.str):this.deletes(i)?("delete"!==s&&(h(),s="delete"),d+=i.length):i.deleted||("retain"!==s&&(h(),s="retain"),l+=i.length);break;case Ar:{const{key:t,value:a}=i.content;if(this.adds(i)){if(!this.deletes(i)){const c=n.get(t)??null;Gn(c,a)?null!==a&&i.delete(e):("retain"===s&&h(),Gn(a,r.get(t)??null)?delete o[t]:o[t]=a)}}else if(this.deletes(i)){r.set(t,a);const e=n.get(t)??null;Gn(e,a)||("retain"===s&&h(),o[t]=e)}else if(!i.deleted){r.set(t,a);const n=o[t];void 0!==n&&(Gn(n,a)?null!==n&&i.delete(e):("retain"===s&&h(),null===a?delete o[t]:o[t]=a))}i.deleted||("insert"===s&&h(),nr(n,i.content));break}}i=i.right}for(h();t.length>0;){const e=t[t.length-1];if(void 0===e.retain||void 0!==e.attributes)break;t.pop()}}),this._delta=t}return this._delta}},ur=class e extends Dn{constructor(e){super(),this._pending=void 0!==e?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??kn(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(e=>e())}catch(n){}this._pending=null}_copy(){return new e}clone(){const t=new e;return t.applyDelta(this.toDelta()),t}_callObserver(e,t){super._callObserver(e,t);const n=new hr(this,e,t);Rn(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??kn();let e="",t=this._start;for(;null!==t;)!t.deleted&&t.countable&&t.content.constructor===Dr&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){null!==this.doc?sn(this.doc,n=>{const r=new Xn(null,this._start,0,new Map);for(let i=0;i<e.length;i++){const s=e[i];if(void 0!==s.insert){const o=t||"string"!=typeof s.insert||i!==e.length-1||null!==r.right||"\n"!==s.insert.slice(-1)?s.insert:s.insert.slice(0,-1);("string"!=typeof o||o.length>0)&&sr(n,this,r,o,s.attributes||{})}else void 0!==s.retain?or(n,this,r,s.retain,s.attributes||{}):void 0!==s.delete&&dr(n,r,s.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,t,n){this.doc??kn();const r=[],i=new Map,s=this.doc;let o="",a=this._start;function c(){if(o.length>0){const e={};let t=!1;i.forEach((n,r)=>{t=!0,e[r]=n});const n={insert:o};t&&(n.attributes=e),r.push(n),o=""}}const l=()=>{for(;null!==a;){if(Bt(a,e)||void 0!==t&&Bt(a,t))switch(a.content.constructor){case Dr:{const r=i.get("ychange");void 0===e||Bt(a,e)?void 0===t||Bt(a,t)?void 0!==r&&(c(),i.delete("ychange")):void 0!==r&&r.user===a.id.client&&"added"===r.type||(c(),i.set("ychange",n?n("added",a.id):{type:"added"})):void 0!==r&&r.user===a.id.client&&"removed"===r.type||(c(),i.set("ychange",n?n("removed",a.id):{type:"removed"})),o+=a.content.str;break}case Vr:case Er:{c();const e={insert:a.content.getContent()[0]};if(i.size>0){const t={};e.attributes=t,i.forEach((e,n)=>{t[n]=e})}r.push(e);break}case Ar:Bt(a,e)&&(c(),nr(i,a.content))}a=a.right}c()};return e||t?sn(s,n=>{e&&Ht(n,e),t&&Ht(n,t),l()},"cleanup"):l(),r}insert(e,t,n){if(t.length<=0)return;const r=this.doc;null!==r?sn(r,r=>{const i=er(r,this,e,!n);n||(n={},i.currentAttributes.forEach((e,t)=>{n[t]=e})),sr(r,this,i,t,n)}):this._pending.push(()=>this.insert(e,t,n))}insertEmbed(e,t,n){const r=this.doc;null!==r?sn(r,r=>{const i=er(r,this,e,!n);sr(r,this,i,t,n||{})}):this._pending.push(()=>this.insertEmbed(e,t,n||{}))}delete(e,t){if(0===t)return;const n=this.doc;null!==n?sn(n,n=>{dr(n,er(n,this,e,!0),t)}):this._pending.push(()=>this.delete(e,t))}format(e,t,n){if(0===t)return;const r=this.doc;null!==r?sn(r,r=>{const i=er(r,this,e,!1);null!==i.right&&or(r,this,i,t,n)}):this._pending.push(()=>this.format(e,t,n))}removeAttribute(e){null!==this.doc?sn(this.doc,t=>{Bn(t,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,t){null!==this.doc?sn(this.doc,n=>{Hn(n,this,e,t)}):this._pending.push(()=>this.setAttribute(e,t))}getAttribute(e){return Wn(this,e)}getAttributes(){return Yn(this)}_write(e){e.writeTypeRef(Lr)}},fr=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??kn()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(null!==e&&(!this._firstCall||e.deleted||!this._filter(t)))do{if(t=e.content.type,e.deleted||t.constructor!==pr&&t.constructor!==gr||null===t._start)for(;null!==e;){const t=e.next;if(null!==t){e=t;break}e=e.parent===this._root?null:e.parent._item}else e=t._start}while(null!==e&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,null===e?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}},gr=class e extends Dn{constructor(){super(),this._prelimContent=[]}get firstChild(){const e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){const t=new e;return t.insert(0,this.toArray().map(e=>e instanceof Dn?e.clone():e)),t}get length(){return this.doc??kn(),null===this._prelimContent?this._length:this._prelimContent.length}createTreeWalker(e){return new fr(this,e)}querySelector(e){e=e.toUpperCase();const t=new fr(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),a.from(new fr(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){Rn(this,e,new mr(this,t,e))}toString(){return Ln(this,e=>e.toString()).join("")}toJSON(){return this.toString()}toDOM(e=document,t={},n){const r=e.createDocumentFragment();return void 0!==n&&n._createAssociation(r,this),Pn(this,i=>{r.insertBefore(i.toDOM(e,t,n),null)}),r}insert(e,t){null!==this.doc?sn(this.doc,n=>{Vn(n,this,e,t)}):this._prelimContent.splice(e,0,...t)}insertAfter(e,t){if(null!==this.doc)sn(this.doc,n=>{const r=e&&e instanceof Dn?e._item:e;Nn(n,this,r,t)});else{const n=this._prelimContent,r=null===e?0:n.findIndex(t=>t===e)+1;if(0===r&&null!==e)throw a.create$1("Reference item not found");n.splice(r,0,...t)}}delete(e,t=1){null!==this.doc?sn(this.doc,n=>{Fn(n,this,e,t)}):this._prelimContent.splice(e,t)}toArray(){return Un(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return In(this,e)}slice(e=0,t=this.length){return On(this,e,t)}forEach(e){Pn(this,e)}_write(e){e.writeTypeRef(Ir)}},pr=class e extends gr{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((e,t)=>{this.setAttribute(t,e)}),this._prelimAttrs=null}_copy(){return new e(this.nodeName)}clone(){const t=new e(this.nodeName),n=this.getAttributes();return a.forEach(n,(e,n)=>{t.setAttribute(n,e)}),t.insert(0,this.toArray().map(e=>e instanceof Dn?e.clone():e)),t}toString(){const e=this.getAttributes(),t=[],n=[];for(const s in e)n.push(s);n.sort();const r=n.length;for(let s=0;s<r;s++){const r=n[s];t.push(r+'="'+e[r]+'"')}const i=this.nodeName.toLocaleLowerCase();return`<${i}${t.length>0?" "+t.join(" "):""}>${super.toString()}</${i}>`}removeAttribute(e){null!==this.doc?sn(this.doc,t=>{Bn(t,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,t){null!==this.doc?sn(this.doc,n=>{Hn(n,this,e,t)}):this._prelimAttrs.set(e,t)}getAttribute(e){return Wn(this,e)}hasAttribute(e){return qn(this,e)}getAttributes(e){return e?((e,t)=>{const n={};return e._map.forEach((e,r)=>{let i=e;for(;null!==i&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;null!==i&&Bt(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n})(this,e):Yn(this)}toDOM(e=document,t={},n){const r=e.createElement(this.nodeName),i=this.getAttributes();for(const s in i){const e=i[s];"string"==typeof e&&r.setAttribute(s,e)}return Pn(this,i=>{r.appendChild(i.toDOM(e,t,n))}),void 0!==n&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(Mr),e.writeKey(this.nodeName)}},mr=class extends _n{constructor(e,t,n){super(e,n),this.childListChanged=!1,this.attributesChanged=new Set,t.forEach(e=>{null===e?this.childListChanged=!0:this.attributesChanged.add(e)})}},yr=class e extends Qn{constructor(e){super(),this.hookName=e}_copy(){return new e(this.hookName)}clone(){const t=new e(this.hookName);return this.forEach((e,n)=>{t.set(n,e)}),t}toDOM(e=document,t={},n){const r=t[this.hookName];let i;return i=void 0!==r?r.createDom(this):document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),void 0!==n&&n._createAssociation(i,this),i}_write(e){e.writeTypeRef(Nr),e.writeKey(this.hookName)}},wr=class e extends ur{get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new e}clone(){const t=new e;return t.applyDelta(this.toDelta()),t}toDOM(e=document,t,n){const r=e.createTextNode(this.toString());return void 0!==n&&n._createAssociation(r,this),r}toString(){return this.toDelta().map(e=>{const t=[];for(const r in e.attributes){const n=[];for(const t in e.attributes[r])n.push({key:t,value:e.attributes[r][t]});n.sort((e,t)=>e.key<t.key?-1:1),t.push({nodeName:r,attrs:n})}t.sort((e,t)=>e.nodeName<t.nodeName?-1:1);let n="";for(let r=0;r<t.length;r++){const e=t[r];n+=`<${e.nodeName}`;for(let t=0;t<e.attrs.length;t++){const r=e.attrs[t];n+=` ${r.key}="${r.value}"`}n+=">"}n+=e.insert;for(let r=t.length-1;r>=0;r--)n+=`</${t[r].nodeName}>`;return n}).join("")}toJSON(){return this.toString()}_write(e){e.writeTypeRef(jr)}},br=class{constructor(e,t){this.id=e,this.length=t}get deleted(){throw a.methodUnimplemented()}mergeWith(e){return!1}write(e,t,n){throw a.methodUnimplemented()}integrate(e,t){throw a.methodUnimplemented()}},vr=class extends br{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){t>0&&(this.id.clock+=t,this.length-=t),Kt(e.doc.store,this)}write(e,t){e.writeInfo(0),e.writeLen(this.length-t)}getMissing(e,t){return null}},_r=class e{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new e(this.content)}splice(e){throw a.methodUnimplemented()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}},Sr=class e{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.len)}splice(t){const n=new e(this.len-t);return this.len=t,n}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){Qe(e.deleteSet,t.id.client,t.id.clock,this.len),t.markDeleted()}delete(e){}gc(e){}write(e,t){e.writeLen(this.len-t)}getRef(){return 1}},kr=(e,t)=>new nt({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1}),Cr=class e{constructor(e){e._item,this.doc=e;const t={};this.opts=t,e.gc||(t.gc=!1),e.autoLoad&&(t.autoLoad=!0),null!==e.meta&&(t.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new e(kr(this.doc.guid,this.opts))}splice(e){throw a.methodUnimplemented()}mergeWith(e){return!1}integrate(e,t){this.doc._item=t,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,t){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}},Er=class e{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new e(this.embed)}splice(e){throw a.methodUnimplemented()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}},Ar=class e{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.key,this.value)}splice(e){throw a.methodUnimplemented()}mergeWith(e){return!1}integrate(e,t){const n=t.parent;n._searchMarker=null,n._hasFormatting=!0}delete(e){}gc(e){}write(e,t){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}},xr=class e{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){const n=new e(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){const n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){const t=this.arr[r];e.writeString(void 0===t?"undefined":JSON.stringify(t))}}getRef(){return 2}},Tr="development"===a.getVariable("node_env"),Rr=class e{constructor(e){this.arr=e,Tr&&a.deepFreeze(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){const n=new e(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){const n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){const t=this.arr[r];e.writeAny(t)}}getRef(){return 8}},Dr=class e{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new e(this.str)}splice(t){const n=new e(this.str.slice(t));this.str=this.str.slice(0,t);const r=this.str.charCodeAt(t-1);return r>=55296&&r<=56319&&(this.str=this.str.slice(0,t-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(e){return this.str+=e.str,!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeString(0===t?this.str:this.str.slice(t))}getRef(){return 4}},Or=[e=>new $n,e=>new Qn,e=>new ur,e=>new pr(e.readKey()),e=>new gr,e=>new yr(e.readKey()),e=>new wr],Ur=0,Pr=1,Lr=2,Mr=3,Ir=4,Nr=5,jr=6,Vr=class e{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new e(this.type._copy())}splice(e){throw a.methodUnimplemented()}mergeWith(e){return!1}integrate(e,t){this.type._integrate(e.doc,t)}delete(e){let t=this.type._start;for(;null!==t;)t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e),t=t.right;this.type._map.forEach(t=>{t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e)}),e.changed.delete(this.type)}gc(e){let t=this.type._start;for(;null!==t;)t.gc(e,!0),t=t.right;this.type._start=null,this.type._map.forEach(t=>{for(;null!==t;)t.gc(e,!0),t=t.left}),this.type._map=new Map}write(e,t){this.type._write(e)}getRef(){return 7}},Fr=(e,t)=>{let n,r=t,i=0;do{i>0&&(r=xt(r.client,r.clock+i)),n=$t(e,r),i=r.clock-n.id.clock,r=n.redone}while(null!==r&&n instanceof qr);return{item:n,diff:i}},Br=(e,t)=>{for(;null!==e&&e.keep!==t;)e.keep=t,e=e.parent._item},Hr=(e,t,n)=>{const{client:r,clock:i}=t.id,s=new qr(xt(r,i+n),t,xt(r,i+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&s.markDeleted(),t.keep&&(s.keep=!0),null!==t.redone&&(s.redone=xt(t.redone.client,t.redone.clock+n)),t.right=s,null!==s.right&&(s.right.left=s),e._mergeStructs.push(s),null!==s.parentSub&&null===s.right&&s.parent._map.set(s.parentSub,s),t.length=n,s},Wr=(e,t)=>a.some(e,e=>ze(e.deletions,t)),Yr=(e,t,n,r,i,s)=>{const o=e.doc,a=o.store,c=o.clientID,l=t.redone;if(null!==l)return Qt(e,l);let d,h=t.parent._item,u=null;if(null!==h&&!0===h.deleted){if(null===h.redone&&(!n.has(h)||null===Yr(e,h,n,r,i,s)))return null;for(;null!==h.redone;)h=Qt(e,h.redone)}const f=null===h?t.parent:h.content.type;if(null===t.parentSub){for(u=t.left,d=t;null!==u;){let t=u;for(;null!==t&&t.parent._item!==h;)t=null===t.redone?null:Qt(e,t.redone);if(null!==t&&t.parent._item===h){u=t;break}u=u.left}for(;null!==d;){let t=d;for(;null!==t&&t.parent._item!==h;)t=null===t.redone?null:Qt(e,t.redone);if(null!==t&&t.parent._item===h){d=t;break}d=d.right}}else{if(d=null,t.right&&!i){for(u=t;null!==u&&null!==u.right&&(u.right.redone||ze(r,u.right.id)||Wr(s.undoStack,u.right.id)||Wr(s.redoStack,u.right.id));)for(u=u.right;u.redone;)u=Qt(e,u.redone);if(u&&null!==u.right)return null}else u=f._map.get(t.parentSub)||null;null!==u&&u.parent._item!==h&&(u=f._map.get(t.parentSub)||null)}const g=qt(a,c),p=xt(c,g),m=new qr(p,u,u&&u.lastId,d,d&&d.id,f,t.parentSub,t.content.copy());return t.redone=p,Br(m,!0),m.integrate(e,0),m},qr=class e extends br{constructor(e,t,n,r,i,s,o,a){super(e,a.getLength()),this.origin=n,this.left=t,this.right=r,this.rightOrigin=i,this.parent=s,this.parentSub=o,this.redone=null,this.content=a,this.info=this.content.isCountable()?2:0}set marker(e){(8&this.info)>0!==e&&(this.info^=8)}get marker(){return(8&this.info)>0}get keep(){return(1&this.info)>0}set keep(e){this.keep!==e&&(this.info^=1)}get countable(){return(2&this.info)>0}get deleted(){return(4&this.info)>0}set deleted(e){this.deleted!==e&&(this.info^=4)}markDeleted(){this.info|=4}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=qt(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=qt(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Et&&this.id.client!==this.parent.client&&this.parent.clock>=qt(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Gt(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=Qt(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===vr||this.right&&this.right.constructor===vr)this.parent=null;else if(this.parent){if(this.parent.constructor===Et){const e=$t(n,this.parent);e.constructor===vr?this.parent=null:this.parent=e.content.type}}else this.left&&this.left.constructor===e?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===e&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=Gt(e,e.doc.store,xt(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(t),this.length-=t),this.parent){if(!this.left&&(!this.right||null!==this.right.left)||this.left&&this.left.right!==this.right){let t,n=this.left;if(null!==n)t=n.right;else if(null!==this.parentSub)for(t=this.parent._map.get(this.parentSub)||null;null!==t&&null!==t.left;)t=t.left;else t=this.parent._start;const r=new Set,i=new Set;for(;null!==t&&t!==this.right;){if(i.add(t),r.add(t),At(this.origin,t.origin)){if(t.id.client<this.id.client)n=t,r.clear();else if(At(this.rightOrigin,t.rightOrigin))break}else{if(null===t.origin||!i.has($t(e.doc.store,t.origin)))break;r.has($t(e.doc.store,t.origin))||(n=t,r.clear())}t=t.right}this.left=n}if(null!==this.left){const e=this.left.right;this.right=e,this.left.right=this}else{let e;if(null!==this.parentSub)for(e=this.parent._map.get(this.parentSub)||null;null!==e&&null!==e.left;)e=e.left;else e=this.parent._start,this.parent._start=this;this.right=e}null!==this.right?this.right.left=this:null!==this.parentSub&&(this.parent._map.set(this.parentSub,this),null!==this.left&&this.left.delete(e)),null===this.parentSub&&this.countable&&!this.deleted&&(this.parent._length+=this.length),Kt(e.doc.store,this),this.content.integrate(e,this),tn(e,this.parent,this.parentSub),(null!==this.parent._item&&this.parent._item.deleted||null!==this.parentSub&&null!==this.right)&&this.delete(e)}else new vr(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;null!==e&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;null!==e&&e.deleted;)e=e.left;return e}get lastId(){return 1===this.length?this.id:xt(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&At(e.origin,this.lastId)&&this.right===e&&At(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&null===this.redone&&null===e.redone&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){const t=this.parent._searchMarker;return t&&t.forEach(t=>{t.p===e&&(t.p=this,!this.deleted&&this.countable&&(t.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,null!==this.right&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){const t=this.parent;this.countable&&null===this.parentSub&&(t._length-=this.length),this.markDeleted(),Qe(e.deleteSet,this.id.client,this.id.clock,this.length),tn(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw a.unexpectedCase();this.content.gc(e),t?((e,t,n)=>{const r=e.clients.get(t.id.client);r[zt(r,t.id.clock)]=n})(e,this,new vr(this.id,this.length)):this.content=new Sr(this.length)}write(e,t){const n=t>0?xt(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,i=this.parentSub,s=31&this.content.getRef()|(null===n?0:128)|(null===r?0:64)|(null===i?0:32);if(e.writeInfo(s),null!==n&&e.writeLeftID(n),null!==r&&e.writeRightID(r),null===n&&null===r){const t=this.parent;if(void 0!==t._item){const n=t._item;if(null===n){const n=Dt(t);e.writeParentInfo(!0),e.writeString(n)}else e.writeParentInfo(!1),e.writeLeftID(n.id)}else t.constructor===String?(e.writeParentInfo(!0),e.writeString(t)):t.constructor===Et?(e.writeParentInfo(!1),e.writeLeftID(t)):a.unexpectedCase();null!==i&&e.writeString(i)}this.content.write(e,t)}},Kr=(e,t)=>zr[31&t](e),zr=[()=>{a.unexpectedCase()},e=>new Sr(e.readLen()),e=>{const t=e.readLen(),n=[];for(let r=0;r<t;r++){const t=e.readString();"undefined"===t?n.push(void 0):n.push(JSON.parse(t))}return new xr(n)},e=>new _r(e.readBuf()),e=>new Dr(e.readString()),e=>new Er(e.readJSON()),e=>new Ar(e.readKey(),e.readJSON()),e=>new Vr(Or[e.readTypeRef()](e)),e=>{const t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new Rr(n)},e=>new Cr(kr(e.readString(),e.readAny())),()=>{a.unexpectedCase()}],$r=class extends br{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){a.unexpectedCase()}write(e,t){e.writeInfo(10),a.writeVarUint(e.restEncoder,this.length-t)}getMissing(e,t){return null}},Jr="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},Qr="__ $YJS$ __";Jr[Qr],Jr[Qr]=!0;var Gr=Object.defineProperty,Xr=Object.defineProperties,Zr=Object.getOwnPropertyDescriptors,ei=Object.getOwnPropertySymbols,ti=Object.prototype.hasOwnProperty,ni=Object.prototype.propertyIsEnumerable,ri=(e,t,n)=>t in e?Gr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ii=(e,t)=>{for(var n in t||(t={}))ti.call(t,n)&&ri(e,n,t[n]);if(ei)for(var n of ei(t))ni.call(t,n)&&ri(e,n,t[n]);return e},si=(e,t)=>Xr(e,Zr(t)),oi=(e,t)=>{var n={};for(var r in e)ti.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&ei)for(var r of ei(e))t.indexOf(r)<0&&ni.call(e,r)&&(n[r]=e[r]);return n};function ai(e){return"[object Object]"===Object.prototype.toString.call(e)}function ci(e){if(!ai(e))return!1;const t=e.constructor;if(void 0===t)return!0;const n=t.prototype;return!1!==ai(n)&&!1!==n.hasOwnProperty("isPrototypeOf")}function li(e,t){for(const n in e){const r=e[n],i=t[n];if(ci(r)&&ci(i)){if(!li(r,i))return!1}else if(Array.isArray(r)&&Array.isArray(i)){if(r.length!==i.length)return!1;for(let e=0;e<r.length;e++)if(r[e]!==i[e])return!1}else if(r!==i)return!1}for(const n in t)if(void 0===e[n]&&void 0!==t[n])return!1;return!0}function di(e,...t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e)))}function hi(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>null!==e))}function ui(e){return function(e){var t,n;const r=[];for(const i of e){if("string"==typeof i.insert&&0===i.insert.length)continue;const e=r[r.length-1];e&&"string"==typeof e.insert&&"string"==typeof i.insert&&(e.attributes===i.attributes||!e.attributes==!i.attributes&&li(null!=(t=e.attributes)?t:{},null!=(n=i.attributes)?n:{}))?e.insert+=i.insert:r.push(i)}return r}(e.toDelta())}function fi({insert:e}){return"string"==typeof e?e.length:1}function gi(e){return e.reduce((e,t)=>e+fi(t),0)}function pi(e,t,n){if(n<1)return[];let r=0;const i=[],s=t+n;for(let o=0;o<e.length&&!(r>=s);o++){const n=e[o],a=fi(n);if(r+a<=t){r+=a;continue}if("string"!=typeof n.insert){r+=a,i.push(n);continue}const c=Math.max(0,t-r),l=Math.min(a,a-(r+a-s));i.push(si(ii({},n),{insert:n.insert.slice(c,l)})),r+=a}return i}function mi(e){return function(e,...t){return Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e)))}(e,i.Text.isText(e)?"text":"children")}function yi(e){const t=ui(e),n=t.length>0?t.map(wi):[{text:""}];return si(ii({},e.getAttributes()),{children:n})}function wi(e){return"string"==typeof e.insert?si(ii({},e.attributes),{text:e.insert}):yi(e.insert)}function bi(e){return e.map(e=>i.Text.isText(e)?{insert:e.text,attributes:mi(e)}:{insert:vi(e)})}function vi(e){var t=e,{children:n}=t,r=oi(t,["children"]);const i=new wr;return Object.entries(r).forEach(([e,t])=>{i.setAttribute(e,t)}),i.applyDelta(bi(n),{sanitize:!1}),i}function _i(e){return e?i.Text.isText(e)?e.text.length:1:0}function Si(e,t,n){var r;if(0===n.length)throw new Error("Path has to a have a length >= 1");if(i.Text.isText(t))throw new Error("Cannot descent into slate text");const[s,...o]=n,a=function(e,t){return e.children.slice(0,t).reduce((e,t)=>e+_i(t),0)}(t,s),c=t.children[s],l=ui(e),d=_i(c),h=pi(l,a,d);if(h.length>1)throw new Error("Path doesn't match yText, yTarget spans multiple nodes");const u=null==(r=h[0])?void 0:r.insert;if(o.length>0){if(!(u instanceof wr))throw new Error("Path doesn't match yText, cannot descent into non-yText");return Si(u,c,o)}return{yParent:e,textRange:{start:a,end:a+d},yTarget:u instanceof wr?u:void 0,slateParent:t,slateTarget:c,targetDelta:h}}function ki(e,t,n={}){const{assoc:r=0,insert:s=!1}=n;let o=0,a=0;for(let l=0;l<e.children.length;l++){const n=e.children[l],s=i.Text.isText(n)?n.text.length:1;s>0&&(a=l);const c=o+s;if(s>0&&(r>=0?c>t:c>=t))return[l,t-o];o+=s}if(t>o+(s?1:0))throw new Error("yOffset out of bounds");if(s)return[e.children.length,0];const c=e.children[a];return[a,i.Text.isText(c)?c.text.length:1]}function Ci(e,t,n){const r=[n];for(;r[0]!==e;){const{parent:e}=r[0];if(!e)throw new Error("yText isn't a descendant of root element");if(!(e instanceof wr))throw new Error("Unexpected y parent type");r.unshift(e)}if(r.length<2)return[];let s=t;return r.reduce((e,t,n)=>{const o=r[n+1];if(!o)return e;let a=0;const c=ui(t);for(const r of c){if(r.insert===o)break;a+="string"==typeof r.insert?r.insert.length:1}if(i.Text.isText(s))throw new Error("Cannot descent into slate text");const[l]=ki(s,a);return s=s.children[l],e.concat(l)},[])}function Ei(e,t,n){const{target:r,changes:s}=n,o=n.delta;if(!(r instanceof wr))throw new Error("Unexpected target node type");const a=[],c=Ci(e,t,r),l=i.Node.get(t,c);if(i.Text.isText(l))throw new Error("Cannot apply yTextEvent to text node");const d=Array.from(s.keys.entries());if(c.length>0&&d.length>0){const e=Object.fromEntries(d.map(([e,t])=>[e,"delete"===t.action?null:r.getAttribute(e)])),t=Object.fromEntries(d.map(([e])=>[e,l[e]]));a.push({type:"set_node",newProperties:e,properties:t,path:c})}return o.length>0&&a.push(...function(e,t,n){const r=[];let s=n.reduce((e,t)=>"retain"in t?e+t.retain:"delete"in t?e+t.delete:e,0);return n.reverse().forEach(n=>{var o;if("attributes"in n&&"retain"in n){const[o,a]=ki(e,s-n.retain),[c,l]=ki(e,s,{assoc:-1});for(let s=c;s>=o;s--){const d=e.children[s],h=[...t,s];if(!i.Text.isText(d))continue;const u=n.attributes,f=di(e,...Object.keys(n.attributes));if(s===o||s===c){const e=s===o?a:0,t=s===c?l:d.text.length;if(t!==d.text.length&&r.push({type:"split_node",path:h,position:t,properties:mi(d)}),0!==e){r.push({type:"split_node",path:h,position:e,properties:hi(ii(ii({},mi(d)),u))});continue}}r.push({type:"set_node",newProperties:u,path:h,properties:f})}}if("retain"in n&&(s-=n.retain),"delete"in n){const[o,a]=ki(e,s-n.delete),[c,l]=ki(e,s,{assoc:-1});for(let n=0===l?c-1:c;n>=o;n--){const d=e.children[n],h=[...t,n];if(i.Text.isText(d)&&(n===o||n===c)){const e=n===o?a:0,t=n===c?l:d.text.length;r.push({type:"remove_text",offset:e,text:d.text.slice(e,t),path:h}),s-=t-e;continue}r.push({type:"remove_node",node:d,path:h}),s-=_i(d)}return}if("insert"in n){const[a,c]=ki(e,s,{insert:!0}),l=e.children[a],d=[...t,a];if(i.Text.isText(l)){const e=r[r.length-1],t=null!=e&&"insert_node"===e.type?e.node:mi(l);let s=[];if(null==e||"insert_node"!==e.type&&"insert_text"!==e.type&&"split_node"!==e.type&&"set_node"!==e.type||(s=e.path),"string"==typeof n.insert&&li(null!=(o=n.attributes)?o:{},t)&&i.Path.equals(d,s))return r.push({type:"insert_text",offset:c,text:n.insert,path:d});const a=wi(n);return 0===c?r.push({type:"insert_node",path:d,node:a}):(c<l.text.length&&r.push({type:"split_node",path:d,position:c,properties:mi(l)}),r.push({type:"insert_node",path:i.Path.next(d),node:a}))}return r.push({type:"insert_node",path:d,node:wi(n)})}}),r}(l,c,o)),a}function Ai(e,t,n){i.Editor$1.withoutNormalizing(t,()=>{n.forEach(n=>{(function(e,t,n){if(n instanceof hr)return Ei(e,t,n);throw new Error("Unexpected Y event type")})(e,t,n).forEach(e=>{t.apply(e)})})})}function xi(e){return e.map(e=>"string"==typeof e.insert?e:si(ii({},e),{insert:Ti(e.insert)}))}function Ti(e){const t=new wr,n=e.getAttributes();return Object.entries(n).forEach(([e,n])=>{t.setAttribute(e,n)}),t.applyDelta(xi(ui(e)),{sanitize:!1}),t}function Ri(e){if(!e.doc)throw new Error("shared type isn't attached to a document")}var Di="__slateYjsStoredPosition_";function Oi(e,t,n){const{yTarget:r,yParent:i,textRange:s}=Si(e,t,n.path);if(r)throw new Error("Slate point points to a non-text element inside sharedRoot");const o=s.start+n.offset;return Mt(i,o,o===s.end?-1:0)}function Ui(e,t,n){if(!e.doc)throw new Error("sharedRoot isn't attach to a yDoc");const r=jt(n,e.doc);return r&&function(e,t,{type:n,index:r,assoc:s}){if(!(n instanceof wr))throw new Error("Absolute position points to a non-XMLText");const o=Ci(e,t,n),a=i.Node.get(t,o);if(i.Text.isText(a))throw new Error("Absolute position doesn't match slateRoot, cannot descent into text");const[c,l]=ki(a,r,{assoc:s}),d=a.children[c];return i.Text.isText(d)?{path:[...o,c],offset:l}:null}(e,t,r)}function Pi(e,t,n){e.setAttribute(Di+t,It(n))}function Li(e,t,n){return Object.fromEntries(Object.entries(e).filter(([,e])=>e.type===t&&(!n||(e.assoc>=0?e.index>=n.start&&e.index<n.end:e.index>n.start&&e.index>=n.end))))}function Mi(e,t,n=""){const r={[n]:Li(e,t)};return ui(t).forEach(({insert:t},i)=>{t instanceof wr&&Object.assign(r,Mi(e,t,n?`${n}.${i}`:i.toString()))}),r}function Ii(e,t,n,r=0){const i=function(e){return Ri(e),Object.fromEntries(Object.entries(e.getAttributes()).filter(([e])=>e.startsWith(Di)).map(([t,n])=>[t.slice(25),jt(Nt(n),e.doc)]).filter(([,e])=>e))}(e),s={"":Li(i,t,{start:r,end:r+gi(n)})};return n.forEach(({insert:e},t)=>{e instanceof wr&&Object.assign(s,Mi(i,e,t.toString()))}),s}function Ni(e,t,n,r,i=0,s=0,o=""){const a=n[o];a&&Object.entries(a).forEach(([n,r])=>{Pi(e,n,Mt(t,r.index-s+i,r.assoc))}),r.forEach(({insert:t},r)=>{t instanceof wr&&Ni(e,t,n,ui(t),0,0,o?`${o}.${r}`:r.toString())})}function ji(e,t,n){return{anchor:Oi(e,t,n.anchor),focus:Oi(e,t,n.focus)}}var Vi={insert_node:function(e,t,n){const{yParent:r,textRange:s}=Si(e,t,n.path);if(i.Text.isText(n.node))return r.insert(s.start,n.node.text,mi(n.node));r.insertEmbed(s.start,vi(n.node))},remove_node:function(e,t,n){const{yParent:r,textRange:i}=Si(e,t,n.path);r.delete(i.start,i.end-i.start)},set_node:function(e,t,n){const{yTarget:r,textRange:i,yParent:s}=Si(e,t,n.path);if(r)return Object.entries(n.newProperties).forEach(([e,t])=>{if(null===t)return r.removeAttribute(e);r.setAttribute(e,t)}),Object.entries(n.properties).forEach(([e])=>{n.newProperties.hasOwnProperty(e)||r.removeAttribute(e)});const o=ii(ii({},Object.fromEntries(Object.keys(n.properties).map(e=>[e,null]))),n.newProperties);s.format(i.start,i.end-i.start,o)},merge_node:function(e,t,n){const r=Si(e,t,n.path),s=Si(r.yParent,r.slateParent,i.Path.previous(n.path.slice(-1)));if(!r.yTarget!=!s.yTarget)throw new Error("Cannot merge y text with y element");if(!s.yTarget||!r.yTarget){const{yParent:e,textRange:s,slateTarget:o}=r;if(!o)throw new Error("Expected Slate target node for merge op.");const a=i.Node.get(t,i.Path.previous(n.path));if(!i.Text.isText(a))throw new Error("Path points to Y.Text but not a Slate text node.");const c=mi(o),l=mi(a),d=Object.keys(c).reduce((e,t)=>t in l?e:si(ii({},e),{[t]:null}),{});return e.format(s.start,s.end-s.start,ii(ii({},d),l))}const o=s.yTarget.length,a=ui(r.yTarget),c=xi(a),l=Ii(e,r.yTarget,a,o),d=[{retain:o},...c];s.yTarget.applyDelta(d,{sanitize:!1}),r.yParent.delete(r.textRange.start,r.textRange.end-r.textRange.start),Ni(e,s.yTarget,l,c,o)},move_node:function(e,t,n){const r=i.Path.parent(n.newPath),s=n.newPath[n.newPath.length-1],o=i.Node.get(t,r);if(i.Text.isText(o))throw new Error("Cannot move slate node into text element");const a=[...r,Math.min(s,o.children.length)],c=Si(e,t,n.path),l=Si(e,t,a),d=xi(c.targetDelta),h=Ii(e,c.yParent,c.targetDelta);c.yParent.delete(c.textRange.start,c.textRange.end-c.textRange.start);const u=gi(ui(l.yParent)),f=Math.min(l.textRange.start,u),g=[{retain:f},...d];l.yParent.applyDelta(g,{sanitize:!1}),Ni(e,l.yParent,h,d,f,c.textRange.start)},split_node:function(e,t,n){const r=Si(e,t,n.path);if(!r.slateTarget)throw new Error("Y target without corresponding slate node");if(!r.yTarget){if(!i.Text.isText(r.slateTarget))throw new Error("Mismatch node type between y target and slate node");const e={};return r.targetDelta.forEach(t=>{t.attributes&&Object.keys(t.attributes).forEach(t=>{e[t]=null})}),r.yParent.format(r.textRange.start,r.textRange.end-r.textRange.start,ii(ii({},e),n.properties))}if(i.Text.isText(r.slateTarget))throw new Error("Mismatch node type between y target and slate node");const s=Si(r.yTarget,r.slateTarget,[n.position]),o=r.slateTarget.children.slice(0,n.position).reduce((e,t)=>e+_i(t),0),a=r.slateTarget.children.reduce((e,t)=>e+_i(t),0),c=pi(ui(r.yTarget),o,a-o),l=xi(c),d=Ii(e,r.yTarget,c,o),h=new wr;h.applyDelta(l,{sanitize:!1}),Object.entries(n.properties).forEach(([e,t])=>{h.setAttribute(e,t)}),r.yTarget.delete(s.textRange.start,r.yTarget.length-s.textRange.start),r.yParent.insertEmbed(r.textRange.end,h),Ni(e,h,d,l,0,o)}};var Fi=si(ii(ii({},{insert_text:function(e,t,n){const{yParent:r,textRange:s}=Si(e,t,n.path),o=i.Node.get(t,n.path);if(!i.Text.isText(o))throw new Error("Cannot insert text into non-text node");r.insert(s.start+n.offset,n.text,mi(o))},remove_text:function(e,t,n){const{yParent:r,textRange:i}=Si(e,t,n.path);r.delete(i.start+n.offset,n.text.length)}}),Vi),{set_selection:()=>{}});var Bi=Symbol("slate-yjs-operation"),Hi=Symbol("slate-yjs-position-storage"),Wi=new WeakMap,Yi=new WeakMap,qi=new WeakSet,Ki={isYjsEditor:e=>i.Editor$1.isEditor(e)&&e.sharedRoot instanceof wr&&"localOrigin"in e&&"positionStorageOrigin"in e&&"function"==typeof e.applyRemoteEvents&&"function"==typeof e.storeLocalChange&&"function"==typeof e.flushLocalChanges&&"function"==typeof e.isLocalOrigin&&"function"==typeof e.connect&&"function"==typeof e.disconnect,localChanges(e){var t;return null!=(t=Yi.get(e))?t:[]},applyRemoteEvents(e,t,n){e.applyRemoteEvents(t,n)},storeLocalChange(e,t){e.storeLocalChange(t)},flushLocalChanges(e){e.flushLocalChanges()},connected:e=>qi.has(e),connect(e){e.connect()},disconnect(e){e.disconnect()},isLocal:e=>e.isLocalOrigin(Ki.origin(e)),origin(e){const t=Wi.get(e);return void 0!==t?t:e.localOrigin},withOrigin(e,t,n){const r=Ki.origin(e);Wi.set(e,t),n(),Wi.set(e,r)},storePosition(e,t,n){const{sharedRoot:r,positionStorageOrigin:i}=e;Ri(r);const s=Oi(r,e,n);r.doc.transact(()=>{Pi(r,t,s)},i)},removeStoredPosition(e,t){const{sharedRoot:n,positionStorageOrigin:r}=e;Ri(n),n.doc.transact(()=>{!function(e,t){e.removeAttribute(Di+t)}(n,t)},r)},position(e,t){const n=function(e,t){const n=e.getAttribute(Di+t);return n?Nt(n):null}(e.sharedRoot,t);if(n)return Ui(e.sharedRoot,e,n)},storedPositionsRelative(e){return t=e.sharedRoot,Object.fromEntries(Object.entries(t.getAttributes()).filter(([e])=>e.startsWith(Di)).map(([e,t])=>{return[e.slice(25),(n=t,new Ut(null==n.type?null:xt(n.type.client,n.type.clock),n.tname??null,null==n.item?null:xt(n.item.client,n.item.clock),null==n.assoc?0:n.assoc))];var n}));var t}};function zi(e,t,{localOrigin:n,positionStorageOrigin:r,autoConnect:s=!1}={}){const o=e;o.sharedRoot=t,o.localOrigin=null!=n?n:Bi,o.positionStorageOrigin=null!=r?r:Hi,o.applyRemoteEvents=(e,t)=>{Ki.flushLocalChanges(o),i.Editor$1.withoutNormalizing(o,()=>{Ki.withOrigin(o,t,()=>{Ai(o.sharedRoot,o,e)})})},o.isLocalOrigin=e=>e===o.localOrigin;const a=(e,t)=>{o.isLocalOrigin(t.origin)||Ki.applyRemoteEvents(o,e,t.origin)};let c=null;s&&(c=setTimeout(()=>{c=null,Ki.connect(o)})),o.connect=()=>{if(Ki.connected(o))throw new Error("already connected");o.sharedRoot.observeDeep(a);const t=yi(o.sharedRoot);o.children=t.children,qi.add(o),i.Editor$1.normalize(e,{force:!0}),e.operations.length||e.onChange()},o.disconnect=()=>{c&&clearTimeout(c),Ki.flushLocalChanges(o),o.sharedRoot.unobserveDeep(a),qi.delete(o)},o.storeLocalChange=t=>{Yi.set(o,[...Ki.localChanges(o),{op:t,doc:e.children,origin:Ki.origin(o)}])},o.flushLocalChanges=()=>{Ri(o.sharedRoot);const e=Ki.localChanges(o);Yi.delete(o);const t=[];e.forEach(e=>{const n=t[t.length-1];if(n&&n[0].origin===e.origin)return n.push(e);t.push([e])}),t.forEach(e=>{Ri(o.sharedRoot),o.sharedRoot.doc.transact(()=>{e.forEach(e=>{Ri(o.sharedRoot),function(e,t,n){const r=Fi[n.type];if(!r)throw new Error(`Unknown operation: ${n.type}`);r(e,t,n)}(o.sharedRoot,{children:e.doc},e.op)})},e[0].origin)})};const{apply:l,onChange:d}=o;return o.apply=e=>{Ki.connected(o)&&Ki.isLocal(o)&&Ki.storeLocalChange(o,e),l(e)},o.onChange=()=>{Ki.connected(o)&&Ki.flushLocalChanges(o),d()},o}var $i=new WeakMap,Ji=Symbol("slate-yjs-history-without-saving");function Qi(e,t={}){var n=t,{withoutSavingOrigin:r=Ji,trackedOrigins:s=new Set([e.localOrigin])}=n,o=oi(n,["withoutSavingOrigin","trackedOrigins"]);const a=e;a.undoManager=new ln(a.sharedRoot,ii({trackedOrigins:s},o)),a.withoutSavingOrigin=r;const{onChange:c,isLocalOrigin:l}=a;a.onChange=()=>{c(),$i.set(a,a.selection&&ji(a.sharedRoot,a,a.selection))},a.isLocalOrigin=e=>e===a.withoutSavingOrigin||l(e);const d=({stackItem:e})=>{e.meta.set("selection",a.selection&&ji(a.sharedRoot,a,a.selection)),e.meta.set("selectionBefore",$i.get(a))},h=({stackItem:e})=>{e.meta.set("selection",a.selection&&ji(a.sharedRoot,a,a.selection))},u=({stackItem:e,type:t})=>{const n="undo"===t?a.undoManager.redoStack:a.undoManager.undoStack,r=n[n.length-1];r&&(r.meta.set("selection",e.meta.get("selectionBefore")),r.meta.set("selectionBefore",e.meta.get("selection")));const s=e.meta.get("selectionBefore");if(!s)return;const o=function(e,t,n){const r=Ui(e,t,n.anchor);if(!r)return null;const i=Ui(e,t,n.focus);return i?{anchor:r,focus:i}:null}(a.sharedRoot,a,s);o&&i.Transforms.select(a,o)},{connect:f,disconnect:g}=a;return a.connect=()=>{f(),a.undoManager.on("stack-item-added",d),a.undoManager.on("stack-item-popped",u),a.undoManager.on("stack-item-updated",h)},a.disconnect=()=>{a.undoManager.off("stack-item-added",d),a.undoManager.off("stack-item-popped",u),a.undoManager.off("stack-item-updated",h),g()},a.undo=()=>{Ki.connected(a)&&(Ki.flushLocalChanges(a),a.undoManager.undo())},a.redo=()=>{Ki.connected(a)&&(Ki.flushLocalChanges(a),a.undoManager.redo())},a}var Gi=new WeakMap,Xi={isCursorEditor:e=>Ki.isYjsEditor(e)&&e.awareness&&"string"==typeof e.cursorDataField&&"string"==typeof e.selectionStateField&&"function"==typeof e.sendCursorPosition&&"function"==typeof e.sendCursorData,sendCursorPosition(e,t=e.selection){e.sendCursorPosition(t)},sendCursorData(e,t){e.sendCursorData(t)},on(e,t,n){var r;if("change"!==t)return;const i=null!=(r=Gi.get(e))?r:new Set;i.add(n),Gi.set(e,i)},off(e,t,n){if("change"!==t)return;const r=Gi.get(e);r&&r.delete(n)},cursorState(e,t){var n;if(t===e.awareness.clientID||!Ki.connected(e))return null;const r=e.awareness.getStates().get(t);return r?{relativeSelection:null!=(n=r[e.selectionStateField])?n:null,data:r[e.cursorDataField],clientId:t}:null},cursorStates:e=>Ki.connected(e)?Object.fromEntries(Array.from(e.awareness.getStates().entries(),([t,n])=>t!==e.awareness.clientID&&n?[t,{relativeSelection:n[e.selectionStateField],data:n[e.cursorDataField]}]:null).filter(Array.isArray)):{}};var Zi=class extends a.Observable{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const e=a.getUnixTime();null!==this.getLocalState()&&15e3<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&3e4<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&es(this,t,"timeout")},a.floor(3e3)),e.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){const t=this.clientID,n=this.meta.get(t),r=void 0===n?0:n.clock+1,i=this.states.get(t);null===e?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:r,lastUpdated:a.getUnixTime()});const s=[],o=[],c=[],l=[];null===e?l.push(t):null==i?null!=e&&s.push(t):(o.push(t),a.equalityDeep(i,e)||c.push(t)),(s.length>0||c.length>0||l.length>0)&&this.emit("change",[{added:s,updated:c,removed:l},"local"]),this.emit("update",[{added:s,updated:o,removed:l},"local"])}setLocalStateField(e,t){const n=this.getLocalState();null!==n&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}},es=(e,t,n)=>{const r=[];for(let i=0;i<t.length;i++){const n=t[i];if(e.states.has(n)){if(e.states.delete(n),n===e.clientID){const t=e.meta.get(n);e.meta.set(n,{clock:t.clock+1,lastUpdated:a.getUnixTime()})}r.push(n)}}r.length>0&&(e.emit("change",[{added:[],updated:[],removed:r},n]),e.emit("update",[{added:[],updated:[],removed:r},n]))},ts=(e,t,n=e.states)=>{const r=t.length,i=a.createEncoder();a.writeVarUint(i,r);for(let s=0;s<r;s++){const r=t[s],o=n.get(r)||null,c=e.meta.get(r).clock;a.writeVarUint(i,r),a.writeVarUint(i,c),a.writeVarString(i,JSON.stringify(o))}return a.toUint8Array(i)},ns=(e,t,n)=>{const r=a.createDecoder(t),i=a.getUnixTime(),s=[],o=[],c=[],l=[],d=a.readVarUint(r);for(let h=0;h<d;h++){const t=a.readVarUint(r);let n=a.readVarUint(r);const d=JSON.parse(a.readVarString(r)),h=e.meta.get(t),u=e.states.get(t),f=void 0===h?0:h.clock;(f<n||f===n&&null===d&&e.states.has(t))&&(null===d?t===e.clientID&&null!=e.getLocalState()?n++:e.states.delete(t):e.states.set(t,d),e.meta.set(t,{clock:n,lastUpdated:i}),void 0===h&&null!==d?s.push(t):void 0!==h&&null===d?l.push(t):null!==d&&(a.equalityDeep(d,u)||c.push(t),o.push(t)))}(s.length>0||c.length>0||l.length>0)&&e.emit("change",[{added:s,updated:c,removed:l},n]),(s.length>0||o.length>0||l.length>0)&&e.emit("update",[{added:s,updated:o,removed:l},n])},rs=(e,t)=>{a.writeVarUint(e,0);const n=(e=>bt(e,new at))(t);a.writeVarUint8Array(e,n)},is=(e,t,n)=>{a.writeVarUint(e,1),a.writeVarUint8Array(e,mt(t,n))},ss=(e,t,n,r)=>{try{gt(t,a.readVarUint8Array(e),n)}catch(i){null!=r&&r(i)}},os=(e,t)=>{a.writeVarUint(e,2),a.writeVarUint8Array(e,t)},as=ss,cs=(e,t,n,r,i)=>{const s=a.readVarUint(e);switch(s){case 0:((e,t,n)=>{is(t,n,a.readVarUint8Array(e))})(e,t,n);break;case 1:ss(e,n,r,i);break;case 2:as(e,n,r,i);break;default:throw new Error("Unknown message type")}return s},ls=class{constructor(){this.callbacks={}}on(e,t){return this.callbacks[e]||(this.callbacks[e]=[]),this.callbacks[e].push(t),this}emit(e,...t){const n=this.callbacks[e];return n&&n.forEach(e=>e.apply(this,t)),this}off(e,t){const n=this.callbacks[e];return n&&(t?this.callbacks[e]=n.filter(e=>e!==t):delete this.callbacks[e]),this}removeAllListeners(){this.callbacks={}}},ds=class{constructor(e){this.data=e,this.encoder=a.createEncoder(),this.decoder=a.createDecoder(new Uint8Array(this.data))}peekVarString(){return a.peekVarString(this.decoder)}readVarUint(){return a.readVarUint(this.decoder)}readVarString(){return a.readVarString(this.decoder)}readVarUint8Array(){return a.readVarUint8Array(this.decoder)}writeVarUint(e){return a.writeVarUint(this.encoder,e)}writeVarString(e){return a.writeVarString(this.encoder,e)}writeVarUint8Array(e){return a.writeVarUint8Array(this.encoder,e)}length(){return a.length(this.encoder)}},hs=function(e){return e[e.Sync=0]="Sync",e[e.Awareness=1]="Awareness",e[e.Auth=2]="Auth",e[e.QueryAwareness=3]="QueryAwareness",e[e.Stateless=5]="Stateless",e[e.CLOSE=7]="CLOSE",e[e.SyncStatus=8]="SyncStatus",e[e.Ping=9]="Ping",e[e.Pong=10]="Pong",e}({}),us=function(e){return e.Connecting="connecting",e.Connected="connected",e.Disconnected="disconnected",e}({}),fs=class{constructor(){this.encoder=a.createEncoder()}get(e){return e.encoder}toUint8Array(){return a.toUint8Array(this.encoder)}},gs=class extends fs{constructor(...e){super(...e),this.type=hs.CLOSE,this.description="Ask the server to close the connection"}get(e){return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),this.encoder}},ps=class e extends ls{static{this.DEDUPLICATABLE_TYPES=new Set([hs.Awareness,hs.QueryAwareness])}constructor(e){super(),this.messageQueue=[],this.configuration={url:"",autoConnect:!0,preserveTrailingSlash:!1,document:void 0,WebSocketPolyfill:void 0,messageReconnectTimeout:3e4,delay:1e3,initialDelay:0,factor:2,maxAttempts:0,minDelay:1e3,maxDelay:3e4,jitter:!0,timeout:0,onOpen:()=>null,onConnect:()=>null,onMessage:()=>null,onOutgoingMessage:()=>null,onStatus:()=>null,onDisconnect:()=>null,onClose:()=>null,onDestroy:()=>null,onAwarenessUpdate:()=>null,onAwarenessChange:()=>null,handleTimeout:null,providerMap:new Map},this.webSocket=null,this.webSocketHandlers={},this.shouldConnect=!0,this.status=us.Disconnected,this.lastMessageReceived=0,this.identifier=0,this.intervals={connectionChecker:null},this.connectionAttempt=null,this.receivedOnOpenPayload=void 0,this.closeTries=0,this.setConfiguration(e),this.configuration.WebSocketPolyfill=e.WebSocketPolyfill?e.WebSocketPolyfill:WebSocket,this.on("open",this.configuration.onOpen),this.on("open",this.onOpen.bind(this)),this.on("connect",this.configuration.onConnect),this.on("message",this.configuration.onMessage),this.on("outgoingMessage",this.configuration.onOutgoingMessage),this.on("status",this.configuration.onStatus),this.on("disconnect",this.configuration.onDisconnect),this.on("close",this.configuration.onClose),this.on("destroy",this.configuration.onDestroy),this.on("awarenessUpdate",this.configuration.onAwarenessUpdate),this.on("awarenessChange",this.configuration.onAwarenessChange),this.on("close",this.onClose.bind(this)),this.on("message",this.onMessage.bind(this)),this.intervals.connectionChecker=setInterval(this.checkConnection.bind(this),this.configuration.messageReconnectTimeout/10),this.shouldConnect&&this.connect()}async onOpen(e){this.status=us.Connected,this.emit("status",{status:us.Connected}),this.cancelWebsocketRetry=void 0,this.receivedOnOpenPayload=e}attach(e){const t=e.effectiveName,n=this.configuration.providerMap.get(t);if(n&&n!==e&&n.isAuthenticated)throw new Error(`Cannot attach two providers with the same effective name "${t}". Use sessionAwareness: true to multiplex providers with the same document name.`);this.configuration.providerMap.set(t,e),this.status===us.Disconnected&&this.shouldConnect&&this.connect(),this.receivedOnOpenPayload&&this.status===us.Connected&&e.onOpen(this.receivedOnOpenPayload)}detach(e){const t=e.effectiveName;this.configuration.providerMap.has(t)&&(e.send(gs,{documentName:t}),this.configuration.providerMap.delete(t))}setConfiguration(e={}){this.configuration={...this.configuration,...e},this.configuration.autoConnect||(this.shouldConnect=!1)}async connect(){if(this.status===us.Connected)return;this.cancelWebsocketRetry&&(this.cancelWebsocketRetry(),this.cancelWebsocketRetry=void 0),this.receivedOnOpenPayload=void 0,this.shouldConnect=!0;const{retryPromise:e,cancelFunc:t}=(()=>{let e=!1;return{retryPromise:z(this.createWebSocketConnection.bind(this),{delay:this.configuration.delay,initialDelay:this.configuration.initialDelay,factor:this.configuration.factor,maxAttempts:this.configuration.maxAttempts,minDelay:this.configuration.minDelay,maxDelay:this.configuration.maxDelay,jitter:this.configuration.jitter,timeout:this.configuration.timeout,handleTimeout:this.configuration.handleTimeout,beforeAttempt:t=>{this.shouldConnect&&!e||t.abort()}}).catch(e=>{if(e&&"ATTEMPT_ABORTED"!==e.code)throw e}),cancelFunc:()=>{e=!0}}})();return this.cancelWebsocketRetry=t,e}attachWebSocketListeners(e,t){const{identifier:n}=e;this.webSocketHandlers[n]={message:e=>this.emit("message",e),close:e=>this.emit("close",{event:e}),open:e=>this.emit("open",e),error:e=>{t(e)}};const r=this.webSocketHandlers[e.identifier];Object.keys(r).forEach(t=>{e.addEventListener(t,r[t])})}cleanupWebSocket(){if(!this.webSocket)return;const{identifier:e}=this.webSocket,t=this.webSocketHandlers[e];Object.keys(t).forEach(n=>{this.webSocket?.removeEventListener(n,t[n]),delete this.webSocketHandlers[e]}),this.webSocket.close(),this.webSocket=null}createWebSocketConnection(){return new Promise((e,t)=>{this.webSocket&&(this.messageQueue=[],this.cleanupWebSocket()),this.lastMessageReceived=0,this.identifier+=1;const n=new this.configuration.WebSocketPolyfill(this.url);n.binaryType="arraybuffer",n.identifier=this.identifier,this.attachWebSocketListeners(n,t),this.webSocket=n,this.status=us.Connecting,this.emit("status",{status:us.Connecting}),this.connectionAttempt={resolve:e,reject:t}})}onMessage(e){this.resolveConnectionAttempt(),this.lastMessageReceived=a.getUnixTime();const t=new Uint8Array(e.data);if(1===t.length&&t[0]===hs.Ping)return void this.sendPong();const n=new ds(t).peekVarString();this.configuration.providerMap.get(n)?.onMessage(e)}sendPong(){const e=a.createEncoder();a.writeVarUint(e,hs.Pong),this.send(a.toUint8Array(e))}resolveConnectionAttempt(){this.connectionAttempt&&(this.connectionAttempt.resolve(),this.connectionAttempt=null,this.status=us.Connected,this.emit("status",{status:us.Connected}),this.emit("connect"),this.messageQueue.forEach(e=>this.send(e)),this.messageQueue=[])}stopConnectionAttempt(){this.connectionAttempt=null}rejectConnectionAttempt(){this.connectionAttempt?.reject(),this.connectionAttempt=null}checkConnection(){this.status===us.Connected&&this.lastMessageReceived&&(this.configuration.messageReconnectTimeout>=a.getUnixTime()-this.lastMessageReceived||(this.closeTries+=1,this.closeTries>2?(this.onClose({event:{code:4408,reason:"forced"}}),this.closeTries=0):(this.webSocket?.close(),this.messageQueue=[])))}get serverUrl(){if(this.configuration.preserveTrailingSlash)return this.configuration.url;let e=this.configuration.url;for(;"/"===e[e.length-1];)e=e.slice(0,e.length-1);return e}get url(){return this.serverUrl}disconnect(){if(this.shouldConnect=!1,null!==this.webSocket)try{this.webSocket.close(),this.messageQueue=[]}catch(e){}}parseQueuedMessage(e){try{const t=a.createDecoder(e);return{documentName:a.readVarString(t),messageType:a.readVarUint(t)}}catch{return null}}addToQueue(t){if(t instanceof Uint8Array){const n=this.parseQueuedMessage(t);n&&e.DEDUPLICATABLE_TYPES.has(n.messageType)&&(this.messageQueue=this.messageQueue.filter(e=>{if(!(e instanceof Uint8Array))return!0;const t=this.parseQueuedMessage(e);return!t||!(t.documentName===n.documentName&&t.messageType===n.messageType)}))}this.messageQueue.push(t)}send(e){this.webSocket?.readyState===Y.Open?this.webSocket.send(e):this.addToQueue(e)}onClose({event:e}){this.closeTries=0,this.cleanupWebSocket(),this.connectionAttempt&&this.rejectConnectionAttempt(),this.status=us.Disconnected,this.emit("status",{status:us.Disconnected}),this.emit("disconnect",{event:e}),!this.cancelWebsocketRetry&&this.shouldConnect&&setTimeout(()=>{this.connect()},this.configuration.delay)}destroy(){this.emit("destroy"),clearInterval(this.intervals.connectionChecker),this.stopConnectionAttempt(),this.disconnect(),this.removeAllListeners(),this.cleanupWebSocket()}},ms=class{constructor(e){this.message=e}apply(e,t){const{message:n}=this,r=n.readVarUint(),i=n.length();switch(r){case hs.Sync:this.applySyncMessage(e,t);break;case hs.Awareness:this.applyAwarenessMessage(e);break;case hs.Auth:this.applyAuthMessage(e);break;case hs.QueryAwareness:this.applyQueryAwarenessMessage(e);break;case hs.Stateless:e.receiveStateless(a.readVarString(n.decoder));break;case hs.SyncStatus:this.applySyncStatusMessage(e,1===a.readVarInt(n.decoder));break;case hs.CLOSE:{const t={code:1e3,reason:a.readVarString(n.decoder)};e.onClose(),e.configuration.onClose({event:t}),e.forwardClose({event:t});break}}n.length()>i+1&&e.send(fs,{encoder:n.encoder})}applySyncMessage(e,t){const{message:n}=this;n.writeVarUint(hs.Sync);const r=cs(n.decoder,n.encoder,e.document,e);t&&1===r&&(e.synced=!0)}applySyncStatusMessage(e,t){t&&e.decrementUnsyncedChanges()}applyAwarenessMessage(e){if(!e.awareness)return;const{message:t}=this;ns(e.awareness,t.readVarUint8Array(),e)}applyAuthMessage(e){const{message:t}=this;F(t.decoder,e.sendToken.bind(e),e.permissionDeniedHandler.bind(e),e.authenticatedHandler.bind(e))}applyQueryAwarenessMessage(e){if(!e.awareness)return;const{message:t}=this;t.writeVarUint(hs.Awareness),t.writeVarUint8Array(ts(e.awareness,Array.from(e.awareness.getStates().keys())))}},ys=class{constructor(e,t={}){this.message=new e,this.encoder=this.message.get(t)}create(){return a.toUint8Array(this.encoder)}send(e){e?.send(this.create())}},ws=class extends fs{constructor(...e){super(...e),this.type=hs.Auth,this.description="Authentication"}get(e){if(void 0===e.token)throw new Error("The authentication message requires `token` as an argument.");return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),V(this.encoder,e.token),a.writeVarString(this.encoder,"4.6.0"),this.encoder}},bs=class extends fs{constructor(...e){super(...e),this.type=hs.Awareness,this.description="Awareness states update"}get(e){if(void 0===e.awareness)throw new Error("The awareness message requires awareness as an argument");if(void 0===e.clients)throw new Error("The awareness message requires clients as an argument");let t;return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),t=void 0===e.states?ts(e.awareness,e.clients):ts(e.awareness,e.clients,e.states),a.writeVarUint8Array(this.encoder,t),this.encoder}},vs=class extends fs{constructor(...e){super(...e),this.type=hs.Stateless,this.description="A stateless message"}get(e){return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),a.writeVarString(this.encoder,e.payload??""),this.encoder}},_s=class extends fs{constructor(...e){super(...e),this.type=hs.Sync,this.description="First sync step"}get(e){if(void 0===e.document)throw new Error("The sync step one message requires document as an argument");return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),rs(this.encoder,e.document),this.encoder}},Ss=class extends fs{constructor(...e){super(...e),this.type=hs.Sync,this.description="A document update"}get(e){return a.writeVarString(this.encoder,e.documentName),a.writeVarUint(this.encoder,this.type),os(this.encoder,e.update),this.encoder}},ks=class extends Error{constructor(...e){super(...e),this.code=1001}},Cs=class extends ls{get effectiveName(){return this.configuration.sessionAwareness?H(this.configuration.name,this.sessionId):this.configuration.name}constructor(e){super(),this.configuration={name:"",document:void 0,awareness:void 0,token:null,sessionAwareness:!1,forceSyncInterval:!1,flushDelay:!1,onAuthenticated:()=>null,onAuthenticationFailed:()=>null,onOpen:()=>null,onConnect:()=>null,onMessage:()=>null,onOutgoingMessage:()=>null,onSynced:()=>null,onStatus:()=>null,onDisconnect:()=>null,onClose:()=>null,onDestroy:()=>null,onAwarenessUpdate:()=>null,onAwarenessChange:()=>null,onStateless:()=>null,onUnsyncedChanges:()=>null},this.isSynced=!1,this.unsyncedChanges=0,this.isAuthenticated=!1,this.authorizedScope=void 0,this.manageSocket=!1,this._isAttached=!1,this.pendingUpdates=[],this.pendingAwarenessClients=new Set,this.flushTimeout=null,this.sessionId=Math.random().toString(36).slice(2),this.intervals={forceSync:null},this.boundDocumentUpdateHandler=this.documentUpdateHandler.bind(this),this.boundAwarenessUpdateHandler=this.awarenessUpdateHandler.bind(this),this.boundPageHide=this.pageHide.bind(this),this.boundOnOpen=this.onOpen.bind(this),this.boundOnClose=this.onClose.bind(this),this.forwardConnect=()=>this.emit("connect"),this.forwardStatus=e=>this.emit("status",e),this.forwardClose=e=>this.emit("close",e),this.forwardDisconnect=e=>this.emit("disconnect",e),this.forwardDestroy=()=>this.emit("destroy"),this.setConfiguration(e),this.configuration.document=e.document?e.document:new nt,this.configuration.awareness=void 0!==e.awareness?e.awareness:new Zi(this.document),this.on("open",this.configuration.onOpen),this.on("message",this.configuration.onMessage),this.on("outgoingMessage",this.configuration.onOutgoingMessage),this.on("synced",this.configuration.onSynced),this.on("destroy",this.configuration.onDestroy),this.on("awarenessUpdate",this.configuration.onAwarenessUpdate),this.on("awarenessChange",this.configuration.onAwarenessChange),this.on("stateless",this.configuration.onStateless),this.on("unsyncedChanges",this.configuration.onUnsyncedChanges),this.on("authenticated",this.configuration.onAuthenticated),this.on("authenticationFailed",this.configuration.onAuthenticationFailed),this.awareness?.on("update",()=>{this.emit("awarenessUpdate",{states:B(this.awareness.getStates())})}),this.awareness?.on("change",()=>{this.emit("awarenessChange",{states:B(this.awareness.getStates())})}),this.document.on("update",this.boundDocumentUpdateHandler),this.awareness?.on("update",this.boundAwarenessUpdateHandler),this.registerEventListeners(),this.configuration.forceSyncInterval&&"number"==typeof this.configuration.forceSyncInterval&&(this.intervals.forceSync=setInterval(this.forceSync.bind(this),this.configuration.forceSyncInterval)),this.manageSocket&&this.attach()}setConfiguration(e={}){e.websocketProvider||(this.manageSocket=!0,this.configuration.websocketProvider=new ps(e)),this.configuration={...this.configuration,...e}}get document(){return this.configuration.document}get isAttached(){return this._isAttached}get awareness(){return this.configuration.awareness}get hasUnsyncedChanges(){return this.unsyncedChanges>0}resetUnsyncedChanges(){this.unsyncedChanges=1,this.emit("unsyncedChanges",{number:this.unsyncedChanges})}incrementUnsyncedChanges(){this.unsyncedChanges+=1,this.emit("unsyncedChanges",{number:this.unsyncedChanges})}decrementUnsyncedChanges(){this.unsyncedChanges>0&&(this.unsyncedChanges-=1),0===this.unsyncedChanges&&(this.synced=!0),this.emit("unsyncedChanges",{number:this.unsyncedChanges})}forceSync(){this.resetUnsyncedChanges(),this.send(_s,{document:this.document,documentName:this.effectiveName})}pageHide(){this.awareness&&es(this.awareness,[this.document.clientID],"page hide")}registerEventListeners(){"undefined"!=typeof window&&"addEventListener"in window&&window.addEventListener("pagehide",this.boundPageHide)}sendStateless(e){this.send(vs,{documentName:this.effectiveName,payload:e})}async sendToken(){let e;try{e=await this.getToken()}catch(t){return void this.permissionDeniedHandler(`Failed to get token during sendToken(): ${t}`)}this.send(ws,{token:e??"",documentName:this.effectiveName})}get batchingEnabled(){return!!this.configuration.flushDelay&&"number"==typeof this.configuration.flushDelay}documentUpdateHandler(e,t){if(t!==this){if(!this.batchingEnabled)return this.incrementUnsyncedChanges(),void this.send(Ss,{update:e,documentName:this.effectiveName});0===this.pendingUpdates.length&&this.incrementUnsyncedChanges(),this.pendingUpdates.push(e),this.scheduleFlush()}}awarenessUpdateHandler({added:e,updated:t,removed:n},r){if(r===this)return;const i=e.concat(t).concat(n);if(this.batchingEnabled){for(const e of i)this.pendingAwarenessClients.add(e);this.scheduleFlush()}else this.send(bs,{awareness:this.awareness,clients:i,documentName:this.effectiveName})}scheduleFlush(){null===this.flushTimeout&&(this.flushTimeout=setTimeout(()=>{this.flushTimeout=null,this.flushPendingUpdates()},this.configuration.flushDelay))}flushPendingUpdates(){if(null!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.pendingUpdates.length>0){const e=1===this.pendingUpdates.length?this.pendingUpdates[0]:un(this.pendingUpdates);this.pendingUpdates=[],this.send(Ss,{update:e,documentName:this.effectiveName})}if(this.pendingAwarenessClients.size>0){const e=Array.from(this.pendingAwarenessClients);this.pendingAwarenessClients.clear(),this.send(bs,{awareness:this.awareness,clients:e,documentName:this.effectiveName})}}get synced(){return this.isSynced}set synced(e){this.isSynced!==e&&(this.isSynced=e,e&&this.emit("synced",{state:e}))}receiveStateless(e){this.emit("stateless",{payload:e})}async connect(){if(this.manageSocket)return this.configuration.websocketProvider.connect()}disconnect(){if(this.manageSocket)return this.configuration.websocketProvider.disconnect()}async onOpen(e){this.isAuthenticated=!1,this.emit("open",{event:e}),await this.sendToken(),this.startSync()}async getToken(){return"function"==typeof this.configuration.token?await this.configuration.token():this.configuration.token}startSync(){this.resetUnsyncedChanges(),this.send(_s,{document:this.document,documentName:this.effectiveName}),this.awareness&&null!==this.awareness.getLocalState()&&this.send(bs,{awareness:this.awareness,clients:[this.document.clientID],documentName:this.effectiveName})}send(e,t){if(!this._isAttached)return;const n=new ys(e,t);this.emit("outgoingMessage",{message:n.message}),n.send(this.configuration.websocketProvider)}onMessage(e){const t=new ds(e.data),{documentName:n}=W(t.readVarString());t.writeVarString(this.effectiveName),this.emit("message",{event:e,message:new ds(e.data)}),new ms(t).apply(this,!0)}onClose(){this.isAuthenticated=!1,this.synced=!1,null!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.pendingUpdates=[],this.pendingAwarenessClients.clear(),this.awareness&&es(this.awareness,Array.from(this.awareness.getStates().keys()).filter(e=>e!==this.document.clientID),this)}destroy(){this.emit("destroy"),this.intervals.forceSync&&clearInterval(this.intervals.forceSync),this.awareness&&(es(this.awareness,[this.document.clientID],"provider destroy"),this.awareness.off("update",this.boundAwarenessUpdateHandler),this.awareness.destroy()),this.flushPendingUpdates(),this.document.off("update",this.boundDocumentUpdateHandler),this.removeAllListeners(),this.detach(),this.manageSocket&&this.configuration.websocketProvider.destroy(),"undefined"!=typeof window&&"removeEventListener"in window&&window.removeEventListener("pagehide",this.boundPageHide)}detach(){this.configuration.websocketProvider.off("connect",this.configuration.onConnect),this.configuration.websocketProvider.off("connect",this.forwardConnect),this.configuration.websocketProvider.off("status",this.forwardStatus),this.configuration.websocketProvider.off("status",this.configuration.onStatus),this.configuration.websocketProvider.off("open",this.boundOnOpen),this.configuration.websocketProvider.off("close",this.boundOnClose),this.configuration.websocketProvider.off("close",this.configuration.onClose),this.configuration.websocketProvider.off("close",this.forwardClose),this.configuration.websocketProvider.off("disconnect",this.configuration.onDisconnect),this.configuration.websocketProvider.off("disconnect",this.forwardDisconnect),this.configuration.websocketProvider.off("destroy",this.configuration.onDestroy),this.configuration.websocketProvider.off("destroy",this.forwardDestroy),this.configuration.websocketProvider.detach(this),this._isAttached=!1}attach(){this._isAttached||(this.configuration.websocketProvider.on("connect",this.configuration.onConnect),this.configuration.websocketProvider.on("connect",this.forwardConnect),this.configuration.websocketProvider.on("status",this.configuration.onStatus),this.configuration.websocketProvider.on("status",this.forwardStatus),this.configuration.websocketProvider.on("open",this.boundOnOpen),this.configuration.websocketProvider.on("close",this.boundOnClose),this.configuration.websocketProvider.on("close",this.configuration.onClose),this.configuration.websocketProvider.on("close",this.forwardClose),this.configuration.websocketProvider.on("disconnect",this.configuration.onDisconnect),this.configuration.websocketProvider.on("disconnect",this.forwardDisconnect),this.configuration.websocketProvider.on("destroy",this.configuration.onDestroy),this.configuration.websocketProvider.on("destroy",this.forwardDestroy),this.configuration.websocketProvider.attach(this),this._isAttached=!0)}permissionDeniedHandler(e){this.emit("authenticationFailed",{reason:e}),this.isAuthenticated=!1}authenticatedHandler(e){this.isAuthenticated=!0,this.authorizedScope=e,this.emit("authenticated",{scope:e})}setAwarenessField(e,t){if(!this.awareness)throw new ks(`Cannot set awareness field "${e}" to ${JSON.stringify(t)}. You have disabled Awareness for this provider by explicitly passing awareness: null in the provider configuration.`);this.awareness.setLocalStateField(e,t)}},Es=e=>a.create((t,n)=>{e.onerror=e=>n(new Error(e.target.error)),e.onsuccess=e=>t(e.target.result)}),As=(e,t,n="readwrite")=>{const r=e.transaction(t,n);return t.map(e=>Us(r,e))},xs=(e,t)=>Es(e.count(t)),Ts=(e,t)=>Es(e.delete(t)),Rs=(e,t)=>Es(e.add(t)),Ds=(e,t=null)=>((e,t,n)=>{let r=null;return Os(e,t,e=>(r=e,!1),n).then(()=>r)})(e,t,"prev"),Os=(e,t,n,r="next")=>((e,t)=>a.create((n,r)=>{e.onerror=r,e.onsuccess=async e=>{const r=e.target.result;if(null===r||!1===await t(r))return n();r.continue()}}))(e.openKeyCursor(t,r),e=>n(e.key)),Us=(e,t)=>e.objectStore(t),Ps="custom",Ls="updates",Ms=(e,t=()=>{},n=()=>{})=>{const[r]=As(e.db,[Ls]);return(i=r,a=e._dbref,c=!1,s=IDBKeyRange.lowerBound(a,c),Es(i.getAll(s,o))).then(i=>{e._destroyed||(t(r),sn(e.doc,()=>{i.forEach(t=>gt(e.doc,t))},e,!1),n(r))}).then(()=>Ds(r).then(t=>{e._dbref=t+1})).then(()=>xs(r).then(t=>{e._dbsize=t})).then(()=>r);var i,s,o,a,c},Is=(e,t=!0)=>Ms(e).then(n=>{(t||e._dbsize>=500)&&Rs(n,mt(e.doc)).then(()=>{return Ts(n,(t=e._dbref,r=!0,IDBKeyRange.upperBound(t,r)));var t,r}).then(()=>xs(n).then(t=>{e._dbsize=t}))}),Ns=class extends a.Observable{constructor(e,t){super(),this.doc=t,this.name=e,this._dbref=0,this._dbsize=0,this._destroyed=!1,this.db=null,this.synced=!1,this._db=((e,t)=>a.create((n,r)=>{const i=indexedDB.open(e);i.onupgradeneeded=e=>t(e.target.result),i.onerror=e=>r(a.create$1(e.target.error)),i.onsuccess=e=>{const t=e.target.result;t.onversionchange=()=>{t.close()},n(t)}}))(e,e=>((e,t)=>t.forEach(t=>e.createObjectStore.apply(e,t)))(e,[["updates",{autoIncrement:!0}],["custom"]])),this.whenSynced=a.create(e=>this.on("synced",()=>e(this))),this._db.then(e=>{this.db=e;Ms(this,e=>Rs(e,mt(t)),()=>{if(this._destroyed)return this;this.synced=!0,this.emit("synced",[this])})}),this._storeTimeout=1e3,this._storeTimeoutId=null,this._storeUpdate=(e,t)=>{if(this.db&&t!==this){const[t]=As(this.db,[Ls]);Rs(t,e),++this._dbsize>=500&&(null!==this._storeTimeoutId&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{Is(this,!1),this._storeTimeoutId=null},this._storeTimeout))}},t.on("update",this._storeUpdate),this.destroy=this.destroy.bind(this),t.on("destroy",this.destroy)}destroy(){return this._storeTimeoutId&&clearTimeout(this._storeTimeoutId),this.doc.off("update",this._storeUpdate),this.doc.off("destroy",this.destroy),this._destroyed=!0,this._db.then(e=>{e.close()})}clearData(){return this.destroy().then(()=>{var e;e=this.name,Es(indexedDB.deleteDatabase(e))})}get(e){return this._db.then(t=>{const[n]=As(t,[Ps],"readonly");return((e,t)=>Es(e.get(t)))(n,e)})}set(e,t){return this._db.then(n=>{const[r]=As(n,[Ps]);return((e,t,n)=>Es(e.put(t,n)))(r,t,e)})}del(e){return this._db.then(t=>{const[n]=As(t,[Ps]);return Ts(n,e)})}},js=3e4,Vs=e=>{if(e.shouldConnect&&null===e.ws){const t=new WebSocket(e.url),n=e.binaryType;let r=null;n&&(t.binaryType=n),e.ws=t,e.connecting=!0,e.connected=!1,t.onmessage=t=>{e.lastMessageReceived=a.getUnixTime();const n=t.data,i="string"==typeof n?JSON.parse(n):n;i&&"pong"===i.type&&(clearTimeout(r),r=setTimeout(s,15e3)),e.emit("message",[i,e])};const i=t=>{null!==e.ws&&(e.ws=null,e.connecting=!1,e.connected?(e.connected=!1,e.emit("disconnect",[{type:"disconnect",error:t},e])):e.unsuccessfulReconnects++,setTimeout(Vs,a.min(1200*a.log10(e.unsuccessfulReconnects+1),2500),e)),clearTimeout(r)},s=()=>{e.ws===t&&e.send({type:"ping"})};t.onclose=()=>i(null),t.onerror=e=>i(e),t.onopen=()=>{e.lastMessageReceived=a.getUnixTime(),e.connecting=!1,e.connected=!0,e.unsuccessfulReconnects=0,e.emit("connect",[{type:"connect"},e]),r=setTimeout(s,15e3)}}},Fs=class extends a.Observable{constructor(e,{binaryType:t}={}){super(),this.url=e,this.ws=null,this.binaryType=t||null,this.connected=!1,this.connecting=!1,this.unsuccessfulReconnects=0,this.lastMessageReceived=0,this.shouldConnect=!0,this._checkInterval=setInterval(()=>{this.connected&&js<a.getUnixTime()-this.lastMessageReceived&&this.ws.close()},15e3),Vs(this)}send(e){this.ws&&this.ws.send(JSON.stringify(e))}destroy(){clearInterval(this._checkInterval),this.disconnect(),super.destroy()}disconnect(){this.shouldConnect=!1,null!==this.ws&&this.ws.close()}connect(){this.shouldConnect=!0,this.connected||null!==this.ws||Vs(this)}},Bs=new Map,Hs="undefined"==typeof BroadcastChannel?class{constructor(e){this.room=e,this.onmessage=null,this._onChange=t=>t.key===e&&null!==this.onmessage&&this.onmessage({data:a.fromBase64(t.newValue||"")}),a.onChange(this._onChange)}postMessage(e){a.varStorage.setItem(this.room,a.toBase64(a.createUint8ArrayFromArrayBuffer(e)))}close(){a.offChange(this._onChange)}}:BroadcastChannel,Ws=e=>a.setIfUndefined(Bs,e,()=>{const t=a.create$2(),n=new Hs(e);return n.onmessage=e=>t.forEach(t=>t(e.data,"broadcastchannel")),{bc:n,subs:t}}),Ys=e.__commonJSMin((e,t)=>{!function(n){if("object"==typeof e&&void 0!==t)t.exports=n();else if("function"==typeof define&&define.amd)define([],n);else{("undefined"==typeof window?"undefined"==typeof global?"undefined"==typeof self?this:self:global:window).SimplePeer=n()}}(function(){var e=Math.floor,t=Math.abs,n=Math.pow;return function e(t,n,r){function i(o,a){if(!n[o]){if(!t[o]){var c="function"==typeof require&&require;if(!a&&c)return c(o,!0);if(s)return s(o,!0);var l=new Error("Cannot find module '"+o+"'");throw l.code="MODULE_NOT_FOUND",l}var d=n[o]={exports:{}};t[o][0].call(d.exports,function(e){return i(t[o][1][e]||e)},d,d.exports,e,t,n,r)}return n[o].exports}for(var s="function"==typeof require&&require,o=0;o<r.length;o++)i(r[o]);return i}({1:[function(e,t,n){"use strict";function r(e){var t=e.length;if(0<t%4)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function i(e){return o[63&e>>18]+o[63&e>>12]+o[63&e>>6]+o[63&e]}function s(e,t,n){for(var r,s=[],o=t;o<n;o+=3)r=(16711680&e[o]<<16)+(65280&e[o+1]<<8)+(255&e[o+2]),s.push(i(r));return s.join("")}n.byteLength=function(e){var t=r(e),n=t[0],i=t[1];return 3*(n+i)/4-i},n.toByteArray=function(e){var t,n,i=r(e),s=i[0],o=i[1],l=new c(function(e,t,n){return 3*(t+n)/4-n}(0,s,o)),d=0,h=0<o?s-4:s;for(n=0;n<h;n+=4)t=a[e.charCodeAt(n)]<<18|a[e.charCodeAt(n+1)]<<12|a[e.charCodeAt(n+2)]<<6|a[e.charCodeAt(n+3)],l[d++]=255&t>>16,l[d++]=255&t>>8,l[d++]=255&t;return 2===o&&(t=a[e.charCodeAt(n)]<<2|a[e.charCodeAt(n+1)]>>4,l[d++]=255&t),1===o&&(t=a[e.charCodeAt(n)]<<10|a[e.charCodeAt(n+1)]<<4|a[e.charCodeAt(n+2)]>>2,l[d++]=255&t>>8,l[d++]=255&t),l},n.fromByteArray=function(e){for(var t,n=e.length,r=n%3,i=[],a=16383,c=0,l=n-r;c<l;c+=a)i.push(s(e,c,c+a>l?l:c+a));return 1===r?(t=e[n-1],i.push(o[t>>2]+o[63&t<<4]+"==")):2===r&&(t=(e[n-2]<<8)+e[n-1],i.push(o[t>>10]+o[63&t>>4]+o[63&t<<2]+"=")),i.join("")};for(var o=[],a=[],c="undefined"==typeof Uint8Array?Array:Uint8Array,l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",d=0;d<64;++d)o[d]=l[d],a[l.charCodeAt(d)]=d;a[45]=62,a[95]=63},{}],2:[function(){},{}],3:[function(e,t,r){(function(){(function(){"use strict";var t=String.fromCharCode,i=Math.min;function s(e){if(2147483647<e)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=o.prototype,t}function o(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return l(e)}return a(e,t,n)}function a(e,t,n){if("string"==typeof e)return function(e,t){if(("string"!=typeof t||""===t)&&(t="utf8"),!o.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var n=0|u(e,t),r=s(n),i=r.write(e,t);return i!==n&&(r=r.slice(0,i)),r}(e,t);if(ArrayBuffer.isView(e))return d(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(V(e,ArrayBuffer)||e&&V(e.buffer,ArrayBuffer))return function(e,t,n){if(0>t||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');var r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n);return r.__proto__=o.prototype,r}(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return o.from(r,t,n);var i=function(e){if(o.isBuffer(e)){var t=0|h(e.length),n=s(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0===e.length?"Buffer"===e.type&&Array.isArray(e.data)?d(e.data):void 0:"number"!=typeof e.length||F(e.length)?s(0):d(e)}(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return o.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function c(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(0>e)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function l(e){return c(e),s(0>e?0:0|h(e))}function d(e){for(var t=0>e.length?0:0|h(e.length),n=s(t),r=0;r<t;r+=1)n[r]=255&e[r];return n}function h(e){if(e>=2147483647)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+2147483647..toString(16)+" bytes");return 0|e}function u(e,t){if(o.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||V(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var n=e.length,r=2<arguments.length&&!0===arguments[2];if(!r&&0===n)return 0;for(var i=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return I(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return N(e).length;default:if(i)return r?-1:I(e).length;t=(""+t).toLowerCase(),i=!0}}function f(e,t,n){var r=!1;if((void 0===t||0>t)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),0>=n)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return T(this,t,n);case"utf8":case"utf-8":return C(this,t,n);case"ascii":return A(this,t,n);case"latin1":case"binary":return x(this,t,n);case"base64":return k(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function g(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function p(e,t,n,r,i){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):2147483647<n?n=2147483647:-2147483648>n&&(n=-2147483648),F(n=+n)&&(n=i?0:e.length-1),0>n&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(0>n){if(!i)return-1;n=0}if("string"==typeof t&&(t=o.from(t,r)),o.isBuffer(t))return 0===t.length?-1:m(e,t,n,r,i);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):m(e,[t],n,r,i);throw new TypeError("val must be string, number or Buffer")}function m(e,t,n,r,i){function s(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}var o,a=1,c=e.length,l=t.length;if(void 0!==r&&("ucs2"===(r=(r+"").toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(2>e.length||2>t.length)return-1;a=2,c/=2,l/=2,n/=2}if(i){var d=-1;for(o=n;o<c;o++)if(s(e,o)!==s(t,-1===d?0:o-d))-1!==d&&(o-=o-d),d=-1;else if(-1===d&&(d=o),o-d+1===l)return d*a}else for(n+l>c&&(n=c-l),o=n;0<=o;o--){for(var h=!0,u=0;u<l;u++)if(s(e,o+u)!==s(t,u)){h=!1;break}if(h)return o}return-1}function y(e,t,n,r){n=+n||0;var i=e.length-n;r?(r=+r)>i&&(r=i):r=i;var s=t.length;r>s/2&&(r=s/2);for(var o,a=0;a<r;++a){if(F(o=parseInt(t.substr(2*a,2),16)))return a;e[n+a]=o}return a}function w(e,t,n,r){return j(I(t,e.length-n),e,n,r)}function b(e,t,n,r){return j(function(e){for(var t=[],n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function v(e,t,n,r){return b(e,t,n,r)}function _(e,t,n,r){return j(N(t),e,n,r)}function S(e,t,n,r){return j(function(e,t){for(var n,r,i,s=[],o=0;o<e.length&&!(0>(t-=2));++o)n=e.charCodeAt(o),r=n>>8,i=n%256,s.push(i),s.push(r);return s}(t,e.length-n),e,n,r)}function k(e,t,n){return 0===t&&n===e.length?B.fromByteArray(e):B.fromByteArray(e.slice(t,n))}function C(e,t,n){n=i(e.length,n);for(var r=[],s=t;s<n;){var o,a,c,l,d=e[s],h=null,u=239<d?4:223<d?3:191<d?2:1;if(s+u<=n)1===u?128>d&&(h=d):2===u?128==(192&(o=e[s+1]))&&(127<(l=(31&d)<<6|63&o)&&(h=l)):3===u?(o=e[s+1],a=e[s+2],128==(192&o)&&128==(192&a)&&(2047<(l=(15&d)<<12|(63&o)<<6|63&a)&&(55296>l||57343<l)&&(h=l))):4===u&&(o=e[s+1],a=e[s+2],c=e[s+3],128==(192&o)&&128==(192&a)&&128==(192&c)&&(65535<(l=(15&d)<<18|(63&o)<<12|(63&a)<<6|63&c)&&1114112>l&&(h=l)));null===h?(h=65533,u=1):65535<h&&(h-=65536,r.push(55296|1023&h>>>10),h=56320|1023&h),r.push(h),s+=u}return E(r)}function E(e){var n=e.length;if(n<=4096)return t.apply(String,e);for(var r="",i=0;i<n;)r+=t.apply(String,e.slice(i,i+=4096));return r}function A(e,n,r){var s="";r=i(e.length,r);for(var o=n;o<r;++o)s+=t(127&e[o]);return s}function x(e,n,r){var s="";r=i(e.length,r);for(var o=n;o<r;++o)s+=t(e[o]);return s}function T(e,t,n){var r=e.length;(!t||0>t)&&(t=0),(!n||0>n||n>r)&&(n=r);for(var i="",s=t;s<n;++s)i+=M(e[s]);return i}function R(e,n,r){for(var i=e.slice(n,r),s="",o=0;o<i.length;o+=2)s+=t(i[o]+256*i[o+1]);return s}function D(e,t,n){if(0!=e%1||0>e)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function O(e,t,n,r,i,s){if(!o.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<s)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function U(e,t,n,r){if(n+r>e.length)throw new RangeError("Index out of range");if(0>n)throw new RangeError("Index out of range")}function P(e,t,n,r,i){return t=+t,n>>>=0,i||U(e,0,n,4),H.write(e,t,n,r,23,4),n+4}function L(e,t,n,r,i){return t=+t,n>>>=0,i||U(e,0,n,8),H.write(e,t,n,r,52,8),n+8}function M(e){return 16>e?"0"+e.toString(16):e.toString(16)}function I(e,t){t=t||1/0;for(var n,r=e.length,i=null,s=[],o=0;o<r;++o){if(55295<(n=e.charCodeAt(o))&&57344>n){if(!i){if(56319<n){-1<(t-=3)&&s.push(239,191,189);continue}if(o+1===r){-1<(t-=3)&&s.push(239,191,189);continue}i=n;continue}if(56320>n){-1<(t-=3)&&s.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&-1<(t-=3)&&s.push(239,191,189);if(i=null,128>n){if(0>(t-=1))break;s.push(n)}else if(2048>n){if(0>(t-=2))break;s.push(192|n>>6,128|63&n)}else if(65536>n){if(0>(t-=3))break;s.push(224|n>>12,128|63&n>>6,128|63&n)}else{if(!(1114112>n))throw new Error("Invalid code point");if(0>(t-=4))break;s.push(240|n>>18,128|63&n>>12,128|63&n>>6,128|63&n)}}return s}function N(e){return B.toByteArray(function(e){if(2>(e=(e=e.split("=")[0]).trim().replace(W,"")).length)return"";for(;0!=e.length%4;)e+="=";return e}(e))}function j(e,t,n,r){for(var i=0;i<r&&!(i+n>=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function V(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function F(e){return e!=e}var B=e("base64-js"),H=e("ieee754");r.Buffer=o,r.SlowBuffer=function(e){return+e!=e&&(e=0),o.alloc(+e)},r.INSPECT_MAX_BYTES=50,r.kMaxLength=2147483647,o.TYPED_ARRAY_SUPPORT=function(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(t){return!1}}(),o.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||console.error,Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){return o.isBuffer(this)?this.buffer:void 0}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){return o.isBuffer(this)?this.byteOffset:void 0}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&o[Symbol.species]===o&&Object.defineProperty(o,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),o.poolSize=8192,o.from=function(e,t,n){return a(e,t,n)},o.prototype.__proto__=Uint8Array.prototype,o.__proto__=Uint8Array,o.alloc=function(e,t,n){return function(e,t,n){return c(e),0>=e||void 0===t?s(e):"string"==typeof n?s(e).fill(t,n):s(e).fill(t)}(e,t,n)},o.allocUnsafe=function(e){return l(e)},o.allocUnsafeSlow=function(e){return l(e)},o.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==o.prototype},o.compare=function(e,t){if(V(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),V(t,Uint8Array)&&(t=o.from(t,t.offset,t.byteLength)),!o.isBuffer(e)||!o.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var n=e.length,r=t.length,s=0,a=i(n,r);s<a;++s)if(e[s]!==t[s]){n=e[s],r=t[s];break}return n<r?-1:r<n?1:0},o.isEncoding=function(e){switch((e+"").toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},o.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return o.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=o.allocUnsafe(t),i=0;for(n=0;n<e.length;++n){var s=e[n];if(V(s,Uint8Array)&&(s=o.from(s)),!o.isBuffer(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(r,i),i+=s.length}return r},o.byteLength=u,o.prototype._isBuffer=!0,o.prototype.swap16=function(){var e=this.length;if(0!=e%2)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)g(this,t,t+1);return this},o.prototype.swap32=function(){var e=this.length;if(0!=e%4)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)g(this,t,t+3),g(this,t+1,t+2);return this},o.prototype.swap64=function(){var e=this.length;if(0!=e%8)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)g(this,t,t+7),g(this,t+1,t+6),g(this,t+2,t+5),g(this,t+3,t+4);return this},o.prototype.toString=function(){var e=this.length;return 0===e?"":0===arguments.length?C(this,0,e):f.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(e){if(!o.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===o.compare(this,e)},o.prototype.inspect=function(){var e="",t=r.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),"<Buffer "+e+">"},o.prototype.compare=function(e,t,n,r,s){if(V(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),!o.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===s&&(s=this.length),0>t||n>e.length||0>r||s>this.length)throw new RangeError("out of range index");if(r>=s&&t>=n)return 0;if(r>=s)return-1;if(t>=n)return 1;if(this===e)return 0;for(var a=(s>>>=0)-(r>>>=0),c=(n>>>=0)-(t>>>=0),l=i(a,c),d=this.slice(r,s),h=e.slice(t,n),u=0;u<l;++u)if(d[u]!==h[u]){a=d[u],c=h[u];break}return a<c?-1:c<a?1:0},o.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},o.prototype.indexOf=function(e,t,n){return p(this,e,t,n,!0)},o.prototype.lastIndexOf=function(e,t,n){return p(this,e,t,n,!1)},o.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var i=this.length-t;if((void 0===n||n>i)&&(n=i),0<e.length&&(0>n||0>t)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var s=!1;;)switch(r){case"hex":return y(this,e,t,n);case"utf8":case"utf-8":return w(this,e,t,n);case"ascii":return b(this,e,t,n);case"latin1":case"binary":return v(this,e,t,n);case"base64":return _(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},o.prototype.slice=function(e,t){var n=this.length;0>(e=~~e)?0>(e+=n)&&(e=0):e>n&&(e=n),0>(t=void 0===t?n:~~t)?0>(t+=n)&&(t=0):t>n&&(t=n),t<e&&(t=e);var r=this.subarray(e,t);return r.__proto__=o.prototype,r},o.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||D(e,t,this.length);for(var r=this[e],i=1,s=0;++s<t&&(i*=256);)r+=this[e+s]*i;return r},o.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||D(e,t,this.length);for(var r=this[e+--t],i=1;0<t&&(i*=256);)r+=this[e+--t]*i;return r},o.prototype.readUInt8=function(e,t){return e>>>=0,t||D(e,1,this.length),this[e]},o.prototype.readUInt16LE=function(e,t){return e>>>=0,t||D(e,2,this.length),this[e]|this[e+1]<<8},o.prototype.readUInt16BE=function(e,t){return e>>>=0,t||D(e,2,this.length),this[e]<<8|this[e+1]},o.prototype.readUInt32LE=function(e,t){return e>>>=0,t||D(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},o.prototype.readUInt32BE=function(e,t){return e>>>=0,t||D(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},o.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||D(e,t,this.length);for(var i=this[e],s=1,o=0;++o<t&&(s*=256);)i+=this[e+o]*s;return i>=(s*=128)&&(i-=n(2,8*t)),i},o.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||D(e,t,this.length);for(var i=t,s=1,o=this[e+--i];0<i&&(s*=256);)o+=this[e+--i]*s;return o>=(s*=128)&&(o-=n(2,8*t)),o},o.prototype.readInt8=function(e,t){return e>>>=0,t||D(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},o.prototype.readInt16LE=function(e,t){e>>>=0,t||D(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},o.prototype.readInt16BE=function(e,t){e>>>=0,t||D(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},o.prototype.readInt32LE=function(e,t){return e>>>=0,t||D(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},o.prototype.readInt32BE=function(e,t){return e>>>=0,t||D(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},o.prototype.readFloatLE=function(e,t){return e>>>=0,t||D(e,4,this.length),H.read(this,e,!0,23,4)},o.prototype.readFloatBE=function(e,t){return e>>>=0,t||D(e,4,this.length),H.read(this,e,!1,23,4)},o.prototype.readDoubleLE=function(e,t){return e>>>=0,t||D(e,8,this.length),H.read(this,e,!0,52,8)},o.prototype.readDoubleBE=function(e,t){return e>>>=0,t||D(e,8,this.length),H.read(this,e,!1,52,8)},o.prototype.writeUIntLE=function(e,t,r,i){(e=+e,t>>>=0,r>>>=0,i)||O(this,e,t,r,n(2,8*r)-1,0);var s=1,o=0;for(this[t]=255&e;++o<r&&(s*=256);)this[t+o]=255&e/s;return t+r},o.prototype.writeUIntBE=function(e,t,r,i){(e=+e,t>>>=0,r>>>=0,i)||O(this,e,t,r,n(2,8*r)-1,0);var s=r-1,o=1;for(this[t+s]=255&e;0<=--s&&(o*=256);)this[t+s]=255&e/o;return t+r},o.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,1,255,0),this[t]=255&e,t+1},o.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},o.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},o.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},o.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},o.prototype.writeIntLE=function(e,t,r,i){if(e=+e,t>>>=0,!i){var s=n(2,8*r-1);O(this,e,t,r,s-1,-s)}var o=0,a=1,c=0;for(this[t]=255&e;++o<r&&(a*=256);)0>e&&0===c&&0!==this[t+o-1]&&(c=1),this[t+o]=255&(e/a|0)-c;return t+r},o.prototype.writeIntBE=function(e,t,r,i){if(e=+e,t>>>=0,!i){var s=n(2,8*r-1);O(this,e,t,r,s-1,-s)}var o=r-1,a=1,c=0;for(this[t+o]=255&e;0<=--o&&(a*=256);)0>e&&0===c&&0!==this[t+o+1]&&(c=1),this[t+o]=255&(e/a|0)-c;return t+r},o.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,1,127,-128),0>e&&(e=255+e+1),this[t]=255&e,t+1},o.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},o.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},o.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},o.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,2147483647,-2147483648),0>e&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},o.prototype.writeFloatLE=function(e,t,n){return P(this,e,t,!0,n)},o.prototype.writeFloatBE=function(e,t,n){return P(this,e,t,!1,n)},o.prototype.writeDoubleLE=function(e,t,n){return L(this,e,t,!0,n)},o.prototype.writeDoubleBE=function(e,t,n){return L(this,e,t,!1,n)},o.prototype.copy=function(e,t,n,r){if(!o.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),0<r&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(0>t)throw new RangeError("targetStart out of bounds");if(0>n||n>=this.length)throw new RangeError("Index out of range");if(0>r)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);var i=r-n;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,n,r);else if(this===e&&n<t&&t<r)for(var s=i-1;0<=s;--s)e[s+t]=this[s+n];else Uint8Array.prototype.set.call(e,this.subarray(n,r),t);return i},o.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!o.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){var i=e.charCodeAt(0);("utf8"===r&&128>i||"latin1"===r)&&(e=i)}}else"number"==typeof e&&(e&=255);if(0>t||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;var s;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(s=t;s<n;++s)this[s]=e;else{var a=o.isBuffer(e)?e:o.from(e,r),c=a.length;if(0===c)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(s=0;s<n-t;++s)this[s+t]=a[s%c]}return this};var W=/[^+/0-9A-Za-z-_]/g}).call(this)}).call(this,e("buffer").Buffer)},{"base64-js":1,buffer:3,ieee754:9}],4:[function(e,t,n){(function(r){(function(){n.formatArgs=function(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;e.splice(1,0,n,"color: inherit");let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{"%%"===e||(r++,"%c"===e&&(i=r))}),e.splice(i,0,n)},n.save=function(e){try{e?n.storage.setItem("debug",e):n.storage.removeItem("debug")}catch(e){}},n.load=function(){let e;try{e=n.storage.getItem("debug")}catch(e){}return!e&&void 0!==r&&"env"in r&&(e=r.env.DEBUG),e},n.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||!("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&31<=parseInt(RegExp.$1,10)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},n.storage=function(){try{return localStorage}catch(e){}}(),n.destroy=(()=>{let e=!1;return()=>{e||(e=!0)}})(),n.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],n.log=console.debug||console.log||(()=>{}),t.exports=e("./common")(n);const{formatters:i}=t.exports;i.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}).call(this)}).call(this,e("_process"))},{"./common":5,_process:12}],5:[function(e,n){n.exports=function(n){function r(e){function t(...e){if(!t.enabled)return;const i=t,s=+new Date;i.diff=s-(n||s),i.prev=n,i.curr=s,n=s,e[0]=r.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,n)=>{if("%%"===t)return"%";o++;const s=r.formatters[n];if("function"==typeof s){const n=e[o];t=s.call(i,n),e.splice(o,1),o--}return t}),r.formatArgs.call(i,e),(i.log||r.log).apply(i,e)}let n,s=null;return t.namespace=e,t.useColors=r.useColors(),t.color=r.selectColor(e),t.extend=i,t.destroy=r.destroy,Object.defineProperty(t,"enabled",{enumerable:!0,configurable:!1,get:()=>null===s?r.enabled(e):s,set:e=>{s=e}}),"function"==typeof r.init&&r.init(t),t}function i(e,t){const n=r(this.namespace+(void 0===t?":":t)+e);return n.log=this.log,n}function s(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return r.debug=r,r.default=r,r.coerce=function(e){return e instanceof Error?e.stack||e.message:e},r.disable=function(){const e=[...r.names.map(s),...r.skips.map(s).map(e=>"-"+e)].join(",");return r.enable(""),e},r.enable=function(e){let t;r.save(e),r.names=[],r.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),i=n.length;for(t=0;t<i;t++)n[t]&&("-"===(e=n[t].replace(/\*/g,".*?"))[0]?r.skips.push(new RegExp("^"+e.substr(1)+"$")):r.names.push(new RegExp("^"+e+"$")))},r.enabled=function(e){if("*"===e[e.length-1])return!0;let t,n;for(t=0,n=r.skips.length;t<n;t++)if(r.skips[t].test(e))return!1;for(t=0,n=r.names.length;t<n;t++)if(r.names[t].test(e))return!0;return!1},r.humanize=e("ms"),r.destroy=function(){},Object.keys(n).forEach(e=>{r[e]=n[e]}),r.names=[],r.skips=[],r.formatters={},r.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return r.colors[t(n)%r.colors.length]},r.enable(r.load()),r}},{ms:11}],6:[function(e,t){"use strict";function n(e,t){for(const n in t)Object.defineProperty(e,n,{value:t[n],enumerable:!0,configurable:!0});return e}t.exports=function(e,t,r){if(!e||"string"==typeof e)throw new TypeError("Please pass an Error to err-code");r||(r={}),"object"==typeof t&&(r=t,t=""),t&&(r.code=t);try{return n(e,r)}catch(t){r.message=e.message,r.stack=e.stack;const i=function(){};return i.prototype=Object.create(Object.getPrototypeOf(e)),n(new i,r)}}},{}],7:[function(e,t){"use strict";function n(){n.init.call(this)}function r(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function i(e){return void 0===e._maxListeners?n.defaultMaxListeners:e._maxListeners}function s(e,t,n,s){var o,a,c;if(r(n),void 0===(a=e._events)?(a=e._events=Object.create(null),e._eventsCount=0):(void 0!==a.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),a=e._events),c=a[t]),void 0===c)c=a[t]=n,++e._eventsCount;else if("function"==typeof c?c=a[t]=s?[n,c]:[c,n]:s?c.unshift(n):c.push(n),0<(o=i(e))&&c.length>o&&!c.warned){c.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=c.length,console&&console.warn}return e}function o(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function a(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=o.bind(r);return i.listener=n,r.wrapFn=i,i}function c(e,t,n){var r=e._events;if(void 0===r)return[];var i=r[t];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]:n?function(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(i):d(i,i.length)}function l(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function d(e,t){for(var n=Array(t),r=0;r<t;++r)n[r]=e[r];return n}function h(e,t,n,r){if("function"==typeof e.on)r.once?e.once(t,n):e.on(t,n);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,function i(s){r.once&&e.removeEventListener(t,i),n(s)})}}var u,f="object"==typeof Reflect?Reflect:null,g=f&&"function"==typeof f.apply?f.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};u=f&&"function"==typeof f.ownKeys?f.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var p=Number.isNaN||function(e){return e!=e};t.exports=n,t.exports.once=function(e,t){return new Promise(function(n,r){function i(n){e.removeListener(t,s),r(n)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",i),n([].slice.call(arguments))}h(e,t,s,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&h(e,"error",t,n)}(e,i,{once:!0})})},n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var m=10;Object.defineProperty(n,"defaultMaxListeners",{enumerable:!0,get:function(){return m},set:function(e){if("number"!=typeof e||0>e||p(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");m=e}}),n.init=function(){(void 0===this._events||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},n.prototype.setMaxListeners=function(e){if("number"!=typeof e||0>e||p(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},n.prototype.getMaxListeners=function(){return i(this)},n.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var r="error"===e,i=this._events;if(void 0!==i)r=r&&void 0===i.error;else if(!r)return!1;if(r){var s;if(0<t.length&&(s=t[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var a=i[e];if(void 0===a)return!1;if("function"==typeof a)g(a,this,t);else{var c=a.length,l=d(a,c);for(n=0;n<c;++n)g(l[n],this,t)}return!0},n.prototype.addListener=function(e,t){return s(this,e,t,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(e,t){return s(this,e,t,!0)},n.prototype.once=function(e,t){return r(t),this.on(e,a(this,e,t)),this},n.prototype.prependOnceListener=function(e,t){return r(t),this.prependListener(e,a(this,e,t)),this},n.prototype.removeListener=function(e,t){var n,i,s,o,a;if(r(t),void 0===(i=this._events))return this;if(void 0===(n=i[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(s=-1,o=n.length-1;0<=o;o--)if(n[o]===t||n[o].listener===t){a=n[o].listener,s=o;break}if(0>s)return this;0===s?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,s),1===n.length&&(i[e]=n[0]),void 0!==i.removeListener&&this.emit("removeListener",e,a||t)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(e){var t,n,r=this._events;if(void 0===r)return this;if(void 0===r.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==r[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete r[e]),this;if(0===arguments.length){var i,s=Object.keys(r);for(n=0;n<s.length;++n)"removeListener"!==(i=s[n])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;0<=n;n--)this.removeListener(e,t[n]);return this},n.prototype.listeners=function(e){return c(this,e,!0)},n.prototype.rawListeners=function(e){return c(this,e,!1)},n.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):l.call(e,t)},n.prototype.listenerCount=l,n.prototype.eventNames=function(){return 0<this._eventsCount?u(this._events):[]}},{}],8:[function(e,t){t.exports=function(){if("undefined"==typeof globalThis)return null;var e={RTCPeerConnection:globalThis.RTCPeerConnection||globalThis.mozRTCPeerConnection||globalThis.webkitRTCPeerConnection,RTCSessionDescription:globalThis.RTCSessionDescription||globalThis.mozRTCSessionDescription||globalThis.webkitRTCSessionDescription,RTCIceCandidate:globalThis.RTCIceCandidate||globalThis.mozRTCIceCandidate||globalThis.webkitRTCIceCandidate};return e.RTCPeerConnection?e:null}},{}],9:[function(r,i,s){s.read=function(e,t,r,i,s){var o,a,c=8*s-i-1,l=(1<<c)-1,d=l>>1,h=-7,u=r?s-1:0,f=r?-1:1,g=e[t+u];for(u+=f,o=g&(1<<-h)-1,g>>=-h,h+=c;0<h;o=256*o+e[t+u],u+=f,h-=8);for(a=o&(1<<-h)-1,o>>=-h,h+=i;0<h;a=256*a+e[t+u],u+=f,h-=8);if(0===o)o=1-d;else{if(o===l)return a?NaN:1/0*(g?-1:1);a+=n(2,i),o-=d}return(g?-1:1)*a*n(2,o-i)},s.write=function(r,i,s,o,a,c){var l,d,h,u=Math.LN2,f=Math.log,g=8*c-a-1,p=(1<<g)-1,m=p>>1,y=23===a?n(2,-24)-n(2,-77):0,w=o?0:c-1,b=o?1:-1,v=0>i||0===i&&0>1/i?1:0;for(i=t(i),isNaN(i)||i===1/0?(d=isNaN(i)?1:0,l=p):(l=e(f(i)/u),1>i*(h=n(2,-l))&&(l--,h*=2),2<=(i+=1<=l+m?y/h:y*n(2,1-m))*h&&(l++,h/=2),l+m>=p?(d=0,l=p):1<=l+m?(d=(i*h-1)*n(2,a),l+=m):(d=i*n(2,m-1)*n(2,a),l=0));8<=a;r[s+w]=255&d,w+=b,d/=256,a-=8);for(l=l<<a|d,g+=a;0<g;r[s+w]=255&l,w+=b,l/=256,g-=8);r[s+w-b]|=128*v}},{}],10:[function(e,t){t.exports="function"==typeof Object.create?function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}},{}],11:[function(e,n){var r=Math.round;function i(e){var n=t(e);return 864e5<=n?r(e/864e5)+"d":36e5<=n?r(e/36e5)+"h":6e4<=n?r(e/6e4)+"m":1e3<=n?r(e/1e3)+"s":e+"ms"}function s(e){var n=t(e);return 864e5<=n?o(e,n,864e5,"day"):36e5<=n?o(e,n,36e5,"hour"):6e4<=n?o(e,n,6e4,"minute"):1e3<=n?o(e,n,1e3,"second"):e+" ms"}function o(e,t,n,i){return r(e/n)+" "+i+(t>=1.5*n?"s":"")}n.exports=function(e,t){t=t||{};var n=typeof e;if("string"==n&&0<e.length)return function(e){if(!(100<(e+="").length)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]),r=(t[2]||"ms").toLowerCase();return"years"===r||"year"===r||"yrs"===r||"yr"===r||"y"===r?315576e5*n:"weeks"===r||"week"===r||"w"===r?6048e5*n:"days"===r||"day"===r||"d"===r?864e5*n:"hours"===r||"hour"===r||"hrs"===r||"hr"===r||"h"===r?36e5*n:"minutes"===r||"minute"===r||"mins"===r||"min"===r||"m"===r?6e4*n:"seconds"===r||"second"===r||"secs"===r||"sec"===r||"s"===r?1e3*n:"milliseconds"===r||"millisecond"===r||"msecs"===r||"msec"===r||"ms"===r?n:void 0}}}(e);if("number"===n&&isFinite(e))return t.long?s(e):i(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},{}],12:[function(e,t){function n(){throw new Error("setTimeout has not been defined")}function r(){throw new Error("clearTimeout has not been defined")}function i(e){if(l===setTimeout)return setTimeout(e,0);if((l===n||!l)&&setTimeout)return l=setTimeout,setTimeout(e,0);try{return l(e,0)}catch(n){try{return l.call(null,e,0)}catch(n){return l.call(this,e,0)}}}function s(){g&&u&&(g=!1,u.length?f=u.concat(f):p=-1,f.length&&o())}function o(){if(!g){var e=i(s);g=!0;for(var t=f.length;t;){for(u=f,f=[];++p<t;)u&&u[p].run();p=-1,t=f.length}u=null,g=!1,function(e){if(d===clearTimeout)return clearTimeout(e);if((d===r||!d)&&clearTimeout)return d=clearTimeout,clearTimeout(e);try{return d(e)}catch(n){try{return d.call(null,e)}catch(n){return d.call(this,e)}}}(e)}}function a(e,t){this.fun=e,this.array=t}function c(){}var l,d,h=t.exports={};!function(){try{l="function"==typeof setTimeout?setTimeout:n}catch(t){l=n}try{d="function"==typeof clearTimeout?clearTimeout:r}catch(t){d=r}}();var u,f=[],g=!1,p=-1;h.nextTick=function(e){var t=Array(arguments.length-1);if(1<arguments.length)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];f.push(new a(e,t)),1!==f.length||g||i(o)},a.prototype.run=function(){this.fun.apply(null,this.array)},h.title="browser",h.browser=!0,h.env={},h.argv=[],h.version="",h.versions={},h.on=c,h.addListener=c,h.once=c,h.off=c,h.removeListener=c,h.removeAllListeners=c,h.emit=c,h.prependListener=c,h.prependOnceListener=c,h.listeners=function(){return[]},h.binding=function(){throw new Error("process.binding is not supported")},h.cwd=function(){return"/"},h.chdir=function(){throw new Error("process.chdir is not supported")},h.umask=function(){return 0}},{}],13:[function(e,t){(function(e){(function(){let n;t.exports="function"==typeof queueMicrotask?queueMicrotask.bind("undefined"==typeof window?e:window):e=>(n||(n=Promise.resolve())).then(e).catch(e=>setTimeout(()=>{throw e},0))}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{}],14:[function(e,t){(function(n,r){(function(){"use strict";var i=e("safe-buffer").Buffer,s=r.crypto||r.msCrypto;t.exports=s&&s.getRandomValues?function(e,t){if(e>4294967295)throw new RangeError("requested too many random bytes");var r=i.allocUnsafe(e);if(0<e)if(65536<e)for(var o=0;o<e;o+=65536)s.getRandomValues(r.slice(o,o+65536));else s.getRandomValues(r);return"function"==typeof t?n.nextTick(function(){t(null,r)}):r}:function(){throw new Error("Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11")}}).call(this)}).call(this,e("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{_process:12,"safe-buffer":30}],15:[function(e,t){"use strict";function n(e,t,n){function r(e,n,r){return"string"==typeof t?t:t(e,n,r)}n||(n=Error);var s=function(e){function t(t,n,i){return e.call(this,r(t,n,i))||this}return function(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}(t,e),t}(n);s.prototype.name=n.name,s.prototype.code=e,i[e]=s}function r(e,t){if(Array.isArray(e)){var n=e.length;return e=e.map(function(e){return e+""}),2<n?"one of ".concat(t," ").concat(e.slice(0,n-1).join(", "),", or ")+e[n-1]:2===n?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(e+"")}var i={};n("ERR_INVALID_OPT_VALUE",function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'},TypeError),n("ERR_INVALID_ARG_TYPE",function(e,t,n){var i,s;if("string"==typeof t&&function(e,t,n){return e.substr(!n||0>n?0:+n,t.length)===t}(t,"not ")?(i="must not be",t=t.replace(/^not /,"")):i="must be",function(e,t,n){return(void 0===n||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}(e," argument"))s="The ".concat(e," ").concat(i," ").concat(r(t,"type"));else{var o=function(e,t,n){return"number"!=typeof n&&(n=0),!(n+t.length>e.length)&&-1!==e.indexOf(t,n)}(e,".")?"property":"argument";s='The "'.concat(e,'" ').concat(o," ").concat(i," ").concat(r(t,"type"))}return s+=". Received type ".concat(typeof n)},TypeError),n("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),n("ERR_METHOD_NOT_IMPLEMENTED",function(e){return"The "+e+" method is not implemented"}),n("ERR_STREAM_PREMATURE_CLOSE","Premature close"),n("ERR_STREAM_DESTROYED",function(e){return"Cannot call "+e+" after a stream was destroyed"}),n("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),n("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),n("ERR_STREAM_WRITE_AFTER_END","write after end"),n("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),n("ERR_UNKNOWN_ENCODING",function(e){return"Unknown encoding: "+e},TypeError),n("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),t.exports.codes=i},{}],16:[function(e,t){(function(n){(function(){"use strict";function r(e){return this instanceof r?(a.call(this,e),c.call(this,e),this.allowHalfOpen=!0,void(e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",i))))):new r(e)}function i(){this._writableState.ended||n.nextTick(s,this)}function s(e){e.end()}var o=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=r;var a=e("./_stream_readable"),c=e("./_stream_writable");e("inherits")(r,a);for(var l,d=o(c.prototype),h=0;h<d.length;h++)l=d[h],r.prototype[l]||(r.prototype[l]=c.prototype[l]);Object.defineProperty(r.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(r.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(r.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(r.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&this._readableState.destroyed&&this._writableState.destroyed},set:function(e){void 0===this._readableState||void 0===this._writableState||(this._readableState.destroyed=e,this._writableState.destroyed=e)}})}).call(this)}).call(this,e("_process"))},{"./_stream_readable":18,"./_stream_writable":20,_process:12,inherits:10}],17:[function(e,t){"use strict";function n(e){return this instanceof n?void r.call(this,e):new n(e)}t.exports=n;var r=e("./_stream_transform");e("inherits")(n,r),n.prototype._transform=function(e,t,n){n(null,e)}},{"./_stream_transform":19,inherits:10}],18:[function(e,t){(function(n,r){(function(){"use strict";function i(t,n,r){S=S||e("./_stream_duplex"),t=t||{},"boolean"!=typeof r&&(r=n instanceof S),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=L(this,t,"readableHighWaterMark",r),this.buffer=new U,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(!R&&(R=e("string_decoder/").StringDecoder),this.decoder=new R(t.encoding),this.encoding=t.encoding)}function s(t){if(S=S||e("./_stream_duplex"),!(this instanceof s))return new s(t);var n=this instanceof S;this._readableState=new i(t,this,n),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),E.call(this)}function o(e,t,n,r,i){k("readableAddChunk",t);var s,o=e._readableState;if(null===t)o.reading=!1,function(e,t){if(k("onEofChunk"),!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?d(e):(t.needReadable=!1,!t.emittedReadable&&(t.emittedReadable=!0,h(e)))}}(e,o);else if(i||(s=c(o,t)),s)F(e,s);else if(o.objectMode||t&&0<t.length)if("string"==typeof t||o.objectMode||Object.getPrototypeOf(t)===A.prototype||(t=function(e){return A.from(e)}(t)),r)o.endEmitted?F(e,new V):a(e,o,t,!0);else if(o.ended)F(e,new N);else{if(o.destroyed)return!1;o.reading=!1,o.decoder&&!n?(t=o.decoder.write(t),o.objectMode||0!==t.length?a(e,o,t,!1):u(e,o)):a(e,o,t,!1)}else r||(o.reading=!1,u(e,o));return!o.ended&&(o.length<o.highWaterMark||0===o.length)}function a(e,t,n,r){t.flowing&&0===t.length&&!t.sync?(t.awaitDrain=0,e.emit("data",n)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&d(e)),u(e,t)}function c(e,t){var n;return function(e){return A.isBuffer(e)||e instanceof x}(t)||"string"==typeof t||void 0===t||e.objectMode||(n=new I("chunk",["string","Buffer","Uint8Array"],t)),n}function l(e,t){return 0>=e||0===t.length&&t.ended?0:t.objectMode?1:e==e?(e>t.highWaterMark&&(t.highWaterMark=function(e){return 1073741824<=e?e=1073741824:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0)):t.flowing&&t.length?t.buffer.head.data.length:t.length}function d(e){var t=e._readableState;k("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(k("emitReadable",t.flowing),t.emittedReadable=!0,n.nextTick(h,e))}function h(e){var t=e._readableState;k("emitReadable_",t.destroyed,t.length,t.ended),!t.destroyed&&(t.length||t.ended)&&(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,y(e)}function u(e,t){t.readingMore||(t.readingMore=!0,n.nextTick(f,e,t))}function f(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&0===t.length);){var n=t.length;if(k("maybeReadMore read 0"),e.read(0),n===t.length)break}t.readingMore=!1}function g(e){var t=e._readableState;t.readableListening=0<e.listenerCount("readable"),t.resumeScheduled&&!t.paused?t.flowing=!0:0<e.listenerCount("data")&&e.resume()}function p(e){k("readable nexttick read 0"),e.read(0)}function m(e,t){k("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),y(e),t.flowing&&!t.reading&&e.read(0)}function y(e){var t=e._readableState;for(k("flow",t.flowing);t.flowing&&null!==e.read(););}function w(e,t){return 0===t.length?null:(t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n);var n}function b(e){var t=e._readableState;k("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,n.nextTick(v,t,e))}function v(e,t){if(k("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}function _(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}var S,k;t.exports=s,s.ReadableState=i,e("events").EventEmitter;var C=function(e,t){return e.listeners(t).length},E=e("./internal/streams/stream"),A=e("buffer").Buffer,x=r.Uint8Array||function(){},T=e("util");k=T&&T.debuglog?T.debuglog("stream"):function(){};var R,D,O,U=e("./internal/streams/buffer_list"),P=e("./internal/streams/destroy"),L=e("./internal/streams/state").getHighWaterMark,M=e("../errors").codes,I=M.ERR_INVALID_ARG_TYPE,N=M.ERR_STREAM_PUSH_AFTER_EOF,j=M.ERR_METHOD_NOT_IMPLEMENTED,V=M.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;e("inherits")(s,E);var F=P.errorOrDestroy,B=["error","close","destroy","pause","resume"];Object.defineProperty(s.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),s.prototype.destroy=P.destroy,s.prototype._undestroy=P.undestroy,s.prototype._destroy=function(e,t){t(e)},s.prototype.push=function(e,t){var n,r=this._readableState;return r.objectMode?n=!0:"string"==typeof e&&((t=t||r.defaultEncoding)!==r.encoding&&(e=A.from(e,t),t=""),n=!0),o(this,e,t,!1,n)},s.prototype.unshift=function(e){return o(this,e,null,!0,!1)},s.prototype.isPaused=function(){return!1===this._readableState.flowing},s.prototype.setEncoding=function(t){R||(R=e("string_decoder/").StringDecoder);var n=new R(t);this._readableState.decoder=n,this._readableState.encoding=this._readableState.decoder.encoding;for(var r=this._readableState.buffer.head,i="";null!==r;)i+=n.write(r.data),r=r.next;return this._readableState.buffer.clear(),""!==i&&this._readableState.buffer.push(i),this._readableState.length=i.length,this},s.prototype.read=function(e){k("read",e),e=parseInt(e,10);var t=this._readableState,n=e;if(0!==e&&(t.emittedReadable=!1),0===e&&t.needReadable&&((0===t.highWaterMark?0<t.length:t.length>=t.highWaterMark)||t.ended))return k("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?b(this):d(this),null;if(0===(e=l(e,t))&&t.ended)return 0===t.length&&b(this),null;var r=t.needReadable;k("need readable",r),(0===t.length||t.length-e<t.highWaterMark)&&k("length less than watermark",r=!0),t.ended||t.reading?k("reading or ended",r=!1):r&&(k("do read"),t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,!t.reading&&(e=l(n,t)));var i=0<e?w(e,t):null;return null===i?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(!t.ended&&(t.needReadable=!0),n!==e&&t.ended&&b(this)),null!==i&&this.emit("data",i),i},s.prototype._read=function(){F(this,new j("_read()"))},s.prototype.pipe=function(e,t){function r(e,t){k("onunpipe"),e===h&&t&&!1===t.hasUnpiped&&(t.hasUnpiped=!0,s())}function i(){k("onend"),e.end()}function s(){k("cleanup"),e.removeListener("close",c),e.removeListener("finish",l),e.removeListener("drain",g),e.removeListener("error",a),e.removeListener("unpipe",r),h.removeListener("end",i),h.removeListener("end",d),h.removeListener("data",o),p=!0,u.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&g()}function o(t){k("ondata");var n=e.write(t);k("dest.write",n),!1===n&&((1===u.pipesCount&&u.pipes===e||1<u.pipesCount&&-1!==_(u.pipes,e))&&!p&&(k("false write response, pause",u.awaitDrain),u.awaitDrain++),h.pause())}function a(t){k("onerror",t),d(),e.removeListener("error",a),0===C(e,"error")&&F(e,t)}function c(){e.removeListener("finish",l),d()}function l(){k("onfinish"),e.removeListener("close",c),d()}function d(){k("unpipe"),h.unpipe(e)}var h=this,u=this._readableState;switch(u.pipesCount){case 0:u.pipes=e;break;case 1:u.pipes=[u.pipes,e];break;default:u.pipes.push(e)}u.pipesCount+=1,k("pipe count=%d opts=%j",u.pipesCount,t);var f=t&&!1===t.end||e===n.stdout||e===n.stderr?d:i;u.endEmitted?n.nextTick(f):h.once("end",f),e.on("unpipe",r);var g=function(e){return function(){var t=e._readableState;k("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&C(e,"data")&&(t.flowing=!0,y(e))}}(h);e.on("drain",g);var p=!1;return h.on("data",o),function(e,t,n){"function"==typeof e.prependListener?e.prependListener(t,n):e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n)}(e,"error",a),e.once("close",c),e.once("finish",l),e.emit("pipe",h),u.flowing||(k("pipe resume"),h.resume()),e},s.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n)),this;if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var s=0;s<i;s++)r[s].emit("unpipe",this,{hasUnpiped:!1});return this}var o=_(t.pipes,e);return-1===o||(t.pipes.splice(o,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,n)),this},s.prototype.on=function(e,t){var r=E.prototype.on.call(this,e,t),i=this._readableState;return"data"===e?(i.readableListening=0<this.listenerCount("readable"),!1!==i.flowing&&this.resume()):"readable"==e&&!i.endEmitted&&!i.readableListening&&(i.readableListening=i.needReadable=!0,i.flowing=!1,i.emittedReadable=!1,k("on readable",i.length,i.reading),i.length?d(this):!i.reading&&n.nextTick(p,this)),r},s.prototype.addListener=s.prototype.on,s.prototype.removeListener=function(e,t){var r=E.prototype.removeListener.call(this,e,t);return"readable"===e&&n.nextTick(g,this),r},s.prototype.removeAllListeners=function(e){var t=E.prototype.removeAllListeners.apply(this,arguments);return("readable"===e||void 0===e)&&n.nextTick(g,this),t},s.prototype.resume=function(){var e=this._readableState;return e.flowing||(k("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,n.nextTick(m,e,t))}(this,e)),e.paused=!1,this},s.prototype.pause=function(){return k("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(k("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},s.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var i in e.on("end",function(){if(k("wrapped end"),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)}),e.on("data",function(i){k("wrapped data"),n.decoder&&(i=n.decoder.write(i)),n.objectMode&&null==i||!(n.objectMode||i&&i.length)||t.push(i)||(r=!0,e.pause())}),e)void 0===this[i]&&"function"==typeof e[i]&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));for(var s=0;s<B.length;s++)e.on(B[s],this.emit.bind(this,B[s]));return this._read=function(t){k("wrapped _read",t),r&&(r=!1,e.resume())},this},"function"==typeof Symbol&&(s.prototype[Symbol.asyncIterator]=function(){return void 0===D&&(D=e("./internal/streams/async_iterator")),D(this)}),Object.defineProperty(s.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(s.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(s.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),s._fromList=w,Object.defineProperty(s.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(s.from=function(t,n){return void 0===O&&(O=e("./internal/streams/from")),O(s,t,n)})}).call(this)}).call(this,e("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"../errors":15,"./_stream_duplex":16,"./internal/streams/async_iterator":21,"./internal/streams/buffer_list":22,"./internal/streams/destroy":23,"./internal/streams/from":25,"./internal/streams/state":27,"./internal/streams/stream":28,_process:12,buffer:3,events:7,inherits:10,"string_decoder/":31,util:2}],19:[function(e,t){"use strict";function n(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(null===r)return this.emit("error",new c);n.writechunk=null,n.writecb=null,null!=t&&this.push(t),r(e);var i=this._readableState;i.reading=!1,(i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}function r(e){return this instanceof r?(h.call(this,e),this._transformState={afterTransform:n.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),void this.on("prefinish",i)):new r(e)}function i(){var e=this;"function"!=typeof this._flush||this._readableState.destroyed?s(this,null,null):this._flush(function(t,n){s(e,t,n)})}function s(e,t,n){if(t)return e.emit("error",t);if(null!=n&&e.push(n),e._writableState.length)throw new d;if(e._transformState.transforming)throw new l;return e.push(null)}t.exports=r;var o=e("../errors").codes,a=o.ERR_METHOD_NOT_IMPLEMENTED,c=o.ERR_MULTIPLE_CALLBACK,l=o.ERR_TRANSFORM_ALREADY_TRANSFORMING,d=o.ERR_TRANSFORM_WITH_LENGTH_0,h=e("./_stream_duplex");e("inherits")(r,h),r.prototype.push=function(e,t){return this._transformState.needTransform=!1,h.prototype.push.call(this,e,t)},r.prototype._transform=function(e,t,n){n(new a("_transform()"))},r.prototype._write=function(e,t,n){var r=this._transformState;if(r.writecb=n,r.writechunk=e,r.writeencoding=t,!r.transforming){var i=this._readableState;(r.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}},r.prototype._read=function(){var e=this._transformState;null===e.writechunk||e.transforming?e.needTransform=!0:(e.transforming=!0,this._transform(e.writechunk,e.writeencoding,e.afterTransform))},r.prototype._destroy=function(e,t){h.prototype._destroy.call(this,e,function(e){t(e)})}},{"../errors":15,"./_stream_duplex":16,inherits:10}],20:[function(e,t){(function(n,r){(function(){"use strict";function i(e){var t=this;this.next=null,this.entry=null,this.finish=function(){!function(e,t,n){var r=e.entry;for(e.entry=null;r;){var i=r.callback;t.pendingcb--,i(n),r=r.next}t.corkedRequestsFree.next=e}(t,e)}}function s(){}function o(t,n,r){v=v||e("./_stream_duplex"),t=t||{},"boolean"!=typeof r&&(r=n instanceof v),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=x(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var s=!1===t.decodeStrings;this.decodeStrings=!s,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){u(n,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new i(this)}function a(t){var n=this instanceof(v=v||e("./_stream_duplex"));return n||_.call(a,this)?(this._writableState=new o(t,this,n),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),void k.call(this)):new a(t)}function c(e,t){var r=new M;N(e,r),n.nextTick(t,r)}function l(e,t,r,i){var s;return null===r?s=new L:"string"!=typeof r&&!t.objectMode&&(s=new R("chunk",["string","Buffer"],r)),!s||(N(e,s),n.nextTick(i,s),!1)}function d(e,t,n,r,i,s){if(!n){var o=function(e,t,n){return e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=C.from(t,n)),t}(t,r,i);r!==o&&(n=!0,i="buffer",r=o)}var a=t.objectMode?1:r.length;t.length+=a;var c=t.length<t.highWaterMark;if(c||(t.needDrain=!0),t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:i,isBuf:n,callback:s,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else h(e,t,!1,a,r,i,s);return c}function h(e,t,n,r,i,s,o){t.writelen=r,t.writecb=o,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new P("write")):n?e._writev(i,t.onwrite):e._write(i,s,t.onwrite),t.sync=!1}function u(e,t){var r=e._writableState,i=r.sync,s=r.writecb;if("function"!=typeof s)throw new O;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(r),t)!function(e,t,r,i,s){--t.pendingcb,r?(n.nextTick(s,i),n.nextTick(w,e,t),e._writableState.errorEmitted=!0,N(e,i)):(s(i),e._writableState.errorEmitted=!0,N(e,i),w(e,t))}(e,r,i,t,s);else{var o=p(r)||e.destroyed;o||r.corked||r.bufferProcessing||!r.bufferedRequest||g(e,r),i?n.nextTick(f,e,r,o,s):f(e,r,o,s)}}function f(e,t,n,r){n||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,r(),w(e,t)}function g(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var r=t.bufferedRequestCount,s=Array(r),o=t.corkedRequestsFree;o.entry=n;for(var a=0,c=!0;n;)s[a]=n,n.isBuf||(c=!1),n=n.next,a+=1;s.allBuffers=c,h(e,t,!0,t.length,s,"",o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new i(t),t.bufferedRequestCount=0}else{for(;n;){var l=n.chunk,d=n.encoding,u=n.callback;if(h(e,t,!1,t.objectMode?1:l.length,l,d,u),n=n.next,t.bufferedRequestCount--,t.writing)break}null===n&&(t.lastBufferedRequest=null)}t.bufferedRequest=n,t.bufferProcessing=!1}function p(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function m(e,t){e._final(function(n){t.pendingcb--,n&&N(e,n),t.prefinished=!0,e.emit("prefinish"),w(e,t)})}function y(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.pendingcb++,t.finalCalled=!0,n.nextTick(m,e,t)))}function w(e,t){var n=p(t);if(n&&(y(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"),t.autoDestroy))){var r=e._readableState;(!r||r.autoDestroy&&r.endEmitted)&&e.destroy()}return n}function b(e,t,r){t.ending=!0,w(e,t),r&&(t.finished?n.nextTick(r):e.once("finish",r)),t.ended=!0,e.writable=!1}var v;t.exports=a,a.WritableState=o;var _,S={deprecate:e("util-deprecate")},k=e("./internal/streams/stream"),C=e("buffer").Buffer,E=r.Uint8Array||function(){},A=e("./internal/streams/destroy"),x=e("./internal/streams/state").getHighWaterMark,T=e("../errors").codes,R=T.ERR_INVALID_ARG_TYPE,D=T.ERR_METHOD_NOT_IMPLEMENTED,O=T.ERR_MULTIPLE_CALLBACK,U=T.ERR_STREAM_CANNOT_PIPE,P=T.ERR_STREAM_DESTROYED,L=T.ERR_STREAM_NULL_VALUES,M=T.ERR_STREAM_WRITE_AFTER_END,I=T.ERR_UNKNOWN_ENCODING,N=A.errorOrDestroy;e("inherits")(a,k),o.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(o.prototype,"buffer",{get:S.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(_=Function.prototype[Symbol.hasInstance],Object.defineProperty(a,Symbol.hasInstance,{value:function(e){return!!_.call(this,e)||!(this!==a)&&e&&e._writableState instanceof o}})):_=function(e){return e instanceof this},a.prototype.pipe=function(){N(this,new U)},a.prototype.write=function(e,t,n){var r=this._writableState,i=!1,o=!r.objectMode&&function(e){return C.isBuffer(e)||e instanceof E}(e);return o&&!C.isBuffer(e)&&(e=function(e){return C.from(e)}(e)),"function"==typeof t&&(n=t,t=null),o?t="buffer":!t&&(t=r.defaultEncoding),"function"!=typeof n&&(n=s),r.ending?c(this,n):(o||l(this,r,e,n))&&(r.pendingcb++,i=d(this,r,o,e,t,n)),i},a.prototype.cork=function(){this._writableState.corked++},a.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest&&g(this,e))},a.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(-1<["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())))throw new I(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(a.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(a.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),a.prototype._write=function(e,t,n){n(new D("_write()"))},a.prototype._writev=null,a.prototype.end=function(e,t,n){var r=this._writableState;return"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||b(this,r,n),this},Object.defineProperty(a.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(a.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),a.prototype.destroy=A.destroy,a.prototype._undestroy=A.undestroy,a.prototype._destroy=function(e,t){t(e)}}).call(this)}).call(this,e("_process"),"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{"../errors":15,"./_stream_duplex":16,"./internal/streams/destroy":23,"./internal/streams/state":27,"./internal/streams/stream":28,_process:12,buffer:3,inherits:10,"util-deprecate":32}],21:[function(e,t){(function(n){(function(){"use strict";function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){return{value:e,done:t}}function s(e){var t=e[l];if(null!==t){var n=e[p].read();null!==n&&(e[f]=null,e[l]=null,e[d]=null,t(i(n,!1)))}}function o(e){n.nextTick(s,e)}var a,c=e("./end-of-stream"),l=Symbol("lastResolve"),d=Symbol("lastReject"),h=Symbol("error"),u=Symbol("ended"),f=Symbol("lastPromise"),g=Symbol("handlePromise"),p=Symbol("stream"),m=Object.getPrototypeOf(function(){}),y=Object.setPrototypeOf((a={get stream(){return this[p]},next:function(){var e=this,t=this[h];if(null!==t)return Promise.reject(t);if(this[u])return Promise.resolve(i(void 0,!0));if(this[p].destroyed)return new Promise(function(t,r){n.nextTick(function(){e[h]?r(e[h]):t(i(void 0,!0))})});var r,s=this[f];if(s)r=new Promise(function(e,t){return function(n,r){e.then(function(){t[u]?n(i(void 0,!0)):t[g](n,r)},r)}}(s,this));else{var o=this[p].read();if(null!==o)return Promise.resolve(i(o,!1));r=new Promise(this[g])}return this[f]=r,r}},r(a,Symbol.asyncIterator,function(){return this}),r(a,"return",function(){var e=this;return new Promise(function(t,n){e[p].destroy(null,function(e){e?n(e):t(i(void 0,!0))})})}),a),m);t.exports=function(e){var t,n=Object.create(y,(r(t={},p,{value:e,writable:!0}),r(t,l,{value:null,writable:!0}),r(t,d,{value:null,writable:!0}),r(t,h,{value:null,writable:!0}),r(t,u,{value:e._readableState.endEmitted,writable:!0}),r(t,g,{value:function(e,t){var r=n[p].read();r?(n[f]=null,n[l]=null,n[d]=null,e(i(r,!1))):(n[l]=e,n[d]=t)},writable:!0}),t));return n[f]=null,c(e,function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=n[d];return null!==t&&(n[f]=null,n[l]=null,n[d]=null,t(e)),void(n[h]=e)}var r=n[l];null!==r&&(n[f]=null,n[l]=null,n[d]=null,r(i(void 0,!0))),n[u]=!0}),e.on("readable",o.bind(null,n)),n}}).call(this)}).call(this,e("_process"))},{"./end-of-stream":24,_process:12}],22:[function(e,t){"use strict";function n(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){for(var n,r=0;r<t.length;r++)(n=t[r]).enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}function s(e,t,n){o.prototype.copy.call(e,t,n)}var o=e("buffer").Buffer,a=e("util").inspect,c=a&&a.custom||"inspect";t.exports=function(){function e(){(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),this.head=null,this.tail=null,this.length=0}return function(e,t,n){t&&i(e.prototype,t),n&&i(e,n)}(e,[{key:"push",value:function(e){var t={data:e,next:null};0<this.length?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:"unshift",value:function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}},{key:"shift",value:function(){if(0!==this.length){var e=this.head.data;return this.head=1===this.length?this.tail=null:this.head.next,--this.length,e}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n}},{key:"concat",value:function(e){if(0===this.length)return o.alloc(0);for(var t=o.allocUnsafe(e>>>0),n=this.head,r=0;n;)s(n.data,t,r),r+=n.data.length,n=n.next;return t}},{key:"consume",value:function(e,t){var n;return e<this.head.data.length?(n=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):n=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),n}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(e){var t=this.head,n=1,r=t.data;for(e-=r.length;t=t.next;){var i=t.data,s=e>i.length?i.length:e;if(r+=s===i.length?i:i.slice(0,e),0===(e-=s)){s===i.length?(++n,this.head=t.next?t.next:this.tail=null):(this.head=t,t.data=i.slice(s));break}++n}return this.length-=n,r}},{key:"_getBuffer",value:function(e){var t=o.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var i=n.data,s=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,s),0===(e-=s)){s===i.length?(++r,this.head=n.next?n.next:this.tail=null):(this.head=n,n.data=i.slice(s));break}++r}return this.length-=r,t}},{key:c,value:function(e,t){return a(this,function(e){for(var t,i=1;i<arguments.length;i++)t=null==arguments[i]?{}:arguments[i],i%2?n(Object(t),!0).forEach(function(n){r(e,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):n(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))});return e}({},t,{depth:0,customInspect:!1}))}}]),e}()},{buffer:3,util:2}],23:[function(e,t){(function(e){(function(){"use strict";function n(e,t){i(e,t),r(e)}function r(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function i(e,t){e.emit("error",t)}t.exports={destroy:function(t,s){var o=this,a=this._readableState&&this._readableState.destroyed,c=this._writableState&&this._writableState.destroyed;return a||c?(s?s(t):t&&(this._writableState?!this._writableState.errorEmitted&&(this._writableState.errorEmitted=!0,e.nextTick(i,this,t)):e.nextTick(i,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,function(t){!s&&t?o._writableState?o._writableState.errorEmitted?e.nextTick(r,o):(o._writableState.errorEmitted=!0,e.nextTick(n,o,t)):e.nextTick(n,o,t):s?(e.nextTick(r,o),s(t)):e.nextTick(r,o)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit("error",t)}}}).call(this)}).call(this,e("_process"))},{_process:12}],24:[function(e,t){"use strict";function n(){}var r=e("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;t.exports=function e(t,i,s){if("function"==typeof i)return e(t,null,i);i||(i={}),s=function(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=Array(n),i=0;i<n;i++)r[i]=arguments[i];e.apply(this,r)}}}(s||n);var o=i.readable||!1!==i.readable&&t.readable,a=i.writable||!1!==i.writable&&t.writable,c=function(){t.writable||d()},l=t._writableState&&t._writableState.finished,d=function(){a=!1,l=!0,o||s.call(t)},h=t._readableState&&t._readableState.endEmitted,u=function(){o=!1,h=!0,a||s.call(t)},f=function(e){s.call(t,e)},g=function(){var e;return o&&!h?(t._readableState&&t._readableState.ended||(e=new r),s.call(t,e)):a&&!l?(t._writableState&&t._writableState.ended||(e=new r),s.call(t,e)):void 0},p=function(){t.req.on("finish",d)};return function(e){return e.setHeader&&"function"==typeof e.abort}(t)?(t.on("complete",d),t.on("abort",g),t.req?p():t.on("request",p)):a&&!t._writableState&&(t.on("end",c),t.on("close",c)),t.on("end",u),t.on("finish",d),!1!==i.error&&t.on("error",f),t.on("close",g),function(){t.removeListener("complete",d),t.removeListener("abort",g),t.removeListener("request",p),t.req&&t.req.removeListener("finish",d),t.removeListener("end",c),t.removeListener("close",c),t.removeListener("finish",d),t.removeListener("end",u),t.removeListener("error",f),t.removeListener("close",g)}}},{"../../../errors":15}],25:[function(e,t){t.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],26:[function(e,t){"use strict";function n(e){if(e)throw e}function r(t,n,r,i){i=function(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}(i);var s=!1;t.on("close",function(){s=!0}),void 0===a&&(a=e("./end-of-stream")),a(t,{readable:n,writable:r},function(e){return e?i(e):(s=!0,void i())});var o=!1;return function(e){if(!s)return o?void 0:(o=!0,function(e){return e.setHeader&&"function"==typeof e.abort}(t)?t.abort():"function"==typeof t.destroy?t.destroy():void i(e||new d("pipe")))}}function i(e){e()}function s(e,t){return e.pipe(t)}function o(e){return e.length&&"function"==typeof e[e.length-1]?e.pop():n}var a,c=e("../../../errors").codes,l=c.ERR_MISSING_ARGS,d=c.ERR_STREAM_DESTROYED;t.exports=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var a=o(t);if(Array.isArray(t[0])&&(t=t[0]),2>t.length)throw new l("streams");var c,d=t.map(function(e,n){var s=n<t.length-1;return r(e,s,0<n,function(e){c||(c=e),e&&d.forEach(i),s||(d.forEach(i),a(c))})});return t.reduce(s)}},{"../../../errors":15,"./end-of-stream":24}],27:[function(t,n){"use strict";var r=t("../../../errors").codes.ERR_INVALID_OPT_VALUE;n.exports={getHighWaterMark:function(t,n,i,s){var o=function(e,t,n){return null==e.highWaterMark?t?e[n]:null:e.highWaterMark}(n,s,i);if(null!=o){if(!isFinite(o)||e(o)!==o||0>o)throw new r(s?i:"highWaterMark",o);return e(o)}return t.objectMode?16:16384}}},{"../../../errors":15}],28:[function(e,t){t.exports=e("events").EventEmitter},{events:7}],29:[function(e,t,n){(n=t.exports=e("./lib/_stream_readable.js")).Stream=n,n.Readable=n,n.Writable=e("./lib/_stream_writable.js"),n.Duplex=e("./lib/_stream_duplex.js"),n.Transform=e("./lib/_stream_transform.js"),n.PassThrough=e("./lib/_stream_passthrough.js"),n.finished=e("./lib/internal/streams/end-of-stream.js"),n.pipeline=e("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":16,"./lib/_stream_passthrough.js":17,"./lib/_stream_readable.js":18,"./lib/_stream_transform.js":19,"./lib/_stream_writable.js":20,"./lib/internal/streams/end-of-stream.js":24,"./lib/internal/streams/pipeline.js":26}],30:[function(e,t,n){function r(e,t){for(var n in e)t[n]=e[n]}function i(e,t,n){return o(e,t,n)}var s=e("buffer"),o=s.Buffer;o.from&&o.alloc&&o.allocUnsafe&&o.allocUnsafeSlow?t.exports=s:(r(s,n),n.Buffer=i),i.prototype=Object.create(o.prototype),r(o,i),i.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return o(e,t,n)},i.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=o(e);return void 0===t?r.fill(0):"string"==typeof n?r.fill(t,n):r.fill(t),r},i.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return o(e)},i.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return s.SlowBuffer(e)}},{buffer:3}],31:[function(e,t,n){"use strict";function r(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(u.isEncoding===f||!f(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=o,this.end=a,t=4;break;case"utf8":this.fillLast=s,t=4;break;case"base64":this.text=c,this.end=l,t=3;break;default:return this.write=d,void(this.end=h)}this.lastNeed=0,this.lastTotal=0,this.lastChar=u.allocUnsafe(t)}function i(e){return 127>=e?0:6==e>>5?2:14==e>>4?3:30==e>>3?4:2==e>>6?-1:-2}function s(e){var t=this.lastTotal-this.lastNeed,n=function(e,t){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(1<e.lastNeed&&1<t.length){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(2<e.lastNeed&&2<t.length&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0===n?this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length)):n}function o(e,t){if(0==(e.length-t)%2){var n=e.toString("utf16le",t);if(n){var r=n.charCodeAt(n.length-1);if(55296<=r&&56319>=r)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function a(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function c(e,t){var n=(e.length-t)%3;return 0==n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1==n?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-n))}function l(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function d(e){return e.toString(this.encoding)}function h(e){return e&&e.length?this.write(e):""}var u=e("safe-buffer").Buffer,f=u.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};n.StringDecoder=r,r.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n<e.length?t?t+this.text(e,n):this.text(e,n):t||""},r.prototype.end=function(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t},r.prototype.text=function(e,t){var n=function(e,t,n){var r=t.length-1;if(r<n)return 0;var s=i(t[r]);return 0<=s?(0<s&&(e.lastNeed=s-1),s):--r<n||-2===s?0:0<=(s=i(t[r]))?(0<s&&(e.lastNeed=s-2),s):--r<n||-2===s?0:0<=(s=i(t[r]))?(0<s&&(2===s?s=0:e.lastNeed=s-3),s):0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString("utf8",t,r)},r.prototype.fillLast=function(e){return this.lastNeed<=e.length?(e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),void(this.lastNeed-=e.length))}},{"safe-buffer":30}],32:[function(e,t){(function(e){(function(){function n(t){try{if(!e.localStorage)return!1}catch(e){return!1}var n=e.localStorage[t];return null!=n&&"true"===(n+"").toLowerCase()}t.exports=function(e,t){if(n("noDeprecation"))return e;var r=!1;return function(){if(!r){if(n("throwDeprecation"))throw new Error(t);n("traceDeprecation"),r=!0}return e.apply(this,arguments)}}}).call(this)}).call(this,"undefined"==typeof global?"undefined"==typeof self?"undefined"==typeof window?{}:window:self:global)},{}],"/":[function(e,t){function n(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}const r=e("debug")("simple-peer"),i=e("get-browser-rtc"),s=e("randombytes"),o=e("readable-stream"),a=e("queue-microtask"),c=e("err-code"),{Buffer:l}=e("buffer"),d=65536;class h extends o.Duplex{constructor(e){if(super(e=Object.assign({allowHalfOpen:!1},e)),this._id=s(4).toString("hex").slice(0,7),this._debug("new peer %o",e),this.channelName=e.initiator?e.channelName||s(20).toString("hex"):null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||h.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},h.config,e.config),this.offerOptions=e.offerOptions||{},this.answerOptions=e.answerOptions||{},this.sdpTransform=e.sdpTransform||(e=>e),this.streams=e.streams||(e.stream?[e.stream]:[]),this.trickle=void 0===e.trickle||e.trickle,this.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,this.iceCompleteTimeout=e.iceCompleteTimeout||5e3,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=e.wrtc&&"object"==typeof e.wrtc?e.wrtc:i(),!this._wrtc)throw"undefined"==typeof window?c(new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"),"ERR_WEBRTC_SUPPORT"):c(new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(e){return void this.destroy(c(e,"ERR_PC_CONSTRUCTOR"))}this._isReactNativeWebrtc="number"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=e=>{this._onIceCandidate(e)},"object"==typeof this._pc.peerIdentity&&this._pc.peerIdentity.catch(e=>{this.destroy(c(e,"ERR_PC_PEER_IDENTITY"))}),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this.streams&&this.streams.forEach(e=>{this.addStream(e)}),this._pc.ontrack=e=>{this._onTrack(e)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(e){if(!this.destroying){if(this.destroyed)throw c(new Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if("string"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}this._debug("signal()"),e.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),e.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(e.transceiverRequest.kind,e.transceiverRequest.init)),e.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(e.candidate):this._pendingCandidates.push(e.candidate)),e.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(e)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(e=>{this._addIceCandidate(e)}),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())}).catch(e=>{this.destroy(c(e,"ERR_SET_REMOTE_DESCRIPTION"))}),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.destroy(c(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(e){const t=new this._wrtc.RTCIceCandidate(e);this._pc.addIceCandidate(t).catch(e=>{!t.address||t.address.endsWith(".local")||this.destroy(c(e,"ERR_ADD_ICE_CANDIDATE"))})}send(e){if(!this.destroying){if(this.destroyed)throw c(new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(e)}}addTransceiver(e,t){if(!this.destroying){if(this.destroyed)throw c(new Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(e,t),this._needsNegotiation()}catch(e){this.destroy(c(e,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:e,init:t}})}}addStream(e){if(!this.destroying){if(this.destroyed)throw c(new Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),e.getTracks().forEach(t=>{this.addTrack(t,e)})}}addTrack(e,t){if(this.destroying)return;if(this.destroyed)throw c(new Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const n=this._senderMap.get(e)||new Map;let r=n.get(t);if(r)throw r.removed?c(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):c(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED");r=this._pc.addTrack(e,t),n.set(t,r),this._senderMap.set(e,n),this._needsNegotiation()}replaceTrack(e,t,n){if(this.destroying)return;if(this.destroyed)throw c(new Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const r=this._senderMap.get(e),i=r?r.get(n):null;if(!i)throw c(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");t&&this._senderMap.set(t,r),null==i.replaceTrack?this.destroy(c(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK")):i.replaceTrack(t)}removeTrack(e,t){if(this.destroying)return;if(this.destroyed)throw c(new Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const n=this._senderMap.get(e),r=n?n.get(t):null;if(!r)throw c(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{r.removed=!0,this._pc.removeTrack(r)}catch(e){"NS_ERROR_UNEXPECTED"===e.name?this._sendersAwaitingStable.push(r):this.destroy(c(e,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(e){if(!this.destroying){if(this.destroyed)throw c(new Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),e.getTracks().forEach(t=>{this.removeTrack(t,e)})}}_needsNegotiation(){this._debug("_needsNegotiation"),this._batchedNegotiation||(this._batchedNegotiation=!0,a(()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1}))}negotiate(){if(!this.destroying){if(this.destroyed)throw c(new Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}destroy(e){this._destroy(e,()=>{})}_destroy(e,t){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",e&&(e.message||e)),a(()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",e&&(e.message||e)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch(e){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(e){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,e&&this.emit("error",e),this.emit("close"),t()}))}_setupData(e){if(!e.channel)return this.destroy(c(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=e.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=d),this.channelName=this._channel.label,this._channel.onmessage=e=>{this._onChannelMessage(e)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=e=>{const t=e.error instanceof Error?e.error:new Error(`Datachannel error: ${e.message} ${e.filename}:${e.lineno}:${e.colno}`);this.destroy(c(t,"ERR_DATA_CHANNEL"))};let t=!1;this._closingInterval=setInterval(()=>{this._channel&&"closing"===this._channel.readyState?(t&&this._onChannelClose(),t=!0):t=!1},5e3)}_read(){}_write(e,t,n){if(this.destroyed)return n(c(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(e)}catch(e){return this.destroy(c(e,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>d?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=n):n(null)}else this._debug("write before connect"),this._chunk=e,this._cb=n}_onFinish(){if(!this.destroyed){const e=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?e():this.once("connect",e)}}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=n(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(!this.destroyed){const t=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:t.type,sdp:t.sdp})}};this._pc.setLocalDescription(e).then(()=>{this._debug("createOffer success"),this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))}).catch(e=>{this.destroy(c(e,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(e=>{this.destroy(c(e,"ERR_CREATE_OFFER"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(e=>{e.mid||!e.sender.track||e.requested||(e.requested=!0,this.addTransceiver(e.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=n(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(!this.destroyed){const t=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:t.type,sdp:t.sdp}),this.initiator||this._requestMissingTransceivers()}};this._pc.setLocalDescription(e).then(()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))}).catch(e=>{this.destroy(c(e,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(e=>{this.destroy(c(e,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(c(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",e,t),this.emit("iceStateChange",e,t),("connected"===e||"completed"===e)&&(this._pcReady=!0,this._maybeReady()),"failed"===e&&this.destroy(c(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),"closed"===e&&this.destroy(c(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(e){const t=e=>("[object Array]"===Object.prototype.toString.call(e.values)&&e.values.forEach(t=>{Object.assign(e,t)}),e);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then(n=>{const r=[];n.forEach(e=>{r.push(t(e))}),e(null,r)},t=>e(t)):0<this._pc.getStats.length?this._pc.getStats(n=>{if(this.destroyed)return;const r=[];n.result().forEach(e=>{const n={};e.names().forEach(t=>{n[t]=e.stat(t)}),n.id=e.id,n.type=e.type,n.timestamp=e.timestamp,r.push(t(n))}),e(null,r)},t=>e(t)):e(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this.getStats((t,n)=>{if(this.destroyed)return;t&&(n=[]);const r={},i={},s={};let o=!1;n.forEach(e=>{("remotecandidate"===e.type||"remote-candidate"===e.type)&&(r[e.id]=e),("localcandidate"===e.type||"local-candidate"===e.type)&&(i[e.id]=e),("candidatepair"===e.type||"candidate-pair"===e.type)&&(s[e.id]=e)});const a=e=>{o=!0;let t=i[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=+t.port):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=+t.portNumber):"string"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(":"),this.localAddress=t[0],this.localPort=+t[1]),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let n=r[e.remoteCandidateId];n&&(n.ip||n.address)?(this.remoteAddress=n.ip||n.address,this.remotePort=+n.port):n&&n.ipAddress?(this.remoteAddress=n.ipAddress,this.remotePort=+n.portNumber):"string"==typeof e.googRemoteAddress&&(n=e.googRemoteAddress.split(":"),this.remoteAddress=n[0],this.remotePort=+n[1]),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(n.forEach(e=>{"transport"===e.type&&e.selectedCandidatePairId&&a(s[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&a(e)}),o||Object.keys(s).length&&!Object.keys(i).length){if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(e){return this.destroy(c(e,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');const t=this._cb;this._cb=null,t(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}else setTimeout(e,100)})};e()}_onInterval(){this._cb&&this._channel&&!(this._channel.bufferedAmount>d)&&this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(e=>{this._pc.removeTrack(e),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(e){this.destroyed||(e.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):!e.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit("_iceComplete")),e.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(e){if(this.destroyed)return;let t=e.data;t instanceof ArrayBuffer&&(t=l.from(t)),this.push(t)}_onChannelBufferedAmountLow(){if(!this.destroyed&&this._cb){this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const e=this._cb;this._cb=null,e(null)}}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(e){this.destroyed||e.streams.forEach(t=>{this._debug("on track"),this.emit("track",e.track,t),this._remoteTracks.push({track:e.track,stream:t}),this._remoteStreams.some(e=>e.id===t.id)||(this._remoteStreams.push(t),a(()=>{this._debug("on stream"),this.emit("stream",t)}))})}_debug(){const e=[].slice.call(arguments);e[0]="["+this._id+"] "+e[0],r.apply(null,e)}}h.WEBRTC_SUPPORT=!!i(),h.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},h.channelConfig={},t.exports=h},{buffer:3,debug:4,"err-code":6,"get-browser-rtc":8,"queue-microtask":13,randombytes:14,"readable-stream":29}]},{},[])("/")})}),qs=e.__toESM(Ys(),1),Ks=(e,t)=>{if(!t)return a.resolve(e);const n=crypto.getRandomValues(new Uint8Array(12));return crypto.subtle.encrypt({name:"AES-GCM",iv:n},t,e).then(e=>{const t=a.createEncoder();return a.writeVarString(t,"AES-GCM"),a.writeVarUint8Array(t,n),a.writeVarUint8Array(t,new Uint8Array(e)),a.toUint8Array(t)})},zs=(e,t)=>{if(!t)return a.resolve(e);const n=a.createDecoder(e);"AES-GCM"!==a.readVarString(n)&&a.reject(a.create$1("Unknown encryption algorithm"));const r=a.readVarUint8Array(n),i=a.readVarUint8Array(n);return crypto.subtle.decrypt({name:"AES-GCM",iv:r},t,i).then(e=>new Uint8Array(e))},$s=a.createModuleLogger("y-webrtc"),Js=new Map,Qs=new Map,Gs=e=>{let t=!0;e.webrtcConns.forEach(e=>{e.synced||(t=!1)}),(!t&&e.synced||t&&!e.synced)&&(e.synced=t,e.provider.emit("synced",[{synced:t}]),$s("synced ",a.BOLD,e.name,a.UNBOLD," with all peers"))},Xs=(e,t,n)=>{const r=a.createDecoder(t),i=a.createEncoder(),s=a.readVarUint(r);if(void 0===e)return null;const o=e.awareness,c=e.doc;let l=!1;switch(s){case 0:{a.writeVarUint(i,0);const t=cs(r,i,c,e);1!==t||e.synced||n(),0===t&&(l=!0);break}case 3:a.writeVarUint(i,1),a.writeVarUint8Array(i,ts(o,Array.from(o.getStates().keys()))),l=!0;break;case 1:ns(o,a.readVarUint8Array(r),e);break;case 4:{const t=1===a.readUint8(r),n=a.readVarString(r);if(n!==e.peerId&&(e.bcConns.has(n)&&!t||!e.bcConns.has(n)&&t)){const r=[],i=[];t?(e.bcConns.add(n),i.push(n)):(e.bcConns.delete(n),r.push(n)),e.provider.emit("peers",[{added:i,removed:r,webrtcPeers:Array.from(e.webrtcConns.keys()),bcPeers:Array.from(e.bcConns)}]),io(e)}break}default:return i}return l?i:null},Zs=(e,t)=>{$s("send message to ",a.BOLD,e.remotePeerId,a.UNBOLD,a.GREY," (",e.room.name,")",a.UNCOLOR);try{e.peer.send(a.toUint8Array(t))}catch(n){}},eo=class{constructor(e,t,n,r){$s("establishing connection to ",a.BOLD,n),this.room=r,this.remotePeerId=n,this.glareToken=void 0,this.closed=!1,this.connected=!1,this.synced=!1,this.peer=new qs.default({initiator:t,...r.provider.peerOpts}),this.peer.on("signal",t=>{void 0===this.glareToken&&(this.glareToken=Date.now()+Math.random()),oo(e,r,{to:n,from:r.peerId,type:"signal",token:this.glareToken,signal:t})}),this.peer.on("connect",()=>{$s("connected to ",a.BOLD,n),this.connected=!0;const e=r.provider.doc,t=r.awareness,i=a.createEncoder();a.writeVarUint(i,0),rs(i,e),Zs(this,i);const s=t.getStates();if(s.size>0){const e=a.createEncoder();a.writeVarUint(e,1),a.writeVarUint8Array(e,ts(t,Array.from(s.keys()))),Zs(this,e)}}),this.peer.on("close",()=>{this.connected=!1,this.closed=!0,r.webrtcConns.has(this.remotePeerId)&&(r.webrtcConns.delete(this.remotePeerId),r.provider.emit("peers",[{removed:[this.remotePeerId],added:[],webrtcPeers:Array.from(r.webrtcConns.keys()),bcPeers:Array.from(r.bcConns)}])),Gs(r),this.peer.destroy(),$s("closed connection to ",a.BOLD,n),ro(r)}),this.peer.on("error",e=>{$s("Error in connection to ",a.BOLD,n,": ",e),ro(r)}),this.peer.on("data",e=>{const t=((e,t)=>{const n=e.room;return $s("received message from ",a.BOLD,e.remotePeerId,a.GREY," (",n.name,")",a.UNBOLD,a.UNCOLOR),Xs(n,t,()=>{e.synced=!0,$s("synced ",a.BOLD,n.name,a.UNBOLD," with ",a.BOLD,e.remotePeerId),Gs(n)})})(this,e);null!==t&&Zs(this,t)})}destroy(){this.peer.destroy()}},to=(e,t)=>Ks(t,e.key).then(t=>e.mux(()=>((e,t,n=null)=>{const r=Ws(e);r.bc.postMessage(t),r.subs.forEach(e=>e(t,n))})(e.name,t))),no=(e,t)=>{e.bcconnected&&to(e,t),((e,t)=>{$s("broadcast message in ",a.BOLD,e.name,a.UNBOLD),e.webrtcConns.forEach(e=>{try{e.peer.send(t)}catch(n){}})})(e,t)},ro=e=>{Js.forEach(t=>{t.connected&&(t.send({type:"subscribe",topics:[e.name]}),e.webrtcConns.size<e.provider.maxConns&&oo(t,e,{type:"announce",from:e.peerId}))})},io=e=>{if(e.provider.filterBcConns){const t=a.createEncoder();a.writeVarUint(t,4),a.writeUint8(t,1),a.writeVarString(t,e.peerId),to(e,a.toUint8Array(t))}},so=class{constructor(e,t,n,r){this.peerId=a.uuidv4(),this.doc=e,this.awareness=t.awareness,this.provider=t,this.synced=!1,this.name=n,this.key=r,this.webrtcConns=new Map,this.bcConns=new Set,this.mux=a.createMutex(),this.bcconnected=!1,this._bcSubscriber=e=>zs(new Uint8Array(e),r).then(e=>this.mux(()=>{const t=Xs(this,e,()=>{});t&&to(this,a.toUint8Array(t))})),this._docUpdateHandler=(e,t)=>{const n=a.createEncoder();a.writeVarUint(n,0),os(n,e),no(this,a.toUint8Array(n))},this._awarenessUpdateHandler=({added:e,updated:t,removed:n},r)=>{const i=e.concat(t).concat(n),s=a.createEncoder();a.writeVarUint(s,1),a.writeVarUint8Array(s,ts(this.awareness,i)),no(this,a.toUint8Array(s))},this._beforeUnloadHandler=()=>{es(this.awareness,[e.clientID],"window unload"),Qs.forEach(e=>{e.disconnect()})},"undefined"!=typeof window?window.addEventListener("beforeunload",this._beforeUnloadHandler):"undefined"!=typeof process&&process.on("exit",this._beforeUnloadHandler)}connect(){this.doc.on("update",this._docUpdateHandler),this.awareness.on("update",this._awarenessUpdateHandler),ro(this);const e=this.name;var t,n;t=e,n=this._bcSubscriber,Ws(t).subs.add(n),this.bcconnected=!0,io(this);const r=a.createEncoder();a.writeVarUint(r,0),rs(r,this.doc),to(this,a.toUint8Array(r));const i=a.createEncoder();a.writeVarUint(i,0),is(i,this.doc),to(this,a.toUint8Array(i));const s=a.createEncoder();a.writeVarUint(s,3),to(this,a.toUint8Array(s));const o=a.createEncoder();a.writeVarUint(o,1),a.writeVarUint8Array(o,ts(this.awareness,[this.doc.clientID])),to(this,a.toUint8Array(o))}disconnect(){Js.forEach(e=>{e.connected&&e.send({type:"unsubscribe",topics:[this.name]})}),es(this.awareness,[this.doc.clientID],"disconnect");const e=a.createEncoder();a.writeVarUint(e,4),a.writeUint8(e,0),a.writeVarString(e,this.peerId),to(this,a.toUint8Array(e)),((e,t)=>{const n=Ws(e),r=n.subs.delete(t);r&&0===n.subs.size&&(n.bc.close(),Bs.delete(e))})(this.name,this._bcSubscriber),this.bcconnected=!1,this.doc.off("update",this._docUpdateHandler),this.awareness.off("update",this._awarenessUpdateHandler),this.webrtcConns.forEach(e=>e.destroy())}destroy(){this.disconnect(),"undefined"!=typeof window?window.removeEventListener("beforeunload",this._beforeUnloadHandler):"undefined"!=typeof process&&process.off("exit",this._beforeUnloadHandler)}},oo=(e,t,n)=>{t.key?((e,t)=>{const n=a.createEncoder();return a.writeAny(n,e),Ks(a.toUint8Array(n),t)})(n,t.key).then(n=>{e.send({type:"publish",topic:t.name,data:a.toBase64(n)})}):e.send({type:"publish",topic:t.name,data:n})},ao=class extends Fs{constructor(e){super(e),this.providers=new Set,this.on("connect",()=>{$s(`connected (${e})`);const t=Array.from(Qs.keys());this.send({type:"subscribe",topics:t}),Qs.forEach(e=>oo(this,e,{type:"announce",from:e.peerId}))}),this.on("message",e=>{if("publish"===e.type){const r=e.topic,i=Qs.get(r);if(null==i||"string"!=typeof r)return;const s=e=>{const t=i.webrtcConns,n=i.peerId;if(null==e||e.from===n||void 0!==e.to&&e.to!==n||i.bcConns.has(e.from))return;const r=t.has(e.from)?()=>{}:()=>i.provider.emit("peers",[{removed:[],added:[e.from],webrtcPeers:Array.from(i.webrtcConns.keys()),bcPeers:Array.from(i.bcConns)}]);switch(e.type){case"announce":t.size<i.provider.maxConns&&(a.setIfUndefined(t,e.from,()=>new eo(this,!0,e.from,i)),r());break;case"signal":if("offer"===e.signal.type){const n=t.get(e.from);if(n){const t=e.token,r=n.glareToken;if(r&&r>t)return void $s("offer rejected: ",e.from);n.glareToken=void 0}}if("answer"===e.signal.type){$s("offer answered by: ",e.from);t.get(e.from).glareToken=void 0}e.to===n&&(a.setIfUndefined(t,e.from,()=>new eo(this,!1,e.from,i)).peer.signal(e.signal),r())}};i.key?"string"==typeof e.data&&(t=a.fromBase64(e.data),n=i.key,zs(t,n).then(e=>a.readAny(a.createDecoder(new Uint8Array(e))))).then(s):s(e.data)}var t,n}),this.on("disconnect",()=>$s(`disconnect (${e})`))}},co=e=>{e.emit("status",[{connected:e.connected}])},lo=class extends a.ObservableV2{constructor(e,t,{signaling:n=["wss://y-webrtc-eu.fly.dev"],password:r=null,awareness:i=new Zi(t),maxConns:s=20+a.floor(15*a.rand()),filterBcConns:o=!0,peerOpts:c={}}={}){super(),this.roomName=e,this.doc=t,this.filterBcConns=o,this.awareness=i,this.shouldConnect=!1,this.signalingUrls=n,this.signalingConns=[],this.maxConns=s,this.peerOpts=c,this.key=r?((e,t)=>{const n=a.encodeUtf8(e).buffer,r=a.encodeUtf8(t).buffer;return crypto.subtle.importKey("raw",n,"PBKDF2",!1,["deriveKey"]).then(e=>crypto.subtle.deriveKey({name:"PBKDF2",salt:r,iterations:1e5,hash:"SHA-256"},e,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]))})(r,e):a.resolve(null),this.room=null,this.key.then(n=>{this.room=((e,t,n,r)=>{if(Qs.has(n))throw a.create$1(`A Yjs Doc connected to room "${n}" already exists!`);const i=new so(e,t,n,r);return Qs.set(n,i),i})(t,this,e,n),this.shouldConnect?this.room.connect():this.room.disconnect(),co(this)}),this.connect(),this.destroy=this.destroy.bind(this),t.on("destroy",this.destroy)}get connected(){return null!==this.room&&this.shouldConnect}connect(){this.shouldConnect=!0,this.signalingUrls.forEach(e=>{const t=a.setIfUndefined(Js,e,()=>new ao(e));this.signalingConns.push(t),t.providers.add(this)}),this.room&&(this.room.connect(),co(this))}disconnect(){this.shouldConnect=!1,this.signalingConns.forEach(e=>{e.providers.delete(this),0===e.providers.size&&(e.destroy(),Js.delete(e.url))}),this.room&&(this.room.disconnect(),co(this))}destroy(){this.doc.off("destroy",this.destroy),this.key.then(()=>{this.room.destroy(),Qs.delete(this.roomName)}),super.destroy()}};async function ho(e,t){const n=await async function(e,t){const n=`${e}-${JSON.stringify(t)}`,r=(new TextEncoder).encode(n),i=globalThis.crypto?.subtle??globalThis.window?.crypto?.subtle;if(!i)throw new Error("Web Crypto API subtle.digest is unavailable");return function(e){const t=new DataView(e).getInt32(0,!1);return Math.abs(t)%2147483647+1}(await i.digest("SHA-256",r))}(e,t),r=new nt({guid:e});r.clientID=n;const i=bi(t);r.get("content",wr).applyDelta(i);const s=mt(r);return r.destroy(),s}var uo={hocuspocus:class{_isConnected=!1;_isSynced=!1;onConnect;onDisconnect;onError;onSyncChange;destroy=()=>{this._isConnected&&this.provider.disconnect()};disconnect=()=>{this._isConnected&&(this.provider.disconnect(),this._isConnected=!1,this._isSynced&&(this._isSynced=!1,this?.onSyncChange?.(!1)))};provider;type="hocuspocus";constructor({awareness:e,doc:t,options:n,wsOptions:r,onConnect:i,onDisconnect:s,onError:o,onSyncChange:a}){this.onConnect=i,this.onDisconnect=s,this.onSyncChange=a,this.onError=o;const c={...n,...t&&{document:t},...e&&{awareness:e},...r&&(()=>{try{return{websocketProvider:new ps(r)}}catch(e){return this.onError?.(e instanceof Error?e:new Error(String(e))),{}}})(),onAwarenessChange:n.onAwarenessChange||(()=>{}),onConnect:()=>{this._isConnected=!0,this.onConnect?.(),n.onConnect?.()},onDisconnect:e=>{this._isConnected=!1,this._isSynced&&(this._isSynced=!1,this.onSyncChange?.(!1)),this.onDisconnect?.(),n.onDisconnect?.(e)},onSynced:e=>{const t=this._isSynced;this._isSynced=!0,t||this.onSyncChange?.(!0),n.onSynced?.(e)}};try{this.provider=new Cs(c)}catch(l){this.provider=new Cs({...c,connect:!1}),this.onError?.(l instanceof Error?l:new Error(String(l)))}}connect(){try{this.provider.connect()}catch(e){this._isConnected=!1}}get awareness(){return this.provider.awareness}get document(){return this.provider.document}get isConnected(){return this._isConnected}get isSynced(){return this._isSynced}},indexeddb:class{_isConnected=!1;_isDestroyed=!1;_isSynced=!1;onConnect;onDisconnect;onError;onSyncChange;providerOptions;_provider=null;awareness;document;isLocalPersistence=!0;type="indexeddb";constructor({awareness:e,doc:t,options:n,onConnect:r,onDisconnect:i,onError:s,onSyncChange:o}){this.document=t??new nt,this.awareness=e??new Zi(this.document),this.providerOptions=n,this.onConnect=r,this.onDisconnect=i,this.onError=s,this.onSyncChange=o}connect=()=>{if(!this._isDestroyed){if(!this._provider)try{const e=new Ns(this.providerOptions.docName,this.document);this._provider=e,e._db.then(()=>{this._provider!==e||this._isDestroyed||this.setConnected(!0)}).catch(t=>{this._provider!==e||this._isDestroyed||(this._provider=null,this.destroyProvider(e,!1),this.handleError(t),this.setSynced(!1),this.setConnected(!1))}),e.whenSynced.then(()=>{this._provider===e&&this._isConnected&&!this._isDestroyed&&this.setSynced(!0)}).catch(e=>{this.handleError(e)})}catch(e){return this.handleError(e),this.setConnected(!1),void this.setSynced(!1)}this._provider.synced&&(this.setConnected(!0),this.setSynced(!0))}};destroy=()=>{this._isDestroyed||(this._isDestroyed=!0,this.disconnect())};disconnect=()=>{const e=this._provider;(e||this._isConnected||this._isSynced)&&(this._provider=null,this.setSynced(!1),this.setConnected(!1),e&&this.destroyProvider(e))};get isConnected(){return this._isConnected}get isConnectionPending(){return!!this._provider&&!this._isConnected&&!this._isDestroyed}get isSyncPending(){return!!this._provider&&!this._isSynced&&!this._isDestroyed}get isSynced(){return this._isSynced}get provider(){return this._provider}destroyProvider(e,t=!0){try{e.destroy().catch(e=>{t&&this.handleError(e)})}catch(n){t&&this.handleError(n)}}handleError(e){this.onError?.(e instanceof Error?e:new Error(String(e)))}setConnected(e){this._isConnected!==e&&(this._isConnected=e,e?this.onConnect?.():this.onDisconnect?.())}setSynced(e){this._isSynced!==e&&(this._isSynced=e,this.onSyncChange?.(e))}},webrtc:class{_isConnected=!1;_isSynced=!1;doc;onSyncChange;provider=null;connect=()=>{if(this.provider)try{this.provider.connect()}catch(e){}};destroy=()=>{if(this.provider)try{this.provider.destroy()}catch(e){}};disconnect=()=>{if(this.provider)try{this.provider.disconnect();const e=this._isSynced;this._isConnected=!1,this._isSynced=!1,e&&this.onSyncChange?.(!1)}catch(e){}};type="webrtc";constructor({awareness:e,doc:t,options:n,onConnect:r,onDisconnect:i,onError:s,onSyncChange:o}){this.onSyncChange=o,this.doc=t||new nt;try{this.provider=new lo(n.roomName,this.doc,{awareness:e,filterBcConns:n.filterBcConns,maxConns:n.maxConns,password:n.password,peerOpts:n.peerOpts,signaling:n.signaling}),this.provider.on("status",e=>{const t=this._isConnected;this._isConnected=e.connected,e.connected?(t||r?.(),this._isSynced||(this._isSynced=!0,o?.(!0))):t&&(i?.(),this._isSynced&&(this._isSynced=!1,o?.(!1)))})}catch(a){s?.(a instanceof Error?a:new Error(String(a)))}}get awareness(){return this.provider.awareness}get document(){return this.doc}get isConnected(){return this._isConnected}get isSynced(){return this._isSynced}}},fo=({type:e,...t})=>{const n=(e=>uo[e])(e);if(!n)throw new Error(`Provider type "${e}" not found in registry`);return new n(t)},go=(e,t,n)=>function(e,t,{cursorStateField:n="selection",cursorDataField:r="data",autoSend:i=!0,data:s}={}){const o=e;o.awareness=t,o.cursorDataField=r,o.selectionStateField=n,o.sendCursorData=e=>{o.awareness.setLocalStateField(o.cursorDataField,e)},o.sendCursorPosition=e=>{const t=o.awareness.getLocalState(),r=null==t?void 0:t[n];if(!e)return void(r&&o.awareness.setLocalStateField(o.selectionStateField,null));const{anchor:i,focus:s}=ji(o.sharedRoot,o,e);r&&Vt(i,r)&&Vt(s,r)||o.awareness.setLocalStateField(o.selectionStateField,{anchor:i,focus:s})};const a=e=>{const t=Gi.get(o);if(!t)return;const n=o.awareness.clientID,r={added:e.added.filter(e=>e!==n),removed:e.removed.filter(e=>e!==n),updated:e.updated.filter(e=>e!==n)};(r.added.length>0||r.removed.length>0||r.updated.length>0)&&t.forEach(e=>e(r))},{connect:c,disconnect:l}=o;return o.connect=()=>{if(c(),o.awareness.on("change",a),a({removed:[],added:Array.from(o.awareness.getStates().keys()),updated:[]}),i){s&&Xi.sendCursorData(o,s);const{onChange:e}=o;o.onChange=()=>{e(),Ki.connected(o)&&Xi.sendCursorPosition(o)}}},o.disconnect=()=>{o.awareness.off("change",a),a({removed:Array.from(o.awareness.getStates().keys()),added:[],updated:[]}),l()},o}(e,t,n),po=e=>"object"==typeof e&&null!==e&&"type"in e&&"options"in e,mo=i.createTSlatePlugin({key:i.KEYS.yjs,extendEditor:({editor:e,getOptions:t})=>{let n=e;const{awareness:r,cursors:i,localOrigin:s,positionStorageOrigin:o,sharedType:a,ydoc:c}=t();if(n=((e,t,n)=>zi(e,t,n))(n,a??c.get("content",wr),{autoConnect:!1,localOrigin:s,positionStorageOrigin:o}),i)if(r){let e=!0;!1===i.autoSend&&(e=!1),n=go(n,r,{...i,autoSend:e})}else n.api.debug.error("Yjs plugin: Internal shared awareness (awareness) is missing but cursors are enabled.");return((e,t)=>Qi(e,t))(n)},options:{_isConnected:!1,_isSynced:!1,userId:null,_providers:[],awareness:null,cursors:{},localOrigin:null,positionStorageOrigin:null,providers:[],sharedType:null,ydoc:null,onConnect:()=>{},onDisconnect:()=>{},onError:()=>{},onSyncChange:()=>{}}}).extend(({getOptions:e})=>{const{localOrigin:t,positionStorageOrigin:n,...r}=e();let{awareness:i,ydoc:s}=r;return s||(s=new nt),i||(i=new Zi(s)),{options:{awareness:i,localOrigin:t??void 0,positionStorageOrigin:n??void 0,ydoc:s}}}).extendApi(e=>({connect:t=>{const{getOptions:n}=e,{_providers:r}=n(),i=t?Array.isArray(t)?t:[t]:null;r.forEach(e=>{if(!i||i.includes(e.type))try{e.connect()}catch(t){n().onError?.({error:t instanceof Error?t:new Error(String(t)),type:e.type})}})},destroy:()=>{const{editor:t,getOptions:n}=e,{_providers:r}=n();for(const e of[...r].reverse())try{(e.isConnected||e.isConnectionPending)&&e.destroy()}catch(i){}try{Ki.disconnect(t)}catch{}},disconnect:t=>{const{editor:n,getOptions:r}=e,{_providers:i}=r(),s=t?Array.isArray(t)?t:[t]:null;for(const e of[...i].reverse())try{!e.isConnected&&!e.isConnectionPending||null!==s&&!s.includes(e.type)||e.disconnect()}catch(o){}},init:async({id:t,autoConnect:n=!0,autoSelect:r,selection:i,value:s,onReady:o}={})=>{const{editor:a,getOptions:c,setOption:l}=e,{awareness:d,providers:h=[],sharedType:u,ydoc:f}=c(),g=()=>{return(e=u??f.get("content",wr)).length>0||null!=e._start;var e};if(0===h.length)throw new Error("No providers specified. Please provide provider configurations or instances in the `providers` array.");const p=[];let m=null;const y=new Promise(e=>{m=e});for(const e of h)if(po(e)){const{options:t,type:n}=e;let r=null;if(!t)continue;try{const e=fo({awareness:d,doc:f,options:t,type:n,onConnect:()=>{c().onConnect?.({type:n}),l("_isConnected",!0)},onDisconnect:()=>{c().onDisconnect?.({type:n});const{_providers:e}=c();e.some(e=>e.isConnected)||l("_isConnected",!1)},onError:e=>{c().onError?.({error:e,type:n})},onSyncChange:e=>{c().onSyncChange?.({isSynced:e,type:n}),l("_isSynced",e);const t=p.some(e=>!e.isLocalPersistence),i=!r?.isLocalPersistence||!t||g();e&&m&&i&&(m(),m=null)}});r=e,p.push(e)}catch{}}else p.push(e);if(l("_providers",p),n&&p.length>0){p.forEach(e=>{try{e.connect()}catch(t){c().onError?.({error:t instanceof Error?t:new Error(String(t)),type:e.type})}});const e=5e3;await Promise.race([y,new Promise(t=>{setTimeout(()=>{m=null,t()},e)})])}if(!g()&&!p.some(e=>e.isLocalPersistence&&(e.isConnectionPending||e.isSyncPending))&&null!==s){let e=s;if("string"==typeof s?e=a.api.html.deserialize({element:s}):"function"==typeof s?e=await s(a):s&&(e=s),e&&0!==e?.length||(e=a.api.create.value()),u){const t=bi(e);f.transact(()=>{u.applyDelta(t)})}else{const n=await ho(t??a.id,e);f.transact(()=>{gt(f,n)})}}Ki.connect(a),a.tf.init({autoSelect:r,selection:i,shouldNormalizeEditor:!1,value:null}),a.api.onChange(),o?.({editor:a,isAsync:!0,value:a.children})}})),yo=i.toPlatePlugin(mo),wo=Object.defineProperty,bo=Object.defineProperties,vo=Object.getOwnPropertyDescriptors,_o=Object.getOwnPropertySymbols,So=Object.prototype.hasOwnProperty,ko=Object.prototype.propertyIsEnumerable,Co=(e,t,n)=>t in e?wo(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Eo=(e,t)=>{for(var n in t||(t={}))So.call(t,n)&&Co(e,n,t[n]);if(_o)for(var n of _o(t))ko.call(t,n)&&Co(e,n,t[n]);return e},Ao=(e,t)=>bo(e,vo(t));function xo(e){return"[object Object]"===Object.prototype.toString.call(e)}function To(e){if(!xo(e))return!1;const t=e.constructor;if(void 0===t)return!0;const n=t.prototype;return!1!==xo(n)&&!1!==n.hasOwnProperty("isPrototypeOf")}function Ro(e,t){for(const n in e){const r=e[n],i=t[n];if(To(r)&&To(i)){if(!Ro(r,i))return!1}else if(Array.isArray(r)&&Array.isArray(i)){if(r.length!==i.length)return!1;for(let e=0;e<r.length;e++)if(r[e]!==i[e])return!1}else if(r!==i)return!1}for(const n in t)if(void 0===e[n]&&void 0!==t[n])return!1;return!0}function Do(e){return function(e){var t,n;const r=[];for(const i of e){if("string"==typeof i.insert&&0===i.insert.length)continue;const e=r[r.length-1];e&&"string"==typeof e.insert&&"string"==typeof i.insert&&(e.attributes===i.attributes||!e.attributes==!i.attributes&&Ro(null!=(t=e.attributes)?t:{},null!=(n=i.attributes)?n:{}))?e.insert+=i.insert:r.push(i)}return r}(e.toDelta())}function Oo({insert:e}){return"string"==typeof e?e.length:1}function Uo(e){return e.reduce((e,t)=>e+Oo(t),0)}function Po(e,t,n){if(n<1)return[];let r=0;const i=[],s=t+n;for(let o=0;o<e.length&&!(r>=s);o++){const n=e[o],a=Oo(n);if(r+a<=t){r+=a;continue}if("string"!=typeof n.insert){r+=a,i.push(n);continue}const c=Math.max(0,t-r),l=Math.min(a,a-(r+a-s));i.push(Ao(Eo({},n),{insert:n.insert.slice(c,l)})),r+=a}return i}function Lo(e){return function(e,...t){return Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e)))}(e,i.Text.isText(e)?"text":"children")}function Mo(e){var t=e,{children:n}=t,r=((e,t)=>{var n={};for(var r in e)So.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&_o)for(var r of _o(e))t.indexOf(r)<0&&ko.call(e,r)&&(n[r]=e[r]);return n})(t,["children"]);const s=new a.YXmlText;return Object.entries(r).forEach(([e,t])=>{s.setAttribute(e,t)}),s.applyDelta(n.map(e=>i.Text.isText(e)?{insert:e.text,attributes:Lo(e)}:{insert:Mo(e)}),{sanitize:!1}),s}function Io(e){return e?i.Text.isText(e)?e.text.length:1:0}function No(e,t,n){var r;if(0===n.length)throw new Error("Path has to a have a length >= 1");if(i.Text.isText(t))throw new Error("Cannot descent into slate text");const[s,...o]=n,c=function(e,t){return e.children.slice(0,t).reduce((e,t)=>e+Io(t),0)}(t,s),l=t.children[s],d=Do(e),h=Io(l),u=Po(d,c,h);if(u.length>1)throw new Error("Path doesn't match yText, yTarget spans multiple nodes");const f=null==(r=u[0])?void 0:r.insert;if(o.length>0){if(!(f instanceof a.YXmlText))throw new Error("Path doesn't match yText, cannot descent into non-yText");return No(f,l,o)}return{yParent:e,textRange:{start:c,end:c+h},yTarget:f instanceof a.YXmlText?f:void 0,slateParent:t,slateTarget:l,targetDelta:u}}function jo(e,t,n={}){const{assoc:r=0,insert:s=!1}=n;let o=0,a=0;for(let l=0;l<e.children.length;l++){const n=e.children[l],s=i.Text.isText(n)?n.text.length:1;s>0&&(a=l);const c=o+s;if(s>0&&(r>=0?c>t:c>=t))return[l,t-o];o+=s}if(t>o+(s?1:0))throw new Error("yOffset out of bounds");if(s)return[e.children.length,0];const c=e.children[a];return[a,i.Text.isText(c)?c.text.length:1]}function Vo(e){return e.map(e=>"string"==typeof e.insert?e:Ao(Eo({},e),{insert:Fo(e.insert)}))}function Fo(e){const t=new a.YXmlText,n=e.getAttributes();return Object.entries(n).forEach(([e,n])=>{t.setAttribute(e,n)}),t.applyDelta(Vo(Do(e)),{sanitize:!1}),t}function Bo(e){if(!e.doc)throw new Error("shared type isn't attached to a document")}var Ho="__slateYjsStoredPosition_";function Wo(e,t,{type:n,index:r,assoc:s}){if(!(n instanceof a.YXmlText))throw new Error("Absolute position points to a non-XMLText");const o=function(e,t,n){const r=[n];for(;r[0]!==e;){const{parent:e}=r[0];if(!e)throw new Error("yText isn't a descendant of root element");if(!(e instanceof a.YXmlText))throw new Error("Unexpected y parent type");r.unshift(e)}if(r.length<2)return[];let s=t;return r.reduce((e,t,n)=>{const o=r[n+1];if(!o)return e;let a=0;const c=Do(t);for(const r of c){if(r.insert===o)break;a+="string"==typeof r.insert?r.insert.length:1}if(i.Text.isText(s))throw new Error("Cannot descent into slate text");const[l]=jo(s,a);return s=s.children[l],e.concat(l)},[])}(e,t,n),c=i.Node.get(t,o);if(i.Text.isText(c))throw new Error("Absolute position doesn't match slateRoot, cannot descent into text");const[l,d]=jo(c,r,{assoc:s}),h=c.children[l];return i.Text.isText(h)?{path:[...o,l],offset:d}:null}function Yo(e,t,n){if(!e.doc)throw new Error("sharedRoot isn't attach to a yDoc");const r=a.createAbsolutePositionFromRelativePosition(n,e.doc);return r&&Wo(e,t,r)}function qo(e,t,n){e.setAttribute(Ho+t,a.encodeRelativePosition(n))}function Ko(e,t,n){return Object.fromEntries(Object.entries(e).filter(([,e])=>e.type===t&&(!n||(e.assoc>=0?e.index>=n.start&&e.index<n.end:e.index>n.start&&e.index>=n.end))))}function zo(e,t,n=""){const r={[n]:Ko(e,t)};return Do(t).forEach(({insert:t},i)=>{t instanceof a.YXmlText&&Object.assign(r,zo(e,t,n?`${n}.${i}`:i.toString()))}),r}function $o(e,t,n,r=0){const i=function(e){return Bo(e),Object.fromEntries(Object.entries(e.getAttributes()).filter(([e])=>e.startsWith(Ho)).map(([t,n])=>[t.slice(25),a.createAbsolutePositionFromRelativePosition(a.decodeRelativePosition(n),e.doc)]).filter(([,e])=>e))}(e),s={"":Ko(i,t,{start:r,end:r+Uo(n)})};return n.forEach(({insert:e},t)=>{e instanceof a.YXmlText&&Object.assign(s,zo(i,e,t.toString()))}),s}function Jo(e,t,n,r,i=0,s=0,o=""){const c=n[o];c&&Object.entries(c).forEach(([n,r])=>{qo(e,n,a.createRelativePositionFromTypeIndex(t,r.index-s+i,r.assoc))}),r.forEach(({insert:t},r)=>{t instanceof a.YXmlText&&Jo(e,t,n,Do(t),0,0,o?`${o}.${r}`:r.toString())})}var Qo={insert_node:function(e,t,n){const{yParent:r,textRange:s}=No(e,t,n.path);if(i.Text.isText(n.node))return r.insert(s.start,n.node.text,Lo(n.node));r.insertEmbed(s.start,Mo(n.node))},remove_node:function(e,t,n){const{yParent:r,textRange:i}=No(e,t,n.path);r.delete(i.start,i.end-i.start)},set_node:function(e,t,n){const{yTarget:r,textRange:i,yParent:s}=No(e,t,n.path);if(r)return Object.entries(n.newProperties).forEach(([e,t])=>{if(null===t)return r.removeAttribute(e);r.setAttribute(e,t)}),Object.entries(n.properties).forEach(([e])=>{n.newProperties.hasOwnProperty(e)||r.removeAttribute(e)});const o=Eo(Eo({},Object.fromEntries(Object.keys(n.properties).map(e=>[e,null]))),n.newProperties);s.format(i.start,i.end-i.start,o)},merge_node:function(e,t,n){const r=No(e,t,n.path),s=No(r.yParent,r.slateParent,i.Path.previous(n.path.slice(-1)));if(!r.yTarget!=!s.yTarget)throw new Error("Cannot merge y text with y element");if(!s.yTarget||!r.yTarget){const{yParent:e,textRange:s,slateTarget:o}=r;if(!o)throw new Error("Expected Slate target node for merge op.");const a=i.Node.get(t,i.Path.previous(n.path));if(!i.Text.isText(a))throw new Error("Path points to Y.Text but not a Slate text node.");const c=Lo(o),l=Lo(a),d=Object.keys(c).reduce((e,t)=>t in l?e:Ao(Eo({},e),{[t]:null}),{});return e.format(s.start,s.end-s.start,Eo(Eo({},d),l))}const o=s.yTarget.length,a=Do(r.yTarget),c=Vo(a),l=$o(e,r.yTarget,a,o),d=[{retain:o},...c];s.yTarget.applyDelta(d,{sanitize:!1}),r.yParent.delete(r.textRange.start,r.textRange.end-r.textRange.start),Jo(e,s.yTarget,l,c,o)},move_node:function(e,t,n){const r=i.Path.parent(n.newPath),s=n.newPath[n.newPath.length-1],o=i.Node.get(t,r);if(i.Text.isText(o))throw new Error("Cannot move slate node into text element");const a=[...r,Math.min(s,o.children.length)],c=No(e,t,n.path),l=No(e,t,a),d=Vo(c.targetDelta),h=$o(e,c.yParent,c.targetDelta);c.yParent.delete(c.textRange.start,c.textRange.end-c.textRange.start);const u=Uo(Do(l.yParent)),f=Math.min(l.textRange.start,u),g=[{retain:f},...d];l.yParent.applyDelta(g,{sanitize:!1}),Jo(e,l.yParent,h,d,f,c.textRange.start)},split_node:function(e,t,n){const r=No(e,t,n.path);if(!r.slateTarget)throw new Error("Y target without corresponding slate node");if(!r.yTarget){if(!i.Text.isText(r.slateTarget))throw new Error("Mismatch node type between y target and slate node");const e={};return r.targetDelta.forEach(t=>{t.attributes&&Object.keys(t.attributes).forEach(t=>{e[t]=null})}),r.yParent.format(r.textRange.start,r.textRange.end-r.textRange.start,Eo(Eo({},e),n.properties))}if(i.Text.isText(r.slateTarget))throw new Error("Mismatch node type between y target and slate node");const s=No(r.yTarget,r.slateTarget,[n.position]),o=r.slateTarget.children.slice(0,n.position).reduce((e,t)=>e+Io(t),0),c=r.slateTarget.children.reduce((e,t)=>e+Io(t),0),l=Po(Do(r.yTarget),o,c-o),d=Vo(l),h=$o(e,r.yTarget,l,o),u=new a.YXmlText;u.applyDelta(d,{sanitize:!1}),Object.entries(n.properties).forEach(([e,t])=>{u.setAttribute(e,t)}),r.yTarget.delete(s.textRange.start,r.yTarget.length-s.textRange.start),r.yParent.insertEmbed(r.textRange.end,u),Jo(e,u,h,d,0,o)}};Ao(Eo(Eo({},{insert_text:function(e,t,n){const{yParent:r,textRange:s}=No(e,t,n.path),o=i.Node.get(t,n.path);if(!i.Text.isText(o))throw new Error("Cannot insert text into non-text node");r.insert(s.start+n.offset,n.text,Lo(o))},remove_text:function(e,t,n){const{yParent:r,textRange:i}=No(e,t,n.path);r.delete(i.start+n.offset,n.text.length)}}),Qo),{set_selection:()=>{}});var Go=new WeakMap,Xo=new WeakMap,Zo=new WeakSet,ea={isYjsEditor:e=>i.Editor$1.isEditor(e)&&e.sharedRoot instanceof a.YXmlText&&"localOrigin"in e&&"positionStorageOrigin"in e&&"function"==typeof e.applyRemoteEvents&&"function"==typeof e.storeLocalChange&&"function"==typeof e.flushLocalChanges&&"function"==typeof e.isLocalOrigin&&"function"==typeof e.connect&&"function"==typeof e.disconnect,localChanges(e){var t;return null!=(t=Xo.get(e))?t:[]},applyRemoteEvents(e,t,n){e.applyRemoteEvents(t,n)},storeLocalChange(e,t){e.storeLocalChange(t)},flushLocalChanges(e){e.flushLocalChanges()},connected:e=>Zo.has(e),connect(e){e.connect()},disconnect(e){e.disconnect()},isLocal:e=>e.isLocalOrigin(ea.origin(e)),origin(e){const t=Go.get(e);return void 0!==t?t:e.localOrigin},withOrigin(e,t,n){const r=ea.origin(e);Go.set(e,t),n(),Go.set(e,r)},storePosition(e,t,n){const{sharedRoot:r,positionStorageOrigin:i}=e;Bo(r);const s=function(e,t,n){const{yTarget:r,yParent:i,textRange:s}=No(e,t,n.path);if(r)throw new Error("Slate point points to a non-text element inside sharedRoot");const o=s.start+n.offset;return a.createRelativePositionFromTypeIndex(i,o,o===s.end?-1:0)}(r,e,n);r.doc.transact(()=>{qo(r,t,s)},i)},removeStoredPosition(e,t){const{sharedRoot:n,positionStorageOrigin:r}=e;Bo(n),n.doc.transact(()=>{!function(e,t){e.removeAttribute(Ho+t)}(n,t)},r)},position(e,t){const n=function(e,t){const n=e.getAttribute(Ho+t);return n?a.decodeRelativePosition(n):null}(e.sharedRoot,t);if(n)return Yo(e.sharedRoot,e,n)},storedPositionsRelative(e){return t=e.sharedRoot,Object.fromEntries(Object.entries(t.getAttributes()).filter(([e])=>e.startsWith(Ho)).map(([e,t])=>[e.slice(25),a.createRelativePositionFromJSON(t)]));var t}},ta=new WeakMap,na={isCursorEditor:e=>ea.isYjsEditor(e)&&e.awareness&&"string"==typeof e.cursorDataField&&"string"==typeof e.selectionStateField&&"function"==typeof e.sendCursorPosition&&"function"==typeof e.sendCursorData,sendCursorPosition(e,t=e.selection){e.sendCursorPosition(t)},sendCursorData(e,t){e.sendCursorData(t)},on(e,t,n){var r;if("change"!==t)return;const i=null!=(r=ta.get(e))?r:new Set;i.add(n),ta.set(e,i)},off(e,t,n){if("change"!==t)return;const r=ta.get(e);r&&r.delete(n)},cursorState(e,t){var n;if(t===e.awareness.clientID||!ea.connected(e))return null;const r=e.awareness.getStates().get(t);return r?{relativeSelection:null!=(n=r[e.selectionStateField])?n:null,data:r[e.cursorDataField],clientId:t}:null},cursorStates:e=>ea.connected(e)?Object.fromEntries(Array.from(e.awareness.getStates().entries(),([t,n])=>t!==e.awareness.clientID&&n?[t,{relativeSelection:n[e.selectionStateField],data:n[e.cursorDataField]}]:null).filter(Array.isArray)):{}},ra=Object.defineProperty,ia=Object.defineProperties,sa=Object.getOwnPropertyDescriptors,oa=Object.getOwnPropertySymbols,aa=Object.prototype.hasOwnProperty,ca=Object.prototype.propertyIsEnumerable,la=(e,t,n)=>t in e?ra(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,da=(e,t)=>{for(var n in t||(t={}))aa.call(t,n)&&la(e,n,t[n]);if(oa)for(var n of oa(t))ca.call(t,n)&&la(e,n,t[n]);return e},ha=new WeakMap;function ua(e,t){if(!t.relativeSelection)return null;let n=ha.get(e.children);n||(n=new WeakMap,ha.set(e.children,n));let r=n.get(t);if(void 0===r)try{r=function(e,t,n){const r=Yo(e,t,n.anchor);if(!r)return null;const i=Yo(e,t,n.focus);return i?{anchor:r,focus:i}:null}(e.sharedRoot,e,t.relativeSelection),n.set(t,r)}catch(i){return null}return r}function fa(){const e=i.useSlateStatic();if(!na.isCursorEditor(e))throw new Error("Cannot use useSyncExternalStore outside the context of a RemoteCursorEditor");return e}var ga=new WeakMap;function pa(e){const t=ga.get(e);if(t)return t;const n=function(e){let t={};const n=new Set,r=n.add.bind(n),i=new Set;let s=null;return[t=>(i.add(t),s||(s=e=>{e.added.forEach(r),e.removed.forEach(r),e.updated.forEach(r),i.forEach(e=>e())},na.on(e,"change",s)),()=>{i.delete(t),s&&0===i.size&&(na.off(e,"change",s),s=null)}),()=>(0===n.size||(n.forEach(n=>{const r=na.cursorState(e,n);null!==r?t[n]=r:delete t[n.toString()]}),n.clear(),t=da({},t)),t)]}(e);return ga.set(e,n),n}function ma(){const[e,t]=pa(fa());return(0,g.useSyncExternalStore)(e,t)}function ya(e,t,{yOffset:n,xOffset:r,shouldGenerateOverlay:s}){const[o,a]=i.Range.edges(t),c=function(e,t){try{return i.ReactEditor.toDOMRange(e,t)}catch(n){return null}}(e,t);if(!c)return{caretPosition:null,selectionRects:[]};const l=[],d=i.Editor$1.nodes(e,{at:t,match:(e,t)=>i.Text.isText(e)&&(!s||s(e,t))});let h=null;const u=i.Range.isBackward(t);for(const[f,g]of d){const s=i.ReactEditor.toDOMNode(e,f),d=i.Path.equals(g,o.path),p=i.Path.equals(g,a.path);let m=null;if(d||p){const e=document.createRange();e.selectNode(s),d&&e.setStart(c.startContainer,c.startOffset),p&&e.setEnd(c.endContainer,c.endOffset),m=e.getClientRects()}else m=s.getClientRects();const y=u?d:p;for(let e=0;e<m.length;e++){const s=m.item(e);if(!s)continue;const o=y&&(u?0===e:e===m.length-1),a=s.top-n,c=s.left-r;o&&(h={height:s.height,top:a,left:c+(u||i.Range.isCollapsed(t)?0:s.width)}),l.push({width:s.width,height:s.height,top:a,left:c})}}return{selectionRects:l,caretPosition:h}}var wa=Object.freeze([]);function ba(e={}){var t,n=e,{containerRef:r,shouldGenerateOverlay:i}=n,s=((e,t)=>{var n={};for(var r in e)aa.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&oa)for(var r of oa(e))t.indexOf(r)<0&&ca.call(e,r)&&(n[r]=e[r]);return n})(n,["containerRef","shouldGenerateOverlay"]);const o=fa(),a=ma(),c=function(){const[,e]=(0,l.useReducer)(e=>e+1,0),t=(0,l.useRef)(null),n=()=>{t.current&&(cancelAnimationFrame(t.current),t.current=0)};return(0,l.useEffect)(n),(0,l.useEffect)(()=>n,[]),(0,l.useCallback)((n=!1)=>{n?e():t.current||(t.current=requestAnimationFrame(e))},[])}(),d=(0,l.useRef)(new WeakMap),[h,u]=(0,l.useState)({}),f=!("refreshOnResize"in s)||(null==(t=s.refreshOnResize)||t);return function(e,t){const n=(0,l.useRef)(t);n.current=t;const[r]=(0,l.useState)(()=>new ResizeObserver(()=>{n.current()}));(0,l.useEffect)(()=>{if(!(null==e?void 0:e.current))return;const{current:t}=e;return r.observe(t),()=>r.unobserve(t)},[r,e])}(f?r:void 0,()=>{d.current=new WeakMap,c("debounced"!==f)}),(0,l.useLayoutEffect)(()=>{var e,t,n;if(r&&!r.current)return;const s=null==(e=null==r?void 0:r.current)?void 0:e.getBoundingClientRect(),c=null!=(t=null==s?void 0:s.x)?t:0,l=null!=(n=null==s?void 0:s.y)?n:0;let f=Object.keys(h).length!==Object.keys(a).length;const g=Object.fromEntries(Object.entries(a).map(([e,t])=>{const n=t.relativeSelection&&ua(o,t);if(!n)return[e,wa];const r=d.current.get(n);if(r)return[e,r];const s=ya(o,n,{xOffset:c,yOffset:l,shouldGenerateOverlay:i});return f=!0,d.current.set(n,s),[e,s]}));f&&u(g)}),[(0,l.useMemo)(()=>Object.entries(a).map(([e,t])=>{var n,r;const i=t.relativeSelection&&ua(o,t),s=h[e];return a=da({},t),c={range:i,caretPosition:null!=(n=null==s?void 0:s.caretPosition)?n:null,selectionRects:null!=(r=null==s?void 0:s.selectionRects)?r:wa},ia(a,sa(c));var a,c}),[a,o,h]),(0,l.useCallback)(()=>{d.current=new WeakMap,c(!0)},[c])]}function va(){return i.usePluginOption(yo,"_isSynced")?(0,u.jsx)(_a,{}):null}function _a(){const e=i.useEditorContainerRef(),[t]=ba({containerRef:e});return(0,u.jsx)(u.Fragment,{children:t.map(e=>(0,u.jsx)(Sa,{...e},e.clientId))})}function Sa({caretPosition:e,data:t,selectionRects:n}){if(!t)return null;const r={backgroundColor:(i=t.color,s=.5,i+Math.round(255*Math.min(Math.max(s,0),1)).toString(16).padStart(2,"0").toUpperCase())};var i,s;return(0,u.jsxs)(u.Fragment,{children:[n.map((e,t)=>(0,u.jsx)("div",{className:"pointer-events-none absolute",style:{...r,...e}},t)),e&&(0,u.jsx)(Ea,{data:t,caretPosition:e})]})}var ka=.7,Ca=1;function Ea({caretPosition:e,data:t}){const[n,r]=l.useState(!1),i={...e,background:t?.color,opacity:ka,transition:"opacity 0.2s"},s={...i,opacity:Ca},o={background:t?.color,opacity:ka,transform:"translateY(-100%)",transition:"opacity 0.2s"},a={...o,opacity:Ca};return(0,u.jsx)("div",{className:"absolute w-0.5",style:n?s:i,children:(0,u.jsx)("div",{className:"absolute top-0 whitespace-nowrap rounded rounded-bl-none px-1.5 py-0.5 text-white text-xs",style:n?a:o,onMouseEnter:()=>{r(!0)},onMouseLeave:()=>{r(!1)},children:t?.name})})}function Aa({documentId:e,initialValue:t=i.EMPTY_PLATE_VALUE,user:n,authToken:r,className:s,renderToolbar:o,overlays:a}){const c=ge("plate",e),d=n.color??be(n.id),h=Boolean(r),f=i.usePlateEditor({plugins:h?[...i.platePlugins,yo.configure({options:{cursors:{data:{color:d,name:n.name}},providers:ye({documentId:e,token:r})},render:{afterEditable:va}})]:i.platePlugins,skipInitialization:h,value:h?void 0:t},[c,h]);l.useEffect(()=>{if(h)return f.getApi(yo).yjs.init({id:c,value:t}),()=>{f.getApi(yo).yjs.destroy()}},[h,f,c]);const[,g]=l.useReducer(e=>e+1,0),p=l.useMemo(()=>f?He(f):b("plate"),[f]);return l.useEffect(()=>{g()},[f]),(0,u.jsx)("div",{className:`flex h-full min-h-0 w-full flex-col ${s??""}`,"data-room":c,children:(0,u.jsxs)(i.Plate,{editor:f,children:[o?o(p):(0,u.jsx)(x,{adapter:p}),(0,u.jsxs)(i.EditorContainer,{className:"relative min-h-0 flex-1",children:[(0,u.jsx)(i.Editor,{placeholder:"Start writing…",variant:"default"}),a]})]})})}exports.AIMenu=i.AIMenu,exports.AIToolbarButton=i.AIToolbarButton,exports.AiKit=i.AiKit,exports.AiPlugin=i.AiPlugin,exports.DEFAULT_PLATE_AI_OPTIONS=i.DEFAULT_PLATE_AI_OPTIONS,exports.EMPTY_PLATE_VALUE=i.EMPTY_PLATE_VALUE,exports.FixedToolbar=i.FixedToolbar,exports.FixedToolbarButtons=i.FixedToolbarButtons,exports.FloatingToolbar=i.FloatingToolbar,exports.FloatingToolbarButtons=i.FloatingToolbarButtons,exports.MediaKit=i.MediaKit,exports.REASON_TOOLBAR=v,exports.REASON_TOOLBAR_SKIN=i.REASON_TOOLBAR_SKIN,exports.ROOM_PREFIX=fe,exports.ReasonPlateEditor=Aa,exports.ReasonPlaygroundEditor=function(e){return(0,u.jsx)(Aa,{...e,overlays:(0,u.jsx)(i.FloatingToolbar,{children:(0,u.jsx)(i.FloatingToolbarButtons,{})}),renderToolbar:()=>(0,u.jsx)(i.FixedToolbar,{className:i.REASON_TOOLBAR_SKIN,children:(0,u.jsx)(i.FixedToolbarButtons,{})})})},exports.ReasonSidebar=function({activeDocumentId:e,linkForDocument:n,onNavigate:r,className:i}){const[s,o]=l.useState([]),[a,c]=l.useState(null),[d,h]=l.useState(""),g=l.useCallback(()=>{o(P())},[]);l.useEffect(()=>(g(),N(g)),[g]);const p=()=>{a&&M(a,d),c(null)};return(0,u.jsxs)("nav",{"aria-label":"Documents",className:t.cn("flex w-56 shrink-0 flex-col gap-0.5 overflow-y-auto border-r border-gray-200 bg-gray-50 p-2 dark:border-slate-700 dark:bg-slate-900",i),"data-testid":"reason-sidebar",children:[(0,u.jsxs)("div",{className:"flex items-center justify-between px-1 pb-2",children:[(0,u.jsx)("span",{className:"text-[11px] font-semibold uppercase tracking-wide text-gray-400",children:"Documents"}),(0,u.jsx)("button",{"aria-label":"New document",className:"rounded p-1 text-gray-500 hover:bg-gray-200 dark:text-gray-400 dark:hover:bg-slate-800",onClick:()=>{r(L().id)},type:"button",children:(0,u.jsx)(f.Plus,{className:"size-3.5"})})]}),s.map(i=>{const o=i.id===e,l=a===i.id;return(0,u.jsxs)("div",{className:t.cn("group flex items-center gap-1.5 rounded px-1.5 py-1 text-sm",o?"bg-gray-200 text-gray-900 dark:bg-slate-700 dark:text-white":"text-gray-600 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-slate-800"),"data-document-id":i.id,children:[(0,u.jsx)(f.FileText,{className:"size-3.5 shrink-0 opacity-60"}),l?(0,u.jsx)("input",{autoFocus:!0,className:"min-w-0 flex-1 rounded border border-gray-300 bg-white px-1 py-0.5 text-sm dark:border-slate-600 dark:bg-slate-800",onBlur:p,onChange:e=>h(e.target.value),onKeyDown:e=>{"Enter"===e.key&&p(),"Escape"===e.key&&c(null)},value:d}):(0,u.jsx)("a",{className:"min-w-0 flex-1 truncate",href:n(i.id),children:i.title}),!l&&(0,u.jsxs)("div",{className:"hidden shrink-0 items-center gap-0.5 group-hover:flex",children:[(0,u.jsx)("button",{"aria-label":`Rename ${i.title}`,className:"rounded p-0.5 text-gray-400 hover:bg-gray-200 dark:hover:bg-slate-700",onClick:()=>(e=>{c(e.id),h(e.title)})(i),type:"button",children:(0,u.jsx)(f.Pencil,{className:"size-3"})}),(0,u.jsx)("button",{"aria-label":`Delete ${i.title}`,className:"rounded p-0.5 text-gray-400 hover:bg-gray-200 dark:hover:bg-slate-700",onClick:()=>(t=>{if("undefined"!=typeof window&&!window.confirm(`Delete "${t.title}"?`))return;if(I(t.id),t.id!==e)return;const n=s.find(e=>e.id!==t.id);r(n?n.id:L().id)})(i),type:"button",children:(0,u.jsx)(f.Trash2,{className:"size-3"})})]})]},i.id)}),0===s.length&&(0,u.jsx)("p",{className:"px-1.5 py-2 text-xs text-gray-400",children:"No documents yet."})]})},exports.ReasonTiptapEditor=function({documentId:e,initialContent:t="",user:n,authToken:i,className:s}){const[o,c]=l.useState(null),[d,h]=l.useState(null),f=ge("tiptap",e),g=n.color??be(n.id);l.useEffect(()=>{if(!i)return;const t=me({engine:"tiptap",documentId:e,token:i});return h(t),()=>{h(null),t.destroy()}},[i,e]);const p=l.useMemo(()=>{const e=r.buildExtensions(r.createDefaultConfig());return d?function(e,t,n){return[...e.filter(e=>"undoRedo"!==e?.name),a.Collaboration.configure({document:t.ydoc}),De.configure({provider:t.provider,user:n})]}(e,d,{name:n.name,color:g}):e},[d,n.name,g]),m=l.useMemo(()=>o?Ee(o):b("tiptap"),[o]);return(0,u.jsx)("div",{className:`flex h-full min-h-0 w-full flex-col ${s??""}`,"data-room":f,children:(0,u.jsx)(r.NovelEditor,{className:"flex min-h-0 flex-1 flex-col",extensions:p,immediatelyRender:!1,initialContent:d?void 0:t,onEditor:c,rebuildKey:d?`collab:${f}`:"local",textDirection:"auto",children:({EditorSurface:e})=>(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)(x,{adapter:m}),(0,u.jsx)("div",{className:"relative min-h-0 flex-1 overflow-auto",children:(0,u.jsx)(e,{className:"h-full"})})]})})})},exports.ReasonToolbar=x,exports.SIDEBAR_DOCUMENTS_STORAGE_KEY=T,exports.collaborationRoom=ge,exports.collectToolbarCommands=function e(t=v){const n=[];for(const r of t)"button"===r.kind&&n.push(r.id),"menu"===r.kind&&n.push(...e(r.children));return n},exports.createAiKit=i.createAiKit,exports.createCollaborationSession=me,exports.createNullAdapter=b,exports.createPlateAdapter=He,exports.createSidebarDocument=L,exports.createTiptapAdapter=Ee,exports.cursorColorFor=be,exports.deleteSidebarDocument=I,exports.getPlateAiController=i.getPlateAiController,exports.hocuspocusUrl=pe,exports.htmlToPlateValue=i.htmlToPlateValue,exports.listSidebarDocuments=P,exports.parseCollaborationRoom=function(e){const[t,n,...r]=e.split(":"),i=r.join(":");return"reason-editor"!==t||"tiptap"!==n&&"plate"!==n?null:i?{engine:n,documentId:i}:null},exports.plateBasePlugins=i.plateBasePlugins,exports.platePlugins=i.platePlugins,exports.plateValueToHtml=i.plateValueToHtml,exports.plateYjsProviders=ye,exports.renameSidebarDocument=M,exports.subscribeSidebarDocuments=N;