@inkeep/open-knowledge 0.0.0-dev-20260427163338 → 0.0.0-dev-20260427194153
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/skills/open-knowledge/SKILL.md +25 -15
- package/dist/cli.mjs +6 -6
- package/dist/constants-CXtb6S9e.mjs +2 -0
- package/dist/{dist-C410Bipn.mjs → dist-B8mg-f6q.mjs} +1 -1
- package/dist/{dist-e1ryjJJb.mjs → dist-mmLEboji.mjs} +16 -4
- package/dist/index.mjs +1 -1
- package/dist/init-BCnlpWMq.mjs +1 -0
- package/dist/{init-BH4lmTY2.mjs → init-Bc8AaeuH.mjs} +3 -3
- package/dist/{init-C-DJ6Bcb.mjs → init-Dn8zvSe9.mjs} +1 -1
- package/dist/{init-CV-fiK86.mjs → init-aygOL5mI.mjs} +2 -2
- package/dist/{loader-BM3mbEZf.mjs → loader-CkLCJZ_a.mjs} +2 -2
- package/dist/loader-VgnU35KK.mjs +1 -0
- package/dist/paths-L4UjjxH7.mjs +1 -0
- package/dist/{paths-pxE-5qU3.mjs → paths-uWxFvwPB.mjs} +2 -2
- package/dist/preview-BRKICSmX.mjs +1 -0
- package/dist/{preview-DRhAyj_V.mjs → preview-DMPV6CsE.mjs} +2 -2
- package/dist/public/assets/ActivityModeContent-7CjHJQA-.js +2 -0
- package/dist/public/assets/{ActivityPanelDiffView-DVyTW-J7.js → ActivityPanelDiffView-D-EUyEh6.js} +1 -1
- package/dist/public/assets/{DocumentContext-D125gYAt.js → DocumentContext-yJTVxTi8.js} +2 -2
- package/dist/public/assets/McpConsentDialogBody-rv8E7452.js +1 -0
- package/dist/public/assets/{SourceEditor-M-p0lLYp.js → SourceEditor-g0En9fI8.js} +1 -1
- package/dist/public/assets/agent-presence-DBKMYj1x.js +1 -0
- package/dist/public/assets/{clipboard-BmiNdq3p.js → clipboard-tp9ju8rD.js} +1 -1
- package/dist/public/assets/dialog-DeibR6sn.js +45 -0
- package/dist/public/assets/index-DsWkmB5S.css +1 -0
- package/dist/public/assets/index-e-6eeSOy.js +1843 -0
- package/dist/public/index.html +6 -6
- package/dist/src-B0_BgXoG.mjs +1 -0
- package/dist/{start-BBTXc3GL.mjs → start-BrAnBRSa.mjs} +2 -2
- package/dist/start-CZ3afhmt.mjs +1 -0
- package/package.json +1 -1
- package/dist/constants-BXmH5dNC.mjs +0 -2
- package/dist/init-BX_jwB_V.mjs +0 -1
- package/dist/loader-v0m1NTka.mjs +0 -1
- package/dist/paths-CYEVSOoI.mjs +0 -1
- package/dist/preview-qf6rsBxN.mjs +0 -1
- package/dist/public/assets/ActivityModeContent-Bh4C07uL.js +0 -2
- package/dist/public/assets/McpConsentDialogBody-QKrs5-z6.js +0 -1
- package/dist/public/assets/agent-presence-BQu9C0ej.js +0 -1
- package/dist/public/assets/dialog-xzAlDsHy.js +0 -45
- package/dist/public/assets/index-DLXD_AE1.js +0 -1838
- package/dist/public/assets/index-DPJk5E6v.css +0 -1
- package/dist/src-CIwfojI2.mjs +0 -1
- package/dist/start-CosrPkb0.mjs +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{r as e,t}from"./chunk-DECur_0Z.js";import{n,t as r}from"./propagation-api-Bugyj7xy.js";import{n as i,r as a,t as o}from"./compiler-runtime-Y11fyRVL.js";import{S as s,n as c,t as l,x as u}from"./button-B1XQHQcX.js";import{C as d,a as f,d as p,f as m,i as h,l as g,m as _,o as v,p as y,r as b,s as x,t as S,u as C,w}from"./dialog-xzAlDsHy.js";import{$ as T,At as E,B as D,C as O,Ct as k,Dt as A,E as ee,Et as j,H as M,Ht as N,It as P,K as F,Lt as I,Mt as L,N as R,Nt as z,Ot as B,P as V,Pt as H,Rt as U,T as W,Tt as G,Ut as K,Vt as q,X as te,Yt as ne,Z as re,_t as ie,a as ae,at as oe,b as se,bt as ce,c as le,ct as ue,d as de,dt as fe,et as pe,f as me,ft as he,gt as ge,h as _e,ht as ve,j as ye,jt as be,kt as xe,lt as Se,m as Ce,mt as we,n as Te,nt as Ee,o as De,ot as Oe,p as ke,pt as Ae,qt as je,r as Me,tt as Ne,w as Pe,x as Fe,xt as Ie,y as Le}from"./PageListContext-BeAv6YTY.js";var Re=u(`circle-alert`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`line`,{x1:`12`,x2:`12`,y1:`8`,y2:`12`,key:`1pkeuh`}],[`line`,{x1:`12`,x2:`12.01`,y1:`16`,y2:`16`,key:`4dfq90`}]]),ze=u(`code-xml`,[[`path`,{d:`m18 16 4-4-4-4`,key:`1inbqp`}],[`path`,{d:`m6 8-4 4 4 4`,key:`15zrgr`}],[`path`,{d:`m14.5 4-5 16`,key:`e7oirm`}]]),Be=u(`external-link`,[[`path`,{d:`M15 3h6v6`,key:`1q9fwt`}],[`path`,{d:`M10 14 21 3`,key:`gplh6r`}],[`path`,{d:`M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6`,key:`a6xqqp`}]]),Ve=u(`file-plus-corner`,[[`path`,{d:`M11.35 22H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.706.706l3.588 3.588A2.4 2.4 0 0 1 20 8v5.35`,key:`17jvcc`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M14 19h6`,key:`bvotb8`}],[`path`,{d:`M17 16v6`,key:`18yu1i`}]]),He=u(`file`,[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`,key:`1oefj6`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}]]),Ue=u(`folder-open`,[[`path`,{d:`m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2`,key:`usdka0`}]]),We=u(`heading-1`,[[`path`,{d:`M4 12h8`,key:`17cfdx`}],[`path`,{d:`M4 18V6`,key:`1rz3zl`}],[`path`,{d:`M12 18V6`,key:`zqpxq5`}],[`path`,{d:`m17 12 3-2v8`,key:`1hhhft`}]]),Ge=u(`heading-2`,[[`path`,{d:`M4 12h8`,key:`17cfdx`}],[`path`,{d:`M4 18V6`,key:`1rz3zl`}],[`path`,{d:`M12 18V6`,key:`zqpxq5`}],[`path`,{d:`M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1`,key:`9jr5yi`}]]),Ke=u(`heading-3`,[[`path`,{d:`M4 12h8`,key:`17cfdx`}],[`path`,{d:`M4 18V6`,key:`1rz3zl`}],[`path`,{d:`M12 18V6`,key:`zqpxq5`}],[`path`,{d:`M17.5 10.5c1.7-1 3.5 0 3.5 1.5a2 2 0 0 1-2 2`,key:`68ncm8`}],[`path`,{d:`M17 17.5c2 1.5 4 .3 4-1.5a2 2 0 0 0-2-2`,key:`1ejuhz`}]]),qe=u(`image`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,ry:`2`,key:`1m3agn`}],[`circle`,{cx:`9`,cy:`9`,r:`2`,key:`af1f0g`}],[`path`,{d:`m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21`,key:`1xmnt7`}]]),Je=u(`list-ordered`,[[`path`,{d:`M11 5h10`,key:`1cz7ny`}],[`path`,{d:`M11 12h10`,key:`1438ji`}],[`path`,{d:`M11 19h10`,key:`11t30w`}],[`path`,{d:`M4 4h1v5`,key:`10yrso`}],[`path`,{d:`M4 9h2`,key:`r1h2o0`}],[`path`,{d:`M6.5 20H3.4c0-1 2.6-1.925 2.6-3.5a1.5 1.5 0 0 0-2.6-1.02`,key:`xtkcd5`}]]),Ye=u(`list-todo`,[[`path`,{d:`M13 5h8`,key:`a7qcls`}],[`path`,{d:`M13 12h8`,key:`h98zly`}],[`path`,{d:`M13 19h8`,key:`c3s6r1`}],[`path`,{d:`m3 17 2 2 4-4`,key:`1jhpwq`}],[`rect`,{x:`3`,y:`4`,width:`6`,height:`6`,rx:`1`,key:`cif1o7`}]]),Xe=u(`list`,[[`path`,{d:`M3 5h.01`,key:`18ugdj`}],[`path`,{d:`M3 12h.01`,key:`nlz23k`}],[`path`,{d:`M3 19h.01`,key:`noohij`}],[`path`,{d:`M8 5h13`,key:`1pao27`}],[`path`,{d:`M8 12h13`,key:`1za7za`}],[`path`,{d:`M8 19h13`,key:`m83p4d`}]]),Ze=u(`loader-circle`,[[`path`,{d:`M21 12a9 9 0 1 1-6.219-8.56`,key:`13zald`}]]),Qe=u(`minus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}]]),$e=u(`pencil`,[[`path`,{d:`M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z`,key:`1a8usu`}],[`path`,{d:`m15 5 4 4`,key:`1mk7zo`}]]),et=u(`quote`,[[`path`,{d:`M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z`,key:`rib7q0`}],[`path`,{d:`M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z`,key:`1ymkrd`}]]),tt=u(`table-2`,[[`path`,{d:`M9 3H5a2 2 0 0 0-2 2v4m6-6h10a2 2 0 0 1 2 2v4M9 3v18m0 0h10a2 2 0 0 0 2-2V9M9 21H5a2 2 0 0 1-2-2V9m0 0h18`,key:`gugj83`}]]),nt=u(`trash-2`,[[`path`,{d:`M10 11v6`,key:`nco0om`}],[`path`,{d:`M14 11v6`,key:`outv1u`}],[`path`,{d:`M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6`,key:`miytrc`}],[`path`,{d:`M3 6h18`,key:`d0wm0j`}],[`path`,{d:`M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2`,key:`e791ji`}]]),rt=t((e=>{var t=i();function n(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var r=typeof Object.is==`function`?Object.is:n,a=t.useState,o=t.useEffect,s=t.useLayoutEffect,c=t.useDebugValue;function l(e,t){var n=t(),r=a({inst:{value:n,getSnapshot:t}}),i=r[0].inst,l=r[1];return s(function(){i.value=n,i.getSnapshot=t,u(i)&&l({inst:i})},[e,n,t]),o(function(){return u(i)&&l({inst:i}),e(function(){u(i)&&l({inst:i})})},[e]),c(n),n}function u(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!r(e,n)}catch{return!0}}function d(e,t){return t()}var f=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?d:l;e.useSyncExternalStore=t.useSyncExternalStore===void 0?f:t.useSyncExternalStore})),it=t(((e,t)=>{t.exports=rt()})),J=e(i(),1),at=o();function ot(e){let t=e.split(`/`);return t.length<2?`ok`:`${t[0]}/${t[1]}`}function st(e){if(!e)return;let t=Object.entries(e);if(t.length!==0)return t.map(([e,t])=>{if(t==null)return[e,String(t)];if(typeof t==`string`)return[e,t];if(typeof t==`number`||typeof t==`boolean`)return[e,String(t)];try{return[e,JSON.stringify(t)]}catch{return[e,`[unserializable]`]}})}function Y(e,t,n){if(typeof performance>`u`||!performance.measure)return;let r=ot(e),i=st(t),a={devtools:{dataType:`track-entry`,track:r,...i?{properties:i}:{},...n?.tooltipText?{tooltipText:n.tooltipText}:{}}},o=performance.now(),s=n?.startTime??o,c=n?.duration??Math.max(0,o-s);try{performance.measure(e,{start:s,duration:c,detail:a})}catch{}({...t?{properties:t}:{}})}var X=a();function ct(e){let t=(0,at.c)(3),{name:n,children:r}=e,i;return t[0]!==r||t[1]!==n?(i=(0,X.jsx)(J.Profiler,{id:n,onRender:lt,children:r}),t[0]=r,t[1]=n,t[2]=i):i=t[2],i}var lt=(e,t,n,r,i,a)=>{Y(`ok/render/${e}`,{phase:t,actualDuration:Math.round(n*1e3)/1e3,baseDuration:Math.round(r*1e3)/1e3},{startTime:i,duration:Math.max(0,a-i)})},ut=e(s(),1),dt=it(),{getOwnPropertyNames:ft,getOwnPropertySymbols:pt}=Object,{hasOwnProperty:mt}=Object.prototype;function ht(e,t){return function(n,r,i){return e(n,r,i)&&t(n,r,i)}}function gt(e){return function(t,n,r){if(!t||!n||typeof t!=`object`||typeof n!=`object`)return e(t,n,r);let{cache:i}=r,a=i.get(t),o=i.get(n);if(a&&o)return a===n&&o===t;i.set(t,n),i.set(n,t);let s=e(t,n,r);return i.delete(t),i.delete(n),s}}function _t(e){return e?.[Symbol.toStringTag]}function vt(e){return ft(e).concat(pt(e))}var yt=Object.hasOwn||((e,t)=>mt.call(e,t));function bt(e,t){return e===t||!e&&!t&&e!==e&&t!==t}var xt=`__v`,St=`__o`,Ct=`_owner`,{getOwnPropertyDescriptor:wt,keys:Tt}=Object;function Et(e,t){return e.byteLength===t.byteLength&&zt(new Uint8Array(e),new Uint8Array(t))}function Dt(e,t,n){let r=e.length;if(t.length!==r)return!1;for(;r-- >0;)if(!n.equals(e[r],t[r],r,r,e,t,n))return!1;return!0}function Ot(e,t){return e.byteLength===t.byteLength&&zt(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}function kt(e,t){return bt(e.getTime(),t.getTime())}function At(e,t){return e.name===t.name&&e.message===t.message&&e.cause===t.cause&&e.stack===t.stack}function jt(e,t){return e===t}function Mt(e,t,n){let r=e.size;if(r!==t.size)return!1;if(!r)return!0;let i=Array(r),a=e.entries(),o,s,c=0;for(;(o=a.next())&&!o.done;){let r=t.entries(),a=!1,l=0;for(;(s=r.next())&&!s.done;){if(i[l]){l++;continue}let r=o.value,u=s.value;if(n.equals(r[0],u[0],c,l,e,t,n)&&n.equals(r[1],u[1],r[0],u[0],e,t,n)){a=i[l]=!0;break}l++}if(!a)return!1;c++}return!0}var Nt=bt;function Pt(e,t,n){let r=Tt(e),i=r.length;if(Tt(t).length!==i)return!1;for(;i-- >0;)if(!Vt(e,t,n,r[i]))return!1;return!0}function Ft(e,t,n){let r=vt(e),i=r.length;if(vt(t).length!==i)return!1;let a,o,s;for(;i-- >0;)if(a=r[i],!Vt(e,t,n,a)||(o=wt(e,a),s=wt(t,a),(o||s)&&(!o||!s||o.configurable!==s.configurable||o.enumerable!==s.enumerable||o.writable!==s.writable)))return!1;return!0}function It(e,t){return bt(e.valueOf(),t.valueOf())}function Lt(e,t){return e.source===t.source&&e.flags===t.flags}function Rt(e,t,n){let r=e.size;if(r!==t.size)return!1;if(!r)return!0;let i=Array(r),a=e.values(),o,s;for(;(o=a.next())&&!o.done;){let r=t.values(),a=!1,c=0;for(;(s=r.next())&&!s.done;){if(!i[c]&&n.equals(o.value,s.value,o.value,s.value,e,t,n)){a=i[c]=!0;break}c++}if(!a)return!1}return!0}function zt(e,t){let n=e.byteLength;if(t.byteLength!==n||e.byteOffset!==t.byteOffset)return!1;for(;n-- >0;)if(e[n]!==t[n])return!1;return!0}function Bt(e,t){return e.hostname===t.hostname&&e.pathname===t.pathname&&e.protocol===t.protocol&&e.port===t.port&&e.hash===t.hash&&e.username===t.username&&e.password===t.password}function Vt(e,t,n,r){return(r===Ct||r===St||r===xt)&&(e.$$typeof||t.$$typeof)?!0:yt(t,r)&&n.equals(e[r],t[r],r,r,e,t,n)}var Ht=`[object ArrayBuffer]`,Ut=`[object Arguments]`,Wt=`[object Boolean]`,Gt=`[object DataView]`,Kt=`[object Date]`,qt=`[object Error]`,Jt=`[object Map]`,Yt=`[object Number]`,Xt=`[object Object]`,Zt=`[object RegExp]`,Qt=`[object Set]`,$t=`[object String]`,en={"[object Int8Array]":!0,"[object Uint8Array]":!0,"[object Uint8ClampedArray]":!0,"[object Int16Array]":!0,"[object Uint16Array]":!0,"[object Int32Array]":!0,"[object Uint32Array]":!0,"[object Float16Array]":!0,"[object Float32Array]":!0,"[object Float64Array]":!0,"[object BigInt64Array]":!0,"[object BigUint64Array]":!0},tn=`[object URL]`,nn=Object.prototype.toString;function rn({areArrayBuffersEqual:e,areArraysEqual:t,areDataViewsEqual:n,areDatesEqual:r,areErrorsEqual:i,areFunctionsEqual:a,areMapsEqual:o,areNumbersEqual:s,areObjectsEqual:c,arePrimitiveWrappersEqual:l,areRegExpsEqual:u,areSetsEqual:d,areTypedArraysEqual:f,areUrlsEqual:p,unknownTagComparators:m}){return function(h,g,_){if(h===g)return!0;if(h==null||g==null)return!1;let v=typeof h;if(v!==typeof g)return!1;if(v!==`object`)return v===`number`?s(h,g,_):v===`function`?a(h,g,_):!1;let y=h.constructor;if(y!==g.constructor)return!1;if(y===Object)return c(h,g,_);if(Array.isArray(h))return t(h,g,_);if(y===Date)return r(h,g,_);if(y===RegExp)return u(h,g,_);if(y===Map)return o(h,g,_);if(y===Set)return d(h,g,_);let b=nn.call(h);if(b===Kt)return r(h,g,_);if(b===Zt)return u(h,g,_);if(b===Jt)return o(h,g,_);if(b===Qt)return d(h,g,_);if(b===Xt)return typeof h.then!=`function`&&typeof g.then!=`function`&&c(h,g,_);if(b===tn)return p(h,g,_);if(b===qt)return i(h,g,_);if(b===Ut)return c(h,g,_);if(en[b])return f(h,g,_);if(b===Ht)return e(h,g,_);if(b===Gt)return n(h,g,_);if(b===Wt||b===Yt||b===$t)return l(h,g,_);if(m){let e=m[b];if(!e){let t=_t(h);t&&(e=m[t])}if(e)return e(h,g,_)}return!1}}function an({circular:e,createCustomConfig:t,strict:n}){let r={areArrayBuffersEqual:Et,areArraysEqual:n?Ft:Dt,areDataViewsEqual:Ot,areDatesEqual:kt,areErrorsEqual:At,areFunctionsEqual:jt,areMapsEqual:n?ht(Mt,Ft):Mt,areNumbersEqual:Nt,areObjectsEqual:n?Ft:Pt,arePrimitiveWrappersEqual:It,areRegExpsEqual:Lt,areSetsEqual:n?ht(Rt,Ft):Rt,areTypedArraysEqual:n?ht(zt,Ft):zt,areUrlsEqual:Bt,unknownTagComparators:void 0};if(t&&(r=Object.assign({},r,t(r))),e){let e=gt(r.areArraysEqual),t=gt(r.areMapsEqual),n=gt(r.areObjectsEqual),i=gt(r.areSetsEqual);r=Object.assign({},r,{areArraysEqual:e,areMapsEqual:t,areObjectsEqual:n,areSetsEqual:i})}return r}function on(e){return function(t,n,r,i,a,o,s){return e(t,n,s)}}function sn({circular:e,comparator:t,createState:n,equals:r,strict:i}){if(n)return function(a,o){let{cache:s=e?new WeakMap:void 0,meta:c}=n();return t(a,o,{cache:s,equals:r,meta:c,strict:i})};if(e)return function(e,n){return t(e,n,{cache:new WeakMap,equals:r,meta:void 0,strict:i})};let a={cache:void 0,equals:r,meta:void 0,strict:i};return function(e,n){return t(e,n,a)}}var cn=ln();ln({strict:!0}),ln({circular:!0}),ln({circular:!0,strict:!0}),ln({createInternalComparator:()=>bt}),ln({strict:!0,createInternalComparator:()=>bt}),ln({circular:!0,createInternalComparator:()=>bt}),ln({circular:!0,createInternalComparator:()=>bt,strict:!0});function ln(e={}){let{circular:t=!1,createInternalComparator:n,createState:r,strict:i=!1}=e,a=rn(an(e));return sn({circular:t,comparator:a,createState:r,equals:n?n(a):on(a),strict:i})}var un=t((e=>{var t=i(),n=it();function r(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var a=typeof Object.is==`function`?Object.is:r,o=n.useSyncExternalStore,s=t.useRef,c=t.useEffect,l=t.useMemo,u=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(e,t,n,r,i){var d=s(null);if(d.current===null){var f={hasValue:!1,value:null};d.current=f}else f=d.current;d=l(function(){function e(e){if(!o){if(o=!0,s=e,e=r(e),i!==void 0&&f.hasValue){var t=f.value;if(i(t,e))return c=t}return c=e}if(t=c,a(s,e))return t;var n=r(e);return i!==void 0&&i(t,n)?(s=e,t):(s=e,c=n)}var o=!1,s,c,l=n===void 0?null:n;return[function(){return e(t())},l===null?void 0:function(){return e(l())}]},[t,n,r,i]);var p=o(e,d[0],d[1]);return c(function(){f.hasValue=!0,f.value=p},[p]),u(p),p}})),dn=t(((e,t)=>{t.exports=un()}))(),fn=(...e)=>t=>{e.forEach(e=>{typeof e==`function`?e(t):e&&(e.current=t)})},pn=({contentComponent:e})=>{let t=(0,dt.useSyncExternalStore)(e.subscribe,e.getSnapshot,e.getServerSnapshot);return(0,X.jsx)(X.Fragment,{children:Object.values(t)})};function mn(){let e=new Set,t={};return{subscribe(t){return e.add(t),()=>{e.delete(t)}},getSnapshot(){return t},getServerSnapshot(){return t},setRenderer(n,r){t={...t,[n]:ut.createPortal(r.reactElement,r.element,n)},e.forEach(e=>e())},removeRenderer(n){let r={...t};delete r[n],t=r,e.forEach(e=>e())}}}var hn=class extends J.Component{constructor(e){super(e),this.editorContentRef=J.createRef()}componentDidMount(){this.init()}componentDidUpdate(){this.init()}init(){let e=this.props.editor;if(e&&!e.isDestroyed&&e.view.dom?.parentNode){if(e.contentComponent)return;let t=this.editorContentRef.current;t.append(...e.view.dom.parentNode.childNodes),e.setOptions({element:t}),e.contentComponent=mn(),e.createNodeViews(),e.isEditorContentInitialized=!0,this.forceUpdate()}}componentWillUnmount(){let e=this.props.editor;if(e){e.isEditorContentInitialized=!1,e.isDestroyed||e.view.setProps({nodeViews:{}}),e.contentComponent=null;try{if(!e.view.dom?.parentNode)return;let t=document.createElement(`div`);t.append(...e.view.dom.parentNode.childNodes),e.setOptions({element:t})}catch{}}}render(){let{editor:e,innerRef:t,...n}=this.props;return(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`div`,{ref:fn(t,this.editorContentRef),...n}),e?.contentComponent&&(0,X.jsx)(pn,{contentComponent:e.contentComponent})]})}},gn=(0,J.forwardRef)((e,t)=>{let n=J.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[e.editor]);return J.createElement(hn,{key:n,innerRef:t,...e})}),_n=J.memo(gn),vn=typeof window<`u`?J.useLayoutEffect:J.useEffect,yn=class{constructor(e){this.transactionNumber=0,this.lastTransactionNumber=0,this.subscribers=new Set,this.editor=e,this.lastSnapshot={editor:e,transactionNumber:0},this.getSnapshot=this.getSnapshot.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.watch=this.watch.bind(this),this.subscribe=this.subscribe.bind(this)}getSnapshot(){return this.transactionNumber===this.lastTransactionNumber?this.lastSnapshot:(this.lastTransactionNumber=this.transactionNumber,this.lastSnapshot={editor:this.editor,transactionNumber:this.transactionNumber},this.lastSnapshot)}getServerSnapshot(){return{editor:null,transactionNumber:0}}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}watch(e){if(this.editor=e,this.editor){let e=()=>{this.transactionNumber+=1,this.subscribers.forEach(e=>e())},t=this.editor;return t.on(`transaction`,e),()=>{t.off(`transaction`,e)}}}};function bn(e){let[t]=(0,J.useState)(()=>new yn(e.editor)),n=(0,dn.useSyncExternalStoreWithSelector)(t.subscribe,t.getSnapshot,t.getServerSnapshot,e.selector,e.equalityFn??cn);return vn(()=>t.watch(e.editor),[e.editor,t]),(0,J.useDebugValue)(n),n}typeof window>`u`||typeof window<`u`&&window.next;var xn=(0,J.createContext)({editor:null});xn.Consumer;var Sn=()=>(0,J.useContext)(xn),Cn=(0,J.createContext)({onDragStart:()=>{},nodeViewContentChildren:void 0,nodeViewContentRef:()=>{}}),wn=()=>(0,J.useContext)(Cn),Tn=J.forwardRef((e,t)=>{let{onDragStart:n}=wn();return(0,X.jsx)(e.as||`div`,{...e,ref:t,"data-node-view-wrapper":``,onDragStart:n,style:{whiteSpace:`normal`,...e.style}})});function En(e){return!!(typeof e==`function`&&e.prototype&&e.prototype.isReactComponent)}function Dn(e){return!!(typeof e==`object`&&e.$$typeof&&(e.$$typeof.toString()===`Symbol(react.forward_ref)`||e.$$typeof.description===`react.forward_ref`))}function On(e){return!!(typeof e==`object`&&e.$$typeof&&(e.$$typeof.toString()===`Symbol(react.memo)`||e.$$typeof.description===`react.memo`))}function kn(e){if(En(e)||Dn(e))return!0;if(On(e)){let t=e.type;if(t)return En(t)||Dn(t)}return!1}function An(){try{if(J.version)return parseInt(J.version.split(`.`)[0],10)>=19}catch{}return!1}var jn=class{constructor(e,{editor:t,props:n={},as:r=`div`,className:i=``}){this.ref=null,this.destroyed=!1,this.id=Math.floor(Math.random()*4294967295).toString(),this.component=e,this.editor=t,this.props=n,this.element=document.createElement(r),this.element.classList.add(`react-renderer`),i&&this.element.classList.add(...i.split(` `)),this.editor.isEditorContentInitialized?(0,ut.flushSync)(()=>{this.render()}):queueMicrotask(()=>{this.destroyed||this.render()})}render(){var e;if(this.destroyed)return;let t=this.component,n=this.props,r=this.editor,i=An(),a=kn(t),o={...n};o.ref&&!(i||a)&&delete o.ref,!o.ref&&(i||a)&&(o.ref=e=>{this.ref=e}),this.reactElement=(0,X.jsx)(t,{...o}),(e=r?.contentComponent)==null||e.setRenderer(this.id,this)}updateProps(e={}){this.destroyed||(this.props={...this.props,...e},this.render())}destroy(){var e;this.destroyed=!0,(e=this.editor?.contentComponent)==null||e.removeRenderer(this.id);try{this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element)}catch{}}updateAttributes(e){Object.keys(e).forEach(t=>{this.element.setAttribute(t,e[t])})}};J.createContext({markViewContentRef:()=>{}});var Mn=class extends Ae{constructor(e,t,n){if(super(e,t,n),this.selectionRafId=null,this.positionCheckCallback=null,this.cachedExtensionWithSyncedStorage=null,!this.node.isLeaf){this.options.contentDOMElementTag?this.contentDOMElement=document.createElement(this.options.contentDOMElementTag):this.contentDOMElement=document.createElement(this.node.isInline?`span`:`div`),this.contentDOMElement.dataset.nodeViewContentReact=``,this.contentDOMElement.dataset.nodeViewWrapper=``,this.contentDOMElement.style.whiteSpace=`inherit`;let e=this.dom.querySelector(`[data-node-view-content]`);if(!e)return;e.appendChild(this.contentDOMElement)}}get extensionWithSyncedStorage(){if(!this.cachedExtensionWithSyncedStorage){let e=this.editor,t=this.extension;this.cachedExtensionWithSyncedStorage=new Proxy(t,{get(n,r,i){return r===`storage`?e.storage[t.name]??{}:Reflect.get(n,r,i)}})}return this.cachedExtensionWithSyncedStorage}mount(){let e={editor:this.editor,node:this.node,decorations:this.decorations,innerDecorations:this.innerDecorations,view:this.view,selected:!1,extension:this.extensionWithSyncedStorage,HTMLAttributes:this.HTMLAttributes,getPos:()=>this.getPos(),updateAttributes:(e={})=>this.updateAttributes(e),deleteNode:()=>this.deleteNode(),ref:(0,J.createRef)()};if(!this.component.displayName){let e=e=>e.charAt(0).toUpperCase()+e.substring(1);this.component.displayName=e(this.extension.name)}let t={onDragStart:this.onDragStart.bind(this),nodeViewContentRef:e=>{e&&this.contentDOMElement&&e.firstChild!==this.contentDOMElement&&(e.hasAttribute(`data-node-view-wrapper`)&&e.removeAttribute(`data-node-view-wrapper`),e.appendChild(this.contentDOMElement))}},n=this.component,r=(0,J.memo)(e=>(0,X.jsx)(Cn.Provider,{value:t,children:(0,J.createElement)(n,e)}));r.displayName=`ReactNodeView`;let i=this.node.isInline?`span`:`div`;this.options.as&&(i=this.options.as);let{className:a=``}=this.options;this.handleSelectionUpdate=this.handleSelectionUpdate.bind(this),this.renderer=new jn(r,{editor:this.editor,props:e,as:i,className:`node-${this.node.type.name} ${a}`.trim()}),this.editor.on(`selectionUpdate`,this.handleSelectionUpdate),this.updateElementAttributes(),this.currentPos=this.getPos(),this.positionCheckCallback=()=>{let e=this.getPos();typeof e!=`number`||e===this.currentPos||(this.currentPos=e,this.renderer.updateProps({getPos:()=>this.getPos()}),typeof this.options.attrs==`function`&&this.updateElementAttributes())},G(this.editor,this.positionCheckCallback)}get dom(){if(this.renderer.element.firstElementChild&&!this.renderer.element.firstElementChild?.hasAttribute(`data-node-view-wrapper`))throw Error(`Please use the NodeViewWrapper component for your node view.`);return this.renderer.element}get contentDOM(){return this.node.isLeaf?null:this.contentDOMElement}handleSelectionUpdate(){this.selectionRafId&&=(cancelAnimationFrame(this.selectionRafId),null),this.selectionRafId=requestAnimationFrame(()=>{this.selectionRafId=null;let{from:e,to:t}=this.editor.state.selection,n=this.currentPos;if(typeof n==`number`)if(e<=n&&t>=n+this.node.nodeSize){if(this.renderer.props.selected)return;this.selectNode()}else{if(!this.renderer.props.selected)return;this.deselectNode()}})}update(e,t,n){let r=e=>{this.renderer.updateProps(e),typeof this.options.attrs==`function`&&this.updateElementAttributes()};if(e.type!==this.node.type)return!1;if(typeof this.options.update==`function`){let i=this.node,a=this.decorations,o=this.innerDecorations;return this.node=e,this.decorations=t,this.innerDecorations=n,this.currentPos=this.getPos(),this.options.update({oldNode:i,oldDecorations:a,newNode:e,newDecorations:t,oldInnerDecorations:o,innerDecorations:n,updateProps:()=>r({node:e,decorations:t,innerDecorations:n,extension:this.extensionWithSyncedStorage})})}let i=this.getPos();return e===this.node&&this.decorations===t&&this.innerDecorations===n?i===this.currentPos?!0:(this.currentPos=i,r({node:e,decorations:t,innerDecorations:n,extension:this.extensionWithSyncedStorage,getPos:()=>this.getPos()}),!0):(this.node=e,this.decorations=t,this.innerDecorations=n,this.currentPos=i,r({node:e,decorations:t,innerDecorations:n,extension:this.extensionWithSyncedStorage}),!0)}selectNode(){this.renderer.updateProps({selected:!0}),this.renderer.element.classList.add(`ProseMirror-selectednode`)}deselectNode(){this.renderer.updateProps({selected:!1}),this.renderer.element.classList.remove(`ProseMirror-selectednode`)}destroy(){this.renderer.destroy(),this.editor.off(`selectionUpdate`,this.handleSelectionUpdate),this.positionCheckCallback&&=(we(this.editor,this.positionCheckCallback),null),this.contentDOMElement=null,this.selectionRafId&&=(cancelAnimationFrame(this.selectionRafId),null)}updateElementAttributes(){if(this.options.attrs){let e={};if(typeof this.options.attrs==`function`){let t=this.editor.extensionManager.attributes,n=ge(this.node,t);e=this.options.attrs({node:this.node,HTMLAttributes:n})}else e=this.options.attrs;this.renderer.updateAttributes(e)}}};function Nn(e,t){return n=>n.editor.contentComponent?new Mn(e,n,t):{}}var Pn=(0,J.createContext)({get editor(){throw Error(`useTiptap must be used within a <Tiptap> provider`)}});Pn.displayName=`TiptapContext`;var Fn=()=>(0,J.useContext)(Pn);function In({editor:e,instance:t,children:n}){let r=e??t;if(!r)throw Error("Tiptap: An editor instance is required. Pass a non-null `editor` prop.");let i=(0,J.useMemo)(()=>({editor:r}),[r]),a=(0,J.useMemo)(()=>({editor:r}),[r]);return(0,X.jsx)(xn.Provider,{value:a,children:(0,X.jsx)(Pn.Provider,{value:i,children:n})})}In.displayName=`Tiptap`;function Ln({...e}){let{editor:t}=Fn();return(0,X.jsx)(_n,{editor:t,...e})}Ln.displayName=`Tiptap.Content`,Object.assign(In,{Content:Ln});var Rn=()=>new Map,zn=e=>{let t=Rn();return e.forEach((e,n)=>{t.set(n,e)}),t},Bn=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r},Vn=(e,t)=>{let n=[];for(let[r,i]of e)n.push(t(i,r));return n},Hn=(e,t)=>{for(let[n,r]of e)if(t(r,n))return!0;return!1},Un=()=>new Set,Wn=e=>e[e.length-1],Gn=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},Kn=Array.from,qn=(e,t)=>{for(let n=0;n<e.length;n++)if(!t(e[n],n,e))return!1;return!0},Jn=(e,t)=>{for(let n=0;n<e.length;n++)if(t(e[n],n,e))return!0;return!1},Yn=(e,t)=>{let n=Array(e);for(let r=0;r<e;r++)n[r]=t(r,n);return n},Xn=Array.isArray,Zn=class{constructor(){this._observers=Rn()}on(e,t){return Bn(this._observers,e,Un).add(t),t}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){let n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return Kn((this._observers.get(e)||Rn()).values()).forEach(e=>e(...t))}destroy(){this._observers=Rn()}},Qn=class{constructor(){this._observers=Rn()}on(e,t){Bn(this._observers,e,Un).add(t)}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){let n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return Kn((this._observers.get(e)||Rn()).values()).forEach(e=>e(...t))}destroy(){this._observers=Rn()}},$n=Math.floor,er=Math.abs,tr=(e,t)=>e<t?e:t,nr=(e,t)=>e>t?e:t;Number.isNaN;var rr=e=>e===0?1/e<0:e<0,ir=1<<17,ar=1<<18,or=1<<19,sr=1<<20,cr=1<<21,lr=1<<22,ur=1<<23,dr=1<<24,fr=1<<25,pr=1<<26,mr=1<<27,hr=1<<28,gr=1<<29;ir-1,ar-1,or-1,sr-1,cr-1,lr-1,ur-1,dr-1,fr-1,pr-1,mr-1,hr-1,gr-1;var _r=2**53-1,vr=-(2**53-1),yr=Number.isInteger||(e=>typeof e==`number`&&isFinite(e)&&$n(e)===e);Number.isNaN,Number.parseInt;var br=String.fromCharCode;String.fromCodePoint,br(65535);var xr=e=>e.toLowerCase(),Sr=/^\s*/g,Cr=e=>e.replace(Sr,``),wr=/([A-Z])/g,Tr=(e,t)=>Cr(e.replace(wr,e=>`${t}${xr(e)}`)),Er=e=>{let t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r},Dr=typeof TextEncoder<`u`?new TextEncoder:null,Or=Dr?e=>Dr.encode(e):Er,kr=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});kr&&kr.decode(new Uint8Array).length===1&&(kr=null);var Ar=(e,t)=>Yn(t,()=>e).join(``),jr=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}},Mr=()=>new jr,Nr=e=>{let t=Mr();return e(t),Fr(t)},Pr=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},Fr=e=>{let t=new Uint8Array(Pr(e)),n=0;for(let r=0;r<e.bufs.length;r++){let i=e.bufs[r];t.set(i,n),n+=i.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t},Ir=(e,t)=>{let n=e.cbuf.length;n-e.cpos<t&&(e.bufs.push(new Uint8Array(e.cbuf.buffer,0,e.cpos)),e.cbuf=new Uint8Array(nr(n,t)*2),e.cpos=0)},Lr=(e,t)=>{let n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Rr=Lr,Z=(e,t)=>{for(;t>127;)Lr(e,128|127&t),t=$n(t/128);Lr(e,127&t)},zr=(e,t)=>{let n=rr(t);for(n&&(t=-t),Lr(e,(t>63?128:0)|(n?64:0)|63&t),t=$n(t/64);t>0;)Lr(e,(t>127?128:0)|127&t),t=$n(t/128)},Br=new Uint8Array(3e4),Vr=Br.length/3,Hr=Dr&&Dr.encodeInto?(e,t)=>{if(t.length<Vr){let n=Dr.encodeInto(t,Br).written||0;Z(e,n);for(let t=0;t<n;t++)Lr(e,Br[t])}else Wr(e,Or(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;Z(e,r);for(let t=0;t<r;t++)Lr(e,n.codePointAt(t))},Ur=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=tr(n-r,t.length),a=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,a>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(nr(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},Wr=(e,t)=>{Z(e,t.byteLength),Ur(e,t)},Gr=(e,t)=>{Ir(e,t);let n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},Kr=(e,t)=>Gr(e,4).setFloat32(0,t,!1),qr=(e,t)=>Gr(e,8).setFloat64(0,t,!1),Jr=(e,t)=>Gr(e,8).setBigInt64(0,t,!1),Yr=new DataView(new ArrayBuffer(4)),Xr=e=>(Yr.setFloat32(0,e),Yr.getFloat32(0)===e),Zr=(e,t)=>{switch(typeof t){case`string`:Lr(e,119),Hr(e,t);break;case`number`:yr(t)&&er(t)<=2147483647?(Lr(e,125),zr(e,t)):Xr(t)?(Lr(e,124),Kr(e,t)):(Lr(e,123),qr(e,t));break;case`bigint`:Lr(e,122),Jr(e,t);break;case`object`:if(t===null)Lr(e,126);else if(Xn(t)){Lr(e,117),Z(e,t.length);for(let n=0;n<t.length;n++)Zr(e,t[n])}else if(t instanceof Uint8Array)Lr(e,116),Wr(e,t);else{Lr(e,118);let n=Object.keys(t);Z(e,n.length);for(let r=0;r<n.length;r++){let i=n[r];Hr(e,i),Zr(e,t[i])}}break;case`boolean`:Lr(e,t?120:121);break;default:Lr(e,127)}},Qr=class extends jr{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&Z(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}},$r=e=>{e.count>0&&(zr(e.encoder,e.count===1?e.s:-e.s),e.count>1&&Z(e.encoder,e.count-2))},ei=class{constructor(){this.encoder=new jr,this.s=0,this.count=0}write(e){this.s===e?this.count++:($r(this),this.count=1,this.s=e)}toUint8Array(){return $r(this),Fr(this.encoder)}},ti=e=>{if(e.count>0){let t=e.diff*2+(e.count===1?0:1);zr(e.encoder,t),e.count>1&&Z(e.encoder,e.count-2)}},ni=class{constructor(){this.encoder=new jr,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(ti(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return ti(this),Fr(this.encoder)}},ri=class{constructor(){this.sarr=[],this.s=``,this.lensE=new ei}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=``),this.lensE.write(e.length)}toUint8Array(){let e=new jr;return this.sarr.push(this.s),this.s=``,Hr(e,this.sarr.join(``)),Ur(e,this.lensE.toUint8Array()),Fr(e)}},ii=e=>Error(e),ai=()=>{throw ii(`Method unimplemented`)},oi=()=>{throw ii(`Unexpected case`)},si=ii(`Unexpected end of array`),ci=ii(`Integer out of Range`),li=class{constructor(e){this.arr=e,this.pos=0}},ui=e=>new li(e),di=e=>e.pos!==e.arr.length,fi=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},pi=e=>fi(e,Q(e)),mi=e=>e.arr[e.pos++],Q=e=>{let t=0,n=1,r=e.arr.length;for(;e.pos<r;){let r=e.arr[e.pos++];if(t+=(r&127)*n,n*=128,r<128)return t;if(t>_r)throw ci}throw si},hi=e=>{let t=e.arr[e.pos++],n=t&63,r=64,i=(t&64)>0?-1:1;if(!(t&128))return i*n;let a=e.arr.length;for(;e.pos<a;){if(t=e.arr[e.pos++],n+=(t&127)*r,r*=128,t<128)return i*n;if(n>_r)throw ci}throw si},gi=kr?e=>kr.decode(pi(e)):e=>{let t=Q(e);if(t===0)return``;{let n=String.fromCodePoint(mi(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(mi(e));else for(;t>0;){let r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}},_i=(e,t)=>{let n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},vi=[e=>void 0,e=>null,hi,e=>_i(e,4).getFloat32(0,!1),e=>_i(e,8).getFloat64(0,!1),e=>_i(e,8).getBigInt64(0,!1),e=>!1,e=>!0,gi,e=>{let t=Q(e),n={};for(let r=0;r<t;r++){let t=gi(e);n[t]=yi(e)}return n},e=>{let t=Q(e),n=[];for(let r=0;r<t;r++)n.push(yi(e));return n},pi],yi=e=>vi[127-mi(e)](e),bi=class extends li{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),di(this)?this.count=Q(this)+1:this.count=-1),this.count--,this.s}},xi=class extends li{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=hi(this);let e=rr(this.s);this.count=1,e&&(this.s=-this.s,this.count=Q(this)+2)}return this.count--,this.s}},Si=class extends li{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){let e=hi(this),t=e&1;this.diff=$n(e/2),this.count=1,t&&(this.count=Q(this)+2)}return this.s+=this.diff,this.count--,this.s}},Ci=class{constructor(e){this.decoder=new xi(e),this.str=gi(this.decoder),this.spos=0}read(){let e=this.spos+this.decoder.read(),t=this.str.slice(this.spos,e);return this.spos=e,t}};crypto.subtle;var wi=crypto.getRandomValues.bind(crypto),Ti=Math.random,Ei=()=>wi(new Uint32Array(1))[0],Di=e=>e[$n(Ti()*e.length)],Oi=`10000000-1000-4000-8000-100000000000`,ki=()=>Oi.replace(/[018]/g,e=>(e^Ei()&15>>e/4).toString(16)),Ai=Date.now,ji=e=>new Promise(e);Promise.all.bind(Promise);var Mi=e=>e===void 0?null:e,Ni=new class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}};try{typeof localStorage<`u`&&localStorage&&(Ni=localStorage)}catch{}var Pi=Ni,Fi=Symbol(`Equality`),Ii=(e,t)=>e===t||!!e?.[Fi]?.(t)||!1,Li=e=>typeof e==`object`,Ri=Object.assign,zi=Object.keys,Bi=(e,t)=>{for(let n in e)t(e[n],n)},Vi=e=>zi(e).length,Hi=e=>{for(let t in e)return!1;return!0},Ui=(e,t)=>{for(let n in e)if(!t(e[n],n))return!1;return!0},Wi=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Gi=(e,t)=>e===t||Vi(e)===Vi(t)&&Ui(e,(e,n)=>(e!==void 0||Wi(t,n))&&Ii(t[n],e)),Ki=Object.freeze,qi=e=>{for(let t in e){let n=e[t];(typeof n==`object`||typeof n==`function`)&&qi(e[t])}return Ki(e)},Ji=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&Ji(e,t,n+1)}},Yi=e=>e,Xi=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[Fi]!=null)return e[Fi](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;break;case Set:if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;break;case Map:if(e.size!==t.size)return!1;for(let n of e.keys())if(!t.has(n)||!Xi(e.get(n),t.get(n)))return!1;break;case void 0:case Object:if(Vi(e)!==Vi(t))return!1;for(let n in e)if(!Wi(e,n)||!Xi(e[n],t[n]))return!1;break;case Array:if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Xi(e[n],t[n]))return!1;break;default:return!1}return!0},Zi=(e,t)=>t.includes(e),Qi=typeof process<`u`&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<`u`?process:0)===`[object process]`,$i=typeof window<`u`&&typeof document<`u`&&!Qi;typeof navigator<`u`&&/Mac/.test(navigator.platform);var ea,ta=[],na=()=>{if(ea===void 0)if(Qi){ea=Rn();let e=process.argv,t=null;for(let n=0;n<e.length;n++){let r=e[n];r[0]===`-`?(t!==null&&ea.set(t,``),t=r):t===null?ta.push(r):(ea.set(t,r),t=null)}t!==null&&ea.set(t,``)}else typeof location==`object`?(ea=Rn(),(location.search||`?`).slice(1).split(`&`).forEach(e=>{if(e.length!==0){let[t,n]=e.split(`=`);ea.set(`--${Tr(t,`-`)}`,n),ea.set(`-${Tr(t,`-`)}`,n)}})):ea=Rn();return ea},ra=e=>na().has(e),ia=e=>Mi(Qi?{}[e.toUpperCase().replaceAll(`-`,`_`)]:Pi.getItem(e)),aa=e=>ra(`--`+e)||ia(e)!==null,oa=aa(`production`),sa=Qi&&Zi({}.FORCE_COLOR,[`true`,`1`,`2`])||!ra(`--no-colors`)&&!aa(`no-color`)&&(!Qi||process.stdout.isTTY)&&(!Qi||ra(`--color`)||ia(`COLORTERM`)!==null||(ia(`TERM`)||``).includes(`color`)),ca=e=>new Uint8Array(e),la=$i?e=>{let t=``;for(let n=0;n<e.byteLength;n++)t+=br(e[n]);return btoa(t)}:e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64`),ua=e=>{let t=ca(e.byteLength);return t.set(e),t},da=e=>Nr(t=>Zr(t,e)),fa=class{constructor(e,t){this.left=e,this.right=t}},pa=(e,t)=>new fa(e,t),ma=(e,t)=>e.forEach(e=>t(e.left,e.right)),ha=e=>e.next()>=.5,ga=(e,t,n)=>$n(e.next()*(n+1-t)+t),_a=(e,t,n)=>$n(e.next()*(n+1-t)+t),va=(e,t,n)=>_a(e,t,n),ya=e=>br(va(e,97,122)),ba=(e,t=0,n=20)=>{let r=va(e,t,n),i=``;for(let t=0;t<r;t++)i+=ya(e);return i},xa=(e,t)=>t[va(e,0,t.length-1)],Sa=Symbol(`0schema`),Ca=class{constructor(){this._rerrs=[]}extend(e,t,n,r=null){this._rerrs.push({path:e,expected:t,has:n,message:r})}toString(){let e=[];for(let t=this._rerrs.length-1;t>0;t--){let n=this._rerrs[t];e.push(Ar(` `,(this._rerrs.length-t)*2)+`${n.path==null?``:`[${n.path}] `}${n.has} doesn't match ${n.expected}. ${n.message}`)}return e.join(`
|
|
1
|
+
import{r as e,t}from"./chunk-DECur_0Z.js";import{n,t as r}from"./propagation-api-Bugyj7xy.js";import{n as i,r as a,t as o}from"./compiler-runtime-Y11fyRVL.js";import{S as s,n as c,t as l,x as u}from"./button-B1XQHQcX.js";import{a as d,b as f,d as p,f as m,i as h,l as g,m as _,o as v,p as y,r as b,s as x,t as S,u as C,x as w}from"./dialog-DeibR6sn.js";import{$ as T,At as E,B as D,C as O,Ct as k,Dt as A,E as ee,Et as j,H as M,Ht as N,It as P,K as F,Lt as I,Mt as L,N as R,Nt as z,Ot as B,P as V,Pt as H,Rt as U,T as W,Tt as G,Ut as K,Vt as q,X as te,Yt as ne,Z as re,_t as ie,a as ae,at as oe,b as se,bt as ce,c as le,ct as ue,d as de,dt as fe,et as pe,f as me,ft as he,gt as ge,h as _e,ht as ve,j as ye,jt as be,kt as xe,lt as Se,m as Ce,mt as we,n as Te,nt as Ee,o as De,ot as Oe,p as ke,pt as Ae,qt as je,r as Me,tt as Ne,w as Pe,x as Fe,xt as Ie,y as Le}from"./PageListContext-BeAv6YTY.js";var Re=u(`circle-alert`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`line`,{x1:`12`,x2:`12`,y1:`8`,y2:`12`,key:`1pkeuh`}],[`line`,{x1:`12`,x2:`12.01`,y1:`16`,y2:`16`,key:`4dfq90`}]]),ze=u(`code-xml`,[[`path`,{d:`m18 16 4-4-4-4`,key:`1inbqp`}],[`path`,{d:`m6 8-4 4 4 4`,key:`15zrgr`}],[`path`,{d:`m14.5 4-5 16`,key:`e7oirm`}]]),Be=u(`external-link`,[[`path`,{d:`M15 3h6v6`,key:`1q9fwt`}],[`path`,{d:`M10 14 21 3`,key:`gplh6r`}],[`path`,{d:`M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6`,key:`a6xqqp`}]]),Ve=u(`file-plus-corner`,[[`path`,{d:`M11.35 22H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.706.706l3.588 3.588A2.4 2.4 0 0 1 20 8v5.35`,key:`17jvcc`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M14 19h6`,key:`bvotb8`}],[`path`,{d:`M17 16v6`,key:`18yu1i`}]]),He=u(`file`,[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`,key:`1oefj6`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}]]),Ue=u(`folder-open`,[[`path`,{d:`m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2`,key:`usdka0`}]]),We=u(`heading-1`,[[`path`,{d:`M4 12h8`,key:`17cfdx`}],[`path`,{d:`M4 18V6`,key:`1rz3zl`}],[`path`,{d:`M12 18V6`,key:`zqpxq5`}],[`path`,{d:`m17 12 3-2v8`,key:`1hhhft`}]]),Ge=u(`heading-2`,[[`path`,{d:`M4 12h8`,key:`17cfdx`}],[`path`,{d:`M4 18V6`,key:`1rz3zl`}],[`path`,{d:`M12 18V6`,key:`zqpxq5`}],[`path`,{d:`M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1`,key:`9jr5yi`}]]),Ke=u(`heading-3`,[[`path`,{d:`M4 12h8`,key:`17cfdx`}],[`path`,{d:`M4 18V6`,key:`1rz3zl`}],[`path`,{d:`M12 18V6`,key:`zqpxq5`}],[`path`,{d:`M17.5 10.5c1.7-1 3.5 0 3.5 1.5a2 2 0 0 1-2 2`,key:`68ncm8`}],[`path`,{d:`M17 17.5c2 1.5 4 .3 4-1.5a2 2 0 0 0-2-2`,key:`1ejuhz`}]]),qe=u(`image`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,ry:`2`,key:`1m3agn`}],[`circle`,{cx:`9`,cy:`9`,r:`2`,key:`af1f0g`}],[`path`,{d:`m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21`,key:`1xmnt7`}]]),Je=u(`list-ordered`,[[`path`,{d:`M11 5h10`,key:`1cz7ny`}],[`path`,{d:`M11 12h10`,key:`1438ji`}],[`path`,{d:`M11 19h10`,key:`11t30w`}],[`path`,{d:`M4 4h1v5`,key:`10yrso`}],[`path`,{d:`M4 9h2`,key:`r1h2o0`}],[`path`,{d:`M6.5 20H3.4c0-1 2.6-1.925 2.6-3.5a1.5 1.5 0 0 0-2.6-1.02`,key:`xtkcd5`}]]),Ye=u(`list-todo`,[[`path`,{d:`M13 5h8`,key:`a7qcls`}],[`path`,{d:`M13 12h8`,key:`h98zly`}],[`path`,{d:`M13 19h8`,key:`c3s6r1`}],[`path`,{d:`m3 17 2 2 4-4`,key:`1jhpwq`}],[`rect`,{x:`3`,y:`4`,width:`6`,height:`6`,rx:`1`,key:`cif1o7`}]]),Xe=u(`list`,[[`path`,{d:`M3 5h.01`,key:`18ugdj`}],[`path`,{d:`M3 12h.01`,key:`nlz23k`}],[`path`,{d:`M3 19h.01`,key:`noohij`}],[`path`,{d:`M8 5h13`,key:`1pao27`}],[`path`,{d:`M8 12h13`,key:`1za7za`}],[`path`,{d:`M8 19h13`,key:`m83p4d`}]]),Ze=u(`loader-circle`,[[`path`,{d:`M21 12a9 9 0 1 1-6.219-8.56`,key:`13zald`}]]),Qe=u(`minus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}]]),$e=u(`pencil`,[[`path`,{d:`M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z`,key:`1a8usu`}],[`path`,{d:`m15 5 4 4`,key:`1mk7zo`}]]),et=u(`quote`,[[`path`,{d:`M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z`,key:`rib7q0`}],[`path`,{d:`M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z`,key:`1ymkrd`}]]),tt=u(`table-2`,[[`path`,{d:`M9 3H5a2 2 0 0 0-2 2v4m6-6h10a2 2 0 0 1 2 2v4M9 3v18m0 0h10a2 2 0 0 0 2-2V9M9 21H5a2 2 0 0 1-2-2V9m0 0h18`,key:`gugj83`}]]),nt=u(`trash-2`,[[`path`,{d:`M10 11v6`,key:`nco0om`}],[`path`,{d:`M14 11v6`,key:`outv1u`}],[`path`,{d:`M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6`,key:`miytrc`}],[`path`,{d:`M3 6h18`,key:`d0wm0j`}],[`path`,{d:`M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2`,key:`e791ji`}]]),rt=t((e=>{var t=i();function n(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var r=typeof Object.is==`function`?Object.is:n,a=t.useState,o=t.useEffect,s=t.useLayoutEffect,c=t.useDebugValue;function l(e,t){var n=t(),r=a({inst:{value:n,getSnapshot:t}}),i=r[0].inst,l=r[1];return s(function(){i.value=n,i.getSnapshot=t,u(i)&&l({inst:i})},[e,n,t]),o(function(){return u(i)&&l({inst:i}),e(function(){u(i)&&l({inst:i})})},[e]),c(n),n}function u(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!r(e,n)}catch{return!0}}function d(e,t){return t()}var f=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?d:l;e.useSyncExternalStore=t.useSyncExternalStore===void 0?f:t.useSyncExternalStore})),it=t(((e,t)=>{t.exports=rt()})),J=e(i(),1),at=o();function ot(e){let t=e.split(`/`);return t.length<2?`ok`:`${t[0]}/${t[1]}`}function st(e){if(!e)return;let t=Object.entries(e);if(t.length!==0)return t.map(([e,t])=>{if(t==null)return[e,String(t)];if(typeof t==`string`)return[e,t];if(typeof t==`number`||typeof t==`boolean`)return[e,String(t)];try{return[e,JSON.stringify(t)]}catch{return[e,`[unserializable]`]}})}function Y(e,t,n){if(typeof performance>`u`||!performance.measure)return;let r=ot(e),i=st(t),a={devtools:{dataType:`track-entry`,track:r,...i?{properties:i}:{},...n?.tooltipText?{tooltipText:n.tooltipText}:{}}},o=performance.now(),s=n?.startTime??o,c=n?.duration??Math.max(0,o-s);try{performance.measure(e,{start:s,duration:c,detail:a})}catch{}({...t?{properties:t}:{}})}var X=a();function ct(e){let t=(0,at.c)(3),{name:n,children:r}=e,i;return t[0]!==r||t[1]!==n?(i=(0,X.jsx)(J.Profiler,{id:n,onRender:lt,children:r}),t[0]=r,t[1]=n,t[2]=i):i=t[2],i}var lt=(e,t,n,r,i,a)=>{Y(`ok/render/${e}`,{phase:t,actualDuration:Math.round(n*1e3)/1e3,baseDuration:Math.round(r*1e3)/1e3},{startTime:i,duration:Math.max(0,a-i)})},ut=e(s(),1),dt=it(),{getOwnPropertyNames:ft,getOwnPropertySymbols:pt}=Object,{hasOwnProperty:mt}=Object.prototype;function ht(e,t){return function(n,r,i){return e(n,r,i)&&t(n,r,i)}}function gt(e){return function(t,n,r){if(!t||!n||typeof t!=`object`||typeof n!=`object`)return e(t,n,r);let{cache:i}=r,a=i.get(t),o=i.get(n);if(a&&o)return a===n&&o===t;i.set(t,n),i.set(n,t);let s=e(t,n,r);return i.delete(t),i.delete(n),s}}function _t(e){return e?.[Symbol.toStringTag]}function vt(e){return ft(e).concat(pt(e))}var yt=Object.hasOwn||((e,t)=>mt.call(e,t));function bt(e,t){return e===t||!e&&!t&&e!==e&&t!==t}var xt=`__v`,St=`__o`,Ct=`_owner`,{getOwnPropertyDescriptor:wt,keys:Tt}=Object;function Et(e,t){return e.byteLength===t.byteLength&&zt(new Uint8Array(e),new Uint8Array(t))}function Dt(e,t,n){let r=e.length;if(t.length!==r)return!1;for(;r-- >0;)if(!n.equals(e[r],t[r],r,r,e,t,n))return!1;return!0}function Ot(e,t){return e.byteLength===t.byteLength&&zt(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}function kt(e,t){return bt(e.getTime(),t.getTime())}function At(e,t){return e.name===t.name&&e.message===t.message&&e.cause===t.cause&&e.stack===t.stack}function jt(e,t){return e===t}function Mt(e,t,n){let r=e.size;if(r!==t.size)return!1;if(!r)return!0;let i=Array(r),a=e.entries(),o,s,c=0;for(;(o=a.next())&&!o.done;){let r=t.entries(),a=!1,l=0;for(;(s=r.next())&&!s.done;){if(i[l]){l++;continue}let r=o.value,u=s.value;if(n.equals(r[0],u[0],c,l,e,t,n)&&n.equals(r[1],u[1],r[0],u[0],e,t,n)){a=i[l]=!0;break}l++}if(!a)return!1;c++}return!0}var Nt=bt;function Pt(e,t,n){let r=Tt(e),i=r.length;if(Tt(t).length!==i)return!1;for(;i-- >0;)if(!Vt(e,t,n,r[i]))return!1;return!0}function Ft(e,t,n){let r=vt(e),i=r.length;if(vt(t).length!==i)return!1;let a,o,s;for(;i-- >0;)if(a=r[i],!Vt(e,t,n,a)||(o=wt(e,a),s=wt(t,a),(o||s)&&(!o||!s||o.configurable!==s.configurable||o.enumerable!==s.enumerable||o.writable!==s.writable)))return!1;return!0}function It(e,t){return bt(e.valueOf(),t.valueOf())}function Lt(e,t){return e.source===t.source&&e.flags===t.flags}function Rt(e,t,n){let r=e.size;if(r!==t.size)return!1;if(!r)return!0;let i=Array(r),a=e.values(),o,s;for(;(o=a.next())&&!o.done;){let r=t.values(),a=!1,c=0;for(;(s=r.next())&&!s.done;){if(!i[c]&&n.equals(o.value,s.value,o.value,s.value,e,t,n)){a=i[c]=!0;break}c++}if(!a)return!1}return!0}function zt(e,t){let n=e.byteLength;if(t.byteLength!==n||e.byteOffset!==t.byteOffset)return!1;for(;n-- >0;)if(e[n]!==t[n])return!1;return!0}function Bt(e,t){return e.hostname===t.hostname&&e.pathname===t.pathname&&e.protocol===t.protocol&&e.port===t.port&&e.hash===t.hash&&e.username===t.username&&e.password===t.password}function Vt(e,t,n,r){return(r===Ct||r===St||r===xt)&&(e.$$typeof||t.$$typeof)?!0:yt(t,r)&&n.equals(e[r],t[r],r,r,e,t,n)}var Ht=`[object ArrayBuffer]`,Ut=`[object Arguments]`,Wt=`[object Boolean]`,Gt=`[object DataView]`,Kt=`[object Date]`,qt=`[object Error]`,Jt=`[object Map]`,Yt=`[object Number]`,Xt=`[object Object]`,Zt=`[object RegExp]`,Qt=`[object Set]`,$t=`[object String]`,en={"[object Int8Array]":!0,"[object Uint8Array]":!0,"[object Uint8ClampedArray]":!0,"[object Int16Array]":!0,"[object Uint16Array]":!0,"[object Int32Array]":!0,"[object Uint32Array]":!0,"[object Float16Array]":!0,"[object Float32Array]":!0,"[object Float64Array]":!0,"[object BigInt64Array]":!0,"[object BigUint64Array]":!0},tn=`[object URL]`,nn=Object.prototype.toString;function rn({areArrayBuffersEqual:e,areArraysEqual:t,areDataViewsEqual:n,areDatesEqual:r,areErrorsEqual:i,areFunctionsEqual:a,areMapsEqual:o,areNumbersEqual:s,areObjectsEqual:c,arePrimitiveWrappersEqual:l,areRegExpsEqual:u,areSetsEqual:d,areTypedArraysEqual:f,areUrlsEqual:p,unknownTagComparators:m}){return function(h,g,_){if(h===g)return!0;if(h==null||g==null)return!1;let v=typeof h;if(v!==typeof g)return!1;if(v!==`object`)return v===`number`?s(h,g,_):v===`function`?a(h,g,_):!1;let y=h.constructor;if(y!==g.constructor)return!1;if(y===Object)return c(h,g,_);if(Array.isArray(h))return t(h,g,_);if(y===Date)return r(h,g,_);if(y===RegExp)return u(h,g,_);if(y===Map)return o(h,g,_);if(y===Set)return d(h,g,_);let b=nn.call(h);if(b===Kt)return r(h,g,_);if(b===Zt)return u(h,g,_);if(b===Jt)return o(h,g,_);if(b===Qt)return d(h,g,_);if(b===Xt)return typeof h.then!=`function`&&typeof g.then!=`function`&&c(h,g,_);if(b===tn)return p(h,g,_);if(b===qt)return i(h,g,_);if(b===Ut)return c(h,g,_);if(en[b])return f(h,g,_);if(b===Ht)return e(h,g,_);if(b===Gt)return n(h,g,_);if(b===Wt||b===Yt||b===$t)return l(h,g,_);if(m){let e=m[b];if(!e){let t=_t(h);t&&(e=m[t])}if(e)return e(h,g,_)}return!1}}function an({circular:e,createCustomConfig:t,strict:n}){let r={areArrayBuffersEqual:Et,areArraysEqual:n?Ft:Dt,areDataViewsEqual:Ot,areDatesEqual:kt,areErrorsEqual:At,areFunctionsEqual:jt,areMapsEqual:n?ht(Mt,Ft):Mt,areNumbersEqual:Nt,areObjectsEqual:n?Ft:Pt,arePrimitiveWrappersEqual:It,areRegExpsEqual:Lt,areSetsEqual:n?ht(Rt,Ft):Rt,areTypedArraysEqual:n?ht(zt,Ft):zt,areUrlsEqual:Bt,unknownTagComparators:void 0};if(t&&(r=Object.assign({},r,t(r))),e){let e=gt(r.areArraysEqual),t=gt(r.areMapsEqual),n=gt(r.areObjectsEqual),i=gt(r.areSetsEqual);r=Object.assign({},r,{areArraysEqual:e,areMapsEqual:t,areObjectsEqual:n,areSetsEqual:i})}return r}function on(e){return function(t,n,r,i,a,o,s){return e(t,n,s)}}function sn({circular:e,comparator:t,createState:n,equals:r,strict:i}){if(n)return function(a,o){let{cache:s=e?new WeakMap:void 0,meta:c}=n();return t(a,o,{cache:s,equals:r,meta:c,strict:i})};if(e)return function(e,n){return t(e,n,{cache:new WeakMap,equals:r,meta:void 0,strict:i})};let a={cache:void 0,equals:r,meta:void 0,strict:i};return function(e,n){return t(e,n,a)}}var cn=ln();ln({strict:!0}),ln({circular:!0}),ln({circular:!0,strict:!0}),ln({createInternalComparator:()=>bt}),ln({strict:!0,createInternalComparator:()=>bt}),ln({circular:!0,createInternalComparator:()=>bt}),ln({circular:!0,createInternalComparator:()=>bt,strict:!0});function ln(e={}){let{circular:t=!1,createInternalComparator:n,createState:r,strict:i=!1}=e,a=rn(an(e));return sn({circular:t,comparator:a,createState:r,equals:n?n(a):on(a),strict:i})}var un=t((e=>{var t=i(),n=it();function r(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var a=typeof Object.is==`function`?Object.is:r,o=n.useSyncExternalStore,s=t.useRef,c=t.useEffect,l=t.useMemo,u=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(e,t,n,r,i){var d=s(null);if(d.current===null){var f={hasValue:!1,value:null};d.current=f}else f=d.current;d=l(function(){function e(e){if(!o){if(o=!0,s=e,e=r(e),i!==void 0&&f.hasValue){var t=f.value;if(i(t,e))return c=t}return c=e}if(t=c,a(s,e))return t;var n=r(e);return i!==void 0&&i(t,n)?(s=e,t):(s=e,c=n)}var o=!1,s,c,l=n===void 0?null:n;return[function(){return e(t())},l===null?void 0:function(){return e(l())}]},[t,n,r,i]);var p=o(e,d[0],d[1]);return c(function(){f.hasValue=!0,f.value=p},[p]),u(p),p}})),dn=t(((e,t)=>{t.exports=un()}))(),fn=(...e)=>t=>{e.forEach(e=>{typeof e==`function`?e(t):e&&(e.current=t)})},pn=({contentComponent:e})=>{let t=(0,dt.useSyncExternalStore)(e.subscribe,e.getSnapshot,e.getServerSnapshot);return(0,X.jsx)(X.Fragment,{children:Object.values(t)})};function mn(){let e=new Set,t={};return{subscribe(t){return e.add(t),()=>{e.delete(t)}},getSnapshot(){return t},getServerSnapshot(){return t},setRenderer(n,r){t={...t,[n]:ut.createPortal(r.reactElement,r.element,n)},e.forEach(e=>e())},removeRenderer(n){let r={...t};delete r[n],t=r,e.forEach(e=>e())}}}var hn=class extends J.Component{constructor(e){super(e),this.editorContentRef=J.createRef()}componentDidMount(){this.init()}componentDidUpdate(){this.init()}init(){let e=this.props.editor;if(e&&!e.isDestroyed&&e.view.dom?.parentNode){if(e.contentComponent)return;let t=this.editorContentRef.current;t.append(...e.view.dom.parentNode.childNodes),e.setOptions({element:t}),e.contentComponent=mn(),e.createNodeViews(),e.isEditorContentInitialized=!0,this.forceUpdate()}}componentWillUnmount(){let e=this.props.editor;if(e){e.isEditorContentInitialized=!1,e.isDestroyed||e.view.setProps({nodeViews:{}}),e.contentComponent=null;try{if(!e.view.dom?.parentNode)return;let t=document.createElement(`div`);t.append(...e.view.dom.parentNode.childNodes),e.setOptions({element:t})}catch{}}}render(){let{editor:e,innerRef:t,...n}=this.props;return(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`div`,{ref:fn(t,this.editorContentRef),...n}),e?.contentComponent&&(0,X.jsx)(pn,{contentComponent:e.contentComponent})]})}},gn=(0,J.forwardRef)((e,t)=>{let n=J.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[e.editor]);return J.createElement(hn,{key:n,innerRef:t,...e})}),_n=J.memo(gn),vn=typeof window<`u`?J.useLayoutEffect:J.useEffect,yn=class{constructor(e){this.transactionNumber=0,this.lastTransactionNumber=0,this.subscribers=new Set,this.editor=e,this.lastSnapshot={editor:e,transactionNumber:0},this.getSnapshot=this.getSnapshot.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.watch=this.watch.bind(this),this.subscribe=this.subscribe.bind(this)}getSnapshot(){return this.transactionNumber===this.lastTransactionNumber?this.lastSnapshot:(this.lastTransactionNumber=this.transactionNumber,this.lastSnapshot={editor:this.editor,transactionNumber:this.transactionNumber},this.lastSnapshot)}getServerSnapshot(){return{editor:null,transactionNumber:0}}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}watch(e){if(this.editor=e,this.editor){let e=()=>{this.transactionNumber+=1,this.subscribers.forEach(e=>e())},t=this.editor;return t.on(`transaction`,e),()=>{t.off(`transaction`,e)}}}};function bn(e){let[t]=(0,J.useState)(()=>new yn(e.editor)),n=(0,dn.useSyncExternalStoreWithSelector)(t.subscribe,t.getSnapshot,t.getServerSnapshot,e.selector,e.equalityFn??cn);return vn(()=>t.watch(e.editor),[e.editor,t]),(0,J.useDebugValue)(n),n}typeof window>`u`||typeof window<`u`&&window.next;var xn=(0,J.createContext)({editor:null});xn.Consumer;var Sn=()=>(0,J.useContext)(xn),Cn=(0,J.createContext)({onDragStart:()=>{},nodeViewContentChildren:void 0,nodeViewContentRef:()=>{}}),wn=()=>(0,J.useContext)(Cn),Tn=J.forwardRef((e,t)=>{let{onDragStart:n}=wn();return(0,X.jsx)(e.as||`div`,{...e,ref:t,"data-node-view-wrapper":``,onDragStart:n,style:{whiteSpace:`normal`,...e.style}})});function En(e){return!!(typeof e==`function`&&e.prototype&&e.prototype.isReactComponent)}function Dn(e){return!!(typeof e==`object`&&e.$$typeof&&(e.$$typeof.toString()===`Symbol(react.forward_ref)`||e.$$typeof.description===`react.forward_ref`))}function On(e){return!!(typeof e==`object`&&e.$$typeof&&(e.$$typeof.toString()===`Symbol(react.memo)`||e.$$typeof.description===`react.memo`))}function kn(e){if(En(e)||Dn(e))return!0;if(On(e)){let t=e.type;if(t)return En(t)||Dn(t)}return!1}function An(){try{if(J.version)return parseInt(J.version.split(`.`)[0],10)>=19}catch{}return!1}var jn=class{constructor(e,{editor:t,props:n={},as:r=`div`,className:i=``}){this.ref=null,this.destroyed=!1,this.id=Math.floor(Math.random()*4294967295).toString(),this.component=e,this.editor=t,this.props=n,this.element=document.createElement(r),this.element.classList.add(`react-renderer`),i&&this.element.classList.add(...i.split(` `)),this.editor.isEditorContentInitialized?(0,ut.flushSync)(()=>{this.render()}):queueMicrotask(()=>{this.destroyed||this.render()})}render(){var e;if(this.destroyed)return;let t=this.component,n=this.props,r=this.editor,i=An(),a=kn(t),o={...n};o.ref&&!(i||a)&&delete o.ref,!o.ref&&(i||a)&&(o.ref=e=>{this.ref=e}),this.reactElement=(0,X.jsx)(t,{...o}),(e=r?.contentComponent)==null||e.setRenderer(this.id,this)}updateProps(e={}){this.destroyed||(this.props={...this.props,...e},this.render())}destroy(){var e;this.destroyed=!0,(e=this.editor?.contentComponent)==null||e.removeRenderer(this.id);try{this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element)}catch{}}updateAttributes(e){Object.keys(e).forEach(t=>{this.element.setAttribute(t,e[t])})}};J.createContext({markViewContentRef:()=>{}});var Mn=class extends Ae{constructor(e,t,n){if(super(e,t,n),this.selectionRafId=null,this.positionCheckCallback=null,this.cachedExtensionWithSyncedStorage=null,!this.node.isLeaf){this.options.contentDOMElementTag?this.contentDOMElement=document.createElement(this.options.contentDOMElementTag):this.contentDOMElement=document.createElement(this.node.isInline?`span`:`div`),this.contentDOMElement.dataset.nodeViewContentReact=``,this.contentDOMElement.dataset.nodeViewWrapper=``,this.contentDOMElement.style.whiteSpace=`inherit`;let e=this.dom.querySelector(`[data-node-view-content]`);if(!e)return;e.appendChild(this.contentDOMElement)}}get extensionWithSyncedStorage(){if(!this.cachedExtensionWithSyncedStorage){let e=this.editor,t=this.extension;this.cachedExtensionWithSyncedStorage=new Proxy(t,{get(n,r,i){return r===`storage`?e.storage[t.name]??{}:Reflect.get(n,r,i)}})}return this.cachedExtensionWithSyncedStorage}mount(){let e={editor:this.editor,node:this.node,decorations:this.decorations,innerDecorations:this.innerDecorations,view:this.view,selected:!1,extension:this.extensionWithSyncedStorage,HTMLAttributes:this.HTMLAttributes,getPos:()=>this.getPos(),updateAttributes:(e={})=>this.updateAttributes(e),deleteNode:()=>this.deleteNode(),ref:(0,J.createRef)()};if(!this.component.displayName){let e=e=>e.charAt(0).toUpperCase()+e.substring(1);this.component.displayName=e(this.extension.name)}let t={onDragStart:this.onDragStart.bind(this),nodeViewContentRef:e=>{e&&this.contentDOMElement&&e.firstChild!==this.contentDOMElement&&(e.hasAttribute(`data-node-view-wrapper`)&&e.removeAttribute(`data-node-view-wrapper`),e.appendChild(this.contentDOMElement))}},n=this.component,r=(0,J.memo)(e=>(0,X.jsx)(Cn.Provider,{value:t,children:(0,J.createElement)(n,e)}));r.displayName=`ReactNodeView`;let i=this.node.isInline?`span`:`div`;this.options.as&&(i=this.options.as);let{className:a=``}=this.options;this.handleSelectionUpdate=this.handleSelectionUpdate.bind(this),this.renderer=new jn(r,{editor:this.editor,props:e,as:i,className:`node-${this.node.type.name} ${a}`.trim()}),this.editor.on(`selectionUpdate`,this.handleSelectionUpdate),this.updateElementAttributes(),this.currentPos=this.getPos(),this.positionCheckCallback=()=>{let e=this.getPos();typeof e!=`number`||e===this.currentPos||(this.currentPos=e,this.renderer.updateProps({getPos:()=>this.getPos()}),typeof this.options.attrs==`function`&&this.updateElementAttributes())},G(this.editor,this.positionCheckCallback)}get dom(){if(this.renderer.element.firstElementChild&&!this.renderer.element.firstElementChild?.hasAttribute(`data-node-view-wrapper`))throw Error(`Please use the NodeViewWrapper component for your node view.`);return this.renderer.element}get contentDOM(){return this.node.isLeaf?null:this.contentDOMElement}handleSelectionUpdate(){this.selectionRafId&&=(cancelAnimationFrame(this.selectionRafId),null),this.selectionRafId=requestAnimationFrame(()=>{this.selectionRafId=null;let{from:e,to:t}=this.editor.state.selection,n=this.currentPos;if(typeof n==`number`)if(e<=n&&t>=n+this.node.nodeSize){if(this.renderer.props.selected)return;this.selectNode()}else{if(!this.renderer.props.selected)return;this.deselectNode()}})}update(e,t,n){let r=e=>{this.renderer.updateProps(e),typeof this.options.attrs==`function`&&this.updateElementAttributes()};if(e.type!==this.node.type)return!1;if(typeof this.options.update==`function`){let i=this.node,a=this.decorations,o=this.innerDecorations;return this.node=e,this.decorations=t,this.innerDecorations=n,this.currentPos=this.getPos(),this.options.update({oldNode:i,oldDecorations:a,newNode:e,newDecorations:t,oldInnerDecorations:o,innerDecorations:n,updateProps:()=>r({node:e,decorations:t,innerDecorations:n,extension:this.extensionWithSyncedStorage})})}let i=this.getPos();return e===this.node&&this.decorations===t&&this.innerDecorations===n?i===this.currentPos?!0:(this.currentPos=i,r({node:e,decorations:t,innerDecorations:n,extension:this.extensionWithSyncedStorage,getPos:()=>this.getPos()}),!0):(this.node=e,this.decorations=t,this.innerDecorations=n,this.currentPos=i,r({node:e,decorations:t,innerDecorations:n,extension:this.extensionWithSyncedStorage}),!0)}selectNode(){this.renderer.updateProps({selected:!0}),this.renderer.element.classList.add(`ProseMirror-selectednode`)}deselectNode(){this.renderer.updateProps({selected:!1}),this.renderer.element.classList.remove(`ProseMirror-selectednode`)}destroy(){this.renderer.destroy(),this.editor.off(`selectionUpdate`,this.handleSelectionUpdate),this.positionCheckCallback&&=(we(this.editor,this.positionCheckCallback),null),this.contentDOMElement=null,this.selectionRafId&&=(cancelAnimationFrame(this.selectionRafId),null)}updateElementAttributes(){if(this.options.attrs){let e={};if(typeof this.options.attrs==`function`){let t=this.editor.extensionManager.attributes,n=ge(this.node,t);e=this.options.attrs({node:this.node,HTMLAttributes:n})}else e=this.options.attrs;this.renderer.updateAttributes(e)}}};function Nn(e,t){return n=>n.editor.contentComponent?new Mn(e,n,t):{}}var Pn=(0,J.createContext)({get editor(){throw Error(`useTiptap must be used within a <Tiptap> provider`)}});Pn.displayName=`TiptapContext`;var Fn=()=>(0,J.useContext)(Pn);function In({editor:e,instance:t,children:n}){let r=e??t;if(!r)throw Error("Tiptap: An editor instance is required. Pass a non-null `editor` prop.");let i=(0,J.useMemo)(()=>({editor:r}),[r]),a=(0,J.useMemo)(()=>({editor:r}),[r]);return(0,X.jsx)(xn.Provider,{value:a,children:(0,X.jsx)(Pn.Provider,{value:i,children:n})})}In.displayName=`Tiptap`;function Ln({...e}){let{editor:t}=Fn();return(0,X.jsx)(_n,{editor:t,...e})}Ln.displayName=`Tiptap.Content`,Object.assign(In,{Content:Ln});var Rn=()=>new Map,zn=e=>{let t=Rn();return e.forEach((e,n)=>{t.set(n,e)}),t},Bn=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r},Vn=(e,t)=>{let n=[];for(let[r,i]of e)n.push(t(i,r));return n},Hn=(e,t)=>{for(let[n,r]of e)if(t(r,n))return!0;return!1},Un=()=>new Set,Wn=e=>e[e.length-1],Gn=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},Kn=Array.from,qn=(e,t)=>{for(let n=0;n<e.length;n++)if(!t(e[n],n,e))return!1;return!0},Jn=(e,t)=>{for(let n=0;n<e.length;n++)if(t(e[n],n,e))return!0;return!1},Yn=(e,t)=>{let n=Array(e);for(let r=0;r<e;r++)n[r]=t(r,n);return n},Xn=Array.isArray,Zn=class{constructor(){this._observers=Rn()}on(e,t){return Bn(this._observers,e,Un).add(t),t}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){let n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return Kn((this._observers.get(e)||Rn()).values()).forEach(e=>e(...t))}destroy(){this._observers=Rn()}},Qn=class{constructor(){this._observers=Rn()}on(e,t){Bn(this._observers,e,Un).add(t)}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){let n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return Kn((this._observers.get(e)||Rn()).values()).forEach(e=>e(...t))}destroy(){this._observers=Rn()}},$n=Math.floor,er=Math.abs,tr=(e,t)=>e<t?e:t,nr=(e,t)=>e>t?e:t;Number.isNaN;var rr=e=>e===0?1/e<0:e<0,ir=1<<17,ar=1<<18,or=1<<19,sr=1<<20,cr=1<<21,lr=1<<22,ur=1<<23,dr=1<<24,fr=1<<25,pr=1<<26,mr=1<<27,hr=1<<28,gr=1<<29;ir-1,ar-1,or-1,sr-1,cr-1,lr-1,ur-1,dr-1,fr-1,pr-1,mr-1,hr-1,gr-1;var _r=2**53-1,vr=-(2**53-1),yr=Number.isInteger||(e=>typeof e==`number`&&isFinite(e)&&$n(e)===e);Number.isNaN,Number.parseInt;var br=String.fromCharCode;String.fromCodePoint,br(65535);var xr=e=>e.toLowerCase(),Sr=/^\s*/g,Cr=e=>e.replace(Sr,``),wr=/([A-Z])/g,Tr=(e,t)=>Cr(e.replace(wr,e=>`${t}${xr(e)}`)),Er=e=>{let t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r},Dr=typeof TextEncoder<`u`?new TextEncoder:null,Or=Dr?e=>Dr.encode(e):Er,kr=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});kr&&kr.decode(new Uint8Array).length===1&&(kr=null);var Ar=(e,t)=>Yn(t,()=>e).join(``),jr=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}},Mr=()=>new jr,Nr=e=>{let t=Mr();return e(t),Fr(t)},Pr=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},Fr=e=>{let t=new Uint8Array(Pr(e)),n=0;for(let r=0;r<e.bufs.length;r++){let i=e.bufs[r];t.set(i,n),n+=i.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t},Ir=(e,t)=>{let n=e.cbuf.length;n-e.cpos<t&&(e.bufs.push(new Uint8Array(e.cbuf.buffer,0,e.cpos)),e.cbuf=new Uint8Array(nr(n,t)*2),e.cpos=0)},Lr=(e,t)=>{let n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Rr=Lr,Z=(e,t)=>{for(;t>127;)Lr(e,128|127&t),t=$n(t/128);Lr(e,127&t)},zr=(e,t)=>{let n=rr(t);for(n&&(t=-t),Lr(e,(t>63?128:0)|(n?64:0)|63&t),t=$n(t/64);t>0;)Lr(e,(t>127?128:0)|127&t),t=$n(t/128)},Br=new Uint8Array(3e4),Vr=Br.length/3,Hr=Dr&&Dr.encodeInto?(e,t)=>{if(t.length<Vr){let n=Dr.encodeInto(t,Br).written||0;Z(e,n);for(let t=0;t<n;t++)Lr(e,Br[t])}else Wr(e,Or(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;Z(e,r);for(let t=0;t<r;t++)Lr(e,n.codePointAt(t))},Ur=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=tr(n-r,t.length),a=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,a>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(nr(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},Wr=(e,t)=>{Z(e,t.byteLength),Ur(e,t)},Gr=(e,t)=>{Ir(e,t);let n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},Kr=(e,t)=>Gr(e,4).setFloat32(0,t,!1),qr=(e,t)=>Gr(e,8).setFloat64(0,t,!1),Jr=(e,t)=>Gr(e,8).setBigInt64(0,t,!1),Yr=new DataView(new ArrayBuffer(4)),Xr=e=>(Yr.setFloat32(0,e),Yr.getFloat32(0)===e),Zr=(e,t)=>{switch(typeof t){case`string`:Lr(e,119),Hr(e,t);break;case`number`:yr(t)&&er(t)<=2147483647?(Lr(e,125),zr(e,t)):Xr(t)?(Lr(e,124),Kr(e,t)):(Lr(e,123),qr(e,t));break;case`bigint`:Lr(e,122),Jr(e,t);break;case`object`:if(t===null)Lr(e,126);else if(Xn(t)){Lr(e,117),Z(e,t.length);for(let n=0;n<t.length;n++)Zr(e,t[n])}else if(t instanceof Uint8Array)Lr(e,116),Wr(e,t);else{Lr(e,118);let n=Object.keys(t);Z(e,n.length);for(let r=0;r<n.length;r++){let i=n[r];Hr(e,i),Zr(e,t[i])}}break;case`boolean`:Lr(e,t?120:121);break;default:Lr(e,127)}},Qr=class extends jr{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&Z(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}},$r=e=>{e.count>0&&(zr(e.encoder,e.count===1?e.s:-e.s),e.count>1&&Z(e.encoder,e.count-2))},ei=class{constructor(){this.encoder=new jr,this.s=0,this.count=0}write(e){this.s===e?this.count++:($r(this),this.count=1,this.s=e)}toUint8Array(){return $r(this),Fr(this.encoder)}},ti=e=>{if(e.count>0){let t=e.diff*2+(e.count===1?0:1);zr(e.encoder,t),e.count>1&&Z(e.encoder,e.count-2)}},ni=class{constructor(){this.encoder=new jr,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(ti(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return ti(this),Fr(this.encoder)}},ri=class{constructor(){this.sarr=[],this.s=``,this.lensE=new ei}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=``),this.lensE.write(e.length)}toUint8Array(){let e=new jr;return this.sarr.push(this.s),this.s=``,Hr(e,this.sarr.join(``)),Ur(e,this.lensE.toUint8Array()),Fr(e)}},ii=e=>Error(e),ai=()=>{throw ii(`Method unimplemented`)},oi=()=>{throw ii(`Unexpected case`)},si=ii(`Unexpected end of array`),ci=ii(`Integer out of Range`),li=class{constructor(e){this.arr=e,this.pos=0}},ui=e=>new li(e),di=e=>e.pos!==e.arr.length,fi=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},pi=e=>fi(e,Q(e)),mi=e=>e.arr[e.pos++],Q=e=>{let t=0,n=1,r=e.arr.length;for(;e.pos<r;){let r=e.arr[e.pos++];if(t+=(r&127)*n,n*=128,r<128)return t;if(t>_r)throw ci}throw si},hi=e=>{let t=e.arr[e.pos++],n=t&63,r=64,i=(t&64)>0?-1:1;if(!(t&128))return i*n;let a=e.arr.length;for(;e.pos<a;){if(t=e.arr[e.pos++],n+=(t&127)*r,r*=128,t<128)return i*n;if(n>_r)throw ci}throw si},gi=kr?e=>kr.decode(pi(e)):e=>{let t=Q(e);if(t===0)return``;{let n=String.fromCodePoint(mi(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(mi(e));else for(;t>0;){let r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}},_i=(e,t)=>{let n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},vi=[e=>void 0,e=>null,hi,e=>_i(e,4).getFloat32(0,!1),e=>_i(e,8).getFloat64(0,!1),e=>_i(e,8).getBigInt64(0,!1),e=>!1,e=>!0,gi,e=>{let t=Q(e),n={};for(let r=0;r<t;r++){let t=gi(e);n[t]=yi(e)}return n},e=>{let t=Q(e),n=[];for(let r=0;r<t;r++)n.push(yi(e));return n},pi],yi=e=>vi[127-mi(e)](e),bi=class extends li{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),di(this)?this.count=Q(this)+1:this.count=-1),this.count--,this.s}},xi=class extends li{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=hi(this);let e=rr(this.s);this.count=1,e&&(this.s=-this.s,this.count=Q(this)+2)}return this.count--,this.s}},Si=class extends li{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){let e=hi(this),t=e&1;this.diff=$n(e/2),this.count=1,t&&(this.count=Q(this)+2)}return this.s+=this.diff,this.count--,this.s}},Ci=class{constructor(e){this.decoder=new xi(e),this.str=gi(this.decoder),this.spos=0}read(){let e=this.spos+this.decoder.read(),t=this.str.slice(this.spos,e);return this.spos=e,t}};crypto.subtle;var wi=crypto.getRandomValues.bind(crypto),Ti=Math.random,Ei=()=>wi(new Uint32Array(1))[0],Di=e=>e[$n(Ti()*e.length)],Oi=`10000000-1000-4000-8000-100000000000`,ki=()=>Oi.replace(/[018]/g,e=>(e^Ei()&15>>e/4).toString(16)),Ai=Date.now,ji=e=>new Promise(e);Promise.all.bind(Promise);var Mi=e=>e===void 0?null:e,Ni=new class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}};try{typeof localStorage<`u`&&localStorage&&(Ni=localStorage)}catch{}var Pi=Ni,Fi=Symbol(`Equality`),Ii=(e,t)=>e===t||!!e?.[Fi]?.(t)||!1,Li=e=>typeof e==`object`,Ri=Object.assign,zi=Object.keys,Bi=(e,t)=>{for(let n in e)t(e[n],n)},Vi=e=>zi(e).length,Hi=e=>{for(let t in e)return!1;return!0},Ui=(e,t)=>{for(let n in e)if(!t(e[n],n))return!1;return!0},Wi=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Gi=(e,t)=>e===t||Vi(e)===Vi(t)&&Ui(e,(e,n)=>(e!==void 0||Wi(t,n))&&Ii(t[n],e)),Ki=Object.freeze,qi=e=>{for(let t in e){let n=e[t];(typeof n==`object`||typeof n==`function`)&&qi(e[t])}return Ki(e)},Ji=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&Ji(e,t,n+1)}},Yi=e=>e,Xi=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[Fi]!=null)return e[Fi](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;break;case Set:if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;break;case Map:if(e.size!==t.size)return!1;for(let n of e.keys())if(!t.has(n)||!Xi(e.get(n),t.get(n)))return!1;break;case void 0:case Object:if(Vi(e)!==Vi(t))return!1;for(let n in e)if(!Wi(e,n)||!Xi(e[n],t[n]))return!1;break;case Array:if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Xi(e[n],t[n]))return!1;break;default:return!1}return!0},Zi=(e,t)=>t.includes(e),Qi=typeof process<`u`&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<`u`?process:0)===`[object process]`,$i=typeof window<`u`&&typeof document<`u`&&!Qi;typeof navigator<`u`&&/Mac/.test(navigator.platform);var ea,ta=[],na=()=>{if(ea===void 0)if(Qi){ea=Rn();let e=process.argv,t=null;for(let n=0;n<e.length;n++){let r=e[n];r[0]===`-`?(t!==null&&ea.set(t,``),t=r):t===null?ta.push(r):(ea.set(t,r),t=null)}t!==null&&ea.set(t,``)}else typeof location==`object`?(ea=Rn(),(location.search||`?`).slice(1).split(`&`).forEach(e=>{if(e.length!==0){let[t,n]=e.split(`=`);ea.set(`--${Tr(t,`-`)}`,n),ea.set(`-${Tr(t,`-`)}`,n)}})):ea=Rn();return ea},ra=e=>na().has(e),ia=e=>Mi(Qi?{}[e.toUpperCase().replaceAll(`-`,`_`)]:Pi.getItem(e)),aa=e=>ra(`--`+e)||ia(e)!==null,oa=aa(`production`),sa=Qi&&Zi({}.FORCE_COLOR,[`true`,`1`,`2`])||!ra(`--no-colors`)&&!aa(`no-color`)&&(!Qi||process.stdout.isTTY)&&(!Qi||ra(`--color`)||ia(`COLORTERM`)!==null||(ia(`TERM`)||``).includes(`color`)),ca=e=>new Uint8Array(e),la=$i?e=>{let t=``;for(let n=0;n<e.byteLength;n++)t+=br(e[n]);return btoa(t)}:e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64`),ua=e=>{let t=ca(e.byteLength);return t.set(e),t},da=e=>Nr(t=>Zr(t,e)),fa=class{constructor(e,t){this.left=e,this.right=t}},pa=(e,t)=>new fa(e,t),ma=(e,t)=>e.forEach(e=>t(e.left,e.right)),ha=e=>e.next()>=.5,ga=(e,t,n)=>$n(e.next()*(n+1-t)+t),_a=(e,t,n)=>$n(e.next()*(n+1-t)+t),va=(e,t,n)=>_a(e,t,n),ya=e=>br(va(e,97,122)),ba=(e,t=0,n=20)=>{let r=va(e,t,n),i=``;for(let t=0;t<r;t++)i+=ya(e);return i},xa=(e,t)=>t[va(e,0,t.length-1)],Sa=Symbol(`0schema`),Ca=class{constructor(){this._rerrs=[]}extend(e,t,n,r=null){this._rerrs.push({path:e,expected:t,has:n,message:r})}toString(){let e=[];for(let t=this._rerrs.length-1;t>0;t--){let n=this._rerrs[t];e.push(Ar(` `,(this._rerrs.length-t)*2)+`${n.path==null?``:`[${n.path}] `}${n.has} doesn't match ${n.expected}. ${n.message}`)}return e.join(`
|
|
2
2
|
`)}},wa=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[Fi]?Ii(e,t):Xn(e)?qn(e,e=>Jn(t,t=>wa(e,t))):Li(e)?Ui(e,(e,n)=>wa(e,t[n])):!1,Ta=class{static _dilutes=!1;extends(e){let[t,n]=[this.shape,e.shape];return this.constructor._dilutes&&([n,t]=[t,n]),wa(t,n)}equals(e){return this.constructor===e.constructor&&Xi(this.shape,e.shape)}[Sa](){return!0}[Fi](e){return this.equals(e)}validate(e){return this.check(e)}check(e,t){ai()}get nullable(){return io(this,bo)}get optional(){return new Ia(this)}cast(e){return wo(e,this),e}expect(e){return wo(e,this),e}},Ea=class extends Ta{constructor(e,t){super(),this.shape=e,this._c=t}check(e,t=void 0){let n=e?.constructor===this.shape&&(this._c==null||this._c(e));return!n&&t?.extend(null,this.shape.name,e?.constructor.name,e?.constructor===this.shape?`Check failed`:`Constructor match failed`),n}},Da=(e,t=null)=>new Ea(e,t);Da(Ea);var Oa=class extends Ta{constructor(e){super(),this.shape=e}check(e,t){let n=this.shape(e);return!n&&t?.extend(null,`custom prop`,e?.constructor.name,`failed to check custom prop`),n}},ka=e=>new Oa(e);Da(Oa);var Aa=class extends Ta{constructor(e){super(),this.shape=e}check(e,t){let n=this.shape.some(t=>t===e);return!n&&t?.extend(null,this.shape.join(` | `),e.toString()),n}},ja=(...e)=>new Aa(e),Ma=Da(Aa),Na=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,e=>`\\`+e)),Pa=e=>{if(ho.check(e))return[Na(e)];if(Ma.check(e))return e.shape.map(e=>e+``);if(mo.check(e))return[`[+-]?\\d+.?\\d*`];if(go.check(e))return[`.*`];if(ao.check(e))return e.shape.map(Pa).flat(1);oi()};Da(class extends Ta{constructor(e){super(),this.shape=e,this._r=RegExp(`^`+e.map(Pa).map(e=>`(${e.join(`|`)})`).join(``)+`$`)}check(e,t){let n=this._r.exec(e)!=null;return!n&&t?.extend(null,this._r.toString(),e.toString(),`String doesn't match string template.`),n}});var Fa=Symbol(`optional`),Ia=class extends Ta{constructor(e){super(),this.shape=e}check(e,t){let n=e===void 0||this.shape.check(e);return!n&&t?.extend(null,`undefined (optional)`,`()`),n}get[Fa](){return!0}},La=Da(Ia),Ra=class extends Ta{check(e,t){return t?.extend(null,`never`,typeof e),!1}};new Ra,Da(Ra);var za=class e extends Ta{constructor(e,t=!1){super(),this.shape=e,this._isPartial=t}static _dilutes=!0;get partial(){return new e(this.shape,!0)}check(e,t){return e==null?(t?.extend(null,`object`,`null`),!1):Ui(this.shape,(n,r)=>{let i=this._isPartial&&!Wi(e,r)||n.check(e[r],t);return!i&&t?.extend(r.toString(),n.toString(),typeof e[r],`Object property does not match`),i})}},Ba=e=>new za(e),Va=Da(za),Ha=ka(e=>e!=null&&(e.constructor===Object||e.constructor==null)),Ua=class extends Ta{constructor(e,t){super(),this.shape={keys:e,values:t}}check(e,t){return e!=null&&Ui(e,(n,r)=>{let i=this.shape.keys.check(r,t);return!i&&t?.extend(r+``,`Record`,typeof e,i?`Key doesn't match schema`:`Value doesn't match value`),i&&this.shape.values.check(n,t)})}},Wa=(e,t)=>new Ua(e,t),Ga=Da(Ua),Ka=class extends Ta{constructor(e){super(),this.shape=e}check(e,t){return e!=null&&Ui(this.shape,(n,r)=>{let i=n.check(e[r],t);return!i&&t?.extend(r.toString(),`Tuple`,typeof n),i})}},qa=(...e)=>new Ka(e);Da(Ka);var Ja=class extends Ta{constructor(e){super(),this.shape=e.length===1?e[0]:new ro(e)}check(e,t){let n=Xn(e)&&qn(e,e=>this.shape.check(e));return!n&&t?.extend(null,`Array`,``),n}},Ya=(...e)=>new Ja(e),Xa=Da(Ja),Za=ka(e=>Xn(e)),Qa=class extends Ta{constructor(e,t){super(),this.shape=e,this._c=t}check(e,t){let n=e instanceof this.shape&&(this._c==null||this._c(e));return!n&&t?.extend(null,this.shape.name,e?.constructor.name),n}},$a=(e,t=null)=>new Qa(e,t);Da(Qa);var eo=$a(Ta),to=Da(class extends Ta{constructor(e){super(),this.len=e.length-1,this.args=qa(...e.slice(-1)),this.res=e[this.len]}check(e,t){let n=e.constructor===Function&&e.length<=this.len;return!n&&t?.extend(null,`function`,typeof e),n}}),no=ka(e=>typeof e==`function`);Da(class extends Ta{constructor(e){super(),this.shape=e}check(e,t){let n=qn(this.shape,n=>n.check(e,t));return!n&&t?.extend(null,`Intersectinon`,typeof e),n}},e=>e.shape.length>0);var ro=class extends Ta{static _dilutes=!0;constructor(e){super(),this.shape=e}check(e,t){let n=Jn(this.shape,n=>n.check(e,t));return t?.extend(null,`Union`,typeof e),n}},io=(...e)=>e.findIndex(e=>ao.check(e))>=0?io(...e.map(e=>Co(e)).map(e=>ao.check(e)?e.shape:[e]).flat(1)):e.length===1?e[0]:new ro(e),ao=Da(ro),oo=()=>!0,so=ka(oo),co=Da(Oa,e=>e.shape===oo),lo=ka(e=>typeof e==`bigint`),uo=ka(e=>e===lo),fo=ka(e=>typeof e==`symbol`);ka(e=>e===fo);var po=ka(e=>typeof e==`number`),mo=ka(e=>e===po),ho=ka(e=>typeof e==`string`),go=ka(e=>e===ho),_o=ka(e=>typeof e==`boolean`),vo=ka(e=>e===_o),yo=ja(void 0);Da(Aa,e=>e.shape.length===1&&e.shape[0]===void 0),ja(void 0);var bo=ja(null),xo=Da(Aa,e=>e.shape.length===1&&e.shape[0]===null);Da(Uint8Array),Da(Ea,e=>e.shape===Uint8Array);var So=io(po,ho,bo,yo,lo,_o,fo);(()=>{let e=Ya(so),t=Wa(ho,so),n=io(po,ho,bo,_o,e,t);return e.shape=n,t.shape.values=n,n})();var Co=e=>{if(eo.check(e))return e;if(Ha.check(e)){let t={};for(let n in e)t[n]=Co(e[n]);return Ba(t)}else if(Za.check(e))return io(...e.map(Co));else if(So.check(e))return ja(e);else if(no.check(e))return Da(e);oi()},wo=oa?()=>{}:(e,t)=>{let n=new Ca;if(!t.check(e,n))throw ii(`Expected value to be of type ${t.constructor.name}.\n${n.toString()}`)},To=class{constructor(e){this.patterns=[],this.$state=e}if(e,t){return this.patterns.push({if:Co(e),h:t}),this}else(e){return this.if(so,e)}done(){return(e,t)=>{for(let n=0;n<this.patterns.length;n++){let r=this.patterns[n];if(r.if.check(e))return r.h(e,t)}throw ii(`Unhandled pattern`)}}},Eo=(e=>new To(e))(so).if(mo,(e,t)=>ga(t,vr,_r)).if(go,(e,t)=>ba(t)).if(vo,(e,t)=>ha(t)).if(uo,(e,t)=>BigInt(ga(t,vr,_r))).if(ao,(e,t)=>Do(t,xa(t,e.shape))).if(Va,(e,t)=>{let n={};for(let r in e.shape){let i=e.shape[r];if(La.check(i)){if(ha(t))continue;i=i.shape}n[r]=Eo(i,t)}return n}).if(Xa,(e,t)=>{let n=[],r=_a(t,0,42);for(let i=0;i<r;i++)n.push(Do(t,e.shape));return n}).if(Ma,(e,t)=>xa(t,e.shape)).if(xo,(e,t)=>null).if(to,(e,t)=>{let n=Do(t,e.res);return()=>n}).if(co,(e,t)=>Do(t,xa(t,[po,ho,bo,yo,lo,_o,Ya(po),Wa(io(`a`,`b`,`c`),po)]))).if(Ga,(e,t)=>{let n={},r=ga(t,0,3);for(let i=0;i<r;i++){let r=Do(t,e.shape.keys);n[r]=Do(t,e.shape.values)}return n}).done(),Do=(e,t)=>Eo(Co(t),e),Oo=typeof document<`u`?document:{},ko=e=>Oo.createElement(e),Ao=()=>Oo.createDocumentFragment();ka(e=>e.nodeType===Ho);var jo=e=>Oo.createTextNode(e);typeof DOMParser<`u`&&new DOMParser;var Mo=(e,t)=>(ma(t,(t,n)=>{n===!1?e.removeAttribute(t):n===!0?e.setAttribute(t,``):e.setAttribute(t,n)}),e),No=e=>{let t=Ao();for(let n=0;n<e.length;n++)Ro(t,e[n]);return t},Po=(e,t)=>(Ro(e,No(t)),e),Fo=(e,t=[],n=[])=>Po(Mo(ko(e),t),n);ka(e=>e.nodeType===zo);var Io=jo;ka(e=>e.nodeType===Bo);var Lo=e=>Vn(e,(e,t)=>`${t}:${e};`).join(``),Ro=(e,t)=>e.appendChild(t),zo=Oo.ELEMENT_NODE,Bo=Oo.TEXT_NODE;Oo.CDATA_SECTION_NODE,Oo.COMMENT_NODE;var Vo=Oo.DOCUMENT_NODE;Oo.DOCUMENT_TYPE_NODE;var Ho=Oo.DOCUMENT_FRAGMENT_NODE;ka(e=>e.nodeType===Vo);var Uo=(e=>class{constructor(e){this._=e}destroy(){e(this._)}})(clearTimeout),Wo=(e,t)=>new Uo(setTimeout(t,e)),Go=Symbol,Ko=Go(),qo=Go(),Jo=Go(),Yo=Go(),Xo=Go(),Zo=Go(),Qo=Go(),$o=Go(),es=Go(),ts=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());let t=[],n=[],r=0;for(;r<e.length;r++){let n=e[r];if(n===void 0)break;if(n.constructor===String||n.constructor===Number)t.push(n);else if(n.constructor===Object)break}for(r>0&&n.push(t.join(``));r<e.length;r++){let t=e[r];t instanceof Symbol||n.push(t)}return n};Ai();var ns={[Ko]:pa(`font-weight`,`bold`),[qo]:pa(`font-weight`,`normal`),[Jo]:pa(`color`,`blue`),[Xo]:pa(`color`,`green`),[Yo]:pa(`color`,`grey`),[Zo]:pa(`color`,`red`),[Qo]:pa(`color`,`purple`),[$o]:pa(`color`,`orange`),[es]:pa(`color`,`black`)},rs=sa?e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());let t=[],n=[],r=Rn(),i=[],a=0;for(;a<e.length;a++){let i=e[a],o=ns[i];if(o!==void 0)r.set(o.left,o.right);else{if(i===void 0)break;if(i.constructor===String||i.constructor===Number){let e=Lo(r);a>0||e.length>0?(t.push(`%c`+i),n.push(e)):t.push(i)}else break}}for(a>0&&(i=n,i.unshift(t.join(``)));a<e.length;a++){let t=e[a];t instanceof Symbol||i.push(t)}return i}:ts,is=(...e)=>{console.log(...rs(e)),os.forEach(t=>t.print(e))},as=(...e)=>{console.warn(...rs(e)),e.unshift($o),os.forEach(t=>t.print(e))},os=Un(),ss=e=>({[Symbol.iterator](){return this},next:e}),cs=(e,t)=>ss(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),ls=(e,t)=>ss(()=>{let{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}}),us=class{constructor(e,t){this.clock=e,this.len=t}},ds=class{constructor(){this.clients=new Map}},fs=(e,t,n)=>t.clients.forEach((t,r)=>{let i=e.doc.store.clients.get(r);if(i!=null){let r=i[i.length-1],a=r.id.clock+r.length;for(let r=0,o=t[r];r<t.length&&o.clock<a;o=t[++r])Ac(e,i,o.clock,o.len,n)}}),ps=(e,t)=>{let n=0,r=e.length-1;for(;n<=r;){let i=$n((n+r)/2),a=e[i],o=a.clock;if(o<=t){if(t<o+a.len)return i;n=i+1}else r=i-1}return null},ms=(e,t)=>{let n=e.clients.get(t.client);return n!==void 0&&ps(n,t.clock)!==null},hs=e=>{e.clients.forEach(e=>{e.sort((e,t)=>e.clock-t.clock);let t,n;for(t=1,n=1;t<e.length;t++){let r=e[n-1],i=e[t];r.clock+r.len>=i.clock?e[n-1]=new us(r.clock,nr(r.len,i.clock+i.len-r.clock)):(n<t&&(e[n]=i),n++)}e.length=n})},gs=e=>{let t=new ds;for(let n=0;n<e.length;n++)e[n].clients.forEach((r,i)=>{if(!t.clients.has(i)){let a=r.slice();for(let t=n+1;t<e.length;t++)Gn(a,e[t].clients.get(i)||[]);t.clients.set(i,a)}});return hs(t),t},_s=(e,t,n,r)=>{Bn(e.clients,t,()=>[]).push(new us(n,r))},vs=()=>new ds,ys=e=>{let t=vs();return e.clients.forEach((e,n)=>{let r=[];for(let t=0;t<e.length;t++){let n=e[t];if(n.deleted){let i=n.id.clock,a=n.length;if(t+1<e.length)for(let n=e[t+1];t+1<e.length&&n.deleted;n=e[++t+1])a+=n.length;r.push(new us(i,a))}}r.length>0&&t.clients.set(n,r)}),t},bs=(e,t)=>{Z(e.restEncoder,t.clients.size),Kn(t.clients.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{e.resetDsCurVal(),Z(e.restEncoder,t);let r=n.length;Z(e.restEncoder,r);for(let t=0;t<r;t++){let r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}})},xs=e=>{let t=new ds,n=Q(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();let n=Q(e.restDecoder),r=Q(e.restDecoder);if(r>0){let i=Bn(t.clients,n,()=>[]);for(let t=0;t<r;t++)i.push(new us(e.readDsClock(),e.readDsLen()))}}return t},Ss=(e,t,n)=>{let r=new ds,i=Q(e.restDecoder);for(let a=0;a<i;a++){e.resetDsCurVal();let i=Q(e.restDecoder),a=Q(e.restDecoder),o=n.clients.get(i)||[],s=Sc(n,i);for(let n=0;n<a;n++){let n=e.readDsClock(),a=n+e.readDsLen();if(n<s){s<a&&_s(r,i,s,a-s);let e=wc(o,n),c=o[e];for(!c.deleted&&c.id.clock<n&&(o.splice(e+1,0,qu(t,c,n-c.id.clock)),e++);e<o.length&&(c=o[e++],c.id.clock<a);)c.deleted||(a<c.id.clock+c.length&&o.splice(e,0,qu(t,c,a-c.id.clock)),c.delete(t))}else _s(r,i,n,a-n)}}if(r.clients.size>0){let e=new Ms;return Z(e.restEncoder,0),bs(e,r),e.toUint8Array()}return null},Cs=Ei,ws=class e extends Zn{constructor({guid:e=ki(),collectionid:t=null,gc:n=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:a=!1,shouldLoad:o=!0}={}){super(),this.gc=n,this.gcFilter=r,this.clientID=Cs(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new bc,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=o,this.autoLoad=a,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=ji(e=>{this.on(`load`,()=>{this.isLoaded=!0,e(this)})});let s=()=>ji(e=>{let t=n=>{(n===void 0||n===!0)&&(this.off(`sync`,t),e())};this.on(`sync`,t)});this.on(`sync`,e=>{e===!1&&this.isSynced&&(this.whenSynced=s()),this.isSynced=e===void 0||e===!0,this.isSynced&&!this.isLoaded&&this.emit(`load`,[this])}),this.whenSynced=s()}load(){let e=this._item;e!==null&&!this.shouldLoad&&Rc(e.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Kn(this.subdocs).map(e=>e.guid))}transact(e,t=null){return Rc(this,e,t)}get(e,t=ml){let n=Bn(this.share,e,()=>{let e=new t;return e._integrate(this,null),e}),r=n.constructor;if(t!==ml&&r!==t)if(r===ml){let r=new t;r._map=n._map,n._map.forEach(e=>{for(;e!==null;e=e.left)e.parent=r}),r._start=n._start;for(let e=r._start;e!==null;e=e.right)e.parent=r;return r._length=n._length,this.share.set(e,r),r._integrate(this,null),r}else throw Error(`Type with the name ${e} has already been defined with a different constructor`);return n}getArray(e=``){return this.get(e,Fl)}getText(e=``){return this.get(e,nu)}getMap(e=``){return this.get(e,Rl)}getXmlElement(e=``){return this.get(e,su)}getXmlFragment(e=``){return this.get(e,au)}toJSON(){let e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,Kn(this.subdocs).forEach(e=>e.destroy());let t=this._item;if(t!==null){this._item=null;let n=t.content;n.doc=new e({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,Rc(t.parent.doc,e=>{let 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()}},Ts=class{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return Q(this.restDecoder)}readDsLen(){return Q(this.restDecoder)}},Es=class extends Ts{readLeftID(){return $(Q(this.restDecoder),Q(this.restDecoder))}readRightID(){return $(Q(this.restDecoder),Q(this.restDecoder))}readClient(){return Q(this.restDecoder)}readInfo(){return mi(this.restDecoder)}readString(){return gi(this.restDecoder)}readParentInfo(){return Q(this.restDecoder)===1}readTypeRef(){return Q(this.restDecoder)}readLen(){return Q(this.restDecoder)}readAny(){return yi(this.restDecoder)}readBuf(){return ua(pi(this.restDecoder))}readJSON(){return JSON.parse(gi(this.restDecoder))}readKey(){return gi(this.restDecoder)}},Ds=class{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=Q(this.restDecoder),this.dsCurrVal}readDsLen(){let e=Q(this.restDecoder)+1;return this.dsCurrVal+=e,e}},Os=class extends Ds{constructor(e){super(e),this.keys=[],Q(e),this.keyClockDecoder=new Si(pi(e)),this.clientDecoder=new xi(pi(e)),this.leftClockDecoder=new Si(pi(e)),this.rightClockDecoder=new Si(pi(e)),this.infoDecoder=new bi(pi(e),mi),this.stringDecoder=new Ci(pi(e)),this.parentInfoDecoder=new bi(pi(e),mi),this.typeRefDecoder=new xi(pi(e)),this.lenDecoder=new xi(pi(e))}readLeftID(){return new tc(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new tc(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return yi(this.restDecoder)}readBuf(){return pi(this.restDecoder)}readJSON(){return yi(this.restDecoder)}readKey(){let e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{let e=this.stringDecoder.read();return this.keys.push(e),e}}},ks=class{constructor(){this.restEncoder=Mr()}toUint8Array(){return Fr(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){Z(this.restEncoder,e)}writeDsLen(e){Z(this.restEncoder,e)}},As=class extends ks{writeLeftID(e){Z(this.restEncoder,e.client),Z(this.restEncoder,e.clock)}writeRightID(e){Z(this.restEncoder,e.client),Z(this.restEncoder,e.clock)}writeClient(e){Z(this.restEncoder,e)}writeInfo(e){Rr(this.restEncoder,e)}writeString(e){Hr(this.restEncoder,e)}writeParentInfo(e){Z(this.restEncoder,+!!e)}writeTypeRef(e){Z(this.restEncoder,e)}writeLen(e){Z(this.restEncoder,e)}writeAny(e){Zr(this.restEncoder,e)}writeBuf(e){Wr(this.restEncoder,e)}writeJSON(e){Hr(this.restEncoder,JSON.stringify(e))}writeKey(e){Hr(this.restEncoder,e)}},js=class{constructor(){this.restEncoder=Mr(),this.dsCurrVal=0}toUint8Array(){return Fr(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){let t=e-this.dsCurrVal;this.dsCurrVal=e,Z(this.restEncoder,t)}writeDsLen(e){e===0&&oi(),Z(this.restEncoder,e-1),this.dsCurrVal+=e}},Ms=class extends js{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new ni,this.clientEncoder=new ei,this.leftClockEncoder=new ni,this.rightClockEncoder=new ni,this.infoEncoder=new Qr(Rr),this.stringEncoder=new ri,this.parentInfoEncoder=new Qr(Rr),this.typeRefEncoder=new ei,this.lenEncoder=new ei}toUint8Array(){let e=Mr();return Z(e,0),Wr(e,this.keyClockEncoder.toUint8Array()),Wr(e,this.clientEncoder.toUint8Array()),Wr(e,this.leftClockEncoder.toUint8Array()),Wr(e,this.rightClockEncoder.toUint8Array()),Wr(e,Fr(this.infoEncoder)),Wr(e,this.stringEncoder.toUint8Array()),Wr(e,Fr(this.parentInfoEncoder)),Wr(e,this.typeRefEncoder.toUint8Array()),Wr(e,this.lenEncoder.toUint8Array()),Ur(e,Fr(this.restEncoder)),Fr(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)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){Zr(this.restEncoder,e)}writeBuf(e){Wr(this.restEncoder,e)}writeJSON(e){Zr(this.restEncoder,e)}writeKey(e){let t=this.keyMap.get(e);t===void 0?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t)}},Ns=(e,t,n,r)=>{r=nr(r,t[0].id.clock);let i=wc(t,r);Z(e.restEncoder,t.length-i),e.writeClient(n),Z(e.restEncoder,r);let a=t[i];a.write(e,r-a.id.clock);for(let n=i+1;n<t.length;n++)t[n].write(e,0)},Ps=(e,t,n)=>{let r=new Map;n.forEach((e,n)=>{Sc(t,n)>e&&r.set(n,e)}),xc(t).forEach((e,t)=>{n.has(t)||r.set(t,0)}),Z(e.restEncoder,r.size),Kn(r.entries()).sort((e,t)=>t[0]-e[0]).forEach(([n,r])=>{Ns(e,t.clients.get(n),n,r)})},Fs=(e,t)=>{let n=Rn(),r=Q(e.restDecoder);for(let i=0;i<r;i++){let r=Q(e.restDecoder),i=Array(r),a=e.readClient(),o=Q(e.restDecoder);n.set(a,{i:0,refs:i});for(let n=0;n<r;n++){let r=e.readInfo();switch(31&r){case 0:{let t=e.readLen();i[n]=new gu($(a,o),t),o+=t;break}case 10:{let t=Q(e.restDecoder);i[n]=new ed($(a,o),t),o+=t;break}default:{let s=(r&192)==0,c=new Xu($(a,o),null,(r&128)==128?e.readLeftID():null,null,(r&64)==64?e.readRightID():null,s?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,s&&(r&32)==32?e.readString():null,Zu(e,r));i[n]=c,o+=c.length}}}}return n},Is=(e,t,n)=>{let r=[],i=Kn(n.keys()).sort((e,t)=>e-t);if(i.length===0)return null;let a=()=>{if(i.length===0)return null;let e=n.get(i[i.length-1]);for(;e.refs.length===e.i;)if(i.pop(),i.length>0)e=n.get(i[i.length-1]);else return null;return e},o=a();if(o===null)return null;let s=new bc,c=new Map,l=(e,t)=>{let n=c.get(e);(n==null||n>t)&&c.set(e,t)},u=o.refs[o.i++],d=new Map,f=()=>{for(let e of r){let t=e.id.client,r=n.get(t);r?(r.i--,s.clients.set(t,r.refs.slice(r.i)),n.delete(t),r.i=0,r.refs=[]):s.clients.set(t,[e]),i=i.filter(e=>e!==t)}r.length=0};for(;;){if(u.constructor!==ed){let i=Bn(d,u.id.client,()=>Sc(t,u.id.client))-u.id.clock;if(i<0)r.push(u),l(u.id.client,u.id.clock-1),f();else{let a=u.getMissing(e,t);if(a!==null){r.push(u);let e=n.get(a)||{refs:[],i:0};if(e.refs.length===e.i)l(a,Sc(t,a)),f();else{u=e.refs[e.i++];continue}}else (i===0||i<u.length)&&(u.integrate(e,i),d.set(u.id.client,u.id.clock+u.length))}}if(r.length>0)u=r.pop();else if(o!==null&&o.i<o.refs.length)u=o.refs[o.i++];else{if(o=a(),o===null)break;u=o.refs[o.i++]}}if(s.clients.size>0){let e=new Ms;return Ps(e,s,new Map),Z(e.restEncoder,0),{missing:c,update:e.toUint8Array()}}return null},Ls=(e,t)=>Ps(e,t.doc.store,t.beforeState),Rs=(e,t,n,r=new Os(e))=>Rc(t,e=>{e.local=!1;let t=!1,n=e.doc,i=n.store,a=Is(e,i,Fs(r,n)),o=i.pendingStructs;if(o){for(let[e,n]of o.missing)if(n<Sc(i,e)){t=!0;break}if(a){for(let[e,t]of a.missing){let n=o.missing.get(e);(n==null||n>t)&&o.missing.set(e,t)}o.update=Jc([o.update,a.update])}}else i.pendingStructs=a;let s=Ss(r,e,i);if(i.pendingDs){let t=new Os(ui(i.pendingDs));Q(t.restDecoder);let n=Ss(t,e,i);s&&n?i.pendingDs=Jc([s,n]):i.pendingDs=s||n}else i.pendingDs=s;if(t){let t=i.pendingStructs.update;i.pendingStructs=null,zs(e.doc,t)}},n,!1),zs=(e,t,n,r=Os)=>{let i=ui(t);Rs(i,e,n,new r(i))},Bs=(e,t,n)=>zs(e,t,n,Es),Vs=(e,t,n=new Map)=>{Ps(e,t.store,n),bs(e,ys(t.store))},Hs=(e,t=new Uint8Array([0]),n=new Ms)=>{Vs(n,e,Gs(t));let r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Yc(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===As)return Kc(r.map((e,t)=>t===0?e:el(e)));if(n.constructor===Ms)return Jc(r)}return r[0]},Us=(e,t)=>Hs(e,t,new As),Ws=e=>{let t=new Map,n=Q(e.restDecoder);for(let r=0;r<n;r++){let n=Q(e.restDecoder),r=Q(e.restDecoder);t.set(n,r)}return t},Gs=e=>Ws(new Ts(ui(e))),Ks=(e,t)=>(Z(e.restEncoder,t.size),Kn(t.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{Z(e.restEncoder,t),Z(e.restEncoder,n)}),e),qs=(e,t)=>Ks(e,xc(t.store)),Js=(e,t=new js)=>(e instanceof Map?Ks(t,e):qs(t,e),t.toUint8Array()),Ys=e=>Js(e,new ks),Xs=class{constructor(){this.l=[]}},Zs=()=>new Xs,Qs=(e,t)=>e.l.push(t),$s=(e,t)=>{let n=e.l,r=n.length;e.l=n.filter(e=>t!==e),r===e.l.length&&console.error(`[yjs] Tried to remove event handler that doesn't exist.`)},ec=(e,t,n)=>Ji(e.l,[t,n]),tc=class{constructor(e,t){this.client=e,this.clock=t}},nc=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,$=(e,t)=>new tc(e,t),rc=e=>{for(let[t,n]of e.doc.share.entries())if(n===e)return t;throw oi()},ic=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1},ac=class{constructor(e,t,n,r=0){this.type=e,this.tname=t,this.item=n,this.assoc=r}},oc=e=>{let t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},sc=e=>new ac(e.type==null?null:$(e.type.client,e.type.clock),e.tname??null,e.item==null?null:$(e.item.client,e.item.clock),e.assoc==null?0:e.assoc),cc=class{constructor(e,t,n=0){this.type=e,this.index=t,this.assoc=n}},lc=(e,t,n=0)=>new cc(e,t,n),uc=(e,t,n)=>{let r=null,i=null;return e._item===null?i=rc(e):r=$(e._item.id.client,e._item.id.clock),new ac(r,i,t,n)},dc=(e,t,n=0)=>{let r=e._start;if(n<0){if(t===0)return uc(e,null,n);t--}for(;r!==null;){if(!r.deleted&&r.countable){if(r.length>t)return uc(e,$(r.id.client,r.id.clock+t),n);t-=r.length}if(r.right===null&&n<0)return uc(e,r.lastId,n);r=r.right}return uc(e,null,n)},fc=(e,t)=>{let n=Tc(e,t);return{item:n,diff:t.clock-n.id.clock}},pc=(e,t,n=!0)=>{let r=t.store,i=e.item,a=e.type,o=e.tname,s=e.assoc,c=null,l=0;if(i!==null){if(Sc(r,i.client)<=i.clock)return null;let e=n?Gu(r,i):fc(r,i),t=e.item;if(!(t instanceof Xu))return null;if(c=t.parent,c._item===null||!c._item.deleted){l=t.deleted||!t.countable?0:e.diff+(s>=0?0:1);let n=t.left;for(;n!==null;)!n.deleted&&n.countable&&(l+=n.length),n=n.left}}else{if(o!==null)c=t.get(o);else if(a!==null){if(Sc(r,a.client)<=a.clock)return null;let{item:e}=n?Gu(r,a):{item:Tc(r,a)};if(e instanceof Xu&&e.content instanceof Uu)c=e.content.type;else return null}else throw oi();l=s>=0?c._length:0}return lc(c,l,e.assoc)},mc=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&nc(e.item,t.item)&&nc(e.type,t.type)&&e.assoc===t.assoc,hc=class{constructor(e,t){this.ds=e,this.sv=t}},gc=(e,t)=>new hc(e,t);gc(vs(),new Map);var _c=e=>gc(ys(e.store),xc(e.store)),vc=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!ms(t.ds,e.id),yc=(e,t)=>{let n=Bn(e.meta,yc,Un),r=e.doc.store;n.has(t)||(t.sv.forEach((t,n)=>{t<Sc(r,n)&&Dc(e,$(n,t))}),fs(e,t.ds,e=>{}),n.add(t))},bc=class{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}},xc=e=>{let t=new Map;return e.clients.forEach((e,n)=>{let r=e[e.length-1];t.set(n,r.id.clock+r.length)}),t},Sc=(e,t)=>{let n=e.clients.get(t);if(n===void 0)return 0;let r=n[n.length-1];return r.id.clock+r.length},Cc=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{let e=n[n.length-1];if(e.id.clock+e.length!==t.id.clock)throw oi()}n.push(t)},wc=(e,t)=>{let n=0,r=e.length-1,i=e[r],a=i.id.clock;if(a===t)return r;let o=$n(t/(a+i.length-1)*r);for(;n<=r;){if(i=e[o],a=i.id.clock,a<=t){if(t<a+i.length)return o;n=o+1}else r=o-1;o=$n((n+r)/2)}throw oi()},Tc=(e,t)=>{let n=e.clients.get(t.client);return n[wc(n,t.clock)]},Ec=(e,t,n)=>{let r=wc(t,n),i=t[r];return i.id.clock<n&&i instanceof Xu?(t.splice(r+1,0,qu(e,i,n-i.id.clock)),r+1):r},Dc=(e,t)=>{let n=e.doc.store.clients.get(t.client);return n[Ec(e,n,t.clock)]},Oc=(e,t,n)=>{let r=t.clients.get(n.client),i=wc(r,n.clock),a=r[i];return n.clock!==a.id.clock+a.length-1&&a.constructor!==gu&&r.splice(i+1,0,qu(e,a,n.clock-a.id.clock+1)),a},kc=(e,t,n)=>{let r=e.clients.get(t.id.client);r[wc(r,t.id.clock)]=n},Ac=(e,t,n,r,i)=>{if(r===0)return;let a=n+r,o=Ec(e,t,n),s;do s=t[o++],a<s.id.clock+s.length&&Ec(e,t,a),i(s);while(o<t.length&&t[o].id.clock<a)},jc=class{constructor(e,t,n){this.doc=e,this.deleteSet=new ds,this.beforeState=xc(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}},Mc=(e,t)=>t.deleteSet.clients.size===0&&!Hn(t.afterState,(e,n)=>t.beforeState.get(n)!==e)?!1:(hs(t.deleteSet),Ls(e,t),bs(e,t.deleteSet),!0),Nc=(e,t,n)=>{let r=t._item;(r===null||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&Bn(e.changed,t,Un).add(n)},Pc=(e,t)=>{let n=e[t],r=e[t-1],i=t;for(;i>0;n=r,r=e[--i-1]){if(r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n)){n instanceof Xu&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);continue}break}let a=t-i;return a&&e.splice(t+1-a,a),a},Fc=(e,t,n)=>{for(let[r,i]of e.clients.entries()){let e=t.clients.get(r);for(let r=i.length-1;r>=0;r--){let a=i[r],o=a.clock+a.len;for(let r=wc(e,a.clock),i=e[r];r<e.length&&i.id.clock<o;i=e[++r]){let i=e[r];if(a.clock+a.len<=i.id.clock)break;i instanceof Xu&&i.deleted&&!i.keep&&n(i)&&i.gc(t,!1)}}}},Ic=(e,t)=>{e.clients.forEach((e,n)=>{let r=t.clients.get(n);for(let t=e.length-1;t>=0;t--){let n=e[t],i=tr(r.length-1,1+wc(r,n.clock+n.len-1));for(let e=i,t=r[e];e>0&&t.id.clock>=n.clock;t=r[e])e-=1+Pc(r,e)}})},Lc=(e,t)=>{if(t<e.length){let n=e[t],r=n.doc,i=r.store,a=n.deleteSet,o=n._mergeStructs;try{hs(a),n.afterState=xc(n.doc.store),r.emit(`beforeObserverCalls`,[n,r]);let e=[];n.changed.forEach((t,r)=>e.push(()=>{(r._item===null||!r._item.deleted)&&r._callObserver(n,t)})),e.push(()=>{n.changedParentTypes.forEach((t,r)=>{r._dEH.l.length>0&&(r._item===null||!r._item.deleted)&&(t=t.filter(e=>e.target._item===null||!e.target._item.deleted),t.forEach(e=>{e.currentTarget=r,e._path=null}),t.sort((e,t)=>e.path.length-t.path.length),e.push(()=>{ec(r._dEH,t,n)}))}),e.push(()=>r.emit(`afterTransaction`,[n,r])),e.push(()=>{n._needFormattingCleanup&&$l(n)})}),Ji(e,[])}finally{r.gc&&Fc(a,i,r.gcFilter),Ic(a,i),n.afterState.forEach((e,t)=>{let r=n.beforeState.get(t)||0;if(r!==e){let e=i.clients.get(t),n=nr(wc(e,r),1);for(let t=e.length-1;t>=n;)t-=1+Pc(e,t)}});for(let e=o.length-1;e>=0;e--){let{client:t,clock:n}=o[e].id,r=i.clients.get(t),a=wc(r,n);a+1<r.length&&Pc(r,a+1)>1||a>0&&Pc(r,a)}if(!n.local&&n.afterState.get(r.clientID)!==n.beforeState.get(r.clientID)&&(is($o,Ko,`[yjs] `,qo,Zo,`Changed the client-id because another client seems to be using it.`),r.clientID=Cs()),r.emit(`afterTransactionCleanup`,[n,r]),r._observers.has(`update`)){let e=new As;Mc(e,n)&&r.emit(`update`,[e.toUint8Array(),n.origin,r,n])}if(r._observers.has(`updateV2`)){let e=new Ms;Mc(e,n)&&r.emit(`updateV2`,[e.toUint8Array(),n.origin,r,n])}let{subdocsAdded:s,subdocsLoaded:c,subdocsRemoved:l}=n;(s.size>0||l.size>0||c.size>0)&&(s.forEach(e=>{e.clientID=r.clientID,e.collectionid??=r.collectionid,r.subdocs.add(e)}),l.forEach(e=>r.subdocs.delete(e)),r.emit(`subdocs`,[{loaded:c,added:s,removed:l},r,n]),l.forEach(e=>e.destroy())),e.length<=t+1?(r._transactionCleanups=[],r.emit(`afterAllTransactions`,[r,e])):Lc(e,t+1)}}},Rc=(e,t,n=null,r=!0)=>{let i=e._transactionCleanups,a=!1,o=null;e._transaction===null&&(a=!0,e._transaction=new jc(e,n,r),i.push(e._transaction),i.length===1&&e.emit(`beforeAllTransactions`,[e]),e.emit(`beforeTransaction`,[e._transaction,e]));try{o=t(e._transaction)}finally{if(a){let t=e._transaction===i[0];e._transaction=null,t&&Lc(i,0)}}return o},zc=class{constructor(e,t){this.insertions=t,this.deletions=e,this.meta=new Map}},Bc=(e,t,n)=>{fs(e,n.deletions,n=>{n instanceof Xu&&t.scope.some(t=>t===e.doc||ic(t,n))&&Ku(n,!1)})},Vc=(e,t,n)=>{let r=null,i=e.doc,a=e.scope;Rc(i,n=>{for(;t.length>0&&e.currStackItem===null;){let r=i.store,o=t.pop(),s=new Set,c=[],l=!1;fs(n,o.insertions,e=>{if(e instanceof Xu){if(e.redone!==null){let{item:t,diff:i}=Gu(r,e.id);i>0&&(t=Dc(n,$(t.id.client,t.id.clock+i))),e=t}!e.deleted&&a.some(t=>t===n.doc||ic(t,e))&&c.push(e)}}),fs(n,o.deletions,e=>{e instanceof Xu&&a.some(t=>t===n.doc||ic(t,e))&&!ms(o.insertions,e.id)&&s.add(e)}),s.forEach(t=>{l=Yu(n,t,s,o.insertions,e.ignoreRemoteMapChanges,e)!==null||l});for(let t=c.length-1;t>=0;t--){let 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);let o=e.currStackItem;if(o!=null){let t=r.changedParentTypes;e.emit(`stack-item-popped`,[{stackItem:o,type:n,changedParentTypes:t,origin:e},e]),e.currStackItem=null}return o},Hc=class extends Zn{constructor(e,{captureTimeout:t=500,captureTransaction:n=e=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:a=!1,doc:o=Xn(e)?e[0].doc:e instanceof ws?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=a,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;let t=this.undoing,n=this.redoing,r=t?this.redoStack:this.undoStack;t?this.stopCapturing():n||this.clear(!1,!0);let i=new ds;e.afterState.forEach((t,n)=>{let r=e.beforeState.get(n)||0,a=t-r;a>0&&_s(i,n,r,a)});let a=Ai(),o=!1;if(this.lastChange>0&&a-this.lastChange<this.captureTimeout&&r.length>0&&!t&&!n){let t=r[r.length-1];t.deletions=gs([t.deletions,e.deleteSet]),t.insertions=gs([t.insertions,i])}else r.push(new zc(e.deleteSet,i)),o=!0;!t&&!n&&(this.lastChange=a),fs(e,e.deleteSet,t=>{t instanceof Xu&&this.scope.some(n=>n===e.doc||ic(n,t))&&Ku(t,!0)});let s=[{stackItem:r[r.length-1],origin:e.origin,type:t?`redo`:`undo`,changedParentTypes:e.changedParentTypes},this];o?this.emit(`stack-item-added`,s):this.emit(`stack-item-updated`,s)},this.doc.on(`afterTransaction`,this.afterTransactionHandler),this.doc.on(`destroy`,()=>{this.destroy()})}addToScope(e){let t=new Set(this.scope);e=Xn(e)?e:[e],e.forEach(e=>{t.has(e)||(t.add(e),(e instanceof ml?e.doc!==this.doc:e!==this.doc)&&as(`[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=>Bc(n,this,e)),this.undoStack=[]),t&&(this.redoStack.forEach(e=>Bc(n,this,e)),this.redoStack=[]),this.emit(`stack-cleared`,[{undoStackCleared:e,redoStackCleared:t}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let e;try{e=Vc(this,this.undoStack,`undo`)}finally{this.undoing=!1}return e}redo(){this.redoing=!0;let e;try{e=Vc(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()}};function*Uc(e){let t=Q(e.restDecoder);for(let n=0;n<t;n++){let t=Q(e.restDecoder),n=e.readClient(),r=Q(e.restDecoder);for(let i=0;i<t;i++){let t=e.readInfo();if(t===10){let t=Q(e.restDecoder);yield new ed($(n,r),t),r+=t}else if(31&t){let i=(t&192)==0,a=new Xu($(n,r),null,(t&128)==128?e.readLeftID():null,null,(t&64)==64?e.readRightID():null,i?e.readParentInfo()?e.readString():e.readLeftID():null,i&&(t&32)==32?e.readString():null,Zu(e,t));yield a,r+=a.length}else{let t=e.readLen();yield new gu($(n,r),t),r+=t}}}}var Wc=class{constructor(e,t){this.gen=Uc(e),this.curr=null,this.done=!1,this.filterSkips=t,this.next()}next(){do this.curr=this.gen.next().value||null;while(this.filterSkips&&this.curr!==null&&this.curr.constructor===ed);return this.curr}},Gc=class{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}},Kc=e=>Jc(e,Es,As),qc=(e,t)=>{if(e.constructor===gu){let{client:n,clock:r}=e.id;return new gu($(n,r+t),e.length-t)}else if(e.constructor===ed){let{client:n,clock:r}=e.id;return new ed($(n,r+t),e.length-t)}else{let n=e,{client:r,clock:i}=n.id;return new Xu($(r,i+t),null,$(r,i+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Jc=(e,t=Os,n=Ms)=>{if(e.length===1)return e[0];let r=e.map(e=>new t(ui(e))),i=r.map(e=>new Wc(e,!0)),a=null,o=new n,s=new Gc(o);for(;i=i.filter(e=>e.curr!==null),i.sort((e,t)=>{if(e.curr.id.client===t.curr.id.client){let n=e.curr.id.clock-t.curr.id.clock;return n===0?e.curr.constructor===t.curr.constructor?0:e.curr.constructor===ed?1:-1:n}else return t.curr.id.client-e.curr.id.client}),i.length!==0;){let e=i[0],t=e.curr.id.client;if(a!==null){let n=e.curr,r=!1;for(;n!==null&&n.id.clock+n.length<=a.struct.id.clock+a.struct.length&&n.id.client>=a.struct.id.client;)n=e.next(),r=!0;if(n===null||n.id.client!==t||r&&n.id.clock>a.struct.id.clock+a.struct.length)continue;if(t!==a.struct.id.client)Zc(s,a.struct,a.offset),a={struct:n,offset:0},e.next();else if(a.struct.id.clock+a.struct.length<n.id.clock)if(a.struct.constructor===ed)a.struct.length=n.id.clock+n.length-a.struct.id.clock;else{Zc(s,a.struct,a.offset);let e=n.id.clock-a.struct.id.clock-a.struct.length;a={struct:new ed($(t,a.struct.id.clock+a.struct.length),e),offset:0}}else{let t=a.struct.id.clock+a.struct.length-n.id.clock;t>0&&(a.struct.constructor===ed?a.struct.length-=t:n=qc(n,t)),a.struct.mergeWith(n)||(Zc(s,a.struct,a.offset),a={struct:n,offset:0},e.next())}}else a={struct:e.curr,offset:0},e.next();for(let n=e.curr;n!==null&&n.id.client===t&&n.id.clock===a.struct.id.clock+a.struct.length&&n.constructor!==ed;n=e.next())Zc(s,a.struct,a.offset),a={struct:n,offset:0}}return a!==null&&(Zc(s,a.struct,a.offset),a=null),Qc(s),bs(o,gs(r.map(e=>xs(e)))),o.toUint8Array()},Yc=(e,t,n=Os,r=Ms)=>{let i=Gs(t),a=new r,o=new Gc(a),s=new n(ui(e)),c=new Wc(s,!1);for(;c.curr;){let e=c.curr,t=e.id.client,n=i.get(t)||0;if(c.curr.constructor===ed){c.next();continue}if(e.id.clock+e.length>n)for(Zc(o,e,nr(n-e.id.clock,0)),c.next();c.curr&&c.curr.id.client===t;)Zc(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===t&&c.curr.id.clock+c.curr.length<=n;)c.next()}return Qc(o),bs(a,xs(s)),a.toUint8Array()},Xc=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:Fr(e.encoder.restEncoder)}),e.encoder.restEncoder=Mr(),e.written=0)},Zc=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&Xc(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),Z(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},Qc=e=>{Xc(e);let t=e.encoder.restEncoder;Z(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){let r=e.clientStructs[n];Z(t,r.written),Ur(t,r.restEncoder)}},$c=(e,t,n,r)=>{let i=new n(ui(e)),a=new Wc(i,!1),o=new r,s=new Gc(o);for(let e=a.curr;e!==null;e=a.next())Zc(s,t(e),0);return Qc(s),bs(o,xs(i)),o.toUint8Array()},el=e=>$c(e,Yi,Os,As),tl=`You must not compute changes after the event-handler fired.`,nl=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||=rl(this.currentTarget,this.target)}deletes(e){return ms(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw ii(tl);let e=new Map,t=this.target;this.transaction.changed.get(t).forEach(n=>{if(n!==null){let r=t._map.get(n),i,a;if(this.adds(r)){let e=r.left;for(;e!==null&&this.adds(e);)e=e.left;if(this.deletes(r))if(e!==null&&this.deletes(e))i=`delete`,a=Wn(e.content.getContent());else return;else e!==null&&this.deletes(e)?(i=`update`,a=Wn(e.content.getContent())):(i=`add`,a=void 0)}else if(this.deletes(r))i=`delete`,a=Wn(r.content.getContent());else return;e.set(n,{action:i,oldValue:a})}}),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(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw ii(tl);let t=this.target,n=Un(),r=Un(),i=[];if(e={added:n,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(t).has(null)){let e=null,a=()=>{e&&i.push(e)};for(let i=t._start;i!==null;i=i.right)i.deleted?this.deletes(i)&&!this.adds(i)&&((e===null||e.delete===void 0)&&(a(),e={delete:0}),e.delete+=i.length,r.add(i)):this.adds(i)?((e===null||e.insert===void 0)&&(a(),e={insert:[]}),e.insert=e.insert.concat(i.content.getContent()),n.add(i)):((e===null||e.retain===void 0)&&(a(),e={retain:0}),e.retain+=i.length);e!==null&&e.retain===void 0&&a()}this._changes=e}return e}},rl=(e,t)=>{let n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let e=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(e+=r.length),r=r.right;n.unshift(e)}t=t._item.parent}return n},il=()=>{as(`Invalid access: Add Yjs type to a document before reading data.`)},al=80,ol=0,sl=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=ol++}},cl=e=>{e.timestamp=ol++},ll=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=ol++},ul=(e,t,n)=>{if(e.length>=al){let r=e.reduce((e,t)=>e.timestamp<t.timestamp?e:t);return ll(r,t,n),r}else{let r=new sl(t,n);return e.push(r),r}},dl=(e,t)=>{if(e._start===null||t===0||e._searchMarker===null)return null;let n=e._searchMarker.length===0?null:e._searchMarker.reduce((e,n)=>er(t-e.index)<er(t-n.index)?e:n),r=e._start,i=0;for(n!==null&&(r=n.p,i=n.index,cl(n));r.right!==null&&i<t;){if(!r.deleted&&r.countable){if(t<i+r.length)break;i+=r.length}r=r.right}for(;r.left!==null&&i>t;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;r.left!==null&&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 n!==null&&er(n.index-i)<r.parent.length/al?(ll(n,r,i),n):ul(e._searchMarker,r,i)},fl=(e,t,n)=>{for(let r=e.length-1;r>=0;r--){let 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(t===null||t.marker===!0){e.splice(r,1);continue}i.p=t,t.marker=!0}(t<i.index||n>0&&t===i.index)&&(i.index=nr(t,i.index+n))}},pl=(e,t,n)=>{let r=e,i=t.changedParentTypes;for(;Bn(i,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;ec(r._eH,n,t)},ml=class{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Zs(),this._dEH=Zs(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw ai()}clone(){throw ai()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){Qs(this._eH,e)}observeDeep(e){Qs(this._dEH,e)}unobserve(e){$s(this._eH,e)}unobserveDeep(e){$s(this._dEH,e)}toJSON(){}},hl=(e,t,n)=>{e.doc??il(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let r=n-t,i=[],a=e._start;for(;a!==null&&r>0;){if(a.countable&&!a.deleted){let e=a.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}}a=a.right}return i},gl=e=>{e.doc??il();let t=[],n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){let e=n.content.getContent();for(let n=0;n<e.length;n++)t.push(e[n])}n=n.right}return t},_l=(e,t)=>{let n=[],r=e._start;for(;r!==null;){if(r.countable&&vc(r,t)){let e=r.content.getContent();for(let t=0;t<e.length;t++)n.push(e[t])}r=r.right}return n},vl=(e,t)=>{let n=0,r=e._start;for(e.doc??il();r!==null;){if(r.countable&&!r.deleted){let i=r.content.getContent();for(let r=0;r<i.length;r++)t(i[r],n++,e)}r=r.right}},yl=(e,t)=>{let n=[];return vl(e,(r,i)=>{n.push(t(r,i,e))}),n},bl=e=>{let t=e._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),r=0,t=t.right}let e=n[r++];return n.length<=r&&(n=null),{done:!1,value:e}}}},xl=(e,t)=>{e.doc??il();let n=dl(e,t),r=e._start;for(n!==null&&(r=n.p,t-=n.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(t<r.length)return r.content.getContent()[t];t-=r.length}},Sl=(e,t,n,r)=>{let i=n,a=e.doc,o=a.clientID,s=a.store,c=n===null?t._start:n.right,l=[],u=()=>{l.length>0&&(i=new Xu($(o,Sc(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new ju(l)),i.integrate(e,0),l=[])};r.forEach(n=>{if(n===null)l.push(n);else switch(n.constructor){case Number:case Object:case Boolean:case Array:case String:l.push(n);break;default:switch(u(),n.constructor){case Uint8Array:case ArrayBuffer:i=new Xu($(o,Sc(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new _u(new Uint8Array(n))),i.integrate(e,0);break;case ws:i=new Xu($(o,Sc(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Su(n)),i.integrate(e,0);break;default:if(n instanceof ml)i=new Xu($(o,Sc(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Uu(n)),i.integrate(e,0);else throw Error(`Unexpected content type in insert operation`)}}}),u()},Cl=()=>ii(`Length exceeded!`),wl=(e,t,n,r)=>{if(n>t._length)throw Cl();if(n===0)return t._searchMarker&&fl(t._searchMarker,n,r.length),Sl(e,t,null,r);let i=n,a=dl(t,n),o=t._start;for(a!==null&&(o=a.p,n-=a.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n<o.length&&Dc(e,$(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&fl(t._searchMarker,i,r.length),Sl(e,t,o,r)},Tl=(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;return Sl(e,t,r,n)},El=(e,t,n,r)=>{if(r===0)return;let i=n,a=r,o=dl(t,n),s=t._start;for(o!==null&&(s=o.p,n-=o.index);s!==null&&n>0;s=s.right)!s.deleted&&s.countable&&(n<s.length&&Dc(e,$(s.id.client,s.id.clock+n)),n-=s.length);for(;r>0&&s!==null;)s.deleted||(r<s.length&&Dc(e,$(s.id.client,s.id.clock+r)),s.delete(e),r-=s.length),s=s.right;if(r>0)throw Cl();t._searchMarker&&fl(t._searchMarker,i,-a+r)},Dl=(e,t,n)=>{let r=t._map.get(n);r!==void 0&&r.delete(e)},Ol=(e,t,n,r)=>{let i=t._map.get(n)||null,a=e.doc,o=a.clientID,s;if(r==null)s=new ju([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:s=new ju([r]);break;case Uint8Array:s=new _u(r);break;case ws:s=new Su(r);break;default:if(r instanceof ml)s=new Uu(r);else throw Error(`Unexpected content type`)}new Xu($(o,Sc(a.store,o)),i,i&&i.lastId,null,null,t,n,s).integrate(e,0)},kl=(e,t)=>{e.doc??il();let n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},Al=e=>{let t={};return e.doc??il(),e._map.forEach((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])}),t},jl=(e,t)=>{e.doc??il();let n=e._map.get(t);return n!==void 0&&!n.deleted},Ml=(e,t)=>{let n={};return e._map.forEach((e,r)=>{let i=e;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&vc(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},Nl=e=>(e.doc??il(),cs(e._map.entries(),e=>!e[1].deleted)),Pl=class extends nl{},Fl=class e extends ml{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){let 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(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof ml?e.clone():e)),t}get length(){return this.doc??il(),this._length}_callObserver(e,t){super._callObserver(e,t),pl(this,e,new Pl(this,e))}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):Rc(this.doc,n=>{wl(n,this,e,t)})}push(e){this.doc===null?this._prelimContent.push(...e):Rc(this.doc,t=>{Tl(t,this,e)})}unshift(e){this.insert(0,e)}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):Rc(this.doc,n=>{El(n,this,e,t)})}get(e){return xl(this,e)}toArray(){return gl(this)}slice(e=0,t=this.length){return hl(this,e,t)}toJSON(){return this.map(e=>e instanceof ml?e.toJSON():e)}map(e){return yl(this,e)}forEach(e){vl(this,e)}[Symbol.iterator](){return bl(this)}_write(e){e.writeTypeRef(Iu)}},Il=e=>new Fl,Ll=class extends nl{constructor(e,t,n){super(e,t),this.keysChanged=n}},Rl=class e extends ml{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=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(){let t=new e;return this.forEach((e,n)=>{t.set(n,e instanceof ml?e.clone():e)}),t}_callObserver(e,t){pl(this,e,new Ll(this,e,t))}toJSON(){this.doc??il();let e={};return this._map.forEach((t,n)=>{if(!t.deleted){let r=t.content.getContent()[t.length-1];e[n]=r instanceof ml?r.toJSON():r}}),e}get size(){return[...Nl(this)].length}keys(){return ls(Nl(this),e=>e[0])}values(){return ls(Nl(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return ls(Nl(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??il(),this._map.forEach((t,n)=>{t.deleted||e(t.content.getContent()[t.length-1],n,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc===null?this._prelimContent.delete(e):Rc(this.doc,t=>{Dl(t,this,e)})}set(e,t){return this.doc===null?this._prelimContent.set(e,t):Rc(this.doc,n=>{Ol(n,this,e,t)}),t}get(e){return kl(this,e)}has(e){return jl(this,e)}clear(){this.doc===null?this._prelimContent.clear():Rc(this.doc,e=>{this.forEach(function(t,n,r){Dl(e,r,n)})})}_write(e){e.writeTypeRef(Lu)}},zl=e=>new Rl,Bl=(e,t)=>e===t||typeof e==`object`&&typeof t==`object`&&e&&t&&Gi(e,t),Vl=class{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){switch(this.right===null&&oi(),this.right.content.constructor){case Eu:this.right.deleted||Gl(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}},Hl=(e,t,n)=>{for(;t.right!==null&&n>0;){switch(t.right.content.constructor){case Eu:t.right.deleted||Gl(t.currentAttributes,t.right.content);break;default:t.right.deleted||(n<t.right.length&&Dc(e,$(t.right.id.client,t.right.id.clock+n)),t.index+=t.right.length,n-=t.right.length);break}t.left=t.right,t.right=t.right.right}return t},Ul=(e,t,n,r)=>{let i=new Map,a=r?dl(t,n):null;return a?Hl(e,new Vl(a.p.left,a.p,a.index,i),n-a.index):Hl(e,new Vl(null,t._start,0,i),n)},Wl=(e,t,n,r)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===Eu&&Bl(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();let i=e.doc,a=i.clientID;r.forEach((r,o)=>{let s=n.left,c=n.right,l=new Xu($(a,Sc(i.store,a)),s,s&&s.lastId,c,c&&c.id,t,null,new Eu(o,r));l.integrate(e,0),n.right=l,n.forward()})},Gl=(e,t)=>{let{key:n,value:r}=t;r===null?e.delete(n):e.set(n,r)},Kl=(e,t)=>{for(;e.right!==null&&(e.right.deleted||e.right.content.constructor===Eu&&Bl(t[e.right.content.key]??null,e.right.content.value));)e.forward()},ql=(e,t,n,r)=>{let i=e.doc,a=i.clientID,o=new Map;for(let s in r){let c=r[s],l=n.currentAttributes.get(s)??null;if(!Bl(l,c)){o.set(s,l);let{left:r,right:u}=n;n.right=new Xu($(a,Sc(i.store,a)),r,r&&r.lastId,u,u&&u.id,t,null,new Eu(s,c)),n.right.integrate(e,0),n.forward()}}return o},Jl=(e,t,n,r,i)=>{n.currentAttributes.forEach((e,t)=>{i[t]===void 0&&(i[t]=null)});let a=e.doc,o=a.clientID;Kl(n,i);let s=ql(e,t,n,i),c=r.constructor===String?new Nu(r):r instanceof ml?new Uu(r):new wu(r),{left:l,right:u,index:d}=n;t._searchMarker&&fl(t._searchMarker,n.index,c.getLength()),u=new Xu($(o,Sc(a.store,o)),l,l&&l.lastId,u,u&&u.id,t,null,c),u.integrate(e,0),n.right=u,n.index=d,n.forward(),Wl(e,t,n,s)},Yl=(e,t,n,r,i)=>{let a=e.doc,o=a.clientID;Kl(n,i);let s=ql(e,t,n,i);iterationLoop:for(;n.right!==null&&(r>0||s.size>0&&(n.right.deleted||n.right.content.constructor===Eu));){if(!n.right.deleted)switch(n.right.content.constructor){case Eu:{let{key:t,value:a}=n.right.content,o=i[t];if(o!==void 0){if(Bl(o,a))s.delete(t);else{if(r===0)break iterationLoop;s.set(t,a)}n.right.delete(e)}else n.currentAttributes.set(t,a);break}default:r<n.right.length&&Dc(e,$(n.right.id.client,n.right.id.clock+r)),r-=n.right.length;break}n.forward()}if(r>0){let i=``;for(;r>0;r--)i+=`
|
|
3
3
|
`;n.right=new Xu($(o,Sc(a.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Nu(i)),n.right.integrate(e,0),n.forward()}Wl(e,t,n,s)},Xl=(e,t,n,r,i)=>{let a=t,o=Rn();for(;a&&(!a.countable||a.deleted);){if(!a.deleted&&a.content.constructor===Eu){let e=a.content;o.set(e.key,e)}a=a.right}let s=0,c=!1;for(;t!==a;){if(n===t&&(c=!0),!t.deleted){let n=t.content;switch(n.constructor){case Eu:{let{key:a,value:l}=n,u=r.get(a)??null;(o.get(a)!==n||u===l)&&(t.delete(e),s++,!c&&(i.get(a)??null)===l&&u!==l&&(u===null?i.delete(a):i.set(a,u))),!c&&!t.deleted&&Gl(i,n);break}}}t=t.right}return s},Zl=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;let n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===Eu){let r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}},Ql=e=>{let t=0;return Rc(e.doc,n=>{let r=e._start,i=e._start,a=Rn(),o=zn(a);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case Eu:Gl(o,i.content);break;default:t+=Xl(n,r,i,a,o),a=zn(o),r=i;break}i=i.right}}),t},$l=e=>{let t=new Set,n=e.doc;for(let[r,i]of e.afterState.entries()){let a=e.beforeState.get(r)||0;i!==a&&Ac(e,n.store.clients.get(r),a,i,e=>{!e.deleted&&e.content.constructor===Eu&&e.constructor!==gu&&t.add(e.parent)})}Rc(n,n=>{fs(e,e.deleteSet,e=>{if(e instanceof gu||!e.parent._hasFormatting||t.has(e.parent))return;let r=e.parent;e.content.constructor===Eu?t.add(r):Zl(n,e)});for(let e of t)Ql(e)})},eu=(e,t,n)=>{let r=n,i=zn(t.currentAttributes),a=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case Uu:case wu:case Nu:n<t.right.length&&Dc(e,$(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e);break}t.forward()}a&&Xl(e,a,t.right,i,t.currentAttributes);let o=(t.left||t.right).parent;return o._searchMarker&&fl(o._searchMarker,t.index,-r+n),t},tu=class extends nl{constructor(e,t,n){super(e,t),this.childListChanged=!1,this.keysChanged=new Set,n.forEach(e=>{e===null?this.childListChanged=!0:this.keysChanged.add(e)})}get changes(){return this._changes===null&&(this._changes={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set}),this._changes}get delta(){if(this._delta===null){let e=this.target.doc,t=[];Rc(e,e=>{let n=new Map,r=new Map,i=this.target._start,a=null,o={},s=``,c=0,l=0,u=()=>{if(a!==null){let e=null;switch(a){case`delete`:l>0&&(e={delete:l}),l=0;break;case`insert`:(typeof s==`object`||s.length>0)&&(e={insert:s},n.size>0&&(e.attributes={},n.forEach((t,n)=>{t!==null&&(e.attributes[n]=t)}))),s=``;break;case`retain`:c>0&&(e={retain:c},Hi(o)||(e.attributes=Ri({},o))),c=0;break}e&&t.push(e),a=null}};for(;i!==null;){switch(i.content.constructor){case Uu:case wu:this.adds(i)?this.deletes(i)||(u(),a=`insert`,s=i.content.getContent()[0],u()):this.deletes(i)?(a!==`delete`&&(u(),a=`delete`),l+=1):i.deleted||(a!==`retain`&&(u(),a=`retain`),c+=1);break;case Nu:this.adds(i)?this.deletes(i)||(a!==`insert`&&(u(),a=`insert`),s+=i.content.str):this.deletes(i)?(a!==`delete`&&(u(),a=`delete`),l+=i.length):i.deleted||(a!==`retain`&&(u(),a=`retain`),c+=i.length);break;case Eu:{let{key:t,value:s}=i.content;if(this.adds(i))this.deletes(i)||(Bl(n.get(t)??null,s)?s!==null&&i.delete(e):(a===`retain`&&u(),Bl(s,r.get(t)??null)?delete o[t]:o[t]=s));else if(this.deletes(i)){r.set(t,s);let e=n.get(t)??null;Bl(e,s)||(a===`retain`&&u(),o[t]=e)}else if(!i.deleted){r.set(t,s);let n=o[t];n!==void 0&&(Bl(n,s)?n!==null&&i.delete(e):(a===`retain`&&u(),s===null?delete o[t]:o[t]=s))}i.deleted||(a===`insert`&&u(),Gl(n,i.content));break}}i=i.right}for(u();t.length>0;){let e=t[t.length-1];if(e.retain!==void 0&&e.attributes===void 0)t.pop();else break}}),this._delta=t}return this._delta}},nu=class e extends ml{constructor(e){super(),this._pending=e===void 0?[]:[()=>this.insert(0,e)],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??il(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(e=>e())}catch(e){console.error(e)}this._pending=null}_copy(){return new e}clone(){let t=new e;return t.applyDelta(this.toDelta()),t}_callObserver(e,t){super._callObserver(e,t);let n=new tu(this,e,t);pl(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??il();let e=``,t=this._start;for(;t!==null;)!t.deleted&&t.countable&&t.content.constructor===Nu&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){this.doc===null?this._pending.push(()=>this.applyDelta(e)):Rc(this.doc,n=>{let r=new Vl(null,this._start,0,new Map);for(let i=0;i<e.length;i++){let a=e[i];if(a.insert!==void 0){let o=!t&&typeof a.insert==`string`&&i===e.length-1&&r.right===null&&a.insert.slice(-1)===`
|
|
4
|
-
`?a.insert.slice(0,-1):a.insert;(typeof o!=`string`||o.length>0)&&Jl(n,this,r,o,a.attributes||{})}else a.retain===void 0?a.delete!==void 0&&eu(n,r,a.delete):Yl(n,this,r,a.retain,a.attributes||{})}})}toDelta(e,t,n){this.doc??il();let r=[],i=new Map,a=this.doc,o=``,s=this._start;function c(){if(o.length>0){let e={},t=!1;i.forEach((n,r)=>{t=!0,e[r]=n});let n={insert:o};t&&(n.attributes=e),r.push(n),o=``}}let l=()=>{for(;s!==null;){if(vc(s,e)||t!==void 0&&vc(s,t))switch(s.content.constructor){case Nu:{let r=i.get(`ychange`);e!==void 0&&!vc(s,e)?(r===void 0||r.user!==s.id.client||r.type!==`removed`)&&(c(),i.set(`ychange`,n?n(`removed`,s.id):{type:`removed`})):t!==void 0&&!vc(s,t)?(r===void 0||r.user!==s.id.client||r.type!==`added`)&&(c(),i.set(`ychange`,n?n(`added`,s.id):{type:`added`})):r!==void 0&&(c(),i.delete(`ychange`)),o+=s.content.str;break}case Uu:case wu:{c();let e={insert:s.content.getContent()[0]};if(i.size>0){let t={};e.attributes=t,i.forEach((e,n)=>{t[n]=e})}r.push(e);break}case Eu:vc(s,e)&&(c(),Gl(i,s.content));break}s=s.right}c()};return e||t?Rc(a,n=>{e&&yc(n,e),t&&yc(n,t),l()},`cleanup`):l(),r}insert(e,t,n){if(t.length<=0)return;let r=this.doc;r===null?this._pending.push(()=>this.insert(e,t,n)):Rc(r,r=>{let i=Ul(r,this,e,!n);n||(n={},i.currentAttributes.forEach((e,t)=>{n[t]=e})),Jl(r,this,i,t,n)})}insertEmbed(e,t,n){let r=this.doc;r===null?this._pending.push(()=>this.insertEmbed(e,t,n||{})):Rc(r,r=>{let i=Ul(r,this,e,!n);Jl(r,this,i,t,n||{})})}delete(e,t){if(t===0)return;let n=this.doc;n===null?this._pending.push(()=>this.delete(e,t)):Rc(n,n=>{eu(n,Ul(n,this,e,!0),t)})}format(e,t,n){if(t===0)return;let r=this.doc;r===null?this._pending.push(()=>this.format(e,t,n)):Rc(r,r=>{let i=Ul(r,this,e,!1);i.right!==null&&Yl(r,this,i,t,n)})}removeAttribute(e){this.doc===null?this._pending.push(()=>this.removeAttribute(e)):Rc(this.doc,t=>{Dl(t,this,e)})}setAttribute(e,t){this.doc===null?this._pending.push(()=>this.setAttribute(e,t)):Rc(this.doc,n=>{Ol(n,this,e,t)})}getAttribute(e){return kl(this,e)}getAttributes(){return Al(this)}_write(e){e.writeTypeRef(Ru)}},ru=e=>new nu,iu=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??il()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(t)))do if(t=e.content.type,!e.deleted&&(t.constructor===su||t.constructor===au)&&t._start!==null)e=t._start;else for(;e!==null;){let t=e.next;if(t!==null){e=t;break}else e=e.parent===this._root?null:e.parent._item}while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}},au=class e extends ml{constructor(){super(),this._prelimContent=[]}get firstChild(){let 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(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof ml?e.clone():e)),t}get length(){return this.doc??il(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new iu(this,e)}querySelector(e){e=e.toUpperCase();let t=new iu(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),Kn(new iu(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){pl(this,e,new lu(this,t,e))}toString(){return yl(this,e=>e.toString()).join(``)}toJSON(){return this.toString()}toDOM(e=document,t={},n){let r=e.createDocumentFragment();return n!==void 0&&n._createAssociation(r,this),vl(this,i=>{r.insertBefore(i.toDOM(e,t,n),null)}),r}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):Rc(this.doc,n=>{wl(n,this,e,t)})}insertAfter(e,t){if(this.doc!==null)Rc(this.doc,n=>{let r=e&&e instanceof ml?e._item:e;Sl(n,this,r,t)});else{let n=this._prelimContent,r=e===null?0:n.findIndex(t=>t===e)+1;if(r===0&&e!==null)throw ii(`Reference item not found`);n.splice(r,0,...t)}}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):Rc(this.doc,n=>{El(n,this,e,t)})}toArray(){return gl(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return xl(this,e)}slice(e=0,t=this.length){return hl(this,e,t)}forEach(e){vl(this,e)}_write(e){e.writeTypeRef(Bu)}},ou=e=>new au,su=class e extends au{constructor(e=`UNDEFINED`){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let 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(){let t=new e(this.nodeName);return Bi(this.getAttributes(),(e,n)=>{t.setAttribute(n,e)}),t.insert(0,this.toArray().map(e=>e instanceof ml?e.clone():e)),t}toString(){let e=this.getAttributes(),t=[],n=[];for(let t in e)n.push(t);n.sort();let r=n.length;for(let i=0;i<r;i++){let r=n[i];t.push(r+`="`+e[r]+`"`)}let i=this.nodeName.toLocaleLowerCase();return`<${i}${t.length>0?` `+t.join(` `):``}>${super.toString()}</${i}>`}removeAttribute(e){this.doc===null?this._prelimAttrs.delete(e):Rc(this.doc,t=>{Dl(t,this,e)})}setAttribute(e,t){this.doc===null?this._prelimAttrs.set(e,t):Rc(this.doc,n=>{Ol(n,this,e,t)})}getAttribute(e){return kl(this,e)}hasAttribute(e){return jl(this,e)}getAttributes(e){return e?Ml(this,e):Al(this)}toDOM(e=document,t={},n){let r=e.createElement(this.nodeName),i=this.getAttributes();for(let e in i){let t=i[e];typeof t==`string`&&r.setAttribute(e,t)}return vl(this,i=>{r.appendChild(i.toDOM(e,t,n))}),n!==void 0&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(zu),e.writeKey(this.nodeName)}},cu=e=>new su(e.readKey()),lu=class extends nl{constructor(e,t,n){super(e,n),this.childListChanged=!1,this.attributesChanged=new Set,t.forEach(e=>{e===null?this.childListChanged=!0:this.attributesChanged.add(e)})}},uu=class e extends Rl{constructor(e){super(),this.hookName=e}_copy(){return new e(this.hookName)}clone(){let t=new e(this.hookName);return this.forEach((e,n)=>{t.set(n,e)}),t}toDOM(e=document,t={},n){let r=t[this.hookName],i;return i=r===void 0?document.createElement(this.hookName):r.createDom(this),i.setAttribute(`data-yjs-hook`,this.hookName),n!==void 0&&n._createAssociation(i,this),i}_write(e){e.writeTypeRef(Vu),e.writeKey(this.hookName)}},du=e=>new uu(e.readKey()),fu=class e extends nu{get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new e}clone(){let t=new e;return t.applyDelta(this.toDelta()),t}toDOM(e=document,t,n){let r=e.createTextNode(this.toString());return n!==void 0&&n._createAssociation(r,this),r}toString(){return this.toDelta().map(e=>{let t=[];for(let n in e.attributes){let r=[];for(let t in e.attributes[n])r.push({key:t,value:e.attributes[n][t]});r.sort((e,t)=>e.key<t.key?-1:1),t.push({nodeName:n,attrs:r})}t.sort((e,t)=>e.nodeName<t.nodeName?-1:1);let n=``;for(let e=0;e<t.length;e++){let r=t[e];n+=`<${r.nodeName}`;for(let e=0;e<r.attrs.length;e++){let t=r.attrs[e];n+=` ${t.key}="${t.value}"`}n+=`>`}n+=e.insert;for(let e=t.length-1;e>=0;e--)n+=`</${t[e].nodeName}>`;return n}).join(``)}toJSON(){return this.toString()}_write(e){e.writeTypeRef(Hu)}},pu=e=>new fu,mu=class{constructor(e,t){this.id=e,this.length=t}get deleted(){throw ai()}mergeWith(e){return!1}write(e,t,n){throw ai()}integrate(e,t){throw ai()}},hu=0,gu=class extends mu{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor?(this.length+=e.length,!0):!1}integrate(e,t){t>0&&(this.id.clock+=t,this.length-=t),Cc(e.doc.store,this)}write(e,t){e.writeInfo(hu),e.writeLen(this.length-t)}getMissing(e,t){return null}},_u=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 ai()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}},vu=e=>new _u(e.readBuf()),yu=class e{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.len)}splice(t){let n=new e(this.len-t);return this.len=t,n}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){_s(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}},bu=e=>new yu(e.readLen()),xu=(e,t)=>new ws({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1}),Su=class e{constructor(e){e._item&&console.error(`This document was already integrated as a sub-document. You should create a second instance instead with the same guid.`),this.doc=e;let t={};this.opts=t,e.gc||(t.gc=!1),e.autoLoad&&(t.autoLoad=!0),e.meta!==null&&(t.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new e(xu(this.doc.guid,this.opts))}splice(e){throw ai()}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}},Cu=e=>new Su(xu(e.readString(),e.readAny())),wu=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 ai()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}},Tu=e=>new wu(e.readJSON()),Eu=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 ai()}mergeWith(e){return!1}integrate(e,t){let 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}},Du=e=>new Eu(e.readKey(),e.readJSON()),Ou=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){let 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){let n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){let t=this.arr[r];e.writeString(t===void 0?`undefined`:JSON.stringify(t))}}getRef(){return 2}},ku=e=>{let t=e.readLen(),n=[];for(let r=0;r<t;r++){let t=e.readString();t===`undefined`?n.push(void 0):n.push(JSON.parse(t))}return new Ou(n)},Au=ia(`node_env`)===`development`,ju=class e{constructor(e){this.arr=e,Au&&qi(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){let 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){let n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){let t=this.arr[r];e.writeAny(t)}}getRef(){return 8}},Mu=e=>{let t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new ju(n)},Nu=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){let n=new e(this.str.slice(t));this.str=this.str.slice(0,t);let 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(t===0?this.str:this.str.slice(t))}getRef(){return 4}},Pu=e=>new Nu(e.readString()),Fu=[Il,zl,ru,cu,ou,du,pu],Iu=0,Lu=1,Ru=2,zu=3,Bu=4,Vu=5,Hu=6,Uu=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 ai()}mergeWith(e){return!1}integrate(e,t){this.type._integrate(e.doc,t)}delete(e){let t=this.type._start;for(;t!==null;)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(;t!==null;)t.gc(e,!0),t=t.right;this.type._start=null,this.type._map.forEach(t=>{for(;t!==null;)t.gc(e,!0),t=t.left}),this.type._map=new Map}write(e,t){this.type._write(e)}getRef(){return 7}},Wu=e=>new Uu(Fu[e.readTypeRef()](e)),Gu=(e,t)=>{let n=t,r=0,i;do r>0&&(n=$(n.client,n.clock+r)),i=Tc(e,n),r=n.clock-i.id.clock,n=i.redone;while(n!==null&&i instanceof Xu);return{item:i,diff:r}},Ku=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},qu=(e,t,n)=>{let{client:r,clock:i}=t.id,a=new Xu($(r,i+n),t,$(r,i+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&a.markDeleted(),t.keep&&(a.keep=!0),t.redone!==null&&(a.redone=$(t.redone.client,t.redone.clock+n)),t.right=a,a.right!==null&&(a.right.left=a),e._mergeStructs.push(a),a.parentSub!==null&&a.right===null&&a.parent._map.set(a.parentSub,a),t.length=n,a},Ju=(e,t)=>Jn(e,e=>ms(e.deletions,t)),Yu=(e,t,n,r,i,a)=>{let o=e.doc,s=o.store,c=o.clientID,l=t.redone;if(l!==null)return Dc(e,l);let u=t.parent._item,d=null,f;if(u!==null&&u.deleted===!0){if(u.redone===null&&(!n.has(u)||Yu(e,u,n,r,i,a)===null))return null;for(;u.redone!==null;)u=Dc(e,u.redone)}let p=u===null?t.parent:u.content.type;if(t.parentSub===null){for(d=t.left,f=t;d!==null;){let t=d;for(;t!==null&&t.parent._item!==u;)t=t.redone===null?null:Dc(e,t.redone);if(t!==null&&t.parent._item===u){d=t;break}d=d.left}for(;f!==null;){let t=f;for(;t!==null&&t.parent._item!==u;)t=t.redone===null?null:Dc(e,t.redone);if(t!==null&&t.parent._item===u){f=t;break}f=f.right}}else if(f=null,t.right&&!i){for(d=t;d!==null&&d.right!==null&&(d.right.redone||ms(r,d.right.id)||Ju(a.undoStack,d.right.id)||Ju(a.redoStack,d.right.id));)for(d=d.right;d.redone;)d=Dc(e,d.redone);if(d&&d.right!==null)return null}else d=p._map.get(t.parentSub)||null;let m=$(c,Sc(s,c)),h=new Xu(m,d,d&&d.lastId,f,f&&f.id,p,t.parentSub,t.content.copy());return t.redone=m,Ku(h,!0),h.integrate(e,0),h},Xu=class e extends mu{constructor(e,t,n,r,i,a,o,s){super(e,s.getLength()),this.origin=n,this.left=t,this.right=r,this.rightOrigin=i,this.parent=a,this.parentSub=o,this.redone=null,this.content=s,this.info=this.content.isCountable()?2:0}set marker(e){(this.info&8)>0!==e&&(this.info^=8)}get marker(){return(this.info&8)>0}get keep(){return(this.info&1)>0}set keep(e){this.keep!==e&&(this.info^=1)}get countable(){return(this.info&2)>0}get deleted(){return(this.info&4)>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>=Sc(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=Sc(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===tc&&this.id.client!==this.parent.client&&this.parent.clock>=Sc(n,this.parent.client))return this.parent.client;if(this.origin&&=(this.left=Oc(t,n,this.origin),this.left.lastId),this.rightOrigin&&=(this.right=Dc(t,this.rightOrigin),this.right.id),this.left&&this.left.constructor===gu||this.right&&this.right.constructor===gu)this.parent=null;else if(!this.parent)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);else if(this.parent.constructor===tc){let e=Tc(n,this.parent);e.constructor===gu?this.parent=null:this.parent=e.content.type}return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=Oc(e,e.doc.store,$(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||this.right.left!==null)||this.left&&this.left.right!==this.right){let t=this.left,n;if(t!==null)n=t.right;else if(this.parentSub!==null)for(n=this.parent._map.get(this.parentSub)||null;n!==null&&n.left!==null;)n=n.left;else n=this.parent._start;let r=new Set,i=new Set;for(;n!==null&&n!==this.right;){if(i.add(n),r.add(n),nc(this.origin,n.origin)){if(n.id.client<this.id.client)t=n,r.clear();else if(nc(this.rightOrigin,n.rightOrigin))break}else if(n.origin!==null&&i.has(Tc(e.doc.store,n.origin)))r.has(Tc(e.doc.store,n.origin))||(t=n,r.clear());else break;n=n.right}this.left=t}if(this.left!==null)this.right=this.left.right,this.left.right=this;else{let e;if(this.parentSub!==null)for(e=this.parent._map.get(this.parentSub)||null;e!==null&&e.left!==null;)e=e.left;else e=this.parent._start,this.parent._start=this;this.right=e}this.right===null?this.parentSub!==null&&(this.parent._map.set(this.parentSub,this),this.left!==null&&this.left.delete(e)):this.right.left=this,this.parentSub===null&&this.countable&&!this.deleted&&(this.parent._length+=this.length),Cc(e.doc.store,this),this.content.integrate(e,this),Nc(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new gu(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;e!==null&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;e!==null&&e.deleted;)e=e.left;return e}get lastId(){return this.length===1?this.id:$(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&nc(e.origin,this.lastId)&&this.right===e&&nc(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&this.redone===null&&e.redone===null&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){let 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,this.right!==null&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){let t=this.parent;this.countable&&this.parentSub===null&&(t._length-=this.length),this.markDeleted(),_s(e.deleteSet,this.id.client,this.id.clock,this.length),Nc(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw oi();this.content.gc(e),t?kc(e,this,new gu(this.id,this.length)):this.content=new yu(this.length)}write(e,t){let n=t>0?$(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,i=this.parentSub,a=this.content.getRef()&31|(n===null?0:128)|(r===null?0:64)|(i===null?0:32);if(e.writeInfo(a),n!==null&&e.writeLeftID(n),r!==null&&e.writeRightID(r),n===null&&r===null){let t=this.parent;if(t._item!==void 0){let n=t._item;if(n===null){let n=rc(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===tc?(e.writeParentInfo(!1),e.writeLeftID(t)):oi();i!==null&&e.writeString(i)}this.content.write(e,t)}},Zu=(e,t)=>Qu[t&31](e),Qu=[()=>{oi()},bu,ku,vu,Pu,Tu,Du,Wu,Mu,Cu,()=>{oi()}],$u=10,ed=class extends mu{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor?(this.length+=e.length,!0):!1}integrate(e,t){oi()}write(e,t){e.writeInfo($u),Z(e.restEncoder,this.length-t)}getMissing(e,t){return null}},td=typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:{},nd=`__ $YJS$ __`;td[nd]===!0&&console.error(`Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438`),td[nd]=!0;var rd=()=>{let e=!0;return(t,n)=>{if(e){e=!1;try{t()}finally{e=!0}}else n!==void 0&&n()}},id=/[\uD800-\uDBFF]/,ad=/[\uDC00-\uDFFF]/,od=(e,t)=>{let n=0,r=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n++;for(n>0&&id.test(e[n-1])&&n--;r+n<e.length&&r+n<t.length&&e[e.length-r-1]===t[t.length-r-1];)r++;return r>0&&ad.test(e[e.length-r])&&r--,{index:n,remove:e.length-n-r,insert:t.slice(n,t.length-r)}},sd=(e,t)=>e>>>t|e<<32-t,cd=e=>sd(e,2)^sd(e,13)^sd(e,22),ld=e=>sd(e,6)^sd(e,11)^sd(e,25),ud=e=>sd(e,7)^sd(e,18)^e>>>3,dd=e=>sd(e,17)^sd(e,19)^e>>>10,fd=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),pd=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),md=class{constructor(){let e=new ArrayBuffer(320);this._H=new Uint32Array(e,0,8),this._H.set(pd),this._W=new Uint32Array(e,64,64)}_updateHash(){let e=this._H,t=this._W;for(let e=16;e<64;e++)t[e]=dd(t[e-2])+t[e-7]+ud(t[e-15])+t[e-16];let n=e[0],r=e[1],i=e[2],a=e[3],o=e[4],s=e[5],c=e[6],l=e[7];for(let e=0,u,d;e<64;e++)u=l+ld(o)+(o&s^~o&c)+fd[e]+t[e]>>>0,d=cd(n)+(n&r^n&i^r&i)>>>0,l=c,c=s,s=o,o=a+u>>>0,a=i,i=r,r=n,n=u+d>>>0;e[0]+=n,e[1]+=r,e[2]+=i,e[3]+=a,e[4]+=o,e[5]+=s,e[6]+=c,e[7]+=l}digest(e){let t=0;for(;t+56<=e.length;){let n=0;for(;n<16&&t+3<e.length;n++)this._W[n]=e[t++]<<24|e[t++]<<16|e[t++]<<8|e[t++];if(t%64!=0){for(this._W.fill(0,n,16);t<e.length;)this._W[n]|=e[t]<<(3-t%4)*8,t++;this._W[n]|=128<<(3-t%4)*8}this._updateHash()}let n=t%64!=0;this._W.fill(0,0,16);let r=0;for(;t<e.length;r++)for(let n=3;n>=0&&t<e.length;n--)this._W[r]|=e[t++]<<n*8;n||(this._W[r-(t%4==0?0:1)]|=128<<(3-t%4)*8),this._W[14]=e.byteLength/gr,this._W[15]=e.byteLength*8,this._updateHash();let i=new Uint8Array(32);for(let e=0;e<this._H.length;e++)for(let t=0;t<4;t++)i[e*4+t]=this._H[e]>>>(3-t)*8;return i}},hd=e=>new md().digest(e),gd=new be(`y-sync`),_d=new be(`y-undo`),vd=new be(`yjs-cursor`),yd=e=>{for(let t=6;t<e.length;t++)e[t%6]=e[t%6]^e[t];return e.slice(0,6)},bd=e=>la(yd(hd(da(e)))),xd=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&t.sv.get(e.id.client)>e.id.clock&&!ms(t.ds,e.id),Sd=[{light:`#ecd44433`,dark:`#ecd444`}],Cd=(e,t,n)=>{if(!e.has(n)){if(e.size<t.length){let n=Un();e.forEach(e=>n.add(e)),t=t.filter(e=>!n.has(e))}e.set(n,Di(t))}return e.get(n)},wd=(e,{colors:t=Sd,colorMapping:n=new Map,permanentUserData:r=null,onFirstRender:i=()=>{},mapping:a}={})=>{let o=!1,s=new Od(e,a),c=new E({props:{editable:e=>{let t=gd.getState(e);return t.snapshot==null&&t.prevSnapshot==null}},key:gd,state:{init:(i,a)=>({type:e,doc:e.doc,binding:s,snapshot:null,prevSnapshot:null,isChangeOrigin:!1,isUndoRedoOperation:!1,addToHistory:!0,colors:t,colorMapping:n,permanentUserData:r}),apply:(e,t)=>{let n=e.getMeta(gd);if(n!==void 0){t=Object.assign({},t);for(let e in n)t[e]=n[e]}return t.addToHistory=e.getMeta(`addToHistory`)!==!1,t.isChangeOrigin=n!==void 0&&!!n.isChangeOrigin,t.isUndoRedoOperation=n!==void 0&&!!n.isChangeOrigin&&!!n.isUndoRedoOperation,s.prosemirrorView!==null&&n!==void 0&&(n.snapshot!=null||n.prevSnapshot!=null)&&Wo(0,()=>{s.prosemirrorView!=null&&(n.restore==null?s._renderSnapshot(n.snapshot,n.prevSnapshot,t):(s._renderSnapshot(n.snapshot,n.snapshot,t),delete t.restore,delete t.snapshot,delete t.prevSnapshot,s.mux(()=>{s._prosemirrorChanged(s.prosemirrorView.state.doc)})))}),t}},view:e=>(s.initView(e),a??s._forceRerender(),i(),{update:()=>{let t=c.getState(e.state);if(t.snapshot==null&&t.prevSnapshot==null&&(o||e.state.doc.content.findDiffStart(e.state.doc.type.createAndFill().content)!==null)){if(o=!0,t.addToHistory===!1&&!t.isChangeOrigin){let t=_d.getState(e.state),n=t&&t.undoManager;n&&n.stopCapturing()}s.mux(()=>{t.doc.transact(n=>{n.meta.set(`addToHistory`,t.addToHistory),s._prosemirrorChanged(e.state.doc)},gd)})}},destroy:()=>{s.destroy()}})});return c},Td=(e,t,n)=>{if(t!==null&&t.anchor!==null&&t.head!==null)if(t.type===`all`)e.setSelection(new B(e.doc));else if(t.type===`node`){let r=rf(n.doc,n.type,t.anchor,n.mapping);e.setSelection(Ed(e,r))}else{let r=rf(n.doc,n.type,t.anchor,n.mapping),i=rf(n.doc,n.type,t.head,n.mapping);r!==null&&i!==null&&e.setSelection(H.between(e.doc.resolve(r),e.doc.resolve(i)))}},Ed=(e,t)=>{let n=e.doc.resolve(t);return n.nodeAfter?xe.create(e.doc,t):H.near(n)},Dd=(e,t)=>({type:t.selection.jsonID,anchor:tf(t.selection.anchor,e.type,e.mapping),head:tf(t.selection.head,e.type,e.mapping)}),Od=class{constructor(e,t=new Map){this.type=e,this.prosemirrorView=null,this.mux=rd(),this.mapping=t,this.isOMark=new Map,this._observeFunction=this._typeChanged.bind(this),this.doc=e.doc,this.beforeTransactionSelection=null,this.beforeAllTransactions=()=>{this.beforeTransactionSelection===null&&this.prosemirrorView!=null&&(this.beforeTransactionSelection=Dd(this,this.prosemirrorView.state))},this.afterAllTransactions=()=>{this.beforeTransactionSelection=null},this._domSelectionInView=null}get _tr(){return this.prosemirrorView.state.tr.setMeta(`addToHistory`,!1)}_isLocalCursorInView(){return this.prosemirrorView.hasFocus()?($i&&this._domSelectionInView===null&&(Wo(0,()=>{this._domSelectionInView=null}),this._domSelectionInView=this._isDomSelectionInView()),this._domSelectionInView):!1}_isDomSelectionInView(){let e=this.prosemirrorView._root.getSelection();if(e==null||e.anchorNode==null)return!1;let t=this.prosemirrorView._root.createRange();t.setStart(e.anchorNode,e.anchorOffset),t.setEnd(e.focusNode,e.focusOffset),t.getClientRects().length===0&&t.startContainer&&t.collapsed&&t.selectNodeContents(t.startContainer);let n=t.getBoundingClientRect(),r=Oo.documentElement;return n.bottom>=0&&n.right>=0&&n.left<=(window.innerWidth||r.clientWidth||0)&&n.top<=(window.innerHeight||r.clientHeight||0)}renderSnapshot(e,t){t||=gc(vs(),new Map),this.prosemirrorView.dispatch(this._tr.setMeta(gd,{snapshot:e,prevSnapshot:t}))}unrenderSnapshot(){this.mapping.clear(),this.mux(()=>{let e=this.type.toArray().map(e=>Ad(e,this.prosemirrorView.state.schema,this)).filter(e=>e!==null),t=this._tr.replace(0,this.prosemirrorView.state.doc.content.size,new U(P.from(e),0,0));t.setMeta(gd,{snapshot:null,prevSnapshot:null}),this.prosemirrorView.dispatch(t)})}_forceRerender(){this.mapping.clear(),this.mux(()=>{let e=this.beforeTransactionSelection===null?this.prosemirrorView.state.selection:null,t=this.type.toArray().map(e=>Ad(e,this.prosemirrorView.state.schema,this)).filter(e=>e!==null),n=this._tr.replace(0,this.prosemirrorView.state.doc.content.size,new U(P.from(t),0,0));if(e){let t=tr(nr(e.anchor,0),n.doc.content.size),r=tr(nr(e.head,0),n.doc.content.size);n.setSelection(H.create(n.doc,t,r))}this.prosemirrorView.dispatch(n.setMeta(gd,{isChangeOrigin:!0,binding:this}))})}_renderSnapshot(e,t,n){let r=this.doc,i=this.type;if(e||=_c(this.doc),e instanceof Uint8Array||t instanceof Uint8Array)if((!(e instanceof Uint8Array)||!(t instanceof Uint8Array))&&oi(),r=new ws({gc:!1}),zs(r,t),t=_c(r),zs(r,e),e=_c(r),i._item===null){let e=Array.from(this.doc.share.keys()).find(e=>this.doc.share.get(e)===this.type);i=r.getXmlFragment(e)}else{let e=r.store.clients.get(i._item.id.client)??[];i=e[wc(e,i._item.id.clock)].content.type}this.mapping.clear(),this.mux(()=>{r.transact(r=>{let a=n.permanentUserData;a&&a.dss.forEach(e=>{fs(r,e,e=>{})});let o=(e,t)=>{let r=e===`added`?a.getUserByClientId(t.client):a.getUserByDeletedId(t);return{user:r,type:e,color:Cd(n.colorMapping,n.colors,r)}},s=_l(i,new hc(t.ds,e.sv)).map(n=>!n._item.deleted||xd(n._item,e)||xd(n._item,t)?Ad(n,this.prosemirrorView.state.schema,{mapping:new Map,isOMark:new Map},e,t,o):null).filter(e=>e!==null),c=this._tr.replace(0,this.prosemirrorView.state.doc.content.size,new U(P.from(s),0,0));this.prosemirrorView.dispatch(c.setMeta(gd,{isChangeOrigin:!0}))},gd)})}_typeChanged(e,t){if(this.prosemirrorView==null)return;let n=gd.getState(this.prosemirrorView.state);if(e.length===0||n.snapshot!=null||n.prevSnapshot!=null){this.renderSnapshot(n.snapshot,n.prevSnapshot);return}this.mux(()=>{let e=(e,t)=>this.mapping.delete(t);fs(t,t.deleteSet,e=>{if(e.constructor===Xu){let t=e.content.type;t&&this.mapping.delete(t)}}),t.changed.forEach(e),t.changedParentTypes.forEach(e);let n=this.type.toArray().map(e=>kd(e,this.prosemirrorView.state.schema,this)).filter(e=>e!==null),r=this._tr.replace(0,this.prosemirrorView.state.doc.content.size,new U(P.from(n),0,0));Td(r,this.beforeTransactionSelection,this),r=r.setMeta(gd,{isChangeOrigin:!0,isUndoRedoOperation:t.origin instanceof Hc}),this.beforeTransactionSelection!==null&&this._isLocalCursorInView()&&r.scrollIntoView(),this.prosemirrorView.dispatch(r)})}_prosemirrorChanged(e){this.doc.transact(()=>{Jd(this.doc,this.type,e,this),this.beforeTransactionSelection=Dd(this,this.prosemirrorView.state)},gd)}initView(e){this.prosemirrorView!=null&&this.destroy(),this.prosemirrorView=e,this.doc.on(`beforeAllTransactions`,this.beforeAllTransactions),this.doc.on(`afterAllTransactions`,this.afterAllTransactions),this.type.observeDeep(this._observeFunction)}destroy(){this.prosemirrorView!=null&&(this.prosemirrorView=null,this.type.unobserveDeep(this._observeFunction),this.doc.off(`beforeAllTransactions`,this.beforeAllTransactions),this.doc.off(`afterAllTransactions`,this.afterAllTransactions))}},kd=(e,t,n,r,i,a)=>{let o=n.mapping.get(e);if(o===void 0){if(e instanceof su)return Ad(e,t,n,r,i,a);throw ai()}return o},Ad=(e,t,n,r,i,a)=>{let o=[],s=e=>{if(e instanceof su){let s=kd(e,t,n,r,i,a);s!==null&&o.push(s)}else{let s=e._item.right?.content?.type;s instanceof nu&&!s._item.deleted&&s._item.id.client===s.doc.clientID&&(e.applyDelta([{retain:e.length},...s.toDelta()]),s.doc.transact(e=>{s._item.delete(e)}));let c=jd(e,t,n,r,i,a);c!==null&&c.forEach(e=>{e!==null&&o.push(e)})}};r===void 0||i===void 0?e.toArray().forEach(s):_l(e,new hc(i.ds,r.sv)).forEach(s);try{let s=e.getAttributes(r);r!==void 0&&(xd(e._item,r)?xd(e._item,i)||(s.ychange=a?a(`added`,e._item.id):{type:`added`}):s.ychange=a?a(`removed`,e._item.id):{type:`removed`});let c=t.node(e.nodeName,s,o);return n.mapping.set(e,c),c}catch(r){console.warn(`[y-prosemirror] schema.node(`+e.nodeName+`) threw:`,String(r&&r.message||r));let i=globalThis.__okYpsCounters=globalThis.__okYpsCounters||{block:0,inline:0};if(t.nodes[e.nodeName]&&t.nodes[e.nodeName].spec&&t.nodes[e.nodeName].spec.inline)i.inline++;else if(i.block++,t.nodes.rawMdxFallback)try{let i=t.node(`rawMdxFallback`,{reason:String(r&&r.message||r)},[t.text(e.nodeName)]);return n.mapping.set(e,i),i}catch(e){console.warn(`[y-prosemirror] rawMdxFallback substitution also failed:`,String(e&&e.message||e))}return n.mapping.delete(e),null}},jd=(e,t,n,r,i,a)=>{let o=[],s=e.toDelta(r,i,a);try{for(let e=0;e<s.length;e++){let n=s[e];o.push(t.text(n.insert,Kd(n.attributes,t)))}}catch(e){console.warn(`[y-prosemirror] schema.text() threw:`,String(e&&e.message||e));let t=globalThis.__okYpsCounters=globalThis.__okYpsCounters||{block:0,inline:0};return t.inline++,null}return o},Md=(e,t)=>{let n=new fu,r=e.map(e=>({insert:e.text,attributes:qd(e.marks,t)}));return n.applyDelta(r),t.mapping.set(n,e),n},Nd=(e,t)=>{let n=new su(e.type.name);for(let t in e.attrs){let r=e.attrs[t];r!==null&&t!==`ychange`&&n.setAttribute(t,r)}return n.insert(0,Ld(e).map(e=>Pd(e,t))),t.mapping.set(n,e),n},Pd=(e,t)=>e instanceof Array?Md(e,t):Nd(e,t),Fd=e=>typeof e==`object`&&!!e,Id=(e,t)=>{let n=Object.keys(e).filter(t=>e[t]!==null),r=n.length===Object.keys(t).filter(e=>t[e]!==null).length;for(let i=0;i<n.length&&r;i++){let a=n[i],o=e[a],s=t[a];r=a===`ychange`||o===s||Fd(o)&&Fd(s)&&Id(o,s)}return r},Ld=e=>{let t=e.content.content,n=[];for(let e=0;e<t.length;e++){let r=t[e];if(r.isText){let r=[];for(let n=t[e];e<t.length&&n.isText;n=t[++e])r.push(n);e--,n.push(r)}else n.push(r)}return n},Rd=(e,t)=>{let n=e.toDelta();return n.length===t.length&&n.every((e,n)=>e.insert===t[n].text&&zi(e.attributes||{}).length===t[n].marks.length&&Ui(e.attributes,(e,r)=>{let i=Gd(r),a=t[n].marks;return a.find(e=>e.type.name===i)?Id(e,a.find(e=>e.type.name===i)?.attrs):!1}))},zd=(e,t)=>{if(e instanceof su&&!(t instanceof Array)&&Yd(e,t)){let n=Ld(t);return e._length===n.length&&Id(e.getAttributes(),t.attrs)&&e.toArray().every((e,t)=>zd(e,n[t]))}return e instanceof fu&&t instanceof Array&&Rd(e,t)},Bd=(e,t)=>e===t||e instanceof Array&&t instanceof Array&&e.length===t.length&&e.every((e,n)=>t[n]===e),Vd=(e,t,n)=>{let r=e.toArray(),i=Ld(t),a=i.length,o=r.length,s=tr(o,a),c=0,l=0,u=!1;for(;c<s;c++){let e=r[c],t=i[c];if(Bd(n.mapping.get(e),t))u=!0;else if(!zd(e,t))break}for(;c+l<s;l++){let e=r[o-l-1],t=i[a-l-1];if(Bd(n.mapping.get(e),t))u=!0;else if(!zd(e,t))break}return{equalityFactor:c+l,foundMappedChild:u}},Hd=e=>{let t=``,n=e._start,r={};for(;n!==null;)n.deleted||(n.countable&&n.content instanceof Nu?t+=n.content.str:n.content instanceof Eu&&(r[n.content.key]=null)),n=n.right;return{str:t,nAttrs:r}},Ud=(e,t,n)=>{n.mapping.set(e,t);let{nAttrs:r,str:i}=Hd(e),a=t.map(e=>({insert:e.text,attributes:Object.assign({},r,qd(e.marks,n))})),{insert:o,remove:s,index:c}=od(i,a.map(e=>e.insert).join(``));e.delete(c,s),e.insert(c,o),e.applyDelta(a.map(e=>({retain:e.insert.length,attributes:e.attributes})))},Wd=/(.*)(--[a-zA-Z0-9+/=]{8})$/,Gd=e=>Wd.exec(e)?.[1]??e,Kd=(e,t)=>{let n=[];for(let r in e)n.push(t.mark(Gd(r),e[r]));return n},qd=(e,t)=>{let n={};return e.forEach(e=>{if(e.type.name!==`ychange`){let r=Bn(t.isOMark,e.type,()=>!e.type.excludes(e.type));n[r?`${e.type.name}--${bd(e.toJSON())}`:e.type.name]=e.attrs}}),n},Jd=(e,t,n,r)=>{if(t instanceof su&&t.nodeName!==n.type.name)throw Error(`node name mismatch!`);if(r.mapping.set(t,n),t instanceof su){let e=t.getAttributes(),r=n.attrs;for(let n in r)r[n]===null?t.removeAttribute(n):e[n]!==r[n]&&n!==`ychange`&&t.setAttribute(n,r[n]);for(let n in e)r[n]===void 0&&t.removeAttribute(n)}let i=Ld(n),a=i.length,o=t.toArray(),s=o.length,c=tr(a,s),l=0,u=0;for(;l<c;l++){let e=o[l],t=i[l];if(!Bd(r.mapping.get(e),t))if(zd(e,t))r.mapping.set(e,t);else break}for(;u+l+1<c;u++){let e=o[s-u-1],t=i[a-u-1];if(!Bd(r.mapping.get(e),t))if(zd(e,t))r.mapping.set(e,t);else break}e.transact(()=>{for(;s-l-u>0&&a-l-u>0;){let n=o[l],c=i[l],d=o[s-u-1],f=i[a-u-1];if(n instanceof fu&&c instanceof Array)Rd(n,c)||Ud(n,c,r),l+=1;else{let i=n instanceof su&&Yd(n,c),a=d instanceof su&&Yd(d,f);if(i&&a){let e=Vd(n,c,r),t=Vd(d,f,r);e.foundMappedChild&&!t.foundMappedChild?a=!1:!e.foundMappedChild&&t.foundMappedChild||e.equalityFactor<t.equalityFactor?i=!1:a=!1}i?(Jd(e,n,c,r),l+=1):a?(Jd(e,d,f,r),u+=1):(r.mapping.delete(t.get(l)),t.delete(l,1),t.insert(l,[Pd(c,r)]),l+=1)}}let n=s-l-u;if(s===1&&a===0&&o[0]instanceof fu?(r.mapping.delete(o[0]),o[0].delete(0,o[0].length)):n>0&&(t.slice(l,l+n).forEach(e=>r.mapping.delete(e)),t.delete(l,n)),l+u<a){let e=[];for(let t=l;t<a-u;t++)e.push(Pd(i[t],r));t.insert(l,e)}},gd)},Yd=(e,t)=>!(t instanceof Array)&&e.nodeName===t.type.name,Xd=null,Zd=class{constructor(e,t,n){this.view=e,this.key=t,this.value=n}apply(){let e=gd.getState(this.view.state);if(e&&e.binding&&!e.binding.isDestroyed){let e=this.view.state.tr;e.setMeta(this.key,this.value),this.view.dispatch(e)}}},Qd=class e{constructor(e=[]){this.entries=e}getFirst(){return this.entries[0]}dequeueFirst(){return this.entries.shift()}isEmpty(){return this.entries.length===0}static fromViewsToUpdate(){let t=Xd;Xd=null;let n=[];return t.forEach((e,t)=>{e.forEach((e,r)=>{n.push(new Zd(t,r,e))})}),new e(n)}},$d=(e=Qd.fromViewsToUpdate(),t=!1)=>{let n=!0;for(;!e.isEmpty();){let r=e.getFirst();try{r.apply()}catch(r){if(r instanceof RangeError){t&&n&&e.dequeueFirst(),e.isEmpty()||Wo(0,()=>$d(e,!0));return}throw r}n=!1,e.dequeueFirst()}},ef=(e,t,n)=>{Xd||(Xd=new Map,Wo(0,$d)),Bn(Xd,e,Rn).set(t,n)},tf=(e,t,n)=>{if(e===0)return dc(t,0,-1);let r=t._first===null?null:t._first.content.type;for(;r!==null&&t!==r;){if(r instanceof fu){if(r._length>=e)return dc(r,e,-1);if(e-=r._length,r._item!==null&&r._item.next!==null)r=r._item.next.content.type;else{do r=r._item===null?null:r._item.parent,e--;while(r!==t&&r!==null&&r._item!==null&&r._item.next===null);r!==null&&r!==t&&(r=r._item===null?null:r._item.next.content.type)}}else{let i=(n.get(r)||{nodeSize:0}).nodeSize;if(r._first!==null&&e<i)r=r._first.content.type,e--;else{if(e===1&&r._length===0&&i>1)return new ac(r._item===null?null:r._item.id,r._item===null?rc(r):null,null);if(e-=i,r._item!==null&&r._item.next!==null)r=r._item.next.content.type;else{if(e===0)return r=r._item===null?r:r._item.parent,new ac(r._item===null?null:r._item.id,r._item===null?rc(r):null,null);do r=r._item.parent,e--;while(r!==t&&r._item.next===null);r!==t&&(r=r._item.next.content.type)}}}if(r===null)throw oi();if(e===0&&r.constructor!==fu&&r!==t)return nf(r._item.parent,r._item)}return dc(t,t._length,-1)},nf=(e,t)=>{let n=null,r=null;return e._item===null?r=rc(e):n=$(e._item.id.client,e._item.id.clock),new ac(n,r,t.id)},rf=(e,t,n,r)=>{let i=pc(n,e);if(i===null||i.type!==t&&!ic(t,i.type._item))return null;let a=i.type,o=0;if(a.constructor===fu)o=i.index;else if(a._item===null||!a._item.deleted){let e=a._first,t=0;for(;t<a._length&&t<i.index&&e!==null;){if(!e.deleted){let n=e.content.type;t++,n instanceof fu?o+=n._length:o+=r.get(n).nodeSize}e=e.right}o+=1}for(;a!==t&&a._item!==null;){let e=a._item.parent;if(e._item===null||!e._item.deleted){o+=1;let t=e._first;for(;t!==null;){let e=t.content.type;if(e===a)break;t.deleted||(e instanceof fu?o+=e._length:o+=r.get(e).nodeSize),t=t.right}}a=e}return o-1},af=(e,t,n)=>e!==t,of=e=>{let t=document.createElement(`span`);t.classList.add(`ProseMirror-yjs-cursor`),t.setAttribute(`style`,`border-color: ${e.color}`);let n=document.createElement(`div`);n.setAttribute(`style`,`background-color: ${e.color}`),n.insertBefore(document.createTextNode(e.name),null);let r=document.createTextNode(``),i=document.createTextNode(``);return t.insertBefore(r,null),t.insertBefore(n,null),t.insertBefore(i,null),t},sf=e=>({style:`background-color: ${e.color}70`,class:`ProseMirror-yjs-selection`}),cf=/^#[0-9a-fA-F]{6}$/,lf=(e,t,n,r,i)=>{let a=gd.getState(e);if(a==null||a.doc==null||a.binding==null)return A.create(e.doc,[]);let o=a.doc,s=[];return a.snapshot!=null||a.prevSnapshot!=null||a.binding.mapping.size===0?A.create(e.doc,[]):(t.getStates().forEach((t,c)=>{if(n(o.clientID,c,t)&&t.cursor!=null){let n=t.user||{};n.color==null?n.color=`#ffa500`:cf.test(n.color)||console.warn(`A user uses an unsupported color format`,n),n.name??=`User: ${c}`;let l=rf(o,a.type,sc(t.cursor.anchor),a.binding.mapping),u=rf(o,a.type,sc(t.cursor.head),a.binding.mapping);if(l!==null&&u!==null){let t=nr(e.doc.content.size-1,0);l=tr(l,t),u=tr(u,t),s.push(j.widget(u,()=>r(n,c),{key:c+``,side:10}));let a=tr(l,u),o=nr(l,u);s.push(j.inline(a,o,i(n,c),{inclusiveEnd:!0,inclusiveStart:!1}))}}}),A.create(e.doc,s))},uf=(e,{awarenessStateFilter:t=af,cursorBuilder:n=of,selectionBuilder:r=sf,getSelection:i=e=>e.selection}={},a=`cursor`)=>new E({key:vd,state:{init(i,a){return lf(a,e,t,n,r)},apply(i,a,o,s){let c=gd.getState(s),l=i.getMeta(vd);return c&&c.isChangeOrigin||l&&l.awarenessUpdated?lf(s,e,t,n,r):a.map(i.mapping,i.doc)}},props:{decorations:e=>vd.getState(e)},view:t=>{let n=()=>{t.docView&&ef(t,vd,{awarenessUpdated:!0})},r=()=>{let n=gd.getState(t.state),r=e.getLocalState()||{};if(t.hasFocus()){let o=i(t.state),s=tf(o.anchor,n.type,n.binding.mapping),c=tf(o.head,n.type,n.binding.mapping);(r.cursor==null||!mc(sc(r.cursor.anchor),s)||!mc(sc(r.cursor.head),c))&&e.setLocalStateField(a,{anchor:s,head:c})}else r.cursor!=null&&rf(n.doc,n.type,sc(r.cursor.anchor),n.binding.mapping)!==null&&e.setLocalStateField(a,null)};return e.on(`change`,n),t.dom.addEventListener(`focusin`,r),t.dom.addEventListener(`focusout`,r),{update:r,destroy:()=>{t.dom.removeEventListener(`focusin`,r),t.dom.removeEventListener(`focusout`,r),e.off(`change`,n),e.setLocalStateField(a,null)}}}}),df=e=>{let t=_d.getState(e).undoManager;if(t!=null)return t.undo(),!0},ff=e=>{let t=_d.getState(e).undoManager;if(t!=null)return t.redo(),!0},pf=new Set([`paragraph`]),mf=(e,t)=>!(e instanceof Xu)||!(e.content instanceof Uu)||!(e.content.type instanceof nu||e.content.type instanceof su&&t.has(e.content.type.nodeName))||e.content.type._length===0,hf=({protectedNodes:e=pf,trackedOrigins:t=[],undoManager:n=null}={})=>new E({key:_d,state:{init:(r,i)=>{let a=gd.getState(i),o=n||new Hc(a.type,{trackedOrigins:new Set([gd].concat(t)),deleteFilter:t=>mf(t,e),captureTransaction:e=>e.meta.get(`addToHistory`)!==!1});return{undoManager:o,prevSel:null,hasUndoOps:o.undoStack.length>0,hasRedoOps:o.redoStack.length>0}},apply:(e,t,n,r)=>{let i=gd.getState(r).binding,a=t.undoManager,o=a.undoStack.length>0,s=a.redoStack.length>0;return i?{undoManager:a,prevSel:Dd(i,n),hasUndoOps:o,hasRedoOps:s}:o!==t.hasUndoOps||s!==t.hasRedoOps?Object.assign({},t,{hasUndoOps:a.undoStack.length>0,hasRedoOps:a.redoStack.length>0}):t}},view:e=>{let t=gd.getState(e.state),n=_d.getState(e.state).undoManager;return n.on(`stack-item-added`,({stackItem:n})=>{let r=t.binding;r&&n.meta.set(r,_d.getState(e.state).prevSel)}),n.on(`stack-item-popped`,({stackItem:e})=>{let n=t.binding;n&&(n.beforeTransactionSelection=e.meta.get(n)||n.beforeTransactionSelection)}),{destroy:()=>{n.destroy()}}}});Ne({event:pe(`ok-branch-switched-clear-failed`),branch:Ee(),docName:Ee(),reason:Ee()});async function gf(e,t){let n=[];for(let[r,i]of e.entries)i.kind===`active`&&n.push(i.persistence.clearData().catch(e=>{let n={event:`ok-branch-switched-clear-failed`,docName:r,branch:t,reason:e instanceof Error?e.message:String(e)};console.warn(JSON.stringify(n))}));await Promise.all(n),e.clearBufferedUpdates(),e.recycleAllEntries()}function _f(e){let t=!1;return()=>{t?e():t=!0}}function vf(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}async function yf(e,t=``){let n;try{n=await fetch(`${t}/api/server-info`,{signal:AbortSignal.timeout(5e3)})}catch{return}if(!n.ok)return;let r;try{r=await n.json()}catch{return}let i=W.safeParse(r);if(!i.success){console.warn(JSON.stringify({event:`ok-server-info-schema-mismatch`,issues:i.error.issues}));return}if(e.setExpectedServerInstanceId(i.data.serverInstanceId),i.data.currentBranch!==void 0&&e.compareAndUpdateObservedBranch(i.data.currentBranch)&&gf(e,i.data.currentBranch),i.data.currentDiskAckSVs!==void 0){let t={};for(let[e,n]of Object.entries(i.data.currentDiskAckSVs))try{t[e]=vf(n)}catch{}e.observeDiskAckBatch(t)}}async function bf(e){let t;try{t=await fetch(`/api/config`,{signal:e,headers:{Accept:`application/json`}})}catch(e){if(e.name===`AbortError`)throw e;return{status:`error`,code:`network`}}if(t.status===404||t.status===501)return{status:`absent`};if(!t.ok)return{status:`error`,code:t.status};let n;try{n=await t.json()}catch{return{status:`error`,code:`invalid-body`}}if(typeof n!=`object`||!n||Array.isArray(n))return{status:`error`,code:`invalid-body`};let r=n;return{status:`ok`,config:{collabUrl:typeof r.collabUrl==`string`?r.collabUrl:null,previewUrl:typeof r.previewUrl==`string`?r.previewUrl:null,port:typeof r.port==`number`?r.port:0}}}function xf(e){return Df(e,ke)}function Sf(e){return Df(e,_e)}function Cf(e){return Df(e,me)}function wf(e){let t=Df(e,Ce);if(!t)return null;try{return{docName:t.docName,sv:Tf(t.sv)}}catch{return null}}function Tf(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function Ef(e,t){let n=Sf(e);if(n){t.onServerInfo?.(n);return}let r=Cf(e);if(r){t.onBranchSwitched?.(r);return}let i=wf(e);if(i){t.onDiskAck?.(i);return}let a=xf(e);if(a){t.onDerivedView?.(a);return}t.onUnknown?.(e)}function Df(e,t){let n;try{n=JSON.parse(e)}catch{return null}let r=t.safeParse(n);return r.success?r.data:null}function Of(){return typeof location>`u`?`ws://localhost/collab`:`${location.protocol===`https:`?`wss`:`ws`}://${location.host}/collab`}function kf(e){if(e===void 0)return null;let t=e.okDesktop;return!t||!t.config.collabUrl||t.config.collabUrl.length===0?null:t}function Af(e){return{collabUrl:e.collabUrl,attempts:0,terminal:!1,lastError:null}}var jf=2e3,Mf=15e3;function Nf(e){let t=e.terminalAfterMs??3e4,n=e.initialDelayMs??jf,r=e.maxDelayMs??Mf,i=e.log??{info:console.info,warn:console.warn},a=new AbortController,o=null,s=n,c=0,l=!1,u=!1,d=null,f=e.now(),p=async()=>{c+=1;let n=null;try{let t=await e.fetchConfig(a.signal);t.status===`absent`?(n=e.fallbackUrl(),d=null):t.status===`ok`&&t.config.collabUrl!==null?(n=t.config.collabUrl,d=null):t.status===`ok`?(u||(u=!0,i.info(`[collab-url] ok ui responded but server.lock has no port yet — retrying`)),d={kind:`null-collab`}):t.status===`error`&&(i.warn(`[collab-url] /api/config error (${t.code}) — retrying in ${s}ms`),d={kind:`error`,code:t.code})}catch(e){if(e.name===`AbortError`)return;d={kind:`error`,code:`network`}}if(!l){if(n!==null){e.onStateChange({collabUrl:n,attempts:c,terminal:!1,lastError:null});return}if(e.now()-f>=t){e.onStateChange({collabUrl:null,attempts:c,terminal:!0,lastError:d});return}e.onStateChange({collabUrl:null,attempts:c,terminal:!1,lastError:d}),o=e.setTimeout(()=>{p()},s),s=Math.min(s*2,r)}};return p(),{cancel:()=>{l=!0,a.abort(),o!==null&&(e.clearTimeout(o),o=null)}}}function Pf(){let e=(0,at.c)(8),t;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t={collabUrl:null,attempts:0,terminal:!1,lastError:null},e[0]=t):t=e[0];let[n,r]=(0,J.useState)(t),i;e[1]===Symbol.for(`react.memo_cache_sentinel`)?(i={token:0},e[1]=i):i=e[1];let a=(0,J.useRef)(i),[o,s]=(0,J.useState)(0),c;e[2]===Symbol.for(`react.memo_cache_sentinel`)?(c=()=>{let e=a.current.token=a.current.token+1,t=kf(typeof window<`u`?window:void 0);if(t){r(Af(t.config));let n=t.onProjectSwitched(t=>{e===a.current.token&&r(Af(t))});return()=>{n()}}let n=Nf({fetchConfig:bf,fallbackUrl:Of,now:Date.now,setTimeout:Rf,clearTimeout:Lf,onStateChange:t=>{e===a.current.token&&r(t)}});return()=>{n.cancel()}},e[2]=c):c=e[2];let l;e[3]===o?l=e[4]:(l=[o],e[3]=o,e[4]=l),(0,J.useEffect)(c,l);let u;e[5]===Symbol.for(`react.memo_cache_sentinel`)?(u=()=>{a.current.token=a.current.token+1,r(If),s(Ff)},e[5]=u):u=e[5];let d=u,f;return e[6]===n?f=e[7]:(f={...n,retry:d},e[6]=n,e[7]=f),f}function Ff(e){return e+1}function If(e){return{...e,terminal:!1,lastError:null}}function Lf(e){return globalThis.clearTimeout(e)}function Rf(e,t){return globalThis.setTimeout(e,t)}function zf(e){return!(e.viewCount>0&&e.viewCount>=50||e.bytes>5e5)}var Bf=new Map,Vf=new Map,Hf=[],Uf=[],Wf=new Set,Gf=null;function Kf(){if(Gf)return Gf;if(typeof document>`u`||typeof document.createElement!=`function`)return null;let e=document.createElement(`div`);return e.setAttribute(`data-ok-editor-parking`,``),e.style.display=`none`,e.style.position=`absolute`,e.style.left=`-99999px`,Gf=e,e}function qf(e){let{docName:t,container:n,factory:r,sizeStats:i}=e;if(i&&!zf(i)){let e=r(n);return Y(`ok/cache/miss`,{docName:t,viewCount:i?.viewCount??-1,bytes:i?.bytes??-1,reason:`size-gate`}),{editor:e.editor,ydoc:e.ydoc,ytext:e.ytext,provider:e.provider,scrollTop:0,hadFocus:!1,activeMountKey:t,__uncached:!0}}let a=Bf.get(t);if(a){if(tp(a,n),a.activeMountKey=t,rp(Hf,t),n.scrollTop=a.scrollTop,a.hadFocus)try{a.editor.commands.focus()}catch{}return Y(`ok/cache/hit`,{docName:t,kind:`tiptap`}),i&&Y(`ok/cold/editor-mount-stats`,{docName:t,viewCount:i.viewCount,bytes:i.bytes,cacheHit:!0,kind:`tiptap`}),a}for(;Bf.size>=10;){let e=ip(Hf,t);if(!e)break;Yf(e)}let o=r(n),s={editor:o.editor,ydoc:o.ydoc,ytext:o.ytext,provider:o.provider,scrollTop:0,hadFocus:!1,activeMountKey:t};return Bf.set(t,s),rp(Hf,t),Y(`ok/cache/miss`,{docName:t,viewCount:i?.viewCount??-1,bytes:i?.bytes??-1,reason:`cold`,kind:`tiptap`}),i&&Y(`ok/cold/editor-mount-stats`,{docName:t,viewCount:i.viewCount,bytes:i.bytes,cacheHit:!1,kind:`tiptap`}),s}function Jf(e){if(e.__uncached){try{e.editor.destroy()}catch{}e.activeMountKey=null;return}let t=$f(e.editor);if(t){e.hadFocus=ep(t.dom),e.scrollTop=(t.scrollDOM??t.dom.parentElement??t.dom).scrollTop??0;let n=t.dom.parentElement;n&&n.removeChild(t.dom);let r=Kf();r&&r.appendChild(t.dom)}e.activeMountKey=null}function Yf(e){let t=Bf.get(e);if(!t)return!1;try{t.editor.destroy()}catch(t){Y(`ok/cache/evict-failed`,{docName:e,kind:`tiptap`,stage:`editor`,message:t instanceof Error?t.message:String(t)})}try{t.provider.destroy()}catch(t){Y(`ok/cache/evict-failed`,{docName:e,kind:`tiptap`,stage:`provider`,message:t instanceof Error?t.message:String(t)})}try{t.ydoc.destroy()}catch(t){Y(`ok/cache/evict-failed`,{docName:e,kind:`tiptap`,stage:`ydoc`,message:t instanceof Error?t.message:String(t)})}Bf.delete(e);let n=Hf.indexOf(e);return n!==-1&&Hf.splice(n,1),Y(`ok/cache/evict`,{docName:e,kind:`tiptap`}),!0}function Xf(e){let{docName:t,container:n,factory:r,sizeStats:i}=e;if(i&&!zf(i)){let e=r(n);return Y(`ok/cache/miss`,{docName:t,viewCount:i?.viewCount??-1,bytes:i?.bytes??-1,reason:`size-gate`,kind:`cm`}),{view:e.view,ydoc:e.ydoc,ytext:e.ytext,provider:e.provider,scrollTop:0,hadFocus:!1,activeMountKey:t,__uncached:!0}}let a=Vf.get(t);if(a){if(np(a,n),a.activeMountKey=t,rp(Uf,t),n.scrollTop=a.scrollTop,a.hadFocus)try{a.view.focus()}catch{}return Y(`ok/cache/hit`,{docName:t,kind:`cm`}),i&&Y(`ok/cold/editor-mount-stats`,{docName:t,viewCount:i.viewCount,bytes:i.bytes,cacheHit:!0,kind:`cm`}),a}for(;Vf.size>=10;){let e=ip(Uf,t);if(!e)break;Qf(e)}let o=r(n),s={view:o.view,ydoc:o.ydoc,ytext:o.ytext,provider:o.provider,scrollTop:0,hadFocus:!1,activeMountKey:t};return Vf.set(t,s),rp(Uf,t),Y(`ok/cache/miss`,{docName:t,viewCount:i?.viewCount??-1,bytes:i?.bytes??-1,reason:`cold`,kind:`cm`}),i&&Y(`ok/cold/editor-mount-stats`,{docName:t,viewCount:i.viewCount,bytes:i.bytes,cacheHit:!1,kind:`cm`}),s}function Zf(e){if(e.__uncached){try{e.view.destroy()}catch{}e.activeMountKey=null;return}let t=e.view.dom;e.hadFocus=ep(t),e.scrollTop=(e.view.scrollDOM??t).scrollTop??0;let n=t.parentElement;n&&n.removeChild(t);let r=Kf();r&&r.appendChild(t),e.activeMountKey=null}function Qf(e){let t=Vf.get(e);if(!t)return!1;try{t.view.destroy()}catch(t){Y(`ok/cache/evict-failed`,{docName:e,kind:`cm`,stage:`view`,message:t instanceof Error?t.message:String(t)})}try{t.provider.destroy()}catch(t){Y(`ok/cache/evict-failed`,{docName:e,kind:`cm`,stage:`provider`,message:t instanceof Error?t.message:String(t)})}try{t.ydoc.destroy()}catch(t){Y(`ok/cache/evict-failed`,{docName:e,kind:`cm`,stage:`ydoc`,message:t instanceof Error?t.message:String(t)})}Vf.delete(e);let n=Uf.indexOf(e);return n!==-1&&Uf.splice(n,1),Y(`ok/cache/evict`,{docName:e,kind:`cm`}),!0}function $f(e){return e.editorView??null}function ep(e){if(typeof document>`u`)return!1;let t=document.activeElement;return t?t===e?!0:e.contains(t):!1}function tp(e,t){let n=$f(e.editor);if(!n)return;let r=n.dom,i=r.parentElement;i&&i!==t&&i.removeChild(r),r.parentElement!==t&&t.appendChild(r)}function np(e,t){let n=e.view.dom,r=n.parentElement;r&&r!==t&&r.removeChild(n),n.parentElement!==t&&t.appendChild(n)}function rp(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1),e.push(t)}function ip(e,t){for(let n of e)if(n!==t&&!Wf.has(n))return n;Y(`ok/cache/evict-fallback-activity-saturated`,{mountingDocName:t,lruLength:e.length,activityMountCount:Wf.size});for(let n of e)if(n!==t)return n;return null}function ap(e){let t=Wf,n=new Set(e);for(let e of t){if(n.has(e))continue;let t=op(e);if(t)try{t.disconnect(),Y(`ok/cache/disconnect`,{docName:e})}catch(t){Y(`ok/cache/disconnect-failed`,{docName:e,message:t instanceof Error?t.message:String(t)})}}for(let e of n){if(t.has(e))continue;let n=op(e);if(!n)continue;let r=t=>{Y(`ok/cache/connect-failed`,{docName:e,message:t instanceof Error?t.message:String(t)})};try{let t=n.connect();t&&typeof t.then==`function`?t.then(()=>Y(`ok/cache/connect`,{docName:e}),e=>r(e)):Y(`ok/cache/connect`,{docName:e})}catch(e){r(e)}}Wf=n}function op(e){let t=Bf.get(e);if(t)return t.provider;let n=Vf.get(e);return n?n.provider:null}function sp(e){return e.onEvict(e=>{Yf(e),Qf(e)})}var cp=Math.floor,lp=(e,t)=>e<t?e:t,up=(e,t)=>e>t?e:t;Number.isNaN;var dp=128,fp=1<<17,pp=1<<18,mp=1<<19,hp=1<<20,gp=1<<21,_p=1<<22,vp=1<<23,yp=1<<24,bp=1<<25,xp=1<<26,Sp=1<<27,Cp=1<<28,wp=1<<29,Tp=1<<30,Ep=127;fp-1,pp-1,mp-1,hp-1,gp-1,_p-1,vp-1,yp-1,bp-1,xp-1,Sp-1,Cp-1,wp-1,Tp-1;var Dp=2**53-1;Number.isInteger,Number.isNaN,Number.parseInt;var Op=String.fromCharCode;String.fromCodePoint,Op(65535);var kp=e=>{let t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r},Ap=typeof TextEncoder<`u`?new TextEncoder:null,jp=Ap?e=>Ap.encode(e):kp,Mp=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});Mp&&Mp.decode(new Uint8Array).length===1&&(Mp=null);var Np=(e,t)=>{let n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Pp=(e,t)=>{for(;t>Ep;)Np(e,dp|Ep&t),t=cp(t/128);Np(e,Ep&t)},Fp=new Uint8Array(3e4),Ip=Fp.length/3,Lp=Ap&&Ap.encodeInto?(e,t)=>{if(t.length<Ip){let n=Ap.encodeInto(t,Fp).written||0;Pp(e,n);for(let t=0;t<n;t++)Np(e,Fp[t])}else zp(e,jp(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;Pp(e,r);for(let t=0;t<r;t++)Np(e,n.codePointAt(t))},Rp=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=lp(n-r,t.length),a=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,a>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(up(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},zp=(e,t)=>{Pp(e,t.byteLength),Rp(e,t)},Bp=e=>Error(e),Vp=Bp(`Unexpected end of array`),Hp=Bp(`Integer out of Range`),Up=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},Wp=e=>Up(e,Kp(e)),Gp=e=>e.arr[e.pos++],Kp=e=>{let t=0,n=1,r=e.arr.length;for(;e.pos<r;){let r=e.arr[e.pos++];if(t+=(r&Ep)*n,n*=128,r<dp)return t;if(t>Dp)throw Hp}throw Vp},qp=Mp?e=>Mp.decode(Wp(e)):e=>{let t=Kp(e);if(t===0)return``;{let n=String.fromCodePoint(Gp(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Gp(e));else for(;t>0;){let r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}},Jp=function(e){return e[e.Token=0]=`Token`,e[e.PermissionDenied=1]=`PermissionDenied`,e[e.Authenticated=2]=`Authenticated`,e}({}),Yp=(e,t)=>{Pp(e,Jp.Token),Lp(e,t)},Xp=(e,t,n,r)=>{switch(Kp(e)){case Jp.Token:t();break;case Jp.PermissionDenied:n(qp(e));break;case Jp.Authenticated:r(qp(e));break;default:}},Zp=e=>Array.from(e.entries()).map(([e,t])=>({clientId:e,...t})),Qp=`\0`;function $p(e,t){return e+Qp+t}function em(e){let t=e.indexOf(Qp);return t===-1?{documentName:e,sessionId:null}:{documentName:e.substring(0,t),sessionId:e.substring(t+1)}}var tm=function(e){return e[e.Connecting=0]=`Connecting`,e[e.Open=1]=`Open`,e[e.Closing=2]=`Closing`,e[e.Closed=3]=`Closed`,e}({});function nm(e){return e||={},{delay:e.delay===void 0?200:e.delay,initialDelay:e.initialDelay===void 0?0:e.initialDelay,minDelay:e.minDelay===void 0?0:e.minDelay,maxDelay:e.maxDelay===void 0?0:e.maxDelay,factor:e.factor===void 0?0:e.factor,maxAttempts:e.maxAttempts===void 0?3:e.maxAttempts,timeout:e.timeout===void 0?0:e.timeout,jitter:e.jitter===!0,initialJitter:e.initialJitter===!0,handleError:e.handleError===void 0?null:e.handleError,handleTimeout:e.handleTimeout===void 0?null:e.handleTimeout,beforeAttempt:e.beforeAttempt===void 0?null:e.beforeAttempt,calculateDelay:e.calculateDelay===void 0?null:e.calculateDelay}}async function rm(e){return new Promise(t=>setTimeout(t,e))}function im(e,t){let n=t.delay;if(n===0)return 0;if(t.factor&&(n*=t.factor**(e.attemptNum-1),t.maxDelay!==0&&(n=Math.min(n,t.maxDelay))),t.jitter){let e=Math.ceil(t.minDelay);n=Math.floor(Math.random()*(Math.floor(n)-e+1))+e}return Math.round(n)}async function am(e,t){let n=nm(t);for(let e of[`delay`,`initialDelay`,`minDelay`,`maxDelay`,`maxAttempts`,`timeout`]){let t=n[e];if(!Number.isInteger(t)||t<0)throw Error(`Value for ${e} must be an integer greater than or equal to 0`)}if(n.factor.constructor!==Number||n.factor<0)throw Error(`Value for factor must be a number greater than or equal to 0`);if(n.delay<n.minDelay)throw Error(`delay cannot be less than minDelay (delay: ${n.delay}, minDelay: ${n.minDelay}`);let r={attemptNum:0,attemptsRemaining:n.maxAttempts?n.maxAttempts:-1,aborted:!1,abort(){r.aborted=!0}},i=n.calculateDelay||im;async function a(){if(n.beforeAttempt&&n.beforeAttempt(r,n),r.aborted){let e=Error(`Attempt aborted`);throw e.code=`ATTEMPT_ABORTED`,e}let t=async e=>{if(n.handleError&&await n.handleError(e,r,n),r.aborted||r.attemptsRemaining===0)throw e;r.attemptNum++;let t=i(r,n);return t&&await rm(t),a()};return r.attemptsRemaining>0&&r.attemptsRemaining--,n.timeout?new Promise((i,a)=>{let o=setTimeout(()=>{if(n.handleTimeout)try{i(n.handleTimeout(r,n))}catch(e){a(e)}else{let e=Error(`Retry timeout (attemptNum: ${r.attemptNum}, timeout: ${n.timeout})`);e.code=`ATTEMPT_TIMEOUT`,a(e)}},n.timeout);e(r,n).then(e=>{clearTimeout(o),i(e)}).catch(e=>{clearTimeout(o),t(e).then(i).catch(a)})}):e(r,n).catch(t)}let o=n.calculateDelay?n.calculateDelay(r,n):n.initialDelay;if(o&&await rm(o),r.attemptNum<1&&n.initialJitter){let e=i(r,n);e&&await rm(e)}return a()}var om=Math.floor,sm=(e,t)=>e<t?e:t,cm=(e,t)=>e>t?e:t;Number.isNaN;var lm=64,um=128,dm=1<<17,fm=1<<18,pm=1<<19,mm=1<<20,hm=1<<21,gm=1<<22,_m=1<<23,vm=1<<24,ym=1<<25,bm=1<<26,xm=1<<27,Sm=1<<28,Cm=1<<29,wm=1<<30,Tm=63,Em=127;dm-1,fm-1,pm-1,mm-1,hm-1,gm-1,_m-1,vm-1,ym-1,bm-1,xm-1,Sm-1,Cm-1,wm-1;var Dm=2**53-1;Number.isInteger,Number.isNaN,Number.parseInt;var Om=()=>new Set,km=Array.from;Array.isArray;var Am=String.fromCharCode;String.fromCodePoint,Am(65535);var jm=e=>{let t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r},Mm=typeof TextEncoder<`u`?new TextEncoder:null,Nm=Mm?e=>Mm.encode(e):jm,Pm=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});Pm&&Pm.decode(new Uint8Array).length===1&&(Pm=null);var Fm=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}},Im=()=>new Fm,Lm=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},Rm=e=>{let t=new Uint8Array(Lm(e)),n=0;for(let r=0;r<e.bufs.length;r++){let i=e.bufs[r];t.set(i,n),n+=i.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t},zm=(e,t)=>{let n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Bm=(e,t)=>{for(;t>Em;)zm(e,um|Em&t),t=om(t/128);zm(e,Em&t)},Vm=new Uint8Array(3e4),Hm=Vm.length/3,Um=Mm&&Mm.encodeInto?(e,t)=>{if(t.length<Hm){let n=Mm.encodeInto(t,Vm).written||0;Bm(e,n);for(let t=0;t<n;t++)zm(e,Vm[t])}else Gm(e,Nm(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;Bm(e,r);for(let t=0;t<r;t++)zm(e,n.codePointAt(t))},Wm=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=sm(n-r,t.length),a=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,a>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(cm(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},Gm=(e,t)=>{Bm(e,t.byteLength),Wm(e,t)},Km=e=>Error(e),qm=Km(`Unexpected end of array`),Jm=Km(`Integer out of Range`),Ym=class{constructor(e){this.arr=e,this.pos=0}},Xm=e=>new Ym(e),Zm=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},Qm=e=>Zm(e,eh(e)),$m=e=>e.arr[e.pos++],eh=e=>{let t=0,n=1,r=e.arr.length;for(;e.pos<r;){let r=e.arr[e.pos++];if(t+=(r&Em)*n,n*=128,r<um)return t;if(t>Dm)throw Jm}throw qm},th=e=>{let t=e.arr[e.pos++],n=t&Tm,r=64,i=(t&lm)>0?-1:1;if((t&um)===0)return i*n;let a=e.arr.length;for(;e.pos<a;){if(t=e.arr[e.pos++],n+=(t&Em)*r,r*=128,t<um)return i*n;if(n>Dm)throw Jm}throw qm},nh=Pm?e=>Pm.decode(Qm(e)):e=>{let t=eh(e);if(t===0)return``;{let n=String.fromCodePoint($m(e));if(--t<100)for(;t--;)n+=String.fromCodePoint($m(e));else for(;t>0;){let r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}},rh=e=>{let t=e.pos,n=nh(e);return e.pos=t,n},ih=Date.now,ah=()=>new Map,oh=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r},sh=class{constructor(){this._observers=ah()}on(e,t){oh(this._observers,e,Om).add(t)}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){let n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return km((this._observers.get(e)||ah()).values()).forEach(e=>e(...t))}destroy(){this._observers=ah()}},ch=Symbol(`Equality`),lh=Object.keys,uh=e=>lh(e).length,dh=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),fh=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[ch]!=null)return e[ch](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;break;case Set:if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;break;case Map:if(e.size!==t.size)return!1;for(let n of e.keys())if(!t.has(n)||!fh(e.get(n),t.get(n)))return!1;break;case void 0:case Object:if(uh(e)!==uh(t))return!1;for(let n in e)if(!dh(e,n)||!fh(e[n],t[n]))return!1;break;case Array:if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!fh(e[n],t[n]))return!1;break;default:return!1}return!0},ph=3e4,mh=class extends sh{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let e=ih();this.getLocalState()!==null&&ph/2<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&ph<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&hh(this,t,`timeout`)},om(ph/10)),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){let t=this.clientID,n=this.meta.get(t),r=n===void 0?0:n.clock+1,i=this.states.get(t);e===null?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:r,lastUpdated:ih()});let a=[],o=[],s=[],c=[];e===null?c.push(t):i==null?e!=null&&a.push(t):(o.push(t),fh(i,e)||s.push(t)),(a.length>0||s.length>0||c.length>0)&&this.emit(`change`,[{added:a,updated:s,removed:c},`local`]),this.emit(`update`,[{added:a,updated:o,removed:c},`local`])}setLocalStateField(e,t){let n=this.getLocalState();n!==null&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}},hh=(e,t,n)=>{let r=[];for(let n=0;n<t.length;n++){let i=t[n];if(e.states.has(i)){if(e.states.delete(i),i===e.clientID){let t=e.meta.get(i);e.meta.set(i,{clock:t.clock+1,lastUpdated:ih()})}r.push(i)}}r.length>0&&(e.emit(`change`,[{added:[],updated:[],removed:r},n]),e.emit(`update`,[{added:[],updated:[],removed:r},n]))},gh=(e,t,n=e.states)=>{let r=t.length,i=Im();Bm(i,r);for(let a=0;a<r;a++){let r=t[a],o=n.get(r)||null,s=e.meta.get(r).clock;Bm(i,r),Bm(i,s),Um(i,JSON.stringify(o))}return Rm(i)},_h=(e,t,n)=>{let r=Xm(t),i=ih(),a=[],o=[],s=[],c=[],l=eh(r);for(let t=0;t<l;t++){let t=eh(r),n=eh(r),l=JSON.parse(nh(r)),u=e.meta.get(t),d=e.states.get(t),f=u===void 0?0:u.clock;(f<n||f===n&&l===null&&e.states.has(t))&&(l===null?t===e.clientID&&e.getLocalState()!=null?n++:e.states.delete(t):e.states.set(t,l),e.meta.set(t,{clock:n,lastUpdated:i}),u===void 0&&l!==null?a.push(t):u!==void 0&&l===null?c.push(t):l!==null&&(fh(l,d)||s.push(t),o.push(t)))}(a.length>0||s.length>0||c.length>0)&&e.emit(`change`,[{added:a,updated:s,removed:c},n]),(a.length>0||o.length>0||c.length>0)&&e.emit(`update`,[{added:a,updated:o,removed:c},n])},vh=class{constructor(){this.callbacks={}}on(e,t){return this.callbacks[e]||(this.callbacks[e]=[]),this.callbacks[e].push(t),this}emit(e,...t){let n=this.callbacks[e];return n&&n.forEach(e=>e.apply(this,t)),this}off(e,t){let n=this.callbacks[e];return n&&(t?this.callbacks[e]=n.filter(e=>e!==t):delete this.callbacks[e]),this}removeAllListeners(){this.callbacks={}}},yh=class{constructor(e){this.data=e,this.encoder=Im(),this.decoder=Xm(new Uint8Array(this.data))}peekVarString(){return rh(this.decoder)}readVarUint(){return eh(this.decoder)}readVarString(){return nh(this.decoder)}readVarUint8Array(){return Qm(this.decoder)}writeVarUint(e){return Bm(this.encoder,e)}writeVarString(e){return Um(this.encoder,e)}writeVarUint8Array(e){return Gm(this.encoder,e)}length(){return Lm(this.encoder)}},bh=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}({}),xh=function(e){return e.Connecting=`connecting`,e.Connected=`connected`,e.Disconnected=`disconnected`,e}({}),Sh=class{constructor(){this.encoder=Im()}get(e){return e.encoder}toUint8Array(){return Rm(this.encoder)}},Ch=class extends Sh{constructor(...e){super(...e),this.type=bh.CLOSE,this.description=`Ask the server to close the connection`}get(e){return Um(this.encoder,e.documentName),Bm(this.encoder,this.type),this.encoder}},wh=class e extends vh{static{this.DEDUPLICATABLE_TYPES=new Set([bh.Awareness,bh.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=xh.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=xh.Connected,this.emit(`status`,{status:xh.Connected}),this.cancelWebsocketRetry=void 0,this.receivedOnOpenPayload=e}attach(e){let t=e.effectiveName,n=this.configuration.providerMap.get(t);if(n&&n!==e&&n.isAuthenticated)throw 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===xh.Disconnected&&this.shouldConnect&&this.connect(),this.receivedOnOpenPayload&&this.status===xh.Connected&&e.onOpen(this.receivedOnOpenPayload)}detach(e){let t=e.effectiveName;this.configuration.providerMap.has(t)&&(e.send(Ch,{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===xh.Connected)return;this.cancelWebsocketRetry&&=(this.cancelWebsocketRetry(),void 0),this.receivedOnOpenPayload=void 0,this.shouldConnect=!0;let{retryPromise:e,cancelFunc:t}=(()=>{let e=!1;return{retryPromise:am(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&&e.code!==`ATTEMPT_ABORTED`)throw e}),cancelFunc:()=>{e=!0}}})();return this.cancelWebsocketRetry=t,e}attachWebSocketListeners(e,t){let{identifier:n}=e,r=e=>this.emit(`message`,e),i=e=>this.emit(`close`,{event:e}),a=e=>this.emit(`open`,e),o=e=>{t(e)};this.webSocketHandlers[n]={message:r,close:i,open:a,error:o};let s=this.webSocketHandlers[e.identifier];Object.keys(s).forEach(t=>{e.addEventListener(t,s[t])})}cleanupWebSocket(){if(!this.webSocket)return;let{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;let n=new this.configuration.WebSocketPolyfill(this.url);n.binaryType=`arraybuffer`,n.identifier=this.identifier,this.attachWebSocketListeners(n,t),this.webSocket=n,this.status=xh.Connecting,this.emit(`status`,{status:xh.Connecting}),this.connectionAttempt={resolve:e,reject:t}})}onMessage(e){this.resolveConnectionAttempt(),this.lastMessageReceived=ih();let t=new Uint8Array(e.data);if(t.length===1&&t[0]===bh.Ping){this.sendPong();return}let n=new yh(t).peekVarString();this.configuration.providerMap.get(n)?.onMessage(e)}sendPong(){let e=Im();Bm(e,bh.Pong),this.send(Rm(e))}resolveConnectionAttempt(){this.connectionAttempt&&(this.connectionAttempt.resolve(),this.connectionAttempt=null,this.status=xh.Connected,this.emit(`status`,{status:xh.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===xh.Connected&&this.lastMessageReceived&&(this.configuration.messageReconnectTimeout>=ih()-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,this.webSocket!==null)try{this.webSocket.close(),this.messageQueue=[]}catch(e){console.error(e)}}parseQueuedMessage(e){try{let t=Xm(e);return{documentName:nh(t),messageType:eh(t)}}catch{return null}}addToQueue(t){if(t instanceof Uint8Array){let n=this.parseQueuedMessage(t);n&&e.DEDUPLICATABLE_TYPES.has(n.messageType)&&(this.messageQueue=this.messageQueue.filter(e=>{if(!(e instanceof Uint8Array))return!0;let t=this.parseQueuedMessage(e);return t?!(t.documentName===n.documentName&&t.messageType===n.messageType):!0}))}this.messageQueue.push(t)}send(e){this.webSocket?.readyState===tm.Open?this.webSocket.send(e):this.addToQueue(e)}onClose({event:e}){this.closeTries=0,this.cleanupWebSocket(),this.connectionAttempt&&this.rejectConnectionAttempt(),this.status=xh.Disconnected,this.emit(`status`,{status:xh.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()}},Th=0,Eh=1,Dh=2,Oh=(e,t)=>{Bm(e,Th),Gm(e,Ys(t))},kh=(e,t,n)=>{Bm(e,Eh),Gm(e,Us(t,n))},Ah=(e,t,n)=>kh(t,n,Qm(e)),jh=(e,t,n,r)=>{try{Bs(t,Qm(e),n)}catch(e){r?.(e),console.error(`Caught error while handling a Yjs update`,e)}},Mh=(e,t)=>{Bm(e,Dh),Gm(e,t)},Nh=jh,Ph=(e,t,n,r,i)=>{let a=eh(e);switch(a){case Th:Ah(e,t,n);break;case Eh:jh(e,n,r,i);break;case Dh:Nh(e,n,r,i);break;default:throw Error(`Unknown message type`)}return a},Fh=class{constructor(e){this.message=e}apply(e,t){let{message:n}=this,r=n.readVarUint(),i=n.length();switch(r){case bh.Sync:this.applySyncMessage(e,t);break;case bh.Awareness:this.applyAwarenessMessage(e);break;case bh.Auth:this.applyAuthMessage(e);break;case bh.QueryAwareness:this.applyQueryAwarenessMessage(e);break;case bh.Stateless:e.receiveStateless(nh(n.decoder));break;case bh.SyncStatus:this.applySyncStatusMessage(e,th(n.decoder)===1);break;case bh.CLOSE:let i={code:1e3,reason:nh(n.decoder)};e.onClose(),e.configuration.onClose({event:i}),e.forwardClose({event:i});break;default:console.error(`Can’t apply message of unknown type: ${r}`)}n.length()>i+1&&e.send(Sh,{encoder:n.encoder})}applySyncMessage(e,t){let{message:n}=this;n.writeVarUint(bh.Sync);let r=Ph(n.decoder,n.encoder,e.document,e);t&&r===Eh&&(e.synced=!0)}applySyncStatusMessage(e,t){t&&e.decrementUnsyncedChanges()}applyAwarenessMessage(e){if(!e.awareness)return;let{message:t}=this;_h(e.awareness,t.readVarUint8Array(),e)}applyAuthMessage(e){let{message:t}=this;Xp(t.decoder,e.sendToken.bind(e),e.permissionDeniedHandler.bind(e),e.authenticatedHandler.bind(e))}applyQueryAwarenessMessage(e){if(!e.awareness)return;let{message:t}=this;t.writeVarUint(bh.Awareness),t.writeVarUint8Array(gh(e.awareness,Array.from(e.awareness.getStates().keys())))}},Ih=class{constructor(e,t={}){this.message=new e,this.encoder=this.message.get(t)}create(){return Rm(this.encoder)}send(e){e?.send(this.create())}},Lh=`4.0.0-rc.1`,Rh=class extends Sh{constructor(...e){super(...e),this.type=bh.Auth,this.description=`Authentication`}get(e){if(e.token===void 0)throw Error("The authentication message requires `token` as an argument.");return Um(this.encoder,e.documentName),Bm(this.encoder,this.type),Yp(this.encoder,e.token),Um(this.encoder,Lh),this.encoder}},zh=class extends Sh{constructor(...e){super(...e),this.type=bh.Awareness,this.description=`Awareness states update`}get(e){if(e.awareness===void 0)throw Error(`The awareness message requires awareness as an argument`);if(e.clients===void 0)throw Error(`The awareness message requires clients as an argument`);Um(this.encoder,e.documentName),Bm(this.encoder,this.type);let t;return t=e.states===void 0?gh(e.awareness,e.clients):gh(e.awareness,e.clients,e.states),Gm(this.encoder,t),this.encoder}},Bh=class extends Sh{constructor(...e){super(...e),this.type=bh.Stateless,this.description=`A stateless message`}get(e){return Um(this.encoder,e.documentName),Bm(this.encoder,this.type),Um(this.encoder,e.payload??``),this.encoder}},Vh=class extends Sh{constructor(...e){super(...e),this.type=bh.Sync,this.description=`First sync step`}get(e){if(e.document===void 0)throw Error(`The sync step one message requires document as an argument`);return Um(this.encoder,e.documentName),Bm(this.encoder,this.type),Oh(this.encoder,e.document),this.encoder}},Hh=class extends Sh{constructor(...e){super(...e),this.type=bh.Sync,this.description=`A document update`}get(e){return Um(this.encoder,e.documentName),Bm(this.encoder,this.type),Mh(this.encoder,e.update),this.encoder}},Uh=class extends Error{constructor(...e){super(...e),this.code=1001}},Wh=class extends vh{get effectiveName(){return this.configuration.sessionAwareness?$p(this.configuration.name,this.sessionId):this.configuration.name}constructor(e){super(),this.configuration={name:``,document:void 0,awareness:void 0,token:null,sessionAwareness:!0,forceSyncInterval:!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.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 ws,this.configuration.awareness=e.awareness===void 0?new mh(this.document):e.awareness,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:Zp(this.awareness.getStates())})}),this.awareness?.on(`change`,()=>{this.emit(`awarenessChange`,{states:Zp(this.awareness.getStates())})}),this.document.on(`update`,this.boundDocumentUpdateHandler),this.awareness?.on(`update`,this.boundAwarenessUpdateHandler),this.registerEventListeners(),this.configuration.forceSyncInterval&&typeof this.configuration.forceSyncInterval==`number`&&(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 wh(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,this.unsyncedChanges===0&&(this.synced=!0),this.emit(`unsyncedChanges`,{number:this.unsyncedChanges})}forceSync(){this.resetUnsyncedChanges(),this.send(Vh,{document:this.document,documentName:this.effectiveName})}pageHide(){this.awareness&&hh(this.awareness,[this.document.clientID],`page hide`)}registerEventListeners(){typeof window>`u`||!(`addEventListener`in window)||window.addEventListener(`pagehide`,this.boundPageHide)}sendStateless(e){this.send(Bh,{documentName:this.effectiveName,payload:e})}async sendToken(){let e;try{e=await this.getToken()}catch(e){this.permissionDeniedHandler(`Failed to get token during sendToken(): ${e}`);return}this.send(Rh,{token:e??``,documentName:this.effectiveName})}documentUpdateHandler(e,t){t!==this&&(this.incrementUnsyncedChanges(),this.send(Hh,{update:e,documentName:this.effectiveName}))}awarenessUpdateHandler({added:e,updated:t,removed:n},r){let i=e.concat(t).concat(n);this.send(zh,{awareness:this.awareness,clients:i,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();console.warn(`HocuspocusProvider::connect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.`)}disconnect(){if(this.manageSocket)return this.configuration.websocketProvider.disconnect();console.warn(`HocuspocusProvider::disconnect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.`)}async onOpen(e){this.isAuthenticated=!1,this.emit(`open`,{event:e}),await this.sendToken(),this.startSync()}async getToken(){return typeof this.configuration.token==`function`?await this.configuration.token():this.configuration.token}startSync(){this.resetUnsyncedChanges(),this.send(Vh,{document:this.document,documentName:this.effectiveName}),this.awareness&&this.awareness.getLocalState()!==null&&this.send(zh,{awareness:this.awareness,clients:[this.document.clientID],documentName:this.effectiveName})}send(e,t){if(!this._isAttached)return;let n=new Ih(e,t);this.emit(`outgoingMessage`,{message:n.message}),n.send(this.configuration.websocketProvider)}onMessage(e){let t=new yh(e.data),{documentName:n}=em(t.readVarString());t.writeVarString(this.effectiveName),this.emit(`message`,{event:e,message:new yh(e.data)}),new Fh(t).apply(this,!0)}onClose(){this.isAuthenticated=!1,this.synced=!1,this.awareness&&hh(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&&(hh(this.awareness,[this.document.clientID],`provider destroy`),this.awareness.off(`update`,this.boundAwarenessUpdateHandler),this.awareness.destroy()),this.document.off(`update`,this.boundDocumentUpdateHandler),this.removeAllListeners(),this.detach(),this.manageSocket&&this.configuration.websocketProvider.destroy(),!(typeof window>`u`||!(`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),!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 Uh(`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)}},Gh=e=>ji((t,n)=>{e.onerror=e=>n(Error(e.target.error)),e.onsuccess=e=>t(e.target.result)}),Kh=(e,t)=>ji((n,r)=>{let i=indexedDB.open(e);i.onupgradeneeded=e=>t(e.target.result),i.onerror=e=>r(ii(e.target.error)),i.onsuccess=e=>{let t=e.target.result;t.onversionchange=()=>{t.close()},n(t)}}),qh=e=>Gh(indexedDB.deleteDatabase(e)),Jh=(e,t)=>t.forEach(t=>e.createObjectStore.apply(e,t)),Yh=(e,t,n=`readwrite`)=>{let r=e.transaction(t,n);return t.map(e=>og(r,e))},Xh=(e,t)=>Gh(e.count(t)),Zh=(e,t)=>Gh(e.get(t)),Qh=(e,t)=>Gh(e.delete(t)),$h=(e,t,n)=>Gh(e.put(t,n)),eg=(e,t)=>Gh(e.add(t)),tg=(e,t,n)=>Gh(e.getAll(t,n)),ng=(e,t,n)=>{let r=null;return ag(e,t,e=>(r=e,!1),n).then(()=>r)},rg=(e,t=null)=>ng(e,t,`prev`),ig=(e,t)=>ji((n,r)=>{e.onerror=r,e.onsuccess=async e=>{let r=e.target.result;if(r===null||await t(r)===!1)return n();r.continue()}}),ag=(e,t,n,r=`next`)=>ig(e.openKeyCursor(t,r),e=>n(e.key)),og=(e,t)=>e.objectStore(t),sg=(e,t)=>IDBKeyRange.upperBound(e,t),cg=(e,t)=>IDBKeyRange.lowerBound(e,t),lg=`custom`,ug=`updates`,dg=(e,t=()=>{},n=()=>{})=>{let[r]=Yh(e.db,[ug]);return tg(r,cg(e._dbref,!1)).then(i=>{e._destroyed||(t(r),Rc(e.doc,()=>{i.forEach(t=>Bs(e.doc,t))},e,!1),n(r))}).then(()=>rg(r).then(t=>{e._dbref=t+1})).then(()=>Xh(r).then(t=>{e._dbsize=t})).then(()=>r)},fg=(e,t=!0)=>dg(e).then(n=>{(t||e._dbsize>=500)&&eg(n,Us(e.doc)).then(()=>Qh(n,sg(e._dbref,!0))).then(()=>Xh(n).then(t=>{e._dbsize=t}))}),pg=class extends Qn{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=Kh(e,e=>Jh(e,[[`updates`,{autoIncrement:!0}],[`custom`]])),this.whenSynced=ji(e=>this.on(`synced`,()=>e(this))),this._db.then(e=>{this.db=e,dg(this,async e=>{await Xh(e)>0&&eg(e,Us(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){let[t]=Yh(this.db,[ug]);eg(t,e).catch(e=>{globalThis.__okYdbWriteWarned||(globalThis.__okYdbWriteWarned=!0,console.warn(JSON.stringify({event:`ok-ydb-write-failed`,cause:e?.name??`unknown`,message:e?.message??String(e)})))}),++this._dbsize>=500&&(this._storeTimeoutId!==null&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{fg(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(()=>{qh(this.name)})}get(e){return this._db.then(t=>{let[n]=Yh(t,[lg],`readonly`);return Zh(n,e)})}set(e,t){return this._db.then(n=>{let[r]=Yh(n,[lg]);return $h(r,t,e)})}del(e){return this._db.then(t=>{let[n]=Yh(t,[lg]);return Qh(n,e)})}},mg=class{_idb;_dbName;whenSynced;constructor({branch:e,docName:t,doc:n}){this._dbName=`ok-ydoc:${e}:${t}`,this._idb=new pg(this._dbName,n),this.whenSynced=this._idb.whenSynced.then(()=>this)}get synced(){return this._idb.synced}async destroy(){await this._idb.destroy()}async clearData(){await this._idb.destroy();let e=this._dbName;await new Promise((t,n)=>{let r=indexedDB.deleteDatabase(e);r.onsuccess=()=>t(),r.onerror=()=>n(r.error),r.onblocked=()=>{console.warn(JSON.stringify({event:`ok-client-persistence-clear-blocked`,dbName:e})),n(Error(`idb-clear-blocked: ${e}`))}})}};function hg(e){return new mg(e)}function gg(e){return Ys(e)}function _g(e,t){return t===null?Us(e):Us(e,t)}function vg(e,t){if(e===null)return t;if(t===null)return e;let n=Gs(e),r=Gs(t),i=new Map;for(let[e,t]of n)i.set(e,t);for(let[e,t]of r){let n=i.get(e);(n===void 0||t>n)&&i.set(e,t)}return Ys(i)}function yg(e){let t={};if(r.inject(n.active(),t),!t.traceparent)return e;let i=e.includes(`?`)?`&`:`?`,a=[`traceparent=${encodeURIComponent(t.traceparent)}`];return t.tracestate&&a.push(`tracestate=${encodeURIComponent(t.tracestate)}`),`${e}${i}${a.join(`&`)}`}var bg=({key:e,editor:t,onPaste:n,onDrop:r,allowedMimeTypes:i})=>new E({key:e||new be(`fileHandler`),props:{handleDrop(e,n){if(!r||!n.dataTransfer?.files.length)return!1;let a=e.posAtCoords({left:n.clientX,top:n.clientY}),o=Array.from(n.dataTransfer.files);return i&&(o=o.filter(e=>i.includes(e.type))),o.length===0?!1:(n.preventDefault(),n.stopPropagation(),r(t,o,a?.pos||0),!0)},handlePaste(e,r){if(!n||!r.clipboardData?.files.length)return!1;let a=Array.from(r.clipboardData.files),o=r.clipboardData.getData(`text/html`);return i&&(a=a.filter(e=>i.includes(e.type))),!(a.length===0||(r.preventDefault(),r.stopPropagation(),n(t,a,o),o.length>0))}}}),xg=fe.create({name:`fileHandler`,addOptions(){return{onPaste:void 0,onDrop:void 0,allowedMimeTypes:void 0}},addProseMirrorPlugins(){return[bg({key:new be(this.name),editor:this.editor,allowedMimeTypes:this.options.allowedMimeTypes,onDrop:this.options.onDrop,onPaste:this.options.onPaste})]}}),Sg=new be(`imageUpload`);function Cg(){let e=document.createElement(`div`);return e.className=`image-upload-skeleton w-full h-40 rounded-md bg-muted animate-pulse motion-reduce:animate-none my-2`,e.setAttribute(`data-upload-widget`,`loading`),e.setAttribute(`role`,`status`),e.setAttribute(`aria-label`,`Uploading image...`),e}var wg=new E({key:Sg,state:{init(){return{decorations:A.empty,uploads:new Map}},apply(e,t){let n=t.decorations.map(e.mapping,e.doc),r=new Map;for(let[n,i]of t.uploads)r.set(n,e.mapping.map(i));let i=e.getMeta(Sg);if(!i)return{decorations:n,uploads:r};if(i.type===`add`){let t=j.widget(i.pos,i.widget,{id:i.id,stopEvent:()=>!0}),a=n.add(e.doc,[t]),o=new Map(r);return o.set(i.id,e.mapping.map(i.pos)),{decorations:a,uploads:o}}if(i.type===`remove`){let e=n.find(void 0,void 0,e=>e.id===i.id),t=n.remove(e),a=new Map(r);return a.delete(i.id),{decorations:t,uploads:a}}return{decorations:n,uploads:r}}},props:{decorations(e){return Sg.getState(e)?.decorations??A.empty}}}),Tg=null;function Eg(e){Tg=e}async function Dg(e,t,n){let r=Tg?`${Tg}.md`:``;if(!r){d.error(`Cannot upload: no document is open`);return}let i=crypto.randomUUID(),a=Cg();t.view.dispatch(t.state.tr.setMeta(Sg,{type:`add`,id:i,pos:n,widget:a}));let o=new FormData;o.append(`file`,e),o.append(`parentDocName`,r);let s;try{s=await fetch(`/api/upload-image`,{method:`POST`,body:o})}catch(e){console.error(`[uploadAndInsert] Network error:`,e),Og(t,i);return}if(!s.ok){let e=`Upload failed (${s.status})`;try{let t=await s.json();t.error&&(e=t.error)}catch{}console.error(`[uploadAndInsert] Server error:`,e),Og(t,i,e);return}let c;try{let e=await s.json();if(typeof e.src!=`string`)throw Error(`missing src in response`);c=e.src}catch(e){console.error(`[uploadAndInsert] Response parse error:`,e),Og(t,i);return}let l=e.name.replace(/\.[^.]+$/,``),{state:u}=t,f=Sg.getState(u)?.uploads.get(i)??n,p=u.schema.nodes.image;if(!p){console.error(`[uploadAndInsert] Image node type not found in schema`),Og(t,i);return}let m=u.tr.setMeta(Sg,{type:`remove`,id:i}).insert(f,p.create({src:c,alt:l}));t.view.dispatch(m)}function Og(e,t,n){e.view.dispatch(e.state.tr.setMeta(Sg,{type:`remove`,id:t})),d.error(n??`Upload failed`)}function kg(e){let{$from:t}=e.selection;return t.depth===0?null:{from:t.before(1),to:t.after(1)}}function Ag(e,t){let n=kg(e);if(!n)return!1;let{from:r,to:i}=n;if(r===0)return!1;let a=e.doc.resolve(r-1);if(a.depth===0)return!1;let o=a.before(1),s=e.doc.slice(r,i).content,c=e.doc.slice(o,r).content;if(!t)return!0;let l=e.tr;l.replaceWith(o,i,s.append(c));let u=o+1,d=o+s.size,f=e.selection.from-r,p=Math.min(u+f,d);return l.setSelection(H.near(l.doc.resolve(p))),l.scrollIntoView(),t(l),!0}function jg(e,t){let n=kg(e);if(!n)return!1;let{from:r,to:i}=n;if(i>=e.doc.content.size)return!1;let a=e.doc.resolve(i+1);if(a.depth===0)return!1;let o=a.after(1),s=e.doc.slice(r,i).content,c=e.doc.slice(i,o).content;if(!t)return!0;let l=e.tr;l.replaceWith(r,o,c.append(s));let u=r+c.size+1,d=r+c.size+s.size,f=e.selection.from-r,p=Math.min(u+f,d);return l.setSelection(H.near(l.doc.resolve(p))),l.scrollIntoView(),t(l),!0}var Mg=fe.create({name:`blockMover`,addKeyboardShortcuts(){return{"Mod-Shift-ArrowUp":({editor:e})=>Ag(e.state,e.view.dispatch),"Mod-Shift-ArrowDown":({editor:e})=>jg(e.state,e.view.dispatch)}}});function Ng(e){return!!e.getMeta(gd)}function Pg(e,t){let n=gd.getState(e);return rf(n.doc,n.type,t,n.binding.mapping)||0}function Fg(e,t){let n=gd.getState(e);return tf(t,n.type,n.binding.mapping)}var Ig=class e extends he{constructor(e,t){super(e),this.yRelativePosition=t}static fromJSON(t){return new e(t.position,t.yRelativePosition)}toJSON(){return{position:this.position,yRelativePosition:this.yRelativePosition}}};function Lg(e,t){return new Ig(e,Fg(t,e))}function Rg(e,t,n){let r=e instanceof Ig?e.yRelativePosition:null;if(Ng(t)&&r)return{position:new Ig(Pg(n,r),r),mapResult:null};let i=ce(e,t),a=i.position.position;return{position:new Ig(a,r??Fg(n,a)),mapResult:i.mapResult}}var zg=fe.create({name:`collaboration`,priority:1e3,addOptions(){return{document:null,field:`default`,fragment:null,provider:null}},addStorage(){return{isDisabled:!1}},onCreate(){this.editor.extensionManager.extensions.find(e=>e.name===`undoRedo`)&&console.warn(`[tiptap warn]: "@tiptap/extension-collaboration" comes with its own history support and is not compatible with "@tiptap/extension-undo-redo".`)},onBeforeCreate(){this.editor.utils.getUpdatedPosition=(e,t)=>Rg(e,t,this.editor.state),this.editor.utils.createMappablePosition=e=>Lg(e,this.editor.state)},addCommands(){return{undo:()=>({tr:e,state:t,dispatch:n})=>(e.setMeta(`preventDispatch`,!0),_d.getState(t).undoManager.undoStack.length===0?!1:n?df(t):!0),redo:()=>({tr:e,state:t,dispatch:n})=>(e.setMeta(`preventDispatch`,!0),_d.getState(t).undoManager.redoStack.length===0?!1:n?ff(t):!0)}},addKeyboardShortcuts(){return{"Mod-z":()=>this.editor.commands.undo(),"Mod-y":()=>this.editor.commands.redo(),"Shift-Mod-z":()=>this.editor.commands.redo()}},addProseMirrorPlugins(){let e=this.options.fragment?this.options.fragment:this.options.document.getXmlFragment(this.options.field),t=hf(this.options.yUndoOptions),n=t.spec.view;return t.spec.view=e=>{let{undoManager:t}=_d.getState(e.state);t.restore&&=(t.restore(),()=>{});let r=n?n(e):void 0;return{destroy:()=>{let e=t.trackedOrigins.has(t),n=t._observers;t.restore=()=>{e&&t.trackedOrigins.add(t),t.doc.on(`afterTransaction`,t.afterTransactionHandler),t._observers=n},r?.destroy&&r.destroy()}}},[wd(e,{...this.options.ySyncOptions,onFirstRender:this.options.onFirstRender}),t,this.editor.options.enableContentCheck&&new E({key:new be(`filterInvalidContent`),filterTransaction:t=>{if(!Ng(t))return!0;if(this.storage.isDisabled)return!1;if(!t.docChanged)return!0;try{return t.doc.check(),!0}catch(t){return this.storage.isDisabled=!0,this.editor.emit(`contentError`,{error:t,editor:this.editor,disableCollaboration:()=>{var t;(t=e.doc)==null||t.destroy()}}),!1}}})].filter(Boolean)}});function Bg(e){if(!e.length)return A.empty;let t=[],n=e[0].$from.node(0);return e.forEach(e=>{let n=e.$from.pos,r=e.$from.nodeAfter;r&&t.push(j.node(n,n+r.nodeSize,{class:`ProseMirror-selectednoderange`}))}),A.create(n,t)}function Vg(e,t,n){let r=n.isText||n.isAtom?0:1;return{start:e+r,end:e+t-r}}function Hg(e,t,n,r={}){let i=[],a=e.node(0),{extendOnBoundaryOverlap:o=!0}=r;typeof n==`number`&&n>=0||(n=e.sameParent(t)?Math.max(0,e.sharedDepth(t.pos)-1):e.sharedDepth(t.pos));let s=new I(e,t,n),c=s.depth===0?0:a.resolve(s.start).posAtIndex(0);return s.parent.forEach((n,r)=>{let l=c+r,u=l+n.nodeSize,d=Vg(l,n.nodeSize,n),f=o?t.pos>=d.start&&e.pos<=d.end:t.pos>d.start&&e.pos<d.end;if(l<s.start||l>=s.end||!f)return;let p=new z(a.resolve(l),a.resolve(u));i.push(p)}),i}var Ug=class e{constructor(e,t){this.anchor=e,this.head=t}map(t){return new e(t.map(this.anchor),t.map(this.head))}resolve(e){return new Wg(e.resolve(this.anchor),e.resolve(this.head))}},Wg=class e extends L{constructor(e,t,n,r=1){let{doc:i}=e,a=e===t,o=e.pos===i.content.size&&t.pos===i.content.size,s=a&&!o?i.resolve(t.pos+(r>0?1:-1)):t,c=a&&o?i.resolve(e.pos-(r>0?1:-1)):e,l=Hg(c.min(s),c.max(s),n),u=s.pos>=e.pos?l[0].$from:l[l.length-1].$to,d=s.pos>=e.pos?l[l.length-1].$to:l[0].$from;super(u,d,l),this.depth=n}get $to(){return this.ranges[this.ranges.length-1].$to}eq(t){return t instanceof e&&t.$from.pos===this.$from.pos&&t.$to.pos===this.$to.pos}map(t,n){return new e(t.resolve(n.map(this.anchor)),t.resolve(n.map(this.head)))}toJSON(){return{type:`nodeRange`,anchor:this.anchor,head:this.head}}get isForwards(){return this.head>=this.anchor}get isBackwards(){return!this.isForwards}extendBackwards(){let{doc:t}=this.$from;if(this.isForwards&&this.ranges.length>1){let t=this.ranges.slice(0,-1),n=t[0].$from,r=t[t.length-1].$to;return new e(n,r,this.depth)}let n=this.ranges[0],r=t.resolve(Math.max(0,n.$from.pos-1));return new e(this.$anchor,r,this.depth)}extendForwards(){let{doc:t}=this.$from;if(this.isBackwards&&this.ranges.length>1){let t=this.ranges.slice(1),n=t[0].$from,r=t[t.length-1].$to;return new e(r,n,this.depth)}let n=this.ranges[this.ranges.length-1],r=t.resolve(Math.min(t.content.size,n.$to.pos+1));return new e(this.$anchor,r,this.depth)}static fromJSON(t,n){return new e(t.resolve(n.anchor),t.resolve(n.head))}static create(e,t,n,r,i=1){return new this(e.resolve(t),e.resolve(n),r,i)}getBookmark(){return new Ug(this.anchor,this.head)}};Wg.prototype.visible=!1;function Gg(e){return e instanceof Wg}fe.create({name:`nodeRange`,addOptions(){return{depth:void 0,key:`Mod`}},addKeyboardShortcuts(){return{"Shift-ArrowUp":({editor:e})=>{let{depth:t}=this.options,{view:n,state:r}=e,{doc:i,selection:a,tr:o}=r,{anchor:s,head:c}=a;if(!Gg(a)){let e=Wg.create(i,s,c,t,-1);return o.setSelection(e),n.dispatch(o),!0}let l=a.extendBackwards();return o.setSelection(l),n.dispatch(o),!0},"Shift-ArrowDown":({editor:e})=>{let{depth:t}=this.options,{view:n,state:r}=e,{doc:i,selection:a,tr:o}=r,{anchor:s,head:c}=a;if(!Gg(a)){let e=Wg.create(i,s,c,t);return o.setSelection(e),n.dispatch(o),!0}let l=a.extendForwards();return o.setSelection(l),n.dispatch(o),!0},"Mod-a":({editor:e})=>{let{depth:t}=this.options,{view:n,state:r}=e,{doc:i,tr:a}=r,o=Wg.create(i,0,i.content.size,t);return a.setSelection(o),n.dispatch(a),!0}}},onSelectionUpdate(){let{selection:e}=this.editor.state;Gg(e)&&this.editor.view.dom.classList.add(`ProseMirror-noderangeselection`)},addProseMirrorPlugins(){let e=!1,t=!1;return[new E({key:new be(`nodeRange`),props:{attributes:()=>e?{class:`ProseMirror-noderangeselection`}:{class:``},handleDOMEvents:{mousedown:(e,n)=>{let{key:r}=this.options,i=/Mac/.test(navigator.platform),a=!!n.shiftKey,o=!!n.ctrlKey,s=!!n.altKey,c=!!n.metaKey;return(r==null||r===`Shift`&&a||r===`Control`&&o||r===`Alt`&&s||r===`Meta`&&c||r===`Mod`&&(i?c:o))&&(t=!0),t&&document.addEventListener(`mouseup`,()=>{t=!1;let{state:n}=e,{doc:r,selection:i,tr:a}=n,{$anchor:o,$head:s}=i;if(o.sameParent(s))return;let c=Wg.create(r,o.pos,s.pos,this.options.depth);a.setSelection(c),e.dispatch(a)},{once:!0}),!1}},decorations:n=>{let{selection:r}=n,i=Gg(r);if(e=!1,!t)return i?(e=!0,Bg(r.ranges)):null;let{$from:a,$to:o}=r;if(!i&&a.sameParent(o))return null;let s=Hg(a,o,this.options.depth);return s.length?(e=!0,Bg(s)):null}}})]}});function Kg(e){let t=``,n=getComputedStyle(e);for(let e=0;e<n.length;e+=1)t+=`${n[e]}:${n.getPropertyValue(n[e])};`;return t}function qg(e){let t=e.cloneNode(!0),n=[e,...Array.from(e.getElementsByTagName(`*`))],r=[t,...Array.from(t.getElementsByTagName(`*`))];return n.forEach((e,t)=>{r[t].style.cssText=Kg(e)}),t}var Jg=[{id:`listItemFirstChild`,evaluate:({parent:e,isFirst:t})=>t&&e&&[`listItem`,`taskItem`].includes(e.type.name)?1e3:0},{id:`listWrapperDeprioritize`,evaluate:({node:e})=>{let t=[`listItem`,`taskItem`],n=e.firstChild;return n&&t.includes(n.type.name)?1e3:0}},{id:`tableStructure`,evaluate:({node:e,parent:t})=>[`tableRow`,`tableCell`,`tableHeader`].includes(e.type.name)||t&&t.type.name===`tableHeader`?1e3:0},{id:`inlineContent`,evaluate:({node:e})=>e.isInline||e.isText?1e3:0}],Yg={edges:[`left`,`top`],threshold:12,strength:500};function Xg(e){return e===void 0||e===`left`?{...Yg}:e===`right`?{edges:[`right`,`top`],threshold:12,strength:500}:e===`both`?{edges:[`left`,`right`,`top`],threshold:12,strength:500}:e===`none`?{edges:[],threshold:0,strength:0}:{...Yg,...e}}function Zg(e,t,n){if(n.edges.length===0)return!1;let r=t.getBoundingClientRect(),{threshold:i,edges:a}=n;return a.some(t=>t===`left`?e.x-r.left<i:t===`right`?r.right-e.x<i:t===`top`?e.y-r.top<i:t===`bottom`?r.bottom-e.y<i:!1)}function Qg(e,t,n,r){return!t||n.edges.length===0?0:Zg(e,t,n)?n.strength*r:0}var $g=1e3;function e_(e,t,n,r){let i=$g,a=!1;if(t.every(t=>{let n=t.evaluate(e);return i-=n,i<=0?(a=!0,!1):!0}),a)return-1;let o=e.view.nodeDOM(e.pos);return i-=Qg(r,o,n,e.depth),i<=0?-1:i}function t_(e,t,n){return Array.from({length:t},(e,n)=>t-1-n).some(t=>n.includes(e.node(t).type.name))}function n_(e,t,n){if(!Number.isFinite(t.x)||!Number.isFinite(t.y))return null;let r=e.posAtCoords({left:t.x,top:t.y});if(!r)return null;let{doc:i}=e.state,a=i.resolve(r.pos),o=[];n.defaultRules&&o.push(...Jg),o.push(...n.rules);let s=Array.from({length:a.depth},(e,t)=>a.depth-t).map(r=>{let i=a.node(r),s=a.before(r);if(n.allowedContainers&&r>0&&!t_(a,r,n.allowedContainers))return null;let c=r>0?a.node(r-1):null,l=r>0?a.index(r-1):0,u=c?c.childCount:1,d=e_({node:i,pos:s,depth:r,parent:c,index:l,isFirst:l===0,isLast:l===u-1,$pos:a,view:e},o,n.edgeDetection,t);return d<0?null:{node:i,pos:s,depth:r,score:d,dom:e.nodeDOM(s)}}).filter(e=>e!==null),c=a.nodeAfter;if(c&&c.isAtom&&!c.isInline){let i=r.pos,l=a.depth+1,u=a.parent,d=a.index(),f=u.childCount,p=!0;if(n.allowedContainers&&(p=t_(a,l,n.allowedContainers)),p){let r=e_({node:c,pos:i,depth:l,parent:u,index:d,isFirst:d===0,isLast:d===f-1,$pos:a,view:e},o,n.edgeDetection,t);if(r>=0){let t=e.nodeDOM(i);t&&s.push({node:c,pos:i,depth:l,score:r,dom:t})}}}if(s.length===0)return null;s.sort((e,t)=>t.score===e.score?t.depth-e.depth:t.score-e.score);let l=s[0];return l.dom?{node:l.node,pos:l.pos,dom:l.dom}:null}function r_(e,t){let n=e;for(;n?.parentElement&&n.parentElement!==t.dom;)n=n.parentElement;return n?.parentElement===t.dom?n:void 0}function i_(e){return Number.isFinite(e.top)&&Number.isFinite(e.bottom)&&Number.isFinite(e.left)&&Number.isFinite(e.right)&&e.width>0&&e.height>0}function a_(e,t,n,r=5){if(!Number.isFinite(t)||!Number.isFinite(n))return null;let i=e.dom,a=i.firstElementChild,o=i.lastElementChild;if(!a||!o)return null;let s=a.getBoundingClientRect(),c=o.getBoundingClientRect();if(!i_(s)||!i_(c))return null;let l=Math.min(Math.max(s.top+r,n),c.bottom-r),u=.5,d=Math.abs(s.left-c.left)<u,f=Math.abs(s.right-c.right)<u,p=s;d&&f&&(p=s);let m=Math.min(Math.max(p.left+r,t),p.right-r);return!Number.isFinite(m)||!Number.isFinite(l)?null:{x:m,y:l}}var o_=e=>{let{x:t,y:n,editor:r,nestedOptions:i}=e,{view:a,state:o}=r,s=a_(a,t,n,5);if(!s)return{resultElement:null,resultNode:null,pos:null};let{x:c,y:l}=s;if(i?.enabled){let e=n_(a,{x:c,y:l},i);return e?{resultElement:e.dom,resultNode:e.node,pos:e.pos}:{resultElement:null,resultNode:null,pos:null}}let u=a.root.elementsFromPoint(c,l),d;if(Array.prototype.some.call(u,e=>{if(!a.dom.contains(e))return!1;let t=r_(e,a);return t?(d=t,!0):!1}),!d){let e=a.posAtCoords({left:c,top:l});if(e){let t=o.doc.resolve(e.pos),n=Math.min(t.depth,1),r=n>0?t.before(n):t.pos,i=o.doc.nodeAt(r);if(i){let e=a.nodeDOM(r);return{resultElement:e instanceof HTMLElement?e:null,resultNode:i,pos:r}}}return{resultElement:null,resultNode:null,pos:null}}let f;try{f=a.posAtDOM(d,0)}catch{return{resultElement:null,resultNode:null,pos:null}}let p=o.doc.nodeAt(f);if(!p){let e=o.doc.resolve(f),t=e.parent;return{resultElement:d,resultNode:t,pos:e.start()}}return{resultElement:d,resultNode:p,pos:f}};function s_(e,t){let n=null,r=e.nodeDOM(t);if(r instanceof Element)n=r;else{let{node:r,offset:i}=e.domAtPos(t),a=r.childNodes[i];a instanceof Element?n=a:r instanceof Element?n=r:r.nodeType===Node.TEXT_NODE&&r.parentElement&&(n=r.parentElement)}return(n?getComputedStyle(n).direction:getComputedStyle(e.dom).direction)||`ltr`}function c_(e){var t;(t=e.parentNode)==null||t.removeChild(e)}function l_(e,t,n,r){let{doc:i}=t.view.state;if(n?.enabled&&r?.node&&r.pos>=0){let e=r.pos,t=r.pos+r.node.nodeSize;return[{$from:i.resolve(e),$to:i.resolve(t)}]}let a=o_({editor:t,x:e.clientX,y:e.clientY,direction:`right`,nestedOptions:n});if(!a.resultNode||a.pos===null)return[];let o=a.resultNode.isText||a.resultNode.isAtom?0:-1;return Hg(i.resolve(a.pos),i.resolve(a.pos+a.resultNode.nodeSize+o),0,{extendOnBoundaryOverlap:!1})}function u_(e,t,n,r){let{view:i}=t;if(!e.dataTransfer)return;let{empty:a,$from:o,$to:s}=i.state.selection,c=l_(e,t,n,r),l=Hg(o,s,0,{extendOnBoundaryOverlap:!1}),u=l.some(e=>c.find(t=>t.$from===e.$from&&t.$to===e.$to)),d=a||!u?c:l;if(!d.length)return;let{tr:f}=i.state,p=document.createElement(`div`),m=d[0].$from.pos,h=d[d.length-1].$to.pos;p.setAttribute(`dir`,s_(i,m));let g=n?.enabled&&r?.node,_,v;g?(_=i.state.doc.slice(m,h),v=xe.create(i.state.doc,m)):(v=Wg.create(i.state.doc,m,h),_=v.content()),d.forEach(e=>{let t=qg(i.nodeDOM(e.$from.pos));p.append(t)}),p.style.position=`absolute`,p.style.top=`-10000px`,document.body.append(p),e.dataTransfer.clearData();let y=p.getBoundingClientRect(),b=e.clientX-y.left;e.dataTransfer.setDragImage(p,Math.max(0,Math.min(b,y.width)),0);let x=!1,S=()=>{x||(x=!0,c_(p),document.removeEventListener(`drop`,S),document.removeEventListener(`dragend`,S))},C=v instanceof xe?v:void 0;i.dragging={slice:_,move:!0,node:C},f.setSelection(v),i.dispatch(f),document.addEventListener(`drop`,S),document.addEventListener(`dragend`,S)}var d_=(e,t)=>{let n=e.resolve(t),{depth:r}=n;return r===0?t:n.pos-n.parentOffset-1},f_=(e,t)=>{let n=e.nodeAt(t),r=e.resolve(t),{depth:i}=r,a=n;for(;i>0;){let e=r.node(i);--i,i===0&&(a=e)}return a},p_=(e,t)=>{let n=gd.getState(e);return n?tf(t,n.type,n.binding.mapping):null},m_=(e,t)=>{let n=gd.getState(e);return n?rf(n.doc,n.type,t,n.binding.mapping)||0:-1},h_=(e,t)=>{let n=t;for(;n?.parentNode&&n.parentNode!==e.dom;)n=n.parentNode;return n},g_=new be(`dragHandle`),__=({pluginKey:e=g_,element:t,editor:n,computePositionConfig:r,getReferencedVirtualElement:i,onNodeChange:a,onElementDragStart:o,onElementDragEnd:s,nestedOptions:c})=>{let l=document.createElement(`div`),u=!1,d=null,f=-1,p,m=null,h=null;function g(){t&&(t.style.visibility=`hidden`,t.style.pointerEvents=`none`)}function _(){if(t){if(!n.isEditable){g();return}t.style.visibility=``,t.style.pointerEvents=`auto`}}function v(e){N(i?.()||{getBoundingClientRect:()=>e.getBoundingClientRect()},t,r).then(e=>{Object.assign(t.style,{position:e.strategy,left:`${e.x}px`,top:`${e.y}px`})})}function y(e){o?.(e),u_(e,n,c,{node:d,pos:f}),t&&(t.dataset.dragging=`true`),setTimeout(()=>{t&&(t.style.pointerEvents=`none`)},0)}function b(e){s?.(e),g(),t&&(t.style.pointerEvents=`auto`,t.dataset.dragging=`false`)}function x(){if(Ie()){let e=n.view.dom;requestAnimationFrame(()=>{e.isContentEditable&&(e.contentEditable=`false`,e.contentEditable=`true`)})}}return l.appendChild(t),{unbind(){t.removeEventListener(`dragstart`,y),t.removeEventListener(`dragend`,b),document.removeEventListener(`drop`,x),m&&(cancelAnimationFrame(m),m=null,h=null)},plugin:new E({key:typeof e==`string`?new be(e):e,state:{init(){return{locked:!1}},apply(e,r,i,o){let s=e.getMeta(`lockDragHandle`),c=e.getMeta(`hideDragHandle`);if(s!==void 0&&(u=s),c)return g(),u=!1,d=null,f=-1,a?.({editor:n,node:null,pos:-1}),r;if(e.docChanged&&f!==-1&&t)if(Ng(e)){let e=m_(o,p);e!==f&&(f=e)}else{let t=e.mapping.map(f);t!==f&&(f=t,p=p_(o,f))}return r}},view:e=>{var r;return t.draggable=!0,t.style.pointerEvents=`auto`,t.dataset.dragging=`false`,(r=n.view.dom.parentElement)==null||r.appendChild(l),l.style.pointerEvents=`none`,l.style.position=`absolute`,l.style.top=`0`,l.style.left=`0`,t.addEventListener(`dragstart`,y),t.addEventListener(`dragend`,b),document.addEventListener(`drop`,x),{update(r,i){if(!t)return;if(!n.isEditable){g();return}if(u?t.draggable=!1:t.draggable=!0,e.state.doc.eq(i.doc)||f===-1)return;let o=e.nodeDOM(f);if(o=h_(e,o),o===e.dom||o?.nodeType!==1)return;let s=e.posAtDOM(o,0),c=f_(n.state.doc,s),l=d_(n.state.doc,s);d=c,f=l,p=p_(e.state,f),a?.({editor:n,node:d,pos:f}),v(o)},destroy(){t.removeEventListener(`dragstart`,y),t.removeEventListener(`dragend`,b),document.removeEventListener(`drop`,x),m&&(cancelAnimationFrame(m),m=null,h=null),t&&c_(l)}}},props:{handleDOMEvents:{keydown(e){return!t||u?!1:e.hasFocus()?(g(),d=null,f=-1,a?.({editor:n,node:null,pos:-1}),!1):!1},mouseleave(e,t){return u||t.target&&!l.contains(t.relatedTarget)&&(g(),d=null,f=-1,a?.({editor:n,node:null,pos:-1})),!1},mousemove(e,r){return!t||u||(h={x:r.clientX,y:r.clientY},m)||(m=requestAnimationFrame(()=>{if(m=null,!h)return;let{x:t,y:r}=h;h=null;let i=o_({x:t,y:r,direction:`right`,editor:n,nestedOptions:c});if(!i.resultElement)return;let o=i.resultElement,s=i.resultNode,l=i.pos;if(!c?.enabled){if(o=h_(e,o),o===e.dom||o?.nodeType!==1)return;let t=e.posAtDOM(o,0);s=f_(n.state.doc,t),l=d_(n.state.doc,t)}s!==d&&(d=s,f=l??-1,p=p_(e.state,f),a?.({editor:n,node:d,pos:f}),v(o),_())})),!1}}}})}};function v_(e){return e===!1||e===void 0?{enabled:!1,rules:[],defaultRules:!0,allowedContainers:void 0,edgeDetection:Xg(`none`)}:e===!0?{enabled:!0,rules:[],defaultRules:!0,allowedContainers:void 0,edgeDetection:Xg(`left`)}:{enabled:!0,rules:e.rules??[],defaultRules:e.defaultRules??!0,allowedContainers:e.allowedContainers,edgeDetection:Xg(e.edgeDetection)}}var y_={placement:`left-start`,strategy:`absolute`};fe.create({name:`dragHandle`,addOptions(){return{render(){let e=document.createElement(`div`);return e.classList.add(`drag-handle`),e},computePositionConfig:{},locked:!1,onNodeChange:()=>null,onElementDragStart:void 0,onElementDragEnd:void 0,nested:!1}},addCommands(){return{lockDragHandle:()=>({editor:e})=>(this.options.locked=!0,e.commands.setMeta(`lockDragHandle`,this.options.locked)),unlockDragHandle:()=>({editor:e})=>(this.options.locked=!1,e.commands.setMeta(`lockDragHandle`,this.options.locked)),toggleDragHandle:()=>({editor:e})=>(this.options.locked=!this.options.locked,e.commands.setMeta(`lockDragHandle`,this.options.locked))}},addProseMirrorPlugins(){let e=this.options.render(),t=v_(this.options.nested);return[__({computePositionConfig:{...y_,...this.options.computePositionConfig},getReferencedVirtualElement:this.options.getReferencedVirtualElement,element:e,editor:this.editor,onNodeChange:this.options.onNodeChange,onElementDragStart:this.options.onElementDragStart,onElementDragEnd:this.options.onElementDragEnd,nestedOptions:t}).plugin]}});var b_=20,x_=44,S_=28;function C_(){let e=document.createElement(`div`);e.className=`ok-block-controls`,e.style.visibility=`hidden`;let t=document.createElement(`button`);t.className=`ok-add-block-btn`,t.setAttribute(`aria-label`,`Add block below`),t.setAttribute(`type`,`button`),t.innerHTML=`<svg aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-plus"><path d="M5 12h14"/><path d="M12 5v14"/></svg>`,t.addEventListener(`mousedown`,e=>{e.preventDefault(),e.stopPropagation()});let n=document.createElement(`div`);return n.className=`ok-drag-grip`,n.setAttribute(`aria-hidden`,`true`),n.innerHTML=`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-grip-vertical-icon lucide-grip-vertical"><circle cx="9" cy="12" r="1"/><circle cx="9" cy="5" r="1"/><circle cx="9" cy="19" r="1"/><circle cx="15" cy="12" r="1"/><circle cx="15" cy="5" r="1"/><circle cx="15" cy="19" r="1"/></svg>`,e.appendChild(t),e.appendChild(n),{container:e,addBtn:t}}function w_(e,t,n){let{state:r,view:i}=e,a=t+n.nodeSize;if(a>r.doc.content.size)return;let{tr:o}=r,s=r.schema.nodes.paragraph?.create();if(!s)return;o.insert(a,s);let c=H.near(o.doc.resolve(a+1));o.setSelection(c).scrollIntoView(),i.dispatch(o),i.focus(),e.commands.insertContent(`/`)}var T_=fe.create({name:`blockDragHandle`,addProseMirrorPlugins(){let e=this.editor,t=null,n=-1,{container:r,addBtn:i}=C_();return i.addEventListener(`click`,()=>{t&&n>=0&&w_(e,n,t)}),[__({element:r,editor:e,onNodeChange({node:e,pos:r}){t=e,n=r??-1},computePositionConfig:{placement:`left-start`,strategy:`absolute`,middleware:[je(({rects:e})=>({mainAxis:10,crossAxis:((e.reference.height<=x_?e.reference.height:S_)-b_)/2}))]},nestedOptions:v_(!1)}).plugin]}});function E_(e){let t=e.trim();if(!t)return null;let n=T(t);return n?{target:n,alias:n===t?null:t,anchor:null}:null}function D_(e){let t=e.trim();if(!t)return[];let n=T(t);return n.length>0&&n!==t?[n]:[]}function O_(e,t){let n=e.trim();return n?t.has(n)?!0:D_(n).some(e=>t.has(e)):!1}var k_=fe.create({name:`headingAnchors`,addProseMirrorPlugins(){return[new E({props:{decorations(e){let t=[],n=new Map;return e.doc.descendants((e,r)=>{if(e.type.name===`heading`){let i=D(e.textContent,n);if(!i)return;t.push(j.node(r,r+e.nodeSize,{id:i}))}}),A.create(e.doc,t)}}})]}}),A_=new Set([`http:`,`https:`,`mailto:`,`tel:`]);function j_(e){try{let t=new URL(e);return A_.has(t.protocol)}catch{return!1}}function M_(e=window.location.hash){let t=e.match(/^#\/([^?#]+)/);return t?decodeURIComponent(t[1]):``}function N_(e,t=window.location.hash){return R(e,M_(t))}function P_({docName:e,anchor:t}){return t?`#/${e}?anchor=${encodeURIComponent(t)}`:`#/${e}`}function F_(e){e.startsWith(`#`)||j_(e)?window.open(e,`_blank`,`noopener,noreferrer`):console.warn(`[safe-nav] blocked non-safe scheme:`,e)}function I_(e){window.location.assign(P_(e))}function L_(e){F_(P_(e))}function R_(e){return e.metaKey||e.ctrlKey}function z_(e,t=window.location.hash){let n=M_(t);if(!n)return;let r=document.getElementById(e);r&&r.scrollIntoView({behavior:`smooth`,block:`start`}),window.location.assign(le(n,e))}function B_(e,t=window.location.hash){if(e.kind===`doc`){I_(e);return}if(e.kind===`anchor`){z_(e.anchor,t);return}F_(e.url)}function V_(e,t,n=window.location.hash){return ye(M_(n),e,t)}var H_=e=>{let t=(0,at.c)(13),{kind:n,ariaLabel:r,onDeactivate:i,children:a,layout:o,className:s,"data-slot":u}=e,d=(o===void 0?`standard`:o)===`wide`?`w-[min(720px,calc(100%-1rem))]`:`w-80`,f;t[0]!==s||t[1]!==d?(f=c(`ok-interaction-prop-panel pointer-events-auto absolute left-1/2 top-2 z-40 -translate-x-1/2 rounded-md border border-border bg-popover p-3 shadow-lg`,d,s),t[0]=s,t[1]=d,t[2]=f):f=t[2];let p;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(p=(0,X.jsx)(w,{className:`size-3.5`,"aria-hidden":`true`}),t[3]=p):p=t[3];let m;t[4]===i?m=t[5]:(m=(0,X.jsx)(l,{type:`button`,variant:`ghost`,size:`icon`,"aria-label":`Close`,onClick:i,className:`absolute right-1 top-1 size-7`,children:p}),t[4]=i,t[5]=m);let h;return t[6]!==r||t[7]!==a||t[8]!==u||t[9]!==n||t[10]!==f||t[11]!==m?(h=(0,X.jsxs)(`div`,{role:`dialog`,"aria-label":r,"data-ok-prop-panel":n,"data-slot":u,className:f,children:[a,m]}),t[6]=r,t[7]=a,t[8]=u,t[9]=n,t[10]=f,t[11]=m,t[12]=h):h=t[12],h};function U_(e,t){let n=[e,...t.fallbackTargets??[]],r=new Set,i=null;for(let e of n){if(r.has(e))continue;r.add(e);let n=Oe(e,{pages:t.pages,folderPaths:t.folderPaths});if(n.kind===`missing`){i??=n;continue}return{kind:`navigate`,displayState:n.kind===`folder`?`folder`:`resolved`,resolvedTarget:n,hashDocName:n.target}}let a=i??Oe(e,{pages:t.pages,folderPaths:t.folderPaths});if(a.kind!==`missing`)return{kind:`navigate`,displayState:a.kind===`folder`?`folder`:`resolved`,resolvedTarget:a,hashDocName:a.target};let o=t.createDialogSeed??ue(a.target);return{kind:`create`,displayState:`missing`,resolvedTarget:a,initialDir:o.initialDir,suggestedName:o.suggestedName}}function W_(e){if(e.kind!==`navigate`||e.displayState!==`folder`)return null;let t=e.resolvedTarget;return`folderPath`in t?{initialDir:t.folderPath,suggestedName:`index.md`}:null}function G_(e){let t=(0,at.c)(10),n,r,i;t[0]===e?(n=t[1],r=t[2],i=t[3]):({className:n,type:i,...r}=e,t[0]=e,t[1]=n,t[2]=r,t[3]=i);let a;t[4]===n?a=t[5]:(a=c(`h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40`,n),t[4]=n,t[5]=a);let o;return t[6]!==r||t[7]!==a||t[8]!==i?(o=(0,X.jsx)(`input`,{type:i,"data-slot":`input`,className:a,...r}),t[6]=r,t[7]=a,t[8]=i,t[9]=o):o=t[9],o}function K_(e){return e.trim()?e.includes(`..`)?`Path cannot contain ".."`:e.startsWith(`/`)?`Path cannot start with "/"`:e.includes(`\\`)?`Path cannot contain backslashes`:e.includes(`\0`)?`Path cannot contain null bytes`:null:`Name cannot be empty`}function q_(e){return e.endsWith(`.md`)?e:`${e}.md`}function J_(e){let t=q_(e.fileName.trim());if(e.kind===`folder`){let n=(e.folderName??``).trim();return`${e.initialDir?`${e.initialDir}/${n}`:n}/${t}`}return e.initialDir?`${e.initialDir}/${t}`:t}function Y_(e){let t=e.target;return t?.tagName===`INPUT`||t?.tagName===`TEXTAREA`||t?.isContentEditable?!1:!!((e.metaKey||e.ctrlKey)&&e.altKey&&e.key.toLowerCase()===`n`)}function X_(e){let t=e.value.lastIndexOf(`.`);t>0?e.setSelectionRange(0,t):e.select()}function Z_(e){let t=(0,at.c)(87),{open:n,onOpenChange:r,kind:i,initialDir:a,suggestedName:o,description:s,onCreated:c}=e,{addPage:u}=Te(),[d,p]=(0,J.useState)(``),[m,g]=(0,J.useState)(``),[_,y]=(0,J.useState)(null),[C,w]=(0,J.useState)(!1),[T,E]=(0,J.useState)(null),D=(0,J.useId)(),O=(0,J.useId)(),k=(0,J.useId)(),A=(0,J.useRef)(null),ee=(0,J.useRef)(null),j,M;t[0]!==i||t[1]!==n||t[2]!==o?(j=()=>{n&&(y(null),E(null),w(!1),g(``),p(i===`file`?o??`untitled.md`:`index.md`))},M=[n,i,o],t[0]=i,t[1]=n,t[2]=o,t[3]=j,t[4]=M):(j=t[3],M=t[4]),(0,J.useEffect)(j,M);let N;t[5]!==d||t[6]!==m||t[7]!==a||t[8]!==i?(N=function(){return J_({kind:i,initialDir:a,fileName:d,folderName:m})},t[5]=d,t[6]=m,t[7]=a,t[8]=i,t[9]=N):N=t[9];let P=N,F;t[10]!==d||t[11]!==m||t[12]!==i?(F=function(){if(i===`folder`){let e=K_(m.trim());if(e)return{message:`Folder name: ${e}`,field:`folder`}}let e=K_(d.trim());return e?{message:e,field:`file`}:null},t[10]=d,t[11]=m,t[12]=i,t[13]=F):F=t[13];let I=F,L;t[14]!==C||t[15]!==d||t[16]!==m||t[17]!==i?(L=C||!d.trim()||i===`folder`&&!m.trim(),t[14]=C,t[15]=d,t[16]=m,t[17]=i,t[18]=L):L=t[18];let R=L,z;t[19]!==u||t[20]!==P||t[21]!==I||t[22]!==i||t[23]!==c||t[24]!==r?(z=async function(){let e=I();if(e){y(e.message),E(e.field);return}w(!0),y(null),E(null);let t=P();try{let e=await fetch(`/api/create-page`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:t})});if(!e.ok){let t=`Server error (HTTP ${e.status})`;try{let n=await e.json();n?.error&&(t=n.error)}catch{}w(!1),y(t),E(`form`);return}let n=await e.json();if(w(!1),!n.ok){y(n.error??`Failed to create ${i}`),E(`form`);return}let a=n.docName??t.replace(/\.md$/,``);r(!1),window.location.hash=`#/${a}`,u(a),Me([`files`,`backlinks`,`graph`]),c?.(a)}catch(e){console.warn(`[NewItemDialog] create failed:`,e),w(!1),y(`Network error — please try again`),E(`form`)}},t[19]=u,t[20]=P,t[21]=I,t[22]=i,t[23]=c,t[24]=r,t[25]=z):z=t[25];let B=z,V=a||`(root)`,H=i===`file`?`New file`:`New folder`,U;t[26]===H?U=t[27]:(U=(0,X.jsx)(x,{children:H}),t[26]=H,t[27]=U);let W;t[28]!==s||t[29]!==V?(W=s??(0,X.jsxs)(X.Fragment,{children:[`Create in `,(0,X.jsx)(`span`,{className:`font-medium text-foreground`,children:V})]}),t[28]=s,t[29]=V,t[30]=W):W=t[30];let G;t[31]===W?G=t[32]:(G=(0,X.jsx)(h,{children:W}),t[31]=W,t[32]=G);let K;t[33]!==U||t[34]!==G?(K=(0,X.jsxs)(v,{children:[U,G]}),t[33]=U,t[34]=G,t[35]=K):K=t[35];let q;t[36]!==_||t[37]!==T||t[38]!==D||t[39]!==O||t[40]!==m||t[41]!==i?(q=i===`folder`&&(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`label`,{className:`mb-1.5 block text-sm font-medium`,htmlFor:O,children:`Folder name`}),(0,X.jsx)(G_,{ref:ee,id:O,value:m,onChange:e=>{g(e.target.value),y(null)},placeholder:`folder-name`,autoFocus:!0,"aria-describedby":_&&(T===`folder`||T===`form`)?D:void 0,"aria-invalid":_&&(T===`folder`||T===`form`)?!0:void 0,onKeyDown:e=>{if(e.key===`Enter`){e.preventDefault();let t=K_(m.trim());if(t){y(`Folder name: ${t}`),E(`folder`);return}A.current?.focus()}}})]}),t[36]=_,t[37]=T,t[38]=D,t[39]=O,t[40]=m,t[41]=i,t[42]=q):q=t[42];let te=i===`folder`?`First file name`:`File name`,ne;t[43]!==k||t[44]!==te?(ne=(0,X.jsx)(`label`,{className:`mb-1.5 block text-sm font-medium`,htmlFor:k,children:te}),t[43]=k,t[44]=te,t[45]=ne):ne=t[45];let re;t[46]===Symbol.for(`react.memo_cache_sentinel`)?(re=e=>{p(e.target.value),y(null)},t[46]=re):re=t[46];let ie=i===`file`,ae=_&&(T===`file`||T===`form`)?D:void 0,oe=_&&(T===`file`||T===`form`)?!0:void 0,se;t[47]!==B||t[48]!==R?(se=e=>{e.key===`Enter`&&!R&&B()},t[47]=B,t[48]=R,t[49]=se):se=t[49];let ce;t[50]!==k||t[51]!==d||t[52]!==ie||t[53]!==ae||t[54]!==oe||t[55]!==se?(ce=(0,X.jsx)(G_,{ref:A,id:k,value:d,onChange:re,placeholder:`my-note.md`,autoFocus:ie,"aria-describedby":ae,"aria-invalid":oe,onFocus:Q_,onKeyDown:se}),t[50]=k,t[51]=d,t[52]=ie,t[53]=ae,t[54]=oe,t[55]=se,t[56]=ce):ce=t[56];let le;t[57]!==ne||t[58]!==ce?(le=(0,X.jsxs)(`div`,{children:[ne,ce]}),t[57]=ne,t[58]=ce,t[59]=le):le=t[59];let ue;t[60]!==_||t[61]!==D?(ue=_&&(0,X.jsx)(`p`,{id:D,role:`alert`,className:`text-xs text-red-600 dark:text-red-400`,children:_}),t[60]=_,t[61]=D,t[62]=ue):ue=t[62];let de;t[63]!==q||t[64]!==le||t[65]!==ue?(de=(0,X.jsxs)(`div`,{className:`space-y-3`,children:[q,le,ue]}),t[63]=q,t[64]=le,t[65]=ue,t[66]=de):de=t[66];let fe;t[67]===r?fe=t[68]:(fe=()=>r(!1),t[67]=r,t[68]=fe);let pe;t[69]!==C||t[70]!==fe?(pe=(0,X.jsx)(l,{variant:`outline`,className:`font-mono uppercase`,onClick:fe,disabled:C,children:`Cancel`}),t[69]=C,t[70]=fe,t[71]=pe):pe=t[71];let me=C?`Creating...`:`Create`,he;t[72]!==B||t[73]!==R||t[74]!==me?(he=(0,X.jsx)(l,{onClick:B,disabled:R,children:me}),t[72]=B,t[73]=R,t[74]=me,t[75]=he):he=t[75];let ge;t[76]!==pe||t[77]!==he?(ge=(0,X.jsxs)(f,{children:[pe,he]}),t[76]=pe,t[77]=he,t[78]=ge):ge=t[78];let _e;t[79]!==K||t[80]!==de||t[81]!==ge?(_e=(0,X.jsxs)(b,{className:`sm:max-w-md`,"data-ok-layer-spawned":``,children:[K,de,ge]}),t[79]=K,t[80]=de,t[81]=ge,t[82]=_e):_e=t[82];let ve;return t[83]!==r||t[84]!==n||t[85]!==_e?(ve=(0,X.jsx)(S,{open:n,onOpenChange:r,children:_e}),t[83]=r,t[84]=n,t[85]=_e,t[86]=ve):ve=t[86],ve}function Q_(e){return X_(e.currentTarget)}var $_=class{registry=new Map;_activeNodeId=null;listeners=new Set;_snapshot={activeNodeId:null,active:null};register(e){this.registry.set(e.nodeId,e),this._activeNodeId===e.nodeId&&this.refreshSnapshot()}deregister(e){this.registry.delete(e)&&this._activeNodeId===e&&(this._activeNodeId=null,this.refreshSnapshot())}setActiveNode(e){this._activeNodeId!==e&&(e!==null&&!this.registry.has(e)||(this._activeNodeId=e,this.refreshSnapshot()))}getActiveNode(){return this._activeNodeId}getRegistration(e){return this.registry.get(e)}hasRegistration(e){return this.registry.has(e)}clear(){this.registry.clear(),this._activeNodeId=null,this.refreshSnapshot()}getSnapshot=()=>this._snapshot;subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});refreshSnapshot(){let e=this._activeNodeId==null?null:this.registry.get(this._activeNodeId)??null;this._snapshot={activeNodeId:this._activeNodeId,active:e};for(let e of this.listeners)e()}};function ev(e,t){let n=e??null;for(;n&&typeof n==`object`;){let e=n.getAttribute;if(typeof e==`function`){let r=e.call(n,`data-mark-id`);if(r&&t.hasRegistration(r))return r;let i=e.call(n,`data-node-id`);if(i&&t.hasRegistration(i))return i}n=n.parentElement??null}return null}var tv=e=>{let t=(0,at.c)(18),{store:n}=e,r;t[0]===n?r=t[1]:(r=()=>n.getSnapshot(),t[0]=n,t[1]=r);let[i,a]=(0,J.useState)(r),o,s;t[2]===n?(o=t[3],s=t[4]):(o=()=>(a(n.getSnapshot()),n.subscribe(()=>{a(n.getSnapshot())})),s=[n],t[2]=n,t[3]=o,t[4]=s),(0,J.useEffect)(o,s);let{active:c}=i;if(!c)return null;let l;t[5]===n?l=t[6]:(l=()=>n.setActiveNode(null),t[5]=n,t[6]=l);let u,d,f;if(t[7]!==c.controls||t[8]!==c.nodeId||t[9]!==c.type||t[10]!==l){let e={nodeId:c.nodeId,type:c.type,deactivate:l};u=c.controls.propPanel?.(e),d=c.controls.toolbar?.(e),f=c.controls.breadcrumb?.(e),t[7]=c.controls,t[8]=c.nodeId,t[9]=c.type,t[10]=l,t[11]=u,t[12]=d,t[13]=f}else u=t[11],d=t[12],f=t[13];let p;return t[14]!==u||t[15]!==d||t[16]!==f?(p=(0,X.jsxs)(X.Fragment,{children:[u,d,f]}),t[14]=u,t[15]=d,t[16]=f,t[17]=p):p=t[17],p};function nv(e){return e.editorView?.dom??e.view?.dom??null}function rv(e,t){let n=e;for(;n;){if(n.getAttribute?.(`data-mark-id`)===t||n.getAttribute?.(`data-node-id`)===t)return!0;n=n.parentElement}return!1}function iv(e){let{editor:t}=e,n=new $_,r=nv(t),i=!1,a=null,o=n.subscribe(()=>{let e=n.getActiveNode();if(e!==null){if(typeof document<`u`){let t=document.activeElement;a=t&&rv(t,e)?t:null}return}if(typeof document>`u`)return;let i=a;if(a=null,i&&document.contains(i)&&typeof i.focus==`function`){try{i.focus({preventScroll:!0})}catch{}return}let o=r??nv(t);if(o&&typeof o.focus==`function`)try{o.focus({preventScroll:!0})}catch{}}),s=e=>{let t=e;if(t.button===2)return;if(t.metaKey||t.ctrlKey||t.button===1){t.button===1&&t.preventDefault?.();return}let r=ev(e.target,n);if(r===null)return;let i=n.getRegistration(r);i?.handlePrimary&&i.handlePrimary({nodeId:r,type:i.type,newTab:!1})||n.setActiveNode(r)},c=e=>{let t=e;if(t.button===2||t.type===`click`&&t.button===1||!(t.metaKey||t.ctrlKey||t.button===1))return;let r=ev(e.target,n);if(r===null)return;let i=n.getRegistration(r);i?.handlePrimary&&i.handlePrimary({nodeId:r,type:i.type,newTab:!0})&&t.preventDefault?.()},l=e=>{let t=e;if(t.key===`Escape`){n.getActiveNode()!==null&&(n.setActiveNode(null),t.preventDefault?.());return}if(t.key!==`Enter`&&t.key!==` `&&t.key!==`Spacebar`)return;let r=ev(e.target,n);if(r===null)return;let i=n.getRegistration(r);t.preventDefault?.(),!(i?.handlePrimary&&i.handlePrimary({nodeId:r,type:i.type,newTab:!1}))&&n.setActiveNode(r)},u=e=>{if(n.getActiveNode()===null)return;let t=e.target;t&&(r?.contains(t)||t instanceof Element&&(t.closest(`[data-ok-interaction-layer]`)||t.closest(`[data-ok-prop-panel]`)||t.closest(`[data-ok-layer-spawned]`))||n.setActiveNode(null))},d=()=>{i||(r=nv(t),r&&(r.addEventListener(`pointerdown`,s,!0),r.addEventListener(`click`,c,!0),r.addEventListener(`auxclick`,c,!0),r.addEventListener(`keydown`,l,!0),typeof document<`u`&&document.addEventListener(`pointerdown`,u,!0),i=!0))},f=()=>{i&&=(r?.removeEventListener(`pointerdown`,s,!0),r?.removeEventListener(`click`,c,!0),r?.removeEventListener(`auxclick`,c,!0),r?.removeEventListener(`keydown`,l,!0),typeof document<`u`&&document.removeEventListener(`pointerdown`,u,!0),!1)};return d(),{register(e){n.register(e),i||d()},deregister(e){n.deregister(e)},setActiveNode(e){n.setActiveNode(e)},getActiveNode(){return n.getActiveNode()},getRegistration(e){return n.getRegistration(e)},destroy(){f(),o(),n.clear()},store:n}}var av=e=>{let t=(0,at.c)(2),{store:n}=e,r;return t[0]===n?r=t[1]:(r=(0,X.jsx)(`div`,{"data-ok-interaction-layer":``,className:`contents`,children:(0,X.jsx)(tv,{store:n})}),t[0]=n,t[1]=r),r},ov=new WeakMap;function sv(e){let t=ov.get(e);if(t)return t;let n=iv({editor:e});return ov.set(e,n),e.on(`destroy`,()=>{n.destroy(),ov.delete(e)}),n}var cv=new be(`markIdentity`);function lv(){return{byId:new Map,counter:0}}function uv(e,t,n,r,i){let a=[];for(let e of t.byId.values()){let t=i?i.map(e.from,-1):e.from,n=i?i.map(e.to,1):e.to;n<=t||a.push({id:e.id,markType:e.markType,attrs:e.attrs,from:t,to:n})}let o=new Map,s=new Set,c=t.counter;return e.descendants((e,t)=>{if(!(!e.isInline||e.marks.length===0))for(let i of e.marks){if(!n.has(i.type.name)||r&&!r(i))continue;let l=null;for(let e of a)if(!s.has(e.id)&&e.markType===i.type.name&&dv(e.attrs,i.attrs)&&!(t<e.from||t>=e.to)){l=e.id;break}let u=l??`m${++c}`;s.add(u);let d=t,f=t+e.nodeSize,p=o.get(u);p?p.to=Math.max(p.to,f):o.set(u,{id:u,markType:i.type.name,attrs:i.attrs,from:d,to:f})}}),{byId:o,counter:c}}function dv(e,t){let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n){let n=e[r],i=t[r];if(n!==i&&!(typeof n==`object`&&n&&typeof i==`object`&&i&&dv(n,i)))return!1}return!0}function fv(e,t,n,r){let i=new Set(t.byId.keys());for(let[r,i]of t.byId)e.has(r)||n?.(i);for(let t of e)i.has(t)||r?.(t);return i}function pv(e){let{markTypes:t,predicate:n,onRegister:r,onDeregister:i}=e,a=new Set(t);return new E({key:cv,state:{init(e,t){return uv(t.doc,lv(),a,n)},apply(e,t,r,i){return e.docChanged?uv(i.doc,t,a,n,e.mapping):t}},view(){let e=new Set;return{update(t){let n=cv.getState(t.state);n&&(e=fv(e,n,r,i))},destroy(){for(let t of e)i?.(t);e=new Set}}}})}function mv(e,t){return cv.getState(e)?.byId.get(t)??null}function hv(e){let{editor:t,layer:n,renderPropPanel:r,handlePrimary:i}=e;return{onRegister:e=>{n.register({type:e.markType,nodeId:e.id,controls:{propPanel:e=>r({editor:t,nodeId:e.nodeId,deactivate:e.deactivate})},handlePrimary:i?e=>i({editor:t,nodeId:e.nodeId,newTab:e.newTab}):void 0})},onDeregister:e=>{n.deregister(e)}}}function gv(e){let{editor:t,layer:n,markTypes:r,predicate:i,renderPropPanel:a,handlePrimary:o}=e,s=hv({editor:t,layer:n,renderPropPanel:a,handlePrimary:o});return pv({markTypes:[...r],predicate:i,onRegister:s.onRegister,onDeregister:s.onDeregister})}function _v(e){let t=sv(e.editor);return gv({...e,layer:t})}function vv(e){let{char:t,allowSpaces:n,allowToIncludeChar:r,allowedPrefixes:i,startOfLine:a,$position:o}=e,s=n&&!r,c=ve(t),l=RegExp(`\\s${c}$`),u=a?`^`:``,d=r?``:c,f=RegExp(s?`${u}${c}.*?(?=\\s${d}|$)`:`${u}(?:^)?${c}[^\\s${d}]*`,`gm`),p=o.nodeBefore?.isText&&o.nodeBefore.text;if(!p)return null;let m=o.pos-p.length,h=Array.from(p.matchAll(f)).pop();if(!h||h.input===void 0||h.index===void 0)return null;let g=h.input.slice(Math.max(0,h.index-1),h.index),_=RegExp(`^[${i?.join(``)}\0]?$`).test(g);if(i!==null&&!_)return null;let v=m+h.index,y=v+h[0].length;return s&&l.test(p.slice(y-1,y+1))&&(h[0]+=` `,y+=1),v<o.pos&&y>=o.pos?{range:{from:v,to:y},query:h[0].slice(t.length),text:h[0]}:null}function yv(e){return e.docChanged?e.steps.some(e=>{let t=e.slice;if(!t?.content)return!1;let n=t.content.textBetween(0,t.content.size,`
|
|
4
|
+
`?a.insert.slice(0,-1):a.insert;(typeof o!=`string`||o.length>0)&&Jl(n,this,r,o,a.attributes||{})}else a.retain===void 0?a.delete!==void 0&&eu(n,r,a.delete):Yl(n,this,r,a.retain,a.attributes||{})}})}toDelta(e,t,n){this.doc??il();let r=[],i=new Map,a=this.doc,o=``,s=this._start;function c(){if(o.length>0){let e={},t=!1;i.forEach((n,r)=>{t=!0,e[r]=n});let n={insert:o};t&&(n.attributes=e),r.push(n),o=``}}let l=()=>{for(;s!==null;){if(vc(s,e)||t!==void 0&&vc(s,t))switch(s.content.constructor){case Nu:{let r=i.get(`ychange`);e!==void 0&&!vc(s,e)?(r===void 0||r.user!==s.id.client||r.type!==`removed`)&&(c(),i.set(`ychange`,n?n(`removed`,s.id):{type:`removed`})):t!==void 0&&!vc(s,t)?(r===void 0||r.user!==s.id.client||r.type!==`added`)&&(c(),i.set(`ychange`,n?n(`added`,s.id):{type:`added`})):r!==void 0&&(c(),i.delete(`ychange`)),o+=s.content.str;break}case Uu:case wu:{c();let e={insert:s.content.getContent()[0]};if(i.size>0){let t={};e.attributes=t,i.forEach((e,n)=>{t[n]=e})}r.push(e);break}case Eu:vc(s,e)&&(c(),Gl(i,s.content));break}s=s.right}c()};return e||t?Rc(a,n=>{e&&yc(n,e),t&&yc(n,t),l()},`cleanup`):l(),r}insert(e,t,n){if(t.length<=0)return;let r=this.doc;r===null?this._pending.push(()=>this.insert(e,t,n)):Rc(r,r=>{let i=Ul(r,this,e,!n);n||(n={},i.currentAttributes.forEach((e,t)=>{n[t]=e})),Jl(r,this,i,t,n)})}insertEmbed(e,t,n){let r=this.doc;r===null?this._pending.push(()=>this.insertEmbed(e,t,n||{})):Rc(r,r=>{let i=Ul(r,this,e,!n);Jl(r,this,i,t,n||{})})}delete(e,t){if(t===0)return;let n=this.doc;n===null?this._pending.push(()=>this.delete(e,t)):Rc(n,n=>{eu(n,Ul(n,this,e,!0),t)})}format(e,t,n){if(t===0)return;let r=this.doc;r===null?this._pending.push(()=>this.format(e,t,n)):Rc(r,r=>{let i=Ul(r,this,e,!1);i.right!==null&&Yl(r,this,i,t,n)})}removeAttribute(e){this.doc===null?this._pending.push(()=>this.removeAttribute(e)):Rc(this.doc,t=>{Dl(t,this,e)})}setAttribute(e,t){this.doc===null?this._pending.push(()=>this.setAttribute(e,t)):Rc(this.doc,n=>{Ol(n,this,e,t)})}getAttribute(e){return kl(this,e)}getAttributes(){return Al(this)}_write(e){e.writeTypeRef(Ru)}},ru=e=>new nu,iu=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??il()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(t)))do if(t=e.content.type,!e.deleted&&(t.constructor===su||t.constructor===au)&&t._start!==null)e=t._start;else for(;e!==null;){let t=e.next;if(t!==null){e=t;break}else e=e.parent===this._root?null:e.parent._item}while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}},au=class e extends ml{constructor(){super(),this._prelimContent=[]}get firstChild(){let 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(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof ml?e.clone():e)),t}get length(){return this.doc??il(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new iu(this,e)}querySelector(e){e=e.toUpperCase();let t=new iu(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),Kn(new iu(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){pl(this,e,new lu(this,t,e))}toString(){return yl(this,e=>e.toString()).join(``)}toJSON(){return this.toString()}toDOM(e=document,t={},n){let r=e.createDocumentFragment();return n!==void 0&&n._createAssociation(r,this),vl(this,i=>{r.insertBefore(i.toDOM(e,t,n),null)}),r}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):Rc(this.doc,n=>{wl(n,this,e,t)})}insertAfter(e,t){if(this.doc!==null)Rc(this.doc,n=>{let r=e&&e instanceof ml?e._item:e;Sl(n,this,r,t)});else{let n=this._prelimContent,r=e===null?0:n.findIndex(t=>t===e)+1;if(r===0&&e!==null)throw ii(`Reference item not found`);n.splice(r,0,...t)}}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):Rc(this.doc,n=>{El(n,this,e,t)})}toArray(){return gl(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return xl(this,e)}slice(e=0,t=this.length){return hl(this,e,t)}forEach(e){vl(this,e)}_write(e){e.writeTypeRef(Bu)}},ou=e=>new au,su=class e extends au{constructor(e=`UNDEFINED`){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let 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(){let t=new e(this.nodeName);return Bi(this.getAttributes(),(e,n)=>{t.setAttribute(n,e)}),t.insert(0,this.toArray().map(e=>e instanceof ml?e.clone():e)),t}toString(){let e=this.getAttributes(),t=[],n=[];for(let t in e)n.push(t);n.sort();let r=n.length;for(let i=0;i<r;i++){let r=n[i];t.push(r+`="`+e[r]+`"`)}let i=this.nodeName.toLocaleLowerCase();return`<${i}${t.length>0?` `+t.join(` `):``}>${super.toString()}</${i}>`}removeAttribute(e){this.doc===null?this._prelimAttrs.delete(e):Rc(this.doc,t=>{Dl(t,this,e)})}setAttribute(e,t){this.doc===null?this._prelimAttrs.set(e,t):Rc(this.doc,n=>{Ol(n,this,e,t)})}getAttribute(e){return kl(this,e)}hasAttribute(e){return jl(this,e)}getAttributes(e){return e?Ml(this,e):Al(this)}toDOM(e=document,t={},n){let r=e.createElement(this.nodeName),i=this.getAttributes();for(let e in i){let t=i[e];typeof t==`string`&&r.setAttribute(e,t)}return vl(this,i=>{r.appendChild(i.toDOM(e,t,n))}),n!==void 0&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(zu),e.writeKey(this.nodeName)}},cu=e=>new su(e.readKey()),lu=class extends nl{constructor(e,t,n){super(e,n),this.childListChanged=!1,this.attributesChanged=new Set,t.forEach(e=>{e===null?this.childListChanged=!0:this.attributesChanged.add(e)})}},uu=class e extends Rl{constructor(e){super(),this.hookName=e}_copy(){return new e(this.hookName)}clone(){let t=new e(this.hookName);return this.forEach((e,n)=>{t.set(n,e)}),t}toDOM(e=document,t={},n){let r=t[this.hookName],i;return i=r===void 0?document.createElement(this.hookName):r.createDom(this),i.setAttribute(`data-yjs-hook`,this.hookName),n!==void 0&&n._createAssociation(i,this),i}_write(e){e.writeTypeRef(Vu),e.writeKey(this.hookName)}},du=e=>new uu(e.readKey()),fu=class e extends nu{get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new e}clone(){let t=new e;return t.applyDelta(this.toDelta()),t}toDOM(e=document,t,n){let r=e.createTextNode(this.toString());return n!==void 0&&n._createAssociation(r,this),r}toString(){return this.toDelta().map(e=>{let t=[];for(let n in e.attributes){let r=[];for(let t in e.attributes[n])r.push({key:t,value:e.attributes[n][t]});r.sort((e,t)=>e.key<t.key?-1:1),t.push({nodeName:n,attrs:r})}t.sort((e,t)=>e.nodeName<t.nodeName?-1:1);let n=``;for(let e=0;e<t.length;e++){let r=t[e];n+=`<${r.nodeName}`;for(let e=0;e<r.attrs.length;e++){let t=r.attrs[e];n+=` ${t.key}="${t.value}"`}n+=`>`}n+=e.insert;for(let e=t.length-1;e>=0;e--)n+=`</${t[e].nodeName}>`;return n}).join(``)}toJSON(){return this.toString()}_write(e){e.writeTypeRef(Hu)}},pu=e=>new fu,mu=class{constructor(e,t){this.id=e,this.length=t}get deleted(){throw ai()}mergeWith(e){return!1}write(e,t,n){throw ai()}integrate(e,t){throw ai()}},hu=0,gu=class extends mu{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor?(this.length+=e.length,!0):!1}integrate(e,t){t>0&&(this.id.clock+=t,this.length-=t),Cc(e.doc.store,this)}write(e,t){e.writeInfo(hu),e.writeLen(this.length-t)}getMissing(e,t){return null}},_u=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 ai()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}},vu=e=>new _u(e.readBuf()),yu=class e{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.len)}splice(t){let n=new e(this.len-t);return this.len=t,n}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){_s(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}},bu=e=>new yu(e.readLen()),xu=(e,t)=>new ws({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1}),Su=class e{constructor(e){e._item&&console.error(`This document was already integrated as a sub-document. You should create a second instance instead with the same guid.`),this.doc=e;let t={};this.opts=t,e.gc||(t.gc=!1),e.autoLoad&&(t.autoLoad=!0),e.meta!==null&&(t.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new e(xu(this.doc.guid,this.opts))}splice(e){throw ai()}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}},Cu=e=>new Su(xu(e.readString(),e.readAny())),wu=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 ai()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}},Tu=e=>new wu(e.readJSON()),Eu=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 ai()}mergeWith(e){return!1}integrate(e,t){let 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}},Du=e=>new Eu(e.readKey(),e.readJSON()),Ou=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){let 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){let n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){let t=this.arr[r];e.writeString(t===void 0?`undefined`:JSON.stringify(t))}}getRef(){return 2}},ku=e=>{let t=e.readLen(),n=[];for(let r=0;r<t;r++){let t=e.readString();t===`undefined`?n.push(void 0):n.push(JSON.parse(t))}return new Ou(n)},Au=ia(`node_env`)===`development`,ju=class e{constructor(e){this.arr=e,Au&&qi(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){let 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){let n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){let t=this.arr[r];e.writeAny(t)}}getRef(){return 8}},Mu=e=>{let t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new ju(n)},Nu=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){let n=new e(this.str.slice(t));this.str=this.str.slice(0,t);let 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(t===0?this.str:this.str.slice(t))}getRef(){return 4}},Pu=e=>new Nu(e.readString()),Fu=[Il,zl,ru,cu,ou,du,pu],Iu=0,Lu=1,Ru=2,zu=3,Bu=4,Vu=5,Hu=6,Uu=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 ai()}mergeWith(e){return!1}integrate(e,t){this.type._integrate(e.doc,t)}delete(e){let t=this.type._start;for(;t!==null;)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(;t!==null;)t.gc(e,!0),t=t.right;this.type._start=null,this.type._map.forEach(t=>{for(;t!==null;)t.gc(e,!0),t=t.left}),this.type._map=new Map}write(e,t){this.type._write(e)}getRef(){return 7}},Wu=e=>new Uu(Fu[e.readTypeRef()](e)),Gu=(e,t)=>{let n=t,r=0,i;do r>0&&(n=$(n.client,n.clock+r)),i=Tc(e,n),r=n.clock-i.id.clock,n=i.redone;while(n!==null&&i instanceof Xu);return{item:i,diff:r}},Ku=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},qu=(e,t,n)=>{let{client:r,clock:i}=t.id,a=new Xu($(r,i+n),t,$(r,i+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&a.markDeleted(),t.keep&&(a.keep=!0),t.redone!==null&&(a.redone=$(t.redone.client,t.redone.clock+n)),t.right=a,a.right!==null&&(a.right.left=a),e._mergeStructs.push(a),a.parentSub!==null&&a.right===null&&a.parent._map.set(a.parentSub,a),t.length=n,a},Ju=(e,t)=>Jn(e,e=>ms(e.deletions,t)),Yu=(e,t,n,r,i,a)=>{let o=e.doc,s=o.store,c=o.clientID,l=t.redone;if(l!==null)return Dc(e,l);let u=t.parent._item,d=null,f;if(u!==null&&u.deleted===!0){if(u.redone===null&&(!n.has(u)||Yu(e,u,n,r,i,a)===null))return null;for(;u.redone!==null;)u=Dc(e,u.redone)}let p=u===null?t.parent:u.content.type;if(t.parentSub===null){for(d=t.left,f=t;d!==null;){let t=d;for(;t!==null&&t.parent._item!==u;)t=t.redone===null?null:Dc(e,t.redone);if(t!==null&&t.parent._item===u){d=t;break}d=d.left}for(;f!==null;){let t=f;for(;t!==null&&t.parent._item!==u;)t=t.redone===null?null:Dc(e,t.redone);if(t!==null&&t.parent._item===u){f=t;break}f=f.right}}else if(f=null,t.right&&!i){for(d=t;d!==null&&d.right!==null&&(d.right.redone||ms(r,d.right.id)||Ju(a.undoStack,d.right.id)||Ju(a.redoStack,d.right.id));)for(d=d.right;d.redone;)d=Dc(e,d.redone);if(d&&d.right!==null)return null}else d=p._map.get(t.parentSub)||null;let m=$(c,Sc(s,c)),h=new Xu(m,d,d&&d.lastId,f,f&&f.id,p,t.parentSub,t.content.copy());return t.redone=m,Ku(h,!0),h.integrate(e,0),h},Xu=class e extends mu{constructor(e,t,n,r,i,a,o,s){super(e,s.getLength()),this.origin=n,this.left=t,this.right=r,this.rightOrigin=i,this.parent=a,this.parentSub=o,this.redone=null,this.content=s,this.info=this.content.isCountable()?2:0}set marker(e){(this.info&8)>0!==e&&(this.info^=8)}get marker(){return(this.info&8)>0}get keep(){return(this.info&1)>0}set keep(e){this.keep!==e&&(this.info^=1)}get countable(){return(this.info&2)>0}get deleted(){return(this.info&4)>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>=Sc(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=Sc(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===tc&&this.id.client!==this.parent.client&&this.parent.clock>=Sc(n,this.parent.client))return this.parent.client;if(this.origin&&=(this.left=Oc(t,n,this.origin),this.left.lastId),this.rightOrigin&&=(this.right=Dc(t,this.rightOrigin),this.right.id),this.left&&this.left.constructor===gu||this.right&&this.right.constructor===gu)this.parent=null;else if(!this.parent)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);else if(this.parent.constructor===tc){let e=Tc(n,this.parent);e.constructor===gu?this.parent=null:this.parent=e.content.type}return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=Oc(e,e.doc.store,$(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||this.right.left!==null)||this.left&&this.left.right!==this.right){let t=this.left,n;if(t!==null)n=t.right;else if(this.parentSub!==null)for(n=this.parent._map.get(this.parentSub)||null;n!==null&&n.left!==null;)n=n.left;else n=this.parent._start;let r=new Set,i=new Set;for(;n!==null&&n!==this.right;){if(i.add(n),r.add(n),nc(this.origin,n.origin)){if(n.id.client<this.id.client)t=n,r.clear();else if(nc(this.rightOrigin,n.rightOrigin))break}else if(n.origin!==null&&i.has(Tc(e.doc.store,n.origin)))r.has(Tc(e.doc.store,n.origin))||(t=n,r.clear());else break;n=n.right}this.left=t}if(this.left!==null)this.right=this.left.right,this.left.right=this;else{let e;if(this.parentSub!==null)for(e=this.parent._map.get(this.parentSub)||null;e!==null&&e.left!==null;)e=e.left;else e=this.parent._start,this.parent._start=this;this.right=e}this.right===null?this.parentSub!==null&&(this.parent._map.set(this.parentSub,this),this.left!==null&&this.left.delete(e)):this.right.left=this,this.parentSub===null&&this.countable&&!this.deleted&&(this.parent._length+=this.length),Cc(e.doc.store,this),this.content.integrate(e,this),Nc(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new gu(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;e!==null&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;e!==null&&e.deleted;)e=e.left;return e}get lastId(){return this.length===1?this.id:$(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&nc(e.origin,this.lastId)&&this.right===e&&nc(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&this.redone===null&&e.redone===null&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){let 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,this.right!==null&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){let t=this.parent;this.countable&&this.parentSub===null&&(t._length-=this.length),this.markDeleted(),_s(e.deleteSet,this.id.client,this.id.clock,this.length),Nc(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw oi();this.content.gc(e),t?kc(e,this,new gu(this.id,this.length)):this.content=new yu(this.length)}write(e,t){let n=t>0?$(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,i=this.parentSub,a=this.content.getRef()&31|(n===null?0:128)|(r===null?0:64)|(i===null?0:32);if(e.writeInfo(a),n!==null&&e.writeLeftID(n),r!==null&&e.writeRightID(r),n===null&&r===null){let t=this.parent;if(t._item!==void 0){let n=t._item;if(n===null){let n=rc(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===tc?(e.writeParentInfo(!1),e.writeLeftID(t)):oi();i!==null&&e.writeString(i)}this.content.write(e,t)}},Zu=(e,t)=>Qu[t&31](e),Qu=[()=>{oi()},bu,ku,vu,Pu,Tu,Du,Wu,Mu,Cu,()=>{oi()}],$u=10,ed=class extends mu{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor?(this.length+=e.length,!0):!1}integrate(e,t){oi()}write(e,t){e.writeInfo($u),Z(e.restEncoder,this.length-t)}getMissing(e,t){return null}},td=typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:{},nd=`__ $YJS$ __`;td[nd]===!0&&console.error(`Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438`),td[nd]=!0;var rd=()=>{let e=!0;return(t,n)=>{if(e){e=!1;try{t()}finally{e=!0}}else n!==void 0&&n()}},id=/[\uD800-\uDBFF]/,ad=/[\uDC00-\uDFFF]/,od=(e,t)=>{let n=0,r=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n++;for(n>0&&id.test(e[n-1])&&n--;r+n<e.length&&r+n<t.length&&e[e.length-r-1]===t[t.length-r-1];)r++;return r>0&&ad.test(e[e.length-r])&&r--,{index:n,remove:e.length-n-r,insert:t.slice(n,t.length-r)}},sd=(e,t)=>e>>>t|e<<32-t,cd=e=>sd(e,2)^sd(e,13)^sd(e,22),ld=e=>sd(e,6)^sd(e,11)^sd(e,25),ud=e=>sd(e,7)^sd(e,18)^e>>>3,dd=e=>sd(e,17)^sd(e,19)^e>>>10,fd=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),pd=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),md=class{constructor(){let e=new ArrayBuffer(320);this._H=new Uint32Array(e,0,8),this._H.set(pd),this._W=new Uint32Array(e,64,64)}_updateHash(){let e=this._H,t=this._W;for(let e=16;e<64;e++)t[e]=dd(t[e-2])+t[e-7]+ud(t[e-15])+t[e-16];let n=e[0],r=e[1],i=e[2],a=e[3],o=e[4],s=e[5],c=e[6],l=e[7];for(let e=0,u,d;e<64;e++)u=l+ld(o)+(o&s^~o&c)+fd[e]+t[e]>>>0,d=cd(n)+(n&r^n&i^r&i)>>>0,l=c,c=s,s=o,o=a+u>>>0,a=i,i=r,r=n,n=u+d>>>0;e[0]+=n,e[1]+=r,e[2]+=i,e[3]+=a,e[4]+=o,e[5]+=s,e[6]+=c,e[7]+=l}digest(e){let t=0;for(;t+56<=e.length;){let n=0;for(;n<16&&t+3<e.length;n++)this._W[n]=e[t++]<<24|e[t++]<<16|e[t++]<<8|e[t++];if(t%64!=0){for(this._W.fill(0,n,16);t<e.length;)this._W[n]|=e[t]<<(3-t%4)*8,t++;this._W[n]|=128<<(3-t%4)*8}this._updateHash()}let n=t%64!=0;this._W.fill(0,0,16);let r=0;for(;t<e.length;r++)for(let n=3;n>=0&&t<e.length;n--)this._W[r]|=e[t++]<<n*8;n||(this._W[r-(t%4==0?0:1)]|=128<<(3-t%4)*8),this._W[14]=e.byteLength/gr,this._W[15]=e.byteLength*8,this._updateHash();let i=new Uint8Array(32);for(let e=0;e<this._H.length;e++)for(let t=0;t<4;t++)i[e*4+t]=this._H[e]>>>(3-t)*8;return i}},hd=e=>new md().digest(e),gd=new be(`y-sync`),_d=new be(`y-undo`),vd=new be(`yjs-cursor`),yd=e=>{for(let t=6;t<e.length;t++)e[t%6]=e[t%6]^e[t];return e.slice(0,6)},bd=e=>la(yd(hd(da(e)))),xd=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&t.sv.get(e.id.client)>e.id.clock&&!ms(t.ds,e.id),Sd=[{light:`#ecd44433`,dark:`#ecd444`}],Cd=(e,t,n)=>{if(!e.has(n)){if(e.size<t.length){let n=Un();e.forEach(e=>n.add(e)),t=t.filter(e=>!n.has(e))}e.set(n,Di(t))}return e.get(n)},wd=(e,{colors:t=Sd,colorMapping:n=new Map,permanentUserData:r=null,onFirstRender:i=()=>{},mapping:a}={})=>{let o=!1,s=new Od(e,a),c=new E({props:{editable:e=>{let t=gd.getState(e);return t.snapshot==null&&t.prevSnapshot==null}},key:gd,state:{init:(i,a)=>({type:e,doc:e.doc,binding:s,snapshot:null,prevSnapshot:null,isChangeOrigin:!1,isUndoRedoOperation:!1,addToHistory:!0,colors:t,colorMapping:n,permanentUserData:r}),apply:(e,t)=>{let n=e.getMeta(gd);if(n!==void 0){t=Object.assign({},t);for(let e in n)t[e]=n[e]}return t.addToHistory=e.getMeta(`addToHistory`)!==!1,t.isChangeOrigin=n!==void 0&&!!n.isChangeOrigin,t.isUndoRedoOperation=n!==void 0&&!!n.isChangeOrigin&&!!n.isUndoRedoOperation,s.prosemirrorView!==null&&n!==void 0&&(n.snapshot!=null||n.prevSnapshot!=null)&&Wo(0,()=>{s.prosemirrorView!=null&&(n.restore==null?s._renderSnapshot(n.snapshot,n.prevSnapshot,t):(s._renderSnapshot(n.snapshot,n.snapshot,t),delete t.restore,delete t.snapshot,delete t.prevSnapshot,s.mux(()=>{s._prosemirrorChanged(s.prosemirrorView.state.doc)})))}),t}},view:e=>(s.initView(e),a??s._forceRerender(),i(),{update:()=>{let t=c.getState(e.state);if(t.snapshot==null&&t.prevSnapshot==null&&(o||e.state.doc.content.findDiffStart(e.state.doc.type.createAndFill().content)!==null)){if(o=!0,t.addToHistory===!1&&!t.isChangeOrigin){let t=_d.getState(e.state),n=t&&t.undoManager;n&&n.stopCapturing()}s.mux(()=>{t.doc.transact(n=>{n.meta.set(`addToHistory`,t.addToHistory),s._prosemirrorChanged(e.state.doc)},gd)})}},destroy:()=>{s.destroy()}})});return c},Td=(e,t,n)=>{if(t!==null&&t.anchor!==null&&t.head!==null)if(t.type===`all`)e.setSelection(new B(e.doc));else if(t.type===`node`){let r=rf(n.doc,n.type,t.anchor,n.mapping);e.setSelection(Ed(e,r))}else{let r=rf(n.doc,n.type,t.anchor,n.mapping),i=rf(n.doc,n.type,t.head,n.mapping);r!==null&&i!==null&&e.setSelection(H.between(e.doc.resolve(r),e.doc.resolve(i)))}},Ed=(e,t)=>{let n=e.doc.resolve(t);return n.nodeAfter?xe.create(e.doc,t):H.near(n)},Dd=(e,t)=>({type:t.selection.jsonID,anchor:tf(t.selection.anchor,e.type,e.mapping),head:tf(t.selection.head,e.type,e.mapping)}),Od=class{constructor(e,t=new Map){this.type=e,this.prosemirrorView=null,this.mux=rd(),this.mapping=t,this.isOMark=new Map,this._observeFunction=this._typeChanged.bind(this),this.doc=e.doc,this.beforeTransactionSelection=null,this.beforeAllTransactions=()=>{this.beforeTransactionSelection===null&&this.prosemirrorView!=null&&(this.beforeTransactionSelection=Dd(this,this.prosemirrorView.state))},this.afterAllTransactions=()=>{this.beforeTransactionSelection=null},this._domSelectionInView=null}get _tr(){return this.prosemirrorView.state.tr.setMeta(`addToHistory`,!1)}_isLocalCursorInView(){return this.prosemirrorView.hasFocus()?($i&&this._domSelectionInView===null&&(Wo(0,()=>{this._domSelectionInView=null}),this._domSelectionInView=this._isDomSelectionInView()),this._domSelectionInView):!1}_isDomSelectionInView(){let e=this.prosemirrorView._root.getSelection();if(e==null||e.anchorNode==null)return!1;let t=this.prosemirrorView._root.createRange();t.setStart(e.anchorNode,e.anchorOffset),t.setEnd(e.focusNode,e.focusOffset),t.getClientRects().length===0&&t.startContainer&&t.collapsed&&t.selectNodeContents(t.startContainer);let n=t.getBoundingClientRect(),r=Oo.documentElement;return n.bottom>=0&&n.right>=0&&n.left<=(window.innerWidth||r.clientWidth||0)&&n.top<=(window.innerHeight||r.clientHeight||0)}renderSnapshot(e,t){t||=gc(vs(),new Map),this.prosemirrorView.dispatch(this._tr.setMeta(gd,{snapshot:e,prevSnapshot:t}))}unrenderSnapshot(){this.mapping.clear(),this.mux(()=>{let e=this.type.toArray().map(e=>Ad(e,this.prosemirrorView.state.schema,this)).filter(e=>e!==null),t=this._tr.replace(0,this.prosemirrorView.state.doc.content.size,new U(P.from(e),0,0));t.setMeta(gd,{snapshot:null,prevSnapshot:null}),this.prosemirrorView.dispatch(t)})}_forceRerender(){this.mapping.clear(),this.mux(()=>{let e=this.beforeTransactionSelection===null?this.prosemirrorView.state.selection:null,t=this.type.toArray().map(e=>Ad(e,this.prosemirrorView.state.schema,this)).filter(e=>e!==null),n=this._tr.replace(0,this.prosemirrorView.state.doc.content.size,new U(P.from(t),0,0));if(e){let t=tr(nr(e.anchor,0),n.doc.content.size),r=tr(nr(e.head,0),n.doc.content.size);n.setSelection(H.create(n.doc,t,r))}this.prosemirrorView.dispatch(n.setMeta(gd,{isChangeOrigin:!0,binding:this}))})}_renderSnapshot(e,t,n){let r=this.doc,i=this.type;if(e||=_c(this.doc),e instanceof Uint8Array||t instanceof Uint8Array)if((!(e instanceof Uint8Array)||!(t instanceof Uint8Array))&&oi(),r=new ws({gc:!1}),zs(r,t),t=_c(r),zs(r,e),e=_c(r),i._item===null){let e=Array.from(this.doc.share.keys()).find(e=>this.doc.share.get(e)===this.type);i=r.getXmlFragment(e)}else{let e=r.store.clients.get(i._item.id.client)??[];i=e[wc(e,i._item.id.clock)].content.type}this.mapping.clear(),this.mux(()=>{r.transact(r=>{let a=n.permanentUserData;a&&a.dss.forEach(e=>{fs(r,e,e=>{})});let o=(e,t)=>{let r=e===`added`?a.getUserByClientId(t.client):a.getUserByDeletedId(t);return{user:r,type:e,color:Cd(n.colorMapping,n.colors,r)}},s=_l(i,new hc(t.ds,e.sv)).map(n=>!n._item.deleted||xd(n._item,e)||xd(n._item,t)?Ad(n,this.prosemirrorView.state.schema,{mapping:new Map,isOMark:new Map},e,t,o):null).filter(e=>e!==null),c=this._tr.replace(0,this.prosemirrorView.state.doc.content.size,new U(P.from(s),0,0));this.prosemirrorView.dispatch(c.setMeta(gd,{isChangeOrigin:!0}))},gd)})}_typeChanged(e,t){if(this.prosemirrorView==null)return;let n=gd.getState(this.prosemirrorView.state);if(e.length===0||n.snapshot!=null||n.prevSnapshot!=null){this.renderSnapshot(n.snapshot,n.prevSnapshot);return}this.mux(()=>{let e=(e,t)=>this.mapping.delete(t);fs(t,t.deleteSet,e=>{if(e.constructor===Xu){let t=e.content.type;t&&this.mapping.delete(t)}}),t.changed.forEach(e),t.changedParentTypes.forEach(e);let n=this.type.toArray().map(e=>kd(e,this.prosemirrorView.state.schema,this)).filter(e=>e!==null),r=this._tr.replace(0,this.prosemirrorView.state.doc.content.size,new U(P.from(n),0,0));Td(r,this.beforeTransactionSelection,this),r=r.setMeta(gd,{isChangeOrigin:!0,isUndoRedoOperation:t.origin instanceof Hc}),this.beforeTransactionSelection!==null&&this._isLocalCursorInView()&&r.scrollIntoView(),this.prosemirrorView.dispatch(r)})}_prosemirrorChanged(e){this.doc.transact(()=>{Jd(this.doc,this.type,e,this),this.beforeTransactionSelection=Dd(this,this.prosemirrorView.state)},gd)}initView(e){this.prosemirrorView!=null&&this.destroy(),this.prosemirrorView=e,this.doc.on(`beforeAllTransactions`,this.beforeAllTransactions),this.doc.on(`afterAllTransactions`,this.afterAllTransactions),this.type.observeDeep(this._observeFunction)}destroy(){this.prosemirrorView!=null&&(this.prosemirrorView=null,this.type.unobserveDeep(this._observeFunction),this.doc.off(`beforeAllTransactions`,this.beforeAllTransactions),this.doc.off(`afterAllTransactions`,this.afterAllTransactions))}},kd=(e,t,n,r,i,a)=>{let o=n.mapping.get(e);if(o===void 0){if(e instanceof su)return Ad(e,t,n,r,i,a);throw ai()}return o},Ad=(e,t,n,r,i,a)=>{let o=[],s=e=>{if(e instanceof su){let s=kd(e,t,n,r,i,a);s!==null&&o.push(s)}else{let s=e._item.right?.content?.type;s instanceof nu&&!s._item.deleted&&s._item.id.client===s.doc.clientID&&(e.applyDelta([{retain:e.length},...s.toDelta()]),s.doc.transact(e=>{s._item.delete(e)}));let c=jd(e,t,n,r,i,a);c!==null&&c.forEach(e=>{e!==null&&o.push(e)})}};r===void 0||i===void 0?e.toArray().forEach(s):_l(e,new hc(i.ds,r.sv)).forEach(s);try{let s=e.getAttributes(r);r!==void 0&&(xd(e._item,r)?xd(e._item,i)||(s.ychange=a?a(`added`,e._item.id):{type:`added`}):s.ychange=a?a(`removed`,e._item.id):{type:`removed`});let c=t.node(e.nodeName,s,o);return n.mapping.set(e,c),c}catch(r){console.warn(`[y-prosemirror] schema.node(`+e.nodeName+`) threw:`,String(r&&r.message||r));let i=globalThis.__okYpsCounters=globalThis.__okYpsCounters||{block:0,inline:0};if(t.nodes[e.nodeName]&&t.nodes[e.nodeName].spec&&t.nodes[e.nodeName].spec.inline)i.inline++;else if(i.block++,t.nodes.rawMdxFallback)try{let i=t.node(`rawMdxFallback`,{reason:String(r&&r.message||r)},[t.text(e.nodeName)]);return n.mapping.set(e,i),i}catch(e){console.warn(`[y-prosemirror] rawMdxFallback substitution also failed:`,String(e&&e.message||e))}return n.mapping.delete(e),null}},jd=(e,t,n,r,i,a)=>{let o=[],s=e.toDelta(r,i,a);try{for(let e=0;e<s.length;e++){let n=s[e];o.push(t.text(n.insert,Kd(n.attributes,t)))}}catch(e){console.warn(`[y-prosemirror] schema.text() threw:`,String(e&&e.message||e));let t=globalThis.__okYpsCounters=globalThis.__okYpsCounters||{block:0,inline:0};return t.inline++,null}return o},Md=(e,t)=>{let n=new fu,r=e.map(e=>({insert:e.text,attributes:qd(e.marks,t)}));return n.applyDelta(r),t.mapping.set(n,e),n},Nd=(e,t)=>{let n=new su(e.type.name);for(let t in e.attrs){let r=e.attrs[t];r!==null&&t!==`ychange`&&n.setAttribute(t,r)}return n.insert(0,Ld(e).map(e=>Pd(e,t))),t.mapping.set(n,e),n},Pd=(e,t)=>e instanceof Array?Md(e,t):Nd(e,t),Fd=e=>typeof e==`object`&&!!e,Id=(e,t)=>{let n=Object.keys(e).filter(t=>e[t]!==null),r=n.length===Object.keys(t).filter(e=>t[e]!==null).length;for(let i=0;i<n.length&&r;i++){let a=n[i],o=e[a],s=t[a];r=a===`ychange`||o===s||Fd(o)&&Fd(s)&&Id(o,s)}return r},Ld=e=>{let t=e.content.content,n=[];for(let e=0;e<t.length;e++){let r=t[e];if(r.isText){let r=[];for(let n=t[e];e<t.length&&n.isText;n=t[++e])r.push(n);e--,n.push(r)}else n.push(r)}return n},Rd=(e,t)=>{let n=e.toDelta();return n.length===t.length&&n.every((e,n)=>e.insert===t[n].text&&zi(e.attributes||{}).length===t[n].marks.length&&Ui(e.attributes,(e,r)=>{let i=Gd(r),a=t[n].marks;return a.find(e=>e.type.name===i)?Id(e,a.find(e=>e.type.name===i)?.attrs):!1}))},zd=(e,t)=>{if(e instanceof su&&!(t instanceof Array)&&Yd(e,t)){let n=Ld(t);return e._length===n.length&&Id(e.getAttributes(),t.attrs)&&e.toArray().every((e,t)=>zd(e,n[t]))}return e instanceof fu&&t instanceof Array&&Rd(e,t)},Bd=(e,t)=>e===t||e instanceof Array&&t instanceof Array&&e.length===t.length&&e.every((e,n)=>t[n]===e),Vd=(e,t,n)=>{let r=e.toArray(),i=Ld(t),a=i.length,o=r.length,s=tr(o,a),c=0,l=0,u=!1;for(;c<s;c++){let e=r[c],t=i[c];if(Bd(n.mapping.get(e),t))u=!0;else if(!zd(e,t))break}for(;c+l<s;l++){let e=r[o-l-1],t=i[a-l-1];if(Bd(n.mapping.get(e),t))u=!0;else if(!zd(e,t))break}return{equalityFactor:c+l,foundMappedChild:u}},Hd=e=>{let t=``,n=e._start,r={};for(;n!==null;)n.deleted||(n.countable&&n.content instanceof Nu?t+=n.content.str:n.content instanceof Eu&&(r[n.content.key]=null)),n=n.right;return{str:t,nAttrs:r}},Ud=(e,t,n)=>{n.mapping.set(e,t);let{nAttrs:r,str:i}=Hd(e),a=t.map(e=>({insert:e.text,attributes:Object.assign({},r,qd(e.marks,n))})),{insert:o,remove:s,index:c}=od(i,a.map(e=>e.insert).join(``));e.delete(c,s),e.insert(c,o),e.applyDelta(a.map(e=>({retain:e.insert.length,attributes:e.attributes})))},Wd=/(.*)(--[a-zA-Z0-9+/=]{8})$/,Gd=e=>Wd.exec(e)?.[1]??e,Kd=(e,t)=>{let n=[];for(let r in e)n.push(t.mark(Gd(r),e[r]));return n},qd=(e,t)=>{let n={};return e.forEach(e=>{if(e.type.name!==`ychange`){let r=Bn(t.isOMark,e.type,()=>!e.type.excludes(e.type));n[r?`${e.type.name}--${bd(e.toJSON())}`:e.type.name]=e.attrs}}),n},Jd=(e,t,n,r)=>{if(t instanceof su&&t.nodeName!==n.type.name)throw Error(`node name mismatch!`);if(r.mapping.set(t,n),t instanceof su){let e=t.getAttributes(),r=n.attrs;for(let n in r)r[n]===null?t.removeAttribute(n):e[n]!==r[n]&&n!==`ychange`&&t.setAttribute(n,r[n]);for(let n in e)r[n]===void 0&&t.removeAttribute(n)}let i=Ld(n),a=i.length,o=t.toArray(),s=o.length,c=tr(a,s),l=0,u=0;for(;l<c;l++){let e=o[l],t=i[l];if(!Bd(r.mapping.get(e),t))if(zd(e,t))r.mapping.set(e,t);else break}for(;u+l+1<c;u++){let e=o[s-u-1],t=i[a-u-1];if(!Bd(r.mapping.get(e),t))if(zd(e,t))r.mapping.set(e,t);else break}e.transact(()=>{for(;s-l-u>0&&a-l-u>0;){let n=o[l],c=i[l],d=o[s-u-1],f=i[a-u-1];if(n instanceof fu&&c instanceof Array)Rd(n,c)||Ud(n,c,r),l+=1;else{let i=n instanceof su&&Yd(n,c),a=d instanceof su&&Yd(d,f);if(i&&a){let e=Vd(n,c,r),t=Vd(d,f,r);e.foundMappedChild&&!t.foundMappedChild?a=!1:!e.foundMappedChild&&t.foundMappedChild||e.equalityFactor<t.equalityFactor?i=!1:a=!1}i?(Jd(e,n,c,r),l+=1):a?(Jd(e,d,f,r),u+=1):(r.mapping.delete(t.get(l)),t.delete(l,1),t.insert(l,[Pd(c,r)]),l+=1)}}let n=s-l-u;if(s===1&&a===0&&o[0]instanceof fu?(r.mapping.delete(o[0]),o[0].delete(0,o[0].length)):n>0&&(t.slice(l,l+n).forEach(e=>r.mapping.delete(e)),t.delete(l,n)),l+u<a){let e=[];for(let t=l;t<a-u;t++)e.push(Pd(i[t],r));t.insert(l,e)}},gd)},Yd=(e,t)=>!(t instanceof Array)&&e.nodeName===t.type.name,Xd=null,Zd=class{constructor(e,t,n){this.view=e,this.key=t,this.value=n}apply(){let e=gd.getState(this.view.state);if(e&&e.binding&&!e.binding.isDestroyed){let e=this.view.state.tr;e.setMeta(this.key,this.value),this.view.dispatch(e)}}},Qd=class e{constructor(e=[]){this.entries=e}getFirst(){return this.entries[0]}dequeueFirst(){return this.entries.shift()}isEmpty(){return this.entries.length===0}static fromViewsToUpdate(){let t=Xd;Xd=null;let n=[];return t.forEach((e,t)=>{e.forEach((e,r)=>{n.push(new Zd(t,r,e))})}),new e(n)}},$d=(e=Qd.fromViewsToUpdate(),t=!1)=>{let n=!0;for(;!e.isEmpty();){let r=e.getFirst();try{r.apply()}catch(r){if(r instanceof RangeError){t&&n&&e.dequeueFirst(),e.isEmpty()||Wo(0,()=>$d(e,!0));return}throw r}n=!1,e.dequeueFirst()}},ef=(e,t,n)=>{Xd||(Xd=new Map,Wo(0,$d)),Bn(Xd,e,Rn).set(t,n)},tf=(e,t,n)=>{if(e===0)return dc(t,0,-1);let r=t._first===null?null:t._first.content.type;for(;r!==null&&t!==r;){if(r instanceof fu){if(r._length>=e)return dc(r,e,-1);if(e-=r._length,r._item!==null&&r._item.next!==null)r=r._item.next.content.type;else{do r=r._item===null?null:r._item.parent,e--;while(r!==t&&r!==null&&r._item!==null&&r._item.next===null);r!==null&&r!==t&&(r=r._item===null?null:r._item.next.content.type)}}else{let i=(n.get(r)||{nodeSize:0}).nodeSize;if(r._first!==null&&e<i)r=r._first.content.type,e--;else{if(e===1&&r._length===0&&i>1)return new ac(r._item===null?null:r._item.id,r._item===null?rc(r):null,null);if(e-=i,r._item!==null&&r._item.next!==null)r=r._item.next.content.type;else{if(e===0)return r=r._item===null?r:r._item.parent,new ac(r._item===null?null:r._item.id,r._item===null?rc(r):null,null);do r=r._item.parent,e--;while(r!==t&&r._item.next===null);r!==t&&(r=r._item.next.content.type)}}}if(r===null)throw oi();if(e===0&&r.constructor!==fu&&r!==t)return nf(r._item.parent,r._item)}return dc(t,t._length,-1)},nf=(e,t)=>{let n=null,r=null;return e._item===null?r=rc(e):n=$(e._item.id.client,e._item.id.clock),new ac(n,r,t.id)},rf=(e,t,n,r)=>{let i=pc(n,e);if(i===null||i.type!==t&&!ic(t,i.type._item))return null;let a=i.type,o=0;if(a.constructor===fu)o=i.index;else if(a._item===null||!a._item.deleted){let e=a._first,t=0;for(;t<a._length&&t<i.index&&e!==null;){if(!e.deleted){let n=e.content.type;t++,n instanceof fu?o+=n._length:o+=r.get(n).nodeSize}e=e.right}o+=1}for(;a!==t&&a._item!==null;){let e=a._item.parent;if(e._item===null||!e._item.deleted){o+=1;let t=e._first;for(;t!==null;){let e=t.content.type;if(e===a)break;t.deleted||(e instanceof fu?o+=e._length:o+=r.get(e).nodeSize),t=t.right}}a=e}return o-1},af=(e,t,n)=>e!==t,of=e=>{let t=document.createElement(`span`);t.classList.add(`ProseMirror-yjs-cursor`),t.setAttribute(`style`,`border-color: ${e.color}`);let n=document.createElement(`div`);n.setAttribute(`style`,`background-color: ${e.color}`),n.insertBefore(document.createTextNode(e.name),null);let r=document.createTextNode(``),i=document.createTextNode(``);return t.insertBefore(r,null),t.insertBefore(n,null),t.insertBefore(i,null),t},sf=e=>({style:`background-color: ${e.color}70`,class:`ProseMirror-yjs-selection`}),cf=/^#[0-9a-fA-F]{6}$/,lf=(e,t,n,r,i)=>{let a=gd.getState(e);if(a==null||a.doc==null||a.binding==null)return A.create(e.doc,[]);let o=a.doc,s=[];return a.snapshot!=null||a.prevSnapshot!=null||a.binding.mapping.size===0?A.create(e.doc,[]):(t.getStates().forEach((t,c)=>{if(n(o.clientID,c,t)&&t.cursor!=null){let n=t.user||{};n.color==null?n.color=`#ffa500`:cf.test(n.color)||console.warn(`A user uses an unsupported color format`,n),n.name??=`User: ${c}`;let l=rf(o,a.type,sc(t.cursor.anchor),a.binding.mapping),u=rf(o,a.type,sc(t.cursor.head),a.binding.mapping);if(l!==null&&u!==null){let t=nr(e.doc.content.size-1,0);l=tr(l,t),u=tr(u,t),s.push(j.widget(u,()=>r(n,c),{key:c+``,side:10}));let a=tr(l,u),o=nr(l,u);s.push(j.inline(a,o,i(n,c),{inclusiveEnd:!0,inclusiveStart:!1}))}}}),A.create(e.doc,s))},uf=(e,{awarenessStateFilter:t=af,cursorBuilder:n=of,selectionBuilder:r=sf,getSelection:i=e=>e.selection}={},a=`cursor`)=>new E({key:vd,state:{init(i,a){return lf(a,e,t,n,r)},apply(i,a,o,s){let c=gd.getState(s),l=i.getMeta(vd);return c&&c.isChangeOrigin||l&&l.awarenessUpdated?lf(s,e,t,n,r):a.map(i.mapping,i.doc)}},props:{decorations:e=>vd.getState(e)},view:t=>{let n=()=>{t.docView&&ef(t,vd,{awarenessUpdated:!0})},r=()=>{let n=gd.getState(t.state),r=e.getLocalState()||{};if(t.hasFocus()){let o=i(t.state),s=tf(o.anchor,n.type,n.binding.mapping),c=tf(o.head,n.type,n.binding.mapping);(r.cursor==null||!mc(sc(r.cursor.anchor),s)||!mc(sc(r.cursor.head),c))&&e.setLocalStateField(a,{anchor:s,head:c})}else r.cursor!=null&&rf(n.doc,n.type,sc(r.cursor.anchor),n.binding.mapping)!==null&&e.setLocalStateField(a,null)};return e.on(`change`,n),t.dom.addEventListener(`focusin`,r),t.dom.addEventListener(`focusout`,r),{update:r,destroy:()=>{t.dom.removeEventListener(`focusin`,r),t.dom.removeEventListener(`focusout`,r),e.off(`change`,n),e.setLocalStateField(a,null)}}}}),df=e=>{let t=_d.getState(e).undoManager;if(t!=null)return t.undo(),!0},ff=e=>{let t=_d.getState(e).undoManager;if(t!=null)return t.redo(),!0},pf=new Set([`paragraph`]),mf=(e,t)=>!(e instanceof Xu)||!(e.content instanceof Uu)||!(e.content.type instanceof nu||e.content.type instanceof su&&t.has(e.content.type.nodeName))||e.content.type._length===0,hf=({protectedNodes:e=pf,trackedOrigins:t=[],undoManager:n=null}={})=>new E({key:_d,state:{init:(r,i)=>{let a=gd.getState(i),o=n||new Hc(a.type,{trackedOrigins:new Set([gd].concat(t)),deleteFilter:t=>mf(t,e),captureTransaction:e=>e.meta.get(`addToHistory`)!==!1});return{undoManager:o,prevSel:null,hasUndoOps:o.undoStack.length>0,hasRedoOps:o.redoStack.length>0}},apply:(e,t,n,r)=>{let i=gd.getState(r).binding,a=t.undoManager,o=a.undoStack.length>0,s=a.redoStack.length>0;return i?{undoManager:a,prevSel:Dd(i,n),hasUndoOps:o,hasRedoOps:s}:o!==t.hasUndoOps||s!==t.hasRedoOps?Object.assign({},t,{hasUndoOps:a.undoStack.length>0,hasRedoOps:a.redoStack.length>0}):t}},view:e=>{let t=gd.getState(e.state),n=_d.getState(e.state).undoManager;return n.on(`stack-item-added`,({stackItem:n})=>{let r=t.binding;r&&n.meta.set(r,_d.getState(e.state).prevSel)}),n.on(`stack-item-popped`,({stackItem:e})=>{let n=t.binding;n&&(n.beforeTransactionSelection=e.meta.get(n)||n.beforeTransactionSelection)}),{destroy:()=>{n.destroy()}}}});Ne({event:pe(`ok-branch-switched-clear-failed`),branch:Ee(),docName:Ee(),reason:Ee()});async function gf(e,t){let n=[];for(let[r,i]of e.entries)i.kind===`active`&&n.push(i.persistence.clearData().catch(e=>{let n={event:`ok-branch-switched-clear-failed`,docName:r,branch:t,reason:e instanceof Error?e.message:String(e)};console.warn(JSON.stringify(n))}));await Promise.all(n),e.clearBufferedUpdates(),e.recycleAllEntries()}function _f(e){let t=!1;return()=>{t?e():t=!0}}function vf(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}async function yf(e,t=``){let n;try{n=await fetch(`${t}/api/server-info`,{signal:AbortSignal.timeout(5e3)})}catch{return}if(!n.ok)return;let r;try{r=await n.json()}catch{return}let i=W.safeParse(r);if(!i.success){console.warn(JSON.stringify({event:`ok-server-info-schema-mismatch`,issues:i.error.issues}));return}if(e.setExpectedServerInstanceId(i.data.serverInstanceId),i.data.currentBranch!==void 0&&e.compareAndUpdateObservedBranch(i.data.currentBranch)&&gf(e,i.data.currentBranch),i.data.currentDiskAckSVs!==void 0){let t={};for(let[e,n]of Object.entries(i.data.currentDiskAckSVs))try{t[e]=vf(n)}catch{}e.observeDiskAckBatch(t)}}async function bf(e){let t;try{t=await fetch(`/api/config`,{signal:e,headers:{Accept:`application/json`}})}catch(e){if(e.name===`AbortError`)throw e;return{status:`error`,code:`network`}}if(t.status===404||t.status===501)return{status:`absent`};if(!t.ok)return{status:`error`,code:t.status};let n;try{n=await t.json()}catch{return{status:`error`,code:`invalid-body`}}if(typeof n!=`object`||!n||Array.isArray(n))return{status:`error`,code:`invalid-body`};let r=n;return{status:`ok`,config:{collabUrl:typeof r.collabUrl==`string`?r.collabUrl:null,previewUrl:typeof r.previewUrl==`string`?r.previewUrl:null,port:typeof r.port==`number`?r.port:0}}}function xf(e){return Df(e,ke)}function Sf(e){return Df(e,_e)}function Cf(e){return Df(e,me)}function wf(e){let t=Df(e,Ce);if(!t)return null;try{return{docName:t.docName,sv:Tf(t.sv)}}catch{return null}}function Tf(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function Ef(e,t){let n=Sf(e);if(n){t.onServerInfo?.(n);return}let r=Cf(e);if(r){t.onBranchSwitched?.(r);return}let i=wf(e);if(i){t.onDiskAck?.(i);return}let a=xf(e);if(a){t.onDerivedView?.(a);return}t.onUnknown?.(e)}function Df(e,t){let n;try{n=JSON.parse(e)}catch{return null}let r=t.safeParse(n);return r.success?r.data:null}function Of(){return typeof location>`u`?`ws://localhost/collab`:`${location.protocol===`https:`?`wss`:`ws`}://${location.host}/collab`}function kf(e){if(e===void 0)return null;let t=e.okDesktop;return!t||!t.config.collabUrl||t.config.collabUrl.length===0?null:t}function Af(e){return{collabUrl:e.collabUrl,attempts:0,terminal:!1,lastError:null}}var jf=2e3,Mf=15e3;function Nf(e){let t=e.terminalAfterMs??3e4,n=e.initialDelayMs??jf,r=e.maxDelayMs??Mf,i=e.log??{info:console.info,warn:console.warn},a=new AbortController,o=null,s=n,c=0,l=!1,u=!1,d=null,f=e.now(),p=async()=>{c+=1;let n=null;try{let t=await e.fetchConfig(a.signal);t.status===`absent`?(n=e.fallbackUrl(),d=null):t.status===`ok`&&t.config.collabUrl!==null?(n=t.config.collabUrl,d=null):t.status===`ok`?(u||(u=!0,i.info(`[collab-url] ok ui responded but server.lock has no port yet — retrying`)),d={kind:`null-collab`}):t.status===`error`&&(i.warn(`[collab-url] /api/config error (${t.code}) — retrying in ${s}ms`),d={kind:`error`,code:t.code})}catch(e){if(e.name===`AbortError`)return;d={kind:`error`,code:`network`}}if(!l){if(n!==null){e.onStateChange({collabUrl:n,attempts:c,terminal:!1,lastError:null});return}if(e.now()-f>=t){e.onStateChange({collabUrl:null,attempts:c,terminal:!0,lastError:d});return}e.onStateChange({collabUrl:null,attempts:c,terminal:!1,lastError:d}),o=e.setTimeout(()=>{p()},s),s=Math.min(s*2,r)}};return p(),{cancel:()=>{l=!0,a.abort(),o!==null&&(e.clearTimeout(o),o=null)}}}function Pf(){let e=(0,at.c)(8),t;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t={collabUrl:null,attempts:0,terminal:!1,lastError:null},e[0]=t):t=e[0];let[n,r]=(0,J.useState)(t),i;e[1]===Symbol.for(`react.memo_cache_sentinel`)?(i={token:0},e[1]=i):i=e[1];let a=(0,J.useRef)(i),[o,s]=(0,J.useState)(0),c;e[2]===Symbol.for(`react.memo_cache_sentinel`)?(c=()=>{let e=a.current.token=a.current.token+1,t=kf(typeof window<`u`?window:void 0);if(t){r(Af(t.config));let n=t.onProjectSwitched(t=>{e===a.current.token&&r(Af(t))});return()=>{n()}}let n=Nf({fetchConfig:bf,fallbackUrl:Of,now:Date.now,setTimeout:Rf,clearTimeout:Lf,onStateChange:t=>{e===a.current.token&&r(t)}});return()=>{n.cancel()}},e[2]=c):c=e[2];let l;e[3]===o?l=e[4]:(l=[o],e[3]=o,e[4]=l),(0,J.useEffect)(c,l);let u;e[5]===Symbol.for(`react.memo_cache_sentinel`)?(u=()=>{a.current.token=a.current.token+1,r(If),s(Ff)},e[5]=u):u=e[5];let d=u,f;return e[6]===n?f=e[7]:(f={...n,retry:d},e[6]=n,e[7]=f),f}function Ff(e){return e+1}function If(e){return{...e,terminal:!1,lastError:null}}function Lf(e){return globalThis.clearTimeout(e)}function Rf(e,t){return globalThis.setTimeout(e,t)}function zf(e){return!(e.viewCount>0&&e.viewCount>=50||e.bytes>5e5)}var Bf=new Map,Vf=new Map,Hf=[],Uf=[],Wf=new Set,Gf=null;function Kf(){if(Gf)return Gf;if(typeof document>`u`||typeof document.createElement!=`function`)return null;let e=document.createElement(`div`);return e.setAttribute(`data-ok-editor-parking`,``),e.style.display=`none`,e.style.position=`absolute`,e.style.left=`-99999px`,Gf=e,e}function qf(e){let{docName:t,container:n,factory:r,sizeStats:i}=e;if(i&&!zf(i)){let e=r(n);return Y(`ok/cache/miss`,{docName:t,viewCount:i?.viewCount??-1,bytes:i?.bytes??-1,reason:`size-gate`}),{editor:e.editor,ydoc:e.ydoc,ytext:e.ytext,provider:e.provider,scrollTop:0,hadFocus:!1,activeMountKey:t,__uncached:!0}}let a=Bf.get(t);if(a){if(tp(a,n),a.activeMountKey=t,rp(Hf,t),n.scrollTop=a.scrollTop,a.hadFocus)try{a.editor.commands.focus()}catch{}return Y(`ok/cache/hit`,{docName:t,kind:`tiptap`}),i&&Y(`ok/cold/editor-mount-stats`,{docName:t,viewCount:i.viewCount,bytes:i.bytes,cacheHit:!0,kind:`tiptap`}),a}for(;Bf.size>=10;){let e=ip(Hf,t);if(!e)break;Yf(e)}let o=r(n),s={editor:o.editor,ydoc:o.ydoc,ytext:o.ytext,provider:o.provider,scrollTop:0,hadFocus:!1,activeMountKey:t};return Bf.set(t,s),rp(Hf,t),Y(`ok/cache/miss`,{docName:t,viewCount:i?.viewCount??-1,bytes:i?.bytes??-1,reason:`cold`,kind:`tiptap`}),i&&Y(`ok/cold/editor-mount-stats`,{docName:t,viewCount:i.viewCount,bytes:i.bytes,cacheHit:!1,kind:`tiptap`}),s}function Jf(e){if(e.__uncached){try{e.editor.destroy()}catch{}e.activeMountKey=null;return}let t=$f(e.editor);if(t){e.hadFocus=ep(t.dom),e.scrollTop=(t.scrollDOM??t.dom.parentElement??t.dom).scrollTop??0;let n=t.dom.parentElement;n&&n.removeChild(t.dom);let r=Kf();r&&r.appendChild(t.dom)}e.activeMountKey=null}function Yf(e){let t=Bf.get(e);if(!t)return!1;try{t.editor.destroy()}catch(t){Y(`ok/cache/evict-failed`,{docName:e,kind:`tiptap`,stage:`editor`,message:t instanceof Error?t.message:String(t)})}try{t.provider.destroy()}catch(t){Y(`ok/cache/evict-failed`,{docName:e,kind:`tiptap`,stage:`provider`,message:t instanceof Error?t.message:String(t)})}try{t.ydoc.destroy()}catch(t){Y(`ok/cache/evict-failed`,{docName:e,kind:`tiptap`,stage:`ydoc`,message:t instanceof Error?t.message:String(t)})}Bf.delete(e);let n=Hf.indexOf(e);return n!==-1&&Hf.splice(n,1),Y(`ok/cache/evict`,{docName:e,kind:`tiptap`}),!0}function Xf(e){let{docName:t,container:n,factory:r,sizeStats:i}=e;if(i&&!zf(i)){let e=r(n);return Y(`ok/cache/miss`,{docName:t,viewCount:i?.viewCount??-1,bytes:i?.bytes??-1,reason:`size-gate`,kind:`cm`}),{view:e.view,ydoc:e.ydoc,ytext:e.ytext,provider:e.provider,scrollTop:0,hadFocus:!1,activeMountKey:t,__uncached:!0}}let a=Vf.get(t);if(a){if(np(a,n),a.activeMountKey=t,rp(Uf,t),n.scrollTop=a.scrollTop,a.hadFocus)try{a.view.focus()}catch{}return Y(`ok/cache/hit`,{docName:t,kind:`cm`}),i&&Y(`ok/cold/editor-mount-stats`,{docName:t,viewCount:i.viewCount,bytes:i.bytes,cacheHit:!0,kind:`cm`}),a}for(;Vf.size>=10;){let e=ip(Uf,t);if(!e)break;Qf(e)}let o=r(n),s={view:o.view,ydoc:o.ydoc,ytext:o.ytext,provider:o.provider,scrollTop:0,hadFocus:!1,activeMountKey:t};return Vf.set(t,s),rp(Uf,t),Y(`ok/cache/miss`,{docName:t,viewCount:i?.viewCount??-1,bytes:i?.bytes??-1,reason:`cold`,kind:`cm`}),i&&Y(`ok/cold/editor-mount-stats`,{docName:t,viewCount:i.viewCount,bytes:i.bytes,cacheHit:!1,kind:`cm`}),s}function Zf(e){if(e.__uncached){try{e.view.destroy()}catch{}e.activeMountKey=null;return}let t=e.view.dom;e.hadFocus=ep(t),e.scrollTop=(e.view.scrollDOM??t).scrollTop??0;let n=t.parentElement;n&&n.removeChild(t);let r=Kf();r&&r.appendChild(t),e.activeMountKey=null}function Qf(e){let t=Vf.get(e);if(!t)return!1;try{t.view.destroy()}catch(t){Y(`ok/cache/evict-failed`,{docName:e,kind:`cm`,stage:`view`,message:t instanceof Error?t.message:String(t)})}try{t.provider.destroy()}catch(t){Y(`ok/cache/evict-failed`,{docName:e,kind:`cm`,stage:`provider`,message:t instanceof Error?t.message:String(t)})}try{t.ydoc.destroy()}catch(t){Y(`ok/cache/evict-failed`,{docName:e,kind:`cm`,stage:`ydoc`,message:t instanceof Error?t.message:String(t)})}Vf.delete(e);let n=Uf.indexOf(e);return n!==-1&&Uf.splice(n,1),Y(`ok/cache/evict`,{docName:e,kind:`cm`}),!0}function $f(e){return e.editorView??null}function ep(e){if(typeof document>`u`)return!1;let t=document.activeElement;return t?t===e?!0:e.contains(t):!1}function tp(e,t){let n=$f(e.editor);if(!n)return;let r=n.dom,i=r.parentElement;i&&i!==t&&i.removeChild(r),r.parentElement!==t&&t.appendChild(r)}function np(e,t){let n=e.view.dom,r=n.parentElement;r&&r!==t&&r.removeChild(n),n.parentElement!==t&&t.appendChild(n)}function rp(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1),e.push(t)}function ip(e,t){for(let n of e)if(n!==t&&!Wf.has(n))return n;Y(`ok/cache/evict-fallback-activity-saturated`,{mountingDocName:t,lruLength:e.length,activityMountCount:Wf.size});for(let n of e)if(n!==t)return n;return null}function ap(e){let t=Wf,n=new Set(e);for(let e of t){if(n.has(e))continue;let t=op(e);if(t)try{t.disconnect(),Y(`ok/cache/disconnect`,{docName:e})}catch(t){Y(`ok/cache/disconnect-failed`,{docName:e,message:t instanceof Error?t.message:String(t)})}}for(let e of n){if(t.has(e))continue;let n=op(e);if(!n)continue;let r=t=>{Y(`ok/cache/connect-failed`,{docName:e,message:t instanceof Error?t.message:String(t)})};try{let t=n.connect();t&&typeof t.then==`function`?t.then(()=>Y(`ok/cache/connect`,{docName:e}),e=>r(e)):Y(`ok/cache/connect`,{docName:e})}catch(e){r(e)}}Wf=n}function op(e){let t=Bf.get(e);if(t)return t.provider;let n=Vf.get(e);return n?n.provider:null}function sp(e){return e.onEvict(e=>{Yf(e),Qf(e)})}var cp=Math.floor,lp=(e,t)=>e<t?e:t,up=(e,t)=>e>t?e:t;Number.isNaN;var dp=128,fp=1<<17,pp=1<<18,mp=1<<19,hp=1<<20,gp=1<<21,_p=1<<22,vp=1<<23,yp=1<<24,bp=1<<25,xp=1<<26,Sp=1<<27,Cp=1<<28,wp=1<<29,Tp=1<<30,Ep=127;fp-1,pp-1,mp-1,hp-1,gp-1,_p-1,vp-1,yp-1,bp-1,xp-1,Sp-1,Cp-1,wp-1,Tp-1;var Dp=2**53-1;Number.isInteger,Number.isNaN,Number.parseInt;var Op=String.fromCharCode;String.fromCodePoint,Op(65535);var kp=e=>{let t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r},Ap=typeof TextEncoder<`u`?new TextEncoder:null,jp=Ap?e=>Ap.encode(e):kp,Mp=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});Mp&&Mp.decode(new Uint8Array).length===1&&(Mp=null);var Np=(e,t)=>{let n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Pp=(e,t)=>{for(;t>Ep;)Np(e,dp|Ep&t),t=cp(t/128);Np(e,Ep&t)},Fp=new Uint8Array(3e4),Ip=Fp.length/3,Lp=Ap&&Ap.encodeInto?(e,t)=>{if(t.length<Ip){let n=Ap.encodeInto(t,Fp).written||0;Pp(e,n);for(let t=0;t<n;t++)Np(e,Fp[t])}else zp(e,jp(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;Pp(e,r);for(let t=0;t<r;t++)Np(e,n.codePointAt(t))},Rp=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=lp(n-r,t.length),a=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,a>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(up(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},zp=(e,t)=>{Pp(e,t.byteLength),Rp(e,t)},Bp=e=>Error(e),Vp=Bp(`Unexpected end of array`),Hp=Bp(`Integer out of Range`),Up=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},Wp=e=>Up(e,Kp(e)),Gp=e=>e.arr[e.pos++],Kp=e=>{let t=0,n=1,r=e.arr.length;for(;e.pos<r;){let r=e.arr[e.pos++];if(t+=(r&Ep)*n,n*=128,r<dp)return t;if(t>Dp)throw Hp}throw Vp},qp=Mp?e=>Mp.decode(Wp(e)):e=>{let t=Kp(e);if(t===0)return``;{let n=String.fromCodePoint(Gp(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Gp(e));else for(;t>0;){let r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}},Jp=function(e){return e[e.Token=0]=`Token`,e[e.PermissionDenied=1]=`PermissionDenied`,e[e.Authenticated=2]=`Authenticated`,e}({}),Yp=(e,t)=>{Pp(e,Jp.Token),Lp(e,t)},Xp=(e,t,n,r)=>{switch(Kp(e)){case Jp.Token:t();break;case Jp.PermissionDenied:n(qp(e));break;case Jp.Authenticated:r(qp(e));break;default:}},Zp=e=>Array.from(e.entries()).map(([e,t])=>({clientId:e,...t})),Qp=`\0`;function $p(e,t){return e+Qp+t}function em(e){let t=e.indexOf(Qp);return t===-1?{documentName:e,sessionId:null}:{documentName:e.substring(0,t),sessionId:e.substring(t+1)}}var tm=function(e){return e[e.Connecting=0]=`Connecting`,e[e.Open=1]=`Open`,e[e.Closing=2]=`Closing`,e[e.Closed=3]=`Closed`,e}({});function nm(e){return e||={},{delay:e.delay===void 0?200:e.delay,initialDelay:e.initialDelay===void 0?0:e.initialDelay,minDelay:e.minDelay===void 0?0:e.minDelay,maxDelay:e.maxDelay===void 0?0:e.maxDelay,factor:e.factor===void 0?0:e.factor,maxAttempts:e.maxAttempts===void 0?3:e.maxAttempts,timeout:e.timeout===void 0?0:e.timeout,jitter:e.jitter===!0,initialJitter:e.initialJitter===!0,handleError:e.handleError===void 0?null:e.handleError,handleTimeout:e.handleTimeout===void 0?null:e.handleTimeout,beforeAttempt:e.beforeAttempt===void 0?null:e.beforeAttempt,calculateDelay:e.calculateDelay===void 0?null:e.calculateDelay}}async function rm(e){return new Promise(t=>setTimeout(t,e))}function im(e,t){let n=t.delay;if(n===0)return 0;if(t.factor&&(n*=t.factor**(e.attemptNum-1),t.maxDelay!==0&&(n=Math.min(n,t.maxDelay))),t.jitter){let e=Math.ceil(t.minDelay);n=Math.floor(Math.random()*(Math.floor(n)-e+1))+e}return Math.round(n)}async function am(e,t){let n=nm(t);for(let e of[`delay`,`initialDelay`,`minDelay`,`maxDelay`,`maxAttempts`,`timeout`]){let t=n[e];if(!Number.isInteger(t)||t<0)throw Error(`Value for ${e} must be an integer greater than or equal to 0`)}if(n.factor.constructor!==Number||n.factor<0)throw Error(`Value for factor must be a number greater than or equal to 0`);if(n.delay<n.minDelay)throw Error(`delay cannot be less than minDelay (delay: ${n.delay}, minDelay: ${n.minDelay}`);let r={attemptNum:0,attemptsRemaining:n.maxAttempts?n.maxAttempts:-1,aborted:!1,abort(){r.aborted=!0}},i=n.calculateDelay||im;async function a(){if(n.beforeAttempt&&n.beforeAttempt(r,n),r.aborted){let e=Error(`Attempt aborted`);throw e.code=`ATTEMPT_ABORTED`,e}let t=async e=>{if(n.handleError&&await n.handleError(e,r,n),r.aborted||r.attemptsRemaining===0)throw e;r.attemptNum++;let t=i(r,n);return t&&await rm(t),a()};return r.attemptsRemaining>0&&r.attemptsRemaining--,n.timeout?new Promise((i,a)=>{let o=setTimeout(()=>{if(n.handleTimeout)try{i(n.handleTimeout(r,n))}catch(e){a(e)}else{let e=Error(`Retry timeout (attemptNum: ${r.attemptNum}, timeout: ${n.timeout})`);e.code=`ATTEMPT_TIMEOUT`,a(e)}},n.timeout);e(r,n).then(e=>{clearTimeout(o),i(e)}).catch(e=>{clearTimeout(o),t(e).then(i).catch(a)})}):e(r,n).catch(t)}let o=n.calculateDelay?n.calculateDelay(r,n):n.initialDelay;if(o&&await rm(o),r.attemptNum<1&&n.initialJitter){let e=i(r,n);e&&await rm(e)}return a()}var om=Math.floor,sm=(e,t)=>e<t?e:t,cm=(e,t)=>e>t?e:t;Number.isNaN;var lm=64,um=128,dm=1<<17,fm=1<<18,pm=1<<19,mm=1<<20,hm=1<<21,gm=1<<22,_m=1<<23,vm=1<<24,ym=1<<25,bm=1<<26,xm=1<<27,Sm=1<<28,Cm=1<<29,wm=1<<30,Tm=63,Em=127;dm-1,fm-1,pm-1,mm-1,hm-1,gm-1,_m-1,vm-1,ym-1,bm-1,xm-1,Sm-1,Cm-1,wm-1;var Dm=2**53-1;Number.isInteger,Number.isNaN,Number.parseInt;var Om=()=>new Set,km=Array.from;Array.isArray;var Am=String.fromCharCode;String.fromCodePoint,Am(65535);var jm=e=>{let t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r},Mm=typeof TextEncoder<`u`?new TextEncoder:null,Nm=Mm?e=>Mm.encode(e):jm,Pm=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});Pm&&Pm.decode(new Uint8Array).length===1&&(Pm=null);var Fm=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}},Im=()=>new Fm,Lm=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},Rm=e=>{let t=new Uint8Array(Lm(e)),n=0;for(let r=0;r<e.bufs.length;r++){let i=e.bufs[r];t.set(i,n),n+=i.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t},zm=(e,t)=>{let n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Bm=(e,t)=>{for(;t>Em;)zm(e,um|Em&t),t=om(t/128);zm(e,Em&t)},Vm=new Uint8Array(3e4),Hm=Vm.length/3,Um=Mm&&Mm.encodeInto?(e,t)=>{if(t.length<Hm){let n=Mm.encodeInto(t,Vm).written||0;Bm(e,n);for(let t=0;t<n;t++)zm(e,Vm[t])}else Gm(e,Nm(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;Bm(e,r);for(let t=0;t<r;t++)zm(e,n.codePointAt(t))},Wm=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=sm(n-r,t.length),a=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,a>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(cm(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},Gm=(e,t)=>{Bm(e,t.byteLength),Wm(e,t)},Km=e=>Error(e),qm=Km(`Unexpected end of array`),Jm=Km(`Integer out of Range`),Ym=class{constructor(e){this.arr=e,this.pos=0}},Xm=e=>new Ym(e),Zm=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},Qm=e=>Zm(e,eh(e)),$m=e=>e.arr[e.pos++],eh=e=>{let t=0,n=1,r=e.arr.length;for(;e.pos<r;){let r=e.arr[e.pos++];if(t+=(r&Em)*n,n*=128,r<um)return t;if(t>Dm)throw Jm}throw qm},th=e=>{let t=e.arr[e.pos++],n=t&Tm,r=64,i=(t&lm)>0?-1:1;if((t&um)===0)return i*n;let a=e.arr.length;for(;e.pos<a;){if(t=e.arr[e.pos++],n+=(t&Em)*r,r*=128,t<um)return i*n;if(n>Dm)throw Jm}throw qm},nh=Pm?e=>Pm.decode(Qm(e)):e=>{let t=eh(e);if(t===0)return``;{let n=String.fromCodePoint($m(e));if(--t<100)for(;t--;)n+=String.fromCodePoint($m(e));else for(;t>0;){let r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}},rh=e=>{let t=e.pos,n=nh(e);return e.pos=t,n},ih=Date.now,ah=()=>new Map,oh=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r},sh=class{constructor(){this._observers=ah()}on(e,t){oh(this._observers,e,Om).add(t)}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){let n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return km((this._observers.get(e)||ah()).values()).forEach(e=>e(...t))}destroy(){this._observers=ah()}},ch=Symbol(`Equality`),lh=Object.keys,uh=e=>lh(e).length,dh=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),fh=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[ch]!=null)return e[ch](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;break;case Set:if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;break;case Map:if(e.size!==t.size)return!1;for(let n of e.keys())if(!t.has(n)||!fh(e.get(n),t.get(n)))return!1;break;case void 0:case Object:if(uh(e)!==uh(t))return!1;for(let n in e)if(!dh(e,n)||!fh(e[n],t[n]))return!1;break;case Array:if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!fh(e[n],t[n]))return!1;break;default:return!1}return!0},ph=3e4,mh=class extends sh{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let e=ih();this.getLocalState()!==null&&ph/2<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&ph<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&hh(this,t,`timeout`)},om(ph/10)),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){let t=this.clientID,n=this.meta.get(t),r=n===void 0?0:n.clock+1,i=this.states.get(t);e===null?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:r,lastUpdated:ih()});let a=[],o=[],s=[],c=[];e===null?c.push(t):i==null?e!=null&&a.push(t):(o.push(t),fh(i,e)||s.push(t)),(a.length>0||s.length>0||c.length>0)&&this.emit(`change`,[{added:a,updated:s,removed:c},`local`]),this.emit(`update`,[{added:a,updated:o,removed:c},`local`])}setLocalStateField(e,t){let n=this.getLocalState();n!==null&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}},hh=(e,t,n)=>{let r=[];for(let n=0;n<t.length;n++){let i=t[n];if(e.states.has(i)){if(e.states.delete(i),i===e.clientID){let t=e.meta.get(i);e.meta.set(i,{clock:t.clock+1,lastUpdated:ih()})}r.push(i)}}r.length>0&&(e.emit(`change`,[{added:[],updated:[],removed:r},n]),e.emit(`update`,[{added:[],updated:[],removed:r},n]))},gh=(e,t,n=e.states)=>{let r=t.length,i=Im();Bm(i,r);for(let a=0;a<r;a++){let r=t[a],o=n.get(r)||null,s=e.meta.get(r).clock;Bm(i,r),Bm(i,s),Um(i,JSON.stringify(o))}return Rm(i)},_h=(e,t,n)=>{let r=Xm(t),i=ih(),a=[],o=[],s=[],c=[],l=eh(r);for(let t=0;t<l;t++){let t=eh(r),n=eh(r),l=JSON.parse(nh(r)),u=e.meta.get(t),d=e.states.get(t),f=u===void 0?0:u.clock;(f<n||f===n&&l===null&&e.states.has(t))&&(l===null?t===e.clientID&&e.getLocalState()!=null?n++:e.states.delete(t):e.states.set(t,l),e.meta.set(t,{clock:n,lastUpdated:i}),u===void 0&&l!==null?a.push(t):u!==void 0&&l===null?c.push(t):l!==null&&(fh(l,d)||s.push(t),o.push(t)))}(a.length>0||s.length>0||c.length>0)&&e.emit(`change`,[{added:a,updated:s,removed:c},n]),(a.length>0||o.length>0||c.length>0)&&e.emit(`update`,[{added:a,updated:o,removed:c},n])},vh=class{constructor(){this.callbacks={}}on(e,t){return this.callbacks[e]||(this.callbacks[e]=[]),this.callbacks[e].push(t),this}emit(e,...t){let n=this.callbacks[e];return n&&n.forEach(e=>e.apply(this,t)),this}off(e,t){let n=this.callbacks[e];return n&&(t?this.callbacks[e]=n.filter(e=>e!==t):delete this.callbacks[e]),this}removeAllListeners(){this.callbacks={}}},yh=class{constructor(e){this.data=e,this.encoder=Im(),this.decoder=Xm(new Uint8Array(this.data))}peekVarString(){return rh(this.decoder)}readVarUint(){return eh(this.decoder)}readVarString(){return nh(this.decoder)}readVarUint8Array(){return Qm(this.decoder)}writeVarUint(e){return Bm(this.encoder,e)}writeVarString(e){return Um(this.encoder,e)}writeVarUint8Array(e){return Gm(this.encoder,e)}length(){return Lm(this.encoder)}},bh=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}({}),xh=function(e){return e.Connecting=`connecting`,e.Connected=`connected`,e.Disconnected=`disconnected`,e}({}),Sh=class{constructor(){this.encoder=Im()}get(e){return e.encoder}toUint8Array(){return Rm(this.encoder)}},Ch=class extends Sh{constructor(...e){super(...e),this.type=bh.CLOSE,this.description=`Ask the server to close the connection`}get(e){return Um(this.encoder,e.documentName),Bm(this.encoder,this.type),this.encoder}},wh=class e extends vh{static{this.DEDUPLICATABLE_TYPES=new Set([bh.Awareness,bh.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=xh.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=xh.Connected,this.emit(`status`,{status:xh.Connected}),this.cancelWebsocketRetry=void 0,this.receivedOnOpenPayload=e}attach(e){let t=e.effectiveName,n=this.configuration.providerMap.get(t);if(n&&n!==e&&n.isAuthenticated)throw 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===xh.Disconnected&&this.shouldConnect&&this.connect(),this.receivedOnOpenPayload&&this.status===xh.Connected&&e.onOpen(this.receivedOnOpenPayload)}detach(e){let t=e.effectiveName;this.configuration.providerMap.has(t)&&(e.send(Ch,{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===xh.Connected)return;this.cancelWebsocketRetry&&=(this.cancelWebsocketRetry(),void 0),this.receivedOnOpenPayload=void 0,this.shouldConnect=!0;let{retryPromise:e,cancelFunc:t}=(()=>{let e=!1;return{retryPromise:am(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&&e.code!==`ATTEMPT_ABORTED`)throw e}),cancelFunc:()=>{e=!0}}})();return this.cancelWebsocketRetry=t,e}attachWebSocketListeners(e,t){let{identifier:n}=e,r=e=>this.emit(`message`,e),i=e=>this.emit(`close`,{event:e}),a=e=>this.emit(`open`,e),o=e=>{t(e)};this.webSocketHandlers[n]={message:r,close:i,open:a,error:o};let s=this.webSocketHandlers[e.identifier];Object.keys(s).forEach(t=>{e.addEventListener(t,s[t])})}cleanupWebSocket(){if(!this.webSocket)return;let{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;let n=new this.configuration.WebSocketPolyfill(this.url);n.binaryType=`arraybuffer`,n.identifier=this.identifier,this.attachWebSocketListeners(n,t),this.webSocket=n,this.status=xh.Connecting,this.emit(`status`,{status:xh.Connecting}),this.connectionAttempt={resolve:e,reject:t}})}onMessage(e){this.resolveConnectionAttempt(),this.lastMessageReceived=ih();let t=new Uint8Array(e.data);if(t.length===1&&t[0]===bh.Ping){this.sendPong();return}let n=new yh(t).peekVarString();this.configuration.providerMap.get(n)?.onMessage(e)}sendPong(){let e=Im();Bm(e,bh.Pong),this.send(Rm(e))}resolveConnectionAttempt(){this.connectionAttempt&&(this.connectionAttempt.resolve(),this.connectionAttempt=null,this.status=xh.Connected,this.emit(`status`,{status:xh.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===xh.Connected&&this.lastMessageReceived&&(this.configuration.messageReconnectTimeout>=ih()-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,this.webSocket!==null)try{this.webSocket.close(),this.messageQueue=[]}catch(e){console.error(e)}}parseQueuedMessage(e){try{let t=Xm(e);return{documentName:nh(t),messageType:eh(t)}}catch{return null}}addToQueue(t){if(t instanceof Uint8Array){let n=this.parseQueuedMessage(t);n&&e.DEDUPLICATABLE_TYPES.has(n.messageType)&&(this.messageQueue=this.messageQueue.filter(e=>{if(!(e instanceof Uint8Array))return!0;let t=this.parseQueuedMessage(e);return t?!(t.documentName===n.documentName&&t.messageType===n.messageType):!0}))}this.messageQueue.push(t)}send(e){this.webSocket?.readyState===tm.Open?this.webSocket.send(e):this.addToQueue(e)}onClose({event:e}){this.closeTries=0,this.cleanupWebSocket(),this.connectionAttempt&&this.rejectConnectionAttempt(),this.status=xh.Disconnected,this.emit(`status`,{status:xh.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()}},Th=0,Eh=1,Dh=2,Oh=(e,t)=>{Bm(e,Th),Gm(e,Ys(t))},kh=(e,t,n)=>{Bm(e,Eh),Gm(e,Us(t,n))},Ah=(e,t,n)=>kh(t,n,Qm(e)),jh=(e,t,n,r)=>{try{Bs(t,Qm(e),n)}catch(e){r?.(e),console.error(`Caught error while handling a Yjs update`,e)}},Mh=(e,t)=>{Bm(e,Dh),Gm(e,t)},Nh=jh,Ph=(e,t,n,r,i)=>{let a=eh(e);switch(a){case Th:Ah(e,t,n);break;case Eh:jh(e,n,r,i);break;case Dh:Nh(e,n,r,i);break;default:throw Error(`Unknown message type`)}return a},Fh=class{constructor(e){this.message=e}apply(e,t){let{message:n}=this,r=n.readVarUint(),i=n.length();switch(r){case bh.Sync:this.applySyncMessage(e,t);break;case bh.Awareness:this.applyAwarenessMessage(e);break;case bh.Auth:this.applyAuthMessage(e);break;case bh.QueryAwareness:this.applyQueryAwarenessMessage(e);break;case bh.Stateless:e.receiveStateless(nh(n.decoder));break;case bh.SyncStatus:this.applySyncStatusMessage(e,th(n.decoder)===1);break;case bh.CLOSE:let i={code:1e3,reason:nh(n.decoder)};e.onClose(),e.configuration.onClose({event:i}),e.forwardClose({event:i});break;default:console.error(`Can’t apply message of unknown type: ${r}`)}n.length()>i+1&&e.send(Sh,{encoder:n.encoder})}applySyncMessage(e,t){let{message:n}=this;n.writeVarUint(bh.Sync);let r=Ph(n.decoder,n.encoder,e.document,e);t&&r===Eh&&(e.synced=!0)}applySyncStatusMessage(e,t){t&&e.decrementUnsyncedChanges()}applyAwarenessMessage(e){if(!e.awareness)return;let{message:t}=this;_h(e.awareness,t.readVarUint8Array(),e)}applyAuthMessage(e){let{message:t}=this;Xp(t.decoder,e.sendToken.bind(e),e.permissionDeniedHandler.bind(e),e.authenticatedHandler.bind(e))}applyQueryAwarenessMessage(e){if(!e.awareness)return;let{message:t}=this;t.writeVarUint(bh.Awareness),t.writeVarUint8Array(gh(e.awareness,Array.from(e.awareness.getStates().keys())))}},Ih=class{constructor(e,t={}){this.message=new e,this.encoder=this.message.get(t)}create(){return Rm(this.encoder)}send(e){e?.send(this.create())}},Lh=`4.0.0-rc.1`,Rh=class extends Sh{constructor(...e){super(...e),this.type=bh.Auth,this.description=`Authentication`}get(e){if(e.token===void 0)throw Error("The authentication message requires `token` as an argument.");return Um(this.encoder,e.documentName),Bm(this.encoder,this.type),Yp(this.encoder,e.token),Um(this.encoder,Lh),this.encoder}},zh=class extends Sh{constructor(...e){super(...e),this.type=bh.Awareness,this.description=`Awareness states update`}get(e){if(e.awareness===void 0)throw Error(`The awareness message requires awareness as an argument`);if(e.clients===void 0)throw Error(`The awareness message requires clients as an argument`);Um(this.encoder,e.documentName),Bm(this.encoder,this.type);let t;return t=e.states===void 0?gh(e.awareness,e.clients):gh(e.awareness,e.clients,e.states),Gm(this.encoder,t),this.encoder}},Bh=class extends Sh{constructor(...e){super(...e),this.type=bh.Stateless,this.description=`A stateless message`}get(e){return Um(this.encoder,e.documentName),Bm(this.encoder,this.type),Um(this.encoder,e.payload??``),this.encoder}},Vh=class extends Sh{constructor(...e){super(...e),this.type=bh.Sync,this.description=`First sync step`}get(e){if(e.document===void 0)throw Error(`The sync step one message requires document as an argument`);return Um(this.encoder,e.documentName),Bm(this.encoder,this.type),Oh(this.encoder,e.document),this.encoder}},Hh=class extends Sh{constructor(...e){super(...e),this.type=bh.Sync,this.description=`A document update`}get(e){return Um(this.encoder,e.documentName),Bm(this.encoder,this.type),Mh(this.encoder,e.update),this.encoder}},Uh=class extends Error{constructor(...e){super(...e),this.code=1001}},Wh=class extends vh{get effectiveName(){return this.configuration.sessionAwareness?$p(this.configuration.name,this.sessionId):this.configuration.name}constructor(e){super(),this.configuration={name:``,document:void 0,awareness:void 0,token:null,sessionAwareness:!0,forceSyncInterval:!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.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 ws,this.configuration.awareness=e.awareness===void 0?new mh(this.document):e.awareness,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:Zp(this.awareness.getStates())})}),this.awareness?.on(`change`,()=>{this.emit(`awarenessChange`,{states:Zp(this.awareness.getStates())})}),this.document.on(`update`,this.boundDocumentUpdateHandler),this.awareness?.on(`update`,this.boundAwarenessUpdateHandler),this.registerEventListeners(),this.configuration.forceSyncInterval&&typeof this.configuration.forceSyncInterval==`number`&&(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 wh(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,this.unsyncedChanges===0&&(this.synced=!0),this.emit(`unsyncedChanges`,{number:this.unsyncedChanges})}forceSync(){this.resetUnsyncedChanges(),this.send(Vh,{document:this.document,documentName:this.effectiveName})}pageHide(){this.awareness&&hh(this.awareness,[this.document.clientID],`page hide`)}registerEventListeners(){typeof window>`u`||!(`addEventListener`in window)||window.addEventListener(`pagehide`,this.boundPageHide)}sendStateless(e){this.send(Bh,{documentName:this.effectiveName,payload:e})}async sendToken(){let e;try{e=await this.getToken()}catch(e){this.permissionDeniedHandler(`Failed to get token during sendToken(): ${e}`);return}this.send(Rh,{token:e??``,documentName:this.effectiveName})}documentUpdateHandler(e,t){t!==this&&(this.incrementUnsyncedChanges(),this.send(Hh,{update:e,documentName:this.effectiveName}))}awarenessUpdateHandler({added:e,updated:t,removed:n},r){let i=e.concat(t).concat(n);this.send(zh,{awareness:this.awareness,clients:i,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();console.warn(`HocuspocusProvider::connect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.`)}disconnect(){if(this.manageSocket)return this.configuration.websocketProvider.disconnect();console.warn(`HocuspocusProvider::disconnect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.`)}async onOpen(e){this.isAuthenticated=!1,this.emit(`open`,{event:e}),await this.sendToken(),this.startSync()}async getToken(){return typeof this.configuration.token==`function`?await this.configuration.token():this.configuration.token}startSync(){this.resetUnsyncedChanges(),this.send(Vh,{document:this.document,documentName:this.effectiveName}),this.awareness&&this.awareness.getLocalState()!==null&&this.send(zh,{awareness:this.awareness,clients:[this.document.clientID],documentName:this.effectiveName})}send(e,t){if(!this._isAttached)return;let n=new Ih(e,t);this.emit(`outgoingMessage`,{message:n.message}),n.send(this.configuration.websocketProvider)}onMessage(e){let t=new yh(e.data),{documentName:n}=em(t.readVarString());t.writeVarString(this.effectiveName),this.emit(`message`,{event:e,message:new yh(e.data)}),new Fh(t).apply(this,!0)}onClose(){this.isAuthenticated=!1,this.synced=!1,this.awareness&&hh(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&&(hh(this.awareness,[this.document.clientID],`provider destroy`),this.awareness.off(`update`,this.boundAwarenessUpdateHandler),this.awareness.destroy()),this.document.off(`update`,this.boundDocumentUpdateHandler),this.removeAllListeners(),this.detach(),this.manageSocket&&this.configuration.websocketProvider.destroy(),!(typeof window>`u`||!(`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),!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 Uh(`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)}},Gh=e=>ji((t,n)=>{e.onerror=e=>n(Error(e.target.error)),e.onsuccess=e=>t(e.target.result)}),Kh=(e,t)=>ji((n,r)=>{let i=indexedDB.open(e);i.onupgradeneeded=e=>t(e.target.result),i.onerror=e=>r(ii(e.target.error)),i.onsuccess=e=>{let t=e.target.result;t.onversionchange=()=>{t.close()},n(t)}}),qh=e=>Gh(indexedDB.deleteDatabase(e)),Jh=(e,t)=>t.forEach(t=>e.createObjectStore.apply(e,t)),Yh=(e,t,n=`readwrite`)=>{let r=e.transaction(t,n);return t.map(e=>og(r,e))},Xh=(e,t)=>Gh(e.count(t)),Zh=(e,t)=>Gh(e.get(t)),Qh=(e,t)=>Gh(e.delete(t)),$h=(e,t,n)=>Gh(e.put(t,n)),eg=(e,t)=>Gh(e.add(t)),tg=(e,t,n)=>Gh(e.getAll(t,n)),ng=(e,t,n)=>{let r=null;return ag(e,t,e=>(r=e,!1),n).then(()=>r)},rg=(e,t=null)=>ng(e,t,`prev`),ig=(e,t)=>ji((n,r)=>{e.onerror=r,e.onsuccess=async e=>{let r=e.target.result;if(r===null||await t(r)===!1)return n();r.continue()}}),ag=(e,t,n,r=`next`)=>ig(e.openKeyCursor(t,r),e=>n(e.key)),og=(e,t)=>e.objectStore(t),sg=(e,t)=>IDBKeyRange.upperBound(e,t),cg=(e,t)=>IDBKeyRange.lowerBound(e,t),lg=`custom`,ug=`updates`,dg=(e,t=()=>{},n=()=>{})=>{let[r]=Yh(e.db,[ug]);return tg(r,cg(e._dbref,!1)).then(i=>{e._destroyed||(t(r),Rc(e.doc,()=>{i.forEach(t=>Bs(e.doc,t))},e,!1),n(r))}).then(()=>rg(r).then(t=>{e._dbref=t+1})).then(()=>Xh(r).then(t=>{e._dbsize=t})).then(()=>r)},fg=(e,t=!0)=>dg(e).then(n=>{(t||e._dbsize>=500)&&eg(n,Us(e.doc)).then(()=>Qh(n,sg(e._dbref,!0))).then(()=>Xh(n).then(t=>{e._dbsize=t}))}),pg=class extends Qn{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=Kh(e,e=>Jh(e,[[`updates`,{autoIncrement:!0}],[`custom`]])),this.whenSynced=ji(e=>this.on(`synced`,()=>e(this))),this._db.then(e=>{this.db=e,dg(this,async e=>{await Xh(e)>0&&eg(e,Us(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){let[t]=Yh(this.db,[ug]);eg(t,e).catch(e=>{globalThis.__okYdbWriteWarned||(globalThis.__okYdbWriteWarned=!0,console.warn(JSON.stringify({event:`ok-ydb-write-failed`,cause:e?.name??`unknown`,message:e?.message??String(e)})))}),++this._dbsize>=500&&(this._storeTimeoutId!==null&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{fg(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(()=>{qh(this.name)})}get(e){return this._db.then(t=>{let[n]=Yh(t,[lg],`readonly`);return Zh(n,e)})}set(e,t){return this._db.then(n=>{let[r]=Yh(n,[lg]);return $h(r,t,e)})}del(e){return this._db.then(t=>{let[n]=Yh(t,[lg]);return Qh(n,e)})}},mg=class{_idb;_dbName;whenSynced;constructor({branch:e,docName:t,doc:n}){this._dbName=`ok-ydoc:${e}:${t}`,this._idb=new pg(this._dbName,n),this.whenSynced=this._idb.whenSynced.then(()=>this)}get synced(){return this._idb.synced}async destroy(){await this._idb.destroy()}async clearData(){await this._idb.destroy();let e=this._dbName;await new Promise((t,n)=>{let r=indexedDB.deleteDatabase(e);r.onsuccess=()=>t(),r.onerror=()=>n(r.error),r.onblocked=()=>{console.warn(JSON.stringify({event:`ok-client-persistence-clear-blocked`,dbName:e})),n(Error(`idb-clear-blocked: ${e}`))}})}};function hg(e){return new mg(e)}function gg(e){return Ys(e)}function _g(e,t){return t===null?Us(e):Us(e,t)}function vg(e,t){if(e===null)return t;if(t===null)return e;let n=Gs(e),r=Gs(t),i=new Map;for(let[e,t]of n)i.set(e,t);for(let[e,t]of r){let n=i.get(e);(n===void 0||t>n)&&i.set(e,t)}return Ys(i)}function yg(e){let t={};if(r.inject(n.active(),t),!t.traceparent)return e;let i=e.includes(`?`)?`&`:`?`,a=[`traceparent=${encodeURIComponent(t.traceparent)}`];return t.tracestate&&a.push(`tracestate=${encodeURIComponent(t.tracestate)}`),`${e}${i}${a.join(`&`)}`}var bg=({key:e,editor:t,onPaste:n,onDrop:r,allowedMimeTypes:i})=>new E({key:e||new be(`fileHandler`),props:{handleDrop(e,n){if(!r||!n.dataTransfer?.files.length)return!1;let a=e.posAtCoords({left:n.clientX,top:n.clientY}),o=Array.from(n.dataTransfer.files);return i&&(o=o.filter(e=>i.includes(e.type))),o.length===0?!1:(n.preventDefault(),n.stopPropagation(),r(t,o,a?.pos||0),!0)},handlePaste(e,r){if(!n||!r.clipboardData?.files.length)return!1;let a=Array.from(r.clipboardData.files),o=r.clipboardData.getData(`text/html`);return i&&(a=a.filter(e=>i.includes(e.type))),!(a.length===0||(r.preventDefault(),r.stopPropagation(),n(t,a,o),o.length>0))}}}),xg=fe.create({name:`fileHandler`,addOptions(){return{onPaste:void 0,onDrop:void 0,allowedMimeTypes:void 0}},addProseMirrorPlugins(){return[bg({key:new be(this.name),editor:this.editor,allowedMimeTypes:this.options.allowedMimeTypes,onDrop:this.options.onDrop,onPaste:this.options.onPaste})]}}),Sg=new be(`imageUpload`);function Cg(){let e=document.createElement(`div`);return e.className=`image-upload-skeleton w-full h-40 rounded-md bg-muted animate-pulse motion-reduce:animate-none my-2`,e.setAttribute(`data-upload-widget`,`loading`),e.setAttribute(`role`,`status`),e.setAttribute(`aria-label`,`Uploading image...`),e}var wg=new E({key:Sg,state:{init(){return{decorations:A.empty,uploads:new Map}},apply(e,t){let n=t.decorations.map(e.mapping,e.doc),r=new Map;for(let[n,i]of t.uploads)r.set(n,e.mapping.map(i));let i=e.getMeta(Sg);if(!i)return{decorations:n,uploads:r};if(i.type===`add`){let t=j.widget(i.pos,i.widget,{id:i.id,stopEvent:()=>!0}),a=n.add(e.doc,[t]),o=new Map(r);return o.set(i.id,e.mapping.map(i.pos)),{decorations:a,uploads:o}}if(i.type===`remove`){let e=n.find(void 0,void 0,e=>e.id===i.id),t=n.remove(e),a=new Map(r);return a.delete(i.id),{decorations:t,uploads:a}}return{decorations:n,uploads:r}}},props:{decorations(e){return Sg.getState(e)?.decorations??A.empty}}}),Tg=null;function Eg(e){Tg=e}async function Dg(e,t,n){let r=Tg?`${Tg}.md`:``;if(!r){f.error(`Cannot upload: no document is open`);return}let i=crypto.randomUUID(),a=Cg();t.view.dispatch(t.state.tr.setMeta(Sg,{type:`add`,id:i,pos:n,widget:a}));let o=new FormData;o.append(`file`,e),o.append(`parentDocName`,r);let s;try{s=await fetch(`/api/upload-image`,{method:`POST`,body:o})}catch(e){console.error(`[uploadAndInsert] Network error:`,e),Og(t,i);return}if(!s.ok){let e=`Upload failed (${s.status})`;try{let t=await s.json();t.error&&(e=t.error)}catch{}console.error(`[uploadAndInsert] Server error:`,e),Og(t,i,e);return}let c;try{let e=await s.json();if(typeof e.src!=`string`)throw Error(`missing src in response`);c=e.src}catch(e){console.error(`[uploadAndInsert] Response parse error:`,e),Og(t,i);return}let l=e.name.replace(/\.[^.]+$/,``),{state:u}=t,d=Sg.getState(u)?.uploads.get(i)??n,p=u.schema.nodes.image;if(!p){console.error(`[uploadAndInsert] Image node type not found in schema`),Og(t,i);return}let m=u.tr.setMeta(Sg,{type:`remove`,id:i}).insert(d,p.create({src:c,alt:l}));t.view.dispatch(m)}function Og(e,t,n){e.view.dispatch(e.state.tr.setMeta(Sg,{type:`remove`,id:t})),f.error(n??`Upload failed`)}function kg(e){let{$from:t}=e.selection;return t.depth===0?null:{from:t.before(1),to:t.after(1)}}function Ag(e,t){let n=kg(e);if(!n)return!1;let{from:r,to:i}=n;if(r===0)return!1;let a=e.doc.resolve(r-1);if(a.depth===0)return!1;let o=a.before(1),s=e.doc.slice(r,i).content,c=e.doc.slice(o,r).content;if(!t)return!0;let l=e.tr;l.replaceWith(o,i,s.append(c));let u=o+1,d=o+s.size,f=e.selection.from-r,p=Math.min(u+f,d);return l.setSelection(H.near(l.doc.resolve(p))),l.scrollIntoView(),t(l),!0}function jg(e,t){let n=kg(e);if(!n)return!1;let{from:r,to:i}=n;if(i>=e.doc.content.size)return!1;let a=e.doc.resolve(i+1);if(a.depth===0)return!1;let o=a.after(1),s=e.doc.slice(r,i).content,c=e.doc.slice(i,o).content;if(!t)return!0;let l=e.tr;l.replaceWith(r,o,c.append(s));let u=r+c.size+1,d=r+c.size+s.size,f=e.selection.from-r,p=Math.min(u+f,d);return l.setSelection(H.near(l.doc.resolve(p))),l.scrollIntoView(),t(l),!0}var Mg=fe.create({name:`blockMover`,addKeyboardShortcuts(){return{"Mod-Shift-ArrowUp":({editor:e})=>Ag(e.state,e.view.dispatch),"Mod-Shift-ArrowDown":({editor:e})=>jg(e.state,e.view.dispatch)}}});function Ng(e){return!!e.getMeta(gd)}function Pg(e,t){let n=gd.getState(e);return rf(n.doc,n.type,t,n.binding.mapping)||0}function Fg(e,t){let n=gd.getState(e);return tf(t,n.type,n.binding.mapping)}var Ig=class e extends he{constructor(e,t){super(e),this.yRelativePosition=t}static fromJSON(t){return new e(t.position,t.yRelativePosition)}toJSON(){return{position:this.position,yRelativePosition:this.yRelativePosition}}};function Lg(e,t){return new Ig(e,Fg(t,e))}function Rg(e,t,n){let r=e instanceof Ig?e.yRelativePosition:null;if(Ng(t)&&r)return{position:new Ig(Pg(n,r),r),mapResult:null};let i=ce(e,t),a=i.position.position;return{position:new Ig(a,r??Fg(n,a)),mapResult:i.mapResult}}var zg=fe.create({name:`collaboration`,priority:1e3,addOptions(){return{document:null,field:`default`,fragment:null,provider:null}},addStorage(){return{isDisabled:!1}},onCreate(){this.editor.extensionManager.extensions.find(e=>e.name===`undoRedo`)&&console.warn(`[tiptap warn]: "@tiptap/extension-collaboration" comes with its own history support and is not compatible with "@tiptap/extension-undo-redo".`)},onBeforeCreate(){this.editor.utils.getUpdatedPosition=(e,t)=>Rg(e,t,this.editor.state),this.editor.utils.createMappablePosition=e=>Lg(e,this.editor.state)},addCommands(){return{undo:()=>({tr:e,state:t,dispatch:n})=>(e.setMeta(`preventDispatch`,!0),_d.getState(t).undoManager.undoStack.length===0?!1:n?df(t):!0),redo:()=>({tr:e,state:t,dispatch:n})=>(e.setMeta(`preventDispatch`,!0),_d.getState(t).undoManager.redoStack.length===0?!1:n?ff(t):!0)}},addKeyboardShortcuts(){return{"Mod-z":()=>this.editor.commands.undo(),"Mod-y":()=>this.editor.commands.redo(),"Shift-Mod-z":()=>this.editor.commands.redo()}},addProseMirrorPlugins(){let e=this.options.fragment?this.options.fragment:this.options.document.getXmlFragment(this.options.field),t=hf(this.options.yUndoOptions),n=t.spec.view;return t.spec.view=e=>{let{undoManager:t}=_d.getState(e.state);t.restore&&=(t.restore(),()=>{});let r=n?n(e):void 0;return{destroy:()=>{let e=t.trackedOrigins.has(t),n=t._observers;t.restore=()=>{e&&t.trackedOrigins.add(t),t.doc.on(`afterTransaction`,t.afterTransactionHandler),t._observers=n},r?.destroy&&r.destroy()}}},[wd(e,{...this.options.ySyncOptions,onFirstRender:this.options.onFirstRender}),t,this.editor.options.enableContentCheck&&new E({key:new be(`filterInvalidContent`),filterTransaction:t=>{if(!Ng(t))return!0;if(this.storage.isDisabled)return!1;if(!t.docChanged)return!0;try{return t.doc.check(),!0}catch(t){return this.storage.isDisabled=!0,this.editor.emit(`contentError`,{error:t,editor:this.editor,disableCollaboration:()=>{var t;(t=e.doc)==null||t.destroy()}}),!1}}})].filter(Boolean)}});function Bg(e){if(!e.length)return A.empty;let t=[],n=e[0].$from.node(0);return e.forEach(e=>{let n=e.$from.pos,r=e.$from.nodeAfter;r&&t.push(j.node(n,n+r.nodeSize,{class:`ProseMirror-selectednoderange`}))}),A.create(n,t)}function Vg(e,t,n){let r=n.isText||n.isAtom?0:1;return{start:e+r,end:e+t-r}}function Hg(e,t,n,r={}){let i=[],a=e.node(0),{extendOnBoundaryOverlap:o=!0}=r;typeof n==`number`&&n>=0||(n=e.sameParent(t)?Math.max(0,e.sharedDepth(t.pos)-1):e.sharedDepth(t.pos));let s=new I(e,t,n),c=s.depth===0?0:a.resolve(s.start).posAtIndex(0);return s.parent.forEach((n,r)=>{let l=c+r,u=l+n.nodeSize,d=Vg(l,n.nodeSize,n),f=o?t.pos>=d.start&&e.pos<=d.end:t.pos>d.start&&e.pos<d.end;if(l<s.start||l>=s.end||!f)return;let p=new z(a.resolve(l),a.resolve(u));i.push(p)}),i}var Ug=class e{constructor(e,t){this.anchor=e,this.head=t}map(t){return new e(t.map(this.anchor),t.map(this.head))}resolve(e){return new Wg(e.resolve(this.anchor),e.resolve(this.head))}},Wg=class e extends L{constructor(e,t,n,r=1){let{doc:i}=e,a=e===t,o=e.pos===i.content.size&&t.pos===i.content.size,s=a&&!o?i.resolve(t.pos+(r>0?1:-1)):t,c=a&&o?i.resolve(e.pos-(r>0?1:-1)):e,l=Hg(c.min(s),c.max(s),n),u=s.pos>=e.pos?l[0].$from:l[l.length-1].$to,d=s.pos>=e.pos?l[l.length-1].$to:l[0].$from;super(u,d,l),this.depth=n}get $to(){return this.ranges[this.ranges.length-1].$to}eq(t){return t instanceof e&&t.$from.pos===this.$from.pos&&t.$to.pos===this.$to.pos}map(t,n){return new e(t.resolve(n.map(this.anchor)),t.resolve(n.map(this.head)))}toJSON(){return{type:`nodeRange`,anchor:this.anchor,head:this.head}}get isForwards(){return this.head>=this.anchor}get isBackwards(){return!this.isForwards}extendBackwards(){let{doc:t}=this.$from;if(this.isForwards&&this.ranges.length>1){let t=this.ranges.slice(0,-1),n=t[0].$from,r=t[t.length-1].$to;return new e(n,r,this.depth)}let n=this.ranges[0],r=t.resolve(Math.max(0,n.$from.pos-1));return new e(this.$anchor,r,this.depth)}extendForwards(){let{doc:t}=this.$from;if(this.isBackwards&&this.ranges.length>1){let t=this.ranges.slice(1),n=t[0].$from,r=t[t.length-1].$to;return new e(r,n,this.depth)}let n=this.ranges[this.ranges.length-1],r=t.resolve(Math.min(t.content.size,n.$to.pos+1));return new e(this.$anchor,r,this.depth)}static fromJSON(t,n){return new e(t.resolve(n.anchor),t.resolve(n.head))}static create(e,t,n,r,i=1){return new this(e.resolve(t),e.resolve(n),r,i)}getBookmark(){return new Ug(this.anchor,this.head)}};Wg.prototype.visible=!1;function Gg(e){return e instanceof Wg}fe.create({name:`nodeRange`,addOptions(){return{depth:void 0,key:`Mod`}},addKeyboardShortcuts(){return{"Shift-ArrowUp":({editor:e})=>{let{depth:t}=this.options,{view:n,state:r}=e,{doc:i,selection:a,tr:o}=r,{anchor:s,head:c}=a;if(!Gg(a)){let e=Wg.create(i,s,c,t,-1);return o.setSelection(e),n.dispatch(o),!0}let l=a.extendBackwards();return o.setSelection(l),n.dispatch(o),!0},"Shift-ArrowDown":({editor:e})=>{let{depth:t}=this.options,{view:n,state:r}=e,{doc:i,selection:a,tr:o}=r,{anchor:s,head:c}=a;if(!Gg(a)){let e=Wg.create(i,s,c,t);return o.setSelection(e),n.dispatch(o),!0}let l=a.extendForwards();return o.setSelection(l),n.dispatch(o),!0},"Mod-a":({editor:e})=>{let{depth:t}=this.options,{view:n,state:r}=e,{doc:i,tr:a}=r,o=Wg.create(i,0,i.content.size,t);return a.setSelection(o),n.dispatch(a),!0}}},onSelectionUpdate(){let{selection:e}=this.editor.state;Gg(e)&&this.editor.view.dom.classList.add(`ProseMirror-noderangeselection`)},addProseMirrorPlugins(){let e=!1,t=!1;return[new E({key:new be(`nodeRange`),props:{attributes:()=>e?{class:`ProseMirror-noderangeselection`}:{class:``},handleDOMEvents:{mousedown:(e,n)=>{let{key:r}=this.options,i=/Mac/.test(navigator.platform),a=!!n.shiftKey,o=!!n.ctrlKey,s=!!n.altKey,c=!!n.metaKey;return(r==null||r===`Shift`&&a||r===`Control`&&o||r===`Alt`&&s||r===`Meta`&&c||r===`Mod`&&(i?c:o))&&(t=!0),t&&document.addEventListener(`mouseup`,()=>{t=!1;let{state:n}=e,{doc:r,selection:i,tr:a}=n,{$anchor:o,$head:s}=i;if(o.sameParent(s))return;let c=Wg.create(r,o.pos,s.pos,this.options.depth);a.setSelection(c),e.dispatch(a)},{once:!0}),!1}},decorations:n=>{let{selection:r}=n,i=Gg(r);if(e=!1,!t)return i?(e=!0,Bg(r.ranges)):null;let{$from:a,$to:o}=r;if(!i&&a.sameParent(o))return null;let s=Hg(a,o,this.options.depth);return s.length?(e=!0,Bg(s)):null}}})]}});function Kg(e){let t=``,n=getComputedStyle(e);for(let e=0;e<n.length;e+=1)t+=`${n[e]}:${n.getPropertyValue(n[e])};`;return t}function qg(e){let t=e.cloneNode(!0),n=[e,...Array.from(e.getElementsByTagName(`*`))],r=[t,...Array.from(t.getElementsByTagName(`*`))];return n.forEach((e,t)=>{r[t].style.cssText=Kg(e)}),t}var Jg=[{id:`listItemFirstChild`,evaluate:({parent:e,isFirst:t})=>t&&e&&[`listItem`,`taskItem`].includes(e.type.name)?1e3:0},{id:`listWrapperDeprioritize`,evaluate:({node:e})=>{let t=[`listItem`,`taskItem`],n=e.firstChild;return n&&t.includes(n.type.name)?1e3:0}},{id:`tableStructure`,evaluate:({node:e,parent:t})=>[`tableRow`,`tableCell`,`tableHeader`].includes(e.type.name)||t&&t.type.name===`tableHeader`?1e3:0},{id:`inlineContent`,evaluate:({node:e})=>e.isInline||e.isText?1e3:0}],Yg={edges:[`left`,`top`],threshold:12,strength:500};function Xg(e){return e===void 0||e===`left`?{...Yg}:e===`right`?{edges:[`right`,`top`],threshold:12,strength:500}:e===`both`?{edges:[`left`,`right`,`top`],threshold:12,strength:500}:e===`none`?{edges:[],threshold:0,strength:0}:{...Yg,...e}}function Zg(e,t,n){if(n.edges.length===0)return!1;let r=t.getBoundingClientRect(),{threshold:i,edges:a}=n;return a.some(t=>t===`left`?e.x-r.left<i:t===`right`?r.right-e.x<i:t===`top`?e.y-r.top<i:t===`bottom`?r.bottom-e.y<i:!1)}function Qg(e,t,n,r){return!t||n.edges.length===0?0:Zg(e,t,n)?n.strength*r:0}var $g=1e3;function e_(e,t,n,r){let i=$g,a=!1;if(t.every(t=>{let n=t.evaluate(e);return i-=n,i<=0?(a=!0,!1):!0}),a)return-1;let o=e.view.nodeDOM(e.pos);return i-=Qg(r,o,n,e.depth),i<=0?-1:i}function t_(e,t,n){return Array.from({length:t},(e,n)=>t-1-n).some(t=>n.includes(e.node(t).type.name))}function n_(e,t,n){if(!Number.isFinite(t.x)||!Number.isFinite(t.y))return null;let r=e.posAtCoords({left:t.x,top:t.y});if(!r)return null;let{doc:i}=e.state,a=i.resolve(r.pos),o=[];n.defaultRules&&o.push(...Jg),o.push(...n.rules);let s=Array.from({length:a.depth},(e,t)=>a.depth-t).map(r=>{let i=a.node(r),s=a.before(r);if(n.allowedContainers&&r>0&&!t_(a,r,n.allowedContainers))return null;let c=r>0?a.node(r-1):null,l=r>0?a.index(r-1):0,u=c?c.childCount:1,d=e_({node:i,pos:s,depth:r,parent:c,index:l,isFirst:l===0,isLast:l===u-1,$pos:a,view:e},o,n.edgeDetection,t);return d<0?null:{node:i,pos:s,depth:r,score:d,dom:e.nodeDOM(s)}}).filter(e=>e!==null),c=a.nodeAfter;if(c&&c.isAtom&&!c.isInline){let i=r.pos,l=a.depth+1,u=a.parent,d=a.index(),f=u.childCount,p=!0;if(n.allowedContainers&&(p=t_(a,l,n.allowedContainers)),p){let r=e_({node:c,pos:i,depth:l,parent:u,index:d,isFirst:d===0,isLast:d===f-1,$pos:a,view:e},o,n.edgeDetection,t);if(r>=0){let t=e.nodeDOM(i);t&&s.push({node:c,pos:i,depth:l,score:r,dom:t})}}}if(s.length===0)return null;s.sort((e,t)=>t.score===e.score?t.depth-e.depth:t.score-e.score);let l=s[0];return l.dom?{node:l.node,pos:l.pos,dom:l.dom}:null}function r_(e,t){let n=e;for(;n?.parentElement&&n.parentElement!==t.dom;)n=n.parentElement;return n?.parentElement===t.dom?n:void 0}function i_(e){return Number.isFinite(e.top)&&Number.isFinite(e.bottom)&&Number.isFinite(e.left)&&Number.isFinite(e.right)&&e.width>0&&e.height>0}function a_(e,t,n,r=5){if(!Number.isFinite(t)||!Number.isFinite(n))return null;let i=e.dom,a=i.firstElementChild,o=i.lastElementChild;if(!a||!o)return null;let s=a.getBoundingClientRect(),c=o.getBoundingClientRect();if(!i_(s)||!i_(c))return null;let l=Math.min(Math.max(s.top+r,n),c.bottom-r),u=.5,d=Math.abs(s.left-c.left)<u,f=Math.abs(s.right-c.right)<u,p=s;d&&f&&(p=s);let m=Math.min(Math.max(p.left+r,t),p.right-r);return!Number.isFinite(m)||!Number.isFinite(l)?null:{x:m,y:l}}var o_=e=>{let{x:t,y:n,editor:r,nestedOptions:i}=e,{view:a,state:o}=r,s=a_(a,t,n,5);if(!s)return{resultElement:null,resultNode:null,pos:null};let{x:c,y:l}=s;if(i?.enabled){let e=n_(a,{x:c,y:l},i);return e?{resultElement:e.dom,resultNode:e.node,pos:e.pos}:{resultElement:null,resultNode:null,pos:null}}let u=a.root.elementsFromPoint(c,l),d;if(Array.prototype.some.call(u,e=>{if(!a.dom.contains(e))return!1;let t=r_(e,a);return t?(d=t,!0):!1}),!d){let e=a.posAtCoords({left:c,top:l});if(e){let t=o.doc.resolve(e.pos),n=Math.min(t.depth,1),r=n>0?t.before(n):t.pos,i=o.doc.nodeAt(r);if(i){let e=a.nodeDOM(r);return{resultElement:e instanceof HTMLElement?e:null,resultNode:i,pos:r}}}return{resultElement:null,resultNode:null,pos:null}}let f;try{f=a.posAtDOM(d,0)}catch{return{resultElement:null,resultNode:null,pos:null}}let p=o.doc.nodeAt(f);if(!p){let e=o.doc.resolve(f),t=e.parent;return{resultElement:d,resultNode:t,pos:e.start()}}return{resultElement:d,resultNode:p,pos:f}};function s_(e,t){let n=null,r=e.nodeDOM(t);if(r instanceof Element)n=r;else{let{node:r,offset:i}=e.domAtPos(t),a=r.childNodes[i];a instanceof Element?n=a:r instanceof Element?n=r:r.nodeType===Node.TEXT_NODE&&r.parentElement&&(n=r.parentElement)}return(n?getComputedStyle(n).direction:getComputedStyle(e.dom).direction)||`ltr`}function c_(e){var t;(t=e.parentNode)==null||t.removeChild(e)}function l_(e,t,n,r){let{doc:i}=t.view.state;if(n?.enabled&&r?.node&&r.pos>=0){let e=r.pos,t=r.pos+r.node.nodeSize;return[{$from:i.resolve(e),$to:i.resolve(t)}]}let a=o_({editor:t,x:e.clientX,y:e.clientY,direction:`right`,nestedOptions:n});if(!a.resultNode||a.pos===null)return[];let o=a.resultNode.isText||a.resultNode.isAtom?0:-1;return Hg(i.resolve(a.pos),i.resolve(a.pos+a.resultNode.nodeSize+o),0,{extendOnBoundaryOverlap:!1})}function u_(e,t,n,r){let{view:i}=t;if(!e.dataTransfer)return;let{empty:a,$from:o,$to:s}=i.state.selection,c=l_(e,t,n,r),l=Hg(o,s,0,{extendOnBoundaryOverlap:!1}),u=l.some(e=>c.find(t=>t.$from===e.$from&&t.$to===e.$to)),d=a||!u?c:l;if(!d.length)return;let{tr:f}=i.state,p=document.createElement(`div`),m=d[0].$from.pos,h=d[d.length-1].$to.pos;p.setAttribute(`dir`,s_(i,m));let g=n?.enabled&&r?.node,_,v;g?(_=i.state.doc.slice(m,h),v=xe.create(i.state.doc,m)):(v=Wg.create(i.state.doc,m,h),_=v.content()),d.forEach(e=>{let t=qg(i.nodeDOM(e.$from.pos));p.append(t)}),p.style.position=`absolute`,p.style.top=`-10000px`,document.body.append(p),e.dataTransfer.clearData();let y=p.getBoundingClientRect(),b=e.clientX-y.left;e.dataTransfer.setDragImage(p,Math.max(0,Math.min(b,y.width)),0);let x=!1,S=()=>{x||(x=!0,c_(p),document.removeEventListener(`drop`,S),document.removeEventListener(`dragend`,S))},C=v instanceof xe?v:void 0;i.dragging={slice:_,move:!0,node:C},f.setSelection(v),i.dispatch(f),document.addEventListener(`drop`,S),document.addEventListener(`dragend`,S)}var d_=(e,t)=>{let n=e.resolve(t),{depth:r}=n;return r===0?t:n.pos-n.parentOffset-1},f_=(e,t)=>{let n=e.nodeAt(t),r=e.resolve(t),{depth:i}=r,a=n;for(;i>0;){let e=r.node(i);--i,i===0&&(a=e)}return a},p_=(e,t)=>{let n=gd.getState(e);return n?tf(t,n.type,n.binding.mapping):null},m_=(e,t)=>{let n=gd.getState(e);return n?rf(n.doc,n.type,t,n.binding.mapping)||0:-1},h_=(e,t)=>{let n=t;for(;n?.parentNode&&n.parentNode!==e.dom;)n=n.parentNode;return n},g_=new be(`dragHandle`),__=({pluginKey:e=g_,element:t,editor:n,computePositionConfig:r,getReferencedVirtualElement:i,onNodeChange:a,onElementDragStart:o,onElementDragEnd:s,nestedOptions:c})=>{let l=document.createElement(`div`),u=!1,d=null,f=-1,p,m=null,h=null;function g(){t&&(t.style.visibility=`hidden`,t.style.pointerEvents=`none`)}function _(){if(t){if(!n.isEditable){g();return}t.style.visibility=``,t.style.pointerEvents=`auto`}}function v(e){N(i?.()||{getBoundingClientRect:()=>e.getBoundingClientRect()},t,r).then(e=>{Object.assign(t.style,{position:e.strategy,left:`${e.x}px`,top:`${e.y}px`})})}function y(e){o?.(e),u_(e,n,c,{node:d,pos:f}),t&&(t.dataset.dragging=`true`),setTimeout(()=>{t&&(t.style.pointerEvents=`none`)},0)}function b(e){s?.(e),g(),t&&(t.style.pointerEvents=`auto`,t.dataset.dragging=`false`)}function x(){if(Ie()){let e=n.view.dom;requestAnimationFrame(()=>{e.isContentEditable&&(e.contentEditable=`false`,e.contentEditable=`true`)})}}return l.appendChild(t),{unbind(){t.removeEventListener(`dragstart`,y),t.removeEventListener(`dragend`,b),document.removeEventListener(`drop`,x),m&&(cancelAnimationFrame(m),m=null,h=null)},plugin:new E({key:typeof e==`string`?new be(e):e,state:{init(){return{locked:!1}},apply(e,r,i,o){let s=e.getMeta(`lockDragHandle`),c=e.getMeta(`hideDragHandle`);if(s!==void 0&&(u=s),c)return g(),u=!1,d=null,f=-1,a?.({editor:n,node:null,pos:-1}),r;if(e.docChanged&&f!==-1&&t)if(Ng(e)){let e=m_(o,p);e!==f&&(f=e)}else{let t=e.mapping.map(f);t!==f&&(f=t,p=p_(o,f))}return r}},view:e=>{var r;return t.draggable=!0,t.style.pointerEvents=`auto`,t.dataset.dragging=`false`,(r=n.view.dom.parentElement)==null||r.appendChild(l),l.style.pointerEvents=`none`,l.style.position=`absolute`,l.style.top=`0`,l.style.left=`0`,t.addEventListener(`dragstart`,y),t.addEventListener(`dragend`,b),document.addEventListener(`drop`,x),{update(r,i){if(!t)return;if(!n.isEditable){g();return}if(u?t.draggable=!1:t.draggable=!0,e.state.doc.eq(i.doc)||f===-1)return;let o=e.nodeDOM(f);if(o=h_(e,o),o===e.dom||o?.nodeType!==1)return;let s=e.posAtDOM(o,0),c=f_(n.state.doc,s),l=d_(n.state.doc,s);d=c,f=l,p=p_(e.state,f),a?.({editor:n,node:d,pos:f}),v(o)},destroy(){t.removeEventListener(`dragstart`,y),t.removeEventListener(`dragend`,b),document.removeEventListener(`drop`,x),m&&(cancelAnimationFrame(m),m=null,h=null),t&&c_(l)}}},props:{handleDOMEvents:{keydown(e){return!t||u?!1:e.hasFocus()?(g(),d=null,f=-1,a?.({editor:n,node:null,pos:-1}),!1):!1},mouseleave(e,t){return u||t.target&&!l.contains(t.relatedTarget)&&(g(),d=null,f=-1,a?.({editor:n,node:null,pos:-1})),!1},mousemove(e,r){return!t||u||(h={x:r.clientX,y:r.clientY},m)||(m=requestAnimationFrame(()=>{if(m=null,!h)return;let{x:t,y:r}=h;h=null;let i=o_({x:t,y:r,direction:`right`,editor:n,nestedOptions:c});if(!i.resultElement)return;let o=i.resultElement,s=i.resultNode,l=i.pos;if(!c?.enabled){if(o=h_(e,o),o===e.dom||o?.nodeType!==1)return;let t=e.posAtDOM(o,0);s=f_(n.state.doc,t),l=d_(n.state.doc,t)}s!==d&&(d=s,f=l??-1,p=p_(e.state,f),a?.({editor:n,node:d,pos:f}),v(o),_())})),!1}}}})}};function v_(e){return e===!1||e===void 0?{enabled:!1,rules:[],defaultRules:!0,allowedContainers:void 0,edgeDetection:Xg(`none`)}:e===!0?{enabled:!0,rules:[],defaultRules:!0,allowedContainers:void 0,edgeDetection:Xg(`left`)}:{enabled:!0,rules:e.rules??[],defaultRules:e.defaultRules??!0,allowedContainers:e.allowedContainers,edgeDetection:Xg(e.edgeDetection)}}var y_={placement:`left-start`,strategy:`absolute`};fe.create({name:`dragHandle`,addOptions(){return{render(){let e=document.createElement(`div`);return e.classList.add(`drag-handle`),e},computePositionConfig:{},locked:!1,onNodeChange:()=>null,onElementDragStart:void 0,onElementDragEnd:void 0,nested:!1}},addCommands(){return{lockDragHandle:()=>({editor:e})=>(this.options.locked=!0,e.commands.setMeta(`lockDragHandle`,this.options.locked)),unlockDragHandle:()=>({editor:e})=>(this.options.locked=!1,e.commands.setMeta(`lockDragHandle`,this.options.locked)),toggleDragHandle:()=>({editor:e})=>(this.options.locked=!this.options.locked,e.commands.setMeta(`lockDragHandle`,this.options.locked))}},addProseMirrorPlugins(){let e=this.options.render(),t=v_(this.options.nested);return[__({computePositionConfig:{...y_,...this.options.computePositionConfig},getReferencedVirtualElement:this.options.getReferencedVirtualElement,element:e,editor:this.editor,onNodeChange:this.options.onNodeChange,onElementDragStart:this.options.onElementDragStart,onElementDragEnd:this.options.onElementDragEnd,nestedOptions:t}).plugin]}});var b_=20,x_=44,S_=28;function C_(){let e=document.createElement(`div`);e.className=`ok-block-controls`,e.style.visibility=`hidden`;let t=document.createElement(`button`);t.className=`ok-add-block-btn`,t.setAttribute(`aria-label`,`Add block below`),t.setAttribute(`type`,`button`),t.innerHTML=`<svg aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-plus"><path d="M5 12h14"/><path d="M12 5v14"/></svg>`,t.addEventListener(`mousedown`,e=>{e.preventDefault(),e.stopPropagation()});let n=document.createElement(`div`);return n.className=`ok-drag-grip`,n.setAttribute(`aria-hidden`,`true`),n.innerHTML=`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-grip-vertical-icon lucide-grip-vertical"><circle cx="9" cy="12" r="1"/><circle cx="9" cy="5" r="1"/><circle cx="9" cy="19" r="1"/><circle cx="15" cy="12" r="1"/><circle cx="15" cy="5" r="1"/><circle cx="15" cy="19" r="1"/></svg>`,e.appendChild(t),e.appendChild(n),{container:e,addBtn:t}}function w_(e,t,n){let{state:r,view:i}=e,a=t+n.nodeSize;if(a>r.doc.content.size)return;let{tr:o}=r,s=r.schema.nodes.paragraph?.create();if(!s)return;o.insert(a,s);let c=H.near(o.doc.resolve(a+1));o.setSelection(c).scrollIntoView(),i.dispatch(o),i.focus(),e.commands.insertContent(`/`)}var T_=fe.create({name:`blockDragHandle`,addProseMirrorPlugins(){let e=this.editor,t=null,n=-1,{container:r,addBtn:i}=C_();return i.addEventListener(`click`,()=>{t&&n>=0&&w_(e,n,t)}),[__({element:r,editor:e,onNodeChange({node:e,pos:r}){t=e,n=r??-1},computePositionConfig:{placement:`left-start`,strategy:`absolute`,middleware:[je(({rects:e})=>({mainAxis:10,crossAxis:((e.reference.height<=x_?e.reference.height:S_)-b_)/2}))]},nestedOptions:v_(!1)}).plugin]}});function E_(e){let t=e.trim();if(!t)return null;let n=T(t);return n?{target:n,alias:n===t?null:t,anchor:null}:null}function D_(e){let t=e.trim();if(!t)return[];let n=T(t);return n.length>0&&n!==t?[n]:[]}function O_(e,t){let n=e.trim();return n?t.has(n)?!0:D_(n).some(e=>t.has(e)):!1}var k_=fe.create({name:`headingAnchors`,addProseMirrorPlugins(){return[new E({props:{decorations(e){let t=[],n=new Map;return e.doc.descendants((e,r)=>{if(e.type.name===`heading`){let i=D(e.textContent,n);if(!i)return;t.push(j.node(r,r+e.nodeSize,{id:i}))}}),A.create(e.doc,t)}}})]}}),A_=new Set([`http:`,`https:`,`mailto:`,`tel:`]);function j_(e){try{let t=new URL(e);return A_.has(t.protocol)}catch{return!1}}function M_(e=window.location.hash){let t=e.match(/^#\/([^?#]+)/);return t?decodeURIComponent(t[1]):``}function N_(e,t=window.location.hash){return R(e,M_(t))}function P_({docName:e,anchor:t}){return t?`#/${e}?anchor=${encodeURIComponent(t)}`:`#/${e}`}function F_(e){e.startsWith(`#`)||j_(e)?window.open(e,`_blank`,`noopener,noreferrer`):console.warn(`[safe-nav] blocked non-safe scheme:`,e)}function I_(e){window.location.assign(P_(e))}function L_(e){F_(P_(e))}function R_(e){return e.metaKey||e.ctrlKey}function z_(e,t=window.location.hash){let n=M_(t);if(!n)return;let r=document.getElementById(e);r&&r.scrollIntoView({behavior:`smooth`,block:`start`}),window.location.assign(le(n,e))}function B_(e,t=window.location.hash){if(e.kind===`doc`){I_(e);return}if(e.kind===`anchor`){z_(e.anchor,t);return}F_(e.url)}function V_(e,t,n=window.location.hash){return ye(M_(n),e,t)}var H_=e=>{let t=(0,at.c)(13),{kind:n,ariaLabel:r,onDeactivate:i,children:a,layout:o,className:s,"data-slot":u}=e,d=(o===void 0?`standard`:o)===`wide`?`w-[min(720px,calc(100%-1rem))]`:`w-80`,f;t[0]!==s||t[1]!==d?(f=c(`ok-interaction-prop-panel pointer-events-auto absolute left-1/2 top-2 z-40 -translate-x-1/2 rounded-md border border-border bg-popover p-3 shadow-lg`,d,s),t[0]=s,t[1]=d,t[2]=f):f=t[2];let p;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(p=(0,X.jsx)(w,{className:`size-3.5`,"aria-hidden":`true`}),t[3]=p):p=t[3];let m;t[4]===i?m=t[5]:(m=(0,X.jsx)(l,{type:`button`,variant:`ghost`,size:`icon`,"aria-label":`Close`,onClick:i,className:`absolute right-1 top-1 size-7`,children:p}),t[4]=i,t[5]=m);let h;return t[6]!==r||t[7]!==a||t[8]!==u||t[9]!==n||t[10]!==f||t[11]!==m?(h=(0,X.jsxs)(`div`,{role:`dialog`,"aria-label":r,"data-ok-prop-panel":n,"data-slot":u,className:f,children:[a,m]}),t[6]=r,t[7]=a,t[8]=u,t[9]=n,t[10]=f,t[11]=m,t[12]=h):h=t[12],h};function U_(e,t){let n=[e,...t.fallbackTargets??[]],r=new Set,i=null;for(let e of n){if(r.has(e))continue;r.add(e);let n=Oe(e,{pages:t.pages,folderPaths:t.folderPaths});if(n.kind===`missing`){i??=n;continue}return{kind:`navigate`,displayState:n.kind===`folder`?`folder`:`resolved`,resolvedTarget:n,hashDocName:n.target}}let a=i??Oe(e,{pages:t.pages,folderPaths:t.folderPaths});if(a.kind!==`missing`)return{kind:`navigate`,displayState:a.kind===`folder`?`folder`:`resolved`,resolvedTarget:a,hashDocName:a.target};let o=t.createDialogSeed??ue(a.target);return{kind:`create`,displayState:`missing`,resolvedTarget:a,initialDir:o.initialDir,suggestedName:o.suggestedName}}function W_(e){if(e.kind!==`navigate`||e.displayState!==`folder`)return null;let t=e.resolvedTarget;return`folderPath`in t?{initialDir:t.folderPath,suggestedName:`index.md`}:null}function G_(e){let t=(0,at.c)(10),n,r,i;t[0]===e?(n=t[1],r=t[2],i=t[3]):({className:n,type:i,...r}=e,t[0]=e,t[1]=n,t[2]=r,t[3]=i);let a;t[4]===n?a=t[5]:(a=c(`h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40`,n),t[4]=n,t[5]=a);let o;return t[6]!==r||t[7]!==a||t[8]!==i?(o=(0,X.jsx)(`input`,{type:i,"data-slot":`input`,className:a,...r}),t[6]=r,t[7]=a,t[8]=i,t[9]=o):o=t[9],o}function K_(e){return e.trim()?e.includes(`..`)?`Path cannot contain ".."`:e.startsWith(`/`)?`Path cannot start with "/"`:e.includes(`\\`)?`Path cannot contain backslashes`:e.includes(`\0`)?`Path cannot contain null bytes`:null:`Name cannot be empty`}function q_(e){return e.endsWith(`.md`)?e:`${e}.md`}function J_(e){let t=q_(e.fileName.trim());if(e.kind===`folder`){let n=(e.folderName??``).trim();return`${e.initialDir?`${e.initialDir}/${n}`:n}/${t}`}return e.initialDir?`${e.initialDir}/${t}`:t}function Y_(e){let t=e.target;return t?.tagName===`INPUT`||t?.tagName===`TEXTAREA`||t?.isContentEditable?!1:!!((e.metaKey||e.ctrlKey)&&e.altKey&&e.key.toLowerCase()===`n`)}function X_(e){let t=e.value.lastIndexOf(`.`);t>0?e.setSelectionRange(0,t):e.select()}function Z_(e){let t=(0,at.c)(87),{open:n,onOpenChange:r,kind:i,initialDir:a,suggestedName:o,description:s,onCreated:c}=e,{addPage:u}=Te(),[f,p]=(0,J.useState)(``),[m,g]=(0,J.useState)(``),[_,y]=(0,J.useState)(null),[C,w]=(0,J.useState)(!1),[T,E]=(0,J.useState)(null),D=(0,J.useId)(),O=(0,J.useId)(),k=(0,J.useId)(),A=(0,J.useRef)(null),ee=(0,J.useRef)(null),j,M;t[0]!==i||t[1]!==n||t[2]!==o?(j=()=>{n&&(y(null),E(null),w(!1),g(``),p(i===`file`?o??`untitled.md`:`index.md`))},M=[n,i,o],t[0]=i,t[1]=n,t[2]=o,t[3]=j,t[4]=M):(j=t[3],M=t[4]),(0,J.useEffect)(j,M);let N;t[5]!==f||t[6]!==m||t[7]!==a||t[8]!==i?(N=function(){return J_({kind:i,initialDir:a,fileName:f,folderName:m})},t[5]=f,t[6]=m,t[7]=a,t[8]=i,t[9]=N):N=t[9];let P=N,F;t[10]!==f||t[11]!==m||t[12]!==i?(F=function(){if(i===`folder`){let e=K_(m.trim());if(e)return{message:`Folder name: ${e}`,field:`folder`}}let e=K_(f.trim());return e?{message:e,field:`file`}:null},t[10]=f,t[11]=m,t[12]=i,t[13]=F):F=t[13];let I=F,L;t[14]!==C||t[15]!==f||t[16]!==m||t[17]!==i?(L=C||!f.trim()||i===`folder`&&!m.trim(),t[14]=C,t[15]=f,t[16]=m,t[17]=i,t[18]=L):L=t[18];let R=L,z;t[19]!==u||t[20]!==P||t[21]!==I||t[22]!==i||t[23]!==c||t[24]!==r?(z=async function(){let e=I();if(e){y(e.message),E(e.field);return}w(!0),y(null),E(null);let t=P();try{let e=await fetch(`/api/create-page`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:t})});if(!e.ok){let t=`Server error (HTTP ${e.status})`;try{let n=await e.json();n?.error&&(t=n.error)}catch{}w(!1),y(t),E(`form`);return}let n=await e.json();if(w(!1),!n.ok){y(n.error??`Failed to create ${i}`),E(`form`);return}let a=n.docName??t.replace(/\.md$/,``);r(!1),window.location.hash=`#/${a}`,u(a),Me([`files`,`backlinks`,`graph`]),c?.(a)}catch(e){console.warn(`[NewItemDialog] create failed:`,e),w(!1),y(`Network error — please try again`),E(`form`)}},t[19]=u,t[20]=P,t[21]=I,t[22]=i,t[23]=c,t[24]=r,t[25]=z):z=t[25];let B=z,V=a||`(root)`,H=i===`file`?`New file`:`New folder`,U;t[26]===H?U=t[27]:(U=(0,X.jsx)(x,{children:H}),t[26]=H,t[27]=U);let W;t[28]!==s||t[29]!==V?(W=s??(0,X.jsxs)(X.Fragment,{children:[`Create in `,(0,X.jsx)(`span`,{className:`font-medium text-foreground`,children:V})]}),t[28]=s,t[29]=V,t[30]=W):W=t[30];let G;t[31]===W?G=t[32]:(G=(0,X.jsx)(h,{children:W}),t[31]=W,t[32]=G);let K;t[33]!==U||t[34]!==G?(K=(0,X.jsxs)(v,{children:[U,G]}),t[33]=U,t[34]=G,t[35]=K):K=t[35];let q;t[36]!==_||t[37]!==T||t[38]!==D||t[39]!==O||t[40]!==m||t[41]!==i?(q=i===`folder`&&(0,X.jsxs)(`div`,{children:[(0,X.jsx)(`label`,{className:`mb-1.5 block text-sm font-medium`,htmlFor:O,children:`Folder name`}),(0,X.jsx)(G_,{ref:ee,id:O,value:m,onChange:e=>{g(e.target.value),y(null)},placeholder:`folder-name`,autoFocus:!0,"aria-describedby":_&&(T===`folder`||T===`form`)?D:void 0,"aria-invalid":_&&(T===`folder`||T===`form`)?!0:void 0,onKeyDown:e=>{if(e.key===`Enter`){e.preventDefault();let t=K_(m.trim());if(t){y(`Folder name: ${t}`),E(`folder`);return}A.current?.focus()}}})]}),t[36]=_,t[37]=T,t[38]=D,t[39]=O,t[40]=m,t[41]=i,t[42]=q):q=t[42];let te=i===`folder`?`First file name`:`File name`,ne;t[43]!==k||t[44]!==te?(ne=(0,X.jsx)(`label`,{className:`mb-1.5 block text-sm font-medium`,htmlFor:k,children:te}),t[43]=k,t[44]=te,t[45]=ne):ne=t[45];let re;t[46]===Symbol.for(`react.memo_cache_sentinel`)?(re=e=>{p(e.target.value),y(null)},t[46]=re):re=t[46];let ie=i===`file`,ae=_&&(T===`file`||T===`form`)?D:void 0,oe=_&&(T===`file`||T===`form`)?!0:void 0,se;t[47]!==B||t[48]!==R?(se=e=>{e.key===`Enter`&&!R&&B()},t[47]=B,t[48]=R,t[49]=se):se=t[49];let ce;t[50]!==k||t[51]!==f||t[52]!==ie||t[53]!==ae||t[54]!==oe||t[55]!==se?(ce=(0,X.jsx)(G_,{ref:A,id:k,value:f,onChange:re,placeholder:`my-note.md`,autoFocus:ie,"aria-describedby":ae,"aria-invalid":oe,onFocus:Q_,onKeyDown:se}),t[50]=k,t[51]=f,t[52]=ie,t[53]=ae,t[54]=oe,t[55]=se,t[56]=ce):ce=t[56];let le;t[57]!==ne||t[58]!==ce?(le=(0,X.jsxs)(`div`,{children:[ne,ce]}),t[57]=ne,t[58]=ce,t[59]=le):le=t[59];let ue;t[60]!==_||t[61]!==D?(ue=_&&(0,X.jsx)(`p`,{id:D,role:`alert`,className:`text-xs text-red-600 dark:text-red-400`,children:_}),t[60]=_,t[61]=D,t[62]=ue):ue=t[62];let de;t[63]!==q||t[64]!==le||t[65]!==ue?(de=(0,X.jsxs)(`div`,{className:`space-y-3`,children:[q,le,ue]}),t[63]=q,t[64]=le,t[65]=ue,t[66]=de):de=t[66];let fe;t[67]===r?fe=t[68]:(fe=()=>r(!1),t[67]=r,t[68]=fe);let pe;t[69]!==C||t[70]!==fe?(pe=(0,X.jsx)(l,{variant:`outline`,className:`font-mono uppercase`,onClick:fe,disabled:C,children:`Cancel`}),t[69]=C,t[70]=fe,t[71]=pe):pe=t[71];let me=C?`Creating...`:`Create`,he;t[72]!==B||t[73]!==R||t[74]!==me?(he=(0,X.jsx)(l,{onClick:B,disabled:R,children:me}),t[72]=B,t[73]=R,t[74]=me,t[75]=he):he=t[75];let ge;t[76]!==pe||t[77]!==he?(ge=(0,X.jsxs)(d,{children:[pe,he]}),t[76]=pe,t[77]=he,t[78]=ge):ge=t[78];let _e;t[79]!==K||t[80]!==de||t[81]!==ge?(_e=(0,X.jsxs)(b,{className:`sm:max-w-md`,"data-ok-layer-spawned":``,children:[K,de,ge]}),t[79]=K,t[80]=de,t[81]=ge,t[82]=_e):_e=t[82];let ve;return t[83]!==r||t[84]!==n||t[85]!==_e?(ve=(0,X.jsx)(S,{open:n,onOpenChange:r,children:_e}),t[83]=r,t[84]=n,t[85]=_e,t[86]=ve):ve=t[86],ve}function Q_(e){return X_(e.currentTarget)}var $_=class{registry=new Map;_activeNodeId=null;listeners=new Set;_snapshot={activeNodeId:null,active:null};register(e){this.registry.set(e.nodeId,e),this._activeNodeId===e.nodeId&&this.refreshSnapshot()}deregister(e){this.registry.delete(e)&&this._activeNodeId===e&&(this._activeNodeId=null,this.refreshSnapshot())}setActiveNode(e){this._activeNodeId!==e&&(e!==null&&!this.registry.has(e)||(this._activeNodeId=e,this.refreshSnapshot()))}getActiveNode(){return this._activeNodeId}getRegistration(e){return this.registry.get(e)}hasRegistration(e){return this.registry.has(e)}clear(){this.registry.clear(),this._activeNodeId=null,this.refreshSnapshot()}getSnapshot=()=>this._snapshot;subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});refreshSnapshot(){let e=this._activeNodeId==null?null:this.registry.get(this._activeNodeId)??null;this._snapshot={activeNodeId:this._activeNodeId,active:e};for(let e of this.listeners)e()}};function ev(e,t){let n=e??null;for(;n&&typeof n==`object`;){let e=n.getAttribute;if(typeof e==`function`){let r=e.call(n,`data-mark-id`);if(r&&t.hasRegistration(r))return r;let i=e.call(n,`data-node-id`);if(i&&t.hasRegistration(i))return i}n=n.parentElement??null}return null}var tv=e=>{let t=(0,at.c)(18),{store:n}=e,r;t[0]===n?r=t[1]:(r=()=>n.getSnapshot(),t[0]=n,t[1]=r);let[i,a]=(0,J.useState)(r),o,s;t[2]===n?(o=t[3],s=t[4]):(o=()=>(a(n.getSnapshot()),n.subscribe(()=>{a(n.getSnapshot())})),s=[n],t[2]=n,t[3]=o,t[4]=s),(0,J.useEffect)(o,s);let{active:c}=i;if(!c)return null;let l;t[5]===n?l=t[6]:(l=()=>n.setActiveNode(null),t[5]=n,t[6]=l);let u,d,f;if(t[7]!==c.controls||t[8]!==c.nodeId||t[9]!==c.type||t[10]!==l){let e={nodeId:c.nodeId,type:c.type,deactivate:l};u=c.controls.propPanel?.(e),d=c.controls.toolbar?.(e),f=c.controls.breadcrumb?.(e),t[7]=c.controls,t[8]=c.nodeId,t[9]=c.type,t[10]=l,t[11]=u,t[12]=d,t[13]=f}else u=t[11],d=t[12],f=t[13];let p;return t[14]!==u||t[15]!==d||t[16]!==f?(p=(0,X.jsxs)(X.Fragment,{children:[u,d,f]}),t[14]=u,t[15]=d,t[16]=f,t[17]=p):p=t[17],p};function nv(e){return e.editorView?.dom??e.view?.dom??null}function rv(e,t){let n=e;for(;n;){if(n.getAttribute?.(`data-mark-id`)===t||n.getAttribute?.(`data-node-id`)===t)return!0;n=n.parentElement}return!1}function iv(e){let{editor:t}=e,n=new $_,r=nv(t),i=!1,a=null,o=n.subscribe(()=>{let e=n.getActiveNode();if(e!==null){if(typeof document<`u`){let t=document.activeElement;a=t&&rv(t,e)?t:null}return}if(typeof document>`u`)return;let i=a;if(a=null,i&&document.contains(i)&&typeof i.focus==`function`){try{i.focus({preventScroll:!0})}catch{}return}let o=r??nv(t);if(o&&typeof o.focus==`function`)try{o.focus({preventScroll:!0})}catch{}}),s=e=>{let t=e;if(t.button===2)return;if(t.metaKey||t.ctrlKey||t.button===1){t.button===1&&t.preventDefault?.();return}let r=ev(e.target,n);if(r===null)return;let i=n.getRegistration(r);i?.handlePrimary&&i.handlePrimary({nodeId:r,type:i.type,newTab:!1})||n.setActiveNode(r)},c=e=>{let t=e;if(t.button===2||t.type===`click`&&t.button===1||!(t.metaKey||t.ctrlKey||t.button===1))return;let r=ev(e.target,n);if(r===null)return;let i=n.getRegistration(r);i?.handlePrimary&&i.handlePrimary({nodeId:r,type:i.type,newTab:!0})&&t.preventDefault?.()},l=e=>{let t=e;if(t.key===`Escape`){n.getActiveNode()!==null&&(n.setActiveNode(null),t.preventDefault?.());return}if(t.key!==`Enter`&&t.key!==` `&&t.key!==`Spacebar`)return;let r=ev(e.target,n);if(r===null)return;let i=n.getRegistration(r);t.preventDefault?.(),!(i?.handlePrimary&&i.handlePrimary({nodeId:r,type:i.type,newTab:!1}))&&n.setActiveNode(r)},u=e=>{if(n.getActiveNode()===null)return;let t=e.target;t&&(r?.contains(t)||t instanceof Element&&(t.closest(`[data-ok-interaction-layer]`)||t.closest(`[data-ok-prop-panel]`)||t.closest(`[data-ok-layer-spawned]`))||n.setActiveNode(null))},d=()=>{i||(r=nv(t),r&&(r.addEventListener(`pointerdown`,s,!0),r.addEventListener(`click`,c,!0),r.addEventListener(`auxclick`,c,!0),r.addEventListener(`keydown`,l,!0),typeof document<`u`&&document.addEventListener(`pointerdown`,u,!0),i=!0))},f=()=>{i&&=(r?.removeEventListener(`pointerdown`,s,!0),r?.removeEventListener(`click`,c,!0),r?.removeEventListener(`auxclick`,c,!0),r?.removeEventListener(`keydown`,l,!0),typeof document<`u`&&document.removeEventListener(`pointerdown`,u,!0),!1)};return d(),{register(e){n.register(e),i||d()},deregister(e){n.deregister(e)},setActiveNode(e){n.setActiveNode(e)},getActiveNode(){return n.getActiveNode()},getRegistration(e){return n.getRegistration(e)},destroy(){f(),o(),n.clear()},store:n}}var av=e=>{let t=(0,at.c)(2),{store:n}=e,r;return t[0]===n?r=t[1]:(r=(0,X.jsx)(`div`,{"data-ok-interaction-layer":``,className:`contents`,children:(0,X.jsx)(tv,{store:n})}),t[0]=n,t[1]=r),r},ov=new WeakMap;function sv(e){let t=ov.get(e);if(t)return t;let n=iv({editor:e});return ov.set(e,n),e.on(`destroy`,()=>{n.destroy(),ov.delete(e)}),n}var cv=new be(`markIdentity`);function lv(){return{byId:new Map,counter:0}}function uv(e,t,n,r,i){let a=[];for(let e of t.byId.values()){let t=i?i.map(e.from,-1):e.from,n=i?i.map(e.to,1):e.to;n<=t||a.push({id:e.id,markType:e.markType,attrs:e.attrs,from:t,to:n})}let o=new Map,s=new Set,c=t.counter;return e.descendants((e,t)=>{if(!(!e.isInline||e.marks.length===0))for(let i of e.marks){if(!n.has(i.type.name)||r&&!r(i))continue;let l=null;for(let e of a)if(!s.has(e.id)&&e.markType===i.type.name&&dv(e.attrs,i.attrs)&&!(t<e.from||t>=e.to)){l=e.id;break}let u=l??`m${++c}`;s.add(u);let d=t,f=t+e.nodeSize,p=o.get(u);p?p.to=Math.max(p.to,f):o.set(u,{id:u,markType:i.type.name,attrs:i.attrs,from:d,to:f})}}),{byId:o,counter:c}}function dv(e,t){let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n){let n=e[r],i=t[r];if(n!==i&&!(typeof n==`object`&&n&&typeof i==`object`&&i&&dv(n,i)))return!1}return!0}function fv(e,t,n,r){let i=new Set(t.byId.keys());for(let[r,i]of t.byId)e.has(r)||n?.(i);for(let t of e)i.has(t)||r?.(t);return i}function pv(e){let{markTypes:t,predicate:n,onRegister:r,onDeregister:i}=e,a=new Set(t);return new E({key:cv,state:{init(e,t){return uv(t.doc,lv(),a,n)},apply(e,t,r,i){return e.docChanged?uv(i.doc,t,a,n,e.mapping):t}},view(){let e=new Set;return{update(t){let n=cv.getState(t.state);n&&(e=fv(e,n,r,i))},destroy(){for(let t of e)i?.(t);e=new Set}}}})}function mv(e,t){return cv.getState(e)?.byId.get(t)??null}function hv(e){let{editor:t,layer:n,renderPropPanel:r,handlePrimary:i}=e;return{onRegister:e=>{n.register({type:e.markType,nodeId:e.id,controls:{propPanel:e=>r({editor:t,nodeId:e.nodeId,deactivate:e.deactivate})},handlePrimary:i?e=>i({editor:t,nodeId:e.nodeId,newTab:e.newTab}):void 0})},onDeregister:e=>{n.deregister(e)}}}function gv(e){let{editor:t,layer:n,markTypes:r,predicate:i,renderPropPanel:a,handlePrimary:o}=e,s=hv({editor:t,layer:n,renderPropPanel:a,handlePrimary:o});return pv({markTypes:[...r],predicate:i,onRegister:s.onRegister,onDeregister:s.onDeregister})}function _v(e){let t=sv(e.editor);return gv({...e,layer:t})}function vv(e){let{char:t,allowSpaces:n,allowToIncludeChar:r,allowedPrefixes:i,startOfLine:a,$position:o}=e,s=n&&!r,c=ve(t),l=RegExp(`\\s${c}$`),u=a?`^`:``,d=r?``:c,f=RegExp(s?`${u}${c}.*?(?=\\s${d}|$)`:`${u}(?:^)?${c}[^\\s${d}]*`,`gm`),p=o.nodeBefore?.isText&&o.nodeBefore.text;if(!p)return null;let m=o.pos-p.length,h=Array.from(p.matchAll(f)).pop();if(!h||h.input===void 0||h.index===void 0)return null;let g=h.input.slice(Math.max(0,h.index-1),h.index),_=RegExp(`^[${i?.join(``)}\0]?$`).test(g);if(i!==null&&!_)return null;let v=m+h.index,y=v+h[0].length;return s&&l.test(p.slice(y-1,y+1))&&(h[0]+=` `,y+=1),v<o.pos&&y>=o.pos?{range:{from:v,to:y},query:h[0].slice(t.length),text:h[0]}:null}function yv(e){return e.docChanged?e.steps.some(e=>{let t=e.slice;if(!t?.content)return!1;let n=t.content.textBetween(0,t.content.size,`
|
|
5
5
|
`);return/\s/.test(n)}):!1}var bv=new be(`suggestion`);function xv({pluginKey:e=bv,editor:t,char:n=`@`,allowSpaces:r=!1,allowToIncludeChar:i=!1,allowedPrefixes:a=[` `],startOfLine:o=!1,decorationTag:s=`span`,decorationClass:c=`suggestion`,decorationContent:l=``,decorationEmptyClass:u=`is-empty`,command:d=()=>null,items:f=()=>[],render:p=()=>({}),allow:m=()=>!0,findSuggestionMatch:h=vv,shouldShow:g,shouldResetDismissed:_}){let v,y=p?.(),b=r&&!i,x=()=>{let e=t.state.selection.$anchor.pos,{top:n,right:r,bottom:i,left:a}=t.view.coordsAtPos(e);try{return new DOMRect(a,n,r-a,i-n)}catch{return null}},S=(n,r)=>r?()=>{let r=e.getState(t.state)?.decorationId;return n.dom.querySelector(`[data-decoration-id="${r}"]`)?.getBoundingClientRect()||null}:x,C=({match:e,dismissedRange:n,state:r,transaction:i})=>_?.({editor:t,state:r,range:n,match:e,transaction:i,allowSpaces:b})?!1:b?e.range.from===n.from:e.range.from===n.from&&!yv(i);function w(n,r){var i;try{let r=e.getState(n.state),a=r?.decorationId?n.dom.querySelector(`[data-decoration-id="${r.decorationId}"]`):null,o={editor:t,range:r?.range||{from:0,to:0},query:r?.query||null,text:r?.text||null,items:[],command:e=>d({editor:t,range:r?.range||{from:0,to:0},props:e}),decorationNode:a,clientRect:S(n,a)};(i=y?.onExit)==null||i.call(y,o)}catch{}let a=n.state.tr.setMeta(r,{exit:!0});n.dispatch(a)}let T=new E({key:e,view(){return{update:async(e,n)=>{var r,i,a,o,s;let c=this.key?.getState(n),l=this.key?.getState(e.state),u=c.active&&l.active&&c.range.from!==l.range.from,p=!c.active&&l.active,m=c.active&&!l.active,h=!p&&!m&&c.query!==l.query,g=p||u&&h,_=h||u,b=m||u&&h;if(!g&&!_&&!b)return;let x=b&&!g?c:l,C=e.dom.querySelector(`[data-decoration-id="${x.decorationId}"]`);v={editor:t,range:x.range,query:x.query,text:x.text,items:[],command:e=>d({editor:t,range:x.range,props:e}),decorationNode:C,clientRect:S(e,C)},g&&((r=y?.onBeforeStart)==null||r.call(y,v)),_&&((i=y?.onBeforeUpdate)==null||i.call(y,v)),(_||g)&&(v.items=await f({editor:t,query:x.query})),b&&((a=y?.onExit)==null||a.call(y,v)),_&&((o=y?.onUpdate)==null||o.call(y,v)),g&&((s=y?.onStart)==null||s.call(y,v))},destroy:()=>{var e;v&&((e=y?.onExit)==null||e.call(y,v))}}},state:{init(){return{active:!1,range:{from:0,to:0},query:null,text:null,composing:!1,dismissedRange:null}},apply(s,c,l,u){let{isEditable:d}=t,{composing:f}=t.view,{selection:p}=s,{empty:_,from:v}=p,y={...c},b=s.getMeta(e);if(b&&b.exit)return y.active=!1,y.decorationId=null,y.range={from:0,to:0},y.query=null,y.text=null,y.dismissedRange=c.active?{...c.range}:c.dismissedRange,y;if(y.composing=f,s.docChanged&&y.dismissedRange!==null&&(y.dismissedRange={from:s.mapping.map(y.dismissedRange.from),to:s.mapping.map(y.dismissedRange.to)}),d&&(_||t.view.composing)){(v<c.range.from||v>c.range.to)&&!f&&!c.composing&&(y.active=!1);let e=h({char:n,allowSpaces:r,allowToIncludeChar:i,allowedPrefixes:a,startOfLine:o,$position:p.$from}),l=`id_${Math.floor(Math.random()*4294967295)}`;e&&m({editor:t,state:u,range:e.range,isActive:c.active})&&(!g||g({editor:t,range:e.range,query:e.query,text:e.text,transaction:s}))?(y.dismissedRange!==null&&!C({match:e,dismissedRange:y.dismissedRange,state:u,transaction:s})&&(y.dismissedRange=null),y.dismissedRange===null?(y.active=!0,y.decorationId=c.decorationId?c.decorationId:l,y.range=e.range,y.query=e.query,y.text=e.text):y.active=!1):(e||(y.dismissedRange=null),y.active=!1)}else y.active=!1;return y.active||(y.decorationId=null,y.range={from:0,to:0},y.query=null,y.text=null),y}},props:{handleKeyDown(t,n){var r;let{active:i,range:a}=T.getState(t.state);if(!i)return!1;if(n.key===`Escape`||n.key===`Esc`){let i=T.getState(t.state);return(r=y?.onKeyDown)==null||r.call(y,{view:t,event:n,range:i.range}),w(t,e),!0}return(y?.onKeyDown)?.call(y,{view:t,event:n,range:a})||!1},decorations(e){let{active:t,range:n,decorationId:r,query:i}=T.getState(e);if(!t)return null;let a=!i?.length,o=[c];return a&&o.push(u),A.create(e.doc,[j.inline(n.from,n.to,{nodeName:s,class:o.join(` `),"data-decoration-id":r,"data-decoration-content":l})])}}});return T}var Sv=xv,Cv=e(t(((e,t)=>{((e,n)=>{typeof define==`function`&&define.amd?define([],n):typeof t==`object`&&t.exports?t.exports=n():e.fuzzysort=n()})(e,e=>{var t=(e,t)=>{if(!e||!t)return P;var n=p(e);ee(t)||(t=f(t));var r=n.bitflags;return(r&t._bitflags)===r?h(n,t):P},n=(e,t,n)=>{if(!e)return n?.all?m(t,n):N;var r=p(e),i=r.bitflags,a=r.containsSpace,o=u(n?.threshold||0),c=n?.limit||j,l=0,d=0,g=t.length;function _(e){l<c?(I.add(e),++l):(++d,e._score>I.peek()._score&&I.replaceTop(e))}if(n?.key)for(var v=n.key,y=0;y<g;++y){var b=t[y],x=A(b,v);if(x&&(ee(x)||(x=f(x)),(i&x._bitflags)===i)){var S=h(r,x);S!==P&&(S._score<o||(S.obj=b,_(S)))}}else if(n?.keys){var C=n.keys,w=C.length;outer:for(var y=0;y<g;++y){for(var b=t[y],T=0,L=0;L<w;++L){var v=C[L],x=A(b,v);if(!x){O[L]=F;continue}ee(x)||(x=f(x)),O[L]=x,T|=x._bitflags}if((i&T)===i){if(a)for(let e=0;e<r.spaceSearches.length;e++)E[e]=M;for(var L=0;L<w;++L){if(x=O[L],x===F){k[L]=F;continue}if(k[L]=h(r,x,!1,a),k[L]===P){k[L]=F;continue}if(a)for(let e=0;e<r.spaceSearches.length;e++){if(D[e]>-1e3&&E[e]>M){var R=(E[e]+D[e])/4;R>E[e]&&(E[e]=R)}D[e]>E[e]&&(E[e]=D[e])}}if(a){for(let e=0;e<r.spaceSearches.length;e++)if(E[e]===M)continue outer}else{var z=!1;for(let e=0;e<w;e++)if(k[e]._score!==M){z=!0;break}if(!z)continue}var B=new s(w);for(let e=0;e<w;e++)B[e]=k[e];if(a){var V=0;for(let e=0;e<r.spaceSearches.length;e++)V+=E[e]}else{var V=M;for(let e=0;e<w;e++){var S=B[e];if(S._score>-1e3&&V>M){var R=(V+S._score)/4;R>V&&(V=R)}S._score>V&&(V=S._score)}}if(B.obj=b,B._score=V,n?.scoreFn){if(V=n.scoreFn(B),!V)continue;V=u(V),B._score=V}V<o||_(B)}}}else for(var y=0;y<g;++y){var x=t[y];if(x&&(ee(x)||(x=f(x)),(i&x._bitflags)===i)){var S=h(r,x);S!==P&&(S._score<o||_(S))}}if(l===0)return N;for(var H=Array(l),y=l-1;y>=0;--y)H[y]=I.poll();return H.total=l+d,H},r=(e,t=`<b>`,n=`</b>`)=>{for(var r=typeof t==`function`?t:void 0,i=e.target,a=i.length,o=e.indexes,s=``,c=0,l=0,u=!1,d=[],f=0;f<a;++f){var p=i[f];if(o[l]===f){if(++l,u||(u=!0,r?(d.push(s),s=``):s+=t),l===o.length){r?(s+=p,d.push(r(s,c++)),s=``,d.push(i.substr(f+1))):s+=p+n+i.substr(f+1);break}}else u&&(u=!1,r?(d.push(r(s,c++)),s=``):s+=n);s+=p}return r?d:s},i=e=>{typeof e==`number`?e=``+e:typeof e!=`string`&&(e=``);var t=v(e);return c(e,{_targetLower:t._lower,_targetLowerCodes:t.lowerCodes,_bitflags:t.bitflags})},a=()=>{x.clear(),S.clear()};class o{get indexes(){return this._indexes.slice(0,this._indexes.len).sort((e,t)=>e-t)}set indexes(e){return this._indexes=e}highlight(e,t){return r(this,e,t)}get score(){return l(this._score)}set score(e){this._score=u(e)}}class s extends Array{get score(){return l(this._score)}set score(e){this._score=u(e)}}var c=(e,t)=>{let n=new o;return n.target=e,n.obj=t.obj??P,n._score=t._score??M,n._indexes=t._indexes??[],n._targetLower=t._targetLower??``,n._targetLowerCodes=t._targetLowerCodes??P,n._nextBeginningIndexes=t._nextBeginningIndexes??P,n._bitflags=t._bitflags??0,n},l=e=>e===M?0:e>1?e:Math.E**(((-e+1)**.04307-1)*-2),u=e=>e===0?M:e>1?e:1-(Math.log(e)/-2+1)**(1/.04307),d=e=>{typeof e==`number`?e=``+e:typeof e!=`string`&&(e=``),e=e.trim();var t=v(e),n=[];if(t.containsSpace){var r=e.split(/\s+/);r=[...new Set(r)];for(var i=0;i<r.length;i++)if(r[i]!==``){var a=v(r[i]);n.push({lowerCodes:a.lowerCodes,_lower:r[i].toLowerCase(),containsSpace:!1})}}return{lowerCodes:t.lowerCodes,_lower:t._lower,containsSpace:t.containsSpace,bitflags:t.bitflags,spaceSearches:n}},f=e=>{if(e.length>999)return i(e);var t=x.get(e);return t===void 0?(t=i(e),x.set(e,t),t):t},p=e=>{if(e.length>999)return d(e);var t=S.get(e);return t===void 0?(t=d(e),S.set(e,t),t):t},m=(e,t)=>{var n=[];n.total=e.length;var r=t?.limit||j;if(t?.key)for(var i=0;i<e.length;i++){var a=e[i],o=A(a,t.key);if(o!=P){ee(o)||(o=f(o));var l=c(o.target,{_score:o._score,obj:a});if(n.push(l),n.length>=r)return n}}else if(t?.keys)for(var i=0;i<e.length;i++){for(var a=e[i],u=new s(t.keys.length),d=t.keys.length-1;d>=0;--d){var o=A(a,t.keys[d]);if(!o){u[d]=F;continue}ee(o)||(o=f(o)),o._score=M,o._indexes.len=0,u[d]=o}if(u.obj=a,u._score=M,n.push(u),n.length>=r)return n}else for(var i=0;i<e.length;i++){var o=e[i];if(o!=P&&(ee(o)||(o=f(o)),o._score=M,o._indexes.len=0,n.push(o),n.length>=r))return n}return n},h=(e,t,n=!1,r=!1)=>{if(n===!1&&e.containsSpace)return g(e,t,r);for(var i=e._lower,a=e.lowerCodes,s=a[0],c=t._targetLowerCodes,l=a.length,u=c.length,d=0,f=0,p=0;;){var m=s===c[f];if(m){if(C[p++]=f,++d,d===l)break;s=a[d]}if(++f,f>=u)return P}var d=0,h=!1,_=0,v=t._nextBeginningIndexes;v===P&&(v=t._nextBeginningIndexes=b(t.target)),f=C[0]===0?0:v[C[0]-1];var y=0;if(f!==u)for(;;)if(f>=u){if(d<=0||(++y,y>200))break;--d;var x=w[--_];f=v[x]}else{var m=a[d]===c[f];if(m){if(w[_++]=f,++d,d===l){h=!0;break}++f}else f=v[f]}var S=l<=1?-1:t._targetLower.indexOf(i,C[0]),T=!!~S,E=T?S===0||t._nextBeginningIndexes[S-1]===S:!1;if(T&&!E){for(var D=0;D<v.length;D=v[D])if(!(D<=S)){for(var O=0;O<l&&a[O]===t._targetLowerCodes[D+O];O++);if(O===l){S=D,E=!0;break}}}var k=e=>{for(var t=0,n=0,r=1;r<l;++r)e[r]-e[r-1]!==1&&(t-=e[r],++n);var i=e[l-1]-e[0]-(l-1);if(t-=(12+i)*n,e[0]!==0&&(t-=e[0]*e[0]*.2),!h)t*=1e3;else{for(var a=1,r=v[0];r<u;r=v[r])++a;a>24&&(t*=(a-24)*10)}return t-=(u-l)/2,T&&(t/=1+l*l*1),E&&(t/=1+l*l*1),t-=(u-l)/2,t};if(!h){if(T)for(var D=0;D<l;++D)C[D]=S+D;var A=C,ee=k(A)}else if(E){for(var D=0;D<l;++D)C[D]=S+D;var A=C,ee=k(C)}else var A=w,ee=k(w);t._score=ee;for(var D=0;D<l;++D)t._indexes[D]=A[D];t._indexes.len=l;let j=new o;return j.target=t.target,j._score=t._score,j._indexes=t._indexes,j},g=(e,t,n)=>{for(var r=new Set,i=0,a=P,o=0,s=e.spaceSearches,c=s.length,l=0,u=()=>{for(let e=l-1;e>=0;e--)t._nextBeginningIndexes[T[e*2+0]]=T[e*2+1]},d=!1,f=0;f<c;++f){D[f]=M;var p=s[f];if(a=h(p,t),n){if(a===P)continue;d=!0}else if(a===P)return u(),P;if(f!==c-1){var m=a._indexes,g=!0;for(let e=0;e<m.len-1;e++)if(m[e+1]-m[e]!==1){g=!1;break}if(g){var _=m[m.len-1]+1,v=t._nextBeginningIndexes[_-1];for(let e=_-1;e>=0&&v===t._nextBeginningIndexes[e];e--)t._nextBeginningIndexes[e]=_,T[l*2+0]=e,T[l*2+1]=v,l++}}i+=a._score/c,D[f]=a._score/c,a._indexes[0]<o&&(i-=(o-a._indexes[0])*2),o=a._indexes[0];for(var y=0;y<a._indexes.len;++y)r.add(a._indexes[y])}if(n&&!d)return P;u();var b=h(e,t,!0);if(b!==P&&b._score>i){if(n)for(var f=0;f<c;++f)D[f]=b._score/c;return b}n&&(a=t),a._score=i;var f=0;for(let e of r)a._indexes[f++]=e;return a._indexes.len=f,a},_=e=>e.replace(/\p{Script=Latin}+/gu,e=>e.normalize(`NFD`)).replace(/[\u0300-\u036f]/g,``),v=e=>{e=_(e);for(var t=e.length,n=e.toLowerCase(),r=[],i=0,a=!1,o=0;o<t;++o){var s=r[o]=n.charCodeAt(o);if(s===32){a=!0;continue}var c=s>=97&&s<=122?s-97:s>=48&&s<=57?26:s<=127?30:31;i|=1<<c}return{lowerCodes:r,bitflags:i,containsSpace:a,_lower:n}},y=e=>{for(var t=e.length,n=[],r=0,i=!1,a=!1,o=0;o<t;++o){var s=e.charCodeAt(o),c=s>=65&&s<=90,l=c||s>=97&&s<=122||s>=48&&s<=57,u=c&&!i||!a||!l;i=c,a=l,u&&(n[r++]=o)}return n},b=e=>{e=_(e);for(var t=e.length,n=y(e),r=[],i=n[0],a=0,o=0;o<t;++o)i>o?r[o]=i:(i=n[++a],r[o]=i===void 0?t:i);return r},x=new Map,S=new Map,C=[],w=[],T=[],E=[],D=[],O=[],k=[],A=(e,t)=>{var n=e[t];if(n!==void 0)return n;if(typeof t==`function`)return t(e);var r=t;Array.isArray(t)||(r=t.split(`.`));for(var i=r.length,a=-1;e&&++a<i;)e=e[r[a]];return e},ee=e=>typeof e==`object`&&typeof e._bitflags==`number`,j=1/0,M=-j,N=[];N.total=0;var P=null,F=i(``),I=(e=>{var t=[],n=0,r={},i=e=>{for(var r=0,i=t[r],a=1;a<n;){var o=a+1;r=a,o<n&&t[o]._score<t[a]._score&&(r=o),t[r-1>>1]=t[r],a=1+(r<<1)}for(var s=r-1>>1;r>0&&i._score<t[s]._score;s=(r=s)-1>>1)t[r]=t[s];t[r]=i};return r.add=(e=>{var r=n;t[n++]=e;for(var i=r-1>>1;r>0&&e._score<t[i]._score;i=(r=i)-1>>1)t[r]=t[i];t[r]=e}),r.poll=(e=>{if(n!==0){var r=t[0];return t[0]=t[--n],i(),r}}),r.peek=(e=>{if(n!==0)return t[0]}),r.replaceTop=(e=>{t[0]=e,i()}),r})();return{single:t,go:n,prepare:i,cleanup:a}})}))(),1);function wv(e){return e.kind===`anchor`?`${e.docName}#${e.slug}`:e.docName}function Tv(e){return e.kind===`anchor`?`Heading H${e.level}: ${e.text}`:e.kind===`create`?e.actionLabel:e.title}function Ev(e){let t=(0,at.c)(41),{items:n,query:r,selectedIndex:i,onSelect:a,loading:o,error:s,mode:c,pageTarget:l,anchorQuery:u}=e,d=o===void 0?!1:o,f=s===void 0?null:s,p=c===void 0?`page`:c,m=l===void 0?``:l,h=u===void 0?``:u,g=(0,J.useRef)(null),_=(0,J.useId)(),v=i>=0&&i<n.length?`${_}-option-${i}`:void 0,y,b;t[0]===i?(y=t[1],b=t[2]):(y=()=>{let e=g.current;if(!e)return;let t=e.querySelectorAll(`[role="option"]`).item(i);t&&t.scrollIntoView({block:`nearest`})},b=[i],t[0]=i,t[1]=y,t[2]=b),(0,J.useEffect)(y,b);let x=Dv;if(d){let e;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(e={maxHeight:`var(--suggestion-menu-max-height, 40vh)`},t[3]=e):e=t[3];let n=p===`anchor`?`Loading headings for ${m}…`:`Loading pages…`,r;return t[4]===n?r=t[5]:(r=(0,X.jsx)(`div`,{ref:g,role:`status`,"aria-live":`polite`,className:`w-64 rounded-lg border bg-popover p-2 shadow-md text-sm text-muted-foreground`,style:e,onMouseDown:x,children:n}),t[4]=n,t[5]=r),r}if(n.length===0){let e;t[6]!==h||t[7]!==f||t[8]!==p||t[9]!==m||t[10]!==r?(e=f??(p===`anchor`?h.trim()?`No headings match "${h.trim()}"`:`No headings in ${m}`:r.trim()?`No pages found for "${r.trim()}"`:`No pages found`),t[6]=h,t[7]=f,t[8]=p,t[9]=m,t[10]=r,t[11]=e):e=t[11];let n=e,i;t[12]===Symbol.for(`react.memo_cache_sentinel`)?(i={maxHeight:`var(--suggestion-menu-max-height, 40vh)`},t[12]=i):i=t[12];let a;return t[13]===n?a=t[14]:(a=(0,X.jsx)(`div`,{ref:g,role:`status`,"aria-live":`polite`,className:`w-64 rounded-lg border bg-popover p-2 shadow-md text-sm text-muted-foreground`,style:i,onMouseDown:x,children:n}),t[13]=n,t[14]=a),a}let S=i>=0&&i<n.length?n[i]:null,C=p===`anchor`?`Heading suggestions`:`Wiki link suggestions`,w;t[15]===Symbol.for(`react.memo_cache_sentinel`)?(w={maxHeight:`var(--suggestion-menu-max-height, 40vh)`},t[15]=w):w=t[15];let T;t[16]===S?T=t[17]:(T=S?Tv(S):``,t[16]=S,t[17]=T);let E;t[18]===T?E=t[19]:(E=(0,X.jsx)(`span`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:T}),t[18]=T,t[19]=E);let D;t[20]===f?D=t[21]:(D=f&&(0,X.jsx)(`div`,{className:`rounded-md px-2 py-1.5 text-xs text-amber-700 dark:text-amber-300`,children:f}),t[20]=f,t[21]=D);let O;t[22]!==p||t[23]!==m?(O=p===`anchor`&&(0,X.jsx)(`div`,{className:`px-2 py-1 text-[10px] font-medium uppercase tracking-wide text-muted-foreground`,children:m}),t[22]=p,t[23]=m,t[24]=O):O=t[24];let k;if(t[25]!==n||t[26]!==_||t[27]!==a||t[28]!==i){let e;t[30]!==_||t[31]!==a||t[32]!==i?(e=(e,t)=>{let n=t===i,r=wv(e);return e.kind===`anchor`?(0,X.jsxs)(`button`,{id:`${_}-option-${t}`,type:`button`,role:`option`,"aria-selected":n,"data-selected":n,className:`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-sm text-left ${n?`bg-accent text-accent-foreground`:``}`,style:{paddingLeft:`${(e.level-1)*10+8}px`},onMouseDown:t=>{t.preventDefault(),a(e)},children:[(0,X.jsxs)(`span`,{className:`w-6 shrink-0 font-mono text-[10px] text-muted-foreground`,children:[`H`,e.level]}),(0,X.jsx)(`span`,{className:`truncate font-medium`,children:e.text})]},r):(0,X.jsxs)(`button`,{id:`${_}-option-${t}`,type:`button`,role:`option`,"aria-selected":n,"data-selected":n,className:`flex w-full flex-col rounded-md px-2 py-1.5 text-sm text-left ${n?`bg-accent text-accent-foreground`:``}`,onMouseDown:t=>{t.preventDefault(),a(e)},children:[(0,X.jsx)(`span`,{className:`truncate font-medium`,children:e.kind===`create`?e.actionLabel:e.title}),e.kind===`page`&&e.title!==e.docName&&(0,X.jsx)(`span`,{className:`truncate text-xs text-muted-foreground`,children:e.docName}),e.kind===`create`&&(0,X.jsxs)(`span`,{className:`truncate text-xs text-muted-foreground`,children:[e.docName,`.md`]})]},r)},t[30]=_,t[31]=a,t[32]=i,t[33]=e):e=t[33],k=n.map(e),t[25]=n,t[26]=_,t[27]=a,t[28]=i,t[29]=k}else k=t[29];let A;return t[34]!==v||t[35]!==E||t[36]!==D||t[37]!==O||t[38]!==k||t[39]!==C?(A=(0,X.jsxs)(`div`,{ref:g,role:`listbox`,"aria-label":C,"aria-activedescendant":v,tabIndex:-1,onMouseDown:x,className:`w-64 overflow-y-auto subtle-scrollbar rounded-lg border bg-popover p-1 shadow-md`,style:w,children:[E,D,O,k]}),t[34]=v,t[35]=E,t[36]=D,t[37]=O,t[38]=k,t[39]=C,t[40]=A):A=t[40],A}function Dv(e){return e.preventDefault()}function Ov(e,t){let n=document.createElement(`div`);n.style.position=`fixed`,n.style.zIndex=`50`,n.style.visibility=`hidden`,document.body.appendChild(n);let r={getBoundingClientRect:()=>e()?.clientRect?.()??new DOMRect,get contextElement(){return e()?.editor.view.dom}},i=!1,a=!1,o=()=>{n.isConnected&&(n.style.removeProperty(`--suggestion-menu-max-height`),N(r,n,{placement:`bottom-start`,middleware:[je(4),K(),ne({apply({availableHeight:e}){n.isConnected&&n.style.setProperty(`--suggestion-menu-max-height`,`${Math.min(e,window.innerHeight*.4)}px`)}})]}).then(({x:e,y:t})=>{n.isConnected&&(n.style.left=`${e}px`,n.style.top=`${t}px`,i&&!a&&(n.style.removeProperty(`visibility`),a=!0))}).catch(e=>{n.isConnected&&console.warn(`[${t}] computePosition failed`,e)}))};return{popup:n,doPosition:o,startAutoUpdate:()=>q(r,n,o),reveal:()=>{a||(i=!0,o())}}}function kv(e){e.stopAutoUpdate?.(),e.stopAutoUpdate=null,e.popup?.remove(),e.popup=null}var Av=new be(`wikiLinkSuggestion`),jv=8;function Mv(e){let t=e.indexOf(`#`);return t>0?{mode:`anchor`,pageTarget:e.slice(0,t),anchorQuery:e.slice(t+1)}:{mode:`page`,pageTarget:``,anchorQuery:``}}function Nv(e,t){return t?Cv.default.go(t,e,{keys:[`title`,`docName`],threshold:-1e4}).map(e=>e.obj).slice(0,jv):e.slice(0,jv)}function Pv(e,t){return t?Cv.default.go(t,e,{key:`text`,threshold:-1e4}).map(e=>e.obj).slice(0,jv):e.slice(0,jv)}function Fv(e,t){let n=Nv(e,t);if(n.length>0)return n.map(e=>({kind:`page`,...e}));let r=E_(t);return r?[{kind:`create`,docName:r.target,title:t.trim(),actionLabel:`Insert unresolved link "${t.trim()}"`}]:[]}function Iv(e,t,n){return Pv(t,n).map(t=>({kind:`anchor`,docName:e,level:t.level,text:t.text,slug:t.slug}))}function Lv(e){let{mode:t,pageTarget:n,anchorQuery:r}=Mv(e);return t===`anchor`&&n?{target:n,alias:null,anchor:r.trim()||null}:E_(e)}function Rv(e){let{$position:t}=e,n=t.parent.textBetween(0,t.parentOffset,void 0,``),r=n.match(/\[\[([^\]]*)$/);if(!r)return null;let i=r[1];return{range:{from:t.start()+n.lastIndexOf(`[[`),to:t.pos},query:i,text:r[0]}}async function zv(){let e=await fetch(`/api/pages`);if(!e.ok)throw Error(`/api/pages responded with ${e.status}`);let t=await e.json();return Array.isArray(t.pages)?t.pages:[]}async function Bv(e){let t=await fetch(`/api/page-headings?docName=${encodeURIComponent(e)}`);if(!t.ok)throw Error(`/api/page-headings responded with ${t.status}`);let n=await t.json();return n.ok&&Array.isArray(n.headings)?n.headings:[]}function Vv(e){let t=[],n=!1,r=!1,i=new Map,a=null,o=null,s=null;return Sv({editor:e,pluginKey:Av,char:`[[`,allowedPrefixes:null,findSuggestionMatch:Rv,items:async({query:e})=>{let{mode:c,pageTarget:l,anchorQuery:u}=Mv(e);if(c===`anchor`){if(!i.has(l)&&a!==l){a=l;try{let e=await Bv(l);i.set(l,e),s=null}catch(e){console.error(`[wiki-link-suggestion] Failed to fetch headings:`,e),i.set(l,[]),s=`Failed to load headings for ${l}. Press Escape and type [[ again to retry.`}finally{a=null}}return Iv(l,i.get(l)??[],u)}if(!n&&!r){r=!0;try{t=await zv(),o=null}catch(e){console.error(`[wiki-link-suggestion] Failed to fetch pages:`,e),o=`Failed to load pages. Press Escape and type [[ again to retry, or continue typing to insert an unresolved link.`,t=[]}finally{n=!0,r=!1}}return Fv(t,e)},command:({editor:e,range:t,props:n})=>{try{let r=null;if(n.kind===`page`?r={target:n.docName,alias:null,anchor:null}:n.kind===`anchor`?r={target:n.docName,alias:null,anchor:n.slug}:n.kind===`create`&&(r=E_(n.title)),!r)return;e.chain().focus().deleteRange(t).insertContent({type:`wikiLink`,attrs:r}).run()}catch(e){console.error(`[wiki-link-suggestion] command failed`,{item:n,range:t},e)}},render:()=>{let e=null,c=null,l=0,u={popup:null,stopAutoUpdate:null},d=null,f=null,p=e=>{c?.command(e)};function m(e,t,r){let{mode:a,pageTarget:c,anchorQuery:u}=Mv(e.query??``),d=t===null?a===`anchor`?!i.has(c):!n:t;return{items:e.items,query:e.query??``,selectedIndex:l,onSelect:r,loading:d,error:a===`page`?o:s,mode:a,pageTarget:c,anchorQuery:u}}let h=t=>{!e||!c||e.updateProps(m(c,t,p))},g=()=>{if(!c)return;let{editor:e,range:t}=c,n=Lv(c.query??``);if(n)try{e.chain().focus().deleteRange(t).insertContent({type:`wikiLink`,attrs:n}).run()}catch(e){console.error(`[wiki-link-suggestion] fallback insert error:`,e)}};return{onBeforeStart(t){c=t,l=0;let n=Ov(()=>c,`wiki-link-suggestion`);u.popup=n.popup,d=n.doPosition,f=n.reveal,e=new jn(Ev,{props:m(t,!0,p),editor:t.editor}),n.popup.appendChild(e.element),u.stopAutoUpdate=n.startAutoUpdate()},onBeforeUpdate(e){let t=c?Mv(c.query??``).mode:null,n=Mv(e.query??``).mode;c=e,t!==n&&(l=0,h(!0))},onStart(e){c=e,l=0,h(null),f?.()},onUpdate(e){c=e,l=Math.min(l,Math.max(0,e.items.length-1)),h(null),d?.()},onKeyDown({event:e}){if(!c)return!1;let t=c.items;if(e.key===`ArrowDown`)return t.length===0?!1:(l=(l+1)%t.length,h(null),!0);if(e.key===`ArrowUp`)return t.length===0?!1:(l=(l-1+t.length)%t.length,h(null),!0);if(e.key===`Enter`||e.key===`Tab`){let e=t[l];return e?c.command(e):g(),!0}return e.key,!1},onExit(){kv(u),d=null,f=null,e?.destroy(),e=null,c=null,l=0,t=[],i=new Map,o=null,s=null,n=!1,r=!1,a=null}}}})}function Hv(e,t){let n=(0,at.c)(4),[r,i]=(0,J.useState)(null),a,o;return n[0]!==e||n[1]!==t?(a=()=>{if(!t||!e){i(null);return}let n=!1;return i(null),Bv(e).then(e=>{n||i(e)}).catch(()=>{n||i([])}),()=>{n=!0}},o=[e,t],n[0]=e,n[1]=t,n[2]=a,n[3]=o):(a=n[2],o=n[3]),(0,J.useEffect)(a,o),r}function Uv(e,t){let n=e.trim();return n?n.startsWith(`#`)?`anchor`:n.startsWith(`/`)||F(n)?`external`:`doc`:t}function Wv(e){return e?.kind===`doc`?`doc`:e?.kind===`anchor`?`anchor`:`external`}function Gv(e){let t=(0,at.c)(64),{open:n,href:r,pages:i,onOpenChange:a,onSave:o}=e,[s,u]=(0,J.useState)(``),[d,f]=(0,J.useState)(``),[h,v]=(0,J.useState)(`doc`),b=(0,J.useId)(),x=(0,J.useId)(),S=(0,J.useId)(),w,T;t[0]!==r||t[1]!==n?(w=()=>{if(!n)return;let e=N_(r);if(v(Wv(e)),e?.kind===`doc`){u(e.docName),f(e.anchor??``);return}if(e?.kind===`anchor`){u(`#${e.anchor}`),f(``);return}u(e?.kind===`external`?e.url:r),f(``)},T=[r,n],t[0]=r,t[1]=n,t[2]=w,t[3]=T):(w=t[2],T=t[3]),(0,J.useEffect)(w,T);let E,D,O;t[4]!==h||t[5]!==s||t[6]!==i?(E=Se(s),D=h===`doc`,O=D&&O_(E,i),t[4]=h,t[5]=s,t[6]=i,t[7]=E,t[8]=D,t[9]=O):(E=t[7],D=t[8],O=t[9]);let k=Hv(E,O&&n),A=!!k?.length,ee;t[10]!==E||t[11]!==D||t[12]!==d||t[13]!==s||t[14]!==a||t[15]!==o?(ee=function(){let e=s.trim();e&&(o(D?V_(E,d.trim()||null):e),a(!1))},t[10]=E,t[11]=D,t[12]=d,t[13]=s,t[14]=a,t[15]=o,t[16]=ee):ee=t[16];let j=ee,M;t[17]===j?M=t[18]:(M=function(e){e.key===`Enter`&&(e.preventDefault(),j())},t[17]=j,t[18]=M);let N=M,P;t[19]===Symbol.for(`react.memo_cache_sentinel`)?(P=(0,X.jsx)(p,{className:`fixed inset-0 z-50 bg-black/40 data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0`}),t[19]=P):P=t[19];let F,I;t[20]===Symbol.for(`react.memo_cache_sentinel`)?(F=(0,X.jsx)(_,{className:`mb-1 text-base font-semibold`,children:`Edit markdown link`}),I=(0,X.jsx)(C,{className:`mb-4 text-sm text-muted-foreground`,children:`Update the destination and optional section anchor.`}),t[20]=F,t[21]=I):(F=t[20],I=t[21]);let L=D?`Page`:`Link target`,R;t[22]!==L||t[23]!==b?(R=(0,X.jsx)(`label`,{className:`mb-1.5 block text-sm font-medium`,htmlFor:b,children:L}),t[22]=L,t[23]=b,t[24]=R):R=t[24];let z;t[25]===Symbol.for(`react.memo_cache_sentinel`)?(z=e=>{let t=e.target.value;u(t),v(e=>Uv(t,e))},t[25]=z):z=t[25];let B;t[26]!==s||t[27]!==N||t[28]!==b?(B=(0,X.jsx)(G_,{id:b,value:s,onChange:z,placeholder:`guides/install or https://example.com`,autoFocus:!0,onKeyDown:N}),t[26]=s,t[27]=N,t[28]=b,t[29]=B):B=t[29];let V;t[30]===D?V=t[31]:(V=D?(0,X.jsx)(`p`,{className:`mt-1.5 text-xs text-muted-foreground`,children:`This changes the destination page. The visible link text stays editable inline in the document.`}):null,t[30]=D,t[31]=V);let H;t[32]!==R||t[33]!==B||t[34]!==V?(H=(0,X.jsxs)(`div`,{children:[R,B,V]}),t[32]=R,t[33]=B,t[34]=V,t[35]=H):H=t[35];let U;t[36]!==x||t[37]!==D||t[38]!==d||t[39]!==N||t[40]!==S||t[41]!==k||t[42]!==A?(U=D?(0,X.jsxs)(`div`,{children:[(0,X.jsxs)(`label`,{className:`mb-1.5 block text-sm font-medium`,htmlFor:x,children:[`Section`,` `,(0,X.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`(optional heading anchor)`})]}),(0,X.jsx)(G_,{id:x,value:d,onChange:e=>f(e.target.value),placeholder:`heading-slug`,"aria-controls":A?S:void 0,"aria-expanded":A?!0:void 0,"aria-haspopup":A?`listbox`:void 0,onKeyDown:N}),A?(0,X.jsx)(`div`,{role:`listbox`,id:S,"aria-label":`Heading anchors`,className:`mt-1.5 max-h-36 overflow-y-auto subtle-scrollbar rounded-md border border-border bg-muted/30`,children:k.map(e=>(0,X.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":d===e.slug,className:c(`flex w-full items-center gap-2 px-2 py-1 text-left text-sm hover:bg-accent hover:text-accent-foreground`,d===e.slug&&`bg-accent text-accent-foreground`),style:{paddingLeft:`${(e.level-1)*12+8}px`},onClick:()=>f(d===e.slug?``:e.slug),children:[(0,X.jsxs)(`span`,{className:`w-7 shrink-0 font-mono text-[10px] text-muted-foreground`,children:[`H`,e.level]}),(0,X.jsx)(`span`,{className:`truncate`,children:e.text})]},`${e.slug}-${e.level}-${e.text}`))}):null]}):null,t[36]=x,t[37]=D,t[38]=d,t[39]=N,t[40]=S,t[41]=k,t[42]=A,t[43]=U):U=t[43];let W;t[44]!==H||t[45]!==U?(W=(0,X.jsxs)(`div`,{className:`mb-4 space-y-6`,children:[H,U]}),t[44]=H,t[45]=U,t[46]=W):W=t[46];let G;t[47]===a?G=t[48]:(G=(0,X.jsx)(l,{variant:`outline`,onClick:()=>a(!1),children:`Cancel`}),t[47]=a,t[48]=G);let K;t[49]===s?K=t[50]:(K=s.trim(),t[49]=s,t[50]=K);let q=!K,te;t[51]!==j||t[52]!==q?(te=(0,X.jsx)(l,{onClick:j,disabled:q,children:`Save`}),t[51]=j,t[52]=q,t[53]=te):te=t[53];let ne;t[54]!==G||t[55]!==te?(ne=(0,X.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[G,te]}),t[54]=G,t[55]=te,t[56]=ne):ne=t[56];let re;t[57]!==W||t[58]!==ne?(re=(0,X.jsxs)(m,{children:[P,(0,X.jsxs)(g,{"data-slot":`dialog-content`,"data-ok-layer-spawned":``,className:`fixed left-1/2 top-1/2 z-50 w-full max-w-md -translate-x-1/2 -translate-y-1/2 rounded-lg border border-border bg-background p-6 shadow-xl data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95`,children:[F,I,W,ne]})]}),t[57]=W,t[58]=ne,t[59]=re):re=t[59];let ie;return t[60]!==a||t[61]!==n||t[62]!==re?(ie=(0,X.jsx)(y,{open:n,onOpenChange:a,children:re}),t[60]=a,t[61]=n,t[62]=re,t[63]=ie):ie=t[63],ie}function Kv(e){let t=(0,at.c)(81),{editor:n,nodeId:r,sourceDocName:i,onClose:a}=e,o=mv(n.state,r),s=o?.attrs?.href??``,[u,d]=(0,J.useState)(!1),[f,p]=(0,J.useState)(null),{folderPaths:m,pages:h,loading:g}=Te();if(!o||!s)return null;let _=R(s,i),v;t[0]!==n||t[1]!==r?(v=function(e){let t=mv(n.state,r);t&&n.chain().setTextSelection({from:t.from,to:t.to}).extendMarkRange(`link`).updateAttributes(`link`,{href:e}).run()},t[0]=n,t[1]=r,t[2]=v):v=t[2];let y=v,b;t[3]!==n||t[4]!==r||t[5]!==a?(b=function(){let e=mv(n.state,r);e&&(n.chain().focus().setTextSelection({from:e.from,to:e.to}).extendMarkRange(`link`).unsetLink().run(),a())},t[3]=n,t[4]=r,t[5]=a,t[6]=b):b=t[6];let x=b,S=function(e){if(_){if(_.kind===`external`){B_(_);return}if(_.kind===`anchor`||_.kind===`doc`){let t=_.kind===`doc`?_.docName:i,n=_.anchor??null;e.newTab?L_({docName:t,anchor:n}):window.location.assign(P_({docName:t,anchor:n}))}}},C=function(e){if(f!==`missing`)return;let t=mv(n.state,r);t&&n.chain().setTextSelection({from:t.from,to:t.to}).extendMarkRange(`link`).updateAttributes(`link`,{href:V_(e,_?.kind===`doc`?_.anchor??null:null)}).run()},w,T=!1,E=!1,D=null;if(g){let e;t[7]===Symbol.for(`react.memo_cache_sentinel`)?(e=(0,X.jsx)(Ze,{className:`size-3.5 shrink-0 animate-spin`,"aria-hidden":`true`}),t[7]=e):e=t[7],w={icon:e,text:`Loading…`,className:`text-muted-foreground`}}else if(_?.kind===`external`){let e;t[8]===Symbol.for(`react.memo_cache_sentinel`)?(e=(0,X.jsx)(Be,{className:`size-3.5 shrink-0`,"aria-hidden":`true`}),t[8]=e):e=t[8],w={icon:e,text:`External link`,className:`text-foreground`}}else if(_?.kind===`anchor`){let e;t[9]===Symbol.for(`react.memo_cache_sentinel`)?(e=(0,X.jsx)(He,{className:`size-3.5 shrink-0`,"aria-hidden":`true`}),t[9]=e):e=t[9],w={icon:e,text:`Anchor in this page`,className:`text-foreground`}}else if(_?.kind===`doc`){let e=U_(_.docName,{pages:h,folderPaths:m});if(D=W_(e),E=e.kind===`navigate`&&e.displayState===`folder`,T=e.kind===`create`,E){let e;t[10]===Symbol.for(`react.memo_cache_sentinel`)?(e=(0,X.jsx)(Ue,{className:`size-3.5 shrink-0`,"aria-hidden":`true`}),t[10]=e):e=t[10],w={icon:e,text:`Folder (no index)`,className:`text-foreground`}}else if(T){let e;t[11]===Symbol.for(`react.memo_cache_sentinel`)?(e=(0,X.jsx)(Re,{className:`size-3.5 shrink-0`,"aria-hidden":`true`}),t[11]=e):e=t[11],w={icon:e,text:`Page not found`,className:`text-red-700 dark:text-red-300`}}else{let e;t[12]===Symbol.for(`react.memo_cache_sentinel`)?(e=(0,X.jsx)(He,{className:`size-3.5 shrink-0`,"aria-hidden":`true`}),t[12]=e):e=t[12],w={icon:e,text:`Page link`,className:`text-foreground`}}}else{let e;t[13]===Symbol.for(`react.memo_cache_sentinel`)?(e=(0,X.jsx)(Re,{className:`size-3.5 shrink-0`,"aria-hidden":`true`}),t[13]=e):e=t[13],w={icon:e,text:`Unrecognized link`,className:`text-muted-foreground`}}let O=c(`text-sm font-medium`,w.className),k;t[14]!==w.text||t[15]!==O?(k=(0,X.jsx)(`div`,{className:O,children:w.text}),t[14]=w.text,t[15]=O,t[16]=k):k=t[16];let A;t[17]===s?A=t[18]:(A=(0,X.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,title:s,children:s}),t[17]=s,t[18]=A);let ee;t[19]!==k||t[20]!==A?(ee=(0,X.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[k,A]}),t[19]=k,t[20]=A,t[21]=ee):ee=t[21];let j;t[22]!==S||t[23]!==T||t[24]!==a||t[25]!==_?.kind?(j=T?null:(0,X.jsx)(l,{size:`sm`,variant:`default`,onClick:()=>{S({}),a()},children:_?.kind===`external`?`Open in new tab`:`Open`}),t[22]=S,t[23]=T,t[24]=a,t[25]=_?.kind,t[26]=j):j=t[26];let M;t[27]!==T||t[28]!==p?(M=T?(0,X.jsx)(l,{size:`sm`,variant:`default`,onClick:()=>p(`missing`),children:`Create page`}):null,t[27]=T,t[28]=p,t[29]=M):M=t[29];let N;t[30]!==D||t[31]!==E||t[32]!==p?(N=E&&D?(0,X.jsxs)(l,{size:`sm`,variant:`outline`,onClick:()=>p(`folder-index`),children:[(0,X.jsx)(Ve,{className:`size-3.5`,"aria-hidden":`true`}),`Create index`]}):null,t[30]=D,t[31]=E,t[32]=p,t[33]=N):N=t[33];let P;t[34]===d?P=t[35]:(P=()=>d(!0),t[34]=d,t[35]=P);let F;t[36]===Symbol.for(`react.memo_cache_sentinel`)?(F=(0,X.jsx)($e,{className:`size-3.5`,"aria-hidden":`true`}),t[36]=F):F=t[36];let I;t[37]===P?I=t[38]:(I=(0,X.jsxs)(l,{size:`sm`,variant:`outline`,onClick:P,children:[F,`Edit`]}),t[37]=P,t[38]=I);let L;t[39]===Symbol.for(`react.memo_cache_sentinel`)?(L=(0,X.jsx)(nt,{className:`size-3.5`,"aria-hidden":`true`}),t[39]=L):L=t[39];let z;t[40]===x?z=t[41]:(z=(0,X.jsxs)(l,{size:`sm`,variant:`outline`,className:`text-red-700 hover:bg-red-50 hover:text-red-800 dark:text-red-300 dark:hover:bg-red-100/10 dark:hover:text-red-200`,onClick:x,children:[L,`Remove`]}),t[40]=x,t[41]=z);let B;t[42]!==N||t[43]!==I||t[44]!==z||t[45]!==j||t[46]!==M?(B=(0,X.jsxs)(`div`,{className:`flex flex-wrap gap-1.5`,children:[j,M,N,I,z]}),t[42]=N,t[43]=I,t[44]=z,t[45]=j,t[46]=M,t[47]=B):B=t[47];let V=f!==null,H;t[48]===p?H=t[49]:(H=e=>{e||p(null)},t[48]=p,t[49]=H);let U;t[50]!==f||t[51]!==D||t[52]!==m||t[53]!==T||t[54]!==h||t[55]!==_?(U=f===`folder-index`&&D?D.initialDir:T&&_?.kind===`doc`&&U_(_.docName,{pages:h,folderPaths:m}).kind===`create`?U_(_.docName,{pages:h,folderPaths:m}).initialDir:``,t[50]=f,t[51]=D,t[52]=m,t[53]=T,t[54]=h,t[55]=_,t[56]=U):U=t[56];let W;t[57]!==f||t[58]!==D||t[59]!==m||t[60]!==T||t[61]!==h||t[62]!==_?(W=f===`folder-index`&&D?D.suggestedName:T&&_?.kind===`doc`&&U_(_.docName,{pages:h,folderPaths:m}).kind===`create`?U_(_.docName,{pages:h,folderPaths:m}).suggestedName:void 0,t[57]=f,t[58]=D,t[59]=m,t[60]=T,t[61]=h,t[62]=_,t[63]=W):W=t[63];let G;t[64]!==f||t[65]!==D||t[66]!==_?(G=f===`folder-index`&&D?(0,X.jsxs)(X.Fragment,{children:[`Create an index note for`,` `,(0,X.jsxs)(`span`,{className:`font-medium text-foreground`,children:[D.initialDir,`/`]})]}):(0,X.jsxs)(X.Fragment,{children:[`Create a page for`,` `,(0,X.jsx)(`span`,{className:`font-medium text-foreground`,children:_?.kind===`doc`?_.docName:``})]}),t[64]=f,t[65]=D,t[66]=_,t[67]=G):G=t[67];let K;t[68]!==C||t[69]!==V||t[70]!==H||t[71]!==U||t[72]!==W||t[73]!==G?(K=(0,X.jsx)(Z_,{open:V,onOpenChange:H,kind:`file`,initialDir:U,suggestedName:W,description:G,onCreated:C}),t[68]=C,t[69]=V,t[70]=H,t[71]=U,t[72]=W,t[73]=G,t[74]=K):K=t[74];let q;return t[75]!==u||t[76]!==y||t[77]!==s||t[78]!==h||t[79]!==d?(q=(0,X.jsx)(Gv,{open:u,href:s,pages:h,onOpenChange:d,onSave:y}),t[75]=u,t[76]=y,t[77]=s,t[78]=h,t[79]=d,t[80]=q):q=t[80],(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(H_,{kind:`internal-link`,ariaLabel:`Link options`,onDeactivate:a,children:[(0,X.jsxs)(`div`,{className:`mb-2 flex items-start gap-2 pr-8`,children:[(0,X.jsx)(`div`,{className:c(`mt-0.5 flex shrink-0`,w.className),children:w.icon}),ee]}),B]}),K,q]})}function qv(e,t,n){let r=R(e,t);if(!r)return`unresolved`;if(r.kind===`external`)return`external`;if(r.kind===`anchor`)return`anchor`;if(n===null)return`loading`;let i=U_(r.docName,{pages:n.pages,folderPaths:n.folderPaths});return i.kind===`create`?`unresolved`:i.displayState}function Jv(e,t,n){let r=e.attrs?.href;return typeof r!=`string`||r.length===0?null:{"data-resolution-state":qv(r,n,t)}}function Yv(e){return(t,n)=>Jv(t,n,e)}var Xv=new be(`linkResolutionDecoration`);function Zv(e,t,n,r,i){if(t.size===0)return null;let a=[];for(let e of t.values()){if(!n.has(e.markType))continue;let t=r(e,i);t!==null&&a.push(j.inline(e.from,e.to,t))}return a.length===0?null:A.create(e,a)}function Qv(e){let t=new Set(e.markTypes),{computeAttrs:n}=e;return new E({key:Xv,state:{init:()=>({version:0}),apply(e,t){let n=e.getMeta(Xv);return n&&typeof n==`object`&&n.refresh?{version:t.version+1}:t}},props:{decorations(e){let r=cv.getState(e);if(!r)return null;let i=ae();return Zv(e.doc,r.byId,t,n,i)}},view(e){let t=De(()=>{e.dispatch(e.state.tr.setMeta(Xv,{refresh:!0}))});return{destroy(){t()}}}})}var $v=new be(`markIdentityDecoration`),ey=`data-mark-id`;function ty(){return new E({key:$v,props:{decorations(e){let t=cv.getState(e);if(!t||t.byId.size===0)return null;let n=[];for(let e of t.byId.values())n.push(j.inline(e.from,e.to,{[ey]:e.id}));return A.create(e.doc,n)}}})}var ny=se.extend({addOptions(){return{...this.parent?.(),docName:``}},renderHTML({HTMLAttributes:e}){let t=typeof e.href==`string`?e.href:``;return[`span`,k(e,{"data-link":``,role:`link`,tabindex:`0`,"aria-label":t?`Link: ${t}`:`Link`,style:`touch-action: manipulation;`}),0]},addProseMirrorPlugins(){let e=this.options.docName??``;return[_v({editor:this.editor,markTypes:[`link`],renderPropPanel:({editor:t,nodeId:n,deactivate:r})=>(0,J.createElement)(Kv,{editor:t,nodeId:n,sourceDocName:e,onClose:r}),handlePrimary:({editor:t,nodeId:n,newTab:r})=>{if(!r)return!1;let i=mv(t.state,n)?.attrs?.href;if(typeof i!=`string`||!i)return!1;let a=R(i,e);return a?a.kind===`doc`?(L_({docName:a.docName,anchor:a.anchor}),!0):a.kind===`anchor`?(L_({docName:e,anchor:a.anchor}),!0):j_(a.url)?(F_(a.url),!0):!1:!1}}),ty(),Qv({markTypes:[`link`],computeAttrs:Yv(e)})]}}),ry={warning:`bg-amber-100 text-amber-900 dark:bg-amber-900/40 dark:text-amber-200`,info:`bg-sky-100 text-sky-900 dark:bg-sky-900/40 dark:text-sky-200`,error:`bg-red-100 text-red-900 dark:bg-red-900/40 dark:text-red-200`},iy={warning:`alert`,error:`alert`,info:`note`};function ay(e){let t=(0,at.c)(11),{type:n,children:r}=e,i=iy[n]||`note`,a=ry[n]||`bg-muted text-foreground`,o;t[0]===a?o=t[1]:(o=c(`p-3 px-4 rounded-md`,a),t[0]=a,t[1]=o);let s;t[2]===n?s=t[3]:(s=n.toUpperCase(),t[2]=n,t[3]=s);let l;t[4]===s?l=t[5]:(l=(0,X.jsx)(`strong`,{children:s}),t[4]=s,t[5]=l);let u;return t[6]!==r||t[7]!==i||t[8]!==o||t[9]!==l?(u=(0,X.jsxs)(`div`,{role:i,className:o,children:[l,`: `,r]}),t[6]=r,t[7]=i,t[8]=o,t[9]=l,t[10]=u):u=t[10],u}function oy(e){let t=e.match(/<(\w+)/);return t?t[1]:`Unknown`}function sy(e){let t=(0,at.c)(19),{editor:n,getPos:r,onDismiss:i}=e,a;if(t[0]!==n||t[1]!==r){let e=r();a=oy((typeof e==`number`?n.state.doc.nodeAt(e):null)?.attrs.content??``),t[0]=n,t[1]=r,t[2]=a}else a=t[2];let o=a,s;t[3]!==n||t[4]!==r||t[5]!==i?(s=function(){let e=r();if(typeof e!=`number`)return;let t=n.state.doc.nodeAt(e);t&&(n.chain().focus().deleteRange({from:e,to:e+t.nodeSize}).run(),i())},t[3]=n,t[4]=r,t[5]=i,t[6]=s):s=t[6];let c=s,u;t[7]===Symbol.for(`react.memo_cache_sentinel`)?(u=(0,X.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`Component`}),t[7]=u):u=t[7];let d;t[8]===o?d=t[9]:(d=(0,X.jsx)(`code`,{className:`rounded bg-muted px-1.5 py-0.5 text-xs font-mono`,children:o}),t[8]=o,t[9]=d);let f;t[10]===Symbol.for(`react.memo_cache_sentinel`)?(f=(0,X.jsx)(`div`,{className:`flex-1`}),t[10]=f):f=t[10];let p;t[11]===c?p=t[12]:(p=(0,X.jsx)(l,{variant:`outline`,size:`sm`,onClick:c,children:`Delete`}),t[11]=c,t[12]=p);let m;t[13]!==d||t[14]!==p?(m=(0,X.jsxs)(`div`,{className:`flex items-center gap-2 pr-8`,children:[u,d,f,p]}),t[13]=d,t[14]=p,t[15]=m):m=t[15];let h;return t[16]!==i||t[17]!==m?(h=(0,X.jsx)(H_,{kind:`jsx-component`,ariaLabel:`Component properties`,onDeactivate:i,children:m}),t[16]=i,t[17]=m,t[18]=h):h=t[18],h}var cy=0;function ly(){return`jsx-${++cy}`}function uy(e){let t=e.match(/<(\w+)\s+type="([^"]*)">([\s\S]*?)<\/\1>/);return t?{component:t[1],type:t[2],children:t[3].trim()}:{component:`Unknown`,type:`info`,children:e.trim()}}function dy(e){let t=(0,at.c)(17),{node:n,editor:r,getPos:i}=e,a=n.attrs.content||``,o;t[0]===a?o=t[1]:(o=uy(a),t[0]=a,t[1]=o);let s=o,[c]=(0,J.useState)(ly),l=(0,J.useRef)(i),u,d;t[2]===i?(u=t[3],d=t[4]):(u=()=>{l.current=i},d=[i],t[2]=i,t[3]=u,t[4]=d),(0,J.useEffect)(u,d);let f,p;t[5]!==r||t[6]!==c?(f=()=>{let e=sv(r),t=()=>{let e=l.current();return typeof e==`number`?e:void 0};return e.register({type:`jsxComponent`,nodeId:c,getPos:t,controls:{propPanel:e=>(0,X.jsx)(sy,{editor:r,getPos:t,onDismiss:e.deactivate})}}),()=>{e.deregister(c)}},p=[r,c],t[5]=r,t[6]=c,t[7]=f,t[8]=p):(f=t[7],p=t[8]),(0,J.useEffect)(f,p);let m;t[9]!==a||t[10]!==s.children||t[11]!==s.component||t[12]!==s.type?(m=s.component===`Callout`?(0,X.jsx)(ay,{type:s.type,children:s.children}):(0,X.jsxs)(`div`,{className:`bg-muted dark:bg-muted/40 p-3 px-4 rounded-md font-mono text-[13px]`,children:[(0,X.jsxs)(`strong`,{children:[`<`,s.component,`>`]}),(0,X.jsx)(`pre`,{className:`mt-2 whitespace-pre-wrap`,children:a})]}),t[9]=a,t[10]=s.children,t[11]=s.component,t[12]=s.type,t[13]=m):m=t[13];let h;return t[14]!==c||t[15]!==m?(h=(0,X.jsx)(Tn,{className:`jsx-component-wrapper`,contentEditable:!1,"data-node-id":c,children:m}),t[14]=c,t[15]=m,t[16]=h):h=t[16],h}var fy=Le.extend({addNodeView(){return Nn(dy)}}),py=`raw-mdx-nav`,my=0;function hy(){return`raw-mdx-${++my}`}function gy(e){let t=e.doc??(typeof document<`u`?document:{createElement:null}),n=t.createElement(`div`);n.setAttribute(`data-raw-mdx-fallback`,``),n.setAttribute(`data-raw-badge`,`raw`),n.setAttribute(`data-node-id`,e.nodeId),n.setAttribute(`contenteditable`,`false`),n.setAttribute(`role`,`button`),n.setAttribute(`tabindex`,`0`),n.setAttribute(`aria-label`,`${e.reason??`Parse failed`} — click to edit`),n.classList.add(`raw-mdx-fallback-wrapper`),e.reason&&n.setAttribute(`data-reason`,e.reason);let r=t.createElement(`span`);r.classList.add(`raw-mdx-fallback-badge`),r.textContent=`raw`,r.setAttribute(`aria-hidden`,`true`),n.appendChild(r);let i=t.createElement(`pre`);return i.classList.add(`raw-mdx-fallback-content`),i.setAttribute(`contenteditable`,`false`),n.appendChild(i),{dom:n,contentDOM:i}}var _y=O.extend({addNodeView(){return({editor:e,node:t,getPos:n,HTMLAttributes:r})=>{let i=hy(),{dom:a,contentDOM:o}=gy({nodeId:i,reason:r.reason??t.attrs.reason}),s=()=>{let e=n();return typeof e==`number`?e:void 0},c=sv(e);return c.register({type:`rawMdxFallback`,nodeId:i,getPos:s,controls:{},handlePrimary:()=>{let t=s();if(typeof t!=`number`)return!1;let n=e.state.doc.nodeAt(t)?.attrs.originalSpan??{start:0,end:0};return window.dispatchEvent(new CustomEvent(py,{detail:{offset:n.start}})),!0}}),{dom:a,contentDOM:o,ignoreMutation:()=>!0,destroy:()=>{c.deregister(i)}}}}}),vy=[{name:`heading1`,label:`Heading 1`,icon:We,category:`basic`,command:e=>e.chain().focus().toggleHeading({level:1}).run(),aliases:[`h1`]},{name:`heading2`,label:`Heading 2`,icon:Ge,category:`basic`,command:e=>e.chain().focus().toggleHeading({level:2}).run(),aliases:[`h2`]},{name:`heading3`,label:`Heading 3`,icon:Ke,category:`basic`,command:e=>e.chain().focus().toggleHeading({level:3}).run(),aliases:[`h3`]},{name:`bulletList`,label:`Bullet List`,icon:Xe,category:`basic`,command:e=>e.chain().focus().toggleBulletList().run(),aliases:[`ul`,`unordered`]},{name:`orderedList`,label:`Ordered List`,icon:Je,category:`basic`,command:e=>e.chain().focus().toggleOrderedList().run(),aliases:[`ol`,`numbered`]},{name:`taskList`,label:`Task List`,icon:Ye,category:`basic`,command:e=>e.chain().focus().toggleTaskList().run(),aliases:[`todo`,`checklist`,`checkbox`]},{name:`blockquote`,label:`Quote`,icon:et,category:`basic`,command:e=>e.chain().focus().toggleBlockquote().run(),aliases:[`quote`]},{name:`codeBlock`,label:`Code Block`,icon:ze,category:`basic`,command:e=>e.chain().focus().toggleCodeBlock().run(),aliases:[`code`,`fence`]},{name:`table`,label:`Table`,icon:tt,category:`insert`,command:e=>e.chain().focus().insertTable({rows:3,cols:3,withHeaderRow:!0}).run(),aliases:[`grid`]},{name:`separator`,label:`Separator`,icon:Qe,category:`insert`,command:e=>e.chain().focus().setHorizontalRule().run(),aliases:[`hr`,`divider`,`rule`]},{name:`image`,label:`Image`,icon:qe,category:`insert`,aliases:[`img`,`photo`],command:e=>{let t=document.createElement(`input`);t.type=`file`,t.accept=de.join(`,`),t.onchange=()=>{let n=t.files?.[0];if(n){let t=e.state.selection.from;Dg(n,e,t)}},t.click()}}];function yy(e,t){if(!t)return e;let n=t.toLowerCase();return e.filter(e=>e.label.toLowerCase().includes(n)||e.name.toLowerCase().includes(n)||e.aliases?.some(e=>e.toLowerCase().includes(n)))}function by(e){let t=(0,at.c)(14),{items:n,selectedIndex:r,categoryLabels:i,onSelect:a}=e,o=(0,J.useRef)(null),s=(0,J.useId)(),c=r>=0&&r<n.length?`${s}-option-${r}`:void 0,l=xy,u,d;if(t[0]===r?(u=t[1],d=t[2]):(u=()=>{let e=o.current;if(!e)return;let t=e.querySelectorAll(`[role="option"]`).item(r);t&&t.scrollIntoView({block:`nearest`})},d=[r],t[0]=r,t[1]=u,t[2]=d),(0,J.useEffect)(u,d),n.length===0){let e;return t[3]===Symbol.for(`react.memo_cache_sentinel`)?(e=(0,X.jsx)(`div`,{ref:o,role:`status`,"aria-live":`polite`,className:`w-56 rounded-lg border bg-popover p-2 shadow-md text-sm text-muted-foreground`,style:{maxHeight:`var(--suggestion-menu-max-height, 40vh)`},onMouseDown:l,children:`No results`}),t[3]=e):e=t[3],e}let f;if(t[4]!==c||t[5]!==i||t[6]!==n||t[7]!==s||t[8]!==a||t[9]!==r){let e=[],u=0,d=new Map;for(let t of n){d.set(t,u++);let n=e.find(e=>e.key===t.category);n?n.items.push(t):e.push({key:t.category,items:[t]})}let p=r>=0&&r<n.length?n[r]:null,m;t[11]===Symbol.for(`react.memo_cache_sentinel`)?(m={maxHeight:`var(--suggestion-menu-max-height, 40vh)`},t[11]=m):m=t[11];let h=p?p.label:``,g;t[12]===h?g=t[13]:(g=(0,X.jsx)(`span`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:h}),t[12]=h,t[13]=g),f=(0,X.jsxs)(`div`,{ref:o,role:`listbox`,"aria-label":`Slash commands`,"aria-activedescendant":c,tabIndex:-1,onMouseDown:l,className:`w-56 overflow-y-auto subtle-scrollbar rounded-lg border bg-popover p-1 shadow-md`,style:m,children:[g,e.map(e=>(0,X.jsxs)(`div`,{role:`group`,"aria-labelledby":`${s}-group-${e.key}`,children:[(0,X.jsx)(`div`,{id:`${s}-group-${e.key}`,className:`px-2 py-1.5 text-xs font-semibold text-muted-foreground`,children:i[e.key]??e.key}),e.items.map(e=>{let t=d.get(e)??0,n=t===r,i=e.icon;return(0,X.jsxs)(`button`,{id:`${s}-option-${t}`,type:`button`,role:`option`,"aria-selected":n,"data-selected":n,className:`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-sm text-left ${n?`bg-accent text-accent-foreground`:``}`,onMouseDown:t=>{t.preventDefault(),a(e)},children:[(0,X.jsx)(i,{className:`size-4 shrink-0 text-muted-foreground`}),(0,X.jsx)(`div`,{className:`flex flex-col min-w-0`,children:(0,X.jsx)(`span`,{className:`truncate`,children:e.label})})]},e.name)})]},e.key))]}),t[4]=c,t[5]=i,t[6]=n,t[7]=s,t[8]=a,t[9]=r,t[10]=f}else f=t[10];return f}function xy(e){return e.preventDefault()}var Sy=new be(`slashCommand`),Cy=fe.create({name:`slashCommand`,addOptions(){return{itemsSources:[()=>vy],categoryLabels:{basic:`Basic blocks`,insert:`Insert`}}},addProseMirrorPlugins(){let e=this;return[Sv({editor:this.editor,pluginKey:Sy,char:`/`,startOfLine:!1,items:({query:t})=>yy(e.options.itemsSources.flatMap(e=>{try{return e()}catch(e){return console.error(`[slash-command] item source threw an error`,e),[]}}),t),command:({editor:e,range:t,props:n})=>{try{e.chain().focus().deleteRange(t).run()}catch(e){console.error(`[slash-command] deleteRange failed for "${n.name}"`,e);return}try{n.command(e)}catch(e){console.error(`[slash-command] command "${n.name}" threw an error`,e)}},render:()=>{let t=null,n=null,r=0,i={popup:null,stopAutoUpdate:null},a=null,o=()=>{!t||!n||t.updateProps({items:n.items,selectedIndex:r,categoryLabels:e.options.categoryLabels,onSelect:n.command})};return{onStart(o){n=o,r=0;let s=Ov(()=>n,`slash-command`);i.popup=s.popup,a=s.doPosition,t=new jn(by,{props:{items:o.items,selectedIndex:r,categoryLabels:e.options.categoryLabels,onSelect:o.command},editor:o.editor}),s.popup.appendChild(t.element),i.stopAutoUpdate=s.startAutoUpdate(),s.reveal()},onUpdate(e){n=e,r=Math.min(r,Math.max(0,e.items.length-1)),o(),a?.()},onKeyDown({event:e}){if(!n||n.items.length===0)return!1;let t=n.items;if(e.key===`ArrowDown`)return r=(r+1)%t.length,o(),!0;if(e.key===`ArrowUp`)return r=(r-1+t.length)%t.length,o(),!0;if(e.key===`Enter`||e.key===`Tab`){let e=t[r];return e&&n.command(e),!0}return e.key,!1},onExit(){kv(i),a=null,t?.destroy(),t=null,n=null,r=0}}}})]}});function wy(e){let t=(0,at.c)(112),{open:n,target:r,alias:i,anchor:a,pages:o,onOpenChange:s,onSave:u}=e,[d,f]=(0,J.useState)(r),[h,v]=(0,J.useState)(i??``),[b,x]=(0,J.useState)(a??``),S=(0,J.useId)(),w=(0,J.useId)(),T=(0,J.useId)(),E=(0,J.useId)(),D;t[0]!==d||t[1]!==o?(D=O_(d,o),t[0]=d,t[1]=o,t[2]=D):D=t[2];let O=Hv(d,D&&n),k,A;t[3]!==i||t[4]!==a||t[5]!==n||t[6]!==r?(k=()=>{n&&(f(r),v(i??``),x(a??``))},A=[n,r,i,a],t[3]=i,t[4]=a,t[5]=n,t[6]=r,t[7]=k,t[8]=A):(k=t[7],A=t[8]),(0,J.useEffect)(k,A);let ee;t[9]!==h||t[10]!==b||t[11]!==d||t[12]!==s||t[13]!==u?(ee=function(){let e=d.trim();e&&(u(e,h.trim()||null,b.trim()||null),s(!1))},t[9]=h,t[10]=b,t[11]=d,t[12]=s,t[13]=u,t[14]=ee):ee=t[14];let j=ee,M;t[15]===j?M=t[16]:(M=function(e){e.key===`Enter`&&j()},t[15]=j,t[16]=M);let N=M,P,F,I,L,R,z,B,V,H,U,W,G,K,q,te,ne;if(t[17]!==w||t[18]!==b||t[19]!==d||t[20]!==N||t[21]!==E||t[22]!==O||t[23]!==s||t[24]!==n||t[25]!==S){let e=new Map,r=O?.map(t=>{let n=e.get(t.slug)??0;e.set(t.slug,n+1);let r=n===0?t.slug:`${t.slug}-${n}`;return{...t,reactKey:r}}),i=!!r?.length;I=y,W=n,G=s,F=m,t[42]===Symbol.for(`react.memo_cache_sentinel`)?(U=(0,X.jsx)(p,{className:`fixed inset-0 z-50 bg-black/40 data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0`}),t[42]=U):U=t[42],P=g,R=`dialog-content`,z=``,B=`fixed left-1/2 top-1/2 z-50 w-full max-w-md -translate-x-1/2 -translate-y-1/2 rounded-lg border border-border bg-background p-6 shadow-xl data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95`,t[43]===Symbol.for(`react.memo_cache_sentinel`)?(V=(0,X.jsx)(_,{className:`mb-1 text-base font-semibold`,children:`Edit wiki link`}),H=(0,X.jsx)(C,{className:`mb-4 text-sm text-muted-foreground`,children:`Modify the link target, anchor, and display label.`}),t[43]=V,t[44]=H):(V=t[43],H=t[44]),ne=`mb-4 space-y-6`;let a;t[45]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,X.jsx)(`span`,{className:`text-red-500`,children:`*`}),t[45]=a):a=t[45];let o;t[46]===S?o=t[47]:(o=(0,X.jsxs)(`label`,{className:`mb-1.5 block text-sm font-medium`,htmlFor:S,children:[`Page `,a]}),t[46]=S,t[47]=o);let l;t[48]===Symbol.for(`react.memo_cache_sentinel`)?(l=e=>f(e.target.value),t[48]=l):l=t[48];let u;t[49]!==d||t[50]!==N||t[51]!==S?(u=(0,X.jsx)(G_,{id:S,value:d,onChange:l,placeholder:`page-name`,autoFocus:!0,"aria-required":`true`,onKeyDown:N}),t[49]=d,t[50]=N,t[51]=S,t[52]=u):u=t[52],t[53]!==o||t[54]!==u?(L=(0,X.jsxs)(`div`,{children:[o,u]}),t[53]=o,t[54]=u,t[55]=L):L=t[55];let h;t[56]===Symbol.for(`react.memo_cache_sentinel`)?(h=(0,X.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`(optional heading anchor)`}),t[56]=h):h=t[56],t[57]===w?K=t[58]:(K=(0,X.jsxs)(`label`,{className:`mb-1.5 block text-sm font-medium`,htmlFor:w,children:[`Section`,` `,h]}),t[57]=w,t[58]=K);let v;t[59]===Symbol.for(`react.memo_cache_sentinel`)?(v=e=>x(e.target.value),t[59]=v):v=t[59],t[60]!==w||t[61]!==b||t[62]!==N?(q=(0,X.jsx)(G_,{id:w,value:b,onChange:v,placeholder:`heading-slug`,onKeyDown:N}),t[60]=w,t[61]=b,t[62]=N,t[63]=q):q=t[63],te=i&&(0,X.jsx)(`div`,{role:`listbox`,id:E,"aria-label":`Heading anchors`,className:`mt-1.5 max-h-36 overflow-y-auto subtle-scrollbar rounded-md border border-border bg-muted/30`,children:r.map(e=>(0,X.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":b===e.slug,className:c(`flex w-full items-center gap-2 px-2 py-1 text-left text-sm hover:bg-accent hover:text-accent-foreground`,b===e.slug&&`bg-accent text-accent-foreground`),style:{paddingLeft:`${(e.level-1)*12+8}px`},onClick:()=>x(b===e.slug?``:e.slug),children:[(0,X.jsxs)(`span`,{className:`w-7 shrink-0 font-mono text-[10px] text-muted-foreground`,children:[`H`,e.level]}),(0,X.jsx)(`span`,{className:`truncate`,children:e.text})]},e.reactKey))}),t[17]=w,t[18]=b,t[19]=d,t[20]=N,t[21]=E,t[22]=O,t[23]=s,t[24]=n,t[25]=S,t[26]=P,t[27]=F,t[28]=I,t[29]=L,t[30]=R,t[31]=z,t[32]=B,t[33]=V,t[34]=H,t[35]=U,t[36]=W,t[37]=G,t[38]=K,t[39]=q,t[40]=te,t[41]=ne}else P=t[26],F=t[27],I=t[28],L=t[29],R=t[30],z=t[31],B=t[32],V=t[33],H=t[34],U=t[35],W=t[36],G=t[37],K=t[38],q=t[39],te=t[40],ne=t[41];let re;t[64]!==K||t[65]!==q||t[66]!==te?(re=(0,X.jsxs)(`div`,{children:[K,q,te]}),t[64]=K,t[65]=q,t[66]=te,t[67]=re):re=t[67];let ie;t[68]===Symbol.for(`react.memo_cache_sentinel`)?(ie=(0,X.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`(optional display text)`}),t[68]=ie):ie=t[68];let ae;t[69]===T?ae=t[70]:(ae=(0,X.jsxs)(`label`,{className:`mb-1.5 block text-sm font-medium`,htmlFor:T,children:[`Label`,` `,ie]}),t[69]=T,t[70]=ae);let oe;t[71]===Symbol.for(`react.memo_cache_sentinel`)?(oe=e=>v(e.target.value),t[71]=oe):oe=t[71];let se;t[72]!==T||t[73]!==h||t[74]!==N?(se=(0,X.jsx)(G_,{id:T,value:h,onChange:oe,placeholder:`Custom display text`,onKeyDown:N}),t[72]=T,t[73]=h,t[74]=N,t[75]=se):se=t[75];let ce;t[76]!==ae||t[77]!==se?(ce=(0,X.jsxs)(`div`,{children:[ae,se]}),t[76]=ae,t[77]=se,t[78]=ce):ce=t[78];let le;t[79]!==L||t[80]!==re||t[81]!==ce||t[82]!==ne?(le=(0,X.jsxs)(`div`,{className:ne,children:[L,re,ce]}),t[79]=L,t[80]=re,t[81]=ce,t[82]=ne,t[83]=le):le=t[83];let ue;t[84]===s?ue=t[85]:(ue=(0,X.jsx)(l,{variant:`outline`,onClick:()=>s(!1),children:`Cancel`}),t[84]=s,t[85]=ue);let de;t[86]===d?de=t[87]:(de=d.trim(),t[86]=d,t[87]=de);let fe=!de,pe;t[88]!==j||t[89]!==fe?(pe=(0,X.jsx)(l,{onClick:j,disabled:fe,children:`Save`}),t[88]=j,t[89]=fe,t[90]=pe):pe=t[90];let me;t[91]!==ue||t[92]!==pe?(me=(0,X.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[ue,pe]}),t[91]=ue,t[92]=pe,t[93]=me):me=t[93];let he;t[94]!==P||t[95]!==R||t[96]!==z||t[97]!==B||t[98]!==V||t[99]!==H||t[100]!==le||t[101]!==me?(he=(0,X.jsxs)(P,{"data-slot":R,"data-ok-layer-spawned":z,className:B,children:[V,H,le,me]}),t[94]=P,t[95]=R,t[96]=z,t[97]=B,t[98]=V,t[99]=H,t[100]=le,t[101]=me,t[102]=he):he=t[102];let ge;t[103]!==F||t[104]!==U||t[105]!==he?(ge=(0,X.jsxs)(F,{children:[U,he]}),t[103]=F,t[104]=U,t[105]=he,t[106]=ge):ge=t[106];let _e;return t[107]!==I||t[108]!==W||t[109]!==G||t[110]!==ge?(_e=(0,X.jsx)(I,{open:W,onOpenChange:G,children:ge}),t[107]=I,t[108]=W,t[109]=G,t[110]=ge,t[111]=_e):_e=t[111],_e}function Ty(e){let t=(0,at.c)(112),{editor:n,getPos:r,onClose:i}=e,a=r(),o=a==null?null:n.state.doc.nodeAt(a),s=String(o?.attrs.target??``),u=te(o?.attrs.alias),d=te(o?.attrs.anchor),f=M({target:s,alias:u,anchor:d}),{folderPaths:p,pages:m,loading:h}=Te(),g=V(s,d),_=g?.kind===`external`?g:null,v=U_(s,{pages:m,folderPaths:p,fallbackTargets:D_(s)}),[y,b]=(0,J.useState)(!1),[x,S]=(0,J.useState)(null),C=W_(v);if(!o)return null;let w;t[0]!==n||t[1]!==r?(w=function(e,t,i){let a=r();a!=null&&n.view.dispatch(n.state.tr.setNodeMarkup(a,void 0,{...n.state.doc.nodeAt(a)?.attrs,target:e,alias:t,anchor:i}))},t[0]=n,t[1]=r,t[2]=w):w=t[2];let T=w,E;t[3]!==n||t[4]!==r||t[5]!==i?(E=function(){let e=r();if(e==null)return;let t=n.state.doc.nodeAt(e);t&&(n.view.dispatch(n.state.tr.delete(e,e+t.nodeSize)),i())},t[3]=n,t[4]=r,t[5]=i,t[6]=E):E=t[6];let D=E,O;t[7]!==d||t[8]!==_||t[9]!==v||t[10]!==S?(O=function(e){if(_){j_(_.url)?window.open(_.url,`_blank`,`noopener,noreferrer`):console.warn(`[safe-nav] blocked non-safe scheme:`,_.url);return}if(v.kind===`create`){S(`missing`);return}let t=v.hashDocName;if(e.newTab){L_({docName:t,anchor:d});return}if(d){let e=window.location.hash.match(/^#\/([^?#/]+)/);if((e?decodeURIComponent(e[1]):null)===t){let e=document.getElementById(d);e&&e.scrollIntoView({behavior:`smooth`,block:`start`})}window.location.hash=`#/${t}?anchor=${encodeURIComponent(d)}`;return}window.location.hash=`#/${t}`},t[7]=d,t[8]=_,t[9]=v,t[10]=S,t[11]=O):O=t[11];let k=O,A;t[12]!==u||t[13]!==x||t[14]!==n||t[15]!==r||t[16]!==f||t[17]!==s?(A=function(e){if(x===`missing`&&e!==s){let t=r();if(t==null)return;n.view.dispatch(n.state.tr.setNodeMarkup(t,void 0,{...n.state.doc.nodeAt(t)?.attrs,target:e,alias:u??f}))}},t[12]=u,t[13]=x,t[14]=n,t[15]=r,t[16]=f,t[17]=s,t[18]=A):A=t[18];let ee=A,j=!_&&!h&&v.kind===`navigate`&&v.displayState===`resolved`,N=!_&&!h&&v.kind===`navigate`&&v.displayState===`folder`,P=!_&&!h&&v.kind===`create`,F,I,L,R,z,B,H,U,W;if(t[19]!==_||t[20]!==N||t[21]!==j||t[22]!==P||t[23]!==h||t[24]!==i){if(h){let e;t[34]===Symbol.for(`react.memo_cache_sentinel`)?(e=(0,X.jsx)(Ze,{className:`size-3.5 shrink-0 animate-spin`,"aria-hidden":`true`}),t[34]=e):e=t[34],I={icon:e,text:`Loading…`,className:`text-muted-foreground`}}else if(_){let e;t[35]===Symbol.for(`react.memo_cache_sentinel`)?(e=(0,X.jsx)(Be,{className:`size-3.5 shrink-0`,"aria-hidden":`true`}),t[35]=e):e=t[35],I={icon:e,text:`External wiki link`,className:`text-foreground`}}else if(N){let e;t[36]===Symbol.for(`react.memo_cache_sentinel`)?(e=(0,X.jsx)(Ue,{className:`size-3.5 shrink-0`,"aria-hidden":`true`}),t[36]=e):e=t[36],I={icon:e,text:`Folder (no index)`,className:`text-foreground`}}else if(P){let e;t[37]===Symbol.for(`react.memo_cache_sentinel`)?(e=(0,X.jsx)(Re,{className:`size-3.5 shrink-0`,"aria-hidden":`true`}),t[37]=e):e=t[37],I={icon:e,text:`Page not found`,className:`text-red-700 dark:text-red-300`}}else if(j){let e;t[38]===Symbol.for(`react.memo_cache_sentinel`)?(e=(0,X.jsx)(He,{className:`size-3.5 shrink-0`,"aria-hidden":`true`}),t[38]=e):e=t[38],I={icon:e,text:`Wiki link`,className:`text-foreground`}}else{let e;t[39]===Symbol.for(`react.memo_cache_sentinel`)?(e=(0,X.jsx)(Re,{className:`size-3.5 shrink-0`,"aria-hidden":`true`}),t[39]=e):e=t[39],I={icon:e,text:`Unrecognized wiki link`,className:`text-muted-foreground`}}F=H_,W=`wiki-link`,L=`Wiki link options`,R=i,H=`mb-2 flex items-start gap-2 pr-8`,U=(0,X.jsx)(`div`,{className:c(`mt-0.5 flex shrink-0`,I.className),children:I.icon}),B=`flex-1 min-w-0`,z=c(`text-sm font-medium`,I.className),t[19]=_,t[20]=N,t[21]=j,t[22]=P,t[23]=h,t[24]=i,t[25]=F,t[26]=I,t[27]=L,t[28]=R,t[29]=z,t[30]=B,t[31]=H,t[32]=U,t[33]=W}else F=t[25],I=t[26],L=t[27],R=t[28],z=t[29],B=t[30],H=t[31],U=t[32],W=t[33];let G;t[40]!==I.text||t[41]!==z?(G=(0,X.jsx)(`div`,{className:z,children:I.text}),t[40]=I.text,t[41]=z,t[42]=G):G=t[42];let K=_?_.url:`[[${s}${d?`#${d}`:``}]]`,q=_?_.url:`[[${s}${d?`#${d}`:``}]]`,ne;t[43]!==K||t[44]!==q?(ne=(0,X.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,title:K,children:q}),t[43]=K,t[44]=q,t[45]=ne):ne=t[45];let re;t[46]!==G||t[47]!==ne||t[48]!==B?(re=(0,X.jsxs)(`div`,{className:B,children:[G,ne]}),t[46]=G,t[47]=ne,t[48]=B,t[49]=re):re=t[49];let ie;t[50]!==re||t[51]!==H||t[52]!==U?(ie=(0,X.jsxs)(`div`,{className:H,children:[U,re]}),t[50]=re,t[51]=H,t[52]=U,t[53]=ie):ie=t[53];let ae;t[54]!==_||t[55]!==k||t[56]!==P||t[57]!==i?(ae=P?null:(0,X.jsx)(l,{size:`sm`,variant:`default`,onClick:()=>{k({}),i()},children:_?`Open in new tab`:`Open`}),t[54]=_,t[55]=k,t[56]=P,t[57]=i,t[58]=ae):ae=t[58];let oe;t[59]!==P||t[60]!==S?(oe=P?(0,X.jsx)(l,{size:`sm`,variant:`default`,onClick:()=>S(`missing`),children:`Create page`}):null,t[59]=P,t[60]=S,t[61]=oe):oe=t[61];let se;t[62]!==C||t[63]!==N||t[64]!==S?(se=N&&C?(0,X.jsxs)(l,{size:`sm`,variant:`outline`,onClick:()=>S(`folder-index`),children:[(0,X.jsx)(Ve,{className:`size-3.5`,"aria-hidden":`true`}),`Create index`]}):null,t[62]=C,t[63]=N,t[64]=S,t[65]=se):se=t[65];let ce;t[66]===b?ce=t[67]:(ce=()=>b(!0),t[66]=b,t[67]=ce);let le;t[68]===Symbol.for(`react.memo_cache_sentinel`)?(le=(0,X.jsx)($e,{className:`size-3.5`,"aria-hidden":`true`}),t[68]=le):le=t[68];let ue;t[69]===ce?ue=t[70]:(ue=(0,X.jsxs)(l,{size:`sm`,variant:`outline`,onClick:ce,children:[le,`Edit`]}),t[69]=ce,t[70]=ue);let de;t[71]===Symbol.for(`react.memo_cache_sentinel`)?(de=(0,X.jsx)(nt,{className:`size-3.5`,"aria-hidden":`true`}),t[71]=de):de=t[71];let fe;t[72]===D?fe=t[73]:(fe=(0,X.jsxs)(l,{size:`sm`,variant:`outline`,className:`text-red-700 hover:bg-red-50 hover:text-red-800 dark:text-red-300 dark:hover:bg-red-100/10 dark:hover:text-red-200`,onClick:D,children:[de,`Remove`]}),t[72]=D,t[73]=fe);let pe;t[74]!==ae||t[75]!==oe||t[76]!==se||t[77]!==ue||t[78]!==fe?(pe=(0,X.jsxs)(`div`,{className:`flex flex-wrap gap-1.5`,children:[ae,oe,se,ue,fe]}),t[74]=ae,t[75]=oe,t[76]=se,t[77]=ue,t[78]=fe,t[79]=pe):pe=t[79];let me;t[80]!==F||t[81]!==L||t[82]!==R||t[83]!==ie||t[84]!==pe||t[85]!==W?(me=(0,X.jsxs)(F,{kind:W,ariaLabel:L,onDeactivate:R,children:[ie,pe]}),t[80]=F,t[81]=L,t[82]=R,t[83]=ie,t[84]=pe,t[85]=W,t[86]=me):me=t[86];let he=x!==null,ge;t[87]===S?ge=t[88]:(ge=e=>{e||S(null)},t[87]=S,t[88]=ge);let _e=x===`folder-index`&&C?C.initialDir:v.kind===`create`?v.initialDir:``,ve=x===`folder-index`&&C?C.suggestedName:v.kind===`create`?v.suggestedName:void 0,ye;t[89]!==x||t[90]!==C||t[91]!==s?(ye=x===`folder-index`&&C?(0,X.jsxs)(X.Fragment,{children:[`Create an index note for`,` `,(0,X.jsxs)(`span`,{className:`font-medium text-foreground`,children:[C.initialDir,`/`]})]}):(0,X.jsxs)(X.Fragment,{children:[`Create a page for `,(0,X.jsx)(`span`,{className:`font-medium text-foreground`,children:s})]}),t[89]=x,t[90]=C,t[91]=s,t[92]=ye):ye=t[92];let be;t[93]!==ee||t[94]!==he||t[95]!==ge||t[96]!==_e||t[97]!==ve||t[98]!==ye?(be=(0,X.jsx)(Z_,{open:he,onOpenChange:ge,kind:`file`,initialDir:_e,suggestedName:ve,description:ye,onCreated:ee}),t[93]=ee,t[94]=he,t[95]=ge,t[96]=_e,t[97]=ve,t[98]=ye,t[99]=be):be=t[99];let xe;t[100]!==u||t[101]!==d||t[102]!==y||t[103]!==T||t[104]!==m||t[105]!==b||t[106]!==s?(xe=(0,X.jsx)(wy,{open:y,target:s,alias:u,anchor:d,pages:m,onOpenChange:b,onSave:T}),t[100]=u,t[101]=d,t[102]=y,t[103]=T,t[104]=m,t[105]=b,t[106]=s,t[107]=xe):xe=t[107];let Se;return t[108]!==me||t[109]!==be||t[110]!==xe?(Se=(0,X.jsxs)(X.Fragment,{children:[me,be,xe]}),t[108]=me,t[109]=be,t[110]=xe,t[111]=Se):Se=t[111],Se}var Ey=0;function Dy(){return`wiki-link-${++Ey}`}function Oy(e){let t=e.doc??(typeof document<`u`?document:{createElement:null,createTextNode:null}),n=t.createElement(`span`);n.setAttribute(`data-wiki-link`,``),n.setAttribute(`data-node-id`,e.nodeId),n.setAttribute(`data-target`,e.target),n.setAttribute(`data-alias`,e.alias??``),n.setAttribute(`data-anchor`,e.anchor??``),n.setAttribute(`contenteditable`,`false`),n.setAttribute(`role`,`button`),n.setAttribute(`tabindex`,`0`),n.setAttribute(`aria-label`,`Wiki link: ${e.target}${e.anchor?`#${e.anchor}`:``}`),n.classList.add(`wiki-link-chip`),n.style.touchAction=`manipulation`;let r=e.alias??`${e.target}${e.anchor?`#${e.anchor}`:``}`,i=t.createTextNode(r);return n.appendChild(i),{dom:n}}var ky=ee.extend({priority:200,addNodeView(){return({editor:e,node:t,getPos:n})=>{let r=Dy(),{dom:i}=Oy({nodeId:r,target:String(t.attrs.target??``),alias:t.attrs.alias==null?null:String(t.attrs.alias),anchor:t.attrs.anchor==null?null:String(t.attrs.anchor)}),a=t,o=()=>{let e=n();return typeof e==`number`?e:void 0},s=sv(e);return s.register({type:`wikiLink`,nodeId:r,getPos:o,controls:{propPanel:t=>(0,J.createElement)(Ty,{editor:e,getPos:o,onClose:t.deactivate})},handlePrimary:({newTab:e})=>{if(!e)return!1;let t=a.attrs,n=typeof t.target==`string`?t.target:``;if(!n)return!1;let r=V(n,typeof t.anchor==`string`?t.anchor:null);return r?r.kind===`doc`?(L_({docName:r.docName,anchor:r.anchor}),!0):j_(r.url)?(F_(r.url),!0):!1:!1}}),{dom:i,ignoreMutation:()=>!0,update:e=>{if(e.type.name!==`wikiLink`)return!1;a=e;let t=String(e.attrs.target??``),n=e.attrs.alias==null?null:String(e.attrs.alias),r=e.attrs.anchor==null?null:String(e.attrs.anchor);return i.setAttribute(`data-target`,t),i.setAttribute(`data-alias`,n??``),i.setAttribute(`data-anchor`,r??``),i.setAttribute(`aria-label`,`Wiki link: ${t}${r?`#${r}`:``}`),i.textContent=n??`${t}${r?`#${r}`:``}`,!0},destroy:()=>{s.deregister(r)}}}},addKeyboardShortcuts(){return{Backspace:()=>{if(Av.getState(this.editor.state)?.active)return!1;let{selection:e}=this.editor.state;if(!e.empty)return!1;let t=e.$from.nodeBefore;if(t?.type.name===`wikiLink`){let{state:n,view:r}=this.editor;return r.dispatch(n.tr.delete(e.from-t.nodeSize,e.from)),!0}return!1},Delete:()=>{if(Av.getState(this.editor.state)?.active)return!1;let{selection:e}=this.editor.state;if(!e.empty)return!1;let t=e.$from.nodeAfter;if(t?.type.name===`wikiLink`){let{state:n,view:r}=this.editor;return r.dispatch(n.tr.delete(e.from,e.from+t.nodeSize)),!0}return!1}}},addProseMirrorPlugins(){return[Vv(this.editor)]}}),Ay=[...re.map(e=>e.name===`jsxComponent`?fy:e.name===`rawMdxFallback`?_y:e.name===`wikiLink`?ky:e.name===`link`?ny:e),Cy,xg.configure({allowedMimeTypes:[...de],onDrop(e,t,n){for(let r of t)Dg(r,e,n)},onPaste(e,t,n){for(let n of t)Dg(n,e,e.state.selection.from)}}),k_,T_,Mg];function jy(e){return e===Pe}function My(){}function Ny(e){let{xmlFragment:t,ytext:n}=e,r=(e,t)=>{},i=(e,t)=>{};return t.observeDeep(r),n.observe(i),()=>{t.unobserveDeep(r),n.unobserve(i)}}var Py=3e4,Fy=class extends Error{docName;elapsedMs;constructor(e,t){super(`Sync timed out for "${e}" after ${t}ms`),this.name=`SyncTimeoutError`,this.docName=e,this.elapsedMs=t}},Iy=class extends Error{docName;constructor(e){super(`Provider disconnected before sync for "${e}"`),this.name=`PreSyncDisconnectError`,this.docName=e}},Ly=class extends Error{docName;constructor(e){super(`Document not found: "${e}"`),this.name=`DocumentNotFoundError`,this.docName=e}},Ry=class extends Error{docName;cause;constructor(e,t){let n=t instanceof Error?t.message:String(t??`unknown`);super(`Bridge setup failed for "${e}": ${n}`),this.name=`BridgeSetupError`,this.docName=e,this.cause=t}},zy=new Map,By=!1;function Vy(){for(let e of zy.values())if(!e.settled)return!0;return!1}function Hy(){typeof document>`u`||document.visibilityState===`visible`&&Uy(Date.now())}function Uy(e){let t=[];for(let[n,r]of zy){if(r.settled)continue;let i=e-r.createdAt;if(i<3e4)continue;r.settled=!0;let a=new Fy(n,i);qy(r),r.reject(a),t.push({docName:n,elapsedMs:i})}if(t.length>0){let e=t.map(e=>`${e.docName} (${e.elapsedMs}ms)`).join(`, `);console.warn(`[syncPromise] reaped ${t.length} timed-out ${t.length===1?`entry`:`entries`} on visibility restore (tab-sleep recovered): ${e}`)}return Vy()||Gy(),t.length}function Wy(){By||typeof document>`u`||(document.addEventListener(`visibilitychange`,Hy),By=!0)}function Gy(){By&&(typeof document>`u`||(document.removeEventListener(`visibilitychange`,Hy),By=!1))}var Ky=new Map;function qy(e){e.detached||(e.detached=!0,e.timeoutHandle!==null&&clearTimeout(e.timeoutHandle),e.provider.off(`synced`,e.onSynced),e.provider.off(`close`,e.onClose))}function Jy(e,t){let n=zy.get(e);if(n)return n.promise;let r=Ky.get(e);if(r!==void 0){Ky.delete(e);let n=r===`timeout`?new Fy(e,0):new Iy(e);console.warn(`[syncPromise] ${e} rejected on creation (test hook, armed ${r}): ${n.message}`),Y(`ok/sync/create`,{docName:e,warm:!1,armed:r}),Y(`ok/sync/reject`,{docName:e,reason:`armed-${r}`});let i=Xy(n);return zy.set(e,Zy(i,t)),i}if(t.synced){console.log(`[syncPromise] ${e} resolved synchronously (warm provider)`),Y(`ok/sync/create`,{docName:e,warm:!0}),Y(`ok/sync/resolve`,{docName:e,elapsedMs:0,warm:!0});let n=Promise.resolve();return zy.set(e,Yy(n,t)),n}let i=Date.now(),a=()=>{},o=()=>{},s=new Promise((e,t)=>{a=e,o=t}),c=()=>{let t=zy.get(e);if(!t||t.settled)return;t.settled=!0;let n=Date.now()-t.createdAt;console.log(`[syncPromise] ${e} resolved in ${n}ms`),Y(`ok/sync/resolve`,{docName:e,elapsedMs:n,warm:!1}),qy(t),Vy()||Gy(),t.resolve()},l=t=>{let n=zy.get(e);if(!n||n.settled)return;n.settled=!0;let r=new Iy(e);console.warn(`[syncPromise] ${e} rejected: ${r.message}`),Y(`ok/sync/reject`,{docName:e,reason:`pre-sync-disconnect`}),qy(n),Vy()||Gy(),n.reject(r)},u=setTimeout(()=>{let t=zy.get(e);if(!t||t.settled)return;t.settled=!0;let n=Date.now()-t.createdAt,r=new Fy(e,n);console.warn(`[syncPromise] ${e} rejected: ${r.message}`),Y(`ok/sync/reject`,{docName:e,reason:`timeout`,elapsedMs:n}),qy(t),Vy()||Gy(),t.reject(r)},Py),d={promise:s,resolve:a,reject:o,createdAt:i,timeoutHandle:u,provider:t,onSynced:c,onClose:l,settled:!1,detached:!1};return zy.set(e,d),t.on(`synced`,c),t.on(`close`,l),Wy(),Y(`ok/sync/create`,{docName:e,warm:!1}),s}function Yy(e,t){return{promise:e,resolve:()=>{},reject:()=>{},createdAt:Date.now(),timeoutHandle:null,provider:t,onSynced:()=>{},onClose:()=>{},settled:!0,detached:!0}}function Xy(e){let t=Promise.reject(e);t.catch(()=>{});let n=t;return n.status=`rejected`,n.reason=e,n}function Zy(e,t){return{promise:e,resolve:()=>{},reject:()=>{},createdAt:Date.now(),timeoutHandle:null,provider:t,onSynced:()=>{},onClose:()=>{},settled:!0,detached:!0}}function Qy(e){let t=zy.get(e);t&&(t.settled=!0,qy(t),zy.delete(e),Vy()||Gy())}function $y(e,t){let n=zy.get(e);return!n||n.settled?!1:(n.settled=!0,console.warn(`[syncPromise] ${e} rejected: ${t.message}`),qy(n),Vy()||Gy(),n.reject(t),!0)}var eb=Object.freeze({kind:`tab-replay`}),tb=ie(Ay),nb=4e3,rb=`ok-last-observed-branch`,ib=5e3,ab=1*1024*1024;function ob(e,t,n=null){let r={};if(e!==null&&(r.principalId=e.principalId,r.tabSessionId=e.tabSessionId),t!==null&&t.length>0&&(r.expectedServerInstanceId=t),n!==null&&n.length>0&&(r.expectedBranch=n),Object.keys(r).length!==0)return JSON.stringify(r)}var sb=class{_entries=new Map;get entries(){return this._entries}lruOrder=[];activeDocName=null;maxSize;wsUrl;recycleDebounceMs;onChange=null;tabIdentity=null;cachedServerInstanceId=null;bufferedUpdates=new Map;storage;constructor(e,t,n){this.maxSize=e,this.wsUrl=t,this.recycleDebounceMs=n?.recycleDebounceMs??nb,n?.storage===void 0?this.storage=globalThis.localStorage===void 0?null:globalThis.localStorage:this.storage=n.storage}setTabIdentity(e){this.tabIdentity=e}setExpectedServerInstanceId(e){this.cachedServerInstanceId!==e&&(this.cachedServerInstanceId=e)}observeDiskAck(e,t){let n=this.entries.get(e);!n||n.kind!==`active`||(n.lastDiskAckedSV=vg(n.lastDiskAckedSV,t))}observeDiskAckBatch(e){for(let[t,n]of Object.entries(e))this.observeDiskAck(t,n)}lastObservedBranch=null;lastObservedBranchInitialized=!1;getOrInitObservedBranch(){if(this.lastObservedBranchInitialized)return this.lastObservedBranch;this.lastObservedBranchInitialized=!0;try{let e=this.storage?.getItem(rb)??null;e!==null&&e.length>0&&(this.lastObservedBranch=e)}catch{}return this.lastObservedBranch}persistObservedBranch(e){this.lastObservedBranch=e,this.lastObservedBranchInitialized=!0;try{e===null||e.length===0?this.storage?.removeItem(rb):this.storage?.setItem(rb,e)}catch{}}setObservedBranch(e){this.persistObservedBranch(e)}compareAndUpdateObservedBranch(e){let t=this.getOrInitObservedBranch();return this.persistObservedBranch(e),t!==null&&t!==e}onBranchMismatch=null;branchMismatchInFlight=null;setOnBranchMismatch(e){if(e===null){this.onBranchMismatch=null;return}this.onBranchMismatch=()=>{if(this.branchMismatchInFlight!==null)return;let t=Promise.resolve().then(e).finally(()=>{this.branchMismatchInFlight===t&&(this.branchMismatchInFlight=null)});this.branchMismatchInFlight=t}}setOnChange(e){this.onChange=e}notify(){this.onChange?.()}evictListeners=new Set;onEvict(e){return this.evictListeners.add(e),()=>{this.evictListeners.delete(e)}}fireEvict(e){for(let t of this.evictListeners)try{t(e)}catch(t){console.warn(`[ProviderPool] evict listener threw for ${e}:`,t)}}touch(e){let t=this.lruOrder.indexOf(e);t!==-1&&this.lruOrder.splice(t,1),this.lruOrder.push(e)}open(e){if(jy(e))return null;let t=this.entries.get(e);if(t)return t.lastAccessedAt=Date.now(),this.touch(e),this.notify(),t;this.entries.size>=this.maxSize&&this.evictLru();let n=ob(this.tabIdentity,this.cachedServerInstanceId,this.getOrInitObservedBranch()),r=new Wh({url:yg(this.wsUrl),name:e,forceSyncInterval:ib,...n===void 0?{}:{token:n}}),i={kind:`active`,provider:r,persistence:hg({branch:this.getOrInitObservedBranch()??`_unknown_`,docName:e,doc:r.document}),lastServerSyncedSV:null,lastDiskAckedSV:null,observerCleanup:null,syncState:`connecting`,docName:e,lastAccessedAt:Date.now(),hasSynced:!1,pendingRecycleTimer:null,bridgeSetupFailed:!1};if(r.on(`status`,({status:t})=>{i.kind!==`active`||this.entries.get(e)!==i||t===`disconnected`&&(i.syncState=`disconnected`,this.notify())}),r.on(`synced`,()=>{if(!(i.kind!==`active`||this.entries.get(e)!==i)&&(i.syncState=`synced`,i.hasSynced=!0,i.lastServerSyncedSV=gg(r.document),i.pendingRecycleTimer&&=(clearTimeout(i.pendingRecycleTimer),null),this.notify(),!i.observerCleanup))try{let t=r.document,n=new Fe({extensions:Ay});i.observerCleanup=Ny({doc:t,xmlFragment:t.getXmlFragment(`default`),ytext:t.getText(`source`),mdManager:n,schema:tb,onSyncError:(t,n)=>{console.warn(`[Sync] ${t} failed for ${e}:`,n.message)}})}catch(t){console.error(`[ProviderPool] setupObservers init failed for ${e}:`,t),i.bridgeSetupFailed=!0,$y(e,new Ry(e,t))}}),r.on(`disconnect`,()=>{i.kind!==`active`||this.entries.get(e)!==i||(i.syncState=`disconnected`,this.notify(),i.hasSynced&&r.unsyncedChanges===0&&!i.pendingRecycleTimer&&(i.pendingRecycleTimer=setTimeout(()=>{i.kind===`active`&&(i.pendingRecycleTimer=null,this.entries.get(e)===i&&this.recycleDisconnectedEntry(e))},this.recycleDebounceMs)))}),r.on(`authenticationFailed`,({reason:e})=>{if(![`server-instance-mismatch`,`branch-mismatch`].includes(e)){console.warn(JSON.stringify({event:`ok-auth-failed-unknown-reason`,reason:e}));return}let t=e;if(t===`server-instance-mismatch`){if(this.cachedServerInstanceId===null)return;this.cachedServerInstanceId=null,this.handleServerInstanceMismatch();return}if(t===`branch-mismatch`){this.onBranchMismatch?.();return}}),this.bufferedUpdates.get(e)!==void 0){let t=()=>{if(r.off(`synced`,t),i.kind!==`active`||this.entries.get(e)!==i)return;let n=this.bufferedUpdates.get(e);if(n!==void 0){this.bufferedUpdates.delete(e);try{Bs(r.document,n,eb)}catch(t){console.warn(JSON.stringify({event:`ok-buffer-replay-failed`,docName:e,bytes:n.byteLength,reason:t instanceof Error?t.message:String(t)}))}}};r.on(`synced`,t)}return this._entries.set(e,i),this.touch(e),this.notify(),i}handleServerInstanceMismatch(){let e=Array.from(this.entries.entries());for(let[t,n]of e){if(n.kind!==`active`)continue;let e=n.lastDiskAckedSV??n.lastServerSyncedSV;if(e===null)continue;let r=_g(n.provider.document,e);if(r.byteLength>ab){Y(`ok/pool/buffer-overflow`,{docName:t,bytes:r.byteLength});continue}r.byteLength>0&&this.bufferedUpdates.set(t,r)}let t=[];for(let[n,r]of e)r.kind===`active`&&t.push({docName:n,promise:r.persistence.clearData()});Promise.allSettled(t.map(e=>e.promise)).then(e=>{let n=[],r=[];if(e.forEach((e,i)=>{let a=t[i]?.docName??`<unknown>`;e.status===`rejected`?(n.push(a),console.warn(JSON.stringify({event:`ok-client-persistence-clear-failed`,docName:a,reason:e.reason instanceof Error?e.reason.message:String(e.reason)}))):r.push(a)}),n.length>0){console.warn(JSON.stringify({event:`ok-mismatch-recycle-partial-clears-failed`,failedDocs:n,clearedDocs:r}));for(let e of r)this.recycleDisconnectedEntry(e);return}this.recycleAllEntries()})}recycleAllEntries(){let e=Array.from(this.entries.keys());for(let t of e)this.recycleDisconnectedEntry(t)}prewarm(e){if(jy(e))return null;let t=this.entries.get(e);if(t)return t;let n=this.open(e);if(!n)return null;let r=this.lruOrder.indexOf(e);return r!==-1&&(this.lruOrder.splice(r,1),this.lruOrder.unshift(e)),n}close(e){let t=this.entries.get(e);t&&(this.destroyEntry(t),this._entries.delete(e),this.lruOrder=this.lruOrder.filter(t=>t!==e),this.bufferedUpdates.delete(e),this.activeDocName===e&&(this.activeDocName=null),this.notify())}clearBufferedUpdates(){this.bufferedUpdates.clear()}__test_seedBufferedUpdate(e,t){this.bufferedUpdates.set(e,t)}__test_bufferedUpdatesSize(){return this.bufferedUpdates.size}__test_hasBufferedUpdate(e){return this.bufferedUpdates.has(e)}__test_getBufferedUpdate(e){return this.bufferedUpdates.get(e)}setActive(e){let t=this.entries.get(e);if(!t)throw Error(`[ProviderPool] Cannot setActive — "${e}" is not open`);t.lastAccessedAt=Date.now(),this.touch(e),this.activeDocName=e,this.notify()}clearActive(){this.activeDocName!==null&&(this.activeDocName=null,this.notify())}getActive(){return this.activeDocName?this.entries.get(this.activeDocName)??null:null}getActiveDocName(){return this.activeDocName}has(e){return this.entries.has(e)}recycle(e){this.recycleDisconnectedEntry(e)}dispose(){for(let e of this._entries.values())this.destroyEntry(e);this._entries.clear(),this.lruOrder=[],this.activeDocName=null,this.onChange=null,this.bufferedUpdates.clear(),this.onBranchMismatch=null,this.branchMismatchInFlight=null,this.evictListeners.clear(),this.cachedServerInstanceId=null,this.tabIdentity=null}evictLru(){for(let e of this.lruOrder)if(e!==this.activeDocName){Y(`ok/pool/evict-lru`,{docName:e}),this.close(e);return}}destroyEntry(e){if(e.kind===`tearing-down`)return;let t=e.observerCleanup,n=e.persistence,r=e.pendingRecycleTimer,i=e.docName,a=e;a.kind=`tearing-down`,a.persistence=null,a.observerCleanup=null,a.pendingRecycleTimer=null,r&&clearTimeout(r),Qy(i),this.fireEvict(i),t?.(),n.destroy().catch(e=>{console.warn(`[ProviderPool] persistence destroy failed for ${i}:`,e)});try{a.provider.destroy()}catch(e){console.warn(`[ProviderPool] Provider destroy failed for ${i}:`,e)}}recycleDisconnectedEntry(e){let t=this.entries.get(e);if(!t||t.kind!==`active`)return;let n=this.activeDocName===e;if(Y(`ok/pool/recycle-disconnected`,{docName:e,wasActive:n}),this.destroyEntry(t),this._entries.delete(e),this.lruOrder=this.lruOrder.filter(t=>t!==e),n){this.open(e)&&this.setActive(e);return}this.notify()}},cb=crypto.randomUUID(),lb=`ok-pin-v1`,ub=!1;function db(e){ub||(ub=!0,console.warn(`[DocumentContext] localStorage unavailable — pinned doc will not persist across tabs/reloads.`,e))}function fb(){if(typeof window>`u`)return null;try{return window.localStorage.getItem(lb)}catch(e){return db(e),null}}function pb(e){if(!(typeof window>`u`))try{e===null?window.localStorage.removeItem(lb):window.localStorage.setItem(lb,e)}catch(e){db(e)}}var mb=(0,J.createContext)(null),hb=null;function gb(e){return hb||(hb=new sb(10,e),sp(hb)),hb}var _b={activeDocName:null,activeProvider:null,syncState:`connecting`,poolEntries:[]};function vb(e){let t=e.getActive(),n=[];for(let t of e.entries.values())n.push({docName:t.docName,provider:t.provider,lastAccessedAt:t.lastAccessedAt});return n.sort((e,t)=>t.lastAccessedAt-e.lastAccessedAt),{activeDocName:e.getActiveDocName(),activeProvider:t?.provider??null,syncState:t?.syncState??`connecting`,poolEntries:n}}function yb(e){let t=(0,at.c)(62),{children:n}=e,[r,i]=(0,J.useState)(_b),[a,o]=(0,J.useState)(null),[s,c]=(0,J.useState)(null),[l,u]=(0,J.useState)(null),[d,f]=(0,J.useState)(`doc`),[p,m]=(0,J.useState)(null),[h,g]=(0,J.useState)(0),{collabUrl:_,terminal:v,lastError:y,retry:b}=Pf(),x,S;t[0]===_?(x=t[1],S=t[2]):(x=()=>{if(_===null)return;let e=gb(_);i(vb(e)),e.setOnBranchMismatch(()=>yf(e)),e.setOnChange(()=>i(vb(e)));let t=fb();return t!==null&&c(t),fetch(`/api/principal`).then(Sb).then(t=>{t&&typeof t.id==`string`&&e.setTabIdentity({principalId:t.id,tabSessionId:cb})}).catch(xb),yf(e),()=>{e.setOnChange(null)}},S=[_],t[0]=_,t[1]=x,t[2]=S),(0,J.useEffect)(x,S);let C,w;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(C=()=>{},w=[],t[3]=C,t[4]=w):(C=t[3],w=t[4]),(0,J.useEffect)(C,w);let T;t[5]===_?T=t[6]:(T=e=>{if(Y(`ok/nav/open-document`,{docName:e,transition:!1}),_===null)return;let t=gb(_);t.open(e)&&(t.setActive(e),o({kind:`doc`,target:e,docName:e}))},t[5]=_,t[6]=T);let E=T,D;t[7]===E?D=t[8]:(D=e=>{Y(`ok/nav/open-document`,{docName:e,transition:!1}),E(e)},t[7]=E,t[8]=D);let O=D,k;t[9]===_?k=t[10]:(k=e=>{if(_===null)return;let t=gb(_),n=oe(e);n?(t.open(n),t.setActive(n)):t.clearActive(),o(e)},t[9]=_,t[10]=k);let A=k,ee;t[11]===A?ee=t[12]:(ee=e=>{Y(`ok/nav/open-target`,{docName:oe(e),kind:e.kind,transition:!1}),A(e)},t[11]=A,t[12]=ee);let j=ee,M,N,P,F;t[13]===_?(M=t[14],N=t[15],P=t[16],F=t[17]):(F=()=>{if(_===null){o(null);return}gb(_).clearActive(),o(null)},M=e=>{_!==null&&(gb(_).close(e),o(t=>t&&(oe(t)===e?null:t)))},N=e=>{_!==null&&gb(_).recycle(e)},P=e=>{_!==null&&gb(_).prewarm(e)},t[13]=_,t[14]=M,t[15]=N,t[16]=P,t[17]=F);let I,L;t[18]===Symbol.for(`react.memo_cache_sentinel`)?(I=e=>{c(e),pb(e)},L=()=>{c(null),pb(null)},t[18]=I,t[19]=L):(I=t[18],L=t[19]);let R,z,B,V,H;t[20]===_?(R=t[21],z=t[22],B=t[23],V=t[24],H=t[25]):(R=e=>{_!==null&&gb(_).setExpectedServerInstanceId(e)},z=async e=>{if(_===null)return;let t=gb(_);t.setObservedBranch(e),await gf(t,e)},B=async e=>{if(_===null)return;let t=gb(_);t.compareAndUpdateObservedBranch(e)&&await gf(t,e)},V=(e,t)=>{_!==null&&gb(_).observeDiskAck(e,t)},H=async()=>{_!==null&&await yf(gb(_))},t[20]=_,t[21]=R,t[22]=z,t[23]=B,t[24]=V,t[25]=H);let U;t[26]!==p||t[27]!==d?(U=e=>{if(d===`agent`&&p===e){f(`doc`);return}m(e),f(`agent`),g(bb)},t[26]=p,t[27]=d,t[28]=U):U=t[28];let W;t[29]===Symbol.for(`react.memo_cache_sentinel`)?(W=()=>{f(`doc`),m(null)},t[29]=W):W=t[29];let G;t[30]!==a||t[31]!==y||t[32]!==v||t[33]!==_||t[34]!==p||t[35]!==h||t[36]!==d||t[37]!==E||t[38]!==O||t[39]!==A||t[40]!==j||t[41]!==s||t[42]!==b||t[43]!==r.activeDocName||t[44]!==r.activeProvider||t[45]!==r.poolEntries||t[46]!==r.syncState||t[47]!==l||t[48]!==M||t[49]!==N||t[50]!==P||t[51]!==R||t[52]!==z||t[53]!==B||t[54]!==V||t[55]!==H||t[56]!==U||t[57]!==F?(G={activeTarget:a,activeDocName:r.activeDocName,activeProvider:r.activeProvider,syncState:r.syncState,poolEntries:r.poolEntries,openDocument:E,openDocumentTransition:O,openTarget:A,openTargetTransition:j,clearTarget:F,closeDocument:M,recycleDocument:N,prewarm:P,pinnedDoc:s,pin:I,unpin:L,systemProvider:l,setSystemProvider:u,updateServerInstanceId:R,onBranchSwitched:z,observeBranch:B,observeDiskAck:V,refreshServerInfo:H,collabUrl:_,collabTerminal:v,collabLastError:y,retryCollab:b,docPanelMode:d,docPanelAgentId:p,docPanelExpandSignal:h,openActivityPanel:U,closeActivityPanel:W},t[30]=a,t[31]=y,t[32]=v,t[33]=_,t[34]=p,t[35]=h,t[36]=d,t[37]=E,t[38]=O,t[39]=A,t[40]=j,t[41]=s,t[42]=b,t[43]=r.activeDocName,t[44]=r.activeProvider,t[45]=r.poolEntries,t[46]=r.syncState,t[47]=l,t[48]=M,t[49]=N,t[50]=P,t[51]=R,t[52]=z,t[53]=B,t[54]=V,t[55]=H,t[56]=U,t[57]=F,t[58]=G):G=t[58];let K=G,q;return t[59]!==n||t[60]!==K?(q=(0,X.jsx)(mb,{value:K,children:n}),t[59]=n,t[60]=K,t[61]=q):q=t[61],q}function bb(e){return e+1}function xb(){}function Sb(e){return e.ok?e.json():null}function Cb(){let e=(0,J.use)(mb);if(!e)throw Error(`useDocumentContext must be used within <DocumentProvider />`);return e}function wb(){let e=(0,at.c)(3),{openDocumentTransition:t,openTargetTransition:n}=Cb(),r;return e[0]!==t||e[1]!==n?(r={openDocumentTransition:t,openTargetTransition:n},e[0]=t,e[1]=n,e[2]=r):r=e[2],r}export{tr as $,Eg as A,uf as B,W_ as C,L_ as D,B_ as E,Zf as F,pc as G,ws as H,Jf as I,oc as J,sc as K,ap as L,Wh as M,Xf as N,R_ as O,qf as P,nr as Q,Ef as R,G_ as S,N_ as T,Hc as U,rd as V,mc as W,Io as X,Fo as Y,pa as Z,Nv as _,Ve as _t,Ly as a,nt as at,Z_ as b,Qy as c,Ze as ct,jy as d,Je as dt,_n as et,Ay as f,Ke as ft,Pv as g,He as gt,zv as h,Ue as ht,Ry as i,Y as it,wg as j,zg as k,Jy as l,Xe as lt,Bv as m,We as mt,Cb as n,bn as nt,Iy as o,et as ot,py as p,Ge as pt,dc as q,wb as r,ct as rt,Fy as s,$e as st,yb as t,Sn as tt,My as u,Ye as ut,sv as v,Be as vt,U_ as w,Y_ as x,av as y,Re as yt,_f as z};
|