@inkeep/open-knowledge 0.0.0-dev-20260421192027 → 0.0.0-dev-20260422092332

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.
Files changed (36) hide show
  1. package/dist/cli.mjs +9 -9
  2. package/dist/constants-DigVOZ9o.mjs +2 -0
  3. package/dist/index.mjs +1 -1
  4. package/dist/init-BPHczY2k.mjs +6 -0
  5. package/dist/{init-DeoOI04P.mjs → init-DiUw5TDX.mjs} +2 -2
  6. package/dist/{init-CyxGRu4t.mjs → init-EiMNbiMk.mjs} +1 -1
  7. package/dist/init-bL3p670c.mjs +1 -0
  8. package/dist/{loader-BNuhNFOT.mjs → loader-BOYrnnNP.mjs} +2 -2
  9. package/dist/loader-CecgSwbH.mjs +1 -0
  10. package/dist/paths-8lEuqzzC.mjs +1 -0
  11. package/dist/paths-Ub0bMbwu.mjs +2 -0
  12. package/dist/preview-CCBPkWf0.mjs +1 -0
  13. package/dist/{preview-oS_HbHIz.mjs → preview-DlFxxSWj.mjs} +2 -2
  14. package/dist/public/assets/index-DVyr5aVx.css +1 -0
  15. package/dist/public/assets/index-e4QpKJH0.js +381 -0
  16. package/dist/public/index.html +2 -2
  17. package/dist/{src-ViJPkmPW.mjs → src-CdcLi3q2.mjs} +8 -8
  18. package/dist/{src-DcVg7_6f.mjs → src-Cgk_X3wh.mjs} +51 -54
  19. package/dist/src-DYjDx2Br.mjs +1 -0
  20. package/dist/src-Dh_UJnt4.mjs +1 -0
  21. package/dist/start-BocQMsT6.mjs +1 -0
  22. package/dist/start-D6ddaQ_D.mjs +2 -0
  23. package/package.json +1 -1
  24. package/dist/constants-BLW6shM6.mjs +0 -2
  25. package/dist/init-B6g8iwyX.mjs +0 -1
  26. package/dist/init-WENor_lZ.mjs +0 -5
  27. package/dist/loader-bM_eCxHL.mjs +0 -1
  28. package/dist/paths-DxI4FHOZ.mjs +0 -2
  29. package/dist/paths-xS3o7pK2.mjs +0 -1
  30. package/dist/preview-BGOwfgOL.mjs +0 -1
  31. package/dist/public/assets/index-BqGPiKcl.js +0 -381
  32. package/dist/public/assets/index-DfpTuEYh.css +0 -1
  33. package/dist/src-D9A_jCdV.mjs +0 -1
  34. package/dist/src-NsJfsnSl.mjs +0 -1
  35. package/dist/start-BPpXybFr.mjs +0 -1
  36. package/dist/start-CNULXoun.mjs +0 -2
@@ -1,93 +1,90 @@
1
- import{i as e,r as t,t as n}from"./chunk-tuRmWmEN.mjs";import{A as r,C as i,E as a,S as o,T as s,_ as c,a as l,b as u,c as d,d as f,f as p,g as m,h,i as g,j as _,k as v,l as y,m as b,n as x,o as S,p as C,r as w,s as T,t as E,u as D,v as O,w as k,x as A,y as j}from"./src-ViJPkmPW.mjs";import{d as M,f as ee,i as N,l as te,n as ne,o as P,r as re,s as F,u as ie}from"./server-lock-B4frNnOB.mjs";import{n as ae,t as I}from"./git-handle-C_GYoScT.mjs";import{createRequire as oe}from"node:module";import{closeSync as se,existsSync as L,lstatSync as ce,mkdirSync as le,openSync as ue,readFileSync as R,readdirSync as de,realpathSync as fe,renameSync as pe,rmSync as me,statSync as he,unlinkSync as ge,writeFileSync as z,writeSync as _e}from"node:fs";import{homedir as ve,hostname as ye,tmpdir as be}from"node:os";import{dirname as xe,extname as Se,join as Ce,posix as we,relative as B,resolve as V,sep as Te}from"node:path";import{URLSearchParams as Ee}from"node:url";import De,{createHash as Oe,randomUUID as ke,webcrypto as Ae}from"node:crypto";import{spawn as je,spawnSync as Me}from"node:child_process";import Ne from"simple-git";import{mkdir as Pe,readFile as Fe,realpath as Ie,rename as Le,writeFile as Re}from"node:fs/promises";import"node:http";import ze from"picomatch";const Be=()=>new Map,Ve=e=>{let t=Be();return e.forEach((e,n)=>{t.set(n,e)}),t},He=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r},Ue=(e,t)=>{for(let[n,r]of e)if(t(r,n))return!0;return!1},We=()=>new Set,Ge=e=>e[e.length-1],Ke=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},qe=Array.from,Je=Array.isArray;var Ye=class{constructor(){this._observers=Be()}on(e,t){return He(this._observers,e,We).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 qe((this._observers.get(e)||Be()).values()).forEach(e=>e(...t))}destroy(){this._observers=Be()}};const Xe=Math.floor,Ze=Math.abs,Qe=(e,t)=>e<t?e:t,$e=(e,t)=>e>t?e:t;Number.isNaN;const et=e=>e===0?1/e<0:e<0,tt=2**53-1,nt=Number.isInteger||(e=>typeof e==`number`&&isFinite(e)&&Xe(e)===e);Number.isNaN,Number.parseInt;const rt=String.fromCharCode;String.fromCodePoint,rt(65535);const it=e=>e.toLowerCase(),at=/^\s*/g,ot=e=>e.replace(at,``),st=/([A-Z])/g,ct=(e,t)=>ot(e.replace(st,e=>`${t}${it(e)}`)),lt=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},ut=typeof TextEncoder<`u`?new TextEncoder:null,dt=ut?e=>ut.encode(e):lt;let ft=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});ft&&ft.decode(new Uint8Array).length===1&&(ft=null);var pt=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const mt=()=>new pt,ht=e=>{let t=mt();return e(t),_t(t)},gt=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},_t=e=>{let t=new Uint8Array(gt(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},vt=(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($e(n,t)*2),e.cpos=0)},yt=(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},bt=yt,H=(e,t)=>{for(;t>127;)yt(e,128|127&t),t=Xe(t/128);yt(e,127&t)},xt=(e,t)=>{let n=et(t);for(n&&(t=-t),yt(e,(t>63?128:0)|(n?64:0)|63&t),t=Xe(t/64);t>0;)yt(e,(t>127?128:0)|127&t),t=Xe(t/128)},St=new Uint8Array(3e4),Ct=St.length/3,wt=ut&&ut.encodeInto?(e,t)=>{if(t.length<Ct){let n=ut.encodeInto(t,St).written||0;H(e,n);for(let t=0;t<n;t++)yt(e,St[t])}else Et(e,dt(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;H(e,r);for(let t=0;t<r;t++)yt(e,n.codePointAt(t))},Tt=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=Qe(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($e(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},Et=(e,t)=>{H(e,t.byteLength),Tt(e,t)},Dt=(e,t)=>{vt(e,t);let n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},Ot=(e,t)=>Dt(e,4).setFloat32(0,t,!1),kt=(e,t)=>Dt(e,8).setFloat64(0,t,!1),At=(e,t)=>Dt(e,8).setBigInt64(0,t,!1),jt=new DataView(new ArrayBuffer(4)),Mt=e=>(jt.setFloat32(0,e),jt.getFloat32(0)===e),Nt=(e,t)=>{switch(typeof t){case`string`:yt(e,119),wt(e,t);break;case`number`:nt(t)&&Ze(t)<=2147483647?(yt(e,125),xt(e,t)):Mt(t)?(yt(e,124),Ot(e,t)):(yt(e,123),kt(e,t));break;case`bigint`:yt(e,122),At(e,t);break;case`object`:if(t===null)yt(e,126);else if(Je(t)){yt(e,117),H(e,t.length);for(let n=0;n<t.length;n++)Nt(e,t[n])}else if(t instanceof Uint8Array)yt(e,116),Et(e,t);else{yt(e,118);let n=Object.keys(t);H(e,n.length);for(let r=0;r<n.length;r++){let i=n[r];wt(e,i),Nt(e,t[i])}}break;case`boolean`:yt(e,t?120:121);break;default:yt(e,127)}};var Pt=class extends pt{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&H(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}};const Ft=e=>{e.count>0&&(xt(e.encoder,e.count===1?e.s:-e.s),e.count>1&&H(e.encoder,e.count-2))};var It=class{constructor(){this.encoder=new pt,this.s=0,this.count=0}write(e){this.s===e?this.count++:(Ft(this),this.count=1,this.s=e)}toUint8Array(){return Ft(this),_t(this.encoder)}};const Lt=e=>{if(e.count>0){let t=e.diff*2+(e.count===1?0:1);xt(e.encoder,t),e.count>1&&H(e.encoder,e.count-2)}};var Rt=class{constructor(){this.encoder=new pt,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(Lt(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return Lt(this),_t(this.encoder)}},zt=class{constructor(){this.sarr=[],this.s=``,this.lensE=new It}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 pt;return this.sarr.push(this.s),this.s=``,wt(e,this.sarr.join(``)),Tt(e,this.lensE.toUint8Array()),_t(e)}};const Bt=e=>Error(e),Vt=()=>{throw Bt(`Method unimplemented`)},Ht=()=>{throw Bt(`Unexpected case`)},Ut=Bt(`Unexpected end of array`),Wt=Bt(`Integer out of Range`);var Gt=class{constructor(e){this.arr=e,this.pos=0}};const Kt=e=>new Gt(e),qt=e=>e.pos!==e.arr.length,Jt=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},Yt=e=>Jt(e,U(e)),Xt=e=>e.arr[e.pos++],U=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>tt)throw Wt}throw Ut},Zt=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>tt)throw Wt}throw Ut},Qt=ft?e=>ft.decode(Yt(e)):e=>{let t=U(e);if(t===0)return``;{let n=String.fromCodePoint(Xt(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Xt(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))}},$t=(e,t)=>{let n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},en=[e=>void 0,e=>null,Zt,e=>$t(e,4).getFloat32(0,!1),e=>$t(e,8).getFloat64(0,!1),e=>$t(e,8).getBigInt64(0,!1),e=>!1,e=>!0,Qt,e=>{let t=U(e),n={};for(let r=0;r<t;r++){let t=Qt(e);n[t]=tn(e)}return n},e=>{let t=U(e),n=[];for(let r=0;r<t;r++)n.push(tn(e));return n},Yt],tn=e=>en[127-Xt(e)](e);var nn=class extends Gt{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),qt(this)?this.count=U(this)+1:this.count=-1),this.count--,this.s}},rn=class extends Gt{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=Zt(this);let e=et(this.s);this.count=1,e&&(this.s=-this.s,this.count=U(this)+2)}return this.count--,this.s}},an=class extends Gt{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){let e=Zt(this),t=e&1;this.diff=Xe(e/2),this.count=1,t&&(this.count=U(this)+2)}return this.s+=this.diff,this.count--,this.s}},on=class{constructor(e){this.decoder=new rn(e),this.str=Qt(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}};Ae.subtle;const sn=Ae.getRandomValues.bind(Ae),cn=()=>sn(new Uint32Array(1))[0],ln=()=>`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^cn()&15>>e/4).toString(16)),un=Date.now,dn=e=>new Promise(e);Promise.all.bind(Promise);const fn=e=>e===void 0?null:e;let pn=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&&(pn=localStorage)}catch{}const mn=pn,hn=Symbol(`Equality`),gn=(e,t)=>e===t||!!e?.[hn]?.(t)||!1,_n=Object.assign,vn=Object.keys,yn=(e,t)=>{for(let n in e)t(e[n],n)},bn=e=>vn(e).length,xn=e=>{for(let t in e)return!1;return!0},Sn=(e,t)=>{for(let n in e)if(!t(e[n],n))return!1;return!0},Cn=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),wn=(e,t)=>e===t||bn(e)===bn(t)&&Sn(e,(e,n)=>(e!==void 0||Cn(t,n))&&gn(t[n],e)),Tn=Object.freeze,En=e=>{for(let t in e){let n=e[t];(typeof n==`object`||typeof n==`function`)&&En(e[t])}return Tn(e)},Dn=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&Dn(e,t,n+1)}},On=e=>e,kn=(e,t)=>t.includes(e),An=typeof process<`u`&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<`u`?process:0)===`[object process]`,jn=typeof window<`u`&&typeof document<`u`&&!An;typeof navigator<`u`&&/Mac/.test(navigator.platform);let Mn;const Nn=[],Pn=()=>{if(Mn===void 0)if(An){Mn=Be();let e=process.argv,t=null;for(let n=0;n<e.length;n++){let r=e[n];r[0]===`-`?(t!==null&&Mn.set(t,``),t=r):t===null?Nn.push(r):(Mn.set(t,r),t=null)}t!==null&&Mn.set(t,``)}else typeof location==`object`?(Mn=Be(),(location.search||`?`).slice(1).split(`&`).forEach(e=>{if(e.length!==0){let[t,n]=e.split(`=`);Mn.set(`--${ct(t,`-`)}`,n),Mn.set(`-${ct(t,`-`)}`,n)}})):Mn=Be();return Mn},Fn=e=>Pn().has(e),In=e=>fn(An?process.env[e.toUpperCase().replaceAll(`-`,`_`)]:mn.getItem(e)),Ln=e=>Fn(`--`+e)||In(e)!==null;Ln(`production`);const Rn=An&&kn(process.env.FORCE_COLOR,[`true`,`1`,`2`])||!Fn(`--no-colors`)&&!Ln(`no-color`)&&(!An||process.stdout.isTTY)&&(!An||Fn(`--color`)||In(`COLORTERM`)!==null||(In(`TERM`)||``).includes(`color`)),zn=e=>new Uint8Array(e),Bn=jn?e=>{let t=``;for(let n=0;n<e.byteLength;n++)t+=rt(e[n]);return btoa(t)}:e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64`),Vn=e=>{let t=zn(e.byteLength);return t.set(e),t},Hn=e=>ht(t=>Nt(t,e)),Un=Symbol,Wn=Un(),Gn=Un(),Kn=Un(),qn=Un(),Jn=Un(),Yn=Un(),Xn=Un(),Zn=Un(),Qn=Un(),$n=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};un();const er={[Wn]:`\x1B[1m`,[Gn]:`\x1B[2m`,[Kn]:`\x1B[34m`,[Jn]:`\x1B[32m`,[qn]:`\x1B[37m`,[Yn]:`\x1B[31m`,[Xn]:`\x1B[35m`,[Zn]:`\x1B[38;5;208m`,[Qn]:`\x1B[0m`},tr=Rn?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],i=er[n];if(i!==void 0)t.push(i);else if(n===void 0)break;else if(n.constructor===String||n.constructor===Number)t.push(n);else break}for(r>0&&(t.push(`\x1B[0m`),n.push(t.join(``)));r<e.length;r++){let t=e[r];t instanceof Symbol||n.push(t)}return n}:$n,nr=(...e)=>{console.log(...tr(e))},rr=(...e)=>{console.warn(...tr(e))},ir=e=>({[Symbol.iterator](){return this},next:e}),ar=(e,t)=>ir(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),or=(e,t)=>ir(()=>{let{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}});var sr=class{constructor(e,t){this.clock=e,this.len=t}},cr=class{constructor(){this.clients=new Map}};const lr=(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])yi(e,i,o.clock,o.len,n)}}),ur=(e,t)=>{let n=0,r=e.length-1;for(;n<=r;){let i=Xe((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},dr=(e,t)=>{let n=e.clients.get(t.client);return n!==void 0&&ur(n,t.clock)!==null},fr=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 sr(r.clock,$e(r.len,i.clock+i.len-r.clock)):(n<t&&(e[n]=i),n++)}e.length=n})},pr=e=>{let t=new cr;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++)Ke(a,e[t].clients.get(i)||[]);t.clients.set(i,a)}});return fr(t),t},mr=(e,t,n,r)=>{He(e.clients,t,()=>[]).push(new sr(n,r))},hr=()=>new cr,gr=e=>{let t=hr();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 sr(i,a))}}r.length>0&&t.clients.set(n,r)}),t},_r=(e,t)=>{H(e.restEncoder,t.clients.size),qe(t.clients.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{e.resetDsCurVal(),H(e.restEncoder,t);let r=n.length;H(e.restEncoder,r);for(let t=0;t<r;t++){let r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}})},vr=e=>{let t=new cr,n=U(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();let n=U(e.restDecoder),r=U(e.restDecoder);if(r>0){let i=He(t.clients,n,()=>[]);for(let t=0;t<r;t++)i.push(new sr(e.readDsClock(),e.readDsLen()))}}return t},yr=(e,t,n)=>{let r=new cr,i=U(e.restDecoder);for(let a=0;a<i;a++){e.resetDsCurVal();let i=U(e.restDecoder),a=U(e.restDecoder),o=n.clients.get(i)||[],s=di(n,i);for(let n=0;n<a;n++){let n=e.readDsClock(),a=n+e.readDsLen();if(n<s){s<a&&mr(r,i,s,a-s);let e=pi(o,n),c=o[e];for(!c.deleted&&c.id.clock<n&&(o.splice(e+1,0,Oo(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,Oo(t,c,a-c.id.clock)),c.delete(t))}else mr(r,i,n,a-n)}}if(r.clients.size>0){let e=new Ar;return H(e.restEncoder,0),_r(e,r),e.toUint8Array()}return null},br=(e,t)=>{if(e.clients.size!==t.clients.size)return!1;for(let[n,r]of e.clients.entries()){let e=t.clients.get(n);if(e===void 0||r.length!==e.length)return!1;for(let t=0;t<r.length;t++){let n=r[t],i=e[t];if(n.clock!==i.clock||n.len!==i.len)return!1}}return!0},xr=cn;var Sr=class e extends Ye{constructor({guid:e=ln(),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=xr(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new li,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=dn(e=>{this.on(`load`,()=>{this.isLoaded=!0,e(this)})});let s=()=>dn(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&&G(e.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(qe(this.subdocs).map(e=>e.guid))}transact(e,t=null){return G(this,e,t)}get(e,t=Zi){let n=He(this.share,e,()=>{let e=new t;return e._integrate(this,null),e}),r=n.constructor;if(t!==Zi&&r!==t)if(r===Zi){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,va)}getText(e=``){return this.get(e,za)}getMap(e=``){return this.get(e,xa)}getXmlElement(e=``){return this.get(e,Wa)}getXmlFragment(e=``){return this.get(e,Ha)}toJSON(){let e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,qe(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,G(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()}},Cr=class{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return U(this.restDecoder)}readDsLen(){return U(this.restDecoder)}},wr=class extends Cr{readLeftID(){return W(U(this.restDecoder),U(this.restDecoder))}readRightID(){return W(U(this.restDecoder),U(this.restDecoder))}readClient(){return U(this.restDecoder)}readInfo(){return Xt(this.restDecoder)}readString(){return Qt(this.restDecoder)}readParentInfo(){return U(this.restDecoder)===1}readTypeRef(){return U(this.restDecoder)}readLen(){return U(this.restDecoder)}readAny(){return tn(this.restDecoder)}readBuf(){return Vn(Yt(this.restDecoder))}readJSON(){return JSON.parse(Qt(this.restDecoder))}readKey(){return Qt(this.restDecoder)}},Tr=class{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=U(this.restDecoder),this.dsCurrVal}readDsLen(){let e=U(this.restDecoder)+1;return this.dsCurrVal+=e,e}},Er=class extends Tr{constructor(e){super(e),this.keys=[],U(e),this.keyClockDecoder=new an(Yt(e)),this.clientDecoder=new rn(Yt(e)),this.leftClockDecoder=new an(Yt(e)),this.rightClockDecoder=new an(Yt(e)),this.infoDecoder=new nn(Yt(e),Xt),this.stringDecoder=new on(Yt(e)),this.parentInfoDecoder=new nn(Yt(e),Xt),this.typeRefDecoder=new rn(Yt(e)),this.lenDecoder=new rn(Yt(e))}readLeftID(){return new $r(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new $r(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 tn(this.restDecoder)}readBuf(){return Yt(this.restDecoder)}readJSON(){return tn(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}}},Dr=class{constructor(){this.restEncoder=mt()}toUint8Array(){return _t(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){H(this.restEncoder,e)}writeDsLen(e){H(this.restEncoder,e)}},Or=class extends Dr{writeLeftID(e){H(this.restEncoder,e.client),H(this.restEncoder,e.clock)}writeRightID(e){H(this.restEncoder,e.client),H(this.restEncoder,e.clock)}writeClient(e){H(this.restEncoder,e)}writeInfo(e){bt(this.restEncoder,e)}writeString(e){wt(this.restEncoder,e)}writeParentInfo(e){H(this.restEncoder,e?1:0)}writeTypeRef(e){H(this.restEncoder,e)}writeLen(e){H(this.restEncoder,e)}writeAny(e){Nt(this.restEncoder,e)}writeBuf(e){Et(this.restEncoder,e)}writeJSON(e){wt(this.restEncoder,JSON.stringify(e))}writeKey(e){wt(this.restEncoder,e)}},kr=class{constructor(){this.restEncoder=mt(),this.dsCurrVal=0}toUint8Array(){return _t(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){let t=e-this.dsCurrVal;this.dsCurrVal=e,H(this.restEncoder,t)}writeDsLen(e){e===0&&Ht(),H(this.restEncoder,e-1),this.dsCurrVal+=e}},Ar=class extends kr{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new Rt,this.clientEncoder=new It,this.leftClockEncoder=new Rt,this.rightClockEncoder=new Rt,this.infoEncoder=new Pt(bt),this.stringEncoder=new zt,this.parentInfoEncoder=new Pt(bt),this.typeRefEncoder=new It,this.lenEncoder=new It}toUint8Array(){let e=mt();return H(e,0),Et(e,this.keyClockEncoder.toUint8Array()),Et(e,this.clientEncoder.toUint8Array()),Et(e,this.leftClockEncoder.toUint8Array()),Et(e,this.rightClockEncoder.toUint8Array()),Et(e,_t(this.infoEncoder)),Et(e,this.stringEncoder.toUint8Array()),Et(e,_t(this.parentInfoEncoder)),Et(e,this.typeRefEncoder.toUint8Array()),Et(e,this.lenEncoder.toUint8Array()),Tt(e,_t(this.restEncoder)),_t(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(e?1:0)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){Nt(this.restEncoder,e)}writeBuf(e){Et(this.restEncoder,e)}writeJSON(e){Nt(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)}};const jr=(e,t,n,r)=>{r=$e(r,t[0].id.clock);let i=pi(t,r);H(e.restEncoder,t.length-i),e.writeClient(n),H(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)},Mr=(e,t,n)=>{let r=new Map;n.forEach((e,n)=>{di(t,n)>e&&r.set(n,e)}),ui(t).forEach((e,t)=>{n.has(t)||r.set(t,0)}),H(e.restEncoder,r.size),qe(r.entries()).sort((e,t)=>t[0]-e[0]).forEach(([n,r])=>{jr(e,t.clients.get(n),n,r)})},Nr=(e,t)=>{let n=Be(),r=U(e.restDecoder);for(let i=0;i<r;i++){let r=U(e.restDecoder),i=Array(r),a=e.readClient(),o=U(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 Qa(W(a,o),t),o+=t;break}case 10:{let t=U(e.restDecoder);i[n]=new Mo(W(a,o),t),o+=t;break}default:{let s=(r&192)==0,c=new ko(W(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,Ao(e,r));i[n]=c,o+=c.length}}}}return n},Pr=(e,t,n)=>{let r=[],i=qe(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 li,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!==Mo){let i=He(d,u.id.client,()=>di(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,di(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 Ar;return Mr(e,s,new Map),H(e.restEncoder,0),{missing:c,update:e.toUint8Array()}}return null},Fr=(e,t)=>Mr(e,t.doc.store,t.beforeState),Ir=(e,t,n,r=new Er(e))=>G(t,e=>{e.local=!1;let t=!1,n=e.doc,i=n.store,a=Pr(e,i,Nr(r,n)),o=i.pendingStructs;if(o){for(let[e,n]of o.missing)if(n<di(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=Mi([o.update,a.update])}}else i.pendingStructs=a;let s=yr(r,e,i);if(i.pendingDs){let t=new Er(Kt(i.pendingDs));U(t.restDecoder);let n=yr(t,e,i);s&&n?i.pendingDs=Mi([s,n]):i.pendingDs=s||n}else i.pendingDs=s;if(t){let t=i.pendingStructs.update;i.pendingStructs=null,Lr(e.doc,t)}},n,!1),Lr=(e,t,n,r=Er)=>{let i=Kt(t);Ir(i,e,n,new r(i))},Rr=(e,t,n)=>Lr(e,t,n,wr),zr=(e,t,n=new Map)=>{Mr(e,t.store,n),_r(e,gr(t.store))},Br=(e,t=new Uint8Array([0]),n=new Ar)=>{zr(n,e,Ur(t));let r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Ni(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===Or)return Ai(r.map((e,t)=>t===0?e:Ri(e)));if(n.constructor===Ar)return Mi(r)}return r[0]},Vr=(e,t)=>Br(e,t,new Or),Hr=e=>{let t=new Map,n=U(e.restDecoder);for(let r=0;r<n;r++){let n=U(e.restDecoder),r=U(e.restDecoder);t.set(n,r)}return t},Ur=e=>Hr(new Cr(Kt(e))),Wr=(e,t)=>(H(e.restEncoder,t.size),qe(t.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{H(e.restEncoder,t),H(e.restEncoder,n)}),e),Gr=(e,t)=>Wr(e,ui(t.store)),Kr=(e,t=new kr)=>(e instanceof Map?Wr(t,e):Gr(t,e),t.toUint8Array()),qr=e=>Kr(e,new Dr);var Jr=class{constructor(){this.l=[]}};const Yr=()=>new Jr,Xr=(e,t)=>e.l.push(t),Zr=(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.`)},Qr=(e,t,n)=>Dn(e.l,[t,n]);var $r=class{constructor(e,t){this.client=e,this.clock=t}};const ei=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,W=(e,t)=>new $r(e,t),ti=e=>{for(let[t,n]of e.doc.share.entries())if(n===e)return t;throw Ht()};var ni=class{constructor(e,t){this.ds=e,this.sv=t}};const ri=(e,t)=>new ni(e,t);ri(hr(),new Map);const ii=e=>ri(gr(e.store),ui(e.store)),ai=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!dr(t.ds,e.id),oi=(e,t)=>{let n=He(e.meta,oi,We),r=e.doc.store;n.has(t)||(t.sv.forEach((t,n)=>{t<di(r,n)&&gi(e,W(n,t))}),lr(e,t.ds,e=>{}),n.add(t))},si=(e,t,n=Er)=>{let r=new n(Kt(t)),i=new Oi(r,!1);for(let t=i.curr;t!==null;t=i.next())if((e.sv.get(t.id.client)||0)<t.id.clock+t.length)return!1;let a=pr([e.ds,vr(r)]);return br(e.ds,a)},ci=(e,t)=>si(e,t,wr);var li=class{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}};const ui=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},di=(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},fi=(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 Ht()}n.push(t)},pi=(e,t)=>{let n=0,r=e.length-1,i=e[r],a=i.id.clock;if(a===t)return r;let o=Xe(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=Xe((n+r)/2)}throw Ht()},mi=(e,t)=>{let n=e.clients.get(t.client);return n[pi(n,t.clock)]},hi=(e,t,n)=>{let r=pi(t,n),i=t[r];return i.id.clock<n&&i instanceof ko?(t.splice(r+1,0,Oo(e,i,n-i.id.clock)),r+1):r},gi=(e,t)=>{let n=e.doc.store.clients.get(t.client);return n[hi(e,n,t.clock)]},_i=(e,t,n)=>{let r=t.clients.get(n.client),i=pi(r,n.clock),a=r[i];return n.clock!==a.id.clock+a.length-1&&a.constructor!==Qa&&r.splice(i+1,0,Oo(e,a,n.clock-a.id.clock+1)),a},vi=(e,t,n)=>{let r=e.clients.get(t.id.client);r[pi(r,t.id.clock)]=n},yi=(e,t,n,r,i)=>{if(r===0)return;let a=n+r,o=hi(e,t,n),s;do s=t[o++],a<s.id.clock+s.length&&hi(e,t,a),i(s);while(o<t.length&&t[o].id.clock<a)};var bi=class{constructor(e,t,n){this.doc=e,this.deleteSet=new cr,this.beforeState=ui(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}};const xi=(e,t)=>t.deleteSet.clients.size===0&&!Ue(t.afterState,(e,n)=>t.beforeState.get(n)!==e)?!1:(fr(t.deleteSet),Fr(e,t),_r(e,t.deleteSet),!0),Si=(e,t,n)=>{let r=t._item;(r===null||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&He(e.changed,t,We).add(n)},Ci=(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 ko&&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},wi=(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=pi(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 ko&&i.deleted&&!i.keep&&n(i)&&i.gc(t,!1)}}}},Ti=(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=Qe(r.length-1,1+pi(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+Ci(r,e)}})},Ei=(e,t)=>{if(t<e.length){let n=e[t],r=n.doc,i=r.store,a=n.deleteSet,o=n._mergeStructs;try{fr(a),n.afterState=ui(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(()=>{Qr(r._dEH,t,n)}))}),e.push(()=>r.emit(`afterTransaction`,[n,r])),e.push(()=>{n._needFormattingCleanup&&Ia(n)})}),Dn(e,[])}finally{r.gc&&wi(a,i,r.gcFilter),Ti(a,i),n.afterState.forEach((e,t)=>{let r=n.beforeState.get(t)||0;if(r!==e){let e=i.clients.get(t),n=$e(pi(e,r),1);for(let t=e.length-1;t>=n;)t-=1+Ci(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=pi(r,n);a+1<r.length&&Ci(r,a+1)>1||a>0&&Ci(r,a)}if(!n.local&&n.afterState.get(r.clientID)!==n.beforeState.get(r.clientID)&&(nr(Zn,Wn,`[yjs] `,Gn,Yn,`Changed the client-id because another client seems to be using it.`),r.clientID=xr()),r.emit(`afterTransactionCleanup`,[n,r]),r._observers.has(`update`)){let e=new Or;xi(e,n)&&r.emit(`update`,[e.toUint8Array(),n.origin,r,n])}if(r._observers.has(`updateV2`)){let e=new Ar;xi(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])):Ei(e,t+1)}}},G=(e,t,n=null,r=!0)=>{let i=e._transactionCleanups,a=!1,o=null;e._transaction===null&&(a=!0,e._transaction=new bi(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&&Ei(i,0)}}return o};function*Di(e){let t=U(e.restDecoder);for(let n=0;n<t;n++){let t=U(e.restDecoder),n=e.readClient(),r=U(e.restDecoder);for(let i=0;i<t;i++){let t=e.readInfo();if(t===10){let t=U(e.restDecoder);yield new Mo(W(n,r),t),r+=t}else if(31&t){let i=(t&192)==0,a=new ko(W(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,Ao(e,t));yield a,r+=a.length}else{let t=e.readLen();yield new Qa(W(n,r),t),r+=t}}}}var Oi=class{constructor(e,t){this.gen=Di(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===Mo);return this.curr}},ki=class{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}};const Ai=e=>Mi(e,wr,Or),ji=(e,t)=>{if(e.constructor===Qa){let{client:n,clock:r}=e.id;return new Qa(W(n,r+t),e.length-t)}else if(e.constructor===Mo){let{client:n,clock:r}=e.id;return new Mo(W(n,r+t),e.length-t)}else{let n=e,{client:r,clock:i}=n.id;return new ko(W(r,i+t),null,W(r,i+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Mi=(e,t=Er,n=Ar)=>{if(e.length===1)return e[0];let r=e.map(e=>new t(Kt(e))),i=r.map(e=>new Oi(e,!0)),a=null,o=new n,s=new ki(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===Mo?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)Fi(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===Mo)a.struct.length=n.id.clock+n.length-a.struct.id.clock;else{Fi(s,a.struct,a.offset);let e=n.id.clock-a.struct.id.clock-a.struct.length;a={struct:new Mo(W(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===Mo?a.struct.length-=t:n=ji(n,t)),a.struct.mergeWith(n)||(Fi(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!==Mo;n=e.next())Fi(s,a.struct,a.offset),a={struct:n,offset:0}}return a!==null&&(Fi(s,a.struct,a.offset),a=null),Ii(s),_r(o,pr(r.map(e=>vr(e)))),o.toUint8Array()},Ni=(e,t,n=Er,r=Ar)=>{let i=Ur(t),a=new r,o=new ki(a),s=new n(Kt(e)),c=new Oi(s,!1);for(;c.curr;){let e=c.curr,t=e.id.client,n=i.get(t)||0;if(c.curr.constructor===Mo){c.next();continue}if(e.id.clock+e.length>n)for(Fi(o,e,$e(n-e.id.clock,0)),c.next();c.curr&&c.curr.id.client===t;)Fi(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 Ii(o),_r(a,vr(s)),a.toUint8Array()},Pi=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:_t(e.encoder.restEncoder)}),e.encoder.restEncoder=mt(),e.written=0)},Fi=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&Pi(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),H(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},Ii=e=>{Pi(e);let t=e.encoder.restEncoder;H(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){let r=e.clientStructs[n];H(t,r.written),Tt(t,r.restEncoder)}},Li=(e,t,n,r)=>{let i=new n(Kt(e)),a=new Oi(i,!1),o=new r,s=new ki(o);for(let e=a.curr;e!==null;e=a.next())Fi(s,t(e),0);return Ii(s),_r(o,vr(i)),o.toUint8Array()},Ri=e=>Li(e,On,Er,Or),zi=`You must not compute changes after the event-handler fired.`;var Bi=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||=Vi(this.currentTarget,this.target)}deletes(e){return dr(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Bt(zi);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=Ge(e.content.getContent());else return;else e!==null&&this.deletes(e)?(i=`update`,a=Ge(e.content.getContent())):(i=`add`,a=void 0)}else if(this.deletes(r))i=`delete`,a=Ge(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 Bt(zi);let t=this.target,n=We(),r=We(),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}};const Vi=(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},Hi=()=>{rr(`Invalid access: Add Yjs type to a document before reading data.`)};let Ui=0;var Wi=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=Ui++}};const Gi=e=>{e.timestamp=Ui++},Ki=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=Ui++},qi=(e,t,n)=>{if(e.length>=80){let r=e.reduce((e,t)=>e.timestamp<t.timestamp?e:t);return Ki(r,t,n),r}else{let r=new Wi(t,n);return e.push(r),r}},Ji=(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)=>Ze(t-e.index)<Ze(t-n.index)?e:n),r=e._start,i=0;for(n!==null&&(r=n.p,i=n.index,Gi(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&&Ze(n.index-i)<r.parent.length/80?(Ki(n,r,i),n):qi(e._searchMarker,r,i)},Yi=(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=$e(t,i.index+n))}},Xi=(e,t,n)=>{let r=e,i=t.changedParentTypes;for(;He(i,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;Qr(r._eH,n,t)};var Zi=class{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Yr(),this._dEH=Yr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw Vt()}clone(){throw Vt()}_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){Xr(this._eH,e)}observeDeep(e){Xr(this._dEH,e)}unobserve(e){Zr(this._eH,e)}unobserveDeep(e){Zr(this._dEH,e)}toJSON(){}};const Qi=(e,t,n)=>{e.doc??Hi(),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},$i=e=>{e.doc??Hi();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},ea=(e,t)=>{let n=[],r=e._start;for(;r!==null;){if(r.countable&&ai(r,t)){let e=r.content.getContent();for(let t=0;t<e.length;t++)n.push(e[t])}r=r.right}return n},ta=(e,t)=>{let n=0,r=e._start;for(e.doc??Hi();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}},na=(e,t)=>{let n=[];return ta(e,(r,i)=>{n.push(t(r,i,e))}),n},ra=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}}}},ia=(e,t)=>{e.doc??Hi();let n=Ji(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}},aa=(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 ko(W(o,di(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new mo(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 ko(W(o,di(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new $a(new Uint8Array(n))),i.integrate(e,0);break;case Sr:i=new ko(W(o,di(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new io(n)),i.integrate(e,0);break;default:if(n instanceof Zi)i=new ko(W(o,di(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Eo(n)),i.integrate(e,0);else throw Error(`Unexpected content type in insert operation`)}}}),u()},oa=()=>Bt(`Length exceeded!`),sa=(e,t,n,r)=>{if(n>t._length)throw oa();if(n===0)return t._searchMarker&&Yi(t._searchMarker,n,r.length),aa(e,t,null,r);let i=n,a=Ji(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&&gi(e,W(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&Yi(t._searchMarker,i,r.length),aa(e,t,o,r)},ca=(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 aa(e,t,r,n)},la=(e,t,n,r)=>{if(r===0)return;let i=n,a=r,o=Ji(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&&gi(e,W(s.id.client,s.id.clock+n)),n-=s.length);for(;r>0&&s!==null;)s.deleted||(r<s.length&&gi(e,W(s.id.client,s.id.clock+r)),s.delete(e),r-=s.length),s=s.right;if(r>0)throw oa();t._searchMarker&&Yi(t._searchMarker,i,-a+r)},ua=(e,t,n)=>{let r=t._map.get(n);r!==void 0&&r.delete(e)},da=(e,t,n,r)=>{let i=t._map.get(n)||null,a=e.doc,o=a.clientID,s;if(r==null)s=new mo([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:s=new mo([r]);break;case Uint8Array:s=new $a(r);break;case Sr:s=new io(r);break;default:if(r instanceof Zi)s=new Eo(r);else throw Error(`Unexpected content type`)}new ko(W(o,di(a.store,o)),i,i&&i.lastId,null,null,t,n,s).integrate(e,0)},fa=(e,t)=>{e.doc??Hi();let n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},pa=e=>{let t={};return e.doc??Hi(),e._map.forEach((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])}),t},ma=(e,t)=>{e.doc??Hi();let n=e._map.get(t);return n!==void 0&&!n.deleted},ha=(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&&ai(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},ga=e=>(e.doc??Hi(),ar(e._map.entries(),e=>!e[1].deleted));var _a=class extends Bi{},va=class e extends Zi{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 Zi?e.clone():e)),t}get length(){return this.doc??Hi(),this._length}_callObserver(e,t){super._callObserver(e,t),Xi(this,e,new _a(this,e))}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):G(this.doc,n=>{sa(n,this,e,t)})}push(e){this.doc===null?this._prelimContent.push(...e):G(this.doc,t=>{ca(t,this,e)})}unshift(e){this.insert(0,e)}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):G(this.doc,n=>{la(n,this,e,t)})}get(e){return ia(this,e)}toArray(){return $i(this)}slice(e=0,t=this.length){return Qi(this,e,t)}toJSON(){return this.map(e=>e instanceof Zi?e.toJSON():e)}map(e){return na(this,e)}forEach(e){ta(this,e)}[Symbol.iterator](){return ra(this)}_write(e){e.writeTypeRef(yo)}};const ya=e=>new va;var ba=class extends Bi{constructor(e,t,n){super(e,t),this.keysChanged=n}},xa=class e extends Zi{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 Zi?e.clone():e)}),t}_callObserver(e,t){Xi(this,e,new ba(this,e,t))}toJSON(){this.doc??Hi();let e={};return this._map.forEach((t,n)=>{if(!t.deleted){let r=t.content.getContent()[t.length-1];e[n]=r instanceof Zi?r.toJSON():r}}),e}get size(){return[...ga(this)].length}keys(){return or(ga(this),e=>e[0])}values(){return or(ga(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return or(ga(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??Hi(),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):G(this.doc,t=>{ua(t,this,e)})}set(e,t){return this.doc===null?this._prelimContent.set(e,t):G(this.doc,n=>{da(n,this,e,t)}),t}get(e){return fa(this,e)}has(e){return ma(this,e)}clear(){this.doc===null?this._prelimContent.clear():G(this.doc,e=>{this.forEach(function(t,n,r){ua(e,r,n)})})}_write(e){e.writeTypeRef(bo)}};const Sa=e=>new xa,Ca=(e,t)=>e===t||typeof e==`object`&&typeof t==`object`&&e&&t&&wn(e,t);var wa=class{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){switch(this.right===null&&Ht(),this.right.content.constructor){case co:this.right.deleted||Oa(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}};const Ta=(e,t,n)=>{for(;t.right!==null&&n>0;){switch(t.right.content.constructor){case co:t.right.deleted||Oa(t.currentAttributes,t.right.content);break;default:t.right.deleted||(n<t.right.length&&gi(e,W(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},Ea=(e,t,n,r)=>{let i=new Map,a=r?Ji(t,n):null;return a?Ta(e,new wa(a.p.left,a.p,a.index,i),n-a.index):Ta(e,new wa(null,t._start,0,i),n)},Da=(e,t,n,r)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===co&&Ca(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 ko(W(a,di(i.store,a)),s,s&&s.lastId,c,c&&c.id,t,null,new co(o,r));l.integrate(e,0),n.right=l,n.forward()})},Oa=(e,t)=>{let{key:n,value:r}=t;r===null?e.delete(n):e.set(n,r)},ka=(e,t)=>{for(;e.right!==null&&(e.right.deleted||e.right.content.constructor===co&&Ca(t[e.right.content.key]??null,e.right.content.value));)e.forward()},Aa=(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(!Ca(l,c)){o.set(s,l);let{left:r,right:u}=n;n.right=new ko(W(a,di(i.store,a)),r,r&&r.lastId,u,u&&u.id,t,null,new co(s,c)),n.right.integrate(e,0),n.forward()}}return o},ja=(e,t,n,r,i)=>{n.currentAttributes.forEach((e,t)=>{i[t]===void 0&&(i[t]=null)});let a=e.doc,o=a.clientID;ka(n,i);let s=Aa(e,t,n,i),c=r.constructor===String?new go(r):r instanceof Zi?new Eo(r):new oo(r),{left:l,right:u,index:d}=n;t._searchMarker&&Yi(t._searchMarker,n.index,c.getLength()),u=new ko(W(o,di(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(),Da(e,t,n,s)},Ma=(e,t,n,r,i)=>{let a=e.doc,o=a.clientID;ka(n,i);let s=Aa(e,t,n,i);iterationLoop:for(;n.right!==null&&(r>0||s.size>0&&(n.right.deleted||n.right.content.constructor===co));){if(!n.right.deleted)switch(n.right.content.constructor){case co:{let{key:t,value:a}=n.right.content,o=i[t];if(o!==void 0){if(Ca(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&&gi(e,W(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+=`
2
- `;n.right=new ko(W(o,di(a.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new go(i)),n.right.integrate(e,0),n.forward()}Da(e,t,n,s)},Na=(e,t,n,r,i)=>{let a=t,o=Be();for(;a&&(!a.countable||a.deleted);){if(!a.deleted&&a.content.constructor===co){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 co:{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&&Oa(i,n);break}}}t=t.right}return s},Pa=(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===co){let r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}},Fa=e=>{let t=0;return G(e.doc,n=>{let r=e._start,i=e._start,a=Be(),o=Ve(a);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case co:Oa(o,i.content);break;default:t+=Na(n,r,i,a,o),a=Ve(o),r=i;break}i=i.right}}),t},Ia=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&&yi(e,n.store.clients.get(r),a,i,e=>{!e.deleted&&e.content.constructor===co&&e.constructor!==Qa&&t.add(e.parent)})}G(n,n=>{lr(e,e.deleteSet,e=>{if(e instanceof Qa||!e.parent._hasFormatting||t.has(e.parent))return;let r=e.parent;e.content.constructor===co?t.add(r):Pa(n,e)});for(let e of t)Fa(e)})},La=(e,t,n)=>{let r=n,i=Ve(t.currentAttributes),a=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case Eo:case oo:case go:n<t.right.length&&gi(e,W(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e);break}t.forward()}a&&Na(e,a,t.right,i,t.currentAttributes);let o=(t.left||t.right).parent;return o._searchMarker&&Yi(o._searchMarker,t.index,-r+n),t};var Ra=class extends Bi{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=[];G(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},xn(o)||(e.attributes=_n({},o))),c=0;break}e&&t.push(e),a=null}};for(;i!==null;){switch(i.content.constructor){case Eo:case oo: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 go: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 co:{let{key:t,value:s}=i.content;if(this.adds(i))this.deletes(i)||(Ca(n.get(t)??null,s)?s!==null&&i.delete(e):(a===`retain`&&u(),Ca(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;Ca(e,s)||(a===`retain`&&u(),o[t]=e)}else if(!i.deleted){r.set(t,s);let n=o[t];n!==void 0&&(Ca(n,s)?n!==null&&i.delete(e):(a===`retain`&&u(),s===null?delete o[t]:o[t]=s))}i.deleted||(a===`insert`&&u(),Oa(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}},za=class e extends Zi{constructor(e){super(),this._pending=e===void 0?[]:[()=>this.insert(0,e)],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Hi(),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 Ra(this,e,t);Xi(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Hi();let e=``,t=this._start;for(;t!==null;)!t.deleted&&t.countable&&t.content.constructor===go&&(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)):G(this.doc,n=>{let r=new wa(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)===`
3
- `?a.insert.slice(0,-1):a.insert;(typeof o!=`string`||o.length>0)&&ja(n,this,r,o,a.attributes||{})}else a.retain===void 0?a.delete!==void 0&&La(n,r,a.delete):Ma(n,this,r,a.retain,a.attributes||{})}})}toDelta(e,t,n){this.doc??Hi();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(ai(s,e)||t!==void 0&&ai(s,t))switch(s.content.constructor){case go:{let r=i.get(`ychange`);e!==void 0&&!ai(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&&!ai(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 Eo:case oo:{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 co:ai(s,e)&&(c(),Oa(i,s.content));break}s=s.right}c()};return e||t?G(a,n=>{e&&oi(n,e),t&&oi(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)):G(r,r=>{let i=Ea(r,this,e,!n);n||(n={},i.currentAttributes.forEach((e,t)=>{n[t]=e})),ja(r,this,i,t,n)})}insertEmbed(e,t,n){let r=this.doc;r===null?this._pending.push(()=>this.insertEmbed(e,t,n||{})):G(r,r=>{let i=Ea(r,this,e,!n);ja(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)):G(n,n=>{La(n,Ea(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)):G(r,r=>{let i=Ea(r,this,e,!1);i.right!==null&&Ma(r,this,i,t,n)})}removeAttribute(e){this.doc===null?this._pending.push(()=>this.removeAttribute(e)):G(this.doc,t=>{ua(t,this,e)})}setAttribute(e,t){this.doc===null?this._pending.push(()=>this.setAttribute(e,t)):G(this.doc,n=>{da(n,this,e,t)})}getAttribute(e){return fa(this,e)}getAttributes(){return pa(this)}_write(e){e.writeTypeRef(xo)}};const Ba=e=>new za;var Va=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Hi()}[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===Wa||t.constructor===Ha)&&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})}},Ha=class e extends Zi{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 Zi?e.clone():e)),t}get length(){return this.doc??Hi(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new Va(this,e)}querySelector(e){e=e.toUpperCase();let t=new Va(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),qe(new Va(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){Xi(this,e,new Ka(this,t,e))}toString(){return na(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),ta(this,i=>{r.insertBefore(i.toDOM(e,t,n),null)}),r}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):G(this.doc,n=>{sa(n,this,e,t)})}insertAfter(e,t){if(this.doc!==null)G(this.doc,n=>{let r=e&&e instanceof Zi?e._item:e;aa(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 Bt(`Reference item not found`);n.splice(r,0,...t)}}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):G(this.doc,n=>{la(n,this,e,t)})}toArray(){return $i(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return ia(this,e)}slice(e=0,t=this.length){return Qi(this,e,t)}forEach(e){ta(this,e)}_write(e){e.writeTypeRef(Co)}};const Ua=e=>new Ha;var Wa=class e extends Ha{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 yn(this.getAttributes(),(e,n)=>{t.setAttribute(n,e)}),t.insert(0,this.toArray().map(e=>e instanceof Zi?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):G(this.doc,t=>{ua(t,this,e)})}setAttribute(e,t){this.doc===null?this._prelimAttrs.set(e,t):G(this.doc,n=>{da(n,this,e,t)})}getAttribute(e){return fa(this,e)}hasAttribute(e){return ma(this,e)}getAttributes(e){return e?ha(this,e):pa(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 ta(this,i=>{r.appendChild(i.toDOM(e,t,n))}),n!==void 0&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(So),e.writeKey(this.nodeName)}};const Ga=e=>new Wa(e.readKey());var Ka=class extends Bi{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)})}},qa=class e extends xa{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(wo),e.writeKey(this.hookName)}};const Ja=e=>new qa(e.readKey());var Ya=class e extends za{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(To)}};const Xa=e=>new Ya;var Za=class{constructor(e,t){this.id=e,this.length=t}get deleted(){throw Vt()}mergeWith(e){return!1}write(e,t,n){throw Vt()}integrate(e,t){throw Vt()}},Qa=class extends Za{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),fi(e.doc.store,this)}write(e,t){e.writeInfo(0),e.writeLen(this.length-t)}getMissing(e,t){return null}},$a=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 Vt()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}};const eo=e=>new $a(e.readBuf());var to=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){mr(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}};const no=e=>new to(e.readLen()),ro=(e,t)=>new Sr({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});var io=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(ro(this.doc.guid,this.opts))}splice(e){throw Vt()}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}};const ao=e=>new io(ro(e.readString(),e.readAny()));var oo=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 Vt()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}};const so=e=>new oo(e.readJSON());var co=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 Vt()}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}};const lo=e=>new co(e.readKey(),e.readJSON());var uo=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}};const fo=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 uo(n)},po=In(`node_env`)===`development`;var mo=class e{constructor(e){this.arr=e,po&&En(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}};const ho=e=>{let t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new mo(n)};var go=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}};const _o=e=>new go(e.readString()),vo=[ya,Sa,Ba,Ga,Ua,Ja,Xa],yo=0,bo=1,xo=2,So=3,Co=4,wo=5,To=6;var Eo=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 Vt()}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}};const Do=e=>new Eo(vo[e.readTypeRef()](e)),Oo=(e,t,n)=>{let{client:r,clock:i}=t.id,a=new ko(W(r,i+n),t,W(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=W(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};var ko=class e extends Za{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>=di(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=di(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===$r&&this.id.client!==this.parent.client&&this.parent.clock>=di(n,this.parent.client))return this.parent.client;if(this.origin&&=(this.left=_i(t,n,this.origin),this.left.lastId),this.rightOrigin&&=(this.right=gi(t,this.rightOrigin),this.right.id),this.left&&this.left.constructor===Qa||this.right&&this.right.constructor===Qa)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===$r){let e=mi(n,this.parent);e.constructor===Qa?this.parent=null:this.parent=e.content.type}return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=_i(e,e.doc.store,W(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),ei(this.origin,n.origin)){if(n.id.client<this.id.client)t=n,r.clear();else if(ei(this.rightOrigin,n.rightOrigin))break}else if(n.origin!==null&&i.has(mi(e.doc.store,n.origin)))r.has(mi(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),fi(e.doc.store,this),this.content.integrate(e,this),Si(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new Qa(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:W(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&ei(e.origin,this.lastId)&&this.right===e&&ei(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(),mr(e.deleteSet,this.id.client,this.id.clock,this.length),Si(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw Ht();this.content.gc(e),t?vi(e,this,new Qa(this.id,this.length)):this.content=new to(this.length)}write(e,t){let n=t>0?W(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=ti(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===$r?(e.writeParentInfo(!1),e.writeLeftID(t)):Ht();i!==null&&e.writeString(i)}this.content.write(e,t)}};const Ao=(e,t)=>jo[t&31](e),jo=[()=>{Ht()},no,fo,eo,_o,so,lo,Do,ho,ao,()=>{Ht()}];var Mo=class extends Za{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor?(this.length+=e.length,!0):!1}integrate(e,t){Ht()}write(e,t){e.writeInfo(10),H(e.restEncoder,this.length-t)}getMissing(e,t){return null}};const No=typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:{},Po=`__ $YJS$ __`;No[Po]===!0&&console.error(`Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438`),No[Po]=!0;const Fo=/[\uD800-\uDBFF]/,Io=/[\uDC00-\uDFFF]/,Lo=(e,t)=>{let n=0,r=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n++;for(n>0&&Fo.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&&Io.test(e[e.length-r])&&r--,{index:n,remove:e.length-n-r,insert:t.slice(n,t.length-r)}},Ro=e=>{let t=Oe(`sha256`);return t.update(e),t.digest()},zo=new i(`y-sync`);new i(`y-undo`),new i(`yjs-cursor`);const Bo=e=>{for(let t=6;t<e.length;t++)e[t%6]=e[t%6]^e[t];return e.slice(0,6)},Vo=e=>Bn(Bo(Ro(Hn(e)))),Ho=()=>({mapping:new Map,isOMark:new Map}),Uo=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&t.sv.get(e.id.client)>e.id.clock&&!dr(t.ds,e.id),Wo=(e,t,n,r,i,a)=>{let o=n.mapping.get(e);if(o===void 0){if(e instanceof Wa)return Go(e,t,n,r,i,a);throw Vt()}return o},Go=(e,t,n,r,i,a)=>{let o=[],s=e=>{if(e instanceof Wa){let s=Wo(e,t,n,r,i,a);s!==null&&o.push(s)}else{let s=e._item.right?.content?.type;s instanceof za&&!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=Ko(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):ea(e,new ni(i.ds,r.sv)).forEach(s);try{let s=e.getAttributes(r);r!==void 0&&(Uo(e._item,r)?Uo(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}},Ko=(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,ss(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},qo=(e,t)=>{let n=new Ya,r=e.map(e=>({insert:e.text,attributes:cs(e.marks,t)}));return n.applyDelta(r),t.mapping.set(n,e),n},Jo=(e,t)=>{let n=new Wa(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,Qo(e).map(e=>Yo(e,t))),t.mapping.set(n,e),n},Yo=(e,t)=>e instanceof Array?qo(e,t):Jo(e,t),Xo=e=>typeof e==`object`&&!!e,Zo=(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||Xo(o)&&Xo(s)&&Zo(o,s)}return r},Qo=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},$o=(e,t)=>{let n=e.toDelta();return n.length===t.length&&n.every((e,n)=>e.insert===t[n].text&&vn(e.attributes||{}).length===t[n].marks.length&&Sn(e.attributes,(e,r)=>{let i=os(r),a=t[n].marks;return a.find(e=>e.type.name===i)?Zo(e,a.find(e=>e.type.name===i)?.attrs):!1}))},es=(e,t)=>{if(e instanceof Wa&&!(t instanceof Array)&&us(e,t)){let n=Qo(t);return e._length===n.length&&Zo(e.getAttributes(),t.attrs)&&e.toArray().every((e,t)=>es(e,n[t]))}return e instanceof Ya&&t instanceof Array&&$o(e,t)},ts=(e,t)=>e===t||e instanceof Array&&t instanceof Array&&e.length===t.length&&e.every((e,n)=>t[n]===e),ns=(e,t,n)=>{let r=e.toArray(),i=Qo(t),a=i.length,o=r.length,s=Qe(o,a),c=0,l=0,u=!1;for(;c<s;c++){let e=r[c],t=i[c];if(ts(n.mapping.get(e),t))u=!0;else if(!es(e,t))break}for(;c+l<s;l++){let e=r[o-l-1],t=i[a-l-1];if(ts(n.mapping.get(e),t))u=!0;else if(!es(e,t))break}return{equalityFactor:c+l,foundMappedChild:u}},rs=e=>{let t=``,n=e._start,r={};for(;n!==null;)n.deleted||(n.countable&&n.content instanceof go?t+=n.content.str:n.content instanceof co&&(r[n.content.key]=null)),n=n.right;return{str:t,nAttrs:r}},is=(e,t,n)=>{n.mapping.set(e,t);let{nAttrs:r,str:i}=rs(e),a=t.map(e=>({insert:e.text,attributes:Object.assign({},r,cs(e.marks,n))})),{insert:o,remove:s,index:c}=Lo(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})))},as=/(.*)(--[a-zA-Z0-9+/=]{8})$/,os=e=>as.exec(e)?.[1]??e,ss=(e,t)=>{let n=[];for(let r in e)n.push(t.mark(os(r),e[r]));return n},cs=(e,t)=>{let n={};return e.forEach(e=>{if(e.type.name!==`ychange`){let r=He(t.isOMark,e.type,()=>!e.type.excludes(e.type));n[r?`${e.type.name}--${Vo(e.toJSON())}`:e.type.name]=e.attrs}}),n},ls=(e,t,n,r)=>{if(t instanceof Wa&&t.nodeName!==n.type.name)throw Error(`node name mismatch!`);if(r.mapping.set(t,n),t instanceof Wa){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=Qo(n),a=i.length,o=t.toArray(),s=o.length,c=Qe(a,s),l=0,u=0;for(;l<c;l++){let e=o[l],t=i[l];if(!ts(r.mapping.get(e),t))if(es(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(!ts(r.mapping.get(e),t))if(es(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 Ya&&c instanceof Array)$o(n,c)||is(n,c,r),l+=1;else{let i=n instanceof Wa&&us(n,c),a=d instanceof Wa&&us(d,f);if(i&&a){let e=ns(n,c,r),t=ns(d,f,r);e.foundMappedChild&&!t.foundMappedChild?a=!1:!e.foundMappedChild&&t.foundMappedChild||e.equalityFactor<t.equalityFactor?i=!1:a=!1}i?(ls(e,n,c,r),l+=1):a?(ls(e,d,f,r),u+=1):(r.mapping.delete(t.get(l)),t.delete(l,1),t.insert(l,[Yo(c,r)]),l+=1)}}let n=s-l-u;if(s===1&&a===0&&o[0]instanceof Ya?(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(Yo(i[t],r));t.insert(l,e)}},zo)},us=(e,t)=>!(t instanceof Array)&&e.nodeName===t.type.name,ds=(e,t)=>{let n=e.toArray().map(e=>Go(e,t,Ho())).filter(e=>e!==null);return k.fromArray(n)},fs=(e,t)=>t.topNodeType.create(null,ds(e,t));var ps=n(((e,t)=>{let n=e=>e&&typeof e.message==`string`,r=e=>{if(!e)return;let t=e.cause;if(typeof t==`function`){let t=e.cause();return n(t)?t:void 0}else return n(t)?t:void 0},i=(e,t)=>{if(!n(e))return``;let a=e.stack||``;if(t.has(e))return a+`
1
+ import{i as e,r as t,t as n}from"./chunk-tuRmWmEN.mjs";import{A as r,C as i,E as a,S as o,T as s,_ as c,a as l,b as u,c as d,d as f,f as p,g as m,h,i as g,j as _,k as v,l as y,m as b,n as x,o as S,p as C,r as w,s as T,t as E,u as D,v as O,w as k,x as A,y as j}from"./src-CdcLi3q2.mjs";import{d as M,f as ee,i as N,l as te,n as ne,o as P,r as re,s as F,u as ie}from"./server-lock-B4frNnOB.mjs";import{n as ae,t as I}from"./git-handle-C_GYoScT.mjs";import{createRequire as oe}from"node:module";import{closeSync as se,existsSync as L,lstatSync as ce,mkdirSync as le,openSync as ue,readFileSync as R,readdirSync as de,realpathSync as fe,renameSync as pe,rmSync as me,statSync as he,unlinkSync as ge,writeFileSync as z,writeSync as _e}from"node:fs";import{homedir as ve,hostname as ye,tmpdir as be}from"node:os";import{dirname as xe,extname as Se,join as Ce,posix as we,relative as B,resolve as V,sep as Te}from"node:path";import{URLSearchParams as Ee}from"node:url";import De,{createHash as Oe,randomUUID as ke,webcrypto as Ae}from"node:crypto";import{execFile as je,spawn as Me,spawnSync as Ne}from"node:child_process";import Pe from"simple-git";import{mkdir as Fe,readFile as Ie,realpath as Le,rename as Re,writeFile as ze}from"node:fs/promises";import"node:http";import Be from"picomatch";import{promisify as Ve}from"node:util";const He=()=>new Map,Ue=e=>{let t=He();return e.forEach((e,n)=>{t.set(n,e)}),t},We=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r},Ge=(e,t)=>{for(let[n,r]of e)if(t(r,n))return!0;return!1},Ke=()=>new Set,qe=e=>e[e.length-1],Je=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},Ye=Array.from,Xe=Array.isArray;var Ze=class{constructor(){this._observers=He()}on(e,t){return We(this._observers,e,Ke).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 Ye((this._observers.get(e)||He()).values()).forEach(e=>e(...t))}destroy(){this._observers=He()}};const Qe=Math.floor,$e=Math.abs,et=(e,t)=>e<t?e:t,tt=(e,t)=>e>t?e:t;Number.isNaN;const nt=e=>e===0?1/e<0:e<0,rt=2**53-1,it=Number.isInteger||(e=>typeof e==`number`&&isFinite(e)&&Qe(e)===e);Number.isNaN,Number.parseInt;const at=String.fromCharCode;String.fromCodePoint,at(65535);const ot=e=>e.toLowerCase(),st=/^\s*/g,ct=e=>e.replace(st,``),lt=/([A-Z])/g,ut=(e,t)=>ct(e.replace(lt,e=>`${t}${ot(e)}`)),dt=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},ft=typeof TextEncoder<`u`?new TextEncoder:null,pt=ft?e=>ft.encode(e):dt;let mt=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});mt&&mt.decode(new Uint8Array).length===1&&(mt=null);var ht=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const gt=()=>new ht,_t=e=>{let t=gt();return e(t),yt(t)},vt=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},yt=e=>{let t=new Uint8Array(vt(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},bt=(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(tt(n,t)*2),e.cpos=0)},xt=(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},St=xt,H=(e,t)=>{for(;t>127;)xt(e,128|127&t),t=Qe(t/128);xt(e,127&t)},Ct=(e,t)=>{let n=nt(t);for(n&&(t=-t),xt(e,(t>63?128:0)|(n?64:0)|63&t),t=Qe(t/64);t>0;)xt(e,(t>127?128:0)|127&t),t=Qe(t/128)},wt=new Uint8Array(3e4),Tt=wt.length/3,Et=ft&&ft.encodeInto?(e,t)=>{if(t.length<Tt){let n=ft.encodeInto(t,wt).written||0;H(e,n);for(let t=0;t<n;t++)xt(e,wt[t])}else Ot(e,pt(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;H(e,r);for(let t=0;t<r;t++)xt(e,n.codePointAt(t))},Dt=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=et(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(tt(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},Ot=(e,t)=>{H(e,t.byteLength),Dt(e,t)},kt=(e,t)=>{bt(e,t);let n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},At=(e,t)=>kt(e,4).setFloat32(0,t,!1),jt=(e,t)=>kt(e,8).setFloat64(0,t,!1),Mt=(e,t)=>kt(e,8).setBigInt64(0,t,!1),Nt=new DataView(new ArrayBuffer(4)),Pt=e=>(Nt.setFloat32(0,e),Nt.getFloat32(0)===e),Ft=(e,t)=>{switch(typeof t){case`string`:xt(e,119),Et(e,t);break;case`number`:it(t)&&$e(t)<=2147483647?(xt(e,125),Ct(e,t)):Pt(t)?(xt(e,124),At(e,t)):(xt(e,123),jt(e,t));break;case`bigint`:xt(e,122),Mt(e,t);break;case`object`:if(t===null)xt(e,126);else if(Xe(t)){xt(e,117),H(e,t.length);for(let n=0;n<t.length;n++)Ft(e,t[n])}else if(t instanceof Uint8Array)xt(e,116),Ot(e,t);else{xt(e,118);let n=Object.keys(t);H(e,n.length);for(let r=0;r<n.length;r++){let i=n[r];Et(e,i),Ft(e,t[i])}}break;case`boolean`:xt(e,t?120:121);break;default:xt(e,127)}};var It=class extends ht{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&H(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}};const Lt=e=>{e.count>0&&(Ct(e.encoder,e.count===1?e.s:-e.s),e.count>1&&H(e.encoder,e.count-2))};var Rt=class{constructor(){this.encoder=new ht,this.s=0,this.count=0}write(e){this.s===e?this.count++:(Lt(this),this.count=1,this.s=e)}toUint8Array(){return Lt(this),yt(this.encoder)}};const zt=e=>{if(e.count>0){let t=e.diff*2+(e.count===1?0:1);Ct(e.encoder,t),e.count>1&&H(e.encoder,e.count-2)}};var Bt=class{constructor(){this.encoder=new ht,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(zt(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return zt(this),yt(this.encoder)}},Vt=class{constructor(){this.sarr=[],this.s=``,this.lensE=new Rt}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 ht;return this.sarr.push(this.s),this.s=``,Et(e,this.sarr.join(``)),Dt(e,this.lensE.toUint8Array()),yt(e)}};const Ht=e=>Error(e),Ut=()=>{throw Ht(`Method unimplemented`)},Wt=()=>{throw Ht(`Unexpected case`)},Gt=Ht(`Unexpected end of array`),Kt=Ht(`Integer out of Range`);var qt=class{constructor(e){this.arr=e,this.pos=0}};const Jt=e=>new qt(e),Yt=e=>e.pos!==e.arr.length,Xt=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},Zt=e=>Xt(e,U(e)),Qt=e=>e.arr[e.pos++],U=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>rt)throw Kt}throw Gt},$t=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>rt)throw Kt}throw Gt},en=mt?e=>mt.decode(Zt(e)):e=>{let t=U(e);if(t===0)return``;{let n=String.fromCodePoint(Qt(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Qt(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))}},tn=(e,t)=>{let n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},nn=[e=>void 0,e=>null,$t,e=>tn(e,4).getFloat32(0,!1),e=>tn(e,8).getFloat64(0,!1),e=>tn(e,8).getBigInt64(0,!1),e=>!1,e=>!0,en,e=>{let t=U(e),n={};for(let r=0;r<t;r++){let t=en(e);n[t]=rn(e)}return n},e=>{let t=U(e),n=[];for(let r=0;r<t;r++)n.push(rn(e));return n},Zt],rn=e=>nn[127-Qt(e)](e);var an=class extends qt{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Yt(this)?this.count=U(this)+1:this.count=-1),this.count--,this.s}},on=class extends qt{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=$t(this);let e=nt(this.s);this.count=1,e&&(this.s=-this.s,this.count=U(this)+2)}return this.count--,this.s}},sn=class extends qt{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){let e=$t(this),t=e&1;this.diff=Qe(e/2),this.count=1,t&&(this.count=U(this)+2)}return this.s+=this.diff,this.count--,this.s}},cn=class{constructor(e){this.decoder=new on(e),this.str=en(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}};Ae.subtle;const ln=Ae.getRandomValues.bind(Ae),un=()=>ln(new Uint32Array(1))[0],dn=()=>`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^un()&15>>e/4).toString(16)),fn=Date.now,pn=e=>new Promise(e);Promise.all.bind(Promise);const mn=e=>e===void 0?null:e;let hn=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&&(hn=localStorage)}catch{}const gn=hn,_n=Symbol(`Equality`),vn=(e,t)=>e===t||!!e?.[_n]?.(t)||!1,yn=Object.assign,bn=Object.keys,xn=(e,t)=>{for(let n in e)t(e[n],n)},Sn=e=>bn(e).length,Cn=e=>{for(let t in e)return!1;return!0},wn=(e,t)=>{for(let n in e)if(!t(e[n],n))return!1;return!0},Tn=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),En=(e,t)=>e===t||Sn(e)===Sn(t)&&wn(e,(e,n)=>(e!==void 0||Tn(t,n))&&vn(t[n],e)),Dn=Object.freeze,On=e=>{for(let t in e){let n=e[t];(typeof n==`object`||typeof n==`function`)&&On(e[t])}return Dn(e)},kn=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&kn(e,t,n+1)}},An=e=>e,jn=(e,t)=>t.includes(e),Mn=typeof process<`u`&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<`u`?process:0)===`[object process]`,Nn=typeof window<`u`&&typeof document<`u`&&!Mn;typeof navigator<`u`&&/Mac/.test(navigator.platform);let Pn;const Fn=[],In=()=>{if(Pn===void 0)if(Mn){Pn=He();let e=process.argv,t=null;for(let n=0;n<e.length;n++){let r=e[n];r[0]===`-`?(t!==null&&Pn.set(t,``),t=r):t===null?Fn.push(r):(Pn.set(t,r),t=null)}t!==null&&Pn.set(t,``)}else typeof location==`object`?(Pn=He(),(location.search||`?`).slice(1).split(`&`).forEach(e=>{if(e.length!==0){let[t,n]=e.split(`=`);Pn.set(`--${ut(t,`-`)}`,n),Pn.set(`-${ut(t,`-`)}`,n)}})):Pn=He();return Pn},Ln=e=>In().has(e),Rn=e=>mn(Mn?process.env[e.toUpperCase().replaceAll(`-`,`_`)]:gn.getItem(e)),zn=e=>Ln(`--`+e)||Rn(e)!==null;zn(`production`);const Bn=Mn&&jn(process.env.FORCE_COLOR,[`true`,`1`,`2`])||!Ln(`--no-colors`)&&!zn(`no-color`)&&(!Mn||process.stdout.isTTY)&&(!Mn||Ln(`--color`)||Rn(`COLORTERM`)!==null||(Rn(`TERM`)||``).includes(`color`)),Vn=e=>new Uint8Array(e),Hn=Nn?e=>{let t=``;for(let n=0;n<e.byteLength;n++)t+=at(e[n]);return btoa(t)}:e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64`),Un=e=>{let t=Vn(e.byteLength);return t.set(e),t},Wn=e=>_t(t=>Ft(t,e)),Gn=Symbol,Kn=Gn(),qn=Gn(),Jn=Gn(),Yn=Gn(),Xn=Gn(),Zn=Gn(),Qn=Gn(),$n=Gn(),er=Gn(),tr=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};fn();const nr={[Kn]:`\x1B[1m`,[qn]:`\x1B[2m`,[Jn]:`\x1B[34m`,[Xn]:`\x1B[32m`,[Yn]:`\x1B[37m`,[Zn]:`\x1B[31m`,[Qn]:`\x1B[35m`,[$n]:`\x1B[38;5;208m`,[er]:`\x1B[0m`},rr=Bn?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],i=nr[n];if(i!==void 0)t.push(i);else if(n===void 0)break;else if(n.constructor===String||n.constructor===Number)t.push(n);else break}for(r>0&&(t.push(`\x1B[0m`),n.push(t.join(``)));r<e.length;r++){let t=e[r];t instanceof Symbol||n.push(t)}return n}:tr,ir=(...e)=>{console.log(...rr(e))},ar=(...e)=>{console.warn(...rr(e))},or=e=>({[Symbol.iterator](){return this},next:e}),sr=(e,t)=>or(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),cr=(e,t)=>or(()=>{let{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}});var lr=class{constructor(e,t){this.clock=e,this.len=t}},ur=class{constructor(){this.clients=new Map}};const dr=(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])xi(e,i,o.clock,o.len,n)}}),fr=(e,t)=>{let n=0,r=e.length-1;for(;n<=r;){let i=Qe((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},pr=(e,t)=>{let n=e.clients.get(t.client);return n!==void 0&&fr(n,t.clock)!==null},mr=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 lr(r.clock,tt(r.len,i.clock+i.len-r.clock)):(n<t&&(e[n]=i),n++)}e.length=n})},hr=e=>{let t=new ur;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++)Je(a,e[t].clients.get(i)||[]);t.clients.set(i,a)}});return mr(t),t},gr=(e,t,n,r)=>{We(e.clients,t,()=>[]).push(new lr(n,r))},_r=()=>new ur,vr=e=>{let t=_r();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 lr(i,a))}}r.length>0&&t.clients.set(n,r)}),t},yr=(e,t)=>{H(e.restEncoder,t.clients.size),Ye(t.clients.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{e.resetDsCurVal(),H(e.restEncoder,t);let r=n.length;H(e.restEncoder,r);for(let t=0;t<r;t++){let r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}})},br=e=>{let t=new ur,n=U(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();let n=U(e.restDecoder),r=U(e.restDecoder);if(r>0){let i=We(t.clients,n,()=>[]);for(let t=0;t<r;t++)i.push(new lr(e.readDsClock(),e.readDsLen()))}}return t},xr=(e,t,n)=>{let r=new ur,i=U(e.restDecoder);for(let a=0;a<i;a++){e.resetDsCurVal();let i=U(e.restDecoder),a=U(e.restDecoder),o=n.clients.get(i)||[],s=pi(n,i);for(let n=0;n<a;n++){let n=e.readDsClock(),a=n+e.readDsLen();if(n<s){s<a&&gr(r,i,s,a-s);let e=hi(o,n),c=o[e];for(!c.deleted&&c.id.clock<n&&(o.splice(e+1,0,Ao(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,Ao(t,c,a-c.id.clock)),c.delete(t))}else gr(r,i,n,a-n)}}if(r.clients.size>0){let e=new Mr;return H(e.restEncoder,0),yr(e,r),e.toUint8Array()}return null},Sr=(e,t)=>{if(e.clients.size!==t.clients.size)return!1;for(let[n,r]of e.clients.entries()){let e=t.clients.get(n);if(e===void 0||r.length!==e.length)return!1;for(let t=0;t<r.length;t++){let n=r[t],i=e[t];if(n.clock!==i.clock||n.len!==i.len)return!1}}return!0},Cr=un;var wr=class e extends Ze{constructor({guid:e=dn(),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=Cr(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new di,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=pn(e=>{this.on(`load`,()=>{this.isLoaded=!0,e(this)})});let s=()=>pn(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&&G(e.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Ye(this.subdocs).map(e=>e.guid))}transact(e,t=null){return G(this,e,t)}get(e,t=$i){let n=We(this.share,e,()=>{let e=new t;return e._integrate(this,null),e}),r=n.constructor;if(t!==$i&&r!==t)if(r===$i){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,ba)}getText(e=``){return this.get(e,Va)}getMap(e=``){return this.get(e,Ca)}getXmlElement(e=``){return this.get(e,Ka)}getXmlFragment(e=``){return this.get(e,Wa)}toJSON(){let e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,Ye(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,G(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()}},Tr=class{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return U(this.restDecoder)}readDsLen(){return U(this.restDecoder)}},Er=class extends Tr{readLeftID(){return W(U(this.restDecoder),U(this.restDecoder))}readRightID(){return W(U(this.restDecoder),U(this.restDecoder))}readClient(){return U(this.restDecoder)}readInfo(){return Qt(this.restDecoder)}readString(){return en(this.restDecoder)}readParentInfo(){return U(this.restDecoder)===1}readTypeRef(){return U(this.restDecoder)}readLen(){return U(this.restDecoder)}readAny(){return rn(this.restDecoder)}readBuf(){return Un(Zt(this.restDecoder))}readJSON(){return JSON.parse(en(this.restDecoder))}readKey(){return en(this.restDecoder)}},Dr=class{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=U(this.restDecoder),this.dsCurrVal}readDsLen(){let e=U(this.restDecoder)+1;return this.dsCurrVal+=e,e}},Or=class extends Dr{constructor(e){super(e),this.keys=[],U(e),this.keyClockDecoder=new sn(Zt(e)),this.clientDecoder=new on(Zt(e)),this.leftClockDecoder=new sn(Zt(e)),this.rightClockDecoder=new sn(Zt(e)),this.infoDecoder=new an(Zt(e),Qt),this.stringDecoder=new cn(Zt(e)),this.parentInfoDecoder=new an(Zt(e),Qt),this.typeRefDecoder=new on(Zt(e)),this.lenDecoder=new on(Zt(e))}readLeftID(){return new ti(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new ti(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 rn(this.restDecoder)}readBuf(){return Zt(this.restDecoder)}readJSON(){return rn(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}}},kr=class{constructor(){this.restEncoder=gt()}toUint8Array(){return yt(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){H(this.restEncoder,e)}writeDsLen(e){H(this.restEncoder,e)}},Ar=class extends kr{writeLeftID(e){H(this.restEncoder,e.client),H(this.restEncoder,e.clock)}writeRightID(e){H(this.restEncoder,e.client),H(this.restEncoder,e.clock)}writeClient(e){H(this.restEncoder,e)}writeInfo(e){St(this.restEncoder,e)}writeString(e){Et(this.restEncoder,e)}writeParentInfo(e){H(this.restEncoder,e?1:0)}writeTypeRef(e){H(this.restEncoder,e)}writeLen(e){H(this.restEncoder,e)}writeAny(e){Ft(this.restEncoder,e)}writeBuf(e){Ot(this.restEncoder,e)}writeJSON(e){Et(this.restEncoder,JSON.stringify(e))}writeKey(e){Et(this.restEncoder,e)}},jr=class{constructor(){this.restEncoder=gt(),this.dsCurrVal=0}toUint8Array(){return yt(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){let t=e-this.dsCurrVal;this.dsCurrVal=e,H(this.restEncoder,t)}writeDsLen(e){e===0&&Wt(),H(this.restEncoder,e-1),this.dsCurrVal+=e}},Mr=class extends jr{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new Bt,this.clientEncoder=new Rt,this.leftClockEncoder=new Bt,this.rightClockEncoder=new Bt,this.infoEncoder=new It(St),this.stringEncoder=new Vt,this.parentInfoEncoder=new It(St),this.typeRefEncoder=new Rt,this.lenEncoder=new Rt}toUint8Array(){let e=gt();return H(e,0),Ot(e,this.keyClockEncoder.toUint8Array()),Ot(e,this.clientEncoder.toUint8Array()),Ot(e,this.leftClockEncoder.toUint8Array()),Ot(e,this.rightClockEncoder.toUint8Array()),Ot(e,yt(this.infoEncoder)),Ot(e,this.stringEncoder.toUint8Array()),Ot(e,yt(this.parentInfoEncoder)),Ot(e,this.typeRefEncoder.toUint8Array()),Ot(e,this.lenEncoder.toUint8Array()),Dt(e,yt(this.restEncoder)),yt(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(e?1:0)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){Ft(this.restEncoder,e)}writeBuf(e){Ot(this.restEncoder,e)}writeJSON(e){Ft(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)}};const Nr=(e,t,n,r)=>{r=tt(r,t[0].id.clock);let i=hi(t,r);H(e.restEncoder,t.length-i),e.writeClient(n),H(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)},Pr=(e,t,n)=>{let r=new Map;n.forEach((e,n)=>{pi(t,n)>e&&r.set(n,e)}),fi(t).forEach((e,t)=>{n.has(t)||r.set(t,0)}),H(e.restEncoder,r.size),Ye(r.entries()).sort((e,t)=>t[0]-e[0]).forEach(([n,r])=>{Nr(e,t.clients.get(n),n,r)})},Fr=(e,t)=>{let n=He(),r=U(e.restDecoder);for(let i=0;i<r;i++){let r=U(e.restDecoder),i=Array(r),a=e.readClient(),o=U(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 eo(W(a,o),t),o+=t;break}case 10:{let t=U(e.restDecoder);i[n]=new Po(W(a,o),t),o+=t;break}default:{let s=(r&192)==0,c=new jo(W(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,Mo(e,r));i[n]=c,o+=c.length}}}}return n},Ir=(e,t,n)=>{let r=[],i=Ye(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 di,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!==Po){let i=We(d,u.id.client,()=>pi(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,pi(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 Mr;return Pr(e,s,new Map),H(e.restEncoder,0),{missing:c,update:e.toUint8Array()}}return null},Lr=(e,t)=>Pr(e,t.doc.store,t.beforeState),Rr=(e,t,n,r=new Or(e))=>G(t,e=>{e.local=!1;let t=!1,n=e.doc,i=n.store,a=Ir(e,i,Fr(r,n)),o=i.pendingStructs;if(o){for(let[e,n]of o.missing)if(n<pi(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=Pi([o.update,a.update])}}else i.pendingStructs=a;let s=xr(r,e,i);if(i.pendingDs){let t=new Or(Jt(i.pendingDs));U(t.restDecoder);let n=xr(t,e,i);s&&n?i.pendingDs=Pi([s,n]):i.pendingDs=s||n}else i.pendingDs=s;if(t){let t=i.pendingStructs.update;i.pendingStructs=null,zr(e.doc,t)}},n,!1),zr=(e,t,n,r=Or)=>{let i=Jt(t);Rr(i,e,n,new r(i))},Br=(e,t,n)=>zr(e,t,n,Er),Vr=(e,t,n=new Map)=>{Pr(e,t.store,n),yr(e,vr(t.store))},Hr=(e,t=new Uint8Array([0]),n=new Mr)=>{Vr(n,e,Gr(t));let r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Fi(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===Ar)return Mi(r.map((e,t)=>t===0?e:Bi(e)));if(n.constructor===Mr)return Pi(r)}return r[0]},Ur=(e,t)=>Hr(e,t,new Ar),Wr=e=>{let t=new Map,n=U(e.restDecoder);for(let r=0;r<n;r++){let n=U(e.restDecoder),r=U(e.restDecoder);t.set(n,r)}return t},Gr=e=>Wr(new Tr(Jt(e))),Kr=(e,t)=>(H(e.restEncoder,t.size),Ye(t.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{H(e.restEncoder,t),H(e.restEncoder,n)}),e),qr=(e,t)=>Kr(e,fi(t.store)),Jr=(e,t=new jr)=>(e instanceof Map?Kr(t,e):qr(t,e),t.toUint8Array()),Yr=e=>Jr(e,new kr);var Xr=class{constructor(){this.l=[]}};const Zr=()=>new Xr,Qr=(e,t)=>e.l.push(t),$r=(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.`)},ei=(e,t,n)=>kn(e.l,[t,n]);var ti=class{constructor(e,t){this.client=e,this.clock=t}};const ni=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,W=(e,t)=>new ti(e,t),ri=e=>{for(let[t,n]of e.doc.share.entries())if(n===e)return t;throw Wt()};var ii=class{constructor(e,t){this.ds=e,this.sv=t}};const ai=(e,t)=>new ii(e,t);ai(_r(),new Map);const oi=e=>ai(vr(e.store),fi(e.store)),si=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!pr(t.ds,e.id),ci=(e,t)=>{let n=We(e.meta,ci,Ke),r=e.doc.store;n.has(t)||(t.sv.forEach((t,n)=>{t<pi(r,n)&&vi(e,W(n,t))}),dr(e,t.ds,e=>{}),n.add(t))},li=(e,t,n=Or)=>{let r=new n(Jt(t)),i=new Ai(r,!1);for(let t=i.curr;t!==null;t=i.next())if((e.sv.get(t.id.client)||0)<t.id.clock+t.length)return!1;let a=hr([e.ds,br(r)]);return Sr(e.ds,a)},ui=(e,t)=>li(e,t,Er);var di=class{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}};const fi=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},pi=(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},mi=(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 Wt()}n.push(t)},hi=(e,t)=>{let n=0,r=e.length-1,i=e[r],a=i.id.clock;if(a===t)return r;let o=Qe(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=Qe((n+r)/2)}throw Wt()},gi=(e,t)=>{let n=e.clients.get(t.client);return n[hi(n,t.clock)]},_i=(e,t,n)=>{let r=hi(t,n),i=t[r];return i.id.clock<n&&i instanceof jo?(t.splice(r+1,0,Ao(e,i,n-i.id.clock)),r+1):r},vi=(e,t)=>{let n=e.doc.store.clients.get(t.client);return n[_i(e,n,t.clock)]},yi=(e,t,n)=>{let r=t.clients.get(n.client),i=hi(r,n.clock),a=r[i];return n.clock!==a.id.clock+a.length-1&&a.constructor!==eo&&r.splice(i+1,0,Ao(e,a,n.clock-a.id.clock+1)),a},bi=(e,t,n)=>{let r=e.clients.get(t.id.client);r[hi(r,t.id.clock)]=n},xi=(e,t,n,r,i)=>{if(r===0)return;let a=n+r,o=_i(e,t,n),s;do s=t[o++],a<s.id.clock+s.length&&_i(e,t,a),i(s);while(o<t.length&&t[o].id.clock<a)};var Si=class{constructor(e,t,n){this.doc=e,this.deleteSet=new ur,this.beforeState=fi(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}};const Ci=(e,t)=>t.deleteSet.clients.size===0&&!Ge(t.afterState,(e,n)=>t.beforeState.get(n)!==e)?!1:(mr(t.deleteSet),Lr(e,t),yr(e,t.deleteSet),!0),wi=(e,t,n)=>{let r=t._item;(r===null||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&We(e.changed,t,Ke).add(n)},Ti=(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 jo&&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},Ei=(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=hi(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 jo&&i.deleted&&!i.keep&&n(i)&&i.gc(t,!1)}}}},Di=(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=et(r.length-1,1+hi(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+Ti(r,e)}})},Oi=(e,t)=>{if(t<e.length){let n=e[t],r=n.doc,i=r.store,a=n.deleteSet,o=n._mergeStructs;try{mr(a),n.afterState=fi(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(()=>{ei(r._dEH,t,n)}))}),e.push(()=>r.emit(`afterTransaction`,[n,r])),e.push(()=>{n._needFormattingCleanup&&Ra(n)})}),kn(e,[])}finally{r.gc&&Ei(a,i,r.gcFilter),Di(a,i),n.afterState.forEach((e,t)=>{let r=n.beforeState.get(t)||0;if(r!==e){let e=i.clients.get(t),n=tt(hi(e,r),1);for(let t=e.length-1;t>=n;)t-=1+Ti(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=hi(r,n);a+1<r.length&&Ti(r,a+1)>1||a>0&&Ti(r,a)}if(!n.local&&n.afterState.get(r.clientID)!==n.beforeState.get(r.clientID)&&(ir($n,Kn,`[yjs] `,qn,Zn,`Changed the client-id because another client seems to be using it.`),r.clientID=Cr()),r.emit(`afterTransactionCleanup`,[n,r]),r._observers.has(`update`)){let e=new Ar;Ci(e,n)&&r.emit(`update`,[e.toUint8Array(),n.origin,r,n])}if(r._observers.has(`updateV2`)){let e=new Mr;Ci(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])):Oi(e,t+1)}}},G=(e,t,n=null,r=!0)=>{let i=e._transactionCleanups,a=!1,o=null;e._transaction===null&&(a=!0,e._transaction=new Si(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&&Oi(i,0)}}return o};function*ki(e){let t=U(e.restDecoder);for(let n=0;n<t;n++){let t=U(e.restDecoder),n=e.readClient(),r=U(e.restDecoder);for(let i=0;i<t;i++){let t=e.readInfo();if(t===10){let t=U(e.restDecoder);yield new Po(W(n,r),t),r+=t}else if(31&t){let i=(t&192)==0,a=new jo(W(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,Mo(e,t));yield a,r+=a.length}else{let t=e.readLen();yield new eo(W(n,r),t),r+=t}}}}var Ai=class{constructor(e,t){this.gen=ki(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===Po);return this.curr}},ji=class{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}};const Mi=e=>Pi(e,Er,Ar),Ni=(e,t)=>{if(e.constructor===eo){let{client:n,clock:r}=e.id;return new eo(W(n,r+t),e.length-t)}else if(e.constructor===Po){let{client:n,clock:r}=e.id;return new Po(W(n,r+t),e.length-t)}else{let n=e,{client:r,clock:i}=n.id;return new jo(W(r,i+t),null,W(r,i+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Pi=(e,t=Or,n=Mr)=>{if(e.length===1)return e[0];let r=e.map(e=>new t(Jt(e))),i=r.map(e=>new Ai(e,!0)),a=null,o=new n,s=new ji(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===Po?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)Li(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===Po)a.struct.length=n.id.clock+n.length-a.struct.id.clock;else{Li(s,a.struct,a.offset);let e=n.id.clock-a.struct.id.clock-a.struct.length;a={struct:new Po(W(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===Po?a.struct.length-=t:n=Ni(n,t)),a.struct.mergeWith(n)||(Li(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!==Po;n=e.next())Li(s,a.struct,a.offset),a={struct:n,offset:0}}return a!==null&&(Li(s,a.struct,a.offset),a=null),Ri(s),yr(o,hr(r.map(e=>br(e)))),o.toUint8Array()},Fi=(e,t,n=Or,r=Mr)=>{let i=Gr(t),a=new r,o=new ji(a),s=new n(Jt(e)),c=new Ai(s,!1);for(;c.curr;){let e=c.curr,t=e.id.client,n=i.get(t)||0;if(c.curr.constructor===Po){c.next();continue}if(e.id.clock+e.length>n)for(Li(o,e,tt(n-e.id.clock,0)),c.next();c.curr&&c.curr.id.client===t;)Li(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 Ri(o),yr(a,br(s)),a.toUint8Array()},Ii=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:yt(e.encoder.restEncoder)}),e.encoder.restEncoder=gt(),e.written=0)},Li=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&Ii(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),H(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},Ri=e=>{Ii(e);let t=e.encoder.restEncoder;H(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){let r=e.clientStructs[n];H(t,r.written),Dt(t,r.restEncoder)}},zi=(e,t,n,r)=>{let i=new n(Jt(e)),a=new Ai(i,!1),o=new r,s=new ji(o);for(let e=a.curr;e!==null;e=a.next())Li(s,t(e),0);return Ri(s),yr(o,br(i)),o.toUint8Array()},Bi=e=>zi(e,An,Or,Ar),Vi=`You must not compute changes after the event-handler fired.`;var Hi=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||=Ui(this.currentTarget,this.target)}deletes(e){return pr(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ht(Vi);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=qe(e.content.getContent());else return;else e!==null&&this.deletes(e)?(i=`update`,a=qe(e.content.getContent())):(i=`add`,a=void 0)}else if(this.deletes(r))i=`delete`,a=qe(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 Ht(Vi);let t=this.target,n=Ke(),r=Ke(),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}};const Ui=(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},Wi=()=>{ar(`Invalid access: Add Yjs type to a document before reading data.`)};let Gi=0;var Ki=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=Gi++}};const qi=e=>{e.timestamp=Gi++},Ji=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=Gi++},Yi=(e,t,n)=>{if(e.length>=80){let r=e.reduce((e,t)=>e.timestamp<t.timestamp?e:t);return Ji(r,t,n),r}else{let r=new Ki(t,n);return e.push(r),r}},Xi=(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)=>$e(t-e.index)<$e(t-n.index)?e:n),r=e._start,i=0;for(n!==null&&(r=n.p,i=n.index,qi(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&&$e(n.index-i)<r.parent.length/80?(Ji(n,r,i),n):Yi(e._searchMarker,r,i)},Zi=(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=tt(t,i.index+n))}},Qi=(e,t,n)=>{let r=e,i=t.changedParentTypes;for(;We(i,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;ei(r._eH,n,t)};var $i=class{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Zr(),this._dEH=Zr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw Ut()}clone(){throw Ut()}_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){Qr(this._eH,e)}observeDeep(e){Qr(this._dEH,e)}unobserve(e){$r(this._eH,e)}unobserveDeep(e){$r(this._dEH,e)}toJSON(){}};const ea=(e,t,n)=>{e.doc??Wi(),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},ta=e=>{e.doc??Wi();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},na=(e,t)=>{let n=[],r=e._start;for(;r!==null;){if(r.countable&&si(r,t)){let e=r.content.getContent();for(let t=0;t<e.length;t++)n.push(e[t])}r=r.right}return n},ra=(e,t)=>{let n=0,r=e._start;for(e.doc??Wi();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}},ia=(e,t)=>{let n=[];return ra(e,(r,i)=>{n.push(t(r,i,e))}),n},aa=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}}}},oa=(e,t)=>{e.doc??Wi();let n=Xi(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}},sa=(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 jo(W(o,pi(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new go(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 jo(W(o,pi(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new to(new Uint8Array(n))),i.integrate(e,0);break;case wr:i=new jo(W(o,pi(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new oo(n)),i.integrate(e,0);break;default:if(n instanceof $i)i=new jo(W(o,pi(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Oo(n)),i.integrate(e,0);else throw Error(`Unexpected content type in insert operation`)}}}),u()},ca=()=>Ht(`Length exceeded!`),la=(e,t,n,r)=>{if(n>t._length)throw ca();if(n===0)return t._searchMarker&&Zi(t._searchMarker,n,r.length),sa(e,t,null,r);let i=n,a=Xi(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&&vi(e,W(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&Zi(t._searchMarker,i,r.length),sa(e,t,o,r)},ua=(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 sa(e,t,r,n)},da=(e,t,n,r)=>{if(r===0)return;let i=n,a=r,o=Xi(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&&vi(e,W(s.id.client,s.id.clock+n)),n-=s.length);for(;r>0&&s!==null;)s.deleted||(r<s.length&&vi(e,W(s.id.client,s.id.clock+r)),s.delete(e),r-=s.length),s=s.right;if(r>0)throw ca();t._searchMarker&&Zi(t._searchMarker,i,-a+r)},fa=(e,t,n)=>{let r=t._map.get(n);r!==void 0&&r.delete(e)},pa=(e,t,n,r)=>{let i=t._map.get(n)||null,a=e.doc,o=a.clientID,s;if(r==null)s=new go([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:s=new go([r]);break;case Uint8Array:s=new to(r);break;case wr:s=new oo(r);break;default:if(r instanceof $i)s=new Oo(r);else throw Error(`Unexpected content type`)}new jo(W(o,pi(a.store,o)),i,i&&i.lastId,null,null,t,n,s).integrate(e,0)},ma=(e,t)=>{e.doc??Wi();let n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},ha=e=>{let t={};return e.doc??Wi(),e._map.forEach((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])}),t},ga=(e,t)=>{e.doc??Wi();let n=e._map.get(t);return n!==void 0&&!n.deleted},_a=(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&&si(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},va=e=>(e.doc??Wi(),sr(e._map.entries(),e=>!e[1].deleted));var ya=class extends Hi{},ba=class e extends $i{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 $i?e.clone():e)),t}get length(){return this.doc??Wi(),this._length}_callObserver(e,t){super._callObserver(e,t),Qi(this,e,new ya(this,e))}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):G(this.doc,n=>{la(n,this,e,t)})}push(e){this.doc===null?this._prelimContent.push(...e):G(this.doc,t=>{ua(t,this,e)})}unshift(e){this.insert(0,e)}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):G(this.doc,n=>{da(n,this,e,t)})}get(e){return oa(this,e)}toArray(){return ta(this)}slice(e=0,t=this.length){return ea(this,e,t)}toJSON(){return this.map(e=>e instanceof $i?e.toJSON():e)}map(e){return ia(this,e)}forEach(e){ra(this,e)}[Symbol.iterator](){return aa(this)}_write(e){e.writeTypeRef(xo)}};const xa=e=>new ba;var Sa=class extends Hi{constructor(e,t,n){super(e,t),this.keysChanged=n}},Ca=class e extends $i{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 $i?e.clone():e)}),t}_callObserver(e,t){Qi(this,e,new Sa(this,e,t))}toJSON(){this.doc??Wi();let e={};return this._map.forEach((t,n)=>{if(!t.deleted){let r=t.content.getContent()[t.length-1];e[n]=r instanceof $i?r.toJSON():r}}),e}get size(){return[...va(this)].length}keys(){return cr(va(this),e=>e[0])}values(){return cr(va(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return cr(va(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??Wi(),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):G(this.doc,t=>{fa(t,this,e)})}set(e,t){return this.doc===null?this._prelimContent.set(e,t):G(this.doc,n=>{pa(n,this,e,t)}),t}get(e){return ma(this,e)}has(e){return ga(this,e)}clear(){this.doc===null?this._prelimContent.clear():G(this.doc,e=>{this.forEach(function(t,n,r){fa(e,r,n)})})}_write(e){e.writeTypeRef(So)}};const wa=e=>new Ca,Ta=(e,t)=>e===t||typeof e==`object`&&typeof t==`object`&&e&&t&&En(e,t);var Ea=class{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){switch(this.right===null&&Wt(),this.right.content.constructor){case uo:this.right.deleted||Aa(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}};const Da=(e,t,n)=>{for(;t.right!==null&&n>0;){switch(t.right.content.constructor){case uo:t.right.deleted||Aa(t.currentAttributes,t.right.content);break;default:t.right.deleted||(n<t.right.length&&vi(e,W(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},Oa=(e,t,n,r)=>{let i=new Map,a=r?Xi(t,n):null;return a?Da(e,new Ea(a.p.left,a.p,a.index,i),n-a.index):Da(e,new Ea(null,t._start,0,i),n)},ka=(e,t,n,r)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===uo&&Ta(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 jo(W(a,pi(i.store,a)),s,s&&s.lastId,c,c&&c.id,t,null,new uo(o,r));l.integrate(e,0),n.right=l,n.forward()})},Aa=(e,t)=>{let{key:n,value:r}=t;r===null?e.delete(n):e.set(n,r)},ja=(e,t)=>{for(;e.right!==null&&(e.right.deleted||e.right.content.constructor===uo&&Ta(t[e.right.content.key]??null,e.right.content.value));)e.forward()},Ma=(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(!Ta(l,c)){o.set(s,l);let{left:r,right:u}=n;n.right=new jo(W(a,pi(i.store,a)),r,r&&r.lastId,u,u&&u.id,t,null,new uo(s,c)),n.right.integrate(e,0),n.forward()}}return o},Na=(e,t,n,r,i)=>{n.currentAttributes.forEach((e,t)=>{i[t]===void 0&&(i[t]=null)});let a=e.doc,o=a.clientID;ja(n,i);let s=Ma(e,t,n,i),c=r.constructor===String?new vo(r):r instanceof $i?new Oo(r):new co(r),{left:l,right:u,index:d}=n;t._searchMarker&&Zi(t._searchMarker,n.index,c.getLength()),u=new jo(W(o,pi(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(),ka(e,t,n,s)},Pa=(e,t,n,r,i)=>{let a=e.doc,o=a.clientID;ja(n,i);let s=Ma(e,t,n,i);iterationLoop:for(;n.right!==null&&(r>0||s.size>0&&(n.right.deleted||n.right.content.constructor===uo));){if(!n.right.deleted)switch(n.right.content.constructor){case uo:{let{key:t,value:a}=n.right.content,o=i[t];if(o!==void 0){if(Ta(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&&vi(e,W(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+=`
2
+ `;n.right=new jo(W(o,pi(a.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new vo(i)),n.right.integrate(e,0),n.forward()}ka(e,t,n,s)},Fa=(e,t,n,r,i)=>{let a=t,o=He();for(;a&&(!a.countable||a.deleted);){if(!a.deleted&&a.content.constructor===uo){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 uo:{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&&Aa(i,n);break}}}t=t.right}return s},Ia=(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===uo){let r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}},La=e=>{let t=0;return G(e.doc,n=>{let r=e._start,i=e._start,a=He(),o=Ue(a);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case uo:Aa(o,i.content);break;default:t+=Fa(n,r,i,a,o),a=Ue(o),r=i;break}i=i.right}}),t},Ra=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&&xi(e,n.store.clients.get(r),a,i,e=>{!e.deleted&&e.content.constructor===uo&&e.constructor!==eo&&t.add(e.parent)})}G(n,n=>{dr(e,e.deleteSet,e=>{if(e instanceof eo||!e.parent._hasFormatting||t.has(e.parent))return;let r=e.parent;e.content.constructor===uo?t.add(r):Ia(n,e)});for(let e of t)La(e)})},za=(e,t,n)=>{let r=n,i=Ue(t.currentAttributes),a=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case Oo:case co:case vo:n<t.right.length&&vi(e,W(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e);break}t.forward()}a&&Fa(e,a,t.right,i,t.currentAttributes);let o=(t.left||t.right).parent;return o._searchMarker&&Zi(o._searchMarker,t.index,-r+n),t};var Ba=class extends Hi{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=[];G(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},Cn(o)||(e.attributes=yn({},o))),c=0;break}e&&t.push(e),a=null}};for(;i!==null;){switch(i.content.constructor){case Oo:case co: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 vo: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 uo:{let{key:t,value:s}=i.content;if(this.adds(i))this.deletes(i)||(Ta(n.get(t)??null,s)?s!==null&&i.delete(e):(a===`retain`&&u(),Ta(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;Ta(e,s)||(a===`retain`&&u(),o[t]=e)}else if(!i.deleted){r.set(t,s);let n=o[t];n!==void 0&&(Ta(n,s)?n!==null&&i.delete(e):(a===`retain`&&u(),s===null?delete o[t]:o[t]=s))}i.deleted||(a===`insert`&&u(),Aa(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}},Va=class e extends $i{constructor(e){super(),this._pending=e===void 0?[]:[()=>this.insert(0,e)],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Wi(),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 Ba(this,e,t);Qi(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Wi();let e=``,t=this._start;for(;t!==null;)!t.deleted&&t.countable&&t.content.constructor===vo&&(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)):G(this.doc,n=>{let r=new Ea(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)===`
3
+ `?a.insert.slice(0,-1):a.insert;(typeof o!=`string`||o.length>0)&&Na(n,this,r,o,a.attributes||{})}else a.retain===void 0?a.delete!==void 0&&za(n,r,a.delete):Pa(n,this,r,a.retain,a.attributes||{})}})}toDelta(e,t,n){this.doc??Wi();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(si(s,e)||t!==void 0&&si(s,t))switch(s.content.constructor){case vo:{let r=i.get(`ychange`);e!==void 0&&!si(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&&!si(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 Oo:case co:{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 uo:si(s,e)&&(c(),Aa(i,s.content));break}s=s.right}c()};return e||t?G(a,n=>{e&&ci(n,e),t&&ci(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)):G(r,r=>{let i=Oa(r,this,e,!n);n||(n={},i.currentAttributes.forEach((e,t)=>{n[t]=e})),Na(r,this,i,t,n)})}insertEmbed(e,t,n){let r=this.doc;r===null?this._pending.push(()=>this.insertEmbed(e,t,n||{})):G(r,r=>{let i=Oa(r,this,e,!n);Na(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)):G(n,n=>{za(n,Oa(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)):G(r,r=>{let i=Oa(r,this,e,!1);i.right!==null&&Pa(r,this,i,t,n)})}removeAttribute(e){this.doc===null?this._pending.push(()=>this.removeAttribute(e)):G(this.doc,t=>{fa(t,this,e)})}setAttribute(e,t){this.doc===null?this._pending.push(()=>this.setAttribute(e,t)):G(this.doc,n=>{pa(n,this,e,t)})}getAttribute(e){return ma(this,e)}getAttributes(){return ha(this)}_write(e){e.writeTypeRef(Co)}};const Ha=e=>new Va;var Ua=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Wi()}[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===Ka||t.constructor===Wa)&&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})}},Wa=class e extends $i{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 $i?e.clone():e)),t}get length(){return this.doc??Wi(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new Ua(this,e)}querySelector(e){e=e.toUpperCase();let t=new Ua(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),Ye(new Ua(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){Qi(this,e,new Ja(this,t,e))}toString(){return ia(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),ra(this,i=>{r.insertBefore(i.toDOM(e,t,n),null)}),r}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):G(this.doc,n=>{la(n,this,e,t)})}insertAfter(e,t){if(this.doc!==null)G(this.doc,n=>{let r=e&&e instanceof $i?e._item:e;sa(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 Ht(`Reference item not found`);n.splice(r,0,...t)}}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):G(this.doc,n=>{da(n,this,e,t)})}toArray(){return ta(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return oa(this,e)}slice(e=0,t=this.length){return ea(this,e,t)}forEach(e){ra(this,e)}_write(e){e.writeTypeRef(To)}};const Ga=e=>new Wa;var Ka=class e extends Wa{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 xn(this.getAttributes(),(e,n)=>{t.setAttribute(n,e)}),t.insert(0,this.toArray().map(e=>e instanceof $i?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):G(this.doc,t=>{fa(t,this,e)})}setAttribute(e,t){this.doc===null?this._prelimAttrs.set(e,t):G(this.doc,n=>{pa(n,this,e,t)})}getAttribute(e){return ma(this,e)}hasAttribute(e){return ga(this,e)}getAttributes(e){return e?_a(this,e):ha(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 ra(this,i=>{r.appendChild(i.toDOM(e,t,n))}),n!==void 0&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(wo),e.writeKey(this.nodeName)}};const qa=e=>new Ka(e.readKey());var Ja=class extends Hi{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)})}},Ya=class e extends Ca{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(Eo),e.writeKey(this.hookName)}};const Xa=e=>new Ya(e.readKey());var Za=class e extends Va{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(Do)}};const Qa=e=>new Za;var $a=class{constructor(e,t){this.id=e,this.length=t}get deleted(){throw Ut()}mergeWith(e){return!1}write(e,t,n){throw Ut()}integrate(e,t){throw Ut()}},eo=class extends $a{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),mi(e.doc.store,this)}write(e,t){e.writeInfo(0),e.writeLen(this.length-t)}getMissing(e,t){return null}},to=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 Ut()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}};const no=e=>new to(e.readBuf());var ro=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){gr(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}};const io=e=>new ro(e.readLen()),ao=(e,t)=>new wr({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});var oo=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(ao(this.doc.guid,this.opts))}splice(e){throw Ut()}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}};const so=e=>new oo(ao(e.readString(),e.readAny()));var co=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 Ut()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}};const lo=e=>new co(e.readJSON());var uo=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 Ut()}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}};const fo=e=>new uo(e.readKey(),e.readJSON());var po=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}};const mo=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 po(n)},ho=Rn(`node_env`)===`development`;var go=class e{constructor(e){this.arr=e,ho&&On(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}};const _o=e=>{let t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new go(n)};var vo=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}};const yo=e=>new vo(e.readString()),bo=[xa,wa,Ha,qa,Ga,Xa,Qa],xo=0,So=1,Co=2,wo=3,To=4,Eo=5,Do=6;var Oo=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 Ut()}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}};const ko=e=>new Oo(bo[e.readTypeRef()](e)),Ao=(e,t,n)=>{let{client:r,clock:i}=t.id,a=new jo(W(r,i+n),t,W(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=W(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};var jo=class e extends $a{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>=pi(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=pi(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===ti&&this.id.client!==this.parent.client&&this.parent.clock>=pi(n,this.parent.client))return this.parent.client;if(this.origin&&=(this.left=yi(t,n,this.origin),this.left.lastId),this.rightOrigin&&=(this.right=vi(t,this.rightOrigin),this.right.id),this.left&&this.left.constructor===eo||this.right&&this.right.constructor===eo)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===ti){let e=gi(n,this.parent);e.constructor===eo?this.parent=null:this.parent=e.content.type}return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=yi(e,e.doc.store,W(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),ni(this.origin,n.origin)){if(n.id.client<this.id.client)t=n,r.clear();else if(ni(this.rightOrigin,n.rightOrigin))break}else if(n.origin!==null&&i.has(gi(e.doc.store,n.origin)))r.has(gi(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),mi(e.doc.store,this),this.content.integrate(e,this),wi(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new eo(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:W(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&ni(e.origin,this.lastId)&&this.right===e&&ni(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(),gr(e.deleteSet,this.id.client,this.id.clock,this.length),wi(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw Wt();this.content.gc(e),t?bi(e,this,new eo(this.id,this.length)):this.content=new ro(this.length)}write(e,t){let n=t>0?W(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=ri(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===ti?(e.writeParentInfo(!1),e.writeLeftID(t)):Wt();i!==null&&e.writeString(i)}this.content.write(e,t)}};const Mo=(e,t)=>No[t&31](e),No=[()=>{Wt()},io,mo,no,yo,lo,fo,ko,_o,so,()=>{Wt()}];var Po=class extends $a{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor?(this.length+=e.length,!0):!1}integrate(e,t){Wt()}write(e,t){e.writeInfo(10),H(e.restEncoder,this.length-t)}getMissing(e,t){return null}};const Fo=typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:{},Io=`__ $YJS$ __`;Fo[Io]===!0&&console.error(`Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438`),Fo[Io]=!0;const Lo=/[\uD800-\uDBFF]/,Ro=/[\uDC00-\uDFFF]/,zo=(e,t)=>{let n=0,r=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n++;for(n>0&&Lo.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&&Ro.test(e[e.length-r])&&r--,{index:n,remove:e.length-n-r,insert:t.slice(n,t.length-r)}},Bo=e=>{let t=Oe(`sha256`);return t.update(e),t.digest()},Vo=new i(`y-sync`);new i(`y-undo`),new i(`yjs-cursor`);const Ho=e=>{for(let t=6;t<e.length;t++)e[t%6]=e[t%6]^e[t];return e.slice(0,6)},Uo=e=>Hn(Ho(Bo(Wn(e)))),Wo=()=>({mapping:new Map,isOMark:new Map}),Go=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&t.sv.get(e.id.client)>e.id.clock&&!pr(t.ds,e.id),Ko=(e,t,n,r,i,a)=>{let o=n.mapping.get(e);if(o===void 0){if(e instanceof Ka)return qo(e,t,n,r,i,a);throw Ut()}return o},qo=(e,t,n,r,i,a)=>{let o=[],s=e=>{if(e instanceof Ka){let s=Ko(e,t,n,r,i,a);s!==null&&o.push(s)}else{let s=e._item.right?.content?.type;s instanceof Va&&!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=Jo(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):na(e,new ii(i.ds,r.sv)).forEach(s);try{let s=e.getAttributes(r);r!==void 0&&(Go(e._item,r)?Go(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}},Jo=(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,ls(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},Yo=(e,t)=>{let n=new Za,r=e.map(e=>({insert:e.text,attributes:us(e.marks,t)}));return n.applyDelta(r),t.mapping.set(n,e),n},Xo=(e,t)=>{let n=new Ka(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,es(e).map(e=>Zo(e,t))),t.mapping.set(n,e),n},Zo=(e,t)=>e instanceof Array?Yo(e,t):Xo(e,t),Qo=e=>typeof e==`object`&&!!e,$o=(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||Qo(o)&&Qo(s)&&$o(o,s)}return r},es=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},ts=(e,t)=>{let n=e.toDelta();return n.length===t.length&&n.every((e,n)=>e.insert===t[n].text&&bn(e.attributes||{}).length===t[n].marks.length&&wn(e.attributes,(e,r)=>{let i=cs(r),a=t[n].marks;return a.find(e=>e.type.name===i)?$o(e,a.find(e=>e.type.name===i)?.attrs):!1}))},ns=(e,t)=>{if(e instanceof Ka&&!(t instanceof Array)&&fs(e,t)){let n=es(t);return e._length===n.length&&$o(e.getAttributes(),t.attrs)&&e.toArray().every((e,t)=>ns(e,n[t]))}return e instanceof Za&&t instanceof Array&&ts(e,t)},rs=(e,t)=>e===t||e instanceof Array&&t instanceof Array&&e.length===t.length&&e.every((e,n)=>t[n]===e),is=(e,t,n)=>{let r=e.toArray(),i=es(t),a=i.length,o=r.length,s=et(o,a),c=0,l=0,u=!1;for(;c<s;c++){let e=r[c],t=i[c];if(rs(n.mapping.get(e),t))u=!0;else if(!ns(e,t))break}for(;c+l<s;l++){let e=r[o-l-1],t=i[a-l-1];if(rs(n.mapping.get(e),t))u=!0;else if(!ns(e,t))break}return{equalityFactor:c+l,foundMappedChild:u}},as=e=>{let t=``,n=e._start,r={};for(;n!==null;)n.deleted||(n.countable&&n.content instanceof vo?t+=n.content.str:n.content instanceof uo&&(r[n.content.key]=null)),n=n.right;return{str:t,nAttrs:r}},os=(e,t,n)=>{n.mapping.set(e,t);let{nAttrs:r,str:i}=as(e),a=t.map(e=>({insert:e.text,attributes:Object.assign({},r,us(e.marks,n))})),{insert:o,remove:s,index:c}=zo(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})))},ss=/(.*)(--[a-zA-Z0-9+/=]{8})$/,cs=e=>ss.exec(e)?.[1]??e,ls=(e,t)=>{let n=[];for(let r in e)n.push(t.mark(cs(r),e[r]));return n},us=(e,t)=>{let n={};return e.forEach(e=>{if(e.type.name!==`ychange`){let r=We(t.isOMark,e.type,()=>!e.type.excludes(e.type));n[r?`${e.type.name}--${Uo(e.toJSON())}`:e.type.name]=e.attrs}}),n},ds=(e,t,n,r)=>{if(t instanceof Ka&&t.nodeName!==n.type.name)throw Error(`node name mismatch!`);if(r.mapping.set(t,n),t instanceof Ka){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=es(n),a=i.length,o=t.toArray(),s=o.length,c=et(a,s),l=0,u=0;for(;l<c;l++){let e=o[l],t=i[l];if(!rs(r.mapping.get(e),t))if(ns(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(!rs(r.mapping.get(e),t))if(ns(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 Za&&c instanceof Array)ts(n,c)||os(n,c,r),l+=1;else{let i=n instanceof Ka&&fs(n,c),a=d instanceof Ka&&fs(d,f);if(i&&a){let e=is(n,c,r),t=is(d,f,r);e.foundMappedChild&&!t.foundMappedChild?a=!1:!e.foundMappedChild&&t.foundMappedChild||e.equalityFactor<t.equalityFactor?i=!1:a=!1}i?(ds(e,n,c,r),l+=1):a?(ds(e,d,f,r),u+=1):(r.mapping.delete(t.get(l)),t.delete(l,1),t.insert(l,[Zo(c,r)]),l+=1)}}let n=s-l-u;if(s===1&&a===0&&o[0]instanceof Za?(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(Zo(i[t],r));t.insert(l,e)}},Vo)},fs=(e,t)=>!(t instanceof Array)&&e.nodeName===t.type.name,ps=(e,t)=>{let n=e.toArray().map(e=>qo(e,t,Wo())).filter(e=>e!==null);return k.fromArray(n)},ms=(e,t)=>t.topNodeType.create(null,ps(e,t));var hs=n(((e,t)=>{let n=e=>e&&typeof e.message==`string`,r=e=>{if(!e)return;let t=e.cause;if(typeof t==`function`){let t=e.cause();return n(t)?t:void 0}else return n(t)?t:void 0},i=(e,t)=>{if(!n(e))return``;let a=e.stack||``;if(t.has(e))return a+`
4
4
  causes have become circular...`;let o=r(e);return o?(t.add(e),a+`
5
- caused by: `+i(o,t)):a},a=e=>i(e,new Set),o=(e,t,i)=>{if(!n(e))return``;let a=i?``:e.message||``;if(t.has(e))return a+`: ...`;let s=r(e);if(s){t.add(e);let n=typeof e.cause==`function`;return a+(n?``:`: `)+o(s,t,n)}else return a};t.exports={isErrorLike:n,getErrorCause:r,stackWithCauses:a,messageWithCauses:e=>o(e,new Set)}})),ms=n(((e,t)=>{let n=Symbol(`circular-ref-tag`),r=Symbol(`pino-raw-err-ref`),i=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[r]},set:function(e){this[r]=e}}});Object.defineProperty(i,r,{writable:!0,value:{}}),t.exports={pinoErrProto:i,pinoErrorSymbols:{seen:n,rawSymbol:r}}})),hs=n(((e,t)=>{t.exports=l;let{messageWithCauses:n,stackWithCauses:r,isErrorLike:i}=ps(),{pinoErrProto:a,pinoErrorSymbols:o}=ms(),{seen:s}=o,{toString:c}=Object.prototype;function l(e){if(!i(e))return e;e[s]=void 0;let t=Object.create(a);t.type=c.call(e.constructor)===`[object Function]`?e.constructor.name:e.name,t.message=n(e),t.stack=r(e),Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(e=>l(e)));for(let n in e)if(t[n]===void 0){let r=e[n];i(r)?n!==`cause`&&!Object.prototype.hasOwnProperty.call(r,s)&&(t[n]=l(r)):t[n]=r}return delete e[s],t.raw=e,t}})),gs=n(((e,t)=>{t.exports=s;let{isErrorLike:n}=ps(),{pinoErrProto:r,pinoErrorSymbols:i}=ms(),{seen:a}=i,{toString:o}=Object.prototype;function s(e){if(!n(e))return e;e[a]=void 0;let t=Object.create(r);t.type=o.call(e.constructor)===`[object Function]`?e.constructor.name:e.name,t.message=e.message,t.stack=e.stack,Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(e=>s(e))),n(e.cause)&&!Object.prototype.hasOwnProperty.call(e.cause,a)&&(t.cause=s(e.cause));for(let r in e)if(t[r]===void 0){let i=e[r];n(i)?Object.prototype.hasOwnProperty.call(i,a)||(t[r]=s(i)):t[r]=i}return delete e[a],t.raw=e,t}})),_s=n(((e,t)=>{t.exports={mapHttpRequest:a,reqSerializer:i};let n=Symbol(`pino-raw-req-ref`),r=Object.create({},{id:{enumerable:!0,writable:!0,value:``},method:{enumerable:!0,writable:!0,value:``},url:{enumerable:!0,writable:!0,value:``},query:{enumerable:!0,writable:!0,value:``},params:{enumerable:!0,writable:!0,value:``},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:``},remotePort:{enumerable:!0,writable:!0,value:``},raw:{enumerable:!1,get:function(){return this[n]},set:function(e){this[n]=e}}});Object.defineProperty(r,n,{writable:!0,value:{}});function i(e){let t=e.info||e.socket,n=Object.create(r);if(n.id=typeof e.id==`function`?e.id():e.id||(e.info?e.info.id:void 0),n.method=e.method,e.originalUrl)n.url=e.originalUrl;else{let t=e.path;n.url=typeof t==`string`?t:e.url?e.url.path||e.url:void 0}return e.query&&(n.query=e.query),e.params&&(n.params=e.params),n.headers=e.headers,n.remoteAddress=t&&t.remoteAddress,n.remotePort=t&&t.remotePort,n.raw=e.raw||e,n}function a(e){return{req:i(e)}}})),vs=n(((e,t)=>{t.exports={mapHttpResponse:a,resSerializer:i};let n=Symbol(`pino-raw-res-ref`),r=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:``},raw:{enumerable:!1,get:function(){return this[n]},set:function(e){this[n]=e}}});Object.defineProperty(r,n,{writable:!0,value:{}});function i(e){let t=Object.create(r);return t.statusCode=e.headersSent?e.statusCode:null,t.headers=e.getHeaders?e.getHeaders():e._headers,t.raw=e,t}function a(e){return{res:i(e)}}})),ys=n(((e,t)=>{let n=hs(),r=gs(),i=_s(),a=vs();t.exports={err:n,errWithCause:r,mapHttpRequest:i.mapHttpRequest,mapHttpResponse:a.mapHttpResponse,req:i.reqSerializer,res:a.resSerializer,wrapErrorSerializer:function(e){return e===n?e:function(t){return e(n(t))}},wrapRequestSerializer:function(e){return e===i.reqSerializer?e:function(t){return e(i.reqSerializer(t))}},wrapResponseSerializer:function(e){return e===a.resSerializer?e:function(t){return e(a.resSerializer(t))}}}})),bs=n(((e,t)=>{function n(e,t){return t}t.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=n;let t=Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(t))return;let r=t.slice(2),i=[];for(let e of r)e&&i.push(e.getFileName());return i}})),xs=n(((e,t)=>{function n(e){if(typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof Array){let t=[];for(let r=0;r<e.length;r++)t[r]=n(e[r]);return t}if(typeof e==`object`){let t=Object.create(Object.getPrototypeOf(e));for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=n(e[r]));return t}return e}function r(e){let t=[],n=``,r=!1,i=!1,a=``;for(let o=0;o<e.length;o++){let s=e[o];!r&&s===`.`?n&&=(t.push(n),``):s===`[`?(n&&=(t.push(n),``),r=!0):s===`]`&&r?(t.push(n),n=``,r=!1,i=!1):(s===`"`||s===`'`)&&r?i?s===a?(i=!1,a=``):n+=s:(i=!0,a=s):n+=s}return n&&t.push(n),t}function i(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){let n=t[e];if(typeof r!=`object`||!r||!(n in r)||typeof r[n]!=`object`||r[n]===null)return!1;r=r[n]}let i=t[t.length-1];if(i===`*`){if(Array.isArray(r))for(let e=0;e<r.length;e++)r[e]=n;else if(typeof r==`object`&&r)for(let e in r)Object.prototype.hasOwnProperty.call(r,e)&&(r[e]=n)}else typeof r==`object`&&r&&i in r&&Object.prototype.hasOwnProperty.call(r,i)&&(r[i]=n);return!0}function a(e,t){let n=e;for(let e=0;e<t.length-1;e++){let r=t[e];if(typeof n!=`object`||!n||!(r in n)||typeof n[r]!=`object`||n[r]===null)return!1;n=n[r]}let r=t[t.length-1];if(r===`*`){if(Array.isArray(n))for(let e=0;e<n.length;e++)n[e]=void 0;else if(typeof n==`object`&&n)for(let e in n)Object.prototype.hasOwnProperty.call(n,e)&&delete n[e]}else typeof n==`object`&&n&&r in n&&Object.prototype.hasOwnProperty.call(n,r)&&delete n[r];return!0}let o=Symbol(`PATH_NOT_FOUND`);function s(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n||!n||!(e in n))return o;n=n[e]}return n}function c(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n||!n)return;n=n[e]}return n}function l(e,t,n,c=!1){for(let l of t){let t=r(l);if(t.includes(`*`))u(e,t,n,l,c);else if(c)a(e,t);else{let r=s(e,t);if(r===o)continue;i(e,t,typeof n==`function`?n(r,t):n)}}}function u(e,t,n,r,i=!1){let a=t.indexOf(`*`);if(a===t.length-1){let r=t.slice(0,-1),a=e;for(let e of r){if(typeof a!=`object`||!a||!a)return;a=a[e]}if(Array.isArray(a))if(i)for(let e=0;e<a.length;e++)a[e]=void 0;else for(let e=0;e<a.length;e++){let t=[...r,e.toString()],i=typeof n==`function`?n(a[e],t):n;a[e]=i}else if(typeof a==`object`&&a)if(i){let e=[];for(let t in a)Object.prototype.hasOwnProperty.call(a,t)&&e.push(t);for(let t of e)delete a[t]}else for(let e in a){let t=[...r,e],i=typeof n==`function`?n(a[e],t):n;a[e]=i}}else d(e,t,n,a,r,i)}function d(e,t,n,r,o,s=!1){let l=t.slice(0,r),d=t.slice(r+1),f=[];function p(e,t){if(t===l.length){if(Array.isArray(e))for(let n=0;n<e.length;n++)f[t]=n.toString(),p(e[n],t+1);else if(typeof e==`object`&&e)for(let n in e)f[t]=n,p(e[n],t+1)}else if(t<l.length){let n=l[t];e&&typeof e==`object`&&e&&n in e&&(f[t]=n,p(e[n],t+1))}else d.includes(`*`)?u(e,d,typeof n==`function`?(e,r)=>n(e,[...f.slice(0,t),...r]):n,o,s):s?a(e,d):i(e,d,typeof n==`function`?n(c(e,d),[...f.slice(0,t),...d]):n)}if(l.length===0)p(e,0);else{let t=e;for(let e=0;e<l.length;e++){let n=l[e];if(typeof t!=`object`||!t||!t)return;t=t[n],f[e]=n}t!=null&&p(t,l.length)}}function f(e){if(e.length===0)return null;let t=new Map;for(let n of e){let e=r(n),i=t;for(let t=0;t<e.length;t++){let n=e[t];i.has(n)||i.set(n,new Map),i=i.get(n)}}return t}function p(e,t){if(!t)return e;function n(e,t,r=0){if(!t||t.size===0||typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e)){let r=[];for(let i=0;i<e.length;i++){let a=i.toString();t.has(a)||t.has(`*`)?r[i]=n(e[i],t.get(a)||t.get(`*`)):r[i]=e[i]}return r}let i=Object.create(Object.getPrototypeOf(e));for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t.has(r)||t.has(`*`)?i[r]=n(e[r],t.get(r)||t.get(`*`)):i[r]=e[r]);return i}return n(e,t)}function m(e){if(typeof e!=`string`)throw Error(`Paths must be (non-empty) strings`);if(e===``)throw Error(`Invalid redaction path ()`);if(e.includes(`..`)||e.includes(`,`))throw Error(`Invalid redaction path (${e})`);let t=0,n=!1,r=``;for(let i=0;i<e.length;i++){let a=e[i];if((a===`"`||a===`'`)&&t>0)n?a===r&&(n=!1,r=``):(n=!0,r=a);else if(a===`[`&&!n)t++;else if(a===`]`&&!n&&(t--,t<0))throw Error(`Invalid redaction path (${e})`)}if(t!==0)throw Error(`Invalid redaction path (${e})`)}function h(e){if(!Array.isArray(e))throw TypeError(`paths must be an array`);for(let t of e)m(t)}function g(e={}){let{paths:t=[],censor:r=`[REDACTED]`,serialize:i=JSON.stringify,strict:a=!0,remove:o=!1}=e;h(t);let s=f(t);return function(e){if(a&&(typeof e!=`object`||!e)&&(typeof e!=`object`||!e))return i?i(e):e;let c=p(e,s),u=e,d=r;return typeof r==`function`&&(d=r),l(c,t,d,o),i===!1?(c.restore=function(){return n(u)},c):typeof i==`function`?i(c):JSON.stringify(c)}}t.exports=g})),Ss=n(((e,t)=>{let n=Symbol(`pino.setLevel`),r=Symbol(`pino.getLevel`),i=Symbol(`pino.levelVal`),a=Symbol(`pino.levelComp`),o=Symbol(`pino.useLevelLabels`),s=Symbol(`pino.useOnlyCustomLevels`),c=Symbol(`pino.mixin`),l=Symbol(`pino.lsCache`),u=Symbol(`pino.chindings`),d=Symbol(`pino.asJson`),f=Symbol(`pino.write`),p=Symbol(`pino.redactFmt`),m=Symbol(`pino.time`),h=Symbol(`pino.timeSliceIndex`),g=Symbol(`pino.stream`),_=Symbol(`pino.stringify`),v=Symbol(`pino.stringifySafe`),y=Symbol(`pino.stringifiers`),b=Symbol(`pino.end`),x=Symbol(`pino.formatOpts`),S=Symbol(`pino.messageKey`),C=Symbol(`pino.errorKey`),w=Symbol(`pino.nestedKey`),T=Symbol(`pino.nestedKeyStr`),E=Symbol(`pino.mixinMergeStrategy`),D=Symbol(`pino.msgPrefix`),O=Symbol(`pino.wildcardFirst`),k=Symbol.for(`pino.serializers`),A=Symbol.for(`pino.formatters`),j=Symbol.for(`pino.hooks`);t.exports={setLevelSym:n,getLevelSym:r,levelValSym:i,levelCompSym:a,useLevelLabelsSym:o,mixinSym:c,lsCacheSym:l,chindingsSym:u,asJsonSym:d,writeSym:f,serializersSym:k,redactFmtSym:p,timeSym:m,timeSliceIndexSym:h,streamSym:g,stringifySym:_,stringifySafeSym:v,stringifiersSym:y,endSym:b,formatOptsSym:x,messageKeySym:S,errorKeySym:C,nestedKeySym:w,wildcardFirstSym:O,needsMetadataGsym:Symbol.for(`pino.metadata`),useOnlyCustomLevelsSym:s,formattersSym:A,hooksSym:j,nestedKeyStrSym:T,mixinMergeStrategySym:E,msgPrefixSym:D}})),Cs=n(((e,t)=>{let n=xs(),{redactFmtSym:r,wildcardFirstSym:i}=Ss(),a=/[^.[\]]+|\[([^[\]]*?)\]/g,o=`[Redacted]`;function s(e,t){let{paths:o,censor:s,remove:l}=c(e),u=o.reduce((e,t)=>{a.lastIndex=0;let n=a.exec(t),r=a.exec(t),o=n[1]===void 0?n[0]:n[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,`$1`);if(o===`*`&&(o=i),r===null)return e[o]=null,e;if(e[o]===null)return e;let{index:s}=r,c=`${t.substr(s,t.length-1)}`;return e[o]=e[o]||[],o!==i&&e[o].length===0&&e[o].push(...e[i]||[]),o===i&&Object.keys(e).forEach(function(t){e[t]&&e[t].push(c)}),e[o].push(c),e},{}),d={[r]:n({paths:o,censor:s,serialize:t,strict:!1,remove:l})},f=(...e)=>t(typeof s==`function`?s(...e):s);return[...Object.keys(u),...Object.getOwnPropertySymbols(u)].reduce((e,r)=>{if(u[r]===null)e[r]=e=>f(e,[r]);else{let i=typeof s==`function`?(e,t)=>s(e,[r,...t]):s;e[r]=n({paths:u[r],censor:i,serialize:t,strict:!1,remove:l})}return e},d)}function c(e){if(Array.isArray(e))return e={paths:e,censor:o},e;let{paths:t,censor:n=o,remove:r}=e;if(Array.isArray(t)===!1)throw Error(`pino – redact must contain an array of strings`);return r===!0&&(n=void 0),{paths:t,censor:n,remove:r}}t.exports=s})),ws=n(((e,t)=>{let n=()=>``,r=()=>`,"time":${Date.now()}`,i=()=>`,"time":${Math.round(Date.now()/1e3)}`,a=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,o=1000000000n,s=BigInt(Date.now())*1000000n,c=process.hrtime.bigint();t.exports={nullTime:n,epochTime:r,unixTime:i,isoTime:a,isoTimeNano:()=>{let e=s+(process.hrtime.bigint()-c),t=e/o,n=e%o,r=Number(t*1000n+n/1000000n),i=new Date(r);return`,"time":"${i.getUTCFullYear()}-${(i.getUTCMonth()+1).toString().padStart(2,`0`)}-${i.getUTCDate().toString().padStart(2,`0`)}T${i.getUTCHours().toString().padStart(2,`0`)}:${i.getUTCMinutes().toString().padStart(2,`0`)}:${i.getUTCSeconds().toString().padStart(2,`0`)}.${n.toString().padStart(9,`0`)}Z"`}}})),Ts=n(((e,t)=>{function n(e){try{return JSON.stringify(e)}catch{return`"[Circular]"`}}t.exports=r;function r(e,t,r){var i=r&&r.stringify||n,a=1;if(typeof e==`object`&&e){var o=t.length+a;if(o===1)return e;var s=Array(o);s[0]=i(e);for(var c=1;c<o;c++)s[c]=i(t[c]);return s.join(` `)}if(typeof e!=`string`)return e;var l=t.length;if(l===0)return e;for(var u=``,d=1-a,f=-1,p=e&&e.length||0,m=0;m<p;){if(e.charCodeAt(m)===37&&m+1<p){switch(f=f>-1?f:0,e.charCodeAt(m+1)){case 100:case 102:if(d>=l||t[d]==null)break;f<m&&(u+=e.slice(f,m)),u+=Number(t[d]),f=m+2,m++;break;case 105:if(d>=l||t[d]==null)break;f<m&&(u+=e.slice(f,m)),u+=Math.floor(Number(t[d])),f=m+2,m++;break;case 79:case 111:case 106:if(d>=l||t[d]===void 0)break;f<m&&(u+=e.slice(f,m));var h=typeof t[d];if(h===`string`){u+=`'`+t[d]+`'`,f=m+2,m++;break}if(h===`function`){u+=t[d].name||`<anonymous>`,f=m+2,m++;break}u+=i(t[d]),f=m+2,m++;break;case 115:if(d>=l)break;f<m&&(u+=e.slice(f,m)),u+=String(t[d]),f=m+2,m++;break;case 37:f<m&&(u+=e.slice(f,m)),u+=`%`,f=m+2,m++,d--;break}++d}++m}return f===-1?e:(f<p&&(u+=e.slice(f)),u)}})),Es=n(((e,t)=>{if(typeof SharedArrayBuffer<`u`&&typeof Atomics<`u`){let e=new Int32Array(new SharedArrayBuffer(4));function n(t){if(!(t>0&&t<1/0))throw typeof t!=`number`&&typeof t!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);Atomics.wait(e,0,0,Number(t))}t.exports=n}else{function e(e){if(!(e>0&&e<1/0))throw typeof e!=`number`&&typeof e!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);let t=Date.now()+Number(e);for(;t>Date.now(););}t.exports=e}})),Ds=n(((e,n)=>{let r=t(`fs`),i=t(`events`),a=t(`util`).inherits,o=t(`path`),s=Es(),c=t(`assert`),l=Buffer.allocUnsafe(0),u=`buffer`,d=`utf8`,[f,p]=(process.versions.node||`0.0`).split(`.`).map(Number),m=f>=22&&p>=7;function h(e,t){t._opening=!0,t._writing=!0,t._asyncDrainScheduled=!1;function n(n,r){if(n){t._reopening=!1,t._writing=!1,t._opening=!1,t.sync?process.nextTick(()=>{t.listenerCount(`error`)>0&&t.emit(`error`,n)}):t.emit(`error`,n);return}let i=t._reopening;t.fd=r,t.file=e,t._reopening=!1,t._opening=!1,t._writing=!1,t.sync?process.nextTick(()=>t.emit(`ready`)):t.emit(`ready`),!t.destroyed&&(!t._writing&&t._len>t.minLength||t._flushPending?t._actualWrite():i&&process.nextTick(()=>t.emit(`drain`)))}let i=t.append?`a`:`w`,a=t.mode;if(t.sync)try{t.mkdir&&r.mkdirSync(o.dirname(e),{recursive:!0}),n(null,r.openSync(e,i,a))}catch(e){throw n(e),e}else t.mkdir?r.mkdir(o.dirname(e),{recursive:!0},t=>{if(t)return n(t);r.open(e,i,a,n)}):r.open(e,i,a,n)}function g(e){if(!(this instanceof g))return new g(e);let{fd:t,dest:n,minLength:i,maxLength:a,maxWrite:o,periodicFlush:c,sync:f,append:p=!0,mkdir:m,retryEAGAIN:y,fsync:S,contentMode:A,mode:j}=e||{};t||=n,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(i||0,16387),this.file=null,this.destroyed=!1,this.minLength=i||0,this.maxLength=a||0,this.maxWrite=o||16384,this._periodicFlush=c||0,this._periodicFlushTimer=void 0,this.sync=f||!1,this.writable=!0,this._fsync=S||!1,this.append=p||!1,this.mode=j,this.retryEAGAIN=y||(()=>!0),this.mkdir=m||!1;let M,ee;if(A===u)this._writingBuf=l,this.write=x,this.flush=w,this.flushSync=E,this._actualWrite=O,M=()=>r.writeSync(this.fd,this._writingBuf),ee=()=>r.write(this.fd,this._writingBuf,this.release);else if(A===void 0||A===d)this._writingBuf=``,this.write=b,this.flush=C,this.flushSync=T,this._actualWrite=D,M=()=>Buffer.isBuffer(this._writingBuf)?r.writeSync(this.fd,this._writingBuf):r.writeSync(this.fd,this._writingBuf,`utf8`),ee=()=>Buffer.isBuffer(this._writingBuf)?r.write(this.fd,this._writingBuf,this.release):r.write(this.fd,this._writingBuf,`utf8`,this.release);else throw Error(`SonicBoom supports "${d}" and "${u}", but passed ${A}`);if(typeof t==`number`)this.fd=t,process.nextTick(()=>this.emit(`ready`));else if(typeof t==`string`)h(t,this);else throw Error(`SonicBoom supports only file descriptors and files`);if(this.minLength>=this.maxWrite)throw Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(e,t)=>{if(e){if((e.code===`EAGAIN`||e.code===`EBUSY`)&&this.retryEAGAIN(e,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{s(100),this.release(void 0,0)}catch(e){this.release(e)}else setTimeout(ee,100);else this._writing=!1,this.emit(`error`,e);return}this.emit(`write`,t);let n=_(this._writingBuf,this._len,t);if(this._len=n.len,this._writingBuf=n.writingBuf,this._writingBuf.length){if(!this.sync){ee();return}try{do{let e=M(),t=_(this._writingBuf,this._len,e);this._len=t.len,this._writingBuf=t.writingBuf}while(this._writingBuf.length)}catch(e){this.release(e);return}}this._fsync&&r.fsyncSync(this.fd);let i=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):i>this.minLength?this._actualWrite():this._ending?i>0?this._actualWrite():(this._writing=!1,k(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(v,this)):this.emit(`drain`))},this.on(`newListener`,function(e){e===`drain`&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function _(e,t,n){return typeof e==`string`&&(e=Buffer.from(e)),t=Math.max(t-n,0),e=e.subarray(n),{writingBuf:e,len:t}}function v(e){e.listenerCount(`drain`)>0&&(e._asyncDrainScheduled=!1,e.emit(`drain`))}a(g,i);function y(e,t){return e.length===0?l:e.length===1?e[0]:Buffer.concat(e,t)}function b(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);e=``+e;let t=Buffer.byteLength(e),n=this._len+t,r=this._bufs;return this.maxLength&&n>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(r.length===0||Buffer.byteLength(r[r.length-1])+t>this.maxWrite?r.push(e):r[r.length-1]+=e,this._len=n,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function x(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);let t=this._len+e.length,n=this._bufs,r=this._lens;return this.maxLength&&t>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(n.length===0||r[r.length-1]+e.length>this.maxWrite?(n.push([e]),r.push(e.length)):(n[n.length-1].push(e),r[r.length-1]+=e.length),this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function S(e){this._flushPending=!0;let t=()=>{if(this._fsync)this._flushPending=!1,e();else try{r.fsync(this.fd,t=>{this._flushPending=!1,e(t)})}catch(t){e(t)}this.off(`error`,n)},n=n=>{this._flushPending=!1,e(n),this.off(`drain`,t)};this.once(`drain`,t),this.once(`error`,n)}function C(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&S.call(this,e),!this._writing&&(this._bufs.length===0&&this._bufs.push(``),this._actualWrite())}function w(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&S.call(this,e),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}g.prototype.reopen=function(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.reopen(e)});return}if(this._ending)return;if(!this.file)throw Error(`Unable to reopen a file descriptor, you must pass a file to SonicBoom`);if(e&&(this.file=e),this._reopening=!0,this._writing)return;let t=this.fd;this.once(`ready`,()=>{t!==this.fd&&r.close(t,e=>{if(e)return this.emit(`error`,e)})}),h(this.file,this)},g.prototype.end=function(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():k(this)))};function T(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf=``);let e=``;for(;this._bufs.length||e.length;){e.length<=0&&(e=this._bufs[0]);try{let t=Buffer.isBuffer(e)?r.writeSync(this.fd,e):r.writeSync(this.fd,e,`utf8`),n=_(e,this._len,t);e=n.writingBuf,this._len=n.len,e.length<=0&&this._bufs.shift()}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;s(100)}}try{r.fsyncSync(this.fd)}catch{}}function E(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=l);let e=l;for(;this._bufs.length||e.length;){e.length<=0&&(e=y(this._bufs[0],this._lens[0]));try{let t=r.writeSync(this.fd,e);e=e.subarray(t),this._len=Math.max(this._len-t,0),e.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;s(100)}}}g.prototype.destroy=function(){this.destroyed||k(this)};function D(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||``,this.sync)try{e(null,Buffer.isBuffer(this._writingBuf)?r.writeSync(this.fd,this._writingBuf):r.writeSync(this.fd,this._writingBuf,`utf8`))}catch(t){e(t)}else r.write(this.fd,this._writingBuf,e)}function O(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:y(this._bufs.shift(),this._lens.shift()),this.sync)try{e(null,r.writeSync(this.fd,this._writingBuf))}catch(t){e(t)}else m&&(this._writingBuf=Buffer.from(this._writingBuf)),r.write(this.fd,this._writingBuf,e)}function k(e){if(e.fd===-1){e.once(`ready`,k.bind(null,e));return}e._periodicFlushTimer!==void 0&&clearInterval(e._periodicFlushTimer),e.destroyed=!0,e._bufs=[],e._lens=[],c(typeof e.fd==`number`,`sonic.fd must be a number, got ${typeof e.fd}`);try{r.fsync(e.fd,t)}catch{}function t(){e.fd!==1&&e.fd!==2?r.close(e.fd,n):n()}function n(t){if(t){e.emit(`error`,t);return}e._ending&&!e._writing&&e.emit(`finish`),e.emit(`close`)}}g.SonicBoom=g,g.default=g,n.exports=g})),Os=n(((e,t)=>{let n={exit:[],beforeExit:[]},r={exit:c,beforeExit:l},i;function a(){i===void 0&&(i=new FinalizationRegistry(d))}function o(e){n[e].length>0||process.on(e,r[e])}function s(e){n[e].length>0||(process.removeListener(e,r[e]),n.exit.length===0&&n.beforeExit.length===0&&(i=void 0))}function c(){u(`exit`)}function l(){u(`beforeExit`)}function u(e){for(let t of n[e]){let n=t.deref(),r=t.fn;n!==void 0&&r(n,e)}n[e]=[]}function d(e){for(let t of[`exit`,`beforeExit`]){let r=n[t].indexOf(e);n[t].splice(r,r+1),s(t)}}function f(e,t,r){if(t===void 0)throw Error(`the object can't be undefined`);o(e);let s=new WeakRef(t);s.fn=r,a(),i.register(t,s),n[e].push(s)}function p(e,t){f(`exit`,e,t)}function m(e,t){f(`beforeExit`,e,t)}function h(e){if(i!==void 0){i.unregister(e);for(let t of[`exit`,`beforeExit`])n[t]=n[t].filter(t=>{let n=t.deref();return n&&n!==e}),s(t)}}t.exports={register:p,registerBeforeExit:m,unregister:h}})),ks=n(((e,t)=>{t.exports={name:`thread-stream`,version:`4.0.0`,description:`A streaming way to send data to a Node.js Worker Thread`,main:`index.js`,types:`index.d.ts`,engines:{node:`>=20`},dependencies:{"real-require":`^0.2.0`},devDependencies:{"@types/node":`^22.0.0`,"@yao-pkg/pkg":`^6.0.0`,borp:`^0.21.0`,desm:`^1.3.0`,eslint:`^9.39.1`,fastbench:`^1.0.1`,husky:`^9.0.6`,neostandard:`^0.12.2`,"pino-elasticsearch":`^8.0.0`,"sonic-boom":`^4.0.1`,"ts-node":`^10.8.0`,typescript:`~5.7.3`},scripts:{build:`tsc --noEmit`,lint:`eslint`,test:`npm run lint && npm run build && npm run transpile && borp --pattern 'test/*.test.{js,mjs}'`,"test:ci":`npm run lint && npm run transpile && borp --pattern 'test/*.test.{js,mjs}'`,"test:yarn":`npm run transpile && borp --pattern 'test/*.test.js'`,transpile:`sh ./test/ts/transpile.sh`,prepare:`husky install`},repository:{type:`git`,url:`git+https://github.com/mcollina/thread-stream.git`},keywords:[`worker`,`thread`,`threads`,`stream`],author:`Matteo Collina <hello@matteocollina.com>`,license:`MIT`,bugs:{url:`https://github.com/mcollina/thread-stream/issues`},homepage:`https://github.com/mcollina/thread-stream#readme`}})),As=n(((e,t)=>{let n=1e4;function r(e,t,r,i,a){let o=i===1/0?1/0:Date.now()+i,s=()=>{let i=Atomics.load(e,t);if(i===r){a(null,`ok`);return}if(o!==1/0&&Date.now()>o){a(null,`timed-out`);return}let c=o===1/0?n:Math.min(n,Math.max(1,o-Date.now())),l=Atomics.waitAsync(e,t,i,c);l.async?l.value.then(s):setImmediate(s)};s()}function i(e,t,r,i,a){let o=i===1/0?1/0:Date.now()+i,s=()=>{if(Atomics.load(e,t)!==r){a(null,`ok`);return}if(o!==1/0&&Date.now()>o){a(null,`timed-out`);return}let i=o===1/0?n:Math.min(n,Math.max(1,o-Date.now())),c=Atomics.waitAsync(e,t,r,i);c.async?c.value.then(s):setImmediate(s)};s()}t.exports={wait:r,waitDiff:i}})),js=n(((e,t)=>{t.exports={WRITE_INDEX:4,READ_INDEX:8}})),Ms=n(((e,n)=>{let{version:r}=ks(),{EventEmitter:i}=t(`events`),{Worker:a}=t(`worker_threads`),{join:o}=t(`path`),{pathToFileURL:s}=t(`url`),{wait:c}=As(),{WRITE_INDEX:l,READ_INDEX:u}=js(),d=t(`buffer`),f=t(`assert`),p=Symbol(`kImpl`),m=d.constants.MAX_STRING_LENGTH;var h=class{constructor(e){this._value=e}deref(){return this._value}},g=class{register(){}unregister(){}};let _=process.env.NODE_V8_COVERAGE?g:global.FinalizationRegistry||g,v=process.env.NODE_V8_COVERAGE?h:global.WeakRef||h,y=new _(e=>{e.exited||e.terminate()});function b(e,t){let{filename:n,workerData:i}=t,c=new a((`__bundlerPathsOverrides`in globalThis?globalThis.__bundlerPathsOverrides:{})[`thread-stream-worker`]||o(__dirname,`lib`,`worker.js`),{...t.workerOpts,trackUnmanagedFds:!1,workerData:{filename:n.indexOf(`file://`)===0?n:s(n).href,dataBuf:e[p].dataBuf,stateBuf:e[p].stateBuf,workerData:{$context:{threadStreamVersion:r},...i}}});return c.stream=new h(e),c.on(`message`,C),c.on(`exit`,w),y.register(e,c),c}function x(e){f(!e[p].sync),e[p].needDrain&&(e[p].needDrain=!1,e.emit(`drain`))}function S(e){let t=Atomics.load(e[p].state,l),n=e[p].data.length-t;if(n>0){if(e[p].buf.length===0){e[p].flushing=!1,e[p].ending?k(e):e[p].needDrain&&process.nextTick(x,e);return}let t=e[p].buf.slice(0,n),r=Buffer.byteLength(t);r<=n?(e[p].buf=e[p].buf.slice(n),O(e,t,S.bind(null,e))):e.flush(()=>{if(!e.destroyed){for(Atomics.store(e[p].state,u,0),Atomics.store(e[p].state,l,0),Atomics.notify(e[p].state,u);r>e[p].data.length;)n/=2,t=e[p].buf.slice(0,n),r=Buffer.byteLength(t);e[p].buf=e[p].buf.slice(n),O(e,t,S.bind(null,e))}})}else if(n===0){if(t===0&&e[p].buf.length===0)return;e.flush(()=>{Atomics.store(e[p].state,u,0),Atomics.store(e[p].state,l,0),Atomics.notify(e[p].state,u),S(e)})}else D(e,Error(`overwritten`))}function C(e){let t=this.stream.deref();if(t===void 0){this.exited=!0,this.terminate();return}switch(e.code){case`READY`:this.stream=new v(t),t.flush(()=>{t[p].ready=!0,t.emit(`ready`)});break;case`ERROR`:D(t,e.err);break;case`EVENT`:Array.isArray(e.args)?t.emit(e.name,...e.args):t.emit(e.name,e.args);break;case`WARNING`:process.emitWarning(e.err);break;default:D(t,Error(`this should not happen: `+e.code))}}function w(e){let t=this.stream.deref();t!==void 0&&(y.unregister(t),t.worker.exited=!0,t.worker.off(`exit`,w),D(t,e===0?null:Error(`the worker thread exited`)))}var T=class extends i{constructor(e={}){if(super(),e.bufferSize<4)throw Error(`bufferSize must at least fit a 4-byte utf-8 char`);this[p]={},this[p].stateBuf=new SharedArrayBuffer(128),this[p].state=new Int32Array(this[p].stateBuf),this[p].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[p].data=Buffer.from(this[p].dataBuf),this[p].sync=e.sync||!1,this[p].ending=!1,this[p].ended=!1,this[p].needDrain=!1,this[p].destroyed=!1,this[p].flushing=!1,this[p].ready=!1,this[p].finished=!1,this[p].errored=null,this[p].closed=!1,this[p].buf=``,this.worker=b(this,e),this.on(`message`,(e,t)=>{this.worker.postMessage(e,t)})}write(e){if(this[p].destroyed)return E(this,Error(`the worker has exited`)),!1;if(this[p].ending)return E(this,Error(`the worker is ending`)),!1;if(this[p].flushing&&this[p].buf.length+e.length>=m)try{A(this),this[p].flushing=!0}catch(e){return D(this,e),!1}if(this[p].buf+=e,this[p].sync)try{return A(this),!0}catch(e){return D(this,e),!1}return this[p].flushing||(this[p].flushing=!0,setImmediate(S,this)),this[p].needDrain=this[p].data.length-this[p].buf.length-Atomics.load(this[p].state,l)<=0,!this[p].needDrain}end(){this[p].destroyed||(this[p].ending=!0,k(this))}flush(e){if(this[p].destroyed){typeof e==`function`&&process.nextTick(e,Error(`the worker has exited`));return}let t=Atomics.load(this[p].state,l);c(this[p].state,u,t,1/0,(t,n)=>{if(t){D(this,t),process.nextTick(e,t);return}if(n===`not-equal`){this.flush(e);return}process.nextTick(e)})}flushSync(){this[p].destroyed||(A(this),j(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[p].ready}get destroyed(){return this[p].destroyed}get closed(){return this[p].closed}get writable(){return!this[p].destroyed&&!this[p].ending}get writableEnded(){return this[p].ending}get writableFinished(){return this[p].finished}get writableNeedDrain(){return this[p].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[p].errored}};function E(e,t){setImmediate(()=>{e.emit(`error`,t)})}function D(e,t){e[p].destroyed||(e[p].destroyed=!0,t&&(e[p].errored=t,E(e,t)),e.worker.exited?setImmediate(()=>{e[p].closed=!0,e.emit(`close`)}):e.worker.terminate().catch(()=>{}).then(()=>{e[p].closed=!0,e.emit(`close`)}))}function O(e,t,n){let r=Atomics.load(e[p].state,l),i=Buffer.byteLength(t);return e[p].data.write(t,r),Atomics.store(e[p].state,l,r+i),Atomics.notify(e[p].state,l),n(),!0}function k(e){if(!(e[p].ended||!e[p].ending||e[p].flushing)){e[p].ended=!0;try{e.flushSync();let t=Atomics.load(e[p].state,u);Atomics.store(e[p].state,l,-1),Atomics.notify(e[p].state,l);let n=0;for(;t!==-1;){if(Atomics.wait(e[p].state,u,t,1e3),t=Atomics.load(e[p].state,u),t===-2){D(e,Error(`end() failed`));return}if(++n===10){D(e,Error(`end() took too long (10s)`));return}}process.nextTick(()=>{e[p].finished=!0,e.emit(`finish`)})}catch(t){D(e,t)}}}function A(e){let t=()=>{e[p].ending?k(e):e[p].needDrain&&process.nextTick(x,e)};for(e[p].flushing=!1;e[p].buf.length!==0;){let n=Atomics.load(e[p].state,l),r=e[p].data.length-n;if(r===0){j(e),Atomics.store(e[p].state,u,0),Atomics.store(e[p].state,l,0),Atomics.notify(e[p].state,u);continue}else if(r<0)throw Error(`overwritten`);let i=e[p].buf.slice(0,r),a=Buffer.byteLength(i);if(a<=r)e[p].buf=e[p].buf.slice(r),O(e,i,t);else{for(j(e),Atomics.store(e[p].state,u,0),Atomics.store(e[p].state,l,0),Atomics.notify(e[p].state,u);a>e[p].buf.length;)r/=2,i=e[p].buf.slice(0,r),a=Buffer.byteLength(i);e[p].buf=e[p].buf.slice(r),O(e,i,t)}}}function j(e){if(e[p].flushing)throw Error(`unable to flush while flushing`);let t=Atomics.load(e[p].state,l),n=0;for(;;){let r=Atomics.load(e[p].state,u);if(r===-2)throw Error(`_flushSync failed`);if(r!==t)Atomics.wait(e[p].state,u,r,1e3);else break;if(++n===10)throw Error(`_flushSync took too long (10s)`)}}n.exports=T})),Ns=n(((e,n)=>{let{createRequire:r}=t(`module`),{existsSync:i}=t(`node:fs`),a=bs(),{join:o,isAbsolute:s,sep:c}=t(`node:path`),{fileURLToPath:l}=t(`node:url`),u=Es(),d=Os(),f=Ms();function p(e){d.register(e,y),d.registerBeforeExit(e,b),e.on(`close`,function(){d.unregister(e)})}function m(){let e=process.execArgv;for(let t=0;t<e.length;t++){let n=e[t];if(n===`--import`||n===`--require`||n===`-r`||n.startsWith(`--import=`)||n.startsWith(`--require=`)||n.startsWith(`-r=`))return!0}return!1}function h(e){let t=e.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!t)return e;let n=[],r=!1;for(let e=0;e<t.length;e++){let i=t[e];if(i===`--require`||i===`-r`||i===`--import`){let a=t[e+1];if(a&&g(a)){r=!0,e++;continue}n.push(i),a&&(n.push(a),e++);continue}if((i.startsWith(`--require=`)||i.startsWith(`-r=`)||i.startsWith(`--import=`))&&g(i.slice(i.indexOf(`=`)+1))){r=!0;continue}n.push(i)}return r?n.join(` `):e}function g(e){let t=_(e);if(!t)return!1;let n=t;if(n.startsWith(`file://`))try{n=l(n)}catch{return!1}return s(n)&&!i(n)}function _(e){let t=e[0],n=e[e.length-1];return t===`"`&&n===`"`||t===`'`&&n===`'`?e.slice(1,-1):e}function v(e,n,r,i,a){if(!r.execArgv&&m()&&t.main===void 0&&(r={...r,execArgv:[]}),!r.env&&process.env.NODE_OPTIONS){let e=h(process.env.NODE_OPTIONS);e!==process.env.NODE_OPTIONS&&(r={...r,env:{...process.env,NODE_OPTIONS:e}})}r={...r,name:a};let o=new f({filename:e,workerData:n,workerOpts:r,sync:i});o.on(`ready`,s),o.on(`close`,function(){process.removeListener(`exit`,c)}),process.on(`exit`,c);function s(){process.removeListener(`exit`,c),o.unref(),r.autoEnd!==!1&&p(o)}function c(){o.closed||(o.flushSync(),u(100),o.end())}return o}function y(e){e.ref(),e.flushSync(),e.end(),e.once(`close`,function(){e.unref()})}function b(e){e.flushSync()}function x(e){let{pipeline:t,targets:n,levels:i,dedupe:l,worker:u={},caller:d=a(),sync:f=!1}=e,p={...e.options},m=typeof d==`string`?[d]:d,h=typeof globalThis==`object`&&Object.prototype.hasOwnProperty.call(globalThis,`__bundlerPathsOverrides`)&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides==`object`?globalThis.__bundlerPathsOverrides:Object.create(null),g=e.target;if(g&&n)throw Error(`only one of target or targets can be specified`);n?(g=h[`pino-worker`]||o(__dirname,`worker.js`),p.targets=n.filter(e=>e.target).map(e=>({...e,target:y(e.target)})),p.pipelines=n.filter(e=>e.pipeline).map(e=>e.pipeline.map(t=>({...t,level:e.level,target:y(t.target)})))):t&&(g=h[`pino-worker`]||o(__dirname,`worker.js`),p.pipelines=[t.map(e=>({...e,target:y(e.target)}))]),i&&(p.levels=i),l&&(p.dedupe=l),p.pinoWillSendConfig=!0;let _=n||t?`pino.transport`:g;return v(y(g),p,u,f,_);function y(e){if(e=h[e]||e,s(e)||e.indexOf(`file://`)===0)return e;if(e===`pino/file`)return o(__dirname,`..`,`file.js`);let t;for(let n of m)try{t=r(n===`node:repl`?process.cwd()+c:n).resolve(e);break}catch{continue}if(!t)throw Error(`unable to determine transport target for "${e}"`);return t}}n.exports=x})),Ps=n(((e,n)=>{let r=t(`node:diagnostics_channel`),i=Ts(),{mapHttpRequest:a,mapHttpResponse:o}=ys(),s=Ds(),c=Os(),{lsCacheSym:l,chindingsSym:u,writeSym:d,serializersSym:f,formatOptsSym:p,endSym:m,stringifiersSym:h,stringifySym:g,stringifySafeSym:_,wildcardFirstSym:v,nestedKeySym:y,formattersSym:b,messageKeySym:x,errorKeySym:S,nestedKeyStrSym:C,msgPrefixSym:w}=Ss(),{isMainThread:T}=t(`worker_threads`),E=Ns(),[D]=process.versions.node.split(`.`).map(e=>Number(e)),O=r.tracingChannel(`pino_asJson`),k=D>=25?e=>JSON.stringify(e):M;function A(){}function j(e,t){if(!t)return n;return function(...r){t.call(this,r,n,e)};function n(t,...n){if(typeof t==`object`){let r=t;t!==null&&(t.method&&t.headers&&t.socket?t=a(t):typeof t.setHeader==`function`&&(t=o(t)));let s;r===null&&n.length===0?s=[null]:(r=n.shift(),s=n),typeof this[w]==`string`&&r!=null&&(r=this[w]+r),this[d](t,i(r,s,this[p]),e)}else{let r=t===void 0?n.shift():t;typeof this[w]==`string`&&r!=null&&(r=this[w]+r),this[d](null,i(r,n,this[p]),e)}}}function M(e){let t=``,n=0,r=!1,i=255,a=e.length;if(a>100)return JSON.stringify(e);for(var o=0;o<a&&i>=32;o++)i=e.charCodeAt(o),(i===34||i===92)&&(t+=e.slice(n,o)+`\\`,n=o,r=!0);return r?t+=e.slice(n):t=e,i<32?JSON.stringify(e):`"`+t+`"`}function ee(e,t,n,r){if(O.hasSubscribers===!1)return N.call(this,e,t,n,r);let i={instance:this,arguments};return O.traceSync(N,i,this,e,t,n,r)}function N(e,t,n,r){let i=this[g],a=this[_],o=this[h],s=this[m],c=this[u],d=this[f],p=this[b],w=this[x],T=this[S],E=this[l][n]+r;E+=c;let D;p.log&&(e=p.log(e));let O=o[v],A=``;for(let t in e)if(D=e[t],Object.prototype.hasOwnProperty.call(e,t)&&D!==void 0){d[t]?D=d[t](D):t===T&&d.err&&(D=d.err(D));let e=o[t]||O;switch(typeof D){case`undefined`:case`function`:continue;case`number`:Number.isFinite(D)===!1&&(D=null);case`boolean`:e&&(D=e(D));break;case`string`:D=(e||k)(D);break;default:D=(e||i)(D,a)}if(D===void 0)continue;let n=k(t);A+=`,`+n+`:`+D}let j=``;if(t!==void 0){D=d[w]?d[w](t):t;let e=o[w]||O;switch(typeof D){case`function`:break;case`number`:Number.isFinite(D)===!1&&(D=null);case`boolean`:e&&(D=e(D)),j=`,"`+w+`":`+D;break;case`string`:D=(e||k)(D),j=`,"`+w+`":`+D;break;default:D=(e||i)(D,a),j=`,"`+w+`":`+D}}return this[y]&&A?E+this[C]+A.slice(1)+`}`+j+s:E+A+j+s}function te(e,t){let n,r=e[u],i=e[g],a=e[_],o=e[h],s=o[v],c=e[f],l=e[b].bindings;t=l(t);for(let e in t)if(n=t[e],((e.length<5||e!==`level`&&e!==`serializers`&&e!==`formatters`&&e!==`customLevels`)&&t.hasOwnProperty(e)&&n!==void 0)===!0){if(n=c[e]?c[e](n):n,n=(o[e]||s||i)(n,a),n===void 0)continue;r+=`,"`+e+`":`+n}return r}function ne(e){return e.write!==e.constructor.prototype.write}function P(e){let t=new s(e);return t.on(`error`,n),!e.sync&&T&&(c.register(t,re),t.on(`close`,function(){c.unregister(t)})),t;function n(e){if(e.code===`EPIPE`){t.write=A,t.end=A,t.flushSync=A,t.destroy=A;return}t.removeListener(`error`,n),t.emit(`error`,e)}}function re(e,t){e.destroyed||(t===`beforeExit`?(e.flush(),e.on(`drain`,function(){e.end()})):e.flushSync())}function F(e){return function(t,n,r={},i){if(typeof r==`string`)i=P({dest:r}),r={};else if(typeof i==`string`){if(r&&r.transport)throw Error(`only one of option.transport or stream can be specified`);i=P({dest:i})}else if(r instanceof s||r.writable||r._writableState)i=r,r={};else if(r.transport){if(r.transport instanceof s||r.transport.writable||r.transport._writableState)throw Error(`option.transport do not allow stream, please pass to option directly. e.g. pino(transport)`);if(r.transport.targets&&r.transport.targets.length&&r.formatters&&typeof r.formatters.level==`function`)throw Error(`option.transport.targets do not allow custom level formatters`);let e;r.customLevels&&(e=r.useOnlyCustomLevels?r.customLevels:Object.assign({},r.levels,r.customLevels)),i=E({caller:n,...r.transport,levels:e})}if(r=Object.assign({},e,r),r.serializers=Object.assign({},e.serializers,r.serializers),r.formatters=Object.assign({},e.formatters,r.formatters),r.prettyPrint)throw Error(`prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)`);let{enabled:a,onChild:o}=r;return a===!1&&(r.level=`silent`),o||(r.onChild=A),i||=ne(process.stdout)?process.stdout:P({fd:process.stdout.fd||1}),{opts:r,stream:i}}}function ie(e,t){try{return JSON.stringify(e)}catch{try{return(t||this[_])(e)}catch{return`"[unable to serialize, circular reference is too complex to analyze]"`}}}function ae(e,t,n){return{level:e,bindings:t,log:n}}function I(e){let t=Number(e);return typeof e==`string`&&Number.isFinite(t)?t:e===void 0?1:e}n.exports={noop:A,buildSafeSonicBoom:P,asChindings:te,asJson:ee,genLog:j,createArgsNormalizer:F,stringify:ie,buildFormatters:ae,normalizeDestFileDescriptor:I}})),Fs=n(((e,t)=>{t.exports={DEFAULT_LEVELS:{trace:10,debug:20,info:30,warn:40,error:50,fatal:60},SORTING_ORDER:{ASC:`ASC`,DESC:`DESC`}}})),Is=n(((e,t)=>{let{lsCacheSym:n,levelValSym:r,useOnlyCustomLevelsSym:i,streamSym:a,formattersSym:o,hooksSym:s,levelCompSym:c}=Ss(),{noop:l,genLog:u}=Ps(),{DEFAULT_LEVELS:d,SORTING_ORDER:f}=Fs(),p={fatal:e=>{let t=u(d.fatal,e);return function(...e){let n=this[a];if(t.call(this,...e),typeof n.flushSync==`function`)try{n.flushSync()}catch{}}},error:e=>u(d.error,e),warn:e=>u(d.warn,e),info:e=>u(d.info,e),debug:e=>u(d.debug,e),trace:e=>u(d.trace,e)},m=Object.keys(d).reduce((e,t)=>(e[d[t]]=t,e),{}),h=Object.keys(m).reduce((e,t)=>(e[t]=`{"level":`+Number(t),e),{});function g(e){let t=e[o].level,{labels:r}=e.levels,i={};for(let e in r){let n=t(r[e],Number(e));i[e]=JSON.stringify(n).slice(0,-1)}return e[n]=i,e}function _(e,t){if(t)return!1;switch(e){case`fatal`:case`error`:case`warn`:case`info`:case`debug`:case`trace`:return!0;default:return!1}}function v(e){let{labels:t,values:n}=this.levels;if(typeof e==`number`){if(t[e]===void 0)throw Error(`unknown level value`+e);e=t[e]}if(n[e]===void 0)throw Error(`unknown level `+e);let a=this[r],o=this[r]=n[e],d=this[i],f=this[c],m=this[s].logMethod;for(let e in n){if(f(n[e],o)===!1){this[e]=l;continue}this[e]=_(e,d)?p[e](m):u(n[e],m)}this.emit(`level-change`,e,o,t[a],a,this)}function y(e){let{levels:t,levelVal:n}=this;return t&&t.labels?t.labels[n]:``}function b(e){let{values:t}=this.levels,n=t[e];return n!==void 0&&this[c](n,this[r])}function x(e,t,n){return e===f.DESC?t<=n:t>=n}function S(e){return typeof e==`string`?x.bind(null,e):e}function C(e=null,t=!1){let n=e?Object.keys(e).reduce((t,n)=>(t[e[n]]=n,t),{}):null;return{labels:Object.assign(Object.create(Object.prototype,{Infinity:{value:`silent`}}),t?null:m,n),values:Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),t?null:d,e)}}function w(e,t,n){if(typeof e==`number`){if(![].concat(Object.keys(t||{}).map(e=>t[e]),n?[]:Object.keys(m).map(e=>+e),1/0).includes(e))throw Error(`default level:${e} must be included in custom levels`);return}if(!(e in Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),n?null:d,t)))throw Error(`default level:${e} must be included in custom levels`)}function T(e,t){let{labels:n,values:r}=e;for(let e in t){if(e in r)throw Error(`levels cannot be overridden`);if(t[e]in n)throw Error(`pre-existing level values cannot be used for new levels`)}}function E(e){if(typeof e!=`function`&&!(typeof e==`string`&&Object.values(f).includes(e)))throw Error(`Levels comparison should be one of "ASC", "DESC" or "function" type`)}t.exports={initialLsCache:h,genLsCache:g,levelMethods:p,getLevel:y,setLevel:v,isLevelEnabled:b,mappings:C,assertNoLevelCollisions:T,assertDefaultLevelFound:w,genLevelComparison:S,assertLevelComparison:E}})),Ls=n(((e,t)=>{t.exports={version:`10.3.1`}})),Rs=n(((e,n)=>{let{EventEmitter:r}=t(`node:events`),{lsCacheSym:i,levelValSym:a,setLevelSym:o,getLevelSym:s,chindingsSym:c,mixinSym:l,asJsonSym:u,writeSym:d,mixinMergeStrategySym:f,timeSym:p,timeSliceIndexSym:m,streamSym:h,serializersSym:g,formattersSym:_,errorKeySym:v,messageKeySym:y,useOnlyCustomLevelsSym:b,needsMetadataGsym:x,redactFmtSym:S,stringifySym:C,formatOptsSym:w,stringifiersSym:T,msgPrefixSym:E,hooksSym:D}=Ss(),{getLevel:O,setLevel:k,isLevelEnabled:A,mappings:j,initialLsCache:M,genLsCache:ee,assertNoLevelCollisions:N}=Is(),{asChindings:te,asJson:ne,buildFormatters:P,stringify:re,noop:F}=Ps(),{version:ie}=Ls(),ae=Cs(),I={constructor:class{},child:se,bindings:L,setBindings:ce,flush:R,isLevelEnabled:A,version:ie,get level(){return this[s]()},set level(e){this[o](e)},get levelVal(){return this[a]},set levelVal(e){throw Error(`levelVal is read-only`)},get msgPrefix(){return this[E]},get[Symbol.toStringTag](){return`Pino`},[i]:M,[d]:ue,[u]:ne,[s]:O,[o]:k};Object.setPrototypeOf(I,r.prototype),n.exports=function(){return Object.create(I)};let oe=e=>e;function se(e,t){if(!e)throw Error(`missing bindings for child Pino`);let n=this[g],r=this[_],i=Object.create(this);if(t==null)return i[_].bindings!==oe&&(i[_]=P(r.level,oe,r.log)),i[c]=te(i,e),this.onChild!==F&&this.onChild(i),i;if(t.hasOwnProperty(`serializers`)===!0){i[g]=Object.create(null);for(let e in n)i[g][e]=n[e];let e=Object.getOwnPropertySymbols(n);for(var a=0;a<e.length;a++){let t=e[a];i[g][t]=n[t]}for(let e in t.serializers)i[g][e]=t.serializers[e];let r=Object.getOwnPropertySymbols(t.serializers);for(var s=0;s<r.length;s++){let e=r[s];i[g][e]=t.serializers[e]}}else i[g]=n;if(t.hasOwnProperty(`formatters`)){let{level:e,bindings:n,log:a}=t.formatters;i[_]=P(e||r.level,n||oe,a||r.log)}else i[_]=P(r.level,oe,r.log);if(t.hasOwnProperty(`customLevels`)===!0&&(N(this.levels,t.customLevels),i.levels=j(t.customLevels,i[b]),ee(i)),typeof t.redact==`object`&&t.redact!==null||Array.isArray(t.redact)){i.redact=t.redact;let e=ae(i.redact,re),n={stringify:e[S]};i[C]=re,i[T]=e,i[w]=n}if(typeof t.msgPrefix==`string`&&(i[E]=(this[E]||``)+t.msgPrefix),i[c]=te(i,e),t.level!==void 0&&t.level!==this.level||t.hasOwnProperty(`customLevels`)){let e=t.level||this.level;i[o](e)}return this.onChild(i),i}function L(){let e=`{${this[c].substr(1)}}`,t=JSON.parse(e);return delete t.pid,delete t.hostname,t}function ce(e){this[c]=te(this,e)}function le(e,t){return Object.assign(t,e)}function ue(e,t,n){let r=this[p](),i=this[l],a=this[v],o=this[y],s=this[f]||le,c,d=this[D].streamWrite;e==null?c={}:e instanceof Error?(c={[a]:e},t===void 0&&(t=e.message)):(c=e,t===void 0&&e[o]===void 0&&e[a]&&(t=e[a].message)),i&&(c=s(c,i(c,n,this)));let g=this[u](c,t,n,r),_=this[h];_[x]===!0&&(_.lastLevel=n,_.lastObj=c,_.lastMsg=t,_.lastTime=r.slice(this[m]),_.lastLogger=this),_.write(d?d(g):g)}function R(e){if(e!=null&&typeof e!=`function`)throw Error(`callback must be a function`);let t=this[h];typeof t.flush==`function`?t.flush(e||F):e&&e()}})),zs=n(((e,t)=>{let{hasOwnProperty:n}=Object.prototype,r=_();r.configure=_,r.stringify=r,r.default=r,e.stringify=r,e.configure=_,t.exports=r;let i=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function a(e){return e.length<5e3&&!i.test(e)?`"${e}"`:JSON.stringify(e)}function o(e,t){if(e.length>200||t)return e.sort(t);for(let t=1;t<e.length;t++){let n=e[t],r=t;for(;r!==0&&e[r-1]>n;)e[r]=e[r-1],r--;e[r]=n}return e}let s=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function c(e){return s.call(e)!==void 0&&e.length!==0}function l(e,t,n){e.length<n&&(n=e.length);let r=t===`,`?``:` `,i=`"0":${r}${e[0]}`;for(let a=1;a<n;a++)i+=`${t}"${a}":${r}${e[a]}`;return i}function u(e){if(n.call(e,`circularValue`)){let t=e.circularValue;if(typeof t==`string`)return`"${t}"`;if(t==null)return t;if(t===Error||t===TypeError)return{toString(){throw TypeError(`Converting circular structure to JSON`)}};throw TypeError(`The "circularValue" argument must be of type string or the value null or undefined`)}return`"[Circular]"`}function d(e){let t;if(n.call(e,`deterministic`)&&(t=e.deterministic,typeof t!=`boolean`&&typeof t!=`function`))throw TypeError(`The "deterministic" argument must be of type boolean or comparator function`);return t===void 0?!0:t}function f(e,t){let r;if(n.call(e,t)&&(r=e[t],typeof r!=`boolean`))throw TypeError(`The "${t}" argument must be of type boolean`);return r===void 0?!0:r}function p(e,t){let r;if(n.call(e,t)){if(r=e[t],typeof r!=`number`)throw TypeError(`The "${t}" argument must be of type number`);if(!Number.isInteger(r))throw TypeError(`The "${t}" argument must be an integer`);if(r<1)throw RangeError(`The "${t}" argument must be >= 1`)}return r===void 0?1/0:r}function m(e){return e===1?`1 item`:`${e} items`}function h(e){let t=new Set;for(let n of e)(typeof n==`string`||typeof n==`number`)&&t.add(String(n));return t}function g(e){if(n.call(e,`strict`)){let t=e.strict;if(typeof t!=`boolean`)throw TypeError(`The "strict" argument must be of type boolean`);if(t)return e=>{let t=`Object can not safely be stringified. Received type ${typeof e}`;throw typeof e!=`function`&&(t+=` (${e.toString()})`),Error(t)}}}function _(e){e={...e};let t=g(e);t&&(e.bigint===void 0&&(e.bigint=!1),`circularValue`in e||(e.circularValue=Error));let n=u(e),r=f(e,`bigint`),i=d(e),s=typeof i==`function`?i:void 0,_=p(e,`maximumDepth`),v=p(e,`maximumBreadth`);function y(e,l,u,d,f,p){let h=l[e];switch(typeof h==`object`&&h&&typeof h.toJSON==`function`&&(h=h.toJSON(e)),h=d.call(l,e,h),typeof h){case`string`:return a(h);case`object`:{if(h===null)return`null`;if(u.indexOf(h)!==-1)return n;let e=``,t=`,`,r=p;if(Array.isArray(h)){if(h.length===0)return`[]`;if(_<u.length+1)return`"[Array]"`;u.push(h),f!==``&&(p+=f,e+=`\n${p}`,t=`,\n${p}`);let n=Math.min(h.length,v),i=0;for(;i<n-1;i++){let n=y(String(i),h,u,d,f,p);e+=n===void 0?`null`:n,e+=t}let a=y(String(i),h,u,d,f,p);if(e+=a===void 0?`null`:a,h.length-1>v){let n=h.length-v-1;e+=`${t}"... ${m(n)} not stringified"`}return f!==``&&(e+=`\n${r}`),u.pop(),`[${e}]`}let l=Object.keys(h),g=l.length;if(g===0)return`{}`;if(_<u.length+1)return`"[Object]"`;let b=``,x=``;f!==``&&(p+=f,t=`,\n${p}`,b=` `);let S=Math.min(g,v);i&&!c(h)&&(l=o(l,s)),u.push(h);for(let n=0;n<S;n++){let r=l[n],i=y(r,h,u,d,f,p);i!==void 0&&(e+=`${x}${a(r)}:${b}${i}`,x=t)}if(g>v){let n=g-v;e+=`${x}"...":${b}"${m(n)} not stringified"`,x=t}return f!==``&&x.length>1&&(e=`\n${p}${e}\n${r}`),u.pop(),`{${e}}`}case`number`:return isFinite(h)?String(h):t?t(h):`null`;case`boolean`:return h===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(h);default:return t?t(h):void 0}}function b(e,i,o,s,c,l){switch(typeof i==`object`&&i&&typeof i.toJSON==`function`&&(i=i.toJSON(e)),typeof i){case`string`:return a(i);case`object`:{if(i===null)return`null`;if(o.indexOf(i)!==-1)return n;let e=l,t=``,r=`,`;if(Array.isArray(i)){if(i.length===0)return`[]`;if(_<o.length+1)return`"[Array]"`;o.push(i),c!==``&&(l+=c,t+=`\n${l}`,r=`,\n${l}`);let n=Math.min(i.length,v),a=0;for(;a<n-1;a++){let e=b(String(a),i[a],o,s,c,l);t+=e===void 0?`null`:e,t+=r}let u=b(String(a),i[a],o,s,c,l);if(t+=u===void 0?`null`:u,i.length-1>v){let e=i.length-v-1;t+=`${r}"... ${m(e)} not stringified"`}return c!==``&&(t+=`\n${e}`),o.pop(),`[${t}]`}o.push(i);let u=``;c!==``&&(l+=c,r=`,\n${l}`,u=` `);let d=``;for(let e of s){let n=b(e,i[e],o,s,c,l);n!==void 0&&(t+=`${d}${a(e)}:${u}${n}`,d=r)}return c!==``&&d.length>1&&(t=`\n${l}${t}\n${e}`),o.pop(),`{${t}}`}case`number`:return isFinite(i)?String(i):t?t(i):`null`;case`boolean`:return i===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(i);default:return t?t(i):void 0}}function x(e,u,d,f,p){switch(typeof u){case`string`:return a(u);case`object`:{if(u===null)return`null`;if(typeof u.toJSON==`function`){if(u=u.toJSON(e),typeof u!=`object`)return x(e,u,d,f,p);if(u===null)return`null`}if(d.indexOf(u)!==-1)return n;let t=p;if(Array.isArray(u)){if(u.length===0)return`[]`;if(_<d.length+1)return`"[Array]"`;d.push(u),p+=f;let e=`\n${p}`,n=`,\n${p}`,r=Math.min(u.length,v),i=0;for(;i<r-1;i++){let t=x(String(i),u[i],d,f,p);e+=t===void 0?`null`:t,e+=n}let a=x(String(i),u[i],d,f,p);if(e+=a===void 0?`null`:a,u.length-1>v){let t=u.length-v-1;e+=`${n}"... ${m(t)} not stringified"`}return e+=`\n${t}`,d.pop(),`[${e}]`}let r=Object.keys(u),h=r.length;if(h===0)return`{}`;if(_<d.length+1)return`"[Object]"`;p+=f;let g=`,\n${p}`,y=``,b=``,S=Math.min(h,v);c(u)&&(y+=l(u,g,v),r=r.slice(u.length),S-=u.length,b=g),i&&(r=o(r,s)),d.push(u);for(let e=0;e<S;e++){let t=r[e],n=x(t,u[t],d,f,p);n!==void 0&&(y+=`${b}${a(t)}: ${n}`,b=g)}if(h>v){let e=h-v;y+=`${b}"...": "${m(e)} not stringified"`,b=g}return b!==``&&(y=`\n${p}${y}\n${t}`),d.pop(),`{${y}}`}case`number`:return isFinite(u)?String(u):t?t(u):`null`;case`boolean`:return u===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(u);default:return t?t(u):void 0}}function S(e,u,d){switch(typeof u){case`string`:return a(u);case`object`:{if(u===null)return`null`;if(typeof u.toJSON==`function`){if(u=u.toJSON(e),typeof u!=`object`)return S(e,u,d);if(u===null)return`null`}if(d.indexOf(u)!==-1)return n;let t=``,r=u.length!==void 0;if(r&&Array.isArray(u)){if(u.length===0)return`[]`;if(_<d.length+1)return`"[Array]"`;d.push(u);let e=Math.min(u.length,v),n=0;for(;n<e-1;n++){let e=S(String(n),u[n],d);t+=e===void 0?`null`:e,t+=`,`}let r=S(String(n),u[n],d);if(t+=r===void 0?`null`:r,u.length-1>v){let e=u.length-v-1;t+=`,"... ${m(e)} not stringified"`}return d.pop(),`[${t}]`}let f=Object.keys(u),p=f.length;if(p===0)return`{}`;if(_<d.length+1)return`"[Object]"`;let h=``,g=Math.min(p,v);r&&c(u)&&(t+=l(u,`,`,v),f=f.slice(u.length),g-=u.length,h=`,`),i&&(f=o(f,s)),d.push(u);for(let e=0;e<g;e++){let n=f[e],r=S(n,u[n],d);r!==void 0&&(t+=`${h}${a(n)}:${r}`,h=`,`)}if(p>v){let e=p-v;t+=`${h}"...":"${m(e)} not stringified"`}return d.pop(),`{${t}}`}case`number`:return isFinite(u)?String(u):t?t(u):`null`;case`boolean`:return u===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(u);default:return t?t(u):void 0}}function C(e,t,n){if(arguments.length>1){let r=``;if(typeof n==`number`?r=` `.repeat(Math.min(n,10)):typeof n==`string`&&(r=n.slice(0,10)),t!=null){if(typeof t==`function`)return y(``,{"":e},[],t,r,``);if(Array.isArray(t))return b(``,e,[],h(t),r,``)}if(r.length!==0)return x(``,e,[],r,``)}return S(``,e,[])}return C}})),Bs=n(((e,t)=>{let n=Symbol.for(`pino.metadata`),{DEFAULT_LEVELS:r}=Fs(),i=r.info;function a(e,t){e||=[],t||={dedupe:!1};let a=Object.create(r);a.silent=1/0,t.levels&&typeof t.levels==`object`&&Object.keys(t.levels).forEach(e=>{a[e]=t.levels[e]});let u={write:d,add:m,remove:h,emit:f,flushSync:p,end:g,minLevel:0,lastId:0,streams:[],clone:_,[n]:!0,streamLevels:a};return Array.isArray(e)?e.forEach(m,u):m.call(u,e),e=null,u;function d(e){let r,i=this.lastLevel,{streams:a}=this,o=0,u;for(let d=s(a.length,t.dedupe);l(d,a.length,t.dedupe);d=c(d,t.dedupe))if(r=a[d],r.level<=i){if(o!==0&&o!==r.level)break;if(u=r.stream,u[n]){let{lastTime:e,lastMsg:t,lastObj:n,lastLogger:r}=this;u.lastLevel=i,u.lastTime=e,u.lastMsg=t,u.lastObj=n,u.lastLogger=r}u.write(e),t.dedupe&&(o=r.level)}else if(!t.dedupe)break}function f(...e){for(let{stream:t}of this.streams)typeof t.emit==`function`&&t.emit(...e)}function p(){for(let{stream:e}of this.streams)typeof e.flushSync==`function`&&e.flushSync()}function m(e){if(!e)return u;let t=typeof e.write==`function`||e.stream,n=e.write?e:e.stream;if(!t)throw Error(`stream object needs to implement either StreamEntry or DestinationStream interface`);let{streams:r,streamLevels:a}=this,s;s=typeof e.levelVal==`number`?e.levelVal:typeof e.level==`string`?a[e.level]:typeof e.level==`number`?e.level:i;let c={stream:n,level:s,levelVal:void 0,id:++u.lastId};return r.unshift(c),r.sort(o),this.minLevel=r[0].level,u}function h(e){let{streams:t}=this,n=t.findIndex(t=>t.id===e);return n>=0&&(t.splice(n,1),t.sort(o),this.minLevel=t.length>0?t[0].level:-1),u}function g(){for(let{stream:e}of this.streams)typeof e.flushSync==`function`&&e.flushSync(),e.end()}function _(e){let t=Array(this.streams.length);for(let n=0;n<t.length;n++)t[n]={level:e,stream:this.streams[n].stream};return{write:d,add:m,remove:h,minLevel:e,streams:t,clone:_,emit:f,flushSync:p,[n]:!0}}}function o(e,t){return e.level-t.level}function s(e,t){return t?e-1:0}function c(e,t){return t?e-1:e+1}function l(e,t,n){return n?e>=0:e<t}t.exports=a})),Vs=n(((e,n)=>{let r=t(`node:os`),i=ys(),a=bs(),o=Cs(),s=ws(),c=Rs(),l=Ss(),{configure:u}=zs(),{assertDefaultLevelFound:d,mappings:f,genLsCache:p,genLevelComparison:m,assertLevelComparison:h}=Is(),{DEFAULT_LEVELS:g,SORTING_ORDER:_}=Fs(),{createArgsNormalizer:v,asChindings:y,buildSafeSonicBoom:b,buildFormatters:x,stringify:S,normalizeDestFileDescriptor:C,noop:w}=Ps(),{version:T}=Ls(),{chindingsSym:E,redactFmtSym:D,serializersSym:O,timeSym:k,timeSliceIndexSym:A,streamSym:j,stringifySym:M,stringifySafeSym:ee,stringifiersSym:N,setLevelSym:te,endSym:ne,formatOptsSym:P,messageKeySym:re,errorKeySym:F,nestedKeySym:ie,mixinSym:ae,levelCompSym:I,useOnlyCustomLevelsSym:oe,formattersSym:se,hooksSym:L,nestedKeyStrSym:ce,mixinMergeStrategySym:le,msgPrefixSym:ue}=l,{epochTime:R,nullTime:de}=s,{pid:fe}=process,pe=r.hostname(),me=i.err,he=v({level:`info`,levelComparison:_.ASC,levels:g,messageKey:`msg`,errorKey:`err`,nestedKey:null,enabled:!0,base:{pid:fe,hostname:pe},serializers:Object.assign(Object.create(null),{err:me}),formatters:Object.assign(Object.create(null),{bindings(e){return e},level(e,t){return{level:t}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:R,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100}),ge=Object.assign(Object.create(null),i);function z(...e){let t={},{opts:n,stream:r}=he(t,a(),...e);n.level&&typeof n.level==`string`&&g[n.level.toLowerCase()]!==void 0&&(n.level=n.level.toLowerCase());let{redact:i,crlf:s,serializers:l,timestamp:_,messageKey:v,errorKey:b,nestedKey:C,base:T,name:fe,level:pe,customLevels:me,levelComparison:ge,mixin:z,mixinMergeStrategy:_e,useOnlyCustomLevels:ve,formatters:ye,hooks:be,depthLimit:xe,edgeLimit:Se,onChild:Ce,msgPrefix:we}=n,B=u({maximumDepth:xe,maximumBreadth:Se}),V=x(ye.level,ye.bindings,ye.log),Te=S.bind({[ee]:B}),Ee=i?o(i,Te):{},De=i?{stringify:Ee[D]}:{stringify:Te},Oe=`}`+(s?`\r
5
+ caused by: `+i(o,t)):a},a=e=>i(e,new Set),o=(e,t,i)=>{if(!n(e))return``;let a=i?``:e.message||``;if(t.has(e))return a+`: ...`;let s=r(e);if(s){t.add(e);let n=typeof e.cause==`function`;return a+(n?``:`: `)+o(s,t,n)}else return a};t.exports={isErrorLike:n,getErrorCause:r,stackWithCauses:a,messageWithCauses:e=>o(e,new Set)}})),gs=n(((e,t)=>{let n=Symbol(`circular-ref-tag`),r=Symbol(`pino-raw-err-ref`),i=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[r]},set:function(e){this[r]=e}}});Object.defineProperty(i,r,{writable:!0,value:{}}),t.exports={pinoErrProto:i,pinoErrorSymbols:{seen:n,rawSymbol:r}}})),_s=n(((e,t)=>{t.exports=l;let{messageWithCauses:n,stackWithCauses:r,isErrorLike:i}=hs(),{pinoErrProto:a,pinoErrorSymbols:o}=gs(),{seen:s}=o,{toString:c}=Object.prototype;function l(e){if(!i(e))return e;e[s]=void 0;let t=Object.create(a);t.type=c.call(e.constructor)===`[object Function]`?e.constructor.name:e.name,t.message=n(e),t.stack=r(e),Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(e=>l(e)));for(let n in e)if(t[n]===void 0){let r=e[n];i(r)?n!==`cause`&&!Object.prototype.hasOwnProperty.call(r,s)&&(t[n]=l(r)):t[n]=r}return delete e[s],t.raw=e,t}})),vs=n(((e,t)=>{t.exports=s;let{isErrorLike:n}=hs(),{pinoErrProto:r,pinoErrorSymbols:i}=gs(),{seen:a}=i,{toString:o}=Object.prototype;function s(e){if(!n(e))return e;e[a]=void 0;let t=Object.create(r);t.type=o.call(e.constructor)===`[object Function]`?e.constructor.name:e.name,t.message=e.message,t.stack=e.stack,Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(e=>s(e))),n(e.cause)&&!Object.prototype.hasOwnProperty.call(e.cause,a)&&(t.cause=s(e.cause));for(let r in e)if(t[r]===void 0){let i=e[r];n(i)?Object.prototype.hasOwnProperty.call(i,a)||(t[r]=s(i)):t[r]=i}return delete e[a],t.raw=e,t}})),ys=n(((e,t)=>{t.exports={mapHttpRequest:a,reqSerializer:i};let n=Symbol(`pino-raw-req-ref`),r=Object.create({},{id:{enumerable:!0,writable:!0,value:``},method:{enumerable:!0,writable:!0,value:``},url:{enumerable:!0,writable:!0,value:``},query:{enumerable:!0,writable:!0,value:``},params:{enumerable:!0,writable:!0,value:``},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:``},remotePort:{enumerable:!0,writable:!0,value:``},raw:{enumerable:!1,get:function(){return this[n]},set:function(e){this[n]=e}}});Object.defineProperty(r,n,{writable:!0,value:{}});function i(e){let t=e.info||e.socket,n=Object.create(r);if(n.id=typeof e.id==`function`?e.id():e.id||(e.info?e.info.id:void 0),n.method=e.method,e.originalUrl)n.url=e.originalUrl;else{let t=e.path;n.url=typeof t==`string`?t:e.url?e.url.path||e.url:void 0}return e.query&&(n.query=e.query),e.params&&(n.params=e.params),n.headers=e.headers,n.remoteAddress=t&&t.remoteAddress,n.remotePort=t&&t.remotePort,n.raw=e.raw||e,n}function a(e){return{req:i(e)}}})),bs=n(((e,t)=>{t.exports={mapHttpResponse:a,resSerializer:i};let n=Symbol(`pino-raw-res-ref`),r=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:``},raw:{enumerable:!1,get:function(){return this[n]},set:function(e){this[n]=e}}});Object.defineProperty(r,n,{writable:!0,value:{}});function i(e){let t=Object.create(r);return t.statusCode=e.headersSent?e.statusCode:null,t.headers=e.getHeaders?e.getHeaders():e._headers,t.raw=e,t}function a(e){return{res:i(e)}}})),xs=n(((e,t)=>{let n=_s(),r=vs(),i=ys(),a=bs();t.exports={err:n,errWithCause:r,mapHttpRequest:i.mapHttpRequest,mapHttpResponse:a.mapHttpResponse,req:i.reqSerializer,res:a.resSerializer,wrapErrorSerializer:function(e){return e===n?e:function(t){return e(n(t))}},wrapRequestSerializer:function(e){return e===i.reqSerializer?e:function(t){return e(i.reqSerializer(t))}},wrapResponseSerializer:function(e){return e===a.resSerializer?e:function(t){return e(a.resSerializer(t))}}}})),Ss=n(((e,t)=>{function n(e,t){return t}t.exports=function(){let e=Error.prepareStackTrace;Error.prepareStackTrace=n;let t=Error().stack;if(Error.prepareStackTrace=e,!Array.isArray(t))return;let r=t.slice(2),i=[];for(let e of r)e&&i.push(e.getFileName());return i}})),Cs=n(((e,t)=>{function n(e){if(typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof Array){let t=[];for(let r=0;r<e.length;r++)t[r]=n(e[r]);return t}if(typeof e==`object`){let t=Object.create(Object.getPrototypeOf(e));for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=n(e[r]));return t}return e}function r(e){let t=[],n=``,r=!1,i=!1,a=``;for(let o=0;o<e.length;o++){let s=e[o];!r&&s===`.`?n&&=(t.push(n),``):s===`[`?(n&&=(t.push(n),``),r=!0):s===`]`&&r?(t.push(n),n=``,r=!1,i=!1):(s===`"`||s===`'`)&&r?i?s===a?(i=!1,a=``):n+=s:(i=!0,a=s):n+=s}return n&&t.push(n),t}function i(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){let n=t[e];if(typeof r!=`object`||!r||!(n in r)||typeof r[n]!=`object`||r[n]===null)return!1;r=r[n]}let i=t[t.length-1];if(i===`*`){if(Array.isArray(r))for(let e=0;e<r.length;e++)r[e]=n;else if(typeof r==`object`&&r)for(let e in r)Object.prototype.hasOwnProperty.call(r,e)&&(r[e]=n)}else typeof r==`object`&&r&&i in r&&Object.prototype.hasOwnProperty.call(r,i)&&(r[i]=n);return!0}function a(e,t){let n=e;for(let e=0;e<t.length-1;e++){let r=t[e];if(typeof n!=`object`||!n||!(r in n)||typeof n[r]!=`object`||n[r]===null)return!1;n=n[r]}let r=t[t.length-1];if(r===`*`){if(Array.isArray(n))for(let e=0;e<n.length;e++)n[e]=void 0;else if(typeof n==`object`&&n)for(let e in n)Object.prototype.hasOwnProperty.call(n,e)&&delete n[e]}else typeof n==`object`&&n&&r in n&&Object.prototype.hasOwnProperty.call(n,r)&&delete n[r];return!0}let o=Symbol(`PATH_NOT_FOUND`);function s(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n||!n||!(e in n))return o;n=n[e]}return n}function c(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n||!n)return;n=n[e]}return n}function l(e,t,n,c=!1){for(let l of t){let t=r(l);if(t.includes(`*`))u(e,t,n,l,c);else if(c)a(e,t);else{let r=s(e,t);if(r===o)continue;i(e,t,typeof n==`function`?n(r,t):n)}}}function u(e,t,n,r,i=!1){let a=t.indexOf(`*`);if(a===t.length-1){let r=t.slice(0,-1),a=e;for(let e of r){if(typeof a!=`object`||!a||!a)return;a=a[e]}if(Array.isArray(a))if(i)for(let e=0;e<a.length;e++)a[e]=void 0;else for(let e=0;e<a.length;e++){let t=[...r,e.toString()],i=typeof n==`function`?n(a[e],t):n;a[e]=i}else if(typeof a==`object`&&a)if(i){let e=[];for(let t in a)Object.prototype.hasOwnProperty.call(a,t)&&e.push(t);for(let t of e)delete a[t]}else for(let e in a){let t=[...r,e],i=typeof n==`function`?n(a[e],t):n;a[e]=i}}else d(e,t,n,a,r,i)}function d(e,t,n,r,o,s=!1){let l=t.slice(0,r),d=t.slice(r+1),f=[];function p(e,t){if(t===l.length){if(Array.isArray(e))for(let n=0;n<e.length;n++)f[t]=n.toString(),p(e[n],t+1);else if(typeof e==`object`&&e)for(let n in e)f[t]=n,p(e[n],t+1)}else if(t<l.length){let n=l[t];e&&typeof e==`object`&&e&&n in e&&(f[t]=n,p(e[n],t+1))}else d.includes(`*`)?u(e,d,typeof n==`function`?(e,r)=>n(e,[...f.slice(0,t),...r]):n,o,s):s?a(e,d):i(e,d,typeof n==`function`?n(c(e,d),[...f.slice(0,t),...d]):n)}if(l.length===0)p(e,0);else{let t=e;for(let e=0;e<l.length;e++){let n=l[e];if(typeof t!=`object`||!t||!t)return;t=t[n],f[e]=n}t!=null&&p(t,l.length)}}function f(e){if(e.length===0)return null;let t=new Map;for(let n of e){let e=r(n),i=t;for(let t=0;t<e.length;t++){let n=e[t];i.has(n)||i.set(n,new Map),i=i.get(n)}}return t}function p(e,t){if(!t)return e;function n(e,t,r=0){if(!t||t.size===0||typeof e!=`object`||!e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e)){let r=[];for(let i=0;i<e.length;i++){let a=i.toString();t.has(a)||t.has(`*`)?r[i]=n(e[i],t.get(a)||t.get(`*`)):r[i]=e[i]}return r}let i=Object.create(Object.getPrototypeOf(e));for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t.has(r)||t.has(`*`)?i[r]=n(e[r],t.get(r)||t.get(`*`)):i[r]=e[r]);return i}return n(e,t)}function m(e){if(typeof e!=`string`)throw Error(`Paths must be (non-empty) strings`);if(e===``)throw Error(`Invalid redaction path ()`);if(e.includes(`..`)||e.includes(`,`))throw Error(`Invalid redaction path (${e})`);let t=0,n=!1,r=``;for(let i=0;i<e.length;i++){let a=e[i];if((a===`"`||a===`'`)&&t>0)n?a===r&&(n=!1,r=``):(n=!0,r=a);else if(a===`[`&&!n)t++;else if(a===`]`&&!n&&(t--,t<0))throw Error(`Invalid redaction path (${e})`)}if(t!==0)throw Error(`Invalid redaction path (${e})`)}function h(e){if(!Array.isArray(e))throw TypeError(`paths must be an array`);for(let t of e)m(t)}function g(e={}){let{paths:t=[],censor:r=`[REDACTED]`,serialize:i=JSON.stringify,strict:a=!0,remove:o=!1}=e;h(t);let s=f(t);return function(e){if(a&&(typeof e!=`object`||!e)&&(typeof e!=`object`||!e))return i?i(e):e;let c=p(e,s),u=e,d=r;return typeof r==`function`&&(d=r),l(c,t,d,o),i===!1?(c.restore=function(){return n(u)},c):typeof i==`function`?i(c):JSON.stringify(c)}}t.exports=g})),ws=n(((e,t)=>{let n=Symbol(`pino.setLevel`),r=Symbol(`pino.getLevel`),i=Symbol(`pino.levelVal`),a=Symbol(`pino.levelComp`),o=Symbol(`pino.useLevelLabels`),s=Symbol(`pino.useOnlyCustomLevels`),c=Symbol(`pino.mixin`),l=Symbol(`pino.lsCache`),u=Symbol(`pino.chindings`),d=Symbol(`pino.asJson`),f=Symbol(`pino.write`),p=Symbol(`pino.redactFmt`),m=Symbol(`pino.time`),h=Symbol(`pino.timeSliceIndex`),g=Symbol(`pino.stream`),_=Symbol(`pino.stringify`),v=Symbol(`pino.stringifySafe`),y=Symbol(`pino.stringifiers`),b=Symbol(`pino.end`),x=Symbol(`pino.formatOpts`),S=Symbol(`pino.messageKey`),C=Symbol(`pino.errorKey`),w=Symbol(`pino.nestedKey`),T=Symbol(`pino.nestedKeyStr`),E=Symbol(`pino.mixinMergeStrategy`),D=Symbol(`pino.msgPrefix`),O=Symbol(`pino.wildcardFirst`),k=Symbol.for(`pino.serializers`),A=Symbol.for(`pino.formatters`),j=Symbol.for(`pino.hooks`);t.exports={setLevelSym:n,getLevelSym:r,levelValSym:i,levelCompSym:a,useLevelLabelsSym:o,mixinSym:c,lsCacheSym:l,chindingsSym:u,asJsonSym:d,writeSym:f,serializersSym:k,redactFmtSym:p,timeSym:m,timeSliceIndexSym:h,streamSym:g,stringifySym:_,stringifySafeSym:v,stringifiersSym:y,endSym:b,formatOptsSym:x,messageKeySym:S,errorKeySym:C,nestedKeySym:w,wildcardFirstSym:O,needsMetadataGsym:Symbol.for(`pino.metadata`),useOnlyCustomLevelsSym:s,formattersSym:A,hooksSym:j,nestedKeyStrSym:T,mixinMergeStrategySym:E,msgPrefixSym:D}})),Ts=n(((e,t)=>{let n=Cs(),{redactFmtSym:r,wildcardFirstSym:i}=ws(),a=/[^.[\]]+|\[([^[\]]*?)\]/g,o=`[Redacted]`;function s(e,t){let{paths:o,censor:s,remove:l}=c(e),u=o.reduce((e,t)=>{a.lastIndex=0;let n=a.exec(t),r=a.exec(t),o=n[1]===void 0?n[0]:n[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,`$1`);if(o===`*`&&(o=i),r===null)return e[o]=null,e;if(e[o]===null)return e;let{index:s}=r,c=`${t.substr(s,t.length-1)}`;return e[o]=e[o]||[],o!==i&&e[o].length===0&&e[o].push(...e[i]||[]),o===i&&Object.keys(e).forEach(function(t){e[t]&&e[t].push(c)}),e[o].push(c),e},{}),d={[r]:n({paths:o,censor:s,serialize:t,strict:!1,remove:l})},f=(...e)=>t(typeof s==`function`?s(...e):s);return[...Object.keys(u),...Object.getOwnPropertySymbols(u)].reduce((e,r)=>{if(u[r]===null)e[r]=e=>f(e,[r]);else{let i=typeof s==`function`?(e,t)=>s(e,[r,...t]):s;e[r]=n({paths:u[r],censor:i,serialize:t,strict:!1,remove:l})}return e},d)}function c(e){if(Array.isArray(e))return e={paths:e,censor:o},e;let{paths:t,censor:n=o,remove:r}=e;if(Array.isArray(t)===!1)throw Error(`pino – redact must contain an array of strings`);return r===!0&&(n=void 0),{paths:t,censor:n,remove:r}}t.exports=s})),Es=n(((e,t)=>{let n=()=>``,r=()=>`,"time":${Date.now()}`,i=()=>`,"time":${Math.round(Date.now()/1e3)}`,a=()=>`,"time":"${new Date(Date.now()).toISOString()}"`,o=1000000000n,s=BigInt(Date.now())*1000000n,c=process.hrtime.bigint();t.exports={nullTime:n,epochTime:r,unixTime:i,isoTime:a,isoTimeNano:()=>{let e=s+(process.hrtime.bigint()-c),t=e/o,n=e%o,r=Number(t*1000n+n/1000000n),i=new Date(r);return`,"time":"${i.getUTCFullYear()}-${(i.getUTCMonth()+1).toString().padStart(2,`0`)}-${i.getUTCDate().toString().padStart(2,`0`)}T${i.getUTCHours().toString().padStart(2,`0`)}:${i.getUTCMinutes().toString().padStart(2,`0`)}:${i.getUTCSeconds().toString().padStart(2,`0`)}.${n.toString().padStart(9,`0`)}Z"`}}})),Ds=n(((e,t)=>{function n(e){try{return JSON.stringify(e)}catch{return`"[Circular]"`}}t.exports=r;function r(e,t,r){var i=r&&r.stringify||n,a=1;if(typeof e==`object`&&e){var o=t.length+a;if(o===1)return e;var s=Array(o);s[0]=i(e);for(var c=1;c<o;c++)s[c]=i(t[c]);return s.join(` `)}if(typeof e!=`string`)return e;var l=t.length;if(l===0)return e;for(var u=``,d=1-a,f=-1,p=e&&e.length||0,m=0;m<p;){if(e.charCodeAt(m)===37&&m+1<p){switch(f=f>-1?f:0,e.charCodeAt(m+1)){case 100:case 102:if(d>=l||t[d]==null)break;f<m&&(u+=e.slice(f,m)),u+=Number(t[d]),f=m+2,m++;break;case 105:if(d>=l||t[d]==null)break;f<m&&(u+=e.slice(f,m)),u+=Math.floor(Number(t[d])),f=m+2,m++;break;case 79:case 111:case 106:if(d>=l||t[d]===void 0)break;f<m&&(u+=e.slice(f,m));var h=typeof t[d];if(h===`string`){u+=`'`+t[d]+`'`,f=m+2,m++;break}if(h===`function`){u+=t[d].name||`<anonymous>`,f=m+2,m++;break}u+=i(t[d]),f=m+2,m++;break;case 115:if(d>=l)break;f<m&&(u+=e.slice(f,m)),u+=String(t[d]),f=m+2,m++;break;case 37:f<m&&(u+=e.slice(f,m)),u+=`%`,f=m+2,m++,d--;break}++d}++m}return f===-1?e:(f<p&&(u+=e.slice(f)),u)}})),Os=n(((e,t)=>{if(typeof SharedArrayBuffer<`u`&&typeof Atomics<`u`){let e=new Int32Array(new SharedArrayBuffer(4));function n(t){if(!(t>0&&t<1/0))throw typeof t!=`number`&&typeof t!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);Atomics.wait(e,0,0,Number(t))}t.exports=n}else{function e(e){if(!(e>0&&e<1/0))throw typeof e!=`number`&&typeof e!=`bigint`?TypeError(`sleep: ms must be a number`):RangeError(`sleep: ms must be a number that is greater than 0 but less than Infinity`);let t=Date.now()+Number(e);for(;t>Date.now(););}t.exports=e}})),ks=n(((e,n)=>{let r=t(`fs`),i=t(`events`),a=t(`util`).inherits,o=t(`path`),s=Os(),c=t(`assert`),l=Buffer.allocUnsafe(0),u=`buffer`,d=`utf8`,[f,p]=(process.versions.node||`0.0`).split(`.`).map(Number),m=f>=22&&p>=7;function h(e,t){t._opening=!0,t._writing=!0,t._asyncDrainScheduled=!1;function n(n,r){if(n){t._reopening=!1,t._writing=!1,t._opening=!1,t.sync?process.nextTick(()=>{t.listenerCount(`error`)>0&&t.emit(`error`,n)}):t.emit(`error`,n);return}let i=t._reopening;t.fd=r,t.file=e,t._reopening=!1,t._opening=!1,t._writing=!1,t.sync?process.nextTick(()=>t.emit(`ready`)):t.emit(`ready`),!t.destroyed&&(!t._writing&&t._len>t.minLength||t._flushPending?t._actualWrite():i&&process.nextTick(()=>t.emit(`drain`)))}let i=t.append?`a`:`w`,a=t.mode;if(t.sync)try{t.mkdir&&r.mkdirSync(o.dirname(e),{recursive:!0}),n(null,r.openSync(e,i,a))}catch(e){throw n(e),e}else t.mkdir?r.mkdir(o.dirname(e),{recursive:!0},t=>{if(t)return n(t);r.open(e,i,a,n)}):r.open(e,i,a,n)}function g(e){if(!(this instanceof g))return new g(e);let{fd:t,dest:n,minLength:i,maxLength:a,maxWrite:o,periodicFlush:c,sync:f,append:p=!0,mkdir:m,retryEAGAIN:y,fsync:S,contentMode:A,mode:j}=e||{};t||=n,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(i||0,16387),this.file=null,this.destroyed=!1,this.minLength=i||0,this.maxLength=a||0,this.maxWrite=o||16384,this._periodicFlush=c||0,this._periodicFlushTimer=void 0,this.sync=f||!1,this.writable=!0,this._fsync=S||!1,this.append=p||!1,this.mode=j,this.retryEAGAIN=y||(()=>!0),this.mkdir=m||!1;let M,ee;if(A===u)this._writingBuf=l,this.write=x,this.flush=w,this.flushSync=E,this._actualWrite=O,M=()=>r.writeSync(this.fd,this._writingBuf),ee=()=>r.write(this.fd,this._writingBuf,this.release);else if(A===void 0||A===d)this._writingBuf=``,this.write=b,this.flush=C,this.flushSync=T,this._actualWrite=D,M=()=>Buffer.isBuffer(this._writingBuf)?r.writeSync(this.fd,this._writingBuf):r.writeSync(this.fd,this._writingBuf,`utf8`),ee=()=>Buffer.isBuffer(this._writingBuf)?r.write(this.fd,this._writingBuf,this.release):r.write(this.fd,this._writingBuf,`utf8`,this.release);else throw Error(`SonicBoom supports "${d}" and "${u}", but passed ${A}`);if(typeof t==`number`)this.fd=t,process.nextTick(()=>this.emit(`ready`));else if(typeof t==`string`)h(t,this);else throw Error(`SonicBoom supports only file descriptors and files`);if(this.minLength>=this.maxWrite)throw Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(e,t)=>{if(e){if((e.code===`EAGAIN`||e.code===`EBUSY`)&&this.retryEAGAIN(e,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{s(100),this.release(void 0,0)}catch(e){this.release(e)}else setTimeout(ee,100);else this._writing=!1,this.emit(`error`,e);return}this.emit(`write`,t);let n=_(this._writingBuf,this._len,t);if(this._len=n.len,this._writingBuf=n.writingBuf,this._writingBuf.length){if(!this.sync){ee();return}try{do{let e=M(),t=_(this._writingBuf,this._len,e);this._len=t.len,this._writingBuf=t.writingBuf}while(this._writingBuf.length)}catch(e){this.release(e);return}}this._fsync&&r.fsyncSync(this.fd);let i=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):i>this.minLength?this._actualWrite():this._ending?i>0?this._actualWrite():(this._writing=!1,k(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(v,this)):this.emit(`drain`))},this.on(`newListener`,function(e){e===`drain`&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function _(e,t,n){return typeof e==`string`&&(e=Buffer.from(e)),t=Math.max(t-n,0),e=e.subarray(n),{writingBuf:e,len:t}}function v(e){e.listenerCount(`drain`)>0&&(e._asyncDrainScheduled=!1,e.emit(`drain`))}a(g,i);function y(e,t){return e.length===0?l:e.length===1?e[0]:Buffer.concat(e,t)}function b(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);e=``+e;let t=Buffer.byteLength(e),n=this._len+t,r=this._bufs;return this.maxLength&&n>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(r.length===0||Buffer.byteLength(r[r.length-1])+t>this.maxWrite?r.push(e):r[r.length-1]+=e,this._len=n,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function x(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);let t=this._len+e.length,n=this._bufs,r=this._lens;return this.maxLength&&t>this.maxLength?(this.emit(`drop`,e),this._len<this._hwm):(n.length===0||r[r.length-1]+e.length>this.maxWrite?(n.push([e]),r.push(e.length)):(n[n.length-1].push(e),r[r.length-1]+=e.length),this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len<this._hwm)}function S(e){this._flushPending=!0;let t=()=>{if(this._fsync)this._flushPending=!1,e();else try{r.fsync(this.fd,t=>{this._flushPending=!1,e(t)})}catch(t){e(t)}this.off(`error`,n)},n=n=>{this._flushPending=!1,e(n),this.off(`drain`,t)};this.once(`drain`,t),this.once(`error`,n)}function C(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&S.call(this,e),!this._writing&&(this._bufs.length===0&&this._bufs.push(``),this._actualWrite())}function w(e){if(e!=null&&typeof e!=`function`)throw Error(`flush cb must be a function`);if(this.destroyed){let t=Error(`SonicBoom destroyed`);if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&S.call(this,e),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}g.prototype.reopen=function(e){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.reopen(e)});return}if(this._ending)return;if(!this.file)throw Error(`Unable to reopen a file descriptor, you must pass a file to SonicBoom`);if(e&&(this.file=e),this._reopening=!0,this._writing)return;let t=this.fd;this.once(`ready`,()=>{t!==this.fd&&r.close(t,e=>{if(e)return this.emit(`error`,e)})}),h(this.file,this)},g.prototype.end=function(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this._opening){this.once(`ready`,()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():k(this)))};function T(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf=``);let e=``;for(;this._bufs.length||e.length;){e.length<=0&&(e=this._bufs[0]);try{let t=Buffer.isBuffer(e)?r.writeSync(this.fd,e):r.writeSync(this.fd,e,`utf8`),n=_(e,this._len,t);e=n.writingBuf,this._len=n.len,e.length<=0&&this._bufs.shift()}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;s(100)}}try{r.fsyncSync(this.fd)}catch{}}function E(){if(this.destroyed)throw Error(`SonicBoom destroyed`);if(this.fd<0)throw Error(`sonic boom is not ready yet`);!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=l);let e=l;for(;this._bufs.length||e.length;){e.length<=0&&(e=y(this._bufs[0],this._lens[0]));try{let t=r.writeSync(this.fd,e);e=e.subarray(t),this._len=Math.max(this._len-t,0),e.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(t){if((t.code===`EAGAIN`||t.code===`EBUSY`)&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;s(100)}}}g.prototype.destroy=function(){this.destroyed||k(this)};function D(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:this._bufs.shift()||``,this.sync)try{e(null,Buffer.isBuffer(this._writingBuf)?r.writeSync(this.fd,this._writingBuf):r.writeSync(this.fd,this._writingBuf,`utf8`))}catch(t){e(t)}else r.write(this.fd,this._writingBuf,e)}function O(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:y(this._bufs.shift(),this._lens.shift()),this.sync)try{e(null,r.writeSync(this.fd,this._writingBuf))}catch(t){e(t)}else m&&(this._writingBuf=Buffer.from(this._writingBuf)),r.write(this.fd,this._writingBuf,e)}function k(e){if(e.fd===-1){e.once(`ready`,k.bind(null,e));return}e._periodicFlushTimer!==void 0&&clearInterval(e._periodicFlushTimer),e.destroyed=!0,e._bufs=[],e._lens=[],c(typeof e.fd==`number`,`sonic.fd must be a number, got ${typeof e.fd}`);try{r.fsync(e.fd,t)}catch{}function t(){e.fd!==1&&e.fd!==2?r.close(e.fd,n):n()}function n(t){if(t){e.emit(`error`,t);return}e._ending&&!e._writing&&e.emit(`finish`),e.emit(`close`)}}g.SonicBoom=g,g.default=g,n.exports=g})),As=n(((e,t)=>{let n={exit:[],beforeExit:[]},r={exit:c,beforeExit:l},i;function a(){i===void 0&&(i=new FinalizationRegistry(d))}function o(e){n[e].length>0||process.on(e,r[e])}function s(e){n[e].length>0||(process.removeListener(e,r[e]),n.exit.length===0&&n.beforeExit.length===0&&(i=void 0))}function c(){u(`exit`)}function l(){u(`beforeExit`)}function u(e){for(let t of n[e]){let n=t.deref(),r=t.fn;n!==void 0&&r(n,e)}n[e]=[]}function d(e){for(let t of[`exit`,`beforeExit`]){let r=n[t].indexOf(e);n[t].splice(r,r+1),s(t)}}function f(e,t,r){if(t===void 0)throw Error(`the object can't be undefined`);o(e);let s=new WeakRef(t);s.fn=r,a(),i.register(t,s),n[e].push(s)}function p(e,t){f(`exit`,e,t)}function m(e,t){f(`beforeExit`,e,t)}function h(e){if(i!==void 0){i.unregister(e);for(let t of[`exit`,`beforeExit`])n[t]=n[t].filter(t=>{let n=t.deref();return n&&n!==e}),s(t)}}t.exports={register:p,registerBeforeExit:m,unregister:h}})),js=n(((e,t)=>{t.exports={name:`thread-stream`,version:`4.0.0`,description:`A streaming way to send data to a Node.js Worker Thread`,main:`index.js`,types:`index.d.ts`,engines:{node:`>=20`},dependencies:{"real-require":`^0.2.0`},devDependencies:{"@types/node":`^22.0.0`,"@yao-pkg/pkg":`^6.0.0`,borp:`^0.21.0`,desm:`^1.3.0`,eslint:`^9.39.1`,fastbench:`^1.0.1`,husky:`^9.0.6`,neostandard:`^0.12.2`,"pino-elasticsearch":`^8.0.0`,"sonic-boom":`^4.0.1`,"ts-node":`^10.8.0`,typescript:`~5.7.3`},scripts:{build:`tsc --noEmit`,lint:`eslint`,test:`npm run lint && npm run build && npm run transpile && borp --pattern 'test/*.test.{js,mjs}'`,"test:ci":`npm run lint && npm run transpile && borp --pattern 'test/*.test.{js,mjs}'`,"test:yarn":`npm run transpile && borp --pattern 'test/*.test.js'`,transpile:`sh ./test/ts/transpile.sh`,prepare:`husky install`},repository:{type:`git`,url:`git+https://github.com/mcollina/thread-stream.git`},keywords:[`worker`,`thread`,`threads`,`stream`],author:`Matteo Collina <hello@matteocollina.com>`,license:`MIT`,bugs:{url:`https://github.com/mcollina/thread-stream/issues`},homepage:`https://github.com/mcollina/thread-stream#readme`}})),Ms=n(((e,t)=>{let n=1e4;function r(e,t,r,i,a){let o=i===1/0?1/0:Date.now()+i,s=()=>{let i=Atomics.load(e,t);if(i===r){a(null,`ok`);return}if(o!==1/0&&Date.now()>o){a(null,`timed-out`);return}let c=o===1/0?n:Math.min(n,Math.max(1,o-Date.now())),l=Atomics.waitAsync(e,t,i,c);l.async?l.value.then(s):setImmediate(s)};s()}function i(e,t,r,i,a){let o=i===1/0?1/0:Date.now()+i,s=()=>{if(Atomics.load(e,t)!==r){a(null,`ok`);return}if(o!==1/0&&Date.now()>o){a(null,`timed-out`);return}let i=o===1/0?n:Math.min(n,Math.max(1,o-Date.now())),c=Atomics.waitAsync(e,t,r,i);c.async?c.value.then(s):setImmediate(s)};s()}t.exports={wait:r,waitDiff:i}})),Ns=n(((e,t)=>{t.exports={WRITE_INDEX:4,READ_INDEX:8}})),Ps=n(((e,n)=>{let{version:r}=js(),{EventEmitter:i}=t(`events`),{Worker:a}=t(`worker_threads`),{join:o}=t(`path`),{pathToFileURL:s}=t(`url`),{wait:c}=Ms(),{WRITE_INDEX:l,READ_INDEX:u}=Ns(),d=t(`buffer`),f=t(`assert`),p=Symbol(`kImpl`),m=d.constants.MAX_STRING_LENGTH;var h=class{constructor(e){this._value=e}deref(){return this._value}},g=class{register(){}unregister(){}};let _=process.env.NODE_V8_COVERAGE?g:global.FinalizationRegistry||g,v=process.env.NODE_V8_COVERAGE?h:global.WeakRef||h,y=new _(e=>{e.exited||e.terminate()});function b(e,t){let{filename:n,workerData:i}=t,c=new a((`__bundlerPathsOverrides`in globalThis?globalThis.__bundlerPathsOverrides:{})[`thread-stream-worker`]||o(__dirname,`lib`,`worker.js`),{...t.workerOpts,trackUnmanagedFds:!1,workerData:{filename:n.indexOf(`file://`)===0?n:s(n).href,dataBuf:e[p].dataBuf,stateBuf:e[p].stateBuf,workerData:{$context:{threadStreamVersion:r},...i}}});return c.stream=new h(e),c.on(`message`,C),c.on(`exit`,w),y.register(e,c),c}function x(e){f(!e[p].sync),e[p].needDrain&&(e[p].needDrain=!1,e.emit(`drain`))}function S(e){let t=Atomics.load(e[p].state,l),n=e[p].data.length-t;if(n>0){if(e[p].buf.length===0){e[p].flushing=!1,e[p].ending?k(e):e[p].needDrain&&process.nextTick(x,e);return}let t=e[p].buf.slice(0,n),r=Buffer.byteLength(t);r<=n?(e[p].buf=e[p].buf.slice(n),O(e,t,S.bind(null,e))):e.flush(()=>{if(!e.destroyed){for(Atomics.store(e[p].state,u,0),Atomics.store(e[p].state,l,0),Atomics.notify(e[p].state,u);r>e[p].data.length;)n/=2,t=e[p].buf.slice(0,n),r=Buffer.byteLength(t);e[p].buf=e[p].buf.slice(n),O(e,t,S.bind(null,e))}})}else if(n===0){if(t===0&&e[p].buf.length===0)return;e.flush(()=>{Atomics.store(e[p].state,u,0),Atomics.store(e[p].state,l,0),Atomics.notify(e[p].state,u),S(e)})}else D(e,Error(`overwritten`))}function C(e){let t=this.stream.deref();if(t===void 0){this.exited=!0,this.terminate();return}switch(e.code){case`READY`:this.stream=new v(t),t.flush(()=>{t[p].ready=!0,t.emit(`ready`)});break;case`ERROR`:D(t,e.err);break;case`EVENT`:Array.isArray(e.args)?t.emit(e.name,...e.args):t.emit(e.name,e.args);break;case`WARNING`:process.emitWarning(e.err);break;default:D(t,Error(`this should not happen: `+e.code))}}function w(e){let t=this.stream.deref();t!==void 0&&(y.unregister(t),t.worker.exited=!0,t.worker.off(`exit`,w),D(t,e===0?null:Error(`the worker thread exited`)))}var T=class extends i{constructor(e={}){if(super(),e.bufferSize<4)throw Error(`bufferSize must at least fit a 4-byte utf-8 char`);this[p]={},this[p].stateBuf=new SharedArrayBuffer(128),this[p].state=new Int32Array(this[p].stateBuf),this[p].dataBuf=new SharedArrayBuffer(e.bufferSize||4*1024*1024),this[p].data=Buffer.from(this[p].dataBuf),this[p].sync=e.sync||!1,this[p].ending=!1,this[p].ended=!1,this[p].needDrain=!1,this[p].destroyed=!1,this[p].flushing=!1,this[p].ready=!1,this[p].finished=!1,this[p].errored=null,this[p].closed=!1,this[p].buf=``,this.worker=b(this,e),this.on(`message`,(e,t)=>{this.worker.postMessage(e,t)})}write(e){if(this[p].destroyed)return E(this,Error(`the worker has exited`)),!1;if(this[p].ending)return E(this,Error(`the worker is ending`)),!1;if(this[p].flushing&&this[p].buf.length+e.length>=m)try{A(this),this[p].flushing=!0}catch(e){return D(this,e),!1}if(this[p].buf+=e,this[p].sync)try{return A(this),!0}catch(e){return D(this,e),!1}return this[p].flushing||(this[p].flushing=!0,setImmediate(S,this)),this[p].needDrain=this[p].data.length-this[p].buf.length-Atomics.load(this[p].state,l)<=0,!this[p].needDrain}end(){this[p].destroyed||(this[p].ending=!0,k(this))}flush(e){if(this[p].destroyed){typeof e==`function`&&process.nextTick(e,Error(`the worker has exited`));return}let t=Atomics.load(this[p].state,l);c(this[p].state,u,t,1/0,(t,n)=>{if(t){D(this,t),process.nextTick(e,t);return}if(n===`not-equal`){this.flush(e);return}process.nextTick(e)})}flushSync(){this[p].destroyed||(A(this),j(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[p].ready}get destroyed(){return this[p].destroyed}get closed(){return this[p].closed}get writable(){return!this[p].destroyed&&!this[p].ending}get writableEnded(){return this[p].ending}get writableFinished(){return this[p].finished}get writableNeedDrain(){return this[p].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[p].errored}};function E(e,t){setImmediate(()=>{e.emit(`error`,t)})}function D(e,t){e[p].destroyed||(e[p].destroyed=!0,t&&(e[p].errored=t,E(e,t)),e.worker.exited?setImmediate(()=>{e[p].closed=!0,e.emit(`close`)}):e.worker.terminate().catch(()=>{}).then(()=>{e[p].closed=!0,e.emit(`close`)}))}function O(e,t,n){let r=Atomics.load(e[p].state,l),i=Buffer.byteLength(t);return e[p].data.write(t,r),Atomics.store(e[p].state,l,r+i),Atomics.notify(e[p].state,l),n(),!0}function k(e){if(!(e[p].ended||!e[p].ending||e[p].flushing)){e[p].ended=!0;try{e.flushSync();let t=Atomics.load(e[p].state,u);Atomics.store(e[p].state,l,-1),Atomics.notify(e[p].state,l);let n=0;for(;t!==-1;){if(Atomics.wait(e[p].state,u,t,1e3),t=Atomics.load(e[p].state,u),t===-2){D(e,Error(`end() failed`));return}if(++n===10){D(e,Error(`end() took too long (10s)`));return}}process.nextTick(()=>{e[p].finished=!0,e.emit(`finish`)})}catch(t){D(e,t)}}}function A(e){let t=()=>{e[p].ending?k(e):e[p].needDrain&&process.nextTick(x,e)};for(e[p].flushing=!1;e[p].buf.length!==0;){let n=Atomics.load(e[p].state,l),r=e[p].data.length-n;if(r===0){j(e),Atomics.store(e[p].state,u,0),Atomics.store(e[p].state,l,0),Atomics.notify(e[p].state,u);continue}else if(r<0)throw Error(`overwritten`);let i=e[p].buf.slice(0,r),a=Buffer.byteLength(i);if(a<=r)e[p].buf=e[p].buf.slice(r),O(e,i,t);else{for(j(e),Atomics.store(e[p].state,u,0),Atomics.store(e[p].state,l,0),Atomics.notify(e[p].state,u);a>e[p].buf.length;)r/=2,i=e[p].buf.slice(0,r),a=Buffer.byteLength(i);e[p].buf=e[p].buf.slice(r),O(e,i,t)}}}function j(e){if(e[p].flushing)throw Error(`unable to flush while flushing`);let t=Atomics.load(e[p].state,l),n=0;for(;;){let r=Atomics.load(e[p].state,u);if(r===-2)throw Error(`_flushSync failed`);if(r!==t)Atomics.wait(e[p].state,u,r,1e3);else break;if(++n===10)throw Error(`_flushSync took too long (10s)`)}}n.exports=T})),Fs=n(((e,n)=>{let{createRequire:r}=t(`module`),{existsSync:i}=t(`node:fs`),a=Ss(),{join:o,isAbsolute:s,sep:c}=t(`node:path`),{fileURLToPath:l}=t(`node:url`),u=Os(),d=As(),f=Ps();function p(e){d.register(e,y),d.registerBeforeExit(e,b),e.on(`close`,function(){d.unregister(e)})}function m(){let e=process.execArgv;for(let t=0;t<e.length;t++){let n=e[t];if(n===`--import`||n===`--require`||n===`-r`||n.startsWith(`--import=`)||n.startsWith(`--require=`)||n.startsWith(`-r=`))return!0}return!1}function h(e){let t=e.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);if(!t)return e;let n=[],r=!1;for(let e=0;e<t.length;e++){let i=t[e];if(i===`--require`||i===`-r`||i===`--import`){let a=t[e+1];if(a&&g(a)){r=!0,e++;continue}n.push(i),a&&(n.push(a),e++);continue}if((i.startsWith(`--require=`)||i.startsWith(`-r=`)||i.startsWith(`--import=`))&&g(i.slice(i.indexOf(`=`)+1))){r=!0;continue}n.push(i)}return r?n.join(` `):e}function g(e){let t=_(e);if(!t)return!1;let n=t;if(n.startsWith(`file://`))try{n=l(n)}catch{return!1}return s(n)&&!i(n)}function _(e){let t=e[0],n=e[e.length-1];return t===`"`&&n===`"`||t===`'`&&n===`'`?e.slice(1,-1):e}function v(e,n,r,i,a){if(!r.execArgv&&m()&&t.main===void 0&&(r={...r,execArgv:[]}),!r.env&&process.env.NODE_OPTIONS){let e=h(process.env.NODE_OPTIONS);e!==process.env.NODE_OPTIONS&&(r={...r,env:{...process.env,NODE_OPTIONS:e}})}r={...r,name:a};let o=new f({filename:e,workerData:n,workerOpts:r,sync:i});o.on(`ready`,s),o.on(`close`,function(){process.removeListener(`exit`,c)}),process.on(`exit`,c);function s(){process.removeListener(`exit`,c),o.unref(),r.autoEnd!==!1&&p(o)}function c(){o.closed||(o.flushSync(),u(100),o.end())}return o}function y(e){e.ref(),e.flushSync(),e.end(),e.once(`close`,function(){e.unref()})}function b(e){e.flushSync()}function x(e){let{pipeline:t,targets:n,levels:i,dedupe:l,worker:u={},caller:d=a(),sync:f=!1}=e,p={...e.options},m=typeof d==`string`?[d]:d,h=typeof globalThis==`object`&&Object.prototype.hasOwnProperty.call(globalThis,`__bundlerPathsOverrides`)&&globalThis.__bundlerPathsOverrides&&typeof globalThis.__bundlerPathsOverrides==`object`?globalThis.__bundlerPathsOverrides:Object.create(null),g=e.target;if(g&&n)throw Error(`only one of target or targets can be specified`);n?(g=h[`pino-worker`]||o(__dirname,`worker.js`),p.targets=n.filter(e=>e.target).map(e=>({...e,target:y(e.target)})),p.pipelines=n.filter(e=>e.pipeline).map(e=>e.pipeline.map(t=>({...t,level:e.level,target:y(t.target)})))):t&&(g=h[`pino-worker`]||o(__dirname,`worker.js`),p.pipelines=[t.map(e=>({...e,target:y(e.target)}))]),i&&(p.levels=i),l&&(p.dedupe=l),p.pinoWillSendConfig=!0;let _=n||t?`pino.transport`:g;return v(y(g),p,u,f,_);function y(e){if(e=h[e]||e,s(e)||e.indexOf(`file://`)===0)return e;if(e===`pino/file`)return o(__dirname,`..`,`file.js`);let t;for(let n of m)try{t=r(n===`node:repl`?process.cwd()+c:n).resolve(e);break}catch{continue}if(!t)throw Error(`unable to determine transport target for "${e}"`);return t}}n.exports=x})),Is=n(((e,n)=>{let r=t(`node:diagnostics_channel`),i=Ds(),{mapHttpRequest:a,mapHttpResponse:o}=xs(),s=ks(),c=As(),{lsCacheSym:l,chindingsSym:u,writeSym:d,serializersSym:f,formatOptsSym:p,endSym:m,stringifiersSym:h,stringifySym:g,stringifySafeSym:_,wildcardFirstSym:v,nestedKeySym:y,formattersSym:b,messageKeySym:x,errorKeySym:S,nestedKeyStrSym:C,msgPrefixSym:w}=ws(),{isMainThread:T}=t(`worker_threads`),E=Fs(),[D]=process.versions.node.split(`.`).map(e=>Number(e)),O=r.tracingChannel(`pino_asJson`),k=D>=25?e=>JSON.stringify(e):M;function A(){}function j(e,t){if(!t)return n;return function(...r){t.call(this,r,n,e)};function n(t,...n){if(typeof t==`object`){let r=t;t!==null&&(t.method&&t.headers&&t.socket?t=a(t):typeof t.setHeader==`function`&&(t=o(t)));let s;r===null&&n.length===0?s=[null]:(r=n.shift(),s=n),typeof this[w]==`string`&&r!=null&&(r=this[w]+r),this[d](t,i(r,s,this[p]),e)}else{let r=t===void 0?n.shift():t;typeof this[w]==`string`&&r!=null&&(r=this[w]+r),this[d](null,i(r,n,this[p]),e)}}}function M(e){let t=``,n=0,r=!1,i=255,a=e.length;if(a>100)return JSON.stringify(e);for(var o=0;o<a&&i>=32;o++)i=e.charCodeAt(o),(i===34||i===92)&&(t+=e.slice(n,o)+`\\`,n=o,r=!0);return r?t+=e.slice(n):t=e,i<32?JSON.stringify(e):`"`+t+`"`}function ee(e,t,n,r){if(O.hasSubscribers===!1)return N.call(this,e,t,n,r);let i={instance:this,arguments};return O.traceSync(N,i,this,e,t,n,r)}function N(e,t,n,r){let i=this[g],a=this[_],o=this[h],s=this[m],c=this[u],d=this[f],p=this[b],w=this[x],T=this[S],E=this[l][n]+r;E+=c;let D;p.log&&(e=p.log(e));let O=o[v],A=``;for(let t in e)if(D=e[t],Object.prototype.hasOwnProperty.call(e,t)&&D!==void 0){d[t]?D=d[t](D):t===T&&d.err&&(D=d.err(D));let e=o[t]||O;switch(typeof D){case`undefined`:case`function`:continue;case`number`:Number.isFinite(D)===!1&&(D=null);case`boolean`:e&&(D=e(D));break;case`string`:D=(e||k)(D);break;default:D=(e||i)(D,a)}if(D===void 0)continue;let n=k(t);A+=`,`+n+`:`+D}let j=``;if(t!==void 0){D=d[w]?d[w](t):t;let e=o[w]||O;switch(typeof D){case`function`:break;case`number`:Number.isFinite(D)===!1&&(D=null);case`boolean`:e&&(D=e(D)),j=`,"`+w+`":`+D;break;case`string`:D=(e||k)(D),j=`,"`+w+`":`+D;break;default:D=(e||i)(D,a),j=`,"`+w+`":`+D}}return this[y]&&A?E+this[C]+A.slice(1)+`}`+j+s:E+A+j+s}function te(e,t){let n,r=e[u],i=e[g],a=e[_],o=e[h],s=o[v],c=e[f],l=e[b].bindings;t=l(t);for(let e in t)if(n=t[e],((e.length<5||e!==`level`&&e!==`serializers`&&e!==`formatters`&&e!==`customLevels`)&&t.hasOwnProperty(e)&&n!==void 0)===!0){if(n=c[e]?c[e](n):n,n=(o[e]||s||i)(n,a),n===void 0)continue;r+=`,"`+e+`":`+n}return r}function ne(e){return e.write!==e.constructor.prototype.write}function P(e){let t=new s(e);return t.on(`error`,n),!e.sync&&T&&(c.register(t,re),t.on(`close`,function(){c.unregister(t)})),t;function n(e){if(e.code===`EPIPE`){t.write=A,t.end=A,t.flushSync=A,t.destroy=A;return}t.removeListener(`error`,n),t.emit(`error`,e)}}function re(e,t){e.destroyed||(t===`beforeExit`?(e.flush(),e.on(`drain`,function(){e.end()})):e.flushSync())}function F(e){return function(t,n,r={},i){if(typeof r==`string`)i=P({dest:r}),r={};else if(typeof i==`string`){if(r&&r.transport)throw Error(`only one of option.transport or stream can be specified`);i=P({dest:i})}else if(r instanceof s||r.writable||r._writableState)i=r,r={};else if(r.transport){if(r.transport instanceof s||r.transport.writable||r.transport._writableState)throw Error(`option.transport do not allow stream, please pass to option directly. e.g. pino(transport)`);if(r.transport.targets&&r.transport.targets.length&&r.formatters&&typeof r.formatters.level==`function`)throw Error(`option.transport.targets do not allow custom level formatters`);let e;r.customLevels&&(e=r.useOnlyCustomLevels?r.customLevels:Object.assign({},r.levels,r.customLevels)),i=E({caller:n,...r.transport,levels:e})}if(r=Object.assign({},e,r),r.serializers=Object.assign({},e.serializers,r.serializers),r.formatters=Object.assign({},e.formatters,r.formatters),r.prettyPrint)throw Error(`prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)`);let{enabled:a,onChild:o}=r;return a===!1&&(r.level=`silent`),o||(r.onChild=A),i||=ne(process.stdout)?process.stdout:P({fd:process.stdout.fd||1}),{opts:r,stream:i}}}function ie(e,t){try{return JSON.stringify(e)}catch{try{return(t||this[_])(e)}catch{return`"[unable to serialize, circular reference is too complex to analyze]"`}}}function ae(e,t,n){return{level:e,bindings:t,log:n}}function I(e){let t=Number(e);return typeof e==`string`&&Number.isFinite(t)?t:e===void 0?1:e}n.exports={noop:A,buildSafeSonicBoom:P,asChindings:te,asJson:ee,genLog:j,createArgsNormalizer:F,stringify:ie,buildFormatters:ae,normalizeDestFileDescriptor:I}})),Ls=n(((e,t)=>{t.exports={DEFAULT_LEVELS:{trace:10,debug:20,info:30,warn:40,error:50,fatal:60},SORTING_ORDER:{ASC:`ASC`,DESC:`DESC`}}})),Rs=n(((e,t)=>{let{lsCacheSym:n,levelValSym:r,useOnlyCustomLevelsSym:i,streamSym:a,formattersSym:o,hooksSym:s,levelCompSym:c}=ws(),{noop:l,genLog:u}=Is(),{DEFAULT_LEVELS:d,SORTING_ORDER:f}=Ls(),p={fatal:e=>{let t=u(d.fatal,e);return function(...e){let n=this[a];if(t.call(this,...e),typeof n.flushSync==`function`)try{n.flushSync()}catch{}}},error:e=>u(d.error,e),warn:e=>u(d.warn,e),info:e=>u(d.info,e),debug:e=>u(d.debug,e),trace:e=>u(d.trace,e)},m=Object.keys(d).reduce((e,t)=>(e[d[t]]=t,e),{}),h=Object.keys(m).reduce((e,t)=>(e[t]=`{"level":`+Number(t),e),{});function g(e){let t=e[o].level,{labels:r}=e.levels,i={};for(let e in r){let n=t(r[e],Number(e));i[e]=JSON.stringify(n).slice(0,-1)}return e[n]=i,e}function _(e,t){if(t)return!1;switch(e){case`fatal`:case`error`:case`warn`:case`info`:case`debug`:case`trace`:return!0;default:return!1}}function v(e){let{labels:t,values:n}=this.levels;if(typeof e==`number`){if(t[e]===void 0)throw Error(`unknown level value`+e);e=t[e]}if(n[e]===void 0)throw Error(`unknown level `+e);let a=this[r],o=this[r]=n[e],d=this[i],f=this[c],m=this[s].logMethod;for(let e in n){if(f(n[e],o)===!1){this[e]=l;continue}this[e]=_(e,d)?p[e](m):u(n[e],m)}this.emit(`level-change`,e,o,t[a],a,this)}function y(e){let{levels:t,levelVal:n}=this;return t&&t.labels?t.labels[n]:``}function b(e){let{values:t}=this.levels,n=t[e];return n!==void 0&&this[c](n,this[r])}function x(e,t,n){return e===f.DESC?t<=n:t>=n}function S(e){return typeof e==`string`?x.bind(null,e):e}function C(e=null,t=!1){let n=e?Object.keys(e).reduce((t,n)=>(t[e[n]]=n,t),{}):null;return{labels:Object.assign(Object.create(Object.prototype,{Infinity:{value:`silent`}}),t?null:m,n),values:Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),t?null:d,e)}}function w(e,t,n){if(typeof e==`number`){if(![].concat(Object.keys(t||{}).map(e=>t[e]),n?[]:Object.keys(m).map(e=>+e),1/0).includes(e))throw Error(`default level:${e} must be included in custom levels`);return}if(!(e in Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),n?null:d,t)))throw Error(`default level:${e} must be included in custom levels`)}function T(e,t){let{labels:n,values:r}=e;for(let e in t){if(e in r)throw Error(`levels cannot be overridden`);if(t[e]in n)throw Error(`pre-existing level values cannot be used for new levels`)}}function E(e){if(typeof e!=`function`&&!(typeof e==`string`&&Object.values(f).includes(e)))throw Error(`Levels comparison should be one of "ASC", "DESC" or "function" type`)}t.exports={initialLsCache:h,genLsCache:g,levelMethods:p,getLevel:y,setLevel:v,isLevelEnabled:b,mappings:C,assertNoLevelCollisions:T,assertDefaultLevelFound:w,genLevelComparison:S,assertLevelComparison:E}})),zs=n(((e,t)=>{t.exports={version:`10.3.1`}})),Bs=n(((e,n)=>{let{EventEmitter:r}=t(`node:events`),{lsCacheSym:i,levelValSym:a,setLevelSym:o,getLevelSym:s,chindingsSym:c,mixinSym:l,asJsonSym:u,writeSym:d,mixinMergeStrategySym:f,timeSym:p,timeSliceIndexSym:m,streamSym:h,serializersSym:g,formattersSym:_,errorKeySym:v,messageKeySym:y,useOnlyCustomLevelsSym:b,needsMetadataGsym:x,redactFmtSym:S,stringifySym:C,formatOptsSym:w,stringifiersSym:T,msgPrefixSym:E,hooksSym:D}=ws(),{getLevel:O,setLevel:k,isLevelEnabled:A,mappings:j,initialLsCache:M,genLsCache:ee,assertNoLevelCollisions:N}=Rs(),{asChindings:te,asJson:ne,buildFormatters:P,stringify:re,noop:F}=Is(),{version:ie}=zs(),ae=Ts(),I={constructor:class{},child:se,bindings:L,setBindings:ce,flush:R,isLevelEnabled:A,version:ie,get level(){return this[s]()},set level(e){this[o](e)},get levelVal(){return this[a]},set levelVal(e){throw Error(`levelVal is read-only`)},get msgPrefix(){return this[E]},get[Symbol.toStringTag](){return`Pino`},[i]:M,[d]:ue,[u]:ne,[s]:O,[o]:k};Object.setPrototypeOf(I,r.prototype),n.exports=function(){return Object.create(I)};let oe=e=>e;function se(e,t){if(!e)throw Error(`missing bindings for child Pino`);let n=this[g],r=this[_],i=Object.create(this);if(t==null)return i[_].bindings!==oe&&(i[_]=P(r.level,oe,r.log)),i[c]=te(i,e),this.onChild!==F&&this.onChild(i),i;if(t.hasOwnProperty(`serializers`)===!0){i[g]=Object.create(null);for(let e in n)i[g][e]=n[e];let e=Object.getOwnPropertySymbols(n);for(var a=0;a<e.length;a++){let t=e[a];i[g][t]=n[t]}for(let e in t.serializers)i[g][e]=t.serializers[e];let r=Object.getOwnPropertySymbols(t.serializers);for(var s=0;s<r.length;s++){let e=r[s];i[g][e]=t.serializers[e]}}else i[g]=n;if(t.hasOwnProperty(`formatters`)){let{level:e,bindings:n,log:a}=t.formatters;i[_]=P(e||r.level,n||oe,a||r.log)}else i[_]=P(r.level,oe,r.log);if(t.hasOwnProperty(`customLevels`)===!0&&(N(this.levels,t.customLevels),i.levels=j(t.customLevels,i[b]),ee(i)),typeof t.redact==`object`&&t.redact!==null||Array.isArray(t.redact)){i.redact=t.redact;let e=ae(i.redact,re),n={stringify:e[S]};i[C]=re,i[T]=e,i[w]=n}if(typeof t.msgPrefix==`string`&&(i[E]=(this[E]||``)+t.msgPrefix),i[c]=te(i,e),t.level!==void 0&&t.level!==this.level||t.hasOwnProperty(`customLevels`)){let e=t.level||this.level;i[o](e)}return this.onChild(i),i}function L(){let e=`{${this[c].substr(1)}}`,t=JSON.parse(e);return delete t.pid,delete t.hostname,t}function ce(e){this[c]=te(this,e)}function le(e,t){return Object.assign(t,e)}function ue(e,t,n){let r=this[p](),i=this[l],a=this[v],o=this[y],s=this[f]||le,c,d=this[D].streamWrite;e==null?c={}:e instanceof Error?(c={[a]:e},t===void 0&&(t=e.message)):(c=e,t===void 0&&e[o]===void 0&&e[a]&&(t=e[a].message)),i&&(c=s(c,i(c,n,this)));let g=this[u](c,t,n,r),_=this[h];_[x]===!0&&(_.lastLevel=n,_.lastObj=c,_.lastMsg=t,_.lastTime=r.slice(this[m]),_.lastLogger=this),_.write(d?d(g):g)}function R(e){if(e!=null&&typeof e!=`function`)throw Error(`callback must be a function`);let t=this[h];typeof t.flush==`function`?t.flush(e||F):e&&e()}})),Vs=n(((e,t)=>{let{hasOwnProperty:n}=Object.prototype,r=_();r.configure=_,r.stringify=r,r.default=r,e.stringify=r,e.configure=_,t.exports=r;let i=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function a(e){return e.length<5e3&&!i.test(e)?`"${e}"`:JSON.stringify(e)}function o(e,t){if(e.length>200||t)return e.sort(t);for(let t=1;t<e.length;t++){let n=e[t],r=t;for(;r!==0&&e[r-1]>n;)e[r]=e[r-1],r--;e[r]=n}return e}let s=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function c(e){return s.call(e)!==void 0&&e.length!==0}function l(e,t,n){e.length<n&&(n=e.length);let r=t===`,`?``:` `,i=`"0":${r}${e[0]}`;for(let a=1;a<n;a++)i+=`${t}"${a}":${r}${e[a]}`;return i}function u(e){if(n.call(e,`circularValue`)){let t=e.circularValue;if(typeof t==`string`)return`"${t}"`;if(t==null)return t;if(t===Error||t===TypeError)return{toString(){throw TypeError(`Converting circular structure to JSON`)}};throw TypeError(`The "circularValue" argument must be of type string or the value null or undefined`)}return`"[Circular]"`}function d(e){let t;if(n.call(e,`deterministic`)&&(t=e.deterministic,typeof t!=`boolean`&&typeof t!=`function`))throw TypeError(`The "deterministic" argument must be of type boolean or comparator function`);return t===void 0?!0:t}function f(e,t){let r;if(n.call(e,t)&&(r=e[t],typeof r!=`boolean`))throw TypeError(`The "${t}" argument must be of type boolean`);return r===void 0?!0:r}function p(e,t){let r;if(n.call(e,t)){if(r=e[t],typeof r!=`number`)throw TypeError(`The "${t}" argument must be of type number`);if(!Number.isInteger(r))throw TypeError(`The "${t}" argument must be an integer`);if(r<1)throw RangeError(`The "${t}" argument must be >= 1`)}return r===void 0?1/0:r}function m(e){return e===1?`1 item`:`${e} items`}function h(e){let t=new Set;for(let n of e)(typeof n==`string`||typeof n==`number`)&&t.add(String(n));return t}function g(e){if(n.call(e,`strict`)){let t=e.strict;if(typeof t!=`boolean`)throw TypeError(`The "strict" argument must be of type boolean`);if(t)return e=>{let t=`Object can not safely be stringified. Received type ${typeof e}`;throw typeof e!=`function`&&(t+=` (${e.toString()})`),Error(t)}}}function _(e){e={...e};let t=g(e);t&&(e.bigint===void 0&&(e.bigint=!1),`circularValue`in e||(e.circularValue=Error));let n=u(e),r=f(e,`bigint`),i=d(e),s=typeof i==`function`?i:void 0,_=p(e,`maximumDepth`),v=p(e,`maximumBreadth`);function y(e,l,u,d,f,p){let h=l[e];switch(typeof h==`object`&&h&&typeof h.toJSON==`function`&&(h=h.toJSON(e)),h=d.call(l,e,h),typeof h){case`string`:return a(h);case`object`:{if(h===null)return`null`;if(u.indexOf(h)!==-1)return n;let e=``,t=`,`,r=p;if(Array.isArray(h)){if(h.length===0)return`[]`;if(_<u.length+1)return`"[Array]"`;u.push(h),f!==``&&(p+=f,e+=`\n${p}`,t=`,\n${p}`);let n=Math.min(h.length,v),i=0;for(;i<n-1;i++){let n=y(String(i),h,u,d,f,p);e+=n===void 0?`null`:n,e+=t}let a=y(String(i),h,u,d,f,p);if(e+=a===void 0?`null`:a,h.length-1>v){let n=h.length-v-1;e+=`${t}"... ${m(n)} not stringified"`}return f!==``&&(e+=`\n${r}`),u.pop(),`[${e}]`}let l=Object.keys(h),g=l.length;if(g===0)return`{}`;if(_<u.length+1)return`"[Object]"`;let b=``,x=``;f!==``&&(p+=f,t=`,\n${p}`,b=` `);let S=Math.min(g,v);i&&!c(h)&&(l=o(l,s)),u.push(h);for(let n=0;n<S;n++){let r=l[n],i=y(r,h,u,d,f,p);i!==void 0&&(e+=`${x}${a(r)}:${b}${i}`,x=t)}if(g>v){let n=g-v;e+=`${x}"...":${b}"${m(n)} not stringified"`,x=t}return f!==``&&x.length>1&&(e=`\n${p}${e}\n${r}`),u.pop(),`{${e}}`}case`number`:return isFinite(h)?String(h):t?t(h):`null`;case`boolean`:return h===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(h);default:return t?t(h):void 0}}function b(e,i,o,s,c,l){switch(typeof i==`object`&&i&&typeof i.toJSON==`function`&&(i=i.toJSON(e)),typeof i){case`string`:return a(i);case`object`:{if(i===null)return`null`;if(o.indexOf(i)!==-1)return n;let e=l,t=``,r=`,`;if(Array.isArray(i)){if(i.length===0)return`[]`;if(_<o.length+1)return`"[Array]"`;o.push(i),c!==``&&(l+=c,t+=`\n${l}`,r=`,\n${l}`);let n=Math.min(i.length,v),a=0;for(;a<n-1;a++){let e=b(String(a),i[a],o,s,c,l);t+=e===void 0?`null`:e,t+=r}let u=b(String(a),i[a],o,s,c,l);if(t+=u===void 0?`null`:u,i.length-1>v){let e=i.length-v-1;t+=`${r}"... ${m(e)} not stringified"`}return c!==``&&(t+=`\n${e}`),o.pop(),`[${t}]`}o.push(i);let u=``;c!==``&&(l+=c,r=`,\n${l}`,u=` `);let d=``;for(let e of s){let n=b(e,i[e],o,s,c,l);n!==void 0&&(t+=`${d}${a(e)}:${u}${n}`,d=r)}return c!==``&&d.length>1&&(t=`\n${l}${t}\n${e}`),o.pop(),`{${t}}`}case`number`:return isFinite(i)?String(i):t?t(i):`null`;case`boolean`:return i===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(i);default:return t?t(i):void 0}}function x(e,u,d,f,p){switch(typeof u){case`string`:return a(u);case`object`:{if(u===null)return`null`;if(typeof u.toJSON==`function`){if(u=u.toJSON(e),typeof u!=`object`)return x(e,u,d,f,p);if(u===null)return`null`}if(d.indexOf(u)!==-1)return n;let t=p;if(Array.isArray(u)){if(u.length===0)return`[]`;if(_<d.length+1)return`"[Array]"`;d.push(u),p+=f;let e=`\n${p}`,n=`,\n${p}`,r=Math.min(u.length,v),i=0;for(;i<r-1;i++){let t=x(String(i),u[i],d,f,p);e+=t===void 0?`null`:t,e+=n}let a=x(String(i),u[i],d,f,p);if(e+=a===void 0?`null`:a,u.length-1>v){let t=u.length-v-1;e+=`${n}"... ${m(t)} not stringified"`}return e+=`\n${t}`,d.pop(),`[${e}]`}let r=Object.keys(u),h=r.length;if(h===0)return`{}`;if(_<d.length+1)return`"[Object]"`;p+=f;let g=`,\n${p}`,y=``,b=``,S=Math.min(h,v);c(u)&&(y+=l(u,g,v),r=r.slice(u.length),S-=u.length,b=g),i&&(r=o(r,s)),d.push(u);for(let e=0;e<S;e++){let t=r[e],n=x(t,u[t],d,f,p);n!==void 0&&(y+=`${b}${a(t)}: ${n}`,b=g)}if(h>v){let e=h-v;y+=`${b}"...": "${m(e)} not stringified"`,b=g}return b!==``&&(y=`\n${p}${y}\n${t}`),d.pop(),`{${y}}`}case`number`:return isFinite(u)?String(u):t?t(u):`null`;case`boolean`:return u===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(u);default:return t?t(u):void 0}}function S(e,u,d){switch(typeof u){case`string`:return a(u);case`object`:{if(u===null)return`null`;if(typeof u.toJSON==`function`){if(u=u.toJSON(e),typeof u!=`object`)return S(e,u,d);if(u===null)return`null`}if(d.indexOf(u)!==-1)return n;let t=``,r=u.length!==void 0;if(r&&Array.isArray(u)){if(u.length===0)return`[]`;if(_<d.length+1)return`"[Array]"`;d.push(u);let e=Math.min(u.length,v),n=0;for(;n<e-1;n++){let e=S(String(n),u[n],d);t+=e===void 0?`null`:e,t+=`,`}let r=S(String(n),u[n],d);if(t+=r===void 0?`null`:r,u.length-1>v){let e=u.length-v-1;t+=`,"... ${m(e)} not stringified"`}return d.pop(),`[${t}]`}let f=Object.keys(u),p=f.length;if(p===0)return`{}`;if(_<d.length+1)return`"[Object]"`;let h=``,g=Math.min(p,v);r&&c(u)&&(t+=l(u,`,`,v),f=f.slice(u.length),g-=u.length,h=`,`),i&&(f=o(f,s)),d.push(u);for(let e=0;e<g;e++){let n=f[e],r=S(n,u[n],d);r!==void 0&&(t+=`${h}${a(n)}:${r}`,h=`,`)}if(p>v){let e=p-v;t+=`${h}"...":"${m(e)} not stringified"`}return d.pop(),`{${t}}`}case`number`:return isFinite(u)?String(u):t?t(u):`null`;case`boolean`:return u===!0?`true`:`false`;case`undefined`:return;case`bigint`:if(r)return String(u);default:return t?t(u):void 0}}function C(e,t,n){if(arguments.length>1){let r=``;if(typeof n==`number`?r=` `.repeat(Math.min(n,10)):typeof n==`string`&&(r=n.slice(0,10)),t!=null){if(typeof t==`function`)return y(``,{"":e},[],t,r,``);if(Array.isArray(t))return b(``,e,[],h(t),r,``)}if(r.length!==0)return x(``,e,[],r,``)}return S(``,e,[])}return C}})),Hs=n(((e,t)=>{let n=Symbol.for(`pino.metadata`),{DEFAULT_LEVELS:r}=Ls(),i=r.info;function a(e,t){e||=[],t||={dedupe:!1};let a=Object.create(r);a.silent=1/0,t.levels&&typeof t.levels==`object`&&Object.keys(t.levels).forEach(e=>{a[e]=t.levels[e]});let u={write:d,add:m,remove:h,emit:f,flushSync:p,end:g,minLevel:0,lastId:0,streams:[],clone:_,[n]:!0,streamLevels:a};return Array.isArray(e)?e.forEach(m,u):m.call(u,e),e=null,u;function d(e){let r,i=this.lastLevel,{streams:a}=this,o=0,u;for(let d=s(a.length,t.dedupe);l(d,a.length,t.dedupe);d=c(d,t.dedupe))if(r=a[d],r.level<=i){if(o!==0&&o!==r.level)break;if(u=r.stream,u[n]){let{lastTime:e,lastMsg:t,lastObj:n,lastLogger:r}=this;u.lastLevel=i,u.lastTime=e,u.lastMsg=t,u.lastObj=n,u.lastLogger=r}u.write(e),t.dedupe&&(o=r.level)}else if(!t.dedupe)break}function f(...e){for(let{stream:t}of this.streams)typeof t.emit==`function`&&t.emit(...e)}function p(){for(let{stream:e}of this.streams)typeof e.flushSync==`function`&&e.flushSync()}function m(e){if(!e)return u;let t=typeof e.write==`function`||e.stream,n=e.write?e:e.stream;if(!t)throw Error(`stream object needs to implement either StreamEntry or DestinationStream interface`);let{streams:r,streamLevels:a}=this,s;s=typeof e.levelVal==`number`?e.levelVal:typeof e.level==`string`?a[e.level]:typeof e.level==`number`?e.level:i;let c={stream:n,level:s,levelVal:void 0,id:++u.lastId};return r.unshift(c),r.sort(o),this.minLevel=r[0].level,u}function h(e){let{streams:t}=this,n=t.findIndex(t=>t.id===e);return n>=0&&(t.splice(n,1),t.sort(o),this.minLevel=t.length>0?t[0].level:-1),u}function g(){for(let{stream:e}of this.streams)typeof e.flushSync==`function`&&e.flushSync(),e.end()}function _(e){let t=Array(this.streams.length);for(let n=0;n<t.length;n++)t[n]={level:e,stream:this.streams[n].stream};return{write:d,add:m,remove:h,minLevel:e,streams:t,clone:_,emit:f,flushSync:p,[n]:!0}}}function o(e,t){return e.level-t.level}function s(e,t){return t?e-1:0}function c(e,t){return t?e-1:e+1}function l(e,t,n){return n?e>=0:e<t}t.exports=a})),Us=n(((e,n)=>{let r=t(`node:os`),i=xs(),a=Ss(),o=Ts(),s=Es(),c=Bs(),l=ws(),{configure:u}=Vs(),{assertDefaultLevelFound:d,mappings:f,genLsCache:p,genLevelComparison:m,assertLevelComparison:h}=Rs(),{DEFAULT_LEVELS:g,SORTING_ORDER:_}=Ls(),{createArgsNormalizer:v,asChindings:y,buildSafeSonicBoom:b,buildFormatters:x,stringify:S,normalizeDestFileDescriptor:C,noop:w}=Is(),{version:T}=zs(),{chindingsSym:E,redactFmtSym:D,serializersSym:O,timeSym:k,timeSliceIndexSym:A,streamSym:j,stringifySym:M,stringifySafeSym:ee,stringifiersSym:N,setLevelSym:te,endSym:ne,formatOptsSym:P,messageKeySym:re,errorKeySym:F,nestedKeySym:ie,mixinSym:ae,levelCompSym:I,useOnlyCustomLevelsSym:oe,formattersSym:se,hooksSym:L,nestedKeyStrSym:ce,mixinMergeStrategySym:le,msgPrefixSym:ue}=l,{epochTime:R,nullTime:de}=s,{pid:fe}=process,pe=r.hostname(),me=i.err,he=v({level:`info`,levelComparison:_.ASC,levels:g,messageKey:`msg`,errorKey:`err`,nestedKey:null,enabled:!0,base:{pid:fe,hostname:pe},serializers:Object.assign(Object.create(null),{err:me}),formatters:Object.assign(Object.create(null),{bindings(e){return e},level(e,t){return{level:t}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:R,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100}),ge=Object.assign(Object.create(null),i);function z(...e){let t={},{opts:n,stream:r}=he(t,a(),...e);n.level&&typeof n.level==`string`&&g[n.level.toLowerCase()]!==void 0&&(n.level=n.level.toLowerCase());let{redact:i,crlf:s,serializers:l,timestamp:_,messageKey:v,errorKey:b,nestedKey:C,base:T,name:fe,level:pe,customLevels:me,levelComparison:ge,mixin:z,mixinMergeStrategy:_e,useOnlyCustomLevels:ve,formatters:ye,hooks:be,depthLimit:xe,edgeLimit:Se,onChild:Ce,msgPrefix:we}=n,B=u({maximumDepth:xe,maximumBreadth:Se}),V=x(ye.level,ye.bindings,ye.log),Te=S.bind({[ee]:B}),Ee=i?o(i,Te):{},De=i?{stringify:Ee[D]}:{stringify:Te},Oe=`}`+(s?`\r
6
6
  `:`
7
- `),ke=y.bind(null,{[E]:``,[O]:l,[N]:Ee,[M]:S,[ee]:B,[se]:V}),Ae=``;T!==null&&(Ae=ke(fe===void 0?T:Object.assign({},T,{name:fe})));let je=_ instanceof Function?_:_?R:de,Me=je().indexOf(`:`)+1;if(ve&&!me)throw Error(`customLevels is required if useOnlyCustomLevels is set true`);if(z&&typeof z!=`function`)throw Error(`Unknown mixin type "${typeof z}" - expected "function"`);if(we&&typeof we!=`string`)throw Error(`Unknown msgPrefix type "${typeof we}" - expected "string"`);d(pe,me,ve);let Ne=f(me,ve);typeof r.emit==`function`&&r.emit(`message`,{code:`PINO_CONFIG`,config:{levels:Ne,messageKey:v,errorKey:b}}),h(ge);let Pe=m(ge);return Object.assign(t,{levels:Ne,[I]:Pe,[oe]:ve,[j]:r,[k]:je,[A]:Me,[M]:S,[ee]:B,[N]:Ee,[ne]:Oe,[P]:De,[re]:v,[F]:b,[ie]:C,[ce]:C?`,${JSON.stringify(C)}:{`:``,[O]:l,[ae]:z,[le]:_e,[E]:Ae,[se]:V,[L]:be,silent:w,onChild:Ce,[ue]:we}),Object.setPrototypeOf(t,c()),p(t),t[te](pe),t}n.exports=z,n.exports.destination=(e=process.stdout.fd)=>typeof e==`object`?(e.dest=C(e.dest||process.stdout.fd),b(e)):b({dest:C(e),minLength:0}),n.exports.transport=Ns(),n.exports.multistream=Bs(),n.exports.levels=f(),n.exports.stdSerializers=ge,n.exports.stdTimeFunctions=Object.assign({},s),n.exports.symbols=l,n.exports.version=T,n.exports.default=z,n.exports.pino=z})),Hs=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});var n=t(`tty`);function r(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if(n!==`default`){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var i=r(n);let{env:a={},argv:o=[],platform:s=``}=typeof process>`u`?{}:process,c=`NO_COLOR`in a||o.includes(`--no-color`),l=`FORCE_COLOR`in a||o.includes(`--color`),u=s===`win32`,d=a.TERM===`dumb`,f=i&&i.isatty&&i.isatty(1)&&a.TERM&&!d,p=`CI`in a&&(`GITHUB_ACTIONS`in a||`GITLAB_CI`in a||`CIRCLECI`in a),m=!c&&(l||u&&!d||f||p),h=(e,t,n,r,i=t.substring(0,e)+r,a=t.substring(e+n.length),o=a.indexOf(n))=>i+(o<0?a:h(o,a,n,r)),g=(e,t,n,r,i)=>e<0?n+t+r:n+h(e,t,r,i)+r,_=(e,t,n=e,r=e.length+1)=>i=>i||!(i===``||i===void 0)?g((``+i).indexOf(t,r),i,e,t,n):``,v=(e,t,n)=>_(`\x1b[${e}m`,`\x1b[${t}m`,n),y={reset:v(0,0),bold:v(1,22,`\x1B[22m\x1B[1m`),dim:v(2,22,`\x1B[22m\x1B[2m`),italic:v(3,23),underline:v(4,24),inverse:v(7,27),hidden:v(8,28),strikethrough:v(9,29),black:v(30,39),red:v(31,39),green:v(32,39),yellow:v(33,39),blue:v(34,39),magenta:v(35,39),cyan:v(36,39),white:v(37,39),gray:v(90,39),bgBlack:v(40,49),bgRed:v(41,49),bgGreen:v(42,49),bgYellow:v(43,49),bgBlue:v(44,49),bgMagenta:v(45,49),bgCyan:v(46,49),bgWhite:v(47,49),blackBright:v(90,39),redBright:v(91,39),greenBright:v(92,39),yellowBright:v(93,39),blueBright:v(94,39),magentaBright:v(95,39),cyanBright:v(96,39),whiteBright:v(97,39),bgBlackBright:v(100,49),bgRedBright:v(101,49),bgGreenBright:v(102,49),bgYellowBright:v(103,49),bgBlueBright:v(104,49),bgMagentaBright:v(105,49),bgCyanBright:v(106,49),bgWhiteBright:v(107,49)},b=({useColor:e=m}={})=>e?y:Object.keys(y).reduce((e,t)=>({...e,[t]:String}),{}),{reset:x,bold:S,dim:C,italic:w,underline:T,inverse:E,hidden:D,strikethrough:O,black:k,red:A,green:j,yellow:M,blue:ee,magenta:N,cyan:te,white:ne,gray:P,bgBlack:re,bgRed:F,bgGreen:ie,bgYellow:ae,bgBlue:I,bgMagenta:oe,bgCyan:se,bgWhite:L,blackBright:ce,redBright:le,greenBright:ue,yellowBright:R,blueBright:de,magentaBright:fe,cyanBright:pe,whiteBright:me,bgBlackBright:he,bgRedBright:ge,bgGreenBright:z,bgYellowBright:_e,bgBlueBright:ve,bgMagentaBright:ye,bgCyanBright:be,bgWhiteBright:xe}=b();e.bgBlack=re,e.bgBlackBright=he,e.bgBlue=I,e.bgBlueBright=ve,e.bgCyan=se,e.bgCyanBright=be,e.bgGreen=ie,e.bgGreenBright=z,e.bgMagenta=oe,e.bgMagentaBright=ye,e.bgRed=F,e.bgRedBright=ge,e.bgWhite=L,e.bgWhiteBright=xe,e.bgYellow=ae,e.bgYellowBright=_e,e.black=k,e.blackBright=ce,e.blue=ee,e.blueBright=de,e.bold=S,e.createColors=b,e.cyan=te,e.cyanBright=pe,e.dim=C,e.gray=P,e.green=j,e.greenBright=ue,e.hidden=D,e.inverse=E,e.isColorSupported=m,e.italic=w,e.magenta=N,e.magentaBright=fe,e.red=A,e.redBright=le,e.reset=x,e.strikethrough=O,e.underline=T,e.white=ne,e.whiteBright=me,e.yellow=M,e.yellowBright=R})),Us=n(((e,t)=>{t.exports=n;function n(e,t){if(e&&t)return n(e)(t);if(typeof e!=`function`)throw TypeError(`need wrapper function`);return Object.keys(e).forEach(function(t){r[t]=e[t]}),r;function r(){for(var t=Array(arguments.length),n=0;n<t.length;n++)t[n]=arguments[n];var r=e.apply(this,t),i=t[t.length-1];return typeof r==`function`&&r!==i&&Object.keys(i).forEach(function(e){r[e]=i[e]}),r}}})),Ws=n(((e,t)=>{var n=Us();t.exports=n(r),t.exports.strict=n(i),r.proto=r(function(){Object.defineProperty(Function.prototype,`once`,{value:function(){return r(this)},configurable:!0}),Object.defineProperty(Function.prototype,`onceStrict`,{value:function(){return i(this)},configurable:!0})});function r(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function i(e){var t=function(){if(t.called)throw Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)};return t.onceError=(e.name||"Function wrapped with `once`")+` shouldn't be called more than once`,t.called=!1,t}})),Gs=n(((e,t)=>{var n=Ws(),r=function(){},i=global.Bare?queueMicrotask:process.nextTick.bind(process),a=function(e){return e.setHeader&&typeof e.abort==`function`},o=function(e){return e.stdio&&Array.isArray(e.stdio)&&e.stdio.length===3},s=function(e,t,c){if(typeof t==`function`)return s(e,null,t);t||={},c=n(c||r);var l=e._writableState,u=e._readableState,d=t.readable||t.readable!==!1&&e.readable,f=t.writable||t.writable!==!1&&e.writable,p=!1,m=function(){e.writable||h()},h=function(){f=!1,d||c.call(e)},g=function(){d=!1,f||c.call(e)},_=function(t){c.call(e,t?Error(`exited with error code: `+t):null)},v=function(t){c.call(e,t)},y=function(){i(b)},b=function(){if(!p&&(d&&!(u&&u.ended&&!u.destroyed)||f&&!(l&&l.ended&&!l.destroyed)))return c.call(e,Error(`premature close`))},x=function(){e.req.on(`finish`,h)};return a(e)?(e.on(`complete`,h),e.on(`abort`,y),e.req?x():e.on(`request`,x)):f&&!l&&(e.on(`end`,m),e.on(`close`,m)),o(e)&&e.on(`exit`,_),e.on(`end`,g),e.on(`finish`,h),t.error!==!1&&e.on(`error`,v),e.on(`close`,y),function(){p=!0,e.removeListener(`complete`,h),e.removeListener(`abort`,y),e.removeListener(`request`,x),e.req&&e.req.removeListener(`finish`,h),e.removeListener(`end`,m),e.removeListener(`close`,m),e.removeListener(`finish`,h),e.removeListener(`exit`,_),e.removeListener(`end`,g),e.removeListener(`error`,v),e.removeListener(`close`,y)}};t.exports=s})),Ks=n(((e,n)=>{var r=Ws(),i=Gs(),a;try{a=t(`fs`)}catch{}var o=function(){},s=typeof process>`u`?!1:/^v?\.0/.test(process.version),c=function(e){return typeof e==`function`},l=function(e){return!s||!a?!1:(e instanceof(a.ReadStream||o)||e instanceof(a.WriteStream||o))&&c(e.close)},u=function(e){return e.setHeader&&c(e.abort)},d=function(e,t,n,a){a=r(a);var s=!1;e.on(`close`,function(){s=!0}),i(e,{readable:t,writable:n},function(e){if(e)return a(e);s=!0,a()});var d=!1;return function(t){if(!s&&!d){if(d=!0,l(e))return e.close(o);if(u(e))return e.abort();if(c(e.destroy))return e.destroy();a(t||Error(`stream was destroyed`))}}},f=function(e){e()},p=function(e,t){return e.pipe(t)};n.exports=function(){var e=Array.prototype.slice.call(arguments),t=c(e[e.length-1]||o)&&e.pop()||o;if(Array.isArray(e[0])&&(e=e[0]),e.length<2)throw Error(`pump requires two streams per minimum`);var n,r=e.map(function(i,a){var o=a<e.length-1;return d(i,o,a>0,function(e){n||=e,e&&r.forEach(f),!o&&(r.forEach(f),t(n))})});return e.reduce(p)}})),qs=n(((e,n)=>{let{Transform:r}=t(`stream`),{StringDecoder:i}=t(`string_decoder`),a=Symbol(`last`),o=Symbol(`decoder`);function s(e,t,n){let r;if(this.overflow){if(r=this[o].write(e).split(this.matcher),r.length===1)return n();r.shift(),this.overflow=!1}else this[a]+=this[o].write(e),r=this[a].split(this.matcher);this[a]=r.pop();for(let e=0;e<r.length;e++)try{l(this,this.mapper(r[e]))}catch(e){return n(e)}if(this.overflow=this[a].length>this.maxLength,this.overflow&&!this.skipOverflow){n(Error(`maximum buffer reached`));return}n()}function c(e){if(this[a]+=this[o].end(),this[a])try{l(this,this.mapper(this[a]))}catch(t){return e(t)}e()}function l(e,t){t!==void 0&&e.push(t)}function u(e){return e}function d(e,t,n){switch(e||=/\r?\n/,t||=u,n||={},arguments.length){case 1:typeof e==`function`?(t=e,e=/\r?\n/):typeof e==`object`&&!(e instanceof RegExp)&&!e[Symbol.split]&&(n=e,e=/\r?\n/);break;case 2:typeof e==`function`?(n=t,t=e,e=/\r?\n/):typeof t==`object`&&(n=t,t=u)}n=Object.assign({},n),n.autoDestroy=!0,n.transform=s,n.flush=c,n.readableObjectMode=!0;let l=new r(n);return l[a]=``,l[o]=new i(`utf8`),l.matcher=e,l.mapper=t,l.maxLength=n.maxLength,l.skipOverflow=n.skipOverflow||!1,l.overflow=!1,l._destroy=function(e,t){this._writableState.errorEmitted=!1,t(e)},l}n.exports=d})),Js=n(((e,n)=>{let r=Symbol.for(`pino.metadata`),i=qs(),{Duplex:a}=t(`stream`),{parentPort:o,workerData:s}=t(`worker_threads`);function c(){let e,t,n=new Promise((n,r)=>{e=n,t=r});return n.resolve=e,n.reject=t,n}n.exports=function(e,t={}){let n=t.expectPinoConfig===!0&&s?.workerData?.pinoWillSendConfig===!0,u=t.parse===`lines`,d=typeof t.parseLine==`function`?t.parseLine:JSON.parse,f=t.close||l,p=i(function(e){let t;try{t=d(e)}catch(t){this.emit(`unknown`,e,t);return}if(t===null){this.emit(`unknown`,e,`Null value ignored`);return}return typeof t!=`object`&&(t={data:t,time:Date.now()}),p[r]&&(p.lastTime=t.time,p.lastLevel=t.level,p.lastObj=t),u?e:t},{autoDestroy:!0});if(p._destroy=function(e,t){let n=f(e,t);n&&typeof n.then==`function`&&n.then(t,t)},t.expectPinoConfig===!0&&s?.workerData?.pinoWillSendConfig!==!0&&setImmediate(()=>{p.emit(`error`,Error(`This transport is not compatible with the current version of pino. Please upgrade pino to the latest version.`))}),t.metadata!==!1&&(p[r]=!0,p.lastTime=0,p.lastLevel=0,p.lastObj=null),n){let e={},t=c();return o.on(`message`,function n(r){r.code===`PINO_CONFIG`&&(e=r.config,t.resolve(),o.off(`message`,n))}),Object.defineProperties(p,{levels:{get(){return e.levels}},messageKey:{get(){return e.messageKey}},errorKey:{get(){return e.errorKey}}}),t.then(m)}return m();function m(){let n=e(p);if(n&&typeof n.catch==`function`)n.catch(e=>{p.destroy(e)}),n=null;else if(t.enablePipelining&&n)return a.from({writable:p,readable:n});return p}};function l(e,t){process.nextTick(t,e)}})),Ys=n(((e,t)=>{t.exports={DATE_FORMAT:`yyyy-mm-dd HH:MM:ss.l o`,DATE_FORMAT_SIMPLE:`HH:MM:ss.l`,ERROR_LIKE_KEYS:[`err`,`error`],MESSAGE_KEY:`msg`,LEVEL_KEY:`level`,LEVEL_LABEL:`levelLabel`,TIMESTAMP_KEY:`time`,LEVELS:{default:`USERLVL`,60:`FATAL`,50:`ERROR`,40:`WARN`,30:`INFO`,20:`DEBUG`,10:`TRACE`},LEVEL_NAMES:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},LOGGER_KEYS:[`pid`,`hostname`,`name`,`level`,`time`,`timestamp`,`caller`]}})),Xs=n(((e,t)=>{t.exports=i;let{LEVELS:n,LEVEL_NAMES:r}=Ys();function i(e,t,i){let a=e?t||n:Object.assign({},n,t),o=e?i||r:Object.assign({},r,i);return function(e){let t=`default`;return t=Number.isInteger(+e)?Object.prototype.hasOwnProperty.call(a,e)?e:t:Object.prototype.hasOwnProperty.call(o,e.toLowerCase())?o[e.toLowerCase()]:t,[a[t],t]}}})),Zs=n(((e,t)=>{let n=e=>e,r={default:n,60:n,50:n,40:n,30:n,20:n,10:n,message:n,greyMessage:n,property:n},{createColors:i}=Hs(),a=Xs(),o=i({useColor:!0}),{white:s,bgRed:c,red:l,yellow:u,green:d,blue:f,gray:p,cyan:m,magenta:h}=o,g={default:s,60:c,50:l,40:u,30:d,20:f,10:p,message:m,greyMessage:p,property:h};function _(e){return e.reduce(function(e,[t,n]){return e[t]=typeof o[n]==`function`?o[n]:s,e},{default:s,message:m,greyMessage:p,property:h})}function v(e){return function(t,n,{customLevels:r,customLevelNames:i}={}){let[o,s]=a(e,r,i)(t);return Object.prototype.hasOwnProperty.call(n,s)?n[s](o):n.default(o)}}function y(e){let t=v(e),n=function(e,n){return t(e,r,n)};return n.message=r.message,n.greyMessage=r.greyMessage,n.property=r.property,n.colors=i({useColor:!1}),n}function b(e){let t=v(e),n=function(e,n){return t(e,g,n)};return n.message=g.message,n.property=g.property,n.greyMessage=g.greyMessage,n.colors=o,n}function x(e,t){let n=_(e),r=t?n:Object.assign({},g,n),i=v(t),a=function(e,t){return i(e,r,t)};return a.colors=o,a.message=a.message||r.message,a.property=a.property||r.property,a.greyMessage=a.greyMessage||r.greyMessage,a}t.exports=function(e=!1,t,n){return e&&t!==void 0?x(t,n):e?b(n):y(n)}})),Qs=n(((e,t)=>{t.exports=function(){}})),$s=n(((e,n)=>{n.exports=o;let{isMainThread:r}=t(`node:worker_threads`),i=Ds(),a=Qs();function o(e){let t=new i(e);return t.on(`error`,n),!e.sync&&r&&s(t),t;function n(e){if(e.code===`EPIPE`){t.write=a,t.end=a,t.flushSync=a,t.destroy=a;return}t.removeListener(`error`,n)}}function s(e){if(global.WeakRef&&global.WeakMap&&global.FinalizationRegistry){let t=Os();t.register(e,c),e.on(`close`,function(){t.unregister(e)})}}function c(e,t){e.destroyed||(t===`beforeExit`?(e.flush(),e.on(`drain`,function(){e.end()})):e.flushSync())}})),ec=n(((e,t)=>{t.exports=n;function n(e){return e instanceof Date&&!Number.isNaN(e.getTime())}})),tc=n(((e,t)=>{t.exports=r;let n=ec();function r(e){let t=new Date(e);return n(t)||(t=new Date(+e)),t}})),nc=n(((e,t)=>{t.exports=n;function n(e){let t=[],n=!1,r=``;for(let i=0;i<e.length;i++){let a=e.charAt(i);if(a===`\\`){n=!0;continue}if(n){n=!1,r+=a;continue}if(a===`.`){t.push(r),r=``;continue}r+=a}return r.length&&t.push(r),t}})),rc=n(((e,t)=>{t.exports=r;let n=nc();function r(e,t){let r=Array.isArray(t)?t:n(t);for(let t of r){if(!Object.prototype.hasOwnProperty.call(e,t))return;e=e[t]}return e}})),ic=n(((e,t)=>{t.exports=i;let n=rc(),r=nc();function i(e,t){let i=r(t),a=i.pop();e=n(e,i),typeof e==`object`&&e&&Object.prototype.hasOwnProperty.call(e,a)&&delete e[a]}})),ac=n((e=>{let t=Function.prototype.toString,n=Object.prototype.toString;function r(e){if(!e)return Object.create(null);let n=e.constructor;if(n===Object)return e===Object.prototype?{}:Object.create(e);if(n&&~t.call(n).indexOf(`[native code]`))try{return new n}catch{}return Object.create(e)}function i(e){let t=e[Symbol.toStringTag];if(t)return t;let r=n.call(e);return r.substring(8,r.length-1)}let{hasOwnProperty:a,propertyIsEnumerable:o}=Object.prototype;function s(e,t,n,r){let i=Object.getOwnPropertyDescriptor(e,n)||{configurable:!0,enumerable:!0,value:e[n],writable:!0},a=i.get||i.set?i:{configurable:i.configurable,enumerable:i.enumerable,value:r.copier(i.value,r),writable:i.writable};try{Object.defineProperty(t,n,a)}catch{t[n]=a.get?a.get():a.value}}function c(e,t,n){let r=Object.getOwnPropertyNames(e);for(let i=0;i<r.length;++i)s(e,t,r[i],n);let i=Object.getOwnPropertySymbols(e);for(let r=0;r<i.length;++r)s(e,t,i[r],n);return t}function l(e,t){let n=new t.Constructor;t.cache.set(e,n);for(let r=0;r<e.length;++r)n[r]=t.copier(e[r],t);return n}function u(e,t){let n=new t.Constructor;return t.cache.set(e,n),c(e,n,t)}function d(e,t){return e.slice(0)}function f(e,t){return e.slice(0,e.size,e.type)}function p(e,t){return new t.Constructor(d(e.buffer))}function m(e,t){return new t.Constructor(e.getTime())}function h(e,t){let n=new t.Constructor;return t.cache.set(e,n),e.forEach((e,r)=>{n.set(r,t.copier(e,t))}),n}function g(e,t){return c(e,h(e,t),t)}function _(e,t){let n=r(t.prototype);t.cache.set(e,n);for(let r in e)a.call(e,r)&&(n[r]=t.copier(e[r],t));let i=Object.getOwnPropertySymbols(e);for(let r=0;r<i.length;++r){let a=i[r];o.call(e,a)&&(n[a]=t.copier(e[a],t))}return n}function v(e,t){let n=r(t.prototype);return t.cache.set(e,n),c(e,n,t)}function y(e,t){return new t.Constructor(e.valueOf())}function b(e,t){let n=new t.Constructor(e.source,e.flags);return n.lastIndex=e.lastIndex,n}function x(e,t){return e}function S(e,t){let n=new t.Constructor;return t.cache.set(e,n),e.forEach(e=>{n.add(t.copier(e,t))}),n}function C(e,t){return c(e,S(e,t),t)}function w(){return new WeakMap}function T({createCache:e,methods:t,strict:n}){let r={array:n?u:l,arrayBuffer:d,asyncGenerator:x,blob:f,dataView:p,date:m,error:x,generator:x,map:n?g:h,object:n?v:_,regExp:b,set:n?C:S},i=t?Object.assign(r,t):r,a=E(i),o=e||w;if(!a.Object||!a.Array)throw Error(`An object and array copier must be provided.`);return{createCache:o,copiers:a,methods:i,strict:!!n}}function E(e){return{Arguments:e.object,Array:e.array,ArrayBuffer:e.arrayBuffer,AsyncGenerator:e.asyncGenerator,Blob:e.blob,Boolean:y,DataView:e.dataView,Date:e.date,Error:e.error,Float32Array:e.arrayBuffer,Float64Array:e.arrayBuffer,Generator:e.generator,Int8Array:e.arrayBuffer,Int16Array:e.arrayBuffer,Int32Array:e.arrayBuffer,Map:e.map,Number:y,Object:e.object,Promise:x,RegExp:e.regExp,Set:e.set,String:y,WeakMap:x,WeakSet:x,Uint8Array:e.arrayBuffer,Uint8ClampedArray:e.arrayBuffer,Uint16Array:e.arrayBuffer,Uint32Array:e.arrayBuffer,Uint64Array:e.arrayBuffer}}function D(e={}){let{createCache:t,copiers:n}=T(e),{Array:r,Object:a}=n;function o(e,t){if(t.prototype=t.Constructor=void 0,!e||typeof e!=`object`)return e;if(t.cache.has(e))return t.cache.get(e);if(t.prototype=Object.getPrototypeOf(e),t.Constructor=t.prototype&&t.prototype.constructor,!t.Constructor||t.Constructor===Object)return a(e,t);if(Array.isArray(e))return r(e,t);let o=n[i(e)];return o?o(e,t):typeof e.then==`function`?e:a(e,t)}return function(e){return o(e,{Constructor:void 0,cache:t(),copier:o,prototype:void 0})}}let O=D({strict:!0});e.copy=D(),e.copyStrict=O,e.createCopier=D})),oc=n(((e,t)=>{t.exports=a;let{createCopier:n}=ac(),r=n({}),i=ic();function a({log:e,context:t}){let{ignoreKeys:n,includeKeys:a}=t,o=r(e);if(a){let e={};return a.forEach(t=>{e[t]=o[t]}),e}return n.forEach(e=>{i(o,e)}),o}})),sc=n(((e,t)=>{function n(e){"@babel/helpers - typeof";return n=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},n(e)}(function(r){var i=arguments,a=function(){var e=/d{1,4}|D{3,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|W{1,2}|[LlopSZN]|"[^"]*"|'[^']*'/g,t=/\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,n=/[^-+\dA-Z]/g;return function(r,d,f,p){if(i.length===1&&u(r)===`string`&&!/\d/.test(r)&&(d=r,r=void 0),r=r||r===0?r:new Date,r instanceof Date||(r=new Date(r)),isNaN(r))throw TypeError(`Invalid date`);d=String(a.masks[d]||d||a.masks.default);var m=d.slice(0,4);(m===`UTC:`||m===`GMT:`)&&(d=d.slice(4),f=!0,m===`GMT:`&&(p=!0));var h=function(){return f?`getUTC`:`get`},g=function(){return r[h()+`Date`]()},_=function(){return r[h()+`Day`]()},v=function(){return r[h()+`Month`]()},y=function(){return r[h()+`FullYear`]()},b=function(){return r[h()+`Hours`]()},x=function(){return r[h()+`Minutes`]()},S=function(){return r[h()+`Seconds`]()},C=function(){return r[h()+`Milliseconds`]()},w=function(){return f?0:r.getTimezoneOffset()},T=function(){return c(r)},E=function(){return l(r)},D={d:function(){return g()},dd:function(){return o(g())},ddd:function(){return a.i18n.dayNames[_()]},DDD:function(){return s({y:y(),m:v(),d:g(),_:h(),dayName:a.i18n.dayNames[_()],short:!0})},dddd:function(){return a.i18n.dayNames[_()+7]},DDDD:function(){return s({y:y(),m:v(),d:g(),_:h(),dayName:a.i18n.dayNames[_()+7]})},m:function(){return v()+1},mm:function(){return o(v()+1)},mmm:function(){return a.i18n.monthNames[v()]},mmmm:function(){return a.i18n.monthNames[v()+12]},yy:function(){return String(y()).slice(2)},yyyy:function(){return o(y(),4)},h:function(){return b()%12||12},hh:function(){return o(b()%12||12)},H:function(){return b()},HH:function(){return o(b())},M:function(){return x()},MM:function(){return o(x())},s:function(){return S()},ss:function(){return o(S())},l:function(){return o(C(),3)},L:function(){return o(Math.floor(C()/10))},t:function(){return b()<12?a.i18n.timeNames[0]:a.i18n.timeNames[1]},tt:function(){return b()<12?a.i18n.timeNames[2]:a.i18n.timeNames[3]},T:function(){return b()<12?a.i18n.timeNames[4]:a.i18n.timeNames[5]},TT:function(){return b()<12?a.i18n.timeNames[6]:a.i18n.timeNames[7]},Z:function(){return p?`GMT`:f?`UTC`:(String(r).match(t)||[``]).pop().replace(n,``).replace(/GMT\+0000/g,`UTC`)},o:function(){return(w()>0?`-`:`+`)+o(Math.floor(Math.abs(w())/60)*100+Math.abs(w())%60,4)},p:function(){return(w()>0?`-`:`+`)+o(Math.floor(Math.abs(w())/60),2)+`:`+o(Math.floor(Math.abs(w())%60),2)},S:function(){return[`th`,`st`,`nd`,`rd`][g()%10>3?0:(g()%100-g()%10!=10)*g()%10]},W:function(){return T()},WW:function(){return o(T())},N:function(){return E()}};return d.replace(e,function(e){return e in D?D[e]():e.slice(1,e.length-1)})}}();a.masks={default:`ddd mmm dd yyyy HH:MM:ss`,shortDate:`m/d/yy`,paddedShortDate:`mm/dd/yyyy`,mediumDate:`mmm d, yyyy`,longDate:`mmmm d, yyyy`,fullDate:`dddd, mmmm d, yyyy`,shortTime:`h:MM TT`,mediumTime:`h:MM:ss TT`,longTime:`h:MM:ss TT Z`,isoDate:`yyyy-mm-dd`,isoTime:`HH:MM:ss`,isoDateTime:`yyyy-mm-dd'T'HH:MM:sso`,isoUtcDateTime:`UTC:yyyy-mm-dd'T'HH:MM:ss'Z'`,expiresHeaderFormat:`ddd, dd mmm yyyy HH:MM:ss Z`},a.i18n={dayNames:[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],monthNames:[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`,`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],timeNames:[`a`,`p`,`am`,`pm`,`A`,`P`,`AM`,`PM`]};var o=function(e,t){for(e=String(e),t||=2;e.length<t;)e=`0`+e;return e},s=function(e){var t=e.y,n=e.m,r=e.d,i=e._,a=e.dayName,o=e.short,s=o===void 0?!1:o,c=new Date,l=new Date;l.setDate(l[i+`Date`]()-1);var u=new Date;return u.setDate(u[i+`Date`]()+1),function(){return c[i+`FullYear`]()}()===t&&function(){return c[i+`Month`]()}()===n&&function(){return c[i+`Date`]()}()===r?s?`Tdy`:`Today`:function(){return l[i+`FullYear`]()}()===t&&function(){return l[i+`Month`]()}()===n&&function(){return l[i+`Date`]()}()===r?s?`Ysd`:`Yesterday`:function(){return u[i+`FullYear`]()}()===t&&function(){return u[i+`Month`]()}()===n&&function(){return u[i+`Date`]()}()===r?s?`Tmw`:`Tomorrow`:a},c=function(e){var t=new Date(e.getFullYear(),e.getMonth(),e.getDate());t.setDate(t.getDate()-(t.getDay()+6)%7+3);var n=new Date(t.getFullYear(),0,4);n.setDate(n.getDate()-(n.getDay()+6)%7+3);var r=t.getTimezoneOffset()-n.getTimezoneOffset();t.setHours(t.getHours()-r);var i=(t-n)/(864e5*7);return 1+Math.floor(i)},l=function(e){var t=e.getDay();return t===0&&(t=7),t},u=function(e){return e===null?`null`:e===void 0?`undefined`:n(e)===`object`?Array.isArray(e)?`array`:{}.toString.call(e).slice(8,-1).toLowerCase():n(e)};typeof define==`function`&&define.amd?define(function(){return a}):(e===void 0?`undefined`:n(e))===`object`?t.exports=a:r.dateFormat=a})(void 0)})),cc=n(((e,t)=>{t.exports=s;let{DATE_FORMAT:n,DATE_FORMAT_SIMPLE:r}=Ys(),i=sc(),a=tc(),o=ec();function s(e,t=!1){if(t===!1)return e;let s=a(e);if(!o(s))return e;if(t===!0)return i(s,r);let c=t.toUpperCase();if(c===`SYS:STANDARD`)return i(s,n);let l=c.substr(0,4);return l===`SYS:`||l===`UTC:`?l===`UTC:`?i(s,t):i(s,t.slice(4)):i(s,`UTC:${t}`)}})),lc=n(((e,t)=>{t.exports=n;function n(e){return e?typeof e==`string`?e.split(`,`).reduce((e,t,n)=>{let[r,i=n]=t.split(`:`);return e[r.toLowerCase()]=i,e},{}):Object.prototype.toString.call(e)===`[object Object]`?Object.keys(e).reduce((t,n)=>(t[n.toLowerCase()]=e[n],t),{}):{}:{}}})),uc=n(((e,t)=>{t.exports=n;function n(e){return e?typeof e==`string`?e.split(`,`).reduce((e,t,n)=>{let[r,i=n]=t.split(`:`);return e[i]=r.toUpperCase(),e},{default:`USERLVL`}):Object.prototype.toString.call(e)===`[object Object]`?Object.keys(e).reduce((t,n)=>(t[e[n]]=n.toUpperCase(),t),{default:`USERLVL`}):{}:{}}})),dc=n(((e,t)=>{t.exports=r;let n=rc();function r(e,t){return e=e.replace(/{if (.*?)}(.*?){end}/g,r),e=e.replace(/{if (.*?)}/g,``),e=e.replace(/{end}/g,``),e.replace(/\s+/g,` `).trim();function r(e,r,i){let a=n(t,r);return a&&i.includes(r)?i.replace(RegExp(`{`+r+`}`,`g`),a):``}}})),fc=n(((e,t)=>{t.exports=n;function n(e){return Object.prototype.toString.apply(e)===`[object Object]`}})),pc=n(((e,t)=>{t.exports=n;function n({input:e,ident:t=` `,eol:n=`
8
- `}){let r=e.split(/\r?\n/);for(let e=1;e<r.length;e+=1)r[e]=t+r[e];return r.join(n)}})),mc=n(((e,t)=>{t.exports=s;let{LEVEL_NAMES:n}=Ys(),r=Zs(),i=uc(),a=lc(),o=Xs();function s(e){let t=e.crlf?`\r
7
+ `),ke=y.bind(null,{[E]:``,[O]:l,[N]:Ee,[M]:S,[ee]:B,[se]:V}),Ae=``;T!==null&&(Ae=ke(fe===void 0?T:Object.assign({},T,{name:fe})));let je=_ instanceof Function?_:_?R:de,Me=je().indexOf(`:`)+1;if(ve&&!me)throw Error(`customLevels is required if useOnlyCustomLevels is set true`);if(z&&typeof z!=`function`)throw Error(`Unknown mixin type "${typeof z}" - expected "function"`);if(we&&typeof we!=`string`)throw Error(`Unknown msgPrefix type "${typeof we}" - expected "string"`);d(pe,me,ve);let Ne=f(me,ve);typeof r.emit==`function`&&r.emit(`message`,{code:`PINO_CONFIG`,config:{levels:Ne,messageKey:v,errorKey:b}}),h(ge);let Pe=m(ge);return Object.assign(t,{levels:Ne,[I]:Pe,[oe]:ve,[j]:r,[k]:je,[A]:Me,[M]:S,[ee]:B,[N]:Ee,[ne]:Oe,[P]:De,[re]:v,[F]:b,[ie]:C,[ce]:C?`,${JSON.stringify(C)}:{`:``,[O]:l,[ae]:z,[le]:_e,[E]:Ae,[se]:V,[L]:be,silent:w,onChild:Ce,[ue]:we}),Object.setPrototypeOf(t,c()),p(t),t[te](pe),t}n.exports=z,n.exports.destination=(e=process.stdout.fd)=>typeof e==`object`?(e.dest=C(e.dest||process.stdout.fd),b(e)):b({dest:C(e),minLength:0}),n.exports.transport=Fs(),n.exports.multistream=Hs(),n.exports.levels=f(),n.exports.stdSerializers=ge,n.exports.stdTimeFunctions=Object.assign({},s),n.exports.symbols=l,n.exports.version=T,n.exports.default=z,n.exports.pino=z})),Ws=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});var n=t(`tty`);function r(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if(n!==`default`){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var i=r(n);let{env:a={},argv:o=[],platform:s=``}=typeof process>`u`?{}:process,c=`NO_COLOR`in a||o.includes(`--no-color`),l=`FORCE_COLOR`in a||o.includes(`--color`),u=s===`win32`,d=a.TERM===`dumb`,f=i&&i.isatty&&i.isatty(1)&&a.TERM&&!d,p=`CI`in a&&(`GITHUB_ACTIONS`in a||`GITLAB_CI`in a||`CIRCLECI`in a),m=!c&&(l||u&&!d||f||p),h=(e,t,n,r,i=t.substring(0,e)+r,a=t.substring(e+n.length),o=a.indexOf(n))=>i+(o<0?a:h(o,a,n,r)),g=(e,t,n,r,i)=>e<0?n+t+r:n+h(e,t,r,i)+r,_=(e,t,n=e,r=e.length+1)=>i=>i||!(i===``||i===void 0)?g((``+i).indexOf(t,r),i,e,t,n):``,v=(e,t,n)=>_(`\x1b[${e}m`,`\x1b[${t}m`,n),y={reset:v(0,0),bold:v(1,22,`\x1B[22m\x1B[1m`),dim:v(2,22,`\x1B[22m\x1B[2m`),italic:v(3,23),underline:v(4,24),inverse:v(7,27),hidden:v(8,28),strikethrough:v(9,29),black:v(30,39),red:v(31,39),green:v(32,39),yellow:v(33,39),blue:v(34,39),magenta:v(35,39),cyan:v(36,39),white:v(37,39),gray:v(90,39),bgBlack:v(40,49),bgRed:v(41,49),bgGreen:v(42,49),bgYellow:v(43,49),bgBlue:v(44,49),bgMagenta:v(45,49),bgCyan:v(46,49),bgWhite:v(47,49),blackBright:v(90,39),redBright:v(91,39),greenBright:v(92,39),yellowBright:v(93,39),blueBright:v(94,39),magentaBright:v(95,39),cyanBright:v(96,39),whiteBright:v(97,39),bgBlackBright:v(100,49),bgRedBright:v(101,49),bgGreenBright:v(102,49),bgYellowBright:v(103,49),bgBlueBright:v(104,49),bgMagentaBright:v(105,49),bgCyanBright:v(106,49),bgWhiteBright:v(107,49)},b=({useColor:e=m}={})=>e?y:Object.keys(y).reduce((e,t)=>({...e,[t]:String}),{}),{reset:x,bold:S,dim:C,italic:w,underline:T,inverse:E,hidden:D,strikethrough:O,black:k,red:A,green:j,yellow:M,blue:ee,magenta:N,cyan:te,white:ne,gray:P,bgBlack:re,bgRed:F,bgGreen:ie,bgYellow:ae,bgBlue:I,bgMagenta:oe,bgCyan:se,bgWhite:L,blackBright:ce,redBright:le,greenBright:ue,yellowBright:R,blueBright:de,magentaBright:fe,cyanBright:pe,whiteBright:me,bgBlackBright:he,bgRedBright:ge,bgGreenBright:z,bgYellowBright:_e,bgBlueBright:ve,bgMagentaBright:ye,bgCyanBright:be,bgWhiteBright:xe}=b();e.bgBlack=re,e.bgBlackBright=he,e.bgBlue=I,e.bgBlueBright=ve,e.bgCyan=se,e.bgCyanBright=be,e.bgGreen=ie,e.bgGreenBright=z,e.bgMagenta=oe,e.bgMagentaBright=ye,e.bgRed=F,e.bgRedBright=ge,e.bgWhite=L,e.bgWhiteBright=xe,e.bgYellow=ae,e.bgYellowBright=_e,e.black=k,e.blackBright=ce,e.blue=ee,e.blueBright=de,e.bold=S,e.createColors=b,e.cyan=te,e.cyanBright=pe,e.dim=C,e.gray=P,e.green=j,e.greenBright=ue,e.hidden=D,e.inverse=E,e.isColorSupported=m,e.italic=w,e.magenta=N,e.magentaBright=fe,e.red=A,e.redBright=le,e.reset=x,e.strikethrough=O,e.underline=T,e.white=ne,e.whiteBright=me,e.yellow=M,e.yellowBright=R})),Gs=n(((e,t)=>{t.exports=n;function n(e,t){if(e&&t)return n(e)(t);if(typeof e!=`function`)throw TypeError(`need wrapper function`);return Object.keys(e).forEach(function(t){r[t]=e[t]}),r;function r(){for(var t=Array(arguments.length),n=0;n<t.length;n++)t[n]=arguments[n];var r=e.apply(this,t),i=t[t.length-1];return typeof r==`function`&&r!==i&&Object.keys(i).forEach(function(e){r[e]=i[e]}),r}}})),Ks=n(((e,t)=>{var n=Gs();t.exports=n(r),t.exports.strict=n(i),r.proto=r(function(){Object.defineProperty(Function.prototype,`once`,{value:function(){return r(this)},configurable:!0}),Object.defineProperty(Function.prototype,`onceStrict`,{value:function(){return i(this)},configurable:!0})});function r(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function i(e){var t=function(){if(t.called)throw Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)};return t.onceError=(e.name||"Function wrapped with `once`")+` shouldn't be called more than once`,t.called=!1,t}})),qs=n(((e,t)=>{var n=Ks(),r=function(){},i=global.Bare?queueMicrotask:process.nextTick.bind(process),a=function(e){return e.setHeader&&typeof e.abort==`function`},o=function(e){return e.stdio&&Array.isArray(e.stdio)&&e.stdio.length===3},s=function(e,t,c){if(typeof t==`function`)return s(e,null,t);t||={},c=n(c||r);var l=e._writableState,u=e._readableState,d=t.readable||t.readable!==!1&&e.readable,f=t.writable||t.writable!==!1&&e.writable,p=!1,m=function(){e.writable||h()},h=function(){f=!1,d||c.call(e)},g=function(){d=!1,f||c.call(e)},_=function(t){c.call(e,t?Error(`exited with error code: `+t):null)},v=function(t){c.call(e,t)},y=function(){i(b)},b=function(){if(!p&&(d&&!(u&&u.ended&&!u.destroyed)||f&&!(l&&l.ended&&!l.destroyed)))return c.call(e,Error(`premature close`))},x=function(){e.req.on(`finish`,h)};return a(e)?(e.on(`complete`,h),e.on(`abort`,y),e.req?x():e.on(`request`,x)):f&&!l&&(e.on(`end`,m),e.on(`close`,m)),o(e)&&e.on(`exit`,_),e.on(`end`,g),e.on(`finish`,h),t.error!==!1&&e.on(`error`,v),e.on(`close`,y),function(){p=!0,e.removeListener(`complete`,h),e.removeListener(`abort`,y),e.removeListener(`request`,x),e.req&&e.req.removeListener(`finish`,h),e.removeListener(`end`,m),e.removeListener(`close`,m),e.removeListener(`finish`,h),e.removeListener(`exit`,_),e.removeListener(`end`,g),e.removeListener(`error`,v),e.removeListener(`close`,y)}};t.exports=s})),Js=n(((e,n)=>{var r=Ks(),i=qs(),a;try{a=t(`fs`)}catch{}var o=function(){},s=typeof process>`u`?!1:/^v?\.0/.test(process.version),c=function(e){return typeof e==`function`},l=function(e){return!s||!a?!1:(e instanceof(a.ReadStream||o)||e instanceof(a.WriteStream||o))&&c(e.close)},u=function(e){return e.setHeader&&c(e.abort)},d=function(e,t,n,a){a=r(a);var s=!1;e.on(`close`,function(){s=!0}),i(e,{readable:t,writable:n},function(e){if(e)return a(e);s=!0,a()});var d=!1;return function(t){if(!s&&!d){if(d=!0,l(e))return e.close(o);if(u(e))return e.abort();if(c(e.destroy))return e.destroy();a(t||Error(`stream was destroyed`))}}},f=function(e){e()},p=function(e,t){return e.pipe(t)};n.exports=function(){var e=Array.prototype.slice.call(arguments),t=c(e[e.length-1]||o)&&e.pop()||o;if(Array.isArray(e[0])&&(e=e[0]),e.length<2)throw Error(`pump requires two streams per minimum`);var n,r=e.map(function(i,a){var o=a<e.length-1;return d(i,o,a>0,function(e){n||=e,e&&r.forEach(f),!o&&(r.forEach(f),t(n))})});return e.reduce(p)}})),Ys=n(((e,n)=>{let{Transform:r}=t(`stream`),{StringDecoder:i}=t(`string_decoder`),a=Symbol(`last`),o=Symbol(`decoder`);function s(e,t,n){let r;if(this.overflow){if(r=this[o].write(e).split(this.matcher),r.length===1)return n();r.shift(),this.overflow=!1}else this[a]+=this[o].write(e),r=this[a].split(this.matcher);this[a]=r.pop();for(let e=0;e<r.length;e++)try{l(this,this.mapper(r[e]))}catch(e){return n(e)}if(this.overflow=this[a].length>this.maxLength,this.overflow&&!this.skipOverflow){n(Error(`maximum buffer reached`));return}n()}function c(e){if(this[a]+=this[o].end(),this[a])try{l(this,this.mapper(this[a]))}catch(t){return e(t)}e()}function l(e,t){t!==void 0&&e.push(t)}function u(e){return e}function d(e,t,n){switch(e||=/\r?\n/,t||=u,n||={},arguments.length){case 1:typeof e==`function`?(t=e,e=/\r?\n/):typeof e==`object`&&!(e instanceof RegExp)&&!e[Symbol.split]&&(n=e,e=/\r?\n/);break;case 2:typeof e==`function`?(n=t,t=e,e=/\r?\n/):typeof t==`object`&&(n=t,t=u)}n=Object.assign({},n),n.autoDestroy=!0,n.transform=s,n.flush=c,n.readableObjectMode=!0;let l=new r(n);return l[a]=``,l[o]=new i(`utf8`),l.matcher=e,l.mapper=t,l.maxLength=n.maxLength,l.skipOverflow=n.skipOverflow||!1,l.overflow=!1,l._destroy=function(e,t){this._writableState.errorEmitted=!1,t(e)},l}n.exports=d})),Xs=n(((e,n)=>{let r=Symbol.for(`pino.metadata`),i=Ys(),{Duplex:a}=t(`stream`),{parentPort:o,workerData:s}=t(`worker_threads`);function c(){let e,t,n=new Promise((n,r)=>{e=n,t=r});return n.resolve=e,n.reject=t,n}n.exports=function(e,t={}){let n=t.expectPinoConfig===!0&&s?.workerData?.pinoWillSendConfig===!0,u=t.parse===`lines`,d=typeof t.parseLine==`function`?t.parseLine:JSON.parse,f=t.close||l,p=i(function(e){let t;try{t=d(e)}catch(t){this.emit(`unknown`,e,t);return}if(t===null){this.emit(`unknown`,e,`Null value ignored`);return}return typeof t!=`object`&&(t={data:t,time:Date.now()}),p[r]&&(p.lastTime=t.time,p.lastLevel=t.level,p.lastObj=t),u?e:t},{autoDestroy:!0});if(p._destroy=function(e,t){let n=f(e,t);n&&typeof n.then==`function`&&n.then(t,t)},t.expectPinoConfig===!0&&s?.workerData?.pinoWillSendConfig!==!0&&setImmediate(()=>{p.emit(`error`,Error(`This transport is not compatible with the current version of pino. Please upgrade pino to the latest version.`))}),t.metadata!==!1&&(p[r]=!0,p.lastTime=0,p.lastLevel=0,p.lastObj=null),n){let e={},t=c();return o.on(`message`,function n(r){r.code===`PINO_CONFIG`&&(e=r.config,t.resolve(),o.off(`message`,n))}),Object.defineProperties(p,{levels:{get(){return e.levels}},messageKey:{get(){return e.messageKey}},errorKey:{get(){return e.errorKey}}}),t.then(m)}return m();function m(){let n=e(p);if(n&&typeof n.catch==`function`)n.catch(e=>{p.destroy(e)}),n=null;else if(t.enablePipelining&&n)return a.from({writable:p,readable:n});return p}};function l(e,t){process.nextTick(t,e)}})),Zs=n(((e,t)=>{t.exports={DATE_FORMAT:`yyyy-mm-dd HH:MM:ss.l o`,DATE_FORMAT_SIMPLE:`HH:MM:ss.l`,ERROR_LIKE_KEYS:[`err`,`error`],MESSAGE_KEY:`msg`,LEVEL_KEY:`level`,LEVEL_LABEL:`levelLabel`,TIMESTAMP_KEY:`time`,LEVELS:{default:`USERLVL`,60:`FATAL`,50:`ERROR`,40:`WARN`,30:`INFO`,20:`DEBUG`,10:`TRACE`},LEVEL_NAMES:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},LOGGER_KEYS:[`pid`,`hostname`,`name`,`level`,`time`,`timestamp`,`caller`]}})),Qs=n(((e,t)=>{t.exports=i;let{LEVELS:n,LEVEL_NAMES:r}=Zs();function i(e,t,i){let a=e?t||n:Object.assign({},n,t),o=e?i||r:Object.assign({},r,i);return function(e){let t=`default`;return t=Number.isInteger(+e)?Object.prototype.hasOwnProperty.call(a,e)?e:t:Object.prototype.hasOwnProperty.call(o,e.toLowerCase())?o[e.toLowerCase()]:t,[a[t],t]}}})),$s=n(((e,t)=>{let n=e=>e,r={default:n,60:n,50:n,40:n,30:n,20:n,10:n,message:n,greyMessage:n,property:n},{createColors:i}=Ws(),a=Qs(),o=i({useColor:!0}),{white:s,bgRed:c,red:l,yellow:u,green:d,blue:f,gray:p,cyan:m,magenta:h}=o,g={default:s,60:c,50:l,40:u,30:d,20:f,10:p,message:m,greyMessage:p,property:h};function _(e){return e.reduce(function(e,[t,n]){return e[t]=typeof o[n]==`function`?o[n]:s,e},{default:s,message:m,greyMessage:p,property:h})}function v(e){return function(t,n,{customLevels:r,customLevelNames:i}={}){let[o,s]=a(e,r,i)(t);return Object.prototype.hasOwnProperty.call(n,s)?n[s](o):n.default(o)}}function y(e){let t=v(e),n=function(e,n){return t(e,r,n)};return n.message=r.message,n.greyMessage=r.greyMessage,n.property=r.property,n.colors=i({useColor:!1}),n}function b(e){let t=v(e),n=function(e,n){return t(e,g,n)};return n.message=g.message,n.property=g.property,n.greyMessage=g.greyMessage,n.colors=o,n}function x(e,t){let n=_(e),r=t?n:Object.assign({},g,n),i=v(t),a=function(e,t){return i(e,r,t)};return a.colors=o,a.message=a.message||r.message,a.property=a.property||r.property,a.greyMessage=a.greyMessage||r.greyMessage,a}t.exports=function(e=!1,t,n){return e&&t!==void 0?x(t,n):e?b(n):y(n)}})),ec=n(((e,t)=>{t.exports=function(){}})),tc=n(((e,n)=>{n.exports=o;let{isMainThread:r}=t(`node:worker_threads`),i=ks(),a=ec();function o(e){let t=new i(e);return t.on(`error`,n),!e.sync&&r&&s(t),t;function n(e){if(e.code===`EPIPE`){t.write=a,t.end=a,t.flushSync=a,t.destroy=a;return}t.removeListener(`error`,n)}}function s(e){if(global.WeakRef&&global.WeakMap&&global.FinalizationRegistry){let t=As();t.register(e,c),e.on(`close`,function(){t.unregister(e)})}}function c(e,t){e.destroyed||(t===`beforeExit`?(e.flush(),e.on(`drain`,function(){e.end()})):e.flushSync())}})),nc=n(((e,t)=>{t.exports=n;function n(e){return e instanceof Date&&!Number.isNaN(e.getTime())}})),rc=n(((e,t)=>{t.exports=r;let n=nc();function r(e){let t=new Date(e);return n(t)||(t=new Date(+e)),t}})),ic=n(((e,t)=>{t.exports=n;function n(e){let t=[],n=!1,r=``;for(let i=0;i<e.length;i++){let a=e.charAt(i);if(a===`\\`){n=!0;continue}if(n){n=!1,r+=a;continue}if(a===`.`){t.push(r),r=``;continue}r+=a}return r.length&&t.push(r),t}})),ac=n(((e,t)=>{t.exports=r;let n=ic();function r(e,t){let r=Array.isArray(t)?t:n(t);for(let t of r){if(!Object.prototype.hasOwnProperty.call(e,t))return;e=e[t]}return e}})),oc=n(((e,t)=>{t.exports=i;let n=ac(),r=ic();function i(e,t){let i=r(t),a=i.pop();e=n(e,i),typeof e==`object`&&e&&Object.prototype.hasOwnProperty.call(e,a)&&delete e[a]}})),sc=n((e=>{let t=Function.prototype.toString,n=Object.prototype.toString;function r(e){if(!e)return Object.create(null);let n=e.constructor;if(n===Object)return e===Object.prototype?{}:Object.create(e);if(n&&~t.call(n).indexOf(`[native code]`))try{return new n}catch{}return Object.create(e)}function i(e){let t=e[Symbol.toStringTag];if(t)return t;let r=n.call(e);return r.substring(8,r.length-1)}let{hasOwnProperty:a,propertyIsEnumerable:o}=Object.prototype;function s(e,t,n,r){let i=Object.getOwnPropertyDescriptor(e,n)||{configurable:!0,enumerable:!0,value:e[n],writable:!0},a=i.get||i.set?i:{configurable:i.configurable,enumerable:i.enumerable,value:r.copier(i.value,r),writable:i.writable};try{Object.defineProperty(t,n,a)}catch{t[n]=a.get?a.get():a.value}}function c(e,t,n){let r=Object.getOwnPropertyNames(e);for(let i=0;i<r.length;++i)s(e,t,r[i],n);let i=Object.getOwnPropertySymbols(e);for(let r=0;r<i.length;++r)s(e,t,i[r],n);return t}function l(e,t){let n=new t.Constructor;t.cache.set(e,n);for(let r=0;r<e.length;++r)n[r]=t.copier(e[r],t);return n}function u(e,t){let n=new t.Constructor;return t.cache.set(e,n),c(e,n,t)}function d(e,t){return e.slice(0)}function f(e,t){return e.slice(0,e.size,e.type)}function p(e,t){return new t.Constructor(d(e.buffer))}function m(e,t){return new t.Constructor(e.getTime())}function h(e,t){let n=new t.Constructor;return t.cache.set(e,n),e.forEach((e,r)=>{n.set(r,t.copier(e,t))}),n}function g(e,t){return c(e,h(e,t),t)}function _(e,t){let n=r(t.prototype);t.cache.set(e,n);for(let r in e)a.call(e,r)&&(n[r]=t.copier(e[r],t));let i=Object.getOwnPropertySymbols(e);for(let r=0;r<i.length;++r){let a=i[r];o.call(e,a)&&(n[a]=t.copier(e[a],t))}return n}function v(e,t){let n=r(t.prototype);return t.cache.set(e,n),c(e,n,t)}function y(e,t){return new t.Constructor(e.valueOf())}function b(e,t){let n=new t.Constructor(e.source,e.flags);return n.lastIndex=e.lastIndex,n}function x(e,t){return e}function S(e,t){let n=new t.Constructor;return t.cache.set(e,n),e.forEach(e=>{n.add(t.copier(e,t))}),n}function C(e,t){return c(e,S(e,t),t)}function w(){return new WeakMap}function T({createCache:e,methods:t,strict:n}){let r={array:n?u:l,arrayBuffer:d,asyncGenerator:x,blob:f,dataView:p,date:m,error:x,generator:x,map:n?g:h,object:n?v:_,regExp:b,set:n?C:S},i=t?Object.assign(r,t):r,a=E(i),o=e||w;if(!a.Object||!a.Array)throw Error(`An object and array copier must be provided.`);return{createCache:o,copiers:a,methods:i,strict:!!n}}function E(e){return{Arguments:e.object,Array:e.array,ArrayBuffer:e.arrayBuffer,AsyncGenerator:e.asyncGenerator,Blob:e.blob,Boolean:y,DataView:e.dataView,Date:e.date,Error:e.error,Float32Array:e.arrayBuffer,Float64Array:e.arrayBuffer,Generator:e.generator,Int8Array:e.arrayBuffer,Int16Array:e.arrayBuffer,Int32Array:e.arrayBuffer,Map:e.map,Number:y,Object:e.object,Promise:x,RegExp:e.regExp,Set:e.set,String:y,WeakMap:x,WeakSet:x,Uint8Array:e.arrayBuffer,Uint8ClampedArray:e.arrayBuffer,Uint16Array:e.arrayBuffer,Uint32Array:e.arrayBuffer,Uint64Array:e.arrayBuffer}}function D(e={}){let{createCache:t,copiers:n}=T(e),{Array:r,Object:a}=n;function o(e,t){if(t.prototype=t.Constructor=void 0,!e||typeof e!=`object`)return e;if(t.cache.has(e))return t.cache.get(e);if(t.prototype=Object.getPrototypeOf(e),t.Constructor=t.prototype&&t.prototype.constructor,!t.Constructor||t.Constructor===Object)return a(e,t);if(Array.isArray(e))return r(e,t);let o=n[i(e)];return o?o(e,t):typeof e.then==`function`?e:a(e,t)}return function(e){return o(e,{Constructor:void 0,cache:t(),copier:o,prototype:void 0})}}let O=D({strict:!0});e.copy=D(),e.copyStrict=O,e.createCopier=D})),cc=n(((e,t)=>{t.exports=a;let{createCopier:n}=sc(),r=n({}),i=oc();function a({log:e,context:t}){let{ignoreKeys:n,includeKeys:a}=t,o=r(e);if(a){let e={};return a.forEach(t=>{e[t]=o[t]}),e}return n.forEach(e=>{i(o,e)}),o}})),lc=n(((e,t)=>{function n(e){"@babel/helpers - typeof";return n=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},n(e)}(function(r){var i=arguments,a=function(){var e=/d{1,4}|D{3,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|W{1,2}|[LlopSZN]|"[^"]*"|'[^']*'/g,t=/\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,n=/[^-+\dA-Z]/g;return function(r,d,f,p){if(i.length===1&&u(r)===`string`&&!/\d/.test(r)&&(d=r,r=void 0),r=r||r===0?r:new Date,r instanceof Date||(r=new Date(r)),isNaN(r))throw TypeError(`Invalid date`);d=String(a.masks[d]||d||a.masks.default);var m=d.slice(0,4);(m===`UTC:`||m===`GMT:`)&&(d=d.slice(4),f=!0,m===`GMT:`&&(p=!0));var h=function(){return f?`getUTC`:`get`},g=function(){return r[h()+`Date`]()},_=function(){return r[h()+`Day`]()},v=function(){return r[h()+`Month`]()},y=function(){return r[h()+`FullYear`]()},b=function(){return r[h()+`Hours`]()},x=function(){return r[h()+`Minutes`]()},S=function(){return r[h()+`Seconds`]()},C=function(){return r[h()+`Milliseconds`]()},w=function(){return f?0:r.getTimezoneOffset()},T=function(){return c(r)},E=function(){return l(r)},D={d:function(){return g()},dd:function(){return o(g())},ddd:function(){return a.i18n.dayNames[_()]},DDD:function(){return s({y:y(),m:v(),d:g(),_:h(),dayName:a.i18n.dayNames[_()],short:!0})},dddd:function(){return a.i18n.dayNames[_()+7]},DDDD:function(){return s({y:y(),m:v(),d:g(),_:h(),dayName:a.i18n.dayNames[_()+7]})},m:function(){return v()+1},mm:function(){return o(v()+1)},mmm:function(){return a.i18n.monthNames[v()]},mmmm:function(){return a.i18n.monthNames[v()+12]},yy:function(){return String(y()).slice(2)},yyyy:function(){return o(y(),4)},h:function(){return b()%12||12},hh:function(){return o(b()%12||12)},H:function(){return b()},HH:function(){return o(b())},M:function(){return x()},MM:function(){return o(x())},s:function(){return S()},ss:function(){return o(S())},l:function(){return o(C(),3)},L:function(){return o(Math.floor(C()/10))},t:function(){return b()<12?a.i18n.timeNames[0]:a.i18n.timeNames[1]},tt:function(){return b()<12?a.i18n.timeNames[2]:a.i18n.timeNames[3]},T:function(){return b()<12?a.i18n.timeNames[4]:a.i18n.timeNames[5]},TT:function(){return b()<12?a.i18n.timeNames[6]:a.i18n.timeNames[7]},Z:function(){return p?`GMT`:f?`UTC`:(String(r).match(t)||[``]).pop().replace(n,``).replace(/GMT\+0000/g,`UTC`)},o:function(){return(w()>0?`-`:`+`)+o(Math.floor(Math.abs(w())/60)*100+Math.abs(w())%60,4)},p:function(){return(w()>0?`-`:`+`)+o(Math.floor(Math.abs(w())/60),2)+`:`+o(Math.floor(Math.abs(w())%60),2)},S:function(){return[`th`,`st`,`nd`,`rd`][g()%10>3?0:(g()%100-g()%10!=10)*g()%10]},W:function(){return T()},WW:function(){return o(T())},N:function(){return E()}};return d.replace(e,function(e){return e in D?D[e]():e.slice(1,e.length-1)})}}();a.masks={default:`ddd mmm dd yyyy HH:MM:ss`,shortDate:`m/d/yy`,paddedShortDate:`mm/dd/yyyy`,mediumDate:`mmm d, yyyy`,longDate:`mmmm d, yyyy`,fullDate:`dddd, mmmm d, yyyy`,shortTime:`h:MM TT`,mediumTime:`h:MM:ss TT`,longTime:`h:MM:ss TT Z`,isoDate:`yyyy-mm-dd`,isoTime:`HH:MM:ss`,isoDateTime:`yyyy-mm-dd'T'HH:MM:sso`,isoUtcDateTime:`UTC:yyyy-mm-dd'T'HH:MM:ss'Z'`,expiresHeaderFormat:`ddd, dd mmm yyyy HH:MM:ss Z`},a.i18n={dayNames:[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],monthNames:[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`,`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],timeNames:[`a`,`p`,`am`,`pm`,`A`,`P`,`AM`,`PM`]};var o=function(e,t){for(e=String(e),t||=2;e.length<t;)e=`0`+e;return e},s=function(e){var t=e.y,n=e.m,r=e.d,i=e._,a=e.dayName,o=e.short,s=o===void 0?!1:o,c=new Date,l=new Date;l.setDate(l[i+`Date`]()-1);var u=new Date;return u.setDate(u[i+`Date`]()+1),function(){return c[i+`FullYear`]()}()===t&&function(){return c[i+`Month`]()}()===n&&function(){return c[i+`Date`]()}()===r?s?`Tdy`:`Today`:function(){return l[i+`FullYear`]()}()===t&&function(){return l[i+`Month`]()}()===n&&function(){return l[i+`Date`]()}()===r?s?`Ysd`:`Yesterday`:function(){return u[i+`FullYear`]()}()===t&&function(){return u[i+`Month`]()}()===n&&function(){return u[i+`Date`]()}()===r?s?`Tmw`:`Tomorrow`:a},c=function(e){var t=new Date(e.getFullYear(),e.getMonth(),e.getDate());t.setDate(t.getDate()-(t.getDay()+6)%7+3);var n=new Date(t.getFullYear(),0,4);n.setDate(n.getDate()-(n.getDay()+6)%7+3);var r=t.getTimezoneOffset()-n.getTimezoneOffset();t.setHours(t.getHours()-r);var i=(t-n)/(864e5*7);return 1+Math.floor(i)},l=function(e){var t=e.getDay();return t===0&&(t=7),t},u=function(e){return e===null?`null`:e===void 0?`undefined`:n(e)===`object`?Array.isArray(e)?`array`:{}.toString.call(e).slice(8,-1).toLowerCase():n(e)};typeof define==`function`&&define.amd?define(function(){return a}):(e===void 0?`undefined`:n(e))===`object`?t.exports=a:r.dateFormat=a})(void 0)})),uc=n(((e,t)=>{t.exports=s;let{DATE_FORMAT:n,DATE_FORMAT_SIMPLE:r}=Zs(),i=lc(),a=rc(),o=nc();function s(e,t=!1){if(t===!1)return e;let s=a(e);if(!o(s))return e;if(t===!0)return i(s,r);let c=t.toUpperCase();if(c===`SYS:STANDARD`)return i(s,n);let l=c.substr(0,4);return l===`SYS:`||l===`UTC:`?l===`UTC:`?i(s,t):i(s,t.slice(4)):i(s,`UTC:${t}`)}})),dc=n(((e,t)=>{t.exports=n;function n(e){return e?typeof e==`string`?e.split(`,`).reduce((e,t,n)=>{let[r,i=n]=t.split(`:`);return e[r.toLowerCase()]=i,e},{}):Object.prototype.toString.call(e)===`[object Object]`?Object.keys(e).reduce((t,n)=>(t[n.toLowerCase()]=e[n],t),{}):{}:{}}})),fc=n(((e,t)=>{t.exports=n;function n(e){return e?typeof e==`string`?e.split(`,`).reduce((e,t,n)=>{let[r,i=n]=t.split(`:`);return e[i]=r.toUpperCase(),e},{default:`USERLVL`}):Object.prototype.toString.call(e)===`[object Object]`?Object.keys(e).reduce((t,n)=>(t[e[n]]=n.toUpperCase(),t),{default:`USERLVL`}):{}:{}}})),pc=n(((e,t)=>{t.exports=r;let n=ac();function r(e,t){return e=e.replace(/{if (.*?)}(.*?){end}/g,r),e=e.replace(/{if (.*?)}/g,``),e=e.replace(/{end}/g,``),e.replace(/\s+/g,` `).trim();function r(e,r,i){let a=n(t,r);return a&&i.includes(r)?i.replace(RegExp(`{`+r+`}`,`g`),a):``}}})),mc=n(((e,t)=>{t.exports=n;function n(e){return Object.prototype.toString.apply(e)===`[object Object]`}})),hc=n(((e,t)=>{t.exports=n;function n({input:e,ident:t=` `,eol:n=`
8
+ `}){let r=e.split(/\r?\n/);for(let e=1;e<r.length;e+=1)r[e]=t+r[e];return r.join(n)}})),gc=n(((e,t)=>{t.exports=s;let{LEVEL_NAMES:n}=Zs(),r=$s(),i=fc(),a=dc(),o=Qs();function s(e){let t=e.crlf?`\r
9
9
  `:`
10
- `,{customPrettifiers:s,errorLikeObjectKeys:c,hideObject:l,levelFirst:u,levelKey:d,levelLabel:f,messageFormat:p,messageKey:m,minimumLevel:h,singleLine:g,timestampKey:_,translateTime:v}=e,y=e.errorProps.split(`,`),b=typeof e.useOnlyCustomProps==`boolean`?e.useOnlyCustomProps:e.useOnlyCustomProps===`true`,x=i(e.customLevels),S=a(e.customLevels),C=o(b,x,S),w;if(e.customColors)if(typeof e.customColors==`string`)w=e.customColors.split(`,`).reduce((t,r)=>{let[i,a]=r.split(`:`),o=(b?e.customLevels:S[i]!==void 0)?S[i]:n[i],s=o===void 0?i:o;return t.push([s,a]),t},[]);else if(typeof e.customColors==`object`)w=Object.keys(e.customColors).reduce((t,r)=>{let[i,a]=[r,e.customColors[r]],o=(b?e.customLevels:S[i]!==void 0)?S[i]:n[i],s=o===void 0?i:o;return t.push([s,a]),t},[]);else throw Error(`options.customColors must be of type string or object.`);let T={customLevels:x,customLevelNames:S};b===!0&&!e.customLevels&&(T.customLevels=void 0,T.customLevelNames=void 0);let E=e.include===void 0?void 0:new Set(e.include.split(`,`)),D=!E&&e.ignore?new Set(e.ignore.split(`,`)):void 0,O=r(e.colorize,w,b),k=e.colorizeObjects?O:r(!1,[],!1);return{EOL:t,IDENT:` `,colorizer:O,customColors:w,customLevelNames:S,customLevels:x,customPrettifiers:s,customProperties:T,errorLikeObjectKeys:c,errorProps:y,getLevelLabelData:C,hideObject:l,ignoreKeys:D,includeKeys:E,levelFirst:u,levelKey:d,levelLabel:f,messageFormat:p,messageKey:m,minimumLevel:h,objectColorizer:k,singleLine:g,timestampKey:_,translateTime:v,useOnlyCustomProps:b}}})),hc=n(((e,t)=>{t.exports=s,s.default=s,s.stable=d,s.stableStringify=d;var n=`[...]`,r=`[Circular]`,i=[],a=[];function o(){return{depthLimit:2**53-1,edgesLimit:2**53-1}}function s(e,t,n,r){r===void 0&&(r=o()),l(e,``,0,[],void 0,0,r);var s;try{s=a.length===0?JSON.stringify(e,t,n):JSON.stringify(e,p(t),n)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;i.length!==0;){var c=i.pop();c.length===4?Object.defineProperty(c[0],c[1],c[3]):c[0][c[1]]=c[2]}}return s}function c(e,t,n,r){var o=Object.getOwnPropertyDescriptor(r,n);o.get===void 0?(r[n]=e,i.push([r,n,t])):o.configurable?(Object.defineProperty(r,n,{value:e}),i.push([r,n,t,o])):a.push([t,n,e])}function l(e,t,i,a,o,s,u){s+=1;var d;if(typeof e==`object`&&e){for(d=0;d<a.length;d++)if(a[d]===e){c(r,e,t,o);return}if(u.depthLimit!==void 0&&s>u.depthLimit){c(n,e,t,o);return}if(u.edgesLimit!==void 0&&i+1>u.edgesLimit){c(n,e,t,o);return}if(a.push(e),Array.isArray(e))for(d=0;d<e.length;d++)l(e[d],d,d,a,e,s,u);else{var f=Object.keys(e);for(d=0;d<f.length;d++){var p=f[d];l(e[p],p,d,a,e,s,u)}}a.pop()}}function u(e,t){return e<t?-1:e>t?1:0}function d(e,t,n,r){r===void 0&&(r=o());var s=f(e,``,0,[],void 0,0,r)||e,c;try{c=a.length===0?JSON.stringify(s,t,n):JSON.stringify(s,p(t),n)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;i.length!==0;){var l=i.pop();l.length===4?Object.defineProperty(l[0],l[1],l[3]):l[0][l[1]]=l[2]}}return c}function f(e,t,a,o,s,l,d){l+=1;var p;if(typeof e==`object`&&e){for(p=0;p<o.length;p++)if(o[p]===e){c(r,e,t,s);return}try{if(typeof e.toJSON==`function`)return}catch{return}if(d.depthLimit!==void 0&&l>d.depthLimit){c(n,e,t,s);return}if(d.edgesLimit!==void 0&&a+1>d.edgesLimit){c(n,e,t,s);return}if(o.push(e),Array.isArray(e))for(p=0;p<e.length;p++)f(e[p],p,p,o,e,l,d);else{var m={},h=Object.keys(e).sort(u);for(p=0;p<h.length;p++){var g=h[p];f(e[g],g,p,o,e,l,d),m[g]=e[g]}if(s!==void 0)i.push([s,t,e]),s[t]=m;else return m}o.pop()}}function p(e){return e=e===void 0?function(e,t){return t}:e,function(t,n){if(a.length>0)for(var r=0;r<a.length;r++){var i=a[r];if(i[1]===t&&i[0]===n){n=i[2],a.splice(r,1);break}}return e.call(this,t,n)}}})),gc=n(((e,t)=>{t.exports=r;let n=pc();function r({keyName:e,lines:t,eol:r,ident:i}){let a=``,o=`${i}${e}: ${n({input:t,ident:i,eol:r})}${r}`.split(r);for(let e=0;e<o.length;e+=1){e!==0&&(a+=r);let t=o[e];if(/^\s*"stack"/.test(t)){let e=/^(\s*"stack":)\s*(".*"),?$/.exec(t);if(e&&e.length===3){let n=/^\s*/.exec(t)[0].length+4,i=` `.repeat(n),o=e[2];a+=e[1]+r+i+JSON.parse(o).replace(/\n/g,r+i)}else a+=t}else a+=t}return a}})),_c=n(((e,t)=>{t.exports=o;let{LOGGER_KEYS:n}=Ys(),r=hc(),i=pc(),a=gc();function o({log:e,excludeLoggerKeys:t=!0,skipKeys:o=[],context:s}){let{EOL:c,IDENT:l,customPrettifiers:u,errorLikeObjectKeys:d,objectColorizer:f,singleLine:p,colorizer:m}=s,h=[].concat(o);t===!0&&Array.prototype.push.apply(h,n);let g=``,{plain:_,errors:v}=Object.entries(e).reduce(({plain:t,errors:n},[r,i])=>{if(h.includes(r)===!1){let a=typeof u[r]==`function`?u[r](i,r,e,{colors:m.colors}):i;d.includes(r)?n[r]=a:t[r]=a}return{plain:t,errors:n}},{plain:{},errors:{}});return p?(Object.keys(_).length>0&&(g+=f.greyMessage(r(_))),g+=c,g=g.replace(/\\\\/gi,`\\`)):Object.entries(_).forEach(([e,t])=>{let n=typeof u[e]==`function`?t:r(t,null,2);if(n===void 0)return;n=n.replace(/\\\\/gi,`\\`);let a=i({input:n,ident:l,eol:c});g+=`${l}${f.property(e)}:${a.startsWith(c)?``:` `}${a}${c}`}),Object.entries(v).forEach(([e,t])=>{let n=typeof u[e]==`function`?t:r(t,null,2);n!==void 0&&(g+=a({keyName:e,lines:n,eol:c,ident:l}))}),g}})),vc=n(((e,t)=>{t.exports=o;let{LOGGER_KEYS:n}=Ys(),r=fc(),i=pc(),a=_c();function o({log:e,context:t}){let{EOL:o,IDENT:s,errorProps:c,messageKey:l}=t,u=e.stack,d=`${s}${i({input:u,ident:s,eol:o})}${o}`;if(c.length>0){let i=n.concat(l,`type`,`stack`),u;u=c[0]===`*`?Object.keys(e).filter(e=>i.includes(e)===!1):c.filter(e=>i.includes(e)===!1);for(let n=0;n<u.length;n+=1){let i=u[n];if(i in e){if(r(e[i])){let n=a({log:e[i],excludeLoggerKeys:!1,context:{...t,IDENT:s+s}});d=`${d}${s}${i}: {${o}${n}${s}}${o}`;continue}d=`${d}${s}${i}: ${e[i]}${o}`}}}return d}})),yc=n(((e,t)=>{t.exports=r;let n=rc();function r({log:e,context:t}){let{colorizer:r,customLevels:i,customLevelNames:a,levelKey:o,getLevelLabelData:s}=t,c=t.customPrettifiers?.level,l=n(e,o);if(l===void 0)return;let u=r(l,{customLevels:i,customLevelNames:a});if(c){let[t]=s(l);return c(l,o,e,{label:t,labelColorized:u,colors:r.colors})}return u}})),bc=n(((e,t)=>{t.exports=a;let{LEVELS:n}=Ys(),r=rc(),i=dc();function a({log:e,context:t}){let{colorizer:a,customLevels:o,levelKey:s,levelLabel:c,messageFormat:l,messageKey:u,useOnlyCustomProps:d}=t;if(l&&typeof l==`string`){let t=i(l,e),u=String(t).replace(/{([^{}]+)}/g,function(t,i){let a;if(i===c&&(a=r(e,s))!==void 0)return(d?o===void 0:o[a]===void 0)?n[a]:o[a];let l=r(e,i);return l===void 0?``:l});return a.message(u)}if(l&&typeof l==`function`){let t=l(e,u,c,{colors:a.colors});return a.message(t)}if(u in e&&!(typeof e[u]!=`string`&&typeof e[u]!=`number`&&typeof e[u]!=`boolean`))return a.message(e[u])}})),xc=n(((e,t)=>{t.exports=n;function n({log:e,context:t}){let{customPrettifiers:n,colorizer:r}=t,i=``;if(e.name||e.pid||e.hostname){if(i+=`(`,e.name&&(i+=n.name?n.name(e.name,`name`,e,{colors:r.colors}):e.name),e.pid){let t=n.pid?n.pid(e.pid,`pid`,e,{colors:r.colors}):e.pid;e.name&&e.pid?i+=`/`+t:i+=t}if(e.hostname){let t=n.hostname?n.hostname(e.hostname,`hostname`,e,{colors:r.colors}):e.hostname;i+=`${i===`(`?`on`:` on`} ${t}`}i+=`)`}if(e.caller){let t=n.caller?n.caller(e.caller,`caller`,e,{colors:r.colors}):e.caller;i+=`${i===``?``:` `}<${t}>`}if(i!==``)return i}})),Sc=n(((e,t)=>{t.exports=r;let n=cc();function r({log:e,context:t}){let{timestampKey:r,translateTime:i}=t,a=t.customPrettifiers?.time,o=null;if(r in e?o=e[r]:`timestamp`in e&&(o=e.timestamp),o===null)return;let s=i?n(o,i):o;return a?a(s):`[${s}]`}})),Cc=n(((e,t)=>{t.exports={buildSafeSonicBoom:$s(),createDate:tc(),deleteLogProperty:ic(),filterLog:oc(),formatTime:cc(),getPropertyValue:rc(),handleCustomLevelsNamesOpts:lc(),handleCustomLevelsOpts:uc(),interpretConditionals:dc(),isObject:fc(),isValidDate:ec(),joinLinesWithIndentation:pc(),noop:Qs(),parseFactoryOptions:mc(),prettifyErrorLog:vc(),prettifyError:gc(),prettifyLevel:yc(),prettifyMessage:bc(),prettifyMetadata:xc(),prettifyObject:_c(),prettifyTime:Sc(),splitPropertyKey:nc(),getLevelLabelData:Xs()}})),wc=n(((e,t)=>{let n=typeof Buffer<`u`,r=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,i=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function a(e,t,a){a==null&&typeof t==`object`&&t&&(a=t,t=void 0),n&&Buffer.isBuffer(e)&&(e=e.toString()),e&&e.charCodeAt(0)===65279&&(e=e.slice(1));let s=JSON.parse(e,t);if(typeof s!=`object`||!s)return s;let c=a&&a.protoAction||`error`,l=a&&a.constructorAction||`error`;if(c===`ignore`&&l===`ignore`)return s;if(c!==`ignore`&&l!==`ignore`){if(r.test(e)===!1&&i.test(e)===!1)return s}else if(c!==`ignore`&&l===`ignore`){if(r.test(e)===!1)return s}else if(i.test(e)===!1)return s;return o(s,{protoAction:c,constructorAction:l,safe:a&&a.safe})}function o(e,{protoAction:t=`error`,constructorAction:n=`error`,safe:r}={}){let i=[e];for(;i.length;){let e=i;i=[];for(let a of e){if(t!==`ignore`&&Object.prototype.hasOwnProperty.call(a,`__proto__`)){if(r===!0)return null;if(t===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete a.__proto__}if(n!==`ignore`&&Object.prototype.hasOwnProperty.call(a,`constructor`)&&a.constructor!==null&&typeof a.constructor==`object`&&Object.prototype.hasOwnProperty.call(a.constructor,`prototype`)){if(r===!0)return null;if(n===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete a.constructor}for(let e in a){let t=a[e];t&&typeof t==`object`&&i.push(t)}}}return e}function s(e,t,n){let{stackTraceLimit:r}=Error;Error.stackTraceLimit=0;try{return a(e,t,n)}finally{Error.stackTraceLimit=r}}function c(e,t){let{stackTraceLimit:n}=Error;Error.stackTraceLimit=0;try{return a(e,t,{safe:!0})}catch{return}finally{Error.stackTraceLimit=n}}t.exports=s,t.exports.default=s,t.exports.parse=s,t.exports.safeParse=c,t.exports.scan=o})),Tc=n(((e,t)=>{t.exports=h;let n=wc(),r=fc(),i=vc(),a=yc(),o=bc(),s=xc(),c=_c(),l=Sc(),u=oc(),{LEVELS:d,LEVEL_KEY:f,LEVEL_NAMES:p}=Ys(),m=e=>{try{return{value:n.parse(e,{protoAction:`remove`})}}catch(e){return{err:e}}};function h(e){let t;if(r(e))t=e;else{let n=m(e);if(n.err||!r(n.value))return e+this.EOL;t=n.value}if(this.minimumLevel){let e;e=this.useOnlyCustomProps?this.customLevels:this.customLevelNames[this.minimumLevel]!==void 0;let n;if(n=e?this.customLevelNames[this.minimumLevel]:p[this.minimumLevel],n||=typeof this.minimumLevel==`string`?p[this.minimumLevel]:p[d[this.minimumLevel].toLowerCase()],t[this.levelKey===void 0?f:this.levelKey]<n)return}let n=o({log:t,context:this.context});(this.ignoreKeys||this.includeKeys)&&(t=u({log:t,context:this.context}));let h=a({log:t,context:{...this.context,...this.context.customProperties}}),g=s({log:t,context:this.context}),_=l({log:t,context:this.context}),v=``;if(this.levelFirst&&h&&(v=`${h}`),_&&v===``?v=`${_}`:_&&(v=`${v} ${_}`),!this.levelFirst&&h&&(v=v.length>0?`${v} ${h}`:h),g&&(v=v.length>0?`${v} ${g}:`:g),v.endsWith(`:`)===!1&&v!==``&&(v+=`:`),n!==void 0&&(v=v.length>0?`${v} ${n}`:n),v.length>0&&!this.singleLine&&(v+=this.EOL),t.type===`Error`&&typeof t.stack==`string`){let e=i({log:t,context:this.context});this.singleLine&&(v+=this.EOL),v+=e}else if(this.hideObject===!1){let e=[this.messageKey,this.levelKey,this.timestampKey].map(e=>e.replaceAll(/\\/g,``)).filter(e=>typeof t[e]==`string`||typeof t[e]==`number`||typeof t[e]==`boolean`),n=c({log:t,skipKeys:e,context:this.context});this.singleLine&&!/^\s$/.test(n)&&(v+=` `),v+=n}return v}})),Ec=n(((e,n)=>{let{isColorSupported:r}=Hs(),i=Ks(),{Transform:a}=t(`node:stream`),o=Js(),s=Zs(),{ERROR_LIKE_KEYS:c,LEVEL_KEY:l,LEVEL_LABEL:u,MESSAGE_KEY:d,TIMESTAMP_KEY:f}=Ys(),{buildSafeSonicBoom:p,parseFactoryOptions:m}=Cc(),h=Tc(),g={colorize:r,colorizeObjects:!0,crlf:!1,customColors:null,customLevels:null,customPrettifiers:{},errorLikeObjectKeys:c,errorProps:``,hideObject:!1,ignore:`hostname`,include:void 0,levelFirst:!1,levelKey:l,levelLabel:u,messageFormat:null,messageKey:d,minimumLevel:void 0,outputStream:process.stdout,singleLine:!1,timestampKey:f,translateTime:!0,useOnlyCustomProps:!0};function _(e){let t=m(Object.assign({},g,e));return h.bind({...t,context:t})}function v(e={}){let t=_(e),n;return o(function(r){r.on(`message`,function n(i){!i||i.code!==`PINO_CONFIG`||(Object.assign(e,{messageKey:i.config.messageKey,errorLikeObjectKeys:Array.from(new Set([...e.errorLikeObjectKeys||c,i.config.errorKey])),customLevels:i.config.levels.values}),t=_(e),r.off(`message`,n))});let o=new a({objectMode:!0,autoDestroy:!0,transform(e,n,r){r(null,t(e))}});return n=typeof e.destination==`object`&&typeof e.destination.write==`function`?e.destination:p({dest:e.destination||1,append:e.append,mkdir:e.mkdir,sync:e.sync}),r.on(`unknown`,function(e){n.write(e+`
11
- `)}),i(r,o,n),o},{parse:`lines`,close(e,t){n.on(`close`,()=>{t(e)})}})}n.exports=v,n.exports.build=v,n.exports.PinoPretty=v,n.exports.prettyFactory=_,n.exports.colorizerFactory=s,n.exports.isColorSupported=r,n.exports.default=v})),Dc=e(Vs(),1),Oc=e(Ec(),1);function kc(){return process.env.NO_COLOR&&process.env.NO_COLOR!==``?!1:process.stdout.isTTY??!1}var Ac=class{name;transportConfigs=[];pinoInstance;options;constructor(e,t={}){this.name=e,this.options={name:this.name,level:process.env.LOG_LEVEL||(process.env.NODE_ENV===`test`?`silent`:`info`),serializers:{err:Dc.default.stdSerializers.err,error:Dc.default.stdSerializers.err},...t.options},t.transportConfigs&&(this.transportConfigs=t.transportConfigs),this.pinoInstance=this.buildInstance()}buildInstance(){if(this.transportConfigs.length>0)return(0,Dc.default)(this.options,Dc.default.transport({targets:this.transportConfigs}));try{let e=(0,Oc.default)({colorize:kc(),translateTime:`HH:MM:ss`,ignore:`pid,hostname`});return(0,Dc.default)(this.options,e)}catch(e){return console.warn(`[PinoLogger] pino-pretty failed, falling back to JSON:`,e),(0,Dc.default)(this.options)}}recreateInstance(){typeof this.pinoInstance.flush==`function`&&this.pinoInstance.flush(),this.pinoInstance=this.buildInstance()}addTransport(e){this.transportConfigs.push(e),this.recreateInstance()}removeTransport(e){e>=0&&e<this.transportConfigs.length&&(this.transportConfigs.splice(e,1),this.recreateInstance())}getTransports(){return[...this.transportConfigs]}updateOptions(e){this.options={...this.options,...e},this.recreateInstance()}getPinoInstance(){return this.pinoInstance}error(e,t){this.pinoInstance.error(e,t)}warn(e,t){this.pinoInstance.warn(e,t)}info(e,t){this.pinoInstance.info(e,t)}debug(e,t){this.pinoInstance.debug(e,t)}};const jc=new class{config={};loggers=new Map;configure(e){this.config=e,this.loggers.clear()}getLogger(e){let t=this.loggers.get(e);if(t)return t;let n;return n=this.config.loggerFactory?this.config.loggerFactory(e):this.config.defaultLogger?this.config.defaultLogger:new Ac(e,this.config.pinoConfig),this.loggers.set(e,n),n}reset(){this.config={},this.loggers.clear()}};function Mc(e){return jc.getLogger(e)}const K={reconcileCount:0,conflictCount:0,batchCount:0,upstreamImportCount:0,rescueBufferCount:0,branchSwitchCount:0,parkCount:0,gitAutoSaveFailureCount:0,cc1BroadcastCount:0,cc1BroadcastDropCount:0,cc1SubscriberCount:0,cc1LastSeq:{},serverObserverFiresA:0,serverObserverFiresB:0,serverObserverErrorsA:0,serverObserverErrorsB:0,persistenceDiskWrites:0,bridgeMergeContentLoss:0,bridgeMergeCheckpointCreated:0,collabSocketEpipeCount:0,collabSocketEconnresetCount:0};function Nc(){K.reconcileCount++}function Pc(){K.conflictCount++}function Fc(){K.batchCount++}function Ic(){K.upstreamImportCount++}function Lc(){K.rescueBufferCount++}function Rc(){K.branchSwitchCount++}function zc(){K.parkCount++}function Bc(){K.gitAutoSaveFailureCount++}function Vc(){K.cc1BroadcastCount++}function Hc(){K.cc1BroadcastDropCount++}function Uc(e){K.cc1SubscriberCount=e}function Wc(e){e===`a`?K.serverObserverFiresA++:K.serverObserverFiresB++}function Gc(){K.persistenceDiskWrites++}function Kc(e){e===`a`?K.serverObserverErrorsA++:K.serverObserverErrorsB++}function qc(){K.bridgeMergeContentLoss++}function Jc(){K.bridgeMergeCheckpointCreated++}function Yc(e){e===`EPIPE`?K.collabSocketEpipeCount++:K.collabSocketEconnresetCount++}function Xc(e){return e.code===`EPIPE`||e.code===`ECONNRESET`?(Yc(e.code),!0):!1}function Zc(e,t){K.cc1LastSeq[e]=t}function Qc(){return{...K,cc1LastSeq:{...K.cc1LastSeq}}}function q(e){return e===r}var $c=class{hocuspocus;seqs=new Map;timers=new Map;log=Mc(`cc1`);warnedMissing=!1;constructor(e){this.hocuspocus=e}signal(e){let t=this.timers.get(e);t!==void 0&&clearTimeout(t),this.timers.set(e,setTimeout(()=>{this.timers.delete(e),this.broadcast(e)},100))}broadcast(e){try{let t=this.hocuspocus.documents.get(r);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found — broadcasts will be dropped until it is materialized`),!0),Hc();return}let n=(this.seqs.get(e)??0)+1;this.seqs.set(e,n);let i={v:1,ch:e,seq:n};t.broadcastStateless(JSON.stringify(i)),Vc(),Zc(e,n),Uc(t.getConnectionsCount())}catch(t){this.log.error({err:t,channel:e},`[cc1] broadcast failed`)}}get subscriberCount(){let e=this.hocuspocus.documents.get(r);return e?e.getConnectionsCount():0}destroy(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};const el=new m({extensions:O}),tl=o(O),nl=Mc(`agent-sessions`),rl={source:`local`,skipStoreHooks:!1,context:{origin:`agent-write`,paired:!0}};function il(e){return e?{"claude-code":`claude`,"claude-ai":`claude`,cursor:`cursor`,"cursor-vscode":`cursor`,cascade:`windsurf`,codex:`openai`,copilot:`github`,cline:`cline`}[e]??`bot`:`bot`}function al(e,t,n){try{let r=e.getXmlFragment(`default`),i=e.getText(`source`),a=e.getMap(`metadata`),o=fs(r,tl).toJSON(),s=el.serialize(o),c=a.get(`frontmatter`)??``,{frontmatter:l,body:d}=A(t),f,m;switch(n){case`replace`:f=l||c,m=d.trim();break;case`prepend`:f=c,m=`${d.trim()}\n\n${s}`;break;case`append`:f=c,m=s.trim()?`${s}\n\n${d.trim()}\n`:`${d.trim()}\n`;break}let h=el.parseWithFallback(m);ls(e,r,tl.nodeFromJSON(h),{mapping:new Map,isOMark:new Map}),f!==c&&a.set(`frontmatter`,f);let g=el.serialize(fs(r,tl).toJSON()),_=u(f,g);p(i,i.toString(),_)}catch(r){throw nl.error({err:r,docName:e.name,position:n,markdownLen:t.length},`[applyAgentMarkdownWrite] failed for '${e.name}'`),r}}var ol=class{sessions=new Map;hocuspocus;constructor(e){this.hocuspocus=e}sessionKey(e,t){return`${e}\0${t}`}async getSession(e,t=`claude-1`,n){if(q(e))throw Error(`Cannot create agent session for reserved doc: ${e}`);let r=this.sessionKey(e,t),i=this.sessions.get(r);if(!i){i=await this.hocuspocus.openDirectConnection(e);let a=il(n?.clientName),o=g[a]??l(n?.colorSeed??t);i.document.awareness.setLocalState({user:{name:n?.displayName??`Claude`,color:o,type:`agent`,icon:a,tabId:`agent-${t}`},mode:`idle`}),this.sessions.set(r,i),nl.info({docName:e,agentId:t},`[agent-session] Created session for: ${e} / ${t}`)}return i}hasSession(e,t=`claude-1`){return this.sessions.has(this.sessionKey(e,t))}async closeSession(e,t=`claude-1`){let n=this.sessionKey(e,t),r=this.sessions.get(n);r&&(r.document.awareness.setLocalState(null),await r.disconnect(),this.sessions.delete(n),nl.info({docName:e,agentId:t},`[agent-session] Closed session for: ${e} / ${t}`))}async closeAllForAgent(e){let t=`\0${e}`;for(let[n,r]of this.sessions)if(n.endsWith(t))try{r.document.awareness.setLocalState(null),await r.disconnect(),this.sessions.delete(n)}catch(t){nl.error({err:t,agentId:e},`[agent-session] Failed to close session for agent ${e}`)}}async closeAllForDoc(e){let t=`${e}\0`;for(let[n,r]of this.sessions)if(n.startsWith(t))try{r.document.awareness.setLocalState(null),await r.disconnect(),this.sessions.delete(n)}catch(t){nl.error({err:t,docName:e},`[agent-session] Failed to close session for doc ${e}`)}}async closeAll(e){if(e){await this.closeAllForDoc(e);return}let t=[...this.sessions.keys()];for(let e of t){let t=this.sessions.get(e);if(t)try{t.document.awareness.setLocalState(null),await t.disconnect(),this.sessions.delete(e)}catch(t){nl.error({err:t,key:e},`[agent-session] Failed to close session: ${e}`)}}}},sl=n(((e,t)=>{function n(e){if(e.length===0)return;let t=Object.create(null),n=0;for(;n<e.length;++n){let t=e.charCodeAt(n);if(u[t]!==1){if(t!==47||n===0)return;break}}if(n===e.length)return;let i=e.slice(0,n).toLowerCase(),a=++n;for(;n<e.length;++n)if(u[e.charCodeAt(n)]!==1){if(n===a||r(e,n,t)===void 0)return;break}if(n!==a)return{type:i,subtype:e.slice(a,n).toLowerCase(),params:t}}function r(e,t,n){for(;t<e.length;){for(;t<e.length;++t){let n=e.charCodeAt(t);if(n!==32&&n!==9)break}if(t===e.length)break;if(e.charCodeAt(t++)!==59)return;for(;t<e.length;++t){let n=e.charCodeAt(t);if(n!==32&&n!==9)break}if(t===e.length)return;let r,i=t;for(;t<e.length;++t){let n=e.charCodeAt(t);if(u[n]!==1){if(n!==61)return;break}}if(t===e.length||(r=e.slice(i,t),++t,t===e.length))return;let a=``,o;if(e.charCodeAt(t)===34){o=++t;let n=!1;for(;t<e.length;++t){let r=e.charCodeAt(t);if(r===92){n?(o=t,n=!1):(a+=e.slice(o,t),n=!0);continue}if(r===34){if(n){o=t,n=!1;continue}a+=e.slice(o,t);break}if(n&&=(o=t-1,!1),d[r]!==1)return}if(t===e.length)return;++t}else{for(o=t;t<e.length;++t)if(u[e.charCodeAt(t)]!==1){if(t===o)return;break}a=e.slice(o,t)}r=r.toLowerCase(),n[r]===void 0&&(n[r]=a)}return n}function i(e,t){if(e.length===0)return;let n=Object.create(null),r=0;for(;r<e.length;++r)if(u[e.charCodeAt(r)]!==1){if(a(e,r,n,t)===void 0)return;break}return{type:e.slice(0,r).toLowerCase(),params:n}}function a(e,t,n,r){for(;t<e.length;){for(;t<e.length;++t){let n=e.charCodeAt(t);if(n!==32&&n!==9)break}if(t===e.length)break;if(e.charCodeAt(t++)!==59)return;for(;t<e.length;++t){let n=e.charCodeAt(t);if(n!==32&&n!==9)break}if(t===e.length)return;let i,a=t;for(;t<e.length;++t){let n=e.charCodeAt(t);if(u[n]!==1){if(n===61)break;return}}if(t===e.length)return;let o=``,s,l;if(i=e.slice(a,t),i.charCodeAt(i.length-1)===42){let n=++t;for(;t<e.length;++t){let n=e.charCodeAt(t);if(f[n]!==1){if(n!==39)return;break}}if(t===e.length)return;for(l=e.slice(n,t),++t;t<e.length&&e.charCodeAt(t)!==39;++t);if(t===e.length||(++t,t===e.length))return;s=t;let r=0;for(;t<e.length;++t){let n=e.charCodeAt(t);if(p[n]!==1){if(n===37){let n,i;if(t+2<e.length&&(n=m[e.charCodeAt(t+1)])!==-1&&(i=m[e.charCodeAt(t+2)])!==-1){let a=(n<<4)+i;o+=e.slice(s,t),o+=String.fromCharCode(a),t+=2,s=t+1,a>=128?r=2:r===0&&(r=1);continue}return}break}}if(o+=e.slice(s,t),o=c(o,l,r),o===void 0)return}else{if(++t,t===e.length)return;if(e.charCodeAt(t)===34){s=++t;let n=!1;for(;t<e.length;++t){let r=e.charCodeAt(t);if(r===92){n?(s=t,n=!1):(o+=e.slice(s,t),n=!0);continue}if(r===34){if(n){s=t,n=!1;continue}o+=e.slice(s,t);break}if(n&&=(s=t-1,!1),d[r]!==1)return}if(t===e.length)return;++t}else{for(s=t;t<e.length;++t)if(u[e.charCodeAt(t)]!==1){if(t===s)return;break}o=e.slice(s,t)}if(o=r(o,2),o===void 0)return}i=i.toLowerCase(),n[i]===void 0&&(n[i]=o)}return n}function o(e){let t;for(;;)switch(e){case`utf-8`:case`utf8`:return s.utf8;case`latin1`:case`ascii`:case`us-ascii`:case`iso-8859-1`:case`iso8859-1`:case`iso88591`:case`iso_8859-1`:case`windows-1252`:case`iso_8859-1:1987`:case`cp1252`:case`x-cp1252`:return s.latin1;case`utf16le`:case`utf-16le`:case`ucs2`:case`ucs-2`:return s.utf16le;case`base64`:return s.base64;default:if(t===void 0){t=!0,e=e.toLowerCase();continue}return s.other.bind(e)}}let s={utf8:(e,t)=>{if(e.length===0)return``;if(typeof e==`string`){if(t<2)return e;e=Buffer.from(e,`latin1`)}return e.utf8Slice(0,e.length)},latin1:(e,t)=>e.length===0?``:typeof e==`string`?e:e.latin1Slice(0,e.length),utf16le:(e,t)=>e.length===0?``:(typeof e==`string`&&(e=Buffer.from(e,`latin1`)),e.ucs2Slice(0,e.length)),base64:(e,t)=>e.length===0?``:(typeof e==`string`&&(e=Buffer.from(e,`latin1`)),e.base64Slice(0,e.length)),other:(t,n)=>{if(t.length===0)return``;typeof t==`string`&&(t=Buffer.from(t,`latin1`));try{return new TextDecoder(e).decode(t)}catch{}}};function c(e,t,n){let r=o(t);if(r)return r(e,n)}function l(e){if(typeof e!=`string`)return``;for(let t=e.length-1;t>=0;--t)switch(e.charCodeAt(t)){case 47:case 92:return e=e.slice(t+1),e===`..`||e===`.`?``:e}return e===`..`||e===`.`?``:e}let u=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],d=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],f=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,0,0,0,0,1,0,1,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],p=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,1,0,0,0,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],m=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1];t.exports={basename:l,convertToUTF8:c,getDecoder:o,parseContentType:n,parseDisposition:i}})),cl=n(((e,t)=>{function n(e,t,n,r,i){for(let a=0;a<i;++a)if(e[t+a]!==n[r+a])return!1;return!0}var r=class{constructor(e,t){if(typeof t!=`function`)throw Error(`Missing match callback`);if(typeof e==`string`)e=Buffer.from(e);else if(!Buffer.isBuffer(e))throw Error(`Expected Buffer for needle, got ${typeof e}`);let n=e.length;if(this.maxMatches=1/0,this.matches=0,this._cb=t,this._lookbehindSize=0,this._needle=e,this._bufPos=0,this._lookbehind=Buffer.allocUnsafe(n),this._occ=[n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n],n>1)for(let t=0;t<n-1;++t)this._occ[e[t]]=n-1-t}reset(){this.matches=0,this._lookbehindSize=0,this._bufPos=0}push(e,t){let n;Buffer.isBuffer(e)||(e=Buffer.from(e,`latin1`));let r=e.length;for(this._bufPos=t||0;n!==r&&this.matches<this.maxMatches;)n=i(this,e);return n}destroy(){let e=this._lookbehindSize;e&&this._cb(!1,this._lookbehind,0,e,!1),this.reset()}};function i(e,t){let r=t.length,i=e._needle,o=i.length,s=-e._lookbehindSize,c=o-1,l=i[c],u=r-o,d=e._occ,f=e._lookbehind;if(s<0){for(;s<0&&s<=u;){let n=s+c,r=n<0?f[e._lookbehindSize+n]:t[n];if(r===l&&a(e,t,s,c))return e._lookbehindSize=0,++e.matches,s>-e._lookbehindSize?e._cb(!0,f,0,e._lookbehindSize+s,!1):e._cb(!0,void 0,0,0,!0),e._bufPos=s+o;s+=d[r]}for(;s<0&&!a(e,t,s,r-s);)++s;if(s<0){let n=e._lookbehindSize+s;return n>0&&e._cb(!1,f,0,n,!1),e._lookbehindSize-=n,f.copy(f,0,n,e._lookbehindSize),f.set(t,e._lookbehindSize),e._lookbehindSize+=r,e._bufPos=r,r}e._cb(!1,f,0,e._lookbehindSize,!1),e._lookbehindSize=0}s+=e._bufPos;let p=i[0];for(;s<=u;){let r=t[s+c];if(r===l&&t[s]===p&&n(i,0,t,s,c))return++e.matches,s>0?e._cb(!0,t,e._bufPos,s,!0):e._cb(!0,void 0,0,0,!0),e._bufPos=s+o;s+=d[r]}for(;s<r;){if(t[s]!==p||!n(t,s,i,0,r-s)){++s;continue}t.copy(f,0,s,r),e._lookbehindSize=r-s;break}return s>0&&e._cb(!1,t,e._bufPos,s<r?s:r,!0),e._bufPos=r,r}function a(e,t,n,r){let i=e._lookbehind,a=e._lookbehindSize,o=e._needle;for(let e=0;e<r;++e,++n)if((n<0?i[a+n]:t[n])!==o[e])return!1;return!0}t.exports=r})),ll=n(((e,n)=>{let{Readable:r,Writable:i}=t(`stream`),a=cl(),{basename:o,convertToUTF8:s,getDecoder:c,parseContentType:l,parseDisposition:u}=sl(),d=Buffer.from(`\r
12
- `),f=Buffer.from(`\r`),p=Buffer.from(`-`);function m(){}let h=16*1024;var g=class{constructor(e){this.header=Object.create(null),this.pairCount=0,this.byteCount=0,this.state=0,this.name=``,this.value=``,this.crlf=0,this.cb=e}reset(){this.header=Object.create(null),this.pairCount=0,this.byteCount=0,this.state=0,this.name=``,this.value=``,this.crlf=0}push(e,t,n){let r=t;for(;t<n;)switch(this.state){case 0:{let i=!1;for(;t<n;++t){if(this.byteCount===h)return-1;++this.byteCount;let n=e[t];if(w[n]!==1){if(n!==58||(this.name+=e.latin1Slice(r,t),this.name.length===0))return-1;++t,i=!0,this.state=1;break}}if(!i){this.name+=e.latin1Slice(r,t);break}}case 1:{let i=!1;for(;t<n;++t){if(this.byteCount===h)return-1;++this.byteCount;let n=e[t];if(n!==32&&n!==9){r=t,i=!0,this.state=2;break}}if(!i)break}case 2:switch(this.crlf){case 0:for(;t<n;++t){if(this.byteCount===h)return-1;++this.byteCount;let n=e[t];if(T[n]!==1){if(n!==13)return-1;++this.crlf;break}}this.value+=e.latin1Slice(r,t++);break;case 1:if(this.byteCount===h||(++this.byteCount,e[t++]!==10))return-1;++this.crlf;break;case 2:{if(this.byteCount===h)return-1;++this.byteCount;let n=e[t];n===32||n===9?(r=t,this.crlf=0):(++this.pairCount<2e3&&(this.name=this.name.toLowerCase(),this.header[this.name]===void 0?this.header[this.name]=[this.value]:this.header[this.name].push(this.value)),n===13?(++this.crlf,++t):(r=t,this.crlf=0,this.state=0,this.name=``,this.value=``));break}case 3:{if(this.byteCount===h||(++this.byteCount,e[t++]!==10))return-1;let n=this.header;return this.reset(),this.cb(n),t}}break}return t}},_=class extends r{constructor(e,t){super(e),this.truncated=!1,this._readcb=null,this.once(`end`,()=>{if(this._read(),--t._fileEndsLeft===0&&t._finalcb){let e=t._finalcb;t._finalcb=null,process.nextTick(e)}})}_read(e){let t=this._readcb;t&&(this._readcb=null,t())}};let v={push:(e,t)=>{},destroy:()=>{}};function y(e,t){let n=e._writecb;e._writecb=null,t?e.destroy(t):n&&n()}function b(e,t){return e}var x=class extends i{constructor(e){let t={autoDestroy:!0,emitClose:!0,highWaterMark:typeof e.highWaterMark==`number`?e.highWaterMark:void 0};if(super(t),!e.conType.params||typeof e.conType.params.boundary!=`string`)throw Error(`Multipart: Boundary not found`);let n=e.conType.params.boundary,r=typeof e.defParamCharset==`string`&&e.defParamCharset?c(e.defParamCharset):b,i=e.defCharset||`utf8`,h=e.preservePath,y={autoDestroy:!0,emitClose:!0,highWaterMark:typeof e.fileHwm==`number`?e.fileHwm:void 0},x=e.limits,S=x&&typeof x.fieldSize==`number`?x.fieldSize:1*1024*1024,C=x&&typeof x.fileSize==`number`?x.fileSize:1/0,w=x&&typeof x.files==`number`?x.files:1/0,T=x&&typeof x.fields==`number`?x.fields:1/0,E=x&&typeof x.parts==`number`?x.parts:1/0,D=-1,O=0,k=0,A=!1;this._fileEndsLeft=0,this._fileStream=void 0,this._complete=!1;let j=0,M,ee=0,N,te,ne,P,re=!1,F=!1,ie=!1;this._hparser=null;let ae=new g(e=>{this._hparser=null,A=!1,ne=`text/plain`,N=i,te=`7bit`,P=void 0,re=!1;let t;if(!e[`content-disposition`]){A=!0;return}let n=u(e[`content-disposition`][0],r);if(!n||n.type!==`form-data`){A=!0;return}if(n.params&&(n.params.name&&(P=n.params.name),n.params[`filename*`]?t=n.params[`filename*`]:n.params.filename&&(t=n.params.filename),t!==void 0&&!h&&(t=o(t))),e[`content-type`]){let t=l(e[`content-type`][0]);t&&(ne=`${t.type}/${t.subtype}`,t.params&&typeof t.params.charset==`string`&&(N=t.params.charset.toLowerCase()))}if(e[`content-transfer-encoding`]&&(te=e[`content-transfer-encoding`][0].toLowerCase()),ne===`application/octet-stream`||t!==void 0){if(k===w){F||(F=!0,this.emit(`filesLimit`)),A=!0;return}if(++k,this.listenerCount(`file`)===0){A=!0;return}j=0,this._fileStream=new _(y,this),++this._fileEndsLeft,this.emit(`file`,P,this._fileStream,{filename:t,encoding:te,mimeType:ne})}else{if(O===T){ie||(ie=!0,this.emit(`fieldsLimit`)),A=!0;return}if(++O,this.listenerCount(`field`)===0){A=!0;return}M=[],ee=0}}),I=0,oe=(e,t,n,r,i)=>{retrydata:for(;t;){if(this._hparser!==null){let e=this._hparser.push(t,n,r);if(e===-1){this._hparser=null,ae.reset(),this.emit(`error`,Error(`Malformed part header`));break}n=e}if(n===r)break;if(I!==0){if(I===1){switch(t[n]){case 45:I=2,++n;break;case 13:I=3,++n;break;default:I=0}if(n===r)return}if(I===2){if(I=0,t[n]===45){this._complete=!0,this._bparser=v;return}let e=this._writecb;this._writecb=m,oe(!1,p,0,1,!1),this._writecb=e}else if(I===3)if(I=0,t[n]===10){if(++n,D>=E||(this._hparser=ae,n===r))break;continue retrydata}else{let e=this._writecb;this._writecb=m,oe(!1,f,0,1,!1),this._writecb=e}}if(!A){if(this._fileStream){let e,a=Math.min(r-n,C-j);i?e=t.slice(n,n+a):(e=Buffer.allocUnsafe(a),t.copy(e,0,n,n+a)),j+=e.length,j===C?(e.length>0&&this._fileStream.push(e),this._fileStream.emit(`limit`),this._fileStream.truncated=!0,A=!0):this._fileStream.push(e)||(this._writecb&&(this._fileStream._readcb=this._writecb),this._writecb=null)}else if(M!==void 0){let e,a=Math.min(r-n,S-ee);i?e=t.slice(n,n+a):(e=Buffer.allocUnsafe(a),t.copy(e,0,n,n+a)),ee+=a,M.push(e),ee===S&&(A=!0,re=!0)}}break}if(e){if(I=1,this._fileStream)this._fileStream.push(null),this._fileStream=null;else if(M!==void 0){let e;switch(M.length){case 0:e=``;break;case 1:e=s(M[0],N,0);break;default:e=s(Buffer.concat(M,ee),N,0)}M=void 0,ee=0,this.emit(`field`,P,e,{nameTruncated:!1,valueTruncated:re,encoding:te,mimeType:ne})}++D===E&&this.emit(`partsLimit`)}};this._bparser=new a(`\r\n--${n}`,oe),this._writecb=null,this._finalcb=null,this.write(d)}static detect(e){return e.type===`multipart`&&e.subtype===`form-data`}_write(e,t,n){this._writecb=n,this._bparser.push(e,0),this._writecb&&y(this)}_destroy(e,t){this._hparser=null,this._bparser=v,e||=C(this);let n=this._fileStream;n&&(this._fileStream=null,n.destroy(e)),t(e)}_final(e){if(this._bparser.destroy(),!this._complete)return e(Error(`Unexpected end of form`));this._fileEndsLeft?this._finalcb=S.bind(null,this,e):S(this,e)}};function S(e,t,n){if(n)return t(n);n=C(e),t(n)}function C(e){if(e._hparser)return Error(`Malformed part header`);let t=e._fileStream;if(t&&(e._fileStream=null,t.destroy(Error(`Unexpected end of file`))),!e._complete)return Error(`Unexpected end of form`)}let w=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],T=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];n.exports=x})),ul=n(((e,n)=>{let{Writable:r}=t(`stream`),{getDecoder:i}=sl();var a=class extends r{constructor(e){let t={autoDestroy:!0,emitClose:!0,highWaterMark:typeof e.highWaterMark==`number`?e.highWaterMark:void 0};super(t);let n=e.defCharset||`utf8`;e.conType.params&&typeof e.conType.params.charset==`string`&&(n=e.conType.params.charset),this.charset=n;let r=e.limits;this.fieldSizeLimit=r&&typeof r.fieldSize==`number`?r.fieldSize:1*1024*1024,this.fieldsLimit=r&&typeof r.fields==`number`?r.fields:1/0,this.fieldNameSizeLimit=r&&typeof r.fieldNameSize==`number`?r.fieldNameSize:100,this._inKey=!0,this._keyTrunc=!1,this._valTrunc=!1,this._bytesKey=0,this._bytesVal=0,this._fields=0,this._key=``,this._val=``,this._byte=-2,this._lastPos=0,this._encode=0,this._decoder=i(n)}static detect(e){return e.type===`application`&&e.subtype===`x-www-form-urlencoded`}_write(e,t,n){if(this._fields>=this.fieldsLimit)return n();let r=0,i=e.length;if(this._lastPos=0,this._byte!==-2){if(r=o(this,e,r,i),r===-1)return n(Error(`Malformed urlencoded form`));if(r>=i)return n();this._inKey?++this._bytesKey:++this._bytesVal}main:for(;r<i;)if(this._inKey){for(r=s(this,e,r,i);r<i;){switch(e[r]){case 61:this._lastPos<r&&(this._key+=e.latin1Slice(this._lastPos,r)),this._lastPos=++r,this._key=this._decoder(this._key,this._encode),this._encode=0,this._inKey=!1;continue main;case 38:if(this._lastPos<r&&(this._key+=e.latin1Slice(this._lastPos,r)),this._lastPos=++r,this._key=this._decoder(this._key,this._encode),this._encode=0,this._bytesKey>0&&this.emit(`field`,this._key,``,{nameTruncated:this._keyTrunc,valueTruncated:!1,encoding:this.charset,mimeType:`text/plain`}),this._key=``,this._val=``,this._keyTrunc=!1,this._valTrunc=!1,this._bytesKey=0,this._bytesVal=0,++this._fields>=this.fieldsLimit)return this.emit(`fieldsLimit`),n();continue;case 43:this._lastPos<r&&(this._key+=e.latin1Slice(this._lastPos,r)),this._key+=` `,this._lastPos=r+1;break;case 37:if(this._encode===0&&(this._encode=1),this._lastPos<r&&(this._key+=e.latin1Slice(this._lastPos,r)),this._lastPos=r+1,this._byte=-1,r=o(this,e,r+1,i),r===-1)return n(Error(`Malformed urlencoded form`));if(r>=i)return n();++this._bytesKey,r=s(this,e,r,i);continue}++r,++this._bytesKey,r=s(this,e,r,i)}this._lastPos<r&&(this._key+=e.latin1Slice(this._lastPos,r))}else{for(r=c(this,e,r,i);r<i;){switch(e[r]){case 38:if(this._lastPos<r&&(this._val+=e.latin1Slice(this._lastPos,r)),this._lastPos=++r,this._inKey=!0,this._val=this._decoder(this._val,this._encode),this._encode=0,(this._bytesKey>0||this._bytesVal>0)&&this.emit(`field`,this._key,this._val,{nameTruncated:this._keyTrunc,valueTruncated:this._valTrunc,encoding:this.charset,mimeType:`text/plain`}),this._key=``,this._val=``,this._keyTrunc=!1,this._valTrunc=!1,this._bytesKey=0,this._bytesVal=0,++this._fields>=this.fieldsLimit)return this.emit(`fieldsLimit`),n();continue main;case 43:this._lastPos<r&&(this._val+=e.latin1Slice(this._lastPos,r)),this._val+=` `,this._lastPos=r+1;break;case 37:if(this._encode===0&&(this._encode=1),this._lastPos<r&&(this._val+=e.latin1Slice(this._lastPos,r)),this._lastPos=r+1,this._byte=-1,r=o(this,e,r+1,i),r===-1)return n(Error(`Malformed urlencoded form`));if(r>=i)return n();++this._bytesVal,r=c(this,e,r,i);continue}++r,++this._bytesVal,r=c(this,e,r,i)}this._lastPos<r&&(this._val+=e.latin1Slice(this._lastPos,r))}n()}_final(e){if(this._byte!==-2)return e(Error(`Malformed urlencoded form`));(!this._inKey||this._bytesKey>0||this._bytesVal>0)&&(this._inKey?this._key=this._decoder(this._key,this._encode):this._val=this._decoder(this._val,this._encode),this.emit(`field`,this._key,this._val,{nameTruncated:this._keyTrunc,valueTruncated:this._valTrunc,encoding:this.charset,mimeType:`text/plain`})),e()}};function o(e,t,n,r){if(n>=r)return r;if(e._byte===-1){let i=l[t[n++]];if(i===-1)return-1;if(i>=8&&(e._encode=2),n<r){let r=l[t[n++]];if(r===-1)return-1;e._inKey?e._key+=String.fromCharCode((i<<4)+r):e._val+=String.fromCharCode((i<<4)+r),e._byte=-2,e._lastPos=n}else e._byte=i}else{let r=l[t[n++]];if(r===-1)return-1;e._inKey?e._key+=String.fromCharCode((e._byte<<4)+r):e._val+=String.fromCharCode((e._byte<<4)+r),e._byte=-2,e._lastPos=n}return n}function s(e,t,n,r){if(e._bytesKey>e.fieldNameSizeLimit){for(e._keyTrunc||e._lastPos<n&&(e._key+=t.latin1Slice(e._lastPos,n-1)),e._keyTrunc=!0;n<r;++n){let r=t[n];if(r===61||r===38)break;++e._bytesKey}e._lastPos=n}return n}function c(e,t,n,r){if(e._bytesVal>e.fieldSizeLimit){for(e._valTrunc||e._lastPos<n&&(e._val+=t.latin1Slice(e._lastPos,n-1)),e._valTrunc=!0;n<r&&t[n]!==38;++n)++e._bytesVal;e._lastPos=n}return n}let l=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1];n.exports=a})),dl=n(((e,t)=>{let{parseContentType:n}=sl();function r(e){let t=e.headers,r=n(t[`content-type`]);if(!r)throw Error(`Malformed content type`);for(let n of i){if(!n.detect(r))continue;let i={limits:e.limits,headers:t,conType:r,highWaterMark:void 0,fileHwm:void 0,defCharset:void 0,defParamCharset:void 0,preservePath:!1};return e.highWaterMark&&(i.highWaterMark=e.highWaterMark),e.fileHwm&&(i.fileHwm=e.fileHwm),i.defCharset=e.defCharset,i.defParamCharset=e.defParamCharset,i.preservePath=e.preservePath,new n(i)}throw Error(`Unsupported content type: ${t[`content-type`]}`)}let i=[ll(),ul()].filter(function(e){return typeof e.detect==`function`});t.exports=e=>{if((typeof e!=`object`||!e)&&(e={}),typeof e.headers!=`object`||e.headers===null||typeof e.headers[`content-type`]!=`string`)throw Error(`Missing Content-Type`);return r(e)}})),fl=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}else return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h){d[r]=void 0;continue}if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}};new class extends fl{};function pl(e,t){let n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function ml(e,t){let n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function hl(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function gl(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function _l(e,t){return hl(e,t,``)}function vl(e,t){return gl(e,t,``)}function yl(e,t){return t.slice(0,bl(e,t))}function bl(e,t){let n=0;e.length>t.length&&(n=e.length-t.length);let r=t.length;e.length<t.length&&(r=e.length);let i=Array(r),a=0;i[0]=0;for(let e=1;e<r;e++){for(t[e]==t[a]?i[e]=i[a]:i[e]=a;a>0&&t[e]!=t[a];)a=i[a];t[e]==t[a]&&a++}a=0;for(let r=n;r<e.length;r++){for(;a>0&&e[r]!=t[a];)a=i[a];e[r]==t[a]&&a++}return a}function xl(e,t){let n=[];for(let r of Array.from(t.segment(e))){let e=r.segment;n.length&&/\s/.test(n[n.length-1])&&/\s/.test(e)?n[n.length-1]+=e:n.push(e)}return n}function Sl(e,t){if(t)return wl(e,t)[1];let n;for(n=e.length-1;n>=0&&e[n].match(/\s/);n--);return e.substring(n+1)}function Cl(e,t){if(t)return wl(e,t)[0];let n=e.match(/^\s*/);return n?n[0]:``}function wl(e,t){if(!t)return[Cl(e),Sl(e)];if(t.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);let n=xl(e,t),r=n[0],i=n[n.length-1];return[/\s/.test(r)?r:``,/\s/.test(i)?i:``]}const Tl=`a-zA-Z0-9_\\u{AD}\\u{C0}-\\u{D6}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,El=RegExp(`[${Tl}]+|\\s+|[^${Tl}]`,`ug`);new class extends fl{equals(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()}tokenize(e,t={}){let n;if(t.intlSegmenter){let r=t.intlSegmenter;if(r.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=xl(e,r)}else n=e.match(El)||[];let r=[],i=null;return n.forEach(e=>{/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):i!=null&&/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r}join(e){return e.map((e,t)=>t==0?e:e.replace(/^\s+/,``)).join(``)}postProcess(e,t){if(!e||t.oneChangePerToken)return e;let n=null,r=null,i=null;return e.forEach(e=>{e.added?r=e:e.removed?i=e:((r||i)&&Dl(n,i,r,e,t.intlSegmenter),n=e,r=null,i=null)}),(r||i)&&Dl(n,i,r,null,t.intlSegmenter),e}};function Dl(e,t,n,r,i){if(t&&n){let[a,o]=wl(t.value,i),[s,c]=wl(n.value,i);if(e){let r=pl(a,s);e.value=gl(e.value,s,r),t.value=_l(t.value,r),n.value=_l(n.value,r)}if(r){let e=ml(o,c);r.value=hl(r.value,c,e),t.value=vl(t.value,e),n.value=vl(n.value,e)}}else if(n){if(e){let e=Cl(n.value,i);n.value=n.value.substring(e.length)}if(r){let e=Cl(r.value,i);r.value=r.value.substring(e.length)}}else if(e&&r){let n=Cl(r.value,i),[a,o]=wl(t.value,i),s=pl(n,a);t.value=_l(t.value,s);let c=ml(_l(n,s),o);t.value=vl(t.value,c),r.value=hl(r.value,n,c),e.value=gl(e.value,n,n.slice(0,n.length-c.length))}else if(r){let e=Cl(r.value,i),n=yl(Sl(t.value,i),e);t.value=vl(t.value,n)}else if(e){let n=yl(Sl(e.value,i),Cl(t.value,i));t.value=_l(t.value,n)}}new class extends fl{tokenize(e){let t=RegExp(`(\\r?\\n)|[${Tl}]+|[^\\S\\n\\r]+|[^${Tl}]`,`ug`);return e.match(t)||[]}};const Ol=new class extends fl{constructor(){super(...arguments),this.tokenize=Al}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
10
+ `,{customPrettifiers:s,errorLikeObjectKeys:c,hideObject:l,levelFirst:u,levelKey:d,levelLabel:f,messageFormat:p,messageKey:m,minimumLevel:h,singleLine:g,timestampKey:_,translateTime:v}=e,y=e.errorProps.split(`,`),b=typeof e.useOnlyCustomProps==`boolean`?e.useOnlyCustomProps:e.useOnlyCustomProps===`true`,x=i(e.customLevels),S=a(e.customLevels),C=o(b,x,S),w;if(e.customColors)if(typeof e.customColors==`string`)w=e.customColors.split(`,`).reduce((t,r)=>{let[i,a]=r.split(`:`),o=(b?e.customLevels:S[i]!==void 0)?S[i]:n[i],s=o===void 0?i:o;return t.push([s,a]),t},[]);else if(typeof e.customColors==`object`)w=Object.keys(e.customColors).reduce((t,r)=>{let[i,a]=[r,e.customColors[r]],o=(b?e.customLevels:S[i]!==void 0)?S[i]:n[i],s=o===void 0?i:o;return t.push([s,a]),t},[]);else throw Error(`options.customColors must be of type string or object.`);let T={customLevels:x,customLevelNames:S};b===!0&&!e.customLevels&&(T.customLevels=void 0,T.customLevelNames=void 0);let E=e.include===void 0?void 0:new Set(e.include.split(`,`)),D=!E&&e.ignore?new Set(e.ignore.split(`,`)):void 0,O=r(e.colorize,w,b),k=e.colorizeObjects?O:r(!1,[],!1);return{EOL:t,IDENT:` `,colorizer:O,customColors:w,customLevelNames:S,customLevels:x,customPrettifiers:s,customProperties:T,errorLikeObjectKeys:c,errorProps:y,getLevelLabelData:C,hideObject:l,ignoreKeys:D,includeKeys:E,levelFirst:u,levelKey:d,levelLabel:f,messageFormat:p,messageKey:m,minimumLevel:h,objectColorizer:k,singleLine:g,timestampKey:_,translateTime:v,useOnlyCustomProps:b}}})),_c=n(((e,t)=>{t.exports=s,s.default=s,s.stable=d,s.stableStringify=d;var n=`[...]`,r=`[Circular]`,i=[],a=[];function o(){return{depthLimit:2**53-1,edgesLimit:2**53-1}}function s(e,t,n,r){r===void 0&&(r=o()),l(e,``,0,[],void 0,0,r);var s;try{s=a.length===0?JSON.stringify(e,t,n):JSON.stringify(e,p(t),n)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;i.length!==0;){var c=i.pop();c.length===4?Object.defineProperty(c[0],c[1],c[3]):c[0][c[1]]=c[2]}}return s}function c(e,t,n,r){var o=Object.getOwnPropertyDescriptor(r,n);o.get===void 0?(r[n]=e,i.push([r,n,t])):o.configurable?(Object.defineProperty(r,n,{value:e}),i.push([r,n,t,o])):a.push([t,n,e])}function l(e,t,i,a,o,s,u){s+=1;var d;if(typeof e==`object`&&e){for(d=0;d<a.length;d++)if(a[d]===e){c(r,e,t,o);return}if(u.depthLimit!==void 0&&s>u.depthLimit){c(n,e,t,o);return}if(u.edgesLimit!==void 0&&i+1>u.edgesLimit){c(n,e,t,o);return}if(a.push(e),Array.isArray(e))for(d=0;d<e.length;d++)l(e[d],d,d,a,e,s,u);else{var f=Object.keys(e);for(d=0;d<f.length;d++){var p=f[d];l(e[p],p,d,a,e,s,u)}}a.pop()}}function u(e,t){return e<t?-1:e>t?1:0}function d(e,t,n,r){r===void 0&&(r=o());var s=f(e,``,0,[],void 0,0,r)||e,c;try{c=a.length===0?JSON.stringify(s,t,n):JSON.stringify(s,p(t),n)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;i.length!==0;){var l=i.pop();l.length===4?Object.defineProperty(l[0],l[1],l[3]):l[0][l[1]]=l[2]}}return c}function f(e,t,a,o,s,l,d){l+=1;var p;if(typeof e==`object`&&e){for(p=0;p<o.length;p++)if(o[p]===e){c(r,e,t,s);return}try{if(typeof e.toJSON==`function`)return}catch{return}if(d.depthLimit!==void 0&&l>d.depthLimit){c(n,e,t,s);return}if(d.edgesLimit!==void 0&&a+1>d.edgesLimit){c(n,e,t,s);return}if(o.push(e),Array.isArray(e))for(p=0;p<e.length;p++)f(e[p],p,p,o,e,l,d);else{var m={},h=Object.keys(e).sort(u);for(p=0;p<h.length;p++){var g=h[p];f(e[g],g,p,o,e,l,d),m[g]=e[g]}if(s!==void 0)i.push([s,t,e]),s[t]=m;else return m}o.pop()}}function p(e){return e=e===void 0?function(e,t){return t}:e,function(t,n){if(a.length>0)for(var r=0;r<a.length;r++){var i=a[r];if(i[1]===t&&i[0]===n){n=i[2],a.splice(r,1);break}}return e.call(this,t,n)}}})),vc=n(((e,t)=>{t.exports=r;let n=hc();function r({keyName:e,lines:t,eol:r,ident:i}){let a=``,o=`${i}${e}: ${n({input:t,ident:i,eol:r})}${r}`.split(r);for(let e=0;e<o.length;e+=1){e!==0&&(a+=r);let t=o[e];if(/^\s*"stack"/.test(t)){let e=/^(\s*"stack":)\s*(".*"),?$/.exec(t);if(e&&e.length===3){let n=/^\s*/.exec(t)[0].length+4,i=` `.repeat(n),o=e[2];a+=e[1]+r+i+JSON.parse(o).replace(/\n/g,r+i)}else a+=t}else a+=t}return a}})),yc=n(((e,t)=>{t.exports=o;let{LOGGER_KEYS:n}=Zs(),r=_c(),i=hc(),a=vc();function o({log:e,excludeLoggerKeys:t=!0,skipKeys:o=[],context:s}){let{EOL:c,IDENT:l,customPrettifiers:u,errorLikeObjectKeys:d,objectColorizer:f,singleLine:p,colorizer:m}=s,h=[].concat(o);t===!0&&Array.prototype.push.apply(h,n);let g=``,{plain:_,errors:v}=Object.entries(e).reduce(({plain:t,errors:n},[r,i])=>{if(h.includes(r)===!1){let a=typeof u[r]==`function`?u[r](i,r,e,{colors:m.colors}):i;d.includes(r)?n[r]=a:t[r]=a}return{plain:t,errors:n}},{plain:{},errors:{}});return p?(Object.keys(_).length>0&&(g+=f.greyMessage(r(_))),g+=c,g=g.replace(/\\\\/gi,`\\`)):Object.entries(_).forEach(([e,t])=>{let n=typeof u[e]==`function`?t:r(t,null,2);if(n===void 0)return;n=n.replace(/\\\\/gi,`\\`);let a=i({input:n,ident:l,eol:c});g+=`${l}${f.property(e)}:${a.startsWith(c)?``:` `}${a}${c}`}),Object.entries(v).forEach(([e,t])=>{let n=typeof u[e]==`function`?t:r(t,null,2);n!==void 0&&(g+=a({keyName:e,lines:n,eol:c,ident:l}))}),g}})),bc=n(((e,t)=>{t.exports=o;let{LOGGER_KEYS:n}=Zs(),r=mc(),i=hc(),a=yc();function o({log:e,context:t}){let{EOL:o,IDENT:s,errorProps:c,messageKey:l}=t,u=e.stack,d=`${s}${i({input:u,ident:s,eol:o})}${o}`;if(c.length>0){let i=n.concat(l,`type`,`stack`),u;u=c[0]===`*`?Object.keys(e).filter(e=>i.includes(e)===!1):c.filter(e=>i.includes(e)===!1);for(let n=0;n<u.length;n+=1){let i=u[n];if(i in e){if(r(e[i])){let n=a({log:e[i],excludeLoggerKeys:!1,context:{...t,IDENT:s+s}});d=`${d}${s}${i}: {${o}${n}${s}}${o}`;continue}d=`${d}${s}${i}: ${e[i]}${o}`}}}return d}})),xc=n(((e,t)=>{t.exports=r;let n=ac();function r({log:e,context:t}){let{colorizer:r,customLevels:i,customLevelNames:a,levelKey:o,getLevelLabelData:s}=t,c=t.customPrettifiers?.level,l=n(e,o);if(l===void 0)return;let u=r(l,{customLevels:i,customLevelNames:a});if(c){let[t]=s(l);return c(l,o,e,{label:t,labelColorized:u,colors:r.colors})}return u}})),Sc=n(((e,t)=>{t.exports=a;let{LEVELS:n}=Zs(),r=ac(),i=pc();function a({log:e,context:t}){let{colorizer:a,customLevels:o,levelKey:s,levelLabel:c,messageFormat:l,messageKey:u,useOnlyCustomProps:d}=t;if(l&&typeof l==`string`){let t=i(l,e),u=String(t).replace(/{([^{}]+)}/g,function(t,i){let a;if(i===c&&(a=r(e,s))!==void 0)return(d?o===void 0:o[a]===void 0)?n[a]:o[a];let l=r(e,i);return l===void 0?``:l});return a.message(u)}if(l&&typeof l==`function`){let t=l(e,u,c,{colors:a.colors});return a.message(t)}if(u in e&&!(typeof e[u]!=`string`&&typeof e[u]!=`number`&&typeof e[u]!=`boolean`))return a.message(e[u])}})),Cc=n(((e,t)=>{t.exports=n;function n({log:e,context:t}){let{customPrettifiers:n,colorizer:r}=t,i=``;if(e.name||e.pid||e.hostname){if(i+=`(`,e.name&&(i+=n.name?n.name(e.name,`name`,e,{colors:r.colors}):e.name),e.pid){let t=n.pid?n.pid(e.pid,`pid`,e,{colors:r.colors}):e.pid;e.name&&e.pid?i+=`/`+t:i+=t}if(e.hostname){let t=n.hostname?n.hostname(e.hostname,`hostname`,e,{colors:r.colors}):e.hostname;i+=`${i===`(`?`on`:` on`} ${t}`}i+=`)`}if(e.caller){let t=n.caller?n.caller(e.caller,`caller`,e,{colors:r.colors}):e.caller;i+=`${i===``?``:` `}<${t}>`}if(i!==``)return i}})),wc=n(((e,t)=>{t.exports=r;let n=uc();function r({log:e,context:t}){let{timestampKey:r,translateTime:i}=t,a=t.customPrettifiers?.time,o=null;if(r in e?o=e[r]:`timestamp`in e&&(o=e.timestamp),o===null)return;let s=i?n(o,i):o;return a?a(s):`[${s}]`}})),Tc=n(((e,t)=>{t.exports={buildSafeSonicBoom:tc(),createDate:rc(),deleteLogProperty:oc(),filterLog:cc(),formatTime:uc(),getPropertyValue:ac(),handleCustomLevelsNamesOpts:dc(),handleCustomLevelsOpts:fc(),interpretConditionals:pc(),isObject:mc(),isValidDate:nc(),joinLinesWithIndentation:hc(),noop:ec(),parseFactoryOptions:gc(),prettifyErrorLog:bc(),prettifyError:vc(),prettifyLevel:xc(),prettifyMessage:Sc(),prettifyMetadata:Cc(),prettifyObject:yc(),prettifyTime:wc(),splitPropertyKey:ic(),getLevelLabelData:Qs()}})),Ec=n(((e,t)=>{let n=typeof Buffer<`u`,r=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,i=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function a(e,t,a){a==null&&typeof t==`object`&&t&&(a=t,t=void 0),n&&Buffer.isBuffer(e)&&(e=e.toString()),e&&e.charCodeAt(0)===65279&&(e=e.slice(1));let s=JSON.parse(e,t);if(typeof s!=`object`||!s)return s;let c=a&&a.protoAction||`error`,l=a&&a.constructorAction||`error`;if(c===`ignore`&&l===`ignore`)return s;if(c!==`ignore`&&l!==`ignore`){if(r.test(e)===!1&&i.test(e)===!1)return s}else if(c!==`ignore`&&l===`ignore`){if(r.test(e)===!1)return s}else if(i.test(e)===!1)return s;return o(s,{protoAction:c,constructorAction:l,safe:a&&a.safe})}function o(e,{protoAction:t=`error`,constructorAction:n=`error`,safe:r}={}){let i=[e];for(;i.length;){let e=i;i=[];for(let a of e){if(t!==`ignore`&&Object.prototype.hasOwnProperty.call(a,`__proto__`)){if(r===!0)return null;if(t===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete a.__proto__}if(n!==`ignore`&&Object.prototype.hasOwnProperty.call(a,`constructor`)&&a.constructor!==null&&typeof a.constructor==`object`&&Object.prototype.hasOwnProperty.call(a.constructor,`prototype`)){if(r===!0)return null;if(n===`error`)throw SyntaxError(`Object contains forbidden prototype property`);delete a.constructor}for(let e in a){let t=a[e];t&&typeof t==`object`&&i.push(t)}}}return e}function s(e,t,n){let{stackTraceLimit:r}=Error;Error.stackTraceLimit=0;try{return a(e,t,n)}finally{Error.stackTraceLimit=r}}function c(e,t){let{stackTraceLimit:n}=Error;Error.stackTraceLimit=0;try{return a(e,t,{safe:!0})}catch{return}finally{Error.stackTraceLimit=n}}t.exports=s,t.exports.default=s,t.exports.parse=s,t.exports.safeParse=c,t.exports.scan=o})),Dc=n(((e,t)=>{t.exports=h;let n=Ec(),r=mc(),i=bc(),a=xc(),o=Sc(),s=Cc(),c=yc(),l=wc(),u=cc(),{LEVELS:d,LEVEL_KEY:f,LEVEL_NAMES:p}=Zs(),m=e=>{try{return{value:n.parse(e,{protoAction:`remove`})}}catch(e){return{err:e}}};function h(e){let t;if(r(e))t=e;else{let n=m(e);if(n.err||!r(n.value))return e+this.EOL;t=n.value}if(this.minimumLevel){let e;e=this.useOnlyCustomProps?this.customLevels:this.customLevelNames[this.minimumLevel]!==void 0;let n;if(n=e?this.customLevelNames[this.minimumLevel]:p[this.minimumLevel],n||=typeof this.minimumLevel==`string`?p[this.minimumLevel]:p[d[this.minimumLevel].toLowerCase()],t[this.levelKey===void 0?f:this.levelKey]<n)return}let n=o({log:t,context:this.context});(this.ignoreKeys||this.includeKeys)&&(t=u({log:t,context:this.context}));let h=a({log:t,context:{...this.context,...this.context.customProperties}}),g=s({log:t,context:this.context}),_=l({log:t,context:this.context}),v=``;if(this.levelFirst&&h&&(v=`${h}`),_&&v===``?v=`${_}`:_&&(v=`${v} ${_}`),!this.levelFirst&&h&&(v=v.length>0?`${v} ${h}`:h),g&&(v=v.length>0?`${v} ${g}:`:g),v.endsWith(`:`)===!1&&v!==``&&(v+=`:`),n!==void 0&&(v=v.length>0?`${v} ${n}`:n),v.length>0&&!this.singleLine&&(v+=this.EOL),t.type===`Error`&&typeof t.stack==`string`){let e=i({log:t,context:this.context});this.singleLine&&(v+=this.EOL),v+=e}else if(this.hideObject===!1){let e=[this.messageKey,this.levelKey,this.timestampKey].map(e=>e.replaceAll(/\\/g,``)).filter(e=>typeof t[e]==`string`||typeof t[e]==`number`||typeof t[e]==`boolean`),n=c({log:t,skipKeys:e,context:this.context});this.singleLine&&!/^\s$/.test(n)&&(v+=` `),v+=n}return v}})),Oc=n(((e,n)=>{let{isColorSupported:r}=Ws(),i=Js(),{Transform:a}=t(`node:stream`),o=Xs(),s=$s(),{ERROR_LIKE_KEYS:c,LEVEL_KEY:l,LEVEL_LABEL:u,MESSAGE_KEY:d,TIMESTAMP_KEY:f}=Zs(),{buildSafeSonicBoom:p,parseFactoryOptions:m}=Tc(),h=Dc(),g={colorize:r,colorizeObjects:!0,crlf:!1,customColors:null,customLevels:null,customPrettifiers:{},errorLikeObjectKeys:c,errorProps:``,hideObject:!1,ignore:`hostname`,include:void 0,levelFirst:!1,levelKey:l,levelLabel:u,messageFormat:null,messageKey:d,minimumLevel:void 0,outputStream:process.stdout,singleLine:!1,timestampKey:f,translateTime:!0,useOnlyCustomProps:!0};function _(e){let t=m(Object.assign({},g,e));return h.bind({...t,context:t})}function v(e={}){let t=_(e),n;return o(function(r){r.on(`message`,function n(i){!i||i.code!==`PINO_CONFIG`||(Object.assign(e,{messageKey:i.config.messageKey,errorLikeObjectKeys:Array.from(new Set([...e.errorLikeObjectKeys||c,i.config.errorKey])),customLevels:i.config.levels.values}),t=_(e),r.off(`message`,n))});let o=new a({objectMode:!0,autoDestroy:!0,transform(e,n,r){r(null,t(e))}});return n=typeof e.destination==`object`&&typeof e.destination.write==`function`?e.destination:p({dest:e.destination||1,append:e.append,mkdir:e.mkdir,sync:e.sync}),r.on(`unknown`,function(e){n.write(e+`
11
+ `)}),i(r,o,n),o},{parse:`lines`,close(e,t){n.on(`close`,()=>{t(e)})}})}n.exports=v,n.exports.build=v,n.exports.PinoPretty=v,n.exports.prettyFactory=_,n.exports.colorizerFactory=s,n.exports.isColorSupported=r,n.exports.default=v})),kc=e(Us(),1),Ac=e(Oc(),1);function jc(){return process.env.NO_COLOR&&process.env.NO_COLOR!==``?!1:process.stdout.isTTY??!1}var Mc=class{name;transportConfigs=[];pinoInstance;options;constructor(e,t={}){this.name=e,this.options={name:this.name,level:process.env.LOG_LEVEL||(process.env.NODE_ENV===`test`?`silent`:`info`),serializers:{err:kc.default.stdSerializers.err,error:kc.default.stdSerializers.err},...t.options},t.transportConfigs&&(this.transportConfigs=t.transportConfigs),this.pinoInstance=this.buildInstance()}buildInstance(){if(this.transportConfigs.length>0)return(0,kc.default)(this.options,kc.default.transport({targets:this.transportConfigs}));try{let e=(0,Ac.default)({colorize:jc(),translateTime:`HH:MM:ss`,ignore:`pid,hostname`});return(0,kc.default)(this.options,e)}catch(e){return console.warn(`[PinoLogger] pino-pretty failed, falling back to JSON:`,e),(0,kc.default)(this.options)}}recreateInstance(){typeof this.pinoInstance.flush==`function`&&this.pinoInstance.flush(),this.pinoInstance=this.buildInstance()}addTransport(e){this.transportConfigs.push(e),this.recreateInstance()}removeTransport(e){e>=0&&e<this.transportConfigs.length&&(this.transportConfigs.splice(e,1),this.recreateInstance())}getTransports(){return[...this.transportConfigs]}updateOptions(e){this.options={...this.options,...e},this.recreateInstance()}getPinoInstance(){return this.pinoInstance}error(e,t){this.pinoInstance.error(e,t)}warn(e,t){this.pinoInstance.warn(e,t)}info(e,t){this.pinoInstance.info(e,t)}debug(e,t){this.pinoInstance.debug(e,t)}};const Nc=new class{config={};loggers=new Map;configure(e){this.config=e,this.loggers.clear()}getLogger(e){let t=this.loggers.get(e);if(t)return t;let n;return n=this.config.loggerFactory?this.config.loggerFactory(e):this.config.defaultLogger?this.config.defaultLogger:new Mc(e,this.config.pinoConfig),this.loggers.set(e,n),n}reset(){this.config={},this.loggers.clear()}};function Pc(e){return Nc.getLogger(e)}const K={reconcileCount:0,conflictCount:0,batchCount:0,upstreamImportCount:0,rescueBufferCount:0,branchSwitchCount:0,parkCount:0,gitAutoSaveFailureCount:0,cc1BroadcastCount:0,cc1BroadcastDropCount:0,cc1SubscriberCount:0,cc1LastSeq:{},serverObserverFiresA:0,serverObserverFiresB:0,serverObserverErrorsA:0,serverObserverErrorsB:0,persistenceDiskWrites:0,bridgeMergeContentLoss:0,bridgeMergeCheckpointCreated:0,collabSocketEpipeCount:0,collabSocketEconnresetCount:0};function Fc(){K.reconcileCount++}function Ic(){K.conflictCount++}function Lc(){K.batchCount++}function Rc(){K.upstreamImportCount++}function zc(){K.rescueBufferCount++}function Bc(){K.branchSwitchCount++}function Vc(){K.parkCount++}function Hc(){K.gitAutoSaveFailureCount++}function Uc(){K.cc1BroadcastCount++}function Wc(){K.cc1BroadcastDropCount++}function Gc(e){K.cc1SubscriberCount=e}function Kc(e){e===`a`?K.serverObserverFiresA++:K.serverObserverFiresB++}function qc(){K.persistenceDiskWrites++}function Jc(e){e===`a`?K.serverObserverErrorsA++:K.serverObserverErrorsB++}function Yc(){K.bridgeMergeContentLoss++}function Xc(){K.bridgeMergeCheckpointCreated++}function Zc(e){e===`EPIPE`?K.collabSocketEpipeCount++:K.collabSocketEconnresetCount++}function Qc(e){return e.code===`EPIPE`||e.code===`ECONNRESET`?(Zc(e.code),!0):!1}function $c(e,t){K.cc1LastSeq[e]=t}function el(){return{...K,cc1LastSeq:{...K.cc1LastSeq}}}function q(e){return e===r}var tl=class{hocuspocus;seqs=new Map;timers=new Map;log=Pc(`cc1`);warnedMissing=!1;constructor(e){this.hocuspocus=e}signal(e){let t=this.timers.get(e);t!==void 0&&clearTimeout(t),this.timers.set(e,setTimeout(()=>{this.timers.delete(e),this.broadcast(e)},100))}broadcast(e){try{let t=this.hocuspocus.documents.get(r);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found — broadcasts will be dropped until it is materialized`),!0),Wc();return}let n=(this.seqs.get(e)??0)+1;this.seqs.set(e,n);let i={v:1,ch:e,seq:n};t.broadcastStateless(JSON.stringify(i)),Uc(),$c(e,n),Gc(t.getConnectionsCount())}catch(t){this.log.error({err:t,channel:e},`[cc1] broadcast failed`)}}get subscriberCount(){let e=this.hocuspocus.documents.get(r);return e?e.getConnectionsCount():0}destroy(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};const nl=new m({extensions:O}),rl=o(O),il=Pc(`agent-sessions`),al={source:`local`,skipStoreHooks:!1,context:{origin:`agent-write`,paired:!0}};function ol(e){return e?{"claude-code":`claude`,"claude-ai":`claude`,cursor:`cursor`,"cursor-vscode":`cursor`,cascade:`windsurf`,codex:`openai`,copilot:`github`,cline:`cline`}[e]??`bot`:`bot`}function sl(e,t,n){try{let r=e.getXmlFragment(`default`),i=e.getText(`source`),a=e.getMap(`metadata`),o=ms(r,rl).toJSON(),s=nl.serialize(o),c=a.get(`frontmatter`)??``,{frontmatter:l,body:d}=A(t),f,m;switch(n){case`replace`:f=l||c,m=d.trim();break;case`prepend`:f=c,m=`${d.trim()}\n\n${s}`;break;case`append`:f=c,m=s.trim()?`${s}\n\n${d.trim()}\n`:`${d.trim()}\n`;break}let h=nl.parseWithFallback(m);ds(e,r,rl.nodeFromJSON(h),{mapping:new Map,isOMark:new Map}),f!==c&&a.set(`frontmatter`,f);let g=nl.serialize(ms(r,rl).toJSON()),_=u(f,g);p(i,i.toString(),_)}catch(r){throw il.error({err:r,docName:e.name,position:n,markdownLen:t.length},`[applyAgentMarkdownWrite] failed for '${e.name}'`),r}}var cl=class{sessions=new Map;hocuspocus;constructor(e){this.hocuspocus=e}sessionKey(e,t){return`${e}\0${t}`}async getSession(e,t=`claude-1`,n){if(q(e))throw Error(`Cannot create agent session for reserved doc: ${e}`);let r=this.sessionKey(e,t),i=this.sessions.get(r);if(!i){i=await this.hocuspocus.openDirectConnection(e);let a=ol(n?.clientName),o=g[a]??l(n?.colorSeed??t);i.document.awareness.setLocalState({user:{name:n?.displayName??`Claude`,color:o,type:`agent`,icon:a,tabId:`agent-${t}`},mode:`idle`}),this.sessions.set(r,i),il.info({docName:e,agentId:t},`[agent-session] Created session for: ${e} / ${t}`)}return i}hasSession(e,t=`claude-1`){return this.sessions.has(this.sessionKey(e,t))}async closeSession(e,t=`claude-1`){let n=this.sessionKey(e,t),r=this.sessions.get(n);r&&(r.document.awareness.setLocalState(null),await r.disconnect(),this.sessions.delete(n),il.info({docName:e,agentId:t},`[agent-session] Closed session for: ${e} / ${t}`))}async closeAllForAgent(e){let t=`\0${e}`;for(let[n,r]of this.sessions)if(n.endsWith(t))try{r.document.awareness.setLocalState(null),await r.disconnect(),this.sessions.delete(n)}catch(t){il.error({err:t,agentId:e},`[agent-session] Failed to close session for agent ${e}`)}}async closeAllForDoc(e){let t=`${e}\0`;for(let[n,r]of this.sessions)if(n.startsWith(t))try{r.document.awareness.setLocalState(null),await r.disconnect(),this.sessions.delete(n)}catch(t){il.error({err:t,docName:e},`[agent-session] Failed to close session for doc ${e}`)}}async closeAll(e){if(e){await this.closeAllForDoc(e);return}let t=[...this.sessions.keys()];for(let e of t){let t=this.sessions.get(e);if(t)try{t.document.awareness.setLocalState(null),await t.disconnect(),this.sessions.delete(e)}catch(t){il.error({err:t,key:e},`[agent-session] Failed to close session: ${e}`)}}}},ll=n(((e,t)=>{function n(e){if(e.length===0)return;let t=Object.create(null),n=0;for(;n<e.length;++n){let t=e.charCodeAt(n);if(u[t]!==1){if(t!==47||n===0)return;break}}if(n===e.length)return;let i=e.slice(0,n).toLowerCase(),a=++n;for(;n<e.length;++n)if(u[e.charCodeAt(n)]!==1){if(n===a||r(e,n,t)===void 0)return;break}if(n!==a)return{type:i,subtype:e.slice(a,n).toLowerCase(),params:t}}function r(e,t,n){for(;t<e.length;){for(;t<e.length;++t){let n=e.charCodeAt(t);if(n!==32&&n!==9)break}if(t===e.length)break;if(e.charCodeAt(t++)!==59)return;for(;t<e.length;++t){let n=e.charCodeAt(t);if(n!==32&&n!==9)break}if(t===e.length)return;let r,i=t;for(;t<e.length;++t){let n=e.charCodeAt(t);if(u[n]!==1){if(n!==61)return;break}}if(t===e.length||(r=e.slice(i,t),++t,t===e.length))return;let a=``,o;if(e.charCodeAt(t)===34){o=++t;let n=!1;for(;t<e.length;++t){let r=e.charCodeAt(t);if(r===92){n?(o=t,n=!1):(a+=e.slice(o,t),n=!0);continue}if(r===34){if(n){o=t,n=!1;continue}a+=e.slice(o,t);break}if(n&&=(o=t-1,!1),d[r]!==1)return}if(t===e.length)return;++t}else{for(o=t;t<e.length;++t)if(u[e.charCodeAt(t)]!==1){if(t===o)return;break}a=e.slice(o,t)}r=r.toLowerCase(),n[r]===void 0&&(n[r]=a)}return n}function i(e,t){if(e.length===0)return;let n=Object.create(null),r=0;for(;r<e.length;++r)if(u[e.charCodeAt(r)]!==1){if(a(e,r,n,t)===void 0)return;break}return{type:e.slice(0,r).toLowerCase(),params:n}}function a(e,t,n,r){for(;t<e.length;){for(;t<e.length;++t){let n=e.charCodeAt(t);if(n!==32&&n!==9)break}if(t===e.length)break;if(e.charCodeAt(t++)!==59)return;for(;t<e.length;++t){let n=e.charCodeAt(t);if(n!==32&&n!==9)break}if(t===e.length)return;let i,a=t;for(;t<e.length;++t){let n=e.charCodeAt(t);if(u[n]!==1){if(n===61)break;return}}if(t===e.length)return;let o=``,s,l;if(i=e.slice(a,t),i.charCodeAt(i.length-1)===42){let n=++t;for(;t<e.length;++t){let n=e.charCodeAt(t);if(f[n]!==1){if(n!==39)return;break}}if(t===e.length)return;for(l=e.slice(n,t),++t;t<e.length&&e.charCodeAt(t)!==39;++t);if(t===e.length||(++t,t===e.length))return;s=t;let r=0;for(;t<e.length;++t){let n=e.charCodeAt(t);if(p[n]!==1){if(n===37){let n,i;if(t+2<e.length&&(n=m[e.charCodeAt(t+1)])!==-1&&(i=m[e.charCodeAt(t+2)])!==-1){let a=(n<<4)+i;o+=e.slice(s,t),o+=String.fromCharCode(a),t+=2,s=t+1,a>=128?r=2:r===0&&(r=1);continue}return}break}}if(o+=e.slice(s,t),o=c(o,l,r),o===void 0)return}else{if(++t,t===e.length)return;if(e.charCodeAt(t)===34){s=++t;let n=!1;for(;t<e.length;++t){let r=e.charCodeAt(t);if(r===92){n?(s=t,n=!1):(o+=e.slice(s,t),n=!0);continue}if(r===34){if(n){s=t,n=!1;continue}o+=e.slice(s,t);break}if(n&&=(s=t-1,!1),d[r]!==1)return}if(t===e.length)return;++t}else{for(s=t;t<e.length;++t)if(u[e.charCodeAt(t)]!==1){if(t===s)return;break}o=e.slice(s,t)}if(o=r(o,2),o===void 0)return}i=i.toLowerCase(),n[i]===void 0&&(n[i]=o)}return n}function o(e){let t;for(;;)switch(e){case`utf-8`:case`utf8`:return s.utf8;case`latin1`:case`ascii`:case`us-ascii`:case`iso-8859-1`:case`iso8859-1`:case`iso88591`:case`iso_8859-1`:case`windows-1252`:case`iso_8859-1:1987`:case`cp1252`:case`x-cp1252`:return s.latin1;case`utf16le`:case`utf-16le`:case`ucs2`:case`ucs-2`:return s.utf16le;case`base64`:return s.base64;default:if(t===void 0){t=!0,e=e.toLowerCase();continue}return s.other.bind(e)}}let s={utf8:(e,t)=>{if(e.length===0)return``;if(typeof e==`string`){if(t<2)return e;e=Buffer.from(e,`latin1`)}return e.utf8Slice(0,e.length)},latin1:(e,t)=>e.length===0?``:typeof e==`string`?e:e.latin1Slice(0,e.length),utf16le:(e,t)=>e.length===0?``:(typeof e==`string`&&(e=Buffer.from(e,`latin1`)),e.ucs2Slice(0,e.length)),base64:(e,t)=>e.length===0?``:(typeof e==`string`&&(e=Buffer.from(e,`latin1`)),e.base64Slice(0,e.length)),other:(t,n)=>{if(t.length===0)return``;typeof t==`string`&&(t=Buffer.from(t,`latin1`));try{return new TextDecoder(e).decode(t)}catch{}}};function c(e,t,n){let r=o(t);if(r)return r(e,n)}function l(e){if(typeof e!=`string`)return``;for(let t=e.length-1;t>=0;--t)switch(e.charCodeAt(t)){case 47:case 92:return e=e.slice(t+1),e===`..`||e===`.`?``:e}return e===`..`||e===`.`?``:e}let u=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],d=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],f=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,0,0,0,0,1,0,1,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],p=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,1,0,0,0,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],m=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1];t.exports={basename:l,convertToUTF8:c,getDecoder:o,parseContentType:n,parseDisposition:i}})),ul=n(((e,t)=>{function n(e,t,n,r,i){for(let a=0;a<i;++a)if(e[t+a]!==n[r+a])return!1;return!0}var r=class{constructor(e,t){if(typeof t!=`function`)throw Error(`Missing match callback`);if(typeof e==`string`)e=Buffer.from(e);else if(!Buffer.isBuffer(e))throw Error(`Expected Buffer for needle, got ${typeof e}`);let n=e.length;if(this.maxMatches=1/0,this.matches=0,this._cb=t,this._lookbehindSize=0,this._needle=e,this._bufPos=0,this._lookbehind=Buffer.allocUnsafe(n),this._occ=[n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n],n>1)for(let t=0;t<n-1;++t)this._occ[e[t]]=n-1-t}reset(){this.matches=0,this._lookbehindSize=0,this._bufPos=0}push(e,t){let n;Buffer.isBuffer(e)||(e=Buffer.from(e,`latin1`));let r=e.length;for(this._bufPos=t||0;n!==r&&this.matches<this.maxMatches;)n=i(this,e);return n}destroy(){let e=this._lookbehindSize;e&&this._cb(!1,this._lookbehind,0,e,!1),this.reset()}};function i(e,t){let r=t.length,i=e._needle,o=i.length,s=-e._lookbehindSize,c=o-1,l=i[c],u=r-o,d=e._occ,f=e._lookbehind;if(s<0){for(;s<0&&s<=u;){let n=s+c,r=n<0?f[e._lookbehindSize+n]:t[n];if(r===l&&a(e,t,s,c))return e._lookbehindSize=0,++e.matches,s>-e._lookbehindSize?e._cb(!0,f,0,e._lookbehindSize+s,!1):e._cb(!0,void 0,0,0,!0),e._bufPos=s+o;s+=d[r]}for(;s<0&&!a(e,t,s,r-s);)++s;if(s<0){let n=e._lookbehindSize+s;return n>0&&e._cb(!1,f,0,n,!1),e._lookbehindSize-=n,f.copy(f,0,n,e._lookbehindSize),f.set(t,e._lookbehindSize),e._lookbehindSize+=r,e._bufPos=r,r}e._cb(!1,f,0,e._lookbehindSize,!1),e._lookbehindSize=0}s+=e._bufPos;let p=i[0];for(;s<=u;){let r=t[s+c];if(r===l&&t[s]===p&&n(i,0,t,s,c))return++e.matches,s>0?e._cb(!0,t,e._bufPos,s,!0):e._cb(!0,void 0,0,0,!0),e._bufPos=s+o;s+=d[r]}for(;s<r;){if(t[s]!==p||!n(t,s,i,0,r-s)){++s;continue}t.copy(f,0,s,r),e._lookbehindSize=r-s;break}return s>0&&e._cb(!1,t,e._bufPos,s<r?s:r,!0),e._bufPos=r,r}function a(e,t,n,r){let i=e._lookbehind,a=e._lookbehindSize,o=e._needle;for(let e=0;e<r;++e,++n)if((n<0?i[a+n]:t[n])!==o[e])return!1;return!0}t.exports=r})),dl=n(((e,n)=>{let{Readable:r,Writable:i}=t(`stream`),a=ul(),{basename:o,convertToUTF8:s,getDecoder:c,parseContentType:l,parseDisposition:u}=ll(),d=Buffer.from(`\r
12
+ `),f=Buffer.from(`\r`),p=Buffer.from(`-`);function m(){}let h=16*1024;var g=class{constructor(e){this.header=Object.create(null),this.pairCount=0,this.byteCount=0,this.state=0,this.name=``,this.value=``,this.crlf=0,this.cb=e}reset(){this.header=Object.create(null),this.pairCount=0,this.byteCount=0,this.state=0,this.name=``,this.value=``,this.crlf=0}push(e,t,n){let r=t;for(;t<n;)switch(this.state){case 0:{let i=!1;for(;t<n;++t){if(this.byteCount===h)return-1;++this.byteCount;let n=e[t];if(w[n]!==1){if(n!==58||(this.name+=e.latin1Slice(r,t),this.name.length===0))return-1;++t,i=!0,this.state=1;break}}if(!i){this.name+=e.latin1Slice(r,t);break}}case 1:{let i=!1;for(;t<n;++t){if(this.byteCount===h)return-1;++this.byteCount;let n=e[t];if(n!==32&&n!==9){r=t,i=!0,this.state=2;break}}if(!i)break}case 2:switch(this.crlf){case 0:for(;t<n;++t){if(this.byteCount===h)return-1;++this.byteCount;let n=e[t];if(T[n]!==1){if(n!==13)return-1;++this.crlf;break}}this.value+=e.latin1Slice(r,t++);break;case 1:if(this.byteCount===h||(++this.byteCount,e[t++]!==10))return-1;++this.crlf;break;case 2:{if(this.byteCount===h)return-1;++this.byteCount;let n=e[t];n===32||n===9?(r=t,this.crlf=0):(++this.pairCount<2e3&&(this.name=this.name.toLowerCase(),this.header[this.name]===void 0?this.header[this.name]=[this.value]:this.header[this.name].push(this.value)),n===13?(++this.crlf,++t):(r=t,this.crlf=0,this.state=0,this.name=``,this.value=``));break}case 3:{if(this.byteCount===h||(++this.byteCount,e[t++]!==10))return-1;let n=this.header;return this.reset(),this.cb(n),t}}break}return t}},_=class extends r{constructor(e,t){super(e),this.truncated=!1,this._readcb=null,this.once(`end`,()=>{if(this._read(),--t._fileEndsLeft===0&&t._finalcb){let e=t._finalcb;t._finalcb=null,process.nextTick(e)}})}_read(e){let t=this._readcb;t&&(this._readcb=null,t())}};let v={push:(e,t)=>{},destroy:()=>{}};function y(e,t){let n=e._writecb;e._writecb=null,t?e.destroy(t):n&&n()}function b(e,t){return e}var x=class extends i{constructor(e){let t={autoDestroy:!0,emitClose:!0,highWaterMark:typeof e.highWaterMark==`number`?e.highWaterMark:void 0};if(super(t),!e.conType.params||typeof e.conType.params.boundary!=`string`)throw Error(`Multipart: Boundary not found`);let n=e.conType.params.boundary,r=typeof e.defParamCharset==`string`&&e.defParamCharset?c(e.defParamCharset):b,i=e.defCharset||`utf8`,h=e.preservePath,y={autoDestroy:!0,emitClose:!0,highWaterMark:typeof e.fileHwm==`number`?e.fileHwm:void 0},x=e.limits,S=x&&typeof x.fieldSize==`number`?x.fieldSize:1*1024*1024,C=x&&typeof x.fileSize==`number`?x.fileSize:1/0,w=x&&typeof x.files==`number`?x.files:1/0,T=x&&typeof x.fields==`number`?x.fields:1/0,E=x&&typeof x.parts==`number`?x.parts:1/0,D=-1,O=0,k=0,A=!1;this._fileEndsLeft=0,this._fileStream=void 0,this._complete=!1;let j=0,M,ee=0,N,te,ne,P,re=!1,F=!1,ie=!1;this._hparser=null;let ae=new g(e=>{this._hparser=null,A=!1,ne=`text/plain`,N=i,te=`7bit`,P=void 0,re=!1;let t;if(!e[`content-disposition`]){A=!0;return}let n=u(e[`content-disposition`][0],r);if(!n||n.type!==`form-data`){A=!0;return}if(n.params&&(n.params.name&&(P=n.params.name),n.params[`filename*`]?t=n.params[`filename*`]:n.params.filename&&(t=n.params.filename),t!==void 0&&!h&&(t=o(t))),e[`content-type`]){let t=l(e[`content-type`][0]);t&&(ne=`${t.type}/${t.subtype}`,t.params&&typeof t.params.charset==`string`&&(N=t.params.charset.toLowerCase()))}if(e[`content-transfer-encoding`]&&(te=e[`content-transfer-encoding`][0].toLowerCase()),ne===`application/octet-stream`||t!==void 0){if(k===w){F||(F=!0,this.emit(`filesLimit`)),A=!0;return}if(++k,this.listenerCount(`file`)===0){A=!0;return}j=0,this._fileStream=new _(y,this),++this._fileEndsLeft,this.emit(`file`,P,this._fileStream,{filename:t,encoding:te,mimeType:ne})}else{if(O===T){ie||(ie=!0,this.emit(`fieldsLimit`)),A=!0;return}if(++O,this.listenerCount(`field`)===0){A=!0;return}M=[],ee=0}}),I=0,oe=(e,t,n,r,i)=>{retrydata:for(;t;){if(this._hparser!==null){let e=this._hparser.push(t,n,r);if(e===-1){this._hparser=null,ae.reset(),this.emit(`error`,Error(`Malformed part header`));break}n=e}if(n===r)break;if(I!==0){if(I===1){switch(t[n]){case 45:I=2,++n;break;case 13:I=3,++n;break;default:I=0}if(n===r)return}if(I===2){if(I=0,t[n]===45){this._complete=!0,this._bparser=v;return}let e=this._writecb;this._writecb=m,oe(!1,p,0,1,!1),this._writecb=e}else if(I===3)if(I=0,t[n]===10){if(++n,D>=E||(this._hparser=ae,n===r))break;continue retrydata}else{let e=this._writecb;this._writecb=m,oe(!1,f,0,1,!1),this._writecb=e}}if(!A){if(this._fileStream){let e,a=Math.min(r-n,C-j);i?e=t.slice(n,n+a):(e=Buffer.allocUnsafe(a),t.copy(e,0,n,n+a)),j+=e.length,j===C?(e.length>0&&this._fileStream.push(e),this._fileStream.emit(`limit`),this._fileStream.truncated=!0,A=!0):this._fileStream.push(e)||(this._writecb&&(this._fileStream._readcb=this._writecb),this._writecb=null)}else if(M!==void 0){let e,a=Math.min(r-n,S-ee);i?e=t.slice(n,n+a):(e=Buffer.allocUnsafe(a),t.copy(e,0,n,n+a)),ee+=a,M.push(e),ee===S&&(A=!0,re=!0)}}break}if(e){if(I=1,this._fileStream)this._fileStream.push(null),this._fileStream=null;else if(M!==void 0){let e;switch(M.length){case 0:e=``;break;case 1:e=s(M[0],N,0);break;default:e=s(Buffer.concat(M,ee),N,0)}M=void 0,ee=0,this.emit(`field`,P,e,{nameTruncated:!1,valueTruncated:re,encoding:te,mimeType:ne})}++D===E&&this.emit(`partsLimit`)}};this._bparser=new a(`\r\n--${n}`,oe),this._writecb=null,this._finalcb=null,this.write(d)}static detect(e){return e.type===`multipart`&&e.subtype===`form-data`}_write(e,t,n){this._writecb=n,this._bparser.push(e,0),this._writecb&&y(this)}_destroy(e,t){this._hparser=null,this._bparser=v,e||=C(this);let n=this._fileStream;n&&(this._fileStream=null,n.destroy(e)),t(e)}_final(e){if(this._bparser.destroy(),!this._complete)return e(Error(`Unexpected end of form`));this._fileEndsLeft?this._finalcb=S.bind(null,this,e):S(this,e)}};function S(e,t,n){if(n)return t(n);n=C(e),t(n)}function C(e){if(e._hparser)return Error(`Malformed part header`);let t=e._fileStream;if(t&&(e._fileStream=null,t.destroy(Error(`Unexpected end of file`))),!e._complete)return Error(`Unexpected end of form`)}let w=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],T=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];n.exports=x})),fl=n(((e,n)=>{let{Writable:r}=t(`stream`),{getDecoder:i}=ll();var a=class extends r{constructor(e){let t={autoDestroy:!0,emitClose:!0,highWaterMark:typeof e.highWaterMark==`number`?e.highWaterMark:void 0};super(t);let n=e.defCharset||`utf8`;e.conType.params&&typeof e.conType.params.charset==`string`&&(n=e.conType.params.charset),this.charset=n;let r=e.limits;this.fieldSizeLimit=r&&typeof r.fieldSize==`number`?r.fieldSize:1*1024*1024,this.fieldsLimit=r&&typeof r.fields==`number`?r.fields:1/0,this.fieldNameSizeLimit=r&&typeof r.fieldNameSize==`number`?r.fieldNameSize:100,this._inKey=!0,this._keyTrunc=!1,this._valTrunc=!1,this._bytesKey=0,this._bytesVal=0,this._fields=0,this._key=``,this._val=``,this._byte=-2,this._lastPos=0,this._encode=0,this._decoder=i(n)}static detect(e){return e.type===`application`&&e.subtype===`x-www-form-urlencoded`}_write(e,t,n){if(this._fields>=this.fieldsLimit)return n();let r=0,i=e.length;if(this._lastPos=0,this._byte!==-2){if(r=o(this,e,r,i),r===-1)return n(Error(`Malformed urlencoded form`));if(r>=i)return n();this._inKey?++this._bytesKey:++this._bytesVal}main:for(;r<i;)if(this._inKey){for(r=s(this,e,r,i);r<i;){switch(e[r]){case 61:this._lastPos<r&&(this._key+=e.latin1Slice(this._lastPos,r)),this._lastPos=++r,this._key=this._decoder(this._key,this._encode),this._encode=0,this._inKey=!1;continue main;case 38:if(this._lastPos<r&&(this._key+=e.latin1Slice(this._lastPos,r)),this._lastPos=++r,this._key=this._decoder(this._key,this._encode),this._encode=0,this._bytesKey>0&&this.emit(`field`,this._key,``,{nameTruncated:this._keyTrunc,valueTruncated:!1,encoding:this.charset,mimeType:`text/plain`}),this._key=``,this._val=``,this._keyTrunc=!1,this._valTrunc=!1,this._bytesKey=0,this._bytesVal=0,++this._fields>=this.fieldsLimit)return this.emit(`fieldsLimit`),n();continue;case 43:this._lastPos<r&&(this._key+=e.latin1Slice(this._lastPos,r)),this._key+=` `,this._lastPos=r+1;break;case 37:if(this._encode===0&&(this._encode=1),this._lastPos<r&&(this._key+=e.latin1Slice(this._lastPos,r)),this._lastPos=r+1,this._byte=-1,r=o(this,e,r+1,i),r===-1)return n(Error(`Malformed urlencoded form`));if(r>=i)return n();++this._bytesKey,r=s(this,e,r,i);continue}++r,++this._bytesKey,r=s(this,e,r,i)}this._lastPos<r&&(this._key+=e.latin1Slice(this._lastPos,r))}else{for(r=c(this,e,r,i);r<i;){switch(e[r]){case 38:if(this._lastPos<r&&(this._val+=e.latin1Slice(this._lastPos,r)),this._lastPos=++r,this._inKey=!0,this._val=this._decoder(this._val,this._encode),this._encode=0,(this._bytesKey>0||this._bytesVal>0)&&this.emit(`field`,this._key,this._val,{nameTruncated:this._keyTrunc,valueTruncated:this._valTrunc,encoding:this.charset,mimeType:`text/plain`}),this._key=``,this._val=``,this._keyTrunc=!1,this._valTrunc=!1,this._bytesKey=0,this._bytesVal=0,++this._fields>=this.fieldsLimit)return this.emit(`fieldsLimit`),n();continue main;case 43:this._lastPos<r&&(this._val+=e.latin1Slice(this._lastPos,r)),this._val+=` `,this._lastPos=r+1;break;case 37:if(this._encode===0&&(this._encode=1),this._lastPos<r&&(this._val+=e.latin1Slice(this._lastPos,r)),this._lastPos=r+1,this._byte=-1,r=o(this,e,r+1,i),r===-1)return n(Error(`Malformed urlencoded form`));if(r>=i)return n();++this._bytesVal,r=c(this,e,r,i);continue}++r,++this._bytesVal,r=c(this,e,r,i)}this._lastPos<r&&(this._val+=e.latin1Slice(this._lastPos,r))}n()}_final(e){if(this._byte!==-2)return e(Error(`Malformed urlencoded form`));(!this._inKey||this._bytesKey>0||this._bytesVal>0)&&(this._inKey?this._key=this._decoder(this._key,this._encode):this._val=this._decoder(this._val,this._encode),this.emit(`field`,this._key,this._val,{nameTruncated:this._keyTrunc,valueTruncated:this._valTrunc,encoding:this.charset,mimeType:`text/plain`})),e()}};function o(e,t,n,r){if(n>=r)return r;if(e._byte===-1){let i=l[t[n++]];if(i===-1)return-1;if(i>=8&&(e._encode=2),n<r){let r=l[t[n++]];if(r===-1)return-1;e._inKey?e._key+=String.fromCharCode((i<<4)+r):e._val+=String.fromCharCode((i<<4)+r),e._byte=-2,e._lastPos=n}else e._byte=i}else{let r=l[t[n++]];if(r===-1)return-1;e._inKey?e._key+=String.fromCharCode((e._byte<<4)+r):e._val+=String.fromCharCode((e._byte<<4)+r),e._byte=-2,e._lastPos=n}return n}function s(e,t,n,r){if(e._bytesKey>e.fieldNameSizeLimit){for(e._keyTrunc||e._lastPos<n&&(e._key+=t.latin1Slice(e._lastPos,n-1)),e._keyTrunc=!0;n<r;++n){let r=t[n];if(r===61||r===38)break;++e._bytesKey}e._lastPos=n}return n}function c(e,t,n,r){if(e._bytesVal>e.fieldSizeLimit){for(e._valTrunc||e._lastPos<n&&(e._val+=t.latin1Slice(e._lastPos,n-1)),e._valTrunc=!0;n<r&&t[n]!==38;++n)++e._bytesVal;e._lastPos=n}return n}let l=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1];n.exports=a})),pl=n(((e,t)=>{let{parseContentType:n}=ll();function r(e){let t=e.headers,r=n(t[`content-type`]);if(!r)throw Error(`Malformed content type`);for(let n of i){if(!n.detect(r))continue;let i={limits:e.limits,headers:t,conType:r,highWaterMark:void 0,fileHwm:void 0,defCharset:void 0,defParamCharset:void 0,preservePath:!1};return e.highWaterMark&&(i.highWaterMark=e.highWaterMark),e.fileHwm&&(i.fileHwm=e.fileHwm),i.defCharset=e.defCharset,i.defParamCharset=e.defParamCharset,i.preservePath=e.preservePath,new n(i)}throw Error(`Unsupported content type: ${t[`content-type`]}`)}let i=[dl(),fl()].filter(function(e){return typeof e.detect==`function`});t.exports=e=>{if((typeof e!=`object`||!e)&&(e={}),typeof e.headers!=`object`||e.headers===null||typeof e.headers[`content-type`]!=`string`)throw Error(`Missing Content-Type`);return r(e)}})),ml=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}else return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h){d[r]=void 0;continue}if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}};new class extends ml{};function hl(e,t){let n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function gl(e,t){let n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function _l(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function vl(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function yl(e,t){return _l(e,t,``)}function bl(e,t){return vl(e,t,``)}function xl(e,t){return t.slice(0,Sl(e,t))}function Sl(e,t){let n=0;e.length>t.length&&(n=e.length-t.length);let r=t.length;e.length<t.length&&(r=e.length);let i=Array(r),a=0;i[0]=0;for(let e=1;e<r;e++){for(t[e]==t[a]?i[e]=i[a]:i[e]=a;a>0&&t[e]!=t[a];)a=i[a];t[e]==t[a]&&a++}a=0;for(let r=n;r<e.length;r++){for(;a>0&&e[r]!=t[a];)a=i[a];e[r]==t[a]&&a++}return a}function Cl(e,t){let n=[];for(let r of Array.from(t.segment(e))){let e=r.segment;n.length&&/\s/.test(n[n.length-1])&&/\s/.test(e)?n[n.length-1]+=e:n.push(e)}return n}function wl(e,t){if(t)return El(e,t)[1];let n;for(n=e.length-1;n>=0&&e[n].match(/\s/);n--);return e.substring(n+1)}function Tl(e,t){if(t)return El(e,t)[0];let n=e.match(/^\s*/);return n?n[0]:``}function El(e,t){if(!t)return[Tl(e),wl(e)];if(t.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);let n=Cl(e,t),r=n[0],i=n[n.length-1];return[/\s/.test(r)?r:``,/\s/.test(i)?i:``]}const Dl=`a-zA-Z0-9_\\u{AD}\\u{C0}-\\u{D6}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,Ol=RegExp(`[${Dl}]+|\\s+|[^${Dl}]`,`ug`);new class extends ml{equals(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()}tokenize(e,t={}){let n;if(t.intlSegmenter){let r=t.intlSegmenter;if(r.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=Cl(e,r)}else n=e.match(Ol)||[];let r=[],i=null;return n.forEach(e=>{/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):i!=null&&/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r}join(e){return e.map((e,t)=>t==0?e:e.replace(/^\s+/,``)).join(``)}postProcess(e,t){if(!e||t.oneChangePerToken)return e;let n=null,r=null,i=null;return e.forEach(e=>{e.added?r=e:e.removed?i=e:((r||i)&&kl(n,i,r,e,t.intlSegmenter),n=e,r=null,i=null)}),(r||i)&&kl(n,i,r,null,t.intlSegmenter),e}};function kl(e,t,n,r,i){if(t&&n){let[a,o]=El(t.value,i),[s,c]=El(n.value,i);if(e){let r=hl(a,s);e.value=vl(e.value,s,r),t.value=yl(t.value,r),n.value=yl(n.value,r)}if(r){let e=gl(o,c);r.value=_l(r.value,c,e),t.value=bl(t.value,e),n.value=bl(n.value,e)}}else if(n){if(e){let e=Tl(n.value,i);n.value=n.value.substring(e.length)}if(r){let e=Tl(r.value,i);r.value=r.value.substring(e.length)}}else if(e&&r){let n=Tl(r.value,i),[a,o]=El(t.value,i),s=hl(n,a);t.value=yl(t.value,s);let c=gl(yl(n,s),o);t.value=bl(t.value,c),r.value=_l(r.value,n,c),e.value=vl(e.value,n,n.slice(0,n.length-c.length))}else if(r){let e=Tl(r.value,i),n=xl(wl(t.value,i),e);t.value=bl(t.value,n)}else if(e){let n=xl(wl(e.value,i),Tl(t.value,i));t.value=yl(t.value,n)}}new class extends ml{tokenize(e){let t=RegExp(`(\\r?\\n)|[${Dl}]+|[^\\S\\n\\r]+|[^${Dl}]`,`ug`);return e.match(t)||[]}};const Al=new class extends ml{constructor(){super(...arguments),this.tokenize=Ml}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
13
13
  `))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(`
14
14
  `))&&(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
15
15
  `)&&(e=e.slice(0,-1)),t.endsWith(`
16
- `)&&(t=t.slice(0,-1))),super.equals(e,t,n)}};function kl(e,t,n){return Ol.diff(e,t,n)}function Al(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
17
- `));let n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(let e=0;e<r.length;e++){let i=r[e];e%2&&!t.newlineIsToken?n[n.length-1]+=i:n.push(i)}return n}function jl(e){return e==`.`||e==`!`||e==`?`}new class extends fl{tokenize(e){let t=[],n=0;for(let r=0;r<e.length;r++){if(r==e.length-1){t.push(e.slice(n));break}if(jl(e[r])&&e[r+1].match(/\s/)){for(t.push(e.slice(n,r+1)),r=n=r+1;e[r+1]?.match(/\s/);)r++;t.push(e.slice(n,r+1)),n=r+1}}return t}},new class extends fl{tokenize(e){return e.split(/([{}:;,]|\s+)/)}},new class extends fl{constructor(){super(...arguments),this.tokenize=Al}get useLongestToken(){return!0}castInput(e,t){let{undefinedReplacement:n,stringifyReplacer:r=(e,t)=>t===void 0?n:t}=t;return typeof e==`string`?e:JSON.stringify(Ml(e,null,null,r),null,` `)}equals(e,t,n){return super.equals(e.replace(/,([\r\n])/g,`$1`),t.replace(/,([\r\n])/g,`$1`),n)}};function Ml(e,t,n,r,i){t||=[],n||=[],r&&(e=r(i===void 0?``:i,e));let a;for(a=0;a<t.length;a+=1)if(t[a]===e)return n[a];let o;if(Object.prototype.toString.call(e)===`[object Array]`){for(t.push(e),o=Array(e.length),n.push(o),a=0;a<e.length;a+=1)o[a]=Ml(e[a],t,n,r,String(a));return t.pop(),n.pop(),o}if(e&&e.toJSON&&(e=e.toJSON()),typeof e==`object`&&e){t.push(e),o={},n.push(o);let i=[],s;for(s in e)Object.prototype.hasOwnProperty.call(e,s)&&i.push(s);for(i.sort(),a=0;a<i.length;a+=1)s=i[a],o[s]=Ml(e[s],t,n,r,s);t.pop(),n.pop()}else o=e;return o}new class extends fl{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}};const Nl={128:`€`,130:`‚`,131:`ƒ`,132:`„`,133:`…`,134:`†`,135:`‡`,136:`ˆ`,137:`‰`,138:`Š`,139:`‹`,140:`Œ`,142:`Ž`,145:`‘`,146:`’`,147:`“`,148:`”`,149:`•`,150:`–`,151:`—`,152:`˜`,153:`™`,154:`š`,155:`›`,156:`œ`,158:`ž`,159:`Ÿ`},Pl={};for(let[e,t]of Object.entries(Nl))Pl[t]=Number.parseInt(e,10);let Fl;function Il(){if(globalThis.TextDecoder!==void 0)return Fl??=new globalThis.TextDecoder(`utf-8`)}const Ll=32*1024,Rl=65533;function zl(e,t=`utf-8`){switch(t.toLowerCase()){case`utf-8`:case`utf8`:{let t=Il();return t?t.decode(e):Ul(e)}case`utf-16le`:return Wl(e);case`us-ascii`:case`ascii`:return Gl(e);case`latin1`:case`iso-8859-1`:return Kl(e);case`windows-1252`:return ql(e);default:throw RangeError(`Encoding '${t}' not supported`)}}function Bl(e,t){t.length!==0&&(e.push(String.fromCharCode.apply(null,t)),t.length=0)}function Vl(e,t,n){t.push(n),t.length>=Ll&&Bl(e,t)}function Hl(e,t,n){if(n<=65535){Vl(e,t,n);return}n-=65536,Vl(e,t,55296+(n>>10)),Vl(e,t,56320+(n&1023))}function Ul(e){let t=[],n=[],r=0;for(e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191&&(r=3);r<e.length;){let i=e[r];if(i<=127){Vl(t,n,i),r++;continue}if(i<194||i>244){Vl(t,n,Rl),r++;continue}if(i<=223){if(r+1>=e.length){Vl(t,n,Rl),r++;continue}let a=e[r+1];if((a&192)!=128){Vl(t,n,Rl),r++;continue}Vl(t,n,(i&31)<<6|a&63),r+=2;continue}if(i<=239){if(r+2>=e.length){Vl(t,n,Rl),r++;continue}let a=e[r+1],o=e[r+2];if(!((a&192)==128&&(o&192)==128&&!(i===224&&a<160)&&!(i===237&&a>=160))){Vl(t,n,Rl),r++;continue}Vl(t,n,(i&15)<<12|(a&63)<<6|o&63),r+=3;continue}if(r+3>=e.length){Vl(t,n,Rl),r++;continue}let a=e[r+1],o=e[r+2],s=e[r+3];if(!((a&192)==128&&(o&192)==128&&(s&192)==128&&!(i===240&&a<144)&&!(i===244&&a>143))){Vl(t,n,Rl),r++;continue}Hl(t,n,(i&7)<<18|(a&63)<<12|(o&63)<<6|s&63),r+=4}return Bl(t,n),t.join(``)}function Wl(e){let t=[],n=[],r=e.length,i=0;for(;i+1<r;){let a=e[i]|e[i+1]<<8;if(i+=2,a>=55296&&a<=56319){if(i+1<r){let r=e[i]|e[i+1]<<8;r>=56320&&r<=57343?(Vl(t,n,a),Vl(t,n,r),i+=2):Vl(t,n,Rl)}else Vl(t,n,Rl);continue}if(a>=56320&&a<=57343){Vl(t,n,Rl);continue}Vl(t,n,a)}return i<r&&Vl(t,n,Rl),Bl(t,n),t.join(``)}function Gl(e){let t=[];for(let n=0;n<e.length;n+=Ll){let r=Math.min(e.length,n+Ll),i=Array(r-n);for(let t=n,a=0;t<r;t++,a++)i[a]=e[t]&127;t.push(String.fromCharCode.apply(null,i))}return t.join(``)}function Kl(e){let t=[];for(let n=0;n<e.length;n+=Ll){let r=Math.min(e.length,n+Ll),i=Array(r-n);for(let t=n,a=0;t<r;t++,a++)i[a]=e[t];t.push(String.fromCharCode.apply(null,i))}return t.join(``)}function ql(e){let t=[],n=``;for(let r=0;r<e.length;r++){let i=e[r],a=i>=128&&i<=159?Nl[i]:void 0;n+=a??String.fromCharCode(i),n.length>=Ll&&(t.push(n),n=``)}return n&&t.push(n),t.join(``)}function Jl(e){return new DataView(e.buffer,e.byteOffset)}const Yl={len:1,get(e,t){return Jl(e).getUint8(t)},put(e,t,n){return Jl(e).setUint8(t,n),t+1}},Xl={len:2,get(e,t){return Jl(e).getUint16(t,!0)},put(e,t,n){return Jl(e).setUint16(t,n,!0),t+2}},Zl={len:2,get(e,t){return Jl(e).getUint16(t)},put(e,t,n){return Jl(e).setUint16(t,n),t+2}},Ql={len:4,get(e,t){return Jl(e).getUint32(t,!0)},put(e,t,n){return Jl(e).setUint32(t,n,!0),t+4}},$l={len:4,get(e,t){return Jl(e).getUint32(t)},put(e,t,n){return Jl(e).setUint32(t,n),t+4}},eu={len:4,get(e,t){return Jl(e).getInt32(t)},put(e,t,n){return Jl(e).setInt32(t,n),t+4}},tu={len:8,get(e,t){return Jl(e).getBigUint64(t,!0)},put(e,t,n){return Jl(e).setBigUint64(t,n,!0),t+8}};var nu=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){return zl(e.subarray(t,t+this.len),this.encoding)}},ru=class extends Error{constructor(){super(`End-Of-Stream`),this.name=`EndOfStreamError`}},iu=class extends Error{constructor(e=`The operation was aborted`){super(e),this.name=`AbortError`}},au=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){let n=await this.read(e,t);return this.peekQueue.push(e.subarray(0,n)),n}async read(e,t=!1){if(e.length===0)return 0;let n=this.readFromPeekBuffer(e);if(this.endOfStream||(n+=await this.readRemainderFromStream(e.subarray(n),t)),n===0&&!t)throw new ru;return n}readFromPeekBuffer(e){let t=e.length,n=0;for(;this.peekQueue.length>0&&t>0;){let r=this.peekQueue.pop();if(!r)throw Error(`peekData should be defined`);let i=Math.min(r.length,t);e.set(r.subarray(0,i),n),n+=i,t-=i,i<r.length&&this.peekQueue.push(r.subarray(i))}return n}async readRemainderFromStream(e,t){let n=0;for(;n<e.length&&!this.endOfStream;){if(this.interrupted)throw new iu;let r=await this.readFromStream(e.subarray(n),t);if(r===0)break;n+=r}if(!t&&n<e.length)throw new ru;return n}},ou=class extends au{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}},su=class extends ou{async readFromStream(e,t){if(e.length===0)return 0;let n=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return n.done&&(this.endOfStream=n.done),n.value?(e.set(n.value),n.value.length):0}},cu=class extends au{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){let n=Math.min(t.length,e.length);return e.set(t.subarray(0,n)),n<t.length?this.buffer=t.subarray(n):this.buffer=null,n}async readFromStream(e,t){if(e.length===0)return 0;let n=0;for(this.buffer&&(n+=this.writeChunk(e,this.buffer));n<e.length&&!this.endOfStream;){let t=await this.reader.read();if(t.done){this.endOfStream=!0;break}t.value&&(n+=this.writeChunk(e.subarray(n),t.value))}if(!t&&n===0&&this.endOfStream)throw new ru;return n}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function lu(e){try{let t=e.getReader({mode:`byob`});return t instanceof ReadableStreamDefaultReader?new cu(t):new su(t)}catch(t){if(t instanceof TypeError)return new cu(e.getReader());throw t}}var uu=class{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=e?.onClose,e?.abortSignal&&e.abortSignal.addEventListener(`abort`,()=>{this.abort()})}async readToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.readBuffer(n,{position:t})<e.len)throw new ru;return e.get(n,0)}async peekToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.peekBuffer(n,{position:t})<e.len)throw new ru;return e.get(n,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new ru;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new ru;return e.get(this.numBuffer,0)}async ignore(e){if(e<0)throw RangeError(`ignore length must be ≥ 0 bytes`);if(this.fileInfo.size!==void 0){let t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&t.position!==void 0&&t.position<this.position)throw Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}},du=class extends uu{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let n=this.normalizeOptions(e,t),r=n.position-this.position;if(r>0)return await this.ignore(r),this.readBuffer(e,t);if(r<0)throw Error("`options.position` must be equal or greater than `tokenizer.position`");if(n.length===0)return 0;let i=await this.streamReader.read(e.subarray(0,n.length),n.mayBeLess);if(this.position+=i,(!t||!t.mayBeLess)&&i<n.length)throw new ru;return i}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=0;if(n.position){let t=n.position-this.position;if(t>0){let i=new Uint8Array(n.length+t);return r=await this.peekBuffer(i,{mayBeLess:n.mayBeLess}),e.set(i.subarray(t)),r-t}if(t<0)throw Error(`Cannot peek from a negative offset in a stream`)}if(n.length>0){try{r=await this.streamReader.peek(e.subarray(0,n.length),n.mayBeLess)}catch(e){if(t?.mayBeLess&&e instanceof ru)return 0;throw e}if(!n.mayBeLess&&r<n.length)throw new ru}return r}async ignore(e){if(e<0)throw RangeError(`ignore length must be ≥ 0 bytes`);let t=Math.min(256e3,e),n=new Uint8Array(t),r=0;for(;r<e;){let i=e-r,a=await this.readBuffer(n,{length:Math.min(t,i)});if(a<0)return a;r+=a}return r}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}},fu=class extends uu{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...t?.fileInfo??{},size:e.length}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=Math.min(this.uint8Array.length-n.position,n.length);if(!n.mayBeLess&&r<n.length)throw new ru;return e.set(this.uint8Array.subarray(n.position,n.position+r)),r}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}},pu=class extends uu{constructor(e,t){super(t),this.blob=e,this.fileInfo={...t?.fileInfo??{},size:e.size,mimeType:e.type}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=Math.min(this.blob.size-n.position,n.length);if(!n.mayBeLess&&r<n.length)throw new ru;let i=await this.blob.slice(n.position,n.position+r).arrayBuffer();return e.set(new Uint8Array(i)),r}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};function mu(e,t){let n=lu(e),r=t??{},i=r.onClose;return r.onClose=async()=>{if(await n.close(),i)return i()},new du(n,r)}function hu(e,t){return new fu(e,t)}function gu(e,t){return new pu(e,t)}var _u=n(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})),vu=n(((e,t)=>{function n(e){n.debug=n,n.default=n,n.coerce=c,n.disable=o,n.enable=i,n.enabled=s,n.humanize=_u(),n.destroy=l,Object.keys(e).forEach(t=>{n[t]=e[t]}),n.names=[],n.skips=[],n.formatters={};function t(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return n.colors[Math.abs(t)%n.colors.length]}n.selectColor=t;function n(e){let t,i=null,a,o;function s(...e){if(!s.enabled)return;let r=s,i=Number(new Date);r.diff=i-(t||i),r.prev=t,r.curr=i,t=i,e[0]=n.coerce(e[0]),typeof e[0]!=`string`&&e.unshift(`%O`);let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,i)=>{if(t===`%%`)return`%`;a++;let o=n.formatters[i];if(typeof o==`function`){let n=e[a];t=o.call(r,n),e.splice(a,1),a--}return t}),n.formatArgs.call(r,e),(r.log||n.log).apply(r,e)}return s.namespace=e,s.useColors=n.useColors(),s.color=n.selectColor(e),s.extend=r,s.destroy=n.destroy,Object.defineProperty(s,`enabled`,{enumerable:!0,configurable:!1,get:()=>i===null?(a!==n.namespaces&&(a=n.namespaces,o=n.enabled(e)),o):i,set:e=>{i=e}}),typeof n.init==`function`&&n.init(s),s}function r(e,t){let r=n(this.namespace+(t===void 0?`:`:t)+e);return r.log=this.log,r}function i(e){n.save(e),n.namespaces=e,n.names=[],n.skips=[];let t=(typeof e==`string`?e:``).trim().replace(/\s+/g,`,`).split(`,`).filter(Boolean);for(let e of t)e[0]===`-`?n.skips.push(e.slice(1)):n.names.push(e)}function a(e,t){let n=0,r=0,i=-1,a=0;for(;n<e.length;)if(r<t.length&&(t[r]===e[n]||t[r]===`*`))t[r]===`*`?(i=r,a=n,r++):(n++,r++);else if(i!==-1)r=i+1,a++,n=a;else return!1;for(;r<t.length&&t[r]===`*`;)r++;return r===t.length}function o(){let e=[...n.names,...n.skips.map(e=>`-`+e)].join(`,`);return n.enable(``),e}function s(e){for(let t of n.skips)if(a(e,t))return!1;for(let t of n.names)if(a(e,t))return!0;return!1}function c(e){return e instanceof Error?e.stack||e.message:e}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}t.exports=n})),yu=n(((e,t)=>{e.formatArgs=r,e.save=i,e.load=a,e.useColors=n,e.storage=o(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=`#0000CC.#0000FF.#0033CC.#0033FF.#0066CC.#0066FF.#0099CC.#0099FF.#00CC00.#00CC33.#00CC66.#00CC99.#00CCCC.#00CCFF.#3300CC.#3300FF.#3333CC.#3333FF.#3366CC.#3366FF.#3399CC.#3399FF.#33CC00.#33CC33.#33CC66.#33CC99.#33CCCC.#33CCFF.#6600CC.#6600FF.#6633CC.#6633FF.#66CC00.#66CC33.#9900CC.#9900FF.#9933CC.#9933FF.#99CC00.#99CC33.#CC0000.#CC0033.#CC0066.#CC0099.#CC00CC.#CC00FF.#CC3300.#CC3333.#CC3366.#CC3399.#CC33CC.#CC33FF.#CC6600.#CC6633.#CC9900.#CC9933.#CCCC00.#CCCC33.#FF0000.#FF0033.#FF0066.#FF0099.#FF00CC.#FF00FF.#FF3300.#FF3333.#FF3366.#FF3399.#FF33CC.#FF33FF.#FF6600.#FF6633.#FF9900.#FF9933.#FFCC00.#FFCC33`.split(`.`);function n(){if(typeof window<`u`&&window.process&&(window.process.type===`renderer`||window.process.__nwjs))return!0;if(typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<`u`&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<`u`&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<`u`&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(e){if(e[0]=(this.useColors?`%c`:``)+this.namespace+(this.useColors?` %c`:` `)+e[0]+(this.useColors?`%c `:` `)+`+`+t.exports.humanize(this.diff),!this.useColors)return;let n=`color: `+this.color;e.splice(1,0,n,`color: inherit`);let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{e!==`%%`&&(r++,e===`%c`&&(i=r))}),e.splice(i,0,n)}e.log=console.debug||console.log||(()=>{});function i(t){try{t?e.storage.setItem(`debug`,t):e.storage.removeItem(`debug`)}catch{}}function a(){let t;try{t=e.storage.getItem(`debug`)||e.storage.getItem(`DEBUG`)}catch{}return!t&&typeof process<`u`&&`env`in process&&(t=process.env.DEBUG),t}function o(){try{return localStorage}catch{}}t.exports=vu()(e);let{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})),bu=n(((e,t)=>{t.exports=(e,t=process.argv)=>{let n=e.startsWith(`-`)?``:e.length===1?`-`:`--`,r=t.indexOf(n+e),i=t.indexOf(`--`);return r!==-1&&(i===-1||r<i)}})),xu=n(((e,n)=>{let r=t(`os`),i=t(`tty`),a=bu(),{env:o}=process,s;a(`no-color`)||a(`no-colors`)||a(`color=false`)||a(`color=never`)?s=0:(a(`color`)||a(`colors`)||a(`color=true`)||a(`color=always`))&&(s=1),`FORCE_COLOR`in o&&(s=o.FORCE_COLOR===`true`?1:o.FORCE_COLOR===`false`?0:o.FORCE_COLOR.length===0?1:Math.min(parseInt(o.FORCE_COLOR,10),3));function c(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function l(e,t){if(s===0)return 0;if(a(`color=16m`)||a(`color=full`)||a(`color=truecolor`))return 3;if(a(`color=256`))return 2;if(e&&!t&&s===void 0)return 0;let n=s||0;if(o.TERM===`dumb`)return n;if(process.platform===`win32`){let e=r.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in o)return[`TRAVIS`,`CIRCLECI`,`APPVEYOR`,`GITLAB_CI`,`GITHUB_ACTIONS`,`BUILDKITE`].some(e=>e in o)||o.CI_NAME===`codeship`?1:n;if(`TEAMCITY_VERSION`in o)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(o.TEAMCITY_VERSION)?1:0;if(o.COLORTERM===`truecolor`)return 3;if(`TERM_PROGRAM`in o){let e=parseInt((o.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(o.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(o.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(o.TERM)||`COLORTERM`in o?1:n}function u(e){return c(l(e,e&&e.isTTY))}n.exports={supportsColor:u,stdout:c(l(!0,i.isatty(1))),stderr:c(l(!0,i.isatty(2)))}})),Su=n(((e,n)=>{let r=t(`tty`),i=t(`util`);e.init=d,e.log=c,e.formatArgs=o,e.save=l,e.load=u,e.useColors=a,e.destroy=i.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{let t=xu();t&&(t.stderr||t).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}e.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{let n=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase()),r=process.env[t];return r=/^(yes|on|true|enabled)$/i.test(r)?!0:/^(no|off|false|disabled)$/i.test(r)?!1:r===`null`?null:Number(r),e[n]=r,e},{});function a(){return`colors`in e.inspectOpts?!!e.inspectOpts.colors:r.isatty(process.stderr.fd)}function o(e){let{namespace:t,useColors:r}=this;if(r){let r=this.color,i=`\x1B[3`+(r<8?r:`8;5;`+r),a=` ${i};1m${t} \u001B[0m`;e[0]=a+e[0].split(`
16
+ `)&&(t=t.slice(0,-1))),super.equals(e,t,n)}};function jl(e,t,n){return Al.diff(e,t,n)}function Ml(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
17
+ `));let n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(let e=0;e<r.length;e++){let i=r[e];e%2&&!t.newlineIsToken?n[n.length-1]+=i:n.push(i)}return n}function Nl(e){return e==`.`||e==`!`||e==`?`}new class extends ml{tokenize(e){let t=[],n=0;for(let r=0;r<e.length;r++){if(r==e.length-1){t.push(e.slice(n));break}if(Nl(e[r])&&e[r+1].match(/\s/)){for(t.push(e.slice(n,r+1)),r=n=r+1;e[r+1]?.match(/\s/);)r++;t.push(e.slice(n,r+1)),n=r+1}}return t}},new class extends ml{tokenize(e){return e.split(/([{}:;,]|\s+)/)}},new class extends ml{constructor(){super(...arguments),this.tokenize=Ml}get useLongestToken(){return!0}castInput(e,t){let{undefinedReplacement:n,stringifyReplacer:r=(e,t)=>t===void 0?n:t}=t;return typeof e==`string`?e:JSON.stringify(Pl(e,null,null,r),null,` `)}equals(e,t,n){return super.equals(e.replace(/,([\r\n])/g,`$1`),t.replace(/,([\r\n])/g,`$1`),n)}};function Pl(e,t,n,r,i){t||=[],n||=[],r&&(e=r(i===void 0?``:i,e));let a;for(a=0;a<t.length;a+=1)if(t[a]===e)return n[a];let o;if(Object.prototype.toString.call(e)===`[object Array]`){for(t.push(e),o=Array(e.length),n.push(o),a=0;a<e.length;a+=1)o[a]=Pl(e[a],t,n,r,String(a));return t.pop(),n.pop(),o}if(e&&e.toJSON&&(e=e.toJSON()),typeof e==`object`&&e){t.push(e),o={},n.push(o);let i=[],s;for(s in e)Object.prototype.hasOwnProperty.call(e,s)&&i.push(s);for(i.sort(),a=0;a<i.length;a+=1)s=i[a],o[s]=Pl(e[s],t,n,r,s);t.pop(),n.pop()}else o=e;return o}new class extends ml{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}};const Fl={128:`€`,130:`‚`,131:`ƒ`,132:`„`,133:`…`,134:`†`,135:`‡`,136:`ˆ`,137:`‰`,138:`Š`,139:`‹`,140:`Œ`,142:`Ž`,145:`‘`,146:`’`,147:`“`,148:`”`,149:`•`,150:`–`,151:`—`,152:`˜`,153:`™`,154:`š`,155:`›`,156:`œ`,158:`ž`,159:`Ÿ`},Il={};for(let[e,t]of Object.entries(Fl))Il[t]=Number.parseInt(e,10);let Ll;function Rl(){if(globalThis.TextDecoder!==void 0)return Ll??=new globalThis.TextDecoder(`utf-8`)}const zl=32*1024,Bl=65533;function Vl(e,t=`utf-8`){switch(t.toLowerCase()){case`utf-8`:case`utf8`:{let t=Rl();return t?t.decode(e):Gl(e)}case`utf-16le`:return Kl(e);case`us-ascii`:case`ascii`:return ql(e);case`latin1`:case`iso-8859-1`:return Jl(e);case`windows-1252`:return Yl(e);default:throw RangeError(`Encoding '${t}' not supported`)}}function Hl(e,t){t.length!==0&&(e.push(String.fromCharCode.apply(null,t)),t.length=0)}function Ul(e,t,n){t.push(n),t.length>=zl&&Hl(e,t)}function Wl(e,t,n){if(n<=65535){Ul(e,t,n);return}n-=65536,Ul(e,t,55296+(n>>10)),Ul(e,t,56320+(n&1023))}function Gl(e){let t=[],n=[],r=0;for(e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191&&(r=3);r<e.length;){let i=e[r];if(i<=127){Ul(t,n,i),r++;continue}if(i<194||i>244){Ul(t,n,Bl),r++;continue}if(i<=223){if(r+1>=e.length){Ul(t,n,Bl),r++;continue}let a=e[r+1];if((a&192)!=128){Ul(t,n,Bl),r++;continue}Ul(t,n,(i&31)<<6|a&63),r+=2;continue}if(i<=239){if(r+2>=e.length){Ul(t,n,Bl),r++;continue}let a=e[r+1],o=e[r+2];if(!((a&192)==128&&(o&192)==128&&!(i===224&&a<160)&&!(i===237&&a>=160))){Ul(t,n,Bl),r++;continue}Ul(t,n,(i&15)<<12|(a&63)<<6|o&63),r+=3;continue}if(r+3>=e.length){Ul(t,n,Bl),r++;continue}let a=e[r+1],o=e[r+2],s=e[r+3];if(!((a&192)==128&&(o&192)==128&&(s&192)==128&&!(i===240&&a<144)&&!(i===244&&a>143))){Ul(t,n,Bl),r++;continue}Wl(t,n,(i&7)<<18|(a&63)<<12|(o&63)<<6|s&63),r+=4}return Hl(t,n),t.join(``)}function Kl(e){let t=[],n=[],r=e.length,i=0;for(;i+1<r;){let a=e[i]|e[i+1]<<8;if(i+=2,a>=55296&&a<=56319){if(i+1<r){let r=e[i]|e[i+1]<<8;r>=56320&&r<=57343?(Ul(t,n,a),Ul(t,n,r),i+=2):Ul(t,n,Bl)}else Ul(t,n,Bl);continue}if(a>=56320&&a<=57343){Ul(t,n,Bl);continue}Ul(t,n,a)}return i<r&&Ul(t,n,Bl),Hl(t,n),t.join(``)}function ql(e){let t=[];for(let n=0;n<e.length;n+=zl){let r=Math.min(e.length,n+zl),i=Array(r-n);for(let t=n,a=0;t<r;t++,a++)i[a]=e[t]&127;t.push(String.fromCharCode.apply(null,i))}return t.join(``)}function Jl(e){let t=[];for(let n=0;n<e.length;n+=zl){let r=Math.min(e.length,n+zl),i=Array(r-n);for(let t=n,a=0;t<r;t++,a++)i[a]=e[t];t.push(String.fromCharCode.apply(null,i))}return t.join(``)}function Yl(e){let t=[],n=``;for(let r=0;r<e.length;r++){let i=e[r],a=i>=128&&i<=159?Fl[i]:void 0;n+=a??String.fromCharCode(i),n.length>=zl&&(t.push(n),n=``)}return n&&t.push(n),t.join(``)}function Xl(e){return new DataView(e.buffer,e.byteOffset)}const Zl={len:1,get(e,t){return Xl(e).getUint8(t)},put(e,t,n){return Xl(e).setUint8(t,n),t+1}},Ql={len:2,get(e,t){return Xl(e).getUint16(t,!0)},put(e,t,n){return Xl(e).setUint16(t,n,!0),t+2}},$l={len:2,get(e,t){return Xl(e).getUint16(t)},put(e,t,n){return Xl(e).setUint16(t,n),t+2}},eu={len:4,get(e,t){return Xl(e).getUint32(t,!0)},put(e,t,n){return Xl(e).setUint32(t,n,!0),t+4}},tu={len:4,get(e,t){return Xl(e).getUint32(t)},put(e,t,n){return Xl(e).setUint32(t,n),t+4}},nu={len:4,get(e,t){return Xl(e).getInt32(t)},put(e,t,n){return Xl(e).setInt32(t,n),t+4}},ru={len:8,get(e,t){return Xl(e).getBigUint64(t,!0)},put(e,t,n){return Xl(e).setBigUint64(t,n,!0),t+8}};var iu=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){return Vl(e.subarray(t,t+this.len),this.encoding)}},au=class extends Error{constructor(){super(`End-Of-Stream`),this.name=`EndOfStreamError`}},ou=class extends Error{constructor(e=`The operation was aborted`){super(e),this.name=`AbortError`}},su=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){let n=await this.read(e,t);return this.peekQueue.push(e.subarray(0,n)),n}async read(e,t=!1){if(e.length===0)return 0;let n=this.readFromPeekBuffer(e);if(this.endOfStream||(n+=await this.readRemainderFromStream(e.subarray(n),t)),n===0&&!t)throw new au;return n}readFromPeekBuffer(e){let t=e.length,n=0;for(;this.peekQueue.length>0&&t>0;){let r=this.peekQueue.pop();if(!r)throw Error(`peekData should be defined`);let i=Math.min(r.length,t);e.set(r.subarray(0,i),n),n+=i,t-=i,i<r.length&&this.peekQueue.push(r.subarray(i))}return n}async readRemainderFromStream(e,t){let n=0;for(;n<e.length&&!this.endOfStream;){if(this.interrupted)throw new ou;let r=await this.readFromStream(e.subarray(n),t);if(r===0)break;n+=r}if(!t&&n<e.length)throw new au;return n}},cu=class extends su{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}},lu=class extends cu{async readFromStream(e,t){if(e.length===0)return 0;let n=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return n.done&&(this.endOfStream=n.done),n.value?(e.set(n.value),n.value.length):0}},uu=class extends su{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){let n=Math.min(t.length,e.length);return e.set(t.subarray(0,n)),n<t.length?this.buffer=t.subarray(n):this.buffer=null,n}async readFromStream(e,t){if(e.length===0)return 0;let n=0;for(this.buffer&&(n+=this.writeChunk(e,this.buffer));n<e.length&&!this.endOfStream;){let t=await this.reader.read();if(t.done){this.endOfStream=!0;break}t.value&&(n+=this.writeChunk(e.subarray(n),t.value))}if(!t&&n===0&&this.endOfStream)throw new au;return n}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function du(e){try{let t=e.getReader({mode:`byob`});return t instanceof ReadableStreamDefaultReader?new uu(t):new lu(t)}catch(t){if(t instanceof TypeError)return new uu(e.getReader());throw t}}var fu=class{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=e?.onClose,e?.abortSignal&&e.abortSignal.addEventListener(`abort`,()=>{this.abort()})}async readToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.readBuffer(n,{position:t})<e.len)throw new au;return e.get(n,0)}async peekToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.peekBuffer(n,{position:t})<e.len)throw new au;return e.get(n,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new au;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new au;return e.get(this.numBuffer,0)}async ignore(e){if(e<0)throw RangeError(`ignore length must be ≥ 0 bytes`);if(this.fileInfo.size!==void 0){let t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&t.position!==void 0&&t.position<this.position)throw Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}},pu=class extends fu{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let n=this.normalizeOptions(e,t),r=n.position-this.position;if(r>0)return await this.ignore(r),this.readBuffer(e,t);if(r<0)throw Error("`options.position` must be equal or greater than `tokenizer.position`");if(n.length===0)return 0;let i=await this.streamReader.read(e.subarray(0,n.length),n.mayBeLess);if(this.position+=i,(!t||!t.mayBeLess)&&i<n.length)throw new au;return i}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=0;if(n.position){let t=n.position-this.position;if(t>0){let i=new Uint8Array(n.length+t);return r=await this.peekBuffer(i,{mayBeLess:n.mayBeLess}),e.set(i.subarray(t)),r-t}if(t<0)throw Error(`Cannot peek from a negative offset in a stream`)}if(n.length>0){try{r=await this.streamReader.peek(e.subarray(0,n.length),n.mayBeLess)}catch(e){if(t?.mayBeLess&&e instanceof au)return 0;throw e}if(!n.mayBeLess&&r<n.length)throw new au}return r}async ignore(e){if(e<0)throw RangeError(`ignore length must be ≥ 0 bytes`);let t=Math.min(256e3,e),n=new Uint8Array(t),r=0;for(;r<e;){let i=e-r,a=await this.readBuffer(n,{length:Math.min(t,i)});if(a<0)return a;r+=a}return r}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}},mu=class extends fu{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...t?.fileInfo??{},size:e.length}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=Math.min(this.uint8Array.length-n.position,n.length);if(!n.mayBeLess&&r<n.length)throw new au;return e.set(this.uint8Array.subarray(n.position,n.position+r)),r}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}},hu=class extends fu{constructor(e,t){super(t),this.blob=e,this.fileInfo={...t?.fileInfo??{},size:e.size,mimeType:e.type}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=Math.min(this.blob.size-n.position,n.length);if(!n.mayBeLess&&r<n.length)throw new au;let i=await this.blob.slice(n.position,n.position+r).arrayBuffer();return e.set(new Uint8Array(i)),r}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};function gu(e,t){let n=du(e),r=t??{},i=r.onClose;return r.onClose=async()=>{if(await n.close(),i)return i()},new pu(n,r)}function _u(e,t){return new mu(e,t)}function vu(e,t){return new hu(e,t)}var yu=n(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})),bu=n(((e,t)=>{function n(e){n.debug=n,n.default=n,n.coerce=c,n.disable=o,n.enable=i,n.enabled=s,n.humanize=yu(),n.destroy=l,Object.keys(e).forEach(t=>{n[t]=e[t]}),n.names=[],n.skips=[],n.formatters={};function t(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return n.colors[Math.abs(t)%n.colors.length]}n.selectColor=t;function n(e){let t,i=null,a,o;function s(...e){if(!s.enabled)return;let r=s,i=Number(new Date);r.diff=i-(t||i),r.prev=t,r.curr=i,t=i,e[0]=n.coerce(e[0]),typeof e[0]!=`string`&&e.unshift(`%O`);let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,i)=>{if(t===`%%`)return`%`;a++;let o=n.formatters[i];if(typeof o==`function`){let n=e[a];t=o.call(r,n),e.splice(a,1),a--}return t}),n.formatArgs.call(r,e),(r.log||n.log).apply(r,e)}return s.namespace=e,s.useColors=n.useColors(),s.color=n.selectColor(e),s.extend=r,s.destroy=n.destroy,Object.defineProperty(s,`enabled`,{enumerable:!0,configurable:!1,get:()=>i===null?(a!==n.namespaces&&(a=n.namespaces,o=n.enabled(e)),o):i,set:e=>{i=e}}),typeof n.init==`function`&&n.init(s),s}function r(e,t){let r=n(this.namespace+(t===void 0?`:`:t)+e);return r.log=this.log,r}function i(e){n.save(e),n.namespaces=e,n.names=[],n.skips=[];let t=(typeof e==`string`?e:``).trim().replace(/\s+/g,`,`).split(`,`).filter(Boolean);for(let e of t)e[0]===`-`?n.skips.push(e.slice(1)):n.names.push(e)}function a(e,t){let n=0,r=0,i=-1,a=0;for(;n<e.length;)if(r<t.length&&(t[r]===e[n]||t[r]===`*`))t[r]===`*`?(i=r,a=n,r++):(n++,r++);else if(i!==-1)r=i+1,a++,n=a;else return!1;for(;r<t.length&&t[r]===`*`;)r++;return r===t.length}function o(){let e=[...n.names,...n.skips.map(e=>`-`+e)].join(`,`);return n.enable(``),e}function s(e){for(let t of n.skips)if(a(e,t))return!1;for(let t of n.names)if(a(e,t))return!0;return!1}function c(e){return e instanceof Error?e.stack||e.message:e}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}t.exports=n})),xu=n(((e,t)=>{e.formatArgs=r,e.save=i,e.load=a,e.useColors=n,e.storage=o(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=`#0000CC.#0000FF.#0033CC.#0033FF.#0066CC.#0066FF.#0099CC.#0099FF.#00CC00.#00CC33.#00CC66.#00CC99.#00CCCC.#00CCFF.#3300CC.#3300FF.#3333CC.#3333FF.#3366CC.#3366FF.#3399CC.#3399FF.#33CC00.#33CC33.#33CC66.#33CC99.#33CCCC.#33CCFF.#6600CC.#6600FF.#6633CC.#6633FF.#66CC00.#66CC33.#9900CC.#9900FF.#9933CC.#9933FF.#99CC00.#99CC33.#CC0000.#CC0033.#CC0066.#CC0099.#CC00CC.#CC00FF.#CC3300.#CC3333.#CC3366.#CC3399.#CC33CC.#CC33FF.#CC6600.#CC6633.#CC9900.#CC9933.#CCCC00.#CCCC33.#FF0000.#FF0033.#FF0066.#FF0099.#FF00CC.#FF00FF.#FF3300.#FF3333.#FF3366.#FF3399.#FF33CC.#FF33FF.#FF6600.#FF6633.#FF9900.#FF9933.#FFCC00.#FFCC33`.split(`.`);function n(){if(typeof window<`u`&&window.process&&(window.process.type===`renderer`||window.process.__nwjs))return!0;if(typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<`u`&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<`u`&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<`u`&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(e){if(e[0]=(this.useColors?`%c`:``)+this.namespace+(this.useColors?` %c`:` `)+e[0]+(this.useColors?`%c `:` `)+`+`+t.exports.humanize(this.diff),!this.useColors)return;let n=`color: `+this.color;e.splice(1,0,n,`color: inherit`);let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{e!==`%%`&&(r++,e===`%c`&&(i=r))}),e.splice(i,0,n)}e.log=console.debug||console.log||(()=>{});function i(t){try{t?e.storage.setItem(`debug`,t):e.storage.removeItem(`debug`)}catch{}}function a(){let t;try{t=e.storage.getItem(`debug`)||e.storage.getItem(`DEBUG`)}catch{}return!t&&typeof process<`u`&&`env`in process&&(t=process.env.DEBUG),t}function o(){try{return localStorage}catch{}}t.exports=bu()(e);let{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})),Su=n(((e,t)=>{t.exports=(e,t=process.argv)=>{let n=e.startsWith(`-`)?``:e.length===1?`-`:`--`,r=t.indexOf(n+e),i=t.indexOf(`--`);return r!==-1&&(i===-1||r<i)}})),Cu=n(((e,n)=>{let r=t(`os`),i=t(`tty`),a=Su(),{env:o}=process,s;a(`no-color`)||a(`no-colors`)||a(`color=false`)||a(`color=never`)?s=0:(a(`color`)||a(`colors`)||a(`color=true`)||a(`color=always`))&&(s=1),`FORCE_COLOR`in o&&(s=o.FORCE_COLOR===`true`?1:o.FORCE_COLOR===`false`?0:o.FORCE_COLOR.length===0?1:Math.min(parseInt(o.FORCE_COLOR,10),3));function c(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function l(e,t){if(s===0)return 0;if(a(`color=16m`)||a(`color=full`)||a(`color=truecolor`))return 3;if(a(`color=256`))return 2;if(e&&!t&&s===void 0)return 0;let n=s||0;if(o.TERM===`dumb`)return n;if(process.platform===`win32`){let e=r.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in o)return[`TRAVIS`,`CIRCLECI`,`APPVEYOR`,`GITLAB_CI`,`GITHUB_ACTIONS`,`BUILDKITE`].some(e=>e in o)||o.CI_NAME===`codeship`?1:n;if(`TEAMCITY_VERSION`in o)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(o.TEAMCITY_VERSION)?1:0;if(o.COLORTERM===`truecolor`)return 3;if(`TERM_PROGRAM`in o){let e=parseInt((o.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(o.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(o.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(o.TERM)||`COLORTERM`in o?1:n}function u(e){return c(l(e,e&&e.isTTY))}n.exports={supportsColor:u,stdout:c(l(!0,i.isatty(1))),stderr:c(l(!0,i.isatty(2)))}})),wu=n(((e,n)=>{let r=t(`tty`),i=t(`util`);e.init=d,e.log=c,e.formatArgs=o,e.save=l,e.load=u,e.useColors=a,e.destroy=i.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{let t=Cu();t&&(t.stderr||t).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}e.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{let n=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase()),r=process.env[t];return r=/^(yes|on|true|enabled)$/i.test(r)?!0:/^(no|off|false|disabled)$/i.test(r)?!1:r===`null`?null:Number(r),e[n]=r,e},{});function a(){return`colors`in e.inspectOpts?!!e.inspectOpts.colors:r.isatty(process.stderr.fd)}function o(e){let{namespace:t,useColors:r}=this;if(r){let r=this.color,i=`\x1B[3`+(r<8?r:`8;5;`+r),a=` ${i};1m${t} \u001B[0m`;e[0]=a+e[0].split(`
18
18
  `).join(`
19
19
  `+a),e.push(i+`m+`+n.exports.humanize(this.diff)+`\x1B[0m`)}else e[0]=s()+t+` `+e[0]}function s(){return e.inspectOpts.hideDate?``:new Date().toISOString()+` `}function c(...t){return process.stderr.write(i.formatWithOptions(e.inspectOpts,...t)+`
20
- `)}function l(e){e?process.env.DEBUG=e:delete process.env.DEBUG}function u(){return process.env.DEBUG}function d(t){t.inspectOpts={};let n=Object.keys(e.inspectOpts);for(let r=0;r<n.length;r++)t.inspectOpts[n[r]]=e.inspectOpts[n[r]]}n.exports=vu()(e);let{formatters:f}=n.exports;f.o=function(e){return this.inspectOpts.colors=this.useColors,i.inspect(e,this.inspectOpts).split(`
21
- `).map(e=>e.trim()).join(` `)},f.O=function(e){return this.inspectOpts.colors=this.useColors,i.inspect(e,this.inspectOpts)}})),Cu=n(((e,t)=>{typeof process>`u`||process.type===`renderer`||process.browser===!0||process.__nwjs?t.exports=yu():t.exports=Su()}));const wu={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},Tu={get(e){return{signature:Ql.get(e,0),compressedSize:Ql.get(e,8),uncompressedSize:Ql.get(e,12)}},len:16},Eu={get(e){let t=Xl.get(e,6);return{signature:Ql.get(e,0),minVersion:Xl.get(e,4),dataDescriptor:!!(t&8),compressedMethod:Xl.get(e,8),compressedSize:Ql.get(e,18),uncompressedSize:Ql.get(e,22),filenameLength:Xl.get(e,26),extraFieldLength:Xl.get(e,28),filename:null}},len:30},Du={get(e){return{signature:Ql.get(e,0),nrOfThisDisk:Xl.get(e,4),nrOfThisDiskWithTheStart:Xl.get(e,6),nrOfEntriesOnThisDisk:Xl.get(e,8),nrOfEntriesOfSize:Xl.get(e,10),sizeOfCd:Ql.get(e,12),offsetOfStartOfCd:Ql.get(e,16),zipFileCommentLength:Xl.get(e,20)}},len:22},Ou={get(e){let t=Xl.get(e,8);return{signature:Ql.get(e,0),minVersion:Xl.get(e,6),dataDescriptor:!!(t&8),compressedMethod:Xl.get(e,10),compressedSize:Ql.get(e,20),uncompressedSize:Ql.get(e,24),filenameLength:Xl.get(e,28),extraFieldLength:Xl.get(e,30),fileCommentLength:Xl.get(e,32),relativeOffsetOfLocalHeader:Ql.get(e,42),filename:null}},len:46};var ku=e(Cu(),1);function Au(e){let t=new Uint8Array(Ql.len);return Ql.put(t,0,e),t}const ju=(0,ku.default)(`tokenizer:inflate`),Mu=256*1024,Nu=Au(wu.DataDescriptor),Pu=Au(wu.EndOfCentralDirectory);var Fu=class e{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(Mu)}async isZip(){return await this.peekSignature()===wu.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(Ql)}async findEndOfCentralDirectoryLocator(){let e=this.tokenizer,t=Math.min(16*1024,e.fileInfo.size),n=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(n,{position:e.fileInfo.size-t});for(let r=n.length-4;r>=0;r--)if(n[r]===Pu[0]&&n[r+1]===Pu[1]&&n[r+2]===Pu[2]&&n[r+3]===Pu[3])return e.fileInfo.size-t+r;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){ju(`Cannot reading central-directory without random-read support`);return}ju(`Reading central-directory...`);let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){ju(`Central-directory 32-bit signature found`);let n=await this.tokenizer.readToken(Du,t),r=[];this.tokenizer.setPosition(n.offsetOfStartOfCd);for(let e=0;e<n.nrOfEntriesOfSize;++e){let t=await this.tokenizer.readToken(Ou);if(t.signature!==wu.CentralFileHeader)throw Error(`Expected Central-File-Header signature`);t.filename=await this.tokenizer.readToken(new nu(t.filenameLength,`utf-8`)),await this.tokenizer.ignore(t.extraFieldLength),await this.tokenizer.ignore(t.fileCommentLength),r.push(t),ju(`Add central-directory file-entry: n=${e+1}/${r.length}: filename=${r[e].filename}`)}return this.tokenizer.setPosition(e),r}this.tokenizer.setPosition(e)}async unzip(e){let t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let n=!1;do{let t=await this.readLocalFileHeader();if(!t)break;let r=e(t);n=!!r.stop;let i;if(await this.tokenizer.ignore(t.extraFieldLength),t.dataDescriptor&&t.compressedSize===0){let e=[],n=Mu;ju(`Compressed-file-size unknown, scanning for next data-descriptor-signature....`);let i=-1;for(;i<0&&n===Mu;){n=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),i=Iu(this.syncBuffer.subarray(0,n),Nu);let t=i>=0?i:n;if(r.handler){let n=new Uint8Array(t);await this.tokenizer.readBuffer(n),e.push(n)}else await this.tokenizer.ignore(t)}ju(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),r.handler&&await this.inflate(t,Lu(e),r.handler)}else r.handler?(ju(`Reading compressed-file-data: ${t.compressedSize} bytes`),i=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(i),await this.inflate(t,i,r.handler)):(ju(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(ju(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor&&(await this.tokenizer.readToken(Tu)).signature!==134695760)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-Tu.len}`)}while(!n)}async iterateOverCentralDirectory(e,t){for(let n of e){let e=t(n);if(e.handler){this.tokenizer.setPosition(n.relativeOffsetOfLocalHeader);let t=await this.readLocalFileHeader();if(t){await this.tokenizer.ignore(t.extraFieldLength);let r=new Uint8Array(n.compressedSize);await this.tokenizer.readBuffer(r),await this.inflate(t,r,e.handler)}}if(e.stop)break}}async inflate(t,n,r){if(t.compressedMethod===0)return r(n);if(t.compressedMethod!==8)throw Error(`Unsupported ZIP compression method: ${t.compressedMethod}`);return ju(`Decompress filename=${t.filename}, compressed-size=${n.length}`),r(await e.decompressDeflateRaw(n))}static async decompressDeflateRaw(e){let t=new ReadableStream({start(t){t.enqueue(e),t.close()}}),n=new DecompressionStream(`deflate-raw`),r=t.pipeThrough(n);try{let e=await new Response(r).arrayBuffer();return new Uint8Array(e)}catch(e){let t=e instanceof Error?`Failed to deflate ZIP entry: ${e.message}`:`Unknown decompression error in ZIP entry`;throw TypeError(t)}}async readLocalFileHeader(){let e=await this.tokenizer.peekToken(Ql);if(e===wu.LocalFileHeader){let e=await this.tokenizer.readToken(Eu);return e.filename=await this.tokenizer.readToken(new nu(e.filenameLength,`utf-8`)),e}if(e===wu.CentralFileHeader)return!1;throw Error(e===3759263696?`Encrypted ZIP`:`Unexpected signature`)}};function Iu(e,t){let n=e.length,r=t.length;if(r>n)return-1;for(let i=0;i<=n-r;i++){let n=!0;for(let a=0;a<r;a++)if(e[i+a]!==t[a]){n=!1;break}if(n)return i}return-1}function Lu(e){let t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}var Ru=class{constructor(e){this.tokenizer=e}inflate(){let e=this.tokenizer;return new ReadableStream({async pull(t){let n=new Uint8Array(1024),r=await e.readBuffer(n,{mayBeLess:!0});if(r===0){t.close();return}t.enqueue(n.subarray(0,r))}}).pipeThrough(new DecompressionStream(`gzip`))}};const zu=Object.prototype.toString;function Bu(e,t,n){return e?e.constructor===t?!0:zu.call(e)===n:!1}function Vu(e){return Bu(e,Uint8Array,`[object Uint8Array]`)}function Hu(e){if(!Vu(e))throw TypeError(`Expected \`Uint8Array\`, got \`${typeof e}\``)}function Uu(e,t){if(e.length===0)return new Uint8Array;t??=e.reduce((e,t)=>e+t.length,0);let n=new Uint8Array(t),r=0;for(let t of e)Hu(t),n.set(t,r),r+=t.length;return n}new globalThis.TextDecoder(`utf8`),new globalThis.TextEncoder,Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function Wu(e){let{byteLength:t}=e;if(t===6)return e.getUint16(0)*2**32+e.getUint32(2);if(t===5)return e.getUint8(0)*2**32+e.getUint32(1);if(t===4)return e.getUint32(0);if(t===3)return e.getUint8(0)*2**16+e.getUint16(1);if(t===2)return e.getUint16(0);if(t===1)return e.getUint8(0)}function Gu(e,t){if(t===`utf-16le`){let t=[];for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t.push(r&255,r>>8&255)}return t}if(t===`utf-16be`){let t=[];for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t.push(r>>8&255,r&255)}return t}return[...e].map(e=>e.charCodeAt(0))}function Ku(e,t=0){let n=Number.parseInt(new nu(6).get(e,148).replace(/\0.*$/v,``).trim(),8);if(Number.isNaN(n))return!1;let r=256;for(let n=t;n<t+148;n++)r+=e[n];for(let n=t+156;n<t+512;n++)r+=e[n];return n===r}const qu={get:(e,t)=>e[t+3]&127|(e[t+2]&127)<<7|(e[t+1]&127)<<14|(e[t]&127)<<21,len:4},Ju=`jpg,png,apng,gif,webp,flif,xcf,cr2,cr3,orf,arw,dng,nef,rw2,raf,tif,bmp,icns,jxr,psd,indd,zip,tar,rar,gz,bz2,7z,dmg,mp4,mid,mkv,webm,mov,avi,mpg,mp2,mp3,m4a,oga,ogg,ogv,opus,flac,wav,spx,amr,pdf,epub,elf,macho,exe,swf,rtf,wasm,woff,woff2,eot,ttf,otf,ttc,ico,flv,ps,xz,sqlite,nes,crx,xpi,cab,deb,ar,rpm,Z,lz,cfb,mxf,mts,blend,bpg,docx,pptx,xlsx,3gp,3g2,j2c,jp2,jpm,jpx,mj2,aif,qcp,odt,ods,odp,xml,mobi,heic,cur,ktx,ape,wv,dcm,ics,glb,pcap,dsf,lnk,alias,voc,ac3,m4v,m4p,m4b,f4v,f4p,f4b,f4a,mie,asf,ogm,ogx,mpc,arrow,shp,aac,mp1,it,s3m,xm,skp,avif,eps,lzh,pgp,asar,stl,chm,3mf,zst,jxl,vcf,jls,pst,dwg,parquet,class,arj,cpio,ace,avro,icc,fbx,vsdx,vtt,apk,drc,lz4,potx,xltx,dotx,xltm,ott,ots,otp,odg,otg,xlsm,docm,dotm,potm,pptm,jar,jmp,rm,sav,ppsm,ppsx,tar.gz,reg,dat,key,numbers,pages`.split(`,`),Yu=`image/jpeg,image/png,image/gif,image/webp,image/flif,image/x-xcf,image/x-canon-cr2,image/x-canon-cr3,image/tiff,image/bmp,image/vnd.ms-photo,image/vnd.adobe.photoshop,application/x-indesign,application/epub+zip,application/x-xpinstall,application/vnd.ms-powerpoint.slideshow.macroenabled.12,application/vnd.oasis.opendocument.text,application/vnd.oasis.opendocument.spreadsheet,application/vnd.oasis.opendocument.presentation,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.presentationml.slideshow,application/zip,application/x-tar,application/x-rar-compressed,application/gzip,application/x-bzip2,application/x-7z-compressed,application/x-apple-diskimage,application/vnd.apache.arrow.file,video/mp4,audio/midi,video/matroska,video/webm,video/quicktime,video/vnd.avi,audio/wav,audio/qcelp,audio/x-ms-asf,video/x-ms-asf,application/vnd.ms-asf,video/mpeg,video/3gpp,audio/mpeg,audio/mp4,video/ogg,audio/ogg,audio/ogg; codecs=opus,application/ogg,audio/flac,audio/ape,audio/wavpack,audio/amr,application/pdf,application/x-elf,application/x-mach-binary,application/x-msdownload,application/x-shockwave-flash,application/rtf,application/wasm,font/woff,font/woff2,application/vnd.ms-fontobject,font/ttf,font/otf,font/collection,image/x-icon,video/x-flv,application/postscript,application/eps,application/x-xz,application/x-sqlite3,application/x-nintendo-nes-rom,application/x-google-chrome-extension,application/vnd.ms-cab-compressed,application/x-deb,application/x-unix-archive,application/x-rpm,application/x-compress,application/lzip,application/x-cfb,application/x-mie,application/mxf,video/mp2t,application/x-blender,image/bpg,image/j2c,image/jp2,image/jpx,image/jpm,image/mj2,audio/aiff,application/xml,application/x-mobipocket-ebook,image/heif,image/heif-sequence,image/heic,image/heic-sequence,image/icns,image/ktx,application/dicom,audio/x-musepack,text/calendar,text/vcard,text/vtt,model/gltf-binary,application/vnd.tcpdump.pcap,audio/x-dsf,application/x-ms-shortcut,application/x-ft-apple.alias,audio/x-voc,audio/vnd.dolby.dd-raw,audio/x-m4a,image/apng,image/x-olympus-orf,image/x-sony-arw,image/x-adobe-dng,image/x-nikon-nef,image/x-panasonic-rw2,image/x-fujifilm-raf,video/x-m4v,video/3gpp2,application/x-esri-shape,audio/aac,audio/x-it,audio/x-s3m,audio/x-xm,video/MP1S,video/MP2P,application/vnd.sketchup.skp,image/avif,application/x-lzh-compressed,application/pgp-encrypted,application/x-asar,model/stl,application/vnd.ms-htmlhelp,model/3mf,image/jxl,application/zstd,image/jls,application/vnd.ms-outlook,image/vnd.dwg,application/vnd.apache.parquet,application/java-vm,application/x-arj,application/x-cpio,application/x-ace-compressed,application/avro,application/vnd.iccprofile,application/x-ft-fbx,application/vnd.visio,application/vnd.android.package-archive,application/x-ft-draco,application/x-lz4,application/vnd.openxmlformats-officedocument.presentationml.template,application/vnd.openxmlformats-officedocument.spreadsheetml.template,application/vnd.openxmlformats-officedocument.wordprocessingml.template,application/vnd.ms-excel.template.macroenabled.12,application/vnd.oasis.opendocument.text-template,application/vnd.oasis.opendocument.spreadsheet-template,application/vnd.oasis.opendocument.presentation-template,application/vnd.oasis.opendocument.graphics,application/vnd.oasis.opendocument.graphics-template,application/vnd.ms-excel.sheet.macroenabled.12,application/vnd.ms-word.document.macroenabled.12,application/vnd.ms-word.template.macroenabled.12,application/vnd.ms-powerpoint.template.macroenabled.12,application/vnd.ms-powerpoint.presentation.macroenabled.12,application/java-archive,application/vnd.rn-realmedia,application/x-spss-sav,application/x-ms-regedit,application/x-ft-windows-registry-hive,application/x-jmp-data,application/vnd.apple.keynote,application/vnd.apple.numbers,application/vnd.apple.pages`.split(`,`),Xu=16*1024*1024;var Zu=class extends Error{};function Qu(e,t,n){if(!Number.isFinite(e)||e<0||e>t)throw new Zu(`${n} has invalid size ${e} (maximum ${t} bytes)`);return e}async function $u(e,t,{maximumLength:n=Xu,reason:r=`skip`}={}){let i=Qu(t,n,r);await e.ignore(i)}async function ed(e,t,n,{maximumLength:r=t.length,reason:i=`read`}={}){let a=Qu(n?.length??t.length,r,i);return e.readBuffer(t,{...n,length:a})}function td(e,t,n){n={offset:0,...n};for(let[r,i]of t.entries())if(n.mask){if(i!==(n.mask[r]&e[r+n.offset]))return!1}else if(i!==e[r+n.offset])return!1;return!0}function nd(e){let t=e.fileInfo.size;return!Number.isFinite(t)||t===2**53-1}function rd(e,t,n){return nd(e)&&e.position-t>n}const id=1024*1024,ad=1024,od=2**31-1,sd=id,cd=new Set([`Unexpected signature`,`Encrypted ZIP`,`Expected Central-File-Header signature`]),ld=[`ZIP entry count exceeds `,`Unsupported ZIP compression method:`,`ZIP entry compressed data exceeds `,`ZIP entry decompressed data exceeds `,`Expected data-descriptor-signature at position `],ud=new Set([`Z_BUF_ERROR`,`Z_DATA_ERROR`,`ERR_INVALID_STATE`]);async function dd(e,{maximumLength:t=id}={}){let n=new ReadableStream({start(t){t.enqueue(e),t.close()}}).pipeThrough(new DecompressionStream(`deflate-raw`)).getReader(),r=[],i=0;try{for(;;){let{done:e,value:a}=await n.read();if(e)break;if(i+=a.length,i>t)throw await n.cancel(),Error(`ZIP entry decompressed data exceeds ${t} bytes`);r.push(a)}}finally{n.releaseLock()}let a=new Uint8Array(i),o=0;for(let e of r)a.set(e,o),o+=e.length;return a}function fd(e,t){let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function pd(e){let t=e.fileInfo.size,n=Number.isFinite(t)?Math.max(0,t-e.position):2**53-1;return Math.min(n,od)}function md(e){if(e instanceof ru||e instanceof Zu)return!0;if(!(e instanceof Error))return!1;if(cd.has(e.message)||ud.has(e.code))return!0;for(let t of ld)if(e.message.startsWith(t))return!0;return!1}function hd(e,t=id){let n=[e.compressedSize,e.uncompressedSize];for(let e of n)if(!Number.isFinite(e)||e<0||e>t)return!1;return!0}function gd(){return{hasDocumentEntry:!1,hasMasterSlideEntry:!1,hasTablesEntry:!1,hasCalculationEngineEntry:!1}}function _d(e,t){t===`Index/Document.iwa`&&(e.hasDocumentEntry=!0),t.startsWith(`Index/MasterSlide`)&&(e.hasMasterSlideEntry=!0),t.startsWith(`Index/Tables/`)&&(e.hasTablesEntry=!0),t===`Index/CalculationEngine.iwa`&&(e.hasCalculationEngineEntry=!0)}function vd(e){if(e.hasDocumentEntry)return e.hasMasterSlideEntry?{ext:`key`,mime:`application/vnd.apple.keynote`}:e.hasTablesEntry?{ext:`numbers`,mime:`application/vnd.apple.numbers`}:{ext:`pages`,mime:`application/vnd.apple.pages`}}function yd(e){switch(e=e.toLowerCase(),e){case`application/epub+zip`:return{ext:`epub`,mime:e};case`application/vnd.oasis.opendocument.text`:return{ext:`odt`,mime:e};case`application/vnd.oasis.opendocument.text-template`:return{ext:`ott`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet`:return{ext:`ods`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet-template`:return{ext:`ots`,mime:e};case`application/vnd.oasis.opendocument.presentation`:return{ext:`odp`,mime:e};case`application/vnd.oasis.opendocument.presentation-template`:return{ext:`otp`,mime:e};case`application/vnd.oasis.opendocument.graphics`:return{ext:`odg`,mime:e};case`application/vnd.oasis.opendocument.graphics-template`:return{ext:`otg`,mime:e};case`application/vnd.openxmlformats-officedocument.presentationml.slideshow`:return{ext:`ppsx`,mime:e};case`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`:return{ext:`xlsx`,mime:e};case`application/vnd.ms-excel.sheet.macroenabled`:return{ext:`xlsm`,mime:`application/vnd.ms-excel.sheet.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.spreadsheetml.template`:return{ext:`xltx`,mime:e};case`application/vnd.ms-excel.template.macroenabled`:return{ext:`xltm`,mime:`application/vnd.ms-excel.template.macroenabled.12`};case`application/vnd.ms-powerpoint.slideshow.macroenabled`:return{ext:`ppsm`,mime:`application/vnd.ms-powerpoint.slideshow.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.document`:return{ext:`docx`,mime:e};case`application/vnd.ms-word.document.macroenabled`:return{ext:`docm`,mime:`application/vnd.ms-word.document.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.template`:return{ext:`dotx`,mime:e};case`application/vnd.ms-word.template.macroenabledtemplate`:return{ext:`dotm`,mime:`application/vnd.ms-word.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.template`:return{ext:`potx`,mime:e};case`application/vnd.ms-powerpoint.template.macroenabled`:return{ext:`potm`,mime:`application/vnd.ms-powerpoint.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.presentation`:return{ext:`pptx`,mime:e};case`application/vnd.ms-powerpoint.presentation.macroenabled`:return{ext:`pptm`,mime:`application/vnd.ms-powerpoint.presentation.macroenabled.12`};case`application/vnd.ms-visio.drawing`:return{ext:`vsdx`,mime:`application/vnd.visio`};case`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`:return{ext:`3mf`,mime:`model/3mf`};default:}}function bd(){return{hasContentTypesEntry:!1,hasParsedContentTypesEntry:!1,isParsingContentTypes:!1,hasUnparseableContentTypes:!1,hasWordDirectory:!1,hasPresentationDirectory:!1,hasSpreadsheetDirectory:!1,hasThreeDimensionalModelEntry:!1}}function xd(e,t){t.startsWith(`word/`)&&(e.hasWordDirectory=!0),t.startsWith(`ppt/`)&&(e.hasPresentationDirectory=!0),t.startsWith(`xl/`)&&(e.hasSpreadsheetDirectory=!0),t.startsWith(`3D/`)&&t.endsWith(`.model`)&&(e.hasThreeDimensionalModelEntry=!0)}function Sd(e){if(e.hasWordDirectory)return{ext:`docx`,mime:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`};if(e.hasPresentationDirectory)return{ext:`pptx`,mime:`application/vnd.openxmlformats-officedocument.presentationml.presentation`};if(e.hasSpreadsheetDirectory)return{ext:`xlsx`,mime:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`};if(e.hasThreeDimensionalModelEntry)return{ext:`3mf`,mime:`model/3mf`}}function Cd(e){if(!(!e.hasContentTypesEntry||e.hasUnparseableContentTypes||e.isParsingContentTypes||e.hasParsedContentTypesEntry))return Sd(e)}function wd(e){let t=e.indexOf(`.main+xml"`);if(t===-1){let t=`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`;return e.includes(`ContentType="${t}"`)?t:void 0}let n=e.slice(0,t),r=n.lastIndexOf(`"`);return n.slice(r+1)}const Td=134695760;function Ed(e,t){if(e.length<16)return-1;let n=e.length-16;for(let r=0;r<=n;r++)if(Ql.get(e,r)===Td&&Ql.get(e,r+8)===t+r)return r;return-1}async function Dd(e,{shouldBuffer:t,maximumLength:n=id}={}){let{syncBuffer:r}=e,{length:i}=r,a=[],o=0;for(;;){let s=await e.tokenizer.peekBuffer(r,{mayBeLess:!0}),c=Ed(r.subarray(0,s),o),l=c>=0?0:s===i?Math.min(15,s-1):0,u=c>=0?c:s-l;if(u===0)break;if(o+=u,o>n)throw Error(`ZIP entry compressed data exceeds ${n} bytes`);if(t){let t=new Uint8Array(u);await e.tokenizer.readBuffer(t),a.push(t)}else await e.tokenizer.ignore(u);if(c>=0)break}if(nd(e.tokenizer)||(e.knownSizeDescriptorScannedBytes+=o),t)return fd(a,o)}function Od(e,t){return nd(e.tokenizer)?Math.max(0,Xu-(e.tokenizer.position-t)):Math.max(0,id-e.knownSizeDescriptorScannedBytes)}async function kd(e,t,{shouldBuffer:n,maximumDescriptorLength:r=id}={}){if(t.dataDescriptor&&t.compressedSize===0)return Dd(e,{shouldBuffer:n,maximumLength:r});if(!n){await $u(e.tokenizer,t.compressedSize,{maximumLength:nd(e.tokenizer)?id:e.tokenizer.fileInfo.size,reason:`ZIP entry compressed data`});return}let i=pd(e.tokenizer);if(!Number.isFinite(t.compressedSize)||t.compressedSize<0||t.compressedSize>i)throw Error(`ZIP entry compressed data exceeds ${i} bytes`);let a=new Uint8Array(t.compressedSize);return await e.tokenizer.readBuffer(a),a}Fu.prototype.inflate=async function(e,t,n){if(e.compressedMethod===0)return n(t);if(e.compressedMethod!==8)throw Error(`Unsupported ZIP compression method: ${e.compressedMethod}`);return n(await dd(t,{maximumLength:id}))},Fu.prototype.unzip=async function(e){let t=!1,n=0,r=this.tokenizer.position;this.knownSizeDescriptorScannedBytes=0;do{if(rd(this.tokenizer,r,16777216))throw new Zu(`ZIP stream probing exceeds ${Xu} bytes`);let i=await this.readLocalFileHeader();if(!i)break;if(n++,n>ad)throw Error(`ZIP entry count exceeds ${ad}`);let a=e(i);t=!!a.stop,await this.tokenizer.ignore(i.extraFieldLength);let o=await kd(this,i,{shouldBuffer:!!a.handler,maximumDescriptorLength:Math.min(id,Od(this,r))});if(a.handler&&await this.inflate(i,o,a.handler),i.dataDescriptor){let e=new Uint8Array(16);if(await this.tokenizer.readBuffer(e),Ql.get(e,0)!==Td)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-e.length}`)}if(rd(this.tokenizer,r,16777216))throw new Zu(`ZIP stream probing exceeds ${Xu} bytes`)}while(!t)};async function Ad(e){let t,n=bd(),r=gd();try{await new Fu(e).unzip(e=>{if(xd(n,e.filename),_d(r,e.filename),r.hasDocumentEntry&&(r.hasMasterSlideEntry||r.hasTablesEntry))return t=vd(r),{stop:!0};let i=e.filename===`[Content_Types].xml`,a=Cd(n);if(!i&&a)return t=a,{stop:!0};switch(e.filename){case`META-INF/mozilla.rsa`:return t={ext:`xpi`,mime:`application/x-xpinstall`},{stop:!0};case`META-INF/MANIFEST.MF`:return t={ext:`jar`,mime:`application/java-archive`},{stop:!0};case`mimetype`:return hd(e,sd)?{async handler(e){t=yd(new TextDecoder(`utf-8`).decode(e).trim())},stop:!0}:{};case`[Content_Types].xml`:return n.hasContentTypesEntry=!0,hd(e,sd)?(n.isParsingContentTypes=!0,{async handler(e){let r=wd(new TextDecoder(`utf-8`).decode(e));r&&(t=yd(r)),n.hasParsedContentTypesEntry=!0,n.isParsingContentTypes=!1},stop:!0}):(n.hasUnparseableContentTypes=!0,{});default:return/classes\d*\.dex/v.test(e.filename)?(t={ext:`apk`,mime:`application/vnd.android.package-archive`},{stop:!0}):{}}})}catch(e){if(!md(e))throw e;n.isParsingContentTypes&&(n.isParsingContentTypes=!1,n.hasUnparseableContentTypes=!0),!t&&e instanceof ru&&!n.hasContentTypesEntry&&(t=Sd(n))}let i=nd(e)&&r.hasDocumentEntry&&!r.hasMasterSlideEntry&&!r.hasTablesEntry&&!r.hasCalculationEngineEntry?void 0:vd(r);return t??Cd(n)??i??{ext:`zip`,mime:`application/zip`}}const jd=1024*1024;async function Md(e){async function t(){let t=await e.peekNumber(Yl),n=128,r=0;for(;(t&n)===0&&n!==0;)++r,n>>=1;let i=new Uint8Array(r+1);return await ed(e,i,void 0,{maximumLength:i.length,reason:`EBML field`}),i}async function n(){let e=await t(),n=await t();n[0]^=128>>n.length-1;let r=Math.min(6,n.length),i=new DataView(e.buffer),a=new DataView(n.buffer,n.length-r,r);return{id:Wu(i),len:Wu(a)}}async function r(t){let r=0;for(;t>0;){if(r++,r>256||rd(e,a,16777216))return;let i=e.position,o=await n();if(o.id===17026){if(o.len>64)return;let t=Qu(o.len,64,`EBML DocType`);return(await e.readToken(new nu(t))).replaceAll(/\0.*$/gv,``)}if(nd(e)&&(!Number.isFinite(o.len)||o.len<0||o.len>jd)||(await $u(e,o.len,{maximumLength:nd(e)?jd:e.fileInfo.size,reason:`EBML payload`}),--t,e.position<=i))return}}let i=await n(),a=e.position;switch(await r(i.len)){case`webm`:return{ext:`webm`,mime:`video/webm`};case`matroska`:return{ext:`mkv`,mime:`video/matroska`};default:}}const Nd=1024*1024;function Pd(e){return(e.codePointAt(0)&32)!=0}async function Fd(e){let t={ext:`png`,mime:`image/png`},n={ext:`apng`,mime:`image/apng`};await e.ignore(8);async function r(){return{length:await e.readToken(eu),type:await e.readToken(new nu(4,`latin1`))}}let i=nd(e),a=e.position,o=0,s=!1;do{if(o++,o>512||rd(e,a,16777216))break;let c=e.position,l=await r();if(l.length<0)return;if(l.type===`IHDR`){if(l.length!==13)return;s=!0}switch(l.type){case`IDAT`:return t;case`acTL`:return n;default:if(!s&&l.type!==`CgBI`)return;if(i&&l.length>Nd)return s&&Pd(l.type)?t:void 0;try{await $u(e,l.length+4,{maximumLength:i?Nd+4:e.fileInfo.size,reason:`PNG chunk payload`})}catch(e){if(!i&&(e instanceof Zu||e instanceof ru))return t;throw e}}if(e.position<=c)break}while(e.position+8<e.fileInfo.size);return t}const Id=1024*1024;async function Ld(e){let t=!1;try{async function n(){let t=new Uint8Array(16);return await ed(e,t,void 0,{maximumLength:t.length,reason:`ASF header GUID`}),{id:t,size:Number(await e.readToken(tu))}}await $u(e,30,{maximumLength:30,reason:`ASF header prelude`});let r=nd(e),i=e.position,a=0;for(;e.position+24<e.fileInfo.size&&(a++,!(a>512||rd(e,i,16777216)));){let i=e.position,a=await n(),o=a.size-24;if(!Number.isFinite(o)||o<0){t=!0;break}if(td(a.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let t=new Uint8Array(16);if(o-=await ed(e,t,void 0,{maximumLength:t.length,reason:`ASF stream type GUID`}),td(t,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`audio/x-ms-asf`};if(td(t,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`video/x-ms-asf`};break}if(r&&o>Id){t=!0;break}if(await $u(e,o,{maximumLength:r?Id:e.fileInfo.size,reason:`ASF header payload`}),e.position<=i){t=!0;break}}}catch(n){if(n instanceof ru||n instanceof Zu)nd(e)&&(t=!0);else throw n}if(!t)return{ext:`asf`,mime:`application/vnd.ms-asf`}}const Rd=4100;Rd-2;const zd=Xu,Bd=Xu;function Vd(e){return Number.isFinite(e)?Math.max(1,Math.trunc(e)):Rd}function Hd(e){return Number.isFinite(e)?Math.max(0,Math.min(4098,Math.trunc(e))):0}function Ud(e){return Number.isFinite(e)?Math.max(0,e):2**53-1}function Wd(e){return import(e)}function Gd(e){return e.pipeThrough(new TransformStream)}function Kd(e,t){return t===void 0?e.read():(t.throwIfAborted(),Promise.race([e.read(),new Promise((n,r)=>{t.addEventListener(`abort`,()=>{r(t.reason),e.cancel(t.reason).catch(()=>{})},{once:!0})})]))}function qd(e,t){let n=e.getReader(),r=0,i=!1,a=!1,o=async e=>{i||a||(a=!0,await n.cancel(e))};return new ReadableStream({async pull(e){if(r>=t){e.close(),await o();return}let{done:a,value:s}=await n.read();if(a||!s){i=!0,e.close();return}let c=t-r;if(s.length>c){e.enqueue(s.subarray(0,c)),r+=c,e.close(),await o();return}e.enqueue(s),r+=s.length},async cancel(e){await o(e)}})}async function Jd(e,t){return new Yd(t).fromBuffer(e)}var Yd=class e{constructor(e){let t=Hd(e?.mpegOffsetTolerance);this.options={...e,mpegOffsetTolerance:t},this.detectors=[...this.options.customDetectors??[],{id:`core`,detect:this.detectConfident},{id:`core.imprecise`,detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:this.options.signal},this.gzipProbeDepth=0}getTokenizerOptions(){return{...this.tokenizerOptions}}createTokenizerFromWebStream(e){return mu(Gd(e),this.getTokenizerOptions())}async parseTokenizer(e,t=0){this.detectionReentryCount=t;let n=e.position;for(let t of this.detectors){let r;try{r=await t.detect(e)}catch(e){if(e instanceof ru||e instanceof Zu)return;throw e}if(r)return r;if(n!==e.position)return}}async fromTokenizer(e){try{return await this.parseTokenizer(e)}finally{await e.close()}}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``);let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t?.length>1)return this.fromTokenizer(hu(t,this.getTokenizerOptions()))}async fromBlob(e){this.options.signal?.throwIfAborted();let t=gu(e,this.getTokenizerOptions());return this.fromTokenizer(t)}async fromStream(e){this.options.signal?.throwIfAborted();let t=this.createTokenizerFromWebStream(e);return this.fromTokenizer(t)}async fromFile(e){this.options.signal?.throwIfAborted();let[{default:t},{FileTokenizer:n}]=await Promise.all([Wd(`node:fs/promises`),Wd(`strtok3`)]),r=await t.open(e,t.constants.O_RDONLY|t.constants.O_NONBLOCK),i=await r.stat();if(!i.isFile()){await r.close();return}let a=new n(r,{...this.getTokenizerOptions(),fileInfo:{path:e,size:i.size}});return this.fromTokenizer(a)}async toDetectionStream(e,t){this.options.signal?.throwIfAborted();let n=Vd(t?.sampleSize??4100),r,i=!1,a=e.getReader(),o=[],s=0;try{for(;s<n;){let{value:e,done:t}=await Kd(a,this.options.signal);if(t||!e){i=!0;break}o.push(e),s+=e.length}if(!i&&s===n){let{value:e,done:t}=await Kd(a,this.options.signal);t||!e?i=!0:(o.push(e),s+=e.length)}}finally{a.releaseLock()}if(s>0){let e=o.length===1?o[0]:Uu(o);try{r=await this.fromBuffer(e.subarray(0,n))}catch(e){if(!(e instanceof ru))throw e;r=void 0}!i&&r?.ext===`pages`&&(r={ext:`zip`,mime:`application/zip`})}let c=new TransformStream({start(e){for(let t of o)e.enqueue(t)},transform(e,t){t.enqueue(e)}}),l=e.pipeThrough(c);return l.fileType=r,l}async detectGzip(t){if(this.gzipProbeDepth>=1)return{ext:`gz`,mime:`application/gzip`};let n=qd(new Ru(t).inflate(),16777216),r=nd(t),i,a,o,s;if(r){let t=new AbortController;i=setTimeout(()=>{t.abort(new DOMException(`Operation timed out after 100 ms`,`TimeoutError`))},100),a=this.options.signal===void 0?t.signal:AbortSignal.any([this.options.signal,t.signal]),o=new e({...this.options,signal:a}),o.gzipProbeDepth=this.gzipProbeDepth+1}else this.gzipProbeDepth++;try{s=await(o??this).fromStream(n)}catch(e){if(e?.name===`AbortError`&&a?.reason?.name!==`TimeoutError`)throw e}finally{clearTimeout(i),r||this.gzipProbeDepth--}return s?.ext===`tar`?{ext:`tar.gz`,mime:`application/gzip`}:{ext:`gz`,mime:`application/gzip`}}check(e,t){return td(this.buffer,e,t)}checkString(e,t){return this.check(Gu(e,t?.encoding),t)}detectConfident=async e=>{if(this.buffer=new Uint8Array(Rd),e.fileInfo.size===void 0&&(e.fileInfo.size=2**53-1),this.tokenizer=e,nd(e)&&(await e.peekBuffer(this.buffer,{length:3,mayBeLess:!0}),this.check([31,139,8])))return this.detectGzip(e);if(await e.peekBuffer(this.buffer,{length:32,mayBeLess:!0}),this.check([66,77]))return{ext:`bmp`,mime:`image/bmp`};if(this.check([11,119]))return{ext:`ac3`,mime:`audio/vnd.dolby.dd-raw`};if(this.check([120,1]))return{ext:`dmg`,mime:`application/x-apple-diskimage`};if(this.check([77,90]))return{ext:`exe`,mime:`application/x-msdownload`};if(this.check([37,33]))return await e.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString(`PS-Adobe-`,{offset:2})&&this.checkString(` EPSF-`,{offset:14})?{ext:`eps`,mime:`application/eps`}:{ext:`ps`,mime:`application/postscript`};if(this.check([31,160])||this.check([31,157]))return{ext:`Z`,mime:`application/x-compress`};if(this.check([199,113]))return{ext:`cpio`,mime:`application/x-cpio`};if(this.check([96,234]))return{ext:`arj`,mime:`application/x-arj`};if(this.check([239,187,191]))return this.detectionReentryCount>=256?void 0:(this.detectionReentryCount++,await this.tokenizer.ignore(3),this.detectConfident(e));if(this.check([71,73,70]))return{ext:`gif`,mime:`image/gif`};if(this.check([73,73,188]))return{ext:`jxr`,mime:`image/vnd.ms-photo`};if(this.check([31,139,8]))return this.detectGzip(e);if(this.check([66,90,104]))return{ext:`bz2`,mime:`application/x-bzip2`};if(this.checkString(`ID3`)){await $u(e,6,{maximumLength:6,reason:`ID3 header prefix`});let t=await e.readToken(qu),n=nd(e);if(!Number.isFinite(t)||t<0||n&&(t>zd||e.position+t>zd))return;if(e.position+t>e.fileInfo.size)return n?void 0:{ext:`mp3`,mime:`audio/mpeg`};try{await $u(e,t,{maximumLength:n?zd:e.fileInfo.size,reason:`ID3 payload`})}catch(e){if(e instanceof ru)return;throw e}return this.detectionReentryCount>=256?void 0:(this.detectionReentryCount++,this.parseTokenizer(e,this.detectionReentryCount))}if(this.checkString(`MP+`))return{ext:`mpc`,mime:`audio/x-musepack`};if((this.buffer[0]===67||this.buffer[0]===70)&&this.check([87,83],{offset:1}))return{ext:`swf`,mime:`application/x-shockwave-flash`};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:`jls`,mime:`image/jls`}:{ext:`jpg`,mime:`image/jpeg`};if(this.check([79,98,106,1]))return{ext:`avro`,mime:`application/avro`};if(this.checkString(`FLIF`))return{ext:`flif`,mime:`image/flif`};if(this.checkString(`8BPS`))return{ext:`psd`,mime:`image/vnd.adobe.photoshop`};if(this.checkString(`MPCK`))return{ext:`mpc`,mime:`audio/x-musepack`};if(this.checkString(`FORM`))return{ext:`aif`,mime:`audio/aiff`};if(this.checkString(`icns`,{offset:0}))return{ext:`icns`,mime:`image/icns`};if(this.check([80,75,3,4]))return Ad(e);if(this.checkString(`OggS`)){await e.ignore(28);let t=new Uint8Array(8);return await e.readBuffer(t),td(t,[79,112,117,115,72,101,97,100])?{ext:`opus`,mime:`audio/ogg; codecs=opus`}:td(t,[128,116,104,101,111,114,97])?{ext:`ogv`,mime:`video/ogg`}:td(t,[1,118,105,100,101,111,0])?{ext:`ogm`,mime:`video/ogg`}:td(t,[127,70,76,65,67])?{ext:`oga`,mime:`audio/ogg`}:td(t,[83,112,101,101,120,32,32])?{ext:`spx`,mime:`audio/ogg`}:td(t,[1,118,111,114,98,105,115])?{ext:`ogg`,mime:`audio/ogg`}:{ext:`ogx`,mime:`application/ogg`}}if(this.check([80,75])&&(this.buffer[2]===3||this.buffer[2]===5||this.buffer[2]===7)&&(this.buffer[3]===4||this.buffer[3]===6||this.buffer[3]===8))return{ext:`zip`,mime:`application/zip`};if(this.checkString(`MThd`))return{ext:`mid`,mime:`audio/midi`};if(this.checkString(`wOFF`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff`,mime:`font/woff`};if(this.checkString(`wOF2`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff2`,mime:`font/woff2`};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:`pcap`,mime:`application/vnd.tcpdump.pcap`};if(this.checkString(`DSD `))return{ext:`dsf`,mime:`audio/x-dsf`};if(this.checkString(`LZIP`))return{ext:`lz`,mime:`application/lzip`};if(this.checkString(`fLaC`))return{ext:`flac`,mime:`audio/flac`};if(this.check([66,80,71,251]))return{ext:`bpg`,mime:`image/bpg`};if(this.checkString(`wvpk`))return{ext:`wv`,mime:`audio/wavpack`};if(this.checkString(`%PDF`))return{ext:`pdf`,mime:`application/pdf`};if(this.check([0,97,115,109]))return{ext:`wasm`,mime:`application/wasm`};if(this.check([73,73])){let e=await this.readTiffHeader(!1);if(e)return e}if(this.check([77,77])){let e=await this.readTiffHeader(!0);if(e)return e}if(this.checkString(`MAC `))return{ext:`ape`,mime:`audio/ape`};if(this.check([26,69,223,163]))return Md(e);if(this.checkString(`SQLi`))return{ext:`sqlite`,mime:`application/x-sqlite3`};if(this.check([78,69,83,26]))return{ext:`nes`,mime:`application/x-nintendo-nes-rom`};if(this.checkString(`Cr24`))return{ext:`crx`,mime:`application/x-google-chrome-extension`};if(this.checkString(`MSCF`)||this.checkString(`ISc(`))return{ext:`cab`,mime:`application/vnd.ms-cab-compressed`};if(this.check([237,171,238,219]))return{ext:`rpm`,mime:`application/x-rpm`};if(this.check([197,208,211,198]))return{ext:`eps`,mime:`application/eps`};if(this.check([40,181,47,253]))return{ext:`zst`,mime:`application/zstd`};if(this.check([127,69,76,70]))return{ext:`elf`,mime:`application/x-elf`};if(this.check([33,66,68,78]))return{ext:`pst`,mime:`application/vnd.ms-outlook`};if(this.checkString(`PAR1`)||this.checkString(`PARE`))return{ext:`parquet`,mime:`application/vnd.apache.parquet`};if(this.checkString(`ttcf`))return{ext:`ttc`,mime:`font/collection`};if(this.check([254,237,250,206])||this.check([254,237,250,207])||this.check([206,250,237,254])||this.check([207,250,237,254]))return{ext:`macho`,mime:`application/x-mach-binary`};if(this.check([4,34,77,24]))return{ext:`lz4`,mime:`application/x-lz4`};if(this.checkString(`regf`))return{ext:`dat`,mime:`application/x-ft-windows-registry-hive`};if(this.checkString(`$FL2`)||this.checkString(`$FL3`))return{ext:`sav`,mime:`application/x-spss-sav`};if(this.check([79,84,84,79,0]))return{ext:`otf`,mime:`font/otf`};if(this.checkString(`#!AMR`))return{ext:`amr`,mime:`audio/amr`};if(this.checkString(String.raw`{\rtf`))return{ext:`rtf`,mime:`application/rtf`};if(this.check([70,76,86,1]))return{ext:`flv`,mime:`video/x-flv`};if(this.checkString(`IMPM`))return{ext:`it`,mime:`audio/x-it`};if(this.checkString(`-lh0-`,{offset:2})||this.checkString(`-lh1-`,{offset:2})||this.checkString(`-lh2-`,{offset:2})||this.checkString(`-lh3-`,{offset:2})||this.checkString(`-lh4-`,{offset:2})||this.checkString(`-lh5-`,{offset:2})||this.checkString(`-lh6-`,{offset:2})||this.checkString(`-lh7-`,{offset:2})||this.checkString(`-lzs-`,{offset:2})||this.checkString(`-lz4-`,{offset:2})||this.checkString(`-lz5-`,{offset:2})||this.checkString(`-lhd-`,{offset:2}))return{ext:`lzh`,mime:`application/x-lzh-compressed`};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:`mpg`,mime:`video/MP1S`};if(this.check([68],{offset:4,mask:[196]}))return{ext:`mpg`,mime:`video/MP2P`}}if(this.checkString(`ITSF`))return{ext:`chm`,mime:`application/vnd.ms-htmlhelp`};if(this.check([202,254,186,190])){let e=$l.get(this.buffer,4),t=Zl.get(this.buffer,6);if(e>0&&e<=30)return{ext:`macho`,mime:`application/x-mach-binary`};if(t>30)return{ext:`class`,mime:`application/java-vm`}}if(this.checkString(`.RMF`))return{ext:`rm`,mime:`application/vnd.rn-realmedia`};if(this.checkString(`DRACO`))return{ext:`drc`,mime:`application/x-ft-draco`};if(this.check([253,55,122,88,90,0]))return{ext:`xz`,mime:`application/x-xz`};if(this.checkString(`<?xml `))return{ext:`xml`,mime:`application/xml`};if(this.check([55,122,188,175,39,28]))return{ext:`7z`,mime:`application/x-7z-compressed`};if(this.check([82,97,114,33,26,7])&&(this.buffer[6]===0||this.buffer[6]===1))return{ext:`rar`,mime:`application/x-rar-compressed`};if(this.checkString(`solid `))return{ext:`stl`,mime:`model/stl`};if(this.checkString(`AC`)){let e=new nu(4,`latin1`).get(this.buffer,2);if(/^\d+$/v.test(e)&&e>=1e3&&e<=1050)return{ext:`dwg`,mime:`image/vnd.dwg`}}if(this.checkString(`070707`))return{ext:`cpio`,mime:`application/x-cpio`};if(this.checkString(`BLENDER`))return{ext:`blend`,mime:`application/x-blender`};if(this.checkString(`!<arch>`))return await e.ignore(8),await e.readToken(new nu(13,`ascii`))===`debian-binary`?{ext:`deb`,mime:`application/x-deb`}:{ext:`ar`,mime:`application/x-unix-archive`};if(this.checkString(`WEBVTT`)&&[`
22
- `,`\r`,` `,` `,`\0`].some(e=>this.checkString(e,{offset:6})))return{ext:`vtt`,mime:`text/vtt`};if(this.check([137,80,78,71,13,10,26,10]))return Fd(e);if(this.check([65,82,82,79,87,49,0,0]))return{ext:`arrow`,mime:`application/vnd.apache.arrow.file`};if(this.check([103,108,84,70,2,0,0,0]))return{ext:`glb`,mime:`model/gltf-binary`};if(this.check([102,114,101,101],{offset:4})||this.check([109,100,97,116],{offset:4})||this.check([109,111,111,118],{offset:4})||this.check([119,105,100,101],{offset:4}))return{ext:`mov`,mime:`video/quicktime`};if(this.check([73,73,82,79,8,0,0,0,24]))return{ext:`orf`,mime:`image/x-olympus-orf`};if(this.checkString(`gimp xcf `))return{ext:`xcf`,mime:`image/x-xcf`};if(this.checkString(`ftyp`,{offset:4})&&this.buffer[8]&96){let e=new nu(4,`latin1`).get(this.buffer,8).replace(`\0`,` `).trim();switch(e){case`avif`:case`avis`:return{ext:`avif`,mime:`image/avif`};case`mif1`:return{ext:`heic`,mime:`image/heif`};case`msf1`:return{ext:`heic`,mime:`image/heif-sequence`};case`heic`:case`heix`:return{ext:`heic`,mime:`image/heic`};case`hevc`:case`hevx`:return{ext:`heic`,mime:`image/heic-sequence`};case`qt`:return{ext:`mov`,mime:`video/quicktime`};case`M4V`:case`M4VH`:case`M4VP`:return{ext:`m4v`,mime:`video/x-m4v`};case`M4P`:return{ext:`m4p`,mime:`video/mp4`};case`M4B`:return{ext:`m4b`,mime:`audio/mp4`};case`M4A`:return{ext:`m4a`,mime:`audio/x-m4a`};case`F4V`:return{ext:`f4v`,mime:`video/mp4`};case`F4P`:return{ext:`f4p`,mime:`video/mp4`};case`F4A`:return{ext:`f4a`,mime:`audio/mp4`};case`F4B`:return{ext:`f4b`,mime:`audio/mp4`};case`crx`:return{ext:`cr3`,mime:`image/x-canon-cr3`};default:return e.startsWith(`3g`)?e.startsWith(`3g2`)?{ext:`3g2`,mime:`video/3gpp2`}:{ext:`3gp`,mime:`video/3gpp`}:{ext:`mp4`,mime:`video/mp4`}}}if(this.checkString(`REGEDIT4\r
23
- `))return{ext:`reg`,mime:`application/x-ms-regedit`};if(this.check([82,73,70,70])){if(this.checkString(`WEBP`,{offset:8}))return{ext:`webp`,mime:`image/webp`};if(this.check([65,86,73],{offset:8}))return{ext:`avi`,mime:`video/vnd.avi`};if(this.check([87,65,86,69],{offset:8}))return{ext:`wav`,mime:`audio/wav`};if(this.check([81,76,67,77],{offset:8}))return{ext:`qcp`,mime:`audio/qcelp`}}if(this.check([73,73,85,0,24,0,0,0,136,231,116,216]))return{ext:`rw2`,mime:`image/x-panasonic-rw2`};if(this.check([48,38,178,117,142,102,207,17,166,217]))return Ld(e);if(this.check([171,75,84,88,32,49,49,187,13,10,26,10]))return{ext:`ktx`,mime:`image/ktx`};if((this.check([126,16,4])||this.check([126,24,4]))&&this.check([48,77,73,69],{offset:4}))return{ext:`mie`,mime:`application/x-mie`};if(this.check([39,10,0,0,0,0,0,0,0,0,0,0],{offset:2}))return{ext:`shp`,mime:`application/x-esri-shape`};if(this.check([255,79,255,81]))return{ext:`j2c`,mime:`image/j2c`};if(this.check([0,0,0,12,106,80,32,32,13,10,135,10]))switch(await e.ignore(20),await e.readToken(new nu(4,`ascii`))){case`jp2 `:return{ext:`jp2`,mime:`image/jp2`};case`jpx `:return{ext:`jpx`,mime:`image/jpx`};case`jpm `:return{ext:`jpm`,mime:`image/jpm`};case`mjp2`:return{ext:`mj2`,mime:`image/mj2`};default:return}if(this.check([255,10])||this.check([0,0,0,12,74,88,76,32,13,10,135,10]))return{ext:`jxl`,mime:`image/jxl`};if(this.check([254,255]))return this.checkString(`<?xml `,{offset:2,encoding:`utf-16be`})?{ext:`xml`,mime:`application/xml`}:void 0;if(this.check([208,207,17,224,161,177,26,225]))return{ext:`cfb`,mime:`application/x-cfb`};if(await e.peekBuffer(this.buffer,{length:Math.min(256,e.fileInfo.size),mayBeLess:!0}),this.check([97,99,115,112],{offset:36}))return{ext:`icc`,mime:`application/vnd.iccprofile`};if(this.checkString(`**ACE`,{offset:7})&&this.checkString(`**`,{offset:12}))return{ext:`ace`,mime:`application/x-ace-compressed`};if(this.checkString(`BEGIN:`)){if(this.checkString(`VCARD`,{offset:6}))return{ext:`vcf`,mime:`text/vcard`};if(this.checkString(`VCALENDAR`,{offset:6}))return{ext:`ics`,mime:`text/calendar`}}if(this.checkString(`FUJIFILMCCD-RAW`))return{ext:`raf`,mime:`image/x-fujifilm-raf`};if(this.checkString(`Extended Module:`))return{ext:`xm`,mime:`audio/x-xm`};if(this.checkString(`Creative Voice File`))return{ext:`voc`,mime:`audio/x-voc`};if(this.check([4,0,0,0])&&this.buffer.length>=16){let e=new DataView(this.buffer.buffer).getUint32(12,!0);if(e>12&&this.buffer.length>=e+16)try{let t=new TextDecoder().decode(this.buffer.subarray(16,e+16));if(JSON.parse(t).files)return{ext:`asar`,mime:`application/x-asar`}}catch{}}if(this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2]))return{ext:`mxf`,mime:`application/mxf`};if(this.checkString(`SCRM`,{offset:44}))return{ext:`s3m`,mime:`audio/x-s3m`};if(this.check([71])&&this.check([71],{offset:188})||this.check([71],{offset:4})&&this.check([71],{offset:196}))return{ext:`mts`,mime:`video/mp2t`};if(this.check([66,79,79,75,77,79,66,73],{offset:60}))return{ext:`mobi`,mime:`application/x-mobipocket-ebook`};if(this.check([68,73,67,77],{offset:128}))return{ext:`dcm`,mime:`application/dicom`};if(this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70]))return{ext:`lnk`,mime:`application/x-ms-shortcut`};if(this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0]))return{ext:`alias`,mime:`application/x-ft-apple.alias`};if(this.checkString(`Kaydara FBX Binary \0`))return{ext:`fbx`,mime:`application/x-ft-fbx`};if(this.check([76,80],{offset:34})&&(this.check([0,0,1],{offset:8})||this.check([1,0,2],{offset:8})||this.check([2,0,2],{offset:8})))return{ext:`eot`,mime:`application/vnd.ms-fontobject`};if(this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29]))return{ext:`indd`,mime:`application/x-indesign`};if(this.check([255,255,0,0,7,0,0,0,4,0,0,0,1,0,1,0])||this.check([0,0,255,255,0,0,0,7,0,0,0,4,0,1,0,1]))return{ext:`jmp`,mime:`application/x-jmp-data`};if(await e.peekBuffer(this.buffer,{length:Math.min(512,e.fileInfo.size),mayBeLess:!0}),this.checkString(`ustar`,{offset:257})&&(this.checkString(`\0`,{offset:262})||this.checkString(` `,{offset:262}))||this.check([0,0,0,0,0,0],{offset:257})&&Ku(this.buffer))return{ext:`tar`,mime:`application/x-tar`};if(this.check([255,254])){let e=`utf-16le`;return this.checkString(`<?xml `,{offset:2,encoding:e})?{ext:`xml`,mime:`application/xml`}:this.check([255,14],{offset:2})&&this.checkString(`SketchUp Model`,{offset:4,encoding:e})?{ext:`skp`,mime:`application/vnd.sketchup.skp`}:this.checkString(`Windows Registry Editor Version 5.00\r
24
- `,{offset:2,encoding:e})?{ext:`reg`,mime:`application/x-ms-regedit`}:void 0}if(this.checkString(`-----BEGIN PGP MESSAGE-----`))return{ext:`pgp`,mime:`application/pgp-encrypted`}};detectImprecise=async e=>{this.buffer=new Uint8Array(Rd);let t=Ud(e.fileInfo.size);if(await e.peekBuffer(this.buffer,{length:Math.min(8,t),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:`mpg`,mime:`video/mpeg`};if(this.check([0,1,0,0,0]))return{ext:`ttf`,mime:`font/ttf`};if(this.check([0,0,1,0]))return{ext:`ico`,mime:`image/x-icon`};if(this.check([0,0,2,0]))return{ext:`cur`,mime:`image/x-icon`};if(await e.peekBuffer(this.buffer,{length:Math.min(2+this.options.mpegOffsetTolerance,t),mayBeLess:!0}),this.buffer.length>=2+this.options.mpegOffsetTolerance)for(let e=0;e<=this.options.mpegOffsetTolerance;++e){let t=this.scanMpeg(e);if(t)return t}};async readTiffTag(e){let t=await this.tokenizer.readToken(e?Zl:Xl);switch(await this.tokenizer.ignore(10),t){case 50341:return{ext:`arw`,mime:`image/x-sony-arw`};case 50706:return{ext:`dng`,mime:`image/x-adobe-dng`};default:}}async readTiffIFD(e){let t=await this.tokenizer.readToken(e?Zl:Xl);if(!(t>512)&&!(nd(this.tokenizer)&&2+t*12>Bd))for(let n=0;n<t;++n){let t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){let t={ext:`tif`,mime:`image/tiff`},n=(e?Zl:Xl).get(this.buffer,2),r=(e?$l:Ql).get(this.buffer,4);if(n===42){if(r>=6){if(this.checkString(`CR`,{offset:8}))return{ext:`cr2`,mime:`image/x-canon-cr2`};if(r>=8){let t=(e?Zl:Xl).get(this.buffer,8),n=(e?Zl:Xl).get(this.buffer,10);if(t===28&&n===254||t===31&&n===11)return{ext:`nef`,mime:`image/x-nikon-nef`}}}if(nd(this.tokenizer)&&r>1048576)return t;let n=nd(this.tokenizer)?Bd:this.tokenizer.fileInfo.size;try{await $u(this.tokenizer,r,{maximumLength:n,reason:`TIFF IFD offset`})}catch(e){if(e instanceof ru)return;throw e}let i;try{i=await this.readTiffIFD(e)}catch(e){if(e instanceof ru)return;throw e}return i??t}if(n===43)return t}scanMpeg(e){if(this.check([255,224],{offset:e,mask:[255,224]})){if(this.check([16],{offset:e+1,mask:[22]}))return this.check([8],{offset:e+1,mask:[8]}),{ext:`aac`,mime:`audio/aac`};if(this.check([2],{offset:e+1,mask:[6]}))return{ext:`mp3`,mime:`audio/mpeg`};if(this.check([4],{offset:e+1,mask:[6]}))return{ext:`mp2`,mime:`audio/mpeg`};if(this.check([6],{offset:e+1,mask:[6]}))return{ext:`mp1`,mime:`audio/mpeg`}}}};new Set(Ju),new Set(Yu);let Xd=new Map;function Zd(e,t,n,r){let i=Xd.get(t);i||(i={agentId:t,displayName:n,colorSeed:r??n,docs:new Set},Xd.set(t,i)),i.docs.add(e)}function Qd(){let e=Xd;return Xd=new Map,e}function $d(e){for(let[t,n]of e){let e=Xd.get(t);e||(e={agentId:t,displayName:n.displayName,colorSeed:n.colorSeed,docs:new Set},Xd.set(t,e));for(let t of n.docs)e.docs.add(t)}}function ef(e){if(e.size===0)return``;let t=[``];for(let n of e.values())t.push(`ok-contributors: ${JSON.stringify({v:1,id:n.agentId,name:n.displayName,colorSeed:n.colorSeed,docs:[...n.docs]})}`);return t.join(`
25
- `)}const tf=[`INDEX`,`README`,`REPORT`,`SPEC`];function nf(e,t){let n=[],r=new Set,i=t=>{!t||r.has(t)||t!==e&&(r.add(t),n.push(t))},a=af(t),o=of(e);for(;;){for(let e of tf)if(i(rf(t,a,cf(o,e))),n.length>=3)return n;let e=o===``?null:sf(o);if(e&&(i(rf(t,a,cf(o,e))),n.length>=3))return n;if(o===``)break;o=of(o)}return n}function rf(e,t,n){return e.has(n)?n:t.get(n.toLowerCase())??null}function af(e){let t=new Map;for(let n of e.keys()){let e=n.toLowerCase();t.has(e)||t.set(e,n)}return t}function of(e){let t=e.lastIndexOf(`/`);return t<0?``:e.slice(0,t)}function sf(e){let t=e.lastIndexOf(`/`);return t<0?e:e.slice(t+1)}function cf(e,t){return e===``?t:`${e}/${t}`}function lf(e){return e?e.replace(/^---\r?\n/,``).replace(/\r?\n---(?:\r?\n)?$/,``).split(/\r?\n/):[]}function uf(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1).trim():t}function df(e,t){let n=`${t}:`;for(let t of lf(e))if(t.startsWith(n))return uf(t.slice(n.length))||null;return null}function ff(e){let t=[],n=``,r=null;for(let i of e){if(r){n+=i,i===r&&(r=null);continue}if(i===`"`||i===`'`){r=i,n+=i;continue}if(i===`,`){let e=uf(n);e&&t.push(e),n=``;continue}n+=i}let i=uf(n);return i&&t.push(i),t}function pf(e){let t=[],n=new Set;for(let r of e)!r||n.has(r)||(n.add(r),t.push(r));return t}function mf(e){let{frontmatter:t}=A(e);if(!t)return[];let n=lf(t);for(let e=0;e<n.length;e+=1){let t=n[e]?.match(/^aliases:\s*(.*)$/);if(!t)continue;let r=t[1]?.trim()??``;if(r){if(r.startsWith(`[`)&&r.endsWith(`]`))return pf(ff(r.slice(1,-1)));let e=uf(r);return e?[e]:[]}let i=[];for(let t=e+1;t<n.length;t+=1){let e=n[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=uf(e.replace(/^\s*-\s+/,``));t&&i.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return pf(i)}return[]}function hf(e,t){let{frontmatter:n,body:r}=A(e),i=df(n,`title`);if(i)return i;let a=r.match(/^# (.+)$/m);return a?a[1].trim():t}function gf(e){return e?.trim()?{cluster:df(e,`cluster`)??void 0,category:df(e,`category`)??void 0,tags:_f(e,`tags`)}:{cluster:void 0,category:void 0,tags:void 0}}function _f(e,t){let n=`${t}:`,r=lf(e);for(let e=0;e<r.length;e+=1){let t=r[e];if(!t?.startsWith(n))continue;let i=t.slice(n.length).trim();if(i){if(i.startsWith(`[`)&&i.endsWith(`]`)){let e=ff(i.slice(1,-1));return e.length>0?e:void 0}let e=uf(i);return e?[e]:void 0}let a=[];for(let t=e+1;t<r.length;t+=1){let e=r[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=uf(e.replace(/^\s*-\s+/,``));t&&a.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return a.length>0?a:void 0}}function vf(e,t){let n=hf(e,t),r=mf(e),i=pf([n,...r]),a=[],o=new Set;for(let e of i){let t=h(e);!t||o.has(t)||(o.add(t),a.push(t))}return{docName:t,title:n,aliases:r,matchLabels:i,normalizedMatchLabels:a}}var yf=class extends P{constructor(e,t){super(e,t,`ui`),this.name=`UiLockCollisionError`}};function bf(e,t){try{return F({lockName:`ui`,lockDir:e,metadata:t}).lockPath}catch(e){throw e instanceof P&&e.lockName===`ui`?new yf(e.existing,e.lockPath):e}}function xf(e,t){M({lockName:`ui`,lockDir:e,port:t})}function Sf(e){return te({lockName:`ui`,lockDir:e})}function Cf(e){ie({lockName:`ui`,lockDir:e})}const wf=[`.mdx`,`.md`];function Tf(e){let t=Se(e).toLowerCase();return wf.includes(t)}function Ef(e){let t=e.toLowerCase();for(let n of wf)if(t.endsWith(n))return e.slice(0,-n.length);return e}function Df(e){return wf.indexOf(e)}const Of=new Map;function kf(e,t){let n=Of.get(e);return n?n===t?{effective:n,changed:!1,shadowed:null}:Df(t)<Df(n)?(Of.set(e,t),{effective:t,changed:!0,shadowed:n}):{effective:n,changed:!1,shadowed:t}:(Of.set(e,t),{effective:t,changed:!0,shadowed:null})}function Af(e){return Of.get(e)??`.md`}function jf(e){Of.delete(e)}const Mf=/\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/y,Nf=/\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y;function Pf(){return{backward:new Map,forward:new Map,externalForward:new Map,externalBackward:new Map}}function Ff(e,t){return e?{anchor:e.anchor??t.anchor,snippet:e.snippet??t.snippet}:t}function If(e){if(!e)return null;for(let[,t]of[...e.entries()].sort(([e],[t])=>e.localeCompare(t)))if(t.anchor)return t.anchor;return null}function Lf(e){return`external:${e}`}function Rf(e){return e.startsWith(`external:`)?e.slice(9):null}function zf(e){return e.replace(/\s+/g,` `).trim()}function Bf(e,t,n){if(!zf(e))return null;let r=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
20
+ `)}function l(e){e?process.env.DEBUG=e:delete process.env.DEBUG}function u(){return process.env.DEBUG}function d(t){t.inspectOpts={};let n=Object.keys(e.inspectOpts);for(let r=0;r<n.length;r++)t.inspectOpts[n[r]]=e.inspectOpts[n[r]]}n.exports=bu()(e);let{formatters:f}=n.exports;f.o=function(e){return this.inspectOpts.colors=this.useColors,i.inspect(e,this.inspectOpts).split(`
21
+ `).map(e=>e.trim()).join(` `)},f.O=function(e){return this.inspectOpts.colors=this.useColors,i.inspect(e,this.inspectOpts)}})),Tu=n(((e,t)=>{typeof process>`u`||process.type===`renderer`||process.browser===!0||process.__nwjs?t.exports=xu():t.exports=wu()}));const Eu={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},Du={get(e){return{signature:eu.get(e,0),compressedSize:eu.get(e,8),uncompressedSize:eu.get(e,12)}},len:16},Ou={get(e){let t=Ql.get(e,6);return{signature:eu.get(e,0),minVersion:Ql.get(e,4),dataDescriptor:!!(t&8),compressedMethod:Ql.get(e,8),compressedSize:eu.get(e,18),uncompressedSize:eu.get(e,22),filenameLength:Ql.get(e,26),extraFieldLength:Ql.get(e,28),filename:null}},len:30},ku={get(e){return{signature:eu.get(e,0),nrOfThisDisk:Ql.get(e,4),nrOfThisDiskWithTheStart:Ql.get(e,6),nrOfEntriesOnThisDisk:Ql.get(e,8),nrOfEntriesOfSize:Ql.get(e,10),sizeOfCd:eu.get(e,12),offsetOfStartOfCd:eu.get(e,16),zipFileCommentLength:Ql.get(e,20)}},len:22},Au={get(e){let t=Ql.get(e,8);return{signature:eu.get(e,0),minVersion:Ql.get(e,6),dataDescriptor:!!(t&8),compressedMethod:Ql.get(e,10),compressedSize:eu.get(e,20),uncompressedSize:eu.get(e,24),filenameLength:Ql.get(e,28),extraFieldLength:Ql.get(e,30),fileCommentLength:Ql.get(e,32),relativeOffsetOfLocalHeader:eu.get(e,42),filename:null}},len:46};var ju=e(Tu(),1);function Mu(e){let t=new Uint8Array(eu.len);return eu.put(t,0,e),t}const Nu=(0,ju.default)(`tokenizer:inflate`),Pu=256*1024,Fu=Mu(Eu.DataDescriptor),Iu=Mu(Eu.EndOfCentralDirectory);var Lu=class e{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(Pu)}async isZip(){return await this.peekSignature()===Eu.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(eu)}async findEndOfCentralDirectoryLocator(){let e=this.tokenizer,t=Math.min(16*1024,e.fileInfo.size),n=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(n,{position:e.fileInfo.size-t});for(let r=n.length-4;r>=0;r--)if(n[r]===Iu[0]&&n[r+1]===Iu[1]&&n[r+2]===Iu[2]&&n[r+3]===Iu[3])return e.fileInfo.size-t+r;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){Nu(`Cannot reading central-directory without random-read support`);return}Nu(`Reading central-directory...`);let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){Nu(`Central-directory 32-bit signature found`);let n=await this.tokenizer.readToken(ku,t),r=[];this.tokenizer.setPosition(n.offsetOfStartOfCd);for(let e=0;e<n.nrOfEntriesOfSize;++e){let t=await this.tokenizer.readToken(Au);if(t.signature!==Eu.CentralFileHeader)throw Error(`Expected Central-File-Header signature`);t.filename=await this.tokenizer.readToken(new iu(t.filenameLength,`utf-8`)),await this.tokenizer.ignore(t.extraFieldLength),await this.tokenizer.ignore(t.fileCommentLength),r.push(t),Nu(`Add central-directory file-entry: n=${e+1}/${r.length}: filename=${r[e].filename}`)}return this.tokenizer.setPosition(e),r}this.tokenizer.setPosition(e)}async unzip(e){let t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let n=!1;do{let t=await this.readLocalFileHeader();if(!t)break;let r=e(t);n=!!r.stop;let i;if(await this.tokenizer.ignore(t.extraFieldLength),t.dataDescriptor&&t.compressedSize===0){let e=[],n=Pu;Nu(`Compressed-file-size unknown, scanning for next data-descriptor-signature....`);let i=-1;for(;i<0&&n===Pu;){n=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),i=Ru(this.syncBuffer.subarray(0,n),Fu);let t=i>=0?i:n;if(r.handler){let n=new Uint8Array(t);await this.tokenizer.readBuffer(n),e.push(n)}else await this.tokenizer.ignore(t)}Nu(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),r.handler&&await this.inflate(t,zu(e),r.handler)}else r.handler?(Nu(`Reading compressed-file-data: ${t.compressedSize} bytes`),i=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(i),await this.inflate(t,i,r.handler)):(Nu(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(Nu(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor&&(await this.tokenizer.readToken(Du)).signature!==134695760)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-Du.len}`)}while(!n)}async iterateOverCentralDirectory(e,t){for(let n of e){let e=t(n);if(e.handler){this.tokenizer.setPosition(n.relativeOffsetOfLocalHeader);let t=await this.readLocalFileHeader();if(t){await this.tokenizer.ignore(t.extraFieldLength);let r=new Uint8Array(n.compressedSize);await this.tokenizer.readBuffer(r),await this.inflate(t,r,e.handler)}}if(e.stop)break}}async inflate(t,n,r){if(t.compressedMethod===0)return r(n);if(t.compressedMethod!==8)throw Error(`Unsupported ZIP compression method: ${t.compressedMethod}`);return Nu(`Decompress filename=${t.filename}, compressed-size=${n.length}`),r(await e.decompressDeflateRaw(n))}static async decompressDeflateRaw(e){let t=new ReadableStream({start(t){t.enqueue(e),t.close()}}),n=new DecompressionStream(`deflate-raw`),r=t.pipeThrough(n);try{let e=await new Response(r).arrayBuffer();return new Uint8Array(e)}catch(e){let t=e instanceof Error?`Failed to deflate ZIP entry: ${e.message}`:`Unknown decompression error in ZIP entry`;throw TypeError(t)}}async readLocalFileHeader(){let e=await this.tokenizer.peekToken(eu);if(e===Eu.LocalFileHeader){let e=await this.tokenizer.readToken(Ou);return e.filename=await this.tokenizer.readToken(new iu(e.filenameLength,`utf-8`)),e}if(e===Eu.CentralFileHeader)return!1;throw Error(e===3759263696?`Encrypted ZIP`:`Unexpected signature`)}};function Ru(e,t){let n=e.length,r=t.length;if(r>n)return-1;for(let i=0;i<=n-r;i++){let n=!0;for(let a=0;a<r;a++)if(e[i+a]!==t[a]){n=!1;break}if(n)return i}return-1}function zu(e){let t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}var Bu=class{constructor(e){this.tokenizer=e}inflate(){let e=this.tokenizer;return new ReadableStream({async pull(t){let n=new Uint8Array(1024),r=await e.readBuffer(n,{mayBeLess:!0});if(r===0){t.close();return}t.enqueue(n.subarray(0,r))}}).pipeThrough(new DecompressionStream(`gzip`))}};const Vu=Object.prototype.toString;function Hu(e,t,n){return e?e.constructor===t?!0:Vu.call(e)===n:!1}function Uu(e){return Hu(e,Uint8Array,`[object Uint8Array]`)}function Wu(e){if(!Uu(e))throw TypeError(`Expected \`Uint8Array\`, got \`${typeof e}\``)}function Gu(e,t){if(e.length===0)return new Uint8Array;t??=e.reduce((e,t)=>e+t.length,0);let n=new Uint8Array(t),r=0;for(let t of e)Wu(t),n.set(t,r),r+=t.length;return n}new globalThis.TextDecoder(`utf8`),new globalThis.TextEncoder,Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function Ku(e){let{byteLength:t}=e;if(t===6)return e.getUint16(0)*2**32+e.getUint32(2);if(t===5)return e.getUint8(0)*2**32+e.getUint32(1);if(t===4)return e.getUint32(0);if(t===3)return e.getUint8(0)*2**16+e.getUint16(1);if(t===2)return e.getUint16(0);if(t===1)return e.getUint8(0)}function qu(e,t){if(t===`utf-16le`){let t=[];for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t.push(r&255,r>>8&255)}return t}if(t===`utf-16be`){let t=[];for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t.push(r>>8&255,r&255)}return t}return[...e].map(e=>e.charCodeAt(0))}function Ju(e,t=0){let n=Number.parseInt(new iu(6).get(e,148).replace(/\0.*$/v,``).trim(),8);if(Number.isNaN(n))return!1;let r=256;for(let n=t;n<t+148;n++)r+=e[n];for(let n=t+156;n<t+512;n++)r+=e[n];return n===r}const Yu={get:(e,t)=>e[t+3]&127|(e[t+2]&127)<<7|(e[t+1]&127)<<14|(e[t]&127)<<21,len:4},Xu=`jpg,png,apng,gif,webp,flif,xcf,cr2,cr3,orf,arw,dng,nef,rw2,raf,tif,bmp,icns,jxr,psd,indd,zip,tar,rar,gz,bz2,7z,dmg,mp4,mid,mkv,webm,mov,avi,mpg,mp2,mp3,m4a,oga,ogg,ogv,opus,flac,wav,spx,amr,pdf,epub,elf,macho,exe,swf,rtf,wasm,woff,woff2,eot,ttf,otf,ttc,ico,flv,ps,xz,sqlite,nes,crx,xpi,cab,deb,ar,rpm,Z,lz,cfb,mxf,mts,blend,bpg,docx,pptx,xlsx,3gp,3g2,j2c,jp2,jpm,jpx,mj2,aif,qcp,odt,ods,odp,xml,mobi,heic,cur,ktx,ape,wv,dcm,ics,glb,pcap,dsf,lnk,alias,voc,ac3,m4v,m4p,m4b,f4v,f4p,f4b,f4a,mie,asf,ogm,ogx,mpc,arrow,shp,aac,mp1,it,s3m,xm,skp,avif,eps,lzh,pgp,asar,stl,chm,3mf,zst,jxl,vcf,jls,pst,dwg,parquet,class,arj,cpio,ace,avro,icc,fbx,vsdx,vtt,apk,drc,lz4,potx,xltx,dotx,xltm,ott,ots,otp,odg,otg,xlsm,docm,dotm,potm,pptm,jar,jmp,rm,sav,ppsm,ppsx,tar.gz,reg,dat,key,numbers,pages`.split(`,`),Zu=`image/jpeg,image/png,image/gif,image/webp,image/flif,image/x-xcf,image/x-canon-cr2,image/x-canon-cr3,image/tiff,image/bmp,image/vnd.ms-photo,image/vnd.adobe.photoshop,application/x-indesign,application/epub+zip,application/x-xpinstall,application/vnd.ms-powerpoint.slideshow.macroenabled.12,application/vnd.oasis.opendocument.text,application/vnd.oasis.opendocument.spreadsheet,application/vnd.oasis.opendocument.presentation,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.presentationml.slideshow,application/zip,application/x-tar,application/x-rar-compressed,application/gzip,application/x-bzip2,application/x-7z-compressed,application/x-apple-diskimage,application/vnd.apache.arrow.file,video/mp4,audio/midi,video/matroska,video/webm,video/quicktime,video/vnd.avi,audio/wav,audio/qcelp,audio/x-ms-asf,video/x-ms-asf,application/vnd.ms-asf,video/mpeg,video/3gpp,audio/mpeg,audio/mp4,video/ogg,audio/ogg,audio/ogg; codecs=opus,application/ogg,audio/flac,audio/ape,audio/wavpack,audio/amr,application/pdf,application/x-elf,application/x-mach-binary,application/x-msdownload,application/x-shockwave-flash,application/rtf,application/wasm,font/woff,font/woff2,application/vnd.ms-fontobject,font/ttf,font/otf,font/collection,image/x-icon,video/x-flv,application/postscript,application/eps,application/x-xz,application/x-sqlite3,application/x-nintendo-nes-rom,application/x-google-chrome-extension,application/vnd.ms-cab-compressed,application/x-deb,application/x-unix-archive,application/x-rpm,application/x-compress,application/lzip,application/x-cfb,application/x-mie,application/mxf,video/mp2t,application/x-blender,image/bpg,image/j2c,image/jp2,image/jpx,image/jpm,image/mj2,audio/aiff,application/xml,application/x-mobipocket-ebook,image/heif,image/heif-sequence,image/heic,image/heic-sequence,image/icns,image/ktx,application/dicom,audio/x-musepack,text/calendar,text/vcard,text/vtt,model/gltf-binary,application/vnd.tcpdump.pcap,audio/x-dsf,application/x-ms-shortcut,application/x-ft-apple.alias,audio/x-voc,audio/vnd.dolby.dd-raw,audio/x-m4a,image/apng,image/x-olympus-orf,image/x-sony-arw,image/x-adobe-dng,image/x-nikon-nef,image/x-panasonic-rw2,image/x-fujifilm-raf,video/x-m4v,video/3gpp2,application/x-esri-shape,audio/aac,audio/x-it,audio/x-s3m,audio/x-xm,video/MP1S,video/MP2P,application/vnd.sketchup.skp,image/avif,application/x-lzh-compressed,application/pgp-encrypted,application/x-asar,model/stl,application/vnd.ms-htmlhelp,model/3mf,image/jxl,application/zstd,image/jls,application/vnd.ms-outlook,image/vnd.dwg,application/vnd.apache.parquet,application/java-vm,application/x-arj,application/x-cpio,application/x-ace-compressed,application/avro,application/vnd.iccprofile,application/x-ft-fbx,application/vnd.visio,application/vnd.android.package-archive,application/x-ft-draco,application/x-lz4,application/vnd.openxmlformats-officedocument.presentationml.template,application/vnd.openxmlformats-officedocument.spreadsheetml.template,application/vnd.openxmlformats-officedocument.wordprocessingml.template,application/vnd.ms-excel.template.macroenabled.12,application/vnd.oasis.opendocument.text-template,application/vnd.oasis.opendocument.spreadsheet-template,application/vnd.oasis.opendocument.presentation-template,application/vnd.oasis.opendocument.graphics,application/vnd.oasis.opendocument.graphics-template,application/vnd.ms-excel.sheet.macroenabled.12,application/vnd.ms-word.document.macroenabled.12,application/vnd.ms-word.template.macroenabled.12,application/vnd.ms-powerpoint.template.macroenabled.12,application/vnd.ms-powerpoint.presentation.macroenabled.12,application/java-archive,application/vnd.rn-realmedia,application/x-spss-sav,application/x-ms-regedit,application/x-ft-windows-registry-hive,application/x-jmp-data,application/vnd.apple.keynote,application/vnd.apple.numbers,application/vnd.apple.pages`.split(`,`),Qu=16*1024*1024;var $u=class extends Error{};function ed(e,t,n){if(!Number.isFinite(e)||e<0||e>t)throw new $u(`${n} has invalid size ${e} (maximum ${t} bytes)`);return e}async function td(e,t,{maximumLength:n=Qu,reason:r=`skip`}={}){let i=ed(t,n,r);await e.ignore(i)}async function nd(e,t,n,{maximumLength:r=t.length,reason:i=`read`}={}){let a=ed(n?.length??t.length,r,i);return e.readBuffer(t,{...n,length:a})}function rd(e,t,n){n={offset:0,...n};for(let[r,i]of t.entries())if(n.mask){if(i!==(n.mask[r]&e[r+n.offset]))return!1}else if(i!==e[r+n.offset])return!1;return!0}function id(e){let t=e.fileInfo.size;return!Number.isFinite(t)||t===2**53-1}function ad(e,t,n){return id(e)&&e.position-t>n}const od=1024*1024,sd=1024,cd=2**31-1,ld=od,ud=new Set([`Unexpected signature`,`Encrypted ZIP`,`Expected Central-File-Header signature`]),dd=[`ZIP entry count exceeds `,`Unsupported ZIP compression method:`,`ZIP entry compressed data exceeds `,`ZIP entry decompressed data exceeds `,`Expected data-descriptor-signature at position `],fd=new Set([`Z_BUF_ERROR`,`Z_DATA_ERROR`,`ERR_INVALID_STATE`]);async function pd(e,{maximumLength:t=od}={}){let n=new ReadableStream({start(t){t.enqueue(e),t.close()}}).pipeThrough(new DecompressionStream(`deflate-raw`)).getReader(),r=[],i=0;try{for(;;){let{done:e,value:a}=await n.read();if(e)break;if(i+=a.length,i>t)throw await n.cancel(),Error(`ZIP entry decompressed data exceeds ${t} bytes`);r.push(a)}}finally{n.releaseLock()}let a=new Uint8Array(i),o=0;for(let e of r)a.set(e,o),o+=e.length;return a}function md(e,t){let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function hd(e){let t=e.fileInfo.size,n=Number.isFinite(t)?Math.max(0,t-e.position):2**53-1;return Math.min(n,cd)}function gd(e){if(e instanceof au||e instanceof $u)return!0;if(!(e instanceof Error))return!1;if(ud.has(e.message)||fd.has(e.code))return!0;for(let t of dd)if(e.message.startsWith(t))return!0;return!1}function _d(e,t=od){let n=[e.compressedSize,e.uncompressedSize];for(let e of n)if(!Number.isFinite(e)||e<0||e>t)return!1;return!0}function vd(){return{hasDocumentEntry:!1,hasMasterSlideEntry:!1,hasTablesEntry:!1,hasCalculationEngineEntry:!1}}function yd(e,t){t===`Index/Document.iwa`&&(e.hasDocumentEntry=!0),t.startsWith(`Index/MasterSlide`)&&(e.hasMasterSlideEntry=!0),t.startsWith(`Index/Tables/`)&&(e.hasTablesEntry=!0),t===`Index/CalculationEngine.iwa`&&(e.hasCalculationEngineEntry=!0)}function bd(e){if(e.hasDocumentEntry)return e.hasMasterSlideEntry?{ext:`key`,mime:`application/vnd.apple.keynote`}:e.hasTablesEntry?{ext:`numbers`,mime:`application/vnd.apple.numbers`}:{ext:`pages`,mime:`application/vnd.apple.pages`}}function xd(e){switch(e=e.toLowerCase(),e){case`application/epub+zip`:return{ext:`epub`,mime:e};case`application/vnd.oasis.opendocument.text`:return{ext:`odt`,mime:e};case`application/vnd.oasis.opendocument.text-template`:return{ext:`ott`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet`:return{ext:`ods`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet-template`:return{ext:`ots`,mime:e};case`application/vnd.oasis.opendocument.presentation`:return{ext:`odp`,mime:e};case`application/vnd.oasis.opendocument.presentation-template`:return{ext:`otp`,mime:e};case`application/vnd.oasis.opendocument.graphics`:return{ext:`odg`,mime:e};case`application/vnd.oasis.opendocument.graphics-template`:return{ext:`otg`,mime:e};case`application/vnd.openxmlformats-officedocument.presentationml.slideshow`:return{ext:`ppsx`,mime:e};case`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`:return{ext:`xlsx`,mime:e};case`application/vnd.ms-excel.sheet.macroenabled`:return{ext:`xlsm`,mime:`application/vnd.ms-excel.sheet.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.spreadsheetml.template`:return{ext:`xltx`,mime:e};case`application/vnd.ms-excel.template.macroenabled`:return{ext:`xltm`,mime:`application/vnd.ms-excel.template.macroenabled.12`};case`application/vnd.ms-powerpoint.slideshow.macroenabled`:return{ext:`ppsm`,mime:`application/vnd.ms-powerpoint.slideshow.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.document`:return{ext:`docx`,mime:e};case`application/vnd.ms-word.document.macroenabled`:return{ext:`docm`,mime:`application/vnd.ms-word.document.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.template`:return{ext:`dotx`,mime:e};case`application/vnd.ms-word.template.macroenabledtemplate`:return{ext:`dotm`,mime:`application/vnd.ms-word.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.template`:return{ext:`potx`,mime:e};case`application/vnd.ms-powerpoint.template.macroenabled`:return{ext:`potm`,mime:`application/vnd.ms-powerpoint.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.presentation`:return{ext:`pptx`,mime:e};case`application/vnd.ms-powerpoint.presentation.macroenabled`:return{ext:`pptm`,mime:`application/vnd.ms-powerpoint.presentation.macroenabled.12`};case`application/vnd.ms-visio.drawing`:return{ext:`vsdx`,mime:`application/vnd.visio`};case`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`:return{ext:`3mf`,mime:`model/3mf`};default:}}function Sd(){return{hasContentTypesEntry:!1,hasParsedContentTypesEntry:!1,isParsingContentTypes:!1,hasUnparseableContentTypes:!1,hasWordDirectory:!1,hasPresentationDirectory:!1,hasSpreadsheetDirectory:!1,hasThreeDimensionalModelEntry:!1}}function Cd(e,t){t.startsWith(`word/`)&&(e.hasWordDirectory=!0),t.startsWith(`ppt/`)&&(e.hasPresentationDirectory=!0),t.startsWith(`xl/`)&&(e.hasSpreadsheetDirectory=!0),t.startsWith(`3D/`)&&t.endsWith(`.model`)&&(e.hasThreeDimensionalModelEntry=!0)}function wd(e){if(e.hasWordDirectory)return{ext:`docx`,mime:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`};if(e.hasPresentationDirectory)return{ext:`pptx`,mime:`application/vnd.openxmlformats-officedocument.presentationml.presentation`};if(e.hasSpreadsheetDirectory)return{ext:`xlsx`,mime:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`};if(e.hasThreeDimensionalModelEntry)return{ext:`3mf`,mime:`model/3mf`}}function Td(e){if(!(!e.hasContentTypesEntry||e.hasUnparseableContentTypes||e.isParsingContentTypes||e.hasParsedContentTypesEntry))return wd(e)}function Ed(e){let t=e.indexOf(`.main+xml"`);if(t===-1){let t=`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`;return e.includes(`ContentType="${t}"`)?t:void 0}let n=e.slice(0,t),r=n.lastIndexOf(`"`);return n.slice(r+1)}const Dd=134695760;function Od(e,t){if(e.length<16)return-1;let n=e.length-16;for(let r=0;r<=n;r++)if(eu.get(e,r)===Dd&&eu.get(e,r+8)===t+r)return r;return-1}async function kd(e,{shouldBuffer:t,maximumLength:n=od}={}){let{syncBuffer:r}=e,{length:i}=r,a=[],o=0;for(;;){let s=await e.tokenizer.peekBuffer(r,{mayBeLess:!0}),c=Od(r.subarray(0,s),o),l=c>=0?0:s===i?Math.min(15,s-1):0,u=c>=0?c:s-l;if(u===0)break;if(o+=u,o>n)throw Error(`ZIP entry compressed data exceeds ${n} bytes`);if(t){let t=new Uint8Array(u);await e.tokenizer.readBuffer(t),a.push(t)}else await e.tokenizer.ignore(u);if(c>=0)break}if(id(e.tokenizer)||(e.knownSizeDescriptorScannedBytes+=o),t)return md(a,o)}function Ad(e,t){return id(e.tokenizer)?Math.max(0,Qu-(e.tokenizer.position-t)):Math.max(0,od-e.knownSizeDescriptorScannedBytes)}async function jd(e,t,{shouldBuffer:n,maximumDescriptorLength:r=od}={}){if(t.dataDescriptor&&t.compressedSize===0)return kd(e,{shouldBuffer:n,maximumLength:r});if(!n){await td(e.tokenizer,t.compressedSize,{maximumLength:id(e.tokenizer)?od:e.tokenizer.fileInfo.size,reason:`ZIP entry compressed data`});return}let i=hd(e.tokenizer);if(!Number.isFinite(t.compressedSize)||t.compressedSize<0||t.compressedSize>i)throw Error(`ZIP entry compressed data exceeds ${i} bytes`);let a=new Uint8Array(t.compressedSize);return await e.tokenizer.readBuffer(a),a}Lu.prototype.inflate=async function(e,t,n){if(e.compressedMethod===0)return n(t);if(e.compressedMethod!==8)throw Error(`Unsupported ZIP compression method: ${e.compressedMethod}`);return n(await pd(t,{maximumLength:od}))},Lu.prototype.unzip=async function(e){let t=!1,n=0,r=this.tokenizer.position;this.knownSizeDescriptorScannedBytes=0;do{if(ad(this.tokenizer,r,16777216))throw new $u(`ZIP stream probing exceeds ${Qu} bytes`);let i=await this.readLocalFileHeader();if(!i)break;if(n++,n>sd)throw Error(`ZIP entry count exceeds ${sd}`);let a=e(i);t=!!a.stop,await this.tokenizer.ignore(i.extraFieldLength);let o=await jd(this,i,{shouldBuffer:!!a.handler,maximumDescriptorLength:Math.min(od,Ad(this,r))});if(a.handler&&await this.inflate(i,o,a.handler),i.dataDescriptor){let e=new Uint8Array(16);if(await this.tokenizer.readBuffer(e),eu.get(e,0)!==Dd)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-e.length}`)}if(ad(this.tokenizer,r,16777216))throw new $u(`ZIP stream probing exceeds ${Qu} bytes`)}while(!t)};async function Md(e){let t,n=Sd(),r=vd();try{await new Lu(e).unzip(e=>{if(Cd(n,e.filename),yd(r,e.filename),r.hasDocumentEntry&&(r.hasMasterSlideEntry||r.hasTablesEntry))return t=bd(r),{stop:!0};let i=e.filename===`[Content_Types].xml`,a=Td(n);if(!i&&a)return t=a,{stop:!0};switch(e.filename){case`META-INF/mozilla.rsa`:return t={ext:`xpi`,mime:`application/x-xpinstall`},{stop:!0};case`META-INF/MANIFEST.MF`:return t={ext:`jar`,mime:`application/java-archive`},{stop:!0};case`mimetype`:return _d(e,ld)?{async handler(e){t=xd(new TextDecoder(`utf-8`).decode(e).trim())},stop:!0}:{};case`[Content_Types].xml`:return n.hasContentTypesEntry=!0,_d(e,ld)?(n.isParsingContentTypes=!0,{async handler(e){let r=Ed(new TextDecoder(`utf-8`).decode(e));r&&(t=xd(r)),n.hasParsedContentTypesEntry=!0,n.isParsingContentTypes=!1},stop:!0}):(n.hasUnparseableContentTypes=!0,{});default:return/classes\d*\.dex/v.test(e.filename)?(t={ext:`apk`,mime:`application/vnd.android.package-archive`},{stop:!0}):{}}})}catch(e){if(!gd(e))throw e;n.isParsingContentTypes&&(n.isParsingContentTypes=!1,n.hasUnparseableContentTypes=!0),!t&&e instanceof au&&!n.hasContentTypesEntry&&(t=wd(n))}let i=id(e)&&r.hasDocumentEntry&&!r.hasMasterSlideEntry&&!r.hasTablesEntry&&!r.hasCalculationEngineEntry?void 0:bd(r);return t??Td(n)??i??{ext:`zip`,mime:`application/zip`}}const Nd=1024*1024;async function Pd(e){async function t(){let t=await e.peekNumber(Zl),n=128,r=0;for(;(t&n)===0&&n!==0;)++r,n>>=1;let i=new Uint8Array(r+1);return await nd(e,i,void 0,{maximumLength:i.length,reason:`EBML field`}),i}async function n(){let e=await t(),n=await t();n[0]^=128>>n.length-1;let r=Math.min(6,n.length),i=new DataView(e.buffer),a=new DataView(n.buffer,n.length-r,r);return{id:Ku(i),len:Ku(a)}}async function r(t){let r=0;for(;t>0;){if(r++,r>256||ad(e,a,16777216))return;let i=e.position,o=await n();if(o.id===17026){if(o.len>64)return;let t=ed(o.len,64,`EBML DocType`);return(await e.readToken(new iu(t))).replaceAll(/\0.*$/gv,``)}if(id(e)&&(!Number.isFinite(o.len)||o.len<0||o.len>Nd)||(await td(e,o.len,{maximumLength:id(e)?Nd:e.fileInfo.size,reason:`EBML payload`}),--t,e.position<=i))return}}let i=await n(),a=e.position;switch(await r(i.len)){case`webm`:return{ext:`webm`,mime:`video/webm`};case`matroska`:return{ext:`mkv`,mime:`video/matroska`};default:}}const Fd=1024*1024;function Id(e){return(e.codePointAt(0)&32)!=0}async function Ld(e){let t={ext:`png`,mime:`image/png`},n={ext:`apng`,mime:`image/apng`};await e.ignore(8);async function r(){return{length:await e.readToken(nu),type:await e.readToken(new iu(4,`latin1`))}}let i=id(e),a=e.position,o=0,s=!1;do{if(o++,o>512||ad(e,a,16777216))break;let c=e.position,l=await r();if(l.length<0)return;if(l.type===`IHDR`){if(l.length!==13)return;s=!0}switch(l.type){case`IDAT`:return t;case`acTL`:return n;default:if(!s&&l.type!==`CgBI`)return;if(i&&l.length>Fd)return s&&Id(l.type)?t:void 0;try{await td(e,l.length+4,{maximumLength:i?Fd+4:e.fileInfo.size,reason:`PNG chunk payload`})}catch(e){if(!i&&(e instanceof $u||e instanceof au))return t;throw e}}if(e.position<=c)break}while(e.position+8<e.fileInfo.size);return t}const Rd=1024*1024;async function zd(e){let t=!1;try{async function n(){let t=new Uint8Array(16);return await nd(e,t,void 0,{maximumLength:t.length,reason:`ASF header GUID`}),{id:t,size:Number(await e.readToken(ru))}}await td(e,30,{maximumLength:30,reason:`ASF header prelude`});let r=id(e),i=e.position,a=0;for(;e.position+24<e.fileInfo.size&&(a++,!(a>512||ad(e,i,16777216)));){let i=e.position,a=await n(),o=a.size-24;if(!Number.isFinite(o)||o<0){t=!0;break}if(rd(a.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let t=new Uint8Array(16);if(o-=await nd(e,t,void 0,{maximumLength:t.length,reason:`ASF stream type GUID`}),rd(t,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`audio/x-ms-asf`};if(rd(t,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`video/x-ms-asf`};break}if(r&&o>Rd){t=!0;break}if(await td(e,o,{maximumLength:r?Rd:e.fileInfo.size,reason:`ASF header payload`}),e.position<=i){t=!0;break}}}catch(n){if(n instanceof au||n instanceof $u)id(e)&&(t=!0);else throw n}if(!t)return{ext:`asf`,mime:`application/vnd.ms-asf`}}const Bd=4100;Bd-2;const Vd=Qu,Hd=Qu;function Ud(e){return Number.isFinite(e)?Math.max(1,Math.trunc(e)):Bd}function Wd(e){return Number.isFinite(e)?Math.max(0,Math.min(4098,Math.trunc(e))):0}function Gd(e){return Number.isFinite(e)?Math.max(0,e):2**53-1}function Kd(e){return import(e)}function qd(e){return e.pipeThrough(new TransformStream)}function Jd(e,t){return t===void 0?e.read():(t.throwIfAborted(),Promise.race([e.read(),new Promise((n,r)=>{t.addEventListener(`abort`,()=>{r(t.reason),e.cancel(t.reason).catch(()=>{})},{once:!0})})]))}function Yd(e,t){let n=e.getReader(),r=0,i=!1,a=!1,o=async e=>{i||a||(a=!0,await n.cancel(e))};return new ReadableStream({async pull(e){if(r>=t){e.close(),await o();return}let{done:a,value:s}=await n.read();if(a||!s){i=!0,e.close();return}let c=t-r;if(s.length>c){e.enqueue(s.subarray(0,c)),r+=c,e.close(),await o();return}e.enqueue(s),r+=s.length},async cancel(e){await o(e)}})}async function Xd(e,t){return new Zd(t).fromBuffer(e)}var Zd=class e{constructor(e){let t=Wd(e?.mpegOffsetTolerance);this.options={...e,mpegOffsetTolerance:t},this.detectors=[...this.options.customDetectors??[],{id:`core`,detect:this.detectConfident},{id:`core.imprecise`,detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:this.options.signal},this.gzipProbeDepth=0}getTokenizerOptions(){return{...this.tokenizerOptions}}createTokenizerFromWebStream(e){return gu(qd(e),this.getTokenizerOptions())}async parseTokenizer(e,t=0){this.detectionReentryCount=t;let n=e.position;for(let t of this.detectors){let r;try{r=await t.detect(e)}catch(e){if(e instanceof au||e instanceof $u)return;throw e}if(r)return r;if(n!==e.position)return}}async fromTokenizer(e){try{return await this.parseTokenizer(e)}finally{await e.close()}}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``);let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t?.length>1)return this.fromTokenizer(_u(t,this.getTokenizerOptions()))}async fromBlob(e){this.options.signal?.throwIfAborted();let t=vu(e,this.getTokenizerOptions());return this.fromTokenizer(t)}async fromStream(e){this.options.signal?.throwIfAborted();let t=this.createTokenizerFromWebStream(e);return this.fromTokenizer(t)}async fromFile(e){this.options.signal?.throwIfAborted();let[{default:t},{FileTokenizer:n}]=await Promise.all([Kd(`node:fs/promises`),Kd(`strtok3`)]),r=await t.open(e,t.constants.O_RDONLY|t.constants.O_NONBLOCK),i=await r.stat();if(!i.isFile()){await r.close();return}let a=new n(r,{...this.getTokenizerOptions(),fileInfo:{path:e,size:i.size}});return this.fromTokenizer(a)}async toDetectionStream(e,t){this.options.signal?.throwIfAborted();let n=Ud(t?.sampleSize??4100),r,i=!1,a=e.getReader(),o=[],s=0;try{for(;s<n;){let{value:e,done:t}=await Jd(a,this.options.signal);if(t||!e){i=!0;break}o.push(e),s+=e.length}if(!i&&s===n){let{value:e,done:t}=await Jd(a,this.options.signal);t||!e?i=!0:(o.push(e),s+=e.length)}}finally{a.releaseLock()}if(s>0){let e=o.length===1?o[0]:Gu(o);try{r=await this.fromBuffer(e.subarray(0,n))}catch(e){if(!(e instanceof au))throw e;r=void 0}!i&&r?.ext===`pages`&&(r={ext:`zip`,mime:`application/zip`})}let c=new TransformStream({start(e){for(let t of o)e.enqueue(t)},transform(e,t){t.enqueue(e)}}),l=e.pipeThrough(c);return l.fileType=r,l}async detectGzip(t){if(this.gzipProbeDepth>=1)return{ext:`gz`,mime:`application/gzip`};let n=Yd(new Bu(t).inflate(),16777216),r=id(t),i,a,o,s;if(r){let t=new AbortController;i=setTimeout(()=>{t.abort(new DOMException(`Operation timed out after 100 ms`,`TimeoutError`))},100),a=this.options.signal===void 0?t.signal:AbortSignal.any([this.options.signal,t.signal]),o=new e({...this.options,signal:a}),o.gzipProbeDepth=this.gzipProbeDepth+1}else this.gzipProbeDepth++;try{s=await(o??this).fromStream(n)}catch(e){if(e?.name===`AbortError`&&a?.reason?.name!==`TimeoutError`)throw e}finally{clearTimeout(i),r||this.gzipProbeDepth--}return s?.ext===`tar`?{ext:`tar.gz`,mime:`application/gzip`}:{ext:`gz`,mime:`application/gzip`}}check(e,t){return rd(this.buffer,e,t)}checkString(e,t){return this.check(qu(e,t?.encoding),t)}detectConfident=async e=>{if(this.buffer=new Uint8Array(Bd),e.fileInfo.size===void 0&&(e.fileInfo.size=2**53-1),this.tokenizer=e,id(e)&&(await e.peekBuffer(this.buffer,{length:3,mayBeLess:!0}),this.check([31,139,8])))return this.detectGzip(e);if(await e.peekBuffer(this.buffer,{length:32,mayBeLess:!0}),this.check([66,77]))return{ext:`bmp`,mime:`image/bmp`};if(this.check([11,119]))return{ext:`ac3`,mime:`audio/vnd.dolby.dd-raw`};if(this.check([120,1]))return{ext:`dmg`,mime:`application/x-apple-diskimage`};if(this.check([77,90]))return{ext:`exe`,mime:`application/x-msdownload`};if(this.check([37,33]))return await e.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString(`PS-Adobe-`,{offset:2})&&this.checkString(` EPSF-`,{offset:14})?{ext:`eps`,mime:`application/eps`}:{ext:`ps`,mime:`application/postscript`};if(this.check([31,160])||this.check([31,157]))return{ext:`Z`,mime:`application/x-compress`};if(this.check([199,113]))return{ext:`cpio`,mime:`application/x-cpio`};if(this.check([96,234]))return{ext:`arj`,mime:`application/x-arj`};if(this.check([239,187,191]))return this.detectionReentryCount>=256?void 0:(this.detectionReentryCount++,await this.tokenizer.ignore(3),this.detectConfident(e));if(this.check([71,73,70]))return{ext:`gif`,mime:`image/gif`};if(this.check([73,73,188]))return{ext:`jxr`,mime:`image/vnd.ms-photo`};if(this.check([31,139,8]))return this.detectGzip(e);if(this.check([66,90,104]))return{ext:`bz2`,mime:`application/x-bzip2`};if(this.checkString(`ID3`)){await td(e,6,{maximumLength:6,reason:`ID3 header prefix`});let t=await e.readToken(Yu),n=id(e);if(!Number.isFinite(t)||t<0||n&&(t>Vd||e.position+t>Vd))return;if(e.position+t>e.fileInfo.size)return n?void 0:{ext:`mp3`,mime:`audio/mpeg`};try{await td(e,t,{maximumLength:n?Vd:e.fileInfo.size,reason:`ID3 payload`})}catch(e){if(e instanceof au)return;throw e}return this.detectionReentryCount>=256?void 0:(this.detectionReentryCount++,this.parseTokenizer(e,this.detectionReentryCount))}if(this.checkString(`MP+`))return{ext:`mpc`,mime:`audio/x-musepack`};if((this.buffer[0]===67||this.buffer[0]===70)&&this.check([87,83],{offset:1}))return{ext:`swf`,mime:`application/x-shockwave-flash`};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:`jls`,mime:`image/jls`}:{ext:`jpg`,mime:`image/jpeg`};if(this.check([79,98,106,1]))return{ext:`avro`,mime:`application/avro`};if(this.checkString(`FLIF`))return{ext:`flif`,mime:`image/flif`};if(this.checkString(`8BPS`))return{ext:`psd`,mime:`image/vnd.adobe.photoshop`};if(this.checkString(`MPCK`))return{ext:`mpc`,mime:`audio/x-musepack`};if(this.checkString(`FORM`))return{ext:`aif`,mime:`audio/aiff`};if(this.checkString(`icns`,{offset:0}))return{ext:`icns`,mime:`image/icns`};if(this.check([80,75,3,4]))return Md(e);if(this.checkString(`OggS`)){await e.ignore(28);let t=new Uint8Array(8);return await e.readBuffer(t),rd(t,[79,112,117,115,72,101,97,100])?{ext:`opus`,mime:`audio/ogg; codecs=opus`}:rd(t,[128,116,104,101,111,114,97])?{ext:`ogv`,mime:`video/ogg`}:rd(t,[1,118,105,100,101,111,0])?{ext:`ogm`,mime:`video/ogg`}:rd(t,[127,70,76,65,67])?{ext:`oga`,mime:`audio/ogg`}:rd(t,[83,112,101,101,120,32,32])?{ext:`spx`,mime:`audio/ogg`}:rd(t,[1,118,111,114,98,105,115])?{ext:`ogg`,mime:`audio/ogg`}:{ext:`ogx`,mime:`application/ogg`}}if(this.check([80,75])&&(this.buffer[2]===3||this.buffer[2]===5||this.buffer[2]===7)&&(this.buffer[3]===4||this.buffer[3]===6||this.buffer[3]===8))return{ext:`zip`,mime:`application/zip`};if(this.checkString(`MThd`))return{ext:`mid`,mime:`audio/midi`};if(this.checkString(`wOFF`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff`,mime:`font/woff`};if(this.checkString(`wOF2`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff2`,mime:`font/woff2`};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:`pcap`,mime:`application/vnd.tcpdump.pcap`};if(this.checkString(`DSD `))return{ext:`dsf`,mime:`audio/x-dsf`};if(this.checkString(`LZIP`))return{ext:`lz`,mime:`application/lzip`};if(this.checkString(`fLaC`))return{ext:`flac`,mime:`audio/flac`};if(this.check([66,80,71,251]))return{ext:`bpg`,mime:`image/bpg`};if(this.checkString(`wvpk`))return{ext:`wv`,mime:`audio/wavpack`};if(this.checkString(`%PDF`))return{ext:`pdf`,mime:`application/pdf`};if(this.check([0,97,115,109]))return{ext:`wasm`,mime:`application/wasm`};if(this.check([73,73])){let e=await this.readTiffHeader(!1);if(e)return e}if(this.check([77,77])){let e=await this.readTiffHeader(!0);if(e)return e}if(this.checkString(`MAC `))return{ext:`ape`,mime:`audio/ape`};if(this.check([26,69,223,163]))return Pd(e);if(this.checkString(`SQLi`))return{ext:`sqlite`,mime:`application/x-sqlite3`};if(this.check([78,69,83,26]))return{ext:`nes`,mime:`application/x-nintendo-nes-rom`};if(this.checkString(`Cr24`))return{ext:`crx`,mime:`application/x-google-chrome-extension`};if(this.checkString(`MSCF`)||this.checkString(`ISc(`))return{ext:`cab`,mime:`application/vnd.ms-cab-compressed`};if(this.check([237,171,238,219]))return{ext:`rpm`,mime:`application/x-rpm`};if(this.check([197,208,211,198]))return{ext:`eps`,mime:`application/eps`};if(this.check([40,181,47,253]))return{ext:`zst`,mime:`application/zstd`};if(this.check([127,69,76,70]))return{ext:`elf`,mime:`application/x-elf`};if(this.check([33,66,68,78]))return{ext:`pst`,mime:`application/vnd.ms-outlook`};if(this.checkString(`PAR1`)||this.checkString(`PARE`))return{ext:`parquet`,mime:`application/vnd.apache.parquet`};if(this.checkString(`ttcf`))return{ext:`ttc`,mime:`font/collection`};if(this.check([254,237,250,206])||this.check([254,237,250,207])||this.check([206,250,237,254])||this.check([207,250,237,254]))return{ext:`macho`,mime:`application/x-mach-binary`};if(this.check([4,34,77,24]))return{ext:`lz4`,mime:`application/x-lz4`};if(this.checkString(`regf`))return{ext:`dat`,mime:`application/x-ft-windows-registry-hive`};if(this.checkString(`$FL2`)||this.checkString(`$FL3`))return{ext:`sav`,mime:`application/x-spss-sav`};if(this.check([79,84,84,79,0]))return{ext:`otf`,mime:`font/otf`};if(this.checkString(`#!AMR`))return{ext:`amr`,mime:`audio/amr`};if(this.checkString(String.raw`{\rtf`))return{ext:`rtf`,mime:`application/rtf`};if(this.check([70,76,86,1]))return{ext:`flv`,mime:`video/x-flv`};if(this.checkString(`IMPM`))return{ext:`it`,mime:`audio/x-it`};if(this.checkString(`-lh0-`,{offset:2})||this.checkString(`-lh1-`,{offset:2})||this.checkString(`-lh2-`,{offset:2})||this.checkString(`-lh3-`,{offset:2})||this.checkString(`-lh4-`,{offset:2})||this.checkString(`-lh5-`,{offset:2})||this.checkString(`-lh6-`,{offset:2})||this.checkString(`-lh7-`,{offset:2})||this.checkString(`-lzs-`,{offset:2})||this.checkString(`-lz4-`,{offset:2})||this.checkString(`-lz5-`,{offset:2})||this.checkString(`-lhd-`,{offset:2}))return{ext:`lzh`,mime:`application/x-lzh-compressed`};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:`mpg`,mime:`video/MP1S`};if(this.check([68],{offset:4,mask:[196]}))return{ext:`mpg`,mime:`video/MP2P`}}if(this.checkString(`ITSF`))return{ext:`chm`,mime:`application/vnd.ms-htmlhelp`};if(this.check([202,254,186,190])){let e=tu.get(this.buffer,4),t=$l.get(this.buffer,6);if(e>0&&e<=30)return{ext:`macho`,mime:`application/x-mach-binary`};if(t>30)return{ext:`class`,mime:`application/java-vm`}}if(this.checkString(`.RMF`))return{ext:`rm`,mime:`application/vnd.rn-realmedia`};if(this.checkString(`DRACO`))return{ext:`drc`,mime:`application/x-ft-draco`};if(this.check([253,55,122,88,90,0]))return{ext:`xz`,mime:`application/x-xz`};if(this.checkString(`<?xml `))return{ext:`xml`,mime:`application/xml`};if(this.check([55,122,188,175,39,28]))return{ext:`7z`,mime:`application/x-7z-compressed`};if(this.check([82,97,114,33,26,7])&&(this.buffer[6]===0||this.buffer[6]===1))return{ext:`rar`,mime:`application/x-rar-compressed`};if(this.checkString(`solid `))return{ext:`stl`,mime:`model/stl`};if(this.checkString(`AC`)){let e=new iu(4,`latin1`).get(this.buffer,2);if(/^\d+$/v.test(e)&&e>=1e3&&e<=1050)return{ext:`dwg`,mime:`image/vnd.dwg`}}if(this.checkString(`070707`))return{ext:`cpio`,mime:`application/x-cpio`};if(this.checkString(`BLENDER`))return{ext:`blend`,mime:`application/x-blender`};if(this.checkString(`!<arch>`))return await e.ignore(8),await e.readToken(new iu(13,`ascii`))===`debian-binary`?{ext:`deb`,mime:`application/x-deb`}:{ext:`ar`,mime:`application/x-unix-archive`};if(this.checkString(`WEBVTT`)&&[`
22
+ `,`\r`,` `,` `,`\0`].some(e=>this.checkString(e,{offset:6})))return{ext:`vtt`,mime:`text/vtt`};if(this.check([137,80,78,71,13,10,26,10]))return Ld(e);if(this.check([65,82,82,79,87,49,0,0]))return{ext:`arrow`,mime:`application/vnd.apache.arrow.file`};if(this.check([103,108,84,70,2,0,0,0]))return{ext:`glb`,mime:`model/gltf-binary`};if(this.check([102,114,101,101],{offset:4})||this.check([109,100,97,116],{offset:4})||this.check([109,111,111,118],{offset:4})||this.check([119,105,100,101],{offset:4}))return{ext:`mov`,mime:`video/quicktime`};if(this.check([73,73,82,79,8,0,0,0,24]))return{ext:`orf`,mime:`image/x-olympus-orf`};if(this.checkString(`gimp xcf `))return{ext:`xcf`,mime:`image/x-xcf`};if(this.checkString(`ftyp`,{offset:4})&&this.buffer[8]&96){let e=new iu(4,`latin1`).get(this.buffer,8).replace(`\0`,` `).trim();switch(e){case`avif`:case`avis`:return{ext:`avif`,mime:`image/avif`};case`mif1`:return{ext:`heic`,mime:`image/heif`};case`msf1`:return{ext:`heic`,mime:`image/heif-sequence`};case`heic`:case`heix`:return{ext:`heic`,mime:`image/heic`};case`hevc`:case`hevx`:return{ext:`heic`,mime:`image/heic-sequence`};case`qt`:return{ext:`mov`,mime:`video/quicktime`};case`M4V`:case`M4VH`:case`M4VP`:return{ext:`m4v`,mime:`video/x-m4v`};case`M4P`:return{ext:`m4p`,mime:`video/mp4`};case`M4B`:return{ext:`m4b`,mime:`audio/mp4`};case`M4A`:return{ext:`m4a`,mime:`audio/x-m4a`};case`F4V`:return{ext:`f4v`,mime:`video/mp4`};case`F4P`:return{ext:`f4p`,mime:`video/mp4`};case`F4A`:return{ext:`f4a`,mime:`audio/mp4`};case`F4B`:return{ext:`f4b`,mime:`audio/mp4`};case`crx`:return{ext:`cr3`,mime:`image/x-canon-cr3`};default:return e.startsWith(`3g`)?e.startsWith(`3g2`)?{ext:`3g2`,mime:`video/3gpp2`}:{ext:`3gp`,mime:`video/3gpp`}:{ext:`mp4`,mime:`video/mp4`}}}if(this.checkString(`REGEDIT4\r
23
+ `))return{ext:`reg`,mime:`application/x-ms-regedit`};if(this.check([82,73,70,70])){if(this.checkString(`WEBP`,{offset:8}))return{ext:`webp`,mime:`image/webp`};if(this.check([65,86,73],{offset:8}))return{ext:`avi`,mime:`video/vnd.avi`};if(this.check([87,65,86,69],{offset:8}))return{ext:`wav`,mime:`audio/wav`};if(this.check([81,76,67,77],{offset:8}))return{ext:`qcp`,mime:`audio/qcelp`}}if(this.check([73,73,85,0,24,0,0,0,136,231,116,216]))return{ext:`rw2`,mime:`image/x-panasonic-rw2`};if(this.check([48,38,178,117,142,102,207,17,166,217]))return zd(e);if(this.check([171,75,84,88,32,49,49,187,13,10,26,10]))return{ext:`ktx`,mime:`image/ktx`};if((this.check([126,16,4])||this.check([126,24,4]))&&this.check([48,77,73,69],{offset:4}))return{ext:`mie`,mime:`application/x-mie`};if(this.check([39,10,0,0,0,0,0,0,0,0,0,0],{offset:2}))return{ext:`shp`,mime:`application/x-esri-shape`};if(this.check([255,79,255,81]))return{ext:`j2c`,mime:`image/j2c`};if(this.check([0,0,0,12,106,80,32,32,13,10,135,10]))switch(await e.ignore(20),await e.readToken(new iu(4,`ascii`))){case`jp2 `:return{ext:`jp2`,mime:`image/jp2`};case`jpx `:return{ext:`jpx`,mime:`image/jpx`};case`jpm `:return{ext:`jpm`,mime:`image/jpm`};case`mjp2`:return{ext:`mj2`,mime:`image/mj2`};default:return}if(this.check([255,10])||this.check([0,0,0,12,74,88,76,32,13,10,135,10]))return{ext:`jxl`,mime:`image/jxl`};if(this.check([254,255]))return this.checkString(`<?xml `,{offset:2,encoding:`utf-16be`})?{ext:`xml`,mime:`application/xml`}:void 0;if(this.check([208,207,17,224,161,177,26,225]))return{ext:`cfb`,mime:`application/x-cfb`};if(await e.peekBuffer(this.buffer,{length:Math.min(256,e.fileInfo.size),mayBeLess:!0}),this.check([97,99,115,112],{offset:36}))return{ext:`icc`,mime:`application/vnd.iccprofile`};if(this.checkString(`**ACE`,{offset:7})&&this.checkString(`**`,{offset:12}))return{ext:`ace`,mime:`application/x-ace-compressed`};if(this.checkString(`BEGIN:`)){if(this.checkString(`VCARD`,{offset:6}))return{ext:`vcf`,mime:`text/vcard`};if(this.checkString(`VCALENDAR`,{offset:6}))return{ext:`ics`,mime:`text/calendar`}}if(this.checkString(`FUJIFILMCCD-RAW`))return{ext:`raf`,mime:`image/x-fujifilm-raf`};if(this.checkString(`Extended Module:`))return{ext:`xm`,mime:`audio/x-xm`};if(this.checkString(`Creative Voice File`))return{ext:`voc`,mime:`audio/x-voc`};if(this.check([4,0,0,0])&&this.buffer.length>=16){let e=new DataView(this.buffer.buffer).getUint32(12,!0);if(e>12&&this.buffer.length>=e+16)try{let t=new TextDecoder().decode(this.buffer.subarray(16,e+16));if(JSON.parse(t).files)return{ext:`asar`,mime:`application/x-asar`}}catch{}}if(this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2]))return{ext:`mxf`,mime:`application/mxf`};if(this.checkString(`SCRM`,{offset:44}))return{ext:`s3m`,mime:`audio/x-s3m`};if(this.check([71])&&this.check([71],{offset:188})||this.check([71],{offset:4})&&this.check([71],{offset:196}))return{ext:`mts`,mime:`video/mp2t`};if(this.check([66,79,79,75,77,79,66,73],{offset:60}))return{ext:`mobi`,mime:`application/x-mobipocket-ebook`};if(this.check([68,73,67,77],{offset:128}))return{ext:`dcm`,mime:`application/dicom`};if(this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70]))return{ext:`lnk`,mime:`application/x-ms-shortcut`};if(this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0]))return{ext:`alias`,mime:`application/x-ft-apple.alias`};if(this.checkString(`Kaydara FBX Binary \0`))return{ext:`fbx`,mime:`application/x-ft-fbx`};if(this.check([76,80],{offset:34})&&(this.check([0,0,1],{offset:8})||this.check([1,0,2],{offset:8})||this.check([2,0,2],{offset:8})))return{ext:`eot`,mime:`application/vnd.ms-fontobject`};if(this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29]))return{ext:`indd`,mime:`application/x-indesign`};if(this.check([255,255,0,0,7,0,0,0,4,0,0,0,1,0,1,0])||this.check([0,0,255,255,0,0,0,7,0,0,0,4,0,1,0,1]))return{ext:`jmp`,mime:`application/x-jmp-data`};if(await e.peekBuffer(this.buffer,{length:Math.min(512,e.fileInfo.size),mayBeLess:!0}),this.checkString(`ustar`,{offset:257})&&(this.checkString(`\0`,{offset:262})||this.checkString(` `,{offset:262}))||this.check([0,0,0,0,0,0],{offset:257})&&Ju(this.buffer))return{ext:`tar`,mime:`application/x-tar`};if(this.check([255,254])){let e=`utf-16le`;return this.checkString(`<?xml `,{offset:2,encoding:e})?{ext:`xml`,mime:`application/xml`}:this.check([255,14],{offset:2})&&this.checkString(`SketchUp Model`,{offset:4,encoding:e})?{ext:`skp`,mime:`application/vnd.sketchup.skp`}:this.checkString(`Windows Registry Editor Version 5.00\r
24
+ `,{offset:2,encoding:e})?{ext:`reg`,mime:`application/x-ms-regedit`}:void 0}if(this.checkString(`-----BEGIN PGP MESSAGE-----`))return{ext:`pgp`,mime:`application/pgp-encrypted`}};detectImprecise=async e=>{this.buffer=new Uint8Array(Bd);let t=Gd(e.fileInfo.size);if(await e.peekBuffer(this.buffer,{length:Math.min(8,t),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:`mpg`,mime:`video/mpeg`};if(this.check([0,1,0,0,0]))return{ext:`ttf`,mime:`font/ttf`};if(this.check([0,0,1,0]))return{ext:`ico`,mime:`image/x-icon`};if(this.check([0,0,2,0]))return{ext:`cur`,mime:`image/x-icon`};if(await e.peekBuffer(this.buffer,{length:Math.min(2+this.options.mpegOffsetTolerance,t),mayBeLess:!0}),this.buffer.length>=2+this.options.mpegOffsetTolerance)for(let e=0;e<=this.options.mpegOffsetTolerance;++e){let t=this.scanMpeg(e);if(t)return t}};async readTiffTag(e){let t=await this.tokenizer.readToken(e?$l:Ql);switch(await this.tokenizer.ignore(10),t){case 50341:return{ext:`arw`,mime:`image/x-sony-arw`};case 50706:return{ext:`dng`,mime:`image/x-adobe-dng`};default:}}async readTiffIFD(e){let t=await this.tokenizer.readToken(e?$l:Ql);if(!(t>512)&&!(id(this.tokenizer)&&2+t*12>Hd))for(let n=0;n<t;++n){let t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){let t={ext:`tif`,mime:`image/tiff`},n=(e?$l:Ql).get(this.buffer,2),r=(e?tu:eu).get(this.buffer,4);if(n===42){if(r>=6){if(this.checkString(`CR`,{offset:8}))return{ext:`cr2`,mime:`image/x-canon-cr2`};if(r>=8){let t=(e?$l:Ql).get(this.buffer,8),n=(e?$l:Ql).get(this.buffer,10);if(t===28&&n===254||t===31&&n===11)return{ext:`nef`,mime:`image/x-nikon-nef`}}}if(id(this.tokenizer)&&r>1048576)return t;let n=id(this.tokenizer)?Hd:this.tokenizer.fileInfo.size;try{await td(this.tokenizer,r,{maximumLength:n,reason:`TIFF IFD offset`})}catch(e){if(e instanceof au)return;throw e}let i;try{i=await this.readTiffIFD(e)}catch(e){if(e instanceof au)return;throw e}return i??t}if(n===43)return t}scanMpeg(e){if(this.check([255,224],{offset:e,mask:[255,224]})){if(this.check([16],{offset:e+1,mask:[22]}))return this.check([8],{offset:e+1,mask:[8]}),{ext:`aac`,mime:`audio/aac`};if(this.check([2],{offset:e+1,mask:[6]}))return{ext:`mp3`,mime:`audio/mpeg`};if(this.check([4],{offset:e+1,mask:[6]}))return{ext:`mp2`,mime:`audio/mpeg`};if(this.check([6],{offset:e+1,mask:[6]}))return{ext:`mp1`,mime:`audio/mpeg`}}}};new Set(Xu),new Set(Zu);let Qd=new Map;function $d(e,t,n,r){let i=Qd.get(t);i||(i={agentId:t,displayName:n,colorSeed:r??n,docs:new Set},Qd.set(t,i)),i.docs.add(e)}function ef(){let e=Qd;return Qd=new Map,e}function tf(e){for(let[t,n]of e){let e=Qd.get(t);e||(e={agentId:t,displayName:n.displayName,colorSeed:n.colorSeed,docs:new Set},Qd.set(t,e));for(let t of n.docs)e.docs.add(t)}}function nf(e){if(e.size===0)return``;let t=[``];for(let n of e.values())t.push(`ok-contributors: ${JSON.stringify({v:1,id:n.agentId,name:n.displayName,colorSeed:n.colorSeed,docs:[...n.docs]})}`);return t.join(`
25
+ `)}const rf=[`INDEX`,`README`,`REPORT`,`SPEC`];function af(e,t){let n=[],r=new Set,i=t=>{!t||r.has(t)||t!==e&&(r.add(t),n.push(t))},a=sf(t),o=cf(e);for(;;){for(let e of rf)if(i(of(t,a,uf(o,e))),n.length>=3)return n;let e=o===``?null:lf(o);if(e&&(i(of(t,a,uf(o,e))),n.length>=3))return n;if(o===``)break;o=cf(o)}return n}function of(e,t,n){return e.has(n)?n:t.get(n.toLowerCase())??null}function sf(e){let t=new Map;for(let n of e.keys()){let e=n.toLowerCase();t.has(e)||t.set(e,n)}return t}function cf(e){let t=e.lastIndexOf(`/`);return t<0?``:e.slice(0,t)}function lf(e){let t=e.lastIndexOf(`/`);return t<0?e:e.slice(t+1)}function uf(e,t){return e===``?t:`${e}/${t}`}function df(e){return e?e.replace(/^---\r?\n/,``).replace(/\r?\n---(?:\r?\n)?$/,``).split(/\r?\n/):[]}function ff(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1).trim():t}function pf(e,t){let n=`${t}:`;for(let t of df(e))if(t.startsWith(n))return ff(t.slice(n.length))||null;return null}function mf(e){let t=[],n=``,r=null;for(let i of e){if(r){n+=i,i===r&&(r=null);continue}if(i===`"`||i===`'`){r=i,n+=i;continue}if(i===`,`){let e=ff(n);e&&t.push(e),n=``;continue}n+=i}let i=ff(n);return i&&t.push(i),t}function hf(e){let t=[],n=new Set;for(let r of e)!r||n.has(r)||(n.add(r),t.push(r));return t}function gf(e){let{frontmatter:t}=A(e);if(!t)return[];let n=df(t);for(let e=0;e<n.length;e+=1){let t=n[e]?.match(/^aliases:\s*(.*)$/);if(!t)continue;let r=t[1]?.trim()??``;if(r){if(r.startsWith(`[`)&&r.endsWith(`]`))return hf(mf(r.slice(1,-1)));let e=ff(r);return e?[e]:[]}let i=[];for(let t=e+1;t<n.length;t+=1){let e=n[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=ff(e.replace(/^\s*-\s+/,``));t&&i.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return hf(i)}return[]}function _f(e,t){let{frontmatter:n,body:r}=A(e),i=pf(n,`title`);if(i)return i;let a=r.match(/^# (.+)$/m);return a?a[1].trim():t}function vf(e){return e?.trim()?{cluster:pf(e,`cluster`)??void 0,category:pf(e,`category`)??void 0,tags:yf(e,`tags`)}:{cluster:void 0,category:void 0,tags:void 0}}function yf(e,t){let n=`${t}:`,r=df(e);for(let e=0;e<r.length;e+=1){let t=r[e];if(!t?.startsWith(n))continue;let i=t.slice(n.length).trim();if(i){if(i.startsWith(`[`)&&i.endsWith(`]`)){let e=mf(i.slice(1,-1));return e.length>0?e:void 0}let e=ff(i);return e?[e]:void 0}let a=[];for(let t=e+1;t<r.length;t+=1){let e=r[t];if(e?.trim()){if(/^\s*-\s+/.test(e)){let t=ff(e.replace(/^\s*-\s+/,``));t&&a.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return a.length>0?a:void 0}}function bf(e,t){let n=_f(e,t),r=gf(e),i=hf([n,...r]),a=[],o=new Set;for(let e of i){let t=h(e);!t||o.has(t)||(o.add(t),a.push(t))}return{docName:t,title:n,aliases:r,matchLabels:i,normalizedMatchLabels:a}}var xf=class extends P{constructor(e,t){super(e,t,`ui`),this.name=`UiLockCollisionError`}};function Sf(e,t){try{return F({lockName:`ui`,lockDir:e,metadata:t}).lockPath}catch(e){throw e instanceof P&&e.lockName===`ui`?new xf(e.existing,e.lockPath):e}}function Cf(e,t){M({lockName:`ui`,lockDir:e,port:t})}function wf(e){return te({lockName:`ui`,lockDir:e})}function Tf(e){ie({lockName:`ui`,lockDir:e})}const Ef=[`.mdx`,`.md`];function Df(e){let t=Se(e).toLowerCase();return Ef.includes(t)}function Of(e){let t=e.toLowerCase();for(let n of Ef)if(t.endsWith(n))return e.slice(0,-n.length);return e}function kf(e){return Ef.indexOf(e)}const Af=new Map;function jf(e,t){let n=Af.get(e);return n?n===t?{effective:n,changed:!1,shadowed:null}:kf(t)<kf(n)?(Af.set(e,t),{effective:t,changed:!0,shadowed:n}):{effective:n,changed:!1,shadowed:t}:(Af.set(e,t),{effective:t,changed:!0,shadowed:null})}function Mf(e){return Af.get(e)??`.md`}function Nf(e){Af.delete(e)}const Pf=/\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/y,Ff=/\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y;function If(){return{backward:new Map,forward:new Map,externalForward:new Map,externalBackward:new Map}}function Lf(e,t){return e?{anchor:e.anchor??t.anchor,snippet:e.snippet??t.snippet}:t}function Rf(e){if(!e)return null;for(let[,t]of[...e.entries()].sort(([e],[t])=>e.localeCompare(t)))if(t.anchor)return t.anchor;return null}function zf(e){return`external:${e}`}function Bf(e){return e.startsWith(`external:`)?e.slice(9):null}function Vf(e){return e.replace(/\s+/g,` `).trim()}function Hf(e,t,n){if(!Vf(e))return null;let r=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
26
26
  `,t-1)),i=[e.indexOf(`.`,n),e.indexOf(`?`,n),e.indexOf(`!`,n),e.indexOf(`
27
- `,n)].filter(e=>e>=0),a=r>=0?r+1:Math.max(0,t-60),o=i.length>0?Math.min(...i)+1:Math.min(e.length,n+60),s=a>0?`…`:``,c=o<e.length?`…`:``,l=zf(e.slice(a,o));return l?`${s}${l}${c}`:null}function Vf(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let n=t[1],r=n[0];return r!=="`"&&r!==`~`?null:{char:r,length:n.length}}function Hf(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function Uf(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function Wf(e,t){let n=0;for(;e[t+n]==="`";)n++;if(n===0)return null;let r=t+n,i=r;for(;i<e.length;){if(e[i]!=="`"){i++;continue}let t=0;for(;e[i+t]==="`";)t++;if(t===n)return{text:e.slice(r,i),nextIndex:i+n};i+=t}return null}function Gf(e,t){Mf.lastIndex=t;let n=Mf.exec(e);if(!n)return null;let r=n[1]?.trim(),i=n[2]?.trim()||null,a=n[3]?.trim()||null;return r?{target:r,alias:a,anchor:i,nextIndex:t+n[0].length}:null}function Kf(e){let t=``,n=[],r=Uf(e);for(;r<e.length;){if(e[r]===`\\`&&r+1<e.length){t+=e[r+1],r+=2;continue}if(e[r]==="`"){let n=Wf(e,r);if(n){t+=n.text,r=n.nextIndex;continue}}if(e[r]===`[`&&e[r+1]===`[`){let i=Gf(e,r);if(i){let e=j(i),a=t.length;t+=e;let o=x(i.target,i.anchor);o?.kind===`doc`&&n.push({target:o.docName,anchor:o.anchor,start:a,end:a+e.length}),r=i.nextIndex;continue}}t+=e[r],r++}return{text:t,occurrences:n}}function qf(e){let t=``,n=[],r=Uf(e);for(;r<e.length;){if(e[r]===`\\`&&r+1<e.length){t+=e[r+1],r+=2;continue}if(e[r]==="`"){let n=Wf(e,r);if(n){t+=n.text,r=n.nextIndex;continue}}if(e[r]===`[`&&e[r+1]===`[`){let i=Gf(e,r);if(i){let e=j(i),a=t.length;t+=e;let o=x(i.target,i.anchor);o?.kind===`external`&&n.push({url:o.url,label:e,start:a,end:a+e.length}),r=i.nextIndex;continue}}t+=e[r],r++}return{text:t,occurrences:n}}function Jf(e){return e.startsWith(`<`)&&e.endsWith(`>`)?e.slice(1,-1):e}function Yf(e,t){Nf.lastIndex=t;let n=Nf.exec(e);return n?{text:n[1]??``,href:Jf(n[2]??``),nextIndex:t+n[0].length}:null}function Xf(e,t){let n=``,r=[],i=Uf(e);for(;i<e.length;){if(e[i]===`\\`&&i+1<e.length){n+=e[i+1],i+=2;continue}if(e[i]==="`"){let t=Wf(e,i);if(t){n+=t.text,i=t.nextIndex;continue}}if(e[i]===`[`&&e[i+1]===`[`){let t=Gf(e,i);if(t){n+=j(t),i=t.nextIndex;continue}}if(e[i]===`[`&&e[i-1]!==`!`){let a=Yf(e,i);if(a){let e=E(a.href,t);if(e?.kind===`doc`){let t=n.length;n+=a.text,r.push({target:e.docName,anchor:e.anchor,start:t,end:t+a.text.length})}else n+=a.text;i=a.nextIndex;continue}}n+=e[i],i++}return{text:n,occurrences:r}}function Zf(e,t){let n=``,r=[],i=Uf(e);for(;i<e.length;){if(e[i]===`\\`&&i+1<e.length){n+=e[i+1],i+=2;continue}if(e[i]==="`"){let t=Wf(e,i);if(t){n+=t.text,i=t.nextIndex;continue}}if(e[i]===`[`&&e[i+1]===`[`){let t=Gf(e,i);if(t){n+=j(t),i=t.nextIndex;continue}}if(e[i]===`[`&&e[i-1]!==`!`){let a=Yf(e,i);if(a){let e=E(a.href,t);if(n+=a.text,e?.kind===`external`){let t=n.length-a.text.length;r.push({url:e.url,label:a.text||null,start:t,end:t+a.text.length})}i=a.nextIndex;continue}}n+=e[i],i++}return{text:n,occurrences:r}}function Qf(e,t){let n=e.replaceAll(`\r
27
+ `,n)].filter(e=>e>=0),a=r>=0?r+1:Math.max(0,t-60),o=i.length>0?Math.min(...i)+1:Math.min(e.length,n+60),s=a>0?`…`:``,c=o<e.length?`…`:``,l=Vf(e.slice(a,o));return l?`${s}${l}${c}`:null}function Uf(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let n=t[1],r=n[0];return r!=="`"&&r!==`~`?null:{char:r,length:n.length}}function Wf(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function Gf(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function Kf(e,t){let n=0;for(;e[t+n]==="`";)n++;if(n===0)return null;let r=t+n,i=r;for(;i<e.length;){if(e[i]!=="`"){i++;continue}let t=0;for(;e[i+t]==="`";)t++;if(t===n)return{text:e.slice(r,i),nextIndex:i+n};i+=t}return null}function qf(e,t){Pf.lastIndex=t;let n=Pf.exec(e);if(!n)return null;let r=n[1]?.trim(),i=n[2]?.trim()||null,a=n[3]?.trim()||null;return r?{target:r,alias:a,anchor:i,nextIndex:t+n[0].length}:null}function Jf(e){let t=``,n=[],r=Gf(e);for(;r<e.length;){if(e[r]===`\\`&&r+1<e.length){t+=e[r+1],r+=2;continue}if(e[r]==="`"){let n=Kf(e,r);if(n){t+=n.text,r=n.nextIndex;continue}}if(e[r]===`[`&&e[r+1]===`[`){let i=qf(e,r);if(i){let e=j(i),a=t.length;t+=e;let o=x(i.target,i.anchor);o?.kind===`doc`&&n.push({target:o.docName,anchor:o.anchor,start:a,end:a+e.length}),r=i.nextIndex;continue}}t+=e[r],r++}return{text:t,occurrences:n}}function Yf(e){let t=``,n=[],r=Gf(e);for(;r<e.length;){if(e[r]===`\\`&&r+1<e.length){t+=e[r+1],r+=2;continue}if(e[r]==="`"){let n=Kf(e,r);if(n){t+=n.text,r=n.nextIndex;continue}}if(e[r]===`[`&&e[r+1]===`[`){let i=qf(e,r);if(i){let e=j(i),a=t.length;t+=e;let o=x(i.target,i.anchor);o?.kind===`external`&&n.push({url:o.url,label:e,start:a,end:a+e.length}),r=i.nextIndex;continue}}t+=e[r],r++}return{text:t,occurrences:n}}function Xf(e){return e.startsWith(`<`)&&e.endsWith(`>`)?e.slice(1,-1):e}function Zf(e,t){Ff.lastIndex=t;let n=Ff.exec(e);return n?{text:n[1]??``,href:Xf(n[2]??``),nextIndex:t+n[0].length}:null}function Qf(e,t){let n=``,r=[],i=Gf(e);for(;i<e.length;){if(e[i]===`\\`&&i+1<e.length){n+=e[i+1],i+=2;continue}if(e[i]==="`"){let t=Kf(e,i);if(t){n+=t.text,i=t.nextIndex;continue}}if(e[i]===`[`&&e[i+1]===`[`){let t=qf(e,i);if(t){n+=j(t),i=t.nextIndex;continue}}if(e[i]===`[`&&e[i-1]!==`!`){let a=Zf(e,i);if(a){let e=E(a.href,t);if(e?.kind===`doc`){let t=n.length;n+=a.text,r.push({target:e.docName,anchor:e.anchor,start:t,end:t+a.text.length})}else n+=a.text;i=a.nextIndex;continue}}n+=e[i],i++}return{text:n,occurrences:r}}function $f(e,t){let n=``,r=[],i=Gf(e);for(;i<e.length;){if(e[i]===`\\`&&i+1<e.length){n+=e[i+1],i+=2;continue}if(e[i]==="`"){let t=Kf(e,i);if(t){n+=t.text,i=t.nextIndex;continue}}if(e[i]===`[`&&e[i+1]===`[`){let t=qf(e,i);if(t){n+=j(t),i=t.nextIndex;continue}}if(e[i]===`[`&&e[i-1]!==`!`){let a=Zf(e,i);if(a){let e=E(a.href,t);if(n+=a.text,e?.kind===`external`){let t=n.length-a.text.length;r.push({url:e.url,label:a.text||null,start:t,end:t+a.text.length})}i=a.nextIndex;continue}}n+=e[i],i++}return{text:n,occurrences:r}}function ep(e,t){let n=e.replaceAll(`\r
28
28
  `,`
29
29
  `).replaceAll(`\r`,`
30
30
  `).split(`
31
- `),r=[],i=null;for(let e of n)if(i)Hf(e,i)&&(i=null);else{let n=Vf(e);if(n)i=n;else{let n=Xf(e,t);r.push(...n.occurrences.map(({target:e,anchor:t,start:r,end:i})=>({target:e,anchor:t,snippet:Bf(n.text,r,i)})))}}return r}function $f(e){let t=e.replaceAll(`\r
31
+ `),r=[],i=null;for(let e of n)if(i)Wf(e,i)&&(i=null);else{let n=Uf(e);if(n)i=n;else{let n=Qf(e,t);r.push(...n.occurrences.map(({target:e,anchor:t,start:r,end:i})=>({target:e,anchor:t,snippet:Hf(n.text,r,i)})))}}return r}function tp(e){let t=e.replaceAll(`\r
32
32
  `,`
33
33
  `).replaceAll(`\r`,`
34
34
  `).split(`
35
- `),n=[],r=null;for(let e=0;e<t.length;e++){let i=t[e]??``;if(r)Hf(i,r)&&(r=null);else{let e=Vf(i);if(e)r=e;else{let e=Kf(i);n.push(...e.occurrences.map(({target:t,anchor:n,start:r,end:i})=>({target:t,anchor:n,snippet:Bf(e.text,r,i)})))}}}return n}function ep(e){let t=e.replaceAll(`\r
35
+ `),n=[],r=null;for(let e=0;e<t.length;e++){let i=t[e]??``;if(r)Wf(i,r)&&(r=null);else{let e=Uf(i);if(e)r=e;else{let e=Jf(i);n.push(...e.occurrences.map(({target:t,anchor:n,start:r,end:i})=>({target:t,anchor:n,snippet:Hf(e.text,r,i)})))}}}return n}function np(e){let t=e.replaceAll(`\r
36
36
  `,`
37
37
  `).replaceAll(`\r`,`
38
38
  `).split(`
39
- `),n=[],r=null;for(let e of t)if(r)Hf(e,r)&&(r=null);else{let t=Vf(e);if(t)r=t;else{let t=qf(e);n.push(...t.occurrences.map(({url:e,label:n,start:r,end:i})=>({url:e,label:n,snippet:Bf(t.text,r,i)})))}}return n}function tp(e,t){let n=e.replaceAll(`\r
39
+ `),n=[],r=null;for(let e of t)if(r)Wf(e,r)&&(r=null);else{let t=Uf(e);if(t)r=t;else{let t=Yf(e);n.push(...t.occurrences.map(({url:e,label:n,start:r,end:i})=>({url:e,label:n,snippet:Hf(t.text,r,i)})))}}return n}function rp(e,t){let n=e.replaceAll(`\r
40
40
  `,`
41
41
  `).replaceAll(`\r`,`
42
42
  `).split(`
43
- `),r=[],i=null;for(let e of n)if(i)Hf(e,i)&&(i=null);else{let n=Vf(e);if(n)i=n;else{let n=Zf(e,t);r.push(...n.occurrences.map(({url:e,label:t,start:r,end:i})=>({url:e,label:t,snippet:Bf(n.text,r,i)})))}}return r}function np(e){return{backward:Object.fromEntries([...e.backward.entries()].map(([e,t])=>[e,[...t.entries()].map(([e,t])=>({source:e,anchor:t.anchor,snippet:t.snippet}))])),forward:Object.fromEntries([...e.forward.entries()].map(([e,t])=>[e,[...t].sort()])),externalForward:Object.fromEntries([...e.externalForward.entries()].map(([e,t])=>[e,[...t.entries()].map(([e,t])=>({url:e,label:t.label,snippet:t.snippet})).sort((e,t)=>e.url.localeCompare(t.url))]))}}function rp(e){let t=new Map;for(let[n,r]of e)for(let[e,i]of r){let r=t.get(e);r||(r=new Map,t.set(e,r)),r.set(n,i)}return t}function ip(e){let t=new Map(Object.entries(e.externalForward??{}).map(([e,t])=>[e,new Map(t.map(e=>[e.url,{label:e.label??null,snippet:e.snippet??null}]))]));return{backward:new Map(Object.entries(e.backward??{}).map(([e,t])=>[e,new Map(t.map(e=>[e.source,{anchor:e.anchor??null,snippet:e.snippet??null}]))])),forward:new Map(Object.entries(e.forward??{}).map(([e,t])=>[e,new Set(t)])),externalForward:t,externalBackward:rp(t)}}var ap=class{projectDir;contentDir;contentFilter;states=new Map;activeBranch=`main`;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.states.set(this.activeBranch,Pf())}getState(e=this.activeBranch){let t=this.states.get(e);return t||(t=Pf(),this.states.set(e,t)),t}getActiveBranch(){return this.activeBranch}switchBranch(e){this.activeBranch=e,this.getState(e)}cachePath(e=this.activeBranch){return V(this.projectDir,`.open-knowledge`,`cache`,e,`backlinks.json`)}updateDocument(e,t,n=[],r=this.activeBranch){if(q(e))return;let i=this.getState(r),a=i.forward.get(e)??new Set,o=i.externalForward.get(e)??new Map;for(let t of a){let n=i.backward.get(t);n&&(n.delete(e),n.size===0&&i.backward.delete(t))}for(let t of o.keys()){let n=i.externalBackward.get(t);n&&(n.delete(e),n.size===0&&i.externalBackward.delete(t))}let s=new Set,c=new Map;i.forward.set(e,s),i.externalForward.set(e,c);for(let n of t){if(!n.target)continue;s.add(n.target);let t=i.backward.get(n.target);t||(t=new Map,i.backward.set(n.target,t)),t.set(e,Ff(t.get(e),{anchor:n.anchor,snippet:n.snippet}))}for(let t of n){if(!t.url)continue;c.set(t.url,{label:t.label,snippet:t.snippet});let n=i.externalBackward.get(t.url);n||(n=new Map,i.externalBackward.set(t.url,n)),(!n.has(e)||!n.get(e)?.snippet&&t.snippet)&&n.set(e,{label:t.label,snippet:t.snippet})}}updateDocumentFromMarkdown(e,t,n=this.activeBranch){try{let{body:r}=A(t),i=$f(r),a=Qf(r,e),o=ep(r),s=tp(r,e),c=new Set(i.map(e=>e.target)),l=[...i,...a.filter(e=>!c.has(e.target))],u=new Set(o.map(e=>e.url)),d=[...o,...s.filter(e=>!u.has(e.url))];this.updateDocument(e,l,d,n)}catch(t){console.warn(`[backlinks] Failed to scan ${e} for link extraction:`,t),this.deleteDocument(e,n)}}deleteDocument(e,t=this.activeBranch){if(q(e))return;let n=this.getState(t),r=n.forward.get(e)??new Set,i=n.externalForward.get(e)??new Map;for(let t of r){let r=n.backward.get(t);r&&(r.delete(e),r.size===0&&n.backward.delete(t))}for(let t of i.keys()){let r=n.externalBackward.get(t);r&&(r.delete(e),r.size===0&&n.externalBackward.delete(t))}n.forward.delete(e),n.externalForward.delete(e)}renameDocument(e,t,n,r=this.activeBranch){this.deleteDocument(e,r),this.updateDocumentFromMarkdown(t,n,r)}getBacklinks(e,t=this.activeBranch){let n=this.getState(t).backward.get(e);return n?[...n.entries()].map(([e,t])=>({source:e,anchor:t.anchor,snippet:t.snippet})).sort((e,t)=>e.source.localeCompare(t.source)):[]}getBacklinkCount(e,t=this.activeBranch){return this.getState(t).backward.get(e)?.size??0}getForwardLinks(e,t=this.activeBranch){return[...this.getState(t).forward.get(e)??new Set].sort((e,t)=>e.localeCompare(t))}getForwardLinkEntries(e,t=this.activeBranch){let n=this.getState(t),r=this.getForwardLinks(e,t).map(t=>({kind:`doc`,target:t,anchor:n.backward.get(t)?.get(e)?.anchor??null,snippet:n.backward.get(t)?.get(e)?.snippet??null})),i=[...(n.externalForward.get(e)??new Map).entries()].map(([e,t])=>({kind:`external`,url:e,label:t.label,snippet:t.snippet})).sort((e,t)=>e.url.localeCompare(t.url));return[...r,...i]}getOrphans(e,t=`both`,n=this.activeBranch){let r=this.getState(n);return[...e].filter(e=>{let n=(r.backward.get(e)?.size??0)>0,i=(r.forward.get(e)?.size??0)>0;return t===`incoming`?!n:(t===`outgoing`||!n)&&!i}).sort((e,t)=>e.localeCompare(t))}getHubs(e=20,t=this.activeBranch){return[...this.getState(t).backward.entries()].map(([e,t])=>({docName:e,count:t.size})).sort((e,t)=>t.count===e.count?e.docName.localeCompare(t.docName):t.count-e.count).slice(0,e)}getDeadLinks(e,t,n=this.activeBranch){let r=this.getState(n),i=new Set(e),a=t?.length?new Set(t):null;return[...r.backward.entries()].filter(([e,t])=>{if(i.has(e))return!1;if(!a)return t.size>0;for(let e of t.keys())if(a.has(e))return!0;return!1}).map(([e,t])=>({target:e,sources:[...t.entries()].filter(([e])=>!a||a.has(e)).map(([e,t])=>({source:e,anchor:t.anchor,snippet:t.snippet})).sort((e,t)=>e.source.localeCompare(t.source))})).filter(e=>e.sources.length>0).sort((e,t)=>t.sources.length===e.sources.length?e.target.localeCompare(t.target):t.sources.length-e.sources.length)}getLinkGraph(e=this.activeBranch){let t=this.getState(e),n=new Map,r=[];for(let[e,i]of t.forward){n.set(e,{kind:`doc`,id:e,docName:e,anchor:If(t.backward.get(e))});for(let a of i)n.set(a,{kind:`doc`,id:a,docName:a,anchor:If(t.backward.get(a))}),r.push({source:e,target:a})}for(let[e,i]of t.externalForward){n.set(e,{kind:`doc`,id:e,docName:e,anchor:If(t.backward.get(e))});for(let[t,a]of i){let i=Lf(t);n.set(i,{kind:`external`,id:i,url:t,label:a.label}),r.push({source:e,target:i})}}return{nodes:[...n.values()].sort((e,t)=>e.id.localeCompare(t.id)),links:r}}getLinkGraphNeighborhood(e,t,n=this.activeBranch){let r=this.getState(n),i=new Map;for(let e of r.externalForward.values())for(let[t,n]of e)i.has(t)||i.set(t,n.label);let a=new Set([e]),o=[{nodeId:e,degree:0}],s=0;for(;s<o.length;){let e=o[s++];if(e.degree>=t)continue;let n=Rf(e.nodeId),i=new Set;if(n)for(let e of r.externalBackward.get(n)?.keys()??[])i.add(e);else{for(let t of r.forward.get(e.nodeId)??new Set)i.add(t);for(let t of r.externalForward.get(e.nodeId)?.keys()??[])i.add(Lf(t));for(let t of r.backward.get(e.nodeId)?.keys()??[])i.add(t)}for(let t of i)a.has(t)||(a.add(t),o.push({nodeId:t,degree:e.degree+1}))}let c=[];for(let[e,t]of r.forward)if(a.has(e))for(let n of t)a.has(n)&&c.push({source:e,target:n});for(let[e,t]of r.externalForward)if(a.has(e))for(let n of t.keys()){let t=Lf(n);a.has(t)&&c.push({source:e,target:t})}return{nodes:[...a].sort().map(e=>{let t=Rf(e);return t?{kind:`external`,id:e,url:t,label:i.get(t)??null}:{kind:`doc`,id:e,docName:e,anchor:If(r.backward.get(e))}}),links:c}}async saveToDisk(e=this.activeBranch){let t=this.cachePath(e);le(xe(t),{recursive:!0});let n=this.getState(e);await Re(t,JSON.stringify(np(n),null,2),`utf-8`)}async loadFromDisk(e=this.activeBranch){let t=this.cachePath(e);if(!L(t))return!1;try{let n=await Fe(t,`utf-8`),r=JSON.parse(n);return this.states.set(e,ip(r)),!0}catch(t){return console.warn(`[backlinks] Failed to load cache for ${e}:`,t),!1}}clear(e=this.activeBranch){this.states.set(e,Pf())}rebuildFileList(e,t){let n;try{n=de(e,{withFileTypes:!0})}catch(t){console.warn(`[backlinks] Failed to read directory ${e}:`,t);return}for(let r of n){let n=Ce(e,r.name);if(r.isDirectory()){let e=B(this.contentDir,n);if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;this.rebuildFileList(n,t);continue}if(!r.isFile()||!Tf(r.name))continue;let i=B(this.contentDir,n);this.contentFilter?.isExcluded(i)||t.push(Ef(i))}}listDocsOnDisk(){if(!L(this.contentDir))return[];let e=[];return this.rebuildFileList(this.contentDir,e),Array.from(new Set(e)).sort((e,t)=>e.localeCompare(t))}rebuildFromDisk(e=this.activeBranch){let t=Pf();for(let e of this.listDocsOnDisk()){let n=V(this.contentDir,`${e}${Af(e)}`);try{let{body:r}=A(R(n,`utf-8`)),i=$f(r),a=Qf(r,e),o=ep(r),s=tp(r,e),c=new Set(i.map(e=>e.target)),l=[...i,...a.filter(e=>!c.has(e.target))],u=new Set(o.map(e=>e.url)),d=[...o,...s.filter(e=>!u.has(e.url))],f=new Set,p=new Map;t.forward.set(e,f),t.externalForward.set(e,p);for(let n of l){if(!n.target)continue;f.add(n.target);let r=t.backward.get(n.target);r||(r=new Map,t.backward.set(n.target,r)),r.set(e,Ff(r.get(e),{anchor:n.anchor,snippet:n.snippet}))}for(let n of d){if(!n.url)continue;p.set(n.url,{label:n.label,snippet:n.snippet});let r=t.externalBackward.get(n.url);r||(r=new Map,t.externalBackward.set(n.url,r)),r.set(e,{label:n.label,snippet:n.snippet})}}catch(t){console.warn(`[backlinks] Failed to rebuild entry for ${e}:`,t)}}this.states.set(e,t)}};const op=/^(human-[^/]+|agent-[^/]+|upstream|server)$/;function sp(e){let t=V(e),n=V(t,`.git`);try{if(he(n).isDirectory())return{path:V(n,`openknowledge`),mode:`integrated`}}catch{}return{path:V(t,`.openknowledge`),mode:`standalone`}}function cp(e){let{path:t}=sp(e);return L(V(t,`HEAD`))?t:null}function lp(e){return`refs/wip/${e}/`}function up(e){if(!e)return[];let t=[];for(let n of e.split(`
44
- `)){let e=n.trim();if(e.startsWith(`ok-contributors: `))try{let n=JSON.parse(e.slice(17));typeof n==`object`&&n&&`id`in n&&typeof n.id==`string`&&`name`in n&&typeof n.name==`string`&&`docs`in n&&Array.isArray(n.docs)&&n.docs.every(e=>typeof e==`string`)&&(!(`colorSeed`in n)||typeof n.colorSeed==`string`)&&t.push(n)}catch{}}return t}const dp=`ok-checkpoint-v1: `;function fp(e){if(!e)return null;for(let t of e.split(`
45
- `)){let e=t.trim();if(!e.startsWith(dp))continue;let n;try{n=JSON.parse(e.slice(18))}catch{return null}if(typeof n!=`object`||!n)return null;let r=n,i=r.kind,a=r.metadata;if(typeof a!=`object`||!a)return null;let o=typeof r.docName==`string`?r.docName:null,s=typeof r.size==`number`&&Number.isFinite(r.size)?r.size:null;if(i===`bridge-merge-loss`){let e=a;return Array.isArray(e.lostSubstrings)&&e.lostSubstrings.every(e=>typeof e==`string`)?{kind:`bridge-merge-loss`,docName:o,size:s,metadata:{lostSubstrings:e.lostSubstrings}}:null}if(i===`external-change-rescue`){let e=a;return typeof e.incomingDiskSha==`string`?{kind:`external-change-rescue`,docName:o,size:s,metadata:{incomingDiskSha:e.incomingDiskSha}}:null}return null}return null}function pp(e){let t={kind:e.kind,metadata:e.metadata};return e.docName!==null&&(t.docName=e.docName),e.size!==null&&(t.size=e.size),`${dp}${JSON.stringify(t)}`}function mp(e){return op.test(e)?e.startsWith(`agent-`)?{id:e,classification:`agent`,isAgent:!0}:e.startsWith(`human-`)?{id:e,classification:`human`,isAgent:!1}:e===`upstream`?{id:e,classification:`upstream`,isAgent:null}:e===`server`?{id:e,classification:`server`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}}function hp(e,t){let n=V(e,`lock`);if(L(n)){let t=null;try{t=JSON.parse(R(n,`utf-8`))}catch{console.warn(`[shadow-lock] Corrupt lock file at ${n} — replacing`)}if(t){let n=t.hostname===ye();if(!(n&&t.pid===process.pid)){if(n&&ee(t.pid))throw Error(`Shadow repo at ${e} is locked by another writer (pid=${t.pid}, worktree=${t.worktreeRoot}, started=${t.startedAt}). Only one active writer instance may mutate a given shadow root at a time.`);console.warn(`[shadow-lock] Stale lock detected (pid=${t.pid}, host=${t.hostname}) — replacing`)}}}let r={pid:process.pid,hostname:ye(),startedAt:new Date().toISOString(),worktreeRoot:t};return z(n,JSON.stringify(r,null,2),`utf-8`),n}function gp(e){let t=V(e,`lock`);try{ge(t)}catch{}}const _p=3e4;function vp(e){return Ne({baseDir:e.workTree,timeout:{block:_p}}).env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree})}async function yp(e){let{path:t,mode:n}=sp(e);if(!L(V(t,`HEAD`))){le(t,{recursive:!0}),await Ne({baseDir:e,timeout:{block:_p}}).raw(`init`,`--bare`,t);let n=Ne({timeout:{block:_p}}).env({GIT_DIR:t});await n.raw(`config`,`--unset`,`core.bare`),await n.raw(`config`,`core.worktree`,e),await n.raw(`config`,`user.name`,`openknowledge`),await n.raw(`config`,`user.email`,`noreply@openknowledge.local`)}if(n===`standalone`){let t=V(e,`.gitignore`),n=`.openknowledge/`,r=``;try{r=R(t,`utf-8`)}catch{}if(!r.split(`
46
- `).some(e=>e.trim()===n)){let e=r.length>0&&!r.endsWith(`
47
- `)?`
48
- `:``;z(t,`${r}${e}${n}\n`,`utf-8`)}}return hp(t,e),{gitDir:t,workTree:e}}function bp(e){gp(e.gitDir)}async function xp(e,t,n,r,i=`main`){let a=V(e.gitDir,`index-wip-${t.id}`),o=`refs/wip/${i}/${t.id}`,s=vp(e),c=n||`.`;try{try{let t=(await s.raw(`rev-parse`,`${o}^{tree}`)).trim();await s.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:a}).raw(`read-tree`,t)}catch(e){let t=e instanceof Error?e.message:String(e);if(!(t.includes(`unknown revision`)||t.includes(`bad revision`)))throw console.error(`[shadow-repo] Unexpected error seeding index for ${o}:`,e),e}await s.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:a}).raw(`add`,c);let n=(await s.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:a}).raw(`write-tree`)).trim(),i=null;try{i=(await s.raw(`rev-parse`,o)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw console.error(`[shadow-repo] Unexpected error resolving ${o}:`,e),e}let l=[`commit-tree`,n,`-m`,r];i&&l.push(`-p`,i);let u=(await s.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:t.name,GIT_AUTHOR_EMAIL:t.email,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(...l)).trim();return await s.raw(`update-ref`,o,u),u}finally{try{me(a)}catch{}}}const Sp={id:`upstream`,name:`upstream`,email:`noreply@openknowledge.local`};async function Cp(e,t,n,r,i=`main`){return xp(e,Sp,t,n?`upstream: import from ${n.slice(0,8)}..${r.slice(0,8)}`:`upstream: initial import at ${r.slice(0,8)}`,i)}const wp={id:`openknowledge-server`,name:`openknowledge-server`,email:`noreply@openknowledge.local`};async function Tp(e,t,n,r=`main`){return xp(e,wp,t,`safety-checkpoint: pre-${n.action}`,r)}async function Ep(e,t,n){let r=n.branch??`main`,i=vp(e),a=ke(),o=V(e.gitDir,`index-checkpoint-${a}`),s=V(e.gitDir,`tmp-checkpoint-blob-${a}`),c=t?`${t.replace(/\/$/,``)}/${n.docName}`:n.docName,l=Buffer.byteLength(n.contents,`utf-8`),u=pp(n.kind===`bridge-merge-loss`?{kind:`bridge-merge-loss`,docName:n.docName,size:l,metadata:n.metadata}:{kind:`external-change-rescue`,docName:n.docName,size:l,metadata:n.metadata}),d=`checkpoint: ${n.label}\n\n${u}`;try{z(s,n.contents,`utf-8`);let t=(await i.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`hash-object`,`-w`,s)).trim();await i.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${t},${c}`);let a=(await i.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`write-tree`)).trim(),l=(await i.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(`commit-tree`,a,`-m`,d)).trim();return await i.raw(`update-ref`,`refs/checkpoints/${r}/${l}`,l),l}finally{try{me(o)}catch{}try{me(s)}catch{}}}async function Dp(e,t=`main`){let n=vp(e),r;try{r=await n.raw(`for-each-ref`,`--format=%(objectname)`,`refs/checkpoints/${t}/`)}catch{return[]}let i=r.trim().split(`
49
- `).filter(e=>e.length===40);if(i.length===0)return[];let a;try{a=await n.raw(`log`,`--no-walk`,`--author-date-order`,`--format=%H%x00%aI%x00%s%x00%B%x1e`,...i)}catch{return[]}let o=[];for(let e of a.split(``)){let t=e.trimStart();if(!t)continue;let[r=``,i=``,a=``,s=``]=t.split(`\0`),c=fp(s);if(c?.kind!==`external-change-rescue`)continue;let l=c.docName??``,u=c.size??0;if(!l)try{let e=(await n.raw(`ls-tree`,`-r`,`--long`,r)).trim().split(`
50
- `)[0];if(e){let t=e.split(/\s+/);u===0&&(u=Number(t[3]??`0`)),l=(t[4]??``).replace(/\.mdx?$/,``).split(`/`).slice(-1)[0]??``}}catch{}l&&o.push({docName:l,timestamp:i,size:u,sha:r,label:a.replace(/^checkpoint:\s*/,``),incomingDiskSha:c.metadata.incomingDiskSha})}return o}async function Op(e,t,n,r){if(r.length===0)return null;let i=vp(e),a=V(e.gitDir,`index-park-${t.replace(/\//g,`-`)}`),o=`refs/wip/${t}/human-${n}`,s=V(e.gitDir,`tmp-park-blob`);try{for(let t of r){z(s,t.markdown,`utf-8`);let n=(await i.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:a}).raw(`hash-object`,`-w`,s)).trim();await i.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:a}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${n},${t.docName}`),z(s,t.diskSnapshot,`utf-8`);let r=(await i.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:a}).raw(`hash-object`,`-w`,s)).trim();await i.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:a}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${r},.park-base/${t.docName}`)}let t=(await i.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:a}).raw(`write-tree`)).trim(),n=null;try{n=(await i.raw(`rev-parse`,o)).trim()}catch{}let c=[`commit-tree`,t,`-m`,`park: branch context at ${new Date().toISOString()}`];n&&c.push(`-p`,n);let l=(await i.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(...c)).trim();return await i.raw(`update-ref`,o,l),l}finally{try{me(a)}catch{}try{me(s)}catch{}}}async function kp(e,t,n,r){let i=vp(e),a=`refs/wip/${t}/human-${n}`,o;try{o=(await i.raw(`rev-parse`,a)).trim()}catch{return null}try{return(await i.raw(`log`,`-1`,`--format=%s`,o)).trim().startsWith(`park:`)?{markdown:(await i.raw(`show`,`${o}:${r}`)).trim(),diskSnapshot:(await i.raw(`show`,`${o}:.park-base/${r}`)).trim()}:null}catch(e){throw console.error(`[shadow] Failed to read parked state for ${r} from ${a}:`,e),e}}async function Ap(e,t,n,r=`main`){let i=vp(e),a=t||`.`,o=V(e.gitDir,`index-checkpoint`);try{await i.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:o}).raw(`add`,a);let t=(await i.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`write-tree`)).trim(),s=[];for(let e of[...n,{id:`upstream`}])try{let t=(await i.raw(`rev-parse`,`refs/wip/${r}/${e.id}`)).trim();s.push(t)}catch{}let c=[...new Set(s)];if(c.length===0)try{let e=(await i.raw(`for-each-ref`,`--sort=-creatordate`,`--format=%(objectname)`,`refs/checkpoints/${r}/`)).trim().split(`
51
- `).filter(Boolean);e[0]&&c.push(e[0])}catch{}let l=[`commit-tree`,t,`-m`,`checkpoint: Checkpoint version`];for(let e of c)l.push(`-p`,e);let u=(await i.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(...l)).trim(),d=`refs/checkpoints/${r}/${u}`;await i.raw(`update-ref`,d,u);for(let e of n)try{await i.raw(`update-ref`,`-d`,`refs/wip/${r}/${e.id}`)}catch{}try{await i.raw(`update-ref`,`-d`,`refs/wip/${r}/upstream`)}catch{}return{checkpointRef:d}}finally{try{me(o)}catch{}}}const jp=Mc(`persistence`);function Mp(e,t){if(e.includes(`\0`))throw Error(`Invalid document name: ${e}`);let n=V(t,`${e}${Af(e)}`);if(!n.startsWith(`${t}/`))throw Error(`Invalid document name: ${e}`);return n}function Np(e,t){return e===t||e.startsWith(t+Te)}const Pp=new Map;let Fp=`main`;function Ip(e){Fp=e,Pp.has(e)||Pp.set(e,new Map)}function Lp(){return Fp}function Rp(e){return Pp.get(Fp)?.get(e)}function zp(e,t){Pp.has(Fp)||Pp.set(Fp,new Map),Pp.get(Fp)?.set(e,t)}function Bp(e){Pp.get(Fp)?.delete(e)}let Vp=!1;function Hp(e){Vp=e}function Up(){return Vp}function Wp(e){let t=e?.contentDir??process.cwd(),n;try{n=fe(t)}catch{n=t}let r=e?.projectDir??process.cwd(),i=e?.shadowRef,a=e?.contentRoot??(B(r,n)||`content`),o=e?.backlinkIndex,s=new Map,c=e?.gitEnabled??!0,l=e?.commitDebounceMs??15e3,d=e?.wipRef??`refs/wip/main`,f=e?.getCurrentBranch,p={id:`server`,name:`openknowledge-server`,email:`noreply@openknowledge.local`},m=null,h=0,g=null,_=!1;async function v(){let e=i?.current;if(e){let t=Qd(),n=ef(t),r=`WIP auto-save ${new Date().toISOString()}${n}`,i=f?.()??`main`;try{let t=await xp(e,p,a,r,i);h=0,jp.info({sha:t.slice(0,8),writer:p.id},`[persistence] Shadow WIP commit: ${t.slice(0,8)} on refs/wip/${p.id}`)}catch(e){$d(t),h++,Bc(),jp.error({err:e,attempt:h},`[persistence] Shadow commit failed (attempt ${h})`),h>=3&&jp.error({attempt:h},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}return}let t=vp({gitDir:V(r,`.git`),workTree:r}),n=V(r,`.git/index-wip`),o={GIT_INDEX_FILE:n};try{try{let e=(await t.raw(`rev-parse`,`HEAD^{tree}`)).trim();await t.env(o).raw(`read-tree`,e)}catch(e){let t=e instanceof Error?e.message:String(e);t.includes(`unknown revision`)||t.includes(`bad revision`)?jp.info({},`[persistence] Empty repo — starting with empty index`):jp.error({err:e},`[persistence] Failed to read HEAD tree, falling back to empty index`)}await t.env(o).raw(`add`,a);let e=(await t.env(o).raw(`write-tree`)).trim(),n=null;try{n=(await t.raw(`rev-parse`,d)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw e}let r=[`commit-tree`,e,`-m`,`WIP auto-save ${new Date().toISOString()}`];n&&r.push(`-p`,n);let i=(await t.raw(...r)).trim();await t.raw(`update-ref`,d,i),h=0,jp.info({sha:i.slice(0,8),wipRef:d},`[persistence] Git commit: ${i.slice(0,8)} on ${d}`)}catch(e){h++,Bc(),jp.error({err:e,attempt:h},`[persistence] Git commit failed (attempt ${h})`),h>=3&&jp.error({attempt:h},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}finally{try{ge(n)}catch{}}}function y(){c&&(Up()||(m&&clearTimeout(m),m=setTimeout(()=>{if(m=null,g){_=!0;return}g=v().finally(()=>{g=null,_&&(_=!1,y())})},l)))}async function b(){m&&(clearTimeout(m),m=null,g||=v().finally(()=>{g=null,_&&(_=!1,y())})),g&&await g}let x={async onLoadDocument({document:e,documentName:t,context:r}){if(q(t))return;jp.info({documentName:t,connections:e.getConnectionsCount?.()??`?`},`[persistence] onLoadDocument called for ${t} (connections: ${e.getConnectionsCount?.()??`?`})`);let i=Mp(t,n);if(!L(i))return;try{let e=fe(i);if(!Np(e,n)){console.warn(`[persistence] symlink-escape on load: ${i} → ${e}, refusing`);return}}catch(e){if(e.code===`ELOOP`){console.warn(`[persistence] Symlink cycle on load: ${i}, refusing`);return}}let{frontmatter:a,body:o}=A(R(i,`utf-8`));a&&(s.set(t,a),e.getMap(`metadata`).set(`frontmatter`,a));let c=el.parseWithFallback(o),l=e.getXmlFragment(`default`);jp.info({documentName:t,fragmentLength:l.length},`[persistence] onLoadDocument ${t}: fragment.length=${l.length} before update`),l.length===0?(ls(e,l,tl.nodeFromJSON(c),{mapping:new Map,isOMark:new Map}),jp.info({filePath:i,children:l.length},`[persistence] Loaded ${i} into Y.Doc (${l.length} children)`),l.observeDeep(()=>{jp.info({documentName:t,fragmentLength:l.length},`[persistence] MUTATION on ${t}: fragment.length=${l.length}`)})):jp.info({documentName:t,children:l.length},`[persistence] Skipped load for ${t} — fragment already has ${l.length} children`),zp(t,u(a,el.serialize(fs(l,tl).toJSON())))},async onStoreDocument({document:e,documentName:t}){if(q(t)||Up())return;let r=fs(e.getXmlFragment(`default`),tl).toJSON(),i=el.serialize(r),a=e.getMap(`metadata`).get(`frontmatter`),c=u(typeof a==`string`?a:s.get(t)||``,i),l=Rp(t);if(l!==void 0&&c===l)return;l&&c.length>l.length*1.5&&(jp.warn({documentName:t,markdownLength:c.length,baseLength:l.length},`[persistence] WARNING: serialized content is ${c.length} bytes vs base ${l.length} bytes for ${t} — possible duplication`),jp.warn({documentName:t,children:e.getXmlFragment(`default`).length},`[persistence] Fragment children: ${e.getXmlFragment(`default`).length}`));let d=Mp(t,n);await Pe(xe(d),{recursive:!0});let f;try{f=await Ie(d)}catch(e){let n=e.code;if(n===`ENOENT`){let e=!1;try{e=ce(d).isSymbolicLink()}catch(e){e.code!==`ENOENT`&&jp.warn({err:e,path:d},`[persistence] lstat failed during broken-symlink check`)}e&&console.warn(`[persistence] broken-symlink fallback`,{docName:t,reason:`broken-symlink`}),f=d}else if(n===`ELOOP`)throw console.error(`[persistence] Symlink cycle at ${d}`),Error(`Symlink cycle detected at ${d}`);else throw e}if(!Np(f,n)){let e=`symlink-escape: ${d} resolves to ${f} outside ${n}`;throw console.error(`[persistence] ${e}`,{docName:t,originalPath:d,canonical:f,contentDir:n}),Error(e)}let p=`${f}.tmp.${crypto.randomUUID()}`;try{await Re(p,c,`utf-8`),await Le(p,f),em(f,nm(c)),Gc()}catch(e){try{ge(p)}catch{}throw jp.error({err:e,documentName:t},`[persistence] Failed to save ${t}`),e}jp.info({filePath:f,bytes:c.length},`[persistence] Wrote ${f} (${c.length} bytes)`),zp(t,c),o&&(o.updateDocumentFromMarkdown(t,c),o.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache for ${t}:`,e)})),y()}};async function S(){g&&await g}return{extension:x,flushPendingGitCommit:b,waitForPendingCommits:S}}const Gp=/^(<{7} |={7}$|>{7} |\|{7} )/m;function Kp(e){return Gp.test(e)}function qp(e){let t=e.replace(/\n+$/,``);if(!t)return[];let n=t.split(`
43
+ `),r=[],i=null;for(let e of n)if(i)Wf(e,i)&&(i=null);else{let n=Uf(e);if(n)i=n;else{let n=$f(e,t);r.push(...n.occurrences.map(({url:e,label:t,start:r,end:i})=>({url:e,label:t,snippet:Hf(n.text,r,i)})))}}return r}function ip(e){return{backward:Object.fromEntries([...e.backward.entries()].map(([e,t])=>[e,[...t.entries()].map(([e,t])=>({source:e,anchor:t.anchor,snippet:t.snippet}))])),forward:Object.fromEntries([...e.forward.entries()].map(([e,t])=>[e,[...t].sort()])),externalForward:Object.fromEntries([...e.externalForward.entries()].map(([e,t])=>[e,[...t.entries()].map(([e,t])=>({url:e,label:t.label,snippet:t.snippet})).sort((e,t)=>e.url.localeCompare(t.url))]))}}function ap(e){let t=new Map;for(let[n,r]of e)for(let[e,i]of r){let r=t.get(e);r||(r=new Map,t.set(e,r)),r.set(n,i)}return t}function op(e){let t=new Map(Object.entries(e.externalForward??{}).map(([e,t])=>[e,new Map(t.map(e=>[e.url,{label:e.label??null,snippet:e.snippet??null}]))]));return{backward:new Map(Object.entries(e.backward??{}).map(([e,t])=>[e,new Map(t.map(e=>[e.source,{anchor:e.anchor??null,snippet:e.snippet??null}]))])),forward:new Map(Object.entries(e.forward??{}).map(([e,t])=>[e,new Set(t)])),externalForward:t,externalBackward:ap(t)}}var sp=class{projectDir;contentDir;contentFilter;states=new Map;activeBranch=`main`;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.states.set(this.activeBranch,If())}getState(e=this.activeBranch){let t=this.states.get(e);return t||(t=If(),this.states.set(e,t)),t}getActiveBranch(){return this.activeBranch}switchBranch(e){this.activeBranch=e,this.getState(e)}cachePath(e=this.activeBranch){return V(this.projectDir,`.open-knowledge`,`cache`,e,`backlinks.json`)}updateDocument(e,t,n=[],r=this.activeBranch){if(q(e))return;let i=this.getState(r),a=i.forward.get(e)??new Set,o=i.externalForward.get(e)??new Map;for(let t of a){let n=i.backward.get(t);n&&(n.delete(e),n.size===0&&i.backward.delete(t))}for(let t of o.keys()){let n=i.externalBackward.get(t);n&&(n.delete(e),n.size===0&&i.externalBackward.delete(t))}let s=new Set,c=new Map;i.forward.set(e,s),i.externalForward.set(e,c);for(let n of t){if(!n.target)continue;s.add(n.target);let t=i.backward.get(n.target);t||(t=new Map,i.backward.set(n.target,t)),t.set(e,Lf(t.get(e),{anchor:n.anchor,snippet:n.snippet}))}for(let t of n){if(!t.url)continue;c.set(t.url,{label:t.label,snippet:t.snippet});let n=i.externalBackward.get(t.url);n||(n=new Map,i.externalBackward.set(t.url,n)),(!n.has(e)||!n.get(e)?.snippet&&t.snippet)&&n.set(e,{label:t.label,snippet:t.snippet})}}updateDocumentFromMarkdown(e,t,n=this.activeBranch){try{let{body:r}=A(t),i=tp(r),a=ep(r,e),o=np(r),s=rp(r,e),c=new Set(i.map(e=>e.target)),l=[...i,...a.filter(e=>!c.has(e.target))],u=new Set(o.map(e=>e.url)),d=[...o,...s.filter(e=>!u.has(e.url))];this.updateDocument(e,l,d,n)}catch(t){console.warn(`[backlinks] Failed to scan ${e} for link extraction:`,t),this.deleteDocument(e,n)}}deleteDocument(e,t=this.activeBranch){if(q(e))return;let n=this.getState(t),r=n.forward.get(e)??new Set,i=n.externalForward.get(e)??new Map;for(let t of r){let r=n.backward.get(t);r&&(r.delete(e),r.size===0&&n.backward.delete(t))}for(let t of i.keys()){let r=n.externalBackward.get(t);r&&(r.delete(e),r.size===0&&n.externalBackward.delete(t))}n.forward.delete(e),n.externalForward.delete(e)}renameDocument(e,t,n,r=this.activeBranch){this.deleteDocument(e,r),this.updateDocumentFromMarkdown(t,n,r)}getBacklinks(e,t=this.activeBranch){let n=this.getState(t).backward.get(e);return n?[...n.entries()].map(([e,t])=>({source:e,anchor:t.anchor,snippet:t.snippet})).sort((e,t)=>e.source.localeCompare(t.source)):[]}getBacklinkCount(e,t=this.activeBranch){return this.getState(t).backward.get(e)?.size??0}getForwardLinks(e,t=this.activeBranch){return[...this.getState(t).forward.get(e)??new Set].sort((e,t)=>e.localeCompare(t))}getForwardLinkEntries(e,t=this.activeBranch){let n=this.getState(t),r=this.getForwardLinks(e,t).map(t=>({kind:`doc`,target:t,anchor:n.backward.get(t)?.get(e)?.anchor??null,snippet:n.backward.get(t)?.get(e)?.snippet??null})),i=[...(n.externalForward.get(e)??new Map).entries()].map(([e,t])=>({kind:`external`,url:e,label:t.label,snippet:t.snippet})).sort((e,t)=>e.url.localeCompare(t.url));return[...r,...i]}getOrphans(e,t=`both`,n=this.activeBranch){let r=this.getState(n);return[...e].filter(e=>{let n=(r.backward.get(e)?.size??0)>0,i=(r.forward.get(e)?.size??0)>0;return t===`incoming`?!n:(t===`outgoing`||!n)&&!i}).sort((e,t)=>e.localeCompare(t))}getHubs(e=20,t=this.activeBranch){return[...this.getState(t).backward.entries()].map(([e,t])=>({docName:e,count:t.size})).sort((e,t)=>t.count===e.count?e.docName.localeCompare(t.docName):t.count-e.count).slice(0,e)}getDeadLinks(e,t,n=this.activeBranch){let r=this.getState(n),i=new Set(e),a=t?.length?new Set(t):null;return[...r.backward.entries()].filter(([e,t])=>{if(i.has(e))return!1;if(!a)return t.size>0;for(let e of t.keys())if(a.has(e))return!0;return!1}).map(([e,t])=>({target:e,sources:[...t.entries()].filter(([e])=>!a||a.has(e)).map(([e,t])=>({source:e,anchor:t.anchor,snippet:t.snippet})).sort((e,t)=>e.source.localeCompare(t.source))})).filter(e=>e.sources.length>0).sort((e,t)=>t.sources.length===e.sources.length?e.target.localeCompare(t.target):t.sources.length-e.sources.length)}getLinkGraph(e=this.activeBranch){let t=this.getState(e),n=new Map,r=[];for(let[e,i]of t.forward){n.set(e,{kind:`doc`,id:e,docName:e,anchor:Rf(t.backward.get(e))});for(let a of i)n.set(a,{kind:`doc`,id:a,docName:a,anchor:Rf(t.backward.get(a))}),r.push({source:e,target:a})}for(let[e,i]of t.externalForward){n.set(e,{kind:`doc`,id:e,docName:e,anchor:Rf(t.backward.get(e))});for(let[t,a]of i){let i=zf(t);n.set(i,{kind:`external`,id:i,url:t,label:a.label}),r.push({source:e,target:i})}}return{nodes:[...n.values()].sort((e,t)=>e.id.localeCompare(t.id)),links:r}}getLinkGraphNeighborhood(e,t,n=this.activeBranch){let r=this.getState(n),i=new Map;for(let e of r.externalForward.values())for(let[t,n]of e)i.has(t)||i.set(t,n.label);let a=new Set([e]),o=[{nodeId:e,degree:0}],s=0;for(;s<o.length;){let e=o[s++];if(e.degree>=t)continue;let n=Bf(e.nodeId),i=new Set;if(n)for(let e of r.externalBackward.get(n)?.keys()??[])i.add(e);else{for(let t of r.forward.get(e.nodeId)??new Set)i.add(t);for(let t of r.externalForward.get(e.nodeId)?.keys()??[])i.add(zf(t));for(let t of r.backward.get(e.nodeId)?.keys()??[])i.add(t)}for(let t of i)a.has(t)||(a.add(t),o.push({nodeId:t,degree:e.degree+1}))}let c=[];for(let[e,t]of r.forward)if(a.has(e))for(let n of t)a.has(n)&&c.push({source:e,target:n});for(let[e,t]of r.externalForward)if(a.has(e))for(let n of t.keys()){let t=zf(n);a.has(t)&&c.push({source:e,target:t})}return{nodes:[...a].sort().map(e=>{let t=Bf(e);return t?{kind:`external`,id:e,url:t,label:i.get(t)??null}:{kind:`doc`,id:e,docName:e,anchor:Rf(r.backward.get(e))}}),links:c}}async saveToDisk(e=this.activeBranch){let t=this.cachePath(e);le(xe(t),{recursive:!0});let n=this.getState(e);await ze(t,JSON.stringify(ip(n),null,2),`utf-8`)}async loadFromDisk(e=this.activeBranch){let t=this.cachePath(e);if(!L(t))return!1;try{let n=await Ie(t,`utf-8`),r=JSON.parse(n);return this.states.set(e,op(r)),!0}catch(t){return console.warn(`[backlinks] Failed to load cache for ${e}:`,t),!1}}clear(e=this.activeBranch){this.states.set(e,If())}rebuildFileList(e,t){let n;try{n=de(e,{withFileTypes:!0})}catch(t){console.warn(`[backlinks] Failed to read directory ${e}:`,t);return}for(let r of n){let n=Ce(e,r.name);if(r.isDirectory()){let e=B(this.contentDir,n);if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;this.rebuildFileList(n,t);continue}if(!r.isFile()||!Df(r.name))continue;let i=B(this.contentDir,n);this.contentFilter?.isExcluded(i)||t.push(Of(i))}}listDocsOnDisk(){if(!L(this.contentDir))return[];let e=[];return this.rebuildFileList(this.contentDir,e),Array.from(new Set(e)).sort((e,t)=>e.localeCompare(t))}rebuildFromDisk(e=this.activeBranch){let t=If();for(let e of this.listDocsOnDisk()){let n=V(this.contentDir,`${e}${Mf(e)}`);try{let{body:r}=A(R(n,`utf-8`)),i=tp(r),a=ep(r,e),o=np(r),s=rp(r,e),c=new Set(i.map(e=>e.target)),l=[...i,...a.filter(e=>!c.has(e.target))],u=new Set(o.map(e=>e.url)),d=[...o,...s.filter(e=>!u.has(e.url))],f=new Set,p=new Map;t.forward.set(e,f),t.externalForward.set(e,p);for(let n of l){if(!n.target)continue;f.add(n.target);let r=t.backward.get(n.target);r||(r=new Map,t.backward.set(n.target,r)),r.set(e,Lf(r.get(e),{anchor:n.anchor,snippet:n.snippet}))}for(let n of d){if(!n.url)continue;p.set(n.url,{label:n.label,snippet:n.snippet});let r=t.externalBackward.get(n.url);r||(r=new Map,t.externalBackward.set(n.url,r)),r.set(e,{label:n.label,snippet:n.snippet})}}catch(t){console.warn(`[backlinks] Failed to rebuild entry for ${e}:`,t)}}this.states.set(e,t)}};const cp=/^(human-[^/]+|agent-[^/]+|upstream|server)$/;function lp(e){return V(e,`.git/open-knowledge`)}function up(e){let t=lp(e);return L(V(t,`HEAD`))?t:null}function dp(e){return`refs/wip/${e}/`}function fp(e){if(!e)return[];let t=[];for(let n of e.split(`
44
+ `)){let e=n.trim();if(e.startsWith(`ok-contributors: `))try{let n=JSON.parse(e.slice(17));typeof n==`object`&&n&&`id`in n&&typeof n.id==`string`&&`name`in n&&typeof n.name==`string`&&`docs`in n&&Array.isArray(n.docs)&&n.docs.every(e=>typeof e==`string`)&&(!(`colorSeed`in n)||typeof n.colorSeed==`string`)&&t.push(n)}catch{}}return t}const pp=`ok-checkpoint-v1: `;function mp(e){if(!e)return null;for(let t of e.split(`
45
+ `)){let e=t.trim();if(!e.startsWith(pp))continue;let n;try{n=JSON.parse(e.slice(18))}catch{return null}if(typeof n!=`object`||!n)return null;let r=n,i=r.kind,a=r.metadata;if(typeof a!=`object`||!a)return null;let o=typeof r.docName==`string`?r.docName:null,s=typeof r.size==`number`&&Number.isFinite(r.size)?r.size:null;if(i===`bridge-merge-loss`){let e=a;return Array.isArray(e.lostSubstrings)&&e.lostSubstrings.every(e=>typeof e==`string`)?{kind:`bridge-merge-loss`,docName:o,size:s,metadata:{lostSubstrings:e.lostSubstrings}}:null}if(i===`external-change-rescue`){let e=a;return typeof e.incomingDiskSha==`string`?{kind:`external-change-rescue`,docName:o,size:s,metadata:{incomingDiskSha:e.incomingDiskSha}}:null}return null}return null}function hp(e){let t={kind:e.kind,metadata:e.metadata};return e.docName!==null&&(t.docName=e.docName),e.size!==null&&(t.size=e.size),`${pp}${JSON.stringify(t)}`}function gp(e){return cp.test(e)?e.startsWith(`agent-`)?{id:e,classification:`agent`,isAgent:!0}:e.startsWith(`human-`)?{id:e,classification:`human`,isAgent:!1}:e===`upstream`?{id:e,classification:`upstream`,isAgent:null}:e===`server`?{id:e,classification:`server`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}}function _p(e,t){let n=V(e,`lock`);if(L(n)){let t=null;try{t=JSON.parse(R(n,`utf-8`))}catch{console.warn(`[shadow-lock] Corrupt lock file at ${n} — replacing`)}if(t){let n=t.hostname===ye();if(!(n&&t.pid===process.pid)){if(n&&ee(t.pid))throw Error(`Shadow repo at ${e} is locked by another writer (pid=${t.pid}, worktree=${t.worktreeRoot}, started=${t.startedAt}). Only one active writer instance may mutate a given shadow root at a time.`);console.warn(`[shadow-lock] Stale lock detected (pid=${t.pid}, host=${t.hostname}) — replacing`)}}}let r={pid:process.pid,hostname:ye(),startedAt:new Date().toISOString(),worktreeRoot:t};return z(n,JSON.stringify(r,null,2),`utf-8`),n}function vp(e){let t=V(e,`lock`);try{ge(t)}catch{}}const yp=3e4;function bp(e){return Pe({baseDir:e.workTree,timeout:{block:yp}}).env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree})}async function xp(e){let t=lp(e),n=V(e,`.git/openknowledge`),r=L(n),i=L(t);if(r&&!i?pe(n,t):r&&i&&console.warn(`[shadow-repo] unexpected legacy + new shadow both present — no rename performed`),!L(V(t,`HEAD`))){le(t,{recursive:!0}),await Pe({baseDir:e,timeout:{block:yp}}).raw(`init`,`--bare`,t);let n=Pe({timeout:{block:yp}}).env({GIT_DIR:t});await n.raw(`config`,`--unset`,`core.bare`),await n.raw(`config`,`core.worktree`,e),await n.raw(`config`,`user.name`,`openknowledge`),await n.raw(`config`,`user.email`,`noreply@openknowledge.local`)}return _p(t,e),{gitDir:t,workTree:e}}function Sp(e){vp(e.gitDir)}async function Cp(e,t,n,r,i=`main`){let a=V(e.gitDir,`index-wip-${t.id}`),o=`refs/wip/${i}/${t.id}`,s=bp(e),c=n||`.`;try{try{let t=(await s.raw(`rev-parse`,`${o}^{tree}`)).trim();await s.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:a}).raw(`read-tree`,t)}catch(e){let t=e instanceof Error?e.message:String(e);if(!(t.includes(`unknown revision`)||t.includes(`bad revision`)))throw console.error(`[shadow-repo] Unexpected error seeding index for ${o}:`,e),e}await s.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:a}).raw(`add`,c);let n=(await s.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:a}).raw(`write-tree`)).trim(),i=null;try{i=(await s.raw(`rev-parse`,o)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw console.error(`[shadow-repo] Unexpected error resolving ${o}:`,e),e}let l=[`commit-tree`,n,`-m`,r];i&&l.push(`-p`,i);let u=(await s.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:t.name,GIT_AUTHOR_EMAIL:t.email,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(...l)).trim();return await s.raw(`update-ref`,o,u),u}finally{try{me(a)}catch{}}}const wp={id:`upstream`,name:`upstream`,email:`noreply@openknowledge.local`};async function Tp(e,t,n,r,i=`main`){return Cp(e,wp,t,n?`upstream: import from ${n.slice(0,8)}..${r.slice(0,8)}`:`upstream: initial import at ${r.slice(0,8)}`,i)}const Ep={id:`openknowledge-server`,name:`openknowledge-server`,email:`noreply@openknowledge.local`};async function Dp(e,t,n,r=`main`){return Cp(e,Ep,t,`safety-checkpoint: pre-${n.action}`,r)}async function Op(e,t,n){let r=n.branch??`main`,i=bp(e),a=ke(),o=V(e.gitDir,`index-checkpoint-${a}`),s=V(e.gitDir,`tmp-checkpoint-blob-${a}`),c=t?`${t.replace(/\/$/,``)}/${n.docName}`:n.docName,l=Buffer.byteLength(n.contents,`utf-8`),u=hp(n.kind===`bridge-merge-loss`?{kind:`bridge-merge-loss`,docName:n.docName,size:l,metadata:n.metadata}:{kind:`external-change-rescue`,docName:n.docName,size:l,metadata:n.metadata}),d=`checkpoint: ${n.label}\n\n${u}`;try{z(s,n.contents,`utf-8`);let t=(await i.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`hash-object`,`-w`,s)).trim();await i.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${t},${c}`);let a=(await i.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`write-tree`)).trim(),l=(await i.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(`commit-tree`,a,`-m`,d)).trim();return await i.raw(`update-ref`,`refs/checkpoints/${r}/${l}`,l),l}finally{try{me(o)}catch{}try{me(s)}catch{}}}async function kp(e,t=`main`){let n=bp(e),r;try{r=await n.raw(`for-each-ref`,`--format=%(objectname)`,`refs/checkpoints/${t}/`)}catch{return[]}let i=r.trim().split(`
46
+ `).filter(e=>e.length===40);if(i.length===0)return[];let a;try{a=await n.raw(`log`,`--no-walk`,`--author-date-order`,`--format=%H%x00%aI%x00%s%x00%B%x1e`,...i)}catch{return[]}let o=[];for(let e of a.split(``)){let t=e.trimStart();if(!t)continue;let[r=``,i=``,a=``,s=``]=t.split(`\0`),c=mp(s);if(c?.kind!==`external-change-rescue`)continue;let l=c.docName??``,u=c.size??0;if(!l)try{let e=(await n.raw(`ls-tree`,`-r`,`--long`,r)).trim().split(`
47
+ `)[0];if(e){let t=e.split(/\s+/);u===0&&(u=Number(t[3]??`0`)),l=(t[4]??``).replace(/\.mdx?$/,``).split(`/`).slice(-1)[0]??``}}catch{}l&&o.push({docName:l,timestamp:i,size:u,sha:r,label:a.replace(/^checkpoint:\s*/,``),incomingDiskSha:c.metadata.incomingDiskSha})}return o}async function Ap(e,t,n,r){if(r.length===0)return null;let i=bp(e),a=V(e.gitDir,`index-park-${t.replace(/\//g,`-`)}`),o=`refs/wip/${t}/human-${n}`,s=V(e.gitDir,`tmp-park-blob`);try{for(let t of r){z(s,t.markdown,`utf-8`);let n=(await i.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:a}).raw(`hash-object`,`-w`,s)).trim();await i.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:a}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${n},${t.docName}`),z(s,t.diskSnapshot,`utf-8`);let r=(await i.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:a}).raw(`hash-object`,`-w`,s)).trim();await i.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:a}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${r},.park-base/${t.docName}`)}let t=(await i.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:a}).raw(`write-tree`)).trim(),n=null;try{n=(await i.raw(`rev-parse`,o)).trim()}catch{}let c=[`commit-tree`,t,`-m`,`park: branch context at ${new Date().toISOString()}`];n&&c.push(`-p`,n);let l=(await i.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(...c)).trim();return await i.raw(`update-ref`,o,l),l}finally{try{me(a)}catch{}try{me(s)}catch{}}}async function jp(e,t,n,r){let i=bp(e),a=`refs/wip/${t}/human-${n}`,o;try{o=(await i.raw(`rev-parse`,a)).trim()}catch{return null}try{return(await i.raw(`log`,`-1`,`--format=%s`,o)).trim().startsWith(`park:`)?{markdown:(await i.raw(`show`,`${o}:${r}`)).trim(),diskSnapshot:(await i.raw(`show`,`${o}:.park-base/${r}`)).trim()}:null}catch(e){throw console.error(`[shadow] Failed to read parked state for ${r} from ${a}:`,e),e}}async function Mp(e,t,n,r=`main`){let i=bp(e),a=t||`.`,o=V(e.gitDir,`index-checkpoint`);try{await i.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:o}).raw(`add`,a);let t=(await i.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`write-tree`)).trim(),s=[];for(let e of[...n,{id:`upstream`}])try{let t=(await i.raw(`rev-parse`,`refs/wip/${r}/${e.id}`)).trim();s.push(t)}catch{}let c=[...new Set(s)];if(c.length===0)try{let e=(await i.raw(`for-each-ref`,`--sort=-creatordate`,`--format=%(objectname)`,`refs/checkpoints/${r}/`)).trim().split(`
48
+ `).filter(Boolean);e[0]&&c.push(e[0])}catch{}let l=[`commit-tree`,t,`-m`,`checkpoint: Checkpoint version`];for(let e of c)l.push(`-p`,e);let u=(await i.env({GIT_DIR:e.gitDir,GIT_AUTHOR_NAME:`openknowledge`,GIT_AUTHOR_EMAIL:`noreply@openknowledge.local`,GIT_COMMITTER_NAME:`openknowledge`,GIT_COMMITTER_EMAIL:`noreply@openknowledge.local`}).raw(...l)).trim(),d=`refs/checkpoints/${r}/${u}`;await i.raw(`update-ref`,d,u);for(let e of n)try{await i.raw(`update-ref`,`-d`,`refs/wip/${r}/${e.id}`)}catch{}try{await i.raw(`update-ref`,`-d`,`refs/wip/${r}/upstream`)}catch{}return{checkpointRef:d}}finally{try{me(o)}catch{}}}const Np=Pc(`persistence`);function Pp(e,t){if(e.includes(`\0`))throw Error(`Invalid document name: ${e}`);let n=V(t,`${e}${Mf(e)}`);if(!n.startsWith(`${t}/`))throw Error(`Invalid document name: ${e}`);return n}function Fp(e,t){return e===t||e.startsWith(t+Te)}const Ip=new Map;let Lp=`main`;function Rp(e){Lp=e,Ip.has(e)||Ip.set(e,new Map)}function zp(){return Lp}function Bp(e){return Ip.get(Lp)?.get(e)}function Vp(e,t){Ip.has(Lp)||Ip.set(Lp,new Map),Ip.get(Lp)?.set(e,t)}function Hp(e){Ip.get(Lp)?.delete(e)}let Up=!1;function Wp(e){Up=e}function Gp(){return Up}function Kp(e){let t=e?.contentDir??process.cwd(),n;try{n=fe(t)}catch{n=t}let r=e?.projectDir??process.cwd(),i=e?.shadowRef,a=e?.contentRoot??(B(r,n)||`content`),o=e?.backlinkIndex,s=new Map,c=e?.gitEnabled??!0,l=e?.commitDebounceMs??15e3,d=e?.wipRef??`refs/wip/main`,f=e?.getCurrentBranch,p={id:`server`,name:`openknowledge-server`,email:`noreply@openknowledge.local`},m=null,h=0,g=null,_=!1;async function v(){let e=i?.current;if(e){let t=ef(),n=nf(t),r=`WIP auto-save ${new Date().toISOString()}${n}`,i=f?.()??`main`;try{let t=await Cp(e,p,a,r,i);h=0,Np.info({sha:t.slice(0,8),writer:p.id},`[persistence] Shadow WIP commit: ${t.slice(0,8)} on refs/wip/${p.id}`)}catch(e){tf(t),h++,Hc(),Np.error({err:e,attempt:h},`[persistence] Shadow commit failed (attempt ${h})`),h>=3&&Np.error({attempt:h},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}return}let t=bp({gitDir:V(r,`.git`),workTree:r}),n=V(r,`.git/index-wip`),o={GIT_INDEX_FILE:n};try{try{let e=(await t.raw(`rev-parse`,`HEAD^{tree}`)).trim();await t.env(o).raw(`read-tree`,e)}catch(e){let t=e instanceof Error?e.message:String(e);t.includes(`unknown revision`)||t.includes(`bad revision`)?Np.info({},`[persistence] Empty repo — starting with empty index`):Np.error({err:e},`[persistence] Failed to read HEAD tree, falling back to empty index`)}await t.env(o).raw(`add`,a);let e=(await t.env(o).raw(`write-tree`)).trim(),n=null;try{n=(await t.raw(`rev-parse`,d)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw e}let r=[`commit-tree`,e,`-m`,`WIP auto-save ${new Date().toISOString()}`];n&&r.push(`-p`,n);let i=(await t.raw(...r)).trim();await t.raw(`update-ref`,d,i),h=0,Np.info({sha:i.slice(0,8),wipRef:d},`[persistence] Git commit: ${i.slice(0,8)} on ${d}`)}catch(e){h++,Hc(),Np.error({err:e,attempt:h},`[persistence] Git commit failed (attempt ${h})`),h>=3&&Np.error({attempt:h},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}finally{try{ge(n)}catch{}}}function y(){c&&(Gp()||(m&&clearTimeout(m),m=setTimeout(()=>{if(m=null,g){_=!0;return}g=v().finally(()=>{g=null,_&&(_=!1,y())})},l)))}async function b(){m&&(clearTimeout(m),m=null,g||=v().finally(()=>{g=null,_&&(_=!1,y())})),g&&await g}let x={async onLoadDocument({document:e,documentName:t,context:r}){if(q(t))return;Np.info({documentName:t,connections:e.getConnectionsCount?.()??`?`},`[persistence] onLoadDocument called for ${t} (connections: ${e.getConnectionsCount?.()??`?`})`);let i=Pp(t,n);if(!L(i))return;try{let e=fe(i);if(!Fp(e,n)){console.warn(`[persistence] symlink-escape on load: ${i} → ${e}, refusing`);return}}catch(e){if(e.code===`ELOOP`){console.warn(`[persistence] Symlink cycle on load: ${i}, refusing`);return}}let{frontmatter:a,body:o}=A(R(i,`utf-8`));a&&(s.set(t,a),e.getMap(`metadata`).set(`frontmatter`,a));let c=nl.parseWithFallback(o),l=e.getXmlFragment(`default`);Np.info({documentName:t,fragmentLength:l.length},`[persistence] onLoadDocument ${t}: fragment.length=${l.length} before update`),l.length===0?(ds(e,l,rl.nodeFromJSON(c),{mapping:new Map,isOMark:new Map}),Np.info({filePath:i,children:l.length},`[persistence] Loaded ${i} into Y.Doc (${l.length} children)`),l.observeDeep(()=>{Np.info({documentName:t,fragmentLength:l.length},`[persistence] MUTATION on ${t}: fragment.length=${l.length}`)})):Np.info({documentName:t,children:l.length},`[persistence] Skipped load for ${t} — fragment already has ${l.length} children`),Vp(t,u(a,nl.serialize(ms(l,rl).toJSON())))},async onStoreDocument({document:e,documentName:t}){if(q(t)||Gp())return;let r=ms(e.getXmlFragment(`default`),rl).toJSON(),i=nl.serialize(r),a=e.getMap(`metadata`).get(`frontmatter`),c=u(typeof a==`string`?a:s.get(t)||``,i),l=Bp(t);if(l!==void 0&&c===l)return;l&&c.length>l.length*1.5&&(Np.warn({documentName:t,markdownLength:c.length,baseLength:l.length},`[persistence] WARNING: serialized content is ${c.length} bytes vs base ${l.length} bytes for ${t} — possible duplication`),Np.warn({documentName:t,children:e.getXmlFragment(`default`).length},`[persistence] Fragment children: ${e.getXmlFragment(`default`).length}`));let d=Pp(t,n);await Fe(xe(d),{recursive:!0});let f;try{f=await Le(d)}catch(e){let n=e.code;if(n===`ENOENT`){let e=!1;try{e=ce(d).isSymbolicLink()}catch(e){e.code!==`ENOENT`&&Np.warn({err:e,path:d},`[persistence] lstat failed during broken-symlink check`)}e&&console.warn(`[persistence] broken-symlink fallback`,{docName:t,reason:`broken-symlink`}),f=d}else if(n===`ELOOP`)throw console.error(`[persistence] Symlink cycle at ${d}`),Error(`Symlink cycle detected at ${d}`);else throw e}if(!Fp(f,n)){let e=`symlink-escape: ${d} resolves to ${f} outside ${n}`;throw console.error(`[persistence] ${e}`,{docName:t,originalPath:d,canonical:f,contentDir:n}),Error(e)}let p=`${f}.tmp.${crypto.randomUUID()}`;try{await ze(p,c,`utf-8`),await Re(p,f),nm(f,im(c)),qc()}catch(e){try{ge(p)}catch{}throw Np.error({err:e,documentName:t},`[persistence] Failed to save ${t}`),e}Np.info({filePath:f,bytes:c.length},`[persistence] Wrote ${f} (${c.length} bytes)`),Vp(t,c),o&&(o.updateDocumentFromMarkdown(t,c),o.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache for ${t}:`,e)})),y()}};async function S(){g&&await g}return{extension:x,flushPendingGitCommit:b,waitForPendingCommits:S}}const qp=/^(<{7} |={7}$|>{7} |\|{7} )/m;function Jp(e){return qp.test(e)}function Yp(e){let t=e.replace(/\n+$/,``);if(!t)return[];let n=t.split(`
52
49
  `),r=[],i=[],a=null;for(let e of n){let t=e.match(/^(`{3,}|~{3,})/);if(t){let e=t[1][0];a?e===a&&(a=null):a=e}a===null&&e.trim()===``&&i.length>0?(r.push(i.join(`
53
50
  `).trim()),i=[]):i.push(e)}if(i.length>0){let e=i.join(`
54
- `).trim();e&&r.push(e)}return r}function Jp(e){if(q(e.docName))return{kind:`noop`};let{base:t,ours:n,theirs:r}=e;return Kp(r)?{kind:`refused`,reason:`conflict-markers`}:r===t?{kind:`noop`}:n===t?{kind:`clean`,newContent:r}:Yp(qp(t),qp(n),qp(r))}function Yp(e,t,n){let r=Xp(e,t),i=Xp(e,n),a=[],o=[];for(let t=0;t<e.length;t++){let n=e[t],s=r.get(t),c=i.get(t),l=s?.insertsBefore??[],u=c?.insertsBefore??[];a.push(...l,...u);let d=s?.action??`keep`,f=c?.action??`keep`;if(d===`keep`&&f===`keep`)a.push(n);else if(d===`keep`&&f!==`keep`)f===`modify`&&c?.newContent!==void 0&&a.push(c.newContent);else if(d!==`keep`&&f===`keep`)d===`modify`&&s?.newContent!==void 0&&a.push(s.newContent);else{let e=d===`modify`?s?.newContent:null,r=f===`modify`?c?.newContent:null;e===r||o.push({blockIndex:t,base:n,ours:e??``,theirs:r??``}),e!=null&&a.push(e)}}let s=r.get(e.length),c=i.get(e.length);s?.insertsBefore&&a.push(...s.insertsBefore),c?.insertsBefore&&a.push(...c.insertsBefore);let l=a.length>0?`${a.join(`
51
+ `).trim();e&&r.push(e)}return r}function Xp(e){if(q(e.docName))return{kind:`noop`};let{base:t,ours:n,theirs:r}=e;return Jp(r)?{kind:`refused`,reason:`conflict-markers`}:r===t?{kind:`noop`}:n===t?{kind:`clean`,newContent:r}:Zp(Yp(t),Yp(n),Yp(r))}function Zp(e,t,n){let r=Qp(e,t),i=Qp(e,n),a=[],o=[];for(let t=0;t<e.length;t++){let n=e[t],s=r.get(t),c=i.get(t),l=s?.insertsBefore??[],u=c?.insertsBefore??[];a.push(...l,...u);let d=s?.action??`keep`,f=c?.action??`keep`;if(d===`keep`&&f===`keep`)a.push(n);else if(d===`keep`&&f!==`keep`)f===`modify`&&c?.newContent!==void 0&&a.push(c.newContent);else if(d!==`keep`&&f===`keep`)d===`modify`&&s?.newContent!==void 0&&a.push(s.newContent);else{let e=d===`modify`?s?.newContent:null,r=f===`modify`?c?.newContent:null;e===r||o.push({blockIndex:t,base:n,ours:e??``,theirs:r??``}),e!=null&&a.push(e)}}let s=r.get(e.length),c=i.get(e.length);s?.insertsBefore&&a.push(...s.insertsBefore),c?.insertsBefore&&a.push(...c.insertsBefore);let l=a.length>0?`${a.join(`
55
52
 
56
- `)}\n`:``;return o.length>0?{kind:`conflicts`,newContent:l,conflicts:o}:{kind:`merged`,newContent:l,mergedBlocks:a.length}}function Xp(e,t){let n=new Map,r=Zp(e,t);for(let t=0;t<=e.length;t++)n.set(t,{action:`keep`,insertsBefore:[]});let i=new Set,a=new Set;for(let[e,t]of r)i.add(e),a.add(t);let o=-1;for(let s=0;s<e.length;s++)if(i.has(s)){let e=r.find(e=>e[0]===s)?.[1]??-1,i=[];for(let n=o+1;n<e;n++)a.has(n)||i.push(t[n]);let c=n.get(s);c&&(c.insertsBefore=i),o=e}else{let e=r.find(e=>e[0]>s),i=e?e[1]:t.length,c=[];for(let e=o+1;e<i;e++)a.has(e)||c.push(e);if(c.length>0){let e=c[0];a.add(e);let r=n.get(s);r&&(r.action=`modify`,r.newContent=t[e])}else{let e=n.get(s);e&&(e.action=`delete`)}}let s=[];for(let e=o+1;e<t.length;e++)a.has(e)||s.push(t[e]);let c=n.get(e.length);return c&&(c.insertsBefore=s),n}function Zp(e,t){let n=e.length,r=t.length,i=Array.from({length:n+1},()=>Array(r+1).fill(0));for(let a=1;a<=n;a++)for(let n=1;n<=r;n++)e[a-1]===t[n-1]?i[a][n]=i[a-1][n-1]+1:i[a][n]=Math.max(i[a-1][n],i[a][n-1]);let a=[],o=n,s=r;for(;o>0&&s>0;)e[o-1]===t[s-1]?(a.push([o-1,s-1]),o--,s--):i[o-1][s]>=i[o][s-1]?o--:s--;return a.reverse()}const Qp=new Map,$p=1e4;function em(e,t){let n=Qp.get(e)??[];n.push({hash:t,timestamp:Date.now()}),Qp.set(e,n)}function tm(){let e=Date.now();for(let[t,n]of Qp){let r=n.filter(t=>e-t.timestamp<=$p);r.length===0?Qp.delete(t):r.length!==n.length&&Qp.set(t,r)}}function nm(e){return Oe(`sha256`).update(e).digest(`hex`)}function rm(e,t){return Ef(B(t,e))}function im(e){let t=e.toLowerCase();return t.endsWith(`.mdx`)?`.mdx`:t.endsWith(`.md`)?`.md`:null}const am=new Map;function om(e,t){am.set(e,t)}function sm(e){let t=am.get(e);return am.delete(e),t}async function cm(e,t,n,r){let i=[],a=[],o=[];for(let r of e)if(Tf(r.path)){if(n){let e=B(t,r.path);if(n.isExcluded(e))continue}switch(r.type){case`delete`:i.push(r);break;case`create`:am.has(r.path)?o.push(r):a.push(r);break;case`update`:o.push(r);break}}let s=new Map,c=new Map;for(let e of a)try{s.set(e.path,await Fe(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}for(let e of o)try{c.set(e.path,await Fe(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}function l(e){let n=rm(e,t);if(!r)return n;let i=null;try{i=ce(e)}catch(t){return t.code!==`ENOENT`&&console.warn(`[file-watcher] resolveDocName lstat failed for ${e}:`,t),r.has(n)&&r.delete(n),n}if(!i.isSymbolicLink())return r.has(n)&&r.delete(n),n;let a;try{a=fe(e)}catch(t){let i=t.code;return i!==`ENOENT`&&i!==`ELOOP`&&console.warn(`[file-watcher] resolveDocName realpath failed for ${e}:`,t),r.delete(n),n}if(!Np(a,t))return r.delete(n),n;let o=rm(a,t);return o===n?n:(r.set(n,o),o)}let u=[],d=new Set,f=new Set;for(let e of i){let t=sm(e.path);if(t)for(let n of a){if(d.has(n.path))continue;let r=s.get(n.path);if(!r)continue;let i=nm(r);if(i===t){d.add(n.path),f.add(e.path),om(n.path,i),u.push({kind:`rename`,oldPath:e.path,newPath:n.path,oldDocName:l(e.path),newDocName:l(n.path),content:r});break}}}for(let e of i)f.has(e.path)||(sm(e.path),u.push({kind:`delete`,path:e.path,docName:l(e.path)}));for(let e of a){if(d.has(e.path))continue;let t=s.get(e.path);if(!t)continue;let n=nm(t);om(e.path,n),Kp(t)?u.push({kind:`conflict`,path:e.path,docName:l(e.path),content:t}):u.push({kind:`create`,path:e.path,docName:l(e.path),content:t})}for(let e of o){let t=c.get(e.path);if(!t)continue;let n=nm(t);om(e.path,n),Kp(t)?u.push({kind:`conflict`,path:e.path,docName:l(e.path),content:t}):u.push({kind:`update`,path:e.path,docName:l(e.path),content:t})}return u}function lm(e,t){let n=Qp.get(e);if(!n)return!1;let r=n.findIndex(e=>e.hash===t);return r<0?!1:(n.splice(r,1),n.length===0&&Qp.delete(e),!0)}function um(e,t,n,r,i,a){let o=a??new Set;try{let a=de(e,{withFileTypes:!0});for(let s of a){let a=Ce(e,s.name),c;try{c=ce(a)}catch(e){e.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to lstat ${a}, skipping:`,e);continue}if(c.isSymbolicLink()){let e;try{e=fe(a)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?console.warn(`[file-watcher] Broken/cyclic symlink at ${a}, skipping`):console.warn(`[file-watcher] Failed to resolve symlink ${a}:`,e);continue}if(!Np(e,t)){console.warn(`[file-watcher] Symlink escape: ${a} → ${e}, skipping`);continue}try{let c=he(e);if(o.has(c.ino)){if(c.isFile()&&Tf(s.name)){let n=rm(a,t),o=rm(e,t);i.set(n,o);let s=r.get(o);s&&!s.aliases.includes(n)&&s.aliases.push(n)}continue}if(o.add(c.ino),c.isDirectory()){if(n){let r=B(t,e);if(n.isDirExcluded(r))continue}um(e,t,n,r,i,o)}else if(c.isFile()&&Tf(s.name)){if(n){let r=B(t,e);if(n.isExcluded(r))continue}let o=rm(a,t),s=rm(e,t);i.set(o,s);try{let t=nm(R(e,`utf-8`));am.set(e,t);let n=im(e);if(n){let e=kf(s,n);if(e.shadowed&&(console.warn(`[file-watcher] docName "${s}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}r.set(s,{size:c.size,modified:c.mtime.toISOString(),canonicalPath:e,inode:c.ino,aliases:[o]})}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${e}:`,t)}}}catch(t){console.warn(`[file-watcher] Failed to stat symlink target ${e}:`,t)}}else if(c.isDirectory()){if(n){let e=B(t,a);if(n.isDirExcluded(e))continue}um(a,t,n,r,i,o)}else if(c.isFile()&&Tf(s.name)){if(o.has(c.ino))continue;if(o.add(c.ino),n){let e=B(t,a);if(n.isExcluded(e))continue}try{let e=R(a,`utf-8`);am.set(a,nm(e));let n=rm(a,t),i=im(a);if(i){let e=kf(n,i);if(e.shadowed&&(console.warn(`[file-watcher] docName "${n}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}r.set(n,{size:c.size,modified:c.mtime.toISOString(),canonicalPath:a,inode:c.ino,aliases:[]})}catch(e){let t=e.code;t===`EACCES`?console.warn(`[file-watcher] Permission denied reading ${a}, file excluded from index`):t!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${a}:`,e)}}}}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read directory ${e}:`,t)}}function dm(e,t){if(!q(e.kind===`rename`?e.newDocName:e.docName))switch(e.kind){case`create`:case`update`:case`conflict`:{let n=e.docName,r=t.get(n),i=im(e.path);i&&kf(n,i),t.set(n,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:r?.canonicalPath??e.path,inode:r?.inode??0,aliases:r?.aliases??[]});break}case`delete`:if(t.has(e.docName))t.delete(e.docName),jf(e.docName);else for(let[,n]of t){let t=n.aliases.indexOf(e.docName);if(t!==-1){n.aliases.splice(t,1);break}}break;case`rename`:{let n=t.get(e.oldDocName);t.delete(e.oldDocName),jf(e.oldDocName);let r=im(e.newPath);r&&kf(e.newDocName,r),t.set(e.newDocName,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:n?.canonicalPath??e.newPath,inode:n?.inode??0,aliases:n?.aliases??[]});break}}}async function fm(e,t,n,r,i,a){let o=e.filter(e=>Tf(e.path));if(o.length===0)return;let s=await cm(o,t,n,a);for(let e of s){let t=!1;if(e.kind!==`delete`&&e.kind!==`rename`){let n=nm(e.content),r=e.path;try{r=fe(e.path)}catch(t){let n=t.code;n!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.path} (${n})`)}t=lm(r,n)}else if(e.kind===`rename`){let n=nm(e.content),r=e.newPath;try{r=fe(e.newPath)}catch(t){let n=t.code;n!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.newPath} (${n})`)}t=lm(r,n)}if(dm(e,r),n)switch(e.kind){case`create`:n.incrementMdDir(xe(e.docName));break;case`delete`:n.decrementMdDir(xe(e.docName));break;case`rename`:n.decrementMdDir(xe(e.oldDocName)),n.incrementMdDir(xe(e.newDocName));break}if(t){console.log(`[file-watcher] Skipped self-write: ${e.kind} ${e.kind===`rename`?e.newPath:e.path}`);continue}console.log(`[file-watcher] Dispatching: ${e.kind} ${e.kind===`rename`?e.newPath:e.path}`),await i(e)}}async function pm(e,t,n,r,i){let a;try{a=await import(`@parcel/watcher`)}catch(e){return console.warn(`[file-watcher] @parcel/watcher import failed:`,e instanceof Error?e.message:e),null}try{let o=t?{ignore:t.getWatcherIgnoreGlobs()}:void 0;return await a.subscribe(e,async(a,o)=>{if(a){console.error(`[file-watcher]`,a);return}try{await fm(o.map(e=>({type:e.type,path:e.path})),e,t,n,r,i)}catch(e){console.error(`[file-watcher] parcel batch error:`,e)}},o)}catch(e){return console.warn(`[file-watcher] @parcel/watcher subscribe failed, falling back to chokidar:`,e),null}}async function mm(e,t,n,r,i){let{watch:a}=await import(`./chokidar-BlUsUYh_.mjs`);console.warn(`[file-watcher] @parcel/watcher unavailable, using chokidar fallback`);let o=a(e,{ignoreInitial:!0,ignored:t?(n,r)=>{let i=B(e,n);return i===``||i===`.`?!1:r?.isDirectory()?t.isDirExcluded(i):t.isExcluded(i)}:void 0});o.on(`error`,e=>console.error(`[file-watcher] chokidar error:`,e));let s=[],c=null;function l(a,o){s.push({type:a,path:o}),c||=setTimeout(()=>{let a=s;s=[],c=null,fm(a,e,t,n,r,i).catch(e=>console.error(`[file-watcher] chokidar batch error:`,e))},50)}return o.on(`add`,e=>l(`create`,e)),o.on(`change`,e=>l(`update`,e)),o.on(`unlink`,e=>l(`delete`,e)),{unsubscribe:()=>(c&&(clearTimeout(c),c=null,s=[]),o.close())}}async function hm(e,t,n){let r;try{r=fe(e)}catch{r=e}let i=new Map,a=new Map;um(r,r,n,i,a);let o=setInterval(tm,$p),s,c;try{let e=await pm(r,n,i,t,a);e?(s=e,c=`parcel`):(s=await mm(r,n,i,t,a),c=`chokidar`)}catch(e){throw clearInterval(o),e}let l=s.unsubscribe.bind(s);return console.log(`[file-watcher] Watching ${r} for external .md changes (backend: ${c})`),{async unsubscribe(){return clearInterval(o),l()},getFileIndex(){return i},getAliasMap(){return a}}}const gm=(e,t,n)=>{let r=Me(`git`,[`config`,n===`local`?`--local`:`--global`,t],{cwd:e,encoding:`utf-8`,timeout:5e3});return r.status!==0||!r.stdout?null:r.stdout.trim()||null};async function _m(e,t,n,r=gm){let i=r(e,`user.name`,`local`),a=r(e,`user.email`,`local`);if(i&&a)return{name:i,email:a};let o=r(e,`user.name`,`global`),s=r(e,`user.email`,`global`);if(o&&s)return{name:o,email:s};if(t&&n){let e=await t.get(n);if(e){let t=e.name??e.login,n=e.email??`${e.login}@users.noreply.github.com`;if(t)return{name:t,email:n}}}return null}function vm(e,t,n){let r=(t,n)=>{let r=Me(`git`,[`config`,`--local`,t,n],{cwd:e,encoding:`utf-8`,timeout:5e3});if(r.status!==0){let e=r.stderr?.trim()??``;throw Error(`git config --local ${t} failed: ${e}`)}};r(`user.name`,t),r(`user.email`,n)}const ym=[/^https?:\/\//i,/^ssh:\/\//i,/^git:\/\//i,/^git@[^:]+:/],bm=[/^file:\/\//i,/^javascript:/i,/^ext::/i,/^data:/i,/^vbscript:/i];function xm(e){return!e||typeof e!=`string`||bm.some(t=>t.test(e))?!1:ym.some(t=>t.test(e))}function Sm(e){return e===`~`?ve():e.startsWith(`~/`)?Ce(ve(),e.slice(2)):e}function Cm(e){if(!e||typeof e!=`string`||e.includes(`\0`))return!1;let t=ve(),n=V(Sm(e));return n===t||n.startsWith(`${t}/`)}function wm(e){let t=e.socket.remoteAddress;return t===`127.0.0.1`||t===`::1`||t===`::ffff:127.0.0.1`}function Tm(e){let t=e.headers.origin;if(!t)return!0;try{let{hostname:e}=new URL(t);return e===`127.0.0.1`||e===`localhost`||e===`[::1]`||e===`::1`}catch{return!1}}function Em(e,t,n){return wm(e)?Tm(e)?!0:(n(t,403,{ok:!1,error:`Forbidden: invalid origin for local-op endpoint`}),!1):(n(t,403,{ok:!1,error:`Forbidden: local-op endpoints require loopback connection`}),!1)}function Dm(){let e=new Set;return{tryAcquire(t){return e.has(t)?!1:(e.add(t),!0)},release(t){e.delete(t)}}}function Om(e){return e?!!(e===`::1`||e.startsWith(`::ffff:127.`)||e.startsWith(`127.`)):!1}function km(e){if(!e)return!1;if(e.startsWith(`[`)){let t=e.indexOf(`]`);if(t<0)return!1;let n=e.slice(1,t),r=e.slice(t+1);return r!==``&&!/^:\d+$/.test(r)?!1:n===`::1`}let t=e.lastIndexOf(`:`),n=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):null;return r!==null&&!/^\d+$/.test(r)?!1:!!(n===`localhost`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n))}function Am(e){return V(e,`.open-knowledge`)}function jm(e){return V(Am(e),`managed-rename.json`)}function Mm(e){return{version:1,sourceDocName:e.sourceDocName,destinationDocName:e.destinationDocName,createdAt:e.createdAt??new Date().toISOString(),snapshots:e.snapshots}}function Nm(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.docName==`string`&&typeof t.content==`string`}function Pm(e){if(!e||typeof e!=`object`)throw Error(`Managed rename journal must be an object`);let t=e;if(t.version!==1)throw Error(`Unsupported managed rename journal version: ${String(t.version)}`);if(typeof t.sourceDocName!=`string`||t.sourceDocName.length===0)throw Error(`Managed rename journal is missing sourceDocName`);if(typeof t.destinationDocName!=`string`||t.destinationDocName.length===0)throw Error(`Managed rename journal is missing destinationDocName`);if(typeof t.createdAt!=`string`||t.createdAt.length===0)throw Error(`Managed rename journal is missing createdAt`);if(!Array.isArray(t.snapshots)||t.snapshots.length===0)throw Error(`Managed rename journal is missing snapshots`);if(!t.snapshots.every(Nm))throw Error(`Managed rename journal has invalid snapshots`);if(!t.snapshots.some(e=>e.docName===t.sourceDocName))throw Error(`Managed rename journal must include the source document snapshot`);return{version:t.version,sourceDocName:t.sourceDocName,destinationDocName:t.destinationDocName,createdAt:t.createdAt,snapshots:t.snapshots}}function Fm(e){let t=jm(e);if(!L(t))return null;let n=R(t,`utf-8`);try{return Pm(JSON.parse(n))}catch(e){throw Error(`Managed rename journal at ${t} is corrupt: ${e instanceof Error?e.message:String(e)}`)}}function Im(e,t){let n=jm(e);le(xe(n),{recursive:!0});let r=`${n}.tmp`;z(r,JSON.stringify(t,null,2),`utf-8`),pe(r,n)}function Lm(e){me(jm(e),{force:!0})}async function Rm(e,t,n){Im(e,t);let r=await n();return Lm(e),r}function zm(e){let t=Fm(e);if(!t)return{recovered:!1,journal:null,restoredDocNames:[]};let n=new Set,r=[];for(let i of t.snapshots)try{let t=Mp(i.docName,e);le(xe(t),{recursive:!0}),z(t,i.content,`utf-8`),n.add(i.docName)}catch(e){r.push(i.docName),console.warn(`[managed-rename] Failed to restore ${i.docName}:`,e)}if(r.length>0)throw console.warn(`[managed-rename] Recovery incomplete; keeping journal for retry (${r.join(`, `)})`),Error(`Managed rename recovery incomplete; failed to restore: ${r.join(`, `)}`);if(!n.has(t.destinationDocName)){let n=Mp(t.destinationDocName,e);try{me(n,{force:!0})}catch(e){throw L(n)&&console.warn(`[managed-rename] Both source and destination files exist after partial recovery for ${t.destinationDocName}`),console.warn(`[managed-rename] Recovery incomplete; failed to clean destination ${t.destinationDocName}:`,e),Error(`Managed rename recovery incomplete; failed to clean destination: ${t.destinationDocName}`)}}return Lm(e),{recovered:!0,journal:t,restoredDocNames:[...n].sort((e,t)=>e.localeCompare(t))}}function Bm(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let n=t[1],r=n[0];return r!=="`"&&r!==`~`?null:{char:r,length:n.length}}function Vm(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function Hm(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function Um(e,t){let n=0;for(;e[t+n]==="`";)n++;if(n===0)return null;let r=t+n;for(;r<e.length;){if(e[r]!=="`"){r++;continue}let t=0;for(;e[r+t]==="`";)t++;if(t===n)return{nextIndex:r+n};r+=t}return null}function Wm(e,t){let n=/^\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/.exec(e.slice(t));if(!n)return null;let r=n[1]?.trim(),i=n[2]?.trim()||null,a=n[3]?.trim()||null;return r?{target:r,alias:a,anchor:i,nextIndex:t+n[0].length}:null}function Gm(e,t){let n=/^\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!n)return null;let r=n[2]??``;return{text:n[1]??``,hrefRaw:r,href:r.startsWith(`<`)&&r.endsWith(`>`)?r.slice(1,-1):r,titleSuffix:n[3]??``,nextIndex:t+n[0].length}}function Km(e){let t=e.split(/(\r\n|\r|\n)/),n=[];for(let e=0;e<t.length;e+=2)n.push({line:t[e]??``,ending:t[e+1]??``});return n}function qm(e,t,n){let r=``,i=0,a=0,o=Hm(e);for(o>0&&(r+=e.slice(0,o),a=o);a<e.length;){if(e[a]===`\\`&&a+1<e.length){r+=e.slice(a,a+2),a+=2;continue}if(e[a]==="`"){let t=Um(e,a);if(t){r+=e.slice(a,t.nextIndex),a=t.nextIndex;continue}}if(e[a]===`[`&&e[a+1]===`[`){let o=Wm(e,a);if(o){o.target===t?(r+=`[[${n}${o.anchor?`#${o.anchor}`:``}${o.alias?`|${o.alias}`:``}]]`,i++):r+=e.slice(a,o.nextIndex),a=o.nextIndex;continue}}r+=e[a],a++}return{markdown:r,rewrites:i}}function Jm(e,t,n){let r=e.indexOf(`#`),i=r>=0?e.slice(r):``,a=r>=0?e.slice(0,r):e,o=a.indexOf(`?`),s=o>=0?a.slice(o):``,c=o>=0?a.slice(0,o):a,l=we.dirname(t),u=we.relative(l===`.`?``:l,n);return u||=we.basename(n),c.endsWith(`.md`)&&(u+=`.md`),c.startsWith(`./`)&&!u.startsWith(`./`)&&!u.startsWith(`../`)&&(u=`./${u}`),`${u}${s}${i}`}function Ym(e,t,n,r){let i=``,a=0,o=0,s=Hm(e);for(s>0&&(i+=e.slice(0,s),o=s);o<e.length;){if(e[o]===`\\`&&o+1<e.length){i+=e.slice(o,o+2),o+=2;continue}if(e[o]==="`"){let t=Um(e,o);if(t){i+=e.slice(o,t.nextIndex),o=t.nextIndex;continue}}if(e[o]===`[`&&e[o+1]===`[`){let t=Wm(e,o);if(t){i+=e.slice(o,t.nextIndex),o=t.nextIndex;continue}}if(e[o]===`[`&&e[o-1]!==`!`){let s=Gm(e,o);if(s){if(w(s.href,t)?.docName===n){let e=Jm(s.href,t,r),n=s.hrefRaw.startsWith(`<`)&&s.hrefRaw.endsWith(`>`)?`<${e}>`:e;i+=`[${s.text}](${n}${s.titleSuffix})`,a++}else i+=e.slice(o,s.nextIndex);o=s.nextIndex;continue}}i+=e[o],o++}return{markdown:i,rewrites:a}}function Xm(e,t,n){let r=null,i=0;return{markdown:Km(e).map(({line:e,ending:a})=>{if(r)return Vm(e,r)&&(r=null),`${e}${a}`;let o=Bm(e);if(o)return r=o,`${e}${a}`;let s=qm(e,t,n);return i+=s.rewrites,`${s.markdown}${a}`}).join(``),rewrites:i}}function Zm(e,t,n,r){let i=null,a=0;return{markdown:Km(e).map(({line:e,ending:o})=>{if(i)return Vm(e,i)&&(i=null),`${e}${o}`;let s=Bm(e);if(s)return i=s,`${e}${o}`;let c=Ym(e,t,n,r);return a+=c.rewrites,`${c.markdown}${o}`}).join(``),rewrites:a}}const Qm=Mc(`suggest-links`),$m=/[\p{L}\p{N}]/u,eh=/\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/y,th=/\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y,nh=/!\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y;var rh=class extends Error{constructor(e){super(`Document not found: ${e}`),this.name=`SuggestLinksTargetNotFoundError`}};function ih(e){return e.replace(/\s+/g,` `).trim()}function ah(e,t,n){if(!ih(e))return null;let r=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
53
+ `)}\n`:``;return o.length>0?{kind:`conflicts`,newContent:l,conflicts:o}:{kind:`merged`,newContent:l,mergedBlocks:a.length}}function Qp(e,t){let n=new Map,r=$p(e,t);for(let t=0;t<=e.length;t++)n.set(t,{action:`keep`,insertsBefore:[]});let i=new Set,a=new Set;for(let[e,t]of r)i.add(e),a.add(t);let o=-1;for(let s=0;s<e.length;s++)if(i.has(s)){let e=r.find(e=>e[0]===s)?.[1]??-1,i=[];for(let n=o+1;n<e;n++)a.has(n)||i.push(t[n]);let c=n.get(s);c&&(c.insertsBefore=i),o=e}else{let e=r.find(e=>e[0]>s),i=e?e[1]:t.length,c=[];for(let e=o+1;e<i;e++)a.has(e)||c.push(e);if(c.length>0){let e=c[0];a.add(e);let r=n.get(s);r&&(r.action=`modify`,r.newContent=t[e])}else{let e=n.get(s);e&&(e.action=`delete`)}}let s=[];for(let e=o+1;e<t.length;e++)a.has(e)||s.push(t[e]);let c=n.get(e.length);return c&&(c.insertsBefore=s),n}function $p(e,t){let n=e.length,r=t.length,i=Array.from({length:n+1},()=>Array(r+1).fill(0));for(let a=1;a<=n;a++)for(let n=1;n<=r;n++)e[a-1]===t[n-1]?i[a][n]=i[a-1][n-1]+1:i[a][n]=Math.max(i[a-1][n],i[a][n-1]);let a=[],o=n,s=r;for(;o>0&&s>0;)e[o-1]===t[s-1]?(a.push([o-1,s-1]),o--,s--):i[o-1][s]>=i[o][s-1]?o--:s--;return a.reverse()}const em=new Map,tm=1e4;function nm(e,t){let n=em.get(e)??[];n.push({hash:t,timestamp:Date.now()}),em.set(e,n)}function rm(){let e=Date.now();for(let[t,n]of em){let r=n.filter(t=>e-t.timestamp<=tm);r.length===0?em.delete(t):r.length!==n.length&&em.set(t,r)}}function im(e){return Oe(`sha256`).update(e).digest(`hex`)}function am(e,t){return Of(B(t,e))}function om(e){let t=e.toLowerCase();return t.endsWith(`.mdx`)?`.mdx`:t.endsWith(`.md`)?`.md`:null}const sm=new Map;function cm(e,t){sm.set(e,t)}function lm(e){let t=sm.get(e);return sm.delete(e),t}async function um(e,t,n,r){let i=[],a=[],o=[];for(let r of e)if(Df(r.path)){if(n){let e=B(t,r.path);if(n.isExcluded(e))continue}switch(r.type){case`delete`:i.push(r);break;case`create`:sm.has(r.path)?o.push(r):a.push(r);break;case`update`:o.push(r);break}}let s=new Map,c=new Map;for(let e of a)try{s.set(e.path,await Ie(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}for(let e of o)try{c.set(e.path,await Ie(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}function l(e){let n=am(e,t);if(!r)return n;let i=null;try{i=ce(e)}catch(t){return t.code!==`ENOENT`&&console.warn(`[file-watcher] resolveDocName lstat failed for ${e}:`,t),r.has(n)&&r.delete(n),n}if(!i.isSymbolicLink())return r.has(n)&&r.delete(n),n;let a;try{a=fe(e)}catch(t){let i=t.code;return i!==`ENOENT`&&i!==`ELOOP`&&console.warn(`[file-watcher] resolveDocName realpath failed for ${e}:`,t),r.delete(n),n}if(!Fp(a,t))return r.delete(n),n;let o=am(a,t);return o===n?n:(r.set(n,o),o)}let u=[],d=new Set,f=new Set;for(let e of i){let t=lm(e.path);if(t)for(let n of a){if(d.has(n.path))continue;let r=s.get(n.path);if(!r)continue;let i=im(r);if(i===t){d.add(n.path),f.add(e.path),cm(n.path,i),u.push({kind:`rename`,oldPath:e.path,newPath:n.path,oldDocName:l(e.path),newDocName:l(n.path),content:r});break}}}for(let e of i)f.has(e.path)||(lm(e.path),u.push({kind:`delete`,path:e.path,docName:l(e.path)}));for(let e of a){if(d.has(e.path))continue;let t=s.get(e.path);if(!t)continue;let n=im(t);cm(e.path,n),Jp(t)?u.push({kind:`conflict`,path:e.path,docName:l(e.path),content:t}):u.push({kind:`create`,path:e.path,docName:l(e.path),content:t})}for(let e of o){let t=c.get(e.path);if(!t)continue;let n=im(t);cm(e.path,n),Jp(t)?u.push({kind:`conflict`,path:e.path,docName:l(e.path),content:t}):u.push({kind:`update`,path:e.path,docName:l(e.path),content:t})}return u}function dm(e,t){let n=em.get(e);if(!n)return!1;let r=n.findIndex(e=>e.hash===t);return r<0?!1:(n.splice(r,1),n.length===0&&em.delete(e),!0)}function fm(e,t,n,r,i,a){let o=a??new Set;try{let a=de(e,{withFileTypes:!0});for(let s of a){let a=Ce(e,s.name),c;try{c=ce(a)}catch(e){e.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to lstat ${a}, skipping:`,e);continue}if(c.isSymbolicLink()){let e;try{e=fe(a)}catch(e){let t=e.code;t===`ENOENT`||t===`ELOOP`?console.warn(`[file-watcher] Broken/cyclic symlink at ${a}, skipping`):console.warn(`[file-watcher] Failed to resolve symlink ${a}:`,e);continue}if(!Fp(e,t)){console.warn(`[file-watcher] Symlink escape: ${a} → ${e}, skipping`);continue}try{let c=he(e);if(o.has(c.ino)){if(c.isFile()&&Df(s.name)){let n=am(a,t),o=am(e,t);i.set(n,o);let s=r.get(o);s&&!s.aliases.includes(n)&&s.aliases.push(n)}continue}if(o.add(c.ino),c.isDirectory()){if(n){let r=B(t,e);if(n.isDirExcluded(r))continue}fm(e,t,n,r,i,o)}else if(c.isFile()&&Df(s.name)){if(n){let r=B(t,e);if(n.isExcluded(r))continue}let o=am(a,t),s=am(e,t);i.set(o,s);try{let t=im(R(e,`utf-8`));sm.set(e,t);let n=om(e);if(n){let e=jf(s,n);if(e.shadowed&&(console.warn(`[file-watcher] docName "${s}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}r.set(s,{size:c.size,modified:c.mtime.toISOString(),canonicalPath:e,inode:c.ino,aliases:[o]})}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${e}:`,t)}}}catch(t){console.warn(`[file-watcher] Failed to stat symlink target ${e}:`,t)}}else if(c.isDirectory()){if(n){let e=B(t,a);if(n.isDirExcluded(e))continue}fm(a,t,n,r,i,o)}else if(c.isFile()&&Df(s.name)){if(o.has(c.ino))continue;if(o.add(c.ino),n){let e=B(t,a);if(n.isExcluded(e))continue}try{let e=R(a,`utf-8`);sm.set(a,im(e));let n=am(a,t),i=om(a);if(i){let e=jf(n,i);if(e.shadowed&&(console.warn(`[file-watcher] docName "${n}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}r.set(n,{size:c.size,modified:c.mtime.toISOString(),canonicalPath:a,inode:c.ino,aliases:[]})}catch(e){let t=e.code;t===`EACCES`?console.warn(`[file-watcher] Permission denied reading ${a}, file excluded from index`):t!==`ENOENT`&&console.warn(`[file-watcher] Failed to seed hash for ${a}:`,e)}}}}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read directory ${e}:`,t)}}function pm(e,t){if(!q(e.kind===`rename`?e.newDocName:e.docName))switch(e.kind){case`create`:case`update`:case`conflict`:{let n=e.docName,r=t.get(n),i=om(e.path);i&&jf(n,i),t.set(n,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:r?.canonicalPath??e.path,inode:r?.inode??0,aliases:r?.aliases??[]});break}case`delete`:if(t.has(e.docName))t.delete(e.docName),Nf(e.docName);else for(let[,n]of t){let t=n.aliases.indexOf(e.docName);if(t!==-1){n.aliases.splice(t,1);break}}break;case`rename`:{let n=t.get(e.oldDocName);t.delete(e.oldDocName),Nf(e.oldDocName);let r=om(e.newPath);r&&jf(e.newDocName,r),t.set(e.newDocName,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:n?.canonicalPath??e.newPath,inode:n?.inode??0,aliases:n?.aliases??[]});break}}}async function mm(e,t,n,r,i,a){let o=e.filter(e=>Df(e.path));if(o.length===0)return;let s=await um(o,t,n,a);for(let e of s){let t=!1;if(e.kind!==`delete`&&e.kind!==`rename`){let n=im(e.content),r=e.path;try{r=fe(e.path)}catch(t){let n=t.code;n!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.path} (${n})`)}t=dm(r,n)}else if(e.kind===`rename`){let n=im(e.content),r=e.newPath;try{r=fe(e.newPath)}catch(t){let n=t.code;n!==`ENOENT`&&console.warn(`[file-watcher] realpathSync failed for self-write check on ${e.newPath} (${n})`)}t=dm(r,n)}if(pm(e,r),n)switch(e.kind){case`create`:n.incrementMdDir(xe(e.docName));break;case`delete`:n.decrementMdDir(xe(e.docName));break;case`rename`:n.decrementMdDir(xe(e.oldDocName)),n.incrementMdDir(xe(e.newDocName));break}if(t){console.log(`[file-watcher] Skipped self-write: ${e.kind} ${e.kind===`rename`?e.newPath:e.path}`);continue}console.log(`[file-watcher] Dispatching: ${e.kind} ${e.kind===`rename`?e.newPath:e.path}`),await i(e)}}async function hm(e,t,n,r,i){let a;try{a=await import(`@parcel/watcher`)}catch(e){return console.warn(`[file-watcher] @parcel/watcher import failed:`,e instanceof Error?e.message:e),null}try{let o=t?{ignore:t.getWatcherIgnoreGlobs()}:void 0;return await a.subscribe(e,async(a,o)=>{if(a){console.error(`[file-watcher]`,a);return}try{await mm(o.map(e=>({type:e.type,path:e.path})),e,t,n,r,i)}catch(e){console.error(`[file-watcher] parcel batch error:`,e)}},o)}catch(e){return console.warn(`[file-watcher] @parcel/watcher subscribe failed, falling back to chokidar:`,e),null}}async function gm(e,t,n,r,i){let{watch:a}=await import(`./chokidar-BlUsUYh_.mjs`);console.warn(`[file-watcher] @parcel/watcher unavailable, using chokidar fallback`);let o=a(e,{ignoreInitial:!0,ignored:t?(n,r)=>{let i=B(e,n);return i===``||i===`.`?!1:r?.isDirectory()?t.isDirExcluded(i):t.isExcluded(i)}:void 0});o.on(`error`,e=>console.error(`[file-watcher] chokidar error:`,e));let s=[],c=null;function l(a,o){s.push({type:a,path:o}),c||=setTimeout(()=>{let a=s;s=[],c=null,mm(a,e,t,n,r,i).catch(e=>console.error(`[file-watcher] chokidar batch error:`,e))},50)}return o.on(`add`,e=>l(`create`,e)),o.on(`change`,e=>l(`update`,e)),o.on(`unlink`,e=>l(`delete`,e)),{unsubscribe:()=>(c&&(clearTimeout(c),c=null,s=[]),o.close())}}async function _m(e,t,n){let r;try{r=fe(e)}catch{r=e}let i=new Map,a=new Map;fm(r,r,n,i,a);let o=setInterval(rm,tm),s,c;try{let e=await hm(r,n,i,t,a);e?(s=e,c=`parcel`):(s=await gm(r,n,i,t,a),c=`chokidar`)}catch(e){throw clearInterval(o),e}let l=s.unsubscribe.bind(s);return console.log(`[file-watcher] Watching ${r} for external .md changes (backend: ${c})`),{async unsubscribe(){return clearInterval(o),l()},getFileIndex(){return i},getAliasMap(){return a}}}const vm=(e,t,n)=>{let r=Ne(`git`,[`config`,n===`local`?`--local`:`--global`,t],{cwd:e,encoding:`utf-8`,timeout:5e3});return r.status!==0||!r.stdout?null:r.stdout.trim()||null};async function ym(e,t,n,r=vm){let i=r(e,`user.name`,`local`),a=r(e,`user.email`,`local`);if(i&&a)return{name:i,email:a};let o=r(e,`user.name`,`global`),s=r(e,`user.email`,`global`);if(o&&s)return{name:o,email:s};if(t&&n){let e=await t.get(n);if(e){let t=e.name??e.login,n=e.email??`${e.login}@users.noreply.github.com`;if(t)return{name:t,email:n}}}return null}function bm(e,t,n){let r=(t,n)=>{let r=Ne(`git`,[`config`,`--local`,t,n],{cwd:e,encoding:`utf-8`,timeout:5e3});if(r.status!==0){let e=r.stderr?.trim()??``;throw Error(`git config --local ${t} failed: ${e}`)}};r(`user.name`,t),r(`user.email`,n)}const xm=[/^https?:\/\//i,/^ssh:\/\//i,/^git:\/\//i,/^git@[^:]+:/],Sm=[/^file:\/\//i,/^javascript:/i,/^ext::/i,/^data:/i,/^vbscript:/i];function Cm(e){return!e||typeof e!=`string`||Sm.some(t=>t.test(e))?!1:xm.some(t=>t.test(e))}function wm(e){return e===`~`?ve():e.startsWith(`~/`)?Ce(ve(),e.slice(2)):e}function Tm(e){if(!e||typeof e!=`string`||e.includes(`\0`))return!1;let t=ve(),n=V(wm(e));return n===t||n.startsWith(`${t}/`)}function Em(e){let t=e.socket.remoteAddress;return t===`127.0.0.1`||t===`::1`||t===`::ffff:127.0.0.1`}function Dm(e){let t=e.headers.origin;if(!t)return!0;try{let{hostname:e}=new URL(t);return e===`127.0.0.1`||e===`localhost`||e===`[::1]`||e===`::1`}catch{return!1}}function Om(e,t,n){return Em(e)?Dm(e)?!0:(n(t,403,{ok:!1,error:`Forbidden: invalid origin for local-op endpoint`}),!1):(n(t,403,{ok:!1,error:`Forbidden: local-op endpoints require loopback connection`}),!1)}function km(){let e=new Set;return{tryAcquire(t){return e.has(t)?!1:(e.add(t),!0)},release(t){e.delete(t)}}}function Am(e){return e?!!(e===`::1`||e.startsWith(`::ffff:127.`)||e.startsWith(`127.`)):!1}function jm(e){if(!e)return!1;if(e.startsWith(`[`)){let t=e.indexOf(`]`);if(t<0)return!1;let n=e.slice(1,t),r=e.slice(t+1);return r!==``&&!/^:\d+$/.test(r)?!1:n===`::1`}let t=e.lastIndexOf(`:`),n=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):null;return r!==null&&!/^\d+$/.test(r)?!1:!!(n===`localhost`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n))}function Mm(e){return V(e,`.open-knowledge`)}function Nm(e){return V(Mm(e),`managed-rename.json`)}function Pm(e){return{version:1,sourceDocName:e.sourceDocName,destinationDocName:e.destinationDocName,createdAt:e.createdAt??new Date().toISOString(),snapshots:e.snapshots}}function Fm(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.docName==`string`&&typeof t.content==`string`}function Im(e){if(!e||typeof e!=`object`)throw Error(`Managed rename journal must be an object`);let t=e;if(t.version!==1)throw Error(`Unsupported managed rename journal version: ${String(t.version)}`);if(typeof t.sourceDocName!=`string`||t.sourceDocName.length===0)throw Error(`Managed rename journal is missing sourceDocName`);if(typeof t.destinationDocName!=`string`||t.destinationDocName.length===0)throw Error(`Managed rename journal is missing destinationDocName`);if(typeof t.createdAt!=`string`||t.createdAt.length===0)throw Error(`Managed rename journal is missing createdAt`);if(!Array.isArray(t.snapshots)||t.snapshots.length===0)throw Error(`Managed rename journal is missing snapshots`);if(!t.snapshots.every(Fm))throw Error(`Managed rename journal has invalid snapshots`);if(!t.snapshots.some(e=>e.docName===t.sourceDocName))throw Error(`Managed rename journal must include the source document snapshot`);return{version:t.version,sourceDocName:t.sourceDocName,destinationDocName:t.destinationDocName,createdAt:t.createdAt,snapshots:t.snapshots}}function Lm(e){let t=Nm(e);if(!L(t))return null;let n=R(t,`utf-8`);try{return Im(JSON.parse(n))}catch(e){throw Error(`Managed rename journal at ${t} is corrupt: ${e instanceof Error?e.message:String(e)}`)}}function Rm(e,t){let n=Nm(e);le(xe(n),{recursive:!0});let r=`${n}.tmp`;z(r,JSON.stringify(t,null,2),`utf-8`),pe(r,n)}function zm(e){me(Nm(e),{force:!0})}async function Bm(e,t,n){Rm(e,t);let r=await n();return zm(e),r}function Vm(e){let t=Lm(e);if(!t)return{recovered:!1,journal:null,restoredDocNames:[]};let n=new Set,r=[];for(let i of t.snapshots)try{let t=Pp(i.docName,e);le(xe(t),{recursive:!0}),z(t,i.content,`utf-8`),n.add(i.docName)}catch(e){r.push(i.docName),console.warn(`[managed-rename] Failed to restore ${i.docName}:`,e)}if(r.length>0)throw console.warn(`[managed-rename] Recovery incomplete; keeping journal for retry (${r.join(`, `)})`),Error(`Managed rename recovery incomplete; failed to restore: ${r.join(`, `)}`);if(!n.has(t.destinationDocName)){let n=Pp(t.destinationDocName,e);try{me(n,{force:!0})}catch(e){throw L(n)&&console.warn(`[managed-rename] Both source and destination files exist after partial recovery for ${t.destinationDocName}`),console.warn(`[managed-rename] Recovery incomplete; failed to clean destination ${t.destinationDocName}:`,e),Error(`Managed rename recovery incomplete; failed to clean destination: ${t.destinationDocName}`)}}return zm(e),{recovered:!0,journal:t,restoredDocNames:[...n].sort((e,t)=>e.localeCompare(t))}}function Hm(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let n=t[1],r=n[0];return r!=="`"&&r!==`~`?null:{char:r,length:n.length}}function Um(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function Wm(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function Gm(e,t){let n=0;for(;e[t+n]==="`";)n++;if(n===0)return null;let r=t+n;for(;r<e.length;){if(e[r]!=="`"){r++;continue}let t=0;for(;e[r+t]==="`";)t++;if(t===n)return{nextIndex:r+n};r+=t}return null}function Km(e,t){let n=/^\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/.exec(e.slice(t));if(!n)return null;let r=n[1]?.trim(),i=n[2]?.trim()||null,a=n[3]?.trim()||null;return r?{target:r,alias:a,anchor:i,nextIndex:t+n[0].length}:null}function qm(e,t){let n=/^\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)((?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?)\)/.exec(e.slice(t));if(!n)return null;let r=n[2]??``;return{text:n[1]??``,hrefRaw:r,href:r.startsWith(`<`)&&r.endsWith(`>`)?r.slice(1,-1):r,titleSuffix:n[3]??``,nextIndex:t+n[0].length}}function Jm(e){let t=e.split(/(\r\n|\r|\n)/),n=[];for(let e=0;e<t.length;e+=2)n.push({line:t[e]??``,ending:t[e+1]??``});return n}function Ym(e,t,n){let r=``,i=0,a=0,o=Wm(e);for(o>0&&(r+=e.slice(0,o),a=o);a<e.length;){if(e[a]===`\\`&&a+1<e.length){r+=e.slice(a,a+2),a+=2;continue}if(e[a]==="`"){let t=Gm(e,a);if(t){r+=e.slice(a,t.nextIndex),a=t.nextIndex;continue}}if(e[a]===`[`&&e[a+1]===`[`){let o=Km(e,a);if(o){o.target===t?(r+=`[[${n}${o.anchor?`#${o.anchor}`:``}${o.alias?`|${o.alias}`:``}]]`,i++):r+=e.slice(a,o.nextIndex),a=o.nextIndex;continue}}r+=e[a],a++}return{markdown:r,rewrites:i}}function Xm(e,t,n){let r=e.indexOf(`#`),i=r>=0?e.slice(r):``,a=r>=0?e.slice(0,r):e,o=a.indexOf(`?`),s=o>=0?a.slice(o):``,c=o>=0?a.slice(0,o):a,l=we.dirname(t),u=we.relative(l===`.`?``:l,n);return u||=we.basename(n),c.endsWith(`.md`)&&(u+=`.md`),c.startsWith(`./`)&&!u.startsWith(`./`)&&!u.startsWith(`../`)&&(u=`./${u}`),`${u}${s}${i}`}function Zm(e,t,n,r){let i=``,a=0,o=0,s=Wm(e);for(s>0&&(i+=e.slice(0,s),o=s);o<e.length;){if(e[o]===`\\`&&o+1<e.length){i+=e.slice(o,o+2),o+=2;continue}if(e[o]==="`"){let t=Gm(e,o);if(t){i+=e.slice(o,t.nextIndex),o=t.nextIndex;continue}}if(e[o]===`[`&&e[o+1]===`[`){let t=Km(e,o);if(t){i+=e.slice(o,t.nextIndex),o=t.nextIndex;continue}}if(e[o]===`[`&&e[o-1]!==`!`){let s=qm(e,o);if(s){if(w(s.href,t)?.docName===n){let e=Xm(s.href,t,r),n=s.hrefRaw.startsWith(`<`)&&s.hrefRaw.endsWith(`>`)?`<${e}>`:e;i+=`[${s.text}](${n}${s.titleSuffix})`,a++}else i+=e.slice(o,s.nextIndex);o=s.nextIndex;continue}}i+=e[o],o++}return{markdown:i,rewrites:a}}function Qm(e,t,n){let r=null,i=0;return{markdown:Jm(e).map(({line:e,ending:a})=>{if(r)return Um(e,r)&&(r=null),`${e}${a}`;let o=Hm(e);if(o)return r=o,`${e}${a}`;let s=Ym(e,t,n);return i+=s.rewrites,`${s.markdown}${a}`}).join(``),rewrites:i}}function $m(e,t,n,r){let i=null,a=0;return{markdown:Jm(e).map(({line:e,ending:o})=>{if(i)return Um(e,i)&&(i=null),`${e}${o}`;let s=Hm(e);if(s)return i=s,`${e}${o}`;let c=Zm(e,t,n,r);return a+=c.rewrites,`${c.markdown}${o}`}).join(``),rewrites:a}}const eh=Pc(`suggest-links`),th=/[\p{L}\p{N}]/u,nh=/\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/y,rh=/\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y,ih=/!\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y;var ah=class extends Error{constructor(e){super(`Document not found: ${e}`),this.name=`SuggestLinksTargetNotFoundError`}};function oh(e){return e.replace(/\s+/g,` `).trim()}function sh(e,t,n){if(!oh(e))return null;let r=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
57
54
  `,t-1)),i=[e.indexOf(`.`,n),e.indexOf(`?`,n),e.indexOf(`!`,n),e.indexOf(`
58
- `,n)].filter(e=>e>=0),a=r>=0?r+1:Math.max(0,t-60),o=i.length>0?Math.min(...i)+1:Math.min(e.length,n+60),s=a>0?`…`:``,c=o<e.length?`…`:``,l=ih(e.slice(a,o));return l?`${s}${l}${c}`:null}function oh(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let n=t[1],r=n[0];return r!=="`"&&r!==`~`?null:{char:r,length:n.length}}function sh(e,t){let n=e.trimStart();if(e.length-n.length>3)return!1;let r=0;for(;n[r]===t.char;)r+=1;return r<t.length?!1:n.slice(r).trim().length===0}function ch(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function lh(e,t){let n=0;for(;e[t+n]==="`";)n++;if(n===0)return null;let r=t+n,i=r;for(;i<e.length;){if(e[i]!=="`"){i+=1;continue}let t=0;for(;e[i+t]==="`";)t+=1;if(t===n)return{text:e.slice(r,i),nextIndex:i+n};i+=t}return null}function uh(e,t){eh.lastIndex=t;let n=eh.exec(e);if(!n)return null;let r=n[1]??``,i=r.trim(),a=n[2]?.trim()||null,o=n[3]??null,s=o?.trim()||null;if(!i)return null;let c=s??i,l=s?o:r,u=s?n[0].lastIndexOf(o??``):2,d=l?.indexOf(c)??0;return{target:i,alias:s,anchor:a,label:c,labelStart:t+u+Math.max(d,0),nextIndex:t+n[0].length}}function dh(e){return e.startsWith(`<`)&&e.endsWith(`>`)?e.slice(1,-1):e}function fh(e,t){th.lastIndex=t;let n=th.exec(e);return n?{text:n[1]??``,href:dh(n[2]??``),nextIndex:t+n[0].length}:null}function ph(e,t){nh.lastIndex=t;let n=nh.exec(e);return n?{alt:n[1]??``,nextIndex:t+n[0].length}:null}function mh(e){return!e||!$m.test(e)}function hh(e,t,n){return mh(e[t-1])&&mh(e[n])}function gh(e){let t=[],n=new Set;for(let r of e.matchLabels){let e=r.trim();if(!e)continue;let i=e.toLocaleLowerCase();n.has(i)||(n.add(i),t.push({raw:e,lower:i,length:e.length}))}return t.sort((e,t)=>t.length===e.length?e.raw.localeCompare(t.raw):t.length-e.length)}function _h(e,t){let n=e.toLocaleLowerCase(),r=[];for(let i of t){let t=0;for(;t<=n.length-i.length;){let a=n.indexOf(i.lower,t);if(a===-1)break;let o=a+i.length;hh(e,a,o)&&r.push({start:a,end:o}),t=a+1}}r.sort((e,t)=>{if(e.start!==t.start)return e.start-t.start;let n=e.end-e.start,r=t.end-t.start;return r===n?e.end-t.end:r-n});let i=[],a=null;for(let e of r)a&&e.start<a.end||(i.push(e),a=e);return i}function vh(e,t){let n=[];for(let r=0;r<t.length;r+=1)n.push(e+r);return n}function yh(e,t){let n=e.trim();return n?n===t||h(n)===t:!1}function bh(e,t,n,r,i){let a=``,o=[],s=``,c=[];function l(){s&&(o.push({flatStart:a.length,text:s,sourceOffsets:c}),a+=s,s=``,c=[])}function u(e,t){s+=e,c.push(t)}function d(e){l(),a+=e}function f(e,t){l(),e&&(o.push({flatStart:a.length,text:e,sourceOffsets:t}),a+=e)}let p=ch(e);for(;p<e.length;){if(e[p]===`\\`&&p+1<e.length){u(e[p+1]??``,t+p+1),p+=2;continue}if(e[p]==="`"){let t=lh(e,p);if(t){d(t.text),p=t.nextIndex;continue}}if(e[p]===`!`&&e[p+1]===`[`){let t=ph(e,p);if(t){d(t.alt),p=t.nextIndex;continue}}if(e[p]===`[`&&e[p+1]===`[`){let n=uh(e,p);if(n){let e=n.label;yh(n.target,r)?d(e):f(e,vh(t+n.labelStart,e)),p=n.nextIndex;continue}}if(e[p]===`[`&&e[p-1]!==`!`){let i=fh(e,p);if(i){w(i.href,n)?.docName===r?d(i.text):f(i.text,vh(t+p+1,i.text)),p=i.nextIndex;continue}}u(e[p]??``,t+p),p+=1}l();let m=[];for(let e of o){let t=_h(e.text,i);for(let n of t){let t=e.flatStart+n.start,r=e.flatStart+n.end,i=ah(a,t,r)??e.text.slice(n.start,n.end),o=e.sourceOffsets[n.start];typeof o==`number`&&m.push({excerpt:i,offset:o})}}return m}function xh(e,t,n,r){let{frontmatter:i,body:a}=A(e),o=i.length,s=[],c=null,l=0,u=0;for(;u<=a.length;){let e=a[u];if(!(u===a.length||e===`
59
- `||e===`\r`)){u+=1;continue}let i=a.slice(l,u);if(c)sh(i,c)&&(c=null);else{let e=oh(i);e?c=e:s.push(...bh(i,o+l,t,n,r))}if(u===a.length)break;if(e===`\r`&&a[u+1]===`
60
- `){u+=2,l=u;continue}u+=1,l=u}return s}function Sh(e){let t=e.getXmlFragment(`default`),n=el.serialize(fs(t,tl).toJSON()),r=e.getMap(`metadata`).get(`frontmatter`);return u(typeof r==`string`?r:``,n)}async function Ch(e,t,n){let r=e.documents.get(t);if(r)try{return Sh(r)}catch(e){return Qm.warn({docName:t,err:e},`[suggest-links] Failed live serialization, falling back to live source text`),r.getText(`source`).toString()}return await Fe(n.canonicalPath,`utf-8`)}function wh(e){return{docName:e.docName,title:e.title,aliases:e.aliases}}async function Th(e){let{hocuspocus:t,fileIndex:n,docName:r,scanBudgetMs:i=500,now:a=()=>Date.now(),onComplete:o}=e,s=a(),c=n.get(r);if(!c)throw new rh(r);let l=vf(await Ch(t,r,c),r),u=gh(l),d=[...n.keys()].filter(e=>e!==r).sort((e,t)=>e.localeCompare(t)),f=new Map,p=!1;for(let e of d){if(a()-s>i){p=!0;break}let o=n.get(e);if(!o)continue;let c;try{c=await Ch(t,e,o)}catch(t){Qm.warn({docName:e,err:t},`[suggest-links] Failed to read source doc`);continue}let l=xh(c,e,r,u).map(t=>({source:e,excerpt:t.excerpt,offset:t.offset}));l.length>0&&f.set(e,l)}let m=[...f.entries()].sort(([e,t],[n,r])=>r.length===t.length?e===n?(t[0]?.offset??2**53-1)-(r[0]?.offset??2**53-1):e.localeCompare(n):r.length-t.length).flatMap(([,e])=>e),g=a()-s,_={durationMs:g,corpusDocCount:d.length,candidateCount:m.length,truncated:p};return Qm.info({docName:r,durationMs:g,corpusDocCount:d.length,candidateCount:m.length,truncated:p,labelCount:u.length,normalizedTarget:h(l.title)},`[suggest-links] scan completed`),o?.(_),{target:wh(l),mentions:m,truncated:p}}const Eh=`%H%x00%aI%x00%an%x00%ae%x00%s%x00%B%x1e`,Dh={entries:[],total:0,hasMore:!1};function Oh(e){return e.startsWith(`checkpoint:`)?`checkpoint`:e.startsWith(`upstream:`)?`upstream`:`wip`}function kh(e){return e.trim()?e.split(``).map(e=>{let t=e.trimStart();if(!t)return null;let[n=``,r=``,i=``,a=``,o=``,s=``]=t.split(`\0`),c=Oh(o);return{sha:n.trim(),timestamp:r,author:i,authorEmail:a,type:c,message:o,contributors:up(s),checkpoint:c===`checkpoint`?fp(s):null}}).filter(e=>e!==null&&e.sha.length===40):[]}function Ah(e){return e?Array.isArray(e)?e:e.split(`,`).map(e=>e.trim()).filter(Boolean):[]}function jh(e,t){return t.length===0?!0:t.some(t=>e.author.toLowerCase().includes(t.toLowerCase())||e.authorEmail.toLowerCase().includes(t.toLowerCase()))}async function Mh(e,t,n=`content`){if(!L(e.workTree)||!L(e.gitDir))return Dh;let r=t.branch??`main`,i=Math.max(1,t.limit??50),a=Math.max(0,t.offset??0),o=Ah(t.type),s=Ah(t.author),c=Ah(t.excludeAuthor),l=n.replace(/^\.\//,``),u=t.docName?l?`${l}/${t.docName}${Af(t.docName)}`:`${t.docName}${Af(t.docName)}`:void 0;try{let t=vp(e);if(o.length===1&&o[0]===`checkpoint`){let e=(await t.raw(`for-each-ref`,`--sort=-creatordate`,`--format=%(objectname)`,`refs/checkpoints/${r}/`)).trim().split(`
55
+ `,n)].filter(e=>e>=0),a=r>=0?r+1:Math.max(0,t-60),o=i.length>0?Math.min(...i)+1:Math.min(e.length,n+60),s=a>0?`…`:``,c=o<e.length?`…`:``,l=oh(e.slice(a,o));return l?`${s}${l}${c}`:null}function ch(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let n=t[1],r=n[0];return r!=="`"&&r!==`~`?null:{char:r,length:n.length}}function lh(e,t){let n=e.trimStart();if(e.length-n.length>3)return!1;let r=0;for(;n[r]===t.char;)r+=1;return r<t.length?!1:n.slice(r).trim().length===0}function uh(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function dh(e,t){let n=0;for(;e[t+n]==="`";)n++;if(n===0)return null;let r=t+n,i=r;for(;i<e.length;){if(e[i]!=="`"){i+=1;continue}let t=0;for(;e[i+t]==="`";)t+=1;if(t===n)return{text:e.slice(r,i),nextIndex:i+n};i+=t}return null}function fh(e,t){nh.lastIndex=t;let n=nh.exec(e);if(!n)return null;let r=n[1]??``,i=r.trim(),a=n[2]?.trim()||null,o=n[3]??null,s=o?.trim()||null;if(!i)return null;let c=s??i,l=s?o:r,u=s?n[0].lastIndexOf(o??``):2,d=l?.indexOf(c)??0;return{target:i,alias:s,anchor:a,label:c,labelStart:t+u+Math.max(d,0),nextIndex:t+n[0].length}}function ph(e){return e.startsWith(`<`)&&e.endsWith(`>`)?e.slice(1,-1):e}function mh(e,t){rh.lastIndex=t;let n=rh.exec(e);return n?{text:n[1]??``,href:ph(n[2]??``),nextIndex:t+n[0].length}:null}function hh(e,t){ih.lastIndex=t;let n=ih.exec(e);return n?{alt:n[1]??``,nextIndex:t+n[0].length}:null}function gh(e){return!e||!th.test(e)}function _h(e,t,n){return gh(e[t-1])&&gh(e[n])}function vh(e){let t=[],n=new Set;for(let r of e.matchLabels){let e=r.trim();if(!e)continue;let i=e.toLocaleLowerCase();n.has(i)||(n.add(i),t.push({raw:e,lower:i,length:e.length}))}return t.sort((e,t)=>t.length===e.length?e.raw.localeCompare(t.raw):t.length-e.length)}function yh(e,t){let n=e.toLocaleLowerCase(),r=[];for(let i of t){let t=0;for(;t<=n.length-i.length;){let a=n.indexOf(i.lower,t);if(a===-1)break;let o=a+i.length;_h(e,a,o)&&r.push({start:a,end:o}),t=a+1}}r.sort((e,t)=>{if(e.start!==t.start)return e.start-t.start;let n=e.end-e.start,r=t.end-t.start;return r===n?e.end-t.end:r-n});let i=[],a=null;for(let e of r)a&&e.start<a.end||(i.push(e),a=e);return i}function bh(e,t){let n=[];for(let r=0;r<t.length;r+=1)n.push(e+r);return n}function xh(e,t){let n=e.trim();return n?n===t||h(n)===t:!1}function Sh(e,t,n,r,i){let a=``,o=[],s=``,c=[];function l(){s&&(o.push({flatStart:a.length,text:s,sourceOffsets:c}),a+=s,s=``,c=[])}function u(e,t){s+=e,c.push(t)}function d(e){l(),a+=e}function f(e,t){l(),e&&(o.push({flatStart:a.length,text:e,sourceOffsets:t}),a+=e)}let p=uh(e);for(;p<e.length;){if(e[p]===`\\`&&p+1<e.length){u(e[p+1]??``,t+p+1),p+=2;continue}if(e[p]==="`"){let t=dh(e,p);if(t){d(t.text),p=t.nextIndex;continue}}if(e[p]===`!`&&e[p+1]===`[`){let t=hh(e,p);if(t){d(t.alt),p=t.nextIndex;continue}}if(e[p]===`[`&&e[p+1]===`[`){let n=fh(e,p);if(n){let e=n.label;xh(n.target,r)?d(e):f(e,bh(t+n.labelStart,e)),p=n.nextIndex;continue}}if(e[p]===`[`&&e[p-1]!==`!`){let i=mh(e,p);if(i){w(i.href,n)?.docName===r?d(i.text):f(i.text,bh(t+p+1,i.text)),p=i.nextIndex;continue}}u(e[p]??``,t+p),p+=1}l();let m=[];for(let e of o){let t=yh(e.text,i);for(let n of t){let t=e.flatStart+n.start,r=e.flatStart+n.end,i=sh(a,t,r)??e.text.slice(n.start,n.end),o=e.sourceOffsets[n.start];typeof o==`number`&&m.push({excerpt:i,offset:o})}}return m}function Ch(e,t,n,r){let{frontmatter:i,body:a}=A(e),o=i.length,s=[],c=null,l=0,u=0;for(;u<=a.length;){let e=a[u];if(!(u===a.length||e===`
56
+ `||e===`\r`)){u+=1;continue}let i=a.slice(l,u);if(c)lh(i,c)&&(c=null);else{let e=ch(i);e?c=e:s.push(...Sh(i,o+l,t,n,r))}if(u===a.length)break;if(e===`\r`&&a[u+1]===`
57
+ `){u+=2,l=u;continue}u+=1,l=u}return s}function wh(e){let t=e.getXmlFragment(`default`),n=nl.serialize(ms(t,rl).toJSON()),r=e.getMap(`metadata`).get(`frontmatter`);return u(typeof r==`string`?r:``,n)}async function Th(e,t,n){let r=e.documents.get(t);if(r)try{return wh(r)}catch(e){return eh.warn({docName:t,err:e},`[suggest-links] Failed live serialization, falling back to live source text`),r.getText(`source`).toString()}return await Ie(n.canonicalPath,`utf-8`)}function Eh(e){return{docName:e.docName,title:e.title,aliases:e.aliases}}async function Dh(e){let{hocuspocus:t,fileIndex:n,docName:r,scanBudgetMs:i=500,now:a=()=>Date.now(),onComplete:o}=e,s=a(),c=n.get(r);if(!c)throw new ah(r);let l=bf(await Th(t,r,c),r),u=vh(l),d=[...n.keys()].filter(e=>e!==r).sort((e,t)=>e.localeCompare(t)),f=new Map,p=!1;for(let e of d){if(a()-s>i){p=!0;break}let o=n.get(e);if(!o)continue;let c;try{c=await Th(t,e,o)}catch(t){eh.warn({docName:e,err:t},`[suggest-links] Failed to read source doc`);continue}let l=Ch(c,e,r,u).map(t=>({source:e,excerpt:t.excerpt,offset:t.offset}));l.length>0&&f.set(e,l)}let m=[...f.entries()].sort(([e,t],[n,r])=>r.length===t.length?e===n?(t[0]?.offset??2**53-1)-(r[0]?.offset??2**53-1):e.localeCompare(n):r.length-t.length).flatMap(([,e])=>e),g=a()-s,_={durationMs:g,corpusDocCount:d.length,candidateCount:m.length,truncated:p};return eh.info({docName:r,durationMs:g,corpusDocCount:d.length,candidateCount:m.length,truncated:p,labelCount:u.length,normalizedTarget:h(l.title)},`[suggest-links] scan completed`),o?.(_),{target:Eh(l),mentions:m,truncated:p}}const Oh=`%H%x00%aI%x00%an%x00%ae%x00%s%x00%B%x1e`,kh={entries:[],total:0,hasMore:!1};function Ah(e){return e.startsWith(`checkpoint:`)?`checkpoint`:e.startsWith(`upstream:`)?`upstream`:`wip`}function jh(e){return e.trim()?e.split(``).map(e=>{let t=e.trimStart();if(!t)return null;let[n=``,r=``,i=``,a=``,o=``,s=``]=t.split(`\0`),c=Ah(o);return{sha:n.trim(),timestamp:r,author:i,authorEmail:a,type:c,message:o,contributors:fp(s),checkpoint:c===`checkpoint`?mp(s):null}}).filter(e=>e!==null&&e.sha.length===40):[]}function Mh(e){return e?Array.isArray(e)?e:e.split(`,`).map(e=>e.trim()).filter(Boolean):[]}function Nh(e,t){return t.length===0?!0:t.some(t=>e.author.toLowerCase().includes(t.toLowerCase())||e.authorEmail.toLowerCase().includes(t.toLowerCase()))}async function Ph(e,t,n=`content`){if(!L(e.workTree)||!L(e.gitDir))return kh;let r=t.branch??`main`,i=Math.max(1,t.limit??50),a=Math.max(0,t.offset??0),o=Mh(t.type),s=Mh(t.author),c=Mh(t.excludeAuthor),l=n.replace(/^\.\//,``),u=t.docName?l?`${l}/${t.docName}${Mf(t.docName)}`:`${t.docName}${Mf(t.docName)}`:void 0;try{let t=bp(e);if(o.length===1&&o[0]===`checkpoint`){let e=(await t.raw(`for-each-ref`,`--sort=-creatordate`,`--format=%(objectname)`,`refs/checkpoints/${r}/`)).trim().split(`
61
58
  `).filter(e=>e.length===40),n=[];if(r!==`main`)try{n=(await t.raw(`for-each-ref`,`--sort=-creatordate`,`--format=%(objectname)`,`refs/checkpoints/main/`)).trim().split(`
62
- `).filter(e=>e.length===40)}catch{}let o=[...e,...n];if(o.length===0)return Dh;let l=kh(await t.raw(`log`,`--no-walk`,`--author-date-order`,`--format=${Eh}`,...o,...u?[`--`,u]:[])).map(e=>({...e,type:`checkpoint`}));if(r!==`main`&&e.length>0&&n.length>0){let t=new Set(e),n=l.filter(e=>t.has(e.sha)),r=l.filter(e=>!t.has(e.sha)),i=n.reduce((e,t)=>Math.min(e,new Date(t.timestamp).getTime()),1/0);l=[...n,...r.filter(e=>new Date(e.timestamp).getTime()<i)]}let d=l.filter(e=>jh(e,s)&&(c.length===0||!jh(e,c))),f=d.length;return{entries:d.slice(a,a+i),total:f,hasMore:a+i<f}}let n=[],l=[],d=r!==`main`;try{let e=(await t.raw(`for-each-ref`,`--format=%(objectname)`,`refs/checkpoints/${r}/`)).trim().split(`
59
+ `).filter(e=>e.length===40)}catch{}let o=[...e,...n];if(o.length===0)return kh;let l=jh(await t.raw(`log`,`--no-walk`,`--author-date-order`,`--format=${Oh}`,...o,...u?[`--`,u]:[])).map(e=>({...e,type:`checkpoint`}));if(r!==`main`&&e.length>0&&n.length>0){let t=new Set(e),n=l.filter(e=>t.has(e.sha)),r=l.filter(e=>!t.has(e.sha)),i=n.reduce((e,t)=>Math.min(e,new Date(t.timestamp).getTime()),1/0);l=[...n,...r.filter(e=>new Date(e.timestamp).getTime()<i)]}let d=l.filter(e=>Nh(e,s)&&(c.length===0||!Nh(e,c))),f=d.length;return{entries:d.slice(a,a+i),total:f,hasMore:a+i<f}}let n=[],l=[],d=r!==`main`;try{let e=(await t.raw(`for-each-ref`,`--format=%(objectname)`,`refs/checkpoints/${r}/`)).trim().split(`
63
60
  `).filter(e=>e.length===40);n.push(...e)}catch{}let f=[];if(d)try{f=(await t.raw(`for-each-ref`,`--format=%(objectname)`,`refs/checkpoints/main/`)).trim().split(`
64
61
  `).filter(e=>e.length===40)}catch{}try{let e=(await t.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/${r}/`)).trim().split(`
65
62
  `).filter(Boolean);l.push(...e)}catch{}if(d&&l.length===0)try{let e=(await t.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/main/`)).trim().split(`
66
- `).filter(Boolean);l.push(...e)}catch{}if(l.length===0&&n.length===0&&f.length===0)return Dh;let p=[...n,...f],m=[];if(p.length>0){let e=kh(await t.raw(`log`,`--no-walk`,`--author-date-order`,`--format=${Eh}`,...p)).map(e=>({...e,type:`checkpoint`}));if(d&&n.length>0&&f.length>0){let t=new Set(n),r=e.filter(e=>t.has(e.sha)),i=e.filter(e=>!t.has(e.sha)),a=r.reduce((e,t)=>{let n=new Date(t.timestamp).getTime();return n<e?n:e},1/0);m=[...r,...i.filter(e=>new Date(e.timestamp).getTime()<a)]}else m=e}let h=[...l];for(let e of p)h.push(e);let g=[];h.length>0&&(g=kh(await t.raw(`log`,`--full-history`,`--author-date-order`,`--format=${Eh}`,...h,...u?[`--`,u]:[])));let _=[...m,...g],v=new Set,y=[];for(let e of _)v.has(e.sha)||(v.add(e.sha),y.push(e));y.sort((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime());let b=y;o.length>0&&(b=b.filter(e=>o.includes(e.type))),s.length>0&&(b=b.filter(e=>jh(e,s))),c.length>0&&(b=b.filter(e=>!jh(e,c)));let x=b.length;return{entries:b.slice(a,a+i),total:x,hasMore:a+i<x}}catch(e){return console.warn(`[timeline] getDocumentHistory failed, returning empty result:`,e),Dh}}var Nh=e(dl(),1);const Ph={source:`local`,skipStoreHooks:!1,context:{origin:`rollback-apply`,paired:!0}},Fh={source:`local`,skipStoreHooks:!1,context:{origin:`managed-rename`,paired:!0}},Ih=Mc(`api`);function Lh(e,t){if(!e||e.includes(`..`)||e.includes(`\0`))return{error:`Invalid document name`};let n=t.replace(/^\.\//,``),r=Af(e);return{path:n?`${n}/${e}${r}`:`${e}${r}`}}const Rh=new Set(s),zh=/^(image\.(png|jpe?g|gif|webp)|Clipboard.*|Untitled.*)$/i;function Bh(e){let t=e.replace(/[/\\]/g,``),n=Se(t);return(t.slice(0,t.length-n.length).replace(/[^a-zA-Z0-9_\-.]/g,`_`)||`upload`)+n.replace(/[^a-zA-Z0-9_.]/g,``)}function Vh(e,t,n){let r=Se(t),i=t.slice(0,t.length-r.length),a=[t,...Array.from({length:99},(e,t)=>`${i}-${t+1}${r}`)];for(let t of a){let r=V(e,t);try{let e=ue(r,`wx`);try{_e(e,n)}finally{se(e)}return t}catch(e){if(e.code===`EEXIST`)continue;throw e}}throw Error(`Could not find available filename after 100 attempts`)}function Hh(e,t){return new Promise((n,r)=>{let i;try{i=(0,Nh.default)({headers:e.headers,limits:{fileSize:t,files:1}})}catch(e){r(e);return}let a=!1,o=`upload`,s=``,c=``,l=[],u=!1;i.on(`field`,(e,t)=>{e===`parentDocName`&&(c=t)}),i.on(`file`,(t,n,c)=>{o=c.filename||`upload`,s=c.mimeType||``,n.on(`data`,e=>{l.push(e)}),n.on(`limit`,()=>{u=!0,e.unpipe(i),a||(a=!0,r(Error(`Payload too large`)))}),n.on(`error`,e=>{a||(a=!0,r(e))})}),i.on(`finish`,()=>{if(!a){if(u){a=!0,r(Error(`Payload too large`));return}if(!s&&l.length===0){a=!0,r(Error(`No file received`));return}a=!0,n({filename:o,mimeType:s,buffer:Buffer.concat(l),parentDocName:c})}}),i.on(`error`,e=>{a||(a=!0,r(e))}),e.pipe(i)})}function Uh(e,t){let n=V(e,t);if(n!==e&&!n.startsWith(`${e}/`))throw Error(`Invalid directory: ${t}`);return n}function Wh(e){return!e||e.startsWith(`/`)||e.includes(`\\`)||e.includes(`\0`)?!1:e.split(`/`).every(e=>e&&e!==`.`&&e!==`..`)}function Gh(e,t,n){let r=[...e.keys()].filter(e=>t===`file`?e===n:e===n||e.startsWith(`${n}/`));return r.sort((e,t)=>e.localeCompare(t)),r}function Kh(e,t,n,r){return t===`file`||e===n?r:`${r}${e.slice(n.length)}`}function qh(e,t,n,r){let{frontmatter:i,body:a}=A(e),o=Xm(a,n,r),s=Zm(o.markdown,t,n,r);return{markdown:u(i,s.markdown),rewrites:o.rewrites+s.rewrites}}function Jh(e,t){let n;try{n=fe(t)}catch{return}let r=e;for(;;)try{if(!Np(fe(r),n))throw Error(`symlink-escape: path resolves outside content directory`);return}catch(e){let n=e.code;if(n===`ELOOP`)throw Error(`symlink-escape: symlink cycle in path`);if(n!==`ENOENT`)throw e;let i=xe(r);if(i===r||i!==t&&!i.startsWith(`${t}${Te}`))throw e;r=i}}function Yh(e,t,n){if(!Wh(n))throw Error(`path must be a relative content path`);let r=V(e),i=V(r,t===`file`?`${n}${Af(n)}`:n);if(i!==r&&!i.startsWith(`${r}${Te}`))throw Error(`path must not escape content directory`);return Jh(i,r),i}async function Xh(e){let t=[],n=0;for await(let r of e){if(n+=r.length,n>1048576)throw Error(`Payload too large`);t.push(r)}return Buffer.concat(t)}function J(e,t,n){e.writeHead(t,{"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`}),e.end(JSON.stringify(n))}function Zh(e){let t=e;if(e.startsWith(`---
63
+ `).filter(Boolean);l.push(...e)}catch{}if(l.length===0&&n.length===0&&f.length===0)return kh;let p=[...n,...f],m=[];if(p.length>0){let e=jh(await t.raw(`log`,`--no-walk`,`--author-date-order`,`--format=${Oh}`,...p)).map(e=>({...e,type:`checkpoint`}));if(d&&n.length>0&&f.length>0){let t=new Set(n),r=e.filter(e=>t.has(e.sha)),i=e.filter(e=>!t.has(e.sha)),a=r.reduce((e,t)=>{let n=new Date(t.timestamp).getTime();return n<e?n:e},1/0);m=[...r,...i.filter(e=>new Date(e.timestamp).getTime()<a)]}else m=e}let h=[...l];for(let e of p)h.push(e);let g=[];h.length>0&&(g=jh(await t.raw(`log`,`--full-history`,`--author-date-order`,`--format=${Oh}`,...h,...u?[`--`,u]:[])));let _=[...m,...g],v=new Set,y=[];for(let e of _)v.has(e.sha)||(v.add(e.sha),y.push(e));y.sort((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime());let b=y;o.length>0&&(b=b.filter(e=>o.includes(e.type))),s.length>0&&(b=b.filter(e=>Nh(e,s))),c.length>0&&(b=b.filter(e=>!Nh(e,c)));let x=b.length;return{entries:b.slice(a,a+i),total:x,hasMore:a+i<x}}catch(e){return console.warn(`[timeline] getDocumentHistory failed, returning empty result:`,e),kh}}var Fh=e(pl(),1);const Ih={source:`local`,skipStoreHooks:!1,context:{origin:`rollback-apply`,paired:!0}},Lh={source:`local`,skipStoreHooks:!1,context:{origin:`managed-rename`,paired:!0}},Rh=Pc(`api`);function zh(e,t){if(!e||e.includes(`..`)||e.includes(`\0`))return{error:`Invalid document name`};let n=t.replace(/^\.\//,``),r=Mf(e);return{path:n?`${n}/${e}${r}`:`${e}${r}`}}const Bh=new Set(s),Vh=/^(image\.(png|jpe?g|gif|webp)|Clipboard.*|Untitled.*)$/i;function Hh(e){let t=e.replace(/[/\\]/g,``),n=Se(t);return(t.slice(0,t.length-n.length).replace(/[^a-zA-Z0-9_\-.]/g,`_`)||`upload`)+n.replace(/[^a-zA-Z0-9_.]/g,``)}function Uh(e,t,n){let r=Se(t),i=t.slice(0,t.length-r.length),a=[t,...Array.from({length:99},(e,t)=>`${i}-${t+1}${r}`)];for(let t of a){let r=V(e,t);try{let e=ue(r,`wx`);try{_e(e,n)}finally{se(e)}return t}catch(e){if(e.code===`EEXIST`)continue;throw e}}throw Error(`Could not find available filename after 100 attempts`)}function Wh(e,t){return new Promise((n,r)=>{let i;try{i=(0,Fh.default)({headers:e.headers,limits:{fileSize:t,files:1}})}catch(e){r(e);return}let a=!1,o=`upload`,s=``,c=``,l=[],u=!1;i.on(`field`,(e,t)=>{e===`parentDocName`&&(c=t)}),i.on(`file`,(t,n,c)=>{o=c.filename||`upload`,s=c.mimeType||``,n.on(`data`,e=>{l.push(e)}),n.on(`limit`,()=>{u=!0,e.unpipe(i),a||(a=!0,r(Error(`Payload too large`)))}),n.on(`error`,e=>{a||(a=!0,r(e))})}),i.on(`finish`,()=>{if(!a){if(u){a=!0,r(Error(`Payload too large`));return}if(!s&&l.length===0){a=!0,r(Error(`No file received`));return}a=!0,n({filename:o,mimeType:s,buffer:Buffer.concat(l),parentDocName:c})}}),i.on(`error`,e=>{a||(a=!0,r(e))}),e.pipe(i)})}function Gh(e,t){let n=V(e,t);if(n!==e&&!n.startsWith(`${e}/`))throw Error(`Invalid directory: ${t}`);return n}function Kh(e){return!e||e.startsWith(`/`)||e.includes(`\\`)||e.includes(`\0`)?!1:e.split(`/`).every(e=>e&&e!==`.`&&e!==`..`)}function qh(e,t,n){let r=[...e.keys()].filter(e=>t===`file`?e===n:e===n||e.startsWith(`${n}/`));return r.sort((e,t)=>e.localeCompare(t)),r}function Jh(e,t,n,r){return t===`file`||e===n?r:`${r}${e.slice(n.length)}`}function Yh(e,t,n,r){let{frontmatter:i,body:a}=A(e),o=Qm(a,n,r),s=$m(o.markdown,t,n,r);return{markdown:u(i,s.markdown),rewrites:o.rewrites+s.rewrites}}function Xh(e,t){let n;try{n=fe(t)}catch{return}let r=e;for(;;)try{if(!Fp(fe(r),n))throw Error(`symlink-escape: path resolves outside content directory`);return}catch(e){let n=e.code;if(n===`ELOOP`)throw Error(`symlink-escape: symlink cycle in path`);if(n!==`ENOENT`)throw e;let i=xe(r);if(i===r||i!==t&&!i.startsWith(`${t}${Te}`))throw e;r=i}}function Zh(e,t,n){if(!Kh(n))throw Error(`path must be a relative content path`);let r=V(e),i=V(r,t===`file`?`${n}${Mf(n)}`:n);if(i!==r&&!i.startsWith(`${r}${Te}`))throw Error(`path must not escape content directory`);return Xh(i,r),i}async function Qh(e){let t=[],n=0;for await(let r of e){if(n+=r.length,n>1048576)throw Error(`Payload too large`);t.push(r)}return Buffer.concat(t)}function J(e,t,n,r){e.writeHead(t,{"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`,...r}),e.end(JSON.stringify(n))}function $h(e){let t=e;if(e.startsWith(`---
67
64
  `)||e.startsWith(`---\r
68
65
  `)){let n=e.indexOf(`
69
66
  ---`,3);n!==-1&&(t=e.slice(n+4))}let n=[],r=new Map,i=S();for(let e of t.split(`
70
- `)){if(i(e))continue;let t=e.match(/^(#{1,6})\s+(.+)$/);if(t){let e=t[2].trim(),i=b(e,r);i&&n.push({level:t[1].length,text:e,slug:i})}}return n}function Qh(e){return!(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))}function $h(e){let{hocuspocus:t,sessionManager:n,contentDir:r,getFileIndex:i,getAliasMap:a,enableTestRoutes:o=!1,shadowRef:s,flushGitCommit:l,getCurrentBranch:d,contentRoot:f,backlinkIndex:m,signalChannel:h,agentFocusBroadcaster:g,onAgentWrite:_,getSyncEngine:y,localOpCliArgs:b=[`open-knowledge`],projectDir:x}=e,S=Dm();function C(e){if(!Qh(e))return null;let t=V(r),n=V(t,`${e}${Af(e)}`);return!n.startsWith(`${t}/`)&&n!==t?null:n}function w(e){let t=C(e);if(!t||!L(t))return e;try{return hf(R(t,`utf-8`),e)}catch{return e}}let T={cluster:void 0,category:void 0,tags:void 0};function E(e){try{let n=t.documents.get(e);if(n){let e=n.getMap(`metadata`).get(`frontmatter`);if(typeof e==`string`&&e)return gf(e)}}catch{}try{let t=C(e);if(!t||!L(t))return T;let{frontmatter:n}=A(R(t,`utf-8`));return n?gf(n):T}catch{return T}}function D(e){if(m)try{if(m.getBacklinks(e).length>0)return;let t=performance.now(),n=nf(e,i()),r=performance.now()-t;return r>5&&Ih.debug({docName:e,elapsedMs:r,candidateCount:n.length},`[orphan-hint] findHubCandidates slow`),n.length===0?void 0:[{type:`orphan`,parentCandidates:n,message:`This doc has no backlinks yet. To make it discoverable, consider linking from a parent hub doc (index/overview files in the folder tree): ${n.map(e=>`[[${e}]]`).join(`, `)}.`}]}catch(e){console.warn(`[orphan-hint] computeOrphanHints failed:`,e);return}}function O(e){return a?.().get(e)??e}function k(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function j(e,n){let r=`onStoreDocument-${e}`;(t.debouncer.isDebounced(r)?t.debouncer.executeNow(r):Promise.resolve()).then(()=>l?.()).catch(e=>{Ih.warn({err:e},`[${n}] post-write flush failed`)})}function M(){let e=new Set;for(let[t,n]of i()){e.add(t);for(let t of n.aliases)e.add(t)}return e}function ee(){let e=Promise.resolve();return async function(t){let n=e,r=()=>{};e=new Promise(e=>{r=e}),await n;try{return await t()}finally{r()}}}let N=ee();function te(e){return e instanceof Error&&(e.message===`Managed rename requires backlink index support`||e.message.startsWith(`Cannot rename missing document:`)||e.message.startsWith(`symlink-escape:`))?e.message:`Failed to rename document`}async function ne(e){let r=new Map;for(let n of e){let e=t.documents.get(n);e&&r.set(n,e.getText(`source`).toString())}for(let t of e)await n.closeAllForDoc(t).catch(e=>{console.warn(`[file-ops] Failed to close agent session for ${t}:`,e)});for(let n of e){let e=t.documents.get(n);Bp(n),e&&(t.closeConnections(n),await t.unloadDocument(e))}return r}function P(e,t){for(let{fromDocName:n,toDocName:i}of e){let e=Mp(i,r),a=t.get(n);typeof a==`string`&&z(e,a,`utf-8`);let o=typeof a==`string`?a:L(e)?R(e,`utf-8`):null;typeof o==`string`&&em(e,nm(o))}}function F(e,t){return e.map(e=>{let n=t.get(e);if(typeof n==`string`)return{docName:e,content:n};let i=Mp(e,r);if(!L(i))throw Error(`Cannot snapshot missing document: ${e}`);return{docName:e,content:R(i,`utf-8`)}})}function ie(e){let n=t.documents.get(e);if(n)return n.getText(`source`).toString();let i=Yh(r,`file`,e);return L(i)?R(i,`utf-8`):null}function I(e,t){let n=Yh(r,`file`,e);le(xe(n),{recursive:!0}),z(n,t,`utf-8`),em(n,nm(t)),zp(e,t);let a=i();a instanceof Map&&dm({kind:`update`,path:n,docName:e,content:t},a)}function oe(e,n,r){let i=t.documents.get(e);if(!i)throw Error(`Document is not loaded: ${e}`);let a={markdown:``,rewrites:0};return i.transact(()=>{let t=i.getXmlFragment(`default`),o=i.getText(`source`),s=o.toString();if(a=qh(s,e,n,r),a.rewrites===0)return;let{body:c}=A(a.markdown),l=el.parseWithFallback(c);ls(i,t,tl.nodeFromJSON(l),{mapping:new Map,isOMark:new Map}),p(o,s,a.markdown)},Fh),a}async function se(e,n){return N(async()=>{if(!m)throw Error(`Managed rename requires backlink index support`);let a=Yh(r,`file`,e),o=Yh(r,`file`,n),s=[{fromDocName:e,toDocName:n}],c=[...new Set(m.getBacklinks(e).map(e=>e.source))].sort((e,t)=>e.localeCompare(t)),l=new Map,u=[],d=[];for(let t of[e,...c]){if(l.has(t))continue;let n=ie(t);typeof n==`string`?(l.set(t,n),t!==e&&u.push(t)):t!==e&&d.push(t)}if(typeof l.get(e)!=`string`)throw Error(`Cannot rename missing document: ${e}`);let f=Mm({sourceDocName:e,destinationDocName:n,snapshots:F([...l.keys()],l)}),p=[];return await Rm(r,f,async()=>{for(let e of d)m.deleteDocument(e);for(let r of u){let i=t.documents.get(r)?oe(r,e,n):qh(l.get(r)??``,r,e,n);i.rewrites>0&&(I(r,i.markdown),p.push({docName:r,rewrites:i.rewrites})),m.updateDocumentFromMarkdown(r,i.markdown)}let r=qh((await ne([e])).get(e)??l.get(e)??R(a,`utf-8`),e,e,n);le(xe(o),{recursive:!0}),pe(a,o),P(s,new Map([[e,r.markdown]])),zp(n,r.markdown);let c=i();c instanceof Map&&dm({kind:`rename`,oldPath:a,newPath:o,oldDocName:e,newDocName:n,content:r.markdown},c),m.renameDocument(e,n,r.markdown),r.rewrites>0&&p.push({docName:n,rewrites:r.rewrites})}),m.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${n}:`,t)}),h?.(`files`),h?.(`backlinks`),h?.(`graph`),p.sort((e,t)=>e.docName.localeCompare(t.docName)),{renamed:s,rewrittenDocs:p}})}let ce=/^[a-zA-Z0-9_-]+$/;function ue(e){let t=typeof e.agentId==`string`?e.agentId:void 0;t!==void 0&&!ce.test(t)&&(t=void 0);let n=t?`agent-${t}`:`claude-1`,r=typeof e.agentName==`string`?e.agentName.slice(0,128).replace(/[\r\n]/g,``):`Claude`,i=typeof e.clientName==`string`?e.clientName:void 0;i!==void 0&&(i=i.slice(0,128).replace(/[\r\n]/g,``));let a=typeof e.colorSeed==`string`&&e.colorSeed.length>0?e.colorSeed.slice(0,128):t??n;return{rawAgentId:t,agentId:n,agentName:r,colorSeed:a,clientName:i}}async function _e(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await Xh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=r.length>0?JSON.parse(r.toString()):{}}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}let a=typeof i.docName==`string`&&i.docName.length>0?i.docName:`test-doc`;if(!Qh(a)){J(t,400,{ok:!1,error:`Invalid docName`});return}let o=O(a);if(q(o)){J(t,400,{ok:!1,error:`'${o}' is a reserved document name`});return}let{agentId:s,agentName:c,colorSeed:l,clientName:u}=ue(i),d=await n.getSession(o,s,{displayName:c,colorSeed:l,clientName:u}),f=new Date().toISOString(),p=typeof i.content==`string`?i.content:`Hello from the agent! ${f}`;d.document.awareness.setLocalStateField(`mode`,`editing`);try{d.document.transact(()=>{al(d.document,`${p}\n`,`append`),d.document.getMap(`activity`).set(s,{agentId:s,timestamp:Date.now(),type:`insert`,description:`Added (${c}): ${p.slice(0,50)}`})},rl),Zd(o,s,c,l)}finally{d.document.awareness.setLocalStateField(`mode`,`idle`)}j(o,`agent-write`),J(t,200,{ok:!0,timestamp:f})}catch(e){Ih.error({err:e},`[agent-write] handler failed`),J(t,500,{ok:!1,error:`Internal server error`})}}async function ve(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await Xh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(r.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){J(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{markdown:a,position:o}=i;if(!a||typeof a!=`string`){J(t,400,{ok:!1,error:`markdown field required`});return}let s=o===`prepend`?`prepend`:o===`replace`?`replace`:`append`,c=i.docName,l=typeof c==`string`&&c.length>0?c:`test-doc`;if(!Qh(l)){J(t,400,{ok:!1,error:`Invalid docName`});return}let u=O(l);if(q(u)){J(t,400,{ok:!1,error:`'${u}' is a reserved document name`});return}let{agentId:d,agentName:f,colorSeed:p,clientName:m}=ue(i),h=await n.getSession(u,d,{displayName:f,colorSeed:p,clientName:m}),v=new Date().toISOString();h.document.awareness.setLocalStateField(`mode`,`editing`);try{h.document.transact(()=>{al(h.document,a,s),h.document.getMap(`activity`).set(d,{agentId:d,timestamp:Date.now(),type:`insert`,description:`Added (${f}): ${a.trim().slice(0,50)}`})},rl),Zd(u,d,f,p)}finally{h.document.awareness.setLocalStateField(`mode`,`idle`)}j(u,`agent-write-md`),g?.setFocus(d,{agentName:f,currentDoc:u,writeKind:`write`,ts:Date.now()}),_?.();let y=D(u);J(t,200,{ok:!0,timestamp:v,subscriberCount:k(u),...y?{hints:y}:{}})}catch(e){Ih.error({err:e},`[agent-write-md] handler failed`),J(t,500,{ok:!1,error:`Internal server error`})}}async function ye(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!Qh(r)){J(t,400,{ok:!1,error:`Invalid docName`});return}let i=O(r);if(q(i)){J(t,400,{ok:!1,error:`'${i}' is a reserved document name`});return}J(t,200,{ok:!0,docName:i,content:(await n.getSession(i)).document.getText(`source`).toString()})}catch(e){console.error(`[document-read]`,e),J(t,500,{ok:!1,error:`Internal server error`})}}async function be(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`dir`);if(n)try{Uh(r,n)}catch{J(t,400,{ok:!1,error:`Invalid directory parameter`});return}let a=i(),o=[];for(let[e,t]of a)if(!(n&&!e.startsWith(`${n}/`)&&e!==n)){o.push({docName:e,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let i of t.aliases){if(n&&!i.startsWith(`${n}/`)&&i!==n)continue;let a=B(r,t.canonicalPath);o.push({docName:i,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:a})}}o.sort((e,t)=>e.docName.localeCompare(t.docName)),J(t,200,{ok:!0,documents:o})}catch(e){console.error(`[document-list]`,e),J(t,500,{ok:!1,error:`Internal server error`})}}async function Se(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){J(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!Qh(n)){J(t,400,{ok:!1,error:`Invalid docName`});return}J(t,200,{ok:!0,docName:n,backlinks:m.getBacklinks(n).map(e=>({source:e.source,anchor:e.anchor,title:w(e.source),snippet:e.snippet}))})}catch(e){console.error(`[backlinks]`,e),J(t,500,{ok:!1,error:`Failed to read backlinks`})}}async function Ce(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!n){J(t,400,{ok:!1,error:`Missing docNames parameter`});return}let r={};for(let e of n.split(`,`)){let t=e.trim();!t||!Qh(t)||(r[t]=m.getBacklinkCount(t))}J(t,200,{ok:!0,counts:r})}catch(e){console.error(`[backlink-counts]`,e),J(t,500,{ok:!1,error:`Failed to read backlink counts`})}}async function we(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){J(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!Qh(n)){J(t,400,{ok:!1,error:`Invalid docName`});return}J(t,200,{ok:!0,docName:n,forwardLinks:m.getForwardLinkEntries(n).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:w(e.target),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})})}catch(e){console.error(`[forward-links]`,e),J(t,500,{ok:!1,error:`Failed to read forward links`})}}async function Ee(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`docName`);if(r&&!Qh(r)){J(t,400,{ok:!1,error:`Invalid docName`});return}let i=n.searchParams.get(`degrees`);if(i&&!r){J(t,400,{ok:!1,error:`docName is required when degrees is provided`});return}let a,o;if(i&&r){let e=Number.parseInt(i,10);if(!Number.isFinite(e)||e<0){J(t,400,{ok:!1,error:`degrees must be a non-negative integer`});return}({nodes:a,links:o}=m.getLinkGraphNeighborhood(r,e))}else ({nodes:a,links:o}=m.getLinkGraph());J(t,200,{ok:!0,nodes:a.map(e=>{if(e.kind===`doc`){let t=E(e.docName);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:w(e.docName),cluster:t.cluster??null,category:t.category??null,tags:t.tags??null}}return{id:e.id,kind:`external`,url:e.url,label:e.label??e.url}}),links:o})}catch(e){console.error(`[link-graph]`,e),J(t,500,{ok:!1,error:`Failed to read link graph`})}}async function De(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!v(n)){J(t,400,{ok:!1,error:`Invalid orphan mode. Allowed values: incoming, outgoing, both`});return}J(t,200,{ok:!0,orphans:m.getOrphans([...i().keys()],n).map(e=>({docName:e,title:w(e)}))})}catch(e){console.error(`[orphans]`,e),J(t,500,{ok:!1,error:`Failed to read orphan pages`})}}async function Oe(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),r=n?Number.parseInt(n,10):20,i=Number.isFinite(r)&&r>0?r:20;J(t,200,{ok:!0,hubs:m.getHubs(i).map(e=>({docName:e.docName,title:w(e.docName),count:e.count}))})}catch(e){console.error(`[hubs]`,e),J(t,500,{ok:!1,error:`Failed to read hub pages`})}}async function ke(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.getAll(`sourceDocName`);if(n.some(e=>e.length===0||!Qh(e))){J(t,400,{ok:!1,error:`Invalid sourceDocName`});return}let r=n.length?[...new Set(n.map(e=>O(e)))]:void 0;J(t,200,{ok:!0,deadLinks:m.getDeadLinks(M(),r).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:w(e.source),snippet:e.snippet}))}))})}catch(e){console.error(`[dead-links]`,e),J(t,500,{ok:!1,error:`Failed to read dead links`})}}async function Ae(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await Xh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(r.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){J(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{find:a,replace:o,docName:s,offset:c}=i;if(typeof a!=`string`||a.length===0){J(t,400,{ok:!1,error:`find field required`});return}if(typeof o!=`string`){J(t,400,{ok:!1,error:`replace field required`});return}let l=Object.hasOwn(i,`offset`),d;if(l){if(typeof c!=`number`||!Number.isInteger(c)||c<0){J(t,400,{ok:!1,error:`offset must be a non-negative integer`});return}d=c}let f=typeof s==`string`&&s.length>0?s:`test-doc`;if(!Qh(f)){J(t,400,{ok:!1,error:`Invalid docName`});return}let p=O(f);if(q(p)){J(t,400,{ok:!1,error:`'${p}' is a reserved document name`});return}let{agentId:m,agentName:h,colorSeed:v,clientName:y}=ue(i),b=await n.getSession(p,m,{displayName:h,colorSeed:v,clientName:y}),x=new Date().toISOString(),S=!1,C=!1;b.document.awareness.setLocalStateField(`mode`,`editing`);try{b.document.transact(()=>{let e=b.document.getXmlFragment(`default`),t=b.document.getMap(`metadata`),n=t.get(`frontmatter`)??``,r=u(n,el.serialize(fs(e,tl).toJSON())),i=d==null?r.indexOf(a):r.slice(d,d+a.length)===a?d:-1;if(i===-1){d==null?S=!0:C=!0;return}let{frontmatter:s,body:c}=A(r.slice(0,i)+o+r.slice(i+a.length));s!==n&&t.set(`frontmatter`,s),al(b.document,c,`replace`),b.document.getMap(`activity`).set(m,{agentId:m,timestamp:Date.now(),type:`insert`,description:`Patched (${h}): ${a.slice(0,50)}`})},rl),!S&&!C&&Zd(p,m,h,v)}finally{b.document.awareness.setLocalStateField(`mode`,`idle`)}if(C){J(t,409,{ok:!1,error:`Target text no longer matches at the requested offset`});return}if(S){J(t,404,{ok:!1,error:`Text not found in document`});return}j(p,`agent-patch`),g?.setFocus(m,{agentName:h,currentDoc:p,writeKind:`edit`,ts:Date.now()}),_?.(),J(t,200,{ok:!0,timestamp:x,subscriberCount:k(p)})}catch(e){Ih.error({err:e},`[agent-patch] handler failed`),J(t,500,{ok:!1,error:`Internal server error`})}}async function Me(e,i){if(e.method!==`POST`){i.writeHead(405),i.end(`Method not allowed`);return}try{let a=O(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??`test-doc`),o;try{o=Mp(a,r)}catch(e){console.error(`[test-reset] safeContentPath rejected docName:`,a,e),J(i,400,{ok:!1,error:`Invalid docName`});return}await n.closeAll(a),t.closeConnections(a);let s=`onStoreDocument-${a}`;t.debouncer.isDebounced(s)&&await t.debouncer.executeNow(s);let c=t.documents.get(a);c&&await t.unloadDocument(c),z(o,``,`utf-8`),m&&(m.deleteDocument(a),m.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${a}:`,e)}),h?.(`backlinks`),h?.(`graph`)),h?.(`files`),J(i,200,{ok:!0})}catch(e){console.error(`[test-reset]`,e),J(i,500,{ok:!1,error:`Internal server error`})}}async function Pe(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}m.rebuildFromDisk(),m.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),h?.(`backlinks`),h?.(`graph`),J(t,200,{ok:!0})}catch(e){console.error(`[test-rescan-backlinks]`,e),J(t,500,{ok:!1,error:`Internal server error`})}}async function Fe(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}let n=s?.current;if(!n){J(t,400,{ok:!1,error:`Shadow repo not configured`});return}try{let r;try{r=await Xh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let i=/^[a-zA-Z0-9_-]+$/,a=[],o;if(r.length>0){let e;try{e=JSON.parse(r.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}typeof e.message==`string`&&e.message.trim()&&(o=e.message.replace(/[\r\n]/g,` `).slice(0,256)),Array.isArray(e.writers)&&(a=e.writers.map(e=>{let t=e.id??`unknown`;if(!i.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}}))}a.length===0&&(a=[{id:`server`,name:`openknowledge-server`,email:`noreply@openknowledge.local`}]);let s=f??`content`,c=await Ap(n,s,a);console.log(`[shadow] checkpoint ${c.checkpointRef}`);let l;if(x)try{l=await ae(async()=>{let e=Ne({baseDir:x,timeout:{block:15e3}}),t=(await e.tags([`--list`,`ok/v*`])).all.length+1,n=`ok/v${t}`,r=o??`Checkpoint v${t}`,i=s||`.`;return await e.add(i),await e.commit(r,{"--allow-empty":null}),await e.addTag(n),console.log(`[checkpoint] parent-git commit + tag ${n}`),n})}catch(e){console.warn(`[checkpoint] parent-git commit failed (non-fatal):`,e)}J(t,200,{ok:!0,checkpointRef:c.checkpointRef,...l?{versionTag:l}:{}})}catch(e){console.error(`[save-version]`,e),J(t,500,{ok:!1,error:`Internal server error`})}}async function Ie(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=s?.current;if(!n){J(t,400,{ok:!1,error:`Shadow repo not configured`});return}let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=r.searchParams.get(`docName`)??``,a=r.searchParams.get(`branch`)??d?.()??`main`;if(!i){J(t,400,{ok:!1,error:`docName query parameter is required`});return}if(a.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(a)){J(t,400,{ok:!1,error:`Invalid branch name`});return}let o=Number(r.searchParams.get(`limit`)??`50`),c=Number(r.searchParams.get(`offset`)??`0`),l=Math.min(200,Number.isFinite(o)?o:50),u=Number.isFinite(c)?c:0,p=r.searchParams.get(`type`)??void 0,m=r.searchParams.get(`author`)??void 0,h=r.searchParams.get(`excludeAuthor`)??void 0,g=Date.now();try{let e=await Mh(n,{docName:i,branch:a,limit:l,offset:u,type:p,author:m,excludeAuthor:h},f??`content`),r=Date.now()-g;console.log(`[timeline] query docName=${i} entries=${e.entries.length} duration=${r}ms`),J(t,200,{ok:!0,...e})}catch(e){console.error(`[history]`,e),J(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function Le(e,t,n){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let r=s?.current;if(!r){J(t,400,{ok:!1,error:`Shadow repo not configured`});return}let i=Lh(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,f??`content`);if(`error`in i){J(t,400,{ok:!1,error:i.error});return}let a=i.path,o=vp(r);if(!/^[0-9a-f]{40}$/i.test(n)){J(t,400,{ok:!1,error:`Invalid commit SHA`});return}try{try{await o.raw(`cat-file`,`-e`,`${n}:${a}`)}catch{J(t,404,{ok:!1,error:`Document did not exist at this version`});return}let e=await o.raw(`show`,`${n}:${a}`),[r=``,i=``]=(await o.raw(`log`,`-1`,`--format=%aI%x00%an`,n)).trim().split(`\0`);J(t,200,{ok:!0,sha:n,content:e,timestamp:r,author:i})}catch(e){console.error(`[history-version]`,e),J(t,500,{ok:!1,error:`Internal server error`})}}async function Re(e,n){if(e.method!==`GET`){n.writeHead(405),n.end(`Method not allowed`);return}let r=s?.current;if(!r){J(n,400,{ok:!1,error:`Shadow repo not configured`});return}let i=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),a=i.searchParams.get(`docName`)??``,o=i.searchParams.get(`from`)??``,c=i.searchParams.get(`to`)??``;if(!c||!/^[0-9a-f]{40}$/i.test(c)){J(n,400,{ok:!1,error:`'to' must be a valid 40-char commit SHA`});return}let l=Lh(a,f??`content`);if(`error`in l){J(n,400,{ok:!1,error:l.error});return}let u=l.path,d=vp(r);try{let e;try{e=await d.raw(`show`,`${c}:${u}`)}catch{J(n,404,{ok:!1,error:`Document did not exist at the target version`});return}let r;if(o&&/^[0-9a-f]{40}$/i.test(o))try{r=await d.raw(`show`,`${o}:${u}`)}catch{J(n,404,{ok:!1,error:`Document did not exist at the source version`});return}else{let e=t.documents.get(a);if(!e){J(n,409,{ok:!1,error:`Document is not currently open — open it in the editor first`});return}r=e.getText(`source`).toString()}let i=A(r).body,s=A(e).body,l=kl(i,s),f=[],p=0,m=0;for(let e of l){let t=e.value.replace(/\n$/,``).split(`
71
- `),n=e.added?`added`:e.removed?`removed`:`unchanged`;for(let e of t)f.push({type:n,text:e});e.added&&(p+=t.length),e.removed&&(m+=t.length)}J(n,200,{ok:!0,lines:f,additions:p,deletions:m})}catch(e){console.error(`[diff]`,e),J(n,500,{ok:!1,error:`Internal server error`})}}async function ze(e,n){if(e.method!==`POST`){n.writeHead(405),n.end(`Method not allowed`);return}let r=s?.current;if(!r){J(n,400,{ok:!1,error:`Shadow repo not configured`});return}let i;try{i=await Xh(e)}catch{J(n,413,{ok:!1,error:`Payload too large`});return}let a;try{a=i.length>0?JSON.parse(i.toString()):{}}catch{J(n,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){J(n,400,{ok:!1,error:`Body must be a JSON object`});return}let{docName:o,commitSha:c,versionTag:u}=a,d=typeof o==`string`?o:``,p=typeof c==`string`?c:``,m=typeof u==`string`?u:void 0;if(!d){J(n,400,{ok:!1,error:`docName required`});return}if(!p||!/^[0-9a-f]{40}$/i.test(p)){J(n,400,{ok:!1,error:`commitSha must be a valid 40-char commit SHA`});return}let h=f??`content`,g=Lh(d,h);if(`error`in g){J(n,400,{ok:!1,error:g.error});return}let _=g.path,v=vp(r),y=Date.now();try{try{await v.raw(`cat-file`,`-e`,`${p}:${_}`)}catch{J(n,404,{ok:!1,error:`Document did not exist at this version`});return}let e=await v.raw(`show`,`${p}:${_}`),i=new Date().toISOString();await Tp(r,h,{action:`rollback`,context:{docName:d,targetSha:p}});let a=t.documents.get(d);if(!a){J(n,409,{ok:!1,error:`Document is not currently open — open it in the editor first`});return}let{frontmatter:o,body:s}=A(e),c=el.parseWithFallback(s),u=tl.nodeFromJSON(c),g=a.getXmlFragment(`default`);a.transact(()=>{ls(a,g,u,{mapping:new Map,isOMark:new Map});let t=a.getText(`source`),n=t.toString();n!==e&&(t.delete(0,n.length),t.insert(0,e)),a.getMap(`metadata`).set(`frontmatter`,o)},Ph),zp(d,e),l&&l().catch(e=>{console.warn(`[rollback] flush git commit failed:`,e)});let b=Date.now()-y;if(console.log(`[rollback] docName=${d} from=${p.slice(0,8)} duration=${b}ms`),x){let e=`Restored to ${m??p.slice(0,8)}: ${d}`,t=f??`content`;ae(async()=>{let n=Ne({baseDir:x,timeout:{block:15e3}}),r=t||`.`;await n.add(r),await n.commit(e,{"--allow-empty":null}),console.log(`[rollback] parent-git commit: ${e}`)}).catch(e=>{console.warn(`[rollback] parent-git commit failed (non-fatal):`,e)})}J(n,200,{ok:!0,restoredFrom:p,timestamp:i})}catch(e){console.error(`[rollback]`,e),J(n,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function Be(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}J(t,200,Qc())}async function Ve(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}J(t,200,c())}async function He(e,t){if(!Om(e.socket.remoteAddress)){J(t,403,{ok:!1,error:`loopback-required`});return}if(!km(e.headers.host)){J(t,403,{ok:!1,error:`host-header-not-allowed`});return}if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=V(r),i=n,a=!0;try{i=fe(n)}catch(e){let r=e?.code;if(r===`ENOENT`)console.warn(`[workspace] contentDir does not exist; returning unresolved path`,{path:n}),a=!1;else{console.warn(`[workspace] realpath failed for contentDir`,{path:n,err:e}),J(t,500,{ok:!1,error:`workspace-realpath-failed`,code:r??null});return}}J(t,200,{ok:!0,contentDir:i,pathSeparator:Te,symlinkResolved:a})}let Ue=1440*60*1e3;async function We(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}if(!s?.current){J(t,200,[]);return}let n=Date.now(),r=[],i=V(s.current.gitDir,`rescue`);if(L(i))try{let e=de(i).filter(e=>Tf(e));for(let t of e){let e=V(i,t),a=he(e);if(n-a.mtimeMs>Ue){try{ge(e)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}r.push({docName:Ef(t),timestamp:a.mtime.toISOString(),size:a.size,source:`flat`})}}catch(e){console.error(`[rescue] Failed to list flat-file rescue buffers:`,e)}try{let e=d?.()??`main`,t=await Dp(s.current,e);for(let e of t)r.push({...e,source:`timeline`})}catch(e){console.error(`[rescue] Failed to list timeline-ref rescue checkpoints:`,e)}J(t,200,r)}async function Ge(e,t,n){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}if(!s?.current){t.writeHead(404),t.end(`Not found`);return}let r=V(s.current.gitDir,`rescue`),i=V(r,`${n}${Af(n)}`);if(!i.startsWith(`${r}/`)){t.writeHead(400),t.end(`Invalid document name`);return}if(L(i)){let e=he(i);if(Date.now()-e.mtimeMs>Ue)try{ge(i)}catch{}else{let e=R(i,`utf-8`);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(e);return}}try{let e=d?.()??`main`,r=(await Dp(s.current,e)).filter(e=>e.docName===n).sort((e,t)=>t.timestamp.localeCompare(e.timestamp))[0];if(r){let e=vp(s.current),n=((await e.raw(`ls-tree`,`-r`,r.sha)).trim().split(`
72
- `)[0]??``).split(/\s+/)[2];if(n){let r=await e.raw(`cat-file`,`-p`,n);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(r);return}}}catch(e){console.warn(`[rescue] timeline-ref fallback failed:`,e)}t.writeHead(404),t.end(`Not found`)}async function Ke(e,t){if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await Xh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let a;try{a=JSON.parse(n.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){J(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{path:o}=a;if(!o||typeof o!=`string`||o.length===0){J(t,400,{ok:!1,error:`path is required`});return}if(!Tf(o)){J(t,400,{ok:!1,error:`path must end with .md or .mdx`});return}if(o.includes(`..`)||o.startsWith(`/`)||o.includes(`\0`)||o.includes(`\\`)){J(t,400,{ok:!1,error:`path must not contain .. or start with /`});return}let s=V(r),c=V(s,o);if(!c.startsWith(`${s}/`)&&c!==s){J(t,400,{ok:!1,error:`path must not escape content directory`});return}let l=Ef(o);if(q(l)){J(t,400,{ok:!1,error:`'${l}' is a reserved document name`});return}le(xe(c),{recursive:!0});try{z(c,``,{encoding:`utf-8`,flag:`wx`})}catch(e){if(e.code===`EEXIST`){J(t,409,{ok:!1,error:`File already exists`});return}throw e}let u=Ef(o),d=typeof i==`function`?i():null;d instanceof Map&&dm({kind:`create`,path:c,docName:u,content:``},d),m&&(m.updateDocumentFromMarkdown(u,``),m.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${u}:`,e)}),h?.(`backlinks`),h?.(`graph`)),h?.(`files`),J(t,200,{ok:!0,docName:u})}catch(e){console.error(`[create-page]`,e),J(t,500,{ok:!1,error:`Failed to create page`})}}async function qe(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n||typeof n!=`string`||n.length===0){J(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!Qh(n)){J(t,400,{ok:!1,error:`Invalid docName`});return}let r=C(n);if(!r){J(t,400,{ok:!1,error:`Invalid docName`});return}if(!L(r)){J(t,404,{ok:!1,error:`Page not found`});return}J(t,200,{ok:!0,docName:n,headings:Zh(R(r,`utf-8`))})}catch(e){console.error(`[page-headings]`,e),J(t,500,{ok:!1,error:`Failed to read headings`})}}async function Je(e,t){if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await Xh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(n.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){J(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{docName:a,newDocName:o}=i;if(typeof a!=`string`||typeof o!=`string`){J(t,400,{ok:!1,error:`docName and newDocName are required`});return}if(!Wh(a)||!Wh(o)){J(t,400,{ok:!1,error:`Document names must be relative content paths`});return}if(q(a)||q(o)){J(t,400,{ok:!1,error:`Reserved document names cannot be renamed`});return}if(a===o){J(t,200,{ok:!0,renamed:[],rewrittenDocs:[]});return}if(!m){J(t,503,{ok:!1,error:`Backlink index unavailable`});return}let s=Yh(r,`file`,a),c=Yh(r,`file`,o);if(!L(s)){J(t,404,{ok:!1,error:`Document does not exist`});return}if(L(c)){J(t,409,{ok:!1,error:`Destination already exists`});return}let l=await se(a,o);J(t,200,{ok:!0,renamed:l.renamed,rewrittenDocs:l.rewrittenDocs})}catch(e){console.error(`[rename]`,e),J(t,500,{ok:!1,error:te(e)})}}async function Ye(e,t){if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await Xh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let a;try{a=JSON.parse(n.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){J(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{kind:o,fromPath:s,toPath:c}=a;if(o!==`file`&&o!==`folder`){J(t,400,{ok:!1,error:`kind must be "file" or "folder"`});return}if(typeof s!=`string`||typeof c!=`string`){J(t,400,{ok:!1,error:`fromPath and toPath are required`});return}if(!Wh(s)||!Wh(c)){J(t,400,{ok:!1,error:`Paths must be relative content paths`});return}if(s===c){J(t,200,{ok:!0,renamed:[]});return}let l=Yh(r,o,s),u=Yh(r,o,c);if(!L(l)){J(t,404,{ok:!1,error:`${o} does not exist`});return}if(L(u)){J(t,409,{ok:!1,error:`Destination already exists`});return}let d=he(l);if(o===`file`&&!d.isFile()||o===`folder`&&!d.isDirectory()){J(t,400,{ok:!1,error:`Source path is not a ${o}`});return}let f=Gh(i(),o,s),p=o===`file`?[{fromDocName:s,toDocName:c}]:f.map(e=>({fromDocName:e,toDocName:Kh(e,o,s,c)})),m=await ne(p.map(({fromDocName:e})=>e)),h=()=>{le(xe(u),{recursive:!0}),pe(l,u),P(p,m)};o===`file`?await Rm(r,Mm({sourceDocName:s,destinationDocName:c,snapshots:F(p.map(({fromDocName:e})=>e),m)}),h):h(),J(t,200,{ok:!0,renamed:p})}catch(e){console.error(`[rename-path]`,e),J(t,500,{ok:!1,error:`Failed to rename path`})}}async function Xe(e,t){if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await Xh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let a;try{a=JSON.parse(n.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){J(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{kind:o,path:s}=a;if(o!==`file`&&o!==`folder`){J(t,400,{ok:!1,error:`kind must be "file" or "folder"`});return}if(typeof s!=`string`||!Wh(s)){J(t,400,{ok:!1,error:`path must be a relative content path`});return}let c=Yh(r,o,s);if(!L(c)){J(t,404,{ok:!1,error:`${o} does not exist`});return}let l=he(c);if(o===`file`&&!l.isFile()||o===`folder`&&!l.isDirectory()){J(t,400,{ok:!1,error:`Target path is not a ${o}`});return}let u=o===`file`?[s]:Gh(i(),o,s);await ne(u),o===`file`?ge(c):me(c,{recursive:!0,force:!1}),J(t,200,{ok:!0,deletedDocNames:u})}catch(e){console.error(`[delete-path]`,e),J(t,500,{ok:!1,error:`Failed to delete path`})}}async function Ze(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}try{let e=i(),n=[];for(let[t,i]of e){let e=t;try{e=hf(R(V(r,`${t}${Af(t)}`),`utf-8`),t)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}n.push({docName:t,title:e,size:i.size,modified:i.modified})}n.sort((e,t)=>e.docName.localeCompare(t.docName)),J(t,200,{ok:!0,pages:n})}catch(e){console.error(`[pages]`,e),J(t,500,{ok:!1,error:`Failed to list pages`})}}async function Qe(e,n){if(e.method!==`GET`){J(n,405,{ok:!1,error:`Method not allowed`});return}try{let r=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!r){J(n,400,{ok:!1,error:`Missing docName parameter`});return}if(!Qh(r)){J(n,400,{ok:!1,error:`Invalid docName`});return}if(q(r)){J(n,400,{ok:!1,error:`'${r}' is a reserved document name`});return}J(n,200,{ok:!0,...await Th({hocuspocus:t,fileIndex:i(),docName:r})})}catch(e){if(e instanceof rh){J(n,404,{ok:!1,error:`Page not found`});return}console.error(`[suggest-links]`,e),J(n,500,{ok:!1,error:`Failed to suggest links`})}}async function $e(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}let n;try{n=await Hh(e,10485760)}catch(e){let n=e instanceof Error?e.message:String(e);n===`Payload too large`?J(t,413,{ok:!1,error:`Payload too large`}):n===`No file received`?J(t,400,{ok:!1,error:`No file received`}):J(t,400,{ok:!1,error:`Failed to parse upload: ${n}`});return}let{filename:i,buffer:a,parentDocName:o}=n;if(!o){J(t,400,{ok:!1,error:`parentDocName is required`});return}if(o.includes(`\0`)||o.includes(`..`)||o.startsWith(`/`)){J(t,400,{ok:!1,error:`path-escape`});return}let s=V(r),c=V(s,xe(o));if(!Np(c,s)){J(t,400,{ok:!1,error:`path-escape`});return}try{let e=fe(c),n;try{n=fe(s)}catch{n=s}if(!Np(e,n)){J(t,400,{ok:!1,error:`path-escape`});return}}catch(e){if(e.code!==`ENOENT`){J(t,400,{ok:!1,error:`path-escape`});return}}let l=await Jd(a),u=l?.mime,d=l?.ext;if(!u){let e=a.subarray(0,256).toString(`utf-8`).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(u=`image/svg+xml`,d=`svg`)}if(!u||!d||!Rh.has(u)){J(t,400,{ok:!1,error:`Unsupported file type${u?`: ${u}`:``}`});return}let f;f=!i||i===`upload`||zh.test(i)?`pasted-${new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`)}.${d}`:Bh(i),le(c,{recursive:!0});try{let e=Vh(c,f,a),n=B(r,V(c,e));console.log(`[upload] ok ${n} ${a.length}`),J(t,200,{ok:!0,src:e})}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`[upload] error ${f} ${a.length} ${n}`),J(t,500,{ok:!1,error:`Failed to save file`})}}let et=`/api/local-op/clone`,tt=`/api/local-op/open`,nt=600*1e3;async function rt(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n,r;try{let i=await Xh(e),a=JSON.parse(i.toString());if(typeof a.url!=`string`||!a.url){J(t,400,{ok:!1,error:`Missing or invalid url`});return}if(typeof a.dir!=`string`||!a.dir){J(t,400,{ok:!1,error:`Missing or invalid dir`});return}n=a.url,r=a.dir}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!xm(n)){J(t,400,{ok:!1,error:`URL protocol not allowed`});return}if(!Cm(r)){J(t,400,{ok:!1,error:`dir must be within the user home directory`});return}if(!S.tryAcquire(et)){J(t,429,{ok:!1,error:`A clone operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let i=Sm(r),[a,...o]=b,s=[...o,`clone`,`--json`,n,i],c=!1,l=!1,u=null,d=``,f=je(a,s,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),p=setTimeout(()=>{c=!0,f.kill(`SIGTERM`)},nt);f.stdout.on(`data`,e=>{d+=e.toString(`utf-8`);let n=d.split(`
73
- `);d=n.pop()??``;for(let e of n){if(!e.trim())continue;let n=null;try{n=JSON.parse(e)}catch{}if(n&&n.type===`complete`&&typeof n.dir==`string`){u=n.dir;continue}t.writableEnded||t.write(`${e}\n`)}});let m=[];f.stderr.on(`data`,e=>{m.push(e),Ih.debug({msg:e.toString(`utf-8`).trim()},`[local-op/clone] stderr`)}),f.on(`close`,e=>{clearTimeout(p);let i=Buffer.concat(m).toString(`utf-8`).trim();if(l){S.release(et);return}l=!0,(async()=>{try{if(c&&!t.writableEnded)t.write(`${JSON.stringify({type:`error`,message:`Clone timed out after 10 minutes`})}\n`);else if(e!==0&&!t.writableEnded){i&&Ih.warn({code:e,stderr:i,url:n,dir:r},`[local-op/clone] clone failed`);let a=i?` — ${i}`:``;t.write(`${JSON.stringify({type:`error`,message:`Clone process exited with code ${e}${a}`})}\n`)}else if(e===0&&u&&!t.writableEnded){let e=await it(u);t.writableEnded||(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port})}\n`):t.write(`${JSON.stringify({type:`error`,message:e.error})}\n`))}}finally{t.writableEnded||t.end(),S.release(et)}})()}),f.on(`error`,e=>{clearTimeout(p),l||(l=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),S.release(et)})}async function it(e){let t=V(Sm(e)),n=V(t,`.open-knowledge`),r=Sf(n);if(r&&r.port>0)return{port:r.port};let i=re(n),[a,...o]=b,s=i&&i.port>0?`ui`:`start`,c=je(a,[...o,s],{cwd:t,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env}}),l=[];c.stderr?.on(`data`,e=>{l.push(e),Ih.warn({cwd:t,cliCmd:s,msg:e.toString(`utf-8`).trim()},`[local-op/open] child stderr`)});let u=null;c.on(`exit`,e=>{u=e??-1}),c.unref();let d=Date.now()+45e3;for(;Date.now()<d;){await new Promise(e=>setTimeout(e,500));let e=Sf(n);if(e&&e.port>0)return{port:e.port};if(u!==null){let e=Buffer.concat(l).toString(`utf-8`).trim();return{error:`\`ok ${s}\` exited (code ${u})${e?` — ${e}`:``}`}}}let f=Buffer.concat(l).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${f?` — ${f}`:``}`}}async function at(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n;try{let r=await Xh(e),i=JSON.parse(r.toString());if(typeof i.dir!=`string`||!i.dir){J(t,400,{ok:!1,error:`Missing or invalid dir`});return}n=i.dir}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!Cm(n)){J(t,400,{ok:!1,error:`dir must be within the user home directory`});return}if(!S.tryAcquire(tt)){J(t,429,{ok:!1,error:`A server-open operation is already in progress`});return}try{let e=await it(n);`port`in e?J(t,200,{port:e.port}):J(t,504,{ok:!1,error:e.error})}finally{S.release(tt)}}let ot=`/api/local-op/auth/login`,st=`/api/local-op/auth/status`,ct=`/api/local-op/auth/repos`,lt=`/api/local-op/auth/signout`,ut=`/api/local-op/auth/pat`;async function dt(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=await Xh(e),r=JSON.parse(t.toString());typeof r.host==`string`&&r.host&&(n=r.host)}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!S.tryAcquire(ot)){J(t,429,{ok:!1,error:`An auth login operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let[r,...i]=b,a=[...i,`auth`,`login`,`--json`,`--host`,n],o=!1,s=!1,c=``,l=je(r,a,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),u=setTimeout(()=>{l.kill(`SIGTERM`)},nt),d=()=>{l.killed||l.kill(`SIGTERM`)};t.on(`close`,d),l.stdout.on(`data`,e=>{t.writableEnded||t.write(e),c+=e.toString(`utf-8`);let n=c.split(`
74
- `);c=n.pop()??``;for(let e of n)if(e.trim())try{let t=JSON.parse(e);(t.type===`complete`||t.type===`error`)&&(s=!0)}catch{}}),l.stderr.on(`data`,e=>{Ih.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/login] stderr`)}),l.on(`close`,e=>{clearTimeout(u),t.off(`close`,d),o||(o=!0,t.writableEnded||(e===0&&!s?t.write(`${JSON.stringify({type:`complete`,host:n,login:``})}\n`):e!==0&&t.write(`${JSON.stringify({type:`error`,message:`auth login exited with code ${e}`})}\n`)),t.end()),S.release(ot)}),l.on(`error`,e=>{clearTimeout(u),t.off(`close`,d),o||(o=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),S.release(ot)})}async function ft(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=(await Xh(e)).toString().trim();if(t.length>0){let e=JSON.parse(t);typeof e.host==`string`&&e.host&&(n=e.host)}}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!S.tryAcquire(st)){J(t,429,{ok:!1,error:`An auth status operation is already in progress`});return}try{let[e,...r]=b,i=[...r,`auth`,`status`,`--json`,`--host`,n],a=(await new Promise((t,n)=>{let r=je(e,i,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4),o=[];r.stdout.on(`data`,e=>o.push(e)),r.on(`close`,()=>{clearTimeout(a),t(Buffer.concat(o).toString(`utf-8`))}),r.on(`error`,e=>{clearTimeout(a),n(e)})})).split(`
75
- `).map(e=>e.trim()).filter(Boolean),o=null;for(let e=a.length-1;e>=0;e--)try{o=JSON.parse(a[e]);break}catch{}o===null?J(t,200,{authenticated:!1}):J(t,200,o)}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:`auth status failed`})}finally{S.release(st)}}async function pt(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=(await Xh(e)).toString().trim();if(t.length>0){let e=JSON.parse(t);typeof e.host==`string`&&e.host&&(n=e.host)}}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!S.tryAcquire(ct)){J(t,429,{ok:!1,error:`An auth repos operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let[r,...i]=b,a=[...i,`auth`,`repos`,`--json`,`--host`,n],o=!1,s=je(r,a,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),c=setTimeout(()=>{s.kill(`SIGTERM`)},nt);s.stdout.on(`data`,e=>{t.writableEnded||t.write(e)}),s.stderr.on(`data`,e=>{Ih.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),s.on(`close`,e=>{clearTimeout(c),o||(o=!0,e!==0&&!t.writableEnded&&t.write(`${JSON.stringify({type:`error`,message:`auth repos exited with code ${e}`})}\n`),t.end()),S.release(ct)}),s.on(`error`,e=>{clearTimeout(c),o||(o=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),S.release(ct)})}async function mt(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=await Xh(e),r=JSON.parse(t.toString());typeof r.host==`string`&&r.host&&(n=r.host)}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!S.tryAcquire(lt)){J(t,429,{ok:!1,error:`An auth signout operation is already in progress`});return}try{let[e,...r]=b,i=[...r,`auth`,`signout`,`--host`,n];await new Promise((t,n)=>{let r=je(e,i,{stdio:`ignore`,env:{...process.env}}),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4);r.on(`close`,()=>{clearTimeout(a),t()}),r.on(`error`,e=>{clearTimeout(a),n(e)})}),J(t,200,{ok:!0})}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:`auth signout failed`})}finally{S.release(lt)}}async function ht(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`,r;try{let i=await Xh(e),a=JSON.parse(i.toString());if(typeof a.pat!=`string`||!a.pat){J(t,400,{ok:!1,error:`Missing or invalid pat`});return}r=a.pat,typeof a.host==`string`&&a.host&&(n=a.host)}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!S.tryAcquire(ut)){J(t,429,{ok:!1,error:`An auth pat operation is already in progress`});return}try{let[e,...i]=b,a=[...i,`auth`,`pat`,`--json`,`--host`,n],o=(await new Promise((t,n)=>{let i=je(e,a,{stdio:[`pipe`,`pipe`,`pipe`],env:{...process.env}}),o=setTimeout(()=>{i.kill(`SIGTERM`)},3e4);i.stdin.write(`${r}\n`),i.stdin.end();let s=[];i.stdout.on(`data`,e=>s.push(e)),i.on(`close`,e=>{clearTimeout(o),e===0?t(Buffer.concat(s).toString(`utf-8`)):n(Error(`auth pat exited with code ${e}`))}),i.on(`error`,e=>{clearTimeout(o),n(e)})})).split(`
76
- `).map(e=>e.trim()).filter(Boolean),s=null;for(let e=o.length-1;e>=0;e--)try{s=JSON.parse(o[e]);break}catch{}s===null?J(t,200,{ok:!0}):J(t,200,s)}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:`auth pat failed`})}finally{S.release(ut)}}async function gt(e,t){if(Em(e,t,J)){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!x){J(t,400,{ok:!1,error:`No project directory configured`});return}try{J(t,200,{ok:!0,identity:await _m(x)})}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:`identity resolution failed`})}}}let _t=`/api/local-op/auth/set-identity`;async function vt(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n,r;try{let i=await Xh(e),a=JSON.parse(i.toString());if(typeof a.name!=`string`||!a.name.trim()){J(t,400,{ok:!1,error:`Missing or invalid name`});return}if(typeof a.email!=`string`||!a.email.trim()){J(t,400,{ok:!1,error:`Missing or invalid email`});return}n=a.name.trim(),r=a.email.trim()}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!x){J(t,400,{ok:!1,error:`No project directory configured`});return}if(!S.tryAcquire(_t)){J(t,429,{ok:!1,error:`A set-identity operation is already in progress`});return}try{vm(x,n,r),y?.()?.refreshIdentity().catch(()=>{}),J(t,200,{ok:!0})}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:`set-identity failed`})}finally{S.release(_t)}}async function yt(e,t){if(!Em(e,t,J))return;if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=y?.();if(!n){J(t,200,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1});return}J(t,200,n.getStatus())}async function bt(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=y?.();if(!n){J(t,503,{ok:!1,error:`Sync engine not active`});return}let r=`sync`;try{let t=await Xh(e);if(t.length>0){let e=JSON.parse(t.toString());(e.op===`push`||e.op===`pull`||e.op===`sync`)&&(r=e.op)}}catch{}J(t,202,{ok:!0,op:r}),n.trigger(r)}async function H(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=y?.();if(!n){J(t,503,{ok:!1,error:`Sync engine not active`});return}let r;try{let n=await Xh(e),i=JSON.parse(n.toString());if(typeof i.enabled!=`boolean`){J(t,400,{ok:!1,error:`enabled must be a boolean`});return}r=i.enabled}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}await n.setEnabled(r),J(t,200,{ok:!0,status:n.getStatus()})}async function xt(e,t){if(!Em(e,t,J))return;if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=y?.();J(t,200,{conflicts:n?n.getConflicts():[]})}async function St(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=y?.();if(!n){J(t,503,{ok:!1,error:`Sync engine not active`});return}let r;try{let t=await Xh(e);r=JSON.parse(t.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}let{file:i,strategy:a,content:o}=r;if(!i||typeof i!=`string`){J(t,400,{ok:!1,error:`Missing required field: file`});return}if(a!==`mine`&&a!==`theirs`&&a!==`content`){J(t,400,{ok:!1,error:`Invalid strategy: must be 'mine', 'theirs', or 'content'`});return}try{await n.resolveConflict(i,a,o),J(t,200,{ok:!0})}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function Ct(e,t){if(!Em(e,t,J))return;if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!x){J(t,503,{ok:!1,error:`Project repo not configured`});return}let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`file`);if(!n){J(t,400,{ok:!1,error:`Missing required query param: file`});return}if(n.includes(`..`)||n.startsWith(`/`)){J(t,400,{ok:!1,error:`Invalid file path`});return}let r=Ne({baseDir:x,timeout:{block:15e3}});async function i(e){try{return await r.raw([`show`,`:${e}:${n}`])}catch{return``}}try{let[e,r,a]=await Promise.all([i(1),i(2),i(3)]);J(t,200,{ok:!0,file:n,base:e,ours:r,theirs:a})}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function wt(e,t){if(!Em(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=y?.();if(!n){J(t,503,{ok:!1,error:`Sync engine not active`});return}try{await n.abortMerge(),J(t,200,{ok:!0})}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}let Tt={"/api/document":ye,"/api/documents":be,"/api/backlinks":Se,"/api/backlink-counts":Ce,"/api/forward-links":we,"/api/link-graph":Ee,"/api/dead-links":ke,"/api/orphans":De,"/api/hubs":Oe,"/api/pages":Ze,"/api/suggest-links":Qe,"/api/page-headings":qe,"/api/create-page":Ke,"/api/rename":Je,"/api/rename-path":Ye,"/api/delete-path":Xe,"/api/upload-image":$e,"/api/agent-write":_e,"/api/agent-write-md":ve,"/api/agent-patch":Ae,"/api/save-version":Fe,"/api/history":Ie,"/api/diff":Re,"/api/rollback":ze,"/api/metrics/reconciliation":Be,"/api/metrics/parse-health":Ve,"/api/rescue":We,"/api/workspace":He,"/api/sync/status":yt,"/api/sync/trigger":bt,"/api/sync/set-enabled":H,"/api/sync/conflicts":xt,"/api/sync/conflict-content":Ct,"/api/sync/resolve-conflict":St,"/api/sync/abort-merge":wt,"/api/local-op/clone":rt,"/api/local-op/open":at,"/api/local-op/auth/login":dt,"/api/local-op/auth/status":ft,"/api/local-op/auth/repos":pt,"/api/local-op/auth/signout":mt,"/api/local-op/auth/pat":ht,"/api/local-op/auth/identity":gt,"/api/local-op/auth/set-identity":vt};return o&&(Tt[`/api/test-reset`]=Me,Tt[`/api/test-rescan-backlinks`]=Pe),{priority:100,async onRequest({request:e,response:t}){let n=e.url?.split(`?`)[0];if(!n)return;if(n.startsWith(`/api/`)&&(typeof t.setHeader==`function`&&(t.setHeader(`Access-Control-Allow-Origin`,`*`),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization`)),e.method===`OPTIONS`)){t.writeHead(204),t.end();return}let r=Tt[n];if(r){await r(e,t);return}if(n.startsWith(`/api/rescue/`)){let r=decodeURIComponent(n.slice(12));r&&await Ge(e,t,r);return}if(n.startsWith(`/api/history/`)){let r=decodeURIComponent(n.slice(13));r&&await Le(e,t,r);return}}}}function eg(e){let t=e.scheduler??T,n=e.warnBeforeMs??3e5,r=0,i=null,a=null,o=!1,s=!1;function c(){i!==null&&(t.clearTimeout(i),i=null),a!==null&&(t.clearTimeout(a),a=null)}function l(){c(),!(s||o)&&r===0&&(n>0&&n<e.thresholdMs&&(a=t.setTimeout(()=>{a=null,r===0&&!o&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),i=t.setTimeout(()=>{if(i=null,!(s||o)&&r===0){o=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let u=(e,t)=>{e.url?.startsWith(`/collab`)&&(r++,c(),t.once(`close`,()=>{r--,r<0&&(r=0),r===0&&l()}))};return e.httpServer.on(`upgrade`,u),l(),{detach:()=>{s||(s=!0,e.httpServer.off(`upgrade`,u),c())}}}const tg=Math.floor,ng=(e,t)=>e<t?e:t,rg=(e,t)=>e>t?e:t;Number.isNaN,Number.isInteger,Number.isNaN,Number.parseInt;const ig=String.fromCharCode;String.fromCodePoint,ig(65535);const ag=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},og=typeof TextEncoder<`u`?new TextEncoder:null,sg=og?e=>og.encode(e):ag;let cg=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});cg&&cg.decode(new Uint8Array).length===1&&(cg=null);const lg=(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},ug=(e,t)=>{for(;t>127;)lg(e,128|127&t),t=tg(t/128);lg(e,127&t)},dg=new Uint8Array(3e4),fg=dg.length/3,pg=og&&og.encodeInto?(e,t)=>{if(t.length<fg){let n=og.encodeInto(t,dg).written||0;ug(e,n);for(let t=0;t<n;t++)lg(e,dg[t])}else hg(e,sg(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;ug(e,r);for(let t=0;t<r;t++)lg(e,n.codePointAt(t))},mg=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=ng(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(rg(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},hg=(e,t)=>{ug(e,t.byteLength),mg(e,t)},gg=e=>Error(e);gg(`Unexpected end of array`),gg(`Integer out of Range`);let _g=function(e){return e[e.Token=0]=`Token`,e[e.PermissionDenied=1]=`PermissionDenied`,e[e.Authenticated=2]=`Authenticated`,e}({});const vg=(e,t)=>{ug(e,_g.PermissionDenied),pg(e,t)},yg=(e,t)=>{ug(e,_g.Authenticated),pg(e,t)},bg=e=>{ug(e,_g.Token)},xg={code:4205,reason:`Reset Connection`},Sg={code:4401,reason:`Unauthorized`},Cg={code:4403,reason:`Forbidden`},wg={code:4408,reason:`Connection Timeout`},Tg=e=>Array.from(e.entries()).map(([e,t])=>({clientId:e,...t}));var Eg=class extends Error{constructor(e){super(e??`Further hooks skipped`),this.name=`SkipFurtherHooksError`}};let Dg=function(e){return e[e.Connecting=0]=`Connecting`,e[e.Open=1]=`Open`,e[e.Closing=2]=`Closing`,e[e.Closed=3]=`Closed`,e}({});const Og=Error(`request for lock canceled`);var kg=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},Ag=class{constructor(e,t=Og){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return new Promise((n,r)=>{let i={resolve:n,reject:r,weight:e,priority:t},a=Mg(this._queue,e=>t<=e.priority);a===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(a+1,0,i)})}runExclusive(e){return kg(this,arguments,void 0,function*(e,t=1,n=0){let[r,i]=yield this.acquire(t,n);try{return yield e(r)}finally{i()}})}waitForUnlock(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),jg(this._weightedWaiters[e-1],{resolve:n,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let t=this._weightedWaiters[e-1];t&&(t.forEach(e=>e.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let t=this._value;t>0;t--){let n=this._weightedWaiters[t-1];if(!n)continue;let r=n.findIndex(t=>t.priority<=e);(r===-1?n:n.splice(0,r)).forEach((e=>e.resolve()))}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}};function jg(e,t){let n=Mg(e,e=>t.priority<=e.priority);e.splice(n+1,0,t)}function Mg(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}var Ng=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},Pg=class{constructor(e){this._semaphore=new Ag(1,e)}acquire(){return Ng(this,arguments,void 0,function*(e=0){let[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};let Fg,Ig,Lg,Rg,zg=!0;typeof process<`u`&&({FORCE_COLOR:Fg,NODE_DISABLE_COLORS:Ig,NO_COLOR:Lg,TERM:Rg}=process.env||{},zg=process.stdout&&process.stdout.isTTY);const Y={enabled:!Ig&&Lg==null&&Rg!==`dumb`&&(Fg!=null&&Fg!==`0`||zg),reset:X(0,0),bold:X(1,22),dim:X(2,22),italic:X(3,23),underline:X(4,24),inverse:X(7,27),hidden:X(8,28),strikethrough:X(9,29),black:X(30,39),red:X(31,39),green:X(32,39),yellow:X(33,39),blue:X(34,39),magenta:X(35,39),cyan:X(36,39),white:X(37,39),gray:X(90,39),grey:X(90,39),bgBlack:X(40,49),bgRed:X(41,49),bgGreen:X(42,49),bgYellow:X(43,49),bgBlue:X(44,49),bgMagenta:X(45,49),bgCyan:X(46,49),bgWhite:X(47,49)};function Bg(e,t){let n=0,r,i=``,a=``;for(;n<e.length;n++)r=e[n],i+=r.open,a+=r.close,~t.indexOf(r.close)&&(t=t.replace(r.rgx,r.close+r.open));return i+t+a}function Vg(e,t){let n={has:e,keys:t};return n.reset=Y.reset.bind(n),n.bold=Y.bold.bind(n),n.dim=Y.dim.bind(n),n.italic=Y.italic.bind(n),n.underline=Y.underline.bind(n),n.inverse=Y.inverse.bind(n),n.hidden=Y.hidden.bind(n),n.strikethrough=Y.strikethrough.bind(n),n.black=Y.black.bind(n),n.red=Y.red.bind(n),n.green=Y.green.bind(n),n.yellow=Y.yellow.bind(n),n.blue=Y.blue.bind(n),n.magenta=Y.magenta.bind(n),n.cyan=Y.cyan.bind(n),n.white=Y.white.bind(n),n.gray=Y.gray.bind(n),n.grey=Y.grey.bind(n),n.bgBlack=Y.bgBlack.bind(n),n.bgRed=Y.bgRed.bind(n),n.bgGreen=Y.bgGreen.bind(n),n.bgYellow=Y.bgYellow.bind(n),n.bgBlue=Y.bgBlue.bind(n),n.bgMagenta=Y.bgMagenta.bind(n),n.bgCyan=Y.bgCyan.bind(n),n.bgWhite=Y.bgWhite.bind(n),n}function X(e,t){let n={open:`\x1b[${e}m`,close:`\x1b[${t}m`,rgx:RegExp(`\\x1b\\[${t}m`,`g`)};return function(t){return this!==void 0&&this.has!==void 0?(~this.has.indexOf(e)||(this.has.push(e),this.keys.push(n)),t===void 0?this:Y.enabled?Bg(this.keys,t+``):t+``):t===void 0?Vg([e],[n]):Y.enabled?Bg([n],t+``):t+``}}const Hg=Math.floor,Ug=(e,t)=>e<t?e:t,Wg=(e,t)=>e>t?e:t;Number.isNaN;const Gg=2**53-1;Number.isInteger,Number.isNaN,Number.parseInt;const Kg=()=>new Set,qg=Array.from;Array.isArray;const Jg=String.fromCharCode;String.fromCodePoint,Jg(65535);const Yg=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},Xg=typeof TextEncoder<`u`?new TextEncoder:null,Zg=Xg?e=>Xg.encode(e):Yg;let Qg=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});Qg&&Qg.decode(new Uint8Array).length===1&&(Qg=null);const $g=e=>Error(e);var e_=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const t_=()=>new e_,n_=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},r_=e=>{let t=new Uint8Array(n_(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},i_=(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},Z=(e,t)=>{for(;t>127;)i_(e,128|127&t),t=Hg(t/128);i_(e,127&t)},a_=new Uint8Array(3e4),o_=a_.length/3,s_=Xg&&Xg.encodeInto?(e,t)=>{if(t.length<o_){let n=Xg.encodeInto(t,a_).written||0;Z(e,n);for(let t=0;t<n;t++)i_(e,a_[t])}else l_(e,Zg(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;Z(e,r);for(let t=0;t<r;t++)i_(e,n.codePointAt(t))},c_=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=Ug(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(Wg(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},l_=(e,t)=>{Z(e,t.byteLength),c_(e,t)},u_=$g(`Unexpected end of array`),d_=$g(`Integer out of Range`);var f_=class{constructor(e){this.arr=e,this.pos=0}};const p_=e=>new f_(e),m_=e=>e.pos!==e.arr.length,h_=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},g_=e=>h_(e,v_(e)),__=e=>e.arr[e.pos++],v_=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>Gg)throw d_}throw u_},y_=Qg?e=>Qg.decode(g_(e)):e=>{let t=v_(e);if(t===0)return``;{let n=String.fromCodePoint(__(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(__(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))}};var b_=class{constructor(e){e instanceof Uint8Array||(e=new Uint8Array(e)),this.decoder=p_(e)}get encoder(){return this.encoderInternal||=t_(),this.encoderInternal}readVarUint8Array(){return g_(this.decoder)}peekVarUint8Array(){let{pos:e}=this.decoder,t=g_(this.decoder);return this.decoder.pos=e,t}readVarUint(){return v_(this.decoder)}readVarString(){return y_(this.decoder)}toUint8Array(){return r_(this.encoder)}writeVarUint(e){Z(this.encoder,e)}writeVarString(e){s_(this.encoder,e)}get length(){return n_(this.encoder)}};const x_=Date.now,S_=()=>new Map,C_=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r};var w_=class{constructor(){this._observers=S_()}on(e,t){C_(this._observers,e,Kg).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 qg((this._observers.get(e)||S_()).values()).forEach(e=>e(...t))}destroy(){this._observers=S_()}};const T_=Symbol(`Equality`),E_=Object.keys,D_=e=>E_(e).length,O_=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),k_=(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[T_]!=null)return e[T_](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)||!k_(e.get(n),t.get(n)))return!1;break;case void 0:case Object:if(D_(e)!==D_(t))return!1;for(let n in e)if(!O_(e,n)||!k_(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(!k_(e[n],t[n]))return!1;break;default:return!1}return!0},A_=3e4;var j_=class extends w_{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let e=x_();this.getLocalState()!==null&&A_/2<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&A_<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&M_(this,t,`timeout`)},Hg(A_/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:x_()});let a=[],o=[],s=[],c=[];e===null?c.push(t):i==null?e!=null&&a.push(t):(o.push(t),k_(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}};const M_=(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:x_()})}r.push(i)}}r.length>0&&(e.emit(`change`,[{added:[],updated:[],removed:r},n]),e.emit(`update`,[{added:[],updated:[],removed:r},n]))},N_=(e,t,n=e.states)=>{let r=t.length,i=t_();Z(i,r);for(let a=0;a<r;a++){let r=t[a],o=n.get(r)||null,s=e.meta.get(r).clock;Z(i,r),Z(i,s),s_(i,JSON.stringify(o))}return r_(i)},P_=(e,t,n)=>{let r=p_(t),i=x_(),a=[],o=[],s=[],c=[],l=v_(r);for(let t=0;t<l;t++){let t=v_(r),n=v_(r),l=JSON.parse(y_(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&&(k_(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])},F_=(e,t)=>{Z(e,0),l_(e,qr(t))},I_=(e,t,n)=>{Z(e,1),l_(e,Vr(t,n))},L_=(e,t,n)=>I_(t,n,g_(e)),R_=(e,t,n,r)=>{try{Rr(t,g_(e),n)}catch(e){r?.(e),console.error(`Caught error while handling a Yjs update`,e)}},z_=(e,t)=>{Z(e,2),l_(e,t)},B_=R_;function V_(e){return typeof e==`object`&&!!e&&`source`in e&&(e.source===`connection`||e.source===`redis`||e.source===`local`)}function H_(e){if(!V_(e))return!1;switch(e.source){case`connection`:return!1;case`redis`:return!0;case`local`:return e.skipStoreHooks??!1}}let Q=function(e){return e[e.Unknown=-1]=`Unknown`,e[e.Sync=0]=`Sync`,e[e.Awareness=1]=`Awareness`,e[e.Auth=2]=`Auth`,e[e.QueryAwareness=3]=`QueryAwareness`,e[e.SyncReply=4]=`SyncReply`,e[e.Stateless=5]=`Stateless`,e[e.BroadcastStateless=6]=`BroadcastStateless`,e[e.CLOSE=7]=`CLOSE`,e[e.SyncStatus=8]=`SyncStatus`,e[e.Ping=9]=`Ping`,e[e.Pong=10]=`Pong`,e}({});var U_=class{constructor(e){this.encoder=t_(),s_(this.encoder,e)}createSyncMessage(){return this.type=Q.Sync,Z(this.encoder,Q.Sync),this}createSyncReplyMessage(){return this.type=Q.SyncReply,Z(this.encoder,Q.SyncReply),this}createAwarenessUpdateMessage(e,t){this.type=Q.Awareness,this.category=`Update`;let n=N_(e,t||Array.from(e.getStates().keys()));return Z(this.encoder,Q.Awareness),l_(this.encoder,n),this}writeQueryAwareness(){return this.type=Q.QueryAwareness,this.category=`Update`,Z(this.encoder,Q.QueryAwareness),this}writeTokenSyncRequest(){return this.type=Q.Auth,this.category=`TokenSync`,Z(this.encoder,Q.Auth),bg(this.encoder),this}writeAuthenticated(e){return this.type=Q.Auth,this.category=`Authenticated`,Z(this.encoder,Q.Auth),yg(this.encoder,e?`readonly`:`read-write`),this}writePermissionDenied(e){return this.type=Q.Auth,this.category=`PermissionDenied`,Z(this.encoder,Q.Auth),vg(this.encoder,e),this}writeFirstSyncStepFor(e){return this.category=`SyncStep1`,F_(this.encoder,e),this}writeUpdate(e){return this.category=`Update`,z_(this.encoder,e),this}writeStateless(e){return this.category=`Stateless`,Z(this.encoder,Q.Stateless),s_(this.encoder,e),this}writeBroadcastStateless(e){return this.category=`Stateless`,Z(this.encoder,Q.BroadcastStateless),s_(this.encoder,e),this}writeSyncStatus(e){return this.category=`SyncStatus`,Z(this.encoder,Q.SyncStatus),Z(this.encoder,e?1:0),this}writeCloseMessage(e){return this.type=Q.CLOSE,Z(this.encoder,Q.CLOSE),s_(this.encoder,e),this}toUint8Array(){return r_(this.encoder)}},W_=class{constructor(e,t){this.message=e,this.defaultTransactionOrigin=t}async apply(e,t,n){let{message:r}=this,i=r.readVarUint(),a=r.length;switch(i){case Q.Sync:case Q.SyncReply:r.writeVarUint(Q.Sync),await this.readSyncMessage(r,e,t,n,i!==Q.SyncReply),r.length>a+1&&(n?n(r.toUint8Array()):t&&t.send(r.toUint8Array()));break;case Q.Awareness:P_(e.awareness,r.readVarUint8Array(),t??null);break;case Q.QueryAwareness:this.applyQueryAwarenessMessage(e,t,n);break;case Q.Stateless:t?.callbacks.statelessCallback({connection:t,documentName:e.name,document:e,payload:y_(r.decoder)});break;case Q.BroadcastStateless:{let t=r.readVarString();e.getConnections().forEach(e=>{e.sendStateless(t)});break}case Q.CLOSE:t?.close({code:1e3,reason:`provider_initiated`});break;case Q.Auth:if(r.readVarUint()===_g.Token){t?.callbacks.onTokenSyncCallback({token:r.readVarString()});break}console.error(`Received an authentication message on a connection that is already fully authenticated. Probably your provider has been destroyed + recreated really fast.`);break;default:console.error(`Unable to handle message of type ${i}: no handler defined! Are your provider/server versions aligned?`)}}async readSyncMessage(e,t,n,r,i=!0){let a=e.readVarUint(),o=n?.messageAddress??t.name;switch(n&&await n.callbacks.beforeSync(n,{type:a,payload:e.peekVarUint8Array()}),a){case 0:if(L_(e.decoder,e.encoder,t),r&&i)r(new U_(o).createSyncReplyMessage().writeFirstSyncStepFor(t).toUint8Array());else if(n){let e=new U_(o).createSyncMessage().writeFirstSyncStepFor(t);n.send(e.toUint8Array())}break;case 1:if(n?.readOnly){if(ci(ii(t),g_(e.decoder))){let e=new U_(o).writeSyncStatus(!0);n.send(e.toUint8Array())}else{let e=new U_(o).writeSyncStatus(!1);n.send(e.toUint8Array())}break}R_(e.decoder,t,n?{source:`connection`,connection:n}:this.defaultTransactionOrigin??{source:`local`}),n&&n.send(new U_(o).writeSyncStatus(!0).toUint8Array());break;case 2:if(n?.readOnly){n.send(new U_(o).writeSyncStatus(!1).toUint8Array());break}B_(e.decoder,t,n?{source:`connection`,connection:n}:this.defaultTransactionOrigin??{source:`local`}),n&&n.send(new U_(o).writeSyncStatus(!0).toUint8Array());break;default:throw Error(`Received a message with an unknown type: ${a}`)}return a}applyQueryAwarenessMessage(e,t,n){let r=new U_(t?.messageAddress??e.name).createAwarenessUpdateMessage(e.awareness);n&&n(r.toUint8Array())}},G_=class{get messageAddress(){return this.sessionId?`${this.document.name}\0${this.sessionId}`:this.document.name}constructor(e,t,n,r,i,a=!1,o,s){this.callbacks={onClose:[(e,t)=>{}],beforeHandleMessage:(e,t)=>Promise.resolve(),beforeSync:(e,t)=>Promise.resolve(),statelessCallback:e=>Promise.resolve(),onTokenSyncCallback:e=>Promise.resolve()},this.messageQueue=[],this.processingPromise=Promise.resolve(),this.webSocket=e,this.context=i,this.document=n,this.request=t,this.socketId=r,this.readOnly=a,this.sessionId=o??null,this.providerVersion=s??null,this.document.addConnection(this),this.sendCurrentAwareness()}onClose(e){return this.callbacks.onClose.push(e),this}onStatelessCallback(e){return this.callbacks.statelessCallback=e,this}beforeHandleMessage(e){return this.callbacks.beforeHandleMessage=e,this}beforeSync(e){return this.callbacks.beforeSync=e,this}onTokenSyncCallback(e){return this.callbacks.onTokenSyncCallback=e,this}waitForPendingMessages(){return this.processingPromise}send(e){if(this.webSocket.readyState===Dg.Closing||this.webSocket.readyState===Dg.Closed){this.close();return}try{this.webSocket.send(e)}catch{this.close()}}sendStateless(e){let t=new U_(this.messageAddress).writeStateless(e);this.send(t.toUint8Array())}requestToken(){let e=new U_(this.messageAddress).writeTokenSyncRequest();this.send(e.toUint8Array())}close(e){if(this.document.hasConnection(this)){this.document.removeConnection(this),this.callbacks.onClose.forEach(t=>t(this.document,e));let t=new U_(this.messageAddress);t.writeCloseMessage(e?.reason??`Server closed the connection`),this.send(t.toUint8Array())}}sendCurrentAwareness(){if(!this.document.hasAwarenessStates())return;let e=new U_(this.messageAddress).createAwarenessUpdateMessage(this.document.awareness);this.send(e.toUint8Array())}handleMessage(e){this.messageQueue.push(e),this.messageQueue.length===1&&(this.processingPromise=this.processMessages())}async processMessages(){for(;this.messageQueue.length>0;){let e=this.messageQueue.at(0),t=new b_(e),n=t.readVarString(),r=n.indexOf(`\0`),i=r===-1?n:n.substring(0,r);if(i!==this.document.name){this.messageQueue.shift();continue}t.writeVarString(this.messageAddress);try{await this.callbacks.beforeHandleMessage(this,e),await new W_(t).apply(this.document,this)}catch(e){console.error(`closing connection ${this.socketId} (while handling ${i}) because of exception`,e),this.close({code:`code`in e&&typeof e.code==`number`?e.code:xg.code,reason:`reason`in e?e.reason:xg.reason})}this.messageQueue.shift()}}},K_=class extends Sr{constructor(e,t){super(t),this.callbacks={onUpdate:(e,t,n)=>{},beforeBroadcastStateless:(e,t)=>{}},this.connections=new Map,this.directConnectionsCount=0,this.isDestroyed=!1,this.saveMutex=new Pg,this.lastChangeTime=0,this.name=e,this.awareness=new j_(this),this.awareness.setLocalState(null),this.awareness.on(`update`,this.handleAwarenessUpdate.bind(this)),this.on(`update`,this.handleUpdate.bind(this)),this.isLoading=!0}isEmpty(e){return!this.get(e)._start&&!this.get(e)._map.size}merge(e){return(Array.isArray(e)?e:[e]).forEach(e=>{Rr(this,Vr(e))}),this}onUpdate(e){return this.callbacks.onUpdate=e,this}beforeBroadcastStateless(e){return this.callbacks.beforeBroadcastStateless=e,this}addConnection(e){return this.connections.set(e,{clients:new Set}),this}hasConnection(e){return this.connections.has(e)}removeConnection(e){let t=this.connections.get(e);return t&&M_(this.awareness,Array.from(t.clients),null),this.connections.delete(e),this}addDirectConnection(){return this.directConnectionsCount+=1,this}removeDirectConnection(){return this.directConnectionsCount>0&&--this.directConnectionsCount,this}getConnectionsCount(){return this.connections.size+this.directConnectionsCount}getConnections(){return Array.from(this.connections.keys())}getClients(e){let t=this.connections.get(e);return t?.clients===void 0?new Set:t.clients}hasAwarenessStates(){return this.awareness.getStates().size>0}applyAwarenessUpdate(e,t){return P_(this.awareness,t,e),this}handleAwarenessUpdate({added:e,updated:t,removed:n},r){let i=e.concat(t,n);if(r!==null){let t=this.connections.get(r);t&&(e.forEach(e=>t.clients.add(e)),n.forEach(e=>t.clients.delete(e)))}for(let e of this.getConnections()){let t=new U_(e.messageAddress).createAwarenessUpdateMessage(this.awareness,i);e.send(t.toUint8Array())}return this}handleUpdate(e,t){this.callbacks.onUpdate(this,t,e);for(let t of this.getConnections()){let n=new U_(t.messageAddress).createSyncMessage().writeUpdate(e);t.send(n.toUint8Array())}return this}broadcastStateless(e,t){this.callbacks.beforeBroadcastStateless(this,e),(t?this.getConnections().filter(t):this.getConnections()).forEach(t=>{t.sendStateless(e)})}destroy(){super.destroy(),this.isDestroyed=!0}},q_=`4.0.0-rc.1`;function J_(e){let t=e?.url;return t?t.includes(`://`)?new URL(t).searchParams:new URLSearchParams(t.split(`?`)[1]||``):new URLSearchParams}var Y_=class{constructor(e,t,n,r,i,a={}){this.websocket=e,this.request=t,this.documentProvider=n,this.hooks=r,this.opts=i,this.defaultContext=a,this.documentConnections={},this.incomingMessageQueue={},this.documentConnectionsEstablished=new Set,this.hookPayloads={},this.callbacks={onClose:[(e,t)=>{}]},this.socketId=De.randomUUID(),this.lastMessageReceivedAt=Date.now(),this.check=()=>{Date.now()-this.lastMessageReceivedAt>this.timeout&&this.close(wg)},this.setUpNewConnection=async(e,t,n)=>{let r=this.hookPayloads[e],i=await this.documentProvider.createDocument(t,r.request,r.socketId,r.connectionConfig,r.context),a=this.createConnection(this.websocket,i,r,n,r.providerVersion);if(a.onClose((t,n)=>{delete this.hookPayloads[e],delete this.documentConnections[e],delete this.incomingMessageQueue[e],this.documentConnectionsEstablished.delete(e)}),a.onTokenSyncCallback(async e=>{try{return await this.hooks(`onTokenSync`,{...r,...e,document:i,connection:a,documentName:t},e=>{r.context={...r.context,...e}})}catch(e){console.error(e);let t={...Sg,...e};a.close({code:t.code,reason:t.reason})}}),this.documentConnections[e]=a,this.websocket.readyState===Dg.Closing||this.websocket.readyState===Dg.Closed){this.close();return}this.incomingMessageQueue[e]?.forEach(e=>{a.handleMessage(e)}),await this.hooks(`connected`,{...r,documentName:t,context:r.context,connection:a})},this.handleQueueingMessage=async(e,t,n)=>{try{let r=new b_(e);if(y_(r.decoder),!(v_(r.decoder)===Q.Auth&&!this.documentConnectionsEstablished.has(t))){this.incomingMessageQueue[t].push(e);return}this.documentConnectionsEstablished.add(t),v_(r.decoder);let i=y_(r.decoder),a=null;m_(r.decoder)&&(a=y_(r.decoder));let o=t.indexOf(`\0`),s=o===-1?null:t.substring(o+1),c=t;try{let e=this.hookPayloads[t];e.providerVersion=a,await this.hooks(`onConnect`,{...e,documentName:n},t=>{e.context={...e.context,...t}}),await this.hooks(`onAuthenticate`,{token:i,...e,documentName:n},t=>{e.context={...e.context,...t}}),e.connectionConfig.isAuthenticated=!0;let r=new U_(c).writeAuthenticated(e.connectionConfig.readOnly);this.websocket.send(r.toUint8Array()),await this.setUpNewConnection(t,n,s)}catch(e){let n=e||Cg,r=new U_(c).writePermissionDenied(n.reason??`permission-denied`);this.websocket.send(r.toUint8Array()),this.documentConnectionsEstablished.delete(t),delete this.hookPayloads[t],delete this.incomingMessageQueue[t]}}catch(e){console.error(e),this.websocket.close(xg.code,xg.reason)}},this.handleMessage=e=>{this.lastMessageReceivedAt=Date.now();try{let t=y_(new b_(e).decoder),n=t.indexOf(`\0`),r=n===-1?t:t.substring(0,n),i=this.documentConnections[t]??this.documentConnections[r];if(i){i.handleMessage(e);return}if(this.incomingMessageQueue[t]===void 0){if(this.incomingMessageQueue[t]=[],this.hookPayloads[t])throw Error(`first message, but hookPayloads exists`);this.hookPayloads[t]={instance:this.documentProvider,request:this.request,connectionConfig:{readOnly:!1,isAuthenticated:!1},requestHeaders:this.request.headers,requestParameters:J_(this.request),socketId:this.socketId,context:{...this.defaultContext},providerVersion:null}}this.handleQueueingMessage(e,t,r)}catch(e){console.error(e),this.websocket.close(Sg.code,Sg.reason)}},this.timeout=i.timeout,this.pingInterval=setInterval(this.check,this.timeout)}handleClose(e){this.close(e),clearInterval(this.pingInterval)}close(e){Object.values(this.documentConnections).forEach(t=>t.close(e))}onClose(e){return this.callbacks.onClose.push(e),this}createConnection(e,t,n,r,i){let a=new G_(e,n.request,t,n.socketId,n.context,n.connectionConfig.readOnly,r,i);return a.onClose(async(e,t)=>{await a.waitForPendingMessages();let r={instance:this.documentProvider,clientsCount:e.getConnectionsCount(),context:n.context,document:e,socketId:n.socketId,documentName:e.name,requestHeaders:n.request.headers,requestParameters:J_(n.request)};await this.hooks(`onDisconnect`,r),this.callbacks.onClose.forEach(t=>t(e,r))}),a.onStatelessCallback(async e=>{try{return await this.hooks(`onStateless`,e)}catch(e){if(e?.message)throw e}}),a.beforeHandleMessage((e,r)=>{let i={instance:this.documentProvider,clientsCount:t.getConnectionsCount(),context:n.context,document:t,socketId:n.socketId,connection:e,documentName:t.name,requestHeaders:n.request.headers,requestParameters:J_(n.request),update:r};return this.hooks(`beforeHandleMessage`,i)}),a.beforeSync((e,r)=>{let i={clientsCount:t.getConnectionsCount(),context:n.context,document:t,documentName:t.name,connection:e,type:r.type,payload:r.payload};return this.hooks(`beforeSync`,i)}),a}},X_=class{constructor(e,t,n){this.document=null,this.document=e,this.instance=t,this.context=n??{},this.document.addDirectConnection()}async transact(e){if(!this.document)throw Error(`direct connection closed`);this.document.transact(t=>{e(this.document)},{source:`local`,context:this.context})}async disconnect(){this.document&&=(this.document?.removeDirectConnection(),await this.instance.storeDocumentHooks(this.document,{clientsCount:this.document.getConnectionsCount(),lastContext:this.context,lastTransactionOrigin:{source:`local`,context:this.context},document:this.document,documentName:this.document.name,instance:this.instance},!0),this.document.getConnectionsCount()===0&&!this.document.saveMutex.isLocked()&&(await this.instance.hooks(`onDisconnect`,{instance:this.instance,clientsCount:this.document.getConnectionsCount(),context:this.context,document:this.document,socketId:`server`,documentName:this.document.name,requestHeaders:new Headers,requestParameters:new Ee}),await this.instance.unloadDocument(this.document)),null)}};const Z_=()=>{let e=new Map,t=new Map;return{debounce:async(n,r,i,a)=>{let o=e.get(n),s=o?.start||Date.now(),c=async()=>{t.has(n)&&await t.get(n),e.delete(n);let i=r();t.set(n,i);let a=await i;return t.delete(n),a};if(o?.timeout&&clearTimeout(o.timeout),i===0||Date.now()-s>=a)return c();e.set(n,{start:s,timeout:setTimeout(c,i),func:c})},isDebounced:t=>e.has(t),isCurrentlyExecuting:e=>t.has(e),executeNow:t=>{let n=e.get(t);if(n)return clearTimeout(n.timeout),n.func()}}},Q_={name:null,timeout:6e4,debounce:2e3,maxDebounce:1e4,quiet:!1,yDocOptions:{gc:!0,gcFilter:()=>!0},unloadImmediately:!0};var $_=class{constructor(e){this.configuration={...Q_,extensions:[],onConfigure:()=>new Promise(e=>e(null)),onListen:()=>new Promise(e=>e(null)),onUpgrade:()=>new Promise(e=>e(null)),onConnect:()=>new Promise(e=>e(null)),connected:()=>new Promise(e=>e(null)),beforeHandleMessage:()=>new Promise(e=>e(null)),beforeSync:()=>new Promise(e=>e(null)),beforeBroadcastStateless:()=>new Promise(e=>e(null)),onStateless:()=>new Promise(e=>e(null)),onChange:()=>new Promise(e=>e(null)),onCreateDocument:()=>new Promise(e=>e(null)),onLoadDocument:()=>new Promise(e=>e(null)),onStoreDocument:()=>new Promise(e=>e(null)),afterStoreDocument:()=>new Promise(e=>e(null)),onAwarenessUpdate:()=>new Promise(e=>e(null)),onRequest:()=>new Promise(e=>e(null)),onDisconnect:()=>new Promise(e=>e(null)),onDestroy:()=>new Promise(e=>e(null))},this.loadingDocuments=new Map,this.unloadingDocuments=new Map,this.documents=new Map,this.debouncer=Z_(),e&&this.configure(e)}configure(e){return this.configuration={...this.configuration,...e},this.configuration.extensions.sort((e,t)=>{let n=e.priority===void 0?100:e.priority,r=t.priority===void 0?100:t.priority;return n>r?-1:n<r?1:0}),this.configuration.extensions.push({onConfigure:this.configuration.onConfigure,onListen:this.configuration.onListen,onUpgrade:this.configuration.onUpgrade,onConnect:this.configuration.onConnect,connected:this.configuration.connected,onAuthenticate:this.configuration.onAuthenticate,onTokenSync:this.configuration.onTokenSync,onLoadDocument:this.configuration.onLoadDocument,afterLoadDocument:this.configuration.afterLoadDocument,beforeHandleMessage:this.configuration.beforeHandleMessage,beforeBroadcastStateless:this.configuration.beforeBroadcastStateless,beforeSync:this.configuration.beforeSync,onStateless:this.configuration.onStateless,onChange:this.configuration.onChange,onStoreDocument:this.configuration.onStoreDocument,afterStoreDocument:this.configuration.afterStoreDocument,onAwarenessUpdate:this.configuration.onAwarenessUpdate,onRequest:this.configuration.onRequest,beforeUnloadDocument:this.configuration.beforeUnloadDocument,afterUnloadDocument:this.configuration.afterUnloadDocument,onDisconnect:this.configuration.onDisconnect,onDestroy:this.configuration.onDestroy}),this.hooks(`onConfigure`,{configuration:this.configuration,version:q_,instance:this}),this}getDocumentsCount(){return this.documents.size}getConnectionsCount(){let e=new Set,t=Array.from(this.documents.values()).reduce((t,n)=>(n.getConnections().forEach(({socketId:t})=>{e.add(t)}),t+n.directConnectionsCount),0);return e.size+t}flushPendingStores(){this.documents.forEach(e=>{let t=`onStoreDocument-${e.name}`;!e.isLoading&&this.debouncer.isDebounced(t)&&this.debouncer.executeNow(t)})}closeConnections(e){this.documents.forEach(t=>{e&&t.name!==e||t.connections.forEach((e,t)=>{t.close(xg)})})}handleConnection(e,t,n={}){let r=new Y_(e,t,this,this.hooks.bind(this),{timeout:this.configuration.timeout},n);return r.onClose((e,t)=>{e.getConnectionsCount()>0||(!e.isLoading&&this.debouncer.isDebounced(`onStoreDocument-${e.name}`)?this.configuration.unloadImmediately&&this.debouncer.executeNow(`onStoreDocument-${e.name}`):this.unloadDocument(e))}),r}handleDocumentUpdate(e,t,n){let r=V_(t)&&t.source===`connection`?t.connection:void 0,i=r?.request,a=V_(t)?t.source===`connection`?t.connection.context:t.source===`local`?t.context??{}:{}:{},o={instance:this,clientsCount:e.getConnectionsCount(),document:e,documentName:e.name,requestHeaders:i?.headers??new Headers,requestParameters:J_(i),socketId:r?.socketId??``,update:n,transactionOrigin:t,connection:r,context:a};if(this.hooks(`onChange`,o),H_(t))return;let s={instance:this,clientsCount:e.getConnectionsCount(),document:e,lastContext:a,lastTransactionOrigin:t,documentName:e.name};this.storeDocumentHooks(e,s)}async createDocument(e,t,n,r,i){if(!e.trim())throw Error(`Document name must not be empty`);let a=this.loadingDocuments.get(e);if(a)return a;let o=this.documents.get(e);if(o)return Promise.resolve(o);let s=this.loadDocument(e,t,n,r,i);this.loadingDocuments.set(e,s);try{let t=await s;return this.documents.set(e,t),this.loadingDocuments.delete(e),t}catch(t){throw this.loadingDocuments.delete(e),t}}async loadDocument(e,t,n,r,i){let a=t.headers,o=J_(t),s=i??{},c=await this.hooks(`onCreateDocument`,{documentName:e,requestHeaders:a,requestParameters:o,connectionConfig:r,context:s,socketId:n,instance:this}),l=new K_(e,{...this.configuration.yDocOptions,...c}),u={instance:this,context:s,connectionConfig:r,document:l,documentName:e,socketId:n,requestHeaders:a,requestParameters:o};try{await this.hooks(`onLoadDocument`,u,e=>{e instanceof Sr?Rr(l,Vr(e)):e instanceof Uint8Array&&Rr(l,e)})}catch(t){throw this.closeConnections(e),this.unloadDocument(l),t}return l.isLoading=!1,l.onUpdate((e,t,n)=>{e.lastChangeTime=Date.now(),this.handleDocumentUpdate(e,t,n)}),await this.hooks(`afterLoadDocument`,u),l.beforeBroadcastStateless((e,t)=>{let n={document:e,documentName:e.name,payload:t};this.hooks(`beforeBroadcastStateless`,n)}),l.awareness.on(`update`,(t,n)=>{this.hooks(`onAwarenessUpdate`,{document:l,documentName:e,instance:this,...t,transactionOrigin:n,connection:V_(n)&&n.source===`connection`?n.connection:void 0,awareness:l.awareness,states:Tg(l.awareness.getStates())})}),l}storeDocumentHooks(e,t,n){let r=`onStoreDocument-${e.name}`;return this.debouncer.debounce(r,async()=>{try{await e.saveMutex.runExclusive(async()=>{await this.hooks(`onStoreDocument`,t),await this.hooks(`afterStoreDocument`,t)})}catch(t){if(t instanceof Eg){setTimeout(()=>{this.shouldUnloadDocument(e)&&this.unloadDocument(e)},0);return}console.error(`Caught error during storeDocumentHooks. Document stays in memory to avoid data loss`,t);return}setTimeout(()=>{this.shouldUnloadDocument(e)&&this.unloadDocument(e)},0)},n?0:this.configuration.debounce,this.configuration.maxDebounce)}hooks(e,t,n=null){let{extensions:r}=this.configuration,i=Promise.resolve();return r.filter(t=>typeof t[e]==`function`).forEach(r=>{i=i.then(()=>r[e]?.(t)).catch(t=>{throw t?.message&&console.error(`[${e}]`,t.message),t}),n&&(i=i.then((...e)=>n(...e)))}),i}shouldUnloadDocument(e){return(this.debouncer.isDebounced(`onStoreDocument-${e.name}`)||this.debouncer.isCurrentlyExecuting(`onStoreDocument-${e.name}`)||e.saveMutex.isLocked())===!1&&e.getConnectionsCount()===0}async unloadDocument(e){let t=e.name;if(!this.shouldUnloadDocument(e)||!this.documents.has(t))return;if(this.unloadingDocuments.has(t))return this.unloadingDocuments.get(t);let n=(async()=>{try{await this.hooks(`beforeUnloadDocument`,{instance:this,documentName:t,document:e})}catch{return}this.shouldUnloadDocument(e)&&(this.documents.delete(t),e.destroy(),await this.hooks(`afterUnloadDocument`,{instance:this,documentName:t}))})();this.unloadingDocuments.set(t,Promise.resolve(n)),await n,this.unloadingDocuments.delete(t)}async openDirectConnection(e,t){return new X_(await this.createDocument(e,new Request(`http://localhost`),De.randomUUID(),{isAuthenticated:!0,readOnly:!1},t),this,t)}},ev=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),tv=oe(import.meta.url),nv=ev(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),rv=ev(((e,t)=>{let{EMPTY_BUFFER:n}=nv(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}if(t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=tv(`bufferutil`);t.exports.mask=function(t,n,r,i,o){o<48?a(t,n,r,i,o):e.mask(t,n,r,i,o)},t.exports.unmask=function(t,n){t.length<32?o(t,n):e.unmask(t,n)}}catch{}})),iv=ev(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),av=ev(((e,t)=>{let n=tv(`zlib`),r=rv(),i=iv(),{kStatusCode:a}=nv(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;t.exports=class{constructor(e,t,n){this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,p||=new i(this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit)}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,g),this._inflate.on(`data`,h)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,m)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(e){if(this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(e);return}this[f]=RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})),ov=ev(((e,t)=>{let{isUtf8:n}=tv(`buffer`),{hasBlob:r}=nv(),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=tv(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})),sv=ev(((e,t)=>{let{Writable:n}=tv(`stream`),r=av(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=nv(),{concat:c,toArrayBuffer:l,unmask:u}=rv(),{isValidStatusCode:d,isValidUTF8:f}=ov(),p=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=a;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}}})),cv=ev(((e,t)=>{let{Duplex:n}=tv(`stream`),{randomFillSync:r}=tv(`crypto`),i=av(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=nv(),{isBlob:c,isValidStatusCode:l}=ov(),{mask:u,toBuffer:d}=rv(),f=Symbol(`kByteLength`),p=Buffer.alloc(4),m=8*1024,h,g=m;t.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=s,this[o]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||p,t.generateMask?t.generateMask(n):(g===m&&(h===void 0&&(h=Buffer.alloc(m)),r(h,0,m),g=0),n[0]=h[g++],n[1]=h[g++],n[2]=h[g++],n[3]=h[g++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[f]!==void 0?s=t[f]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(u(e,n,l,a,s),[l]):(u(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=a;else if(typeof t!=`number`||!l(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`?o.write(n,2):o.set(n,2)}let s={[f]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,s),i):this.enqueue([this.dispatch,o,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[i.extensionName],a=t.binary?2:1,o=t.compress,s,l;typeof e==`string`?(s=Buffer.byteLength(e),l=!1):c(e)?(s=e.size,l=!1):(e=d(e),s=e.length,l=d.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,a=0),t.fin&&(this._firstFragment=!0);let u={[f]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:l,rsv1:o};c(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[f],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(_,this,e,i);return}this._bufferedBytes-=r[f];let a=d(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(v,this,e,i)})}dispatch(t,n,r,a){if(!n){this.sendFrame(e.frame(t,r),a);return}let o=this._extensions[i.extensionName];this._bufferedBytes+=r[f],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){_(this,Error(`The socket was closed while data was being compressed`),a);return}this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),a),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function _(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function v(e,t,n){_(e,t,n),e.onerror(t)}})),lv=ev(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=nv(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,`target`,{enumerable:!0}),Object.defineProperty(f.prototype,`type`,{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,`code`,{enumerable:!0}),Object.defineProperty(p.prototype,`reason`,{enumerable:!0}),Object.defineProperty(p.prototype,`wasClean`,{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,`error`,{enumerable:!0}),Object.defineProperty(m.prototype,`message`,{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),uv=ev(((e,t)=>{let{tokenChars:n}=ov();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),dv=ev(((e,t)=>{let n=tv(`events`),r=tv(`https`),i=tv(`http`),a=tv(`net`),o=tv(`tls`),{randomBytes:s,createHash:c}=tv(`crypto`),{Duplex:l,Readable:u}=tv(`stream`),{URL:d}=tv(`url`),f=av(),p=sv(),m=cv(),{isBlob:h}=ov(),{BINARY_TYPES:g,CLOSE_TIMEOUT:_,EMPTY_BUFFER:v,GUID:y,kForOnEventAttribute:b,kListener:x,kStatusCode:S,kWebSocket:C,NOOP:w}=nv(),{EventTarget:{addEventListener:T,removeEventListener:E}}=lv(),{format:D,parse:O}=uv(),{toBuffer:k}=rv(),A=Symbol(`kAborted`),j=[8,13],M=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],ee=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var N=class e extends n{constructor(t,n,r){super(),this._binaryType=g[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=v,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),te(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){g.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new p({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new m(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[C]=this,a[C]=this,t[C]=this,i.on(`conclude`,ae),i.on(`drain`,I),i.on(`error`,oe),i.on(`message`,L),i.on(`ping`,ce),i.on(`pong`,le),a.onerror=R,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,fe),t.on(`data`,pe),t.on(`end`,me),t.on(`error`,he),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){F(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),de(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ie(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||v,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ie(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||v,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ie(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[f.extensionName]||(i.compress=!1),this._sender.send(t||v,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){F(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(N,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(N.prototype,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(N,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(N.prototype,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(N,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(N.prototype,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(N,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),Object.defineProperty(N.prototype,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(N.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(N.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[b])return t[x];return null},set(t){for(let t of this.listeners(e))if(t[b]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[b]:!0})}})}),N.prototype.addEventListener=T,N.prototype.removeEventListener=E,t.exports=N;function te(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_,protocolVersion:j[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!j.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${j.join(`, `)})`);let l;if(t instanceof d)l=t;else try{l=new d(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}l.protocol===`http:`?l.protocol=`ws:`:l.protocol===`https:`&&(l.protocol=`wss:`),e._url=l.href;let u=l.protocol===`wss:`,p=l.protocol===`ws+unix:`,m;if(l.protocol!==`ws:`&&!u&&!p?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?m=`The URL's pathname is empty`:l.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;ne(e,t);return}let h=u?443:80,g=s(16).toString(`base64`),v=u?r.request:i.request,b=new Set,x;if(o.createConnection=o.createConnection||(u?re:P),o.defaultPort=o.defaultPort||h,o.port=l.port||h,o.host=l.hostname.startsWith(`[`)?l.hostname.slice(1,-1):l.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=l.pathname+l.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(x=new f(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=D({[f.extensionName]:x.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!ee.test(e)||b.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);b.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(l.username||l.password)&&(o.auth=`${l.username}:${l.password}`),p){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let S;if(o.followRedirects){if(e._redirects===0){e._originalIpc=p,e._originalSecure=u,e._originalHostOrSocketPath=p?o.socketPath:l.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=p?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:l.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),S=e._req=v(o),e._redirects&&e.emit(`redirect`,e.url,S)}else S=e._req=v(o);o.timeout&&S.on(`timeout`,()=>{F(e,S,`Opening handshake has timed out`)}),S.on(`error`,t=>{S===null||S[A]||(S=e._req=null,ne(e,t))}),S.on(`response`,r=>{let i=r.headers.location,s=r.statusCode;if(i&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){F(e,S,`Maximum redirects exceeded`);return}S.abort();let r;try{r=new d(i,t)}catch{ne(e,SyntaxError(`Invalid URL: ${i}`));return}te(e,r,n,a)}else e.emit(`unexpected-response`,S,r)||F(e,S,`Unexpected server response: ${r.statusCode}`)}),S.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==N.CONNECTING)return;S=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){F(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+y).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){F(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],l;if(s===void 0?b.size&&(l=`Server sent no subprotocol`):b.size?b.has(s)||(l=`Server sent an invalid subprotocol`):l=`Server sent a subprotocol but none was requested`,l){F(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!x){F(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=O(u)}catch{F(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){F(e,n,`Server indicated an extension that was not requested`);return}try{x.accept(t[f.extensionName])}catch{F(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[f.extensionName]=x}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(S,e):S.end()}function ne(e,t){e._readyState=N.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function P(e){return e.path=e.socketPath,a.connect(e)}function re(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function F(e,t,n){e._readyState=N.CLOSING;let r=Error(n);Error.captureStackTrace(r,F),t.setHeader?(t[A]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(ne,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function ie(e,t,n){if(t){let n=h(t)?t.size:k(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${M[e.readyState]})`);process.nextTick(n,t)}}function ae(e,t){let n=this[C];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[C]!==void 0&&(n._socket.removeListener(`data`,pe),process.nextTick(ue,n._socket),e===1005?n.close():n.close(e,t))}function I(){let e=this[C];e.isPaused||e._socket.resume()}function oe(e){let t=this[C];t._socket[C]!==void 0&&(t._socket.removeListener(`data`,pe),process.nextTick(ue,t._socket),t.close(e[S])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function se(){this[C].emitClose()}function L(e,t){this[C].emit(`message`,e,t)}function ce(e){let t=this[C];t._autoPong&&t.pong(e,!this._isServer,w),t.emit(`ping`,e)}function le(e){this[C].emit(`pong`,e)}function ue(e){e.resume()}function R(e){let t=this[C];t.readyState!==N.CLOSED&&(t.readyState===N.OPEN&&(t._readyState=N.CLOSING,de(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function de(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function fe(){let e=this[C];if(this.removeListener(`close`,fe),this.removeListener(`data`,pe),this.removeListener(`end`,me),e._readyState=N.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[C]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,se),e._receiver.on(`finish`,se))}function pe(e){this[C]._receiver.write(e)||this.pause()}function me(){let e=this[C];e._readyState=N.CLOSING,e._receiver.end(),this.end()}function he(){let e=this[C];this.removeListener(`error`,he),this.on(`error`,w),e&&(e._readyState=N.CLOSING,this.destroy())}})),fv=ev(((e,t)=>{dv();let{Duplex:n}=tv(`stream`);function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})),pv=ev(((e,t)=>{let{tokenChars:n}=ov();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),mv=ev(((e,t)=>{let n=tv(`events`),r=tv(`http`),{Duplex:i}=tv(`stream`),{createHash:a}=tv(`crypto`),o=uv(),s=av(),c=pv(),l=dv(),{CLOSE_TIMEOUT:u,GUID:d,kWebSocket:f}=nv(),p=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:u,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=m(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(h,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(h,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{h(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,g);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){v(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){v(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!p.test(i)){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){_(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{v(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&f!==void 0){let n=new s(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=o.parse(f);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{v(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${l===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return _(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return _(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[f])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return _(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+d).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
67
+ `)){if(i(e))continue;let t=e.match(/^(#{1,6})\s+(.+)$/);if(t){let e=t[2].trim(),i=b(e,r);i&&n.push({level:t[1].length,text:e,slug:i})}}return n}function eg(e){return!(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))}function tg(e){let{hocuspocus:t,sessionManager:n,contentDir:r,getFileIndex:i,getAliasMap:a,enableTestRoutes:o=!1,shadowRef:s,flushGitCommit:l,getCurrentBranch:d,contentRoot:f,backlinkIndex:m,signalChannel:h,agentFocusBroadcaster:g,onAgentWrite:_,getSyncEngine:y,localOpCliArgs:b=[`open-knowledge`],projectDir:x}=e,S=km();function C(e){if(!eg(e))return null;let t=V(r),n=V(t,`${e}${Mf(e)}`);return!n.startsWith(`${t}/`)&&n!==t?null:n}function w(e){let t=C(e);if(!t||!L(t))return e;try{return _f(R(t,`utf-8`),e)}catch{return e}}let T={cluster:void 0,category:void 0,tags:void 0};function E(e){try{let n=t.documents.get(e);if(n){let e=n.getMap(`metadata`).get(`frontmatter`);if(typeof e==`string`&&e)return vf(e)}}catch{}try{let t=C(e);if(!t||!L(t))return T;let{frontmatter:n}=A(R(t,`utf-8`));return n?vf(n):T}catch{return T}}function D(e){if(m)try{if(m.getBacklinks(e).length>0)return;let t=performance.now(),n=af(e,i()),r=performance.now()-t;return r>5&&Rh.debug({docName:e,elapsedMs:r,candidateCount:n.length},`[orphan-hint] findHubCandidates slow`),n.length===0?void 0:[{type:`orphan`,parentCandidates:n,message:`This doc has no backlinks yet. To make it discoverable, consider linking from a parent hub doc (index/overview files in the folder tree): ${n.map(e=>`[[${e}]]`).join(`, `)}.`}]}catch(e){console.warn(`[orphan-hint] computeOrphanHints failed:`,e);return}}function O(e){return a?.().get(e)??e}function k(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function j(e,n){let r=`onStoreDocument-${e}`;(t.debouncer.isDebounced(r)?t.debouncer.executeNow(r):Promise.resolve()).then(()=>l?.()).catch(e=>{Rh.warn({err:e},`[${n}] post-write flush failed`)})}function M(){let e=new Set;for(let[t,n]of i()){e.add(t);for(let t of n.aliases)e.add(t)}return e}function ee(){let e=Promise.resolve();return async function(t){let n=e,r=()=>{};e=new Promise(e=>{r=e}),await n;try{return await t()}finally{r()}}}let N=ee();function te(e){return e instanceof Error&&(e.message===`Managed rename requires backlink index support`||e.message.startsWith(`Cannot rename missing document:`)||e.message.startsWith(`symlink-escape:`))?e.message:`Failed to rename document`}async function ne(e){let r=new Map;for(let n of e){let e=t.documents.get(n);e&&r.set(n,e.getText(`source`).toString())}for(let t of e)await n.closeAllForDoc(t).catch(e=>{console.warn(`[file-ops] Failed to close agent session for ${t}:`,e)});for(let n of e){let e=t.documents.get(n);Hp(n),e&&(t.closeConnections(n),await t.unloadDocument(e))}return r}function P(e,t){for(let{fromDocName:n,toDocName:i}of e){let e=Pp(i,r),a=t.get(n);typeof a==`string`&&z(e,a,`utf-8`);let o=typeof a==`string`?a:L(e)?R(e,`utf-8`):null;typeof o==`string`&&nm(e,im(o))}}function F(e,t){return e.map(e=>{let n=t.get(e);if(typeof n==`string`)return{docName:e,content:n};let i=Pp(e,r);if(!L(i))throw Error(`Cannot snapshot missing document: ${e}`);return{docName:e,content:R(i,`utf-8`)}})}function ie(e){let n=t.documents.get(e);if(n)return n.getText(`source`).toString();let i=Zh(r,`file`,e);return L(i)?R(i,`utf-8`):null}function I(e,t){let n=Zh(r,`file`,e);le(xe(n),{recursive:!0}),z(n,t,`utf-8`),nm(n,im(t)),Vp(e,t);let a=i();a instanceof Map&&pm({kind:`update`,path:n,docName:e,content:t},a)}function oe(e,n,r){let i=t.documents.get(e);if(!i)throw Error(`Document is not loaded: ${e}`);let a={markdown:``,rewrites:0};return i.transact(()=>{let t=i.getXmlFragment(`default`),o=i.getText(`source`),s=o.toString();if(a=Yh(s,e,n,r),a.rewrites===0)return;let{body:c}=A(a.markdown),l=nl.parseWithFallback(c);ds(i,t,rl.nodeFromJSON(l),{mapping:new Map,isOMark:new Map}),p(o,s,a.markdown)},Lh),a}async function se(e,n){return N(async()=>{if(!m)throw Error(`Managed rename requires backlink index support`);let a=Zh(r,`file`,e),o=Zh(r,`file`,n),s=[{fromDocName:e,toDocName:n}],c=[...new Set(m.getBacklinks(e).map(e=>e.source))].sort((e,t)=>e.localeCompare(t)),l=new Map,u=[],d=[];for(let t of[e,...c]){if(l.has(t))continue;let n=ie(t);typeof n==`string`?(l.set(t,n),t!==e&&u.push(t)):t!==e&&d.push(t)}if(typeof l.get(e)!=`string`)throw Error(`Cannot rename missing document: ${e}`);let f=Pm({sourceDocName:e,destinationDocName:n,snapshots:F([...l.keys()],l)}),p=[];return await Bm(r,f,async()=>{for(let e of d)m.deleteDocument(e);for(let r of u){let i=t.documents.get(r)?oe(r,e,n):Yh(l.get(r)??``,r,e,n);i.rewrites>0&&(I(r,i.markdown),p.push({docName:r,rewrites:i.rewrites})),m.updateDocumentFromMarkdown(r,i.markdown)}let r=Yh((await ne([e])).get(e)??l.get(e)??R(a,`utf-8`),e,e,n);le(xe(o),{recursive:!0}),pe(a,o),P(s,new Map([[e,r.markdown]])),Vp(n,r.markdown);let c=i();c instanceof Map&&pm({kind:`rename`,oldPath:a,newPath:o,oldDocName:e,newDocName:n,content:r.markdown},c),m.renameDocument(e,n,r.markdown),r.rewrites>0&&p.push({docName:n,rewrites:r.rewrites})}),m.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist managed rename cache for ${e} -> ${n}:`,t)}),h?.(`files`),h?.(`backlinks`),h?.(`graph`),p.sort((e,t)=>e.docName.localeCompare(t.docName)),{renamed:s,rewrittenDocs:p}})}let ce=/^[a-zA-Z0-9_-]+$/;function ue(e){let t=typeof e.agentId==`string`?e.agentId:void 0;t!==void 0&&!ce.test(t)&&(t=void 0);let n=t?`agent-${t}`:`claude-1`,r=typeof e.agentName==`string`?e.agentName.slice(0,128).replace(/[\r\n]/g,``):`Claude`,i=typeof e.clientName==`string`?e.clientName:void 0;i!==void 0&&(i=i.slice(0,128).replace(/[\r\n]/g,``));let a=typeof e.colorSeed==`string`&&e.colorSeed.length>0?e.colorSeed.slice(0,128):t??n;return{rawAgentId:t,agentId:n,agentName:r,colorSeed:a,clientName:i}}async function _e(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await Qh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=r.length>0?JSON.parse(r.toString()):{}}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}let a=typeof i.docName==`string`&&i.docName.length>0?i.docName:`test-doc`;if(!eg(a)){J(t,400,{ok:!1,error:`Invalid docName`});return}let o=O(a);if(q(o)){J(t,400,{ok:!1,error:`'${o}' is a reserved document name`});return}let{agentId:s,agentName:c,colorSeed:l,clientName:u}=ue(i),d=await n.getSession(o,s,{displayName:c,colorSeed:l,clientName:u}),f=new Date().toISOString(),p=typeof i.content==`string`?i.content:`Hello from the agent! ${f}`;d.document.awareness.setLocalStateField(`mode`,`editing`);try{d.document.transact(()=>{sl(d.document,`${p}\n`,`append`),d.document.getMap(`activity`).set(s,{agentId:s,timestamp:Date.now(),type:`insert`,description:`Added (${c}): ${p.slice(0,50)}`})},al),$d(o,s,c,l)}finally{d.document.awareness.setLocalStateField(`mode`,`idle`)}j(o,`agent-write`),J(t,200,{ok:!0,timestamp:f})}catch(e){Rh.error({err:e},`[agent-write] handler failed`),J(t,500,{ok:!1,error:`Internal server error`})}}async function ve(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await Qh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(r.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){J(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{markdown:a,position:o}=i;if(!a||typeof a!=`string`){J(t,400,{ok:!1,error:`markdown field required`});return}let s=o===`prepend`?`prepend`:o===`replace`?`replace`:`append`,c=i.docName,l=typeof c==`string`&&c.length>0?c:`test-doc`;if(!eg(l)){J(t,400,{ok:!1,error:`Invalid docName`});return}let u=O(l);if(q(u)){J(t,400,{ok:!1,error:`'${u}' is a reserved document name`});return}let{agentId:d,agentName:f,colorSeed:p,clientName:m}=ue(i),h=await n.getSession(u,d,{displayName:f,colorSeed:p,clientName:m}),v=new Date().toISOString();h.document.awareness.setLocalStateField(`mode`,`editing`);try{h.document.transact(()=>{sl(h.document,a,s),h.document.getMap(`activity`).set(d,{agentId:d,timestamp:Date.now(),type:`insert`,description:`Added (${f}): ${a.trim().slice(0,50)}`})},al),$d(u,d,f,p)}finally{h.document.awareness.setLocalStateField(`mode`,`idle`)}j(u,`agent-write-md`),g?.setFocus(d,{agentName:f,currentDoc:u,writeKind:`write`,ts:Date.now()}),_?.();let y=D(u);J(t,200,{ok:!0,timestamp:v,subscriberCount:k(u),...y?{hints:y}:{}})}catch(e){Rh.error({err:e},`[agent-write-md] handler failed`),J(t,500,{ok:!1,error:`Internal server error`})}}async function ye(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!eg(r)){J(t,400,{ok:!1,error:`Invalid docName`});return}let i=O(r);if(q(i)){J(t,400,{ok:!1,error:`'${i}' is a reserved document name`});return}J(t,200,{ok:!0,docName:i,content:(await n.getSession(i)).document.getText(`source`).toString()})}catch(e){console.error(`[document-read]`,e),J(t,500,{ok:!1,error:`Internal server error`})}}async function be(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`dir`);if(n)try{Gh(r,n)}catch{J(t,400,{ok:!1,error:`Invalid directory parameter`});return}let a=i(),o=[];for(let[e,t]of a)if(!(n&&!e.startsWith(`${n}/`)&&e!==n)){o.push({docName:e,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let i of t.aliases){if(n&&!i.startsWith(`${n}/`)&&i!==n)continue;let a=B(r,t.canonicalPath);o.push({docName:i,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:a})}}o.sort((e,t)=>e.docName.localeCompare(t.docName)),J(t,200,{ok:!0,documents:o})}catch(e){console.error(`[document-list]`,e),J(t,500,{ok:!1,error:`Internal server error`})}}async function Se(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){J(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!eg(n)){J(t,400,{ok:!1,error:`Invalid docName`});return}J(t,200,{ok:!0,docName:n,backlinks:m.getBacklinks(n).map(e=>({source:e.source,anchor:e.anchor,title:w(e.source),snippet:e.snippet}))})}catch(e){console.error(`[backlinks]`,e),J(t,500,{ok:!1,error:`Failed to read backlinks`})}}async function Ce(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!n){J(t,400,{ok:!1,error:`Missing docNames parameter`});return}let r={};for(let e of n.split(`,`)){let t=e.trim();!t||!eg(t)||(r[t]=m.getBacklinkCount(t))}J(t,200,{ok:!0,counts:r})}catch(e){console.error(`[backlink-counts]`,e),J(t,500,{ok:!1,error:`Failed to read backlink counts`})}}async function we(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){J(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!eg(n)){J(t,400,{ok:!1,error:`Invalid docName`});return}J(t,200,{ok:!0,docName:n,forwardLinks:m.getForwardLinkEntries(n).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:w(e.target),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})})}catch(e){console.error(`[forward-links]`,e),J(t,500,{ok:!1,error:`Failed to read forward links`})}}async function Ee(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`docName`);if(r&&!eg(r)){J(t,400,{ok:!1,error:`Invalid docName`});return}let i=n.searchParams.get(`degrees`);if(i&&!r){J(t,400,{ok:!1,error:`docName is required when degrees is provided`});return}let a,o;if(i&&r){let e=Number.parseInt(i,10);if(!Number.isFinite(e)||e<0){J(t,400,{ok:!1,error:`degrees must be a non-negative integer`});return}({nodes:a,links:o}=m.getLinkGraphNeighborhood(r,e))}else ({nodes:a,links:o}=m.getLinkGraph());J(t,200,{ok:!0,nodes:a.map(e=>{if(e.kind===`doc`){let t=E(e.docName);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:w(e.docName),cluster:t.cluster??null,category:t.category??null,tags:t.tags??null}}return{id:e.id,kind:`external`,url:e.url,label:e.label??e.url}}),links:o})}catch(e){console.error(`[link-graph]`,e),J(t,500,{ok:!1,error:`Failed to read link graph`})}}async function De(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!v(n)){J(t,400,{ok:!1,error:`Invalid orphan mode. Allowed values: incoming, outgoing, both`});return}J(t,200,{ok:!0,orphans:m.getOrphans([...i().keys()],n).map(e=>({docName:e,title:w(e)}))})}catch(e){console.error(`[orphans]`,e),J(t,500,{ok:!1,error:`Failed to read orphan pages`})}}async function Oe(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),r=n?Number.parseInt(n,10):20,i=Number.isFinite(r)&&r>0?r:20;J(t,200,{ok:!0,hubs:m.getHubs(i).map(e=>({docName:e.docName,title:w(e.docName),count:e.count}))})}catch(e){console.error(`[hubs]`,e),J(t,500,{ok:!1,error:`Failed to read hub pages`})}}async function ke(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.getAll(`sourceDocName`);if(n.some(e=>e.length===0||!eg(e))){J(t,400,{ok:!1,error:`Invalid sourceDocName`});return}let r=n.length?[...new Set(n.map(e=>O(e)))]:void 0;J(t,200,{ok:!0,deadLinks:m.getDeadLinks(M(),r).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:w(e.source),snippet:e.snippet}))}))})}catch(e){console.error(`[dead-links]`,e),J(t,500,{ok:!1,error:`Failed to read dead links`})}}async function Ae(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await Qh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(r.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){J(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{find:a,replace:o,docName:s,offset:c}=i;if(typeof a!=`string`||a.length===0){J(t,400,{ok:!1,error:`find field required`});return}if(typeof o!=`string`){J(t,400,{ok:!1,error:`replace field required`});return}let l=Object.hasOwn(i,`offset`),d;if(l){if(typeof c!=`number`||!Number.isInteger(c)||c<0){J(t,400,{ok:!1,error:`offset must be a non-negative integer`});return}d=c}let f=typeof s==`string`&&s.length>0?s:`test-doc`;if(!eg(f)){J(t,400,{ok:!1,error:`Invalid docName`});return}let p=O(f);if(q(p)){J(t,400,{ok:!1,error:`'${p}' is a reserved document name`});return}let{agentId:m,agentName:h,colorSeed:v,clientName:y}=ue(i),b=await n.getSession(p,m,{displayName:h,colorSeed:v,clientName:y}),x=new Date().toISOString(),S=!1,C=!1;b.document.awareness.setLocalStateField(`mode`,`editing`);try{b.document.transact(()=>{let e=b.document.getXmlFragment(`default`),t=b.document.getMap(`metadata`),n=t.get(`frontmatter`)??``,r=u(n,nl.serialize(ms(e,rl).toJSON())),i=d==null?r.indexOf(a):r.slice(d,d+a.length)===a?d:-1;if(i===-1){d==null?S=!0:C=!0;return}let{frontmatter:s,body:c}=A(r.slice(0,i)+o+r.slice(i+a.length));s!==n&&t.set(`frontmatter`,s),sl(b.document,c,`replace`),b.document.getMap(`activity`).set(m,{agentId:m,timestamp:Date.now(),type:`insert`,description:`Patched (${h}): ${a.slice(0,50)}`})},al),!S&&!C&&$d(p,m,h,v)}finally{b.document.awareness.setLocalStateField(`mode`,`idle`)}if(C){J(t,409,{ok:!1,error:`Target text no longer matches at the requested offset`});return}if(S){J(t,404,{ok:!1,error:`Text not found in document`});return}j(p,`agent-patch`),g?.setFocus(m,{agentName:h,currentDoc:p,writeKind:`edit`,ts:Date.now()}),_?.(),J(t,200,{ok:!0,timestamp:x,subscriberCount:k(p)})}catch(e){Rh.error({err:e},`[agent-patch] handler failed`),J(t,500,{ok:!1,error:`Internal server error`})}}async function je(e,i){if(e.method!==`POST`){i.writeHead(405),i.end(`Method not allowed`);return}try{let a=O(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??`test-doc`),o;try{o=Pp(a,r)}catch(e){console.error(`[test-reset] safeContentPath rejected docName:`,a,e),J(i,400,{ok:!1,error:`Invalid docName`});return}await n.closeAll(a),t.closeConnections(a);let s=`onStoreDocument-${a}`;t.debouncer.isDebounced(s)&&await t.debouncer.executeNow(s);let c=t.documents.get(a);c&&await t.unloadDocument(c),z(o,``,`utf-8`),m&&(m.deleteDocument(a),m.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-reset for ${a}:`,e)}),h?.(`backlinks`),h?.(`graph`)),h?.(`files`),J(i,200,{ok:!0})}catch(e){console.error(`[test-reset]`,e),J(i,500,{ok:!1,error:`Internal server error`})}}async function Ne(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{if(!m){J(t,503,{ok:!1,error:`Backlink index not configured`});return}m.rebuildFromDisk(),m.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist cache after test-rescan-backlinks:`,e)}),h?.(`backlinks`),h?.(`graph`),J(t,200,{ok:!0})}catch(e){console.error(`[test-rescan-backlinks]`,e),J(t,500,{ok:!1,error:`Internal server error`})}}async function Fe(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}let n=s?.current;if(!n){J(t,400,{ok:!1,error:`Shadow repo not configured`});return}try{let r;try{r=await Qh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let i=/^[a-zA-Z0-9_-]+$/,a=[],o;if(r.length>0){let e;try{e=JSON.parse(r.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}typeof e.message==`string`&&e.message.trim()&&(o=e.message.replace(/[\r\n]/g,` `).slice(0,256)),Array.isArray(e.writers)&&(a=e.writers.map(e=>{let t=e.id??`unknown`;if(!i.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}}))}a.length===0&&(a=[{id:`server`,name:`openknowledge-server`,email:`noreply@openknowledge.local`}]);let s=f??`content`,c=await Mp(n,s,a);console.log(`[shadow] checkpoint ${c.checkpointRef}`);let l;if(x)try{l=await ae(async()=>{let e=Pe({baseDir:x,timeout:{block:15e3}}),t=(await e.tags([`--list`,`ok/v*`])).all.length+1,n=`ok/v${t}`,r=o??`Checkpoint v${t}`,i=s||`.`;return await e.add(i),await e.commit(r,{"--allow-empty":null}),await e.addTag(n),console.log(`[checkpoint] parent-git commit + tag ${n}`),n})}catch(e){console.warn(`[checkpoint] parent-git commit failed (non-fatal):`,e)}J(t,200,{ok:!0,checkpointRef:c.checkpointRef,...l?{versionTag:l}:{}})}catch(e){console.error(`[save-version]`,e),J(t,500,{ok:!1,error:`Internal server error`})}}async function Ie(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=s?.current;if(!n){J(t,400,{ok:!1,error:`Shadow repo not configured`});return}let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=r.searchParams.get(`docName`)??``,a=r.searchParams.get(`branch`)??d?.()??`main`;if(!i){J(t,400,{ok:!1,error:`docName query parameter is required`});return}if(a.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(a)){J(t,400,{ok:!1,error:`Invalid branch name`});return}let o=Number(r.searchParams.get(`limit`)??`50`),c=Number(r.searchParams.get(`offset`)??`0`),l=Math.min(200,Number.isFinite(o)?o:50),u=Number.isFinite(c)?c:0,p=r.searchParams.get(`type`)??void 0,m=r.searchParams.get(`author`)??void 0,h=r.searchParams.get(`excludeAuthor`)??void 0,g=Date.now();try{let e=await Ph(n,{docName:i,branch:a,limit:l,offset:u,type:p,author:m,excludeAuthor:h},f??`content`),r=Date.now()-g;console.log(`[timeline] query docName=${i} entries=${e.entries.length} duration=${r}ms`),J(t,200,{ok:!0,...e})}catch(e){console.error(`[history]`,e),J(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function Le(e,t,n){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let r=s?.current;if(!r){J(t,400,{ok:!1,error:`Shadow repo not configured`});return}let i=zh(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,f??`content`);if(`error`in i){J(t,400,{ok:!1,error:i.error});return}let a=i.path,o=bp(r);if(!/^[0-9a-f]{40}$/i.test(n)){J(t,400,{ok:!1,error:`Invalid commit SHA`});return}try{try{await o.raw(`cat-file`,`-e`,`${n}:${a}`)}catch{J(t,404,{ok:!1,error:`Document did not exist at this version`});return}let e=await o.raw(`show`,`${n}:${a}`),[r=``,i=``]=(await o.raw(`log`,`-1`,`--format=%aI%x00%an`,n)).trim().split(`\0`);J(t,200,{ok:!0,sha:n,content:e,timestamp:r,author:i})}catch(e){console.error(`[history-version]`,e),J(t,500,{ok:!1,error:`Internal server error`})}}async function Re(e,n){if(e.method!==`GET`){n.writeHead(405),n.end(`Method not allowed`);return}let r=s?.current;if(!r){J(n,400,{ok:!1,error:`Shadow repo not configured`});return}let i=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),a=i.searchParams.get(`docName`)??``,o=i.searchParams.get(`from`)??``,c=i.searchParams.get(`to`)??``;if(!c||!/^[0-9a-f]{40}$/i.test(c)){J(n,400,{ok:!1,error:`'to' must be a valid 40-char commit SHA`});return}let l=zh(a,f??`content`);if(`error`in l){J(n,400,{ok:!1,error:l.error});return}let u=l.path,d=bp(r);try{let e;try{e=await d.raw(`show`,`${c}:${u}`)}catch{J(n,404,{ok:!1,error:`Document did not exist at the target version`});return}let r;if(o&&/^[0-9a-f]{40}$/i.test(o))try{r=await d.raw(`show`,`${o}:${u}`)}catch{J(n,404,{ok:!1,error:`Document did not exist at the source version`});return}else{let e=t.documents.get(a);if(!e){J(n,409,{ok:!1,error:`Document is not currently open — open it in the editor first`});return}r=e.getText(`source`).toString()}let i=A(r).body,s=A(e).body,l=jl(i,s),f=[],p=0,m=0;for(let e of l){let t=e.value.replace(/\n$/,``).split(`
68
+ `),n=e.added?`added`:e.removed?`removed`:`unchanged`;for(let e of t)f.push({type:n,text:e});e.added&&(p+=t.length),e.removed&&(m+=t.length)}J(n,200,{ok:!0,lines:f,additions:p,deletions:m})}catch(e){console.error(`[diff]`,e),J(n,500,{ok:!1,error:`Internal server error`})}}async function ze(e,n){if(e.method!==`POST`){n.writeHead(405),n.end(`Method not allowed`);return}let r=s?.current;if(!r){J(n,400,{ok:!1,error:`Shadow repo not configured`});return}let i;try{i=await Qh(e)}catch{J(n,413,{ok:!1,error:`Payload too large`});return}let a;try{a=i.length>0?JSON.parse(i.toString()):{}}catch{J(n,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){J(n,400,{ok:!1,error:`Body must be a JSON object`});return}let{docName:o,commitSha:c,versionTag:u}=a,d=typeof o==`string`?o:``,p=typeof c==`string`?c:``,m=typeof u==`string`?u:void 0;if(!d){J(n,400,{ok:!1,error:`docName required`});return}if(!p||!/^[0-9a-f]{40}$/i.test(p)){J(n,400,{ok:!1,error:`commitSha must be a valid 40-char commit SHA`});return}let h=f??`content`,g=zh(d,h);if(`error`in g){J(n,400,{ok:!1,error:g.error});return}let _=g.path,v=bp(r),y=Date.now();try{try{await v.raw(`cat-file`,`-e`,`${p}:${_}`)}catch{J(n,404,{ok:!1,error:`Document did not exist at this version`});return}let e=await v.raw(`show`,`${p}:${_}`),i=new Date().toISOString();await Dp(r,h,{action:`rollback`,context:{docName:d,targetSha:p}});let a=t.documents.get(d);if(!a){J(n,409,{ok:!1,error:`Document is not currently open — open it in the editor first`});return}let{frontmatter:o,body:s}=A(e),c=nl.parseWithFallback(s),u=rl.nodeFromJSON(c),g=a.getXmlFragment(`default`);a.transact(()=>{ds(a,g,u,{mapping:new Map,isOMark:new Map});let t=a.getText(`source`),n=t.toString();n!==e&&(t.delete(0,n.length),t.insert(0,e)),a.getMap(`metadata`).set(`frontmatter`,o)},Ih),Vp(d,e),l&&l().catch(e=>{console.warn(`[rollback] flush git commit failed:`,e)});let b=Date.now()-y;if(console.log(`[rollback] docName=${d} from=${p.slice(0,8)} duration=${b}ms`),x){let e=`Restored to ${m??p.slice(0,8)}: ${d}`,t=f??`content`;ae(async()=>{let n=Pe({baseDir:x,timeout:{block:15e3}}),r=t||`.`;await n.add(r),await n.commit(e,{"--allow-empty":null}),console.log(`[rollback] parent-git commit: ${e}`)}).catch(e=>{console.warn(`[rollback] parent-git commit failed (non-fatal):`,e)})}J(n,200,{ok:!0,restoredFrom:p,timestamp:i})}catch(e){console.error(`[rollback]`,e),J(n,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function Be(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}J(t,200,el())}async function Ve(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}J(t,200,c())}async function He(e,t){if(!Am(e.socket.remoteAddress)){J(t,403,{ok:!1,error:`loopback-required`});return}if(!jm(e.headers.host)){J(t,403,{ok:!1,error:`host-header-not-allowed`});return}if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=V(r),i=n,a=!0;try{i=fe(n)}catch(e){let r=e?.code;if(r===`ENOENT`)console.warn(`[workspace] contentDir does not exist; returning unresolved path`,{path:n}),a=!1;else{console.warn(`[workspace] realpath failed for contentDir`,{path:n,err:e}),J(t,500,{ok:!1,error:`workspace-realpath-failed`,code:r??null});return}}J(t,200,{ok:!0,contentDir:i,pathSeparator:Te,symlinkResolved:a})}let Ue=1440*60*1e3;async function We(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}if(!s?.current){J(t,200,[]);return}let n=Date.now(),r=[],i=V(s.current.gitDir,`rescue`);if(L(i))try{let e=de(i).filter(e=>Df(e));for(let t of e){let e=V(i,t),a=he(e);if(n-a.mtimeMs>Ue){try{ge(e)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}r.push({docName:Of(t),timestamp:a.mtime.toISOString(),size:a.size,source:`flat`})}}catch(e){console.error(`[rescue] Failed to list flat-file rescue buffers:`,e)}try{let e=d?.()??`main`,t=await kp(s.current,e);for(let e of t)r.push({...e,source:`timeline`})}catch(e){console.error(`[rescue] Failed to list timeline-ref rescue checkpoints:`,e)}J(t,200,r)}async function Ge(e,t,n){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}if(!s?.current){t.writeHead(404),t.end(`Not found`);return}let r=V(s.current.gitDir,`rescue`),i=V(r,`${n}${Mf(n)}`);if(!i.startsWith(`${r}/`)){t.writeHead(400),t.end(`Invalid document name`);return}if(L(i)){let e=he(i);if(Date.now()-e.mtimeMs>Ue)try{ge(i)}catch{}else{let e=R(i,`utf-8`);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(e);return}}try{let e=d?.()??`main`,r=(await kp(s.current,e)).filter(e=>e.docName===n).sort((e,t)=>t.timestamp.localeCompare(e.timestamp))[0];if(r){let e=bp(s.current),n=((await e.raw(`ls-tree`,`-r`,r.sha)).trim().split(`
69
+ `)[0]??``).split(/\s+/)[2];if(n){let r=await e.raw(`cat-file`,`-p`,n);t.writeHead(200,{"Content-Type":`text/markdown`,"X-Content-Type-Options":`nosniff`}),t.end(r);return}}}catch(e){console.warn(`[rescue] timeline-ref fallback failed:`,e)}t.writeHead(404),t.end(`Not found`)}async function Ke(e,t){if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await Qh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let a;try{a=JSON.parse(n.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){J(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{path:o}=a;if(!o||typeof o!=`string`||o.length===0){J(t,400,{ok:!1,error:`path is required`});return}if(!Df(o)){J(t,400,{ok:!1,error:`path must end with .md or .mdx`});return}if(o.includes(`..`)||o.startsWith(`/`)||o.includes(`\0`)||o.includes(`\\`)){J(t,400,{ok:!1,error:`path must not contain .. or start with /`});return}let s=V(r),c=V(s,o);if(!c.startsWith(`${s}/`)&&c!==s){J(t,400,{ok:!1,error:`path must not escape content directory`});return}let l=Of(o);if(q(l)){J(t,400,{ok:!1,error:`'${l}' is a reserved document name`});return}le(xe(c),{recursive:!0});try{z(c,``,{encoding:`utf-8`,flag:`wx`})}catch(e){if(e.code===`EEXIST`){J(t,409,{ok:!1,error:`File already exists`});return}throw e}let u=Of(o),d=typeof i==`function`?i():null;d instanceof Map&&pm({kind:`create`,path:c,docName:u,content:``},d),m&&(m.updateDocumentFromMarkdown(u,``),m.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${u}:`,e)}),h?.(`backlinks`),h?.(`graph`)),h?.(`files`),J(t,200,{ok:!0,docName:u})}catch(e){console.error(`[create-page]`,e),J(t,500,{ok:!1,error:`Failed to create page`})}}async function qe(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n||typeof n!=`string`||n.length===0){J(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!eg(n)){J(t,400,{ok:!1,error:`Invalid docName`});return}let r=C(n);if(!r){J(t,400,{ok:!1,error:`Invalid docName`});return}if(!L(r)){J(t,404,{ok:!1,error:`Page not found`});return}J(t,200,{ok:!0,docName:n,headings:$h(R(r,`utf-8`))})}catch(e){console.error(`[page-headings]`,e),J(t,500,{ok:!1,error:`Failed to read headings`})}}async function Je(e,t){if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await Qh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(n.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){J(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{docName:a,newDocName:o}=i;if(typeof a!=`string`||typeof o!=`string`){J(t,400,{ok:!1,error:`docName and newDocName are required`});return}if(!Kh(a)||!Kh(o)){J(t,400,{ok:!1,error:`Document names must be relative content paths`});return}if(q(a)||q(o)){J(t,400,{ok:!1,error:`Reserved document names cannot be renamed`});return}if(a===o){J(t,200,{ok:!0,renamed:[],rewrittenDocs:[]});return}if(!m){J(t,503,{ok:!1,error:`Backlink index unavailable`});return}let s=Zh(r,`file`,a),c=Zh(r,`file`,o);if(!L(s)){J(t,404,{ok:!1,error:`Document does not exist`});return}if(L(c)){J(t,409,{ok:!1,error:`Destination already exists`});return}let l=await se(a,o);J(t,200,{ok:!0,renamed:l.renamed,rewrittenDocs:l.rewrittenDocs})}catch(e){console.error(`[rename]`,e),J(t,500,{ok:!1,error:te(e)})}}async function Ye(e,t){if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await Qh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let a;try{a=JSON.parse(n.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){J(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{kind:o,fromPath:s,toPath:c}=a;if(o!==`file`&&o!==`folder`){J(t,400,{ok:!1,error:`kind must be "file" or "folder"`});return}if(typeof s!=`string`||typeof c!=`string`){J(t,400,{ok:!1,error:`fromPath and toPath are required`});return}if(!Kh(s)||!Kh(c)){J(t,400,{ok:!1,error:`Paths must be relative content paths`});return}if(s===c){J(t,200,{ok:!0,renamed:[]});return}let l=Zh(r,o,s),u=Zh(r,o,c);if(!L(l)){J(t,404,{ok:!1,error:`${o} does not exist`});return}if(L(u)){J(t,409,{ok:!1,error:`Destination already exists`});return}let d=he(l);if(o===`file`&&!d.isFile()||o===`folder`&&!d.isDirectory()){J(t,400,{ok:!1,error:`Source path is not a ${o}`});return}let f=qh(i(),o,s),p=o===`file`?[{fromDocName:s,toDocName:c}]:f.map(e=>({fromDocName:e,toDocName:Jh(e,o,s,c)})),m=await ne(p.map(({fromDocName:e})=>e)),h=()=>{le(xe(u),{recursive:!0}),pe(l,u),P(p,m)};o===`file`?await Bm(r,Pm({sourceDocName:s,destinationDocName:c,snapshots:F(p.map(({fromDocName:e})=>e),m)}),h):h(),J(t,200,{ok:!0,renamed:p})}catch(e){console.error(`[rename-path]`,e),J(t,500,{ok:!1,error:`Failed to rename path`})}}async function Xe(e,t){if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await Qh(e)}catch{J(t,413,{ok:!1,error:`Payload too large`});return}let a;try{a=JSON.parse(n.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){J(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{kind:o,path:s}=a;if(o!==`file`&&o!==`folder`){J(t,400,{ok:!1,error:`kind must be "file" or "folder"`});return}if(typeof s!=`string`||!Kh(s)){J(t,400,{ok:!1,error:`path must be a relative content path`});return}let c=Zh(r,o,s);if(!L(c)){J(t,404,{ok:!1,error:`${o} does not exist`});return}let l=he(c);if(o===`file`&&!l.isFile()||o===`folder`&&!l.isDirectory()){J(t,400,{ok:!1,error:`Target path is not a ${o}`});return}let u=o===`file`?[s]:qh(i(),o,s);await ne(u),o===`file`?ge(c):me(c,{recursive:!0,force:!1}),J(t,200,{ok:!0,deletedDocNames:u})}catch(e){console.error(`[delete-path]`,e),J(t,500,{ok:!1,error:`Failed to delete path`})}}async function Ze(e,t){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}try{let e=i(),n=[];for(let[t,i]of e){let e=t;try{e=_f(R(V(r,`${t}${Mf(t)}`),`utf-8`),t)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}n.push({docName:t,title:e,size:i.size,modified:i.modified})}n.sort((e,t)=>e.docName.localeCompare(t.docName)),J(t,200,{ok:!0,pages:n})}catch(e){console.error(`[pages]`,e),J(t,500,{ok:!1,error:`Failed to list pages`})}}async function Qe(e,n){if(e.method!==`GET`){J(n,405,{ok:!1,error:`Method not allowed`});return}try{let r=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!r){J(n,400,{ok:!1,error:`Missing docName parameter`});return}if(!eg(r)){J(n,400,{ok:!1,error:`Invalid docName`});return}if(q(r)){J(n,400,{ok:!1,error:`'${r}' is a reserved document name`});return}J(n,200,{ok:!0,...await Dh({hocuspocus:t,fileIndex:i(),docName:r})})}catch(e){if(e instanceof ah){J(n,404,{ok:!1,error:`Page not found`});return}console.error(`[suggest-links]`,e),J(n,500,{ok:!1,error:`Failed to suggest links`})}}async function $e(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}let n;try{n=await Wh(e,10485760)}catch(e){let n=e instanceof Error?e.message:String(e);n===`Payload too large`?J(t,413,{ok:!1,error:`Payload too large`}):n===`No file received`?J(t,400,{ok:!1,error:`No file received`}):J(t,400,{ok:!1,error:`Failed to parse upload: ${n}`});return}let{filename:i,buffer:a,parentDocName:o}=n;if(!o){J(t,400,{ok:!1,error:`parentDocName is required`});return}if(o.includes(`\0`)||o.includes(`..`)||o.startsWith(`/`)){J(t,400,{ok:!1,error:`path-escape`});return}let s=V(r),c=V(s,xe(o));if(!Fp(c,s)){J(t,400,{ok:!1,error:`path-escape`});return}try{let e=fe(c),n;try{n=fe(s)}catch{n=s}if(!Fp(e,n)){J(t,400,{ok:!1,error:`path-escape`});return}}catch(e){if(e.code!==`ENOENT`){J(t,400,{ok:!1,error:`path-escape`});return}}let l=await Xd(a),u=l?.mime,d=l?.ext;if(!u){let e=a.subarray(0,256).toString(`utf-8`).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(u=`image/svg+xml`,d=`svg`)}if(!u||!d||!Bh.has(u)){J(t,400,{ok:!1,error:`Unsupported file type${u?`: ${u}`:``}`});return}let f;f=!i||i===`upload`||Vh.test(i)?`pasted-${new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`)}.${d}`:Hh(i),le(c,{recursive:!0});try{let e=Uh(c,f,a),n=B(r,V(c,e));console.log(`[upload] ok ${n} ${a.length}`),J(t,200,{ok:!0,src:e})}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`[upload] error ${f} ${a.length} ${n}`),J(t,500,{ok:!1,error:`Failed to save file`})}}let et=`/api/local-op/clone`,tt=`/api/local-op/open`,nt=600*1e3;async function rt(e,t){if(!Om(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n,r;try{let i=await Qh(e),a=JSON.parse(i.toString());if(typeof a.url!=`string`||!a.url){J(t,400,{ok:!1,error:`Missing or invalid url`});return}if(typeof a.dir!=`string`||!a.dir){J(t,400,{ok:!1,error:`Missing or invalid dir`});return}n=a.url,r=a.dir}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!Cm(n)){J(t,400,{ok:!1,error:`URL protocol not allowed`});return}if(!Tm(r)){J(t,400,{ok:!1,error:`dir must be within the user home directory`});return}if(!S.tryAcquire(et)){J(t,429,{ok:!1,error:`A clone operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let i=wm(r),[a,...o]=b,s=[...o,`clone`,`--json`,n,i],c=!1,l=!1,u=null,d=``,f=Me(a,s,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),p=setTimeout(()=>{c=!0,f.kill(`SIGTERM`)},nt);f.stdout.on(`data`,e=>{d+=e.toString(`utf-8`);let n=d.split(`
70
+ `);d=n.pop()??``;for(let e of n){if(!e.trim())continue;let n=null;try{n=JSON.parse(e)}catch{}if(n&&n.type===`complete`&&typeof n.dir==`string`){u=n.dir;continue}t.writableEnded||t.write(`${e}\n`)}});let m=[];f.stderr.on(`data`,e=>{m.push(e),Rh.debug({msg:e.toString(`utf-8`).trim()},`[local-op/clone] stderr`)}),f.on(`close`,e=>{clearTimeout(p);let i=Buffer.concat(m).toString(`utf-8`).trim();if(l){S.release(et);return}l=!0,(async()=>{try{if(c&&!t.writableEnded)t.write(`${JSON.stringify({type:`error`,message:`Clone timed out after 10 minutes`})}\n`);else if(e!==0&&!t.writableEnded){i&&Rh.warn({code:e,stderr:i,url:n,dir:r},`[local-op/clone] clone failed`);let a=i?` — ${i}`:``;t.write(`${JSON.stringify({type:`error`,message:`Clone process exited with code ${e}${a}`})}\n`)}else if(e===0&&u&&!t.writableEnded){let e=await it(u);t.writableEnded||(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port})}\n`):t.write(`${JSON.stringify({type:`error`,message:e.error})}\n`))}}finally{t.writableEnded||t.end(),S.release(et)}})()}),f.on(`error`,e=>{clearTimeout(p),l||(l=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),S.release(et)})}async function it(e){let t=V(wm(e)),n=V(t,`.open-knowledge`),r=wf(n);if(r&&r.port>0)return{port:r.port};let i=re(n),[a,...o]=b,s=i&&i.port>0?`ui`:`start`,c=Me(a,[...o,s],{cwd:t,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env}}),l=[];c.stderr?.on(`data`,e=>{l.push(e),Rh.warn({cwd:t,cliCmd:s,msg:e.toString(`utf-8`).trim()},`[local-op/open] child stderr`)});let u=null;c.on(`exit`,e=>{u=e??-1}),c.unref();let d=Date.now()+45e3;for(;Date.now()<d;){await new Promise(e=>setTimeout(e,500));let e=wf(n);if(e&&e.port>0)return{port:e.port};if(u!==null){let e=Buffer.concat(l).toString(`utf-8`).trim();return{error:`\`ok ${s}\` exited (code ${u})${e?` — ${e}`:``}`}}}let f=Buffer.concat(l).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${f?` — ${f}`:``}`}}async function at(e,t){if(!Om(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n;try{let r=await Qh(e),i=JSON.parse(r.toString());if(typeof i.dir!=`string`||!i.dir){J(t,400,{ok:!1,error:`Missing or invalid dir`});return}n=i.dir}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!Tm(n)){J(t,400,{ok:!1,error:`dir must be within the user home directory`});return}if(!S.tryAcquire(tt)){J(t,429,{ok:!1,error:`A server-open operation is already in progress`});return}try{let e=await it(n);`port`in e?J(t,200,{port:e.port}):J(t,504,{ok:!1,error:e.error})}finally{S.release(tt)}}let ot=`/api/local-op/auth/login`,st=`/api/local-op/auth/status`,ct=`/api/local-op/auth/repos`,lt=`/api/local-op/auth/signout`,ut=`/api/local-op/auth/pat`;async function dt(e,t){if(!Om(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=await Qh(e),r=JSON.parse(t.toString());typeof r.host==`string`&&r.host&&(n=r.host)}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!S.tryAcquire(ot)){J(t,429,{ok:!1,error:`An auth login operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let[r,...i]=b,a=[...i,`auth`,`login`,`--json`,`--host`,n],o=!1,s=!1,c=``,l=Me(r,a,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),u=setTimeout(()=>{l.kill(`SIGTERM`)},nt),d=()=>{l.killed||l.kill(`SIGTERM`)};t.on(`close`,d),l.stdout.on(`data`,e=>{t.writableEnded||t.write(e),c+=e.toString(`utf-8`);let n=c.split(`
71
+ `);c=n.pop()??``;for(let e of n)if(e.trim())try{let t=JSON.parse(e);(t.type===`complete`||t.type===`error`)&&(s=!0)}catch{}}),l.stderr.on(`data`,e=>{Rh.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/login] stderr`)}),l.on(`close`,e=>{clearTimeout(u),t.off(`close`,d),o||(o=!0,t.writableEnded||(e===0&&!s?t.write(`${JSON.stringify({type:`complete`,host:n,login:``})}\n`):e!==0&&t.write(`${JSON.stringify({type:`error`,message:`auth login exited with code ${e}`})}\n`)),t.end()),S.release(ot)}),l.on(`error`,e=>{clearTimeout(u),t.off(`close`,d),o||(o=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),S.release(ot)})}async function ft(e,t){if(!Om(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=(await Qh(e)).toString().trim();if(t.length>0){let e=JSON.parse(t);typeof e.host==`string`&&e.host&&(n=e.host)}}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!S.tryAcquire(st)){J(t,429,{ok:!1,error:`An auth status operation is already in progress`});return}try{let[e,...r]=b,i=[...r,`auth`,`status`,`--json`,`--host`,n],a=(await new Promise((t,n)=>{let r=Me(e,i,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4),o=[];r.stdout.on(`data`,e=>o.push(e)),r.on(`close`,()=>{clearTimeout(a),t(Buffer.concat(o).toString(`utf-8`))}),r.on(`error`,e=>{clearTimeout(a),n(e)})})).split(`
72
+ `).map(e=>e.trim()).filter(Boolean),o=null;for(let e=a.length-1;e>=0;e--)try{o=JSON.parse(a[e]);break}catch{}o===null?J(t,200,{authenticated:!1}):J(t,200,o)}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:`auth status failed`})}finally{S.release(st)}}async function pt(e,t){if(!Om(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=(await Qh(e)).toString().trim();if(t.length>0){let e=JSON.parse(t);typeof e.host==`string`&&e.host&&(n=e.host)}}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!S.tryAcquire(ct)){J(t,429,{ok:!1,error:`An auth repos operation is already in progress`});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let[r,...i]=b,a=[...i,`auth`,`repos`,`--json`,`--host`,n],o=!1,s=Me(r,a,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),c=setTimeout(()=>{s.kill(`SIGTERM`)},nt);s.stdout.on(`data`,e=>{t.writableEnded||t.write(e)}),s.stderr.on(`data`,e=>{Rh.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),s.on(`close`,e=>{clearTimeout(c),o||(o=!0,e!==0&&!t.writableEnded&&t.write(`${JSON.stringify({type:`error`,message:`auth repos exited with code ${e}`})}\n`),t.end()),S.release(ct)}),s.on(`error`,e=>{clearTimeout(c),o||(o=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),S.release(ct)})}async function mt(e,t){if(!Om(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=await Qh(e),r=JSON.parse(t.toString());typeof r.host==`string`&&r.host&&(n=r.host)}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!S.tryAcquire(lt)){J(t,429,{ok:!1,error:`An auth signout operation is already in progress`});return}try{let[e,...r]=b,i=[...r,`auth`,`signout`,`--host`,n];await new Promise((t,n)=>{let r=Me(e,i,{stdio:`ignore`,env:{...process.env}}),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4);r.on(`close`,()=>{clearTimeout(a),t()}),r.on(`error`,e=>{clearTimeout(a),n(e)})}),J(t,200,{ok:!0})}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:`auth signout failed`})}finally{S.release(lt)}}async function ht(e,t){if(!Om(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`,r;try{let i=await Qh(e),a=JSON.parse(i.toString());if(typeof a.pat!=`string`||!a.pat){J(t,400,{ok:!1,error:`Missing or invalid pat`});return}r=a.pat,typeof a.host==`string`&&a.host&&(n=a.host)}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!S.tryAcquire(ut)){J(t,429,{ok:!1,error:`An auth pat operation is already in progress`});return}try{let[e,...i]=b,a=[...i,`auth`,`pat`,`--json`,`--host`,n],o=(await new Promise((t,n)=>{let i=Me(e,a,{stdio:[`pipe`,`pipe`,`pipe`],env:{...process.env}}),o=setTimeout(()=>{i.kill(`SIGTERM`)},3e4);i.stdin.write(`${r}\n`),i.stdin.end();let s=[];i.stdout.on(`data`,e=>s.push(e)),i.on(`close`,e=>{clearTimeout(o),e===0?t(Buffer.concat(s).toString(`utf-8`)):n(Error(`auth pat exited with code ${e}`))}),i.on(`error`,e=>{clearTimeout(o),n(e)})})).split(`
73
+ `).map(e=>e.trim()).filter(Boolean),s=null;for(let e=o.length-1;e>=0;e--)try{s=JSON.parse(o[e]);break}catch{}s===null?J(t,200,{ok:!0}):J(t,200,s)}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:`auth pat failed`})}finally{S.release(ut)}}async function gt(e,t){if(Om(e,t,J)){if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!x){J(t,400,{ok:!1,error:`No project directory configured`});return}try{J(t,200,{ok:!0,identity:await ym(x)})}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:`identity resolution failed`})}}}let _t=`/api/local-op/auth/set-identity`;async function vt(e,t){if(!Om(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n,r;try{let i=await Qh(e),a=JSON.parse(i.toString());if(typeof a.name!=`string`||!a.name.trim()){J(t,400,{ok:!1,error:`Missing or invalid name`});return}if(typeof a.email!=`string`||!a.email.trim()){J(t,400,{ok:!1,error:`Missing or invalid email`});return}n=a.name.trim(),r=a.email.trim()}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!x){J(t,400,{ok:!1,error:`No project directory configured`});return}if(!S.tryAcquire(_t)){J(t,429,{ok:!1,error:`A set-identity operation is already in progress`});return}try{bm(x,n,r),y?.()?.refreshIdentity().catch(()=>{}),J(t,200,{ok:!0})}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:`set-identity failed`})}finally{S.release(_t)}}async function yt(e,t){if(!Om(e,t,J))return;if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=y?.();if(!n){J(t,200,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1});return}J(t,200,n.getStatus())}async function bt(e,t){if(!Om(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=y?.();if(!n){J(t,503,{ok:!1,error:`Sync engine not active`});return}let r=`sync`;try{let t=await Qh(e);if(t.length>0){let e=JSON.parse(t.toString());(e.op===`push`||e.op===`pull`||e.op===`sync`)&&(r=e.op)}}catch{}J(t,202,{ok:!0,op:r}),n.trigger(r)}async function xt(e,t){if(!Om(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=y?.();if(!n){J(t,503,{ok:!1,error:`Sync engine not active`});return}let r;try{let n=await Qh(e),i=JSON.parse(n.toString());if(typeof i.enabled!=`boolean`){J(t,400,{ok:!1,error:`enabled must be a boolean`});return}r=i.enabled}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}await n.setEnabled(r),J(t,200,{ok:!0,status:n.getStatus()})}async function St(e,t){if(!Om(e,t,J))return;if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=y?.();J(t,200,{conflicts:n?n.getConflicts():[]})}async function H(e,t){if(!Om(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=y?.();if(!n){J(t,503,{ok:!1,error:`Sync engine not active`});return}let r;try{let t=await Qh(e);r=JSON.parse(t.toString())}catch{J(t,400,{ok:!1,error:`Invalid JSON body`});return}let{file:i,strategy:a,content:o}=r;if(!i||typeof i!=`string`){J(t,400,{ok:!1,error:`Missing required field: file`});return}if(a!==`mine`&&a!==`theirs`&&a!==`content`){J(t,400,{ok:!1,error:`Invalid strategy: must be 'mine', 'theirs', or 'content'`});return}try{await n.resolveConflict(i,a,o),J(t,200,{ok:!0})}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function Ct(e,t){if(!Om(e,t,J))return;if(e.method!==`GET`){J(t,405,{ok:!1,error:`Method not allowed`});return}if(!x){J(t,503,{ok:!1,error:`Project repo not configured`});return}let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`file`);if(!n){J(t,400,{ok:!1,error:`Missing required query param: file`});return}if(n.includes(`..`)||n.startsWith(`/`)){J(t,400,{ok:!1,error:`Invalid file path`});return}let r=Pe({baseDir:x,timeout:{block:15e3}});async function i(e){try{return await r.raw([`show`,`:${e}:${n}`])}catch{return``}}try{let[e,r,a]=await Promise.all([i(1),i(2),i(3)]);J(t,200,{ok:!0,file:n,base:e,ours:r,theirs:a})}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function wt(e,t){if(!Om(e,t,J))return;if(e.method!==`POST`){J(t,405,{ok:!1,error:`Method not allowed`});return}let n=y?.();if(!n){J(t,503,{ok:!1,error:`Sync engine not active`});return}try{await n.abortMerge(),J(t,200,{ok:!0})}catch(e){J(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}let Tt={"/api/document":ye,"/api/documents":be,"/api/backlinks":Se,"/api/backlink-counts":Ce,"/api/forward-links":we,"/api/link-graph":Ee,"/api/dead-links":ke,"/api/orphans":De,"/api/hubs":Oe,"/api/pages":Ze,"/api/suggest-links":Qe,"/api/page-headings":qe,"/api/create-page":Ke,"/api/rename":Je,"/api/rename-path":Ye,"/api/delete-path":Xe,"/api/upload-image":$e,"/api/agent-write":_e,"/api/agent-write-md":ve,"/api/agent-patch":Ae,"/api/save-version":Fe,"/api/history":Ie,"/api/diff":Re,"/api/rollback":ze,"/api/metrics/reconciliation":Be,"/api/metrics/parse-health":Ve,"/api/rescue":We,"/api/workspace":He,"/api/sync/status":yt,"/api/sync/trigger":bt,"/api/sync/set-enabled":xt,"/api/sync/conflicts":St,"/api/sync/conflict-content":Ct,"/api/sync/resolve-conflict":H,"/api/sync/abort-merge":wt,"/api/local-op/clone":rt,"/api/local-op/open":at,"/api/local-op/auth/login":dt,"/api/local-op/auth/status":ft,"/api/local-op/auth/repos":pt,"/api/local-op/auth/signout":mt,"/api/local-op/auth/pat":ht,"/api/local-op/auth/identity":gt,"/api/local-op/auth/set-identity":vt};return o&&(Tt[`/api/test-reset`]=je,Tt[`/api/test-rescan-backlinks`]=Ne),{priority:100,async onRequest({request:e,response:t}){let n=e.url?.split(`?`)[0];if(!n)return;if(n.startsWith(`/api/`)&&(typeof t.setHeader==`function`&&(t.setHeader(`Access-Control-Allow-Origin`,`*`),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization`)),e.method===`OPTIONS`)){t.writeHead(204),t.end();return}let r=Tt[n];if(r){await r(e,t);return}if(n.startsWith(`/api/rescue/`)){let r=decodeURIComponent(n.slice(12));r&&await Ge(e,t,r);return}if(n.startsWith(`/api/history/`)){let r=decodeURIComponent(n.slice(13));r&&await Le(e,t,r);return}}}}function ng(e){let t=e.scheduler??T,n=e.warnBeforeMs??3e5,r=0,i=null,a=null,o=!1,s=!1;function c(){i!==null&&(t.clearTimeout(i),i=null),a!==null&&(t.clearTimeout(a),a=null)}function l(){c(),!(s||o)&&r===0&&(n>0&&n<e.thresholdMs&&(a=t.setTimeout(()=>{a=null,r===0&&!o&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),i=t.setTimeout(()=>{if(i=null,!(s||o)&&r===0){o=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let u=(e,t)=>{e.url?.startsWith(`/collab`)&&(r++,c(),t.once(`close`,()=>{r--,r<0&&(r=0),r===0&&l()}))};return e.httpServer.on(`upgrade`,u),l(),{detach:()=>{s||(s=!0,e.httpServer.off(`upgrade`,u),c())}}}const rg=Math.floor,ig=(e,t)=>e<t?e:t,ag=(e,t)=>e>t?e:t;Number.isNaN,Number.isInteger,Number.isNaN,Number.parseInt;const og=String.fromCharCode;String.fromCodePoint,og(65535);const sg=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},cg=typeof TextEncoder<`u`?new TextEncoder:null,lg=cg?e=>cg.encode(e):sg;let ug=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});ug&&ug.decode(new Uint8Array).length===1&&(ug=null);const dg=(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},fg=(e,t)=>{for(;t>127;)dg(e,128|127&t),t=rg(t/128);dg(e,127&t)},pg=new Uint8Array(3e4),mg=pg.length/3,hg=cg&&cg.encodeInto?(e,t)=>{if(t.length<mg){let n=cg.encodeInto(t,pg).written||0;fg(e,n);for(let t=0;t<n;t++)dg(e,pg[t])}else _g(e,lg(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;fg(e,r);for(let t=0;t<r;t++)dg(e,n.codePointAt(t))},gg=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=ig(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(ag(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},_g=(e,t)=>{fg(e,t.byteLength),gg(e,t)},vg=e=>Error(e);vg(`Unexpected end of array`),vg(`Integer out of Range`);let yg=function(e){return e[e.Token=0]=`Token`,e[e.PermissionDenied=1]=`PermissionDenied`,e[e.Authenticated=2]=`Authenticated`,e}({});const bg=(e,t)=>{fg(e,yg.PermissionDenied),hg(e,t)},xg=(e,t)=>{fg(e,yg.Authenticated),hg(e,t)},Sg=e=>{fg(e,yg.Token)},Cg={code:4205,reason:`Reset Connection`},wg={code:4401,reason:`Unauthorized`},Tg={code:4403,reason:`Forbidden`},Eg={code:4408,reason:`Connection Timeout`},Dg=e=>Array.from(e.entries()).map(([e,t])=>({clientId:e,...t}));var Og=class extends Error{constructor(e){super(e??`Further hooks skipped`),this.name=`SkipFurtherHooksError`}};let kg=function(e){return e[e.Connecting=0]=`Connecting`,e[e.Open=1]=`Open`,e[e.Closing=2]=`Closing`,e[e.Closed=3]=`Closed`,e}({});const Ag=Error(`request for lock canceled`);var jg=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},Mg=class{constructor(e,t=Ag){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return new Promise((n,r)=>{let i={resolve:n,reject:r,weight:e,priority:t},a=Pg(this._queue,e=>t<=e.priority);a===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(a+1,0,i)})}runExclusive(e){return jg(this,arguments,void 0,function*(e,t=1,n=0){let[r,i]=yield this.acquire(t,n);try{return yield e(r)}finally{i()}})}waitForUnlock(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),Ng(this._weightedWaiters[e-1],{resolve:n,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let t=this._weightedWaiters[e-1];t&&(t.forEach(e=>e.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let t=this._value;t>0;t--){let n=this._weightedWaiters[t-1];if(!n)continue;let r=n.findIndex(t=>t.priority<=e);(r===-1?n:n.splice(0,r)).forEach((e=>e.resolve()))}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}};function Ng(e,t){let n=Pg(e,e=>t.priority<=e.priority);e.splice(n+1,0,t)}function Pg(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}var Fg=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},Ig=class{constructor(e){this._semaphore=new Mg(1,e)}acquire(){return Fg(this,arguments,void 0,function*(e=0){let[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};let Lg,Rg,zg,Bg,Vg=!0;typeof process<`u`&&({FORCE_COLOR:Lg,NODE_DISABLE_COLORS:Rg,NO_COLOR:zg,TERM:Bg}=process.env||{},Vg=process.stdout&&process.stdout.isTTY);const Y={enabled:!Rg&&zg==null&&Bg!==`dumb`&&(Lg!=null&&Lg!==`0`||Vg),reset:X(0,0),bold:X(1,22),dim:X(2,22),italic:X(3,23),underline:X(4,24),inverse:X(7,27),hidden:X(8,28),strikethrough:X(9,29),black:X(30,39),red:X(31,39),green:X(32,39),yellow:X(33,39),blue:X(34,39),magenta:X(35,39),cyan:X(36,39),white:X(37,39),gray:X(90,39),grey:X(90,39),bgBlack:X(40,49),bgRed:X(41,49),bgGreen:X(42,49),bgYellow:X(43,49),bgBlue:X(44,49),bgMagenta:X(45,49),bgCyan:X(46,49),bgWhite:X(47,49)};function Hg(e,t){let n=0,r,i=``,a=``;for(;n<e.length;n++)r=e[n],i+=r.open,a+=r.close,~t.indexOf(r.close)&&(t=t.replace(r.rgx,r.close+r.open));return i+t+a}function Ug(e,t){let n={has:e,keys:t};return n.reset=Y.reset.bind(n),n.bold=Y.bold.bind(n),n.dim=Y.dim.bind(n),n.italic=Y.italic.bind(n),n.underline=Y.underline.bind(n),n.inverse=Y.inverse.bind(n),n.hidden=Y.hidden.bind(n),n.strikethrough=Y.strikethrough.bind(n),n.black=Y.black.bind(n),n.red=Y.red.bind(n),n.green=Y.green.bind(n),n.yellow=Y.yellow.bind(n),n.blue=Y.blue.bind(n),n.magenta=Y.magenta.bind(n),n.cyan=Y.cyan.bind(n),n.white=Y.white.bind(n),n.gray=Y.gray.bind(n),n.grey=Y.grey.bind(n),n.bgBlack=Y.bgBlack.bind(n),n.bgRed=Y.bgRed.bind(n),n.bgGreen=Y.bgGreen.bind(n),n.bgYellow=Y.bgYellow.bind(n),n.bgBlue=Y.bgBlue.bind(n),n.bgMagenta=Y.bgMagenta.bind(n),n.bgCyan=Y.bgCyan.bind(n),n.bgWhite=Y.bgWhite.bind(n),n}function X(e,t){let n={open:`\x1b[${e}m`,close:`\x1b[${t}m`,rgx:RegExp(`\\x1b\\[${t}m`,`g`)};return function(t){return this!==void 0&&this.has!==void 0?(~this.has.indexOf(e)||(this.has.push(e),this.keys.push(n)),t===void 0?this:Y.enabled?Hg(this.keys,t+``):t+``):t===void 0?Ug([e],[n]):Y.enabled?Hg([n],t+``):t+``}}const Wg=Math.floor,Gg=(e,t)=>e<t?e:t,Kg=(e,t)=>e>t?e:t;Number.isNaN;const qg=2**53-1;Number.isInteger,Number.isNaN,Number.parseInt;const Jg=()=>new Set,Yg=Array.from;Array.isArray;const Xg=String.fromCharCode;String.fromCodePoint,Xg(65535);const Zg=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},Qg=typeof TextEncoder<`u`?new TextEncoder:null,$g=Qg?e=>Qg.encode(e):Zg;let e_=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});e_&&e_.decode(new Uint8Array).length===1&&(e_=null);const t_=e=>Error(e);var n_=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const r_=()=>new n_,i_=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},a_=e=>{let t=new Uint8Array(i_(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},o_=(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},Z=(e,t)=>{for(;t>127;)o_(e,128|127&t),t=Wg(t/128);o_(e,127&t)},s_=new Uint8Array(3e4),c_=s_.length/3,l_=Qg&&Qg.encodeInto?(e,t)=>{if(t.length<c_){let n=Qg.encodeInto(t,s_).written||0;Z(e,n);for(let t=0;t<n;t++)o_(e,s_[t])}else d_(e,$g(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;Z(e,r);for(let t=0;t<r;t++)o_(e,n.codePointAt(t))},u_=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=Gg(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(Kg(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},d_=(e,t)=>{Z(e,t.byteLength),u_(e,t)},f_=t_(`Unexpected end of array`),p_=t_(`Integer out of Range`);var m_=class{constructor(e){this.arr=e,this.pos=0}};const h_=e=>new m_(e),g_=e=>e.pos!==e.arr.length,__=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},v_=e=>__(e,b_(e)),y_=e=>e.arr[e.pos++],b_=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>qg)throw p_}throw f_},x_=e_?e=>e_.decode(v_(e)):e=>{let t=b_(e);if(t===0)return``;{let n=String.fromCodePoint(y_(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(y_(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))}};var S_=class{constructor(e){e instanceof Uint8Array||(e=new Uint8Array(e)),this.decoder=h_(e)}get encoder(){return this.encoderInternal||=r_(),this.encoderInternal}readVarUint8Array(){return v_(this.decoder)}peekVarUint8Array(){let{pos:e}=this.decoder,t=v_(this.decoder);return this.decoder.pos=e,t}readVarUint(){return b_(this.decoder)}readVarString(){return x_(this.decoder)}toUint8Array(){return a_(this.encoder)}writeVarUint(e){Z(this.encoder,e)}writeVarString(e){l_(this.encoder,e)}get length(){return i_(this.encoder)}};const C_=Date.now,w_=()=>new Map,T_=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r};var E_=class{constructor(){this._observers=w_()}on(e,t){T_(this._observers,e,Jg).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 Yg((this._observers.get(e)||w_()).values()).forEach(e=>e(...t))}destroy(){this._observers=w_()}};const D_=Symbol(`Equality`),O_=Object.keys,k_=e=>O_(e).length,A_=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),j_=(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[D_]!=null)return e[D_](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)||!j_(e.get(n),t.get(n)))return!1;break;case void 0:case Object:if(k_(e)!==k_(t))return!1;for(let n in e)if(!A_(e,n)||!j_(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(!j_(e[n],t[n]))return!1;break;default:return!1}return!0},M_=3e4;var N_=class extends E_{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let e=C_();this.getLocalState()!==null&&M_/2<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&M_<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&P_(this,t,`timeout`)},Wg(M_/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:C_()});let a=[],o=[],s=[],c=[];e===null?c.push(t):i==null?e!=null&&a.push(t):(o.push(t),j_(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}};const P_=(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:C_()})}r.push(i)}}r.length>0&&(e.emit(`change`,[{added:[],updated:[],removed:r},n]),e.emit(`update`,[{added:[],updated:[],removed:r},n]))},F_=(e,t,n=e.states)=>{let r=t.length,i=r_();Z(i,r);for(let a=0;a<r;a++){let r=t[a],o=n.get(r)||null,s=e.meta.get(r).clock;Z(i,r),Z(i,s),l_(i,JSON.stringify(o))}return a_(i)},I_=(e,t,n)=>{let r=h_(t),i=C_(),a=[],o=[],s=[],c=[],l=b_(r);for(let t=0;t<l;t++){let t=b_(r),n=b_(r),l=JSON.parse(x_(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&&(j_(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])},L_=(e,t)=>{Z(e,0),d_(e,Yr(t))},R_=(e,t,n)=>{Z(e,1),d_(e,Ur(t,n))},z_=(e,t,n)=>R_(t,n,v_(e)),B_=(e,t,n,r)=>{try{Br(t,v_(e),n)}catch(e){r?.(e),console.error(`Caught error while handling a Yjs update`,e)}},V_=(e,t)=>{Z(e,2),d_(e,t)},H_=B_;function U_(e){return typeof e==`object`&&!!e&&`source`in e&&(e.source===`connection`||e.source===`redis`||e.source===`local`)}function W_(e){if(!U_(e))return!1;switch(e.source){case`connection`:return!1;case`redis`:return!0;case`local`:return e.skipStoreHooks??!1}}let Q=function(e){return e[e.Unknown=-1]=`Unknown`,e[e.Sync=0]=`Sync`,e[e.Awareness=1]=`Awareness`,e[e.Auth=2]=`Auth`,e[e.QueryAwareness=3]=`QueryAwareness`,e[e.SyncReply=4]=`SyncReply`,e[e.Stateless=5]=`Stateless`,e[e.BroadcastStateless=6]=`BroadcastStateless`,e[e.CLOSE=7]=`CLOSE`,e[e.SyncStatus=8]=`SyncStatus`,e[e.Ping=9]=`Ping`,e[e.Pong=10]=`Pong`,e}({});var G_=class{constructor(e){this.encoder=r_(),l_(this.encoder,e)}createSyncMessage(){return this.type=Q.Sync,Z(this.encoder,Q.Sync),this}createSyncReplyMessage(){return this.type=Q.SyncReply,Z(this.encoder,Q.SyncReply),this}createAwarenessUpdateMessage(e,t){this.type=Q.Awareness,this.category=`Update`;let n=F_(e,t||Array.from(e.getStates().keys()));return Z(this.encoder,Q.Awareness),d_(this.encoder,n),this}writeQueryAwareness(){return this.type=Q.QueryAwareness,this.category=`Update`,Z(this.encoder,Q.QueryAwareness),this}writeTokenSyncRequest(){return this.type=Q.Auth,this.category=`TokenSync`,Z(this.encoder,Q.Auth),Sg(this.encoder),this}writeAuthenticated(e){return this.type=Q.Auth,this.category=`Authenticated`,Z(this.encoder,Q.Auth),xg(this.encoder,e?`readonly`:`read-write`),this}writePermissionDenied(e){return this.type=Q.Auth,this.category=`PermissionDenied`,Z(this.encoder,Q.Auth),bg(this.encoder,e),this}writeFirstSyncStepFor(e){return this.category=`SyncStep1`,L_(this.encoder,e),this}writeUpdate(e){return this.category=`Update`,V_(this.encoder,e),this}writeStateless(e){return this.category=`Stateless`,Z(this.encoder,Q.Stateless),l_(this.encoder,e),this}writeBroadcastStateless(e){return this.category=`Stateless`,Z(this.encoder,Q.BroadcastStateless),l_(this.encoder,e),this}writeSyncStatus(e){return this.category=`SyncStatus`,Z(this.encoder,Q.SyncStatus),Z(this.encoder,e?1:0),this}writeCloseMessage(e){return this.type=Q.CLOSE,Z(this.encoder,Q.CLOSE),l_(this.encoder,e),this}toUint8Array(){return a_(this.encoder)}},K_=class{constructor(e,t){this.message=e,this.defaultTransactionOrigin=t}async apply(e,t,n){let{message:r}=this,i=r.readVarUint(),a=r.length;switch(i){case Q.Sync:case Q.SyncReply:r.writeVarUint(Q.Sync),await this.readSyncMessage(r,e,t,n,i!==Q.SyncReply),r.length>a+1&&(n?n(r.toUint8Array()):t&&t.send(r.toUint8Array()));break;case Q.Awareness:I_(e.awareness,r.readVarUint8Array(),t??null);break;case Q.QueryAwareness:this.applyQueryAwarenessMessage(e,t,n);break;case Q.Stateless:t?.callbacks.statelessCallback({connection:t,documentName:e.name,document:e,payload:x_(r.decoder)});break;case Q.BroadcastStateless:{let t=r.readVarString();e.getConnections().forEach(e=>{e.sendStateless(t)});break}case Q.CLOSE:t?.close({code:1e3,reason:`provider_initiated`});break;case Q.Auth:if(r.readVarUint()===yg.Token){t?.callbacks.onTokenSyncCallback({token:r.readVarString()});break}console.error(`Received an authentication message on a connection that is already fully authenticated. Probably your provider has been destroyed + recreated really fast.`);break;default:console.error(`Unable to handle message of type ${i}: no handler defined! Are your provider/server versions aligned?`)}}async readSyncMessage(e,t,n,r,i=!0){let a=e.readVarUint(),o=n?.messageAddress??t.name;switch(n&&await n.callbacks.beforeSync(n,{type:a,payload:e.peekVarUint8Array()}),a){case 0:if(z_(e.decoder,e.encoder,t),r&&i)r(new G_(o).createSyncReplyMessage().writeFirstSyncStepFor(t).toUint8Array());else if(n){let e=new G_(o).createSyncMessage().writeFirstSyncStepFor(t);n.send(e.toUint8Array())}break;case 1:if(n?.readOnly){if(ui(oi(t),v_(e.decoder))){let e=new G_(o).writeSyncStatus(!0);n.send(e.toUint8Array())}else{let e=new G_(o).writeSyncStatus(!1);n.send(e.toUint8Array())}break}B_(e.decoder,t,n?{source:`connection`,connection:n}:this.defaultTransactionOrigin??{source:`local`}),n&&n.send(new G_(o).writeSyncStatus(!0).toUint8Array());break;case 2:if(n?.readOnly){n.send(new G_(o).writeSyncStatus(!1).toUint8Array());break}H_(e.decoder,t,n?{source:`connection`,connection:n}:this.defaultTransactionOrigin??{source:`local`}),n&&n.send(new G_(o).writeSyncStatus(!0).toUint8Array());break;default:throw Error(`Received a message with an unknown type: ${a}`)}return a}applyQueryAwarenessMessage(e,t,n){let r=new G_(t?.messageAddress??e.name).createAwarenessUpdateMessage(e.awareness);n&&n(r.toUint8Array())}},q_=class{get messageAddress(){return this.sessionId?`${this.document.name}\0${this.sessionId}`:this.document.name}constructor(e,t,n,r,i,a=!1,o,s){this.callbacks={onClose:[(e,t)=>{}],beforeHandleMessage:(e,t)=>Promise.resolve(),beforeSync:(e,t)=>Promise.resolve(),statelessCallback:e=>Promise.resolve(),onTokenSyncCallback:e=>Promise.resolve()},this.messageQueue=[],this.processingPromise=Promise.resolve(),this.webSocket=e,this.context=i,this.document=n,this.request=t,this.socketId=r,this.readOnly=a,this.sessionId=o??null,this.providerVersion=s??null,this.document.addConnection(this),this.sendCurrentAwareness()}onClose(e){return this.callbacks.onClose.push(e),this}onStatelessCallback(e){return this.callbacks.statelessCallback=e,this}beforeHandleMessage(e){return this.callbacks.beforeHandleMessage=e,this}beforeSync(e){return this.callbacks.beforeSync=e,this}onTokenSyncCallback(e){return this.callbacks.onTokenSyncCallback=e,this}waitForPendingMessages(){return this.processingPromise}send(e){if(this.webSocket.readyState===kg.Closing||this.webSocket.readyState===kg.Closed){this.close();return}try{this.webSocket.send(e)}catch{this.close()}}sendStateless(e){let t=new G_(this.messageAddress).writeStateless(e);this.send(t.toUint8Array())}requestToken(){let e=new G_(this.messageAddress).writeTokenSyncRequest();this.send(e.toUint8Array())}close(e){if(this.document.hasConnection(this)){this.document.removeConnection(this),this.callbacks.onClose.forEach(t=>t(this.document,e));let t=new G_(this.messageAddress);t.writeCloseMessage(e?.reason??`Server closed the connection`),this.send(t.toUint8Array())}}sendCurrentAwareness(){if(!this.document.hasAwarenessStates())return;let e=new G_(this.messageAddress).createAwarenessUpdateMessage(this.document.awareness);this.send(e.toUint8Array())}handleMessage(e){this.messageQueue.push(e),this.messageQueue.length===1&&(this.processingPromise=this.processMessages())}async processMessages(){for(;this.messageQueue.length>0;){let e=this.messageQueue.at(0),t=new S_(e),n=t.readVarString(),r=n.indexOf(`\0`),i=r===-1?n:n.substring(0,r);if(i!==this.document.name){this.messageQueue.shift();continue}t.writeVarString(this.messageAddress);try{await this.callbacks.beforeHandleMessage(this,e),await new K_(t).apply(this.document,this)}catch(e){console.error(`closing connection ${this.socketId} (while handling ${i}) because of exception`,e),this.close({code:`code`in e&&typeof e.code==`number`?e.code:Cg.code,reason:`reason`in e?e.reason:Cg.reason})}this.messageQueue.shift()}}},J_=class extends wr{constructor(e,t){super(t),this.callbacks={onUpdate:(e,t,n)=>{},beforeBroadcastStateless:(e,t)=>{}},this.connections=new Map,this.directConnectionsCount=0,this.isDestroyed=!1,this.saveMutex=new Ig,this.lastChangeTime=0,this.name=e,this.awareness=new N_(this),this.awareness.setLocalState(null),this.awareness.on(`update`,this.handleAwarenessUpdate.bind(this)),this.on(`update`,this.handleUpdate.bind(this)),this.isLoading=!0}isEmpty(e){return!this.get(e)._start&&!this.get(e)._map.size}merge(e){return(Array.isArray(e)?e:[e]).forEach(e=>{Br(this,Ur(e))}),this}onUpdate(e){return this.callbacks.onUpdate=e,this}beforeBroadcastStateless(e){return this.callbacks.beforeBroadcastStateless=e,this}addConnection(e){return this.connections.set(e,{clients:new Set}),this}hasConnection(e){return this.connections.has(e)}removeConnection(e){let t=this.connections.get(e);return t&&P_(this.awareness,Array.from(t.clients),null),this.connections.delete(e),this}addDirectConnection(){return this.directConnectionsCount+=1,this}removeDirectConnection(){return this.directConnectionsCount>0&&--this.directConnectionsCount,this}getConnectionsCount(){return this.connections.size+this.directConnectionsCount}getConnections(){return Array.from(this.connections.keys())}getClients(e){let t=this.connections.get(e);return t?.clients===void 0?new Set:t.clients}hasAwarenessStates(){return this.awareness.getStates().size>0}applyAwarenessUpdate(e,t){return I_(this.awareness,t,e),this}handleAwarenessUpdate({added:e,updated:t,removed:n},r){let i=e.concat(t,n);if(r!==null){let t=this.connections.get(r);t&&(e.forEach(e=>t.clients.add(e)),n.forEach(e=>t.clients.delete(e)))}for(let e of this.getConnections()){let t=new G_(e.messageAddress).createAwarenessUpdateMessage(this.awareness,i);e.send(t.toUint8Array())}return this}handleUpdate(e,t){this.callbacks.onUpdate(this,t,e);for(let t of this.getConnections()){let n=new G_(t.messageAddress).createSyncMessage().writeUpdate(e);t.send(n.toUint8Array())}return this}broadcastStateless(e,t){this.callbacks.beforeBroadcastStateless(this,e),(t?this.getConnections().filter(t):this.getConnections()).forEach(t=>{t.sendStateless(e)})}destroy(){super.destroy(),this.isDestroyed=!0}},Y_=`4.0.0-rc.1`;function X_(e){let t=e?.url;return t?t.includes(`://`)?new URL(t).searchParams:new URLSearchParams(t.split(`?`)[1]||``):new URLSearchParams}var Z_=class{constructor(e,t,n,r,i,a={}){this.websocket=e,this.request=t,this.documentProvider=n,this.hooks=r,this.opts=i,this.defaultContext=a,this.documentConnections={},this.incomingMessageQueue={},this.documentConnectionsEstablished=new Set,this.hookPayloads={},this.callbacks={onClose:[(e,t)=>{}]},this.socketId=De.randomUUID(),this.lastMessageReceivedAt=Date.now(),this.check=()=>{Date.now()-this.lastMessageReceivedAt>this.timeout&&this.close(Eg)},this.setUpNewConnection=async(e,t,n)=>{let r=this.hookPayloads[e],i=await this.documentProvider.createDocument(t,r.request,r.socketId,r.connectionConfig,r.context),a=this.createConnection(this.websocket,i,r,n,r.providerVersion);if(a.onClose((t,n)=>{delete this.hookPayloads[e],delete this.documentConnections[e],delete this.incomingMessageQueue[e],this.documentConnectionsEstablished.delete(e)}),a.onTokenSyncCallback(async e=>{try{return await this.hooks(`onTokenSync`,{...r,...e,document:i,connection:a,documentName:t},e=>{r.context={...r.context,...e}})}catch(e){console.error(e);let t={...wg,...e};a.close({code:t.code,reason:t.reason})}}),this.documentConnections[e]=a,this.websocket.readyState===kg.Closing||this.websocket.readyState===kg.Closed){this.close();return}this.incomingMessageQueue[e]?.forEach(e=>{a.handleMessage(e)}),await this.hooks(`connected`,{...r,documentName:t,context:r.context,connection:a})},this.handleQueueingMessage=async(e,t,n)=>{try{let r=new S_(e);if(x_(r.decoder),!(b_(r.decoder)===Q.Auth&&!this.documentConnectionsEstablished.has(t))){this.incomingMessageQueue[t].push(e);return}this.documentConnectionsEstablished.add(t),b_(r.decoder);let i=x_(r.decoder),a=null;g_(r.decoder)&&(a=x_(r.decoder));let o=t.indexOf(`\0`),s=o===-1?null:t.substring(o+1),c=t;try{let e=this.hookPayloads[t];e.providerVersion=a,await this.hooks(`onConnect`,{...e,documentName:n},t=>{e.context={...e.context,...t}}),await this.hooks(`onAuthenticate`,{token:i,...e,documentName:n},t=>{e.context={...e.context,...t}}),e.connectionConfig.isAuthenticated=!0;let r=new G_(c).writeAuthenticated(e.connectionConfig.readOnly);this.websocket.send(r.toUint8Array()),await this.setUpNewConnection(t,n,s)}catch(e){let n=e||Tg,r=new G_(c).writePermissionDenied(n.reason??`permission-denied`);this.websocket.send(r.toUint8Array()),this.documentConnectionsEstablished.delete(t),delete this.hookPayloads[t],delete this.incomingMessageQueue[t]}}catch(e){console.error(e),this.websocket.close(Cg.code,Cg.reason)}},this.handleMessage=e=>{this.lastMessageReceivedAt=Date.now();try{let t=x_(new S_(e).decoder),n=t.indexOf(`\0`),r=n===-1?t:t.substring(0,n),i=this.documentConnections[t]??this.documentConnections[r];if(i){i.handleMessage(e);return}if(this.incomingMessageQueue[t]===void 0){if(this.incomingMessageQueue[t]=[],this.hookPayloads[t])throw Error(`first message, but hookPayloads exists`);this.hookPayloads[t]={instance:this.documentProvider,request:this.request,connectionConfig:{readOnly:!1,isAuthenticated:!1},requestHeaders:this.request.headers,requestParameters:X_(this.request),socketId:this.socketId,context:{...this.defaultContext},providerVersion:null}}this.handleQueueingMessage(e,t,r)}catch(e){console.error(e),this.websocket.close(wg.code,wg.reason)}},this.timeout=i.timeout,this.pingInterval=setInterval(this.check,this.timeout)}handleClose(e){this.close(e),clearInterval(this.pingInterval)}close(e){Object.values(this.documentConnections).forEach(t=>t.close(e))}onClose(e){return this.callbacks.onClose.push(e),this}createConnection(e,t,n,r,i){let a=new q_(e,n.request,t,n.socketId,n.context,n.connectionConfig.readOnly,r,i);return a.onClose(async(e,t)=>{await a.waitForPendingMessages();let r={instance:this.documentProvider,clientsCount:e.getConnectionsCount(),context:n.context,document:e,socketId:n.socketId,documentName:e.name,requestHeaders:n.request.headers,requestParameters:X_(n.request)};await this.hooks(`onDisconnect`,r),this.callbacks.onClose.forEach(t=>t(e,r))}),a.onStatelessCallback(async e=>{try{return await this.hooks(`onStateless`,e)}catch(e){if(e?.message)throw e}}),a.beforeHandleMessage((e,r)=>{let i={instance:this.documentProvider,clientsCount:t.getConnectionsCount(),context:n.context,document:t,socketId:n.socketId,connection:e,documentName:t.name,requestHeaders:n.request.headers,requestParameters:X_(n.request),update:r};return this.hooks(`beforeHandleMessage`,i)}),a.beforeSync((e,r)=>{let i={clientsCount:t.getConnectionsCount(),context:n.context,document:t,documentName:t.name,connection:e,type:r.type,payload:r.payload};return this.hooks(`beforeSync`,i)}),a}},Q_=class{constructor(e,t,n){this.document=null,this.document=e,this.instance=t,this.context=n??{},this.document.addDirectConnection()}async transact(e){if(!this.document)throw Error(`direct connection closed`);this.document.transact(t=>{e(this.document)},{source:`local`,context:this.context})}async disconnect(){this.document&&=(this.document?.removeDirectConnection(),await this.instance.storeDocumentHooks(this.document,{clientsCount:this.document.getConnectionsCount(),lastContext:this.context,lastTransactionOrigin:{source:`local`,context:this.context},document:this.document,documentName:this.document.name,instance:this.instance},!0),this.document.getConnectionsCount()===0&&!this.document.saveMutex.isLocked()&&(await this.instance.hooks(`onDisconnect`,{instance:this.instance,clientsCount:this.document.getConnectionsCount(),context:this.context,document:this.document,socketId:`server`,documentName:this.document.name,requestHeaders:new Headers,requestParameters:new Ee}),await this.instance.unloadDocument(this.document)),null)}};const $_=()=>{let e=new Map,t=new Map;return{debounce:async(n,r,i,a)=>{let o=e.get(n),s=o?.start||Date.now(),c=async()=>{t.has(n)&&await t.get(n),e.delete(n);let i=r();t.set(n,i);let a=await i;return t.delete(n),a};if(o?.timeout&&clearTimeout(o.timeout),i===0||Date.now()-s>=a)return c();e.set(n,{start:s,timeout:setTimeout(c,i),func:c})},isDebounced:t=>e.has(t),isCurrentlyExecuting:e=>t.has(e),executeNow:t=>{let n=e.get(t);if(n)return clearTimeout(n.timeout),n.func()}}},ev={name:null,timeout:6e4,debounce:2e3,maxDebounce:1e4,quiet:!1,yDocOptions:{gc:!0,gcFilter:()=>!0},unloadImmediately:!0};var tv=class{constructor(e){this.configuration={...ev,extensions:[],onConfigure:()=>new Promise(e=>e(null)),onListen:()=>new Promise(e=>e(null)),onUpgrade:()=>new Promise(e=>e(null)),onConnect:()=>new Promise(e=>e(null)),connected:()=>new Promise(e=>e(null)),beforeHandleMessage:()=>new Promise(e=>e(null)),beforeSync:()=>new Promise(e=>e(null)),beforeBroadcastStateless:()=>new Promise(e=>e(null)),onStateless:()=>new Promise(e=>e(null)),onChange:()=>new Promise(e=>e(null)),onCreateDocument:()=>new Promise(e=>e(null)),onLoadDocument:()=>new Promise(e=>e(null)),onStoreDocument:()=>new Promise(e=>e(null)),afterStoreDocument:()=>new Promise(e=>e(null)),onAwarenessUpdate:()=>new Promise(e=>e(null)),onRequest:()=>new Promise(e=>e(null)),onDisconnect:()=>new Promise(e=>e(null)),onDestroy:()=>new Promise(e=>e(null))},this.loadingDocuments=new Map,this.unloadingDocuments=new Map,this.documents=new Map,this.debouncer=$_(),e&&this.configure(e)}configure(e){return this.configuration={...this.configuration,...e},this.configuration.extensions.sort((e,t)=>{let n=e.priority===void 0?100:e.priority,r=t.priority===void 0?100:t.priority;return n>r?-1:n<r?1:0}),this.configuration.extensions.push({onConfigure:this.configuration.onConfigure,onListen:this.configuration.onListen,onUpgrade:this.configuration.onUpgrade,onConnect:this.configuration.onConnect,connected:this.configuration.connected,onAuthenticate:this.configuration.onAuthenticate,onTokenSync:this.configuration.onTokenSync,onLoadDocument:this.configuration.onLoadDocument,afterLoadDocument:this.configuration.afterLoadDocument,beforeHandleMessage:this.configuration.beforeHandleMessage,beforeBroadcastStateless:this.configuration.beforeBroadcastStateless,beforeSync:this.configuration.beforeSync,onStateless:this.configuration.onStateless,onChange:this.configuration.onChange,onStoreDocument:this.configuration.onStoreDocument,afterStoreDocument:this.configuration.afterStoreDocument,onAwarenessUpdate:this.configuration.onAwarenessUpdate,onRequest:this.configuration.onRequest,beforeUnloadDocument:this.configuration.beforeUnloadDocument,afterUnloadDocument:this.configuration.afterUnloadDocument,onDisconnect:this.configuration.onDisconnect,onDestroy:this.configuration.onDestroy}),this.hooks(`onConfigure`,{configuration:this.configuration,version:Y_,instance:this}),this}getDocumentsCount(){return this.documents.size}getConnectionsCount(){let e=new Set,t=Array.from(this.documents.values()).reduce((t,n)=>(n.getConnections().forEach(({socketId:t})=>{e.add(t)}),t+n.directConnectionsCount),0);return e.size+t}flushPendingStores(){this.documents.forEach(e=>{let t=`onStoreDocument-${e.name}`;!e.isLoading&&this.debouncer.isDebounced(t)&&this.debouncer.executeNow(t)})}closeConnections(e){this.documents.forEach(t=>{e&&t.name!==e||t.connections.forEach((e,t)=>{t.close(Cg)})})}handleConnection(e,t,n={}){let r=new Z_(e,t,this,this.hooks.bind(this),{timeout:this.configuration.timeout},n);return r.onClose((e,t)=>{e.getConnectionsCount()>0||(!e.isLoading&&this.debouncer.isDebounced(`onStoreDocument-${e.name}`)?this.configuration.unloadImmediately&&this.debouncer.executeNow(`onStoreDocument-${e.name}`):this.unloadDocument(e))}),r}handleDocumentUpdate(e,t,n){let r=U_(t)&&t.source===`connection`?t.connection:void 0,i=r?.request,a=U_(t)?t.source===`connection`?t.connection.context:t.source===`local`?t.context??{}:{}:{},o={instance:this,clientsCount:e.getConnectionsCount(),document:e,documentName:e.name,requestHeaders:i?.headers??new Headers,requestParameters:X_(i),socketId:r?.socketId??``,update:n,transactionOrigin:t,connection:r,context:a};if(this.hooks(`onChange`,o),W_(t))return;let s={instance:this,clientsCount:e.getConnectionsCount(),document:e,lastContext:a,lastTransactionOrigin:t,documentName:e.name};this.storeDocumentHooks(e,s)}async createDocument(e,t,n,r,i){if(!e.trim())throw Error(`Document name must not be empty`);let a=this.loadingDocuments.get(e);if(a)return a;let o=this.documents.get(e);if(o)return Promise.resolve(o);let s=this.loadDocument(e,t,n,r,i);this.loadingDocuments.set(e,s);try{let t=await s;return this.documents.set(e,t),this.loadingDocuments.delete(e),t}catch(t){throw this.loadingDocuments.delete(e),t}}async loadDocument(e,t,n,r,i){let a=t.headers,o=X_(t),s=i??{},c=await this.hooks(`onCreateDocument`,{documentName:e,requestHeaders:a,requestParameters:o,connectionConfig:r,context:s,socketId:n,instance:this}),l=new J_(e,{...this.configuration.yDocOptions,...c}),u={instance:this,context:s,connectionConfig:r,document:l,documentName:e,socketId:n,requestHeaders:a,requestParameters:o};try{await this.hooks(`onLoadDocument`,u,e=>{e instanceof wr?Br(l,Ur(e)):e instanceof Uint8Array&&Br(l,e)})}catch(t){throw this.closeConnections(e),this.unloadDocument(l),t}return l.isLoading=!1,l.onUpdate((e,t,n)=>{e.lastChangeTime=Date.now(),this.handleDocumentUpdate(e,t,n)}),await this.hooks(`afterLoadDocument`,u),l.beforeBroadcastStateless((e,t)=>{let n={document:e,documentName:e.name,payload:t};this.hooks(`beforeBroadcastStateless`,n)}),l.awareness.on(`update`,(t,n)=>{this.hooks(`onAwarenessUpdate`,{document:l,documentName:e,instance:this,...t,transactionOrigin:n,connection:U_(n)&&n.source===`connection`?n.connection:void 0,awareness:l.awareness,states:Dg(l.awareness.getStates())})}),l}storeDocumentHooks(e,t,n){let r=`onStoreDocument-${e.name}`;return this.debouncer.debounce(r,async()=>{try{await e.saveMutex.runExclusive(async()=>{await this.hooks(`onStoreDocument`,t),await this.hooks(`afterStoreDocument`,t)})}catch(t){if(t instanceof Og){setTimeout(()=>{this.shouldUnloadDocument(e)&&this.unloadDocument(e)},0);return}console.error(`Caught error during storeDocumentHooks. Document stays in memory to avoid data loss`,t);return}setTimeout(()=>{this.shouldUnloadDocument(e)&&this.unloadDocument(e)},0)},n?0:this.configuration.debounce,this.configuration.maxDebounce)}hooks(e,t,n=null){let{extensions:r}=this.configuration,i=Promise.resolve();return r.filter(t=>typeof t[e]==`function`).forEach(r=>{i=i.then(()=>r[e]?.(t)).catch(t=>{throw t?.message&&console.error(`[${e}]`,t.message),t}),n&&(i=i.then((...e)=>n(...e)))}),i}shouldUnloadDocument(e){return(this.debouncer.isDebounced(`onStoreDocument-${e.name}`)||this.debouncer.isCurrentlyExecuting(`onStoreDocument-${e.name}`)||e.saveMutex.isLocked())===!1&&e.getConnectionsCount()===0}async unloadDocument(e){let t=e.name;if(!this.shouldUnloadDocument(e)||!this.documents.has(t))return;if(this.unloadingDocuments.has(t))return this.unloadingDocuments.get(t);let n=(async()=>{try{await this.hooks(`beforeUnloadDocument`,{instance:this,documentName:t,document:e})}catch{return}this.shouldUnloadDocument(e)&&(this.documents.delete(t),e.destroy(),await this.hooks(`afterUnloadDocument`,{instance:this,documentName:t}))})();this.unloadingDocuments.set(t,Promise.resolve(n)),await n,this.unloadingDocuments.delete(t)}async openDirectConnection(e,t){return new Q_(await this.createDocument(e,new Request(`http://localhost`),De.randomUUID(),{isAuthenticated:!0,readOnly:!1},t),this,t)}},nv=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),rv=oe(import.meta.url),iv=nv(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),av=nv(((e,t)=>{let{EMPTY_BUFFER:n}=iv(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}if(t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=rv(`bufferutil`);t.exports.mask=function(t,n,r,i,o){o<48?a(t,n,r,i,o):e.mask(t,n,r,i,o)},t.exports.unmask=function(t,n){t.length<32?o(t,n):e.unmask(t,n)}}catch{}})),ov=nv(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),sv=nv(((e,t)=>{let n=rv(`zlib`),r=av(),i=ov(),{kStatusCode:a}=iv(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;t.exports=class{constructor(e,t,n){this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,p||=new i(this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit)}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,g),this._inflate.on(`data`,h)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,m)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(e){if(this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(e);return}this[f]=RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})),cv=nv(((e,t)=>{let{isUtf8:n}=rv(`buffer`),{hasBlob:r}=iv(),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=rv(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})),lv=nv(((e,t)=>{let{Writable:n}=rv(`stream`),r=sv(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=iv(),{concat:c,toArrayBuffer:l,unmask:u}=av(),{isValidStatusCode:d,isValidUTF8:f}=cv(),p=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=a;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}}})),uv=nv(((e,t)=>{let{Duplex:n}=rv(`stream`),{randomFillSync:r}=rv(`crypto`),i=sv(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=iv(),{isBlob:c,isValidStatusCode:l}=cv(),{mask:u,toBuffer:d}=av(),f=Symbol(`kByteLength`),p=Buffer.alloc(4),m=8*1024,h,g=m;t.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=s,this[o]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||p,t.generateMask?t.generateMask(n):(g===m&&(h===void 0&&(h=Buffer.alloc(m)),r(h,0,m),g=0),n[0]=h[g++],n[1]=h[g++],n[2]=h[g++],n[3]=h[g++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[f]!==void 0?s=t[f]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(u(e,n,l,a,s),[l]):(u(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=a;else if(typeof t!=`number`||!l(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`?o.write(n,2):o.set(n,2)}let s={[f]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,s),i):this.enqueue([this.dispatch,o,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[i.extensionName],a=t.binary?2:1,o=t.compress,s,l;typeof e==`string`?(s=Buffer.byteLength(e),l=!1):c(e)?(s=e.size,l=!1):(e=d(e),s=e.length,l=d.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,a=0),t.fin&&(this._firstFragment=!0);let u={[f]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:l,rsv1:o};c(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[f],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(_,this,e,i);return}this._bufferedBytes-=r[f];let a=d(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(v,this,e,i)})}dispatch(t,n,r,a){if(!n){this.sendFrame(e.frame(t,r),a);return}let o=this._extensions[i.extensionName];this._bufferedBytes+=r[f],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){_(this,Error(`The socket was closed while data was being compressed`),a);return}this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),a),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function _(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function v(e,t,n){_(e,t,n),e.onerror(t)}})),dv=nv(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=iv(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,`target`,{enumerable:!0}),Object.defineProperty(f.prototype,`type`,{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,`code`,{enumerable:!0}),Object.defineProperty(p.prototype,`reason`,{enumerable:!0}),Object.defineProperty(p.prototype,`wasClean`,{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,`error`,{enumerable:!0}),Object.defineProperty(m.prototype,`message`,{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),fv=nv(((e,t)=>{let{tokenChars:n}=cv();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),pv=nv(((e,t)=>{let n=rv(`events`),r=rv(`https`),i=rv(`http`),a=rv(`net`),o=rv(`tls`),{randomBytes:s,createHash:c}=rv(`crypto`),{Duplex:l,Readable:u}=rv(`stream`),{URL:d}=rv(`url`),f=sv(),p=lv(),m=uv(),{isBlob:h}=cv(),{BINARY_TYPES:g,CLOSE_TIMEOUT:_,EMPTY_BUFFER:v,GUID:y,kForOnEventAttribute:b,kListener:x,kStatusCode:S,kWebSocket:C,NOOP:w}=iv(),{EventTarget:{addEventListener:T,removeEventListener:E}}=dv(),{format:D,parse:O}=fv(),{toBuffer:k}=av(),A=Symbol(`kAborted`),j=[8,13],M=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],ee=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var N=class e extends n{constructor(t,n,r){super(),this._binaryType=g[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=v,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),te(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){g.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new p({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new m(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[C]=this,a[C]=this,t[C]=this,i.on(`conclude`,ae),i.on(`drain`,I),i.on(`error`,oe),i.on(`message`,L),i.on(`ping`,ce),i.on(`pong`,le),a.onerror=R,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,fe),t.on(`data`,pe),t.on(`end`,me),t.on(`error`,he),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){F(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),de(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ie(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||v,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ie(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||v,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ie(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[f.extensionName]||(i.compress=!1),this._sender.send(t||v,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){F(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(N,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(N.prototype,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(N,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(N.prototype,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(N,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(N.prototype,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(N,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),Object.defineProperty(N.prototype,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(N.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(N.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[b])return t[x];return null},set(t){for(let t of this.listeners(e))if(t[b]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[b]:!0})}})}),N.prototype.addEventListener=T,N.prototype.removeEventListener=E,t.exports=N;function te(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_,protocolVersion:j[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!j.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${j.join(`, `)})`);let l;if(t instanceof d)l=t;else try{l=new d(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}l.protocol===`http:`?l.protocol=`ws:`:l.protocol===`https:`&&(l.protocol=`wss:`),e._url=l.href;let u=l.protocol===`wss:`,p=l.protocol===`ws+unix:`,m;if(l.protocol!==`ws:`&&!u&&!p?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?m=`The URL's pathname is empty`:l.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;ne(e,t);return}let h=u?443:80,g=s(16).toString(`base64`),v=u?r.request:i.request,b=new Set,x;if(o.createConnection=o.createConnection||(u?re:P),o.defaultPort=o.defaultPort||h,o.port=l.port||h,o.host=l.hostname.startsWith(`[`)?l.hostname.slice(1,-1):l.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=l.pathname+l.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(x=new f(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=D({[f.extensionName]:x.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!ee.test(e)||b.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);b.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(l.username||l.password)&&(o.auth=`${l.username}:${l.password}`),p){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let S;if(o.followRedirects){if(e._redirects===0){e._originalIpc=p,e._originalSecure=u,e._originalHostOrSocketPath=p?o.socketPath:l.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=p?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:l.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),S=e._req=v(o),e._redirects&&e.emit(`redirect`,e.url,S)}else S=e._req=v(o);o.timeout&&S.on(`timeout`,()=>{F(e,S,`Opening handshake has timed out`)}),S.on(`error`,t=>{S===null||S[A]||(S=e._req=null,ne(e,t))}),S.on(`response`,r=>{let i=r.headers.location,s=r.statusCode;if(i&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){F(e,S,`Maximum redirects exceeded`);return}S.abort();let r;try{r=new d(i,t)}catch{ne(e,SyntaxError(`Invalid URL: ${i}`));return}te(e,r,n,a)}else e.emit(`unexpected-response`,S,r)||F(e,S,`Unexpected server response: ${r.statusCode}`)}),S.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==N.CONNECTING)return;S=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){F(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+y).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){F(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],l;if(s===void 0?b.size&&(l=`Server sent no subprotocol`):b.size?b.has(s)||(l=`Server sent an invalid subprotocol`):l=`Server sent a subprotocol but none was requested`,l){F(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!x){F(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=O(u)}catch{F(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){F(e,n,`Server indicated an extension that was not requested`);return}try{x.accept(t[f.extensionName])}catch{F(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[f.extensionName]=x}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(S,e):S.end()}function ne(e,t){e._readyState=N.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function P(e){return e.path=e.socketPath,a.connect(e)}function re(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function F(e,t,n){e._readyState=N.CLOSING;let r=Error(n);Error.captureStackTrace(r,F),t.setHeader?(t[A]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(ne,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function ie(e,t,n){if(t){let n=h(t)?t.size:k(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${M[e.readyState]})`);process.nextTick(n,t)}}function ae(e,t){let n=this[C];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[C]!==void 0&&(n._socket.removeListener(`data`,pe),process.nextTick(ue,n._socket),e===1005?n.close():n.close(e,t))}function I(){let e=this[C];e.isPaused||e._socket.resume()}function oe(e){let t=this[C];t._socket[C]!==void 0&&(t._socket.removeListener(`data`,pe),process.nextTick(ue,t._socket),t.close(e[S])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function se(){this[C].emitClose()}function L(e,t){this[C].emit(`message`,e,t)}function ce(e){let t=this[C];t._autoPong&&t.pong(e,!this._isServer,w),t.emit(`ping`,e)}function le(e){this[C].emit(`pong`,e)}function ue(e){e.resume()}function R(e){let t=this[C];t.readyState!==N.CLOSED&&(t.readyState===N.OPEN&&(t._readyState=N.CLOSING,de(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function de(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function fe(){let e=this[C];if(this.removeListener(`close`,fe),this.removeListener(`data`,pe),this.removeListener(`end`,me),e._readyState=N.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[C]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,se),e._receiver.on(`finish`,se))}function pe(e){this[C]._receiver.write(e)||this.pause()}function me(){let e=this[C];e._readyState=N.CLOSING,e._receiver.end(),this.end()}function he(){let e=this[C];this.removeListener(`error`,he),this.on(`error`,w),e&&(e._readyState=N.CLOSING,this.destroy())}})),mv=nv(((e,t)=>{pv();let{Duplex:n}=rv(`stream`);function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})),hv=nv(((e,t)=>{let{tokenChars:n}=cv();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),gv=nv(((e,t)=>{let n=rv(`events`),r=rv(`http`),{Duplex:i}=rv(`stream`),{createHash:a}=rv(`crypto`),o=fv(),s=sv(),c=hv(),l=pv(),{CLOSE_TIMEOUT:u,GUID:d,kWebSocket:f}=iv(),p=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:u,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=m(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(h,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(h,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{h(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,g);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){v(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){v(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!p.test(i)){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){_(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{v(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&f!==void 0){let n=new s(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=o.parse(f);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{v(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${l===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return _(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return _(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[f])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return _(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+d).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
77
74
  `).join(`\r
78
75
  `)),i.removeListener(`error`,g),p.setSocket(i,c,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on(`close`,()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(h,this)})),l(p,r)}};function m(e,t){for(let n of Object.keys(t))e.on(n,t[n]);return function(){for(let n of Object.keys(t))e.removeListener(n,t[n])}}function h(e){e._state=2,e.emit(`close`)}function g(){this.destroy()}function _(e,t,n,i){n||=r.STATUS_CODES[t],i={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(n),...i},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${r.STATUS_CODES[t]}\r\n`+Object.keys(i).map(e=>`${e}: ${i[e]}`).join(`\r
79
76
  `)+`\r
80
77
  \r
81
- `+n)}function v(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,v),e.emit(`wsClientError`,r,n,t)}else _(n,r,i,a)}}));fv(),sv(),cv(),dv(),mv();var hv=class{hocuspocus;log=Mc(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){this.mutateAgentFocus(n=>({...n,[e]:t}))}clearFocus(e){this.mutateAgentFocus(t=>{if(!(e in t))return t;let{[e]:n,...r}=t;return r})}getFocusMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentFocus??{}:{}}mutateAgentFocus(e){let t=this.resolveAwareness();if(t)try{let n=t.getLocalState()??{},r=e(n.agentFocus??{});t.setLocalState({...n,agentFocus:r})}catch(e){this.log.error({err:e},`[agent-focus] awareness mutation failed`)}}resolveAwareness(){let e=this.hocuspocus.documents.get(r);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),gv(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function gv(e){return e?.awareness??null}var _v=e(n(((e,t)=>{function n(e){return Array.isArray(e)?e:[e]}let r=/^\s+$/,i=/(?:[^\\]|^)\\$/,a=/^\\!/,o=/^\\#/,s=/\r?\n/g,c=/^\.*\/|^\.+$/,l=`node-ignore`;typeof Symbol<`u`&&(l=Symbol.for(`node-ignore`));let u=l,d=(e,t,n)=>Object.defineProperty(e,t,{value:n}),f=/([0-z])-([0-z])/g,p=()=>!1,m=e=>e.replace(f,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:``),h=e=>{let{length:t}=e;return e.slice(0,t-t%2)},g=[[/^\uFEFF/,()=>``],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf(`\\`)===0?` `:``)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+` `}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>`[^/]`],[/^\//,()=>`^`],[/\//g,()=>`\\/`],[/^\^*\\\*\\\*\\\//,()=>`^(?:.*\\/)?`],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?`^`:`(?:^|\\/)`}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,n)=>t+6<n.length?`(?:\\/[^\\/]+)*`:`\\/.+`],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,n)=>t+n.replace(/\\\*/g,`[^\\/]*`)],[/\\\\\\(?=[$.|*+(){^])/g,()=>`\\`],[/\\\\/g,()=>`\\`],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,r,i)=>t===`\\`?`\\[${n}${h(r)}${i}`:i===`]`&&r.length%2==0?`[${m(n)}${r}]`:`[]`],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(e,t)=>`${t?`${t}[^/]+`:`[^/]*`}(?=$|\\/$)`]],_=Object.create(null),v=(e,t)=>{let n=_[e];return n||(n=g.reduce((t,[n,r])=>t.replace(n,r.bind(e)),e),_[e]=n),t?new RegExp(n,`i`):new RegExp(n)},y=e=>typeof e==`string`,b=e=>e&&y(e)&&!r.test(e)&&!i.test(e)&&e.indexOf(`#`)!==0,x=e=>e.split(s);var S=class{constructor(e,t,n,r){this.origin=e,this.pattern=t,this.negative=n,this.regex=r}};let C=(e,t)=>{let n=e,r=!1;e.indexOf(`!`)===0&&(r=!0,e=e.substr(1)),e=e.replace(a,`!`).replace(o,`#`);let i=v(e,t);return new S(n,e,r,i)},w=(e,t)=>{throw new t(e)},T=(e,t,n)=>y(e)?e?T.isNotRelative(e)?n(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):!0:n(`path must not be empty`,TypeError):n(`path must be a string, but got \`${t}\``,TypeError),E=e=>c.test(e);T.isNotRelative=E,T.convert=e=>e;var D=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){d(this,u,!0),this._rules=[],this._ignoreCase=t,this._allowRelativePaths=n,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}_addPattern(e){if(e&&e[u]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(b(e)){let t=C(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,n(y(e)?x(e):e).forEach(this._addPattern,this),this._added&&this._initCache(),this}addPattern(e){return this.add(e)}_testOne(e,t){let n=!1,r=!1;return this._rules.forEach(i=>{let{negative:a}=i;r===a&&n!==r||a&&!n&&!r&&!t||i.regex.test(e)&&(n=!a,r=a)}),{ignored:n,unignored:r}}_test(e,t,n,r){let i=e&&T.convert(e);return T(i,e,this._allowRelativePaths?p:w),this._t(i,t,n,r)}_t(e,t,n,r){if(e in t)return t[e];if(r||=e.split(`/`),r.pop(),!r.length)return t[e]=this._testOne(e,n);let i=this._t(r.join(`/`)+`/`,t,n,r);return t[e]=i.ignored?i:this._testOne(e,n)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return n(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}};let O=e=>new D(e);if(O.isPathValid=e=>T(e&&T.convert(e),e,p),O.default=O,t.exports=O,typeof process<`u`&&(process.env&&process.env.IGNORE_TEST_WIN32||process.platform===`win32`)){T.convert=e=>/^\\\\\?\\/.test(e)||/["<>|\u0000-\u001F]+/u.test(e)?e:e.replace(/\\/g,`/`);let e=/^[a-z]:\//i;T.isNotRelative=t=>e.test(t)||E(t)}}))(),1);const vv=new Set([`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`,`.git`]);function yv(e){let{projectDir:t,contentDir:n,includePatterns:r,excludePatterns:i}=e,o=ze(r,{dot:!0}),s=(0,_v.default)();s.add(`.git`);let c=Ce(t,`.gitignore`),l=[];if(L(c))try{let e=xv(R(c,`utf-8`));l.push(...e),s.add(e)}catch(e){console.warn(`[content-filter] Failed to read .gitignore at ${c}:`,e)}let u=B(t,n),d=u.startsWith(`..`);if(i.length>0&&(u?s.add(i.map(e=>`${u}/${e}`)):s.add(i)),u){let e=Ce(n,`.gitignore`);if(L(e))try{let t=xv(R(e,`utf-8`)).map(e=>e.startsWith(`!`)?`!${u}/${e.slice(1)}`:`${u}/${e}`);s.add(t)}catch(t){console.warn(`[content-filter] Failed to read .gitignore at ${e}:`,t)}}Sv(n,t,s);let f=[...l,...i].filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`)),p=new Map;function m(e){if(d)return!1;let t=u?`${u}/${e}`:e;return s.ignores(t)}return bv(n,``,o,m,p),{isExcluded(e){if(q(Ef(e))||!d&&m(e))return!0;if(o(e))return!1;let t=Se(e).slice(1).toLowerCase();if(a.has(t)){let t=xe(e),n=t===`.`?``:t;if((p.get(n)??0)>0)return!1}return!0},isDirExcluded(e){let t=e.split(`/`)[0];if(vv.has(t))return!0;if(d)return!1;let n=u?`${u}/${e}`:e;return s.ignores(n)||s.ignores(`${n}/`)},getWatcherIgnoreGlobs(){return f},incrementMdDir(e){let t=e===`.`?``:e;p.set(t,(p.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,n=p.get(t)??0;n<=1?p.delete(t):p.set(t,n-1)}}}function bv(e,t,n,r,i){let a;try{a=de(e,{withFileTypes:!0})}catch{return}for(let o of a){let a=t?`${t}/${o.name}`:o.name;if(o.isDirectory()){if(vv.has(o.name)||r(a)||r(`${a}/`))continue;bv(Ce(e,o.name),a,n,r,i)}else if(o.isFile()&&Tf(o.name)&&n(a)&&!r(a)){let e=t===``?``:t;i.set(e,(i.get(e)??0)+1)}}}function xv(e){return e.split(`
82
- `).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`))}function Sv(e,t,n){let r;try{r=de(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory ${e}:`,t);return}for(let i of r){if(!i.isDirectory()||vv.has(i.name))continue;let r=Ce(e,i.name),a=B(t,r);if(a.startsWith(`..`)||n.ignores(a)||n.ignores(`${a}/`))continue;let o=Ce(r,`.gitignore`);if(L(o))try{let e=xv(R(o,`utf-8`)).map(e=>e.startsWith(`!`)?`!${a}/${e.slice(1)}`:`${a}/${e}`);n.add(e)}catch(e){console.warn(`[content-filter] Failed to read nested .gitignore at ${o}:`,e)}Sv(r,t,n)}}const Cv={source:`local`,skipStoreHooks:!0,context:{origin:`file-watcher`,paired:!0}};function wv(e,t,n){if(q(t))return;let r=e.documents.get(t);if(!r)return;let{frontmatter:i,body:a}=A(n),o=el.parseWithFallback(a),s=tl.nodeFromJSON(o),c=r.getXmlFragment(`default`);r.transact(()=>{ls(r,c,s,{mapping:new Map,isOMark:new Map}),r.getMap(`metadata`).set(`frontmatter`,i);let e=r.getText(`source`),t=e.toString();t!==n&&p(e,t,n)},Cv),zp(t,n)}const Tv=new Set([`HEAD`,`MERGE_HEAD`,`ORIG_HEAD`,`index.lock`]);function Ev(e){let t=V(e,`.git`);try{let n=he(t);if(n.isDirectory())return t;if(n.isFile()){let n=R(t,`utf-8`).trim().match(/^gitdir:\s*(.+)$/);if(n)return V(e,n[1])}}catch{}return null}function Dv(e){try{let t=R(V(e,`HEAD`),`utf-8`).trim();if(t.startsWith(`ref: `)){let n=V(e,t.slice(5));try{return R(n,`utf-8`).trim()}catch{try{let n=R(V(e,`packed-refs`),`utf-8`),r=t.slice(5),i=n.split(`
83
- `).find(e=>e.endsWith(` ${r}`));if(i)return i.split(` `)[0]}catch{}return null}}return t.length>=40?t.slice(0,40):null}catch{return null}}function Ov(e){try{let t=R(V(e,`HEAD`),`utf-8`).trim();return t.startsWith(`ref: refs/heads/`)?t.slice(16):t.length>=40?`detached-${t.slice(0,12)}`:null}catch{return null}}async function kv(e,t,n){let r=Ev(e);if(!r)return{unsubscribe:async()=>{},getLastKnownBranch:()=>null};let i=r,a=!1,o=null,s=null,c=null,l=null;async function u(e){if(f&&await f,!a)return;o&&=(clearTimeout(o),null),s&&=(clearTimeout(s),null);let t=Dv(i),r=c!==t,u=Ov(i),d;d=u?.startsWith(`detached-`)?`detached-head`:l===u?`within-branch`:`cross-branch`;let p=l;try{await n({headMoved:r,oldHead:c,newHead:t,timeout:e,batchKind:d,oldBranch:p,newBranch:u})}catch(e){console.error(`[head-watcher] onBatchEnd callback failed:`,e)}finally{a=!1,c=t,l=u}}function d(){o&&clearTimeout(o),o=setTimeout(()=>{o=null,u(!1)},100)}let f=null;async function p(e){if(!a){a=!0,c=Dv(i);let n=(async()=>{try{await t({trigger:e})}catch(e){console.error(`[head-watcher] onBatchBegin callback failed:`,e)}})();f=n,await n,f=null,s=setTimeout(()=>{s=null,u(!0)},3e4)}d()}let m,h;try{h=await import(`@parcel/watcher`)}catch(e){throw Error(`@parcel/watcher unavailable for HEAD watching: ${e instanceof Error?e.message:e}`)}try{let e=await h.subscribe(i,(e,t)=>{if(e){console.error(`[head-watcher]`,e);return}for(let e of t){let t=e.path.split(`/`).pop()??``;if(Tv.has(t)){p(t);break}}});m=()=>e.unsubscribe()}catch(e){throw Error(`@parcel/watcher subscribe failed for HEAD watching: ${e instanceof Error?e.message:e}`)}return c=Dv(i),l=Ov(i),console.log(`[head-watcher] Watching ${i} for HEAD changes`),{unsubscribe:async()=>{a&&await u(!1),o&&clearTimeout(o),s&&clearTimeout(s),await m()},getLastKnownBranch:()=>l}}function Av(e){return typeof e!=`object`||!e?!1:e.source===`local`}function jv(e){let t=e.getXmlFragment(`default`),n=el.serialize(fs(t,tl).toJSON()),r=e.getMap(`metadata`).get(`frontmatter`);return u(typeof r==`string`?r:``,n)}function Mv(e){let{backlinkIndex:t,signalChannel:n,debounceMs:r=100}=e,i=new Map;function a(e){let t=i.get(e);t&&(clearTimeout(t),i.delete(e))}function o(e,o){a(e),i.set(e,setTimeout(()=>{i.delete(e);try{t.updateDocumentFromMarkdown(e,jv(o)),n?.(`backlinks`),n?.(`graph`)}catch(t){console.error(`[live-derived-index] Failed to update backlinks for ${e}:`,t)}},r))}return{async onChange({documentName:e,document:t,transactionOrigin:n}){q(e)||Av(n)&&n.context?.origin===`file-watcher`||o(e,t)},async beforeUnloadDocument({documentName:e}){a(e)},async onDestroy(){for(let e of i.values())clearTimeout(e);i.clear()}}}const Nv={source:`local`,skipStoreHooks:!0,context:{origin:`observer-sync`}},Pv=e=>typeof e!=`object`||!e?!1:e.context?.paired===!0;function Fv(e=process.env){return e.NODE_ENV===`test`||e.OK_RETHROW_BRIDGE_LOSS===`1`}function Iv(e){let{doc:t,xmlFragment:n,ytext:r,mdManager:i,schema:a}=e,o=(t,n)=>{let r=process.env.OK_TELEMETRY_VERBOSE===`1`;console.warn(JSON.stringify({...t.toLog({verbose:r}),docName:e.docName??null,timestamp:new Date().toISOString()})),qc();let i=e.shadow?.();if(!i||!e.docName)return;let a=e.getBranch?.()??`main`,o=e.contentRoot??``;queueMicrotask(()=>{Ep(i,o,{kind:`bridge-merge-loss`,docName:e.docName,contents:n,label:`Before concurrent merge @ ${new Date().toISOString()}`,branch:a,metadata:{lostSubstrings:t.info.lostSubstrings}}).then(t=>{Jc(),console.warn(JSON.stringify({event:`bridge-merge-checkpoint-created`,docName:e.docName,sha:t,kind:`bridge-merge-loss`,timestamp:new Date().toISOString()}))}).catch(e=>{let t=e instanceof Error?e:Error(String(e));console.warn(`[Server Observer A] Silent checkpoint write failed:`,{name:t.name,message:t.message,stack:t.stack?.split(`
78
+ `+n)}function v(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,v),e.emit(`wsClientError`,r,n,t)}else _(n,r,i,a)}}));mv(),lv(),uv(),pv(),gv();var _v=class{hocuspocus;log=Pc(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){this.mutateAgentFocus(n=>({...n,[e]:t}))}clearFocus(e){this.mutateAgentFocus(t=>{if(!(e in t))return t;let{[e]:n,...r}=t;return r})}getFocusMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentFocus??{}:{}}mutateAgentFocus(e){let t=this.resolveAwareness();if(t)try{let n=t.getLocalState()??{},r=e(n.agentFocus??{});t.setLocalState({...n,agentFocus:r})}catch(e){this.log.error({err:e},`[agent-focus] awareness mutation failed`)}}resolveAwareness(){let e=this.hocuspocus.documents.get(r);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),vv(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function vv(e){return e?.awareness??null}var yv=e(n(((e,t)=>{function n(e){return Array.isArray(e)?e:[e]}let r=/^\s+$/,i=/(?:[^\\]|^)\\$/,a=/^\\!/,o=/^\\#/,s=/\r?\n/g,c=/^\.*\/|^\.+$/,l=`node-ignore`;typeof Symbol<`u`&&(l=Symbol.for(`node-ignore`));let u=l,d=(e,t,n)=>Object.defineProperty(e,t,{value:n}),f=/([0-z])-([0-z])/g,p=()=>!1,m=e=>e.replace(f,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:``),h=e=>{let{length:t}=e;return e.slice(0,t-t%2)},g=[[/^\uFEFF/,()=>``],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf(`\\`)===0?` `:``)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+` `}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>`[^/]`],[/^\//,()=>`^`],[/\//g,()=>`\\/`],[/^\^*\\\*\\\*\\\//,()=>`^(?:.*\\/)?`],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?`^`:`(?:^|\\/)`}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,n)=>t+6<n.length?`(?:\\/[^\\/]+)*`:`\\/.+`],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,n)=>t+n.replace(/\\\*/g,`[^\\/]*`)],[/\\\\\\(?=[$.|*+(){^])/g,()=>`\\`],[/\\\\/g,()=>`\\`],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,r,i)=>t===`\\`?`\\[${n}${h(r)}${i}`:i===`]`&&r.length%2==0?`[${m(n)}${r}]`:`[]`],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(e,t)=>`${t?`${t}[^/]+`:`[^/]*`}(?=$|\\/$)`]],_=Object.create(null),v=(e,t)=>{let n=_[e];return n||(n=g.reduce((t,[n,r])=>t.replace(n,r.bind(e)),e),_[e]=n),t?new RegExp(n,`i`):new RegExp(n)},y=e=>typeof e==`string`,b=e=>e&&y(e)&&!r.test(e)&&!i.test(e)&&e.indexOf(`#`)!==0,x=e=>e.split(s);var S=class{constructor(e,t,n,r){this.origin=e,this.pattern=t,this.negative=n,this.regex=r}};let C=(e,t)=>{let n=e,r=!1;e.indexOf(`!`)===0&&(r=!0,e=e.substr(1)),e=e.replace(a,`!`).replace(o,`#`);let i=v(e,t);return new S(n,e,r,i)},w=(e,t)=>{throw new t(e)},T=(e,t,n)=>y(e)?e?T.isNotRelative(e)?n(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):!0:n(`path must not be empty`,TypeError):n(`path must be a string, but got \`${t}\``,TypeError),E=e=>c.test(e);T.isNotRelative=E,T.convert=e=>e;var D=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){d(this,u,!0),this._rules=[],this._ignoreCase=t,this._allowRelativePaths=n,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}_addPattern(e){if(e&&e[u]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(b(e)){let t=C(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,n(y(e)?x(e):e).forEach(this._addPattern,this),this._added&&this._initCache(),this}addPattern(e){return this.add(e)}_testOne(e,t){let n=!1,r=!1;return this._rules.forEach(i=>{let{negative:a}=i;r===a&&n!==r||a&&!n&&!r&&!t||i.regex.test(e)&&(n=!a,r=a)}),{ignored:n,unignored:r}}_test(e,t,n,r){let i=e&&T.convert(e);return T(i,e,this._allowRelativePaths?p:w),this._t(i,t,n,r)}_t(e,t,n,r){if(e in t)return t[e];if(r||=e.split(`/`),r.pop(),!r.length)return t[e]=this._testOne(e,n);let i=this._t(r.join(`/`)+`/`,t,n,r);return t[e]=i.ignored?i:this._testOne(e,n)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return n(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}};let O=e=>new D(e);if(O.isPathValid=e=>T(e&&T.convert(e),e,p),O.default=O,t.exports=O,typeof process<`u`&&(process.env&&process.env.IGNORE_TEST_WIN32||process.platform===`win32`)){T.convert=e=>/^\\\\\?\\/.test(e)||/["<>|\u0000-\u001F]+/u.test(e)?e:e.replace(/\\/g,`/`);let e=/^[a-z]:\//i;T.isNotRelative=t=>e.test(t)||E(t)}}))(),1);const bv=new Set([`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`,`.git`]);function xv(e){let{projectDir:t,contentDir:n,includePatterns:r,excludePatterns:i}=e,o=Be(r,{dot:!0}),s=(0,yv.default)();s.add(`.git`);let c=Ce(t,`.gitignore`),l=[];if(L(c))try{let e=Cv(R(c,`utf-8`));l.push(...e),s.add(e)}catch(e){console.warn(`[content-filter] Failed to read .gitignore at ${c}:`,e)}let u=B(t,n),d=u.startsWith(`..`);if(i.length>0&&(u?s.add(i.map(e=>`${u}/${e}`)):s.add(i)),u){let e=Ce(n,`.gitignore`);if(L(e))try{let t=Cv(R(e,`utf-8`)).map(e=>e.startsWith(`!`)?`!${u}/${e.slice(1)}`:`${u}/${e}`);s.add(t)}catch(t){console.warn(`[content-filter] Failed to read .gitignore at ${e}:`,t)}}wv(n,t,s);let f=[...l,...i].filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`)),p=new Map;function m(e){if(d)return!1;let t=u?`${u}/${e}`:e;return s.ignores(t)}return Sv(n,``,o,m,p),{isExcluded(e){if(q(Of(e))||!d&&m(e))return!0;if(o(e))return!1;let t=Se(e).slice(1).toLowerCase();if(a.has(t)){let t=xe(e),n=t===`.`?``:t;if((p.get(n)??0)>0)return!1}return!0},isDirExcluded(e){let t=e.split(`/`)[0];if(bv.has(t))return!0;if(d)return!1;let n=u?`${u}/${e}`:e;return s.ignores(n)||s.ignores(`${n}/`)},getWatcherIgnoreGlobs(){return f},incrementMdDir(e){let t=e===`.`?``:e;p.set(t,(p.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,n=p.get(t)??0;n<=1?p.delete(t):p.set(t,n-1)}}}function Sv(e,t,n,r,i){let a;try{a=de(e,{withFileTypes:!0})}catch{return}for(let o of a){let a=t?`${t}/${o.name}`:o.name;if(o.isDirectory()){if(bv.has(o.name)||r(a)||r(`${a}/`))continue;Sv(Ce(e,o.name),a,n,r,i)}else if(o.isFile()&&Df(o.name)&&n(a)&&!r(a)){let e=t===``?``:t;i.set(e,(i.get(e)??0)+1)}}}function Cv(e){return e.split(`
79
+ `).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`))}function wv(e,t,n){let r;try{r=de(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory ${e}:`,t);return}for(let i of r){if(!i.isDirectory()||bv.has(i.name))continue;let r=Ce(e,i.name),a=B(t,r);if(a.startsWith(`..`)||n.ignores(a)||n.ignores(`${a}/`))continue;let o=Ce(r,`.gitignore`);if(L(o))try{let e=Cv(R(o,`utf-8`)).map(e=>e.startsWith(`!`)?`!${a}/${e.slice(1)}`:`${a}/${e}`);n.add(e)}catch(e){console.warn(`[content-filter] Failed to read nested .gitignore at ${o}:`,e)}wv(r,t,n)}}const Tv={source:`local`,skipStoreHooks:!0,context:{origin:`file-watcher`,paired:!0}};function Ev(e,t,n){if(q(t))return;let r=e.documents.get(t);if(!r)return;let{frontmatter:i,body:a}=A(n),o=nl.parseWithFallback(a),s=rl.nodeFromJSON(o),c=r.getXmlFragment(`default`);r.transact(()=>{ds(r,c,s,{mapping:new Map,isOMark:new Map}),r.getMap(`metadata`).set(`frontmatter`,i);let e=r.getText(`source`),t=e.toString();t!==n&&p(e,t,n)},Tv),Vp(t,n)}const Dv=new Set([`HEAD`,`MERGE_HEAD`,`ORIG_HEAD`,`index.lock`]);function Ov(e){let t=V(e,`.git`);try{let n=he(t);if(n.isDirectory())return t;if(n.isFile()){let n=R(t,`utf-8`).trim().match(/^gitdir:\s*(.+)$/);if(n)return V(e,n[1])}}catch{}return null}function kv(e){try{let t=R(V(e,`HEAD`),`utf-8`).trim();if(t.startsWith(`ref: `)){let n=V(e,t.slice(5));try{return R(n,`utf-8`).trim()}catch{try{let n=R(V(e,`packed-refs`),`utf-8`),r=t.slice(5),i=n.split(`
80
+ `).find(e=>e.endsWith(` ${r}`));if(i)return i.split(` `)[0]}catch{}return null}}return t.length>=40?t.slice(0,40):null}catch{return null}}function Av(e){try{let t=R(V(e,`HEAD`),`utf-8`).trim();return t.startsWith(`ref: refs/heads/`)?t.slice(16):t.length>=40?`detached-${t.slice(0,12)}`:null}catch{return null}}async function jv(e,t,n){let r=Ov(e);if(!r)return{unsubscribe:async()=>{},getLastKnownBranch:()=>null};let i=r,a=!1,o=null,s=null,c=null,l=null;async function u(e){if(f&&await f,!a)return;o&&=(clearTimeout(o),null),s&&=(clearTimeout(s),null);let t=kv(i),r=c!==t,u=Av(i),d;d=u?.startsWith(`detached-`)?`detached-head`:l===u?`within-branch`:`cross-branch`;let p=l;try{await n({headMoved:r,oldHead:c,newHead:t,timeout:e,batchKind:d,oldBranch:p,newBranch:u})}catch(e){console.error(`[head-watcher] onBatchEnd callback failed:`,e)}finally{a=!1,c=t,l=u}}function d(){o&&clearTimeout(o),o=setTimeout(()=>{o=null,u(!1)},100)}let f=null;async function p(e){if(!a){a=!0,c=kv(i);let n=(async()=>{try{await t({trigger:e})}catch(e){console.error(`[head-watcher] onBatchBegin callback failed:`,e)}})();f=n,await n,f=null,s=setTimeout(()=>{s=null,u(!0)},3e4)}d()}let m,h;try{h=await import(`@parcel/watcher`)}catch(e){throw Error(`@parcel/watcher unavailable for HEAD watching: ${e instanceof Error?e.message:e}`)}try{let e=await h.subscribe(i,(e,t)=>{if(e){console.error(`[head-watcher]`,e);return}for(let e of t){let t=e.path.split(`/`).pop()??``;if(Dv.has(t)){p(t);break}}});m=()=>e.unsubscribe()}catch(e){throw Error(`@parcel/watcher subscribe failed for HEAD watching: ${e instanceof Error?e.message:e}`)}return c=kv(i),l=Av(i),console.log(`[head-watcher] Watching ${i} for HEAD changes`),{unsubscribe:async()=>{a&&await u(!1),o&&clearTimeout(o),s&&clearTimeout(s),await m()},getLastKnownBranch:()=>l}}function Mv(e){return typeof e!=`object`||!e?!1:e.source===`local`}function Nv(e){let t=e.getXmlFragment(`default`),n=nl.serialize(ms(t,rl).toJSON()),r=e.getMap(`metadata`).get(`frontmatter`);return u(typeof r==`string`?r:``,n)}function Pv(e){let{backlinkIndex:t,signalChannel:n,debounceMs:r=100}=e,i=new Map;function a(e){let t=i.get(e);t&&(clearTimeout(t),i.delete(e))}function o(e,o){a(e),i.set(e,setTimeout(()=>{i.delete(e);try{t.updateDocumentFromMarkdown(e,Nv(o)),n?.(`backlinks`),n?.(`graph`)}catch(t){console.error(`[live-derived-index] Failed to update backlinks for ${e}:`,t)}},r))}return{async onChange({documentName:e,document:t,transactionOrigin:n}){q(e)||Mv(n)&&n.context?.origin===`file-watcher`||o(e,t)},async beforeUnloadDocument({documentName:e}){a(e)},async onDestroy(){for(let e of i.values())clearTimeout(e);i.clear()}}}const Fv={source:`local`,skipStoreHooks:!0,context:{origin:`observer-sync`}},Iv=e=>typeof e!=`object`||!e?!1:e.context?.paired===!0;function Lv(e=process.env){return e.NODE_ENV===`test`||e.OK_RETHROW_BRIDGE_LOSS===`1`}function Rv(e){let{doc:t,xmlFragment:n,ytext:r,mdManager:i,schema:a}=e,o=(t,n)=>{let r=process.env.OK_TELEMETRY_VERBOSE===`1`;console.warn(JSON.stringify({...t.toLog({verbose:r}),docName:e.docName??null,timestamp:new Date().toISOString()})),Yc();let i=e.shadow?.();if(!i||!e.docName)return;let a=e.getBranch?.()??`main`,o=e.contentRoot??``;queueMicrotask(()=>{Op(i,o,{kind:`bridge-merge-loss`,docName:e.docName,contents:n,label:`Before concurrent merge @ ${new Date().toISOString()}`,branch:a,metadata:{lostSubstrings:t.info.lostSubstrings}}).then(t=>{Xc(),console.warn(JSON.stringify({event:`bridge-merge-checkpoint-created`,docName:e.docName,sha:t,kind:`bridge-merge-loss`,timestamp:new Date().toISOString()}))}).catch(e=>{let t=e instanceof Error?e:Error(String(e));console.warn(`[Server Observer A] Silent checkpoint write failed:`,{name:t.name,message:t.message,stack:t.stack?.split(`
84
81
  `).slice(0,4).join(`
85
- `)})})})},s=``,c=!1,l=!1;try{let e=fs(n,a).toJSON(),r=i.serialize(e);s=u(f(t),r)}catch(e){Kc(`a`),console.warn(`[Server Observer A] Baseline init failed — starting from empty snapshot:`,e instanceof Error?e.message:String(e)),s=``}let m=()=>{try{let e=fs(n,a).toJSON(),c=i.serialize(e),l=u(f(t),c);if(s===l)return;let m=r.toString();if(d(m)===d(l)){s=l;return}let h=s;t.transact(()=>{if(m===s)C(r,m,l);else try{p(r,m,D(s,l,m))}catch(e){if(!(e instanceof y)||(o(e,h),Fv()))throw e;p(r,m,e.info.result)}},Nv),Wc(`a`),s=r.toString()}catch(e){Kc(`a`),console.error(`[Server Observer A] Failed to sync tree→text:`,e);try{s=r.toString()}catch(e){console.warn(`[Server Observer A] Baseline recovery also failed:`,e)}}},h=(e,r)=>{if(r.origin!==Nv){if(Pv(r.origin)){try{let e=fs(n,a).toJSON(),r=i.serialize(e);s=u(f(t),r)}catch(e){Kc(`a`),console.warn(`[Server Observer A] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),c=!0}return}c=!0}};if(n.length>0&&r.length===0)try{let e=fs(n,a).toJSON(),o=i.serialize(e),c=u(f(t),o);t.transact(()=>{r.insert(0,c)},Nv),s=c}catch(e){Kc(`a`),console.error(`[Server Observer A] Failed initial sync:`,e),s=``}let g=()=>{try{let a=r.toString(),{frontmatter:o,body:c}=A(a);if(d(s)===d(a)){let e=t.getMap(`metadata`);(e.get(`frontmatter`)??``)!==o&&t.transact(()=>{e.set(`frontmatter`,o)},Nv);return}let l;try{l=i.parse(c)}catch(e){if(e instanceof SyntaxError||e instanceof _||e instanceof RangeError&&e.message.includes(`Invalid content for node`)){console.debug(`[Server Observer B] Parse skipped (partial/invalid markdown):`,e),s=u(o,c);return}throw e}let f=e.schema.nodeFromJSON(l);t.transact(()=>{ls(t,n,f,{mapping:new Map,isOMark:new Map}),t.getMap(`metadata`).set(`frontmatter`,o)},Nv),Wc(`b`);try{let e=i.serialize(l);if(e===c)s=u(o,c);else{let n=u(o,e),i=r.toString();i!==n&&t.transact(()=>{p(r,i,n)},Nv),s=n}}catch(e){console.warn(`[Server Observer B] Post-sync re-serialization failed — using input body as baseline:`,e),s=u(o,c)}}catch(e){Kc(`b`),console.error(`[Server Observer B] Failed to sync text→tree:`,e);try{let e=fs(n,a).toJSON(),r=i.serialize(e);s=u(f(t),r)}catch(e){console.warn(`[Server Observer B] Baseline recovery also failed:`,e)}}},v=(e,r)=>{if(r.origin!==Nv){if(Pv(r.origin)){try{let e=fs(n,a).toJSON(),r=i.serialize(e);s=u(f(t),r)}catch(e){Kc(`b`),console.warn(`[Server Observer B] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),l=!0}return}l=!0}},b=(t,n)=>{if(!c&&!l){e.onDispatch?.(`none`);return}if(n.every(e=>e.origin===Nv)){c=!1,l=!1,e.onDispatch?.(`none`);return}c&&(c=!1,e.onDispatch?.(`a`),m()),l&&(l=!1,e.onDispatch?.(`b`),g())};return n.observeDeep(h),r.observe(v),t.on(`afterAllTransactions`,b),()=>{t.off(`afterAllTransactions`,b),n.unobserveDeep(h),r.unobserve(v)}}function Lv(e){let t=new Map,n=new Map;return{async afterLoadDocument({documentName:r,document:i}){if(q(r)||t.has(r))return;let a=i,o=a.getXmlFragment(`default`),s=a.getText(`source`),c=()=>{try{let n=Iv({doc:a,xmlFragment:o,ytext:s,mdManager:e.mdManager,schema:e.schema,docName:r,shadow:e.shadowRef?()=>e.shadowRef?.current:void 0,getBranch:e.getCurrentBranch?()=>e.getCurrentBranch?.()??`main`:void 0,contentRoot:e.contentRoot});return t.set(r,n),!0}catch(e){return console.error(`[ServerObserverExtension] Failed to attach observers for '${r}':`,e),Kc(`a`),Kc(`b`),!1}};if(!c()){let e=setTimeout(()=>{n.delete(r),!t.has(r)&&(console.warn(`[ServerObserverExtension] Retrying observer attachment for '${r}'`),c())},5e3);n.set(r,e)}},async afterUnloadDocument({documentName:e}){let r=n.get(e);r&&(clearTimeout(r),n.delete(e));let i=t.get(e);i&&(i(),t.delete(e))},async onDestroy(){for(let e of n.values())clearTimeout(e);n.clear();for(let[e,n]of t.entries())try{n()}catch(t){console.error(`[ServerObserverExtension] Cleanup failed for '${e}':`,t)}t.clear()}}}const Rv=Mc(`conflict-storage`);var zv=class{storePath;projectDir;branch;conflicts=[];constructor(e,t,n=`main`){this.storePath=Ce(e,`.open-knowledge`,`conflicts.json`),this.projectDir=t,this.branch=n,this.load()}load(){if(!L(this.storePath)){this.conflicts=[];return}try{let e=R(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){Rv.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){Rv.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=xe(this.storePath);L(e)||le(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};z(this.storePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){Rv.warn({err:e},`[conflicts] failed to save conflicts.json`)}}addConflict(e){let t=this.conflicts.findIndex(t=>t.file===e.file);t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,n,r=[]){if(!this.conflicts.find(t=>t.file===e))throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let{createGitInstance:i}=await import(`./git-handle-BIUIUt1r.mjs`),a=i(this.projectDir,{credentialArgs:r});switch(t){case`mine`:await a.git.raw([`checkout`,`--ours`,`--`,e]),await a.git.raw([`add`,`--`,e]);break;case`theirs`:await a.git.raw([`checkout`,`--theirs`,`--`,e]),await a.git.raw([`add`,`--`,e]);break;case`content`:{if(!n)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=V(this.projectDir),r=V(t,e);if(r!==t&&!r.startsWith(`${t}/`))throw Error(`[conflicts] file path escapes project directory: ${e}`);z(r,n,`utf-8`),await a.git.raw([`add`,`--`,e]);break}default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await a.git.raw([`commit`,`--no-edit`]),Rv.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=(await a.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).split(`
86
- `).map(e=>e.trim()).filter(Boolean);for(let t of e)this.addConflict({file:t,detectedAt:n});r=e.length>0}catch(e){Rv.warn({err:e},`[conflicts] commit failed and re-scan of unmerged files failed — falling back to single-file re-add`)}r||this.addConflict({file:e,detectedAt:n}),Rv.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`)}}};function Bv(e){return e.git?.toString()??e.message??``}function Vv(e,t){return t.some(t=>t.test(e))}const Hv=[/\b(401|403)\b/,/authentication failed/i,/authorization failed/i,/invalid credentials/i,/credential helper/i,/bad credentials/i,/token.*expired/i,/expired.*token/i,/permission denied.*\(publickey\)/i,/host key verification failed/i,/fatal:.*repository.*not found/i],Uv=[/insufficient scopes/i,/missing.*scope/i,/required scope/i],Wv=[/non-fast-forward/i,/rejected.*non-fast-forward/i,/would overwrite.*commits/i,/\[rejected\]/,/fetch first/i,/updates were rejected/i],Gv=[/protected branch/i,/refusing to allow/i,/at least \d+ approving review/i,/required status check/i,/branch policy/i,/GH001/i,/GH002/i,/GH003/i,/GH004/i,/push declined due to repository rule/i,/cannot push to a protected branch/i],Kv=[/\bmerge conflict\b/i,/automatic merge failed/i,/CONFLICT \(/,/\bconflict\b.*\bmerge\b/i,/(?:^|\n)CONFLICTS:\s/i],qv=[/lfs.*quota/i,/exceeded.*bandwidth/i,/lfs storage/i],Jv=[/file.*too large/i,/exceeded.*file size/i,/push file size limit/i],Yv=[/pre-receive hook/i,/remote:.*rejected/i,/hook declined/i],Xv=[/secret.*detected/i,/push.*secret/i,/secret scanning/i,/leaking.*credentials/i,/token.*detected/i],Zv=[/\.git\/index\.lock/i,/another git process/i,/unable to create.*\.lock/i],Qv=[/dirty.*working tree/i,/working tree.*not clean/i,/untracked.*files.*would be overwritten/i,/local changes.*would be overwritten/i,/uncommitted changes/i,/changes.*not staged/i,/please.*commit.*changes/i,/please.*stash/i,/commit your changes or stash/i],$v=[/no space left on device/i,/disk quota exceeded/i,/ENOSPC/],ey=[/could not resolve host/i,/name.*resolution/i,/connection.*timed out/i,/operation timed out/i,/connection refused/i,/network.*unreachable/i,/ssl.*handshake/i,/unable to connect/i,/getaddrinfo/i,/econnrefused/i,/enotfound/i,/etimedout/i,/ehostunreach/i],ty=[/\bHTTP[\s/]*5[0-9]{2}\b/i,/\bstatus:?\s*5[0-9]{2}\b/i,/\berror\s*5[0-9]{2}\b/i,/\bresponse.*?\b5[0-9]{2}\b/i],ny=[/\bHTTP[\s/]*429\b/i,/\bstatus:?\s*429\b/i,/\berror\s*429\b/i,/rate.?limit/i,/too many requests/i];function ry(e){let t=e instanceof Error?e:Error(String(e)),n=Bv(t),r=`${t.message}\n${n}`.toLowerCase();return Vv(r,Zv)?{class:`local`,subclass:`index-lock`,retryable:!0,message:`Git index locked by another process`,rawStderr:n}:Vv(r,Qv)?{class:`local`,subclass:`dirty-tree`,retryable:!0,message:`Working tree has uncommitted changes`,rawStderr:n}:Vv(r,$v)?{class:`local`,subclass:`disk-full`,retryable:!0,message:`Disk full or quota exceeded`,rawStderr:n}:Vv(r,Uv)?{class:`auth`,subclass:`scope-mismatch`,retryable:!1,message:`GitHub token missing required scopes`,rawStderr:n}:Vv(r,Hv)?/\b401\b/.test(r)||/token.*expired/i.test(r)?{class:`auth`,subclass:`401`,retryable:!1,message:`Authentication failed — token may be expired`,rawStderr:n}:/\b403\b/.test(r)?Vv(r,Gv)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:{class:`auth`,subclass:`403`,retryable:!1,message:`Access denied (403)`,rawStderr:n}:{class:`auth`,subclass:`unknown-auth`,retryable:!1,message:`Authentication failed`,rawStderr:n}:Vv(r,Gv)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:Vv(r,Wv)?{class:`semantic`,subclass:`non-fast-forward`,retryable:!1,message:`Push rejected — remote has diverged (non-fast-forward)`,rawStderr:n}:Vv(r,Kv)?{class:`semantic`,subclass:`merge-conflict`,retryable:!1,message:`Merge conflict — manual resolution required`,rawStderr:n}:Vv(r,qv)?{class:`structural`,subclass:`lfs-quota`,retryable:!1,message:`Git LFS quota exceeded`,rawStderr:n}:Vv(r,Jv)?{class:`structural`,subclass:`large-file`,retryable:!1,message:`File exceeds size limit`,rawStderr:n}:Vv(r,Xv)?{class:`structural`,subclass:`secret-detected`,retryable:!1,message:`Push blocked — secret or credential detected in content`,rawStderr:n}:Vv(r,Yv)?{class:`structural`,subclass:`pre-receive-hook`,retryable:!1,message:`Push rejected by server pre-receive hook`,rawStderr:n}:Vv(r,ny)?{class:`network`,subclass:`429`,retryable:!0,message:`Rate limited — too many requests`,rawStderr:n}:Vv(r,ty)?{class:`network`,subclass:`5xx`,retryable:!0,message:`Server error (5xx)`,rawStderr:n}:Vv(r,ey)?/timed? out/i.test(r)?{class:`network`,subclass:`timeout`,retryable:!0,message:`Connection timed out`,rawStderr:n}:/refused/i.test(r)||/econnrefused/i.test(r)?{class:`network`,subclass:`connection-refused`,retryable:!0,message:`Connection refused`,rawStderr:n}:/resolve.*host/i.test(r)||/enotfound/i.test(r)||/getaddrinfo/i.test(r)?{class:`network`,subclass:`dns`,retryable:!0,message:`DNS resolution failed`,rawStderr:n}:{class:`network`,subclass:`unknown-network`,retryable:!0,message:`Network error`,rawStderr:n}:{class:`local`,subclass:`unknown-local`,retryable:!0,message:t.message||`Unknown git error`,rawStderr:n}}function iy(e,t,n=Date.now()){if(!e)return 0;let r=new Date(e).getTime();if(Number.isNaN(r))return 0;let i=r+t*1e3;return Math.max(0,i-n)}const $=Mc(`sync-engine`),ay=/^[0-9a-f]{40}$/i;function oy(e){let t=e*1e3,n=t*.15*(2*Math.random()-1);return Math.round(t+n)}function sy(e){try{let t=Ce(e,`.git`,`HEAD`);if(!L(t))return!1;let n=R(t,`utf-8`).trim(),r=/^ref:\s+(refs\/.+)$/.exec(n);if(!r)return!1;let i=r[1];if(L(Ce(e,`.git`,i)))return!1;let a=Ce(e,`.git`,`packed-refs`);if(L(a)){let e=R(a,`utf-8`);if(RegExp(`^[0-9a-f]+\\s+${i}$`,`m`).test(e))return!1}return!0}catch{return!1}}function cy(e){return e>=8?3600*1e3:e>=5?900*1e3:e>=3?300*1e3:0}var ly=class{state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;pullIntervalSeconds;pushIntervalSeconds;syncEnabled;credentialArgs;cc1Broadcaster;onStateChange;setBatchInProgress;pullTimer=null;pushTimer=null;stateSaveTimer=null;lastSyncUtc=null;lastFetchUtc=null;lastPushedSha=null;consecutiveFailures=0;ahead=0;behind=0;conflictCount=0;error;pausedReason;currentBranch=`main`;pullInFlight=!1;pushInFlight=!1;hasRemote=!1;identityUnresolved=!1;statePath;conflictStore;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.contentRoot=e.contentRoot??``,this.pullIntervalSeconds=e.pullIntervalSeconds??30,this.pushIntervalSeconds=e.pushIntervalSeconds??60,this.syncEnabled=e.syncEnabled,this.credentialArgs=e.credentialArgs??[],this.cc1Broadcaster=e.cc1Broadcaster??null,this.onStateChange=e.onStateChange,this.setBatchInProgress=e.setBatchInProgress,this.statePath=V(this.contentDir,`.open-knowledge`,`sync-state.json`),this.conflictStore=new zv(this.contentDir,this.projectDir,this.currentBranch)}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=I(this.projectDir,{credentialArgs:this.credentialArgs});e=(await t.git.raw(`remote`,`-v`)).trim().length>0,this.hasRemote=e;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();e&&e!==`HEAD`&&(this.currentBranch=e,this.conflictStore.setBranch(e))}catch{}}catch(e){$.warn({err:e},`[sync] remote detection failed`)}if(this.syncEnabled!==!0){e&&this.transitionTo(`disabled`),$.info({hasRemote:e,syncEnabled:this.syncEnabled},`[sync] sync not enabled — staying inactive`);return}if(!e){$.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=L(Ce(this.projectDir,`.git`,`MERGE_HEAD`));if(this.conflictCount>0&&!t)$.warn({count:this.conflictCount},`[sync] persisted conflicts but no MERGE_HEAD — clearing stale state`),this.conflictStore.clear(),this.conflictCount=0;else if(this.conflictCount>0&&t)try{let e=(await I(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim(),t=new Set(e?e.split(`
87
- `).map(e=>e.trim()).filter(Boolean):[]),n=this.conflictCount;for(let e of this.conflictStore.list())t.has(e.file)||this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<n&&$.info({cleared:n-this.conflictCount,remaining:this.conflictCount},`[sync] reconciled conflicts.json against git unmerged index`)}catch(e){$.warn({err:e},`[sync] failed to reconcile conflicts with git index`)}if(t&&this.conflictCount===0){$.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await I(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`merge`,`--abort`])}catch(e){$.warn({err:e},`[sync] git merge --abort for stale MERGE_HEAD failed`)}}if(this.conflictCount>0){this.transitionTo(`conflict`),$.warn({count:this.conflictCount},`[sync] restarted with active conflicts — sync paused`);return}let n=iy(this.lastFetchUtc,this.pullIntervalSeconds),r=iy(this.lastSyncUtc,this.pushIntervalSeconds);this.schedulePull(n>0?n:void 0),this.schedulePush(r>0?r:void 0),$.info({branch:this.currentBranch,pullDelayMs:n,pushDelayMs:r},`[sync] started`)}stop(){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.stateSaveTimer!==null&&(clearTimeout(this.stateSaveTimer),this.stateSaveTimer=null),this.state!==`dormant`&&this.transitionTo(`dormant`)}async destroy(){this.stop(),this.saveStateNow()}async setEnabled(e){if(this.syncEnabled!==e){if(this.syncEnabled=e,!e){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null);let e=Date.now();for(;this.pullInFlight||this.pushInFlight;){if(Date.now()-e>3e4){$.warn({pullInFlight:this.pullInFlight,pushInFlight:this.pushInFlight},`[sync] setEnabled(false): timed out waiting for in-flight cycle to drain`);break}await new Promise(e=>setTimeout(e,50))}this.pausedReason=void 0,this.error=void 0,this.transitionTo(this.hasRemote?`disabled`:`dormant`),this.saveStateNow();return}try{this.hasRemote=(await I(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw(`remote`,`-v`)).trim().length>0}catch(e){$.warn({err:e},`[sync] remote detection failed during enable`)}if(this.pausedReason=void 0,this.error=void 0,this.consecutiveFailures=0,!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow()}}async trigger(e=`sync`){this.consecutiveFailures=0,(this.pausedReason===`dirty-tree`||this.pausedReason===`external-changes-pending`)&&(this.pausedReason=void 0,this.error=void 0),this.state===`dormant`||this.state===`disabled`||this.state===`conflict`||this.state===`auth-error`?$.warn({op:e,state:this.state,syncEnabled:this.syncEnabled,hasRemote:this.hasRemote,pausedReason:this.pausedReason,conflictCount:this.conflictCount},`[sync] trigger(${e}) ignored — state=${this.state}`):$.info({op:e,state:this.state},`[sync] trigger(${e}) running`),e===`push`?await this.runPushCycle():(e===`pull`||await this.runPushCycle(),await this.runPullCycle())}getStatus(){return{state:this.state,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,ahead:this.ahead,behind:this.behind,consecutiveFailures:this.consecutiveFailures,conflictCount:this.conflictCount,hasRemote:this.hasRemote,syncEnabled:this.syncEnabled===!0,identityUnresolved:this.identityUnresolved,error:this.error,pausedReason:this.pausedReason}}async refreshIdentity(){let e=await _m(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}getConflicts(){return this.conflictStore.list()}async resolveConflict(e,t,n){await this.conflictStore.resolveConflict(e,t,n),this.conflictCount=this.conflictStore.count(),this.conflictCount===0&&this.state===`conflict`&&(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()),this.scheduleSaveState()}updateCurrentBranch(e){e===null?this.state!==`dormant`&&this.state!==`disabled`&&(this.transitionTo(`disabled`),this.pausedReason=`detached-head`,this.scheduleSaveState()):this.currentBranch!==e&&(this.currentBranch=e,this.conflictStore.setBranch(e),this.state===`disabled`&&this.pausedReason===`detached-head`&&(this.pausedReason=void 0,this.transitionTo(`idle`),this.schedulePull(),this.schedulePush()))}schedulePull(e){this.pullTimer!==null&&clearTimeout(this.pullTimer);let t=e??this.effectivePullDelayMs();this.pullTimer=setTimeout(()=>{this.pullTimer=null,this.runPullCycle().catch(e=>{$.error({err:e},`[sync] pull cycle uncaught error`)})},t)}schedulePush(e){this.pushTimer!==null&&clearTimeout(this.pushTimer);let t=e??oy(this.pushIntervalSeconds);this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.runPushCycle().catch(e=>{$.error({err:e},`[sync] push cycle uncaught error`)})},t)}effectivePullDelayMs(){let e=this.consecutiveFailures,t=cy(e);return t>0?t:oy(this.pullIntervalSeconds)}async runPullCycle(){if(!this.pullInFlight&&!(this.state===`dormant`||this.state===`disabled`)){if(this.state===`conflict`){this.schedulePull();return}if(sy(this.projectDir)){this.schedulePull();return}this.pullInFlight=!0;try{await this.doPullCycle()}finally{this.pullInFlight=!1,this.schedulePull()}}}async doPullCycle(){let e=I(this.projectDir,{credentialArgs:this.credentialArgs}),t;try{let n=(await e.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();if(!n||n===`HEAD`){this.transitionTo(`disabled`),this.pausedReason=`detached-head`,$.warn({},`[sync] detached HEAD — pausing sync`);return}t=n,this.currentBranch=t}catch(e){this.handleError(ry(e instanceof Error?e:Error(String(e))));return}this.transitionTo(`fetching`);try{await e.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.consecutiveFailures=0,this.error=void 0}catch(e){let t=ry(e instanceof Error?e:Error(String(e)));this.handleError(t);return}try{let t=await e.git.status();this.ahead=t.ahead,this.behind=t.behind}catch{}if(this.behind>0&&this.conflictCount===0){this.transitionTo(`pulling`),this.setBatchInProgress?.(!0);try{if(await this.commitDirtyContentFilesToHead(e),!await this.pauseIfNonContentDirty(e))return;await e.git.merge([`origin/${t}`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`)}catch(e){let t=ry(e instanceof Error?e:Error(String(e)));t.class===`semantic`&&t.subclass===`merge-conflict`?await this.handleMergeConflict():this.handleError(t);return}finally{this.setBatchInProgress?.(!1)}}else this.transitionTo(`idle`);this.scheduleSaveState()}async runPushCycle(){if(!this.pushInFlight&&!(this.state===`dormant`||this.state===`disabled`)&&!(this.state===`conflict`||this.state===`auth-error`)){if(sy(this.projectDir)){this.schedulePush();return}this.pushInFlight=!0;try{await this.doPushCycle(1)}finally{this.pushInFlight=!1,this.schedulePush()}}}async doPushCycle(e=0){let t=this.gatherContentFilesSync(),n=Ce(be(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),r=null;this.transitionTo(`pushing`);try{await ae(async()=>{let e=I(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:n});if(sy(this.projectDir)){$.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}let i;try{i=(await e.git.revparse(`HEAD`)).trim()}catch(e){let t=e instanceof Error?e.message:String(e),n=`${t}\n${e.git?.toString()??t}`;if(/unknown revision or path not in the working tree/i.test(n)||/ambiguous argument 'HEAD'/i.test(n)||/does not have any commits yet/i.test(n)){$.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}this.handleError(ry(e instanceof Error?e:Error(String(e))));return}await e.git.raw([`read-tree`,i]);let a=new Set;try{let t=(await e.git.raw([`ls-tree`,`-r`,`--name-only`,i])).trim();for(let e of t?t.split(`
82
+ `)})})})},s=``,c=!1,l=!1;try{let e=ms(n,a).toJSON(),r=i.serialize(e);s=u(f(t),r)}catch(e){Jc(`a`),console.warn(`[Server Observer A] Baseline init failed — starting from empty snapshot:`,e instanceof Error?e.message:String(e)),s=``}let m=()=>{try{let e=ms(n,a).toJSON(),c=i.serialize(e),l=u(f(t),c);if(s===l)return;let m=r.toString();if(d(m)===d(l)){s=l;return}let h=s;t.transact(()=>{if(m===s)C(r,m,l);else try{p(r,m,D(s,l,m))}catch(e){if(!(e instanceof y)||(o(e,h),Lv()))throw e;p(r,m,e.info.result)}},Fv),Kc(`a`),s=r.toString()}catch(e){Jc(`a`),console.error(`[Server Observer A] Failed to sync tree→text:`,e);try{s=r.toString()}catch(e){console.warn(`[Server Observer A] Baseline recovery also failed:`,e)}}},h=(e,r)=>{if(r.origin!==Fv){if(Iv(r.origin)){try{let e=ms(n,a).toJSON(),r=i.serialize(e);s=u(f(t),r)}catch(e){Jc(`a`),console.warn(`[Server Observer A] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),c=!0}return}c=!0}};if(n.length>0&&r.length===0)try{let e=ms(n,a).toJSON(),o=i.serialize(e),c=u(f(t),o);t.transact(()=>{r.insert(0,c)},Fv),s=c}catch(e){Jc(`a`),console.error(`[Server Observer A] Failed initial sync:`,e),s=``}let g=()=>{try{let a=r.toString(),{frontmatter:o,body:c}=A(a);if(d(s)===d(a)){let e=t.getMap(`metadata`);(e.get(`frontmatter`)??``)!==o&&t.transact(()=>{e.set(`frontmatter`,o)},Fv);return}let l;try{l=i.parse(c)}catch(e){if(e instanceof SyntaxError||e instanceof _||e instanceof RangeError&&e.message.includes(`Invalid content for node`)){console.debug(`[Server Observer B] Parse skipped (partial/invalid markdown):`,e),s=u(o,c);return}throw e}let f=e.schema.nodeFromJSON(l);t.transact(()=>{ds(t,n,f,{mapping:new Map,isOMark:new Map}),t.getMap(`metadata`).set(`frontmatter`,o)},Fv),Kc(`b`);try{let e=i.serialize(l);if(e===c)s=u(o,c);else{let n=u(o,e),i=r.toString();i!==n&&t.transact(()=>{p(r,i,n)},Fv),s=n}}catch(e){console.warn(`[Server Observer B] Post-sync re-serialization failed — using input body as baseline:`,e),s=u(o,c)}}catch(e){Jc(`b`),console.error(`[Server Observer B] Failed to sync text→tree:`,e);try{let e=ms(n,a).toJSON(),r=i.serialize(e);s=u(f(t),r)}catch(e){console.warn(`[Server Observer B] Baseline recovery also failed:`,e)}}},v=(e,r)=>{if(r.origin!==Fv){if(Iv(r.origin)){try{let e=ms(n,a).toJSON(),r=i.serialize(e);s=u(f(t),r)}catch(e){Jc(`b`),console.warn(`[Server Observer B] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),l=!0}return}l=!0}},b=(t,n)=>{if(!c&&!l){e.onDispatch?.(`none`);return}if(n.every(e=>e.origin===Fv)){c=!1,l=!1,e.onDispatch?.(`none`);return}c&&(c=!1,e.onDispatch?.(`a`),m()),l&&(l=!1,e.onDispatch?.(`b`),g())};return n.observeDeep(h),r.observe(v),t.on(`afterAllTransactions`,b),()=>{t.off(`afterAllTransactions`,b),n.unobserveDeep(h),r.unobserve(v)}}function zv(e){let t=new Map,n=new Map;return{async afterLoadDocument({documentName:r,document:i}){if(q(r)||t.has(r))return;let a=i,o=a.getXmlFragment(`default`),s=a.getText(`source`),c=()=>{try{let n=Rv({doc:a,xmlFragment:o,ytext:s,mdManager:e.mdManager,schema:e.schema,docName:r,shadow:e.shadowRef?()=>e.shadowRef?.current:void 0,getBranch:e.getCurrentBranch?()=>e.getCurrentBranch?.()??`main`:void 0,contentRoot:e.contentRoot});return t.set(r,n),!0}catch(e){return console.error(`[ServerObserverExtension] Failed to attach observers for '${r}':`,e),Jc(`a`),Jc(`b`),!1}};if(!c()){let e=setTimeout(()=>{n.delete(r),!t.has(r)&&(console.warn(`[ServerObserverExtension] Retrying observer attachment for '${r}'`),c())},5e3);n.set(r,e)}},async afterUnloadDocument({documentName:e}){let r=n.get(e);r&&(clearTimeout(r),n.delete(e));let i=t.get(e);i&&(i(),t.delete(e))},async onDestroy(){for(let e of n.values())clearTimeout(e);n.clear();for(let[e,n]of t.entries())try{n()}catch(t){console.error(`[ServerObserverExtension] Cleanup failed for '${e}':`,t)}t.clear()}}}const Bv=Pc(`conflict-storage`);var Vv=class{storePath;projectDir;branch;conflicts=[];constructor(e,t,n=`main`){this.storePath=Ce(e,`.open-knowledge`,`conflicts.json`),this.projectDir=t,this.branch=n,this.load()}load(){if(!L(this.storePath)){this.conflicts=[];return}try{let e=R(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){Bv.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){Bv.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=xe(this.storePath);L(e)||le(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};z(this.storePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){Bv.warn({err:e},`[conflicts] failed to save conflicts.json`)}}addConflict(e){let t=this.conflicts.findIndex(t=>t.file===e.file);t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,n,r=[]){if(!this.conflicts.find(t=>t.file===e))throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let{createGitInstance:i}=await import(`./git-handle-BIUIUt1r.mjs`),a=i(this.projectDir,{credentialArgs:r});switch(t){case`mine`:await a.git.raw([`checkout`,`--ours`,`--`,e]),await a.git.raw([`add`,`--`,e]);break;case`theirs`:await a.git.raw([`checkout`,`--theirs`,`--`,e]),await a.git.raw([`add`,`--`,e]);break;case`content`:{if(!n)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=V(this.projectDir),r=V(t,e);if(r!==t&&!r.startsWith(`${t}/`))throw Error(`[conflicts] file path escapes project directory: ${e}`);z(r,n,`utf-8`),await a.git.raw([`add`,`--`,e]);break}default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await a.git.raw([`commit`,`--no-edit`]),Bv.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=(await a.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).split(`
83
+ `).map(e=>e.trim()).filter(Boolean);for(let t of e)this.addConflict({file:t,detectedAt:n});r=e.length>0}catch(e){Bv.warn({err:e},`[conflicts] commit failed and re-scan of unmerged files failed — falling back to single-file re-add`)}r||this.addConflict({file:e,detectedAt:n}),Bv.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`)}}};function Hv(e){return e.git?.toString()??e.message??``}function Uv(e,t){return t.some(t=>t.test(e))}const Wv=[/\b(401|403)\b/,/authentication failed/i,/authorization failed/i,/invalid credentials/i,/credential helper/i,/bad credentials/i,/token.*expired/i,/expired.*token/i,/permission denied.*\(publickey\)/i,/host key verification failed/i,/fatal:.*repository.*not found/i],Gv=[/insufficient scopes/i,/missing.*scope/i,/required scope/i],Kv=[/non-fast-forward/i,/rejected.*non-fast-forward/i,/would overwrite.*commits/i,/\[rejected\]/,/fetch first/i,/updates were rejected/i],qv=[/protected branch/i,/refusing to allow/i,/at least \d+ approving review/i,/required status check/i,/branch policy/i,/GH001/i,/GH002/i,/GH003/i,/GH004/i,/push declined due to repository rule/i,/cannot push to a protected branch/i],Jv=[/\bmerge conflict\b/i,/automatic merge failed/i,/CONFLICT \(/,/\bconflict\b.*\bmerge\b/i,/(?:^|\n)CONFLICTS:\s/i],Yv=[/lfs.*quota/i,/exceeded.*bandwidth/i,/lfs storage/i],Xv=[/file.*too large/i,/exceeded.*file size/i,/push file size limit/i],Zv=[/pre-receive hook/i,/remote:.*rejected/i,/hook declined/i],Qv=[/secret.*detected/i,/push.*secret/i,/secret scanning/i,/leaking.*credentials/i,/token.*detected/i],$v=[/\.git\/index\.lock/i,/another git process/i,/unable to create.*\.lock/i],ey=[/dirty.*working tree/i,/working tree.*not clean/i,/untracked.*files.*would be overwritten/i,/local changes.*would be overwritten/i,/uncommitted changes/i,/changes.*not staged/i,/please.*commit.*changes/i,/please.*stash/i,/commit your changes or stash/i],ty=[/no space left on device/i,/disk quota exceeded/i,/ENOSPC/],ny=[/could not resolve host/i,/name.*resolution/i,/connection.*timed out/i,/operation timed out/i,/connection refused/i,/network.*unreachable/i,/ssl.*handshake/i,/unable to connect/i,/getaddrinfo/i,/econnrefused/i,/enotfound/i,/etimedout/i,/ehostunreach/i],ry=[/\bHTTP[\s/]*5[0-9]{2}\b/i,/\bstatus:?\s*5[0-9]{2}\b/i,/\berror\s*5[0-9]{2}\b/i,/\bresponse.*?\b5[0-9]{2}\b/i],iy=[/\bHTTP[\s/]*429\b/i,/\bstatus:?\s*429\b/i,/\berror\s*429\b/i,/rate.?limit/i,/too many requests/i];function ay(e){let t=e instanceof Error?e:Error(String(e)),n=Hv(t),r=`${t.message}\n${n}`.toLowerCase();return Uv(r,$v)?{class:`local`,subclass:`index-lock`,retryable:!0,message:`Git index locked by another process`,rawStderr:n}:Uv(r,ey)?{class:`local`,subclass:`dirty-tree`,retryable:!0,message:`Working tree has uncommitted changes`,rawStderr:n}:Uv(r,ty)?{class:`local`,subclass:`disk-full`,retryable:!0,message:`Disk full or quota exceeded`,rawStderr:n}:Uv(r,Gv)?{class:`auth`,subclass:`scope-mismatch`,retryable:!1,message:`GitHub token missing required scopes`,rawStderr:n}:Uv(r,Wv)?/\b401\b/.test(r)||/token.*expired/i.test(r)?{class:`auth`,subclass:`401`,retryable:!1,message:`Authentication failed — token may be expired`,rawStderr:n}:/\b403\b/.test(r)?Uv(r,qv)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:{class:`auth`,subclass:`403`,retryable:!1,message:`Access denied (403)`,rawStderr:n}:{class:`auth`,subclass:`unknown-auth`,retryable:!1,message:`Authentication failed`,rawStderr:n}:Uv(r,qv)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:Uv(r,Kv)?{class:`semantic`,subclass:`non-fast-forward`,retryable:!1,message:`Push rejected — remote has diverged (non-fast-forward)`,rawStderr:n}:Uv(r,Jv)?{class:`semantic`,subclass:`merge-conflict`,retryable:!1,message:`Merge conflict — manual resolution required`,rawStderr:n}:Uv(r,Yv)?{class:`structural`,subclass:`lfs-quota`,retryable:!1,message:`Git LFS quota exceeded`,rawStderr:n}:Uv(r,Xv)?{class:`structural`,subclass:`large-file`,retryable:!1,message:`File exceeds size limit`,rawStderr:n}:Uv(r,Qv)?{class:`structural`,subclass:`secret-detected`,retryable:!1,message:`Push blocked — secret or credential detected in content`,rawStderr:n}:Uv(r,Zv)?{class:`structural`,subclass:`pre-receive-hook`,retryable:!1,message:`Push rejected by server pre-receive hook`,rawStderr:n}:Uv(r,iy)?{class:`network`,subclass:`429`,retryable:!0,message:`Rate limited — too many requests`,rawStderr:n}:Uv(r,ry)?{class:`network`,subclass:`5xx`,retryable:!0,message:`Server error (5xx)`,rawStderr:n}:Uv(r,ny)?/timed? out/i.test(r)?{class:`network`,subclass:`timeout`,retryable:!0,message:`Connection timed out`,rawStderr:n}:/refused/i.test(r)||/econnrefused/i.test(r)?{class:`network`,subclass:`connection-refused`,retryable:!0,message:`Connection refused`,rawStderr:n}:/resolve.*host/i.test(r)||/enotfound/i.test(r)||/getaddrinfo/i.test(r)?{class:`network`,subclass:`dns`,retryable:!0,message:`DNS resolution failed`,rawStderr:n}:{class:`network`,subclass:`unknown-network`,retryable:!0,message:`Network error`,rawStderr:n}:{class:`local`,subclass:`unknown-local`,retryable:!0,message:t.message||`Unknown git error`,rawStderr:n}}function oy(e,t,n=Date.now()){if(!e)return 0;let r=new Date(e).getTime();if(Number.isNaN(r))return 0;let i=r+t*1e3;return Math.max(0,i-n)}const $=Pc(`sync-engine`),sy=/^[0-9a-f]{40}$/i;function cy(e){let t=e*1e3,n=t*.15*(2*Math.random()-1);return Math.round(t+n)}function ly(e){try{let t=Ce(e,`.git`,`HEAD`);if(!L(t))return!1;let n=R(t,`utf-8`).trim(),r=/^ref:\s+(refs\/.+)$/.exec(n);if(!r)return!1;let i=r[1];if(L(Ce(e,`.git`,i)))return!1;let a=Ce(e,`.git`,`packed-refs`);if(L(a)){let e=R(a,`utf-8`);if(RegExp(`^[0-9a-f]+\\s+${i}$`,`m`).test(e))return!1}return!0}catch{return!1}}function uy(e){return e>=8?3600*1e3:e>=5?900*1e3:e>=3?300*1e3:0}var dy=class{state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;pullIntervalSeconds;pushIntervalSeconds;syncEnabled;credentialArgs;cc1Broadcaster;onStateChange;setBatchInProgress;pullTimer=null;pushTimer=null;stateSaveTimer=null;lastSyncUtc=null;lastFetchUtc=null;lastPushedSha=null;consecutiveFailures=0;ahead=0;behind=0;conflictCount=0;error;pausedReason;currentBranch=`main`;pullInFlight=!1;pushInFlight=!1;hasRemote=!1;identityUnresolved=!1;statePath;conflictStore;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.contentRoot=e.contentRoot??``,this.pullIntervalSeconds=e.pullIntervalSeconds??30,this.pushIntervalSeconds=e.pushIntervalSeconds??60,this.syncEnabled=e.syncEnabled,this.credentialArgs=e.credentialArgs??[],this.cc1Broadcaster=e.cc1Broadcaster??null,this.onStateChange=e.onStateChange,this.setBatchInProgress=e.setBatchInProgress,this.statePath=V(this.contentDir,`.open-knowledge`,`sync-state.json`),this.conflictStore=new Vv(this.contentDir,this.projectDir,this.currentBranch)}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=I(this.projectDir,{credentialArgs:this.credentialArgs});e=(await t.git.raw(`remote`,`-v`)).trim().length>0,this.hasRemote=e;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();e&&e!==`HEAD`&&(this.currentBranch=e,this.conflictStore.setBranch(e))}catch{}}catch(e){$.warn({err:e},`[sync] remote detection failed`)}if(this.syncEnabled!==!0){e&&this.transitionTo(`disabled`),$.info({hasRemote:e,syncEnabled:this.syncEnabled},`[sync] sync not enabled — staying inactive`);return}if(!e){$.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=L(Ce(this.projectDir,`.git`,`MERGE_HEAD`));if(this.conflictCount>0&&!t)$.warn({count:this.conflictCount},`[sync] persisted conflicts but no MERGE_HEAD — clearing stale state`),this.conflictStore.clear(),this.conflictCount=0;else if(this.conflictCount>0&&t)try{let e=(await I(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim(),t=new Set(e?e.split(`
84
+ `).map(e=>e.trim()).filter(Boolean):[]),n=this.conflictCount;for(let e of this.conflictStore.list())t.has(e.file)||this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<n&&$.info({cleared:n-this.conflictCount,remaining:this.conflictCount},`[sync] reconciled conflicts.json against git unmerged index`)}catch(e){$.warn({err:e},`[sync] failed to reconcile conflicts with git index`)}if(t&&this.conflictCount===0){$.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await I(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`merge`,`--abort`])}catch(e){$.warn({err:e},`[sync] git merge --abort for stale MERGE_HEAD failed`)}}if(this.conflictCount>0){this.transitionTo(`conflict`),$.warn({count:this.conflictCount},`[sync] restarted with active conflicts — sync paused`);return}let n=oy(this.lastFetchUtc,this.pullIntervalSeconds),r=oy(this.lastSyncUtc,this.pushIntervalSeconds);this.schedulePull(n>0?n:void 0),this.schedulePush(r>0?r:void 0),$.info({branch:this.currentBranch,pullDelayMs:n,pushDelayMs:r},`[sync] started`)}stop(){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.stateSaveTimer!==null&&(clearTimeout(this.stateSaveTimer),this.stateSaveTimer=null),this.state!==`dormant`&&this.transitionTo(`dormant`)}async destroy(){this.stop(),this.saveStateNow()}async setEnabled(e){if(this.syncEnabled!==e){if(this.syncEnabled=e,!e){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null);let e=Date.now();for(;this.pullInFlight||this.pushInFlight;){if(Date.now()-e>3e4){$.warn({pullInFlight:this.pullInFlight,pushInFlight:this.pushInFlight},`[sync] setEnabled(false): timed out waiting for in-flight cycle to drain`);break}await new Promise(e=>setTimeout(e,50))}this.pausedReason=void 0,this.error=void 0,this.transitionTo(this.hasRemote?`disabled`:`dormant`),this.saveStateNow();return}try{this.hasRemote=(await I(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw(`remote`,`-v`)).trim().length>0}catch(e){$.warn({err:e},`[sync] remote detection failed during enable`)}if(this.pausedReason=void 0,this.error=void 0,this.consecutiveFailures=0,!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow()}}async trigger(e=`sync`){this.consecutiveFailures=0,(this.pausedReason===`dirty-tree`||this.pausedReason===`external-changes-pending`)&&(this.pausedReason=void 0,this.error=void 0),this.state===`dormant`||this.state===`disabled`||this.state===`conflict`||this.state===`auth-error`?$.warn({op:e,state:this.state,syncEnabled:this.syncEnabled,hasRemote:this.hasRemote,pausedReason:this.pausedReason,conflictCount:this.conflictCount},`[sync] trigger(${e}) ignored — state=${this.state}`):$.info({op:e,state:this.state},`[sync] trigger(${e}) running`),e===`push`?await this.runPushCycle():(e===`pull`||await this.runPushCycle(),await this.runPullCycle())}getStatus(){return{state:this.state,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,ahead:this.ahead,behind:this.behind,consecutiveFailures:this.consecutiveFailures,conflictCount:this.conflictCount,hasRemote:this.hasRemote,syncEnabled:this.syncEnabled===!0,identityUnresolved:this.identityUnresolved,error:this.error,pausedReason:this.pausedReason}}async refreshIdentity(){let e=await ym(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}getConflicts(){return this.conflictStore.list()}async resolveConflict(e,t,n){await this.conflictStore.resolveConflict(e,t,n),this.conflictCount=this.conflictStore.count(),this.conflictCount===0&&this.state===`conflict`&&(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()),this.scheduleSaveState()}updateCurrentBranch(e){e===null?this.state!==`dormant`&&this.state!==`disabled`&&(this.transitionTo(`disabled`),this.pausedReason=`detached-head`,this.scheduleSaveState()):this.currentBranch!==e&&(this.currentBranch=e,this.conflictStore.setBranch(e),this.state===`disabled`&&this.pausedReason===`detached-head`&&(this.pausedReason=void 0,this.transitionTo(`idle`),this.schedulePull(),this.schedulePush()))}schedulePull(e){this.pullTimer!==null&&clearTimeout(this.pullTimer);let t=e??this.effectivePullDelayMs();this.pullTimer=setTimeout(()=>{this.pullTimer=null,this.runPullCycle().catch(e=>{$.error({err:e},`[sync] pull cycle uncaught error`)})},t)}schedulePush(e){this.pushTimer!==null&&clearTimeout(this.pushTimer);let t=e??cy(this.pushIntervalSeconds);this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.runPushCycle().catch(e=>{$.error({err:e},`[sync] push cycle uncaught error`)})},t)}effectivePullDelayMs(){let e=this.consecutiveFailures,t=uy(e);return t>0?t:cy(this.pullIntervalSeconds)}async runPullCycle(){if(!this.pullInFlight&&!(this.state===`dormant`||this.state===`disabled`)){if(this.state===`conflict`){this.schedulePull();return}if(ly(this.projectDir)){this.schedulePull();return}this.pullInFlight=!0;try{await this.doPullCycle()}finally{this.pullInFlight=!1,this.schedulePull()}}}async doPullCycle(){let e=I(this.projectDir,{credentialArgs:this.credentialArgs}),t;try{let n=(await e.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();if(!n||n===`HEAD`){this.transitionTo(`disabled`),this.pausedReason=`detached-head`,$.warn({},`[sync] detached HEAD — pausing sync`);return}t=n,this.currentBranch=t}catch(e){this.handleError(ay(e instanceof Error?e:Error(String(e))));return}this.transitionTo(`fetching`);try{await e.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.consecutiveFailures=0,this.error=void 0}catch(e){let t=ay(e instanceof Error?e:Error(String(e)));this.handleError(t);return}try{let t=await e.git.status();this.ahead=t.ahead,this.behind=t.behind}catch{}if(this.behind>0&&this.conflictCount===0){this.transitionTo(`pulling`),this.setBatchInProgress?.(!0);try{if(await this.commitDirtyContentFilesToHead(e),!await this.pauseIfNonContentDirty(e))return;await e.git.merge([`origin/${t}`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`)}catch(e){let t=ay(e instanceof Error?e:Error(String(e)));t.class===`semantic`&&t.subclass===`merge-conflict`?await this.handleMergeConflict():this.handleError(t);return}finally{this.setBatchInProgress?.(!1)}}else this.transitionTo(`idle`);this.scheduleSaveState()}async runPushCycle(){if(!this.pushInFlight&&!(this.state===`dormant`||this.state===`disabled`)&&!(this.state===`conflict`||this.state===`auth-error`)){if(ly(this.projectDir)){this.schedulePush();return}this.pushInFlight=!0;try{await this.doPushCycle(1)}finally{this.pushInFlight=!1,this.schedulePush()}}}async doPushCycle(e=0){let t=this.gatherContentFilesSync(),n=Ce(be(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),r=null;this.transitionTo(`pushing`);try{await ae(async()=>{let e=I(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:n});if(ly(this.projectDir)){$.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}let i;try{i=(await e.git.revparse(`HEAD`)).trim()}catch(e){let t=e instanceof Error?e.message:String(e),n=`${t}\n${e.git?.toString()??t}`;if(/unknown revision or path not in the working tree/i.test(n)||/ambiguous argument 'HEAD'/i.test(n)||/does not have any commits yet/i.test(n)){$.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}this.handleError(ay(e instanceof Error?e:Error(String(e))));return}await e.git.raw([`read-tree`,i]);let a=new Set;try{let t=(await e.git.raw([`ls-tree`,`-r`,`--name-only`,i])).trim();for(let e of t?t.split(`
88
85
  `):[]){let t=e.trim();if(!t)continue;let n=Ce(this.projectDir,t),r=B(this.contentDir,n);!r.startsWith(`..`)&&!this.contentFilter.isExcluded(r)&&a.add(t)}}catch{}if(t.length>0)for(let n=0;n<t.length;n+=100){let r=t.slice(n,n+100).map(e=>e.projectRelPath);await e.git.raw([`add`,`--`,...r])}let o=new Set(t.map(e=>e.projectRelPath)),s=[...a].filter(e=>!o.has(e));s.length>0&&await e.git.raw([`rm`,`--cached`,`--`,...s]);let c=(await e.git.raw([`write-tree`])).trim(),l=``;try{l=(await e.git.raw([`rev-parse`,`${i}^{tree}`])).trim()}catch{}if(l&&l===c){let n=null;try{n=(await e.git.raw([`rev-parse`,`origin/${this.currentBranch}`])).trim()}catch{}if(n===i){$.info({contentFileCount:t.length,headSha:i},`[sync] push cycle: nothing to commit (tree unchanged, origin matches HEAD)`),this.lastPushedSha=i,this.transitionTo(`idle`);return}$.info({headSha:i,upstreamSha:n},`[sync] push cycle: tree unchanged but local ahead of origin — pushing existing commits`);let a=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),a=!0}catch{}a?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),r=i;return}let u=[];try{let n=(await e.git.raw([`diff-tree`,`--name-only`,`-r`,i,c])).trim();if(n){let e=new Map(t.map(e=>[e.projectRelPath,e.contentRelPath]));for(let t of n.split(`
89
- `)){let n=t.trim();if(!n)continue;let r=e.get(n)??B(this.contentDir,Ce(this.projectDir,n));r&&!r.startsWith(`..`)&&u.push(r)}}}catch{u=t.map(e=>e.contentRelPath)}let d=this.buildCommitMessage(u),f=await _m(this.projectDir),p=f===null;this.identityUnresolved!==p&&(this.identityUnresolved=p,this.cc1Broadcaster?.signal(`sync-status`));let m=f?.name??`Open Knowledge`,h=f?.email??`sync@open-knowledge.local`;e.git.env({GIT_AUTHOR_NAME:m,GIT_AUTHOR_EMAIL:h,GIT_COMMITTER_NAME:m,GIT_COMMITTER_EMAIL:h});let g=(await e.git.raw([`commit-tree`,c,`-p`,i,`-m`,d])).trim();if(!g||!ay.test(g)){$.warn({raw:g},`[sync] commit-tree returned invalid SHA — aborting push`),this.transitionTo(`idle`);return}if(await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,g,i]),t.length>0){let e=I(this.projectDir,{credentialArgs:this.credentialArgs});for(let n=0;n<t.length;n+=100){let r=t.slice(n,n+100).map(e=>e.projectRelPath);try{await e.git.raw([`reset`,`HEAD`,`--`,...r])}catch{}}}let _=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),_=!0}catch{}_?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),r=g}),r&&(this.lastPushedSha=r,this.lastSyncUtc=new Date().toISOString(),this.ahead=0,this.state===`pushing`&&this.transitionTo(`idle`),this.pausedReason===`dirty-tree`&&(this.pausedReason=void 0,this.error=void 0,this.schedulePull(0)))}catch(t){let n=ry(t instanceof Error?t:Error(String(t)));if(n.class===`semantic`&&n.subclass===`non-fast-forward`){if(e>0){$.info({},`[sync] push rejected (non-fast-forward) — fetching, merging, retrying`);let e=I(this.projectDir,{credentialArgs:this.credentialArgs});this.setBatchInProgress?.(!0);try{if(await e.git.fetch(`origin`),await this.commitDirtyContentFilesToHead(e),!await this.pauseIfNonContentDirty(e)){this.setBatchInProgress?.(!1);return}await e.git.merge([`origin/${this.currentBranch}`])}catch(e){let t=ry(e instanceof Error?e:Error(String(e)));t.class===`semantic`&&t.subclass===`merge-conflict`?await this.handleMergeConflict():this.handleError(t),this.scheduleSaveState();return}finally{this.setBatchInProgress?.(!1)}await this.doPushCycle(0);return}$.info({},`[sync] push still rejected after retry — waiting for next pull cycle`),this.consecutiveFailures++,this.state===`pushing`&&this.transitionTo(`idle`)}else this.handleError(n)}finally{try{ge(n)}catch{}}this.scheduleSaveState()}async commitDirtyContentFilesToHead(e){if((await e.git.status()).files.length===0)return null;let t=(await e.git.revparse(`HEAD`)).trim(),n=this.gatherContentFilesSync();if(n.length===0)return null;let r=Ce(be(),`ok-sync-retry-idx-${process.pid}-${Date.now()}.idx`),i=I(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:r});try{await i.git.raw([`read-tree`,t]);for(let e=0;e<n.length;e+=100){let t=n.slice(e,e+100).map(e=>e.projectRelPath);await i.git.raw([`add`,`--`,...t])}let r=(await i.git.raw([`write-tree`])).trim();if(r===(await i.git.raw([`rev-parse`,`${t}^{tree}`])).trim())return null;let a=await _m(this.projectDir),o=a?.name??`Open Knowledge`,s=a?.email??`sync@open-knowledge.local`;i.git.env({GIT_AUTHOR_NAME:o,GIT_AUTHOR_EMAIL:s,GIT_COMMITTER_NAME:o,GIT_COMMITTER_EMAIL:s});let c=(await i.git.raw([`commit-tree`,r,`-p`,t,`-m`,`Auto-save: interim before merge`])).trim();if(!c||!ay.test(c))return $.warn({raw:c},`[sync] commit-tree returned invalid SHA in commitDirtyContentFilesToHead`),null;await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,c,t]);for(let t=0;t<n.length;t+=100){let r=n.slice(t,t+100).map(e=>e.projectRelPath);try{await e.git.raw([`reset`,`HEAD`,`--`,...r])}catch{}}return c}finally{try{ge(r)}catch{}}}async pauseIfNonContentDirty(e){let t=``;try{t=(await e.git.raw([`diff-index`,`--name-only`,`HEAD`])).trim()}catch{return!0}if(!t)return!0;let n=t.split(`
86
+ `)){let n=t.trim();if(!n)continue;let r=e.get(n)??B(this.contentDir,Ce(this.projectDir,n));r&&!r.startsWith(`..`)&&u.push(r)}}}catch{u=t.map(e=>e.contentRelPath)}let d=this.buildCommitMessage(u),f=await ym(this.projectDir),p=f===null;this.identityUnresolved!==p&&(this.identityUnresolved=p,this.cc1Broadcaster?.signal(`sync-status`));let m=f?.name??`Open Knowledge`,h=f?.email??`sync@open-knowledge.local`;e.git.env({GIT_AUTHOR_NAME:m,GIT_AUTHOR_EMAIL:h,GIT_COMMITTER_NAME:m,GIT_COMMITTER_EMAIL:h});let g=(await e.git.raw([`commit-tree`,c,`-p`,i,`-m`,d])).trim();if(!g||!sy.test(g)){$.warn({raw:g},`[sync] commit-tree returned invalid SHA — aborting push`),this.transitionTo(`idle`);return}if(await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,g,i]),t.length>0){let e=I(this.projectDir,{credentialArgs:this.credentialArgs});for(let n=0;n<t.length;n+=100){let r=t.slice(n,n+100).map(e=>e.projectRelPath);try{await e.git.raw([`reset`,`HEAD`,`--`,...r])}catch{}}}let _=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),_=!0}catch{}_?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),r=g}),r&&(this.lastPushedSha=r,this.lastSyncUtc=new Date().toISOString(),this.ahead=0,this.state===`pushing`&&this.transitionTo(`idle`),this.pausedReason===`dirty-tree`&&(this.pausedReason=void 0,this.error=void 0,this.schedulePull(0)))}catch(t){let n=ay(t instanceof Error?t:Error(String(t)));if(n.class===`semantic`&&n.subclass===`non-fast-forward`){if(e>0){$.info({},`[sync] push rejected (non-fast-forward) — fetching, merging, retrying`);let e=I(this.projectDir,{credentialArgs:this.credentialArgs});this.setBatchInProgress?.(!0);try{if(await e.git.fetch(`origin`),await this.commitDirtyContentFilesToHead(e),!await this.pauseIfNonContentDirty(e)){this.setBatchInProgress?.(!1);return}await e.git.merge([`origin/${this.currentBranch}`])}catch(e){let t=ay(e instanceof Error?e:Error(String(e)));t.class===`semantic`&&t.subclass===`merge-conflict`?await this.handleMergeConflict():this.handleError(t),this.scheduleSaveState();return}finally{this.setBatchInProgress?.(!1)}await this.doPushCycle(0);return}$.info({},`[sync] push still rejected after retry — waiting for next pull cycle`),this.consecutiveFailures++,this.state===`pushing`&&this.transitionTo(`idle`)}else this.handleError(n)}finally{try{ge(n)}catch{}}this.scheduleSaveState()}async commitDirtyContentFilesToHead(e){if((await e.git.status()).files.length===0)return null;let t=(await e.git.revparse(`HEAD`)).trim(),n=this.gatherContentFilesSync();if(n.length===0)return null;let r=Ce(be(),`ok-sync-retry-idx-${process.pid}-${Date.now()}.idx`),i=I(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:r});try{await i.git.raw([`read-tree`,t]);for(let e=0;e<n.length;e+=100){let t=n.slice(e,e+100).map(e=>e.projectRelPath);await i.git.raw([`add`,`--`,...t])}let r=(await i.git.raw([`write-tree`])).trim();if(r===(await i.git.raw([`rev-parse`,`${t}^{tree}`])).trim())return null;let a=await ym(this.projectDir),o=a?.name??`Open Knowledge`,s=a?.email??`sync@open-knowledge.local`;i.git.env({GIT_AUTHOR_NAME:o,GIT_AUTHOR_EMAIL:s,GIT_COMMITTER_NAME:o,GIT_COMMITTER_EMAIL:s});let c=(await i.git.raw([`commit-tree`,r,`-p`,t,`-m`,`Auto-save: interim before merge`])).trim();if(!c||!sy.test(c))return $.warn({raw:c},`[sync] commit-tree returned invalid SHA in commitDirtyContentFilesToHead`),null;await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,c,t]);for(let t=0;t<n.length;t+=100){let r=n.slice(t,t+100).map(e=>e.projectRelPath);try{await e.git.raw([`reset`,`HEAD`,`--`,...r])}catch{}}return c}finally{try{ge(r)}catch{}}}async pauseIfNonContentDirty(e){let t=``;try{t=(await e.git.raw([`diff-index`,`--name-only`,`HEAD`])).trim()}catch{return!0}if(!t)return!0;let n=t.split(`
90
87
  `).map(e=>e.trim()).filter(Boolean);return n.length===0?!0:(this.error=`External changes pending: ${n.slice(0,3).join(`, `)}${n.length>3?`, +${n.length-3} more`:``}`,this.pausedReason=`external-changes-pending`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),$.warn({files:n},`[sync] paused — non-content tracked files dirty`),!1)}gatherContentFilesSync(){let e=[],t=n=>{let r;try{r=de(n,{withFileTypes:!0})}catch{return}for(let i of r){let r=Ce(n,i.name);if(i.isDirectory()){if(i.name===`node_modules`||i.name===`.git`||i.name.startsWith(`.`)&&i.name!==`.open-knowledge`)continue;t(r)}else if(i.isFile()){let t=B(this.contentDir,r);if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t)){let n=B(this.projectDir,r);e.push({contentRelPath:t,projectRelPath:n})}}}};return L(this.contentDir)&&t(this.contentDir),e}buildCommitMessage(e){return e.length===0?`Auto-save: changes saved`:e.length<=3?`Auto-save: Updated ${e.join(`, `)}`:`Auto-save: ${e.length} files changed`}async handleMergeConflict(){let e=I(this.projectDir,{credentialArgs:this.credentialArgs}),t=[];try{let n=(await e.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();t=n?n.split(`
91
- `).map(e=>e.trim()).filter(Boolean):[]}catch(t){$.error({err:t},`[sync] failed to list conflicted files — aborting merge to avoid committing unresolved state`);try{await e.git.raw([`merge`,`--abort`])}catch(e){$.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.error=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let n=[],r=[];for(let e of t){let t=Ce(this.projectDir,e),i=B(this.contentDir,t);!i.startsWith(`..`)&&!this.contentFilter.isExcluded(i)?n.push(e):r.push(e)}for(let t of r)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),$.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){$.warn({err:e,file:t},`[sync] auto-resolve failed — escalating to content conflict`),n.push(t)}if(n.length>0){for(let e of n)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),$.warn({files:n},`[sync] content conflicts — sync paused until resolved`)}else try{await e.git.raw([`commit`,`--no-edit`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),$.info({},`[sync] all conflicts auto-resolved — merge committed`)}catch(t){$.warn({err:t},`[sync] failed to commit after auto-resolving conflicts — aborting merge`);try{await e.git.raw([`merge`,`--abort`])}catch(e){$.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.transitionTo(`idle`)}}async abortMerge(){let e=I(this.projectDir,{credentialArgs:this.credentialArgs});try{await e.git.raw([`merge`,`--abort`]),$.info({},`[sync] merge aborted`)}catch(e){$.warn({err:e},`[sync] git merge --abort failed — conflicts.json still cleared`)}this.conflictStore.clear(),this.conflictCount=0,this.transitionTo(`idle`),this.scheduleSaveState()}handleError(e){this.error=e.message,$.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`?(this.transitionTo(`auth-error`),this.pausedReason=`auth-error`):e.class===`semantic`&&e.subclass===`protected-branch`?(this.syncEnabled=!1,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`):e.class===`local`&&e.subclass===`dirty-tree`?(this.consecutiveFailures++,this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)):e.retryable?(this.consecutiveFailures++,this.transitionTo(`offline`)):(this.consecutiveFailures++,this.transitionTo(`idle`))}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,$.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){try{let e={version:1,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutiveFailures,pausedReason:this.pausedReason,pausedSinceUtc:this.pausedReason?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file),syncEnabled:this.syncEnabled};z(this.statePath,JSON.stringify(e,null,2),`utf-8`)}catch(e){$.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(L(this.statePath))try{let e=R(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutiveFailures=t.consecutiveFailures??0,this.pausedReason=t.pausedReason,t.syncEnabled!==void 0&&(this.syncEnabled=t.syncEnabled);let n=t.inflightConflicts??[];if(n.length>0){for(let e of n)this.conflictStore.list().some(t=>t.file===e)||this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count()}}catch(e){$.warn({err:e},`[sync] failed to load sync state`)}}};function uy(e){let{contentDir:t,projectDir:n=t,quiet:i=!0,debounce:a=2e3,maxDebounce:o=1e4,gitEnabled:s=!0,commitDebounceMs:c=3e4,wipRef:l=`refs/wip/main`,enableTestRoutes:d=!1,shadowRepo:f,contentRoot:p,includePatterns:m=[`**/*.md`,`**/*.mdx`],excludePatterns:h=[],destroyTimeoutMs:g=1e4,localOpCliArgs:_}=e,v=Mc(`server`),y=V(t,`.open-knowledge`);ne(y,{port:e.port??0,worktreeRoot:n});let b,x,S,C,w,T,E=null,D=null;function O(e){E?.signal(e)}try{b=yv({projectDir:n,contentDir:t,includePatterns:m,excludePatterns:h}),x=new ap({projectDir:n,contentDir:t,contentFilter:b}),S={current:f},C=Wp({contentDir:t,projectDir:n,gitEnabled:s,commitDebounceMs:c,wipRef:l,shadowRef:S,contentRoot:p,backlinkIndex:x,getCurrentBranch:()=>ae?.getLastKnownBranch()??null}),w=new $_({quiet:i,debounce:a,maxDebounce:o,extensions:[C.extension]}),E=new $c(w),D=new hv(w),T=new ol(w);let r=Mv({backlinkIndex:x,signalChannel:O});w.configuration.extensions.push(r);let u=$h({hocuspocus:w,sessionManager:T,contentDir:t,getFileIndex:()=>ie?ie.getFileIndex():new Map,getAliasMap:()=>ie?ie.getAliasMap():new Map,enableTestRoutes:d,shadowRef:S,flushGitCommit:()=>C.flushPendingGitCommit(),getCurrentBranch:()=>ae?.getLastKnownBranch()??null,contentRoot:p,backlinkIndex:x,signalChannel:O,agentFocusBroadcaster:D,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>I,localOpCliArgs:_,projectDir:n});w.configuration.extensions.push(u),w.configuration.extensions.push(Lv({mdManager:el,schema:tl,shadowRef:S,contentRoot:p,getCurrentBranch:()=>ae?.getLastKnownBranch()??null}))}catch(e){throw N(y),e}let k=null;function A(e,t){let n=V(e,`rescue`),r=V(n,`${t}${Af(t)}`);return r.startsWith(`${n}/`)?r:null}function j(e){let t=w.documents.get(e);if(!t)return null;let n=fs(t.getXmlFragment(`default`),tl).toJSON(),r=el.serialize(n),i=t.getMap(`metadata`).get(`frontmatter`);return u(typeof i==`string`?i:``,r)}let M=(e,t)=>wv(w,e,t);function ee(e){return e.kind===`rename`?e.newDocName:e.docName}async function te(e){try{switch(e.kind){case`create`:v.info({docName:e.docName},`[reconcile] create: ${e.docName}`),x.updateDocumentFromMarkdown(e.docName,e.content),x.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist create for ${e.docName}:`,t)}),O(`files`),O(`backlinks`),O(`graph`);break;case`update`:{let{docName:t,content:n}=e,r=w.documents.get(t);if(!r){x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc update for ${t}:`,e)}),O(`backlinks`),O(`graph`);return}let i=Rp(t)??``,a=j(t)??i,o=Jp({docName:t,base:i,ours:a,theirs:n}),s=nm(i).slice(0,6),c=nm(a).slice(0,6),l=nm(n).slice(0,6);switch(v.info({docName:t,base:s,ours:c,theirs:l,result:o.kind},`[reconcile] ${t} base=${s} ours=${c} theirs=${l} result=${o.kind}`),o.kind){case`noop`:x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist noop update for ${t}:`,e)}),O(`backlinks`),O(`graph`);break;case`clean`:try{M(t,o.newContent),zp(t,o.newContent),Nc(),x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist clean update for ${t}:`,e)}),O(`backlinks`),O(`graph`)}catch(e){v.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),zp(t,n)}break;case`merged`:try{M(t,o.newContent),zp(t,o.newContent),Nc(),x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist merged update for ${t}:`,e)}),O(`backlinks`),O(`graph`)}catch(e){v.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),zp(t,n)}break;case`conflicts`:try{M(t,o.newContent),zp(t,o.newContent),Nc(),Pc(),x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist conflict update for ${t}:`,e)}),O(`backlinks`),O(`graph`)}catch(e){v.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),zp(t,n)}break;case`refused`:{Pc();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=w.documents.get(t);if(!n){x.deleteDocument(t),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc delete for ${t}:`,e)}),O(`files`),O(`backlinks`),O(`graph`);return}let r=Rp(t)??``,i=j(t)??``,a=i!==r;if(a&&S.current){let e=S.current,n=ae?.getLastKnownBranch()??`main`;queueMicrotask(()=>{Ep(e,p??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{Lc(),v.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{v.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),Bp(t),x.deleteDocument(t),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist delete for ${t}:`,e)}),v.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),w.closeConnections(t),await w.unloadDocument(n),O(`files`),O(`backlinks`),O(`graph`);break}case`rename`:{let{oldDocName:t,newDocName:n,content:r}=e,i=w.documents.get(t);if(Bp(t),zp(n,r),x.renameDocument(t,n,r),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist rename for ${t} -> ${n}:`,e)}),i){let e=i.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,n)}v.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),O(`files`),O(`backlinks`),O(`graph`);break}case`conflict`:{let{docName:t}=e,n=w.documents.get(t);if(!n)return;let r=n.getMap(`lifecycle`);r.set(`status`,`conflict`),r.set(`reason`,`conflict-markers`),v.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}}}catch(t){v.error({err:t,kind:e.kind,docName:ee(e)},`[reconcile] failed to handle ${e.kind} for ${ee(e)}`)}}let P=[];async function re(e){if(Up()){P.push(e);return}await te(e)}async function F(){let e=P.splice(0,P.length);for(let t of e)await te(t)}let ie=null,ae=null,I=null,oe=null;async function se(e){if(w.documents.size===0)return;let t=!1,n=new Promise(e=>{w.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(w.documents.keys());w.closeConnections(),w.flushPendingStores();let i,a=new Promise((n,a)=>{i=setTimeout(()=>{t=!0;let n=Array.from(w.documents.keys()),i=[],o=[];if(S.current){for(let e of n)if(!q(e))try{let t=j(e);if(t===null){v.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=A(S.current.gitDir,e);if(!n){v.warn({docName:e,gitDir:S.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}le(xe(n),{recursive:!0}),z(n,t,`utf-8`),Lc(),i.push(e),v.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),v.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else v.warn({stillLoadedCount:n.length},`[rescue] shadow repo unavailable at flush timeout — ${n.length} doc(s) will be lost: [${n.join(`, `)}]`),o.push(...n);let s=i.length>0||o.length>0?` — rescued [${i.join(`, `)}]${o.length>0?`, lost [${o.join(`, `)}]`:``}`:``;a(Error(`flushAllStoresAndWait timeout after ${e}ms — ${n.length}/${r.length} docs did not unload: [${n.join(`, `)}]${s}`))},e)});try{await Promise.race([n,a])}finally{i!==void 0&&clearTimeout(i)}}async function ce(){return oe||(oe=(async()=>{let e=Date.now(),t=[],r,i=await Promise.race([fe.then(()=>`completed`,e=>(v.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{r=setTimeout(()=>e(`timeout`),5e3)})]);r!==void 0&&clearTimeout(r),i===`timeout`&&v.warn({},`[server] init did not complete within 5s during shutdown`);let a=w.documents.size;try{try{try{ae&&=(await ae.unsubscribe(),null),ie&&=(await ie.unsubscribe(),null)}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{E?.destroy(),k&&=(await k.disconnect(),null)}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await T.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await se(g)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await C.flushPendingGitCommit(),await C.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),g)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{I&&=(await I.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(S.current){try{let e=(await Ne({baseDir:n,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&z(V(S.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{bp(S.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let r=Date.now()-e;t.length===0?v.info({documentCount:a,durationMs:r},`[server] shutdown flushed ${a} documents in ${r}ms`):v.warn({documentCount:a,durationMs:r,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${r}ms with ${t.length} phase error(s)`)}}finally{try{N(y)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}}})(),oe)}let ue=[];async function de(){if(!S.current)try{S.current=await yp(n),v.info({gitDir:S.current.gitDir},`[server] shadow repo initialized at ${S.current.gitDir}`)}catch(e){v.error({err:e},`[server] shadow repo init failed`),ue.push(`shadow-repo`)}if(S.current)try{await vp(S.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){v.warn({},`[server] shadow repo appears corrupted — reinitializing`);try{S.current=await yp(n)}catch(e){v.error({err:e},`[server] shadow repo reinit failed`),S.current=void 0,ue.includes(`shadow-repo`)||ue.push(`shadow-repo`)}}else v.error({err:e},`[server] shadow repo check failed (transient?)`)}if(S.current)try{let e=V(S.current.gitDir,`last-known-head`),t=null;try{t=R(e,`utf-8`).trim()||null}catch{}let r=null;try{r=(await Ne({baseDir:n,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(r!==null){if(r!==t){let e=`main`;try{let t=(await Ne({baseDir:n,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}v.info({lastKnownHead:t,currentHead:r,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=import`);try{await Cp(S.current,p??``,t,r,e),Ic()}catch(e){v.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else v.info({currentHead:r},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=noop`);try{z(e,r,`utf-8`)}catch(e){v.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){v.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=zm(t);e.recovered&&e.journal&&v.warn({sourceDocName:e.journal.sourceDocName,destinationDocName:e.journal.destinationDocName,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${e.journal.sourceDocName} -> ${e.journal.destinationDocName}`)}catch(e){v.error({err:e},`[server] managed rename recovery failed`),ue.push(`managed-rename-recovery`)}try{k=await w.openDirectConnection(r)}catch(e){v.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),ue.push(`cc1-push`)}try{ie=await hm(t,re,b),x.rebuildFromDisk(Lp()),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist startup cache for ${Lp()}:`,e)})}catch(e){v.error({err:e},`[server] disk bridge watcher failed to start`),ue.push(`file-watcher`)}try{ae=await kv(n,async({trigger:e})=>{if(v.info({trigger:e},`[batch] begin trigger=${e}`),Fc(),w.flushPendingStores(),await C.flushPendingGitCommit(),S.current){let e=Lp(),t=[];for(let[e]of w.documents){if(q(e))continue;let n=j(e);if(n===null)continue;let r=Rp(e)??n;t.push({docName:e,markdown:n,diskSnapshot:r})}if(t.length>0)try{let n=await Op(S.current,e,`server`,t);n&&(zc(),v.info({count:t.length,branch:e,sha:n.slice(0,8)},`[shadow] parked ${t.length} docs on ${e} → ${n.slice(0,8)}`))}catch(e){v.error({err:e},`[shadow] park failed`)}}Hp(!0)},async e=>{let n=P.length,r=e.newBranch??`main`;if(Hp(!1),v.info({kind:e.batchKind,headMoved:e.headMoved,docs:n,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${n}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`)await F();else{Rc(),P.splice(0,P.length),Ip(r),x.switchBranch(r);for(let[e,n]of w.documents)if(!q(e))try{let i=Mp(e,t);if(!L(i)){let t=Rp(e)??``,i=j(e)??``;if(i!==t&&S.current){let t=S.current;queueMicrotask(()=>{Ep(t,p??``,{kind:`external-change-rescue`,docName:e,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:r,metadata:{incomingDiskSha:``}}).then(()=>{Lc(),v.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{v.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),v.info({docName:e,branch:r},`[branch-switch] tombstone: ${e} (not on ${r})`);continue}let a=R(i,`utf-8`);M(e,a),zp(e,a),v.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){v.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}if(v.info({branch:r,docCount:w.documents.size},`[branch-switch] loaded branch ${r} (${w.documents.size} docs)`),x.rebuildFromDisk(r),x.saveToDisk(r).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${r}:`,e)}),S.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of w.documents)if(!q(t))try{let n=await kp(S.current,r,`server`,t);if(!n||n.markdown===n.diskSnapshot)continue;let i=Rp(t);if(!i)continue;let a=Jp({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:i});switch(a.kind){case`merged`:case`clean`:M(t,a.newContent),zp(t,a.newContent),e++;break;case`conflicts`:M(t,a.newContent),zp(t,a.newContent),Pc(),e++;break;case`noop`:case`refused`:break}}catch(e){v.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&v.info({count:e,branch:r},`[branch-switch] restored ${e} parked docs on ${r}`)}if(e.oldBranch?.startsWith(`detached-`)&&S.current)try{let t=vp(S.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(n){for(let e of n.split(`
92
- `))e&&await t.raw(`update-ref`,`-d`,e);v.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){v.error({err:e},`[branch-switch] detached cleanup failed`)}}if(e.headMoved&&e.newHead&&S.current&&n>0){let t=p??`content`;try{let n=await Cp(S.current,t,e.oldHead,e.newHead,r);Ic(),v.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[shadow] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){v.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){v.error({err:e},`[server] HEAD watcher failed to start`),ue.push(`head-watcher`)}let e=_?.[0]??`open-knowledge`,i=[`-c`,`credential.helper=!${_&&_.length>1?_.join(` `):e} auth git-credential`];try{I=new ly({projectDir:n,contentDir:t,contentFilter:b,contentRoot:p,credentialArgs:i,cc1Broadcaster:E,setBatchInProgress:Hp,onStateChange:e=>{v.info({state:e},`[sync] state → ${e}`)}}),await I.start()}catch(e){v.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),I=null}}let fe=de();return{hocuspocus:w,sessionManager:T,cc1Broadcaster:E,agentFocusBroadcaster:D,contentFilter:b,destroy:ce,ready:fe,degraded:ue,lockDir:y,get syncEngine(){return I}}}async function dy(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.idleShutdownMs,i=e.log??Mc(`boot`),{createServer:a}=await import(`node:http`),{WebSocketServer:o}=await import(`./wrapper-BK_jpkDm.mjs`),{updateServerLockPort:s}=await import(`./server-lock-CPmOhzSz.mjs`),c=!1;if(!t&&e.autoInitFn)try{c=!!await e.autoInitFn()}catch(e){i.warn({err:e},`autoInitFn failed`)}let l=uy({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,includePatterns:e.includePatterns,excludePatterns:e.excludePatterns,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite}),{hocuspocus:u,destroy:d,ready:f,degraded:p,lockDir:m}=l,h=a((e,t)=>{let n=e.url?.split(`?`)[0];if(n?.startsWith(`/api/`)){u.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||(t.statusCode=404,t.setHeader(`Content-Type`,`application/json`),t.end(JSON.stringify({error:`API route not found`,path:n})))}).catch(e=>{i.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?(t.writeHead(500),t.end(`Internal server error`)):t.writableEnded||t.end()});return}t.writeHead(404,{"Content-Type":`application/json`}),t.end(JSON.stringify({error:"Not found. The React UI is served by `ok ui` (default port 3000).",path:n??`/`}))}),g=new o({noServer:!0});g.on(`error`,e=>{i.error({err:e},`WebSocketServer error`)}),h.on(`upgrade`,(e,t,n)=>{if(e.url?.startsWith(`/collab/keepalive`)){t.on(`error`,e=>{Xc(e)||i.error({err:e},`MCP keepalive socket error`)}),g.handleUpgrade(e,t,n,e=>{let t=setInterval(()=>{try{e.ping()}catch{}},3e4);t.unref?.(),e.on(`close`,()=>clearInterval(t)),e.on(`error`,t=>{Xc(t)||i.error({err:t},`MCP keepalive WS error`),e.terminate()})});return}e.url?.startsWith(`/collab`)&&(t.on(`error`,e=>{Xc(e)||i.error({err:e},`Upgrade socket error`)}),g.handleUpgrade(e,t,n,t=>{let n=u.handleConnection(t,e);t.on(`message`,e=>{n.handleMessage((e instanceof ArrayBuffer,new Uint8Array(e)))}),t.on(`close`,(e,t)=>{n.handleClose({code:e,reason:t.toString()})}),t.on(`error`,e=>{Xc(e)||i.error({err:e},`WebSocket error`),t.terminate()})}))});let _=null;r!==null&&(_=eg({httpServer:h,thresholdMs:r??18e5,log:i,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await d()})})),await new Promise((t,n)=>{let r=e=>n(e);h.once(`error`,r),h.listen(e.port,e.host,()=>{h.removeListener(`error`,r),t()})});let v=h.address(),y=typeof v==`object`&&v?v.port:e.port??0;if(s(m,y),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:m,log:i})}catch(e){i.warn({err:e},`spawnUiSiblingFn failed`)}let b=!1;return{httpServer:h,destroy:async()=>{b||(b=!0,_?.detach(),await new Promise(e=>{h.close(()=>e())}),await d())},lockDir:m,contentDir:e.contentDir,port:y,ready:f,degraded:p,didAutoInit:c,serverInstance:l}}export{Zd as $,Jp as A,Ap as B,em as C,Qp as D,om as E,xp as F,mp as G,cp as H,yp as I,yf as J,ap as K,Dp as L,Wp as M,Mp as N,Gp as O,Cp as P,xf as Q,Tp as R,rm as S,hm as T,lp as U,vp as V,up as W,Sf as X,bf as Y,Cf as Z,cm as _,Mv as a,q as at,lm as b,wv as c,Yc as ct,Fh as d,Mc as dt,rl as et,Ph as f,jc as ft,Xm as g,Zm as h,Nv as i,$c as it,qp as j,Kp as k,yv as l,Wc as lt,Uh as m,uy as n,al as nt,Ov as o,Qc as ot,$h as p,$f as q,Lv as r,il as rt,Cv as s,Xc as st,dy as t,ol as tt,eg as u,Ac as ut,nm as v,sm as w,am as x,tm as y,Ep as z};
93
- //# sourceMappingURL=src-DcVg7_6f.mjs.map
88
+ `).map(e=>e.trim()).filter(Boolean):[]}catch(t){$.error({err:t},`[sync] failed to list conflicted files — aborting merge to avoid committing unresolved state`);try{await e.git.raw([`merge`,`--abort`])}catch(e){$.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.error=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let n=[],r=[];for(let e of t){let t=Ce(this.projectDir,e),i=B(this.contentDir,t);!i.startsWith(`..`)&&!this.contentFilter.isExcluded(i)?n.push(e):r.push(e)}for(let t of r)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),$.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){$.warn({err:e,file:t},`[sync] auto-resolve failed — escalating to content conflict`),n.push(t)}if(n.length>0){for(let e of n)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),$.warn({files:n},`[sync] content conflicts — sync paused until resolved`)}else try{await e.git.raw([`commit`,`--no-edit`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),$.info({},`[sync] all conflicts auto-resolved — merge committed`)}catch(t){$.warn({err:t},`[sync] failed to commit after auto-resolving conflicts — aborting merge`);try{await e.git.raw([`merge`,`--abort`])}catch(e){$.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.transitionTo(`idle`)}}async abortMerge(){let e=I(this.projectDir,{credentialArgs:this.credentialArgs});try{await e.git.raw([`merge`,`--abort`]),$.info({},`[sync] merge aborted`)}catch(e){$.warn({err:e},`[sync] git merge --abort failed — conflicts.json still cleared`)}this.conflictStore.clear(),this.conflictCount=0,this.transitionTo(`idle`),this.scheduleSaveState()}handleError(e){this.error=e.message,$.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`?(this.transitionTo(`auth-error`),this.pausedReason=`auth-error`):e.class===`semantic`&&e.subclass===`protected-branch`?(this.syncEnabled=!1,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`):e.class===`local`&&e.subclass===`dirty-tree`?(this.consecutiveFailures++,this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)):e.retryable?(this.consecutiveFailures++,this.transitionTo(`offline`)):(this.consecutiveFailures++,this.transitionTo(`idle`))}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,$.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){try{let e={version:1,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutiveFailures,pausedReason:this.pausedReason,pausedSinceUtc:this.pausedReason?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file),syncEnabled:this.syncEnabled};z(this.statePath,JSON.stringify(e,null,2),`utf-8`)}catch(e){$.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(L(this.statePath))try{let e=R(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutiveFailures=t.consecutiveFailures??0,this.pausedReason=t.pausedReason,t.syncEnabled!==void 0&&(this.syncEnabled=t.syncEnabled);let n=t.inflightConflicts??[];if(n.length>0){for(let e of n)this.conflictStore.list().some(t=>t.file===e)||this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count()}}catch(e){$.warn({err:e},`[sync] failed to load sync state`)}}};function fy(e){let{contentDir:t,projectDir:n=t,quiet:i=!0,debounce:a=2e3,maxDebounce:o=1e4,gitEnabled:s=!0,commitDebounceMs:c=3e4,wipRef:l=`refs/wip/main`,enableTestRoutes:d=!1,shadowRepo:f,contentRoot:p,includePatterns:m=[`**/*.md`,`**/*.mdx`],excludePatterns:h=[],destroyTimeoutMs:g=1e4,localOpCliArgs:_}=e,v=Pc(`server`),y=V(t,`.open-knowledge`);ne(y,{port:e.port??0,worktreeRoot:n});let b,x,S,C,w,T,E=null,D=null;function O(e){E?.signal(e)}try{b=xv({projectDir:n,contentDir:t,includePatterns:m,excludePatterns:h}),x=new sp({projectDir:n,contentDir:t,contentFilter:b}),S={current:f},C=Kp({contentDir:t,projectDir:n,gitEnabled:s,commitDebounceMs:c,wipRef:l,shadowRef:S,contentRoot:p,backlinkIndex:x,getCurrentBranch:()=>ae?.getLastKnownBranch()??null}),w=new tv({quiet:i,debounce:a,maxDebounce:o,extensions:[C.extension]}),E=new tl(w),D=new _v(w),T=new cl(w);let r=Pv({backlinkIndex:x,signalChannel:O});w.configuration.extensions.push(r);let u=tg({hocuspocus:w,sessionManager:T,contentDir:t,getFileIndex:()=>ie?ie.getFileIndex():new Map,getAliasMap:()=>ie?ie.getAliasMap():new Map,enableTestRoutes:d,shadowRef:S,flushGitCommit:()=>C.flushPendingGitCommit(),getCurrentBranch:()=>ae?.getLastKnownBranch()??null,contentRoot:p,backlinkIndex:x,signalChannel:O,agentFocusBroadcaster:D,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>I,localOpCliArgs:_,projectDir:n});w.configuration.extensions.push(u),w.configuration.extensions.push(zv({mdManager:nl,schema:rl,shadowRef:S,contentRoot:p,getCurrentBranch:()=>ae?.getLastKnownBranch()??null}))}catch(e){throw N(y),e}let k=null;function A(e,t){let n=V(e,`rescue`),r=V(n,`${t}${Mf(t)}`);return r.startsWith(`${n}/`)?r:null}function j(e){let t=w.documents.get(e);if(!t)return null;let n=ms(t.getXmlFragment(`default`),rl).toJSON(),r=nl.serialize(n),i=t.getMap(`metadata`).get(`frontmatter`);return u(typeof i==`string`?i:``,r)}let M=(e,t)=>Ev(w,e,t);function ee(e){return e.kind===`rename`?e.newDocName:e.docName}async function te(e){try{switch(e.kind){case`create`:v.info({docName:e.docName},`[reconcile] create: ${e.docName}`),x.updateDocumentFromMarkdown(e.docName,e.content),x.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist create for ${e.docName}:`,t)}),O(`files`),O(`backlinks`),O(`graph`);break;case`update`:{let{docName:t,content:n}=e,r=w.documents.get(t);if(!r){x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc update for ${t}:`,e)}),O(`backlinks`),O(`graph`);return}let i=Bp(t)??``,a=j(t)??i,o=Xp({docName:t,base:i,ours:a,theirs:n}),s=im(i).slice(0,6),c=im(a).slice(0,6),l=im(n).slice(0,6);switch(v.info({docName:t,base:s,ours:c,theirs:l,result:o.kind},`[reconcile] ${t} base=${s} ours=${c} theirs=${l} result=${o.kind}`),o.kind){case`noop`:x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist noop update for ${t}:`,e)}),O(`backlinks`),O(`graph`);break;case`clean`:try{M(t,o.newContent),Vp(t,o.newContent),Fc(),x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist clean update for ${t}:`,e)}),O(`backlinks`),O(`graph`)}catch(e){v.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),Vp(t,n)}break;case`merged`:try{M(t,o.newContent),Vp(t,o.newContent),Fc(),x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist merged update for ${t}:`,e)}),O(`backlinks`),O(`graph`)}catch(e){v.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),Vp(t,n)}break;case`conflicts`:try{M(t,o.newContent),Vp(t,o.newContent),Fc(),Ic(),x.updateDocumentFromMarkdown(t,n),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist conflict update for ${t}:`,e)}),O(`backlinks`),O(`graph`)}catch(e){v.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),Vp(t,n)}break;case`refused`:{Ic();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=w.documents.get(t);if(!n){x.deleteDocument(t),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc delete for ${t}:`,e)}),O(`files`),O(`backlinks`),O(`graph`);return}let r=Bp(t)??``,i=j(t)??``,a=i!==r;if(a&&S.current){let e=S.current,n=ae?.getLastKnownBranch()??`main`;queueMicrotask(()=>{Op(e,p??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{zc(),v.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{v.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),Hp(t),x.deleteDocument(t),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist delete for ${t}:`,e)}),v.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),w.closeConnections(t),await w.unloadDocument(n),O(`files`),O(`backlinks`),O(`graph`);break}case`rename`:{let{oldDocName:t,newDocName:n,content:r}=e,i=w.documents.get(t);if(Hp(t),Vp(n,r),x.renameDocument(t,n,r),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist rename for ${t} -> ${n}:`,e)}),i){let e=i.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,n)}v.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),O(`files`),O(`backlinks`),O(`graph`);break}case`conflict`:{let{docName:t}=e,n=w.documents.get(t);if(!n)return;let r=n.getMap(`lifecycle`);r.set(`status`,`conflict`),r.set(`reason`,`conflict-markers`),v.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}}}catch(t){v.error({err:t,kind:e.kind,docName:ee(e)},`[reconcile] failed to handle ${e.kind} for ${ee(e)}`)}}let P=[];async function re(e){if(Gp()){P.push(e);return}await te(e)}async function F(){let e=P.splice(0,P.length);for(let t of e)await te(t)}let ie=null,ae=null,I=null,oe=null;async function se(e){if(w.documents.size===0)return;let t=!1,n=new Promise(e=>{w.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(w.documents.keys());w.closeConnections(),w.flushPendingStores();let i,a=new Promise((n,a)=>{i=setTimeout(()=>{t=!0;let n=Array.from(w.documents.keys()),i=[],o=[];if(S.current){for(let e of n)if(!q(e))try{let t=j(e);if(t===null){v.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=A(S.current.gitDir,e);if(!n){v.warn({docName:e,gitDir:S.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}le(xe(n),{recursive:!0}),z(n,t,`utf-8`),zc(),i.push(e),v.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),v.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else v.warn({stillLoadedCount:n.length},`[rescue] shadow repo unavailable at flush timeout — ${n.length} doc(s) will be lost: [${n.join(`, `)}]`),o.push(...n);let s=i.length>0||o.length>0?` — rescued [${i.join(`, `)}]${o.length>0?`, lost [${o.join(`, `)}]`:``}`:``;a(Error(`flushAllStoresAndWait timeout after ${e}ms — ${n.length}/${r.length} docs did not unload: [${n.join(`, `)}]${s}`))},e)});try{await Promise.race([n,a])}finally{i!==void 0&&clearTimeout(i)}}async function ce(){return oe||(oe=(async()=>{let e=Date.now(),t=[],r,i=await Promise.race([fe.then(()=>`completed`,e=>(v.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{r=setTimeout(()=>e(`timeout`),5e3)})]);r!==void 0&&clearTimeout(r),i===`timeout`&&v.warn({},`[server] init did not complete within 5s during shutdown`);let a=w.documents.size;try{try{try{ae&&=(await ae.unsubscribe(),null),ie&&=(await ie.unsubscribe(),null)}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{E?.destroy(),k&&=(await k.disconnect(),null)}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await T.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await se(g)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await C.flushPendingGitCommit(),await C.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),g)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{I&&=(await I.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(S.current){try{let e=(await Pe({baseDir:n,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&z(V(S.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{Sp(S.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let r=Date.now()-e;t.length===0?v.info({documentCount:a,durationMs:r},`[server] shutdown flushed ${a} documents in ${r}ms`):v.warn({documentCount:a,durationMs:r,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${r}ms with ${t.length} phase error(s)`)}}finally{try{N(y)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),v.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}}})(),oe)}let ue=[];async function de(){if(!S.current)try{S.current=await xp(n),v.info({gitDir:S.current.gitDir},`[server] shadow repo initialized at ${S.current.gitDir}`)}catch(e){v.error({err:e},`[server] shadow repo init failed`),ue.push(`shadow-repo`)}if(S.current)try{await bp(S.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){v.warn({},`[server] shadow repo appears corrupted — reinitializing`);try{S.current=await xp(n)}catch(e){v.error({err:e},`[server] shadow repo reinit failed`),S.current=void 0,ue.includes(`shadow-repo`)||ue.push(`shadow-repo`)}}else v.error({err:e},`[server] shadow repo check failed (transient?)`)}if(S.current)try{let e=V(S.current.gitDir,`last-known-head`),t=null;try{t=R(e,`utf-8`).trim()||null}catch{}let r=null;try{r=(await Pe({baseDir:n,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(r!==null){if(r!==t){let e=`main`;try{let t=(await Pe({baseDir:n,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}v.info({lastKnownHead:t,currentHead:r,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=import`);try{await Tp(S.current,p??``,t,r,e),Rc()}catch(e){v.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else v.info({currentHead:r},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=noop`);try{z(e,r,`utf-8`)}catch(e){v.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){v.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=Vm(t);e.recovered&&e.journal&&v.warn({sourceDocName:e.journal.sourceDocName,destinationDocName:e.journal.destinationDocName,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${e.journal.sourceDocName} -> ${e.journal.destinationDocName}`)}catch(e){v.error({err:e},`[server] managed rename recovery failed`),ue.push(`managed-rename-recovery`)}try{k=await w.openDirectConnection(r)}catch(e){v.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),ue.push(`cc1-push`)}try{ie=await _m(t,re,b),x.rebuildFromDisk(zp()),x.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist startup cache for ${zp()}:`,e)})}catch(e){v.error({err:e},`[server] disk bridge watcher failed to start`),ue.push(`file-watcher`)}try{ae=await jv(n,async({trigger:e})=>{if(v.info({trigger:e},`[batch] begin trigger=${e}`),Lc(),w.flushPendingStores(),await C.flushPendingGitCommit(),S.current){let e=zp(),t=[];for(let[e]of w.documents){if(q(e))continue;let n=j(e);if(n===null)continue;let r=Bp(e)??n;t.push({docName:e,markdown:n,diskSnapshot:r})}if(t.length>0)try{let n=await Ap(S.current,e,`server`,t);n&&(Vc(),v.info({count:t.length,branch:e,sha:n.slice(0,8)},`[shadow] parked ${t.length} docs on ${e} → ${n.slice(0,8)}`))}catch(e){v.error({err:e},`[shadow] park failed`)}}Wp(!0)},async e=>{let n=P.length,r=e.newBranch??`main`;if(Wp(!1),v.info({kind:e.batchKind,headMoved:e.headMoved,docs:n,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${n}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`)await F();else{Bc(),P.splice(0,P.length),Rp(r),x.switchBranch(r);for(let[e,n]of w.documents)if(!q(e))try{let i=Pp(e,t);if(!L(i)){let t=Bp(e)??``,i=j(e)??``;if(i!==t&&S.current){let t=S.current;queueMicrotask(()=>{Op(t,p??``,{kind:`external-change-rescue`,docName:e,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:r,metadata:{incomingDiskSha:``}}).then(()=>{zc(),v.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{v.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),v.info({docName:e,branch:r},`[branch-switch] tombstone: ${e} (not on ${r})`);continue}let a=R(i,`utf-8`);M(e,a),Vp(e,a),v.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){v.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}if(v.info({branch:r,docCount:w.documents.size},`[branch-switch] loaded branch ${r} (${w.documents.size} docs)`),x.rebuildFromDisk(r),x.saveToDisk(r).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${r}:`,e)}),S.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of w.documents)if(!q(t))try{let n=await jp(S.current,r,`server`,t);if(!n||n.markdown===n.diskSnapshot)continue;let i=Bp(t);if(!i)continue;let a=Xp({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:i});switch(a.kind){case`merged`:case`clean`:M(t,a.newContent),Vp(t,a.newContent),e++;break;case`conflicts`:M(t,a.newContent),Vp(t,a.newContent),Ic(),e++;break;case`noop`:case`refused`:break}}catch(e){v.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&v.info({count:e,branch:r},`[branch-switch] restored ${e} parked docs on ${r}`)}if(e.oldBranch?.startsWith(`detached-`)&&S.current)try{let t=bp(S.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(n){for(let e of n.split(`
89
+ `))e&&await t.raw(`update-ref`,`-d`,e);v.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){v.error({err:e},`[branch-switch] detached cleanup failed`)}}if(e.headMoved&&e.newHead&&S.current&&n>0){let t=p??`content`;try{let n=await Tp(S.current,t,e.oldHead,e.newHead,r);Rc(),v.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[shadow] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){v.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){v.error({err:e},`[server] HEAD watcher failed to start`),ue.push(`head-watcher`)}let e=_?.[0]??`open-knowledge`,i=[`-c`,`credential.helper=!${_&&_.length>1?_.join(` `):e} auth git-credential`];try{I=new dy({projectDir:n,contentDir:t,contentFilter:b,contentRoot:p,credentialArgs:i,cc1Broadcaster:E,setBatchInProgress:Wp,onStateChange:e=>{v.info({state:e},`[sync] state → ${e}`)}}),await I.start()}catch(e){v.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),I=null}}let fe=de();return{hocuspocus:w,sessionManager:T,cc1Broadcaster:E,agentFocusBroadcaster:D,contentFilter:b,destroy:ce,ready:fe,degraded:ue,lockDir:y,get syncEngine(){return I}}}async function py(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.idleShutdownMs,i=e.log??Pc(`boot`),{createServer:a}=await import(`node:http`),{WebSocketServer:o}=await import(`./wrapper-BK_jpkDm.mjs`),{updateServerLockPort:s}=await import(`./server-lock-CPmOhzSz.mjs`),c=!1;!t&&e.ensureProjectGitFn&&(c=!!(await e.ensureProjectGitFn()).didInit);let l=!1;if(!t&&e.autoInitFn)try{l=!!await e.autoInitFn()}catch(e){i.warn({err:e},`autoInitFn failed`)}let u=fy({contentDir:e.contentDir,projectDir:e.projectDir,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,includePatterns:e.includePatterns,excludePatterns:e.excludePatterns,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite}),{hocuspocus:d,destroy:f,ready:p,degraded:m,lockDir:h}=u,g=a((e,t)=>{let n=e.url?.split(`?`)[0];if(n?.startsWith(`/api/`)){d.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||(t.statusCode=404,t.setHeader(`Content-Type`,`application/json`),t.end(JSON.stringify({error:`API route not found`,path:n})))}).catch(e=>{i.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?(t.writeHead(500),t.end(`Internal server error`)):t.writableEnded||t.end()});return}t.writeHead(404,{"Content-Type":`application/json`}),t.end(JSON.stringify({error:"Not found. The React UI is served by `ok ui` (default port 3000).",path:n??`/`}))}),_=new o({noServer:!0});_.on(`error`,e=>{i.error({err:e},`WebSocketServer error`)}),g.on(`upgrade`,(e,t,n)=>{if(e.url?.startsWith(`/collab/keepalive`)){t.on(`error`,e=>{Qc(e)||i.error({err:e},`MCP keepalive socket error`)}),_.handleUpgrade(e,t,n,e=>{let t=setInterval(()=>{try{e.ping()}catch{}},3e4);t.unref?.(),e.on(`close`,()=>clearInterval(t)),e.on(`error`,t=>{Qc(t)||i.error({err:t},`MCP keepalive WS error`),e.terminate()})});return}e.url?.startsWith(`/collab`)&&(t.on(`error`,e=>{Qc(e)||i.error({err:e},`Upgrade socket error`)}),_.handleUpgrade(e,t,n,t=>{let n=d.handleConnection(t,e);t.on(`message`,e=>{n.handleMessage((e instanceof ArrayBuffer,new Uint8Array(e)))}),t.on(`close`,(e,t)=>{n.handleClose({code:e,reason:t.toString()})}),t.on(`error`,e=>{Qc(e)||i.error({err:e},`WebSocket error`),t.terminate()})}))});let v=null;r!==null&&(v=ng({httpServer:g,thresholdMs:r??18e5,log:i,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await f()})})),await new Promise((t,n)=>{let r=e=>n(e);g.once(`error`,r),g.listen(e.port,e.host,()=>{g.removeListener(`error`,r),t()})});let y=g.address(),b=typeof y==`object`&&y?y.port:e.port??0;if(s(h,b),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:h,log:i})}catch(e){i.warn({err:e},`spawnUiSiblingFn failed`)}let x=!1;return{httpServer:g,destroy:async()=>{x||(x=!0,v?.detach(),await new Promise(e=>{g.close(()=>e())}),await f())},lockDir:h,contentDir:e.contentDir,port:b,ready:p,degraded:m,didAutoInit:l,didGitInit:c,serverInstance:u}}const my=Ve(je);var hy=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function gy(e){let t=V(e),n=V(t,`.git`);if(L(n))return{didInit:!1};let r=``;try{r=(await my(`git`,[`init`,`--initial-branch=main`,t])).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new hy(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!L(V(n,`HEAD`)))throw new hy(`git init reported success but ${n}/HEAD is missing (partial init detected)`,r);return console.log(`[project-git] initialized .git/ at ${t} (branch: main)`),{didInit:!0}}export{Tf as $,qp as A,Dp as B,sm as C,_m as D,lm as E,Pp as F,dp as G,Mp as H,Tp as I,sp as J,fp as K,Cp as L,Xp as M,Yp as N,cm as O,Kp as P,wf as Q,xp as R,dm as S,nm as T,bp as U,Op as V,up as W,xf as X,tp as Y,Sf as Z,$m as _,zv as a,ol as at,im as b,Av as c,el as ct,xv as d,Kc as dt,Cf as et,ng as f,Mc as ft,Gh as g,tg as h,fy as i,sl as it,Jp as j,em as k,Tv as l,Qc as lt,Ih as m,Nc as mt,gy as n,al as nt,Fv as o,tl as ot,Lh as p,Pc as pt,gp as q,py as r,cl as rt,Pv as s,q as st,hy as t,$d as tt,Ev as u,Zc as ut,Qm as v,am as w,rm as x,um as y,kp as z};
90
+ //# sourceMappingURL=src-Cgk_X3wh.mjs.map