@inkeep/open-knowledge 0.0.0-dev-20260423022549 → 0.0.0-dev-20260423140112

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.
@@ -6,86 +6,87 @@ caused by: `+i(o,t)):a},a=e=>i(e,new Set),o=(e,t,i)=>{if(!n(e))return``;let a=i?
6
6
  `}){let r=e.split(/\r?\n/);for(let e=1;e<r.length;e+=1)r[e]=t+r[e];return r.join(n)}})),Wt=n(((e,t)=>{t.exports=s;let{LEVEL_NAMES:n}=Tt(),r=Dt(),i=Bt(),a=zt(),o=Et();function s(e){let t=e.crlf?`\r
7
7
  `:`
8
8
  `,{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}}})),Gt=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)}}})),Kt=n(((e,t)=>{t.exports=r;let n=Ut();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}})),qt=n(((e,t)=>{t.exports=o;let{LOGGER_KEYS:n}=Tt(),r=Gt(),i=Ut(),a=Kt();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}})),Jt=n(((e,t)=>{t.exports=o;let{LOGGER_KEYS:n}=Tt(),r=Ht(),i=Ut(),a=qt();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}})),Yt=n(((e,t)=>{t.exports=r;let n=Nt();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}})),Xt=n(((e,t)=>{t.exports=a;let{LEVELS:n}=Tt(),r=Nt(),i=Vt();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])}})),Zt=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}})),Qt=n(((e,t)=>{t.exports=r;let n=Rt();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}]`}})),$t=n(((e,t)=>{t.exports={buildSafeSonicBoom:kt(),createDate:jt(),deleteLogProperty:Pt(),filterLog:It(),formatTime:Rt(),getPropertyValue:Nt(),handleCustomLevelsNamesOpts:zt(),handleCustomLevelsOpts:Bt(),interpretConditionals:Vt(),isObject:Ht(),isValidDate:At(),joinLinesWithIndentation:Ut(),noop:Ot(),parseFactoryOptions:Wt(),prettifyErrorLog:Jt(),prettifyError:Kt(),prettifyLevel:Yt(),prettifyMessage:Xt(),prettifyMetadata:Zt(),prettifyObject:qt(),prettifyTime:Qt(),splitPropertyKey:Mt(),getLevelLabelData:Et()}})),en=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})),tn=n(((e,t)=>{t.exports=h;let n=en(),r=Ht(),i=Jt(),a=Yt(),o=Xt(),s=Zt(),c=qt(),l=Qt(),u=It(),{LEVELS:d,LEVEL_KEY:f,LEVEL_NAMES:p}=Tt(),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}})),nn=n(((e,n)=>{let{isColorSupported:r}=vt(),i=St(),{Transform:a}=t(`node:stream`),o=wt(),s=Dt(),{ERROR_LIKE_KEYS:c,LEVEL_KEY:l,LEVEL_LABEL:u,MESSAGE_KEY:d,TIMESTAMP_KEY:f}=Tt(),{buildSafeSonicBoom:p,parseFactoryOptions:m}=$t(),h=tn(),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+`
9
- `)}),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})),rn=e(_t(),1),an=e(nn(),1);function on(){return process.env.NO_COLOR&&process.env.NO_COLOR!==``?!1:process.stdout.isTTY??!1}var sn=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:rn.default.stdSerializers.err,error:rn.default.stdSerializers.err},...t.options},t.transportConfigs&&(this.transportConfigs=t.transportConfigs),this.pinoInstance=this.buildInstance()}buildInstance(){if(this.transportConfigs.length>0)return(0,rn.default)(this.options,rn.default.transport({targets:this.transportConfigs}));try{let e=(0,an.default)({colorize:on(),translateTime:`HH:MM:ss`,ignore:`pid,hostname`});return(0,rn.default)(this.options,e)}catch(e){return console.warn(`[PinoLogger] pino-pretty failed, falling back to JSON:`,e),(0,rn.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 cn=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 sn(e,this.config.pinoConfig),this.loggers.set(e,n),n}reset(){this.config={},this.loggers.clear()}};function ln(e){return cn.getLogger(e)}var un=class{hocuspocus;log=ln(`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(b);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),dn(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function dn(e){return e?.awareness??null}const fn=/^[a-zA-Z0-9_-]+$/;function pn(e){return typeof e!=`string`||e.length===0||!fn.test(e)?null:e}function mn(e){return`agent-${e}`}const U={reconcileCount:0,conflictCount:0,batchCount:0,upstreamImportCount:0,rescueBufferCount:0,branchSwitchCount:0,parkCount:0,gitAutoSaveFailureCount:0,gitWriterCommitFailureCount: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,shadowMigrationLegacyRefsDeleted:0,effectDiffCaptureFailures:0,agentPresenceMutationErrors:0};function hn(){U.reconcileCount++}function gn(){U.conflictCount++}function _n(){U.batchCount++}function vn(){U.upstreamImportCount++}function yn(){U.rescueBufferCount++}function bn(){U.branchSwitchCount++}function xn(){U.parkCount++}function Sn(){U.gitAutoSaveFailureCount++}function Cn(){U.gitWriterCommitFailureCount++}function wn(){U.cc1BroadcastCount++}function Tn(){U.cc1BroadcastDropCount++}function En(e){U.cc1SubscriberCount=e}function Dn(e){e===`a`?U.serverObserverFiresA++:U.serverObserverFiresB++}function On(){U.persistenceDiskWrites++}function kn(e){e===`a`?U.serverObserverErrorsA++:U.serverObserverErrorsB++}function An(){U.bridgeMergeContentLoss++}function jn(){U.bridgeMergeCheckpointCreated++}function Mn(e){e===`EPIPE`?U.collabSocketEpipeCount++:U.collabSocketEconnresetCount++}function Nn(e){U.shadowMigrationLegacyRefsDeleted+=e}function Pn(){U.effectDiffCaptureFailures++}function Fn(){U.agentPresenceMutationErrors++}function In(e){return e.code===`EPIPE`||e.code===`ECONNRESET`?(Mn(e.code),!0):!1}function Ln(e,t){U.cc1LastSeq[e]=t}function Rn(){return{...U,cc1LastSeq:{...U.cc1LastSeq}}}var zn=class{hocuspocus;log=ln(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){let n=0;this.mutateAgentPresence(r=>{let i=Date.now(),a={};for(let[t,o]of Object.entries(r)){if(i-o.ts>=2e4&&t!==e){n++;continue}a[t]=o}return a[e]=t,a})&&(this.log.debug({agentId:e,action:`set`,currentDoc:t.currentDoc,ts:t.ts},`[agent-presence] set`),n>0&&this.log.info({evictedCount:n,thresholdMs:2e4},`[agent-presence] evicted stale entries`))}clearPresence(e){let t=!1;this.mutateAgentPresence(n=>{if(!n[e])return n;t=!0;let{[e]:r,...i}=n;return i})&&t&&this.log.info({agentId:e,action:`clear`,currentDoc:null,ts:Date.now()},`[agent-presence] clear`)}touchMode(e,t){let n=[],r=!1,i=this.mutateAgentPresence(i=>{let a=i[e];if(!a)return i;r=!0;let o=Date.now();return n.push({currentDoc:a.currentDoc,ts:o}),{...i,[e]:{...a,mode:t,ts:o}}}),a=n[0];i&&a?this.log.debug({agentId:e,action:`touchMode`,currentDoc:a.currentDoc,ts:a.ts,mode:t},`[agent-presence] touchMode`):r||this.log.debug({agentId:e,action:`touchMode`,mode:t,reason:`entry-missing`},`[agent-presence] touchMode skipped — no entry for agentId`)}bumpPresenceTs(e){let t=null;this.mutateAgentPresence(n=>{let r=n[e];if(!r)return n;let i=Date.now();return t=i,{...n,[e]:{...r,ts:i}}}),t!==null&&this.log.debug({agentId:e,action:`bumpTs`,ts:t},`[agent-presence] bumpTs`)}getPresenceMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentPresence??{}:{}}destroy(){this.destroyed=!0}mutateAgentPresence(e){if(this.destroyed)return!1;let t=this.resolveAwareness();if(!t)return!1;try{let n=t.getLocalState()??{},r=e(n.agentPresence??{});return t.setLocalState({...n,agentPresence:r}),!0}catch(e){return Fn(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(b);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),Bn(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function Bn(e){return e?.awareness??null}const Vn=()=>new Map,Hn=e=>{let t=Vn();return e.forEach((e,n)=>{t.set(n,e)}),t},Un=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r},Wn=(e,t)=>{for(let[n,r]of e)if(t(r,n))return!0;return!1},Gn=()=>new Set,Kn=e=>e[e.length-1],qn=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},Jn=Array.from,Yn=(e,t)=>{for(let n=0;n<e.length;n++)if(t(e[n],n,e))return!0;return!1},Xn=Array.isArray;var Zn=class{constructor(){this._observers=Vn()}on(e,t){return Un(this._observers,e,Gn).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 Jn((this._observers.get(e)||Vn()).values()).forEach(e=>e(...t))}destroy(){this._observers=Vn()}};const Qn=Math.floor,$n=Math.abs,er=(e,t)=>e<t?e:t,tr=(e,t)=>e>t?e:t;Number.isNaN;const nr=e=>e===0?1/e<0:e<0,rr=2**53-1,ir=Number.isInteger||(e=>typeof e==`number`&&isFinite(e)&&Qn(e)===e);Number.isNaN,Number.parseInt;const ar=String.fromCharCode;String.fromCodePoint,ar(65535);const or=e=>e.toLowerCase(),sr=/^\s*/g,cr=e=>e.replace(sr,``),lr=/([A-Z])/g,ur=(e,t)=>cr(e.replace(lr,e=>`${t}${or(e)}`)),dr=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},fr=typeof TextEncoder<`u`?new TextEncoder:null,pr=fr?e=>fr.encode(e):dr;let mr=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});mr&&mr.decode(new Uint8Array).length===1&&(mr=null);var hr=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const gr=()=>new hr,_r=e=>{let t=gr();return e(t),yr(t)},vr=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},yr=e=>{let t=new Uint8Array(vr(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},br=(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(tr(n,t)*2),e.cpos=0)},xr=(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},Sr=xr,W=(e,t)=>{for(;t>127;)xr(e,128|127&t),t=Qn(t/128);xr(e,127&t)},Cr=(e,t)=>{let n=nr(t);for(n&&(t=-t),xr(e,(t>63?128:0)|(n?64:0)|63&t),t=Qn(t/64);t>0;)xr(e,(t>127?128:0)|127&t),t=Qn(t/128)},wr=new Uint8Array(3e4),Tr=wr.length/3,Er=fr&&fr.encodeInto?(e,t)=>{if(t.length<Tr){let n=fr.encodeInto(t,wr).written||0;W(e,n);for(let t=0;t<n;t++)xr(e,wr[t])}else Or(e,pr(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;W(e,r);for(let t=0;t<r;t++)xr(e,n.codePointAt(t))},Dr=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=er(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(tr(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},Or=(e,t)=>{W(e,t.byteLength),Dr(e,t)},kr=(e,t)=>{br(e,t);let n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},Ar=(e,t)=>kr(e,4).setFloat32(0,t,!1),jr=(e,t)=>kr(e,8).setFloat64(0,t,!1),Mr=(e,t)=>kr(e,8).setBigInt64(0,t,!1),Nr=new DataView(new ArrayBuffer(4)),Pr=e=>(Nr.setFloat32(0,e),Nr.getFloat32(0)===e),Fr=(e,t)=>{switch(typeof t){case`string`:xr(e,119),Er(e,t);break;case`number`:ir(t)&&$n(t)<=2147483647?(xr(e,125),Cr(e,t)):Pr(t)?(xr(e,124),Ar(e,t)):(xr(e,123),jr(e,t));break;case`bigint`:xr(e,122),Mr(e,t);break;case`object`:if(t===null)xr(e,126);else if(Xn(t)){xr(e,117),W(e,t.length);for(let n=0;n<t.length;n++)Fr(e,t[n])}else if(t instanceof Uint8Array)xr(e,116),Or(e,t);else{xr(e,118);let n=Object.keys(t);W(e,n.length);for(let r=0;r<n.length;r++){let i=n[r];Er(e,i),Fr(e,t[i])}}break;case`boolean`:xr(e,t?120:121);break;default:xr(e,127)}};var Ir=class extends hr{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&W(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}};const Lr=e=>{e.count>0&&(Cr(e.encoder,e.count===1?e.s:-e.s),e.count>1&&W(e.encoder,e.count-2))};var Rr=class{constructor(){this.encoder=new hr,this.s=0,this.count=0}write(e){this.s===e?this.count++:(Lr(this),this.count=1,this.s=e)}toUint8Array(){return Lr(this),yr(this.encoder)}};const zr=e=>{if(e.count>0){let t=e.diff*2+(e.count===1?0:1);Cr(e.encoder,t),e.count>1&&W(e.encoder,e.count-2)}};var Br=class{constructor(){this.encoder=new hr,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(zr(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return zr(this),yr(this.encoder)}},Vr=class{constructor(){this.sarr=[],this.s=``,this.lensE=new Rr}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 hr;return this.sarr.push(this.s),this.s=``,Er(e,this.sarr.join(``)),Dr(e,this.lensE.toUint8Array()),yr(e)}};const Hr=e=>Error(e),Ur=()=>{throw Hr(`Method unimplemented`)},Wr=()=>{throw Hr(`Unexpected case`)},Gr=Hr(`Unexpected end of array`),Kr=Hr(`Integer out of Range`);var qr=class{constructor(e){this.arr=e,this.pos=0}};const Jr=e=>new qr(e),Yr=e=>e.pos!==e.arr.length,Xr=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},Zr=e=>Xr(e,G(e)),Qr=e=>e.arr[e.pos++],G=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>rr)throw Kr}throw Gr},$r=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>rr)throw Kr}throw Gr},ei=mr?e=>mr.decode(Zr(e)):e=>{let t=G(e);if(t===0)return``;{let n=String.fromCodePoint(Qr(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Qr(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))}},ti=(e,t)=>{let n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},ni=[e=>void 0,e=>null,$r,e=>ti(e,4).getFloat32(0,!1),e=>ti(e,8).getFloat64(0,!1),e=>ti(e,8).getBigInt64(0,!1),e=>!1,e=>!0,ei,e=>{let t=G(e),n={};for(let r=0;r<t;r++){let t=ei(e);n[t]=ri(e)}return n},e=>{let t=G(e),n=[];for(let r=0;r<t;r++)n.push(ri(e));return n},Zr],ri=e=>ni[127-Qr(e)](e);var ii=class extends qr{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Yr(this)?this.count=G(this)+1:this.count=-1),this.count--,this.s}},ai=class extends qr{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=$r(this);let e=nr(this.s);this.count=1,e&&(this.s=-this.s,this.count=G(this)+2)}return this.count--,this.s}},oi=class extends qr{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){let e=$r(this),t=e&1;this.diff=Qn(e/2),this.count=1,t&&(this.count=G(this)+2)}return this.s+=this.diff,this.count--,this.s}},si=class{constructor(e){this.decoder=new ai(e),this.str=ei(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}};je.subtle;const ci=je.getRandomValues.bind(je),li=()=>ci(new Uint32Array(1))[0],ui=()=>`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^li()&15>>e/4).toString(16)),di=Date.now,fi=e=>new Promise(e);Promise.all.bind(Promise);const pi=e=>e===void 0?null:e;let mi=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&&(mi=localStorage)}catch{}const hi=mi,gi=Symbol(`Equality`),_i=(e,t)=>e===t||!!e?.[gi]?.(t)||!1,vi=Object.assign,yi=Object.keys,bi=(e,t)=>{for(let n in e)t(e[n],n)},xi=e=>yi(e).length,Si=e=>{for(let t in e)return!1;return!0},Ci=(e,t)=>{for(let n in e)if(!t(e[n],n))return!1;return!0},wi=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Ti=(e,t)=>e===t||xi(e)===xi(t)&&Ci(e,(e,n)=>(e!==void 0||wi(t,n))&&_i(t[n],e)),Ei=Object.freeze,Di=e=>{for(let t in e){let n=e[t];(typeof n==`object`||typeof n==`function`)&&Di(e[t])}return Ei(e)},Oi=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&Oi(e,t,n+1)}},ki=e=>e,Ai=(e,t)=>t.includes(e),ji=typeof process<`u`&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<`u`?process:0)===`[object process]`,Mi=typeof window<`u`&&typeof document<`u`&&!ji;typeof navigator<`u`&&/Mac/.test(navigator.platform);let Ni;const Pi=[],Fi=()=>{if(Ni===void 0)if(ji){Ni=Vn();let e=process.argv,t=null;for(let n=0;n<e.length;n++){let r=e[n];r[0]===`-`?(t!==null&&Ni.set(t,``),t=r):t===null?Pi.push(r):(Ni.set(t,r),t=null)}t!==null&&Ni.set(t,``)}else typeof location==`object`?(Ni=Vn(),(location.search||`?`).slice(1).split(`&`).forEach(e=>{if(e.length!==0){let[t,n]=e.split(`=`);Ni.set(`--${ur(t,`-`)}`,n),Ni.set(`-${ur(t,`-`)}`,n)}})):Ni=Vn();return Ni},Ii=e=>Fi().has(e),Li=e=>pi(ji?process.env[e.toUpperCase().replaceAll(`-`,`_`)]:hi.getItem(e)),Ri=e=>Ii(`--`+e)||Li(e)!==null;Ri(`production`);const zi=ji&&Ai(process.env.FORCE_COLOR,[`true`,`1`,`2`])||!Ii(`--no-colors`)&&!Ri(`no-color`)&&(!ji||process.stdout.isTTY)&&(!ji||Ii(`--color`)||Li(`COLORTERM`)!==null||(Li(`TERM`)||``).includes(`color`)),Bi=e=>new Uint8Array(e),Vi=Mi?e=>{let t=``;for(let n=0;n<e.byteLength;n++)t+=ar(e[n]);return btoa(t)}:e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64`),Hi=e=>{let t=Bi(e.byteLength);return t.set(e),t},Ui=e=>_r(t=>Fr(t,e)),Wi=Symbol,Gi=Wi(),Ki=Wi(),qi=Wi(),Ji=Wi(),Yi=Wi(),Xi=Wi(),Zi=Wi(),Qi=Wi(),$i=Wi(),ea=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};di();const ta={[Gi]:`\x1B[1m`,[Ki]:`\x1B[2m`,[qi]:`\x1B[34m`,[Yi]:`\x1B[32m`,[Ji]:`\x1B[37m`,[Xi]:`\x1B[31m`,[Zi]:`\x1B[35m`,[Qi]:`\x1B[38;5;208m`,[$i]:`\x1B[0m`},na=zi?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=ta[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}:ea,ra=(...e)=>{console.log(...na(e))},ia=(...e)=>{console.warn(...na(e))},aa=e=>({[Symbol.iterator](){return this},next:e}),oa=(e,t)=>aa(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),sa=(e,t)=>aa(()=>{let{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}});var ca=class{constructor(e,t){this.clock=e,this.len=t}},la=class{constructor(){this.clients=new Map}};const ua=(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])So(e,i,o.clock,o.len,n)}}),da=(e,t)=>{let n=0,r=e.length-1;for(;n<=r;){let i=Qn((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},fa=(e,t)=>{let n=e.clients.get(t.client);return n!==void 0&&da(n,t.clock)!==null},pa=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 ca(r.clock,tr(r.len,i.clock+i.len-r.clock)):(n<t&&(e[n]=i),n++)}e.length=n})},ma=e=>{let t=new la;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++)qn(a,e[t].clients.get(i)||[]);t.clients.set(i,a)}});return pa(t),t},ha=(e,t,n,r)=>{Un(e.clients,t,()=>[]).push(new ca(n,r))},ga=()=>new la,_a=e=>{let t=ga();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 ca(i,a))}}r.length>0&&t.clients.set(n,r)}),t},va=(e,t)=>{W(e.restEncoder,t.clients.size),Jn(t.clients.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{e.resetDsCurVal(),W(e.restEncoder,t);let r=n.length;W(e.restEncoder,r);for(let t=0;t<r;t++){let r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}})},ya=e=>{let t=new la,n=G(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();let n=G(e.restDecoder),r=G(e.restDecoder);if(r>0){let i=Un(t.clients,n,()=>[]);for(let t=0;t<r;t++)i.push(new ca(e.readDsClock(),e.readDsLen()))}}return t},ba=(e,t,n)=>{let r=new la,i=G(e.restDecoder);for(let a=0;a<i;a++){e.resetDsCurVal();let i=G(e.restDecoder),a=G(e.restDecoder),o=n.clients.get(i)||[],s=mo(n,i);for(let n=0;n<a;n++){let n=e.readDsClock(),a=n+e.readDsLen();if(n<s){s<a&&ha(r,i,s,a-s);let e=go(o,n),c=o[e];for(!c.deleted&&c.id.clock<n&&(o.splice(e+1,0,Ic(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,Ic(t,c,a-c.id.clock)),c.delete(t))}else ha(r,i,n,a-n)}}if(r.clients.size>0){let e=new ja;return W(e.restEncoder,0),va(e,r),e.toUint8Array()}return null},xa=(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},Sa=li;var Ca=class e extends Zn{constructor({guid:e=ui(),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=Sa(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new fo,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=fi(e=>{this.on(`load`,()=>{this.isLoaded=!0,e(this)})});let s=()=>fi(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&&q(e.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Jn(this.subdocs).map(e=>e.guid))}transact(e,t=null){return q(this,e,t)}get(e,t=is){let n=Un(this.share,e,()=>{let e=new t;return e._integrate(this,null),e}),r=n.constructor;if(t!==is&&r!==t)if(r===is){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,Ts)}getText(e=``){return this.get(e,Ks)}getMap(e=``){return this.get(e,Os)}getXmlElement(e=``){return this.get(e,Zs)}getXmlFragment(e=``){return this.get(e,Ys)}toJSON(){let e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,Jn(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,q(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()}},wa=class{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return G(this.restDecoder)}readDsLen(){return G(this.restDecoder)}},Ta=class extends wa{readLeftID(){return K(G(this.restDecoder),G(this.restDecoder))}readRightID(){return K(G(this.restDecoder),G(this.restDecoder))}readClient(){return G(this.restDecoder)}readInfo(){return Qr(this.restDecoder)}readString(){return ei(this.restDecoder)}readParentInfo(){return G(this.restDecoder)===1}readTypeRef(){return G(this.restDecoder)}readLen(){return G(this.restDecoder)}readAny(){return ri(this.restDecoder)}readBuf(){return Hi(Zr(this.restDecoder))}readJSON(){return JSON.parse(ei(this.restDecoder))}readKey(){return ei(this.restDecoder)}},Ea=class{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=G(this.restDecoder),this.dsCurrVal}readDsLen(){let e=G(this.restDecoder)+1;return this.dsCurrVal+=e,e}},Da=class extends Ea{constructor(e){super(e),this.keys=[],G(e),this.keyClockDecoder=new oi(Zr(e)),this.clientDecoder=new ai(Zr(e)),this.leftClockDecoder=new oi(Zr(e)),this.rightClockDecoder=new oi(Zr(e)),this.infoDecoder=new ii(Zr(e),Qr),this.stringDecoder=new si(Zr(e)),this.parentInfoDecoder=new ii(Zr(e),Qr),this.typeRefDecoder=new ai(Zr(e)),this.lenDecoder=new ai(Zr(e))}readLeftID(){return new eo(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new eo(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 ri(this.restDecoder)}readBuf(){return Zr(this.restDecoder)}readJSON(){return ri(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}}},Oa=class{constructor(){this.restEncoder=gr()}toUint8Array(){return yr(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){W(this.restEncoder,e)}writeDsLen(e){W(this.restEncoder,e)}},ka=class extends Oa{writeLeftID(e){W(this.restEncoder,e.client),W(this.restEncoder,e.clock)}writeRightID(e){W(this.restEncoder,e.client),W(this.restEncoder,e.clock)}writeClient(e){W(this.restEncoder,e)}writeInfo(e){Sr(this.restEncoder,e)}writeString(e){Er(this.restEncoder,e)}writeParentInfo(e){W(this.restEncoder,e?1:0)}writeTypeRef(e){W(this.restEncoder,e)}writeLen(e){W(this.restEncoder,e)}writeAny(e){Fr(this.restEncoder,e)}writeBuf(e){Or(this.restEncoder,e)}writeJSON(e){Er(this.restEncoder,JSON.stringify(e))}writeKey(e){Er(this.restEncoder,e)}},Aa=class{constructor(){this.restEncoder=gr(),this.dsCurrVal=0}toUint8Array(){return yr(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){let t=e-this.dsCurrVal;this.dsCurrVal=e,W(this.restEncoder,t)}writeDsLen(e){e===0&&Wr(),W(this.restEncoder,e-1),this.dsCurrVal+=e}},ja=class extends Aa{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new Br,this.clientEncoder=new Rr,this.leftClockEncoder=new Br,this.rightClockEncoder=new Br,this.infoEncoder=new Ir(Sr),this.stringEncoder=new Vr,this.parentInfoEncoder=new Ir(Sr),this.typeRefEncoder=new Rr,this.lenEncoder=new Rr}toUint8Array(){let e=gr();return W(e,0),Or(e,this.keyClockEncoder.toUint8Array()),Or(e,this.clientEncoder.toUint8Array()),Or(e,this.leftClockEncoder.toUint8Array()),Or(e,this.rightClockEncoder.toUint8Array()),Or(e,yr(this.infoEncoder)),Or(e,this.stringEncoder.toUint8Array()),Or(e,yr(this.parentInfoEncoder)),Or(e,this.typeRefEncoder.toUint8Array()),Or(e,this.lenEncoder.toUint8Array()),Dr(e,yr(this.restEncoder)),yr(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){Fr(this.restEncoder,e)}writeBuf(e){Or(this.restEncoder,e)}writeJSON(e){Fr(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 Ma=(e,t,n,r)=>{r=tr(r,t[0].id.clock);let i=go(t,r);W(e.restEncoder,t.length-i),e.writeClient(n),W(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)},Na=(e,t,n)=>{let r=new Map;n.forEach((e,n)=>{mo(t,n)>e&&r.set(n,e)}),po(t).forEach((e,t)=>{n.has(t)||r.set(t,0)}),W(e.restEncoder,r.size),Jn(r.entries()).sort((e,t)=>t[0]-e[0]).forEach(([n,r])=>{Ma(e,t.clients.get(n),n,r)})},Pa=(e,t)=>{let n=Vn(),r=G(e.restDecoder);for(let i=0;i<r;i++){let r=G(e.restDecoder),i=Array(r),a=e.readClient(),o=G(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 ac(K(a,o),t),o+=t;break}case 10:{let t=G(e.restDecoder);i[n]=new Hc(K(a,o),t),o+=t;break}default:{let s=(r&192)==0,c=new zc(K(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,Bc(e,r));i[n]=c,o+=c.length}}}}return n},Fa=(e,t,n)=>{let r=[],i=Jn(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 fo,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!==Hc){let i=Un(d,u.id.client,()=>mo(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,mo(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 ja;return Na(e,s,new Map),W(e.restEncoder,0),{missing:c,update:e.toUint8Array()}}return null},Ia=(e,t)=>Na(e,t.doc.store,t.beforeState),La=(e,t,n,r=new Da(e))=>q(t,e=>{e.local=!1;let t=!1,n=e.doc,i=n.store,a=Fa(e,i,Pa(r,n)),o=i.pendingStructs;if(o){for(let[e,n]of o.missing)if(n<mo(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=zo([o.update,a.update])}}else i.pendingStructs=a;let s=ba(r,e,i);if(i.pendingDs){let t=new Da(Jr(i.pendingDs));G(t.restDecoder);let n=ba(t,e,i);s&&n?i.pendingDs=zo([s,n]):i.pendingDs=s||n}else i.pendingDs=s;if(t){let t=i.pendingStructs.update;i.pendingStructs=null,Ra(e.doc,t)}},n,!1),Ra=(e,t,n,r=Da)=>{let i=Jr(t);La(i,e,n,new r(i))},za=(e,t,n)=>Ra(e,t,n,Ta),Ba=(e,t,n=new Map)=>{Na(e,t.store,n),va(e,_a(t.store))},Va=(e,t=new Uint8Array([0]),n=new ja)=>{Ba(n,e,Wa(t));let r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Bo(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===ka)return Lo(r.map((e,t)=>t===0?e:Go(e)));if(n.constructor===ja)return zo(r)}return r[0]},Ha=(e,t)=>Va(e,t,new ka),Ua=e=>{let t=new Map,n=G(e.restDecoder);for(let r=0;r<n;r++){let n=G(e.restDecoder),r=G(e.restDecoder);t.set(n,r)}return t},Wa=e=>Ua(new wa(Jr(e))),Ga=(e,t)=>(W(e.restEncoder,t.size),Jn(t.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{W(e.restEncoder,t),W(e.restEncoder,n)}),e),Ka=(e,t)=>Ga(e,po(t.store)),qa=(e,t=new Aa)=>(e instanceof Map?Ga(t,e):Ka(t,e),t.toUint8Array()),Ja=e=>qa(e,new Oa);var Ya=class{constructor(){this.l=[]}};const Xa=()=>new Ya,Za=(e,t)=>e.l.push(t),Qa=(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.`)},$a=(e,t,n)=>Oi(e.l,[t,n]);var eo=class{constructor(e,t){this.client=e,this.clock=t}};const to=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,K=(e,t)=>new eo(e,t),no=e=>{for(let[t,n]of e.doc.share.entries())if(n===e)return t;throw Wr()},ro=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};var io=class{constructor(e,t){this.ds=e,this.sv=t}};const ao=(e,t)=>new io(e,t);ao(ga(),new Map);const oo=e=>ao(_a(e.store),po(e.store)),so=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!fa(t.ds,e.id),co=(e,t)=>{let n=Un(e.meta,co,Gn),r=e.doc.store;n.has(t)||(t.sv.forEach((t,n)=>{t<mo(r,n)&&yo(e,K(n,t))}),ua(e,t.ds,e=>{}),n.add(t))},lo=(e,t,n=Da)=>{let r=new n(Jr(t)),i=new Fo(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=ma([e.ds,ya(r)]);return xa(e.ds,a)},uo=(e,t)=>lo(e,t,Ta);var fo=class{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}};const po=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},mo=(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},ho=(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 Wr()}n.push(t)},go=(e,t)=>{let n=0,r=e.length-1,i=e[r],a=i.id.clock;if(a===t)return r;let o=Qn(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=Qn((n+r)/2)}throw Wr()},_o=(e,t)=>{let n=e.clients.get(t.client);return n[go(n,t.clock)]},vo=(e,t,n)=>{let r=go(t,n),i=t[r];return i.id.clock<n&&i instanceof zc?(t.splice(r+1,0,Ic(e,i,n-i.id.clock)),r+1):r},yo=(e,t)=>{let n=e.doc.store.clients.get(t.client);return n[vo(e,n,t.clock)]},bo=(e,t,n)=>{let r=t.clients.get(n.client),i=go(r,n.clock),a=r[i];return n.clock!==a.id.clock+a.length-1&&a.constructor!==ac&&r.splice(i+1,0,Ic(e,a,n.clock-a.id.clock+1)),a},xo=(e,t,n)=>{let r=e.clients.get(t.id.client);r[go(r,t.id.clock)]=n},So=(e,t,n,r,i)=>{if(r===0)return;let a=n+r,o=vo(e,t,n),s;do s=t[o++],a<s.id.clock+s.length&&vo(e,t,a),i(s);while(o<t.length&&t[o].id.clock<a)};var Co=class{constructor(e,t,n){this.doc=e,this.deleteSet=new la,this.beforeState=po(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 wo=(e,t)=>t.deleteSet.clients.size===0&&!Wn(t.afterState,(e,n)=>t.beforeState.get(n)!==e)?!1:(pa(t.deleteSet),Ia(e,t),va(e,t.deleteSet),!0),To=(e,t,n)=>{let r=t._item;(r===null||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&Un(e.changed,t,Gn).add(n)},Eo=(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 zc&&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},Do=(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=go(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 zc&&i.deleted&&!i.keep&&n(i)&&i.gc(t,!1)}}}},Oo=(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=er(r.length-1,1+go(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+Eo(r,e)}})},ko=(e,t)=>{if(t<e.length){let n=e[t],r=n.doc,i=r.store,a=n.deleteSet,o=n._mergeStructs;try{pa(a),n.afterState=po(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(()=>{$a(r._dEH,t,n)}))}),e.push(()=>r.emit(`afterTransaction`,[n,r])),e.push(()=>{n._needFormattingCleanup&&Us(n)})}),Oi(e,[])}finally{r.gc&&Do(a,i,r.gcFilter),Oo(a,i),n.afterState.forEach((e,t)=>{let r=n.beforeState.get(t)||0;if(r!==e){let e=i.clients.get(t),n=tr(go(e,r),1);for(let t=e.length-1;t>=n;)t-=1+Eo(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=go(r,n);a+1<r.length&&Eo(r,a+1)>1||a>0&&Eo(r,a)}if(!n.local&&n.afterState.get(r.clientID)!==n.beforeState.get(r.clientID)&&(ra(Qi,Gi,`[yjs] `,Ki,Xi,`Changed the client-id because another client seems to be using it.`),r.clientID=Sa()),r.emit(`afterTransactionCleanup`,[n,r]),r._observers.has(`update`)){let e=new ka;wo(e,n)&&r.emit(`update`,[e.toUint8Array(),n.origin,r,n])}if(r._observers.has(`updateV2`)){let e=new ja;wo(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])):ko(e,t+1)}}},q=(e,t,n=null,r=!0)=>{let i=e._transactionCleanups,a=!1,o=null;e._transaction===null&&(a=!0,e._transaction=new Co(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&&ko(i,0)}}return o};var Ao=class{constructor(e,t){this.insertions=t,this.deletions=e,this.meta=new Map}};const jo=(e,t,n)=>{ua(e,n.deletions,n=>{n instanceof zc&&t.scope.some(t=>t===e.doc||ro(t,n))&&Fc(n,!1)})},Mo=(e,t,n)=>{let r=null,i=e.doc,a=e.scope;q(i,n=>{for(;t.length>0&&e.currStackItem===null;){let r=i.store,o=t.pop(),s=new Set,c=[],l=!1;ua(n,o.insertions,e=>{if(e instanceof zc){if(e.redone!==null){let{item:t,diff:i}=Pc(r,e.id);i>0&&(t=yo(n,K(t.id.client,t.id.clock+i))),e=t}!e.deleted&&a.some(t=>t===n.doc||ro(t,e))&&c.push(e)}}),ua(n,o.deletions,e=>{e instanceof zc&&a.some(t=>t===n.doc||ro(t,e))&&!fa(o.insertions,e.id)&&s.add(e)}),s.forEach(t=>{l=Rc(n,t,s,o.insertions,e.ignoreRemoteMapChanges,e)!==null||l});for(let t=c.length-1;t>=0;t--){let r=c[t];e.deleteFilter(r)&&(r.delete(n),l=!0)}e.currStackItem=l?o:null}n.changed.forEach((e,t)=>{e.has(null)&&t._searchMarker&&(t._searchMarker.length=0)}),r=n},e);let o=e.currStackItem;if(o!=null){let t=r.changedParentTypes;e.emit(`stack-item-popped`,[{stackItem:o,type:n,changedParentTypes:t,origin:e},e]),e.currStackItem=null}return o};var No=class extends Zn{constructor(e,{captureTimeout:t=500,captureTransaction:n=e=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:a=!1,doc:o=Xn(e)?e[0].doc:e instanceof Ca?e:e.doc}={}){super(),this.scope=[],this.doc=o,this.addToScope(e),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=n,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=a,this.captureTimeout=t,this.afterTransactionHandler=e=>{if(!this.captureTransaction(e)||!this.scope.some(t=>e.changedParentTypes.has(t)||t===this.doc)||!this.trackedOrigins.has(e.origin)&&(!e.origin||!this.trackedOrigins.has(e.origin.constructor)))return;let t=this.undoing,n=this.redoing,r=t?this.redoStack:this.undoStack;t?this.stopCapturing():n||this.clear(!1,!0);let i=new la;e.afterState.forEach((t,n)=>{let r=e.beforeState.get(n)||0,a=t-r;a>0&&ha(i,n,r,a)});let a=di(),o=!1;if(this.lastChange>0&&a-this.lastChange<this.captureTimeout&&r.length>0&&!t&&!n){let t=r[r.length-1];t.deletions=ma([t.deletions,e.deleteSet]),t.insertions=ma([t.insertions,i])}else r.push(new Ao(e.deleteSet,i)),o=!0;!t&&!n&&(this.lastChange=a),ua(e,e.deleteSet,t=>{t instanceof zc&&this.scope.some(n=>n===e.doc||ro(n,t))&&Fc(t,!0)});let s=[{stackItem:r[r.length-1],origin:e.origin,type:t?`redo`:`undo`,changedParentTypes:e.changedParentTypes},this];o?this.emit(`stack-item-added`,s):this.emit(`stack-item-updated`,s)},this.doc.on(`afterTransaction`,this.afterTransactionHandler),this.doc.on(`destroy`,()=>{this.destroy()})}addToScope(e){let t=new Set(this.scope);e=Xn(e)?e:[e],e.forEach(e=>{t.has(e)||(t.add(e),(e instanceof is?e.doc!==this.doc:e!==this.doc)&&ia(`[yjs#509] Not same Y.Doc`),this.scope.push(e))})}addTrackedOrigin(e){this.trackedOrigins.add(e)}removeTrackedOrigin(e){this.trackedOrigins.delete(e)}clear(e=!0,t=!0){(e&&this.canUndo()||t&&this.canRedo())&&this.doc.transact(n=>{e&&(this.undoStack.forEach(e=>jo(n,this,e)),this.undoStack=[]),t&&(this.redoStack.forEach(e=>jo(n,this,e)),this.redoStack=[]),this.emit(`stack-cleared`,[{undoStackCleared:e,redoStackCleared:t}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let e;try{e=Mo(this,this.undoStack,`undo`)}finally{this.undoing=!1}return e}redo(){this.redoing=!0;let e;try{e=Mo(this,this.redoStack,`redo`)}finally{this.redoing=!1}return e}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off(`afterTransaction`,this.afterTransactionHandler),super.destroy()}};function*Po(e){let t=G(e.restDecoder);for(let n=0;n<t;n++){let t=G(e.restDecoder),n=e.readClient(),r=G(e.restDecoder);for(let i=0;i<t;i++){let t=e.readInfo();if(t===10){let t=G(e.restDecoder);yield new Hc(K(n,r),t),r+=t}else if(31&t){let i=(t&192)==0,a=new zc(K(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,Bc(e,t));yield a,r+=a.length}else{let t=e.readLen();yield new ac(K(n,r),t),r+=t}}}}var Fo=class{constructor(e,t){this.gen=Po(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===Hc);return this.curr}},Io=class{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}};const Lo=e=>zo(e,Ta,ka),Ro=(e,t)=>{if(e.constructor===ac){let{client:n,clock:r}=e.id;return new ac(K(n,r+t),e.length-t)}else if(e.constructor===Hc){let{client:n,clock:r}=e.id;return new Hc(K(n,r+t),e.length-t)}else{let n=e,{client:r,clock:i}=n.id;return new zc(K(r,i+t),null,K(r,i+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},zo=(e,t=Da,n=ja)=>{if(e.length===1)return e[0];let r=e.map(e=>new t(Jr(e))),i=r.map(e=>new Fo(e,!0)),a=null,o=new n,s=new Io(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===Hc?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)Ho(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===Hc)a.struct.length=n.id.clock+n.length-a.struct.id.clock;else{Ho(s,a.struct,a.offset);let e=n.id.clock-a.struct.id.clock-a.struct.length;a={struct:new Hc(K(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===Hc?a.struct.length-=t:n=Ro(n,t)),a.struct.mergeWith(n)||(Ho(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!==Hc;n=e.next())Ho(s,a.struct,a.offset),a={struct:n,offset:0}}return a!==null&&(Ho(s,a.struct,a.offset),a=null),Uo(s),va(o,ma(r.map(e=>ya(e)))),o.toUint8Array()},Bo=(e,t,n=Da,r=ja)=>{let i=Wa(t),a=new r,o=new Io(a),s=new n(Jr(e)),c=new Fo(s,!1);for(;c.curr;){let e=c.curr,t=e.id.client,n=i.get(t)||0;if(c.curr.constructor===Hc){c.next();continue}if(e.id.clock+e.length>n)for(Ho(o,e,tr(n-e.id.clock,0)),c.next();c.curr&&c.curr.id.client===t;)Ho(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 Uo(o),va(a,ya(s)),a.toUint8Array()},Vo=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:yr(e.encoder.restEncoder)}),e.encoder.restEncoder=gr(),e.written=0)},Ho=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&Vo(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),W(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},Uo=e=>{Vo(e);let t=e.encoder.restEncoder;W(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){let r=e.clientStructs[n];W(t,r.written),Dr(t,r.restEncoder)}},Wo=(e,t,n,r)=>{let i=new n(Jr(e)),a=new Fo(i,!1),o=new r,s=new Io(o);for(let e=a.curr;e!==null;e=a.next())Ho(s,t(e),0);return Uo(s),va(o,ya(i)),o.toUint8Array()},Go=e=>Wo(e,ki,Da,ka),Ko=`You must not compute changes after the event-handler fired.`;var qo=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||=Jo(this.currentTarget,this.target)}deletes(e){return fa(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Hr(Ko);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=Kn(e.content.getContent());else return;else e!==null&&this.deletes(e)?(i=`update`,a=Kn(e.content.getContent())):(i=`add`,a=void 0)}else if(this.deletes(r))i=`delete`,a=Kn(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 Hr(Ko);let t=this.target,n=Gn(),r=Gn(),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 Jo=(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},Yo=()=>{ia(`Invalid access: Add Yjs type to a document before reading data.`)};let Xo=0;var Zo=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=Xo++}};const Qo=e=>{e.timestamp=Xo++},$o=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=Xo++},es=(e,t,n)=>{if(e.length>=80){let r=e.reduce((e,t)=>e.timestamp<t.timestamp?e:t);return $o(r,t,n),r}else{let r=new Zo(t,n);return e.push(r),r}},ts=(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)=>$n(t-e.index)<$n(t-n.index)?e:n),r=e._start,i=0;for(n!==null&&(r=n.p,i=n.index,Qo(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&&$n(n.index-i)<r.parent.length/80?($o(n,r,i),n):es(e._searchMarker,r,i)},ns=(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=tr(t,i.index+n))}},rs=(e,t,n)=>{let r=e,i=t.changedParentTypes;for(;Un(i,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;$a(r._eH,n,t)};var is=class{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Xa(),this._dEH=Xa(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw Ur()}clone(){throw Ur()}_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){Za(this._eH,e)}observeDeep(e){Za(this._dEH,e)}unobserve(e){Qa(this._eH,e)}unobserveDeep(e){Qa(this._dEH,e)}toJSON(){}};const as=(e,t,n)=>{e.doc??Yo(),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},os=e=>{e.doc??Yo();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},ss=(e,t)=>{let n=[],r=e._start;for(;r!==null;){if(r.countable&&so(r,t)){let e=r.content.getContent();for(let t=0;t<e.length;t++)n.push(e[t])}r=r.right}return n},cs=(e,t)=>{let n=0,r=e._start;for(e.doc??Yo();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}},ls=(e,t)=>{let n=[];return cs(e,(r,i)=>{n.push(t(r,i,e))}),n},us=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}}}},ds=(e,t)=>{e.doc??Yo();let n=ts(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}},fs=(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 zc(K(o,mo(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new bc(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 zc(K(o,mo(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new oc(new Uint8Array(n))),i.integrate(e,0);break;case Ca:i=new zc(K(o,mo(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new dc(n)),i.integrate(e,0);break;default:if(n instanceof is)i=new zc(K(o,mo(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Mc(n)),i.integrate(e,0);else throw Error(`Unexpected content type in insert operation`)}}}),u()},ps=()=>Hr(`Length exceeded!`),ms=(e,t,n,r)=>{if(n>t._length)throw ps();if(n===0)return t._searchMarker&&ns(t._searchMarker,n,r.length),fs(e,t,null,r);let i=n,a=ts(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&&yo(e,K(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&ns(t._searchMarker,i,r.length),fs(e,t,o,r)},hs=(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 fs(e,t,r,n)},gs=(e,t,n,r)=>{if(r===0)return;let i=n,a=r,o=ts(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&&yo(e,K(s.id.client,s.id.clock+n)),n-=s.length);for(;r>0&&s!==null;)s.deleted||(r<s.length&&yo(e,K(s.id.client,s.id.clock+r)),s.delete(e),r-=s.length),s=s.right;if(r>0)throw ps();t._searchMarker&&ns(t._searchMarker,i,-a+r)},_s=(e,t,n)=>{let r=t._map.get(n);r!==void 0&&r.delete(e)},vs=(e,t,n,r)=>{let i=t._map.get(n)||null,a=e.doc,o=a.clientID,s;if(r==null)s=new bc([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:s=new bc([r]);break;case Uint8Array:s=new oc(r);break;case Ca:s=new dc(r);break;default:if(r instanceof is)s=new Mc(r);else throw Error(`Unexpected content type`)}new zc(K(o,mo(a.store,o)),i,i&&i.lastId,null,null,t,n,s).integrate(e,0)},ys=(e,t)=>{e.doc??Yo();let n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},bs=e=>{let t={};return e.doc??Yo(),e._map.forEach((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])}),t},xs=(e,t)=>{e.doc??Yo();let n=e._map.get(t);return n!==void 0&&!n.deleted},Ss=(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&&so(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},Cs=e=>(e.doc??Yo(),oa(e._map.entries(),e=>!e[1].deleted));var ws=class extends qo{},Ts=class e extends is{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 is?e.clone():e)),t}get length(){return this.doc??Yo(),this._length}_callObserver(e,t){super._callObserver(e,t),rs(this,e,new ws(this,e))}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):q(this.doc,n=>{ms(n,this,e,t)})}push(e){this.doc===null?this._prelimContent.push(...e):q(this.doc,t=>{hs(t,this,e)})}unshift(e){this.insert(0,e)}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):q(this.doc,n=>{gs(n,this,e,t)})}get(e){return ds(this,e)}toArray(){return os(this)}slice(e=0,t=this.length){return as(this,e,t)}toJSON(){return this.map(e=>e instanceof is?e.toJSON():e)}map(e){return ls(this,e)}forEach(e){cs(this,e)}[Symbol.iterator](){return us(this)}_write(e){e.writeTypeRef(Tc)}};const Es=e=>new Ts;var Ds=class extends qo{constructor(e,t,n){super(e,t),this.keysChanged=n}},Os=class e extends is{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 is?e.clone():e)}),t}_callObserver(e,t){rs(this,e,new Ds(this,e,t))}toJSON(){this.doc??Yo();let e={};return this._map.forEach((t,n)=>{if(!t.deleted){let r=t.content.getContent()[t.length-1];e[n]=r instanceof is?r.toJSON():r}}),e}get size(){return[...Cs(this)].length}keys(){return sa(Cs(this),e=>e[0])}values(){return sa(Cs(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return sa(Cs(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??Yo(),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):q(this.doc,t=>{_s(t,this,e)})}set(e,t){return this.doc===null?this._prelimContent.set(e,t):q(this.doc,n=>{vs(n,this,e,t)}),t}get(e){return ys(this,e)}has(e){return xs(this,e)}clear(){this.doc===null?this._prelimContent.clear():q(this.doc,e=>{this.forEach(function(t,n,r){_s(e,r,n)})})}_write(e){e.writeTypeRef(Ec)}};const ks=e=>new Os,As=(e,t)=>e===t||typeof e==`object`&&typeof t==`object`&&e&&t&&Ti(e,t);var js=class{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){switch(this.right===null&&Wr(),this.right.content.constructor){case hc:this.right.deleted||Fs(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 Ms=(e,t,n)=>{for(;t.right!==null&&n>0;){switch(t.right.content.constructor){case hc:t.right.deleted||Fs(t.currentAttributes,t.right.content);break;default:t.right.deleted||(n<t.right.length&&yo(e,K(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},Ns=(e,t,n,r)=>{let i=new Map,a=r?ts(t,n):null;return a?Ms(e,new js(a.p.left,a.p,a.index,i),n-a.index):Ms(e,new js(null,t._start,0,i),n)},Ps=(e,t,n,r)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===hc&&As(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 zc(K(a,mo(i.store,a)),s,s&&s.lastId,c,c&&c.id,t,null,new hc(o,r));l.integrate(e,0),n.right=l,n.forward()})},Fs=(e,t)=>{let{key:n,value:r}=t;r===null?e.delete(n):e.set(n,r)},Is=(e,t)=>{for(;e.right!==null&&(e.right.deleted||e.right.content.constructor===hc&&As(t[e.right.content.key]??null,e.right.content.value));)e.forward()},Ls=(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(!As(l,c)){o.set(s,l);let{left:r,right:u}=n;n.right=new zc(K(a,mo(i.store,a)),r,r&&r.lastId,u,u&&u.id,t,null,new hc(s,c)),n.right.integrate(e,0),n.forward()}}return o},Rs=(e,t,n,r,i)=>{n.currentAttributes.forEach((e,t)=>{i[t]===void 0&&(i[t]=null)});let a=e.doc,o=a.clientID;Is(n,i);let s=Ls(e,t,n,i),c=r.constructor===String?new Sc(r):r instanceof is?new Mc(r):new pc(r),{left:l,right:u,index:d}=n;t._searchMarker&&ns(t._searchMarker,n.index,c.getLength()),u=new zc(K(o,mo(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(),Ps(e,t,n,s)},zs=(e,t,n,r,i)=>{let a=e.doc,o=a.clientID;Is(n,i);let s=Ls(e,t,n,i);iterationLoop:for(;n.right!==null&&(r>0||s.size>0&&(n.right.deleted||n.right.content.constructor===hc));){if(!n.right.deleted)switch(n.right.content.constructor){case hc:{let{key:t,value:a}=n.right.content,o=i[t];if(o!==void 0){if(As(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&&yo(e,K(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+=`
10
- `;n.right=new zc(K(o,mo(a.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Sc(i)),n.right.integrate(e,0),n.forward()}Ps(e,t,n,s)},Bs=(e,t,n,r,i)=>{let a=t,o=Vn();for(;a&&(!a.countable||a.deleted);){if(!a.deleted&&a.content.constructor===hc){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 hc:{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&&Fs(i,n);break}}}t=t.right}return s},Vs=(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===hc){let r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}},Hs=e=>{let t=0;return q(e.doc,n=>{let r=e._start,i=e._start,a=Vn(),o=Hn(a);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case hc:Fs(o,i.content);break;default:t+=Bs(n,r,i,a,o),a=Hn(o),r=i;break}i=i.right}}),t},Us=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&&So(e,n.store.clients.get(r),a,i,e=>{!e.deleted&&e.content.constructor===hc&&e.constructor!==ac&&t.add(e.parent)})}q(n,n=>{ua(e,e.deleteSet,e=>{if(e instanceof ac||!e.parent._hasFormatting||t.has(e.parent))return;let r=e.parent;e.content.constructor===hc?t.add(r):Vs(n,e)});for(let e of t)Hs(e)})},Ws=(e,t,n)=>{let r=n,i=Hn(t.currentAttributes),a=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case Mc:case pc:case Sc:n<t.right.length&&yo(e,K(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e);break}t.forward()}a&&Bs(e,a,t.right,i,t.currentAttributes);let o=(t.left||t.right).parent;return o._searchMarker&&ns(o._searchMarker,t.index,-r+n),t};var Gs=class extends qo{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=[];q(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},Si(o)||(e.attributes=vi({},o))),c=0;break}e&&t.push(e),a=null}};for(;i!==null;){switch(i.content.constructor){case Mc:case pc: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 Sc: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 hc:{let{key:t,value:s}=i.content;if(this.adds(i))this.deletes(i)||(As(n.get(t)??null,s)?s!==null&&i.delete(e):(a===`retain`&&u(),As(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;As(e,s)||(a===`retain`&&u(),o[t]=e)}else if(!i.deleted){r.set(t,s);let n=o[t];n!==void 0&&(As(n,s)?n!==null&&i.delete(e):(a===`retain`&&u(),s===null?delete o[t]:o[t]=s))}i.deleted||(a===`insert`&&u(),Fs(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}},Ks=class e extends is{constructor(e){super(),this._pending=e===void 0?[]:[()=>this.insert(0,e)],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Yo(),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 Gs(this,e,t);rs(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Yo();let e=``,t=this._start;for(;t!==null;)!t.deleted&&t.countable&&t.content.constructor===Sc&&(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)):q(this.doc,n=>{let r=new js(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)===`
11
- `?a.insert.slice(0,-1):a.insert;(typeof o!=`string`||o.length>0)&&Rs(n,this,r,o,a.attributes||{})}else a.retain===void 0?a.delete!==void 0&&Ws(n,r,a.delete):zs(n,this,r,a.retain,a.attributes||{})}})}toDelta(e,t,n){this.doc??Yo();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(so(s,e)||t!==void 0&&so(s,t))switch(s.content.constructor){case Sc:{let r=i.get(`ychange`);e!==void 0&&!so(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&&!so(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 Mc:case pc:{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 hc:so(s,e)&&(c(),Fs(i,s.content));break}s=s.right}c()};return e||t?q(a,n=>{e&&co(n,e),t&&co(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)):q(r,r=>{let i=Ns(r,this,e,!n);n||(n={},i.currentAttributes.forEach((e,t)=>{n[t]=e})),Rs(r,this,i,t,n)})}insertEmbed(e,t,n){let r=this.doc;r===null?this._pending.push(()=>this.insertEmbed(e,t,n||{})):q(r,r=>{let i=Ns(r,this,e,!n);Rs(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)):q(n,n=>{Ws(n,Ns(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)):q(r,r=>{let i=Ns(r,this,e,!1);i.right!==null&&zs(r,this,i,t,n)})}removeAttribute(e){this.doc===null?this._pending.push(()=>this.removeAttribute(e)):q(this.doc,t=>{_s(t,this,e)})}setAttribute(e,t){this.doc===null?this._pending.push(()=>this.setAttribute(e,t)):q(this.doc,n=>{vs(n,this,e,t)})}getAttribute(e){return ys(this,e)}getAttributes(){return bs(this)}_write(e){e.writeTypeRef(Dc)}};const qs=e=>new Ks;var Js=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Yo()}[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===Zs||t.constructor===Ys)&&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})}},Ys=class e extends is{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 is?e.clone():e)),t}get length(){return this.doc??Yo(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new Js(this,e)}querySelector(e){e=e.toUpperCase();let t=new Js(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),Jn(new Js(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){rs(this,e,new $s(this,t,e))}toString(){return ls(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),cs(this,i=>{r.insertBefore(i.toDOM(e,t,n),null)}),r}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):q(this.doc,n=>{ms(n,this,e,t)})}insertAfter(e,t){if(this.doc!==null)q(this.doc,n=>{let r=e&&e instanceof is?e._item:e;fs(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 Hr(`Reference item not found`);n.splice(r,0,...t)}}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):q(this.doc,n=>{gs(n,this,e,t)})}toArray(){return os(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return ds(this,e)}slice(e=0,t=this.length){return as(this,e,t)}forEach(e){cs(this,e)}_write(e){e.writeTypeRef(kc)}};const Xs=e=>new Ys;var Zs=class e extends Ys{constructor(e=`UNDEFINED`){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((e,t)=>{this.setAttribute(t,e)}),this._prelimAttrs=null}_copy(){return new e(this.nodeName)}clone(){let t=new e(this.nodeName);return bi(this.getAttributes(),(e,n)=>{t.setAttribute(n,e)}),t.insert(0,this.toArray().map(e=>e instanceof is?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):q(this.doc,t=>{_s(t,this,e)})}setAttribute(e,t){this.doc===null?this._prelimAttrs.set(e,t):q(this.doc,n=>{vs(n,this,e,t)})}getAttribute(e){return ys(this,e)}hasAttribute(e){return xs(this,e)}getAttributes(e){return e?Ss(this,e):bs(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 cs(this,i=>{r.appendChild(i.toDOM(e,t,n))}),n!==void 0&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(Oc),e.writeKey(this.nodeName)}};const Qs=e=>new Zs(e.readKey());var $s=class extends qo{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)})}},ec=class e extends Os{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(Ac),e.writeKey(this.hookName)}};const tc=e=>new ec(e.readKey());var nc=class e extends Ks{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(jc)}};const rc=e=>new nc;var ic=class{constructor(e,t){this.id=e,this.length=t}get deleted(){throw Ur()}mergeWith(e){return!1}write(e,t,n){throw Ur()}integrate(e,t){throw Ur()}},ac=class extends ic{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),ho(e.doc.store,this)}write(e,t){e.writeInfo(0),e.writeLen(this.length-t)}getMissing(e,t){return null}},oc=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 Ur()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}};const sc=e=>new oc(e.readBuf());var cc=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){ha(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 lc=e=>new cc(e.readLen()),uc=(e,t)=>new Ca({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});var dc=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(uc(this.doc.guid,this.opts))}splice(e){throw Ur()}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 fc=e=>new dc(uc(e.readString(),e.readAny()));var pc=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 Ur()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}};const mc=e=>new pc(e.readJSON());var hc=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 Ur()}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 gc=e=>new hc(e.readKey(),e.readJSON());var _c=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 vc=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 _c(n)},yc=Li(`node_env`)===`development`;var bc=class e{constructor(e){this.arr=e,yc&&Di(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 xc=e=>{let t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new bc(n)};var Sc=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 Cc=e=>new Sc(e.readString()),wc=[Es,ks,qs,Qs,Xs,tc,rc],Tc=0,Ec=1,Dc=2,Oc=3,kc=4,Ac=5,jc=6;var Mc=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 Ur()}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 Nc=e=>new Mc(wc[e.readTypeRef()](e)),Pc=(e,t)=>{let n=t,r=0,i;do r>0&&(n=K(n.client,n.clock+r)),i=_o(e,n),r=n.clock-i.id.clock,n=i.redone;while(n!==null&&i instanceof zc);return{item:i,diff:r}},Fc=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},Ic=(e,t,n)=>{let{client:r,clock:i}=t.id,a=new zc(K(r,i+n),t,K(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=K(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},Lc=(e,t)=>Yn(e,e=>fa(e.deletions,t)),Rc=(e,t,n,r,i,a)=>{let o=e.doc,s=o.store,c=o.clientID,l=t.redone;if(l!==null)return yo(e,l);let u=t.parent._item,d=null,f;if(u!==null&&u.deleted===!0){if(u.redone===null&&(!n.has(u)||Rc(e,u,n,r,i,a)===null))return null;for(;u.redone!==null;)u=yo(e,u.redone)}let p=u===null?t.parent:u.content.type;if(t.parentSub===null){for(d=t.left,f=t;d!==null;){let t=d;for(;t!==null&&t.parent._item!==u;)t=t.redone===null?null:yo(e,t.redone);if(t!==null&&t.parent._item===u){d=t;break}d=d.left}for(;f!==null;){let t=f;for(;t!==null&&t.parent._item!==u;)t=t.redone===null?null:yo(e,t.redone);if(t!==null&&t.parent._item===u){f=t;break}f=f.right}}else if(f=null,t.right&&!i){for(d=t;d!==null&&d.right!==null&&(d.right.redone||fa(r,d.right.id)||Lc(a.undoStack,d.right.id)||Lc(a.redoStack,d.right.id));)for(d=d.right;d.redone;)d=yo(e,d.redone);if(d&&d.right!==null)return null}else d=p._map.get(t.parentSub)||null;let m=K(c,mo(s,c)),h=new zc(m,d,d&&d.lastId,f,f&&f.id,p,t.parentSub,t.content.copy());return t.redone=m,Fc(h,!0),h.integrate(e,0),h};var zc=class e extends ic{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>=mo(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=mo(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===eo&&this.id.client!==this.parent.client&&this.parent.clock>=mo(n,this.parent.client))return this.parent.client;if(this.origin&&=(this.left=bo(t,n,this.origin),this.left.lastId),this.rightOrigin&&=(this.right=yo(t,this.rightOrigin),this.right.id),this.left&&this.left.constructor===ac||this.right&&this.right.constructor===ac)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===eo){let e=_o(n,this.parent);e.constructor===ac?this.parent=null:this.parent=e.content.type}return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=bo(e,e.doc.store,K(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),to(this.origin,n.origin)){if(n.id.client<this.id.client)t=n,r.clear();else if(to(this.rightOrigin,n.rightOrigin))break}else if(n.origin!==null&&i.has(_o(e.doc.store,n.origin)))r.has(_o(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),ho(e.doc.store,this),this.content.integrate(e,this),To(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new ac(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:K(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&to(e.origin,this.lastId)&&this.right===e&&to(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(),ha(e.deleteSet,this.id.client,this.id.clock,this.length),To(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw Wr();this.content.gc(e),t?xo(e,this,new ac(this.id,this.length)):this.content=new cc(this.length)}write(e,t){let n=t>0?K(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=no(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===eo?(e.writeParentInfo(!1),e.writeLeftID(t)):Wr();i!==null&&e.writeString(i)}this.content.write(e,t)}};const Bc=(e,t)=>Vc[t&31](e),Vc=[()=>{Wr()},lc,vc,sc,Cc,mc,gc,Nc,xc,fc,()=>{Wr()}];var Hc=class extends ic{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor?(this.length+=e.length,!0):!1}integrate(e,t){Wr()}write(e,t){e.writeInfo(10),W(e.restEncoder,this.length-t)}getMissing(e,t){return null}};const Uc=typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:{},Wc=`__ $YJS$ __`;Uc[Wc]===!0&&console.error(`Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438`),Uc[Wc]=!0;const Gc=/[\uD800-\uDBFF]/,Kc=/[\uDC00-\uDFFF]/,qc=(e,t)=>{let n=0,r=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n++;for(n>0&&Gc.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&&Kc.test(e[e.length-r])&&r--,{index:n,remove:e.length-n-r,insert:t.slice(n,t.length-r)}},Jc=e=>{let t=ke(`sha256`);return t.update(e),t.digest()},Yc=new j(`y-sync`);new j(`y-undo`),new j(`yjs-cursor`);const Xc=e=>{for(let t=6;t<e.length;t++)e[t%6]=e[t%6]^e[t];return e.slice(0,6)},Zc=e=>Vi(Xc(Jc(Ui(e)))),Qc=()=>({mapping:new Map,isOMark:new Map}),$c=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&t.sv.get(e.id.client)>e.id.clock&&!fa(t.ds,e.id),el=(e,t,n,r,i,a)=>{let o=n.mapping.get(e);if(o===void 0){if(e instanceof Zs)return tl(e,t,n,r,i,a);throw Ur()}return o},tl=(e,t,n,r,i,a)=>{let o=[],s=e=>{if(e instanceof Zs){let s=el(e,t,n,r,i,a);s!==null&&o.push(s)}else{let s=e._item.right?.content?.type;s instanceof Ks&&!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=nl(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):ss(e,new io(i.ds,r.sv)).forEach(s);try{let s=e.getAttributes(r);r!==void 0&&($c(e._item,r)?$c(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}},nl=(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,_l(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},rl=(e,t)=>{let n=new nc,r=e.map(e=>({insert:e.text,attributes:vl(e.marks,t)}));return n.applyDelta(r),t.mapping.set(n,e),n},il=(e,t)=>{let n=new Zs(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,cl(e).map(e=>al(e,t))),t.mapping.set(n,e),n},al=(e,t)=>e instanceof Array?rl(e,t):il(e,t),ol=e=>typeof e==`object`&&!!e,sl=(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||ol(o)&&ol(s)&&sl(o,s)}return r},cl=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},ll=(e,t)=>{let n=e.toDelta();return n.length===t.length&&n.every((e,n)=>e.insert===t[n].text&&yi(e.attributes||{}).length===t[n].marks.length&&Ci(e.attributes,(e,r)=>{let i=gl(r),a=t[n].marks;return a.find(e=>e.type.name===i)?sl(e,a.find(e=>e.type.name===i)?.attrs):!1}))},ul=(e,t)=>{if(e instanceof Zs&&!(t instanceof Array)&&bl(e,t)){let n=cl(t);return e._length===n.length&&sl(e.getAttributes(),t.attrs)&&e.toArray().every((e,t)=>ul(e,n[t]))}return e instanceof nc&&t instanceof Array&&ll(e,t)},dl=(e,t)=>e===t||e instanceof Array&&t instanceof Array&&e.length===t.length&&e.every((e,n)=>t[n]===e),fl=(e,t,n)=>{let r=e.toArray(),i=cl(t),a=i.length,o=r.length,s=er(o,a),c=0,l=0,u=!1;for(;c<s;c++){let e=r[c],t=i[c];if(dl(n.mapping.get(e),t))u=!0;else if(!ul(e,t))break}for(;c+l<s;l++){let e=r[o-l-1],t=i[a-l-1];if(dl(n.mapping.get(e),t))u=!0;else if(!ul(e,t))break}return{equalityFactor:c+l,foundMappedChild:u}},pl=e=>{let t=``,n=e._start,r={};for(;n!==null;)n.deleted||(n.countable&&n.content instanceof Sc?t+=n.content.str:n.content instanceof hc&&(r[n.content.key]=null)),n=n.right;return{str:t,nAttrs:r}},ml=(e,t,n)=>{n.mapping.set(e,t);let{nAttrs:r,str:i}=pl(e),a=t.map(e=>({insert:e.text,attributes:Object.assign({},r,vl(e.marks,n))})),{insert:o,remove:s,index:c}=qc(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})))},hl=/(.*)(--[a-zA-Z0-9+/=]{8})$/,gl=e=>hl.exec(e)?.[1]??e,_l=(e,t)=>{let n=[];for(let r in e)n.push(t.mark(gl(r),e[r]));return n},vl=(e,t)=>{let n={};return e.forEach(e=>{if(e.type.name!==`ychange`){let r=Un(t.isOMark,e.type,()=>!e.type.excludes(e.type));n[r?`${e.type.name}--${Zc(e.toJSON())}`:e.type.name]=e.attrs}}),n},yl=(e,t,n,r)=>{if(t instanceof Zs&&t.nodeName!==n.type.name)throw Error(`node name mismatch!`);if(r.mapping.set(t,n),t instanceof Zs){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=cl(n),a=i.length,o=t.toArray(),s=o.length,c=er(a,s),l=0,u=0;for(;l<c;l++){let e=o[l],t=i[l];if(!dl(r.mapping.get(e),t))if(ul(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(!dl(r.mapping.get(e),t))if(ul(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 nc&&c instanceof Array)ll(n,c)||ml(n,c,r),l+=1;else{let i=n instanceof Zs&&bl(n,c),a=d instanceof Zs&&bl(d,f);if(i&&a){let e=fl(n,c,r),t=fl(d,f,r);e.foundMappedChild&&!t.foundMappedChild?a=!1:!e.foundMappedChild&&t.foundMappedChild||e.equalityFactor<t.equalityFactor?i=!1:a=!1}i?(yl(e,n,c,r),l+=1):a?(yl(e,d,f,r),u+=1):(r.mapping.delete(t.get(l)),t.delete(l,1),t.insert(l,[al(c,r)]),l+=1)}}let n=s-l-u;if(s===1&&a===0&&o[0]instanceof nc?(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(al(i[t],r));t.insert(l,e)}},Yc)},bl=(e,t)=>!(t instanceof Array)&&e.nodeName===t.type.name,xl=(e,t)=>{let n=e.toArray().map(e=>tl(e,t,Qc())).filter(e=>e!==null);return u.fromArray(n)},Sl=(e,t)=>t.topNodeType.create(null,xl(e,t));function J(e){return e===b}var Cl=class{hocuspocus;seqs=new Map;timers=new Map;log=ln(`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(b);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found — broadcasts will be dropped until it is materialized`),!0),Tn();return}let n=(this.seqs.get(e)??0)+1;this.seqs.set(e,n);let r={v:1,ch:e,seq:n};t.broadcastStateless(JSON.stringify(r)),wn(),Ln(e,n),En(t.getConnectionsCount())}catch(t){this.log.error({err:t,channel:e},`[cc1] broadcast failed`)}}get subscriberCount(){let e=this.hocuspocus.documents.get(b);return e?e.getConnectionsCount():0}destroy(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};const wl=new d({extensions:N}),Tl=i(N),El=ln(`agent-sessions`);function Dl(e,t,n){try{let r=e.getXmlFragment(`default`),i=e.getText(`source`),a=e.getMap(`metadata`),o=Sl(r,Tl).toJSON(),s=wl.serialize(o),c=a.get(`frontmatter`)??``,{frontmatter:u,body:d}=l(t),f,p;switch(n){case`replace`:f=u||c,p=d.trim();break;case`prepend`:f=c,p=`${d.trim()}\n\n${s}`;break;case`append`:f=c,p=s.trim()?`${s}\n\n${d.trim()}\n`:`${d.trim()}\n`;break}let m=wl.parseWithFallback(p);yl(e,r,Tl.nodeFromJSON(m),{mapping:new Map,isOMark:new Map}),f!==c&&a.set(`frontmatter`,f);let h=wl.serialize(Sl(r,Tl).toJSON()),g=M(f,h);T(i,i.toString(),g)}catch(r){throw El.error({err:r,docName:e.name,position:n,markdownLen:t.length},`[applyAgentMarkdownWrite] failed for '${e.name}'`),r}}function Ol(e,t){let{dc:n,um:r,undoOrigin:i}=e,a=n.document,o=a.getXmlFragment(`default`),s=a.getText(`source`),c=a.getMap(`metadata`),u=!1;return a.transact(()=>{if(t===`last`){if(r.undoStack.length===0)return;r.undo(),u=!0}else for(;r.undoStack.length>0;)r.undo(),u=!0;let{body:e,frontmatter:n}=l(s.toString()),i=wl.parseWithFallback(e);yl(a,o,Tl.nodeFromJSON(i),{mapping:new Map,isOMark:new Map});let d=c.get(`frontmatter`)??``,f=n||d;n&&n!==d&&c.set(`frontmatter`,f);let p=M(f,wl.serialize(Sl(o,Tl).toJSON()));T(s,s.toString(),p)},i),u}function kl(e,t,n){let r={origin:`agent-write`,paired:!0,session_id:e};t!==void 0&&(r.agent_type=t),n!==void 0&&(r.principal=n),Object.freeze(r);let i={source:`local`,skipStoreHooks:!1,context:r};return Object.freeze(i),i}function Al(e,t){let n={origin:`agent-undo`,paired:!0,session_id:e};t!==void 0&&(n.agent_type=t),Object.freeze(n);let r={source:`local`,skipStoreHooks:!1,context:n};return Object.freeze(r),r}var jl=class{sessions=new Map;pendingSessions=new Map;hocuspocus;constructor(e){this.hocuspocus=e}sessionKey(e,t){return`${e}\0${t}`}async getSession(e,t=`claude-1`,n){if(J(e))throw Error(`Cannot create agent session for reserved doc: ${e}`);let r=this.sessionKey(e,t),i=this.sessions.get(r);if(i)return i;let a=this.pendingSessions.get(r);if(a)return a;let o=this._createSession(e,t,n);this.pendingSessions.set(r,o);try{let e=await o;return this.sessions.set(r,e),e}finally{this.pendingSessions.delete(r)}}async _createSession(e,t,n){let r=n?.clientName,i=t.startsWith(`agent-`)?t.slice(6):t,a=kl(i,r,n?.principalId),o=Al(i,r),s={session_id:i,...r===void 0?{}:{agent_type:r},...n?.clientName===void 0?{}:{client_name:n.clientName},...n?.principalId===void 0?{}:{principalId:n.principalId}},c=await this.hocuspocus.openDirectConnection(e,s),l=new No([c.document.getText(`source`),c.document.getMap(`metadata`),c.document.getMap(`agent-flash`)],{trackedOrigins:new Set([a]),captureTimeout:500,captureTransaction:e=>e.origin!==o,ignoreRemoteMapChanges:!0});return El.info({docName:e,agentId:t},`[agent-session] Created session for: ${e} / ${t}`),{dc:c,origin:a,undoOrigin:o,um:l,agentId:t,docName:e}}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.um.destroy(),await r.dc.disconnect(),this.sessions.delete(n),El.info({docName:e,agentId:t},`[agent-session] Closed session for: ${e} / ${t}`))}async closeAllForAgent(e){let t=`\0${e}`,n=[...this.pendingSessions.keys()].filter(e=>e.endsWith(t));n.length>0&&await Promise.allSettled(n.map(e=>this.pendingSessions.get(e)));let r=[...this.sessions.keys()].filter(e=>e.endsWith(t));for(let t of r){let n=this.sessions.get(t);if(n)try{n.um.destroy(),await n.dc.disconnect(),this.sessions.delete(t)}catch(t){El.error({err:t,agentId:e},`[agent-session] Failed to close session for agent ${e}`)}}}async closeAllForDoc(e){let t=`${e}\0`,n=[...this.sessions.keys()].filter(e=>e.startsWith(t));for(let t of n){let n=this.sessions.get(t);if(n)try{n.um.destroy(),await n.dc.disconnect(),this.sessions.delete(t)}catch(t){El.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.um.destroy(),await t.dc.disconnect(),this.sessions.delete(e)}catch(t){El.error({err:t,key:e},`[agent-session] Failed to close session: ${e}`)}}}};const Ml=/^(agent-[^/]+|principal-[^/]+|file-system|git-upstream|openknowledge-service)$/;function Nl(e){return H(e,`.git/open-knowledge`)}function Pl(e){let t=Nl(e);return R(H(t,`HEAD`))?t:null}function Fl(e){return`refs/wip/${e}/`}function Il(e){if(!e)return[];let t=[];for(let n of e.split(`
12
- `)){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 Ll=`ok-checkpoint-v1: `;function Rl(e){if(!e)return null;for(let t of e.split(`
13
- `)){let e=t.trim();if(!e.startsWith(Ll))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 zl(e){let t={kind:e.kind,metadata:e.metadata};return e.docName!==null&&(t.docName=e.docName),e.size!==null&&(t.size=e.size),`${Ll}${JSON.stringify(t)}`}function Bl(e){return`ok-actor: ${JSON.stringify(e)}`}function Vl(e){return e.length===0?`wip: auto-save`:e.length===1?`wip: ${e[0]}`:`wip: ${e.length} docs`}function Hl(e){return`reconcile: ${e}`}function Ul(e,t){return`rollback: ${e} to ${t.slice(0,7)}`}function Wl(e,t){return`park: ${e} -> ${t}`}function Gl(e,t){return`rename: ${e} -> ${t}`}function Kl(e){return`checkpoint: ${e}`}function ql(e,t){return e?`import: from ${e.slice(0,8)}..${t.slice(0,8)}`:`import: initial at ${t.slice(0,8)}`}function Jl(e){return Ml.test(e)?e.startsWith(`agent-`)?{id:e,classification:`agent`,isAgent:!0}:e.startsWith(`principal-`)?{id:e,classification:`principal`,isAgent:!1}:e===`file-system`?{id:e,classification:`classified-file-system`,isAgent:null}:e===`git-upstream`?{id:e,classification:`classified-git-upstream`,isAgent:null}:e===`openknowledge-service`?{id:e,classification:`classified-openknowledge-service`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}}var Yl=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}})),Xl=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})),Zl=n(((e,n)=>{let{Readable:r,Writable:i}=t(`stream`),a=Xl(),{basename:o,convertToUTF8:s,getDecoder:c,parseContentType:l,parseDisposition:u}=Yl(),d=Buffer.from(`\r
14
- `),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,N=0,P,ee,te,ne,re=!1,F=!1,ie=!1;this._hparser=null;let ae=new g(e=>{this._hparser=null,A=!1,te=`text/plain`,P=i,ee=`7bit`,ne=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&&(ne=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&&(te=`${t.type}/${t.subtype}`,t.params&&typeof t.params.charset==`string`&&(P=t.params.charset.toLowerCase()))}if(e[`content-transfer-encoding`]&&(ee=e[`content-transfer-encoding`][0].toLowerCase()),te===`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`,ne,this._fileStream,{filename:t,encoding:ee,mimeType:te})}else{if(O===T){ie||(ie=!0,this.emit(`fieldsLimit`)),A=!0;return}if(++O,this.listenerCount(`field`)===0){A=!0;return}M=[],N=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-N);i?e=t.slice(n,n+a):(e=Buffer.allocUnsafe(a),t.copy(e,0,n,n+a)),N+=a,M.push(e),N===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],P,0);break;default:e=s(Buffer.concat(M,N),P,0)}M=void 0,N=0,this.emit(`field`,ne,e,{nameTruncated:!1,valueTruncated:re,encoding:ee,mimeType:te})}++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})),Ql=n(((e,n)=>{let{Writable:r}=t(`stream`),{getDecoder:i}=Yl();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})),$l=n(((e,t)=>{let{parseContentType:n}=Yl();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=[Zl(),Ql()].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)}})),eu=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 eu{};function tu(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 nu(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 ru(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 iu(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 au(e,t){return ru(e,t,``)}function ou(e,t){return iu(e,t,``)}function su(e,t){return t.slice(0,cu(e,t))}function cu(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 lu(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 uu(e,t){if(t)return fu(e,t)[1];let n;for(n=e.length-1;n>=0&&e[n].match(/\s/);n--);return e.substring(n+1)}function du(e,t){if(t)return fu(e,t)[0];let n=e.match(/^\s*/);return n?n[0]:``}function fu(e,t){if(!t)return[du(e),uu(e)];if(t.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);let n=lu(e,t),r=n[0],i=n[n.length-1];return[/\s/.test(r)?r:``,/\s/.test(i)?i:``]}const pu=`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}`,mu=RegExp(`[${pu}]+|\\s+|[^${pu}]`,`ug`);new class extends eu{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=lu(e,r)}else n=e.match(mu)||[];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)&&hu(n,i,r,e,t.intlSegmenter),n=e,r=null,i=null)}),(r||i)&&hu(n,i,r,null,t.intlSegmenter),e}};function hu(e,t,n,r,i){if(t&&n){let[a,o]=fu(t.value,i),[s,c]=fu(n.value,i);if(e){let r=tu(a,s);e.value=iu(e.value,s,r),t.value=au(t.value,r),n.value=au(n.value,r)}if(r){let e=nu(o,c);r.value=ru(r.value,c,e),t.value=ou(t.value,e),n.value=ou(n.value,e)}}else if(n){if(e){let e=du(n.value,i);n.value=n.value.substring(e.length)}if(r){let e=du(r.value,i);r.value=r.value.substring(e.length)}}else if(e&&r){let n=du(r.value,i),[a,o]=fu(t.value,i),s=tu(n,a);t.value=au(t.value,s);let c=nu(au(n,s),o);t.value=ou(t.value,c),r.value=ru(r.value,n,c),e.value=iu(e.value,n,n.slice(0,n.length-c.length))}else if(r){let e=du(r.value,i),n=su(uu(t.value,i),e);t.value=ou(t.value,n)}else if(e){let n=su(uu(e.value,i),du(t.value,i));t.value=au(t.value,n)}}new class extends eu{tokenize(e){let t=RegExp(`(\\r?\\n)|[${pu}]+|[^\\S\\n\\r]+|[^${pu}]`,`ug`);return e.match(t)||[]}};const gu=new class extends eu{constructor(){super(...arguments),this.tokenize=vu}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
9
+ `)}),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})),rn=e(_t(),1),an=e(nn(),1);function on(){return process.env.NO_COLOR&&process.env.NO_COLOR!==``?!1:process.stdout.isTTY??!1}var sn=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:rn.default.stdSerializers.err,error:rn.default.stdSerializers.err},...t.options},t.transportConfigs&&(this.transportConfigs=t.transportConfigs),this.pinoInstance=this.buildInstance()}buildInstance(){if(this.transportConfigs.length>0)return(0,rn.default)(this.options,rn.default.transport({targets:this.transportConfigs}));try{let e=(0,an.default)({colorize:on(),translateTime:`HH:MM:ss`,ignore:`pid,hostname`});return(0,rn.default)(this.options,e)}catch(e){return console.warn(`[PinoLogger] pino-pretty failed, falling back to JSON:`,e),(0,rn.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 cn=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 sn(e,this.config.pinoConfig),this.loggers.set(e,n),n}reset(){this.config={},this.loggers.clear()}};function ln(e){return cn.getLogger(e)}var un=class{hocuspocus;log=ln(`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(b);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),dn(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function dn(e){return e?.awareness??null}const fn=/^[a-zA-Z0-9_-]+$/;function pn(e){return typeof e!=`string`||e.length===0||!fn.test(e)?null:e}function mn(e){return`agent-${e}`}const U={reconcileCount:0,conflictCount:0,batchCount:0,upstreamImportCount:0,rescueBufferCount:0,branchSwitchCount:0,parkCount:0,gitAutoSaveFailureCount:0,gitWriterCommitFailureCount: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,shadowMigrationLegacyRefsDeleted:0,effectDiffCaptureFailures:0,agentPresenceMutationErrors:0,agentWriteCalls:0,summariesProvided:0,summariesTruncated:0};function hn(){U.reconcileCount++}function gn(){U.conflictCount++}function _n(){U.batchCount++}function vn(){U.upstreamImportCount++}function yn(){U.rescueBufferCount++}function bn(){U.branchSwitchCount++}function xn(){U.parkCount++}function Sn(){U.gitAutoSaveFailureCount++}function Cn(){U.gitWriterCommitFailureCount++}function wn(){U.cc1BroadcastCount++}function Tn(){U.cc1BroadcastDropCount++}function En(e){U.cc1SubscriberCount=e}function Dn(e){e===`a`?U.serverObserverFiresA++:U.serverObserverFiresB++}function On(){U.persistenceDiskWrites++}function kn(e){e===`a`?U.serverObserverErrorsA++:U.serverObserverErrorsB++}function An(){U.bridgeMergeContentLoss++}function jn(){U.agentWriteCalls++}function Mn(){U.summariesProvided++}function Nn(){U.summariesTruncated++}function Pn(){U.bridgeMergeCheckpointCreated++}function Fn(e){e===`EPIPE`?U.collabSocketEpipeCount++:U.collabSocketEconnresetCount++}function In(e){U.shadowMigrationLegacyRefsDeleted+=e}function Ln(){U.effectDiffCaptureFailures++}function Rn(){U.agentPresenceMutationErrors++}function zn(e){return e.code===`EPIPE`||e.code===`ECONNRESET`?(Fn(e.code),!0):!1}function Bn(e,t){U.cc1LastSeq[e]=t}function Vn(){return{...U,cc1LastSeq:{...U.cc1LastSeq}}}var Hn=class{hocuspocus;log=ln(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){let n=0;this.mutateAgentPresence(r=>{let i=Date.now(),a={};for(let[t,o]of Object.entries(r)){if(i-o.ts>=2e4&&t!==e){n++;continue}a[t]=o}return a[e]=t,a})&&(this.log.debug({agentId:e,action:`set`,currentDoc:t.currentDoc,ts:t.ts},`[agent-presence] set`),n>0&&this.log.info({evictedCount:n,thresholdMs:2e4},`[agent-presence] evicted stale entries`))}clearPresence(e){let t=!1;this.mutateAgentPresence(n=>{if(!n[e])return n;t=!0;let{[e]:r,...i}=n;return i})&&t&&this.log.info({agentId:e,action:`clear`,currentDoc:null,ts:Date.now()},`[agent-presence] clear`)}touchMode(e,t){let n=[],r=!1,i=this.mutateAgentPresence(i=>{let a=i[e];if(!a)return i;r=!0;let o=Date.now();return n.push({currentDoc:a.currentDoc,ts:o}),{...i,[e]:{...a,mode:t,ts:o}}}),a=n[0];i&&a?this.log.debug({agentId:e,action:`touchMode`,currentDoc:a.currentDoc,ts:a.ts,mode:t},`[agent-presence] touchMode`):r||this.log.debug({agentId:e,action:`touchMode`,mode:t,reason:`entry-missing`},`[agent-presence] touchMode skipped — no entry for agentId`)}bumpPresenceTs(e){let t=null;this.mutateAgentPresence(n=>{let r=n[e];if(!r)return n;let i=Date.now();return t=i,{...n,[e]:{...r,ts:i}}}),t!==null&&this.log.debug({agentId:e,action:`bumpTs`,ts:t},`[agent-presence] bumpTs`)}getPresenceMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentPresence??{}:{}}destroy(){this.destroyed=!0}mutateAgentPresence(e){if(this.destroyed)return!1;let t=this.resolveAwareness();if(!t)return!1;try{let n=t.getLocalState()??{},r=e(n.agentPresence??{});return t.setLocalState({...n,agentPresence:r}),!0}catch(e){return Rn(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(b);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),Un(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function Un(e){return e?.awareness??null}const Wn=()=>new Map,Gn=e=>{let t=Wn();return e.forEach((e,n)=>{t.set(n,e)}),t},Kn=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r},qn=(e,t)=>{for(let[n,r]of e)if(t(r,n))return!0;return!1},Jn=()=>new Set,Yn=e=>e[e.length-1],Xn=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},Zn=Array.from,Qn=(e,t)=>{for(let n=0;n<e.length;n++)if(t(e[n],n,e))return!0;return!1},$n=Array.isArray;var er=class{constructor(){this._observers=Wn()}on(e,t){return Kn(this._observers,e,Jn).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 Zn((this._observers.get(e)||Wn()).values()).forEach(e=>e(...t))}destroy(){this._observers=Wn()}};const tr=Math.floor,nr=Math.abs,rr=(e,t)=>e<t?e:t,ir=(e,t)=>e>t?e:t;Number.isNaN;const ar=e=>e===0?1/e<0:e<0,or=2**53-1,sr=Number.isInteger||(e=>typeof e==`number`&&isFinite(e)&&tr(e)===e);Number.isNaN,Number.parseInt;const cr=String.fromCharCode;String.fromCodePoint,cr(65535);const lr=e=>e.toLowerCase(),ur=/^\s*/g,dr=e=>e.replace(ur,``),fr=/([A-Z])/g,pr=(e,t)=>dr(e.replace(fr,e=>`${t}${lr(e)}`)),mr=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},hr=typeof TextEncoder<`u`?new TextEncoder:null,gr=hr?e=>hr.encode(e):mr;let _r=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});_r&&_r.decode(new Uint8Array).length===1&&(_r=null);var vr=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const yr=()=>new vr,br=e=>{let t=yr();return e(t),Sr(t)},xr=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},Sr=e=>{let t=new Uint8Array(xr(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},Cr=(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(ir(n,t)*2),e.cpos=0)},wr=(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},Tr=wr,W=(e,t)=>{for(;t>127;)wr(e,128|127&t),t=tr(t/128);wr(e,127&t)},Er=(e,t)=>{let n=ar(t);for(n&&(t=-t),wr(e,(t>63?128:0)|(n?64:0)|63&t),t=tr(t/64);t>0;)wr(e,(t>127?128:0)|127&t),t=tr(t/128)},Dr=new Uint8Array(3e4),Or=Dr.length/3,kr=hr&&hr.encodeInto?(e,t)=>{if(t.length<Or){let n=hr.encodeInto(t,Dr).written||0;W(e,n);for(let t=0;t<n;t++)wr(e,Dr[t])}else jr(e,gr(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;W(e,r);for(let t=0;t<r;t++)wr(e,n.codePointAt(t))},Ar=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=rr(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(ir(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},jr=(e,t)=>{W(e,t.byteLength),Ar(e,t)},Mr=(e,t)=>{Cr(e,t);let n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},Nr=(e,t)=>Mr(e,4).setFloat32(0,t,!1),Pr=(e,t)=>Mr(e,8).setFloat64(0,t,!1),Fr=(e,t)=>Mr(e,8).setBigInt64(0,t,!1),Ir=new DataView(new ArrayBuffer(4)),Lr=e=>(Ir.setFloat32(0,e),Ir.getFloat32(0)===e),Rr=(e,t)=>{switch(typeof t){case`string`:wr(e,119),kr(e,t);break;case`number`:sr(t)&&nr(t)<=2147483647?(wr(e,125),Er(e,t)):Lr(t)?(wr(e,124),Nr(e,t)):(wr(e,123),Pr(e,t));break;case`bigint`:wr(e,122),Fr(e,t);break;case`object`:if(t===null)wr(e,126);else if($n(t)){wr(e,117),W(e,t.length);for(let n=0;n<t.length;n++)Rr(e,t[n])}else if(t instanceof Uint8Array)wr(e,116),jr(e,t);else{wr(e,118);let n=Object.keys(t);W(e,n.length);for(let r=0;r<n.length;r++){let i=n[r];kr(e,i),Rr(e,t[i])}}break;case`boolean`:wr(e,t?120:121);break;default:wr(e,127)}};var zr=class extends vr{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&W(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}};const Br=e=>{e.count>0&&(Er(e.encoder,e.count===1?e.s:-e.s),e.count>1&&W(e.encoder,e.count-2))};var Vr=class{constructor(){this.encoder=new vr,this.s=0,this.count=0}write(e){this.s===e?this.count++:(Br(this),this.count=1,this.s=e)}toUint8Array(){return Br(this),Sr(this.encoder)}};const Hr=e=>{if(e.count>0){let t=e.diff*2+(e.count===1?0:1);Er(e.encoder,t),e.count>1&&W(e.encoder,e.count-2)}};var Ur=class{constructor(){this.encoder=new vr,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(Hr(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return Hr(this),Sr(this.encoder)}},Wr=class{constructor(){this.sarr=[],this.s=``,this.lensE=new Vr}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 vr;return this.sarr.push(this.s),this.s=``,kr(e,this.sarr.join(``)),Ar(e,this.lensE.toUint8Array()),Sr(e)}};const Gr=e=>Error(e),Kr=()=>{throw Gr(`Method unimplemented`)},qr=()=>{throw Gr(`Unexpected case`)},Jr=Gr(`Unexpected end of array`),Yr=Gr(`Integer out of Range`);var Xr=class{constructor(e){this.arr=e,this.pos=0}};const Zr=e=>new Xr(e),Qr=e=>e.pos!==e.arr.length,$r=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},ei=e=>$r(e,G(e)),ti=e=>e.arr[e.pos++],G=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>or)throw Yr}throw Jr},ni=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>or)throw Yr}throw Jr},ri=_r?e=>_r.decode(ei(e)):e=>{let t=G(e);if(t===0)return``;{let n=String.fromCodePoint(ti(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(ti(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))}},ii=(e,t)=>{let n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},ai=[e=>void 0,e=>null,ni,e=>ii(e,4).getFloat32(0,!1),e=>ii(e,8).getFloat64(0,!1),e=>ii(e,8).getBigInt64(0,!1),e=>!1,e=>!0,ri,e=>{let t=G(e),n={};for(let r=0;r<t;r++){let t=ri(e);n[t]=oi(e)}return n},e=>{let t=G(e),n=[];for(let r=0;r<t;r++)n.push(oi(e));return n},ei],oi=e=>ai[127-ti(e)](e);var si=class extends Xr{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Qr(this)?this.count=G(this)+1:this.count=-1),this.count--,this.s}},ci=class extends Xr{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=ni(this);let e=ar(this.s);this.count=1,e&&(this.s=-this.s,this.count=G(this)+2)}return this.count--,this.s}},li=class extends Xr{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){let e=ni(this),t=e&1;this.diff=tr(e/2),this.count=1,t&&(this.count=G(this)+2)}return this.s+=this.diff,this.count--,this.s}},ui=class{constructor(e){this.decoder=new ci(e),this.str=ri(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}};je.subtle;const di=je.getRandomValues.bind(je),fi=()=>di(new Uint32Array(1))[0],pi=()=>`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^fi()&15>>e/4).toString(16)),mi=Date.now,hi=e=>new Promise(e);Promise.all.bind(Promise);const gi=e=>e===void 0?null:e;let _i=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&&(_i=localStorage)}catch{}const vi=_i,yi=Symbol(`Equality`),bi=(e,t)=>e===t||!!e?.[yi]?.(t)||!1,xi=Object.assign,Si=Object.keys,Ci=(e,t)=>{for(let n in e)t(e[n],n)},wi=e=>Si(e).length,Ti=e=>{for(let t in e)return!1;return!0},Ei=(e,t)=>{for(let n in e)if(!t(e[n],n))return!1;return!0},Di=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Oi=(e,t)=>e===t||wi(e)===wi(t)&&Ei(e,(e,n)=>(e!==void 0||Di(t,n))&&bi(t[n],e)),ki=Object.freeze,Ai=e=>{for(let t in e){let n=e[t];(typeof n==`object`||typeof n==`function`)&&Ai(e[t])}return ki(e)},ji=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&ji(e,t,n+1)}},Mi=e=>e,Ni=(e,t)=>t.includes(e),Pi=typeof process<`u`&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<`u`?process:0)===`[object process]`,Fi=typeof window<`u`&&typeof document<`u`&&!Pi;typeof navigator<`u`&&/Mac/.test(navigator.platform);let Ii;const Li=[],Ri=()=>{if(Ii===void 0)if(Pi){Ii=Wn();let e=process.argv,t=null;for(let n=0;n<e.length;n++){let r=e[n];r[0]===`-`?(t!==null&&Ii.set(t,``),t=r):t===null?Li.push(r):(Ii.set(t,r),t=null)}t!==null&&Ii.set(t,``)}else typeof location==`object`?(Ii=Wn(),(location.search||`?`).slice(1).split(`&`).forEach(e=>{if(e.length!==0){let[t,n]=e.split(`=`);Ii.set(`--${pr(t,`-`)}`,n),Ii.set(`-${pr(t,`-`)}`,n)}})):Ii=Wn();return Ii},zi=e=>Ri().has(e),Bi=e=>gi(Pi?process.env[e.toUpperCase().replaceAll(`-`,`_`)]:vi.getItem(e)),Vi=e=>zi(`--`+e)||Bi(e)!==null;Vi(`production`);const Hi=Pi&&Ni(process.env.FORCE_COLOR,[`true`,`1`,`2`])||!zi(`--no-colors`)&&!Vi(`no-color`)&&(!Pi||process.stdout.isTTY)&&(!Pi||zi(`--color`)||Bi(`COLORTERM`)!==null||(Bi(`TERM`)||``).includes(`color`)),Ui=e=>new Uint8Array(e),Wi=Fi?e=>{let t=``;for(let n=0;n<e.byteLength;n++)t+=cr(e[n]);return btoa(t)}:e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64`),Gi=e=>{let t=Ui(e.byteLength);return t.set(e),t},Ki=e=>br(t=>Rr(t,e)),qi=Symbol,Ji=qi(),Yi=qi(),Xi=qi(),Zi=qi(),Qi=qi(),$i=qi(),ea=qi(),ta=qi(),na=qi(),ra=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};mi();const ia={[Ji]:`\x1B[1m`,[Yi]:`\x1B[2m`,[Xi]:`\x1B[34m`,[Qi]:`\x1B[32m`,[Zi]:`\x1B[37m`,[$i]:`\x1B[31m`,[ea]:`\x1B[35m`,[ta]:`\x1B[38;5;208m`,[na]:`\x1B[0m`},aa=Hi?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=ia[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}:ra,oa=(...e)=>{console.log(...aa(e))},sa=(...e)=>{console.warn(...aa(e))},ca=e=>({[Symbol.iterator](){return this},next:e}),la=(e,t)=>ca(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),ua=(e,t)=>ca(()=>{let{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}});var da=class{constructor(e,t){this.clock=e,this.len=t}},fa=class{constructor(){this.clients=new Map}};const pa=(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])To(e,i,o.clock,o.len,n)}}),ma=(e,t)=>{let n=0,r=e.length-1;for(;n<=r;){let i=tr((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},ha=(e,t)=>{let n=e.clients.get(t.client);return n!==void 0&&ma(n,t.clock)!==null},ga=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 da(r.clock,ir(r.len,i.clock+i.len-r.clock)):(n<t&&(e[n]=i),n++)}e.length=n})},_a=e=>{let t=new fa;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++)Xn(a,e[t].clients.get(i)||[]);t.clients.set(i,a)}});return ga(t),t},va=(e,t,n,r)=>{Kn(e.clients,t,()=>[]).push(new da(n,r))},ya=()=>new fa,ba=e=>{let t=ya();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 da(i,a))}}r.length>0&&t.clients.set(n,r)}),t},xa=(e,t)=>{W(e.restEncoder,t.clients.size),Zn(t.clients.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{e.resetDsCurVal(),W(e.restEncoder,t);let r=n.length;W(e.restEncoder,r);for(let t=0;t<r;t++){let r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}})},Sa=e=>{let t=new fa,n=G(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();let n=G(e.restDecoder),r=G(e.restDecoder);if(r>0){let i=Kn(t.clients,n,()=>[]);for(let t=0;t<r;t++)i.push(new da(e.readDsClock(),e.readDsLen()))}}return t},Ca=(e,t,n)=>{let r=new fa,i=G(e.restDecoder);for(let a=0;a<i;a++){e.resetDsCurVal();let i=G(e.restDecoder),a=G(e.restDecoder),o=n.clients.get(i)||[],s=_o(n,i);for(let n=0;n<a;n++){let n=e.readDsClock(),a=n+e.readDsLen();if(n<s){s<a&&va(r,i,s,a-s);let e=yo(o,n),c=o[e];for(!c.deleted&&c.id.clock<n&&(o.splice(e+1,0,zc(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,zc(t,c,a-c.id.clock)),c.delete(t))}else va(r,i,n,a-n)}}if(r.clients.size>0){let e=new Pa;return W(e.restEncoder,0),xa(e,r),e.toUint8Array()}return null},wa=(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},Ta=fi;var Ea=class e extends er{constructor({guid:e=pi(),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=Ta(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new ho,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=hi(e=>{this.on(`load`,()=>{this.isLoaded=!0,e(this)})});let s=()=>hi(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&&q(e.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Zn(this.subdocs).map(e=>e.guid))}transact(e,t=null){return q(this,e,t)}get(e,t=ss){let n=Kn(this.share,e,()=>{let e=new t;return e._integrate(this,null),e}),r=n.constructor;if(t!==ss&&r!==t)if(r===ss){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,Os)}getText(e=``){return this.get(e,Ys)}getMap(e=``){return this.get(e,js)}getXmlElement(e=``){return this.get(e,ec)}getXmlFragment(e=``){return this.get(e,Qs)}toJSON(){let e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,Zn(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,q(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()}},Da=class{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return G(this.restDecoder)}readDsLen(){return G(this.restDecoder)}},Oa=class extends Da{readLeftID(){return K(G(this.restDecoder),G(this.restDecoder))}readRightID(){return K(G(this.restDecoder),G(this.restDecoder))}readClient(){return G(this.restDecoder)}readInfo(){return ti(this.restDecoder)}readString(){return ri(this.restDecoder)}readParentInfo(){return G(this.restDecoder)===1}readTypeRef(){return G(this.restDecoder)}readLen(){return G(this.restDecoder)}readAny(){return oi(this.restDecoder)}readBuf(){return Gi(ei(this.restDecoder))}readJSON(){return JSON.parse(ri(this.restDecoder))}readKey(){return ri(this.restDecoder)}},ka=class{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=G(this.restDecoder),this.dsCurrVal}readDsLen(){let e=G(this.restDecoder)+1;return this.dsCurrVal+=e,e}},Aa=class extends ka{constructor(e){super(e),this.keys=[],G(e),this.keyClockDecoder=new li(ei(e)),this.clientDecoder=new ci(ei(e)),this.leftClockDecoder=new li(ei(e)),this.rightClockDecoder=new li(ei(e)),this.infoDecoder=new si(ei(e),ti),this.stringDecoder=new ui(ei(e)),this.parentInfoDecoder=new si(ei(e),ti),this.typeRefDecoder=new ci(ei(e)),this.lenDecoder=new ci(ei(e))}readLeftID(){return new ro(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new ro(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 oi(this.restDecoder)}readBuf(){return ei(this.restDecoder)}readJSON(){return oi(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}}},ja=class{constructor(){this.restEncoder=yr()}toUint8Array(){return Sr(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){W(this.restEncoder,e)}writeDsLen(e){W(this.restEncoder,e)}},Ma=class extends ja{writeLeftID(e){W(this.restEncoder,e.client),W(this.restEncoder,e.clock)}writeRightID(e){W(this.restEncoder,e.client),W(this.restEncoder,e.clock)}writeClient(e){W(this.restEncoder,e)}writeInfo(e){Tr(this.restEncoder,e)}writeString(e){kr(this.restEncoder,e)}writeParentInfo(e){W(this.restEncoder,e?1:0)}writeTypeRef(e){W(this.restEncoder,e)}writeLen(e){W(this.restEncoder,e)}writeAny(e){Rr(this.restEncoder,e)}writeBuf(e){jr(this.restEncoder,e)}writeJSON(e){kr(this.restEncoder,JSON.stringify(e))}writeKey(e){kr(this.restEncoder,e)}},Na=class{constructor(){this.restEncoder=yr(),this.dsCurrVal=0}toUint8Array(){return Sr(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){let t=e-this.dsCurrVal;this.dsCurrVal=e,W(this.restEncoder,t)}writeDsLen(e){e===0&&qr(),W(this.restEncoder,e-1),this.dsCurrVal+=e}},Pa=class extends Na{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new Ur,this.clientEncoder=new Vr,this.leftClockEncoder=new Ur,this.rightClockEncoder=new Ur,this.infoEncoder=new zr(Tr),this.stringEncoder=new Wr,this.parentInfoEncoder=new zr(Tr),this.typeRefEncoder=new Vr,this.lenEncoder=new Vr}toUint8Array(){let e=yr();return W(e,0),jr(e,this.keyClockEncoder.toUint8Array()),jr(e,this.clientEncoder.toUint8Array()),jr(e,this.leftClockEncoder.toUint8Array()),jr(e,this.rightClockEncoder.toUint8Array()),jr(e,Sr(this.infoEncoder)),jr(e,this.stringEncoder.toUint8Array()),jr(e,Sr(this.parentInfoEncoder)),jr(e,this.typeRefEncoder.toUint8Array()),jr(e,this.lenEncoder.toUint8Array()),Ar(e,Sr(this.restEncoder)),Sr(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){Rr(this.restEncoder,e)}writeBuf(e){jr(this.restEncoder,e)}writeJSON(e){Rr(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 Fa=(e,t,n,r)=>{r=ir(r,t[0].id.clock);let i=yo(t,r);W(e.restEncoder,t.length-i),e.writeClient(n),W(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)},Ia=(e,t,n)=>{let r=new Map;n.forEach((e,n)=>{_o(t,n)>e&&r.set(n,e)}),go(t).forEach((e,t)=>{n.has(t)||r.set(t,0)}),W(e.restEncoder,r.size),Zn(r.entries()).sort((e,t)=>t[0]-e[0]).forEach(([n,r])=>{Fa(e,t.clients.get(n),n,r)})},La=(e,t)=>{let n=Wn(),r=G(e.restDecoder);for(let i=0;i<r;i++){let r=G(e.restDecoder),i=Array(r),a=e.readClient(),o=G(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 cc(K(a,o),t),o+=t;break}case 10:{let t=G(e.restDecoder);i[n]=new Gc(K(a,o),t),o+=t;break}default:{let s=(r&192)==0,c=new Hc(K(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,Uc(e,r));i[n]=c,o+=c.length}}}}return n},Ra=(e,t,n)=>{let r=[],i=Zn(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 ho,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!==Gc){let i=Kn(d,u.id.client,()=>_o(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,_o(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 Pa;return Ia(e,s,new Map),W(e.restEncoder,0),{missing:c,update:e.toUint8Array()}}return null},za=(e,t)=>Ia(e,t.doc.store,t.beforeState),Ba=(e,t,n,r=new Aa(e))=>q(t,e=>{e.local=!1;let t=!1,n=e.doc,i=n.store,a=Ra(e,i,La(r,n)),o=i.pendingStructs;if(o){for(let[e,n]of o.missing)if(n<_o(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=Ho([o.update,a.update])}}else i.pendingStructs=a;let s=Ca(r,e,i);if(i.pendingDs){let t=new Aa(Zr(i.pendingDs));G(t.restDecoder);let n=Ca(t,e,i);s&&n?i.pendingDs=Ho([s,n]):i.pendingDs=s||n}else i.pendingDs=s;if(t){let t=i.pendingStructs.update;i.pendingStructs=null,Va(e.doc,t)}},n,!1),Va=(e,t,n,r=Aa)=>{let i=Zr(t);Ba(i,e,n,new r(i))},Ha=(e,t,n)=>Va(e,t,n,Oa),Ua=(e,t,n=new Map)=>{Ia(e,t.store,n),xa(e,ba(t.store))},Wa=(e,t=new Uint8Array([0]),n=new Pa)=>{Ua(n,e,qa(t));let r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Uo(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===Ma)return Bo(r.map((e,t)=>t===0?e:Jo(e)));if(n.constructor===Pa)return Ho(r)}return r[0]},Ga=(e,t)=>Wa(e,t,new Ma),Ka=e=>{let t=new Map,n=G(e.restDecoder);for(let r=0;r<n;r++){let n=G(e.restDecoder),r=G(e.restDecoder);t.set(n,r)}return t},qa=e=>Ka(new Da(Zr(e))),Ja=(e,t)=>(W(e.restEncoder,t.size),Zn(t.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{W(e.restEncoder,t),W(e.restEncoder,n)}),e),Ya=(e,t)=>Ja(e,go(t.store)),Xa=(e,t=new Na)=>(e instanceof Map?Ja(t,e):Ya(t,e),t.toUint8Array()),Za=e=>Xa(e,new ja);var Qa=class{constructor(){this.l=[]}};const $a=()=>new Qa,eo=(e,t)=>e.l.push(t),to=(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.`)},no=(e,t,n)=>ji(e.l,[t,n]);var ro=class{constructor(e,t){this.client=e,this.clock=t}};const io=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,K=(e,t)=>new ro(e,t),ao=e=>{for(let[t,n]of e.doc.share.entries())if(n===e)return t;throw qr()},oo=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};var so=class{constructor(e,t){this.ds=e,this.sv=t}};const co=(e,t)=>new so(e,t);co(ya(),new Map);const lo=e=>co(ba(e.store),go(e.store)),uo=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!ha(t.ds,e.id),fo=(e,t)=>{let n=Kn(e.meta,fo,Jn),r=e.doc.store;n.has(t)||(t.sv.forEach((t,n)=>{t<_o(r,n)&&So(e,K(n,t))}),pa(e,t.ds,e=>{}),n.add(t))},po=(e,t,n=Aa)=>{let r=new n(Zr(t)),i=new Ro(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=_a([e.ds,Sa(r)]);return wa(e.ds,a)},mo=(e,t)=>po(e,t,Oa);var ho=class{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}};const go=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},_o=(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},vo=(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 qr()}n.push(t)},yo=(e,t)=>{let n=0,r=e.length-1,i=e[r],a=i.id.clock;if(a===t)return r;let o=tr(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=tr((n+r)/2)}throw qr()},bo=(e,t)=>{let n=e.clients.get(t.client);return n[yo(n,t.clock)]},xo=(e,t,n)=>{let r=yo(t,n),i=t[r];return i.id.clock<n&&i instanceof Hc?(t.splice(r+1,0,zc(e,i,n-i.id.clock)),r+1):r},So=(e,t)=>{let n=e.doc.store.clients.get(t.client);return n[xo(e,n,t.clock)]},Co=(e,t,n)=>{let r=t.clients.get(n.client),i=yo(r,n.clock),a=r[i];return n.clock!==a.id.clock+a.length-1&&a.constructor!==cc&&r.splice(i+1,0,zc(e,a,n.clock-a.id.clock+1)),a},wo=(e,t,n)=>{let r=e.clients.get(t.id.client);r[yo(r,t.id.clock)]=n},To=(e,t,n,r,i)=>{if(r===0)return;let a=n+r,o=xo(e,t,n),s;do s=t[o++],a<s.id.clock+s.length&&xo(e,t,a),i(s);while(o<t.length&&t[o].id.clock<a)};var Eo=class{constructor(e,t,n){this.doc=e,this.deleteSet=new fa,this.beforeState=go(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 Do=(e,t)=>t.deleteSet.clients.size===0&&!qn(t.afterState,(e,n)=>t.beforeState.get(n)!==e)?!1:(ga(t.deleteSet),za(e,t),xa(e,t.deleteSet),!0),Oo=(e,t,n)=>{let r=t._item;(r===null||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&Kn(e.changed,t,Jn).add(n)},ko=(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 Hc&&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},Ao=(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=yo(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 Hc&&i.deleted&&!i.keep&&n(i)&&i.gc(t,!1)}}}},jo=(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=rr(r.length-1,1+yo(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+ko(r,e)}})},Mo=(e,t)=>{if(t<e.length){let n=e[t],r=n.doc,i=r.store,a=n.deleteSet,o=n._mergeStructs;try{ga(a),n.afterState=go(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(()=>{no(r._dEH,t,n)}))}),e.push(()=>r.emit(`afterTransaction`,[n,r])),e.push(()=>{n._needFormattingCleanup&&Ks(n)})}),ji(e,[])}finally{r.gc&&Ao(a,i,r.gcFilter),jo(a,i),n.afterState.forEach((e,t)=>{let r=n.beforeState.get(t)||0;if(r!==e){let e=i.clients.get(t),n=ir(yo(e,r),1);for(let t=e.length-1;t>=n;)t-=1+ko(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=yo(r,n);a+1<r.length&&ko(r,a+1)>1||a>0&&ko(r,a)}if(!n.local&&n.afterState.get(r.clientID)!==n.beforeState.get(r.clientID)&&(oa(ta,Ji,`[yjs] `,Yi,$i,`Changed the client-id because another client seems to be using it.`),r.clientID=Ta()),r.emit(`afterTransactionCleanup`,[n,r]),r._observers.has(`update`)){let e=new Ma;Do(e,n)&&r.emit(`update`,[e.toUint8Array(),n.origin,r,n])}if(r._observers.has(`updateV2`)){let e=new Pa;Do(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])):Mo(e,t+1)}}},q=(e,t,n=null,r=!0)=>{let i=e._transactionCleanups,a=!1,o=null;e._transaction===null&&(a=!0,e._transaction=new Eo(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&&Mo(i,0)}}return o};var No=class{constructor(e,t){this.insertions=t,this.deletions=e,this.meta=new Map}};const Po=(e,t,n)=>{pa(e,n.deletions,n=>{n instanceof Hc&&t.scope.some(t=>t===e.doc||oo(t,n))&&Rc(n,!1)})},Fo=(e,t,n)=>{let r=null,i=e.doc,a=e.scope;q(i,n=>{for(;t.length>0&&e.currStackItem===null;){let r=i.store,o=t.pop(),s=new Set,c=[],l=!1;pa(n,o.insertions,e=>{if(e instanceof Hc){if(e.redone!==null){let{item:t,diff:i}=Lc(r,e.id);i>0&&(t=So(n,K(t.id.client,t.id.clock+i))),e=t}!e.deleted&&a.some(t=>t===n.doc||oo(t,e))&&c.push(e)}}),pa(n,o.deletions,e=>{e instanceof Hc&&a.some(t=>t===n.doc||oo(t,e))&&!ha(o.insertions,e.id)&&s.add(e)}),s.forEach(t=>{l=Vc(n,t,s,o.insertions,e.ignoreRemoteMapChanges,e)!==null||l});for(let t=c.length-1;t>=0;t--){let r=c[t];e.deleteFilter(r)&&(r.delete(n),l=!0)}e.currStackItem=l?o:null}n.changed.forEach((e,t)=>{e.has(null)&&t._searchMarker&&(t._searchMarker.length=0)}),r=n},e);let o=e.currStackItem;if(o!=null){let t=r.changedParentTypes;e.emit(`stack-item-popped`,[{stackItem:o,type:n,changedParentTypes:t,origin:e},e]),e.currStackItem=null}return o};var Io=class extends er{constructor(e,{captureTimeout:t=500,captureTransaction:n=e=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:a=!1,doc:o=$n(e)?e[0].doc:e instanceof Ea?e:e.doc}={}){super(),this.scope=[],this.doc=o,this.addToScope(e),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=n,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=a,this.captureTimeout=t,this.afterTransactionHandler=e=>{if(!this.captureTransaction(e)||!this.scope.some(t=>e.changedParentTypes.has(t)||t===this.doc)||!this.trackedOrigins.has(e.origin)&&(!e.origin||!this.trackedOrigins.has(e.origin.constructor)))return;let t=this.undoing,n=this.redoing,r=t?this.redoStack:this.undoStack;t?this.stopCapturing():n||this.clear(!1,!0);let i=new fa;e.afterState.forEach((t,n)=>{let r=e.beforeState.get(n)||0,a=t-r;a>0&&va(i,n,r,a)});let a=mi(),o=!1;if(this.lastChange>0&&a-this.lastChange<this.captureTimeout&&r.length>0&&!t&&!n){let t=r[r.length-1];t.deletions=_a([t.deletions,e.deleteSet]),t.insertions=_a([t.insertions,i])}else r.push(new No(e.deleteSet,i)),o=!0;!t&&!n&&(this.lastChange=a),pa(e,e.deleteSet,t=>{t instanceof Hc&&this.scope.some(n=>n===e.doc||oo(n,t))&&Rc(t,!0)});let s=[{stackItem:r[r.length-1],origin:e.origin,type:t?`redo`:`undo`,changedParentTypes:e.changedParentTypes},this];o?this.emit(`stack-item-added`,s):this.emit(`stack-item-updated`,s)},this.doc.on(`afterTransaction`,this.afterTransactionHandler),this.doc.on(`destroy`,()=>{this.destroy()})}addToScope(e){let t=new Set(this.scope);e=$n(e)?e:[e],e.forEach(e=>{t.has(e)||(t.add(e),(e instanceof ss?e.doc!==this.doc:e!==this.doc)&&sa(`[yjs#509] Not same Y.Doc`),this.scope.push(e))})}addTrackedOrigin(e){this.trackedOrigins.add(e)}removeTrackedOrigin(e){this.trackedOrigins.delete(e)}clear(e=!0,t=!0){(e&&this.canUndo()||t&&this.canRedo())&&this.doc.transact(n=>{e&&(this.undoStack.forEach(e=>Po(n,this,e)),this.undoStack=[]),t&&(this.redoStack.forEach(e=>Po(n,this,e)),this.redoStack=[]),this.emit(`stack-cleared`,[{undoStackCleared:e,redoStackCleared:t}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let e;try{e=Fo(this,this.undoStack,`undo`)}finally{this.undoing=!1}return e}redo(){this.redoing=!0;let e;try{e=Fo(this,this.redoStack,`redo`)}finally{this.redoing=!1}return e}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off(`afterTransaction`,this.afterTransactionHandler),super.destroy()}};function*Lo(e){let t=G(e.restDecoder);for(let n=0;n<t;n++){let t=G(e.restDecoder),n=e.readClient(),r=G(e.restDecoder);for(let i=0;i<t;i++){let t=e.readInfo();if(t===10){let t=G(e.restDecoder);yield new Gc(K(n,r),t),r+=t}else if(31&t){let i=(t&192)==0,a=new Hc(K(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,Uc(e,t));yield a,r+=a.length}else{let t=e.readLen();yield new cc(K(n,r),t),r+=t}}}}var Ro=class{constructor(e,t){this.gen=Lo(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===Gc);return this.curr}},zo=class{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}};const Bo=e=>Ho(e,Oa,Ma),Vo=(e,t)=>{if(e.constructor===cc){let{client:n,clock:r}=e.id;return new cc(K(n,r+t),e.length-t)}else if(e.constructor===Gc){let{client:n,clock:r}=e.id;return new Gc(K(n,r+t),e.length-t)}else{let n=e,{client:r,clock:i}=n.id;return new Hc(K(r,i+t),null,K(r,i+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Ho=(e,t=Aa,n=Pa)=>{if(e.length===1)return e[0];let r=e.map(e=>new t(Zr(e))),i=r.map(e=>new Ro(e,!0)),a=null,o=new n,s=new zo(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===Gc?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)Go(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===Gc)a.struct.length=n.id.clock+n.length-a.struct.id.clock;else{Go(s,a.struct,a.offset);let e=n.id.clock-a.struct.id.clock-a.struct.length;a={struct:new Gc(K(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===Gc?a.struct.length-=t:n=Vo(n,t)),a.struct.mergeWith(n)||(Go(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!==Gc;n=e.next())Go(s,a.struct,a.offset),a={struct:n,offset:0}}return a!==null&&(Go(s,a.struct,a.offset),a=null),Ko(s),xa(o,_a(r.map(e=>Sa(e)))),o.toUint8Array()},Uo=(e,t,n=Aa,r=Pa)=>{let i=qa(t),a=new r,o=new zo(a),s=new n(Zr(e)),c=new Ro(s,!1);for(;c.curr;){let e=c.curr,t=e.id.client,n=i.get(t)||0;if(c.curr.constructor===Gc){c.next();continue}if(e.id.clock+e.length>n)for(Go(o,e,ir(n-e.id.clock,0)),c.next();c.curr&&c.curr.id.client===t;)Go(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 Ko(o),xa(a,Sa(s)),a.toUint8Array()},Wo=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:Sr(e.encoder.restEncoder)}),e.encoder.restEncoder=yr(),e.written=0)},Go=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&Wo(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),W(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},Ko=e=>{Wo(e);let t=e.encoder.restEncoder;W(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){let r=e.clientStructs[n];W(t,r.written),Ar(t,r.restEncoder)}},qo=(e,t,n,r)=>{let i=new n(Zr(e)),a=new Ro(i,!1),o=new r,s=new zo(o);for(let e=a.curr;e!==null;e=a.next())Go(s,t(e),0);return Ko(s),xa(o,Sa(i)),o.toUint8Array()},Jo=e=>qo(e,Mi,Aa,Ma),Yo=`You must not compute changes after the event-handler fired.`;var Xo=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||=Zo(this.currentTarget,this.target)}deletes(e){return ha(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Gr(Yo);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=Yn(e.content.getContent());else return;else e!==null&&this.deletes(e)?(i=`update`,a=Yn(e.content.getContent())):(i=`add`,a=void 0)}else if(this.deletes(r))i=`delete`,a=Yn(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 Gr(Yo);let t=this.target,n=Jn(),r=Jn(),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 Zo=(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},Qo=()=>{sa(`Invalid access: Add Yjs type to a document before reading data.`)};let $o=0;var es=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=$o++}};const ts=e=>{e.timestamp=$o++},ns=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=$o++},rs=(e,t,n)=>{if(e.length>=80){let r=e.reduce((e,t)=>e.timestamp<t.timestamp?e:t);return ns(r,t,n),r}else{let r=new es(t,n);return e.push(r),r}},is=(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)=>nr(t-e.index)<nr(t-n.index)?e:n),r=e._start,i=0;for(n!==null&&(r=n.p,i=n.index,ts(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&&nr(n.index-i)<r.parent.length/80?(ns(n,r,i),n):rs(e._searchMarker,r,i)},as=(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=ir(t,i.index+n))}},os=(e,t,n)=>{let r=e,i=t.changedParentTypes;for(;Kn(i,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;no(r._eH,n,t)};var ss=class{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=$a(),this._dEH=$a(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw Kr()}clone(){throw Kr()}_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){eo(this._eH,e)}observeDeep(e){eo(this._dEH,e)}unobserve(e){to(this._eH,e)}unobserveDeep(e){to(this._dEH,e)}toJSON(){}};const cs=(e,t,n)=>{e.doc??Qo(),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},ls=e=>{e.doc??Qo();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},us=(e,t)=>{let n=[],r=e._start;for(;r!==null;){if(r.countable&&uo(r,t)){let e=r.content.getContent();for(let t=0;t<e.length;t++)n.push(e[t])}r=r.right}return n},ds=(e,t)=>{let n=0,r=e._start;for(e.doc??Qo();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}},fs=(e,t)=>{let n=[];return ds(e,(r,i)=>{n.push(t(r,i,e))}),n},ps=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}}}},ms=(e,t)=>{e.doc??Qo();let n=is(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}},hs=(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 Hc(K(o,_o(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Cc(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 Hc(K(o,_o(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new lc(new Uint8Array(n))),i.integrate(e,0);break;case Ea:i=new Hc(K(o,_o(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new mc(n)),i.integrate(e,0);break;default:if(n instanceof ss)i=new Hc(K(o,_o(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Fc(n)),i.integrate(e,0);else throw Error(`Unexpected content type in insert operation`)}}}),u()},gs=()=>Gr(`Length exceeded!`),_s=(e,t,n,r)=>{if(n>t._length)throw gs();if(n===0)return t._searchMarker&&as(t._searchMarker,n,r.length),hs(e,t,null,r);let i=n,a=is(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&&So(e,K(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&as(t._searchMarker,i,r.length),hs(e,t,o,r)},vs=(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 hs(e,t,r,n)},ys=(e,t,n,r)=>{if(r===0)return;let i=n,a=r,o=is(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&&So(e,K(s.id.client,s.id.clock+n)),n-=s.length);for(;r>0&&s!==null;)s.deleted||(r<s.length&&So(e,K(s.id.client,s.id.clock+r)),s.delete(e),r-=s.length),s=s.right;if(r>0)throw gs();t._searchMarker&&as(t._searchMarker,i,-a+r)},bs=(e,t,n)=>{let r=t._map.get(n);r!==void 0&&r.delete(e)},xs=(e,t,n,r)=>{let i=t._map.get(n)||null,a=e.doc,o=a.clientID,s;if(r==null)s=new Cc([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:s=new Cc([r]);break;case Uint8Array:s=new lc(r);break;case Ea:s=new mc(r);break;default:if(r instanceof ss)s=new Fc(r);else throw Error(`Unexpected content type`)}new Hc(K(o,_o(a.store,o)),i,i&&i.lastId,null,null,t,n,s).integrate(e,0)},Ss=(e,t)=>{e.doc??Qo();let n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},Cs=e=>{let t={};return e.doc??Qo(),e._map.forEach((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])}),t},ws=(e,t)=>{e.doc??Qo();let n=e._map.get(t);return n!==void 0&&!n.deleted},Ts=(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&&uo(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},Es=e=>(e.doc??Qo(),la(e._map.entries(),e=>!e[1].deleted));var Ds=class extends Xo{},Os=class e extends ss{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 ss?e.clone():e)),t}get length(){return this.doc??Qo(),this._length}_callObserver(e,t){super._callObserver(e,t),os(this,e,new Ds(this,e))}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):q(this.doc,n=>{_s(n,this,e,t)})}push(e){this.doc===null?this._prelimContent.push(...e):q(this.doc,t=>{vs(t,this,e)})}unshift(e){this.insert(0,e)}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):q(this.doc,n=>{ys(n,this,e,t)})}get(e){return ms(this,e)}toArray(){return ls(this)}slice(e=0,t=this.length){return cs(this,e,t)}toJSON(){return this.map(e=>e instanceof ss?e.toJSON():e)}map(e){return fs(this,e)}forEach(e){ds(this,e)}[Symbol.iterator](){return ps(this)}_write(e){e.writeTypeRef(Oc)}};const ks=e=>new Os;var As=class extends Xo{constructor(e,t,n){super(e,t),this.keysChanged=n}},js=class e extends ss{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 ss?e.clone():e)}),t}_callObserver(e,t){os(this,e,new As(this,e,t))}toJSON(){this.doc??Qo();let e={};return this._map.forEach((t,n)=>{if(!t.deleted){let r=t.content.getContent()[t.length-1];e[n]=r instanceof ss?r.toJSON():r}}),e}get size(){return[...Es(this)].length}keys(){return ua(Es(this),e=>e[0])}values(){return ua(Es(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return ua(Es(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??Qo(),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):q(this.doc,t=>{bs(t,this,e)})}set(e,t){return this.doc===null?this._prelimContent.set(e,t):q(this.doc,n=>{xs(n,this,e,t)}),t}get(e){return Ss(this,e)}has(e){return ws(this,e)}clear(){this.doc===null?this._prelimContent.clear():q(this.doc,e=>{this.forEach(function(t,n,r){bs(e,r,n)})})}_write(e){e.writeTypeRef(kc)}};const Ms=e=>new js,Ns=(e,t)=>e===t||typeof e==`object`&&typeof t==`object`&&e&&t&&Oi(e,t);var Ps=class{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){switch(this.right===null&&qr(),this.right.content.constructor){case vc:this.right.deleted||Rs(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 Fs=(e,t,n)=>{for(;t.right!==null&&n>0;){switch(t.right.content.constructor){case vc:t.right.deleted||Rs(t.currentAttributes,t.right.content);break;default:t.right.deleted||(n<t.right.length&&So(e,K(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},Is=(e,t,n,r)=>{let i=new Map,a=r?is(t,n):null;return a?Fs(e,new Ps(a.p.left,a.p,a.index,i),n-a.index):Fs(e,new Ps(null,t._start,0,i),n)},Ls=(e,t,n,r)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===vc&&Ns(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 Hc(K(a,_o(i.store,a)),s,s&&s.lastId,c,c&&c.id,t,null,new vc(o,r));l.integrate(e,0),n.right=l,n.forward()})},Rs=(e,t)=>{let{key:n,value:r}=t;r===null?e.delete(n):e.set(n,r)},zs=(e,t)=>{for(;e.right!==null&&(e.right.deleted||e.right.content.constructor===vc&&Ns(t[e.right.content.key]??null,e.right.content.value));)e.forward()},Bs=(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(!Ns(l,c)){o.set(s,l);let{left:r,right:u}=n;n.right=new Hc(K(a,_o(i.store,a)),r,r&&r.lastId,u,u&&u.id,t,null,new vc(s,c)),n.right.integrate(e,0),n.forward()}}return o},Vs=(e,t,n,r,i)=>{n.currentAttributes.forEach((e,t)=>{i[t]===void 0&&(i[t]=null)});let a=e.doc,o=a.clientID;zs(n,i);let s=Bs(e,t,n,i),c=r.constructor===String?new Tc(r):r instanceof ss?new Fc(r):new gc(r),{left:l,right:u,index:d}=n;t._searchMarker&&as(t._searchMarker,n.index,c.getLength()),u=new Hc(K(o,_o(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(),Ls(e,t,n,s)},Hs=(e,t,n,r,i)=>{let a=e.doc,o=a.clientID;zs(n,i);let s=Bs(e,t,n,i);iterationLoop:for(;n.right!==null&&(r>0||s.size>0&&(n.right.deleted||n.right.content.constructor===vc));){if(!n.right.deleted)switch(n.right.content.constructor){case vc:{let{key:t,value:a}=n.right.content,o=i[t];if(o!==void 0){if(Ns(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&&So(e,K(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+=`
10
+ `;n.right=new Hc(K(o,_o(a.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Tc(i)),n.right.integrate(e,0),n.forward()}Ls(e,t,n,s)},Us=(e,t,n,r,i)=>{let a=t,o=Wn();for(;a&&(!a.countable||a.deleted);){if(!a.deleted&&a.content.constructor===vc){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 vc:{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&&Rs(i,n);break}}}t=t.right}return s},Ws=(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===vc){let r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}},Gs=e=>{let t=0;return q(e.doc,n=>{let r=e._start,i=e._start,a=Wn(),o=Gn(a);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case vc:Rs(o,i.content);break;default:t+=Us(n,r,i,a,o),a=Gn(o),r=i;break}i=i.right}}),t},Ks=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&&To(e,n.store.clients.get(r),a,i,e=>{!e.deleted&&e.content.constructor===vc&&e.constructor!==cc&&t.add(e.parent)})}q(n,n=>{pa(e,e.deleteSet,e=>{if(e instanceof cc||!e.parent._hasFormatting||t.has(e.parent))return;let r=e.parent;e.content.constructor===vc?t.add(r):Ws(n,e)});for(let e of t)Gs(e)})},qs=(e,t,n)=>{let r=n,i=Gn(t.currentAttributes),a=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case Fc:case gc:case Tc:n<t.right.length&&So(e,K(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e);break}t.forward()}a&&Us(e,a,t.right,i,t.currentAttributes);let o=(t.left||t.right).parent;return o._searchMarker&&as(o._searchMarker,t.index,-r+n),t};var Js=class extends Xo{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=[];q(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},Ti(o)||(e.attributes=xi({},o))),c=0;break}e&&t.push(e),a=null}};for(;i!==null;){switch(i.content.constructor){case Fc:case gc: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 Tc: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 vc:{let{key:t,value:s}=i.content;if(this.adds(i))this.deletes(i)||(Ns(n.get(t)??null,s)?s!==null&&i.delete(e):(a===`retain`&&u(),Ns(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;Ns(e,s)||(a===`retain`&&u(),o[t]=e)}else if(!i.deleted){r.set(t,s);let n=o[t];n!==void 0&&(Ns(n,s)?n!==null&&i.delete(e):(a===`retain`&&u(),s===null?delete o[t]:o[t]=s))}i.deleted||(a===`insert`&&u(),Rs(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}},Ys=class e extends ss{constructor(e){super(),this._pending=e===void 0?[]:[()=>this.insert(0,e)],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Qo(),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 Js(this,e,t);os(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Qo();let e=``,t=this._start;for(;t!==null;)!t.deleted&&t.countable&&t.content.constructor===Tc&&(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)):q(this.doc,n=>{let r=new Ps(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)===`
11
+ `?a.insert.slice(0,-1):a.insert;(typeof o!=`string`||o.length>0)&&Vs(n,this,r,o,a.attributes||{})}else a.retain===void 0?a.delete!==void 0&&qs(n,r,a.delete):Hs(n,this,r,a.retain,a.attributes||{})}})}toDelta(e,t,n){this.doc??Qo();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(uo(s,e)||t!==void 0&&uo(s,t))switch(s.content.constructor){case Tc:{let r=i.get(`ychange`);e!==void 0&&!uo(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&&!uo(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 Fc:case gc:{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 vc:uo(s,e)&&(c(),Rs(i,s.content));break}s=s.right}c()};return e||t?q(a,n=>{e&&fo(n,e),t&&fo(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)):q(r,r=>{let i=Is(r,this,e,!n);n||(n={},i.currentAttributes.forEach((e,t)=>{n[t]=e})),Vs(r,this,i,t,n)})}insertEmbed(e,t,n){let r=this.doc;r===null?this._pending.push(()=>this.insertEmbed(e,t,n||{})):q(r,r=>{let i=Is(r,this,e,!n);Vs(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)):q(n,n=>{qs(n,Is(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)):q(r,r=>{let i=Is(r,this,e,!1);i.right!==null&&Hs(r,this,i,t,n)})}removeAttribute(e){this.doc===null?this._pending.push(()=>this.removeAttribute(e)):q(this.doc,t=>{bs(t,this,e)})}setAttribute(e,t){this.doc===null?this._pending.push(()=>this.setAttribute(e,t)):q(this.doc,n=>{xs(n,this,e,t)})}getAttribute(e){return Ss(this,e)}getAttributes(){return Cs(this)}_write(e){e.writeTypeRef(Ac)}};const Xs=e=>new Ys;var Zs=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Qo()}[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===ec||t.constructor===Qs)&&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})}},Qs=class e extends ss{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 ss?e.clone():e)),t}get length(){return this.doc??Qo(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new Zs(this,e)}querySelector(e){e=e.toUpperCase();let t=new Zs(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),Zn(new Zs(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){os(this,e,new nc(this,t,e))}toString(){return fs(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),ds(this,i=>{r.insertBefore(i.toDOM(e,t,n),null)}),r}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):q(this.doc,n=>{_s(n,this,e,t)})}insertAfter(e,t){if(this.doc!==null)q(this.doc,n=>{let r=e&&e instanceof ss?e._item:e;hs(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 Gr(`Reference item not found`);n.splice(r,0,...t)}}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):q(this.doc,n=>{ys(n,this,e,t)})}toArray(){return ls(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return ms(this,e)}slice(e=0,t=this.length){return cs(this,e,t)}forEach(e){ds(this,e)}_write(e){e.writeTypeRef(Mc)}};const $s=e=>new Qs;var ec=class e extends Qs{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 Ci(this.getAttributes(),(e,n)=>{t.setAttribute(n,e)}),t.insert(0,this.toArray().map(e=>e instanceof ss?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):q(this.doc,t=>{bs(t,this,e)})}setAttribute(e,t){this.doc===null?this._prelimAttrs.set(e,t):q(this.doc,n=>{xs(n,this,e,t)})}getAttribute(e){return Ss(this,e)}hasAttribute(e){return ws(this,e)}getAttributes(e){return e?Ts(this,e):Cs(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 ds(this,i=>{r.appendChild(i.toDOM(e,t,n))}),n!==void 0&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(jc),e.writeKey(this.nodeName)}};const tc=e=>new ec(e.readKey());var nc=class extends Xo{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)})}},rc=class e extends js{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(Nc),e.writeKey(this.hookName)}};const ic=e=>new rc(e.readKey());var ac=class e extends Ys{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(Pc)}};const oc=e=>new ac;var sc=class{constructor(e,t){this.id=e,this.length=t}get deleted(){throw Kr()}mergeWith(e){return!1}write(e,t,n){throw Kr()}integrate(e,t){throw Kr()}},cc=class extends sc{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),vo(e.doc.store,this)}write(e,t){e.writeInfo(0),e.writeLen(this.length-t)}getMissing(e,t){return null}},lc=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 Kr()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}};const uc=e=>new lc(e.readBuf());var dc=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){va(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 fc=e=>new dc(e.readLen()),pc=(e,t)=>new Ea({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});var mc=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(pc(this.doc.guid,this.opts))}splice(e){throw Kr()}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 hc=e=>new mc(pc(e.readString(),e.readAny()));var gc=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 Kr()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}};const _c=e=>new gc(e.readJSON());var vc=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 Kr()}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 yc=e=>new vc(e.readKey(),e.readJSON());var bc=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 xc=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 bc(n)},Sc=Bi(`node_env`)===`development`;var Cc=class e{constructor(e){this.arr=e,Sc&&Ai(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 wc=e=>{let t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new Cc(n)};var Tc=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 Ec=e=>new Tc(e.readString()),Dc=[ks,Ms,Xs,tc,$s,ic,oc],Oc=0,kc=1,Ac=2,jc=3,Mc=4,Nc=5,Pc=6;var Fc=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 Kr()}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 Ic=e=>new Fc(Dc[e.readTypeRef()](e)),Lc=(e,t)=>{let n=t,r=0,i;do r>0&&(n=K(n.client,n.clock+r)),i=bo(e,n),r=n.clock-i.id.clock,n=i.redone;while(n!==null&&i instanceof Hc);return{item:i,diff:r}},Rc=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},zc=(e,t,n)=>{let{client:r,clock:i}=t.id,a=new Hc(K(r,i+n),t,K(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=K(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},Bc=(e,t)=>Qn(e,e=>ha(e.deletions,t)),Vc=(e,t,n,r,i,a)=>{let o=e.doc,s=o.store,c=o.clientID,l=t.redone;if(l!==null)return So(e,l);let u=t.parent._item,d=null,f;if(u!==null&&u.deleted===!0){if(u.redone===null&&(!n.has(u)||Vc(e,u,n,r,i,a)===null))return null;for(;u.redone!==null;)u=So(e,u.redone)}let p=u===null?t.parent:u.content.type;if(t.parentSub===null){for(d=t.left,f=t;d!==null;){let t=d;for(;t!==null&&t.parent._item!==u;)t=t.redone===null?null:So(e,t.redone);if(t!==null&&t.parent._item===u){d=t;break}d=d.left}for(;f!==null;){let t=f;for(;t!==null&&t.parent._item!==u;)t=t.redone===null?null:So(e,t.redone);if(t!==null&&t.parent._item===u){f=t;break}f=f.right}}else if(f=null,t.right&&!i){for(d=t;d!==null&&d.right!==null&&(d.right.redone||ha(r,d.right.id)||Bc(a.undoStack,d.right.id)||Bc(a.redoStack,d.right.id));)for(d=d.right;d.redone;)d=So(e,d.redone);if(d&&d.right!==null)return null}else d=p._map.get(t.parentSub)||null;let m=K(c,_o(s,c)),h=new Hc(m,d,d&&d.lastId,f,f&&f.id,p,t.parentSub,t.content.copy());return t.redone=m,Rc(h,!0),h.integrate(e,0),h};var Hc=class e extends sc{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>=_o(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=_o(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===ro&&this.id.client!==this.parent.client&&this.parent.clock>=_o(n,this.parent.client))return this.parent.client;if(this.origin&&=(this.left=Co(t,n,this.origin),this.left.lastId),this.rightOrigin&&=(this.right=So(t,this.rightOrigin),this.right.id),this.left&&this.left.constructor===cc||this.right&&this.right.constructor===cc)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===ro){let e=bo(n,this.parent);e.constructor===cc?this.parent=null:this.parent=e.content.type}return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=Co(e,e.doc.store,K(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),io(this.origin,n.origin)){if(n.id.client<this.id.client)t=n,r.clear();else if(io(this.rightOrigin,n.rightOrigin))break}else if(n.origin!==null&&i.has(bo(e.doc.store,n.origin)))r.has(bo(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),vo(e.doc.store,this),this.content.integrate(e,this),Oo(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new cc(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:K(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&io(e.origin,this.lastId)&&this.right===e&&io(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(),va(e.deleteSet,this.id.client,this.id.clock,this.length),Oo(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw qr();this.content.gc(e),t?wo(e,this,new cc(this.id,this.length)):this.content=new dc(this.length)}write(e,t){let n=t>0?K(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=ao(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===ro?(e.writeParentInfo(!1),e.writeLeftID(t)):qr();i!==null&&e.writeString(i)}this.content.write(e,t)}};const Uc=(e,t)=>Wc[t&31](e),Wc=[()=>{qr()},fc,xc,uc,Ec,_c,yc,Ic,wc,hc,()=>{qr()}];var Gc=class extends sc{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor?(this.length+=e.length,!0):!1}integrate(e,t){qr()}write(e,t){e.writeInfo(10),W(e.restEncoder,this.length-t)}getMissing(e,t){return null}};const Kc=typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:{},qc=`__ $YJS$ __`;Kc[qc]===!0&&console.error(`Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438`),Kc[qc]=!0;const Jc=/[\uD800-\uDBFF]/,Yc=/[\uDC00-\uDFFF]/,Xc=(e,t)=>{let n=0,r=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n++;for(n>0&&Jc.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&&Yc.test(e[e.length-r])&&r--,{index:n,remove:e.length-n-r,insert:t.slice(n,t.length-r)}},Zc=e=>{let t=ke(`sha256`);return t.update(e),t.digest()},Qc=new j(`y-sync`);new j(`y-undo`),new j(`yjs-cursor`);const $c=e=>{for(let t=6;t<e.length;t++)e[t%6]=e[t%6]^e[t];return e.slice(0,6)},el=e=>Wi($c(Zc(Ki(e)))),tl=()=>({mapping:new Map,isOMark:new Map}),nl=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&t.sv.get(e.id.client)>e.id.clock&&!ha(t.ds,e.id),rl=(e,t,n,r,i,a)=>{let o=n.mapping.get(e);if(o===void 0){if(e instanceof ec)return il(e,t,n,r,i,a);throw Kr()}return o},il=(e,t,n,r,i,a)=>{let o=[],s=e=>{if(e instanceof ec){let s=rl(e,t,n,r,i,a);s!==null&&o.push(s)}else{let s=e._item.right?.content?.type;s instanceof Ys&&!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=al(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):us(e,new so(i.ds,r.sv)).forEach(s);try{let s=e.getAttributes(r);r!==void 0&&(nl(e._item,r)?nl(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}},al=(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,bl(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},ol=(e,t)=>{let n=new ac,r=e.map(e=>({insert:e.text,attributes:xl(e.marks,t)}));return n.applyDelta(r),t.mapping.set(n,e),n},sl=(e,t)=>{let n=new ec(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,dl(e).map(e=>cl(e,t))),t.mapping.set(n,e),n},cl=(e,t)=>e instanceof Array?ol(e,t):sl(e,t),ll=e=>typeof e==`object`&&!!e,ul=(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||ll(o)&&ll(s)&&ul(o,s)}return r},dl=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},fl=(e,t)=>{let n=e.toDelta();return n.length===t.length&&n.every((e,n)=>e.insert===t[n].text&&Si(e.attributes||{}).length===t[n].marks.length&&Ei(e.attributes,(e,r)=>{let i=yl(r),a=t[n].marks;return a.find(e=>e.type.name===i)?ul(e,a.find(e=>e.type.name===i)?.attrs):!1}))},pl=(e,t)=>{if(e instanceof ec&&!(t instanceof Array)&&Cl(e,t)){let n=dl(t);return e._length===n.length&&ul(e.getAttributes(),t.attrs)&&e.toArray().every((e,t)=>pl(e,n[t]))}return e instanceof ac&&t instanceof Array&&fl(e,t)},ml=(e,t)=>e===t||e instanceof Array&&t instanceof Array&&e.length===t.length&&e.every((e,n)=>t[n]===e),hl=(e,t,n)=>{let r=e.toArray(),i=dl(t),a=i.length,o=r.length,s=rr(o,a),c=0,l=0,u=!1;for(;c<s;c++){let e=r[c],t=i[c];if(ml(n.mapping.get(e),t))u=!0;else if(!pl(e,t))break}for(;c+l<s;l++){let e=r[o-l-1],t=i[a-l-1];if(ml(n.mapping.get(e),t))u=!0;else if(!pl(e,t))break}return{equalityFactor:c+l,foundMappedChild:u}},gl=e=>{let t=``,n=e._start,r={};for(;n!==null;)n.deleted||(n.countable&&n.content instanceof Tc?t+=n.content.str:n.content instanceof vc&&(r[n.content.key]=null)),n=n.right;return{str:t,nAttrs:r}},_l=(e,t,n)=>{n.mapping.set(e,t);let{nAttrs:r,str:i}=gl(e),a=t.map(e=>({insert:e.text,attributes:Object.assign({},r,xl(e.marks,n))})),{insert:o,remove:s,index:c}=Xc(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})))},vl=/(.*)(--[a-zA-Z0-9+/=]{8})$/,yl=e=>vl.exec(e)?.[1]??e,bl=(e,t)=>{let n=[];for(let r in e)n.push(t.mark(yl(r),e[r]));return n},xl=(e,t)=>{let n={};return e.forEach(e=>{if(e.type.name!==`ychange`){let r=Kn(t.isOMark,e.type,()=>!e.type.excludes(e.type));n[r?`${e.type.name}--${el(e.toJSON())}`:e.type.name]=e.attrs}}),n},Sl=(e,t,n,r)=>{if(t instanceof ec&&t.nodeName!==n.type.name)throw Error(`node name mismatch!`);if(r.mapping.set(t,n),t instanceof ec){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=dl(n),a=i.length,o=t.toArray(),s=o.length,c=rr(a,s),l=0,u=0;for(;l<c;l++){let e=o[l],t=i[l];if(!ml(r.mapping.get(e),t))if(pl(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(!ml(r.mapping.get(e),t))if(pl(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 ac&&c instanceof Array)fl(n,c)||_l(n,c,r),l+=1;else{let i=n instanceof ec&&Cl(n,c),a=d instanceof ec&&Cl(d,f);if(i&&a){let e=hl(n,c,r),t=hl(d,f,r);e.foundMappedChild&&!t.foundMappedChild?a=!1:!e.foundMappedChild&&t.foundMappedChild||e.equalityFactor<t.equalityFactor?i=!1:a=!1}i?(Sl(e,n,c,r),l+=1):a?(Sl(e,d,f,r),u+=1):(r.mapping.delete(t.get(l)),t.delete(l,1),t.insert(l,[cl(c,r)]),l+=1)}}let n=s-l-u;if(s===1&&a===0&&o[0]instanceof ac?(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(cl(i[t],r));t.insert(l,e)}},Qc)},Cl=(e,t)=>!(t instanceof Array)&&e.nodeName===t.type.name,wl=(e,t)=>{let n=e.toArray().map(e=>il(e,t,tl())).filter(e=>e!==null);return u.fromArray(n)},Tl=(e,t)=>t.topNodeType.create(null,wl(e,t));function J(e){return e===b}var El=class{hocuspocus;seqs=new Map;timers=new Map;log=ln(`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(b);if(!t){this.warnedMissing||=(this.log.warn({},`[cc1] __system__ document not found — broadcasts will be dropped until it is materialized`),!0),Tn();return}let n=(this.seqs.get(e)??0)+1;this.seqs.set(e,n);let r={v:1,ch:e,seq:n};t.broadcastStateless(JSON.stringify(r)),wn(),Bn(e,n),En(t.getConnectionsCount())}catch(t){this.log.error({err:t,channel:e},`[cc1] broadcast failed`)}}get subscriberCount(){let e=this.hocuspocus.documents.get(b);return e?e.getConnectionsCount():0}destroy(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};const Dl=new d({extensions:N}),Ol=i(N),kl=ln(`agent-sessions`);function Al(e,t,n){try{let r=e.getXmlFragment(`default`),i=e.getText(`source`),a=e.getMap(`metadata`),o=Tl(r,Ol).toJSON(),s=Dl.serialize(o),c=a.get(`frontmatter`)??``,{frontmatter:u,body:d}=l(t),f,p;switch(n){case`replace`:f=u||c,p=d.trim();break;case`prepend`:f=c,p=`${d.trim()}\n\n${s}`;break;case`append`:f=c,p=s.trim()?`${s}\n\n${d.trim()}\n`:`${d.trim()}\n`;break}let m=Dl.parseWithFallback(p);Sl(e,r,Ol.nodeFromJSON(m),{mapping:new Map,isOMark:new Map}),f!==c&&a.set(`frontmatter`,f);let h=Dl.serialize(Tl(r,Ol).toJSON()),g=M(f,h);T(i,i.toString(),g)}catch(r){throw kl.error({err:r,docName:e.name,position:n,markdownLen:t.length},`[applyAgentMarkdownWrite] failed for '${e.name}'`),r}}function jl(e,t){let{dc:n,um:r,undoOrigin:i}=e,a=n.document,o=a.getXmlFragment(`default`),s=a.getText(`source`),c=a.getMap(`metadata`),u=!1;return a.transact(()=>{if(t===`last`){if(r.undoStack.length===0)return;r.undo(),u=!0}else for(;r.undoStack.length>0;)r.undo(),u=!0;let{body:e,frontmatter:n}=l(s.toString()),i=Dl.parseWithFallback(e);Sl(a,o,Ol.nodeFromJSON(i),{mapping:new Map,isOMark:new Map});let d=c.get(`frontmatter`)??``,f=n||d;n&&n!==d&&c.set(`frontmatter`,f);let p=M(f,Dl.serialize(Tl(o,Ol).toJSON()));T(s,s.toString(),p)},i),u}function Ml(e,t,n){let r={origin:`agent-write`,paired:!0,session_id:e};t!==void 0&&(r.agent_type=t),n!==void 0&&(r.principal=n),Object.freeze(r);let i={source:`local`,skipStoreHooks:!1,context:r};return Object.freeze(i),i}function Nl(e,t){let n={origin:`agent-undo`,paired:!0,session_id:e};t!==void 0&&(n.agent_type=t),Object.freeze(n);let r={source:`local`,skipStoreHooks:!1,context:n};return Object.freeze(r),r}var Pl=class{sessions=new Map;pendingSessions=new Map;hocuspocus;constructor(e){this.hocuspocus=e}sessionKey(e,t){return`${e}\0${t}`}async getSession(e,t=`claude-1`,n){if(J(e))throw Error(`Cannot create agent session for reserved doc: ${e}`);let r=this.sessionKey(e,t),i=this.sessions.get(r);if(i)return i;let a=this.pendingSessions.get(r);if(a)return a;let o=this._createSession(e,t,n);this.pendingSessions.set(r,o);try{let e=await o;return this.sessions.set(r,e),e}finally{this.pendingSessions.delete(r)}}async _createSession(e,t,n){let r=n?.clientName,i=t.startsWith(`agent-`)?t.slice(6):t,a=Ml(i,r,n?.principalId),o=Nl(i,r),s={session_id:i,...r===void 0?{}:{agent_type:r},...n?.clientName===void 0?{}:{client_name:n.clientName},...n?.principalId===void 0?{}:{principalId:n.principalId}},c=await this.hocuspocus.openDirectConnection(e,s),l=new Io([c.document.getText(`source`),c.document.getMap(`metadata`),c.document.getMap(`agent-flash`)],{trackedOrigins:new Set([a]),captureTimeout:500,captureTransaction:e=>e.origin!==o,ignoreRemoteMapChanges:!0});return kl.info({docName:e,agentId:t},`[agent-session] Created session for: ${e} / ${t}`),{dc:c,origin:a,undoOrigin:o,um:l,agentId:t,docName:e}}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.um.destroy(),await r.dc.disconnect(),this.sessions.delete(n),kl.info({docName:e,agentId:t},`[agent-session] Closed session for: ${e} / ${t}`))}async closeAllForAgent(e){let t=`\0${e}`,n=[...this.pendingSessions.keys()].filter(e=>e.endsWith(t));n.length>0&&await Promise.allSettled(n.map(e=>this.pendingSessions.get(e)));let r=[...this.sessions.keys()].filter(e=>e.endsWith(t));for(let t of r){let n=this.sessions.get(t);if(n)try{n.um.destroy(),await n.dc.disconnect(),this.sessions.delete(t)}catch(t){kl.error({err:t,agentId:e},`[agent-session] Failed to close session for agent ${e}`)}}}async closeAllForDoc(e){let t=`${e}\0`,n=[...this.sessions.keys()].filter(e=>e.startsWith(t));for(let t of n){let n=this.sessions.get(t);if(n)try{n.um.destroy(),await n.dc.disconnect(),this.sessions.delete(t)}catch(t){kl.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.um.destroy(),await t.dc.disconnect(),this.sessions.delete(e)}catch(t){kl.error({err:t,key:e},`[agent-session] Failed to close session: ${e}`)}}}};const Fl=/^(agent-[^/]+|principal-[^/]+|file-system|git-upstream|openknowledge-service)$/;function Il(e){return H(e,`.git/open-knowledge`)}function Ll(e){let t=Il(e);return R(H(t,`HEAD`))?t:null}function Rl(e){return`refs/wip/${e}/`}function zl(e){if(!e)return[];let t=[];for(let n of e.split(`
12
+ `)){let e=n.trim();if(e.startsWith(`ok-contributors: `))try{let n=JSON.parse(e.slice(17));if(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`)){let e=n;if(`summaries`in e){let t=e.summaries;(!Array.isArray(t)||!t.every(e=>typeof e==`string`))&&delete e.summaries}t.push(n)}}catch{}}return t}const Bl=`ok-checkpoint-v1: `;function Vl(e){if(!e)return null;for(let t of e.split(`
13
+ `)){let e=t.trim();if(!e.startsWith(Bl))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 Hl(e){let t={kind:e.kind,metadata:e.metadata};return e.docName!==null&&(t.docName=e.docName),e.size!==null&&(t.size=e.size),`${Bl}${JSON.stringify(t)}`}const Ul=`ok-actor: `;function Wl(e){let{summaries:t,...n}=e,r=t&&t.length>0?{...n,summaries:t}:n;return`${Ul}${JSON.stringify(r)}`}function Gl(e){if(e.v!==1||!(`display_name`in e)||typeof e.display_name!=`string`||!(`docs`in e)||!Array.isArray(e.docs))return null;let t=typeof e.principal==`string`?e.principal:null,n=typeof e.agent_session==`string`?e.agent_session:null,r;if(typeof e.writer_id==`string`&&e.writer_id.length>0)r=e.writer_id;else if(n)r=`agent-${n}`;else if(t)r=t;else switch(e.display_name){case`File System`:r=`file-system`;break;case`Git (upstream)`:r=`git-upstream`;break;default:r=`openknowledge-service`}let i=`summaries`in e&&Array.isArray(e.summaries)&&e.summaries.every(e=>typeof e==`string`)?e.summaries:void 0;return{v:1,writer_id:r,principal:t,agent_session:n,agent_type:typeof e.agent_type==`string`?e.agent_type:null,client_name:typeof e.client_name==`string`?e.client_name:null,client_version:typeof e.client_version==`string`?e.client_version:null,label:typeof e.label==`string`?e.label:null,display_name:e.display_name,color_seed:typeof e.color_seed==`string`?e.color_seed:`unknown`,docs:e.docs.filter(e=>typeof e==`string`),...i&&i.length>0?{summaries:i}:{}}}function Kl(e){if(!e)return[];let t=[];for(let n of e.split(`
14
+ `)){let e=n.trim();if(!e.startsWith(Ul))continue;let r;try{r=JSON.parse(e.slice(10))}catch{continue}if(typeof r!=`object`||!r)continue;let i=Gl(r);i&&t.push(i)}return t}function ql(e){let t={v:1,id:e.writer_id,name:e.display_name,colorSeed:e.color_seed,docs:e.docs};return e.summaries&&e.summaries.length>0&&(t.summaries=e.summaries),t}function Jl(e){let t=Kl(e);return t.length>0?t.map(ql):zl(e)}function Yl(e){return e.length===0?`wip: auto-save`:e.length===1?`wip: ${e[0]}`:`wip: ${e.length} docs`}function Xl(e){return`reconcile: ${e}`}function Zl(e,t){return`rollback: ${e} to ${t.slice(0,7)}`}function Ql(e,t){return`park: ${e} -> ${t}`}function $l(e,t){return`rename: ${e} -> ${t}`}function eu(e){return`checkpoint: ${e}`}function tu(e,t){return e?`import: from ${e.slice(0,8)}..${t.slice(0,8)}`:`import: initial at ${t.slice(0,8)}`}function nu(e,t){if(t.length===0)return e;if(t.length>=2)return`${e} (${t.length} edits)`;let[n]=t;if(n===void 0)return e;let r=`${e} — ${n}`;if(r.length<=72)return r;let i=`${e} — `,a=72-i.length-1;return a<=0?r.slice(0,72):`${i}${n.slice(0,a)}…`}function ru(e){return Fl.test(e)?e.startsWith(`agent-`)?{id:e,classification:`agent`,isAgent:!0}:e.startsWith(`principal-`)?{id:e,classification:`principal`,isAgent:!1}:e===`file-system`?{id:e,classification:`classified-file-system`,isAgent:null}:e===`git-upstream`?{id:e,classification:`classified-git-upstream`,isAgent:null}:e===`openknowledge-service`?{id:e,classification:`classified-openknowledge-service`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}}var iu=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}})),au=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})),ou=n(((e,n)=>{let{Readable:r,Writable:i}=t(`stream`),a=au(),{basename:o,convertToUTF8:s,getDecoder:c,parseContentType:l,parseDisposition:u}=iu(),d=Buffer.from(`\r
15
+ `),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,N=0,P,ee,te,ne,re=!1,F=!1,ie=!1;this._hparser=null;let ae=new g(e=>{this._hparser=null,A=!1,te=`text/plain`,P=i,ee=`7bit`,ne=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&&(ne=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&&(te=`${t.type}/${t.subtype}`,t.params&&typeof t.params.charset==`string`&&(P=t.params.charset.toLowerCase()))}if(e[`content-transfer-encoding`]&&(ee=e[`content-transfer-encoding`][0].toLowerCase()),te===`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`,ne,this._fileStream,{filename:t,encoding:ee,mimeType:te})}else{if(O===T){ie||(ie=!0,this.emit(`fieldsLimit`)),A=!0;return}if(++O,this.listenerCount(`field`)===0){A=!0;return}M=[],N=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-N);i?e=t.slice(n,n+a):(e=Buffer.allocUnsafe(a),t.copy(e,0,n,n+a)),N+=a,M.push(e),N===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],P,0);break;default:e=s(Buffer.concat(M,N),P,0)}M=void 0,N=0,this.emit(`field`,ne,e,{nameTruncated:!1,valueTruncated:re,encoding:ee,mimeType:te})}++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})),su=n(((e,n)=>{let{Writable:r}=t(`stream`),{getDecoder:i}=iu();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})),cu=n(((e,t)=>{let{parseContentType:n}=iu();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=[ou(),su()].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)}})),lu=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 lu{};function uu(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 du(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 fu(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 pu(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 mu(e,t){return fu(e,t,``)}function hu(e,t){return pu(e,t,``)}function gu(e,t){return t.slice(0,_u(e,t))}function _u(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 vu(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 yu(e,t){if(t)return xu(e,t)[1];let n;for(n=e.length-1;n>=0&&e[n].match(/\s/);n--);return e.substring(n+1)}function bu(e,t){if(t)return xu(e,t)[0];let n=e.match(/^\s*/);return n?n[0]:``}function xu(e,t){if(!t)return[bu(e),yu(e)];if(t.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);let n=vu(e,t),r=n[0],i=n[n.length-1];return[/\s/.test(r)?r:``,/\s/.test(i)?i:``]}const Su=`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}`,Cu=RegExp(`[${Su}]+|\\s+|[^${Su}]`,`ug`);new class extends lu{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=vu(e,r)}else n=e.match(Cu)||[];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)&&wu(n,i,r,e,t.intlSegmenter),n=e,r=null,i=null)}),(r||i)&&wu(n,i,r,null,t.intlSegmenter),e}};function wu(e,t,n,r,i){if(t&&n){let[a,o]=xu(t.value,i),[s,c]=xu(n.value,i);if(e){let r=uu(a,s);e.value=pu(e.value,s,r),t.value=mu(t.value,r),n.value=mu(n.value,r)}if(r){let e=du(o,c);r.value=fu(r.value,c,e),t.value=hu(t.value,e),n.value=hu(n.value,e)}}else if(n){if(e){let e=bu(n.value,i);n.value=n.value.substring(e.length)}if(r){let e=bu(r.value,i);r.value=r.value.substring(e.length)}}else if(e&&r){let n=bu(r.value,i),[a,o]=xu(t.value,i),s=uu(n,a);t.value=mu(t.value,s);let c=du(mu(n,s),o);t.value=hu(t.value,c),r.value=fu(r.value,n,c),e.value=pu(e.value,n,n.slice(0,n.length-c.length))}else if(r){let e=bu(r.value,i),n=gu(yu(t.value,i),e);t.value=hu(t.value,n)}else if(e){let n=gu(yu(e.value,i),bu(t.value,i));t.value=mu(t.value,n)}}new class extends lu{tokenize(e){let t=RegExp(`(\\r?\\n)|[${Su}]+|[^\\S\\n\\r]+|[^${Su}]`,`ug`);return e.match(t)||[]}};const Tu=new class extends lu{constructor(){super(...arguments),this.tokenize=Du}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
15
16
  `))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(`
16
17
  `))&&(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
17
18
  `)&&(e=e.slice(0,-1)),t.endsWith(`
18
- `)&&(t=t.slice(0,-1))),super.equals(e,t,n)}};function _u(e,t,n){return gu.diff(e,t,n)}function vu(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
19
- `));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 yu(e){return e==`.`||e==`!`||e==`?`}new class extends eu{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(yu(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 eu{tokenize(e){return e.split(/([{}:;,]|\s+)/)}},new class extends eu{constructor(){super(...arguments),this.tokenize=vu}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(bu(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 bu(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]=bu(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]=bu(e[s],t,n,r,s);t.pop(),n.pop()}else o=e;return o}new class extends eu{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}};const xu={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:`Ÿ`},Su={};for(let[e,t]of Object.entries(xu))Su[t]=Number.parseInt(e,10);let Cu;function wu(){if(globalThis.TextDecoder!==void 0)return Cu??=new globalThis.TextDecoder(`utf-8`)}const Tu=32*1024,Eu=65533;function Du(e,t=`utf-8`){switch(t.toLowerCase()){case`utf-8`:case`utf8`:{let t=wu();return t?t.decode(e):ju(e)}case`utf-16le`:return Mu(e);case`us-ascii`:case`ascii`:return Nu(e);case`latin1`:case`iso-8859-1`:return Pu(e);case`windows-1252`:return Fu(e);default:throw RangeError(`Encoding '${t}' not supported`)}}function Ou(e,t){t.length!==0&&(e.push(String.fromCharCode.apply(null,t)),t.length=0)}function ku(e,t,n){t.push(n),t.length>=Tu&&Ou(e,t)}function Au(e,t,n){if(n<=65535){ku(e,t,n);return}n-=65536,ku(e,t,55296+(n>>10)),ku(e,t,56320+(n&1023))}function ju(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){ku(t,n,i),r++;continue}if(i<194||i>244){ku(t,n,Eu),r++;continue}if(i<=223){if(r+1>=e.length){ku(t,n,Eu),r++;continue}let a=e[r+1];if((a&192)!=128){ku(t,n,Eu),r++;continue}ku(t,n,(i&31)<<6|a&63),r+=2;continue}if(i<=239){if(r+2>=e.length){ku(t,n,Eu),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))){ku(t,n,Eu),r++;continue}ku(t,n,(i&15)<<12|(a&63)<<6|o&63),r+=3;continue}if(r+3>=e.length){ku(t,n,Eu),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))){ku(t,n,Eu),r++;continue}Au(t,n,(i&7)<<18|(a&63)<<12|(o&63)<<6|s&63),r+=4}return Ou(t,n),t.join(``)}function Mu(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?(ku(t,n,a),ku(t,n,r),i+=2):ku(t,n,Eu)}else ku(t,n,Eu);continue}if(a>=56320&&a<=57343){ku(t,n,Eu);continue}ku(t,n,a)}return i<r&&ku(t,n,Eu),Ou(t,n),t.join(``)}function Nu(e){let t=[];for(let n=0;n<e.length;n+=Tu){let r=Math.min(e.length,n+Tu),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 Pu(e){let t=[];for(let n=0;n<e.length;n+=Tu){let r=Math.min(e.length,n+Tu),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 Fu(e){let t=[],n=``;for(let r=0;r<e.length;r++){let i=e[r],a=i>=128&&i<=159?xu[i]:void 0;n+=a??String.fromCharCode(i),n.length>=Tu&&(t.push(n),n=``)}return n&&t.push(n),t.join(``)}function Iu(e){return new DataView(e.buffer,e.byteOffset)}const Lu={len:1,get(e,t){return Iu(e).getUint8(t)},put(e,t,n){return Iu(e).setUint8(t,n),t+1}},Ru={len:2,get(e,t){return Iu(e).getUint16(t,!0)},put(e,t,n){return Iu(e).setUint16(t,n,!0),t+2}},zu={len:2,get(e,t){return Iu(e).getUint16(t)},put(e,t,n){return Iu(e).setUint16(t,n),t+2}},Bu={len:4,get(e,t){return Iu(e).getUint32(t,!0)},put(e,t,n){return Iu(e).setUint32(t,n,!0),t+4}},Vu={len:4,get(e,t){return Iu(e).getUint32(t)},put(e,t,n){return Iu(e).setUint32(t,n),t+4}},Hu={len:4,get(e,t){return Iu(e).getInt32(t)},put(e,t,n){return Iu(e).setInt32(t,n),t+4}},Uu={len:8,get(e,t){return Iu(e).getBigUint64(t,!0)},put(e,t,n){return Iu(e).setBigUint64(t,n,!0),t+8}};var Wu=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){return Du(e.subarray(t,t+this.len),this.encoding)}},Gu=class extends Error{constructor(){super(`End-Of-Stream`),this.name=`EndOfStreamError`}},Ku=class extends Error{constructor(e=`The operation was aborted`){super(e),this.name=`AbortError`}},qu=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 Gu;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 Ku;let r=await this.readFromStream(e.subarray(n),t);if(r===0)break;n+=r}if(!t&&n<e.length)throw new Gu;return n}},Ju=class extends qu{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}},Yu=class extends Ju{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}},Xu=class extends qu{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 Gu;return n}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function Zu(e){try{let t=e.getReader({mode:`byob`});return t instanceof ReadableStreamDefaultReader?new Xu(t):new Yu(t)}catch(t){if(t instanceof TypeError)return new Xu(e.getReader());throw t}}var Qu=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 Gu;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 Gu;return e.get(n,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new Gu;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new Gu;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()}},$u=class extends Qu{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 Gu;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 Gu)return 0;throw e}if(!n.mayBeLess&&r<n.length)throw new Gu}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}},ed=class extends Qu{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 Gu;return e.set(this.uint8Array.subarray(n.position,n.position+r)),r}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}},td=class extends Qu{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 Gu;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 nd(e,t){let n=Zu(e),r=t??{},i=r.onClose;return r.onClose=async()=>{if(await n.close(),i)return i()},new $u(n,r)}function rd(e,t){return new ed(e,t)}function id(e,t){return new td(e,t)}var ad=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`:``)}})),od=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=ad(),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})),sd=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=od()(e);let{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})),cd=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)}})),ld=n(((e,n)=>{let r=t(`os`),i=t(`tty`),a=cd(),{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)))}})),ud=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=ld();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(`
19
+ `)&&(t=t.slice(0,-1))),super.equals(e,t,n)}};function Eu(e,t,n){return Tu.diff(e,t,n)}function Du(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
20
+ `));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 Ou(e){return e==`.`||e==`!`||e==`?`}new class extends lu{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(Ou(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 lu{tokenize(e){return e.split(/([{}:;,]|\s+)/)}},new class extends lu{constructor(){super(...arguments),this.tokenize=Du}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(ku(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 ku(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]=ku(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]=ku(e[s],t,n,r,s);t.pop(),n.pop()}else o=e;return o}new class extends lu{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}};const Au={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:`Ÿ`},ju={};for(let[e,t]of Object.entries(Au))ju[t]=Number.parseInt(e,10);let Mu;function Nu(){if(globalThis.TextDecoder!==void 0)return Mu??=new globalThis.TextDecoder(`utf-8`)}const Pu=32*1024,Fu=65533;function Iu(e,t=`utf-8`){switch(t.toLowerCase()){case`utf-8`:case`utf8`:{let t=Nu();return t?t.decode(e):Bu(e)}case`utf-16le`:return Vu(e);case`us-ascii`:case`ascii`:return Hu(e);case`latin1`:case`iso-8859-1`:return Uu(e);case`windows-1252`:return Wu(e);default:throw RangeError(`Encoding '${t}' not supported`)}}function Lu(e,t){t.length!==0&&(e.push(String.fromCharCode.apply(null,t)),t.length=0)}function Ru(e,t,n){t.push(n),t.length>=Pu&&Lu(e,t)}function zu(e,t,n){if(n<=65535){Ru(e,t,n);return}n-=65536,Ru(e,t,55296+(n>>10)),Ru(e,t,56320+(n&1023))}function Bu(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){Ru(t,n,i),r++;continue}if(i<194||i>244){Ru(t,n,Fu),r++;continue}if(i<=223){if(r+1>=e.length){Ru(t,n,Fu),r++;continue}let a=e[r+1];if((a&192)!=128){Ru(t,n,Fu),r++;continue}Ru(t,n,(i&31)<<6|a&63),r+=2;continue}if(i<=239){if(r+2>=e.length){Ru(t,n,Fu),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))){Ru(t,n,Fu),r++;continue}Ru(t,n,(i&15)<<12|(a&63)<<6|o&63),r+=3;continue}if(r+3>=e.length){Ru(t,n,Fu),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))){Ru(t,n,Fu),r++;continue}zu(t,n,(i&7)<<18|(a&63)<<12|(o&63)<<6|s&63),r+=4}return Lu(t,n),t.join(``)}function Vu(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?(Ru(t,n,a),Ru(t,n,r),i+=2):Ru(t,n,Fu)}else Ru(t,n,Fu);continue}if(a>=56320&&a<=57343){Ru(t,n,Fu);continue}Ru(t,n,a)}return i<r&&Ru(t,n,Fu),Lu(t,n),t.join(``)}function Hu(e){let t=[];for(let n=0;n<e.length;n+=Pu){let r=Math.min(e.length,n+Pu),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 Uu(e){let t=[];for(let n=0;n<e.length;n+=Pu){let r=Math.min(e.length,n+Pu),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 Wu(e){let t=[],n=``;for(let r=0;r<e.length;r++){let i=e[r],a=i>=128&&i<=159?Au[i]:void 0;n+=a??String.fromCharCode(i),n.length>=Pu&&(t.push(n),n=``)}return n&&t.push(n),t.join(``)}function Gu(e){return new DataView(e.buffer,e.byteOffset)}const Ku={len:1,get(e,t){return Gu(e).getUint8(t)},put(e,t,n){return Gu(e).setUint8(t,n),t+1}},qu={len:2,get(e,t){return Gu(e).getUint16(t,!0)},put(e,t,n){return Gu(e).setUint16(t,n,!0),t+2}},Ju={len:2,get(e,t){return Gu(e).getUint16(t)},put(e,t,n){return Gu(e).setUint16(t,n),t+2}},Yu={len:4,get(e,t){return Gu(e).getUint32(t,!0)},put(e,t,n){return Gu(e).setUint32(t,n,!0),t+4}},Xu={len:4,get(e,t){return Gu(e).getUint32(t)},put(e,t,n){return Gu(e).setUint32(t,n),t+4}},Zu={len:4,get(e,t){return Gu(e).getInt32(t)},put(e,t,n){return Gu(e).setInt32(t,n),t+4}},Qu={len:8,get(e,t){return Gu(e).getBigUint64(t,!0)},put(e,t,n){return Gu(e).setBigUint64(t,n,!0),t+8}};var $u=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){return Iu(e.subarray(t,t+this.len),this.encoding)}},ed=class extends Error{constructor(){super(`End-Of-Stream`),this.name=`EndOfStreamError`}},td=class extends Error{constructor(e=`The operation was aborted`){super(e),this.name=`AbortError`}},nd=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 ed;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 td;let r=await this.readFromStream(e.subarray(n),t);if(r===0)break;n+=r}if(!t&&n<e.length)throw new ed;return n}},rd=class extends nd{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}},id=class extends rd{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}},ad=class extends nd{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 ed;return n}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function od(e){try{let t=e.getReader({mode:`byob`});return t instanceof ReadableStreamDefaultReader?new ad(t):new id(t)}catch(t){if(t instanceof TypeError)return new ad(e.getReader());throw t}}var sd=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 ed;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 ed;return e.get(n,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new ed;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new ed;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()}},cd=class extends sd{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 ed;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 ed)return 0;throw e}if(!n.mayBeLess&&r<n.length)throw new ed}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}},ld=class extends sd{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 ed;return e.set(this.uint8Array.subarray(n.position,n.position+r)),r}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}},ud=class extends sd{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 ed;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 dd(e,t){let n=od(e),r=t??{},i=r.onClose;return r.onClose=async()=>{if(await n.close(),i)return i()},new cd(n,r)}function fd(e,t){return new ld(e,t)}function pd(e,t){return new ud(e,t)}var md=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`:``)}})),hd=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=md(),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})),gd=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=hd()(e);let{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})),_d=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)}})),vd=n(((e,n)=>{let r=t(`os`),i=t(`tty`),a=_d(),{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)))}})),yd=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=vd();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(`
20
21
  `).join(`
21
22
  `+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)+`
22
- `)}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=od()(e);let{formatters:f}=n.exports;f.o=function(e){return this.inspectOpts.colors=this.useColors,i.inspect(e,this.inspectOpts).split(`
23
- `).map(e=>e.trim()).join(` `)},f.O=function(e){return this.inspectOpts.colors=this.useColors,i.inspect(e,this.inspectOpts)}})),dd=n(((e,t)=>{typeof process>`u`||process.type===`renderer`||process.browser===!0||process.__nwjs?t.exports=sd():t.exports=ud()}));const fd={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},pd={get(e){return{signature:Bu.get(e,0),compressedSize:Bu.get(e,8),uncompressedSize:Bu.get(e,12)}},len:16},md={get(e){let t=Ru.get(e,6);return{signature:Bu.get(e,0),minVersion:Ru.get(e,4),dataDescriptor:!!(t&8),compressedMethod:Ru.get(e,8),compressedSize:Bu.get(e,18),uncompressedSize:Bu.get(e,22),filenameLength:Ru.get(e,26),extraFieldLength:Ru.get(e,28),filename:null}},len:30},hd={get(e){return{signature:Bu.get(e,0),nrOfThisDisk:Ru.get(e,4),nrOfThisDiskWithTheStart:Ru.get(e,6),nrOfEntriesOnThisDisk:Ru.get(e,8),nrOfEntriesOfSize:Ru.get(e,10),sizeOfCd:Bu.get(e,12),offsetOfStartOfCd:Bu.get(e,16),zipFileCommentLength:Ru.get(e,20)}},len:22},gd={get(e){let t=Ru.get(e,8);return{signature:Bu.get(e,0),minVersion:Ru.get(e,6),dataDescriptor:!!(t&8),compressedMethod:Ru.get(e,10),compressedSize:Bu.get(e,20),uncompressedSize:Bu.get(e,24),filenameLength:Ru.get(e,28),extraFieldLength:Ru.get(e,30),fileCommentLength:Ru.get(e,32),relativeOffsetOfLocalHeader:Bu.get(e,42),filename:null}},len:46};var _d=e(dd(),1);function vd(e){let t=new Uint8Array(Bu.len);return Bu.put(t,0,e),t}const yd=(0,_d.default)(`tokenizer:inflate`),bd=256*1024,xd=vd(fd.DataDescriptor),Sd=vd(fd.EndOfCentralDirectory);var Cd=class e{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(bd)}async isZip(){return await this.peekSignature()===fd.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(Bu)}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]===Sd[0]&&n[r+1]===Sd[1]&&n[r+2]===Sd[2]&&n[r+3]===Sd[3])return e.fileInfo.size-t+r;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){yd(`Cannot reading central-directory without random-read support`);return}yd(`Reading central-directory...`);let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){yd(`Central-directory 32-bit signature found`);let n=await this.tokenizer.readToken(hd,t),r=[];this.tokenizer.setPosition(n.offsetOfStartOfCd);for(let e=0;e<n.nrOfEntriesOfSize;++e){let t=await this.tokenizer.readToken(gd);if(t.signature!==fd.CentralFileHeader)throw Error(`Expected Central-File-Header signature`);t.filename=await this.tokenizer.readToken(new Wu(t.filenameLength,`utf-8`)),await this.tokenizer.ignore(t.extraFieldLength),await this.tokenizer.ignore(t.fileCommentLength),r.push(t),yd(`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=bd;yd(`Compressed-file-size unknown, scanning for next data-descriptor-signature....`);let i=-1;for(;i<0&&n===bd;){n=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),i=wd(this.syncBuffer.subarray(0,n),xd);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)}yd(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),r.handler&&await this.inflate(t,Td(e),r.handler)}else r.handler?(yd(`Reading compressed-file-data: ${t.compressedSize} bytes`),i=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(i),await this.inflate(t,i,r.handler)):(yd(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(yd(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor&&(await this.tokenizer.readToken(pd)).signature!==134695760)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-pd.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 yd(`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(Bu);if(e===fd.LocalFileHeader){let e=await this.tokenizer.readToken(md);return e.filename=await this.tokenizer.readToken(new Wu(e.filenameLength,`utf-8`)),e}if(e===fd.CentralFileHeader)return!1;throw Error(e===3759263696?`Encrypted ZIP`:`Unexpected signature`)}};function wd(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 Td(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 Ed=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 Dd=Object.prototype.toString;function Od(e,t,n){return e?e.constructor===t?!0:Dd.call(e)===n:!1}function kd(e){return Od(e,Uint8Array,`[object Uint8Array]`)}function Ad(e){if(!kd(e))throw TypeError(`Expected \`Uint8Array\`, got \`${typeof e}\``)}function jd(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)Ad(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 Md(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 Nd(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 Pd(e,t=0){let n=Number.parseInt(new Wu(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 Fd={get:(e,t)=>e[t+3]&127|(e[t+2]&127)<<7|(e[t+1]&127)<<14|(e[t]&127)<<21,len:4},Id=`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(`,`),Ld=`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(`,`),Rd=16*1024*1024;var zd=class extends Error{};function Bd(e,t,n){if(!Number.isFinite(e)||e<0||e>t)throw new zd(`${n} has invalid size ${e} (maximum ${t} bytes)`);return e}async function Vd(e,t,{maximumLength:n=Rd,reason:r=`skip`}={}){let i=Bd(t,n,r);await e.ignore(i)}async function Hd(e,t,n,{maximumLength:r=t.length,reason:i=`read`}={}){let a=Bd(n?.length??t.length,r,i);return e.readBuffer(t,{...n,length:a})}function Ud(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 Wd(e){let t=e.fileInfo.size;return!Number.isFinite(t)||t===2**53-1}function Gd(e,t,n){return Wd(e)&&e.position-t>n}const Kd=1024*1024,qd=1024,Jd=2**31-1,Yd=Kd,Xd=new Set([`Unexpected signature`,`Encrypted ZIP`,`Expected Central-File-Header signature`]),Zd=[`ZIP entry count exceeds `,`Unsupported ZIP compression method:`,`ZIP entry compressed data exceeds `,`ZIP entry decompressed data exceeds `,`Expected data-descriptor-signature at position `],Qd=new Set([`Z_BUF_ERROR`,`Z_DATA_ERROR`,`ERR_INVALID_STATE`]);async function $d(e,{maximumLength:t=Kd}={}){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 ef(e,t){let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function tf(e){let t=e.fileInfo.size,n=Number.isFinite(t)?Math.max(0,t-e.position):2**53-1;return Math.min(n,Jd)}function nf(e){if(e instanceof Gu||e instanceof zd)return!0;if(!(e instanceof Error))return!1;if(Xd.has(e.message)||Qd.has(e.code))return!0;for(let t of Zd)if(e.message.startsWith(t))return!0;return!1}function rf(e,t=Kd){let n=[e.compressedSize,e.uncompressedSize];for(let e of n)if(!Number.isFinite(e)||e<0||e>t)return!1;return!0}function af(){return{hasDocumentEntry:!1,hasMasterSlideEntry:!1,hasTablesEntry:!1,hasCalculationEngineEntry:!1}}function of(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 sf(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 cf(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 lf(){return{hasContentTypesEntry:!1,hasParsedContentTypesEntry:!1,isParsingContentTypes:!1,hasUnparseableContentTypes:!1,hasWordDirectory:!1,hasPresentationDirectory:!1,hasSpreadsheetDirectory:!1,hasThreeDimensionalModelEntry:!1}}function uf(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 df(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 ff(e){if(!(!e.hasContentTypesEntry||e.hasUnparseableContentTypes||e.isParsingContentTypes||e.hasParsedContentTypesEntry))return df(e)}function pf(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 mf=134695760;function hf(e,t){if(e.length<16)return-1;let n=e.length-16;for(let r=0;r<=n;r++)if(Bu.get(e,r)===mf&&Bu.get(e,r+8)===t+r)return r;return-1}async function gf(e,{shouldBuffer:t,maximumLength:n=Kd}={}){let{syncBuffer:r}=e,{length:i}=r,a=[],o=0;for(;;){let s=await e.tokenizer.peekBuffer(r,{mayBeLess:!0}),c=hf(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(Wd(e.tokenizer)||(e.knownSizeDescriptorScannedBytes+=o),t)return ef(a,o)}function _f(e,t){return Wd(e.tokenizer)?Math.max(0,Rd-(e.tokenizer.position-t)):Math.max(0,Kd-e.knownSizeDescriptorScannedBytes)}async function vf(e,t,{shouldBuffer:n,maximumDescriptorLength:r=Kd}={}){if(t.dataDescriptor&&t.compressedSize===0)return gf(e,{shouldBuffer:n,maximumLength:r});if(!n){await Vd(e.tokenizer,t.compressedSize,{maximumLength:Wd(e.tokenizer)?Kd:e.tokenizer.fileInfo.size,reason:`ZIP entry compressed data`});return}let i=tf(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}Cd.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 $d(t,{maximumLength:Kd}))},Cd.prototype.unzip=async function(e){let t=!1,n=0,r=this.tokenizer.position;this.knownSizeDescriptorScannedBytes=0;do{if(Gd(this.tokenizer,r,16777216))throw new zd(`ZIP stream probing exceeds ${Rd} bytes`);let i=await this.readLocalFileHeader();if(!i)break;if(n++,n>qd)throw Error(`ZIP entry count exceeds ${qd}`);let a=e(i);t=!!a.stop,await this.tokenizer.ignore(i.extraFieldLength);let o=await vf(this,i,{shouldBuffer:!!a.handler,maximumDescriptorLength:Math.min(Kd,_f(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),Bu.get(e,0)!==mf)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-e.length}`)}if(Gd(this.tokenizer,r,16777216))throw new zd(`ZIP stream probing exceeds ${Rd} bytes`)}while(!t)};async function yf(e){let t,n=lf(),r=af();try{await new Cd(e).unzip(e=>{if(uf(n,e.filename),of(r,e.filename),r.hasDocumentEntry&&(r.hasMasterSlideEntry||r.hasTablesEntry))return t=sf(r),{stop:!0};let i=e.filename===`[Content_Types].xml`,a=ff(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 rf(e,Yd)?{async handler(e){t=cf(new TextDecoder(`utf-8`).decode(e).trim())},stop:!0}:{};case`[Content_Types].xml`:return n.hasContentTypesEntry=!0,rf(e,Yd)?(n.isParsingContentTypes=!0,{async handler(e){let r=pf(new TextDecoder(`utf-8`).decode(e));r&&(t=cf(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(!nf(e))throw e;n.isParsingContentTypes&&(n.isParsingContentTypes=!1,n.hasUnparseableContentTypes=!0),!t&&e instanceof Gu&&!n.hasContentTypesEntry&&(t=df(n))}let i=Wd(e)&&r.hasDocumentEntry&&!r.hasMasterSlideEntry&&!r.hasTablesEntry&&!r.hasCalculationEngineEntry?void 0:sf(r);return t??ff(n)??i??{ext:`zip`,mime:`application/zip`}}const bf=1024*1024;async function xf(e){async function t(){let t=await e.peekNumber(Lu),n=128,r=0;for(;(t&n)===0&&n!==0;)++r,n>>=1;let i=new Uint8Array(r+1);return await Hd(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:Md(i),len:Md(a)}}async function r(t){let r=0;for(;t>0;){if(r++,r>256||Gd(e,a,16777216))return;let i=e.position,o=await n();if(o.id===17026){if(o.len>64)return;let t=Bd(o.len,64,`EBML DocType`);return(await e.readToken(new Wu(t))).replaceAll(/\0.*$/gv,``)}if(Wd(e)&&(!Number.isFinite(o.len)||o.len<0||o.len>bf)||(await Vd(e,o.len,{maximumLength:Wd(e)?bf: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 Sf=1024*1024;function Cf(e){return(e.codePointAt(0)&32)!=0}async function wf(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(Hu),type:await e.readToken(new Wu(4,`latin1`))}}let i=Wd(e),a=e.position,o=0,s=!1;do{if(o++,o>512||Gd(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>Sf)return s&&Cf(l.type)?t:void 0;try{await Vd(e,l.length+4,{maximumLength:i?Sf+4:e.fileInfo.size,reason:`PNG chunk payload`})}catch(e){if(!i&&(e instanceof zd||e instanceof Gu))return t;throw e}}if(e.position<=c)break}while(e.position+8<e.fileInfo.size);return t}const Tf=1024*1024;async function Ef(e){let t=!1;try{async function n(){let t=new Uint8Array(16);return await Hd(e,t,void 0,{maximumLength:t.length,reason:`ASF header GUID`}),{id:t,size:Number(await e.readToken(Uu))}}await Vd(e,30,{maximumLength:30,reason:`ASF header prelude`});let r=Wd(e),i=e.position,a=0;for(;e.position+24<e.fileInfo.size&&(a++,!(a>512||Gd(e,i,16777216)));){let i=e.position,a=await n(),o=a.size-24;if(!Number.isFinite(o)||o<0){t=!0;break}if(Ud(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 Hd(e,t,void 0,{maximumLength:t.length,reason:`ASF stream type GUID`}),Ud(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(Ud(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>Tf){t=!0;break}if(await Vd(e,o,{maximumLength:r?Tf:e.fileInfo.size,reason:`ASF header payload`}),e.position<=i){t=!0;break}}}catch(n){if(n instanceof Gu||n instanceof zd)Wd(e)&&(t=!0);else throw n}if(!t)return{ext:`asf`,mime:`application/vnd.ms-asf`}}const Df=4100;Df-2;const Of=Rd,kf=Rd;function Af(e){return Number.isFinite(e)?Math.max(1,Math.trunc(e)):Df}function jf(e){return Number.isFinite(e)?Math.max(0,Math.min(4098,Math.trunc(e))):0}function Mf(e){return Number.isFinite(e)?Math.max(0,e):2**53-1}function Nf(e){return import(e)}function Pf(e){return e.pipeThrough(new TransformStream)}function Ff(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 If(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 Lf(e,t){return new Rf(t).fromBuffer(e)}var Rf=class e{constructor(e){let t=jf(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 nd(Pf(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 Gu||e instanceof zd)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(rd(t,this.getTokenizerOptions()))}async fromBlob(e){this.options.signal?.throwIfAborted();let t=id(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([Nf(`node:fs/promises`),Nf(`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=Af(t?.sampleSize??4100),r,i=!1,a=e.getReader(),o=[],s=0;try{for(;s<n;){let{value:e,done:t}=await Ff(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 Ff(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]:jd(o);try{r=await this.fromBuffer(e.subarray(0,n))}catch(e){if(!(e instanceof Gu))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=If(new Ed(t).inflate(),16777216),r=Wd(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 Ud(this.buffer,e,t)}checkString(e,t){return this.check(Nd(e,t?.encoding),t)}detectConfident=async e=>{if(this.buffer=new Uint8Array(Df),e.fileInfo.size===void 0&&(e.fileInfo.size=2**53-1),this.tokenizer=e,Wd(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 Vd(e,6,{maximumLength:6,reason:`ID3 header prefix`});let t=await e.readToken(Fd),n=Wd(e);if(!Number.isFinite(t)||t<0||n&&(t>Of||e.position+t>Of))return;if(e.position+t>e.fileInfo.size)return n?void 0:{ext:`mp3`,mime:`audio/mpeg`};try{await Vd(e,t,{maximumLength:n?Of:e.fileInfo.size,reason:`ID3 payload`})}catch(e){if(e instanceof Gu)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 yf(e);if(this.checkString(`OggS`)){await e.ignore(28);let t=new Uint8Array(8);return await e.readBuffer(t),Ud(t,[79,112,117,115,72,101,97,100])?{ext:`opus`,mime:`audio/ogg; codecs=opus`}:Ud(t,[128,116,104,101,111,114,97])?{ext:`ogv`,mime:`video/ogg`}:Ud(t,[1,118,105,100,101,111,0])?{ext:`ogm`,mime:`video/ogg`}:Ud(t,[127,70,76,65,67])?{ext:`oga`,mime:`audio/ogg`}:Ud(t,[83,112,101,101,120,32,32])?{ext:`spx`,mime:`audio/ogg`}:Ud(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 xf(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=Vu.get(this.buffer,4),t=zu.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 Wu(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 Wu(13,`ascii`))===`debian-binary`?{ext:`deb`,mime:`application/x-deb`}:{ext:`ar`,mime:`application/x-unix-archive`};if(this.checkString(`WEBVTT`)&&[`
24
- `,`\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 wf(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 Wu(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
25
- `))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 Ef(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 Wu(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})&&Pd(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
26
- `,{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(Df);let t=Mf(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?zu:Ru);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?zu:Ru);if(!(t>512)&&!(Wd(this.tokenizer)&&2+t*12>kf))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?zu:Ru).get(this.buffer,2),r=(e?Vu:Bu).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?zu:Ru).get(this.buffer,8),n=(e?zu:Ru).get(this.buffer,10);if(t===28&&n===254||t===31&&n===11)return{ext:`nef`,mime:`image/x-nikon-nef`}}}if(Wd(this.tokenizer)&&r>1048576)return t;let n=Wd(this.tokenizer)?kf:this.tokenizer.fileInfo.size;try{await Vd(this.tokenizer,r,{maximumLength:n,reason:`TIFF IFD offset`})}catch(e){if(e instanceof Gu)return;throw e}let i;try{i=await this.readTiffIFD(e)}catch(e){if(e instanceof Gu)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(Id),new Set(Ld);let zf=0;const Bf=Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})});function Vf(e,t,n,r){let i=e.doc;if(!i)return;let a=++zf,o=i.getMap(`agent-effects`),s=l=>{e.unobserve(s),i.off(`destroy`,c);let u=`${t}:${a}`,d={sessionId:t,timestamp:Date.now(),delta:l.delta,agent_type:r??`agent`,color_seed:n??t};try{i.transact(()=>{if(o.set(u,d),o.size>50){let e=[...o.entries()].sort((e,t)=>e[1].timestamp-t[1].timestamp);for(let[t]of e.slice(0,o.size-50))o.delete(t)}},Bf)}catch(e){let n=e instanceof Error?e.message:String(e);if(console.warn(JSON.stringify({event:`effect-diff-capture-failed`,sessionId:t,reason:n})),Pn(),process.env.NODE_ENV!==`production`)throw e}},c=()=>{e.unobserve(s)};e.observe(s),i.once(`destroy`,c)}let Hf=new Map;function Uf(e,t,n,r,i,a){let o=Hf.get(t);if(o||(o={writerId:t,displayName:n,colorSeed:r??n,docs:new Set,subjectOverride:i,actor:a},Hf.set(t,o)),o.docs.add(e),i!==void 0&&(o.subjectOverride=i),a!==void 0){let e=o.actor??{};a.principalId!==void 0&&(e.principalId=a.principalId),a.agentType!==void 0&&(e.agentType=a.agentType),a.clientName!==void 0&&(e.clientName=a.clientName),a.clientVersion!==void 0&&(e.clientVersion=a.clientVersion),a.label!==void 0&&(e.label=a.label),o.actor=e}}function Wf(){let e=Hf;return Hf=new Map,e}function Gf(e){for(let[t,n]of e){let e=Hf.get(t);e||(e={writerId:t,displayName:n.displayName,colorSeed:n.colorSeed,docs:new Set,actor:n.actor},Hf.set(t,e));for(let t of n.docs)e.docs.add(t)}}function Kf(e,t){let n=Hf.get(e);n||(n={writerId:e,displayName:t.displayName,colorSeed:t.colorSeed,docs:new Set,actor:t.actor},Hf.set(e,n));for(let e of t.docs)n.docs.add(e)}function qf(){return Hf.size}function Jf(e){return Hf.has(e)}const Yf=[`claude`,`codex`,`cursor`],Xf=2e3,Zf={claude:[`Claude`],codex:[`Codex`,`OpenAI Codex`],cursor:[`Cursor`]};function Qf(e){let t=new Map,n=e.now??Date.now,r=e.ttlMs??6e4;async function i(i){let a=t.get(i);if(a?.status===`resolved`&&a.expiresAt>n())return a.installed;if(a?.status===`inflight`)return a.promise;let o=(async()=>{try{let a=await e.probe(i);return t.set(i,{status:`resolved`,installed:a,expiresAt:n()+r}),a}catch{return t.set(i,{status:`resolved`,installed:!1,expiresAt:n()+r}),!1}})();return t.set(i,{status:`inflight`,promise:o}),o}async function a(){let e=await Promise.all(Yf.map(async e=>[e,await i(e)]));return Object.fromEntries(e)}return{probeAll:a,probeWithCache:i}}async function $f(e,t,n){if(e.method!==`GET`){ep(t,405,{error:`Method not allowed`});return}try{ep(t,200,await n())}catch(e){console.error(`[installed-agents]`,e),ep(t,500,{error:`Internal server error`})}}function ep(e,t,n){e.writeHead(t,{"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`}),e.end(JSON.stringify(n))}function tp(e,t=Me){return n=>e===`darwin`?np(n,t):e===`win32`?rp(n,t):ip(n,t)}function np(e,t){let n=Zf[e];function r(e){return new Promise(n=>{t(`osascript`,[`-e`,`id of app "${e}"`],{timeout:Xf,encoding:`utf-8`},(e,t)=>{if(e){n(!1);return}n(t.trim().length>0)})})}return(async()=>{for(let e of n)if(await r(e))return!0;return!1})()}function rp(e,t){return new Promise(n=>{t(`reg`,[`query`,`HKCR\\${e}`,`/ve`],{timeout:Xf,encoding:`utf-8`},e=>{n(!e)})})}function ip(e,t){return new Promise(n=>{t(`xdg-mime`,[`query`,`default`,`x-scheme-handler/${e}`],{timeout:Xf,encoding:`utf-8`},(e,t)=>{if(e){n(!1);return}n(t.trim().length>0)})})}const ap=[`INDEX`,`README`,`REPORT`,`SPEC`];function op(e,t){let n=[],r=new Set,i=t=>{!t||r.has(t)||t!==e&&(r.add(t),n.push(t))},a=cp(t),o=lp(e);for(;;){for(let e of ap)if(i(sp(t,a,dp(o,e))),n.length>=3)return n;let e=o===``?null:up(o);if(e&&(i(sp(t,a,dp(o,e))),n.length>=3))return n;if(o===``)break;o=lp(o)}return n}function sp(e,t,n){return e.has(n)?n:t.get(n.toLowerCase())??null}function cp(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 lp(e){let t=e.lastIndexOf(`/`);return t<0?``:e.slice(0,t)}function up(e){let t=e.lastIndexOf(`/`);return t<0?e:e.slice(t+1)}function dp(e,t){return e===``?t:`${e}/${t}`}function fp(e){return e?e.replace(/^---\r?\n/,``).replace(/\r?\n---(?:\r?\n)?$/,``).split(/\r?\n/):[]}function pp(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1).trim():t}function mp(e,t){let n=`${t}:`;for(let t of fp(e))if(t.startsWith(n))return pp(t.slice(n.length))||null;return null}function hp(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=pp(n);e&&t.push(e),n=``;continue}n+=i}let i=pp(n);return i&&t.push(i),t}function gp(e){let t=[],n=new Set;for(let r of e)!r||n.has(r)||(n.add(r),t.push(r));return t}function _p(e){let{frontmatter:t}=l(e);if(!t)return[];let n=fp(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 gp(hp(r.slice(1,-1)));let e=pp(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=pp(e.replace(/^\s*-\s+/,``));t&&i.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return gp(i)}return[]}function vp(e,t){let{frontmatter:n,body:r}=l(e),i=mp(n,`title`);if(i)return i;let a=r.match(/^# (.+)$/m);return a?a[1].trim():t}function yp(e){return e?.trim()?{cluster:mp(e,`cluster`)??void 0,category:mp(e,`category`)??void 0,tags:bp(e,`tags`)}:{cluster:void 0,category:void 0,tags:void 0}}function bp(e,t){let n=`${t}:`,r=fp(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=hp(i.slice(1,-1));return e.length>0?e:void 0}let e=pp(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=pp(e.replace(/^\s*-\s+/,``));t&&a.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return a.length>0?a:void 0}}function xp(e,t){let n=vp(e,t),r=_p(e),i=gp([n,...r]),a=[],o=new Set;for(let e of i){let t=_(e);!t||o.has(t)||(o.add(t),a.push(t))}return{docName:t,title:n,aliases:r,matchLabels:i,normalizedMatchLabels:a}}var Sp=class extends F{constructor(e,t){super(e,t,`ui`),this.name=`UiLockCollisionError`}};function Cp(e,t){try{return ae({lockName:`ui`,lockDir:e,metadata:t}).lockPath}catch(e){throw e instanceof F&&e.lockName===`ui`?new Sp(e.existing,e.lockPath):e}}function wp(e,t){P({lockName:`ui`,lockDir:e,port:t})}function Tp(e){return ne({lockName:`ui`,lockDir:e})}function Ep(e){I({lockName:`ui`,lockDir:e})}const Dp=[`.mdx`,`.md`];function Op(e){let t=Ce(e).toLowerCase();return Dp.includes(t)}function kp(e){let t=e.toLowerCase();for(let n of Dp)if(t.endsWith(n))return e.slice(0,-n.length);return e}function Ap(e){return Dp.indexOf(e)}const jp=new Map;function Mp(e,t){let n=jp.get(e);return n?n===t?{effective:n,changed:!1,shadowed:null}:Ap(t)<Ap(n)?(jp.set(e,t),{effective:t,changed:!0,shadowed:n}):{effective:n,changed:!1,shadowed:t}:(jp.set(e,t),{effective:t,changed:!0,shadowed:null})}function Np(e){return jp.get(e)??`.md`}function Pp(e){jp.delete(e)}const Fp=/\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/y,Ip=/\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y;function Lp(){return{backward:new Map,forward:new Map,externalForward:new Map,externalBackward:new Map}}function Rp(e,t){return e?{anchor:e.anchor??t.anchor,snippet:e.snippet??t.snippet}:t}function zp(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 Bp(e){return`external:${e}`}function Vp(e){return e.startsWith(`external:`)?e.slice(9):null}function Hp(e){return e.replace(/\s+/g,` `).trim()}function Up(e,t,n){if(!Hp(e))return null;let r=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
23
+ `)}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=hd()(e);let{formatters:f}=n.exports;f.o=function(e){return this.inspectOpts.colors=this.useColors,i.inspect(e,this.inspectOpts).split(`
24
+ `).map(e=>e.trim()).join(` `)},f.O=function(e){return this.inspectOpts.colors=this.useColors,i.inspect(e,this.inspectOpts)}})),bd=n(((e,t)=>{typeof process>`u`||process.type===`renderer`||process.browser===!0||process.__nwjs?t.exports=gd():t.exports=yd()}));const xd={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},Sd={get(e){return{signature:Yu.get(e,0),compressedSize:Yu.get(e,8),uncompressedSize:Yu.get(e,12)}},len:16},Cd={get(e){let t=qu.get(e,6);return{signature:Yu.get(e,0),minVersion:qu.get(e,4),dataDescriptor:!!(t&8),compressedMethod:qu.get(e,8),compressedSize:Yu.get(e,18),uncompressedSize:Yu.get(e,22),filenameLength:qu.get(e,26),extraFieldLength:qu.get(e,28),filename:null}},len:30},wd={get(e){return{signature:Yu.get(e,0),nrOfThisDisk:qu.get(e,4),nrOfThisDiskWithTheStart:qu.get(e,6),nrOfEntriesOnThisDisk:qu.get(e,8),nrOfEntriesOfSize:qu.get(e,10),sizeOfCd:Yu.get(e,12),offsetOfStartOfCd:Yu.get(e,16),zipFileCommentLength:qu.get(e,20)}},len:22},Td={get(e){let t=qu.get(e,8);return{signature:Yu.get(e,0),minVersion:qu.get(e,6),dataDescriptor:!!(t&8),compressedMethod:qu.get(e,10),compressedSize:Yu.get(e,20),uncompressedSize:Yu.get(e,24),filenameLength:qu.get(e,28),extraFieldLength:qu.get(e,30),fileCommentLength:qu.get(e,32),relativeOffsetOfLocalHeader:Yu.get(e,42),filename:null}},len:46};var Ed=e(bd(),1);function Dd(e){let t=new Uint8Array(Yu.len);return Yu.put(t,0,e),t}const Od=(0,Ed.default)(`tokenizer:inflate`),kd=256*1024,Ad=Dd(xd.DataDescriptor),jd=Dd(xd.EndOfCentralDirectory);var Md=class e{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(kd)}async isZip(){return await this.peekSignature()===xd.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(Yu)}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]===jd[0]&&n[r+1]===jd[1]&&n[r+2]===jd[2]&&n[r+3]===jd[3])return e.fileInfo.size-t+r;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){Od(`Cannot reading central-directory without random-read support`);return}Od(`Reading central-directory...`);let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){Od(`Central-directory 32-bit signature found`);let n=await this.tokenizer.readToken(wd,t),r=[];this.tokenizer.setPosition(n.offsetOfStartOfCd);for(let e=0;e<n.nrOfEntriesOfSize;++e){let t=await this.tokenizer.readToken(Td);if(t.signature!==xd.CentralFileHeader)throw Error(`Expected Central-File-Header signature`);t.filename=await this.tokenizer.readToken(new $u(t.filenameLength,`utf-8`)),await this.tokenizer.ignore(t.extraFieldLength),await this.tokenizer.ignore(t.fileCommentLength),r.push(t),Od(`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=kd;Od(`Compressed-file-size unknown, scanning for next data-descriptor-signature....`);let i=-1;for(;i<0&&n===kd;){n=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),i=Nd(this.syncBuffer.subarray(0,n),Ad);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)}Od(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),r.handler&&await this.inflate(t,Pd(e),r.handler)}else r.handler?(Od(`Reading compressed-file-data: ${t.compressedSize} bytes`),i=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(i),await this.inflate(t,i,r.handler)):(Od(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(Od(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor&&(await this.tokenizer.readToken(Sd)).signature!==134695760)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-Sd.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 Od(`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(Yu);if(e===xd.LocalFileHeader){let e=await this.tokenizer.readToken(Cd);return e.filename=await this.tokenizer.readToken(new $u(e.filenameLength,`utf-8`)),e}if(e===xd.CentralFileHeader)return!1;throw Error(e===3759263696?`Encrypted ZIP`:`Unexpected signature`)}};function Nd(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 Pd(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 Fd=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 Id=Object.prototype.toString;function Ld(e,t,n){return e?e.constructor===t?!0:Id.call(e)===n:!1}function Rd(e){return Ld(e,Uint8Array,`[object Uint8Array]`)}function zd(e){if(!Rd(e))throw TypeError(`Expected \`Uint8Array\`, got \`${typeof e}\``)}function Bd(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)zd(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 Vd(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 Hd(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 Ud(e,t=0){let n=Number.parseInt(new $u(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 Wd={get:(e,t)=>e[t+3]&127|(e[t+2]&127)<<7|(e[t+1]&127)<<14|(e[t]&127)<<21,len:4},Gd=`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(`,`),Kd=`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(`,`),qd=16*1024*1024;var Jd=class extends Error{};function Yd(e,t,n){if(!Number.isFinite(e)||e<0||e>t)throw new Jd(`${n} has invalid size ${e} (maximum ${t} bytes)`);return e}async function Xd(e,t,{maximumLength:n=qd,reason:r=`skip`}={}){let i=Yd(t,n,r);await e.ignore(i)}async function Zd(e,t,n,{maximumLength:r=t.length,reason:i=`read`}={}){let a=Yd(n?.length??t.length,r,i);return e.readBuffer(t,{...n,length:a})}function Qd(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 $d(e){let t=e.fileInfo.size;return!Number.isFinite(t)||t===2**53-1}function ef(e,t,n){return $d(e)&&e.position-t>n}const tf=1024*1024,nf=1024,rf=2**31-1,af=tf,of=new Set([`Unexpected signature`,`Encrypted ZIP`,`Expected Central-File-Header signature`]),sf=[`ZIP entry count exceeds `,`Unsupported ZIP compression method:`,`ZIP entry compressed data exceeds `,`ZIP entry decompressed data exceeds `,`Expected data-descriptor-signature at position `],cf=new Set([`Z_BUF_ERROR`,`Z_DATA_ERROR`,`ERR_INVALID_STATE`]);async function lf(e,{maximumLength:t=tf}={}){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 uf(e,t){let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function df(e){let t=e.fileInfo.size,n=Number.isFinite(t)?Math.max(0,t-e.position):2**53-1;return Math.min(n,rf)}function ff(e){if(e instanceof ed||e instanceof Jd)return!0;if(!(e instanceof Error))return!1;if(of.has(e.message)||cf.has(e.code))return!0;for(let t of sf)if(e.message.startsWith(t))return!0;return!1}function pf(e,t=tf){let n=[e.compressedSize,e.uncompressedSize];for(let e of n)if(!Number.isFinite(e)||e<0||e>t)return!1;return!0}function mf(){return{hasDocumentEntry:!1,hasMasterSlideEntry:!1,hasTablesEntry:!1,hasCalculationEngineEntry:!1}}function hf(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 gf(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 _f(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 vf(){return{hasContentTypesEntry:!1,hasParsedContentTypesEntry:!1,isParsingContentTypes:!1,hasUnparseableContentTypes:!1,hasWordDirectory:!1,hasPresentationDirectory:!1,hasSpreadsheetDirectory:!1,hasThreeDimensionalModelEntry:!1}}function yf(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 bf(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 xf(e){if(!(!e.hasContentTypesEntry||e.hasUnparseableContentTypes||e.isParsingContentTypes||e.hasParsedContentTypesEntry))return bf(e)}function Sf(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 Cf=134695760;function wf(e,t){if(e.length<16)return-1;let n=e.length-16;for(let r=0;r<=n;r++)if(Yu.get(e,r)===Cf&&Yu.get(e,r+8)===t+r)return r;return-1}async function Tf(e,{shouldBuffer:t,maximumLength:n=tf}={}){let{syncBuffer:r}=e,{length:i}=r,a=[],o=0;for(;;){let s=await e.tokenizer.peekBuffer(r,{mayBeLess:!0}),c=wf(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($d(e.tokenizer)||(e.knownSizeDescriptorScannedBytes+=o),t)return uf(a,o)}function Ef(e,t){return $d(e.tokenizer)?Math.max(0,qd-(e.tokenizer.position-t)):Math.max(0,tf-e.knownSizeDescriptorScannedBytes)}async function Df(e,t,{shouldBuffer:n,maximumDescriptorLength:r=tf}={}){if(t.dataDescriptor&&t.compressedSize===0)return Tf(e,{shouldBuffer:n,maximumLength:r});if(!n){await Xd(e.tokenizer,t.compressedSize,{maximumLength:$d(e.tokenizer)?tf:e.tokenizer.fileInfo.size,reason:`ZIP entry compressed data`});return}let i=df(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}Md.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 lf(t,{maximumLength:tf}))},Md.prototype.unzip=async function(e){let t=!1,n=0,r=this.tokenizer.position;this.knownSizeDescriptorScannedBytes=0;do{if(ef(this.tokenizer,r,16777216))throw new Jd(`ZIP stream probing exceeds ${qd} bytes`);let i=await this.readLocalFileHeader();if(!i)break;if(n++,n>nf)throw Error(`ZIP entry count exceeds ${nf}`);let a=e(i);t=!!a.stop,await this.tokenizer.ignore(i.extraFieldLength);let o=await Df(this,i,{shouldBuffer:!!a.handler,maximumDescriptorLength:Math.min(tf,Ef(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),Yu.get(e,0)!==Cf)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-e.length}`)}if(ef(this.tokenizer,r,16777216))throw new Jd(`ZIP stream probing exceeds ${qd} bytes`)}while(!t)};async function Of(e){let t,n=vf(),r=mf();try{await new Md(e).unzip(e=>{if(yf(n,e.filename),hf(r,e.filename),r.hasDocumentEntry&&(r.hasMasterSlideEntry||r.hasTablesEntry))return t=gf(r),{stop:!0};let i=e.filename===`[Content_Types].xml`,a=xf(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 pf(e,af)?{async handler(e){t=_f(new TextDecoder(`utf-8`).decode(e).trim())},stop:!0}:{};case`[Content_Types].xml`:return n.hasContentTypesEntry=!0,pf(e,af)?(n.isParsingContentTypes=!0,{async handler(e){let r=Sf(new TextDecoder(`utf-8`).decode(e));r&&(t=_f(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(!ff(e))throw e;n.isParsingContentTypes&&(n.isParsingContentTypes=!1,n.hasUnparseableContentTypes=!0),!t&&e instanceof ed&&!n.hasContentTypesEntry&&(t=bf(n))}let i=$d(e)&&r.hasDocumentEntry&&!r.hasMasterSlideEntry&&!r.hasTablesEntry&&!r.hasCalculationEngineEntry?void 0:gf(r);return t??xf(n)??i??{ext:`zip`,mime:`application/zip`}}const kf=1024*1024;async function Af(e){async function t(){let t=await e.peekNumber(Ku),n=128,r=0;for(;(t&n)===0&&n!==0;)++r,n>>=1;let i=new Uint8Array(r+1);return await Zd(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:Vd(i),len:Vd(a)}}async function r(t){let r=0;for(;t>0;){if(r++,r>256||ef(e,a,16777216))return;let i=e.position,o=await n();if(o.id===17026){if(o.len>64)return;let t=Yd(o.len,64,`EBML DocType`);return(await e.readToken(new $u(t))).replaceAll(/\0.*$/gv,``)}if($d(e)&&(!Number.isFinite(o.len)||o.len<0||o.len>kf)||(await Xd(e,o.len,{maximumLength:$d(e)?kf: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 jf=1024*1024;function Mf(e){return(e.codePointAt(0)&32)!=0}async function Nf(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(Zu),type:await e.readToken(new $u(4,`latin1`))}}let i=$d(e),a=e.position,o=0,s=!1;do{if(o++,o>512||ef(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>jf)return s&&Mf(l.type)?t:void 0;try{await Xd(e,l.length+4,{maximumLength:i?jf+4:e.fileInfo.size,reason:`PNG chunk payload`})}catch(e){if(!i&&(e instanceof Jd||e instanceof ed))return t;throw e}}if(e.position<=c)break}while(e.position+8<e.fileInfo.size);return t}const Pf=1024*1024;async function Ff(e){let t=!1;try{async function n(){let t=new Uint8Array(16);return await Zd(e,t,void 0,{maximumLength:t.length,reason:`ASF header GUID`}),{id:t,size:Number(await e.readToken(Qu))}}await Xd(e,30,{maximumLength:30,reason:`ASF header prelude`});let r=$d(e),i=e.position,a=0;for(;e.position+24<e.fileInfo.size&&(a++,!(a>512||ef(e,i,16777216)));){let i=e.position,a=await n(),o=a.size-24;if(!Number.isFinite(o)||o<0){t=!0;break}if(Qd(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 Zd(e,t,void 0,{maximumLength:t.length,reason:`ASF stream type GUID`}),Qd(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(Qd(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>Pf){t=!0;break}if(await Xd(e,o,{maximumLength:r?Pf:e.fileInfo.size,reason:`ASF header payload`}),e.position<=i){t=!0;break}}}catch(n){if(n instanceof ed||n instanceof Jd)$d(e)&&(t=!0);else throw n}if(!t)return{ext:`asf`,mime:`application/vnd.ms-asf`}}const If=4100;If-2;const Lf=qd,Rf=qd;function zf(e){return Number.isFinite(e)?Math.max(1,Math.trunc(e)):If}function Bf(e){return Number.isFinite(e)?Math.max(0,Math.min(4098,Math.trunc(e))):0}function Vf(e){return Number.isFinite(e)?Math.max(0,e):2**53-1}function Hf(e){return import(e)}function Uf(e){return e.pipeThrough(new TransformStream)}function Wf(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 Gf(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 Kf(e,t){return new qf(t).fromBuffer(e)}var qf=class e{constructor(e){let t=Bf(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 dd(Uf(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 ed||e instanceof Jd)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(fd(t,this.getTokenizerOptions()))}async fromBlob(e){this.options.signal?.throwIfAborted();let t=pd(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([Hf(`node:fs/promises`),Hf(`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=zf(t?.sampleSize??4100),r,i=!1,a=e.getReader(),o=[],s=0;try{for(;s<n;){let{value:e,done:t}=await Wf(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 Wf(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]:Bd(o);try{r=await this.fromBuffer(e.subarray(0,n))}catch(e){if(!(e instanceof ed))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=Gf(new Fd(t).inflate(),16777216),r=$d(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 Qd(this.buffer,e,t)}checkString(e,t){return this.check(Hd(e,t?.encoding),t)}detectConfident=async e=>{if(this.buffer=new Uint8Array(If),e.fileInfo.size===void 0&&(e.fileInfo.size=2**53-1),this.tokenizer=e,$d(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 Xd(e,6,{maximumLength:6,reason:`ID3 header prefix`});let t=await e.readToken(Wd),n=$d(e);if(!Number.isFinite(t)||t<0||n&&(t>Lf||e.position+t>Lf))return;if(e.position+t>e.fileInfo.size)return n?void 0:{ext:`mp3`,mime:`audio/mpeg`};try{await Xd(e,t,{maximumLength:n?Lf:e.fileInfo.size,reason:`ID3 payload`})}catch(e){if(e instanceof ed)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 Of(e);if(this.checkString(`OggS`)){await e.ignore(28);let t=new Uint8Array(8);return await e.readBuffer(t),Qd(t,[79,112,117,115,72,101,97,100])?{ext:`opus`,mime:`audio/ogg; codecs=opus`}:Qd(t,[128,116,104,101,111,114,97])?{ext:`ogv`,mime:`video/ogg`}:Qd(t,[1,118,105,100,101,111,0])?{ext:`ogm`,mime:`video/ogg`}:Qd(t,[127,70,76,65,67])?{ext:`oga`,mime:`audio/ogg`}:Qd(t,[83,112,101,101,120,32,32])?{ext:`spx`,mime:`audio/ogg`}:Qd(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 Af(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=Xu.get(this.buffer,4),t=Ju.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 $u(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 $u(13,`ascii`))===`debian-binary`?{ext:`deb`,mime:`application/x-deb`}:{ext:`ar`,mime:`application/x-unix-archive`};if(this.checkString(`WEBVTT`)&&[`
25
+ `,`\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 Nf(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 $u(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
26
+ `))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 Ff(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 $u(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})&&Ud(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
27
+ `,{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(If);let t=Vf(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?Ju:qu);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?Ju:qu);if(!(t>512)&&!($d(this.tokenizer)&&2+t*12>Rf))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?Ju:qu).get(this.buffer,2),r=(e?Xu:Yu).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?Ju:qu).get(this.buffer,8),n=(e?Ju:qu).get(this.buffer,10);if(t===28&&n===254||t===31&&n===11)return{ext:`nef`,mime:`image/x-nikon-nef`}}}if($d(this.tokenizer)&&r>1048576)return t;let n=$d(this.tokenizer)?Rf:this.tokenizer.fileInfo.size;try{await Xd(this.tokenizer,r,{maximumLength:n,reason:`TIFF IFD offset`})}catch(e){if(e instanceof ed)return;throw e}let i;try{i=await this.readTiffIFD(e)}catch(e){if(e instanceof ed)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(Gd),new Set(Kd);let Jf=0;const Yf=Object.freeze({source:`local`,skipStoreHooks:!0,context:Object.freeze({origin:`effect-capture`,paired:!1})});function Xf(e,t,n,r){let i=e.doc;if(!i)return;let a=++Jf,o=i.getMap(`agent-effects`),s=l=>{e.unobserve(s),i.off(`destroy`,c);let u=`${t}:${a}`,d={sessionId:t,timestamp:Date.now(),delta:l.delta,agent_type:r??`agent`,color_seed:n??t};try{i.transact(()=>{if(o.set(u,d),o.size>50){let e=[...o.entries()].sort((e,t)=>e[1].timestamp-t[1].timestamp);for(let[t]of e.slice(0,o.size-50))o.delete(t)}},Yf)}catch(e){let n=e instanceof Error?e.message:String(e);if(console.warn(JSON.stringify({event:`effect-diff-capture-failed`,sessionId:t,reason:n})),Ln(),process.env.NODE_ENV!==`production`)throw e}},c=()=>{e.unobserve(s)};e.observe(s),i.once(`destroy`,c)}function Zf(e){return e===void 0?{kind:`absent`}:typeof e==`string`?e.length===0||e.trim().length===0?{kind:`absent`}:e.length<=80?{kind:`value`,value:e}:{kind:`value`,value:e.slice(0,79)+`…`,truncatedFrom:e.length}:{kind:`invalid`}}let Qf=new Map;function $f(e,t,n,r,i,a,o){let s=Qf.get(t);if(s||(s={writerId:t,displayName:n,colorSeed:r??n,docs:new Set,subjectOverride:i,actor:a,summaries:[]},Qf.set(t,s)),s.docs.add(e),i!==void 0&&(s.subjectOverride=i),a!==void 0){let e=s.actor??{};a.principalId!==void 0&&(e.principalId=a.principalId),a.agentType!==void 0&&(e.agentType=a.agentType),a.clientName!==void 0&&(e.clientName=a.clientName),a.clientVersion!==void 0&&(e.clientVersion=a.clientVersion),a.label!==void 0&&(e.label=a.label),s.actor=e}typeof o==`string`&&o.length>0&&s.summaries.push(o)}function ep(){let e=Qf;return Qf=new Map,e}function tp(e){for(let[t,n]of e){let e=Qf.get(t);e||(e={writerId:t,displayName:n.displayName,colorSeed:n.colorSeed,docs:new Set,actor:n.actor,summaries:[]},Qf.set(t,e));for(let t of n.docs)e.docs.add(t);n.summaries.length>0&&(e.summaries=[...n.summaries,...e.summaries])}}function np(e,t){let n=Qf.get(e);n||(n={writerId:e,displayName:t.displayName,colorSeed:t.colorSeed,docs:new Set,actor:t.actor,summaries:[]},Qf.set(e,n));for(let e of t.docs)n.docs.add(e);t.summaries.length>0&&(n.summaries=[...t.summaries,...n.summaries])}function rp(){return Qf.size}function ip(e){return Qf.has(e)}const ap=[`claude`,`codex`,`cursor`],op=2e3,sp={claude:[`Claude`],codex:[`Codex`,`OpenAI Codex`],cursor:[`Cursor`]};function cp(e){let t=new Map,n=e.now??Date.now,r=e.ttlMs??6e4;async function i(i){let a=t.get(i);if(a?.status===`resolved`&&a.expiresAt>n())return a.installed;if(a?.status===`inflight`)return a.promise;let o=(async()=>{try{let a=await e.probe(i);return t.set(i,{status:`resolved`,installed:a,expiresAt:n()+r}),a}catch{return t.set(i,{status:`resolved`,installed:!1,expiresAt:n()+r}),!1}})();return t.set(i,{status:`inflight`,promise:o}),o}async function a(){let e=await Promise.all(ap.map(async e=>[e,await i(e)]));return Object.fromEntries(e)}return{probeAll:a,probeWithCache:i}}async function lp(e,t,n){if(e.method!==`GET`){up(t,405,{error:`Method not allowed`});return}try{up(t,200,await n())}catch(e){console.error(`[installed-agents]`,e),up(t,500,{error:`Internal server error`})}}function up(e,t,n){e.writeHead(t,{"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`}),e.end(JSON.stringify(n))}function dp(e,t=Me){return n=>e===`darwin`?fp(n,t):e===`win32`?pp(n,t):mp(n,t)}function fp(e,t){let n=sp[e];function r(e){return new Promise(n=>{t(`osascript`,[`-e`,`id of app "${e}"`],{timeout:op,encoding:`utf-8`},(e,t)=>{if(e){n(!1);return}n(t.trim().length>0)})})}return(async()=>{for(let e of n)if(await r(e))return!0;return!1})()}function pp(e,t){return new Promise(n=>{t(`reg`,[`query`,`HKCR\\${e}`,`/ve`],{timeout:op,encoding:`utf-8`},e=>{n(!e)})})}function mp(e,t){return new Promise(n=>{t(`xdg-mime`,[`query`,`default`,`x-scheme-handler/${e}`],{timeout:op,encoding:`utf-8`},(e,t)=>{if(e){n(!1);return}n(t.trim().length>0)})})}const hp=[`INDEX`,`README`,`REPORT`,`SPEC`];function gp(e,t){let n=[],r=new Set,i=t=>{!t||r.has(t)||t!==e&&(r.add(t),n.push(t))},a=vp(t),o=yp(e);for(;;){for(let e of hp)if(i(_p(t,a,xp(o,e))),n.length>=3)return n;let e=o===``?null:bp(o);if(e&&(i(_p(t,a,xp(o,e))),n.length>=3))return n;if(o===``)break;o=yp(o)}return n}function _p(e,t,n){return e.has(n)?n:t.get(n.toLowerCase())??null}function vp(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 yp(e){let t=e.lastIndexOf(`/`);return t<0?``:e.slice(0,t)}function bp(e){let t=e.lastIndexOf(`/`);return t<0?e:e.slice(t+1)}function xp(e,t){return e===``?t:`${e}/${t}`}function Sp(e){return e?e.replace(/^---\r?\n/,``).replace(/\r?\n---(?:\r?\n)?$/,``).split(/\r?\n/):[]}function Cp(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1).trim():t}function wp(e,t){let n=`${t}:`;for(let t of Sp(e))if(t.startsWith(n))return Cp(t.slice(n.length))||null;return null}function Tp(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=Cp(n);e&&t.push(e),n=``;continue}n+=i}let i=Cp(n);return i&&t.push(i),t}function Ep(e){let t=[],n=new Set;for(let r of e)!r||n.has(r)||(n.add(r),t.push(r));return t}function Dp(e){let{frontmatter:t}=l(e);if(!t)return[];let n=Sp(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 Ep(Tp(r.slice(1,-1)));let e=Cp(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=Cp(e.replace(/^\s*-\s+/,``));t&&i.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return Ep(i)}return[]}function Op(e,t){let{frontmatter:n,body:r}=l(e),i=wp(n,`title`);if(i)return i;let a=r.match(/^# (.+)$/m);return a?a[1].trim():t}function kp(e){return e?.trim()?{cluster:wp(e,`cluster`)??void 0,category:wp(e,`category`)??void 0,tags:Ap(e,`tags`)}:{cluster:void 0,category:void 0,tags:void 0}}function Ap(e,t){let n=`${t}:`,r=Sp(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=Tp(i.slice(1,-1));return e.length>0?e:void 0}let e=Cp(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=Cp(e.replace(/^\s*-\s+/,``));t&&a.push(t);continue}if(/^[^\s][^:]*:\s*/.test(e))break;break}}return a.length>0?a:void 0}}function jp(e,t){let n=Op(e,t),r=Dp(e),i=Ep([n,...r]),a=[],o=new Set;for(let e of i){let t=_(e);!t||o.has(t)||(o.add(t),a.push(t))}return{docName:t,title:n,aliases:r,matchLabels:i,normalizedMatchLabels:a}}var Mp=class extends F{constructor(e,t){super(e,t,`ui`),this.name=`UiLockCollisionError`}};function Np(e,t){try{return ae({lockName:`ui`,lockDir:e,metadata:t}).lockPath}catch(e){throw e instanceof F&&e.lockName===`ui`?new Mp(e.existing,e.lockPath):e}}function Pp(e,t){P({lockName:`ui`,lockDir:e,port:t})}function Fp(e){return ne({lockName:`ui`,lockDir:e})}function Ip(e){I({lockName:`ui`,lockDir:e})}const Lp=[`.mdx`,`.md`];function Rp(e){let t=Ce(e).toLowerCase();return Lp.includes(t)}function zp(e){let t=e.toLowerCase();for(let n of Lp)if(t.endsWith(n))return e.slice(0,-n.length);return e}function Bp(e){return Lp.indexOf(e)}const Vp=new Map;function Hp(e,t){let n=Vp.get(e);return n?n===t?{effective:n,changed:!1,shadowed:null}:Bp(t)<Bp(n)?(Vp.set(e,t),{effective:t,changed:!0,shadowed:n}):{effective:n,changed:!1,shadowed:t}:(Vp.set(e,t),{effective:t,changed:!0,shadowed:null})}function Up(e){return Vp.get(e)??`.md`}function Wp(e){Vp.delete(e)}const Gp=/\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/y,Kp=/\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y;function qp(){return{backward:new Map,forward:new Map,externalForward:new Map,externalBackward:new Map}}function Jp(e,t){return e?{anchor:e.anchor??t.anchor,snippet:e.snippet??t.snippet}:t}function Yp(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 Xp(e){return`external:${e}`}function Zp(e){return e.startsWith(`external:`)?e.slice(9):null}function Qp(e){return e.replace(/\s+/g,` `).trim()}function $p(e,t,n){if(!Qp(e))return null;let r=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
27
28
  `,t-1)),i=[e.indexOf(`.`,n),e.indexOf(`?`,n),e.indexOf(`!`,n),e.indexOf(`
28
- `,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=Hp(e.slice(a,o));return l?`${s}${l}${c}`:null}function Wp(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 Gp(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function Kp(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function qp(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 Jp(e,t){Fp.lastIndex=t;let n=Fp.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 Yp(e){let t=``,n=[],r=Kp(e);for(;r<e.length;){if(e[r]===`\\`&&r+1<e.length){t+=e[r+1],r+=2;continue}if(e[r]==="`"){let n=qp(e,r);if(n){t+=n.text,r=n.nextIndex;continue}}if(e[r]===`[`&&e[r+1]===`[`){let i=Jp(e,r);if(i){let e=p(i),a=t.length;t+=e;let o=C(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 Xp(e){let t=``,n=[],r=Kp(e);for(;r<e.length;){if(e[r]===`\\`&&r+1<e.length){t+=e[r+1],r+=2;continue}if(e[r]==="`"){let n=qp(e,r);if(n){t+=n.text,r=n.nextIndex;continue}}if(e[r]===`[`&&e[r+1]===`[`){let i=Jp(e,r);if(i){let e=p(i),a=t.length;t+=e;let o=C(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 Zp(e){return e.startsWith(`<`)&&e.endsWith(`>`)?e.slice(1,-1):e}function Qp(e,t){Ip.lastIndex=t;let n=Ip.exec(e);return n?{text:n[1]??``,href:Zp(n[2]??``),nextIndex:t+n[0].length}:null}function $p(e,t){let n=``,r=[],i=Kp(e);for(;i<e.length;){if(e[i]===`\\`&&i+1<e.length){n+=e[i+1],i+=2;continue}if(e[i]==="`"){let t=qp(e,i);if(t){n+=t.text,i=t.nextIndex;continue}}if(e[i]===`[`&&e[i+1]===`[`){let t=Jp(e,i);if(t){n+=p(t),i=t.nextIndex;continue}}if(e[i]===`[`&&e[i-1]!==`!`){let a=Qp(e,i);if(a){let e=O(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 em(e,t){let n=``,r=[],i=Kp(e);for(;i<e.length;){if(e[i]===`\\`&&i+1<e.length){n+=e[i+1],i+=2;continue}if(e[i]==="`"){let t=qp(e,i);if(t){n+=t.text,i=t.nextIndex;continue}}if(e[i]===`[`&&e[i+1]===`[`){let t=Jp(e,i);if(t){n+=p(t),i=t.nextIndex;continue}}if(e[i]===`[`&&e[i-1]!==`!`){let a=Qp(e,i);if(a){let e=O(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 tm(e,t){let n=e.replaceAll(`\r
29
+ `,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=Qp(e.slice(a,o));return l?`${s}${l}${c}`:null}function em(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 tm(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function nm(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function rm(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 im(e,t){Gp.lastIndex=t;let n=Gp.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 am(e){let t=``,n=[],r=nm(e);for(;r<e.length;){if(e[r]===`\\`&&r+1<e.length){t+=e[r+1],r+=2;continue}if(e[r]==="`"){let n=rm(e,r);if(n){t+=n.text,r=n.nextIndex;continue}}if(e[r]===`[`&&e[r+1]===`[`){let i=im(e,r);if(i){let e=p(i),a=t.length;t+=e;let o=C(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 om(e){let t=``,n=[],r=nm(e);for(;r<e.length;){if(e[r]===`\\`&&r+1<e.length){t+=e[r+1],r+=2;continue}if(e[r]==="`"){let n=rm(e,r);if(n){t+=n.text,r=n.nextIndex;continue}}if(e[r]===`[`&&e[r+1]===`[`){let i=im(e,r);if(i){let e=p(i),a=t.length;t+=e;let o=C(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 sm(e){return e.startsWith(`<`)&&e.endsWith(`>`)?e.slice(1,-1):e}function cm(e,t){Kp.lastIndex=t;let n=Kp.exec(e);return n?{text:n[1]??``,href:sm(n[2]??``),nextIndex:t+n[0].length}:null}function lm(e,t){let n=``,r=[],i=nm(e);for(;i<e.length;){if(e[i]===`\\`&&i+1<e.length){n+=e[i+1],i+=2;continue}if(e[i]==="`"){let t=rm(e,i);if(t){n+=t.text,i=t.nextIndex;continue}}if(e[i]===`[`&&e[i+1]===`[`){let t=im(e,i);if(t){n+=p(t),i=t.nextIndex;continue}}if(e[i]===`[`&&e[i-1]!==`!`){let a=cm(e,i);if(a){let e=O(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 um(e,t){let n=``,r=[],i=nm(e);for(;i<e.length;){if(e[i]===`\\`&&i+1<e.length){n+=e[i+1],i+=2;continue}if(e[i]==="`"){let t=rm(e,i);if(t){n+=t.text,i=t.nextIndex;continue}}if(e[i]===`[`&&e[i+1]===`[`){let t=im(e,i);if(t){n+=p(t),i=t.nextIndex;continue}}if(e[i]===`[`&&e[i-1]!==`!`){let a=cm(e,i);if(a){let e=O(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 dm(e,t){let n=e.replaceAll(`\r
29
30
  `,`
30
31
  `).replaceAll(`\r`,`
31
32
  `).split(`
32
- `),r=[],i=null;for(let e of n)if(i)Gp(e,i)&&(i=null);else{let n=Wp(e);if(n)i=n;else{let n=$p(e,t);r.push(...n.occurrences.map(({target:e,anchor:t,start:r,end:i})=>({target:e,anchor:t,snippet:Up(n.text,r,i)})))}}return r}function nm(e){let t=e.replaceAll(`\r
33
+ `),r=[],i=null;for(let e of n)if(i)tm(e,i)&&(i=null);else{let n=em(e);if(n)i=n;else{let n=lm(e,t);r.push(...n.occurrences.map(({target:e,anchor:t,start:r,end:i})=>({target:e,anchor:t,snippet:$p(n.text,r,i)})))}}return r}function fm(e){let t=e.replaceAll(`\r
33
34
  `,`
34
35
  `).replaceAll(`\r`,`
35
36
  `).split(`
36
- `),n=[],r=null;for(let e=0;e<t.length;e++){let i=t[e]??``;if(r)Gp(i,r)&&(r=null);else{let e=Wp(i);if(e)r=e;else{let e=Yp(i);n.push(...e.occurrences.map(({target:t,anchor:n,start:r,end:i})=>({target:t,anchor:n,snippet:Up(e.text,r,i)})))}}}return n}function rm(e){let t=e.replaceAll(`\r
37
+ `),n=[],r=null;for(let e=0;e<t.length;e++){let i=t[e]??``;if(r)tm(i,r)&&(r=null);else{let e=em(i);if(e)r=e;else{let e=am(i);n.push(...e.occurrences.map(({target:t,anchor:n,start:r,end:i})=>({target:t,anchor:n,snippet:$p(e.text,r,i)})))}}}return n}function pm(e){let t=e.replaceAll(`\r
37
38
  `,`
38
39
  `).replaceAll(`\r`,`
39
40
  `).split(`
40
- `),n=[],r=null;for(let e of t)if(r)Gp(e,r)&&(r=null);else{let t=Wp(e);if(t)r=t;else{let t=Xp(e);n.push(...t.occurrences.map(({url:e,label:n,start:r,end:i})=>({url:e,label:n,snippet:Up(t.text,r,i)})))}}return n}function im(e,t){let n=e.replaceAll(`\r
41
+ `),n=[],r=null;for(let e of t)if(r)tm(e,r)&&(r=null);else{let t=em(e);if(t)r=t;else{let t=om(e);n.push(...t.occurrences.map(({url:e,label:n,start:r,end:i})=>({url:e,label:n,snippet:$p(t.text,r,i)})))}}return n}function mm(e,t){let n=e.replaceAll(`\r
41
42
  `,`
42
43
  `).replaceAll(`\r`,`
43
44
  `).split(`
44
- `),r=[],i=null;for(let e of n)if(i)Gp(e,i)&&(i=null);else{let n=Wp(e);if(n)i=n;else{let n=em(e,t);r.push(...n.occurrences.map(({url:e,label:t,start:r,end:i})=>({url:e,label:t,snippet:Up(n.text,r,i)})))}}return r}function am(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 om(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 sm(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:om(t)}}var cm=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,Lp())}getState(e=this.activeBranch){let t=this.states.get(e);return t||(t=Lp(),this.states.set(e,t)),t}getActiveBranch(){return this.activeBranch}switchBranch(e){this.activeBranch=e,this.getState(e)}cachePath(e=this.activeBranch){return H(this.projectDir,`.open-knowledge`,`cache`,e,`backlinks.json`)}updateDocument(e,t,n=[],r=this.activeBranch){if(J(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,Rp(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}=l(t),i=nm(r),a=tm(r,e),o=rm(r),s=im(r,e),c=new Set(i.map(e=>e.target)),u=[...i,...a.filter(e=>!c.has(e.target))],d=new Set(o.map(e=>e.url)),f=[...o,...s.filter(e=>!d.has(e.url))];this.updateDocument(e,u,f,n)}catch(t){console.warn(`[backlinks] Failed to scan ${e} for link extraction:`,t),this.deleteDocument(e,n)}}deleteDocument(e,t=this.activeBranch){if(J(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:zp(t.backward.get(e))});for(let a of i)n.set(a,{kind:`doc`,id:a,docName:a,anchor:zp(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:zp(t.backward.get(e))});for(let[t,a]of i){let i=Bp(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=Vp(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(Bp(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=Bp(n);a.has(t)&&c.push({source:e,target:t})}return{nodes:[...a].sort().map(e=>{let t=Vp(e);return t?{kind:`external`,id:e,url:t,label:i.get(t)??null}:{kind:`doc`,id:e,docName:e,anchor:zp(r.backward.get(e))}}),links:c}}async saveToDisk(e=this.activeBranch){let t=this.cachePath(e);ue(Se(t),{recursive:!0});let n=this.getState(e);await Be(t,JSON.stringify(am(n),null,2),`utf-8`)}async loadFromDisk(e=this.activeBranch){let t=this.cachePath(e);if(!R(t))return!1;try{let n=await Le(t,`utf-8`),r=JSON.parse(n);return this.states.set(e,sm(r)),!0}catch(t){return console.warn(`[backlinks] Failed to load cache for ${e}:`,t),!1}}clear(e=this.activeBranch){this.states.set(e,Lp())}rebuildFileList(e,t){let n;try{n=fe(e,{withFileTypes:!0})}catch(t){console.warn(`[backlinks] Failed to read directory ${e}:`,t);return}for(let r of n){let n=V(e,r.name);if(r.isDirectory()){let e=Te(this.contentDir,n);if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;this.rebuildFileList(n,t);continue}if(!r.isFile()||!Op(r.name))continue;let i=Te(this.contentDir,n);this.contentFilter?.isExcluded(i)||t.push(kp(i))}}listDocsOnDisk(){if(!R(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=Lp();for(let e of this.listDocsOnDisk()){let n=H(this.contentDir,`${e}${Np(e)}`);try{let{body:r}=l(z(n,`utf-8`)),i=nm(r),a=tm(r,e),o=rm(r),s=im(r,e),c=new Set(i.map(e=>e.target)),u=[...i,...a.filter(e=>!c.has(e.target))],d=new Set(o.map(e=>e.url)),f=[...o,...s.filter(e=>!d.has(e.url))],p=new Set,m=new Map;t.forward.set(e,p),t.externalForward.set(e,m);for(let n of u){if(!n.target)continue;p.add(n.target);let r=t.backward.get(n.target);r||(r=new Map,t.backward.set(n.target,r)),r.set(e,Rp(r.get(e),{anchor:n.anchor,snippet:n.snippet}))}for(let n of f){if(!n.url)continue;m.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)}};function lm(e,t){let n=H(e,`lock`);if(R(n)){let t=null;try{t=JSON.parse(z(n,`utf-8`))}catch{console.warn(`[shadow-lock] Corrupt lock file at ${n} — replacing`)}if(t){let n=t.hostname===be();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:be(),startedAt:new Date().toISOString(),worktreeRoot:t};return B(n,JSON.stringify(r,null,2),`utf-8`),n}function um(e){let t=H(e,`lock`);try{_e(t)}catch{}}const dm=3e4;function fm(e){return Fe({baseDir:e.workTree,timeout:{block:dm}}).env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree})}async function pm(e){let t=Nl(e),n=H(e,`.git/openknowledge`),r=R(n),i=R(t);if(r&&!i?me(n,t):r&&i&&console.warn(`[shadow-repo] unexpected legacy + new shadow both present — no rename performed`),!R(H(t,`HEAD`))){ue(t,{recursive:!0}),await Fe({baseDir:e,timeout:{block:dm}}).raw(`init`,`--bare`,t);let n=Fe({timeout:{block:dm}}).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`)}let a={gitDir:t,workTree:e};return await hm(a),_m(a),lm(t,e),a}function mm(e){um(e.gitDir)}async function hm(e){let t=fm(e),n;try{n=(await t.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip`)).trim().split(`
45
- `).filter(e=>e.length>0)}catch{return 0}let r=[],i={server:0,"human-":0,upstream:0};for(let e of n){let t=e.split(`/`);if(t.length<4)continue;let n=t.slice(3).join(`/`);Jl(n).classification===`unknown`&&(n===`server`?(r.push(e),i.server++):n.startsWith(`human-`)?(r.push(e),i[`human-`]++):n===`upstream`&&(r.push(e),i.upstream++))}if(r.length===0)return 0;for(let e of r)try{await t.raw(`update-ref`,`-d`,e)}catch(t){console.warn(`[shadow-migration] failed to delete legacy ref ${e}:`,t)}let a=r.length;return Nn(a),console.warn(`[shadow-migration] deleted ${a} legacy refs: server=${i.server} human-=${i[`human-`]} upstream=${i.upstream}`),a}async function gm(e,t,n,r,i=`main`){let a=H(e.gitDir,`index-wip-${t.id}`),o=`refs/wip/${i}/${t.id}`,s=fm(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{he(a)}catch{}}}function _m(e){let t=0;try{for(let n of fe(e.gitDir))if(n.startsWith(`index-wip-fanout-`))try{he(H(e.gitDir,n)),t++}catch{}}catch{}return t}async function vm(e,t){let n=H(e.gitDir,`index-wip-fanout-${Ae()}`),r=fm(e),i=t||`.`;try{return await r.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:n}).raw(`add`,i),(await r.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:n}).raw(`write-tree`)).trim()}finally{try{he(n)}catch{}}}async function ym(e,t,n,r,i=`main`){let a=`refs/wip/${i}/${t.id}`,o=fm(e),s=null;try{s=(await o.raw(`rev-parse`,a)).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 ${a}:`,e),e}let c=[`commit-tree`,n,`-m`,r];s&&c.push(`-p`,s);let l=(await o.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(...c)).trim();return await o.raw(`update-ref`,a,l),l}const bm={id:`file-system`,name:`File System`,email:`file-system@openknowledge.local`},xm={id:`git-upstream`,name:`Git (upstream)`,email:`git@openknowledge.local`},Sm={id:`openknowledge-service`,name:`Open Knowledge (service)`,email:`service@openknowledge.local`},Cm=xm;async function wm(e,t,n,r,i=`main`){return gm(e,Cm,t,`${ql(n,r)}\n\n${Bl({v:1,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:Cm.name,color_seed:Cm.id,docs:[]})}`,i)}const Tm=Sm;async function Em(e,t,n,r=`main`){return gm(e,Tm,t,`${Kl(`pre-${n.action}`)}\n\n${Bl({v:1,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:Tm.name,color_seed:Tm.id,docs:[]})}`,r)}async function Dm(e,t,n){let r=n.branch??`main`,i=fm(e),a=Ae(),o=H(e.gitDir,`index-checkpoint-${a}`),s=H(e.gitDir,`tmp-checkpoint-blob-${a}`),c=t?`${t.replace(/\/$/,``)}/${n.docName}`:n.docName,l=Buffer.byteLength(n.contents,`utf-8`),u=zl(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{B(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{he(o)}catch{}try{he(s)}catch{}}}async function Om(e,t=`main`){let n=fm(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=Rl(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 km(e,t,n,r,i){if(r.length===0)return null;let a=fm(e),o=H(e.gitDir,`index-park-${t.replace(/\//g,`-`)}`),s=`refs/wip/${t}/${n}`,c=H(e.gitDir,`tmp-park-blob`);try{for(let t of r){B(c,t.markdown,`utf-8`);let n=(await a.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`hash-object`,`-w`,c)).trim();await a.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${n},${t.docName}`),B(c,t.diskSnapshot,`utf-8`);let r=(await a.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`hash-object`,`-w`,c)).trim();await a.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${r},.park-base/${t.docName}`)}let n=(await a.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`write-tree`)).trim(),l=null;try{l=(await a.raw(`rev-parse`,s)).trim()}catch{}let u={v:1,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:Sm.name,color_seed:Sm.id,docs:r.map(e=>e.docName)},d=[`commit-tree`,n,`-m`,`${Wl(t,i??t)}\n\n${Bl(u)}`];l&&d.push(`-p`,l);let f=(await a.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(...d)).trim();return await a.raw(`update-ref`,s,f),f}finally{try{he(o)}catch{}try{he(c)}catch{}}}async function Am(e,t,n,r){let i=fm(e),a=`refs/wip/${t}/${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 jm(e,t,n,r=`main`){let i=fm(e),a=t||`.`,o=H(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,xm])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={v:1,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:Sm.name,color_seed:Sm.id,docs:[]},u=[`commit-tree`,t,`-m`,`${Kl(`Checkpoint version`)}\n\n${Bl(l)}`];for(let e of c)u.push(`-p`,e);let d=(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(...u)).trim(),f=`refs/checkpoints/${r}/${d}`;await i.raw(`update-ref`,f,d);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}/${xm.id}`)}catch{}return{checkpointRef:f}}finally{try{he(o)}catch{}}}const Mm=ln(`persistence`);function Nm(e,t){if(!e||typeof e!=`object`)return null;let n=e;if(n.source===`local`){let e=n.context;if(!e)return null;if(typeof e.session_id==`string`){let t=e.session_id;return{id:`agent-${t}`,name:`Agent (${t.slice(0,8)})`,email:`agent-${t}@openknowledge.local`}}return e.origin===`file-watcher`?bm:e.origin===`upstream-import`||e.origin===`git-upstream`?xm:Sm}if(n.source===`connection`){let e=n.connection?.context;if(typeof e?.principalId==`string`){let n=e.principalId,r=t?.();return r&&r.id===n&&r.display_name&&r.display_email?{id:r.id,name:r.display_name,email:r.display_email}:{id:n,name:`Local User`,email:`${n}@openknowledge.local`}}return Sm}return null}function Pm(e,t){if(e.includes(`\0`))throw Error(`Invalid document name: ${e}`);let n=H(t,`${e}${Np(e)}`);if(!n.startsWith(`${t}/`))throw Error(`Invalid document name: ${e}`);return n}function Fm(e,t){return e===t||e.startsWith(t+Ee)}const Im=new Map;let Lm=`main`;function Rm(e){Lm=e,Im.has(e)||Im.set(e,new Map)}function zm(){return Lm}function Bm(e){return Im.get(Lm)?.get(e)}function Vm(e,t){Im.has(Lm)||Im.set(Lm,new Map),Im.get(Lm)?.set(e,t)}function Hm(e){Im.get(Lm)?.delete(e)}let Um=!1;function Wm(e){Um=e}function Gm(){return Um}function Km(e){let t=e?.contentDir??process.cwd(),n;try{n=pe(t)}catch{n=t}let r=e?.projectDir??process.cwd(),i=e?.shadowRef,a=e?.contentRoot??(Te(r,n)||`content`),o=e?.backlinkIndex,s=e?.getPrincipal,c=new Map,u=e?.gitEnabled??!0,d=e?.commitDebounceMs??15e3,f=e?.wipRef??`refs/wip/main`,p=e?.getCurrentBranch,m=null,h=0,g=null,_=!1;async function v(){let e=i?.current;if(e){let t=Wf(),n=p?.()??`main`;if(t.size===0){let t={v:1,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:Sm.name,color_seed:Sm.id,docs:[]},r=`${Vl([])}\n\n${Bl(t)}`;try{let t=await gm(e,Sm,a,r,n);h=0,Mm.info({sha:t.slice(0,8),writer:Sm.id},`[persistence] Shadow WIP commit: ${t.slice(0,8)} on refs/wip/${Sm.id}`)}catch(e){h++,Sn(),Mm.error({err:e,attempt:h},`[persistence] Shadow commit failed (attempt ${h})`),h>=3&&Mm.error({attempt:h},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}return}let r;try{r=await vm(e,a)}catch(e){Gf(t),h++,Sn(),Mm.error({err:e,attempt:h},`[persistence] Shadow WIP tree build failed (attempt ${h})`);return}let i=!1;for(let[a,o]of t){let t={id:a,name:o.displayName,email:`${a}@openknowledge.local`},s=[...o.docs],c=o.actor,l={v:1,principal:c?.principalId??null,agent_session:a.startsWith(`agent-`)?a.slice(6):null,agent_type:c?.agentType??null,client_name:c?.clientName??null,client_version:c?.clientVersion??null,label:c?.label??null,display_name:o.displayName,color_seed:o.colorSeed,docs:s},u=`ok-contributors: ${JSON.stringify({v:1,id:a,name:o.displayName,colorSeed:o.colorSeed,docs:s})}`,d=`${o.subjectOverride??Vl(s)}\n\n${u}\n${Bl(l)}`;try{let o=await ym(e,t,r,d,n);i=!0,Mm.info({sha:o.slice(0,8),writer:a,tree:r.slice(0,8)},`[persistence] Shadow WIP commit: ${o.slice(0,8)} on refs/wip/${a}`)}catch(e){Kf(a,o),Cn(),Mm.error({err:e,writer:a},`[persistence] Per-writer shadow commit failed for ${a}`)}}i?h=0:(h++,Sn(),h>=3&&Mm.error({attempt:h},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`));return}let t=fm({gitDir:H(r,`.git`),workTree:r}),n=H(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`)?Mm.info({},`[persistence] Empty repo — starting with empty index`):Mm.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`,f)).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`,f,i),h=0,Mm.info({sha:i.slice(0,8),wipRef:f},`[persistence] Git commit: ${i.slice(0,8)} on ${f}`)}catch(e){h++,Sn(),Mm.error({err:e,attempt:h},`[persistence] Git commit failed (attempt ${h})`),h>=3&&Mm.error({attempt:h},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}finally{try{_e(n)}catch{}}}function y(){u&&(Gm()||(m&&clearTimeout(m),m=setTimeout(()=>{if(m=null,g){_=!0;return}g=v().finally(()=>{g=null,_&&(_=!1,y())})},d)))}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(J(t))return;Mm.info({documentName:t,connections:e.getConnectionsCount?.()??`?`},`[persistence] onLoadDocument called for ${t} (connections: ${e.getConnectionsCount?.()??`?`})`);let i=Pm(t,n);if(!R(i))return;try{let e=pe(i);if(!Fm(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}=l(z(i,`utf-8`));a&&(c.set(t,a),e.getMap(`metadata`).set(`frontmatter`,a));let s=wl.parseWithFallback(o),u=e.getXmlFragment(`default`);Mm.info({documentName:t,fragmentLength:u.length},`[persistence] onLoadDocument ${t}: fragment.length=${u.length} before update`),u.length===0?(yl(e,u,Tl.nodeFromJSON(s),{mapping:new Map,isOMark:new Map}),Mm.info({filePath:i,children:u.length},`[persistence] Loaded ${i} into Y.Doc (${u.length} children)`),u.observeDeep(()=>{Mm.info({documentName:t,fragmentLength:u.length},`[persistence] MUTATION on ${t}: fragment.length=${u.length}`)})):Mm.info({documentName:t,children:u.length},`[persistence] Skipped load for ${t} — fragment already has ${u.length} children`),Vm(t,M(a,wl.serialize(Sl(u,Tl).toJSON())))},async onStoreDocument({document:e,documentName:t,lastTransactionOrigin:r,lastContext:i}){if(J(t)||Gm())return;let a=Nm(r,s);a&&a.id!==Sm.id&&(Jf(a.id)||Uf(t,a.id,a.name,a.id));let l=Sl(e.getXmlFragment(`default`),Tl).toJSON(),u=wl.serialize(l),d=e.getMap(`metadata`).get(`frontmatter`),f=M(typeof d==`string`?d:c.get(t)||``,u),p=Bm(t);if(p!==void 0&&f===p){qf()>0&&y();return}p&&f.length>p.length*1.5&&(Mm.warn({documentName:t,markdownLength:f.length,baseLength:p.length},`[persistence] WARNING: serialized content is ${f.length} bytes vs base ${p.length} bytes for ${t} — possible duplication`),Mm.warn({documentName:t,children:e.getXmlFragment(`default`).length},`[persistence] Fragment children: ${e.getXmlFragment(`default`).length}`));let m=Pm(t,n);await Ie(Se(m),{recursive:!0});let h;try{h=await Re(m)}catch(e){let n=e.code;if(n===`ENOENT`){let e=!1;try{e=le(m).isSymbolicLink()}catch(e){e.code!==`ENOENT`&&Mm.warn({err:e,path:m},`[persistence] lstat failed during broken-symlink check`)}e&&console.warn(`[persistence] broken-symlink fallback`,{docName:t,reason:`broken-symlink`}),h=m}else if(n===`ELOOP`)throw console.error(`[persistence] Symlink cycle at ${m}`),Error(`Symlink cycle detected at ${m}`);else throw e}if(!Fm(h,n)){let e=`symlink-escape: ${m} resolves to ${h} outside ${n}`;throw console.error(`[persistence] ${e}`,{docName:t,originalPath:m,canonical:h,contentDir:n}),Error(e)}let g=`${h}.tmp.${crypto.randomUUID()}`;try{await Be(g,f,`utf-8`),await ze(g,h),nh(h,ih(f)),On()}catch(e){try{_e(g)}catch{}throw Mm.error({err:e,documentName:t},`[persistence] Failed to save ${t}`),e}Mm.info({filePath:h,bytes:f.length},`[persistence] Wrote ${h} (${f.length} bytes)`),Vm(t,f),o&&(o.updateDocumentFromMarkdown(t,f),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 qm=/^(<{7} |={7}$|>{7} |\|{7} )/m;function Jm(e){return qm.test(e)}function Ym(e){let t=e.replace(/\n+$/,``);if(!t)return[];let n=t.split(`
45
+ `),r=[],i=null;for(let e of n)if(i)tm(e,i)&&(i=null);else{let n=em(e);if(n)i=n;else{let n=um(e,t);r.push(...n.occurrences.map(({url:e,label:t,start:r,end:i})=>({url:e,label:t,snippet:$p(n.text,r,i)})))}}return r}function hm(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 gm(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 _m(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:gm(t)}}var vm=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,qp())}getState(e=this.activeBranch){let t=this.states.get(e);return t||(t=qp(),this.states.set(e,t)),t}getActiveBranch(){return this.activeBranch}switchBranch(e){this.activeBranch=e,this.getState(e)}cachePath(e=this.activeBranch){return H(this.projectDir,`.open-knowledge`,`cache`,e,`backlinks.json`)}updateDocument(e,t,n=[],r=this.activeBranch){if(J(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,Jp(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}=l(t),i=fm(r),a=dm(r,e),o=pm(r),s=mm(r,e),c=new Set(i.map(e=>e.target)),u=[...i,...a.filter(e=>!c.has(e.target))],d=new Set(o.map(e=>e.url)),f=[...o,...s.filter(e=>!d.has(e.url))];this.updateDocument(e,u,f,n)}catch(t){console.warn(`[backlinks] Failed to scan ${e} for link extraction:`,t),this.deleteDocument(e,n)}}deleteDocument(e,t=this.activeBranch){if(J(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:Yp(t.backward.get(e))});for(let a of i)n.set(a,{kind:`doc`,id:a,docName:a,anchor:Yp(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:Yp(t.backward.get(e))});for(let[t,a]of i){let i=Xp(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=Zp(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(Xp(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=Xp(n);a.has(t)&&c.push({source:e,target:t})}return{nodes:[...a].sort().map(e=>{let t=Zp(e);return t?{kind:`external`,id:e,url:t,label:i.get(t)??null}:{kind:`doc`,id:e,docName:e,anchor:Yp(r.backward.get(e))}}),links:c}}async saveToDisk(e=this.activeBranch){let t=this.cachePath(e);ue(Se(t),{recursive:!0});let n=this.getState(e);await Be(t,JSON.stringify(hm(n),null,2),`utf-8`)}async loadFromDisk(e=this.activeBranch){let t=this.cachePath(e);if(!R(t))return!1;try{let n=await Le(t,`utf-8`),r=JSON.parse(n);return this.states.set(e,_m(r)),!0}catch(t){return console.warn(`[backlinks] Failed to load cache for ${e}:`,t),!1}}clear(e=this.activeBranch){this.states.set(e,qp())}rebuildFileList(e,t){let n;try{n=fe(e,{withFileTypes:!0})}catch(t){console.warn(`[backlinks] Failed to read directory ${e}:`,t);return}for(let r of n){let n=V(e,r.name);if(r.isDirectory()){let e=Te(this.contentDir,n);if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;this.rebuildFileList(n,t);continue}if(!r.isFile()||!Rp(r.name))continue;let i=Te(this.contentDir,n);this.contentFilter?.isExcluded(i)||t.push(zp(i))}}listDocsOnDisk(){if(!R(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=qp();for(let e of this.listDocsOnDisk()){let n=H(this.contentDir,`${e}${Up(e)}`);try{let{body:r}=l(z(n,`utf-8`)),i=fm(r),a=dm(r,e),o=pm(r),s=mm(r,e),c=new Set(i.map(e=>e.target)),u=[...i,...a.filter(e=>!c.has(e.target))],d=new Set(o.map(e=>e.url)),f=[...o,...s.filter(e=>!d.has(e.url))],p=new Set,m=new Map;t.forward.set(e,p),t.externalForward.set(e,m);for(let n of u){if(!n.target)continue;p.add(n.target);let r=t.backward.get(n.target);r||(r=new Map,t.backward.set(n.target,r)),r.set(e,Jp(r.get(e),{anchor:n.anchor,snippet:n.snippet}))}for(let n of f){if(!n.url)continue;m.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)}};function ym(e,t){let n=H(e,`lock`);if(R(n)){let t=null;try{t=JSON.parse(z(n,`utf-8`))}catch{console.warn(`[shadow-lock] Corrupt lock file at ${n} — replacing`)}if(t){let n=t.hostname===be();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:be(),startedAt:new Date().toISOString(),worktreeRoot:t};return B(n,JSON.stringify(r,null,2),`utf-8`),n}function bm(e){let t=H(e,`lock`);try{_e(t)}catch{}}const xm=3e4;function Sm(e){return Fe({baseDir:e.workTree,timeout:{block:xm}}).env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree})}async function Cm(e){let t=Il(e),n=H(e,`.git/openknowledge`),r=R(n),i=R(t);if(r&&!i?me(n,t):r&&i&&console.warn(`[shadow-repo] unexpected legacy + new shadow both present — no rename performed`),!R(H(t,`HEAD`))){ue(t,{recursive:!0}),await Fe({baseDir:e,timeout:{block:xm}}).raw(`init`,`--bare`,t);let n=Fe({timeout:{block:xm}}).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`)}let a={gitDir:t,workTree:e};return await Tm(a),Dm(a),ym(t,e),a}function wm(e){bm(e.gitDir)}async function Tm(e){let t=Sm(e),n;try{n=(await t.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip`)).trim().split(`
46
+ `).filter(e=>e.length>0)}catch{return 0}let r=[],i={server:0,"human-":0,upstream:0};for(let e of n){let t=e.split(`/`);if(t.length<4)continue;let n=t.slice(3).join(`/`);ru(n).classification===`unknown`&&(n===`server`?(r.push(e),i.server++):n.startsWith(`human-`)?(r.push(e),i[`human-`]++):n===`upstream`&&(r.push(e),i.upstream++))}if(r.length===0)return 0;for(let e of r)try{await t.raw(`update-ref`,`-d`,e)}catch(t){console.warn(`[shadow-migration] failed to delete legacy ref ${e}:`,t)}let a=r.length;return In(a),console.warn(`[shadow-migration] deleted ${a} legacy refs: server=${i.server} human-=${i[`human-`]} upstream=${i.upstream}`),a}async function Em(e,t,n,r,i=`main`){let a=H(e.gitDir,`index-wip-${t.id}`),o=`refs/wip/${i}/${t.id}`,s=Sm(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{he(a)}catch{}}}function Dm(e){let t=0;try{for(let n of fe(e.gitDir))if(n.startsWith(`index-wip-fanout-`))try{he(H(e.gitDir,n)),t++}catch{}}catch{}return t}async function Om(e,t){let n=H(e.gitDir,`index-wip-fanout-${Ae()}`),r=Sm(e),i=t||`.`;try{return await r.env({GIT_DIR:e.gitDir,GIT_WORK_TREE:e.workTree,GIT_INDEX_FILE:n}).raw(`add`,i),(await r.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:n}).raw(`write-tree`)).trim()}finally{try{he(n)}catch{}}}async function km(e,t,n,r,i=`main`){let a=`refs/wip/${i}/${t.id}`,o=Sm(e),s=null;try{s=(await o.raw(`rev-parse`,a)).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 ${a}:`,e),e}let c=[`commit-tree`,n,`-m`,r];s&&c.push(`-p`,s);let l=(await o.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(...c)).trim();return await o.raw(`update-ref`,a,l),l}const Am={id:`file-system`,name:`File System`,email:`file-system@openknowledge.local`},jm={id:`git-upstream`,name:`Git (upstream)`,email:`git@openknowledge.local`},Mm={id:`openknowledge-service`,name:`Open Knowledge (service)`,email:`service@openknowledge.local`},Nm=jm;async function Pm(e,t,n,r,i=`main`){return Em(e,Nm,t,`${tu(n,r)}\n\n${Wl({v:1,writer_id:Nm.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:Nm.name,color_seed:Nm.id,docs:[]})}`,i)}const Fm=Mm;async function Im(e,t,n,r=`main`){return Em(e,Fm,t,`${eu(`pre-${n.action}`)}\n\n${Wl({v:1,writer_id:Fm.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:Fm.name,color_seed:Fm.id,docs:[]})}`,r)}async function Lm(e,t,n){let r=n.branch??`main`,i=Sm(e),a=Ae(),o=H(e.gitDir,`index-checkpoint-${a}`),s=H(e.gitDir,`tmp-checkpoint-blob-${a}`),c=t?`${t.replace(/\/$/,``)}/${n.docName}`:n.docName,l=Buffer.byteLength(n.contents,`utf-8`),u=Hl(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{B(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{he(o)}catch{}try{he(s)}catch{}}}async function Rm(e,t=`main`){let n=Sm(e),r;try{r=await n.raw(`for-each-ref`,`--format=%(objectname)`,`refs/checkpoints/${t}/`)}catch{return[]}let i=r.trim().split(`
47
+ `).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=Vl(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(`
48
+ `)[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 zm(e,t,n,r,i){if(r.length===0)return null;let a=Sm(e),o=H(e.gitDir,`index-park-${t.replace(/\//g,`-`)}`),s=`refs/wip/${t}/${n}`,c=H(e.gitDir,`tmp-park-blob`);try{for(let t of r){B(c,t.markdown,`utf-8`);let n=(await a.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`hash-object`,`-w`,c)).trim();await a.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${n},${t.docName}`),B(c,t.diskSnapshot,`utf-8`);let r=(await a.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`hash-object`,`-w`,c)).trim();await a.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`update-index`,`--add`,`--cacheinfo`,`100644,${r},.park-base/${t.docName}`)}let n=(await a.env({GIT_DIR:e.gitDir,GIT_INDEX_FILE:o}).raw(`write-tree`)).trim(),l=null;try{l=(await a.raw(`rev-parse`,s)).trim()}catch{}let u={v:1,writer_id:Mm.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:Mm.name,color_seed:Mm.id,docs:r.map(e=>e.docName)},d=[`commit-tree`,n,`-m`,`${Ql(t,i??t)}\n\n${Wl(u)}`];l&&d.push(`-p`,l);let f=(await a.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(...d)).trim();return await a.raw(`update-ref`,s,f),f}finally{try{he(o)}catch{}try{he(c)}catch{}}}async function Bm(e,t,n,r){let i=Sm(e),a=`refs/wip/${t}/${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 Vm(e,t,n,r=`main`){let i=Sm(e),a=t||`.`,o=H(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,jm])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(`
49
+ `).filter(Boolean);e[0]&&c.push(e[0])}catch{}let l={v:1,writer_id:Mm.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:Mm.name,color_seed:Mm.id,docs:[]},u=[`commit-tree`,t,`-m`,`${eu(`Checkpoint version`)}\n\n${Wl(l)}`];for(let e of c)u.push(`-p`,e);let d=(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(...u)).trim(),f=`refs/checkpoints/${r}/${d}`;await i.raw(`update-ref`,f,d);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}/${jm.id}`)}catch{}return{checkpointRef:f}}finally{try{he(o)}catch{}}}const Hm=ln(`persistence`);function Um(e,t){if(!e||typeof e!=`object`)return null;let n=e;if(n.source===`local`){let e=n.context;if(!e)return null;if(typeof e.session_id==`string`){let t=e.session_id;return{id:`agent-${t}`,name:`Agent (${t.slice(0,8)})`,email:`agent-${t}@openknowledge.local`}}return e.origin===`file-watcher`?Am:e.origin===`upstream-import`||e.origin===`git-upstream`?jm:Mm}if(n.source===`connection`){let e=n.connection?.context;if(typeof e?.principalId==`string`){let n=e.principalId,r=t?.();return r&&r.id===n&&r.display_name&&r.display_email?{id:r.id,name:r.display_name,email:r.display_email}:{id:n,name:`Local User`,email:`${n}@openknowledge.local`}}return Mm}return null}function Wm(e,t){if(e.includes(`\0`))throw Error(`Invalid document name: ${e}`);let n=H(t,`${e}${Up(e)}`);if(!n.startsWith(`${t}/`))throw Error(`Invalid document name: ${e}`);return n}function Gm(e,t){return e===t||e.startsWith(t+Ee)}const Km=new Map;let qm=`main`;function Jm(e){qm=e,Km.has(e)||Km.set(e,new Map)}function Ym(){return qm}function Xm(e){return Km.get(qm)?.get(e)}function Zm(e,t){Km.has(qm)||Km.set(qm,new Map),Km.get(qm)?.set(e,t)}function Qm(e){Km.get(qm)?.delete(e)}let $m=!1;function eh(e){$m=e}function th(){return $m}function nh(e){let t=e?.contentDir??process.cwd(),n;try{n=pe(t)}catch{n=t}let r=e?.projectDir??process.cwd(),i=e?.shadowRef,a=e?.contentRoot??(Te(r,n)||`content`),o=e?.backlinkIndex,s=e?.getPrincipal,c=new Map,u=e?.gitEnabled??!0,d=e?.commitDebounceMs??15e3,f=e?.wipRef??`refs/wip/main`,p=e?.getCurrentBranch,m=null,h=0,g=null,_=!1;async function v(){let e=i?.current;if(e){let t=ep(),n=p?.()??`main`;if(t.size===0){let t={v:1,writer_id:Mm.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:Mm.name,color_seed:Mm.id,docs:[]},r=`${Yl([])}\n\n${Wl(t)}`;try{let t=await Em(e,Mm,a,r,n);h=0,Hm.info({sha:t.slice(0,8),writer:Mm.id},`[persistence] Shadow WIP commit: ${t.slice(0,8)} on refs/wip/${Mm.id}`)}catch(e){h++,Sn(),Hm.error({err:e,attempt:h},`[persistence] Shadow commit failed (attempt ${h})`),h>=3&&Hm.error({attempt:h},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}return}let r;try{r=await Om(e,a)}catch(e){tp(t),h++,Sn(),Hm.error({err:e,attempt:h},`[persistence] Shadow WIP tree build failed (attempt ${h})`);return}let i=!1;for(let[a,o]of t){let t={id:a,name:o.displayName,email:`${a}@openknowledge.local`},s=[...o.docs],c=o.actor,l=[...o.summaries],u={v:1,writer_id:a,principal:c?.principalId??null,agent_session:a.startsWith(`agent-`)?a.slice(6):null,agent_type:c?.agentType??null,client_name:c?.clientName??null,client_version:c?.clientVersion??null,label:c?.label??null,display_name:o.displayName,color_seed:o.colorSeed,docs:s,...l.length>0?{summaries:l}:{}},d=`${nu(o.subjectOverride??Yl(s),l)}\n\n${Wl(u)}`;try{let o=await km(e,t,r,d,n);i=!0,Hm.info({sha:o.slice(0,8),writer:a,tree:r.slice(0,8)},`[persistence] Shadow WIP commit: ${o.slice(0,8)} on refs/wip/${a}`)}catch(e){np(a,o),Cn(),Hm.error({err:e,writer:a},`[persistence] Per-writer shadow commit failed for ${a}`)}}i?h=0:(h++,Sn(),h>=3&&Hm.error({attempt:h},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`));return}let t=Sm({gitDir:H(r,`.git`),workTree:r}),n=H(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`)?Hm.info({},`[persistence] Empty repo — starting with empty index`):Hm.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`,f)).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`,f,i),h=0,Hm.info({sha:i.slice(0,8),wipRef:f},`[persistence] Git commit: ${i.slice(0,8)} on ${f}`)}catch(e){h++,Sn(),Hm.error({err:e,attempt:h},`[persistence] Git commit failed (attempt ${h})`),h>=3&&Hm.error({attempt:h},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}finally{try{_e(n)}catch{}}}function y(){u&&(th()||(m&&clearTimeout(m),m=setTimeout(()=>{if(m=null,g){_=!0;return}g=v().finally(()=>{g=null,_&&(_=!1,y())})},d)))}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(J(t))return;Hm.info({documentName:t,connections:e.getConnectionsCount?.()??`?`},`[persistence] onLoadDocument called for ${t} (connections: ${e.getConnectionsCount?.()??`?`})`);let i=Wm(t,n);if(!R(i))return;try{let e=pe(i);if(!Gm(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}=l(z(i,`utf-8`));a&&(c.set(t,a),e.getMap(`metadata`).set(`frontmatter`,a));let s=Dl.parseWithFallback(o),u=e.getXmlFragment(`default`);Hm.info({documentName:t,fragmentLength:u.length},`[persistence] onLoadDocument ${t}: fragment.length=${u.length} before update`),u.length===0?(Sl(e,u,Ol.nodeFromJSON(s),{mapping:new Map,isOMark:new Map}),Hm.info({filePath:i,children:u.length},`[persistence] Loaded ${i} into Y.Doc (${u.length} children)`),u.observeDeep(()=>{Hm.info({documentName:t,fragmentLength:u.length},`[persistence] MUTATION on ${t}: fragment.length=${u.length}`)})):Hm.info({documentName:t,children:u.length},`[persistence] Skipped load for ${t} — fragment already has ${u.length} children`),Zm(t,M(a,Dl.serialize(Tl(u,Ol).toJSON())))},async onStoreDocument({document:e,documentName:t,lastTransactionOrigin:r,lastContext:i}){if(J(t)||th())return;let a=Um(r,s);a&&a.id!==Mm.id&&(ip(a.id)||$f(t,a.id,a.name,a.id));let l=Tl(e.getXmlFragment(`default`),Ol).toJSON(),u=Dl.serialize(l),d=e.getMap(`metadata`).get(`frontmatter`),f=M(typeof d==`string`?d:c.get(t)||``,u),p=Xm(t);if(p!==void 0&&f===p){rp()>0&&y();return}p&&f.length>p.length*1.5&&(Hm.warn({documentName:t,markdownLength:f.length,baseLength:p.length},`[persistence] WARNING: serialized content is ${f.length} bytes vs base ${p.length} bytes for ${t} — possible duplication`),Hm.warn({documentName:t,children:e.getXmlFragment(`default`).length},`[persistence] Fragment children: ${e.getXmlFragment(`default`).length}`));let m=Wm(t,n);await Ie(Se(m),{recursive:!0});let h;try{h=await Re(m)}catch(e){let n=e.code;if(n===`ENOENT`){let e=!1;try{e=le(m).isSymbolicLink()}catch(e){e.code!==`ENOENT`&&Hm.warn({err:e,path:m},`[persistence] lstat failed during broken-symlink check`)}e&&console.warn(`[persistence] broken-symlink fallback`,{docName:t,reason:`broken-symlink`}),h=m}else if(n===`ELOOP`)throw console.error(`[persistence] Symlink cycle at ${m}`),Error(`Symlink cycle detected at ${m}`);else throw e}if(!Gm(h,n)){let e=`symlink-escape: ${m} resolves to ${h} outside ${n}`;throw console.error(`[persistence] ${e}`,{docName:t,originalPath:m,canonical:h,contentDir:n}),Error(e)}let g=`${h}.tmp.${crypto.randomUUID()}`;try{await Be(g,f,`utf-8`),await ze(g,h),fh(h,mh(f)),On()}catch(e){try{_e(g)}catch{}throw Hm.error({err:e,documentName:t},`[persistence] Failed to save ${t}`),e}Hm.info({filePath:h,bytes:f.length},`[persistence] Wrote ${h} (${f.length} bytes)`),Zm(t,f),o&&(o.updateDocumentFromMarkdown(t,f),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 rh=/^(<{7} |={7}$|>{7} |\|{7} )/m;function ih(e){return rh.test(e)}function ah(e){let t=e.replace(/\n+$/,``);if(!t)return[];let n=t.split(`
49
50
  `),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(`
50
51
  `).trim()),i=[]):i.push(e)}if(i.length>0){let e=i.join(`
51
- `).trim();e&&r.push(e)}return r}function Xm(e){if(J(e.docName))return{kind:`noop`};let{base:t,ours:n,theirs:r}=e;return Jm(r)?{kind:`refused`,reason:`conflict-markers`}:r===t?{kind:`noop`}:n===t?{kind:`clean`,newContent:r}:Zm(Ym(t),Ym(n),Ym(r))}function Zm(e,t,n){let r=Qm(e,t),i=Qm(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(`
52
+ `).trim();e&&r.push(e)}return r}function oh(e){if(J(e.docName))return{kind:`noop`};let{base:t,ours:n,theirs:r}=e;return ih(r)?{kind:`refused`,reason:`conflict-markers`}:r===t?{kind:`noop`}:n===t?{kind:`clean`,newContent:r}:sh(ah(t),ah(n),ah(r))}function sh(e,t,n){let r=ch(e,t),i=ch(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(`
52
53
 
53
- `)}\n`:``;return o.length>0?{kind:`conflicts`,newContent:l,conflicts:o}:{kind:`merged`,newContent:l,mergedBlocks:a.length}}function Qm(e,t){let n=new Map,r=$m(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 $m(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 eh=new Map,th=1e4;function nh(e,t){let n=eh.get(e)??[];n.push({hash:t,timestamp:Date.now()}),eh.set(e,n)}function rh(){let e=Date.now();for(let[t,n]of eh){let r=n.filter(t=>e-t.timestamp<=th);r.length===0?eh.delete(t):r.length!==n.length&&eh.set(t,r)}}function ih(e){return ke(`sha256`).update(e).digest(`hex`)}function ah(e,t){return kp(Te(t,e))}function oh(e){let t=e.toLowerCase();return t.endsWith(`.mdx`)?`.mdx`:t.endsWith(`.md`)?`.md`:null}const sh=new Map;function ch(e,t){sh.set(e,t)}function lh(e){let t=sh.get(e);return sh.delete(e),t}async function uh(e,t,n,r){let i=[],a=[],o=[];for(let r of e)if(Op(r.path)){if(n){let e=Te(t,r.path);if(n.isExcluded(e))continue}switch(r.type){case`delete`:i.push(r);break;case`create`:sh.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 Le(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 Le(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}function l(e){let n=ah(e,t);if(!r)return n;let i=null;try{i=le(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=pe(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(!Fm(a,t))return r.delete(n),n;let o=ah(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=lh(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=ih(r);if(i===t){d.add(n.path),f.add(e.path),ch(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)||(lh(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=ih(t);ch(e.path,n),Jm(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=ih(t);ch(e.path,n),Jm(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 dh(e,t){let n=eh.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&&eh.delete(e),!0)}function fh(e,t,n,r,i,a){let o=a??new Set;try{let a=fe(e,{withFileTypes:!0});for(let s of a){let a=V(e,s.name),c;try{c=le(a)}catch(e){e.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to lstat ${a}, skipping:`,e);continue}if(c.isSymbolicLink()){let e;try{e=pe(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(!Fm(e,t)){console.warn(`[file-watcher] Symlink escape: ${a} → ${e}, skipping`);continue}try{let c=ge(e);if(o.has(c.ino)){if(c.isFile()&&Op(s.name)){let n=ah(a,t),o=ah(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=Te(t,e);if(n.isDirExcluded(r))continue}fh(e,t,n,r,i,o)}else if(c.isFile()&&Op(s.name)){if(n){let r=Te(t,e);if(n.isExcluded(r))continue}let o=ah(a,t),s=ah(e,t);i.set(o,s);try{let t=ih(z(e,`utf-8`));sh.set(e,t);let n=oh(e);if(n){let e=Mp(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=Te(t,a);if(n.isDirExcluded(e))continue}fh(a,t,n,r,i,o)}else if(c.isFile()&&Op(s.name)){if(o.has(c.ino))continue;if(o.add(c.ino),n){let e=Te(t,a);if(n.isExcluded(e))continue}try{let e=z(a,`utf-8`);sh.set(a,ih(e));let n=ah(a,t),i=oh(a);if(i){let e=Mp(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 ph(e,t){if(!J(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=oh(e.path);i&&Mp(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),Pp(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),Pp(e.oldDocName);let r=oh(e.newPath);r&&Mp(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 mh(e,t,n,r,i,a){let o=e.filter(e=>Op(e.path));if(o.length===0)return;let s=await uh(o,t,n,a);for(let e of s){let t=!1;if(e.kind!==`delete`&&e.kind!==`rename`){let n=ih(e.content),r=e.path;try{r=pe(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=dh(r,n)}else if(e.kind===`rename`){let n=ih(e.content),r=e.newPath;try{r=pe(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=dh(r,n)}if(ph(e,r),n)switch(e.kind){case`create`:n.incrementMdDir(Se(e.docName));break;case`delete`:n.decrementMdDir(Se(e.docName));break;case`rename`:n.decrementMdDir(Se(e.oldDocName)),n.incrementMdDir(Se(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 hh(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 mh(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 gh(e,t,n,r,i){let{watch:a}=await import(`./chokidar-CUkbt9Pk.mjs`);console.warn(`[file-watcher] @parcel/watcher unavailable, using chokidar fallback`);let o=a(e,{ignoreInitial:!0,ignored:t?(n,r)=>{let i=Te(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,mh(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 _h(e,t,n){let r;try{r=pe(e)}catch{r=e}let i=new Map,a=new Map;fh(r,r,n,i,a);let o=setInterval(rh,th),s,c;try{let e=await hh(r,n,i,t,a);e?(s=e,c=`parcel`):(s=await gh(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 vh=(e,t,n)=>{let r=Pe(`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 yh(e,t,n,r=vh){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 bh(e,t,n){let r=(t,n)=>{let r=Pe(`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)}function xh(e){return e.replace(/[<>\r\n]/g,``).trim().slice(0,128)}const Sh=[/^https?:\/\//i,/^ssh:\/\//i,/^git:\/\//i,/^git@[^:]+:/],Ch=[/^file:\/\//i,/^javascript:/i,/^ext::/i,/^data:/i,/^vbscript:/i];function wh(e){return!e||typeof e!=`string`||Ch.some(t=>t.test(e))?!1:Sh.some(t=>t.test(e))}function Th(e){return e===`~`?ye():e.startsWith(`~/`)?V(ye(),e.slice(2)):e}function Eh(e){if(!e||typeof e!=`string`||e.includes(`\0`))return!1;let t=ye(),n=H(Th(e));return n===t||n.startsWith(`${t}/`)}function Dh(e){let t=e.socket.remoteAddress;return t===`127.0.0.1`||t===`::1`||t===`::ffff:127.0.0.1`}function Oh(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 kh(e,t,n){return Dh(e)?Oh(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 Ah(){let e=new Set;return{tryAcquire(t){return e.has(t)?!1:(e.add(t),!0)},release(t){e.delete(t)}}}function jh(e){return e?!!(e===`::1`||e.startsWith(`::ffff:127.`)||e.startsWith(`127.`)):!1}function Mh(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 Nh(e){return H(e,`.open-knowledge`)}function Ph(e){return H(Nh(e),`managed-rename.json`)}function Fh(e){return{version:1,sourceDocName:e.sourceDocName,destinationDocName:e.destinationDocName,createdAt:e.createdAt??new Date().toISOString(),snapshots:e.snapshots}}function Ih(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.docName==`string`&&typeof t.content==`string`}function Lh(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(Ih))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 Rh(e){let t=Ph(e);if(!R(t))return null;let n=z(t,`utf-8`);try{return Lh(JSON.parse(n))}catch(e){throw Error(`Managed rename journal at ${t} is corrupt: ${e instanceof Error?e.message:String(e)}`)}}function zh(e,t){let n=Ph(e);ue(Se(n),{recursive:!0});let r=`${n}.tmp`;B(r,JSON.stringify(t,null,2),`utf-8`),me(r,n)}function Bh(e){he(Ph(e),{force:!0})}async function Vh(e,t,n){zh(e,t);let r=await n();return Bh(e),r}function Hh(e){let t=Rh(e);if(!t)return{recovered:!1,journal:null,restoredDocNames:[]};let n=new Set,r=[];for(let i of t.snapshots)try{let t=Pm(i.docName,e);ue(Se(t),{recursive:!0}),B(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=Pm(t.destinationDocName,e);try{he(n,{force:!0})}catch(e){throw R(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 Bh(e),{recovered:!0,journal:t,restoredDocNames:[...n].sort((e,t)=>e.localeCompare(t))}}function Uh(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 Wh(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function Gh(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function Kh(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 qh(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 Jh(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 Yh(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 Xh(e,t,n){let r=``,i=0,a=0,o=Gh(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=Kh(e,a);if(t){r+=e.slice(a,t.nextIndex),a=t.nextIndex;continue}}if(e[a]===`[`&&e[a+1]===`[`){let o=qh(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 Zh(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 Qh(e,t,n,r){let i=``,a=0,o=0,s=Gh(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=Kh(e,o);if(t){i+=e.slice(o,t.nextIndex),o=t.nextIndex;continue}}if(e[o]===`[`&&e[o+1]===`[`){let t=qh(e,o);if(t){i+=e.slice(o,t.nextIndex),o=t.nextIndex;continue}}if(e[o]===`[`&&e[o-1]!==`!`){let s=Jh(e,o);if(s){if(E(s.href,t)?.docName===n){let e=Zh(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 $h(e,t,n){let r=null,i=0;return{markdown:Yh(e).map(({line:e,ending:a})=>{if(r)return Wh(e,r)&&(r=null),`${e}${a}`;let o=Uh(e);if(o)return r=o,`${e}${a}`;let s=Xh(e,t,n);return i+=s.rewrites,`${s.markdown}${a}`}).join(``),rewrites:i}}function eg(e,t,n,r){let i=null,a=0;return{markdown:Yh(e).map(({line:e,ending:o})=>{if(i)return Wh(e,i)&&(i=null),`${e}${o}`;let s=Uh(e);if(s)return i=s,`${e}${o}`;let c=Qh(e,t,n,r);return a+=c.rewrites,`${c.markdown}${o}`}).join(``),rewrites:a}}const tg=ln(`suggest-links`),ng=/[\p{L}\p{N}]/u,rg=/\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/y,ig=/\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y,ag=/!\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y;var og=class extends Error{constructor(e){super(`Document not found: ${e}`),this.name=`SuggestLinksTargetNotFoundError`}};function sg(e){return e.replace(/\s+/g,` `).trim()}function cg(e,t,n){if(!sg(e))return null;let r=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
54
+ `)}\n`:``;return o.length>0?{kind:`conflicts`,newContent:l,conflicts:o}:{kind:`merged`,newContent:l,mergedBlocks:a.length}}function ch(e,t){let n=new Map,r=lh(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 lh(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 uh=new Map,dh=1e4;function fh(e,t){let n=uh.get(e)??[];n.push({hash:t,timestamp:Date.now()}),uh.set(e,n)}function ph(){let e=Date.now();for(let[t,n]of uh){let r=n.filter(t=>e-t.timestamp<=dh);r.length===0?uh.delete(t):r.length!==n.length&&uh.set(t,r)}}function mh(e){return ke(`sha256`).update(e).digest(`hex`)}function hh(e,t){return zp(Te(t,e))}function gh(e){let t=e.toLowerCase();return t.endsWith(`.mdx`)?`.mdx`:t.endsWith(`.md`)?`.md`:null}const _h=new Map;function vh(e,t){_h.set(e,t)}function yh(e){let t=_h.get(e);return _h.delete(e),t}async function bh(e,t,n,r){let i=[],a=[],o=[];for(let r of e)if(Rp(r.path)){if(n){let e=Te(t,r.path);if(n.isExcluded(e))continue}switch(r.type){case`delete`:i.push(r);break;case`create`:_h.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 Le(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 Le(e.path,`utf-8`))}catch(t){t.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to read ${e.path}:`,t)}function l(e){let n=hh(e,t);if(!r)return n;let i=null;try{i=le(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=pe(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(!Gm(a,t))return r.delete(n),n;let o=hh(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=yh(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=mh(r);if(i===t){d.add(n.path),f.add(e.path),vh(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)||(yh(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=mh(t);vh(e.path,n),ih(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=mh(t);vh(e.path,n),ih(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 xh(e,t){let n=uh.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&&uh.delete(e),!0)}function Sh(e,t,n,r,i,a){let o=a??new Set;try{let a=fe(e,{withFileTypes:!0});for(let s of a){let a=V(e,s.name),c;try{c=le(a)}catch(e){e.code!==`ENOENT`&&console.warn(`[file-watcher] Failed to lstat ${a}, skipping:`,e);continue}if(c.isSymbolicLink()){let e;try{e=pe(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(!Gm(e,t)){console.warn(`[file-watcher] Symlink escape: ${a} → ${e}, skipping`);continue}try{let c=ge(e);if(o.has(c.ino)){if(c.isFile()&&Rp(s.name)){let n=hh(a,t),o=hh(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=Te(t,e);if(n.isDirExcluded(r))continue}Sh(e,t,n,r,i,o)}else if(c.isFile()&&Rp(s.name)){if(n){let r=Te(t,e);if(n.isExcluded(r))continue}let o=hh(a,t),s=hh(e,t);i.set(o,s);try{let t=mh(z(e,`utf-8`));_h.set(e,t);let n=gh(e);if(n){let e=Hp(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=Te(t,a);if(n.isDirExcluded(e))continue}Sh(a,t,n,r,i,o)}else if(c.isFile()&&Rp(s.name)){if(o.has(c.ino))continue;if(o.add(c.ino),n){let e=Te(t,a);if(n.isExcluded(e))continue}try{let e=z(a,`utf-8`);_h.set(a,mh(e));let n=hh(a,t),i=gh(a);if(i){let e=Hp(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 Ch(e,t){if(!J(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=gh(e.path);i&&Hp(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),Wp(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),Wp(e.oldDocName);let r=gh(e.newPath);r&&Hp(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 wh(e,t,n,r,i,a){let o=e.filter(e=>Rp(e.path));if(o.length===0)return;let s=await bh(o,t,n,a);for(let e of s){let t=!1;if(e.kind!==`delete`&&e.kind!==`rename`){let n=mh(e.content),r=e.path;try{r=pe(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=xh(r,n)}else if(e.kind===`rename`){let n=mh(e.content),r=e.newPath;try{r=pe(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=xh(r,n)}if(Ch(e,r),n)switch(e.kind){case`create`:n.incrementMdDir(Se(e.docName));break;case`delete`:n.decrementMdDir(Se(e.docName));break;case`rename`:n.decrementMdDir(Se(e.oldDocName)),n.incrementMdDir(Se(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 Th(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 wh(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 Eh(e,t,n,r,i){let{watch:a}=await import(`./chokidar-CUkbt9Pk.mjs`);console.warn(`[file-watcher] @parcel/watcher unavailable, using chokidar fallback`);let o=a(e,{ignoreInitial:!0,ignored:t?(n,r)=>{let i=Te(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,wh(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 Dh(e,t,n){let r;try{r=pe(e)}catch{r=e}let i=new Map,a=new Map;Sh(r,r,n,i,a);let o=setInterval(ph,dh),s,c;try{let e=await Th(r,n,i,t,a);e?(s=e,c=`parcel`):(s=await Eh(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 Oh=(e,t,n)=>{let r=Pe(`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 kh(e,t,n,r=Oh){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 Ah(e,t,n){let r=(t,n)=>{let r=Pe(`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)}function jh(e){return e.replace(/[<>\r\n]/g,``).trim().slice(0,128)}const Mh=[/^https?:\/\//i,/^ssh:\/\//i,/^git:\/\//i,/^git@[^:]+:/],Nh=[/^file:\/\//i,/^javascript:/i,/^ext::/i,/^data:/i,/^vbscript:/i];function Ph(e){return!e||typeof e!=`string`||Nh.some(t=>t.test(e))?!1:Mh.some(t=>t.test(e))}function Fh(e){return e===`~`?ye():e.startsWith(`~/`)?V(ye(),e.slice(2)):e}function Ih(e){if(!e||typeof e!=`string`||e.includes(`\0`))return!1;let t=ye(),n=H(Fh(e));return n===t||n.startsWith(`${t}/`)}function Lh(e){let t=e.socket.remoteAddress;return t===`127.0.0.1`||t===`::1`||t===`::ffff:127.0.0.1`}function Rh(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 zh(e,t,n){return Lh(e)?Rh(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 Bh(){let e=new Set;return{tryAcquire(t){return e.has(t)?!1:(e.add(t),!0)},release(t){e.delete(t)}}}function Vh(e){return e?!!(e===`::1`||e.startsWith(`::ffff:127.`)||e.startsWith(`127.`)):!1}function Hh(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 Uh(e){return H(e,`.open-knowledge`)}function Wh(e){return H(Uh(e),`managed-rename.json`)}function Gh(e){return{version:1,sourceDocName:e.sourceDocName,destinationDocName:e.destinationDocName,createdAt:e.createdAt??new Date().toISOString(),snapshots:e.snapshots}}function Kh(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.docName==`string`&&typeof t.content==`string`}function qh(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(Kh))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 Jh(e){let t=Wh(e);if(!R(t))return null;let n=z(t,`utf-8`);try{return qh(JSON.parse(n))}catch(e){throw Error(`Managed rename journal at ${t} is corrupt: ${e instanceof Error?e.message:String(e)}`)}}function Yh(e,t){let n=Wh(e);ue(Se(n),{recursive:!0});let r=`${n}.tmp`;B(r,JSON.stringify(t,null,2),`utf-8`),me(r,n)}function Xh(e){he(Wh(e),{force:!0})}async function Zh(e,t,n){Yh(e,t);let r=await n();return Xh(e),r}function Qh(e){let t=Jh(e);if(!t)return{recovered:!1,journal:null,restoredDocNames:[]};let n=new Set,r=[];for(let i of t.snapshots)try{let t=Wm(i.docName,e);ue(Se(t),{recursive:!0}),B(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=Wm(t.destinationDocName,e);try{he(n,{force:!0})}catch(e){throw R(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 Xh(e),{recovered:!0,journal:t,restoredDocNames:[...n].sort((e,t)=>e.localeCompare(t))}}function $h(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 eg(e,t){return RegExp(`^\\s{0,3}\\${t.char}{${t.length},}\\s*$`).test(e)}function tg(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function ng(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 rg(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 ig(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 ag(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 og(e,t,n){let r=``,i=0,a=0,o=tg(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=ng(e,a);if(t){r+=e.slice(a,t.nextIndex),a=t.nextIndex;continue}}if(e[a]===`[`&&e[a+1]===`[`){let o=rg(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 sg(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 cg(e,t,n,r){let i=``,a=0,o=0,s=tg(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=ng(e,o);if(t){i+=e.slice(o,t.nextIndex),o=t.nextIndex;continue}}if(e[o]===`[`&&e[o+1]===`[`){let t=rg(e,o);if(t){i+=e.slice(o,t.nextIndex),o=t.nextIndex;continue}}if(e[o]===`[`&&e[o-1]!==`!`){let s=ig(e,o);if(s){if(E(s.href,t)?.docName===n){let e=sg(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 lg(e,t,n){let r=null,i=0;return{markdown:ag(e).map(({line:e,ending:a})=>{if(r)return eg(e,r)&&(r=null),`${e}${a}`;let o=$h(e);if(o)return r=o,`${e}${a}`;let s=og(e,t,n);return i+=s.rewrites,`${s.markdown}${a}`}).join(``),rewrites:i}}function ug(e,t,n,r){let i=null,a=0;return{markdown:ag(e).map(({line:e,ending:o})=>{if(i)return eg(e,i)&&(i=null),`${e}${o}`;let s=$h(e);if(s)return i=s,`${e}${o}`;let c=cg(e,t,n,r);return a+=c.rewrites,`${c.markdown}${o}`}).join(``),rewrites:a}}const dg=ln(`suggest-links`),fg=/[\p{L}\p{N}]/u,pg=/\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]/y,mg=/\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y,hg=/!\[([^\]\n]*)\]\((<[^>\n]+>|[^)\s\n]+)(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\)/y;var gg=class extends Error{constructor(e){super(`Document not found: ${e}`),this.name=`SuggestLinksTargetNotFoundError`}};function _g(e){return e.replace(/\s+/g,` `).trim()}function vg(e,t,n){if(!_g(e))return null;let r=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
54
55
  `,t-1)),i=[e.indexOf(`.`,n),e.indexOf(`?`,n),e.indexOf(`!`,n),e.indexOf(`
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=sg(e.slice(a,o));return l?`${s}${l}${c}`:null}function lg(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 ug(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 dg(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function fg(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 pg(e,t){rg.lastIndex=t;let n=rg.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 mg(e){return e.startsWith(`<`)&&e.endsWith(`>`)?e.slice(1,-1):e}function hg(e,t){ig.lastIndex=t;let n=ig.exec(e);return n?{text:n[1]??``,href:mg(n[2]??``),nextIndex:t+n[0].length}:null}function gg(e,t){ag.lastIndex=t;let n=ag.exec(e);return n?{alt:n[1]??``,nextIndex:t+n[0].length}:null}function _g(e){return!e||!ng.test(e)}function vg(e,t,n){return _g(e[t-1])&&_g(e[n])}function yg(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 bg(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;vg(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 xg(e,t){let n=[];for(let r=0;r<t.length;r+=1)n.push(e+r);return n}function Sg(e,t){let n=e.trim();return n?n===t||_(n)===t:!1}function Cg(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=dg(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=fg(e,p);if(t){d(t.text),p=t.nextIndex;continue}}if(e[p]===`!`&&e[p+1]===`[`){let t=gg(e,p);if(t){d(t.alt),p=t.nextIndex;continue}}if(e[p]===`[`&&e[p+1]===`[`){let n=pg(e,p);if(n){let e=n.label;Sg(n.target,r)?d(e):f(e,xg(t+n.labelStart,e)),p=n.nextIndex;continue}}if(e[p]===`[`&&e[p-1]!==`!`){let i=hg(e,p);if(i){E(i.href,n)?.docName===r?d(i.text):f(i.text,xg(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=bg(e.text,i);for(let n of t){let t=e.flatStart+n.start,r=e.flatStart+n.end,i=cg(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 wg(e,t,n,r){let{frontmatter:i,body:a}=l(e),o=i.length,s=[],c=null,u=0,d=0;for(;d<=a.length;){let e=a[d];if(!(d===a.length||e===`
56
- `||e===`\r`)){d+=1;continue}let i=a.slice(u,d);if(c)ug(i,c)&&(c=null);else{let e=lg(i);e?c=e:s.push(...Cg(i,o+u,t,n,r))}if(d===a.length)break;if(e===`\r`&&a[d+1]===`
57
- `){d+=2,u=d;continue}d+=1,u=d}return s}function Tg(e){let t=e.getXmlFragment(`default`),n=wl.serialize(Sl(t,Tl).toJSON()),r=e.getMap(`metadata`).get(`frontmatter`);return M(typeof r==`string`?r:``,n)}async function Eg(e,t,n){let r=e.documents.get(t);if(r)try{return Tg(r)}catch(e){return tg.warn({docName:t,err:e},`[suggest-links] Failed live serialization, falling back to live source text`),r.getText(`source`).toString()}return await Le(n.canonicalPath,`utf-8`)}function Dg(e){return{docName:e.docName,title:e.title,aliases:e.aliases}}async function Og(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 og(r);let l=xp(await Eg(t,r,c),r),u=yg(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 Eg(t,e,o)}catch(t){tg.warn({docName:e,err:t},`[suggest-links] Failed to read source doc`);continue}let l=wg(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),h=a()-s,g={durationMs:h,corpusDocCount:d.length,candidateCount:m.length,truncated:p};return tg.info({docName:r,durationMs:h,corpusDocCount:d.length,candidateCount:m.length,truncated:p,labelCount:u.length,normalizedTarget:_(l.title)},`[suggest-links] scan completed`),o?.(g),{target:Dg(l),mentions:m,truncated:p}}const kg=`%H%x00%aI%x00%an%x00%ae%x00%s%x00%B%x1e`,Ag={entries:[],total:0,hasMore:!1};function jg(e){return e.startsWith(`checkpoint:`)?`checkpoint`:e.startsWith(`import:`)||e.startsWith(`upstream:`)?`upstream`:`wip`}function Mg(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=jg(o);return{sha:n.trim(),timestamp:r,author:i,authorEmail:a,type:c,message:o,contributors:Il(s),checkpoint:c===`checkpoint`?Rl(s):null}}).filter(e=>e!==null&&e.sha.length===40):[]}function Ng(e){return e?Array.isArray(e)?e:e.split(`,`).map(e=>e.trim()).filter(Boolean):[]}function Pg(e,t){return t.length===0?!0:t.some(t=>e.author.toLowerCase().includes(t.toLowerCase())||e.authorEmail.toLowerCase().includes(t.toLowerCase()))}async function Fg(e,t,n=`content`){if(!R(e.workTree)||!R(e.gitDir))return Ag;let r=t.branch??`main`,i=Math.max(1,t.limit??50),a=Math.max(0,t.offset??0),o=Ng(t.type),s=Ng(t.author),c=Ng(t.excludeAuthor),l=n.replace(/^\.\//,``),u=t.docName?l?`${l}/${t.docName}${Np(t.docName)}`:`${t.docName}${Np(t.docName)}`:void 0;try{let t=fm(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(`
56
+ `,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=_g(e.slice(a,o));return l?`${s}${l}${c}`:null}function yg(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 bg(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 xg(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function Sg(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 Cg(e,t){pg.lastIndex=t;let n=pg.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 wg(e){return e.startsWith(`<`)&&e.endsWith(`>`)?e.slice(1,-1):e}function Tg(e,t){mg.lastIndex=t;let n=mg.exec(e);return n?{text:n[1]??``,href:wg(n[2]??``),nextIndex:t+n[0].length}:null}function Eg(e,t){hg.lastIndex=t;let n=hg.exec(e);return n?{alt:n[1]??``,nextIndex:t+n[0].length}:null}function Dg(e){return!e||!fg.test(e)}function Og(e,t,n){return Dg(e[t-1])&&Dg(e[n])}function kg(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 Ag(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;Og(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 jg(e,t){let n=[];for(let r=0;r<t.length;r+=1)n.push(e+r);return n}function Mg(e,t){let n=e.trim();return n?n===t||_(n)===t:!1}function Ng(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=xg(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=Sg(e,p);if(t){d(t.text),p=t.nextIndex;continue}}if(e[p]===`!`&&e[p+1]===`[`){let t=Eg(e,p);if(t){d(t.alt),p=t.nextIndex;continue}}if(e[p]===`[`&&e[p+1]===`[`){let n=Cg(e,p);if(n){let e=n.label;Mg(n.target,r)?d(e):f(e,jg(t+n.labelStart,e)),p=n.nextIndex;continue}}if(e[p]===`[`&&e[p-1]!==`!`){let i=Tg(e,p);if(i){E(i.href,n)?.docName===r?d(i.text):f(i.text,jg(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=Ag(e.text,i);for(let n of t){let t=e.flatStart+n.start,r=e.flatStart+n.end,i=vg(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 Pg(e,t,n,r){let{frontmatter:i,body:a}=l(e),o=i.length,s=[],c=null,u=0,d=0;for(;d<=a.length;){let e=a[d];if(!(d===a.length||e===`
57
+ `||e===`\r`)){d+=1;continue}let i=a.slice(u,d);if(c)bg(i,c)&&(c=null);else{let e=yg(i);e?c=e:s.push(...Ng(i,o+u,t,n,r))}if(d===a.length)break;if(e===`\r`&&a[d+1]===`
58
+ `){d+=2,u=d;continue}d+=1,u=d}return s}function Fg(e){let t=e.getXmlFragment(`default`),n=Dl.serialize(Tl(t,Ol).toJSON()),r=e.getMap(`metadata`).get(`frontmatter`);return M(typeof r==`string`?r:``,n)}async function Ig(e,t,n){let r=e.documents.get(t);if(r)try{return Fg(r)}catch(e){return dg.warn({docName:t,err:e},`[suggest-links] Failed live serialization, falling back to live source text`),r.getText(`source`).toString()}return await Le(n.canonicalPath,`utf-8`)}function Lg(e){return{docName:e.docName,title:e.title,aliases:e.aliases}}async function Rg(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 gg(r);let l=jp(await Ig(t,r,c),r),u=kg(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 Ig(t,e,o)}catch(t){dg.warn({docName:e,err:t},`[suggest-links] Failed to read source doc`);continue}let l=Pg(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),h=a()-s,g={durationMs:h,corpusDocCount:d.length,candidateCount:m.length,truncated:p};return dg.info({docName:r,durationMs:h,corpusDocCount:d.length,candidateCount:m.length,truncated:p,labelCount:u.length,normalizedTarget:_(l.title)},`[suggest-links] scan completed`),o?.(g),{target:Lg(l),mentions:m,truncated:p}}const zg=`%H%x00%aI%x00%an%x00%ae%x00%s%x00%B%x1e`,Bg={entries:[],total:0,hasMore:!1};function Vg(e){return e.startsWith(`checkpoint:`)?`checkpoint`:e.startsWith(`import:`)||e.startsWith(`upstream:`)?`upstream`:`wip`}function Hg(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=Vg(o);return{sha:n.trim(),timestamp:r,author:i,authorEmail:a,type:c,message:o,contributors:Jl(s),checkpoint:c===`checkpoint`?Vl(s):null}}).filter(e=>e!==null&&e.sha.length===40):[]}function Ug(e){return e?Array.isArray(e)?e:e.split(`,`).map(e=>e.trim()).filter(Boolean):[]}function Wg(e,t){return t.length===0?!0:t.some(t=>e.author.toLowerCase().includes(t.toLowerCase())||e.authorEmail.toLowerCase().includes(t.toLowerCase()))}async function Gg(e,t,n=`content`){if(!R(e.workTree)||!R(e.gitDir))return Bg;let r=t.branch??`main`,i=Math.max(1,t.limit??50),a=Math.max(0,t.offset??0),o=Ug(t.type),s=Ug(t.author),c=Ug(t.excludeAuthor),l=n.replace(/^\.\//,``),u=t.docName?l?`${l}/${t.docName}${Up(t.docName)}`:`${t.docName}${Up(t.docName)}`:void 0;try{let t=Sm(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(`
58
59
  `).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(`
59
- `).filter(e=>e.length===40)}catch{}let o=[...e,...n];if(o.length===0)return Ag;let l=Mg(await t.raw(`log`,`--no-walk`,`--author-date-order`,`--format=${kg}`,...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=>Pg(e,s)&&(c.length===0||!Pg(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(`
60
+ `).filter(e=>e.length===40)}catch{}let o=[...e,...n];if(o.length===0)return Bg;let l=Hg(await t.raw(`log`,`--no-walk`,`--author-date-order`,`--format=${zg}`,...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=>Wg(e,s)&&(c.length===0||!Wg(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(`
60
61
  `).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(`
61
62
  `).filter(e=>e.length===40)}catch{}try{let e=(await t.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/${r}/`)).trim().split(`
62
63
  `).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(`
63
- `).filter(Boolean);l.push(...e)}catch{}if(l.length===0&&n.length===0&&f.length===0)return Ag;let p=[...n,...f],m=[];if(p.length>0){let e=Mg(await t.raw(`log`,`--no-walk`,`--author-date-order`,`--format=${kg}`,...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=Mg(await t.raw(`log`,`--full-history`,`--author-date-order`,`--format=${kg}`,...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=>Pg(e,s))),c.length>0&&(b=b.filter(e=>!Pg(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),Ag}}var Ig=e($l(),1);const Lg={source:`local`,skipStoreHooks:!1,context:{origin:`rollback-apply`,paired:!0}},Rg={source:`local`,skipStoreHooks:!1,context:{origin:`managed-rename`,paired:!0}},zg=ln(`api`);function Bg(e,t){if(!e||e.includes(`..`)||e.includes(`\0`))return{error:`Invalid document name`};let n=t.replace(/^\.\//,``),r=Np(e);return{path:n?`${n}/${e}${r}`:`${e}${r}`}}const Vg=new Set(o),Hg=/^(image\.(png|jpe?g|gif|webp)|Clipboard.*|Untitled.*)$/i;function Ug(e){let t=e.replace(/[/\\]/g,``),n=Ce(t);return(t.slice(0,t.length-n.length).replace(/[^a-zA-Z0-9_\-.]/g,`_`)||`upload`)+n.replace(/[^a-zA-Z0-9_.]/g,``)}function Wg(e,t,n){let r=Ce(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=H(e,t);try{let e=de(r,`wx`);try{ve(e,n)}finally{ce(e)}return t}catch(e){if(e.code===`EEXIST`)continue;throw e}}throw Error(`Could not find available filename after 100 attempts`)}function Gg(e,t){return new Promise((n,r)=>{let i;try{i=(0,Ig.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 Kg(e,t){let n=H(e,t);if(n!==e&&!n.startsWith(`${e}/`))throw Error(`Invalid directory: ${t}`);return n}function qg(e){return!e||e.startsWith(`/`)||e.includes(`\\`)||e.includes(`\0`)?!1:e.split(`/`).every(e=>e&&e!==`.`&&e!==`..`)}function Jg(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 Yg(e,t,n,r){return t===`file`||e===n?r:`${r}${e.slice(n.length)}`}function Xg(e,t,n,r){let{frontmatter:i,body:a}=l(e),o=$h(a,n,r),s=eg(o.markdown,t,n,r);return{markdown:M(i,s.markdown),rewrites:o.rewrites+s.rewrites}}function Zg(e,t){let n;try{n=pe(t)}catch{return}let r=e;for(;;)try{if(!Fm(pe(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=Se(r);if(i===r||i!==t&&!i.startsWith(`${t}${Ee}`))throw e;r=i}}function Qg(e,t,n){if(!qg(n))throw Error(`path must be a relative content path`);let r=H(e),i=H(r,t===`file`?`${n}${Np(n)}`:n);if(i!==r&&!i.startsWith(`${r}${Ee}`))throw Error(`path must not escape content directory`);return Zg(i,r),i}function $g(e,t){let n=H(e),r=H(t);return r!==n&&!r.startsWith(`${n}${Ee}`)?null:Te(n,r).split(Ee).join(`/`)}async function e_(e,t,n){if(!e)return!1;let r=$g(e,t),i=$g(e,n);return!r||!i?!1:await oe(async()=>{let t=Fe({baseDir:e,timeout:{block:15e3}});if(!(await t.raw(`ls-files`,`--`,r)).trim())return!1;ue(Se(n),{recursive:!0});try{return await t.raw(`mv`,`--`,r,i),!0}catch(e){return console.warn(`[renameTrackedPathInGit] git mv failed, falling back to fs rename:`,e),!1}})}async function t_(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 Y(e,t,n,r){e.writeHead(t,{"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`,...r}),e.end(JSON.stringify(n))}function n_(e){let t=e;if(e.startsWith(`---
64
+ `).filter(Boolean);l.push(...e)}catch{}if(l.length===0&&n.length===0&&f.length===0)return Bg;let p=[...n,...f],m=[];if(p.length>0){let e=Hg(await t.raw(`log`,`--no-walk`,`--author-date-order`,`--format=${zg}`,...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=Hg(await t.raw(`log`,`--full-history`,`--author-date-order`,`--format=${zg}`,...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=>Wg(e,s))),c.length>0&&(b=b.filter(e=>!Wg(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),Bg}}var Kg=e(cu(),1);const qg={source:`local`,skipStoreHooks:!1,context:{origin:`rollback-apply`,paired:!0}},Jg={source:`local`,skipStoreHooks:!1,context:{origin:`managed-rename`,paired:!0}},Yg=ln(`api`);function Xg(e,t){if(!e||e.includes(`..`)||e.includes(`\0`))return{error:`Invalid document name`};let n=t.replace(/^\.\//,``),r=Up(e);return{path:n?`${n}/${e}${r}`:`${e}${r}`}}const Zg=new Set(o),Qg=/^(image\.(png|jpe?g|gif|webp)|Clipboard.*|Untitled.*)$/i;function $g(e){let t=e.replace(/[/\\]/g,``),n=Ce(t);return(t.slice(0,t.length-n.length).replace(/[^a-zA-Z0-9_\-.]/g,`_`)||`upload`)+n.replace(/[^a-zA-Z0-9_.]/g,``)}function e_(e,t,n){let r=Ce(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=H(e,t);try{let e=de(r,`wx`);try{ve(e,n)}finally{ce(e)}return t}catch(e){if(e.code===`EEXIST`)continue;throw e}}throw Error(`Could not find available filename after 100 attempts`)}function t_(e,t){return new Promise((n,r)=>{let i;try{i=(0,Kg.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 n_(e,t){let n=H(e,t);if(n!==e&&!n.startsWith(`${e}/`))throw Error(`Invalid directory: ${t}`);return n}function r_(e){return!e||e.startsWith(`/`)||e.includes(`\\`)||e.includes(`\0`)?!1:e.split(`/`).every(e=>e&&e!==`.`&&e!==`..`)}function i_(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 a_(e,t,n,r){return t===`file`||e===n?r:`${r}${e.slice(n.length)}`}function o_(e,t,n,r){let{frontmatter:i,body:a}=l(e),o=lg(a,n,r),s=ug(o.markdown,t,n,r);return{markdown:M(i,s.markdown),rewrites:o.rewrites+s.rewrites}}function s_(e,t){let n;try{n=pe(t)}catch{return}let r=e;for(;;)try{if(!Gm(pe(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=Se(r);if(i===r||i!==t&&!i.startsWith(`${t}${Ee}`))throw e;r=i}}function c_(e,t,n){if(!r_(n))throw Error(`path must be a relative content path`);let r=H(e),i=H(r,t===`file`?`${n}${Up(n)}`:n);if(i!==r&&!i.startsWith(`${r}${Ee}`))throw Error(`path must not escape content directory`);return s_(i,r),i}function l_(e,t){let n=H(e),r=H(t);return r!==n&&!r.startsWith(`${n}${Ee}`)?null:Te(n,r).split(Ee).join(`/`)}async function u_(e,t,n){if(!e)return!1;let r=l_(e,t),i=l_(e,n);return!r||!i?!1:await oe(async()=>{let t=Fe({baseDir:e,timeout:{block:15e3}});if(!(await t.raw(`ls-files`,`--`,r)).trim())return!1;ue(Se(n),{recursive:!0});try{return await t.raw(`mv`,`--`,r,i),!0}catch(e){return console.warn(`[renameTrackedPathInGit] git mv failed, falling back to fs rename:`,e),!1}})}async function d_(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 Y(e,t,n,r){e.writeHead(t,{"Content-Type":`application/json`,"X-Content-Type-Options":`nosniff`,...r}),e.end(JSON.stringify(n))}function f_(e){let t=e;if(e.startsWith(`---
64
65
  `)||e.startsWith(`---\r
65
66
  `)){let n=e.indexOf(`
66
67
  ---`,3);n!==-1&&(t=e.slice(n+4))}let n=[],r=new Map,i=D();for(let e of t.split(`
67
- `)){if(i(e))continue;let t=e.match(/^(#{1,6})\s+(.+)$/);if(t){let e=t[2].trim(),i=v(e,r);i&&n.push({level:t[1].length,text:e,slug:i})}}return n}function r_(e){return!(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))}function i_(e){if(e===`null`)return!0;try{let{hostname:t}=new URL(e);return t===`localhost`||t===`::1`||t===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}catch{return!1}}function a_(e){let{hocuspocus:t,sessionManager:n,contentDir:i,getFileIndex:a,getAliasMap:o,enableTestRoutes:s=!1,shadowRef:c,flushGitCommit:u,getCurrentBranch:d,contentRoot:p,backlinkIndex:m,signalChannel:h,agentFocusBroadcaster:g,agentPresenceBroadcaster:_,onAgentWrite:v,getSyncEngine:b,localOpCliArgs:x=[`open-knowledge`],projectDir:S,getPrincipal:C,installedAgentsProbe:E}=e,D=Ah(),O=Qf({probe:E??tp(process.platform)});function k(e){if(!r_(e))return null;let t=H(i),n=H(t,`${e}${Np(e)}`);return!n.startsWith(`${t}/`)&&n!==t?null:n}function j(e){let t=k(e);if(!t||!R(t))return e;try{return vp(z(t,`utf-8`),e)}catch{return e}}let N={cluster:void 0,category:void 0,tags:void 0};function P(e){try{let n=t.documents.get(e);if(n){let e=n.getMap(`metadata`).get(`frontmatter`);if(typeof e==`string`&&e)return yp(e)}}catch{}try{let t=k(e);if(!t||!R(t))return N;let{frontmatter:n}=l(z(t,`utf-8`));return n?yp(n):N}catch{return N}}function ee(e){if(m)try{if(m.getBacklinks(e).length>0)return;let t=performance.now(),n=op(e,a()),r=performance.now()-t;return r>5&&zg.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 te(e){return o?.().get(e)??e}function ne(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function re(e,n){let r=`onStoreDocument-${e}`;(t.debouncer.isDebounced(r)?t.debouncer.executeNow(r):Promise.resolve()).then(()=>u?.()).catch(e=>{zg.warn({err:e},`[${n}] post-write flush failed`)})}function F(){let e=new Set;for(let[t,n]of a()){e.add(t);for(let t of n.aliases)e.add(t)}return e}function ae(){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 I=ae();function L(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 se(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);Hm(n),e&&(t.closeConnections(n),await t.unloadDocument(e))}return r}function ce(e,t){for(let{fromDocName:n,toDocName:r}of e){let e=Pm(r,i),a=t.get(n);typeof a==`string`&&B(e,a,`utf-8`);let o=typeof a==`string`?a:R(e)?z(e,`utf-8`):null;typeof o==`string`&&nh(e,ih(o))}}function le(e,t){return e.map(e=>{let n=t.get(e);if(typeof n==`string`)return{docName:e,content:n};let r=Pm(e,i);if(!R(r))throw Error(`Cannot snapshot missing document: ${e}`);return{docName:e,content:z(r,`utf-8`)}})}function de(e){let n=t.documents.get(e);if(n)return n.getText(`source`).toString();let r=Qg(i,`file`,e);return R(r)?z(r,`utf-8`):null}function ve(e,t){let n=Qg(i,`file`,e);ue(Se(n),{recursive:!0}),B(n,t,`utf-8`),nh(n,ih(t)),Vm(e,t);let r=a();r instanceof Map&&ph({kind:`update`,path:n,docName:e,content:t},r)}function ye(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=Xg(s,e,n,r),a.rewrites===0)return;let{body:c}=l(a.markdown),u=wl.parseWithFallback(c);yl(i,t,Tl.nodeFromJSON(u),{mapping:new Map,isOMark:new Map}),T(o,s,a.markdown)},Rg),a}async function be(e,n){return I(async()=>{if(!m)throw Error(`Managed rename requires backlink index support`);let r=Qg(i,`file`,e),o=Qg(i,`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=de(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=Fh({sourceDocName:e,destinationDocName:n,snapshots:le([...l.keys()],l)}),p=[];return await Vh(i,f,async()=>{for(let e of d)m.deleteDocument(e);for(let r of u){let i=t.documents.get(r)?ye(r,e,n):Xg(l.get(r)??``,r,e,n);i.rewrites>0&&(ve(r,i.markdown),p.push({docName:r,rewrites:i.rewrites})),m.updateDocumentFromMarkdown(r,i.markdown)}let i=Xg((await se([e])).get(e)??l.get(e)??z(r,`utf-8`),e,e,n);await e_(S,r,o)||(ue(Se(o),{recursive:!0}),me(r,o)),ce(s,new Map([[e,i.markdown]])),Vm(n,i.markdown);let c=a();c instanceof Map&&ph({kind:`rename`,oldPath:r,newPath:o,oldDocName:e,newDocName:n,content:i.markdown},c),m.renameDocument(e,n,i.markdown),i.rewrites>0&&p.push({docName:n,rewrites:i.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}})}function xe(e){let t=typeof e.agentId==`string`?e.agentId:void 0;t!==void 0&&!fn.test(t)&&(t=void 0);let n=t?mn(t):`claude-1`,r=typeof e.agentName==`string`?xh(e.agentName):`Claude`,i=typeof e.clientName==`string`?e.clientName:void 0;i!==void 0&&(i=xh(i));let a=typeof e.clientVersion==`string`?e.clientVersion:void 0;a!==void 0&&(a=xh(a));let o=typeof e.label==`string`?e.label:void 0;o!==void 0&&(o=xh(o));let s=typeof e.colorSeed==`string`&&e.colorSeed.length>0?e.colorSeed.slice(0,128):t??n;return{rawAgentId:t,agentId:n,agentName:r,colorSeed:s,clientName:i,clientVersion:a,label:o}}function Ce(e){if(!e)return`bot`;let t=e.toLowerCase();return t.includes(`claude`)?`claude`:t.includes(`cursor`)?`cursor`:t.includes(`codex`)?`codex`:t.includes(`cline`)?`cline`:t.includes(`windsurf`)?`windsurf`:`bot`}function V(e){return{principalId:C?.()?.id,agentType:Ce(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}async function we(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await t_(e)}catch{Y(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=r.length>0?JSON.parse(r.toString()):{}}catch{Y(t,400,{ok:!1,error:`Invalid JSON`});return}let a=typeof i.docName==`string`&&i.docName.length>0?i.docName:`test-doc`;if(!r_(a)){Y(t,400,{ok:!1,error:`Invalid docName`});return}let o=te(a);if(J(o)){Y(t,400,{ok:!1,error:`'${o}' is a reserved document name`});return}let{agentId:s,agentName:c,colorSeed:l,clientName:u,clientVersion:d,label:p}=xe(i),m=await n.getSession(o,s,{displayName:c,colorSeed:l,clientName:u}),h=new Date().toISOString(),g=typeof i.content==`string`?i.content:`Hello from the agent! ${h}`;try{let e=w(u),t=y[e]??f(l??s);_?.setPresence(s,{displayName:c,icon:e,color:t,currentDoc:o,mode:`writing`,ts:Date.now()}),Vf(m.dc.document.getText(`source`),s,l,u),m.dc.document.transact(()=>{Dl(m.dc.document,`${g}\n`,`append`),m.dc.document.getMap(`agent-flash`).set(s,{agentId:s,timestamp:Date.now(),type:`insert`,description:`Added (${c}): ${g.slice(0,50)}`})},m.origin),Uf(o,s,c,l,void 0,V({clientName:u,clientVersion:d,label:p}))}finally{_?.touchMode(s,`idle`)}re(o,`agent-write`),v?.(),Y(t,200,{ok:!0,timestamp:h})}catch(e){zg.error({err:e},`[agent-write] handler failed`),Y(t,500,{ok:!1,error:`Internal server error`})}}async function De(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await t_(e)}catch{Y(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(r.toString())}catch{Y(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){Y(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{markdown:a,position:o}=i;if(!a||typeof a!=`string`){Y(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(!r_(l)){Y(t,400,{ok:!1,error:`Invalid docName`});return}let u=te(l);if(J(u)){Y(t,400,{ok:!1,error:`'${u}' is a reserved document name`});return}let{agentId:d,agentName:p,colorSeed:m,clientName:h,clientVersion:b,label:x}=xe(i),S=await n.getSession(u,d,{displayName:p,colorSeed:m,clientName:h}),C=new Date().toISOString();try{let e=w(h),t=y[e]??f(m??d);_?.setPresence(d,{displayName:p,icon:e,color:t,currentDoc:u,mode:`writing`,ts:Date.now()}),Vf(S.dc.document.getText(`source`),d,m,h),S.dc.document.transact(()=>{Dl(S.dc.document,a,s),S.dc.document.getMap(`agent-flash`).set(d,{agentId:d,timestamp:Date.now(),type:`insert`,description:`Added (${p}): ${a.trim().slice(0,50)}`})},S.origin),Uf(u,d,p,m,void 0,V({clientName:h,clientVersion:b,label:x}))}finally{_?.touchMode(d,`idle`)}re(u,`agent-write-md`),g?.setFocus(d,{agentName:p,currentDoc:u,writeKind:`write`,ts:Date.now()}),v?.();let T=ee(u);Y(t,200,{ok:!0,timestamp:C,subscriberCount:ne(u),...T?{hints:T}:{}})}catch(e){zg.error({err:e},`[agent-write-md] handler failed`),Y(t,500,{ok:!1,error:`Internal server error`})}}async function Oe(e,n){if(e.method!==`GET`){n.writeHead(405),n.end(`Method not allowed`);return}try{let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!r_(r)){Y(n,400,{ok:!1,error:`Invalid docName`});return}let i=te(r);if(J(i)){Y(n,400,{ok:!1,error:`'${i}' is a reserved document name`});return}let a=await t.openDirectConnection(i);try{let e=a.document;if(!e){Y(n,500,{ok:!1,error:`Document not available`});return}Y(n,200,{ok:!0,docName:i,content:e.getText(`source`).toString()})}finally{await a.disconnect()}}catch(e){console.error(`[document-read]`,e),Y(n,500,{ok:!1,error:`Internal server error`})}}async function ke(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{Kg(i,n)}catch{Y(t,400,{ok:!1,error:`Invalid directory parameter`});return}let r=a(),o=[];for(let[e,t]of r)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 r of t.aliases){if(n&&!r.startsWith(`${n}/`)&&r!==n)continue;let a=Te(i,t.canonicalPath);o.push({docName:r,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:a})}}o.sort((e,t)=>e.docName.localeCompare(t.docName)),Y(t,200,{ok:!0,documents:o})}catch(e){console.error(`[document-list]`,e),Y(t,500,{ok:!1,error:`Internal server error`})}}async function Ae(e,t){if(e.method!==`GET`){Y(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){Y(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){Y(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!r_(n)){Y(t,400,{ok:!1,error:`Invalid docName`});return}Y(t,200,{ok:!0,docName:n,backlinks:m.getBacklinks(n).map(e=>({source:e.source,anchor:e.anchor,title:j(e.source),snippet:e.snippet}))})}catch(e){console.error(`[backlinks]`,e),Y(t,500,{ok:!1,error:`Failed to read backlinks`})}}async function je(e,t){if(e.method!==`GET`){Y(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){Y(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!n){Y(t,400,{ok:!1,error:`Missing docNames parameter`});return}let r={};for(let e of n.split(`,`)){let t=e.trim();!t||!r_(t)||(r[t]=m.getBacklinkCount(t))}Y(t,200,{ok:!0,counts:r})}catch(e){console.error(`[backlink-counts]`,e),Y(t,500,{ok:!1,error:`Failed to read backlink counts`})}}async function Me(e,t){if(e.method!==`GET`){Y(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){Y(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){Y(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!r_(n)){Y(t,400,{ok:!1,error:`Invalid docName`});return}Y(t,200,{ok:!0,docName:n,forwardLinks:m.getForwardLinkEntries(n).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:j(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),Y(t,500,{ok:!1,error:`Failed to read forward links`})}}async function Pe(e,t){if(e.method!==`GET`){Y(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){Y(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&&!r_(r)){Y(t,400,{ok:!1,error:`Invalid docName`});return}let i=n.searchParams.get(`degrees`);if(i&&!r){Y(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){Y(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());Y(t,200,{ok:!0,nodes:a.map(e=>{if(e.kind===`doc`){let t=P(e.docName);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:j(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),Y(t,500,{ok:!1,error:`Failed to read link graph`})}}async function Ie(e,t){if(e.method!==`GET`){Y(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){Y(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!r(n)){Y(t,400,{ok:!1,error:`Invalid orphan mode. Allowed values: incoming, outgoing, both`});return}Y(t,200,{ok:!0,orphans:m.getOrphans([...a().keys()],n).map(e=>({docName:e,title:j(e)}))})}catch(e){console.error(`[orphans]`,e),Y(t,500,{ok:!1,error:`Failed to read orphan pages`})}}async function Le(e,t){if(e.method!==`GET`){Y(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){Y(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;Y(t,200,{ok:!0,hubs:m.getHubs(i).map(e=>({docName:e.docName,title:j(e.docName),count:e.count}))})}catch(e){console.error(`[hubs]`,e),Y(t,500,{ok:!1,error:`Failed to read hub pages`})}}async function Re(e,t){if(e.method!==`GET`){Y(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){Y(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||!r_(e))){Y(t,400,{ok:!1,error:`Invalid sourceDocName`});return}let r=n.length?[...new Set(n.map(e=>te(e)))]:void 0;Y(t,200,{ok:!0,deadLinks:m.getDeadLinks(F(),r).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:j(e.source),snippet:e.snippet}))}))})}catch(e){console.error(`[dead-links]`,e),Y(t,500,{ok:!1,error:`Failed to read dead links`})}}async function ze(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await t_(e)}catch{Y(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(r.toString())}catch{Y(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){Y(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){Y(t,400,{ok:!1,error:`find field required`});return}if(typeof o!=`string`){Y(t,400,{ok:!1,error:`replace field required`});return}let u=Object.hasOwn(i,`offset`),d;if(u){if(typeof c!=`number`||!Number.isInteger(c)||c<0){Y(t,400,{ok:!1,error:`offset must be a non-negative integer`});return}d=c}let p=typeof s==`string`&&s.length>0?s:`test-doc`;if(!r_(p)){Y(t,400,{ok:!1,error:`Invalid docName`});return}let m=te(p);if(J(m)){Y(t,400,{ok:!1,error:`'${m}' is a reserved document name`});return}let{agentId:h,agentName:b,colorSeed:x,clientName:S,clientVersion:C,label:T}=xe(i),E=await n.getSession(m,h,{displayName:b,colorSeed:x,clientName:S}),D=new Date().toISOString(),O=!1,k=!1;try{let e=w(S),t=y[e]??f(x??h);_?.setPresence(h,{displayName:b,icon:e,color:t,currentDoc:m,mode:`writing`,ts:Date.now()}),Vf(E.dc.document.getText(`source`),h,x,S),E.dc.document.transact(()=>{let e=E.dc.document.getXmlFragment(`default`),t=E.dc.document.getMap(`metadata`),n=t.get(`frontmatter`)??``,r=M(n,wl.serialize(Sl(e,Tl).toJSON())),i=d==null?r.indexOf(a):r.slice(d,d+a.length)===a?d:-1;if(i===-1){d==null?O=!0:k=!0;return}let{frontmatter:s,body:c}=l(r.slice(0,i)+o+r.slice(i+a.length));s!==n&&t.set(`frontmatter`,s),Dl(E.dc.document,c,`replace`),E.dc.document.getMap(`agent-flash`).set(h,{agentId:h,timestamp:Date.now(),type:`insert`,description:`Patched (${b}): ${a.slice(0,50)}`})},E.origin),!O&&!k&&Uf(m,h,b,x,void 0,V({clientName:S,clientVersion:C,label:T}))}finally{_?.touchMode(h,`idle`)}if(k){Y(t,409,{ok:!1,error:`Target text no longer matches at the requested offset`});return}if(O){Y(t,404,{ok:!1,error:`Text not found in document`});return}re(m,`agent-patch`),g?.setFocus(h,{agentName:b,currentDoc:m,writeKind:`edit`,ts:Date.now()}),v?.(),Y(t,200,{ok:!0,timestamp:D,subscriberCount:ne(m)})}catch(e){zg.error({err:e},`[agent-patch] handler failed`),Y(t,500,{ok:!1,error:`Internal server error`})}}async function Be(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await t_(e)}catch{Y(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=r.length>0?JSON.parse(r.toString()):{}}catch{Y(t,400,{ok:!1,error:`Invalid JSON`});return}let{agentId:a,agentName:o,colorSeed:s,clientName:c,clientVersion:l,label:u}=xe(i),d=typeof i.docName==`string`&&i.docName.length>0?i.docName:`test-doc`;if(!r_(d)){Y(t,400,{ok:!1,error:`Invalid docName`});return}let p=te(d);if(J(p)){Y(t,400,{ok:!1,error:`'${p}' is a reserved document name`});return}let m=typeof i.connectionId==`string`?i.connectionId:void 0;if(!m){Y(t,400,{ok:!1,error:`connectionId required`});return}let h=i.scope===`session`?`session`:`last`;if(!n.hasSession(p,m)){Y(t,404,{ok:!1,error:`No active session for this connectionId and docName`});return}let v=await n.getSession(p,m),b=!1;try{let e=w(c),t=y[e]??f(s??a);_?.setPresence(a,{displayName:o,icon:e,color:t,currentDoc:p,mode:`writing`,ts:Date.now()}),b=Ol(v,h),b&&Uf(p,m,o,s,void 0,V({clientName:c,clientVersion:l,label:u}))}finally{_?.touchMode(a,`idle`)}b&&re(p,`agent-undo`),g?.setFocus(m,{agentName:m,currentDoc:p,writeKind:`undo`,ts:Date.now()}),Y(t,200,{ok:!0,docName:p,scope:h,undone:b})}catch(e){zg.error({err:e},`[agent-undo] handler failed`),Y(t,500,{ok:!1,error:`Internal server error`})}}async function Ve(e,r){if(e.method!==`POST`){r.writeHead(405),r.end(`Method not allowed`);return}try{let a=te(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??`test-doc`),o;try{o=Pm(a,i)}catch(e){console.error(`[test-reset] safeContentPath rejected docName:`,a,e),Y(r,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),B(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`),Y(r,200,{ok:!0})}catch(e){console.error(`[test-reset]`,e),Y(r,500,{ok:!1,error:`Internal server error`})}}async function He(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{if(!m){Y(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`),Y(t,200,{ok:!0})}catch(e){console.error(`[test-rescan-backlinks]`,e),Y(t,500,{ok:!1,error:`Internal server error`})}}async function Ue(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}let n=c?.current;if(!n){Y(t,400,{ok:!1,error:`Shadow repo not configured`});return}try{let r;try{r=await t_(e)}catch{Y(t,413,{ok:!1,error:`Payload too large`});return}let i=/^[a-zA-Z0-9_-]+$/,a=[],o,s={},c,l;if(r.length>0){let e;try{e=JSON.parse(r.toString())}catch{Y(t,400,{ok:!1,error:`Invalid JSON`});return}s=e,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,``)}}));let n=e.principal;if(n&&typeof n==`object`&&!Array.isArray(n)){let e=n;typeof e.name==`string`&&e.name.trim()&&(c=xh(e.name.trim())),typeof e.email==`string`&&e.email.trim()&&(l=xh(e.email.trim()))}}let{rawAgentId:u,agentId:d,agentName:f,clientName:m}=xe(s);a.length===0&&(a=u===void 0?[Sm]:[{id:d,name:m?`${f} (${m})`:f,email:`${d}@openknowledge.local`}]);let h=p??`content`,g=await jm(n,h,a);console.log(`[history] checkpoint ${g.checkpointRef}`);let _=Wf(),v;if(S){let e=!1;try{await Fe({baseDir:S,timeout:{block:5e3}}).revparse([`--git-dir`]),e=!0}catch(e){console.warn(`[save-version] parent-git unavailable: ${e instanceof Error?e.message:String(e)}`)}if(e)try{v=await oe(async()=>{let e=Fe({baseDir:S,timeout:{block:15e3}}),t=(await e.tags([`--list`,`ok/v*`])).all.length+1,n=`ok/v${t}`,r=`openknowledge`,i=`noreply@openknowledge.local`;if(c&&l)r=c,i=l;else try{let e=await yh(S);e&&(r=e.name,i=e.email)}catch{}let a=[];for(let e of _.values())if(e.writerId.startsWith(`agent-`)||e.writerId.startsWith(`principal-`)){let t=`${e.writerId}@openknowledge.local`;a.push(`Co-Authored-By: ${e.displayName} <${t}>`)}let s=Kl(o??`Checkpoint v${t}`),u=a.length>0?`${s}\n\n${a.join(`
68
- `)}`:s,d=h||`.`;return await e.add(d),await e.env({GIT_AUTHOR_NAME:r,GIT_AUTHOR_EMAIL:i,GIT_COMMITTER_NAME:r,GIT_COMMITTER_EMAIL:i}).commit(u,[`--allow-empty`]),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)}}Y(t,200,{ok:!0,checkpointRef:g.checkpointRef,...v?{versionTag:v}:{}})}catch(e){console.error(`[save-version]`,e),Y(t,500,{ok:!1,error:`Internal server error`})}}async function We(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=c?.current;if(!n){Y(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){Y(t,400,{ok:!1,error:`docName query parameter is required`});return}if(a.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(a)){Y(t,400,{ok:!1,error:`Invalid branch name`});return}let o=Number(r.searchParams.get(`limit`)??`50`),s=Number(r.searchParams.get(`offset`)??`0`),l=Math.min(200,Number.isFinite(o)?o:50),u=Number.isFinite(s)?s:0,f=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 Fg(n,{docName:i,branch:a,limit:l,offset:u,type:f,author:m,excludeAuthor:h},p??`content`),r=Date.now()-g;console.log(`[timeline] query docName=${i} entries=${e.entries.length} duration=${r}ms`),Y(t,200,{ok:!0,...e})}catch(e){console.error(`[shadow]`,e),Y(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function Ge(e,t,n){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let r=c?.current;if(!r){Y(t,400,{ok:!1,error:`Shadow repo not configured`});return}let i=Bg(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,p??`content`);if(`error`in i){Y(t,400,{ok:!1,error:i.error});return}let a=i.path,o=fm(r);if(!/^[0-9a-f]{40}$/i.test(n)){Y(t,400,{ok:!1,error:`Invalid commit SHA`});return}try{try{await o.raw(`cat-file`,`-e`,`${n}:${a}`)}catch{Y(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`);Y(t,200,{ok:!0,sha:n,content:e,timestamp:r,author:i})}catch(e){console.error(`[shadow-version]`,e),Y(t,500,{ok:!1,error:`Internal server error`})}}async function Ke(e,n){if(e.method!==`GET`){n.writeHead(405),n.end(`Method not allowed`);return}let r=c?.current;if(!r){Y(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`)??``,s=i.searchParams.get(`to`)??``;if(!s||!/^[0-9a-f]{40}$/i.test(s)){Y(n,400,{ok:!1,error:`'to' must be a valid 40-char commit SHA`});return}let u=Bg(a,p??`content`);if(`error`in u){Y(n,400,{ok:!1,error:u.error});return}let d=u.path,f=fm(r);try{let e;try{e=await f.raw(`show`,`${s}:${d}`)}catch{Y(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 f.raw(`show`,`${o}:${d}`)}catch{Y(n,404,{ok:!1,error:`Document did not exist at the source version`});return}else{let e=t.documents.get(a);if(!e){Y(n,409,{ok:!1,error:`Document is not currently open — open it in the editor first`});return}r=e.getText(`source`).toString()}let i=l(r).body,c=l(e).body,u=_u(i,c),p=[],m=0,h=0;for(let e of u){let t=e.value.replace(/\n$/,``).split(`
69
- `),n=e.added?`added`:e.removed?`removed`:`unchanged`;for(let e of t)p.push({type:n,text:e});e.added&&(m+=t.length),e.removed&&(h+=t.length)}Y(n,200,{ok:!0,lines:p,additions:m,deletions:h})}catch(e){console.error(`[diff]`,e),Y(n,500,{ok:!1,error:`Internal server error`})}}async function qe(e,n){if(e.method!==`POST`){n.writeHead(405),n.end(`Method not allowed`);return}let r=c?.current;if(!r){Y(n,400,{ok:!1,error:`Shadow repo not configured`});return}let i;try{i=await t_(e)}catch{Y(n,413,{ok:!1,error:`Payload too large`});return}let a;try{a=i.length>0?JSON.parse(i.toString()):{}}catch{Y(n,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){Y(n,400,{ok:!1,error:`Body must be a JSON object`});return}let{agentId:o,agentName:s,colorSeed:d,clientName:f,clientVersion:m,label:h}=xe(a),{docName:_,commitSha:v,versionTag:y}=a,b=typeof _==`string`?_:``,x=typeof v==`string`?v:``,C=typeof y==`string`?y:void 0;if(!b){Y(n,400,{ok:!1,error:`docName required`});return}if(!x||!/^[0-9a-f]{40}$/i.test(x)){Y(n,400,{ok:!1,error:`commitSha must be a valid 40-char commit SHA`});return}let w=p??`content`,T=Bg(b,w);if(`error`in T){Y(n,400,{ok:!1,error:T.error});return}let E=T.path,D=fm(r),O=Date.now();try{try{await D.raw(`cat-file`,`-e`,`${x}:${E}`)}catch{Y(n,404,{ok:!1,error:`Document did not exist at this version`});return}let e=await D.raw(`show`,`${x}:${E}`),i=new Date().toISOString();await Em(r,w,{action:`rollback`,context:{docName:b,targetSha:x}});let a=t.documents.get(b);if(!a){Y(n,409,{ok:!1,error:`Document is not currently open — open it in the editor first`});return}let{frontmatter:c,body:_}=l(e),v=wl.parseWithFallback(_),y=Tl.nodeFromJSON(v),T=a.getXmlFragment(`default`);a.transact(()=>{yl(a,T,y,{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`,c)},Lg),Uf(b,o,s,d,Ul(b,x),V({clientName:f,clientVersion:m,label:h})),Vm(b,e),u&&u().catch(e=>{console.warn(`[rollback] flush git commit failed:`,e)});let k=Date.now()-O;if(console.log(`[rollback] docName=${b} from=${x.slice(0,8)} duration=${k}ms`),S){let e=`Restored to ${C??x.slice(0,8)}: ${b}`,t=p??`content`;oe(async()=>{let n=Fe({baseDir:S,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)})}g?.setFocus(o,{agentName:s,currentDoc:b,writeKind:`rollback-apply`,ts:Date.now()}),Y(n,200,{ok:!0,restoredFrom:x,timestamp:i})}catch(e){console.error(`[rollback]`,e),Y(n,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function Je(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}Y(t,200,Rn())}async function Ye(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}Y(t,200,A())}async function Xe(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=C?.()??null;if(!n){Y(t,404,{error:`Principal not available`});return}Y(t,200,n)}async function Ze(e,t){if(!jh(e.socket.remoteAddress)){Y(t,403,{ok:!1,error:`loopback-required`});return}if(!Mh(e.headers.host)){Y(t,403,{ok:!1,error:`host-header-not-allowed`});return}if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=_?.getPresenceMap()??{},r=Date.now(),i={};for(let[e,t]of Object.entries(n))r-t.ts<2e4&&(i[e]=t);Y(t,200,{presence:i})}async function Qe(e,t){if(!jh(e.socket.remoteAddress)){Y(t,403,{ok:!1,error:`loopback-required`});return}if(!Mh(e.headers.host)){Y(t,403,{ok:!1,error:`host-header-not-allowed`});return}if(e.method!==`GET`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n=H(i),r=n,a=!0;try{r=pe(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}),Y(t,500,{ok:!1,error:`workspace-realpath-failed`,code:r??null});return}}Y(t,200,{ok:!0,contentDir:r,pathSeparator:Ee,symlinkResolved:a})}let $e=1440*60*1e3;async function et(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}if(!c?.current){Y(t,200,[]);return}let n=Date.now(),r=[],i=H(c.current.gitDir,`rescue`);if(R(i))try{let e=fe(i).filter(e=>Op(e));for(let t of e){let e=H(i,t),a=ge(e);if(n-a.mtimeMs>$e){try{_e(e)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}r.push({docName:kp(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 Om(c.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)}Y(t,200,r)}async function tt(e,t,n){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}if(!c?.current){t.writeHead(404),t.end(`Not found`);return}let r=H(c.current.gitDir,`rescue`),i=H(r,`${n}${Np(n)}`);if(!i.startsWith(`${r}/`)){t.writeHead(400),t.end(`Invalid document name`);return}if(R(i)){let e=ge(i);if(Date.now()-e.mtimeMs>$e)try{_e(i)}catch{}else{let e=z(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 Om(c.current,e)).filter(e=>e.docName===n).sort((e,t)=>t.timestamp.localeCompare(e.timestamp))[0];if(r){let e=fm(c.current),n=((await e.raw(`ls-tree`,`-r`,r.sha)).trim().split(`
70
- `)[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 nt(e,t){if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await t_(e)}catch{Y(t,413,{ok:!1,error:`Payload too large`});return}let r;try{r=JSON.parse(n.toString())}catch{Y(t,400,{ok:!1,error:`Invalid JSON`});return}if(!r||typeof r!=`object`||Array.isArray(r)){Y(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{agentId:o,agentName:s,colorSeed:c,clientName:l,clientVersion:u,label:d}=xe(r),{path:f}=r;if(!f||typeof f!=`string`||f.length===0){Y(t,400,{ok:!1,error:`path is required`});return}if(!Op(f)){Y(t,400,{ok:!1,error:`path must end with .md or .mdx`});return}if(f.includes(`..`)||f.startsWith(`/`)||f.includes(`\0`)||f.includes(`\\`)){Y(t,400,{ok:!1,error:`path must not contain .. or start with /`});return}let p=H(i),g=H(p,f);if(!g.startsWith(`${p}/`)&&g!==p){Y(t,400,{ok:!1,error:`path must not escape content directory`});return}let _=kp(f);if(J(_)){Y(t,400,{ok:!1,error:`'${_}' is a reserved document name`});return}ue(Se(g),{recursive:!0});try{B(g,``,{encoding:`utf-8`,flag:`wx`})}catch(e){if(e.code===`EEXIST`){Y(t,409,{ok:!1,error:`File already exists`});return}throw e}let v=kp(f);Uf(v,o,s,c,void 0,V({clientName:l,clientVersion:u,label:d}));let y=typeof a==`function`?a():null;y instanceof Map&&ph({kind:`create`,path:g,docName:v,content:``},y),m&&(m.updateDocumentFromMarkdown(v,``),m.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${v}:`,e)}),h?.(`backlinks`),h?.(`graph`)),h?.(`files`),Y(t,200,{ok:!0,docName:v})}catch(e){console.error(`[create-page]`,e),Y(t,500,{ok:!1,error:`Failed to create page`})}}async function rt(e,t){if(e.method!==`GET`){Y(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){Y(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!r_(n)){Y(t,400,{ok:!1,error:`Invalid docName`});return}let r=k(n);if(!r){Y(t,400,{ok:!1,error:`Invalid docName`});return}if(!R(r)){Y(t,404,{ok:!1,error:`Page not found`});return}Y(t,200,{ok:!0,docName:n,headings:n_(z(r,`utf-8`))})}catch(e){console.error(`[page-headings]`,e),Y(t,500,{ok:!1,error:`Failed to read headings`})}}async function it(e,t){if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await t_(e)}catch{Y(t,413,{ok:!1,error:`Payload too large`});return}let r;try{r=JSON.parse(n.toString())}catch{Y(t,400,{ok:!1,error:`Invalid JSON`});return}if(!r||typeof r!=`object`||Array.isArray(r)){Y(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{agentId:a,agentName:o,colorSeed:s,clientName:c,clientVersion:l,label:u}=xe(r),{docName:d,newDocName:f}=r;if(typeof d!=`string`||typeof f!=`string`){Y(t,400,{ok:!1,error:`docName and newDocName are required`});return}if(!qg(d)||!qg(f)){Y(t,400,{ok:!1,error:`Document names must be relative content paths`});return}if(J(d)||J(f)){Y(t,400,{ok:!1,error:`Reserved document names cannot be renamed`});return}if(d===f){Y(t,200,{ok:!0,renamed:[],rewrittenDocs:[]});return}if(!m){Y(t,503,{ok:!1,error:`Backlink index unavailable`});return}let p=Qg(i,`file`,d),h=Qg(i,`file`,f);if(!R(p)){Y(t,404,{ok:!1,error:`Document does not exist`});return}if(R(h)){Y(t,409,{ok:!1,error:`Destination already exists`});return}let g=await be(d,f);Uf(d,a,o,s,Gl(d,f),V({clientName:c,clientVersion:l,label:u})),Y(t,200,{ok:!0,renamed:g.renamed,rewrittenDocs:g.rewrittenDocs})}catch(e){console.error(`[rename]`,e),Y(t,500,{ok:!1,error:L(e)})}}async function at(e,t){if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await t_(e)}catch{Y(t,413,{ok:!1,error:`Payload too large`});return}let r;try{r=JSON.parse(n.toString())}catch{Y(t,400,{ok:!1,error:`Invalid JSON`});return}if(!r||typeof r!=`object`||Array.isArray(r)){Y(t,400,{ok:!1,error:`Body must be a JSON object`});return}xe(r);let{kind:o,fromPath:s,toPath:c}=r;if(o!==`file`&&o!==`folder`){Y(t,400,{ok:!1,error:`kind must be "file" or "folder"`});return}if(typeof s!=`string`||typeof c!=`string`){Y(t,400,{ok:!1,error:`fromPath and toPath are required`});return}if(!qg(s)||!qg(c)){Y(t,400,{ok:!1,error:`Paths must be relative content paths`});return}if(s===c){Y(t,200,{ok:!0,renamed:[]});return}let l=Qg(i,o,s),u=Qg(i,o,c);if(!R(l)){Y(t,404,{ok:!1,error:`${o} does not exist`});return}if(R(u)){Y(t,409,{ok:!1,error:`Destination already exists`});return}let d=ge(l);if(o===`file`&&!d.isFile()||o===`folder`&&!d.isDirectory()){Y(t,400,{ok:!1,error:`Source path is not a ${o}`});return}let f=Jg(a(),o,s),p=o===`file`?[{fromDocName:s,toDocName:c}]:f.map(e=>({fromDocName:e,toDocName:Yg(e,o,s,c)})),g=await se(p.map(({fromDocName:e})=>e)),_=async()=>{await e_(S,l,u)||(ue(Se(u),{recursive:!0}),me(l,u)),ce(p,g)};if(o===`file`)await Vh(i,Fh({sourceDocName:s,destinationDocName:c,snapshots:le(p.map(({fromDocName:e})=>e),g)}),_);else{await _();let e=a();for(let{fromDocName:t,toDocName:n}of p)ph({kind:`rename`,oldPath:Qg(i,`file`,t),newPath:Qg(i,`file`,n),oldDocName:t,newDocName:n,content:g.get(t)??z(Qg(i,`file`,n),`utf-8`)},e);if(m){for(let{fromDocName:e,toDocName:t}of p)m.renameDocument(e,t,g.get(e)??z(Qg(i,`file`,t),`utf-8`));m.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist folder rename cache for ${s} -> ${c}:`,e)}),h?.(`backlinks`),h?.(`graph`)}h?.(`files`)}Y(t,200,{ok:!0,renamed:p})}catch(e){console.error(`[rename-path]`,e),Y(t,500,{ok:!1,error:`Failed to rename path`})}}async function ot(e,t){if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await t_(e)}catch{Y(t,413,{ok:!1,error:`Payload too large`});return}let r;try{r=JSON.parse(n.toString())}catch{Y(t,400,{ok:!1,error:`Invalid JSON`});return}if(!r||typeof r!=`object`||Array.isArray(r)){Y(t,400,{ok:!1,error:`Body must be a JSON object`});return}xe(r);let{kind:o,path:s}=r;if(o!==`file`&&o!==`folder`){Y(t,400,{ok:!1,error:`kind must be "file" or "folder"`});return}if(typeof s!=`string`||!qg(s)){Y(t,400,{ok:!1,error:`path must be a relative content path`});return}let c=Qg(i,o,s);if(!R(c)){Y(t,404,{ok:!1,error:`${o} does not exist`});return}let l=ge(c);if(o===`file`&&!l.isFile()||o===`folder`&&!l.isDirectory()){Y(t,400,{ok:!1,error:`Target path is not a ${o}`});return}let u=o===`file`?[s]:Jg(a(),o,s);await se(u),o===`file`?_e(c):he(c,{recursive:!0,force:!1}),Y(t,200,{ok:!0,deletedDocNames:u})}catch(e){console.error(`[delete-path]`,e),Y(t,500,{ok:!1,error:`Failed to delete path`})}}async function st(e,t){if(e.method!==`GET`){Y(t,405,{ok:!1,error:`Method not allowed`});return}try{let e=a(),n=[];for(let[t,r]of e){let e=t;try{e=vp(z(H(i,`${t}${Np(t)}`),`utf-8`),t)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}n.push({docName:t,title:e,size:r.size,modified:r.modified})}n.sort((e,t)=>e.docName.localeCompare(t.docName)),Y(t,200,{ok:!0,pages:n})}catch(e){console.error(`[pages]`,e),Y(t,500,{ok:!1,error:`Failed to list pages`})}}async function ct(e,n){if(e.method!==`GET`){Y(n,405,{ok:!1,error:`Method not allowed`});return}try{let r=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!r){Y(n,400,{ok:!1,error:`Missing docName parameter`});return}if(!r_(r)){Y(n,400,{ok:!1,error:`Invalid docName`});return}if(J(r)){Y(n,400,{ok:!1,error:`'${r}' is a reserved document name`});return}Y(n,200,{ok:!0,...await Og({hocuspocus:t,fileIndex:a(),docName:r})})}catch(e){if(e instanceof og){Y(n,404,{ok:!1,error:`Page not found`});return}console.error(`[suggest-links]`,e),Y(n,500,{ok:!1,error:`Failed to suggest links`})}}async function lt(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}let n;try{n=await Gg(e,10485760)}catch(e){let n=e instanceof Error?e.message:String(e);n===`Payload too large`?Y(t,413,{ok:!1,error:`Payload too large`}):n===`No file received`?Y(t,400,{ok:!1,error:`No file received`}):Y(t,400,{ok:!1,error:`Failed to parse upload: ${n}`});return}let{filename:r,buffer:a,parentDocName:o}=n;if(xe(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries())),!o){Y(t,400,{ok:!1,error:`parentDocName is required`});return}if(o.includes(`\0`)||o.includes(`..`)||o.startsWith(`/`)){Y(t,400,{ok:!1,error:`path-escape`});return}let s=H(i),c=H(s,Se(o));if(!Fm(c,s)){Y(t,400,{ok:!1,error:`path-escape`});return}try{let e=pe(c),n;try{n=pe(s)}catch{n=s}if(!Fm(e,n)){Y(t,400,{ok:!1,error:`path-escape`});return}}catch(e){if(e.code!==`ENOENT`){Y(t,400,{ok:!1,error:`path-escape`});return}}let l=await Lf(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||!Vg.has(u)){Y(t,400,{ok:!1,error:`Unsupported file type${u?`: ${u}`:``}`});return}let f;f=!r||r===`upload`||Hg.test(r)?`pasted-${new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`)}.${d}`:Ug(r),ue(c,{recursive:!0});try{let e=Wg(c,f,a),n=Te(i,H(c,e));console.log(`[upload] ok ${n} ${a.length}`),Y(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}`),Y(t,500,{ok:!1,error:`Failed to save file`})}}let ut=`/api/local-op/clone`,dt=`/api/local-op/open`,ft=600*1e3;async function pt(e,t){if(!kh(e,t,Y))return;if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n,r;try{let i=await t_(e),a=JSON.parse(i.toString());if(typeof a.url!=`string`||!a.url){Y(t,400,{ok:!1,error:`Missing or invalid url`});return}if(typeof a.dir!=`string`||!a.dir){Y(t,400,{ok:!1,error:`Missing or invalid dir`});return}n=a.url,r=a.dir}catch{Y(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!wh(n)){Y(t,400,{ok:!1,error:`URL protocol not allowed`});return}if(!Eh(r)){Y(t,400,{ok:!1,error:`dir must be within the user home directory`});return}if(!D.tryAcquire(ut)){Y(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=Th(r),[a,...o]=x,s=[...o,`clone`,`--json`,n,i],c=!1,l=!1,u=null,d=``,f=Ne(a,s,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),p=setTimeout(()=>{c=!0,f.kill(`SIGTERM`)},ft);f.stdout.on(`data`,e=>{d+=e.toString(`utf-8`);let n=d.split(`
71
- `);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),zg.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){D.release(ut);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&&zg.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 mt(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(),D.release(ut)}})()}),f.on(`error`,e=>{clearTimeout(p),l||(l=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),D.release(ut)})}async function mt(e){let t=H(Th(e)),n=H(t,`.open-knowledge`),r=Tp(n);if(r&&r.port>0)return{port:r.port};let i=ie(n),[a,...o]=x,s=i&&i.port>0?`ui`:`start`,c=Ne(a,[...o,s],{cwd:t,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env}}),l=[];c.stderr?.on(`data`,e=>{l.push(e),zg.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=Tp(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 ht(e,t){if(!kh(e,t,Y))return;if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n;try{let r=await t_(e),i=JSON.parse(r.toString());if(typeof i.dir!=`string`||!i.dir){Y(t,400,{ok:!1,error:`Missing or invalid dir`});return}n=i.dir}catch{Y(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!Eh(n)){Y(t,400,{ok:!1,error:`dir must be within the user home directory`});return}if(!D.tryAcquire(dt)){Y(t,429,{ok:!1,error:`A server-open operation is already in progress`});return}try{let e=await mt(n);`port`in e?Y(t,200,{port:e.port}):Y(t,504,{ok:!1,error:e.error})}finally{D.release(dt)}}let gt=`/api/local-op/auth/login`,_t=`/api/local-op/auth/status`,vt=`/api/local-op/auth/repos`,yt=`/api/local-op/auth/signout`,bt=`/api/local-op/auth/pat`;async function xt(e,t){if(!kh(e,t,Y))return;if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=await t_(e),r=JSON.parse(t.toString());typeof r.host==`string`&&r.host&&(n=r.host)}catch{Y(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!D.tryAcquire(gt)){Y(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]=x,a=[...i,`auth`,`login`,`--json`,`--host`,n],o=!1,s=!1,c=``,l=Ne(r,a,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),u=setTimeout(()=>{l.kill(`SIGTERM`)},ft),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(`
72
- `);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=>{zg.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()),D.release(gt)}),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())),D.release(gt)})}async function St(e,t){if(!kh(e,t,Y))return;if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=(await t_(e)).toString().trim();if(t.length>0){let e=JSON.parse(t);typeof e.host==`string`&&e.host&&(n=e.host)}}catch{Y(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!D.tryAcquire(_t)){Y(t,429,{ok:!1,error:`An auth status operation is already in progress`});return}try{let[e,...r]=x,i=[...r,`auth`,`status`,`--json`,`--host`,n],a=(await new Promise((t,n)=>{let r=Ne(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(`
73
- `).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?Y(t,200,{authenticated:!1}):Y(t,200,o)}catch(e){Y(t,500,{ok:!1,error:e instanceof Error?e.message:`auth status failed`})}finally{D.release(_t)}}async function Ct(e,t){if(!kh(e,t,Y))return;if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=(await t_(e)).toString().trim();if(t.length>0){let e=JSON.parse(t);typeof e.host==`string`&&e.host&&(n=e.host)}}catch{Y(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!D.tryAcquire(vt)){Y(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]=x,a=[...i,`auth`,`repos`,`--json`,`--host`,n],o=!1,s=Ne(r,a,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),c=setTimeout(()=>{s.kill(`SIGTERM`)},ft);s.stdout.on(`data`,e=>{t.writableEnded||t.write(e)}),s.stderr.on(`data`,e=>{zg.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()),D.release(vt)}),s.on(`error`,e=>{clearTimeout(c),o||(o=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),D.release(vt)})}async function wt(e,t){if(!kh(e,t,Y))return;if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=await t_(e),r=JSON.parse(t.toString());typeof r.host==`string`&&r.host&&(n=r.host)}catch{Y(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!D.tryAcquire(yt)){Y(t,429,{ok:!1,error:`An auth signout operation is already in progress`});return}try{let[e,...r]=x,i=[...r,`auth`,`signout`,`--host`,n];await new Promise((t,n)=>{let r=Ne(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)})}),Y(t,200,{ok:!0})}catch(e){Y(t,500,{ok:!1,error:e instanceof Error?e.message:`auth signout failed`})}finally{D.release(yt)}}async function Tt(e,t){if(!kh(e,t,Y))return;if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`,r;try{let i=await t_(e),a=JSON.parse(i.toString());if(typeof a.pat!=`string`||!a.pat){Y(t,400,{ok:!1,error:`Missing or invalid pat`});return}r=a.pat,typeof a.host==`string`&&a.host&&(n=a.host)}catch{Y(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!D.tryAcquire(bt)){Y(t,429,{ok:!1,error:`An auth pat operation is already in progress`});return}try{let[e,...i]=x,a=[...i,`auth`,`pat`,`--json`,`--host`,n],o=(await new Promise((t,n)=>{let i=Ne(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(`
74
- `).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?Y(t,200,{ok:!0}):Y(t,200,s)}catch(e){Y(t,500,{ok:!1,error:e instanceof Error?e.message:`auth pat failed`})}finally{D.release(bt)}}async function Et(e,t){if(kh(e,t,Y)){if(e.method!==`GET`){Y(t,405,{ok:!1,error:`Method not allowed`});return}if(!S){Y(t,400,{ok:!1,error:`No project directory configured`});return}try{Y(t,200,{ok:!0,identity:await yh(S)})}catch(e){Y(t,500,{ok:!1,error:e instanceof Error?e.message:`identity resolution failed`})}}}let Dt=`/api/local-op/auth/set-identity`;async function Ot(e,t){if(!kh(e,t,Y))return;if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n,r;try{let i=await t_(e),a=JSON.parse(i.toString());if(typeof a.name!=`string`||!a.name.trim()){Y(t,400,{ok:!1,error:`Missing or invalid name`});return}if(typeof a.email!=`string`||!a.email.trim()){Y(t,400,{ok:!1,error:`Missing or invalid email`});return}n=a.name.trim(),r=a.email.trim()}catch{Y(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!S){Y(t,400,{ok:!1,error:`No project directory configured`});return}if(!D.tryAcquire(Dt)){Y(t,429,{ok:!1,error:`A set-identity operation is already in progress`});return}try{bh(S,n,r),b?.()?.refreshIdentity().catch(()=>{}),Y(t,200,{ok:!0})}catch(e){Y(t,500,{ok:!1,error:e instanceof Error?e.message:`set-identity failed`})}finally{D.release(Dt)}}async function kt(e,t){if(!kh(e,t,Y))return;if(e.method!==`GET`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n=b?.();if(!n){Y(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}Y(t,200,n.getStatus())}async function At(e,t){if(!kh(e,t,Y))return;if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n=b?.();if(!n){Y(t,503,{ok:!1,error:`Sync engine not active`});return}let r=`sync`;try{let t=await t_(e);if(t.length>0){let e=JSON.parse(t.toString());(e.op===`push`||e.op===`pull`||e.op===`sync`)&&(r=e.op)}}catch{}Y(t,202,{ok:!0,op:r}),n.trigger(r)}async function jt(e,t){if(!kh(e,t,Y))return;if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n=b?.();if(!n){Y(t,503,{ok:!1,error:`Sync engine not active`});return}let r;try{let n=await t_(e),i=JSON.parse(n.toString());if(typeof i.enabled!=`boolean`){Y(t,400,{ok:!1,error:`enabled must be a boolean`});return}r=i.enabled}catch{Y(t,400,{ok:!1,error:`Invalid JSON body`});return}await n.setEnabled(r),Y(t,200,{ok:!0,status:n.getStatus()})}async function Mt(e,t){if(!kh(e,t,Y))return;if(e.method!==`GET`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n=b?.();Y(t,200,{conflicts:n?n.getConflicts():[]})}async function Nt(e,t){if(!kh(e,t,Y))return;if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n=b?.();if(!n){Y(t,503,{ok:!1,error:`Sync engine not active`});return}let r;try{let t=await t_(e);r=JSON.parse(t.toString())}catch{Y(t,400,{ok:!1,error:`Invalid JSON body`});return}let{file:i,strategy:a,content:o}=r;if(!i||typeof i!=`string`){Y(t,400,{ok:!1,error:`Missing required field: file`});return}if(a!==`mine`&&a!==`theirs`&&a!==`content`){Y(t,400,{ok:!1,error:`Invalid strategy: must be 'mine', 'theirs', or 'content'`});return}try{await n.resolveConflict(i,a,o),Y(t,200,{ok:!0})}catch(e){Y(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function Pt(e,t){if(!kh(e,t,Y))return;if(e.method!==`GET`){Y(t,405,{ok:!1,error:`Method not allowed`});return}if(!S){Y(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){Y(t,400,{ok:!1,error:`Missing required query param: file`});return}if(n.includes(`..`)||n.startsWith(`/`)){Y(t,400,{ok:!1,error:`Invalid file path`});return}let r=Fe({baseDir:S,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)]);Y(t,200,{ok:!0,file:n,base:e,ours:r,theirs:a})}catch(e){Y(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function Ft(e,t){if(kh(e,t,Y))return $f(e,t,O.probeAll)}async function It(e,t){if(!kh(e,t,Y))return;if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n=b?.();if(!n){Y(t,503,{ok:!1,error:`Sync engine not active`});return}try{await n.abortMerge(),Y(t,200,{ok:!0})}catch(e){Y(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}let Lt={"/api/document":Oe,"/api/documents":ke,"/api/backlinks":Ae,"/api/backlink-counts":je,"/api/forward-links":Me,"/api/link-graph":Pe,"/api/dead-links":Re,"/api/orphans":Ie,"/api/hubs":Le,"/api/pages":st,"/api/suggest-links":ct,"/api/page-headings":rt,"/api/create-page":nt,"/api/rename":it,"/api/rename-path":at,"/api/delete-path":ot,"/api/upload-image":lt,"/api/agent-write":we,"/api/agent-write-md":De,"/api/agent-patch":ze,"/api/agent-undo":Be,"/api/save-version":Ue,"/api/history":We,"/api/diff":Ke,"/api/rollback":qe,"/api/metrics/reconciliation":Je,"/api/metrics/parse-health":Ye,"/api/metrics/agent-presence":Ze,"/api/principal":Xe,"/api/rescue":et,"/api/workspace":Qe,"/api/sync/status":kt,"/api/sync/trigger":At,"/api/sync/set-enabled":jt,"/api/sync/conflicts":Mt,"/api/sync/conflict-content":Pt,"/api/sync/resolve-conflict":Nt,"/api/sync/abort-merge":It,"/api/local-op/clone":pt,"/api/local-op/open":ht,"/api/local-op/auth/login":xt,"/api/local-op/auth/status":St,"/api/local-op/auth/repos":Ct,"/api/local-op/auth/signout":wt,"/api/local-op/auth/pat":Tt,"/api/local-op/auth/identity":Et,"/api/local-op/auth/set-identity":Ot,"/api/installed-agents":Ft};return s&&(Lt[`/api/test-reset`]=Ve,Lt[`/api/test-rescan-backlinks`]=He),{priority:100,async onRequest({request:e,response:t}){let n=e.url?.split(`?`)[0];if(!n)return;if(n.startsWith(`/api/`)){let n=e.headers.origin;if(n!==void 0&&!i_(n)){typeof t.setHeader==`function`&&t.setHeader(`Content-Type`,`application/json`),t.writeHead(403),t.end(JSON.stringify({ok:!1,error:`origin-not-allowed`}));return}if(typeof t.setHeader==`function`&&(n!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,n),t.setHeader(`Vary`,`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=Lt[n];if(r){await r(e,t);return}if(n.startsWith(`/api/rescue/`)){let r=decodeURIComponent(n.slice(12));r&&await tt(e,t,r);return}if(n.startsWith(`/api/history/`)){let r=decodeURIComponent(n.slice(13));r&&await Ge(e,t,r);return}}}}function o_(e){let t=e.scheduler??m,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 s_=Math.floor,c_=(e,t)=>e<t?e:t,l_=(e,t)=>e>t?e:t;Number.isNaN,Number.isInteger,Number.isNaN,Number.parseInt;const u_=String.fromCharCode;String.fromCodePoint,u_(65535);const d_=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},f_=typeof TextEncoder<`u`?new TextEncoder:null,p_=f_?e=>f_.encode(e):d_;let m_=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});m_&&m_.decode(new Uint8Array).length===1&&(m_=null);const h_=(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},g_=(e,t)=>{for(;t>127;)h_(e,128|127&t),t=s_(t/128);h_(e,127&t)},__=new Uint8Array(3e4),v_=__.length/3,y_=f_&&f_.encodeInto?(e,t)=>{if(t.length<v_){let n=f_.encodeInto(t,__).written||0;g_(e,n);for(let t=0;t<n;t++)h_(e,__[t])}else x_(e,p_(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;g_(e,r);for(let t=0;t<r;t++)h_(e,n.codePointAt(t))},b_=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=c_(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(l_(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},x_=(e,t)=>{g_(e,t.byteLength),b_(e,t)},S_=e=>Error(e);S_(`Unexpected end of array`),S_(`Integer out of Range`);let C_=function(e){return e[e.Token=0]=`Token`,e[e.PermissionDenied=1]=`PermissionDenied`,e[e.Authenticated=2]=`Authenticated`,e}({});const w_=(e,t)=>{g_(e,C_.PermissionDenied),y_(e,t)},T_=(e,t)=>{g_(e,C_.Authenticated),y_(e,t)},E_=e=>{g_(e,C_.Token)},D_={code:4205,reason:`Reset Connection`},O_={code:4401,reason:`Unauthorized`},k_={code:4403,reason:`Forbidden`},A_={code:4408,reason:`Connection Timeout`},j_=e=>Array.from(e.entries()).map(([e,t])=>({clientId:e,...t}));var M_=class extends Error{constructor(e){super(e??`Further hooks skipped`),this.name=`SkipFurtherHooksError`}};let N_=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 P_=Error(`request for lock canceled`);var F_=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())})},I_=class{constructor(e,t=P_){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=R_(this._queue,e=>t<=e.priority);a===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(a+1,0,i)})}runExclusive(e){return F_(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]=[]),L_(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 L_(e,t){let n=R_(e,e=>t.priority<=e.priority);e.splice(n+1,0,t)}function R_(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}var z_=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())})},B_=class{constructor(e){this._semaphore=new I_(1,e)}acquire(){return z_(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 V_,H_,U_,W_,G_=!0;typeof process<`u`&&({FORCE_COLOR:V_,NODE_DISABLE_COLORS:H_,NO_COLOR:U_,TERM:W_}=process.env||{},G_=process.stdout&&process.stdout.isTTY);const X={enabled:!H_&&U_==null&&W_!==`dumb`&&(V_!=null&&V_!==`0`||G_),reset:Z(0,0),bold:Z(1,22),dim:Z(2,22),italic:Z(3,23),underline:Z(4,24),inverse:Z(7,27),hidden:Z(8,28),strikethrough:Z(9,29),black:Z(30,39),red:Z(31,39),green:Z(32,39),yellow:Z(33,39),blue:Z(34,39),magenta:Z(35,39),cyan:Z(36,39),white:Z(37,39),gray:Z(90,39),grey:Z(90,39),bgBlack:Z(40,49),bgRed:Z(41,49),bgGreen:Z(42,49),bgYellow:Z(43,49),bgBlue:Z(44,49),bgMagenta:Z(45,49),bgCyan:Z(46,49),bgWhite:Z(47,49)};function K_(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 q_(e,t){let n={has:e,keys:t};return n.reset=X.reset.bind(n),n.bold=X.bold.bind(n),n.dim=X.dim.bind(n),n.italic=X.italic.bind(n),n.underline=X.underline.bind(n),n.inverse=X.inverse.bind(n),n.hidden=X.hidden.bind(n),n.strikethrough=X.strikethrough.bind(n),n.black=X.black.bind(n),n.red=X.red.bind(n),n.green=X.green.bind(n),n.yellow=X.yellow.bind(n),n.blue=X.blue.bind(n),n.magenta=X.magenta.bind(n),n.cyan=X.cyan.bind(n),n.white=X.white.bind(n),n.gray=X.gray.bind(n),n.grey=X.grey.bind(n),n.bgBlack=X.bgBlack.bind(n),n.bgRed=X.bgRed.bind(n),n.bgGreen=X.bgGreen.bind(n),n.bgYellow=X.bgYellow.bind(n),n.bgBlue=X.bgBlue.bind(n),n.bgMagenta=X.bgMagenta.bind(n),n.bgCyan=X.bgCyan.bind(n),n.bgWhite=X.bgWhite.bind(n),n}function Z(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:X.enabled?K_(this.keys,t+``):t+``):t===void 0?q_([e],[n]):X.enabled?K_([n],t+``):t+``}}const J_=Math.floor,Y_=(e,t)=>e<t?e:t,X_=(e,t)=>e>t?e:t;Number.isNaN;const Z_=2**53-1;Number.isInteger,Number.isNaN,Number.parseInt;const Q_=()=>new Set,$_=Array.from;Array.isArray;const ev=String.fromCharCode;String.fromCodePoint,ev(65535);const tv=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},nv=typeof TextEncoder<`u`?new TextEncoder:null,rv=nv?e=>nv.encode(e):tv;let iv=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});iv&&iv.decode(new Uint8Array).length===1&&(iv=null);const av=e=>Error(e);var ov=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const sv=()=>new ov,cv=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},lv=e=>{let t=new Uint8Array(cv(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},uv=(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},dv=(e,t)=>{for(;t>127;)uv(e,128|127&t),t=J_(t/128);uv(e,127&t)},fv=new Uint8Array(3e4),pv=fv.length/3,mv=nv&&nv.encodeInto?(e,t)=>{if(t.length<pv){let n=nv.encodeInto(t,fv).written||0;dv(e,n);for(let t=0;t<n;t++)uv(e,fv[t])}else gv(e,rv(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;dv(e,r);for(let t=0;t<r;t++)uv(e,n.codePointAt(t))},hv=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=Y_(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(X_(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},gv=(e,t)=>{dv(e,t.byteLength),hv(e,t)},_v=av(`Unexpected end of array`),vv=av(`Integer out of Range`);var yv=class{constructor(e){this.arr=e,this.pos=0}};const bv=e=>new yv(e),xv=e=>e.pos!==e.arr.length,Sv=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},Cv=e=>Sv(e,Tv(e)),wv=e=>e.arr[e.pos++],Tv=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>Z_)throw vv}throw _v},Ev=iv?e=>iv.decode(Cv(e)):e=>{let t=Tv(e);if(t===0)return``;{let n=String.fromCodePoint(wv(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(wv(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 Dv=class{constructor(e){e instanceof Uint8Array||(e=new Uint8Array(e)),this.decoder=bv(e)}get encoder(){return this.encoderInternal||=sv(),this.encoderInternal}readVarUint8Array(){return Cv(this.decoder)}peekVarUint8Array(){let{pos:e}=this.decoder,t=Cv(this.decoder);return this.decoder.pos=e,t}readVarUint(){return Tv(this.decoder)}readVarString(){return Ev(this.decoder)}toUint8Array(){return lv(this.encoder)}writeVarUint(e){dv(this.encoder,e)}writeVarString(e){mv(this.encoder,e)}get length(){return cv(this.encoder)}};const Ov=Date.now,kv=()=>new Map,Av=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r};var jv=class{constructor(){this._observers=kv()}on(e,t){Av(this._observers,e,Q_).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 $_((this._observers.get(e)||kv()).values()).forEach(e=>e(...t))}destroy(){this._observers=kv()}};const Mv=Symbol(`Equality`),Nv=Object.keys,Pv=e=>Nv(e).length,Fv=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Iv=(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[Mv]!=null)return e[Mv](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)||!Iv(e.get(n),t.get(n)))return!1;break;case void 0:case Object:if(Pv(e)!==Pv(t))return!1;for(let n in e)if(!Fv(e,n)||!Iv(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(!Iv(e[n],t[n]))return!1;break;default:return!1}return!0},Lv=3e4;var Rv=class extends jv{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let e=Ov();this.getLocalState()!==null&&Lv/2<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&Lv<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&zv(this,t,`timeout`)},J_(Lv/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:Ov()});let a=[],o=[],s=[],c=[];e===null?c.push(t):i==null?e!=null&&a.push(t):(o.push(t),Iv(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 zv=(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:Ov()})}r.push(i)}}r.length>0&&(e.emit(`change`,[{added:[],updated:[],removed:r},n]),e.emit(`update`,[{added:[],updated:[],removed:r},n]))},Bv=(e,t,n=e.states)=>{let r=t.length,i=sv();dv(i,r);for(let a=0;a<r;a++){let r=t[a],o=n.get(r)||null,s=e.meta.get(r).clock;dv(i,r),dv(i,s),mv(i,JSON.stringify(o))}return lv(i)},Vv=(e,t,n)=>{let r=bv(t),i=Ov(),a=[],o=[],s=[],c=[],l=Tv(r);for(let t=0;t<l;t++){let t=Tv(r),n=Tv(r),l=JSON.parse(Ev(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&&(Iv(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])},Hv=(e,t)=>{dv(e,0),gv(e,Ja(t))},Uv=(e,t,n)=>{dv(e,1),gv(e,Ha(t,n))},Wv=(e,t,n)=>Uv(t,n,Cv(e)),Gv=(e,t,n,r)=>{try{za(t,Cv(e),n)}catch(e){r?.(e),console.error(`Caught error while handling a Yjs update`,e)}},Kv=(e,t)=>{dv(e,2),gv(e,t)},qv=Gv;function Jv(e){return typeof e==`object`&&!!e&&`source`in e&&(e.source===`connection`||e.source===`redis`||e.source===`local`)}function Yv(e){if(!Jv(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 Xv=class{constructor(e){this.encoder=sv(),mv(this.encoder,e)}createSyncMessage(){return this.type=Q.Sync,dv(this.encoder,Q.Sync),this}createSyncReplyMessage(){return this.type=Q.SyncReply,dv(this.encoder,Q.SyncReply),this}createAwarenessUpdateMessage(e,t){this.type=Q.Awareness,this.category=`Update`;let n=Bv(e,t||Array.from(e.getStates().keys()));return dv(this.encoder,Q.Awareness),gv(this.encoder,n),this}writeQueryAwareness(){return this.type=Q.QueryAwareness,this.category=`Update`,dv(this.encoder,Q.QueryAwareness),this}writeTokenSyncRequest(){return this.type=Q.Auth,this.category=`TokenSync`,dv(this.encoder,Q.Auth),E_(this.encoder),this}writeAuthenticated(e){return this.type=Q.Auth,this.category=`Authenticated`,dv(this.encoder,Q.Auth),T_(this.encoder,e?`readonly`:`read-write`),this}writePermissionDenied(e){return this.type=Q.Auth,this.category=`PermissionDenied`,dv(this.encoder,Q.Auth),w_(this.encoder,e),this}writeFirstSyncStepFor(e){return this.category=`SyncStep1`,Hv(this.encoder,e),this}writeUpdate(e){return this.category=`Update`,Kv(this.encoder,e),this}writeStateless(e){return this.category=`Stateless`,dv(this.encoder,Q.Stateless),mv(this.encoder,e),this}writeBroadcastStateless(e){return this.category=`Stateless`,dv(this.encoder,Q.BroadcastStateless),mv(this.encoder,e),this}writeSyncStatus(e){return this.category=`SyncStatus`,dv(this.encoder,Q.SyncStatus),dv(this.encoder,e?1:0),this}writeCloseMessage(e){return this.type=Q.CLOSE,dv(this.encoder,Q.CLOSE),mv(this.encoder,e),this}toUint8Array(){return lv(this.encoder)}},Zv=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:Vv(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:Ev(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()===C_.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(Wv(e.decoder,e.encoder,t),r&&i)r(new Xv(o).createSyncReplyMessage().writeFirstSyncStepFor(t).toUint8Array());else if(n){let e=new Xv(o).createSyncMessage().writeFirstSyncStepFor(t);n.send(e.toUint8Array())}break;case 1:if(n?.readOnly){if(uo(oo(t),Cv(e.decoder))){let e=new Xv(o).writeSyncStatus(!0);n.send(e.toUint8Array())}else{let e=new Xv(o).writeSyncStatus(!1);n.send(e.toUint8Array())}break}Gv(e.decoder,t,n?{source:`connection`,connection:n}:this.defaultTransactionOrigin??{source:`local`}),n&&n.send(new Xv(o).writeSyncStatus(!0).toUint8Array());break;case 2:if(n?.readOnly){n.send(new Xv(o).writeSyncStatus(!1).toUint8Array());break}qv(e.decoder,t,n?{source:`connection`,connection:n}:this.defaultTransactionOrigin??{source:`local`}),n&&n.send(new Xv(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 Xv(t?.messageAddress??e.name).createAwarenessUpdateMessage(e.awareness);n&&n(r.toUint8Array())}},Qv=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===N_.Closing||this.webSocket.readyState===N_.Closed){this.close();return}try{this.webSocket.send(e)}catch{this.close()}}sendStateless(e){let t=new Xv(this.messageAddress).writeStateless(e);this.send(t.toUint8Array())}requestToken(){let e=new Xv(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 Xv(this.messageAddress);t.writeCloseMessage(e?.reason??`Server closed the connection`),this.send(t.toUint8Array())}}sendCurrentAwareness(){if(!this.document.hasAwarenessStates())return;let e=new Xv(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 Dv(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 Zv(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:D_.code,reason:`reason`in e?e.reason:D_.reason})}this.messageQueue.shift()}}},$v=class extends Ca{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 B_,this.lastChangeTime=0,this.name=e,this.awareness=new Rv(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=>{za(this,Ha(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&&zv(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 Vv(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 Xv(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 Xv(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}},ey=`4.0.0-rc.1`;function ty(e){let t=e?.url;return t?t.includes(`://`)?new URL(t).searchParams:new URLSearchParams(t.split(`?`)[1]||``):new URLSearchParams}var ny=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=Oe.randomUUID(),this.lastMessageReceivedAt=Date.now(),this.check=()=>{Date.now()-this.lastMessageReceivedAt>this.timeout&&this.close(A_)},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={...O_,...e};a.close({code:t.code,reason:t.reason})}}),this.documentConnections[e]=a,this.websocket.readyState===N_.Closing||this.websocket.readyState===N_.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 Dv(e);if(Ev(r.decoder),!(Tv(r.decoder)===Q.Auth&&!this.documentConnectionsEstablished.has(t))){this.incomingMessageQueue[t].push(e);return}this.documentConnectionsEstablished.add(t),Tv(r.decoder);let i=Ev(r.decoder),a=null;xv(r.decoder)&&(a=Ev(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 Xv(c).writeAuthenticated(e.connectionConfig.readOnly);this.websocket.send(r.toUint8Array()),await this.setUpNewConnection(t,n,s)}catch(e){let n=e||k_,r=new Xv(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(D_.code,D_.reason)}},this.handleMessage=e=>{this.lastMessageReceivedAt=Date.now();try{let t=Ev(new Dv(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:ty(this.request),socketId:this.socketId,context:{...this.defaultContext},providerVersion:null}}this.handleQueueingMessage(e,t,r)}catch(e){console.error(e),this.websocket.close(O_.code,O_.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 Qv(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:ty(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:ty(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}},ry=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 De}),await this.instance.unloadDocument(this.document)),null)}};const iy=()=>{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()}}},ay={name:null,timeout:6e4,debounce:2e3,maxDebounce:1e4,quiet:!1,yDocOptions:{gc:!0,gcFilter:()=>!0},unloadImmediately:!0};var oy=class{constructor(e){this.configuration={...ay,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=iy(),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:ey,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(D_)})})}handleConnection(e,t,n={}){let r=new ny(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=Jv(t)&&t.source===`connection`?t.connection:void 0,i=r?.request,a=Jv(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:ty(i),socketId:r?.socketId??``,update:n,transactionOrigin:t,connection:r,context:a};if(this.hooks(`onChange`,o),Yv(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=ty(t),s=i??{},c=await this.hooks(`onCreateDocument`,{documentName:e,requestHeaders:a,requestParameters:o,connectionConfig:r,context:s,socketId:n,instance:this}),l=new $v(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 Ca?za(l,Ha(e)):e instanceof Uint8Array&&za(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:Jv(n)&&n.source===`connection`?n.connection:void 0,awareness:l.awareness,states:j_(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 M_){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 ry(await this.createDocument(e,new Request(`http://localhost`),Oe.randomUUID(),{isAuthenticated:!0,readOnly:!1},t),this,t)}},sy=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),cy=se(import.meta.url),ly=sy(((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:()=>{}}})),uy=sy(((e,t)=>{let{EMPTY_BUFFER:n}=ly(),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=cy(`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{}})),dy=sy(((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])}}}})),fy=sy(((e,t)=>{let n=cy(`zlib`),r=uy(),i=dy(),{kStatusCode:a}=ly(),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)}})),py=sy(((e,t)=>{let{isUtf8:n}=cy(`buffer`),{hasBlob:r}=ly(),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=cy(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})),my=sy(((e,t)=>{let{Writable:n}=cy(`stream`),r=fy(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=ly(),{concat:c,toArrayBuffer:l,unmask:u}=uy(),{isValidStatusCode:d,isValidUTF8:f}=py(),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}}})),hy=sy(((e,t)=>{let{Duplex:n}=cy(`stream`),{randomFillSync:r}=cy(`crypto`),i=fy(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=ly(),{isBlob:c,isValidStatusCode:l}=py(),{mask:u,toBuffer:d}=uy(),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)}})),gy=sy(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=ly(),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)}})),_y=sy(((e,t)=>{let{tokenChars:n}=py();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}})),vy=sy(((e,t)=>{let n=cy(`events`),r=cy(`https`),i=cy(`http`),a=cy(`net`),o=cy(`tls`),{randomBytes:s,createHash:c}=cy(`crypto`),{Duplex:l,Readable:u}=cy(`stream`),{URL:d}=cy(`url`),f=fy(),p=my(),m=hy(),{isBlob:h}=py(),{BINARY_TYPES:g,CLOSE_TIMEOUT:_,EMPTY_BUFFER:v,GUID:y,kForOnEventAttribute:b,kListener:x,kStatusCode:S,kWebSocket:C,NOOP:w}=ly(),{EventTarget:{addEventListener:T,removeEventListener:E}}=gy(),{format:D,parse:O}=_y(),{toBuffer:k}=uy(),A=Symbol(`kAborted`),j=[8,13],M=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],N=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var P=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]),ee(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`,se),i.on(`ping`,ce),i.on(`pong`,R),a.onerror=ue,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,z),t.on(`data`,fe),t.on(`end`,pe),t.on(`error`,me),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(P,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(P.prototype,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(P,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(P.prototype,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(P,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(P.prototype,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(P,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),Object.defineProperty(P.prototype,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(P.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(P.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})}})}),P.prototype.addEventListener=T,P.prototype.removeEventListener=E,t.exports=P;function ee(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;te(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:ne),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`||!N.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,te(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{te(e,SyntaxError(`Invalid URL: ${i}`));return}ee(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!==P.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 te(e,t){e._readyState=P.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function ne(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=P.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(te,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`,fe),process.nextTick(le,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`,fe),process.nextTick(le,t._socket),t.close(e[S])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function L(){this[C].emitClose()}function se(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 R(e){this[C].emit(`pong`,e)}function le(e){e.resume()}function ue(e){let t=this[C];t.readyState!==P.CLOSED&&(t.readyState===P.OPEN&&(t._readyState=P.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 z(){let e=this[C];if(this.removeListener(`close`,z),this.removeListener(`data`,fe),this.removeListener(`end`,pe),e._readyState=P.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`,L),e._receiver.on(`finish`,L))}function fe(e){this[C]._receiver.write(e)||this.pause()}function pe(){let e=this[C];e._readyState=P.CLOSING,e._receiver.end(),this.end()}function me(){let e=this[C];this.removeListener(`error`,me),this.on(`error`,w),e&&(e._readyState=P.CLOSING,this.destroy())}})),yy=sy(((e,t)=>{vy();let{Duplex:n}=cy(`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})),by=sy(((e,t)=>{let{tokenChars:n}=py();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}})),xy=sy(((e,t)=>{let n=cy(`events`),r=cy(`http`),{Duplex:i}=cy(`stream`),{createHash:a}=cy(`crypto`),o=_y(),s=fy(),c=by(),l=vy(),{CLOSE_TIMEOUT:u,GUID:d,kWebSocket:f}=ly(),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
68
+ `)){if(i(e))continue;let t=e.match(/^(#{1,6})\s+(.+)$/);if(t){let e=t[2].trim(),i=v(e,r);i&&n.push({level:t[1].length,text:e,slug:i})}}return n}function p_(e){return!(e.includes(`..`)||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))}function m_(e){if(e===`null`)return!0;try{let{hostname:t}=new URL(e);return t===`localhost`||t===`::1`||t===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}catch{return!1}}function h_(e){let{hocuspocus:t,sessionManager:n,contentDir:i,getFileIndex:a,getAliasMap:o,enableTestRoutes:s=!1,shadowRef:c,flushGitCommit:u,getCurrentBranch:d,contentRoot:p,backlinkIndex:m,signalChannel:h,agentFocusBroadcaster:g,agentPresenceBroadcaster:_,onAgentWrite:v,getSyncEngine:b,localOpCliArgs:x=[`open-knowledge`],projectDir:S,getPrincipal:C,installedAgentsProbe:E}=e,D=Bh(),O=cp({probe:E??dp(process.platform)});function k(e){if(!p_(e))return null;let t=H(i),n=H(t,`${e}${Up(e)}`);return!n.startsWith(`${t}/`)&&n!==t?null:n}function j(e){let t=k(e);if(!t||!R(t))return e;try{return Op(z(t,`utf-8`),e)}catch{return e}}let N={cluster:void 0,category:void 0,tags:void 0};function P(e){try{let n=t.documents.get(e);if(n){let e=n.getMap(`metadata`).get(`frontmatter`);if(typeof e==`string`&&e)return kp(e)}}catch{}try{let t=k(e);if(!t||!R(t))return N;let{frontmatter:n}=l(z(t,`utf-8`));return n?kp(n):N}catch{return N}}function ee(e){if(m)try{if(m.getBacklinks(e).length>0)return;let t=performance.now(),n=gp(e,a()),r=performance.now()-t;return r>5&&Yg.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 te(e){return o?.().get(e)??e}function ne(e){try{return t.documents.get(e)?.connections.size??0}catch{return 0}}function re(e,n){let r=`onStoreDocument-${e}`;(t.debouncer.isDebounced(r)?t.debouncer.executeNow(r):Promise.resolve()).then(()=>u?.()).catch(e=>{Yg.warn({err:e},`[${n}] post-write flush failed`)})}function F(){let e=new Set;for(let[t,n]of a()){e.add(t);for(let t of n.aliases)e.add(t)}return e}function ae(){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 I=ae();function L(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 se(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);Qm(n),e&&(t.closeConnections(n),await t.unloadDocument(e))}return r}function ce(e,t){for(let{fromDocName:n,toDocName:r}of e){let e=Wm(r,i),a=t.get(n);typeof a==`string`&&B(e,a,`utf-8`);let o=typeof a==`string`?a:R(e)?z(e,`utf-8`):null;typeof o==`string`&&fh(e,mh(o))}}function le(e,t){return e.map(e=>{let n=t.get(e);if(typeof n==`string`)return{docName:e,content:n};let r=Wm(e,i);if(!R(r))throw Error(`Cannot snapshot missing document: ${e}`);return{docName:e,content:z(r,`utf-8`)}})}function de(e){let n=t.documents.get(e);if(n)return n.getText(`source`).toString();let r=c_(i,`file`,e);return R(r)?z(r,`utf-8`):null}function ve(e,t){let n=c_(i,`file`,e);ue(Se(n),{recursive:!0}),B(n,t,`utf-8`),fh(n,mh(t)),Zm(e,t);let r=a();r instanceof Map&&Ch({kind:`update`,path:n,docName:e,content:t},r)}function ye(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=o_(s,e,n,r),a.rewrites===0)return;let{body:c}=l(a.markdown),u=Dl.parseWithFallback(c);Sl(i,t,Ol.nodeFromJSON(u),{mapping:new Map,isOMark:new Map}),T(o,s,a.markdown)},Jg),a}async function be(e,n){return I(async()=>{if(!m)throw Error(`Managed rename requires backlink index support`);let r=c_(i,`file`,e),o=c_(i,`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=de(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=Gh({sourceDocName:e,destinationDocName:n,snapshots:le([...l.keys()],l)}),p=[];return await Zh(i,f,async()=>{for(let e of d)m.deleteDocument(e);for(let r of u){let i=t.documents.get(r)?ye(r,e,n):o_(l.get(r)??``,r,e,n);i.rewrites>0&&(ve(r,i.markdown),p.push({docName:r,rewrites:i.rewrites})),m.updateDocumentFromMarkdown(r,i.markdown)}let i=o_((await se([e])).get(e)??l.get(e)??z(r,`utf-8`),e,e,n);await u_(S,r,o)||(ue(Se(o),{recursive:!0}),me(r,o)),ce(s,new Map([[e,i.markdown]])),Zm(n,i.markdown);let c=a();c instanceof Map&&Ch({kind:`rename`,oldPath:r,newPath:o,oldDocName:e,newDocName:n,content:i.markdown},c),m.renameDocument(e,n,i.markdown),i.rewrites>0&&p.push({docName:n,rewrites:i.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}})}function xe(e){let t=typeof e.agentId==`string`?e.agentId:void 0;t!==void 0&&!fn.test(t)&&(t=void 0);let n=t?mn(t):`claude-1`,r=typeof e.agentName==`string`?jh(e.agentName):`Claude`,i=typeof e.clientName==`string`?e.clientName:void 0;i!==void 0&&(i=jh(i));let a=typeof e.clientVersion==`string`?e.clientVersion:void 0;a!==void 0&&(a=jh(a));let o=typeof e.label==`string`?e.label:void 0;o!==void 0&&(o=jh(o));let s=typeof e.colorSeed==`string`&&e.colorSeed.length>0?e.colorSeed.slice(0,128):t??n;return{rawAgentId:t,agentId:n,agentName:r,colorSeed:s,clientName:i,clientVersion:a,label:o}}function Ce(e){if(!e)return`bot`;let t=e.toLowerCase();return t.includes(`claude`)?`claude`:t.includes(`cursor`)?`cursor`:t.includes(`codex`)?`codex`:t.includes(`cline`)?`cline`:t.includes(`windsurf`)?`windsurf`:`bot`}function V(e){return{principalId:C?.()?.id,agentType:Ce(e.clientName),clientName:e.clientName,clientVersion:e.clientVersion,label:e.label}}function we(e){return e.kind===`value`?e.truncatedFrom===void 0?{response:{value:e.value},stored:e.value}:{response:{value:e.value,truncatedFrom:e.truncatedFrom,hint:`Summary truncated from ${e.truncatedFrom} chars to 80 (max 80).`},stored:e.value}:{stored:void 0}}function De(e){return{value:e.value}}function Oe(e,t=!1){e.kind===`value`&&(Mn(),e.truncatedFrom!==void 0&&!t&&Nn())}async function ke(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await d_(e)}catch{Y(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=r.length>0?JSON.parse(r.toString()):{}}catch{Y(t,400,{ok:!1,error:`Invalid JSON`});return}let a=typeof i.docName==`string`&&i.docName.length>0?i.docName:`test-doc`;if(!p_(a)){Y(t,400,{ok:!1,error:`Invalid docName`});return}let o=te(a);if(J(o)){Y(t,400,{ok:!1,error:`'${o}' is a reserved document name`});return}let{agentId:s,agentName:c,colorSeed:l,clientName:u,clientVersion:d,label:p}=xe(i),m=Zf(i.summary);if(m.kind===`invalid`){Y(t,400,{ok:!1,error:`summary must be a string`});return}let h=await n.getSession(o,s,{displayName:c,colorSeed:l,clientName:u}),g=new Date().toISOString(),b=typeof i.content==`string`?i.content:`Hello from the agent! ${g}`,{response:x,stored:S}=we(m);try{let e=w(u),t=y[e]??f(l??s);_?.setPresence(s,{displayName:c,icon:e,color:t,currentDoc:o,mode:`writing`,ts:Date.now()}),Xf(h.dc.document.getText(`source`),s,l,u),h.dc.document.transact(()=>{Al(h.dc.document,`${b}\n`,`append`),h.dc.document.getMap(`agent-flash`).set(s,{agentId:s,timestamp:Date.now(),type:`insert`,description:`Added (${c}): ${b.slice(0,50)}`})},h.origin),$f(o,s,c,l,void 0,V({clientName:u,clientVersion:d,label:p}),S),jn(),Oe(m)}finally{_?.touchMode(s,`idle`)}re(o,`agent-write`),v?.(),Y(t,200,{ok:!0,timestamp:g,...x?{summary:x}:{}})}catch(e){Yg.error({err:e},`[agent-write] handler failed`),Y(t,500,{ok:!1,error:`Internal server error`})}}async function Ae(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await d_(e)}catch{Y(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(r.toString())}catch{Y(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){Y(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{markdown:a,position:o}=i;if(!a||typeof a!=`string`){Y(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(!p_(l)){Y(t,400,{ok:!1,error:`Invalid docName`});return}let u=te(l);if(J(u)){Y(t,400,{ok:!1,error:`'${u}' is a reserved document name`});return}let{agentId:d,agentName:p,colorSeed:m,clientName:h,clientVersion:b,label:x}=xe(i),S=Zf(i.summary);if(S.kind===`invalid`){Y(t,400,{ok:!1,error:`summary must be a string`});return}let{response:C,stored:T}=we(S),E=await n.getSession(u,d,{displayName:p,colorSeed:m,clientName:h}),D=new Date().toISOString();try{let e=w(h),t=y[e]??f(m??d);_?.setPresence(d,{displayName:p,icon:e,color:t,currentDoc:u,mode:`writing`,ts:Date.now()}),Xf(E.dc.document.getText(`source`),d,m,h),E.dc.document.transact(()=>{Al(E.dc.document,a,s),E.dc.document.getMap(`agent-flash`).set(d,{agentId:d,timestamp:Date.now(),type:`insert`,description:`Added (${p}): ${a.trim().slice(0,50)}`})},E.origin),$f(u,d,p,m,void 0,V({clientName:h,clientVersion:b,label:x}),T),jn(),Oe(S)}finally{_?.touchMode(d,`idle`)}re(u,`agent-write-md`),g?.setFocus(d,{agentName:p,currentDoc:u,writeKind:`write`,ts:Date.now()}),v?.();let O=ee(u);Y(t,200,{ok:!0,timestamp:D,subscriberCount:ne(u),...O?{hints:O}:{},...C?{summary:C}:{}})}catch(e){Yg.error({err:e},`[agent-write-md] handler failed`),Y(t,500,{ok:!1,error:`Internal server error`})}}async function je(e,n){if(e.method!==`GET`){n.writeHead(405),n.end(`Method not allowed`);return}try{let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!p_(r)){Y(n,400,{ok:!1,error:`Invalid docName`});return}let i=te(r);if(J(i)){Y(n,400,{ok:!1,error:`'${i}' is a reserved document name`});return}let a=await t.openDirectConnection(i);try{let e=a.document;if(!e){Y(n,500,{ok:!1,error:`Document not available`});return}Y(n,200,{ok:!0,docName:i,content:e.getText(`source`).toString()})}finally{await a.disconnect()}}catch(e){console.error(`[document-read]`,e),Y(n,500,{ok:!1,error:`Internal server error`})}}async function Me(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{n_(i,n)}catch{Y(t,400,{ok:!1,error:`Invalid directory parameter`});return}let r=a(),o=[];for(let[e,t]of r)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 r of t.aliases){if(n&&!r.startsWith(`${n}/`)&&r!==n)continue;let a=Te(i,t.canonicalPath);o.push({docName:r,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:a})}}o.sort((e,t)=>e.docName.localeCompare(t.docName)),Y(t,200,{ok:!0,documents:o})}catch(e){console.error(`[document-list]`,e),Y(t,500,{ok:!1,error:`Internal server error`})}}async function Pe(e,t){if(e.method!==`GET`){Y(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){Y(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){Y(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!p_(n)){Y(t,400,{ok:!1,error:`Invalid docName`});return}Y(t,200,{ok:!0,docName:n,backlinks:m.getBacklinks(n).map(e=>({source:e.source,anchor:e.anchor,title:j(e.source),snippet:e.snippet}))})}catch(e){console.error(`[backlinks]`,e),Y(t,500,{ok:!1,error:`Failed to read backlinks`})}}async function Ie(e,t){if(e.method!==`GET`){Y(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){Y(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!n){Y(t,400,{ok:!1,error:`Missing docNames parameter`});return}let r={};for(let e of n.split(`,`)){let t=e.trim();!t||!p_(t)||(r[t]=m.getBacklinkCount(t))}Y(t,200,{ok:!0,counts:r})}catch(e){console.error(`[backlink-counts]`,e),Y(t,500,{ok:!1,error:`Failed to read backlink counts`})}}async function Le(e,t){if(e.method!==`GET`){Y(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){Y(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){Y(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!p_(n)){Y(t,400,{ok:!1,error:`Invalid docName`});return}Y(t,200,{ok:!0,docName:n,forwardLinks:m.getForwardLinkEntries(n).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:j(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),Y(t,500,{ok:!1,error:`Failed to read forward links`})}}async function Re(e,t){if(e.method!==`GET`){Y(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){Y(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&&!p_(r)){Y(t,400,{ok:!1,error:`Invalid docName`});return}let i=n.searchParams.get(`degrees`);if(i&&!r){Y(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){Y(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());Y(t,200,{ok:!0,nodes:a.map(e=>{if(e.kind===`doc`){let t=P(e.docName);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:j(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),Y(t,500,{ok:!1,error:`Failed to read link graph`})}}async function ze(e,t){if(e.method!==`GET`){Y(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){Y(t,503,{ok:!1,error:`Backlink index not configured`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!r(n)){Y(t,400,{ok:!1,error:`Invalid orphan mode. Allowed values: incoming, outgoing, both`});return}Y(t,200,{ok:!0,orphans:m.getOrphans([...a().keys()],n).map(e=>({docName:e,title:j(e)}))})}catch(e){console.error(`[orphans]`,e),Y(t,500,{ok:!1,error:`Failed to read orphan pages`})}}async function Be(e,t){if(e.method!==`GET`){Y(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){Y(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;Y(t,200,{ok:!0,hubs:m.getHubs(i).map(e=>({docName:e.docName,title:j(e.docName),count:e.count}))})}catch(e){console.error(`[hubs]`,e),Y(t,500,{ok:!1,error:`Failed to read hub pages`})}}async function Ve(e,t){if(e.method!==`GET`){Y(t,405,{ok:!1,error:`Method not allowed`});return}if(!m){Y(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||!p_(e))){Y(t,400,{ok:!1,error:`Invalid sourceDocName`});return}let r=n.length?[...new Set(n.map(e=>te(e)))]:void 0;Y(t,200,{ok:!0,deadLinks:m.getDeadLinks(F(),r).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:j(e.source),snippet:e.snippet}))}))})}catch(e){console.error(`[dead-links]`,e),Y(t,500,{ok:!1,error:`Failed to read dead links`})}}async function He(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await d_(e)}catch{Y(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=JSON.parse(r.toString())}catch{Y(t,400,{ok:!1,error:`Invalid JSON`});return}if(!i||typeof i!=`object`||Array.isArray(i)){Y(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){Y(t,400,{ok:!1,error:`find field required`});return}if(typeof o!=`string`){Y(t,400,{ok:!1,error:`replace field required`});return}let u=Object.hasOwn(i,`offset`),d;if(u){if(typeof c!=`number`||!Number.isInteger(c)||c<0){Y(t,400,{ok:!1,error:`offset must be a non-negative integer`});return}d=c}let p=typeof s==`string`&&s.length>0?s:`test-doc`;if(!p_(p)){Y(t,400,{ok:!1,error:`Invalid docName`});return}let m=te(p);if(J(m)){Y(t,400,{ok:!1,error:`'${m}' is a reserved document name`});return}let{agentId:h,agentName:b,colorSeed:x,clientName:S,clientVersion:C,label:T}=xe(i),E=Zf(i.summary);if(E.kind===`invalid`){Y(t,400,{ok:!1,error:`summary must be a string`});return}let D=await n.getSession(m,h,{displayName:b,colorSeed:x,clientName:S}),O=new Date().toISOString(),k=!1,A=!1;try{let e=w(S),t=y[e]??f(x??h);if(_?.setPresence(h,{displayName:b,icon:e,color:t,currentDoc:m,mode:`writing`,ts:Date.now()}),Xf(D.dc.document.getText(`source`),h,x,S),D.dc.document.transact(()=>{let e=D.dc.document.getXmlFragment(`default`),t=D.dc.document.getMap(`metadata`),n=t.get(`frontmatter`)??``,r=M(n,Dl.serialize(Tl(e,Ol).toJSON())),i=d==null?r.indexOf(a):r.slice(d,d+a.length)===a?d:-1;if(i===-1){d==null?k=!0:A=!0;return}let{frontmatter:s,body:c}=l(r.slice(0,i)+o+r.slice(i+a.length));s!==n&&t.set(`frontmatter`,s),Al(D.dc.document,c,`replace`),D.dc.document.getMap(`agent-flash`).set(h,{agentId:h,timestamp:Date.now(),type:`insert`,description:`Patched (${b}): ${a.slice(0,50)}`})},D.origin),!k&&!A){let{stored:e}=we(E);$f(m,h,b,x,void 0,V({clientName:S,clientVersion:C,label:T}),e),jn(),Oe(E)}}finally{_?.touchMode(h,`idle`)}if(A){Y(t,409,{ok:!1,error:`Target text no longer matches at the requested offset`});return}if(k){Y(t,404,{ok:!1,error:`Text not found in document`});return}re(m,`agent-patch`),g?.setFocus(h,{agentName:b,currentDoc:m,writeKind:`edit`,ts:Date.now()}),v?.();let j=ne(m),{response:N}=we(E);Y(t,200,{ok:!0,timestamp:O,subscriberCount:j,...N?{summary:N}:{}})}catch(e){Yg.error({err:e},`[agent-patch] handler failed`),Y(t,500,{ok:!1,error:`Internal server error`})}}async function Ue(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{let r;try{r=await d_(e)}catch{Y(t,413,{ok:!1,error:`Payload too large`});return}let i;try{i=r.length>0?JSON.parse(r.toString()):{}}catch{Y(t,400,{ok:!1,error:`Invalid JSON`});return}let{agentId:a,agentName:o,colorSeed:s,clientName:c,clientVersion:l,label:u}=xe(i),d=typeof i.docName==`string`&&i.docName.length>0?i.docName:`test-doc`;if(!p_(d)){Y(t,400,{ok:!1,error:`Invalid docName`});return}let p=te(d);if(J(p)){Y(t,400,{ok:!1,error:`'${p}' is a reserved document name`});return}let m=typeof i.connectionId==`string`?i.connectionId:void 0;if(!m){Y(t,400,{ok:!1,error:`connectionId required`});return}let h=i.scope===`session`?`session`:`last`;if(!n.hasSession(p,m)){Y(t,404,{ok:!1,error:`No active session for this connectionId and docName`});return}let v=await n.getSession(p,m),b=!1;try{let e=w(c),t=y[e]??f(s??a);_?.setPresence(a,{displayName:o,icon:e,color:t,currentDoc:p,mode:`writing`,ts:Date.now()}),b=jl(v,h),b&&$f(p,m,o,s,void 0,V({clientName:c,clientVersion:l,label:u}))}finally{_?.touchMode(a,`idle`)}b&&re(p,`agent-undo`),g?.setFocus(m,{agentName:m,currentDoc:p,writeKind:`undo`,ts:Date.now()}),Y(t,200,{ok:!0,docName:p,scope:h,undone:b})}catch(e){Yg.error({err:e},`[agent-undo] handler failed`),Y(t,500,{ok:!1,error:`Internal server error`})}}async function We(e,r){if(e.method!==`POST`){r.writeHead(405),r.end(`Method not allowed`);return}try{let a=te(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??`test-doc`),o;try{o=Wm(a,i)}catch(e){console.error(`[test-reset] safeContentPath rejected docName:`,a,e),Y(r,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),B(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`),Y(r,200,{ok:!0})}catch(e){console.error(`[test-reset]`,e),Y(r,500,{ok:!1,error:`Internal server error`})}}async function Ge(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}try{if(!m){Y(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`),Y(t,200,{ok:!0})}catch(e){console.error(`[test-rescan-backlinks]`,e),Y(t,500,{ok:!1,error:`Internal server error`})}}async function Ke(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}let n=c?.current;if(!n){Y(t,400,{ok:!1,error:`Shadow repo not configured`});return}try{let r;try{r=await d_(e)}catch{Y(t,413,{ok:!1,error:`Payload too large`});return}let i=/^[a-zA-Z0-9_-]+$/,a=[],o,s={},c,l;if(r.length>0){let e;try{e=JSON.parse(r.toString())}catch{Y(t,400,{ok:!1,error:`Invalid JSON`});return}s=e,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,``)}}));let n=e.principal;if(n&&typeof n==`object`&&!Array.isArray(n)){let e=n;typeof e.name==`string`&&e.name.trim()&&(c=jh(e.name.trim())),typeof e.email==`string`&&e.email.trim()&&(l=jh(e.email.trim()))}}let{rawAgentId:u,agentId:d,agentName:f,clientName:m}=xe(s);a.length===0&&(a=u===void 0?[Mm]:[{id:d,name:m?`${f} (${m})`:f,email:`${d}@openknowledge.local`}]);let h=p??`content`,g=await Vm(n,h,a);console.log(`[history] checkpoint ${g.checkpointRef}`);let _=ep(),v;if(S){let e=!1;try{await Fe({baseDir:S,timeout:{block:5e3}}).revparse([`--git-dir`]),e=!0}catch(e){console.warn(`[save-version] parent-git unavailable: ${e instanceof Error?e.message:String(e)}`)}if(e)try{v=await oe(async()=>{let e=Fe({baseDir:S,timeout:{block:15e3}}),t=(await e.tags([`--list`,`ok/v*`])).all.length+1,n=`ok/v${t}`,r=`openknowledge`,i=`noreply@openknowledge.local`;if(c&&l)r=c,i=l;else try{let e=await kh(S);e&&(r=e.name,i=e.email)}catch{}let a=[];for(let e of _.values())if(e.writerId.startsWith(`agent-`)||e.writerId.startsWith(`principal-`)){let t=`${e.writerId}@openknowledge.local`;a.push(`Co-Authored-By: ${e.displayName} <${t}>`)}let s=eu(o??`Checkpoint v${t}`),u=a.length>0?`${s}\n\n${a.join(`
69
+ `)}`:s,d=h||`.`;return await e.add(d),await e.env({GIT_AUTHOR_NAME:r,GIT_AUTHOR_EMAIL:i,GIT_COMMITTER_NAME:r,GIT_COMMITTER_EMAIL:i}).commit(u,[`--allow-empty`]),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)}}Y(t,200,{ok:!0,checkpointRef:g.checkpointRef,...v?{versionTag:v}:{}})}catch(e){console.error(`[save-version]`,e),Y(t,500,{ok:!1,error:`Internal server error`})}}async function qe(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=c?.current;if(!n){Y(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){Y(t,400,{ok:!1,error:`docName query parameter is required`});return}if(a.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(a)){Y(t,400,{ok:!1,error:`Invalid branch name`});return}let o=Number(r.searchParams.get(`limit`)??`50`),s=Number(r.searchParams.get(`offset`)??`0`),l=Math.min(200,Number.isFinite(o)?o:50),u=Number.isFinite(s)?s:0,f=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 Gg(n,{docName:i,branch:a,limit:l,offset:u,type:f,author:m,excludeAuthor:h},p??`content`),r=Date.now()-g;console.log(`[timeline] query docName=${i} entries=${e.entries.length} duration=${r}ms`),Y(t,200,{ok:!0,...e})}catch(e){console.error(`[shadow]`,e),Y(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function Je(e,t,n){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let r=c?.current;if(!r){Y(t,400,{ok:!1,error:`Shadow repo not configured`});return}let i=Xg(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,p??`content`);if(`error`in i){Y(t,400,{ok:!1,error:i.error});return}let a=i.path,o=Sm(r);if(!/^[0-9a-f]{40}$/i.test(n)){Y(t,400,{ok:!1,error:`Invalid commit SHA`});return}try{try{await o.raw(`cat-file`,`-e`,`${n}:${a}`)}catch{Y(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`);Y(t,200,{ok:!0,sha:n,content:e,timestamp:r,author:i})}catch(e){console.error(`[shadow-version]`,e),Y(t,500,{ok:!1,error:`Internal server error`})}}async function Ye(e,n){if(e.method!==`GET`){n.writeHead(405),n.end(`Method not allowed`);return}let r=c?.current;if(!r){Y(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`)??``,s=i.searchParams.get(`to`)??``;if(!s||!/^[0-9a-f]{40}$/i.test(s)){Y(n,400,{ok:!1,error:`'to' must be a valid 40-char commit SHA`});return}let u=Xg(a,p??`content`);if(`error`in u){Y(n,400,{ok:!1,error:u.error});return}let d=u.path,f=Sm(r);try{let e;try{e=await f.raw(`show`,`${s}:${d}`)}catch{Y(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 f.raw(`show`,`${o}:${d}`)}catch{Y(n,404,{ok:!1,error:`Document did not exist at the source version`});return}else{let e=t.documents.get(a);if(!e){Y(n,409,{ok:!1,error:`Document is not currently open — open it in the editor first`});return}r=e.getText(`source`).toString()}let i=l(r).body,c=l(e).body,u=Eu(i,c),p=[],m=0,h=0;for(let e of u){let t=e.value.replace(/\n$/,``).split(`
70
+ `),n=e.added?`added`:e.removed?`removed`:`unchanged`;for(let e of t)p.push({type:n,text:e});e.added&&(m+=t.length),e.removed&&(h+=t.length)}Y(n,200,{ok:!0,lines:p,additions:m,deletions:h})}catch(e){console.error(`[diff]`,e),Y(n,500,{ok:!1,error:`Internal server error`})}}async function Xe(e,n){if(e.method!==`POST`){n.writeHead(405),n.end(`Method not allowed`);return}let r=c?.current;if(!r){Y(n,400,{ok:!1,error:`Shadow repo not configured`});return}let i;try{i=await d_(e)}catch{Y(n,413,{ok:!1,error:`Payload too large`});return}let a;try{a=i.length>0?JSON.parse(i.toString()):{}}catch{Y(n,400,{ok:!1,error:`Invalid JSON`});return}if(!a||typeof a!=`object`||Array.isArray(a)){Y(n,400,{ok:!1,error:`Body must be a JSON object`});return}let{agentId:o,agentName:s,colorSeed:u,clientName:d,clientVersion:f,label:m}=xe(a),{docName:h,commitSha:_,versionTag:v}=a,y=typeof h==`string`?h:``,b=typeof _==`string`?_:``,x=typeof v==`string`?v:void 0;if(!y){Y(n,400,{ok:!1,error:`docName required`});return}if(!b||!/^[0-9a-f]{40}$/i.test(b)){Y(n,400,{ok:!1,error:`commitSha must be a valid 40-char commit SHA`});return}let C=a,w=typeof C.agentId==`string`&&C.agentId.length>0,T=Zf(C.summary);if(T.kind===`invalid`){Y(n,400,{ok:!1,error:`summary must be a string`});return}let E=p??`content`,D=Xg(y,E);if(`error`in D){Y(n,400,{ok:!1,error:D.error});return}let O=D.path,k=Sm(r),A=Date.now();try{try{await k.raw(`cat-file`,`-e`,`${b}:${O}`)}catch{Y(n,404,{ok:!1,error:`Document did not exist at this version`});return}let e=await k.raw(`show`,`${b}:${O}`),i=new Date().toISOString();await Im(r,E,{action:`rollback`,context:{docName:y,targetSha:b}});let a=t.documents.get(y);if(!a){Y(n,409,{ok:!1,error:`Document is not currently open — open it in the editor first`});return}let{frontmatter:c,body:h}=l(e),_=Dl.parseWithFallback(h),v=Ol.nodeFromJSON(_),C=a.getXmlFragment(`default`);a.transact(()=>{Sl(a,C,v,{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`,c)},qg);let D;if(w){let e=b.slice(0,8),t=T.kind===`value`,n=t?T:Zf(`Restored to ${e}`),r=we(n);D=t||!r.response?r.response:De(r.response),$f(y,o,s,u,Zl(y,b),V({clientName:d,clientVersion:f,label:m}),r.stored),jn(),Oe(n,!t)}re(y,`rollback`);let j=Date.now()-A;if(console.log(`[rollback] docName=${y} from=${b.slice(0,8)} duration=${j}ms`),S){let e=`Restored to ${x??b.slice(0,8)}: ${y}`,t=p??`content`;oe(async()=>{let n=Fe({baseDir:S,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)})}w&&g?.setFocus(o,{agentName:s,currentDoc:y,writeKind:`rollback-apply`,ts:Date.now()}),Y(n,200,{ok:!0,restoredFrom:b,timestamp:i,...D?{summary:D}:{}})}catch(e){console.error(`[rollback]`,e),Y(n,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function Ze(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}Y(t,200,Vn())}async function Qe(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}Y(t,200,A())}async function $e(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=C?.()??null;if(!n){Y(t,404,{error:`Principal not available`});return}Y(t,200,n)}async function et(e,t){if(!Vh(e.socket.remoteAddress)){Y(t,403,{ok:!1,error:`loopback-required`});return}if(!Hh(e.headers.host)){Y(t,403,{ok:!1,error:`host-header-not-allowed`});return}if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}let n=_?.getPresenceMap()??{},r=Date.now(),i={};for(let[e,t]of Object.entries(n))r-t.ts<2e4&&(i[e]=t);Y(t,200,{presence:i})}async function tt(e,t){if(!Vh(e.socket.remoteAddress)){Y(t,403,{ok:!1,error:`loopback-required`});return}if(!Hh(e.headers.host)){Y(t,403,{ok:!1,error:`host-header-not-allowed`});return}if(e.method!==`GET`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n=H(i),r=n,a=!0;try{r=pe(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}),Y(t,500,{ok:!1,error:`workspace-realpath-failed`,code:r??null});return}}Y(t,200,{ok:!0,contentDir:r,pathSeparator:Ee,symlinkResolved:a})}let nt=1440*60*1e3;async function rt(e,t){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}if(!c?.current){Y(t,200,[]);return}let n=Date.now(),r=[],i=H(c.current.gitDir,`rescue`);if(R(i))try{let e=fe(i).filter(e=>Rp(e));for(let t of e){let e=H(i,t),a=ge(e);if(n-a.mtimeMs>nt){try{_e(e)}catch(e){console.debug(`[rescue] cleanup failed (non-critical):`,e)}continue}r.push({docName:zp(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 Rm(c.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)}Y(t,200,r)}async function it(e,t,n){if(e.method!==`GET`){t.writeHead(405),t.end(`Method not allowed`);return}if(!c?.current){t.writeHead(404),t.end(`Not found`);return}let r=H(c.current.gitDir,`rescue`),i=H(r,`${n}${Up(n)}`);if(!i.startsWith(`${r}/`)){t.writeHead(400),t.end(`Invalid document name`);return}if(R(i)){let e=ge(i);if(Date.now()-e.mtimeMs>nt)try{_e(i)}catch{}else{let e=z(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 Rm(c.current,e)).filter(e=>e.docName===n).sort((e,t)=>t.timestamp.localeCompare(e.timestamp))[0];if(r){let e=Sm(c.current),n=((await e.raw(`ls-tree`,`-r`,r.sha)).trim().split(`
71
+ `)[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 at(e,t){if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await d_(e)}catch{Y(t,413,{ok:!1,error:`Payload too large`});return}let r;try{r=JSON.parse(n.toString())}catch{Y(t,400,{ok:!1,error:`Invalid JSON`});return}if(!r||typeof r!=`object`||Array.isArray(r)){Y(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{agentId:o,agentName:s,colorSeed:c,clientName:l,clientVersion:u,label:d}=xe(r),{path:f}=r;if(!f||typeof f!=`string`||f.length===0){Y(t,400,{ok:!1,error:`path is required`});return}if(!Rp(f)){Y(t,400,{ok:!1,error:`path must end with .md or .mdx`});return}if(f.includes(`..`)||f.startsWith(`/`)||f.includes(`\0`)||f.includes(`\\`)){Y(t,400,{ok:!1,error:`path must not contain .. or start with /`});return}let p=H(i),g=H(p,f);if(!g.startsWith(`${p}/`)&&g!==p){Y(t,400,{ok:!1,error:`path must not escape content directory`});return}let _=zp(f);if(J(_)){Y(t,400,{ok:!1,error:`'${_}' is a reserved document name`});return}ue(Se(g),{recursive:!0});try{B(g,``,{encoding:`utf-8`,flag:`wx`})}catch(e){if(e.code===`EEXIST`){Y(t,409,{ok:!1,error:`File already exists`});return}throw e}let v=zp(f);$f(v,o,s,c,void 0,V({clientName:l,clientVersion:u,label:d}));let y=typeof a==`function`?a():null;y instanceof Map&&Ch({kind:`create`,path:g,docName:v,content:``},y),m&&(m.updateDocumentFromMarkdown(v,``),m.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist create-page cache for ${v}:`,e)}),h?.(`backlinks`),h?.(`graph`)),h?.(`files`),Y(t,200,{ok:!0,docName:v})}catch(e){console.error(`[create-page]`,e),Y(t,500,{ok:!1,error:`Failed to create page`})}}async function ot(e,t){if(e.method!==`GET`){Y(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){Y(t,400,{ok:!1,error:`Missing docName parameter`});return}if(!p_(n)){Y(t,400,{ok:!1,error:`Invalid docName`});return}let r=k(n);if(!r){Y(t,400,{ok:!1,error:`Invalid docName`});return}if(!R(r)){Y(t,404,{ok:!1,error:`Page not found`});return}Y(t,200,{ok:!0,docName:n,headings:f_(z(r,`utf-8`))})}catch(e){console.error(`[page-headings]`,e),Y(t,500,{ok:!1,error:`Failed to read headings`})}}async function st(e,t){if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await d_(e)}catch{Y(t,413,{ok:!1,error:`Payload too large`});return}let r;try{r=JSON.parse(n.toString())}catch{Y(t,400,{ok:!1,error:`Invalid JSON`});return}if(!r||typeof r!=`object`||Array.isArray(r)){Y(t,400,{ok:!1,error:`Body must be a JSON object`});return}let{agentId:a,agentName:o,colorSeed:s,clientName:c,clientVersion:l,label:u}=xe(r),{docName:d,newDocName:f}=r;if(typeof d!=`string`||typeof f!=`string`){Y(t,400,{ok:!1,error:`docName and newDocName are required`});return}if(!r_(d)||!r_(f)){Y(t,400,{ok:!1,error:`Document names must be relative content paths`});return}if(J(d)||J(f)){Y(t,400,{ok:!1,error:`Reserved document names cannot be renamed`});return}if(d===f){Y(t,200,{ok:!0,renamed:[],rewrittenDocs:[]});return}if(!m){Y(t,503,{ok:!1,error:`Backlink index unavailable`});return}let p=r,h=typeof p.agentId==`string`&&p.agentId.length>0,g=Zf(p.summary);if(g.kind===`invalid`){Y(t,400,{ok:!1,error:`summary must be a string`});return}let _=c_(i,`file`,d),v=c_(i,`file`,f);if(!R(_)){Y(t,404,{ok:!1,error:`Document does not exist`});return}if(R(v)){Y(t,409,{ok:!1,error:`Destination already exists`});return}let y=await be(d,f),b;if(h){let e=g.kind===`value`,t=e?g:Zf(`Renamed ${d} → ${f}`),n=we(t);b=e||!n.response?n.response:De(n.response),$f(f,a,o,s,$l(d,f),V({clientName:c,clientVersion:l,label:u}),n.stored),jn(),Oe(t,!e),re(f,`rename`)}Y(t,200,{ok:!0,renamed:y.renamed,rewrittenDocs:y.rewrittenDocs,...b?{summary:b}:{}})}catch(e){console.error(`[rename]`,e),Y(t,500,{ok:!1,error:L(e)})}}async function ct(e,t){if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await d_(e)}catch{Y(t,413,{ok:!1,error:`Payload too large`});return}let r;try{r=JSON.parse(n.toString())}catch{Y(t,400,{ok:!1,error:`Invalid JSON`});return}if(!r||typeof r!=`object`||Array.isArray(r)){Y(t,400,{ok:!1,error:`Body must be a JSON object`});return}xe(r);let{kind:o,fromPath:s,toPath:c}=r;if(o!==`file`&&o!==`folder`){Y(t,400,{ok:!1,error:`kind must be "file" or "folder"`});return}if(typeof s!=`string`||typeof c!=`string`){Y(t,400,{ok:!1,error:`fromPath and toPath are required`});return}if(!r_(s)||!r_(c)){Y(t,400,{ok:!1,error:`Paths must be relative content paths`});return}if(s===c){Y(t,200,{ok:!0,renamed:[]});return}let l=c_(i,o,s),u=c_(i,o,c);if(!R(l)){Y(t,404,{ok:!1,error:`${o} does not exist`});return}if(R(u)){Y(t,409,{ok:!1,error:`Destination already exists`});return}let d=ge(l);if(o===`file`&&!d.isFile()||o===`folder`&&!d.isDirectory()){Y(t,400,{ok:!1,error:`Source path is not a ${o}`});return}let f=i_(a(),o,s),p=o===`file`?[{fromDocName:s,toDocName:c}]:f.map(e=>({fromDocName:e,toDocName:a_(e,o,s,c)})),g=await se(p.map(({fromDocName:e})=>e)),_=async()=>{await u_(S,l,u)||(ue(Se(u),{recursive:!0}),me(l,u)),ce(p,g)};if(o===`file`)await Zh(i,Gh({sourceDocName:s,destinationDocName:c,snapshots:le(p.map(({fromDocName:e})=>e),g)}),_);else{await _();let e=a();for(let{fromDocName:t,toDocName:n}of p)Ch({kind:`rename`,oldPath:c_(i,`file`,t),newPath:c_(i,`file`,n),oldDocName:t,newDocName:n,content:g.get(t)??z(c_(i,`file`,n),`utf-8`)},e);if(m){for(let{fromDocName:e,toDocName:t}of p)m.renameDocument(e,t,g.get(e)??z(c_(i,`file`,t),`utf-8`));m.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist folder rename cache for ${s} -> ${c}:`,e)}),h?.(`backlinks`),h?.(`graph`)}h?.(`files`)}Y(t,200,{ok:!0,renamed:p})}catch(e){console.error(`[rename-path]`,e),Y(t,500,{ok:!1,error:`Failed to rename path`})}}async function lt(e,t){if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}try{let n;try{n=await d_(e)}catch{Y(t,413,{ok:!1,error:`Payload too large`});return}let r;try{r=JSON.parse(n.toString())}catch{Y(t,400,{ok:!1,error:`Invalid JSON`});return}if(!r||typeof r!=`object`||Array.isArray(r)){Y(t,400,{ok:!1,error:`Body must be a JSON object`});return}xe(r);let{kind:o,path:s}=r;if(o!==`file`&&o!==`folder`){Y(t,400,{ok:!1,error:`kind must be "file" or "folder"`});return}if(typeof s!=`string`||!r_(s)){Y(t,400,{ok:!1,error:`path must be a relative content path`});return}let c=c_(i,o,s);if(!R(c)){Y(t,404,{ok:!1,error:`${o} does not exist`});return}let l=ge(c);if(o===`file`&&!l.isFile()||o===`folder`&&!l.isDirectory()){Y(t,400,{ok:!1,error:`Target path is not a ${o}`});return}let u=o===`file`?[s]:i_(a(),o,s);await se(u),o===`file`?_e(c):he(c,{recursive:!0,force:!1}),Y(t,200,{ok:!0,deletedDocNames:u})}catch(e){console.error(`[delete-path]`,e),Y(t,500,{ok:!1,error:`Failed to delete path`})}}async function ut(e,t){if(e.method!==`GET`){Y(t,405,{ok:!1,error:`Method not allowed`});return}try{let e=a(),n=[];for(let[t,r]of e){let e=t;try{e=Op(z(H(i,`${t}${Up(t)}`),`utf-8`),t)}catch(e){console.warn(`[pages] Failed to read title for ${t}:`,e)}n.push({docName:t,title:e,size:r.size,modified:r.modified})}n.sort((e,t)=>e.docName.localeCompare(t.docName)),Y(t,200,{ok:!0,pages:n})}catch(e){console.error(`[pages]`,e),Y(t,500,{ok:!1,error:`Failed to list pages`})}}async function dt(e,n){if(e.method!==`GET`){Y(n,405,{ok:!1,error:`Method not allowed`});return}try{let r=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!r){Y(n,400,{ok:!1,error:`Missing docName parameter`});return}if(!p_(r)){Y(n,400,{ok:!1,error:`Invalid docName`});return}if(J(r)){Y(n,400,{ok:!1,error:`'${r}' is a reserved document name`});return}Y(n,200,{ok:!0,...await Rg({hocuspocus:t,fileIndex:a(),docName:r})})}catch(e){if(e instanceof gg){Y(n,404,{ok:!1,error:`Page not found`});return}console.error(`[suggest-links]`,e),Y(n,500,{ok:!1,error:`Failed to suggest links`})}}async function ft(e,t){if(e.method!==`POST`){t.writeHead(405),t.end(`Method not allowed`);return}let n;try{n=await t_(e,10485760)}catch(e){let n=e instanceof Error?e.message:String(e);n===`Payload too large`?Y(t,413,{ok:!1,error:`Payload too large`}):n===`No file received`?Y(t,400,{ok:!1,error:`No file received`}):Y(t,400,{ok:!1,error:`Failed to parse upload: ${n}`});return}let{filename:r,buffer:a,parentDocName:o}=n;if(xe(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries())),!o){Y(t,400,{ok:!1,error:`parentDocName is required`});return}if(o.includes(`\0`)||o.includes(`..`)||o.startsWith(`/`)){Y(t,400,{ok:!1,error:`path-escape`});return}let s=H(i),c=H(s,Se(o));if(!Gm(c,s)){Y(t,400,{ok:!1,error:`path-escape`});return}try{let e=pe(c),n;try{n=pe(s)}catch{n=s}if(!Gm(e,n)){Y(t,400,{ok:!1,error:`path-escape`});return}}catch(e){if(e.code!==`ENOENT`){Y(t,400,{ok:!1,error:`path-escape`});return}}let l=await Kf(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||!Zg.has(u)){Y(t,400,{ok:!1,error:`Unsupported file type${u?`: ${u}`:``}`});return}let f;f=!r||r===`upload`||Qg.test(r)?`pasted-${new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`)}.${d}`:$g(r),ue(c,{recursive:!0});try{let e=e_(c,f,a),n=Te(i,H(c,e));console.log(`[upload] ok ${n} ${a.length}`),Y(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}`),Y(t,500,{ok:!1,error:`Failed to save file`})}}let pt=`/api/local-op/clone`,mt=`/api/local-op/open`,ht=600*1e3;async function gt(e,t){if(!zh(e,t,Y))return;if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n,r;try{let i=await d_(e),a=JSON.parse(i.toString());if(typeof a.url!=`string`||!a.url){Y(t,400,{ok:!1,error:`Missing or invalid url`});return}if(typeof a.dir!=`string`||!a.dir){Y(t,400,{ok:!1,error:`Missing or invalid dir`});return}n=a.url,r=a.dir}catch{Y(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!Ph(n)){Y(t,400,{ok:!1,error:`URL protocol not allowed`});return}if(!Ih(r)){Y(t,400,{ok:!1,error:`dir must be within the user home directory`});return}if(!D.tryAcquire(pt)){Y(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=Fh(r),[a,...o]=x,s=[...o,`clone`,`--json`,n,i],c=!1,l=!1,u=null,d=``,f=Ne(a,s,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),p=setTimeout(()=>{c=!0,f.kill(`SIGTERM`)},ht);f.stdout.on(`data`,e=>{d+=e.toString(`utf-8`);let n=d.split(`
72
+ `);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),Yg.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){D.release(pt);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&&Yg.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 _t(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(),D.release(pt)}})()}),f.on(`error`,e=>{clearTimeout(p),l||(l=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),D.release(pt)})}async function _t(e){let t=H(Fh(e)),n=H(t,`.open-knowledge`),r=Fp(n);if(r&&r.port>0)return{port:r.port};let i=ie(n),[a,...o]=x,s=i&&i.port>0?`ui`:`start`,c=Ne(a,[...o,s],{cwd:t,detached:!0,stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env}}),l=[];c.stderr?.on(`data`,e=>{l.push(e),Yg.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=Fp(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 vt(e,t){if(!zh(e,t,Y))return;if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n;try{let r=await d_(e),i=JSON.parse(r.toString());if(typeof i.dir!=`string`||!i.dir){Y(t,400,{ok:!1,error:`Missing or invalid dir`});return}n=i.dir}catch{Y(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!Ih(n)){Y(t,400,{ok:!1,error:`dir must be within the user home directory`});return}if(!D.tryAcquire(mt)){Y(t,429,{ok:!1,error:`A server-open operation is already in progress`});return}try{let e=await _t(n);`port`in e?Y(t,200,{port:e.port}):Y(t,504,{ok:!1,error:e.error})}finally{D.release(mt)}}let yt=`/api/local-op/auth/login`,bt=`/api/local-op/auth/status`,xt=`/api/local-op/auth/repos`,St=`/api/local-op/auth/signout`,Ct=`/api/local-op/auth/pat`;async function wt(e,t){if(!zh(e,t,Y))return;if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=await d_(e),r=JSON.parse(t.toString());typeof r.host==`string`&&r.host&&(n=r.host)}catch{Y(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!D.tryAcquire(yt)){Y(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]=x,a=[...i,`auth`,`login`,`--json`,`--host`,n],o=!1,s=!1,c=``,l=Ne(r,a,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),u=setTimeout(()=>{l.kill(`SIGTERM`)},ht),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(`
73
+ `);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=>{Yg.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()),D.release(yt)}),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())),D.release(yt)})}async function Tt(e,t){if(!zh(e,t,Y))return;if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=(await d_(e)).toString().trim();if(t.length>0){let e=JSON.parse(t);typeof e.host==`string`&&e.host&&(n=e.host)}}catch{Y(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!D.tryAcquire(bt)){Y(t,429,{ok:!1,error:`An auth status operation is already in progress`});return}try{let[e,...r]=x,i=[...r,`auth`,`status`,`--json`,`--host`,n],a=(await new Promise((t,n)=>{let r=Ne(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(`
74
+ `).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?Y(t,200,{authenticated:!1}):Y(t,200,o)}catch(e){Y(t,500,{ok:!1,error:e instanceof Error?e.message:`auth status failed`})}finally{D.release(bt)}}async function Et(e,t){if(!zh(e,t,Y))return;if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=(await d_(e)).toString().trim();if(t.length>0){let e=JSON.parse(t);typeof e.host==`string`&&e.host&&(n=e.host)}}catch{Y(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!D.tryAcquire(xt)){Y(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]=x,a=[...i,`auth`,`repos`,`--json`,`--host`,n],o=!1,s=Ne(r,a,{stdio:[`ignore`,`pipe`,`pipe`],env:{...process.env}}),c=setTimeout(()=>{s.kill(`SIGTERM`)},ht);s.stdout.on(`data`,e=>{t.writableEnded||t.write(e)}),s.stderr.on(`data`,e=>{Yg.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()),D.release(xt)}),s.on(`error`,e=>{clearTimeout(c),o||(o=!0,t.writableEnded||(t.write(`${JSON.stringify({type:`error`,message:e.message})}\n`),t.end())),D.release(xt)})}async function Dt(e,t){if(!zh(e,t,Y))return;if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`;try{let t=await d_(e),r=JSON.parse(t.toString());typeof r.host==`string`&&r.host&&(n=r.host)}catch{Y(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!D.tryAcquire(St)){Y(t,429,{ok:!1,error:`An auth signout operation is already in progress`});return}try{let[e,...r]=x,i=[...r,`auth`,`signout`,`--host`,n];await new Promise((t,n)=>{let r=Ne(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)})}),Y(t,200,{ok:!0})}catch(e){Y(t,500,{ok:!1,error:e instanceof Error?e.message:`auth signout failed`})}finally{D.release(St)}}async function Ot(e,t){if(!zh(e,t,Y))return;if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n=`github.com`,r;try{let i=await d_(e),a=JSON.parse(i.toString());if(typeof a.pat!=`string`||!a.pat){Y(t,400,{ok:!1,error:`Missing or invalid pat`});return}r=a.pat,typeof a.host==`string`&&a.host&&(n=a.host)}catch{Y(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!D.tryAcquire(Ct)){Y(t,429,{ok:!1,error:`An auth pat operation is already in progress`});return}try{let[e,...i]=x,a=[...i,`auth`,`pat`,`--json`,`--host`,n],o=(await new Promise((t,n)=>{let i=Ne(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(`
75
+ `).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?Y(t,200,{ok:!0}):Y(t,200,s)}catch(e){Y(t,500,{ok:!1,error:e instanceof Error?e.message:`auth pat failed`})}finally{D.release(Ct)}}async function kt(e,t){if(zh(e,t,Y)){if(e.method!==`GET`){Y(t,405,{ok:!1,error:`Method not allowed`});return}if(!S){Y(t,400,{ok:!1,error:`No project directory configured`});return}try{Y(t,200,{ok:!0,identity:await kh(S)})}catch(e){Y(t,500,{ok:!1,error:e instanceof Error?e.message:`identity resolution failed`})}}}let At=`/api/local-op/auth/set-identity`;async function jt(e,t){if(!zh(e,t,Y))return;if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n,r;try{let i=await d_(e),a=JSON.parse(i.toString());if(typeof a.name!=`string`||!a.name.trim()){Y(t,400,{ok:!1,error:`Missing or invalid name`});return}if(typeof a.email!=`string`||!a.email.trim()){Y(t,400,{ok:!1,error:`Missing or invalid email`});return}n=a.name.trim(),r=a.email.trim()}catch{Y(t,400,{ok:!1,error:`Invalid JSON body`});return}if(!S){Y(t,400,{ok:!1,error:`No project directory configured`});return}if(!D.tryAcquire(At)){Y(t,429,{ok:!1,error:`A set-identity operation is already in progress`});return}try{Ah(S,n,r),b?.()?.refreshIdentity().catch(()=>{}),Y(t,200,{ok:!0})}catch(e){Y(t,500,{ok:!1,error:e instanceof Error?e.message:`set-identity failed`})}finally{D.release(At)}}async function Mt(e,t){if(!zh(e,t,Y))return;if(e.method!==`GET`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n=b?.();if(!n){Y(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}Y(t,200,n.getStatus())}async function Nt(e,t){if(!zh(e,t,Y))return;if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n=b?.();if(!n){Y(t,503,{ok:!1,error:`Sync engine not active`});return}let r=`sync`;try{let t=await d_(e);if(t.length>0){let e=JSON.parse(t.toString());(e.op===`push`||e.op===`pull`||e.op===`sync`)&&(r=e.op)}}catch{}Y(t,202,{ok:!0,op:r}),n.trigger(r)}async function Pt(e,t){if(!zh(e,t,Y))return;if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n=b?.();if(!n){Y(t,503,{ok:!1,error:`Sync engine not active`});return}let r;try{let n=await d_(e),i=JSON.parse(n.toString());if(typeof i.enabled!=`boolean`){Y(t,400,{ok:!1,error:`enabled must be a boolean`});return}r=i.enabled}catch{Y(t,400,{ok:!1,error:`Invalid JSON body`});return}await n.setEnabled(r),Y(t,200,{ok:!0,status:n.getStatus()})}async function Ft(e,t){if(!zh(e,t,Y))return;if(e.method!==`GET`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n=b?.();Y(t,200,{conflicts:n?n.getConflicts():[]})}async function It(e,t){if(!zh(e,t,Y))return;if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n=b?.();if(!n){Y(t,503,{ok:!1,error:`Sync engine not active`});return}let r;try{let t=await d_(e);r=JSON.parse(t.toString())}catch{Y(t,400,{ok:!1,error:`Invalid JSON body`});return}let{file:i,strategy:a,content:o}=r;if(!i||typeof i!=`string`){Y(t,400,{ok:!1,error:`Missing required field: file`});return}if(a!==`mine`&&a!==`theirs`&&a!==`content`){Y(t,400,{ok:!1,error:`Invalid strategy: must be 'mine', 'theirs', or 'content'`});return}try{await n.resolveConflict(i,a,o),Y(t,200,{ok:!0})}catch(e){Y(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function Lt(e,t){if(!zh(e,t,Y))return;if(e.method!==`GET`){Y(t,405,{ok:!1,error:`Method not allowed`});return}if(!S){Y(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){Y(t,400,{ok:!1,error:`Missing required query param: file`});return}if(n.includes(`..`)||n.startsWith(`/`)){Y(t,400,{ok:!1,error:`Invalid file path`});return}let r=Fe({baseDir:S,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)]);Y(t,200,{ok:!0,file:n,base:e,ours:r,theirs:a})}catch(e){Y(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}async function Rt(e,t){if(zh(e,t,Y))return lp(e,t,O.probeAll)}async function zt(e,t){if(!zh(e,t,Y))return;if(e.method!==`POST`){Y(t,405,{ok:!1,error:`Method not allowed`});return}let n=b?.();if(!n){Y(t,503,{ok:!1,error:`Sync engine not active`});return}try{await n.abortMerge(),Y(t,200,{ok:!0})}catch(e){Y(t,500,{ok:!1,error:e instanceof Error?e.message:String(e)})}}let Bt={"/api/document":je,"/api/documents":Me,"/api/backlinks":Pe,"/api/backlink-counts":Ie,"/api/forward-links":Le,"/api/link-graph":Re,"/api/dead-links":Ve,"/api/orphans":ze,"/api/hubs":Be,"/api/pages":ut,"/api/suggest-links":dt,"/api/page-headings":ot,"/api/create-page":at,"/api/rename":st,"/api/rename-path":ct,"/api/delete-path":lt,"/api/upload-image":ft,"/api/agent-write":ke,"/api/agent-write-md":Ae,"/api/agent-patch":He,"/api/agent-undo":Ue,"/api/save-version":Ke,"/api/history":qe,"/api/diff":Ye,"/api/rollback":Xe,"/api/metrics/reconciliation":Ze,"/api/metrics/parse-health":Qe,"/api/metrics/agent-presence":et,"/api/principal":$e,"/api/rescue":rt,"/api/workspace":tt,"/api/sync/status":Mt,"/api/sync/trigger":Nt,"/api/sync/set-enabled":Pt,"/api/sync/conflicts":Ft,"/api/sync/conflict-content":Lt,"/api/sync/resolve-conflict":It,"/api/sync/abort-merge":zt,"/api/local-op/clone":gt,"/api/local-op/open":vt,"/api/local-op/auth/login":wt,"/api/local-op/auth/status":Tt,"/api/local-op/auth/repos":Et,"/api/local-op/auth/signout":Dt,"/api/local-op/auth/pat":Ot,"/api/local-op/auth/identity":kt,"/api/local-op/auth/set-identity":jt,"/api/installed-agents":Rt};return s&&(Bt[`/api/test-reset`]=We,Bt[`/api/test-rescan-backlinks`]=Ge),{priority:100,async onRequest({request:e,response:t}){let n=e.url?.split(`?`)[0];if(!n)return;if(n.startsWith(`/api/`)){let n=e.headers.origin;if(n!==void 0&&!m_(n)){typeof t.setHeader==`function`&&t.setHeader(`Content-Type`,`application/json`),t.writeHead(403),t.end(JSON.stringify({ok:!1,error:`origin-not-allowed`}));return}if(typeof t.setHeader==`function`&&(n!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,n),t.setHeader(`Vary`,`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=Bt[n];if(r){await r(e,t);return}if(n.startsWith(`/api/rescue/`)){let r=decodeURIComponent(n.slice(12));r&&await it(e,t,r);return}if(n.startsWith(`/api/history/`)){let r=decodeURIComponent(n.slice(13));r&&await Je(e,t,r);return}}}}function g_(e){let t=e.scheduler??m,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 __=Math.floor,v_=(e,t)=>e<t?e:t,y_=(e,t)=>e>t?e:t;Number.isNaN,Number.isInteger,Number.isNaN,Number.parseInt;const b_=String.fromCharCode;String.fromCodePoint,b_(65535);const x_=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},S_=typeof TextEncoder<`u`?new TextEncoder:null,C_=S_?e=>S_.encode(e):x_;let w_=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});w_&&w_.decode(new Uint8Array).length===1&&(w_=null);const T_=(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},E_=(e,t)=>{for(;t>127;)T_(e,128|127&t),t=__(t/128);T_(e,127&t)},D_=new Uint8Array(3e4),O_=D_.length/3,k_=S_&&S_.encodeInto?(e,t)=>{if(t.length<O_){let n=S_.encodeInto(t,D_).written||0;E_(e,n);for(let t=0;t<n;t++)T_(e,D_[t])}else j_(e,C_(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;E_(e,r);for(let t=0;t<r;t++)T_(e,n.codePointAt(t))},A_=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=v_(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(y_(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},j_=(e,t)=>{E_(e,t.byteLength),A_(e,t)},M_=e=>Error(e);M_(`Unexpected end of array`),M_(`Integer out of Range`);let N_=function(e){return e[e.Token=0]=`Token`,e[e.PermissionDenied=1]=`PermissionDenied`,e[e.Authenticated=2]=`Authenticated`,e}({});const P_=(e,t)=>{E_(e,N_.PermissionDenied),k_(e,t)},F_=(e,t)=>{E_(e,N_.Authenticated),k_(e,t)},I_=e=>{E_(e,N_.Token)},L_={code:4205,reason:`Reset Connection`},R_={code:4401,reason:`Unauthorized`},z_={code:4403,reason:`Forbidden`},B_={code:4408,reason:`Connection Timeout`},V_=e=>Array.from(e.entries()).map(([e,t])=>({clientId:e,...t}));var H_=class extends Error{constructor(e){super(e??`Further hooks skipped`),this.name=`SkipFurtherHooksError`}};let U_=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 W_=Error(`request for lock canceled`);var G_=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())})},K_=class{constructor(e,t=W_){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=J_(this._queue,e=>t<=e.priority);a===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(a+1,0,i)})}runExclusive(e){return G_(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]=[]),q_(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 q_(e,t){let n=J_(e,e=>t.priority<=e.priority);e.splice(n+1,0,t)}function J_(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}var Y_=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())})},X_=class{constructor(e){this._semaphore=new K_(1,e)}acquire(){return Y_(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 Z_,Q_,$_,ev,tv=!0;typeof process<`u`&&({FORCE_COLOR:Z_,NODE_DISABLE_COLORS:Q_,NO_COLOR:$_,TERM:ev}=process.env||{},tv=process.stdout&&process.stdout.isTTY);const X={enabled:!Q_&&$_==null&&ev!==`dumb`&&(Z_!=null&&Z_!==`0`||tv),reset:Z(0,0),bold:Z(1,22),dim:Z(2,22),italic:Z(3,23),underline:Z(4,24),inverse:Z(7,27),hidden:Z(8,28),strikethrough:Z(9,29),black:Z(30,39),red:Z(31,39),green:Z(32,39),yellow:Z(33,39),blue:Z(34,39),magenta:Z(35,39),cyan:Z(36,39),white:Z(37,39),gray:Z(90,39),grey:Z(90,39),bgBlack:Z(40,49),bgRed:Z(41,49),bgGreen:Z(42,49),bgYellow:Z(43,49),bgBlue:Z(44,49),bgMagenta:Z(45,49),bgCyan:Z(46,49),bgWhite:Z(47,49)};function nv(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 rv(e,t){let n={has:e,keys:t};return n.reset=X.reset.bind(n),n.bold=X.bold.bind(n),n.dim=X.dim.bind(n),n.italic=X.italic.bind(n),n.underline=X.underline.bind(n),n.inverse=X.inverse.bind(n),n.hidden=X.hidden.bind(n),n.strikethrough=X.strikethrough.bind(n),n.black=X.black.bind(n),n.red=X.red.bind(n),n.green=X.green.bind(n),n.yellow=X.yellow.bind(n),n.blue=X.blue.bind(n),n.magenta=X.magenta.bind(n),n.cyan=X.cyan.bind(n),n.white=X.white.bind(n),n.gray=X.gray.bind(n),n.grey=X.grey.bind(n),n.bgBlack=X.bgBlack.bind(n),n.bgRed=X.bgRed.bind(n),n.bgGreen=X.bgGreen.bind(n),n.bgYellow=X.bgYellow.bind(n),n.bgBlue=X.bgBlue.bind(n),n.bgMagenta=X.bgMagenta.bind(n),n.bgCyan=X.bgCyan.bind(n),n.bgWhite=X.bgWhite.bind(n),n}function Z(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:X.enabled?nv(this.keys,t+``):t+``):t===void 0?rv([e],[n]):X.enabled?nv([n],t+``):t+``}}const iv=Math.floor,av=(e,t)=>e<t?e:t,ov=(e,t)=>e>t?e:t;Number.isNaN;const sv=2**53-1;Number.isInteger,Number.isNaN,Number.parseInt;const cv=()=>new Set,lv=Array.from;Array.isArray;const uv=String.fromCharCode;String.fromCodePoint,uv(65535);const dv=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},fv=typeof TextEncoder<`u`?new TextEncoder:null,pv=fv?e=>fv.encode(e):dv;let mv=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});mv&&mv.decode(new Uint8Array).length===1&&(mv=null);const hv=e=>Error(e);var gv=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const _v=()=>new gv,vv=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},yv=e=>{let t=new Uint8Array(vv(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},bv=(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},xv=(e,t)=>{for(;t>127;)bv(e,128|127&t),t=iv(t/128);bv(e,127&t)},Sv=new Uint8Array(3e4),Cv=Sv.length/3,wv=fv&&fv.encodeInto?(e,t)=>{if(t.length<Cv){let n=fv.encodeInto(t,Sv).written||0;xv(e,n);for(let t=0;t<n;t++)bv(e,Sv[t])}else Ev(e,pv(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;xv(e,r);for(let t=0;t<r;t++)bv(e,n.codePointAt(t))},Tv=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=av(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(ov(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},Ev=(e,t)=>{xv(e,t.byteLength),Tv(e,t)},Dv=hv(`Unexpected end of array`),Ov=hv(`Integer out of Range`);var kv=class{constructor(e){this.arr=e,this.pos=0}};const Av=e=>new kv(e),jv=e=>e.pos!==e.arr.length,Mv=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},Nv=e=>Mv(e,Fv(e)),Pv=e=>e.arr[e.pos++],Fv=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>sv)throw Ov}throw Dv},Iv=mv?e=>mv.decode(Nv(e)):e=>{let t=Fv(e);if(t===0)return``;{let n=String.fromCodePoint(Pv(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Pv(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 Lv=class{constructor(e){e instanceof Uint8Array||(e=new Uint8Array(e)),this.decoder=Av(e)}get encoder(){return this.encoderInternal||=_v(),this.encoderInternal}readVarUint8Array(){return Nv(this.decoder)}peekVarUint8Array(){let{pos:e}=this.decoder,t=Nv(this.decoder);return this.decoder.pos=e,t}readVarUint(){return Fv(this.decoder)}readVarString(){return Iv(this.decoder)}toUint8Array(){return yv(this.encoder)}writeVarUint(e){xv(this.encoder,e)}writeVarString(e){wv(this.encoder,e)}get length(){return vv(this.encoder)}};const Rv=Date.now,zv=()=>new Map,Bv=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r};var Vv=class{constructor(){this._observers=zv()}on(e,t){Bv(this._observers,e,cv).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 lv((this._observers.get(e)||zv()).values()).forEach(e=>e(...t))}destroy(){this._observers=zv()}};const Hv=Symbol(`Equality`),Uv=Object.keys,Wv=e=>Uv(e).length,Gv=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Kv=(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[Hv]!=null)return e[Hv](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)||!Kv(e.get(n),t.get(n)))return!1;break;case void 0:case Object:if(Wv(e)!==Wv(t))return!1;for(let n in e)if(!Gv(e,n)||!Kv(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(!Kv(e[n],t[n]))return!1;break;default:return!1}return!0},qv=3e4;var Jv=class extends Vv{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let e=Rv();this.getLocalState()!==null&&qv/2<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&qv<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&Yv(this,t,`timeout`)},iv(qv/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:Rv()});let a=[],o=[],s=[],c=[];e===null?c.push(t):i==null?e!=null&&a.push(t):(o.push(t),Kv(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 Yv=(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:Rv()})}r.push(i)}}r.length>0&&(e.emit(`change`,[{added:[],updated:[],removed:r},n]),e.emit(`update`,[{added:[],updated:[],removed:r},n]))},Xv=(e,t,n=e.states)=>{let r=t.length,i=_v();xv(i,r);for(let a=0;a<r;a++){let r=t[a],o=n.get(r)||null,s=e.meta.get(r).clock;xv(i,r),xv(i,s),wv(i,JSON.stringify(o))}return yv(i)},Zv=(e,t,n)=>{let r=Av(t),i=Rv(),a=[],o=[],s=[],c=[],l=Fv(r);for(let t=0;t<l;t++){let t=Fv(r),n=Fv(r),l=JSON.parse(Iv(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&&(Kv(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])},Qv=(e,t)=>{xv(e,0),Ev(e,Za(t))},$v=(e,t,n)=>{xv(e,1),Ev(e,Ga(t,n))},ey=(e,t,n)=>$v(t,n,Nv(e)),ty=(e,t,n,r)=>{try{Ha(t,Nv(e),n)}catch(e){r?.(e),console.error(`Caught error while handling a Yjs update`,e)}},ny=(e,t)=>{xv(e,2),Ev(e,t)},ry=ty;function iy(e){return typeof e==`object`&&!!e&&`source`in e&&(e.source===`connection`||e.source===`redis`||e.source===`local`)}function ay(e){if(!iy(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 oy=class{constructor(e){this.encoder=_v(),wv(this.encoder,e)}createSyncMessage(){return this.type=Q.Sync,xv(this.encoder,Q.Sync),this}createSyncReplyMessage(){return this.type=Q.SyncReply,xv(this.encoder,Q.SyncReply),this}createAwarenessUpdateMessage(e,t){this.type=Q.Awareness,this.category=`Update`;let n=Xv(e,t||Array.from(e.getStates().keys()));return xv(this.encoder,Q.Awareness),Ev(this.encoder,n),this}writeQueryAwareness(){return this.type=Q.QueryAwareness,this.category=`Update`,xv(this.encoder,Q.QueryAwareness),this}writeTokenSyncRequest(){return this.type=Q.Auth,this.category=`TokenSync`,xv(this.encoder,Q.Auth),I_(this.encoder),this}writeAuthenticated(e){return this.type=Q.Auth,this.category=`Authenticated`,xv(this.encoder,Q.Auth),F_(this.encoder,e?`readonly`:`read-write`),this}writePermissionDenied(e){return this.type=Q.Auth,this.category=`PermissionDenied`,xv(this.encoder,Q.Auth),P_(this.encoder,e),this}writeFirstSyncStepFor(e){return this.category=`SyncStep1`,Qv(this.encoder,e),this}writeUpdate(e){return this.category=`Update`,ny(this.encoder,e),this}writeStateless(e){return this.category=`Stateless`,xv(this.encoder,Q.Stateless),wv(this.encoder,e),this}writeBroadcastStateless(e){return this.category=`Stateless`,xv(this.encoder,Q.BroadcastStateless),wv(this.encoder,e),this}writeSyncStatus(e){return this.category=`SyncStatus`,xv(this.encoder,Q.SyncStatus),xv(this.encoder,e?1:0),this}writeCloseMessage(e){return this.type=Q.CLOSE,xv(this.encoder,Q.CLOSE),wv(this.encoder,e),this}toUint8Array(){return yv(this.encoder)}},sy=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:Zv(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:Iv(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()===N_.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(ey(e.decoder,e.encoder,t),r&&i)r(new oy(o).createSyncReplyMessage().writeFirstSyncStepFor(t).toUint8Array());else if(n){let e=new oy(o).createSyncMessage().writeFirstSyncStepFor(t);n.send(e.toUint8Array())}break;case 1:if(n?.readOnly){if(mo(lo(t),Nv(e.decoder))){let e=new oy(o).writeSyncStatus(!0);n.send(e.toUint8Array())}else{let e=new oy(o).writeSyncStatus(!1);n.send(e.toUint8Array())}break}ty(e.decoder,t,n?{source:`connection`,connection:n}:this.defaultTransactionOrigin??{source:`local`}),n&&n.send(new oy(o).writeSyncStatus(!0).toUint8Array());break;case 2:if(n?.readOnly){n.send(new oy(o).writeSyncStatus(!1).toUint8Array());break}ry(e.decoder,t,n?{source:`connection`,connection:n}:this.defaultTransactionOrigin??{source:`local`}),n&&n.send(new oy(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 oy(t?.messageAddress??e.name).createAwarenessUpdateMessage(e.awareness);n&&n(r.toUint8Array())}},cy=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===U_.Closing||this.webSocket.readyState===U_.Closed){this.close();return}try{this.webSocket.send(e)}catch{this.close()}}sendStateless(e){let t=new oy(this.messageAddress).writeStateless(e);this.send(t.toUint8Array())}requestToken(){let e=new oy(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 oy(this.messageAddress);t.writeCloseMessage(e?.reason??`Server closed the connection`),this.send(t.toUint8Array())}}sendCurrentAwareness(){if(!this.document.hasAwarenessStates())return;let e=new oy(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 Lv(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 sy(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:L_.code,reason:`reason`in e?e.reason:L_.reason})}this.messageQueue.shift()}}},ly=class extends Ea{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 X_,this.lastChangeTime=0,this.name=e,this.awareness=new Jv(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=>{Ha(this,Ga(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&&Yv(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 Zv(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 oy(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 oy(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}},uy=`4.0.0-rc.1`;function dy(e){let t=e?.url;return t?t.includes(`://`)?new URL(t).searchParams:new URLSearchParams(t.split(`?`)[1]||``):new URLSearchParams}var fy=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=Oe.randomUUID(),this.lastMessageReceivedAt=Date.now(),this.check=()=>{Date.now()-this.lastMessageReceivedAt>this.timeout&&this.close(B_)},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={...R_,...e};a.close({code:t.code,reason:t.reason})}}),this.documentConnections[e]=a,this.websocket.readyState===U_.Closing||this.websocket.readyState===U_.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 Lv(e);if(Iv(r.decoder),!(Fv(r.decoder)===Q.Auth&&!this.documentConnectionsEstablished.has(t))){this.incomingMessageQueue[t].push(e);return}this.documentConnectionsEstablished.add(t),Fv(r.decoder);let i=Iv(r.decoder),a=null;jv(r.decoder)&&(a=Iv(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 oy(c).writeAuthenticated(e.connectionConfig.readOnly);this.websocket.send(r.toUint8Array()),await this.setUpNewConnection(t,n,s)}catch(e){let n=e||z_,r=new oy(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(L_.code,L_.reason)}},this.handleMessage=e=>{this.lastMessageReceivedAt=Date.now();try{let t=Iv(new Lv(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:dy(this.request),socketId:this.socketId,context:{...this.defaultContext},providerVersion:null}}this.handleQueueingMessage(e,t,r)}catch(e){console.error(e),this.websocket.close(R_.code,R_.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 cy(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:dy(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:dy(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}},py=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 De}),await this.instance.unloadDocument(this.document)),null)}};const my=()=>{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()}}},hy={name:null,timeout:6e4,debounce:2e3,maxDebounce:1e4,quiet:!1,yDocOptions:{gc:!0,gcFilter:()=>!0},unloadImmediately:!0};var gy=class{constructor(e){this.configuration={...hy,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=my(),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:uy,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(L_)})})}handleConnection(e,t,n={}){let r=new fy(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=iy(t)&&t.source===`connection`?t.connection:void 0,i=r?.request,a=iy(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:dy(i),socketId:r?.socketId??``,update:n,transactionOrigin:t,connection:r,context:a};if(this.hooks(`onChange`,o),ay(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=dy(t),s=i??{},c=await this.hooks(`onCreateDocument`,{documentName:e,requestHeaders:a,requestParameters:o,connectionConfig:r,context:s,socketId:n,instance:this}),l=new ly(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 Ea?Ha(l,Ga(e)):e instanceof Uint8Array&&Ha(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:iy(n)&&n.source===`connection`?n.connection:void 0,awareness:l.awareness,states:V_(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 H_){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 py(await this.createDocument(e,new Request(`http://localhost`),Oe.randomUUID(),{isAuthenticated:!0,readOnly:!1},t),this,t)}},_y=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),vy=se(import.meta.url),yy=_y(((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:()=>{}}})),by=_y(((e,t)=>{let{EMPTY_BUFFER:n}=yy(),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=vy(`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{}})),xy=_y(((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])}}}})),Sy=_y(((e,t)=>{let n=vy(`zlib`),r=by(),i=xy(),{kStatusCode:a}=yy(),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)}})),Cy=_y(((e,t)=>{let{isUtf8:n}=vy(`buffer`),{hasBlob:r}=yy(),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=vy(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})),wy=_y(((e,t)=>{let{Writable:n}=vy(`stream`),r=Sy(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=yy(),{concat:c,toArrayBuffer:l,unmask:u}=by(),{isValidStatusCode:d,isValidUTF8:f}=Cy(),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}}})),Ty=_y(((e,t)=>{let{Duplex:n}=vy(`stream`),{randomFillSync:r}=vy(`crypto`),i=Sy(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=yy(),{isBlob:c,isValidStatusCode:l}=Cy(),{mask:u,toBuffer:d}=by(),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)}})),Ey=_y(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=yy(),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)}})),Dy=_y(((e,t)=>{let{tokenChars:n}=Cy();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}})),Oy=_y(((e,t)=>{let n=vy(`events`),r=vy(`https`),i=vy(`http`),a=vy(`net`),o=vy(`tls`),{randomBytes:s,createHash:c}=vy(`crypto`),{Duplex:l,Readable:u}=vy(`stream`),{URL:d}=vy(`url`),f=Sy(),p=wy(),m=Ty(),{isBlob:h}=Cy(),{BINARY_TYPES:g,CLOSE_TIMEOUT:_,EMPTY_BUFFER:v,GUID:y,kForOnEventAttribute:b,kListener:x,kStatusCode:S,kWebSocket:C,NOOP:w}=yy(),{EventTarget:{addEventListener:T,removeEventListener:E}}=Ey(),{format:D,parse:O}=Dy(),{toBuffer:k}=by(),A=Symbol(`kAborted`),j=[8,13],M=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],N=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var P=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]),ee(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`,se),i.on(`ping`,ce),i.on(`pong`,R),a.onerror=ue,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,z),t.on(`data`,fe),t.on(`end`,pe),t.on(`error`,me),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(P,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(P.prototype,`CONNECTING`,{enumerable:!0,value:M.indexOf(`CONNECTING`)}),Object.defineProperty(P,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(P.prototype,`OPEN`,{enumerable:!0,value:M.indexOf(`OPEN`)}),Object.defineProperty(P,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(P.prototype,`CLOSING`,{enumerable:!0,value:M.indexOf(`CLOSING`)}),Object.defineProperty(P,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),Object.defineProperty(P.prototype,`CLOSED`,{enumerable:!0,value:M.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(P.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(P.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})}})}),P.prototype.addEventListener=T,P.prototype.removeEventListener=E,t.exports=P;function ee(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;te(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:ne),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`||!N.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,te(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{te(e,SyntaxError(`Invalid URL: ${i}`));return}ee(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!==P.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 te(e,t){e._readyState=P.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function ne(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=P.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(te,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`,fe),process.nextTick(le,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`,fe),process.nextTick(le,t._socket),t.close(e[S])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function L(){this[C].emitClose()}function se(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 R(e){this[C].emit(`pong`,e)}function le(e){e.resume()}function ue(e){let t=this[C];t.readyState!==P.CLOSED&&(t.readyState===P.OPEN&&(t._readyState=P.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 z(){let e=this[C];if(this.removeListener(`close`,z),this.removeListener(`data`,fe),this.removeListener(`end`,pe),e._readyState=P.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`,L),e._receiver.on(`finish`,L))}function fe(e){this[C]._receiver.write(e)||this.pause()}function pe(){let e=this[C];e._readyState=P.CLOSING,e._receiver.end(),this.end()}function me(){let e=this[C];this.removeListener(`error`,me),this.on(`error`,w),e&&(e._readyState=P.CLOSING,this.destroy())}})),ky=_y(((e,t)=>{Oy();let{Duplex:n}=vy(`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})),Ay=_y(((e,t)=>{let{tokenChars:n}=Cy();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}})),jy=_y(((e,t)=>{let n=vy(`events`),r=vy(`http`),{Duplex:i}=vy(`stream`),{createHash:a}=vy(`crypto`),o=Dy(),s=Sy(),c=Ay(),l=Oy(),{CLOSE_TIMEOUT:u,GUID:d,kWebSocket:f}=yy(),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
75
76
  `).join(`\r
76
77
  `)),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
77
78
  `)+`\r
78
79
  \r
79
- `+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)}}));yy(),my(),hy(),vy(),xy();var Sy=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 Cy=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 wy(e){let{projectDir:t,contentDir:n,includePatterns:r,excludePatterns:i}=e,o=Ve(r,{dot:!0}),s=(0,Sy.default)();s.add(`.git`);let c=V(t,`.gitignore`),l=[];if(R(c))try{let e=Ey(z(c,`utf-8`));l.push(...e),s.add(e)}catch(e){console.warn(`[content-filter] Failed to read .gitignore at ${c}:`,e)}let u=Te(t,n),d=u.startsWith(`..`);if(i.length>0&&(u?s.add(i.map(e=>`${u}/${e}`)):s.add(i)),u){let e=V(n,`.gitignore`);if(R(e))try{let t=Ey(z(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)}}Dy(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 Ty(n,``,o,m,p),{isExcluded(e){if(J(kp(e))||!d&&m(e))return!0;if(o(e))return!1;let t=Ce(e).slice(1).toLowerCase();if(a.has(t)){let t=Se(e),n=t===`.`?``:t;if((p.get(n)??0)>0)return!1}return!0},isDirExcluded(e){let t=e.split(`/`)[0];if(Cy.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 Ty(e,t,n,r,i){let a;try{a=fe(e,{withFileTypes:!0})}catch{return}for(let o of a){let a=t?`${t}/${o.name}`:o.name;if(o.isDirectory()){if(Cy.has(o.name)||r(a)||r(`${a}/`))continue;Ty(V(e,o.name),a,n,r,i)}else if(o.isFile()&&Op(o.name)&&n(a)&&!r(a)){let e=t===``?``:t;i.set(e,(i.get(e)??0)+1)}}}function Ey(e){return e.split(`
80
- `).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`))}function Dy(e,t,n){let r;try{r=fe(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory ${e}:`,t);return}for(let i of r){if(!i.isDirectory()||Cy.has(i.name))continue;let r=V(e,i.name),a=Te(t,r);if(a.startsWith(`..`)||n.ignores(a)||n.ignores(`${a}/`))continue;let o=V(r,`.gitignore`);if(R(o))try{let e=Ey(z(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)}Dy(r,t,n)}}const Oy={source:`local`,skipStoreHooks:!0,context:{origin:`file-watcher`,paired:!0}};function ky(e,t,n){if(J(t))return;let r=e.documents.get(t);if(!r)return;let{frontmatter:i,body:a}=l(n),o=wl.parseWithFallback(a),s=Tl.nodeFromJSON(o),c=r.getXmlFragment(`default`);r.transact(()=>{yl(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&&T(e,t,n)},Oy),Uf(t,bm.id,bm.name,bm.id,Hl(t)),Vm(t,n)}const Ay=new Set([`HEAD`,`MERGE_HEAD`,`ORIG_HEAD`,`index.lock`]);function jy(e){let t=H(e,`.git`);try{let n=ge(t);if(n.isDirectory())return t;if(n.isFile()){let n=z(t,`utf-8`).trim().match(/^gitdir:\s*(.+)$/);if(n)return H(e,n[1])}}catch{}return null}function My(e){try{let t=z(H(e,`HEAD`),`utf-8`).trim();if(t.startsWith(`ref: `)){let n=H(e,t.slice(5));try{return z(n,`utf-8`).trim()}catch{try{let n=z(H(e,`packed-refs`),`utf-8`),r=t.slice(5),i=n.split(`
81
- `).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 Ny(e){try{let t=z(H(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 Py(e,t,n){let r=jy(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=My(i),r=c!==t,u=Ny(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=My(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(Ay.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=My(i),l=Ny(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 Fy(e){return typeof e!=`object`||!e?!1:e.source===`local`}function Iy(e){let t=e.getXmlFragment(`default`),n=wl.serialize(Sl(t,Tl).toJSON()),r=e.getMap(`metadata`).get(`frontmatter`);return M(typeof r==`string`?r:``,n)}function Ly(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,Iy(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}){J(e)||Fy(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()}}}async function Ry(e){try{let t=Fe({baseDir:e,timeout:{block:3e3}});return{name:(await t.raw(`config`,`--get`,`user.name`)).trim()||null,email:(await t.raw(`config`,`--get`,`user.email`)).trim()||null}}catch{return{name:null,email:null}}}async function zy(e){let t=H(e,c),n=H(t,`principal.json`),{name:r,email:i}=await Ry(e);if(R(n)){let e;try{e=JSON.parse(z(n,`utf-8`))}catch{e={}}let t=typeof e.id==`string`&&e.id.startsWith(`principal-`)?e.id:`principal-${Ae()}`,a=typeof e.created_at==`string`?e.created_at:new Date().toISOString(),o=t.slice(10,18),s={id:t,display_name:r?xh(r):typeof e.display_name==`string`?e.display_name:`Local User`,display_email:i?xh(i):typeof e.display_email==`string`?e.display_email:`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:a};return B(n,JSON.stringify(s,null,2),`utf-8`),s}ue(t,{recursive:!0});let a=`principal-${Ae()}`,o=a.slice(10,18),s={id:a,display_name:r?xh(r):`Local User`,display_email:i?xh(i):`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:new Date().toISOString()};return B(n,JSON.stringify(s,null,2),`utf-8`),s}const By={source:`local`,skipStoreHooks:!0,context:{origin:`observer-sync`}},Vy=e=>typeof e!=`object`||!e?!1:e.context?.paired===!0;function Hy(e=process.env){return e.NODE_ENV===`test`||e.OK_RETHROW_BRIDGE_LOSS===`1`}function Uy(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()})),An();let i=e.shadow?.();if(!i||!e.docName)return;let a=e.getBranch?.()??`main`,o=e.contentRoot??``;queueMicrotask(()=>{Dm(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=>{jn(),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(`
80
+ `+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)}}));ky(),wy(),Ty(),Oy(),jy();var My=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 Ny=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 Py(e){let{projectDir:t,contentDir:n,includePatterns:r,excludePatterns:i}=e,o=Ve(r,{dot:!0}),s=(0,My.default)();s.add(`.git`);let c=V(t,`.gitignore`),l=[];if(R(c))try{let e=Iy(z(c,`utf-8`));l.push(...e),s.add(e)}catch(e){console.warn(`[content-filter] Failed to read .gitignore at ${c}:`,e)}let u=Te(t,n),d=u.startsWith(`..`);if(i.length>0&&(u?s.add(i.map(e=>`${u}/${e}`)):s.add(i)),u){let e=V(n,`.gitignore`);if(R(e))try{let t=Iy(z(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)}}Ly(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 Fy(n,``,o,m,p),{isExcluded(e){if(J(zp(e))||!d&&m(e))return!0;if(o(e))return!1;let t=Ce(e).slice(1).toLowerCase();if(a.has(t)){let t=Se(e),n=t===`.`?``:t;if((p.get(n)??0)>0)return!1}return!0},isDirExcluded(e){let t=e.split(`/`)[0];if(Ny.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 Fy(e,t,n,r,i){let a;try{a=fe(e,{withFileTypes:!0})}catch{return}for(let o of a){let a=t?`${t}/${o.name}`:o.name;if(o.isDirectory()){if(Ny.has(o.name)||r(a)||r(`${a}/`))continue;Fy(V(e,o.name),a,n,r,i)}else if(o.isFile()&&Rp(o.name)&&n(a)&&!r(a)){let e=t===``?``:t;i.set(e,(i.get(e)??0)+1)}}}function Iy(e){return e.split(`
81
+ `).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`))}function Ly(e,t,n){let r;try{r=fe(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory ${e}:`,t);return}for(let i of r){if(!i.isDirectory()||Ny.has(i.name))continue;let r=V(e,i.name),a=Te(t,r);if(a.startsWith(`..`)||n.ignores(a)||n.ignores(`${a}/`))continue;let o=V(r,`.gitignore`);if(R(o))try{let e=Iy(z(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)}Ly(r,t,n)}}const Ry={source:`local`,skipStoreHooks:!0,context:{origin:`file-watcher`,paired:!0}};function zy(e,t,n){if(J(t))return;let r=e.documents.get(t);if(!r)return;let{frontmatter:i,body:a}=l(n),o=Dl.parseWithFallback(a),s=Ol.nodeFromJSON(o),c=r.getXmlFragment(`default`);r.transact(()=>{Sl(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&&T(e,t,n)},Ry),$f(t,Am.id,Am.name,Am.id,Xl(t)),Zm(t,n)}const By=new Set([`HEAD`,`MERGE_HEAD`,`ORIG_HEAD`,`index.lock`]);function Vy(e){let t=H(e,`.git`);try{let n=ge(t);if(n.isDirectory())return t;if(n.isFile()){let n=z(t,`utf-8`).trim().match(/^gitdir:\s*(.+)$/);if(n)return H(e,n[1])}}catch{}return null}function Hy(e){try{let t=z(H(e,`HEAD`),`utf-8`).trim();if(t.startsWith(`ref: `)){let n=H(e,t.slice(5));try{return z(n,`utf-8`).trim()}catch{try{let n=z(H(e,`packed-refs`),`utf-8`),r=t.slice(5),i=n.split(`
82
+ `).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 Uy(e){try{let t=z(H(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 Wy(e,t,n){let r=Vy(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=Hy(i),r=c!==t,u=Uy(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=Hy(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(By.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=Hy(i),l=Uy(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 Gy(e){return typeof e!=`object`||!e?!1:e.source===`local`}function Ky(e){let t=e.getXmlFragment(`default`),n=Dl.serialize(Tl(t,Ol).toJSON()),r=e.getMap(`metadata`).get(`frontmatter`);return M(typeof r==`string`?r:``,n)}function qy(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,Ky(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}){J(e)||Gy(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()}}}async function Jy(e){try{let t=Fe({baseDir:e,timeout:{block:3e3}});return{name:(await t.raw(`config`,`--get`,`user.name`)).trim()||null,email:(await t.raw(`config`,`--get`,`user.email`)).trim()||null}}catch{return{name:null,email:null}}}async function Yy(e){let t=H(e,c),n=H(t,`principal.json`),{name:r,email:i}=await Jy(e);if(R(n)){let e;try{e=JSON.parse(z(n,`utf-8`))}catch{e={}}let t=typeof e.id==`string`&&e.id.startsWith(`principal-`)?e.id:`principal-${Ae()}`,a=typeof e.created_at==`string`?e.created_at:new Date().toISOString(),o=t.slice(10,18),s={id:t,display_name:r?jh(r):typeof e.display_name==`string`?e.display_name:`Local User`,display_email:i?jh(i):typeof e.display_email==`string`?e.display_email:`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:a};return B(n,JSON.stringify(s,null,2),`utf-8`),s}ue(t,{recursive:!0});let a=`principal-${Ae()}`,o=a.slice(10,18),s={id:a,display_name:r?jh(r):`Local User`,display_email:i?jh(i):`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:new Date().toISOString()};return B(n,JSON.stringify(s,null,2),`utf-8`),s}const Xy={source:`local`,skipStoreHooks:!0,context:{origin:`observer-sync`}},Zy=e=>typeof e!=`object`||!e?!1:e.context?.paired===!0;function Qy(e=process.env){return e.NODE_ENV===`test`||e.OK_RETHROW_BRIDGE_LOSS===`1`}function $y(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()})),An();let i=e.shadow?.();if(!i||!e.docName)return;let a=e.getBranch?.()??`main`,o=e.contentRoot??``;queueMicrotask(()=>{Lm(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=>{Pn(),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(`
82
83
  `).slice(0,4).join(`
83
- `)})})})},c=``,u=!1,d=!1;try{let e=Sl(n,a).toJSON(),r=i.serialize(e);c=M(g(t),r)}catch(e){kn(`a`),console.warn(`[Server Observer A] Baseline init failed — starting from empty snapshot:`,e instanceof Error?e.message:String(e)),c=``}let f=()=>{try{let e=Sl(n,a).toJSON(),s=i.serialize(e),l=M(g(t),s);if(c===l)return;let u=r.toString();if(x(u)===x(l)){c=l;return}let d=c;t.transact(()=>{if(u===c)S(r,u,l);else try{T(r,u,h(c,l,u))}catch(e){if(!(e instanceof k)||(o(e,d),Hy()))throw e;T(r,u,e.info.result)}},By),Dn(`a`),c=r.toString()}catch(e){kn(`a`),console.error(`[Server Observer A] Failed to sync tree→text:`,e);try{c=r.toString()}catch(e){console.warn(`[Server Observer A] Baseline recovery also failed:`,e)}}},p=(e,r)=>{if(r.origin!==By){if(Vy(r.origin)){try{let e=Sl(n,a).toJSON(),r=i.serialize(e);c=M(g(t),r)}catch(e){kn(`a`),console.warn(`[Server Observer A] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),u=!0}return}u=!0}};if(n.length>0&&r.length===0)try{let e=Sl(n,a).toJSON(),o=i.serialize(e),s=M(g(t),o);t.transact(()=>{r.insert(0,s)},By),c=s}catch(e){kn(`a`),console.error(`[Server Observer A] Failed initial sync:`,e),c=``}let m=()=>{try{let a=r.toString(),{frontmatter:o,body:u}=l(a);if(x(c)===x(a)){let e=t.getMap(`metadata`);(e.get(`frontmatter`)??``)!==o&&t.transact(()=>{e.set(`frontmatter`,o)},By);return}let d;try{d=i.parse(u)}catch(e){if(e instanceof SyntaxError||e instanceof s||e instanceof RangeError&&e.message.includes(`Invalid content for node`)){console.debug(`[Server Observer B] Parse skipped (partial/invalid markdown):`,e),c=M(o,u);return}throw e}let f=e.schema.nodeFromJSON(d);t.transact(()=>{yl(t,n,f,{mapping:new Map,isOMark:new Map}),t.getMap(`metadata`).set(`frontmatter`,o)},By),Dn(`b`);try{let e=i.serialize(d);if(e===u)c=M(o,u);else{let n=M(o,e),i=r.toString();i!==n&&t.transact(()=>{T(r,i,n)},By),c=n}}catch(e){console.warn(`[Server Observer B] Post-sync re-serialization failed — using input body as baseline:`,e),c=M(o,u)}}catch(e){kn(`b`),console.error(`[Server Observer B] Failed to sync text→tree:`,e);try{let e=Sl(n,a).toJSON(),r=i.serialize(e);c=M(g(t),r)}catch(e){console.warn(`[Server Observer B] Baseline recovery also failed:`,e)}}},_=(e,r)=>{if(r.origin!==By){if(Vy(r.origin)){try{let e=Sl(n,a).toJSON(),r=i.serialize(e);c=M(g(t),r)}catch(e){kn(`b`),console.warn(`[Server Observer B] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),d=!0}return}d=!0}},v=(t,n)=>{if(!u&&!d){e.onDispatch?.(`none`);return}if(n.every(e=>e.origin===By)){u=!1,d=!1,e.onDispatch?.(`none`);return}u&&(u=!1,e.onDispatch?.(`a`),f()),d&&(d=!1,e.onDispatch?.(`b`),m())};return n.observeDeep(p),r.observe(_),t.on(`afterAllTransactions`,v),()=>{t.off(`afterAllTransactions`,v),n.unobserveDeep(p),r.unobserve(_)}}function Wy(e){let t=new Map,n=new Map;return{async afterLoadDocument({documentName:r,document:i}){if(J(r)||t.has(r))return;let a=i,o=a.getXmlFragment(`default`),s=a.getText(`source`),c=()=>{try{let n=Uy({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),kn(`a`),kn(`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 Gy=ln(`conflict-storage`);var Ky=class{storePath;projectDir;branch;conflicts=[];constructor(e,t,n=`main`){this.storePath=V(e,`.open-knowledge`,`conflicts.json`),this.projectDir=t,this.branch=n,this.load()}load(){if(!R(this.storePath)){this.conflicts=[];return}try{let e=z(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){Gy.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){Gy.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=Se(this.storePath);R(e)||ue(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};B(this.storePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){Gy.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=H(this.projectDir),r=H(t,e);if(r!==t&&!r.startsWith(`${t}/`))throw Error(`[conflicts] file path escapes project directory: ${e}`);B(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`]),Gy.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(`
84
- `).map(e=>e.trim()).filter(Boolean);for(let t of e)this.addConflict({file:t,detectedAt:n});r=e.length>0}catch(e){Gy.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}),Gy.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`)}}};function qy(e){return e.git?.toString()??e.message??``}function Jy(e,t){return t.some(t=>t.test(e))}const Yy=[/\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],Xy=[/insufficient scopes/i,/missing.*scope/i,/required scope/i],Zy=[/non-fast-forward/i,/rejected.*non-fast-forward/i,/would overwrite.*commits/i,/\[rejected\]/,/fetch first/i,/updates were rejected/i],Qy=[/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],$y=[/\bmerge conflict\b/i,/automatic merge failed/i,/CONFLICT \(/,/\bconflict\b.*\bmerge\b/i,/(?:^|\n)CONFLICTS:\s/i],eb=[/lfs.*quota/i,/exceeded.*bandwidth/i,/lfs storage/i],tb=[/file.*too large/i,/exceeded.*file size/i,/push file size limit/i],nb=[/pre-receive hook/i,/remote:.*rejected/i,/hook declined/i],rb=[/secret.*detected/i,/push.*secret/i,/secret scanning/i,/leaking.*credentials/i,/token.*detected/i],ib=[/\.git\/index\.lock/i,/another git process/i,/unable to create.*\.lock/i],ab=[/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],ob=[/no space left on device/i,/disk quota exceeded/i,/ENOSPC/],sb=[/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],cb=[/\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],lb=[/\bHTTP[\s/]*429\b/i,/\bstatus:?\s*429\b/i,/\berror\s*429\b/i,/rate.?limit/i,/too many requests/i];function ub(e){let t=e instanceof Error?e:Error(String(e)),n=qy(t),r=`${t.message}\n${n}`.toLowerCase();return Jy(r,ib)?{class:`local`,subclass:`index-lock`,retryable:!0,message:`Git index locked by another process`,rawStderr:n}:Jy(r,ab)?{class:`local`,subclass:`dirty-tree`,retryable:!0,message:`Working tree has uncommitted changes`,rawStderr:n}:Jy(r,ob)?{class:`local`,subclass:`disk-full`,retryable:!0,message:`Disk full or quota exceeded`,rawStderr:n}:Jy(r,Xy)?{class:`auth`,subclass:`scope-mismatch`,retryable:!1,message:`GitHub token missing required scopes`,rawStderr:n}:Jy(r,Yy)?/\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)?Jy(r,Qy)?{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}:Jy(r,Qy)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:Jy(r,Zy)?{class:`semantic`,subclass:`non-fast-forward`,retryable:!1,message:`Push rejected — remote has diverged (non-fast-forward)`,rawStderr:n}:Jy(r,$y)?{class:`semantic`,subclass:`merge-conflict`,retryable:!1,message:`Merge conflict — manual resolution required`,rawStderr:n}:Jy(r,eb)?{class:`structural`,subclass:`lfs-quota`,retryable:!1,message:`Git LFS quota exceeded`,rawStderr:n}:Jy(r,tb)?{class:`structural`,subclass:`large-file`,retryable:!1,message:`File exceeds size limit`,rawStderr:n}:Jy(r,rb)?{class:`structural`,subclass:`secret-detected`,retryable:!1,message:`Push blocked — secret or credential detected in content`,rawStderr:n}:Jy(r,nb)?{class:`structural`,subclass:`pre-receive-hook`,retryable:!1,message:`Push rejected by server pre-receive hook`,rawStderr:n}:Jy(r,lb)?{class:`network`,subclass:`429`,retryable:!0,message:`Rate limited — too many requests`,rawStderr:n}:Jy(r,cb)?{class:`network`,subclass:`5xx`,retryable:!0,message:`Server error (5xx)`,rawStderr:n}:Jy(r,sb)?/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 db(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 $=ln(`sync-engine`),fb=/^[0-9a-f]{40}$/i;function pb(e){let t=e*1e3,n=t*.15*(2*Math.random()-1);return Math.round(t+n)}function mb(e){try{let t=V(e,`.git`,`HEAD`);if(!R(t))return!1;let n=z(t,`utf-8`).trim(),r=/^ref:\s+(refs\/.+)$/.exec(n);if(!r)return!1;let i=r[1];if(R(V(e,`.git`,i)))return!1;let a=V(e,`.git`,`packed-refs`);if(R(a)){let e=z(a,`utf-8`);if(RegExp(`^[0-9a-f]+\\s+${i}$`,`m`).test(e))return!1}return!0}catch{return!1}}function hb(e){return e>=8?3600*1e3:e>=5?900*1e3:e>=3?300*1e3:0}var gb=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=H(this.contentDir,`.open-knowledge`,`sync-state.json`),this.conflictStore=new Ky(this.contentDir,this.projectDir,this.currentBranch)}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=L(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=R(V(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 L(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim(),t=new Set(e?e.split(`
85
- `).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 L(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=db(this.lastFetchUtc,this.pullIntervalSeconds),r=db(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 L(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 yh(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??pb(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=hb(e);return t>0?t:pb(this.pullIntervalSeconds)}async runPullCycle(){if(!this.pullInFlight&&!(this.state===`dormant`||this.state===`disabled`)){if(this.state===`conflict`){this.schedulePull();return}if(mb(this.projectDir)){this.schedulePull();return}this.pullInFlight=!0;try{await this.doPullCycle()}finally{this.pullInFlight=!1,this.schedulePull()}}}async doPullCycle(){let e=L(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(ub(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=ub(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=ub(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(mb(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=V(xe(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),r=null;this.transitionTo(`pushing`);try{await oe(async()=>{let e=L(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:n});if(mb(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(ub(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(`
84
+ `)})})})},c=``,u=!1,d=!1;try{let e=Tl(n,a).toJSON(),r=i.serialize(e);c=M(g(t),r)}catch(e){kn(`a`),console.warn(`[Server Observer A] Baseline init failed — starting from empty snapshot:`,e instanceof Error?e.message:String(e)),c=``}let f=()=>{try{let e=Tl(n,a).toJSON(),s=i.serialize(e),l=M(g(t),s);if(c===l)return;let u=r.toString();if(x(u)===x(l)){c=l;return}let d=c;t.transact(()=>{if(u===c)S(r,u,l);else try{T(r,u,h(c,l,u))}catch(e){if(!(e instanceof k)||(o(e,d),Qy()))throw e;T(r,u,e.info.result)}},Xy),Dn(`a`),c=r.toString()}catch(e){kn(`a`),console.error(`[Server Observer A] Failed to sync tree→text:`,e);try{c=r.toString()}catch(e){console.warn(`[Server Observer A] Baseline recovery also failed:`,e)}}},p=(e,r)=>{if(r.origin!==Xy){if(Zy(r.origin)){try{let e=Tl(n,a).toJSON(),r=i.serialize(e);c=M(g(t),r)}catch(e){kn(`a`),console.warn(`[Server Observer A] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),u=!0}return}u=!0}};if(n.length>0&&r.length===0)try{let e=Tl(n,a).toJSON(),o=i.serialize(e),s=M(g(t),o);t.transact(()=>{r.insert(0,s)},Xy),c=s}catch(e){kn(`a`),console.error(`[Server Observer A] Failed initial sync:`,e),c=``}let m=()=>{try{let a=r.toString(),{frontmatter:o,body:u}=l(a);if(x(c)===x(a)){let e=t.getMap(`metadata`);(e.get(`frontmatter`)??``)!==o&&t.transact(()=>{e.set(`frontmatter`,o)},Xy);return}let d;try{d=i.parse(u)}catch(e){if(e instanceof SyntaxError||e instanceof s||e instanceof RangeError&&e.message.includes(`Invalid content for node`)){console.debug(`[Server Observer B] Parse skipped (partial/invalid markdown):`,e),c=M(o,u);return}throw e}let f=e.schema.nodeFromJSON(d);t.transact(()=>{Sl(t,n,f,{mapping:new Map,isOMark:new Map}),t.getMap(`metadata`).set(`frontmatter`,o)},Xy),Dn(`b`);try{let e=i.serialize(d);if(e===u)c=M(o,u);else{let n=M(o,e),i=r.toString();i!==n&&t.transact(()=>{T(r,i,n)},Xy),c=n}}catch(e){console.warn(`[Server Observer B] Post-sync re-serialization failed — using input body as baseline:`,e),c=M(o,u)}}catch(e){kn(`b`),console.error(`[Server Observer B] Failed to sync text→tree:`,e);try{let e=Tl(n,a).toJSON(),r=i.serialize(e);c=M(g(t),r)}catch(e){console.warn(`[Server Observer B] Baseline recovery also failed:`,e)}}},_=(e,r)=>{if(r.origin!==Xy){if(Zy(r.origin)){try{let e=Tl(n,a).toJSON(),r=i.serialize(e);c=M(g(t),r)}catch(e){kn(`b`),console.warn(`[Server Observer B] Paired-write baseline refresh failed — falling through to settlement:`,e instanceof Error?e.message:String(e)),d=!0}return}d=!0}},v=(t,n)=>{if(!u&&!d){e.onDispatch?.(`none`);return}if(n.every(e=>e.origin===Xy)){u=!1,d=!1,e.onDispatch?.(`none`);return}u&&(u=!1,e.onDispatch?.(`a`),f()),d&&(d=!1,e.onDispatch?.(`b`),m())};return n.observeDeep(p),r.observe(_),t.on(`afterAllTransactions`,v),()=>{t.off(`afterAllTransactions`,v),n.unobserveDeep(p),r.unobserve(_)}}function eb(e){let t=new Map,n=new Map;return{async afterLoadDocument({documentName:r,document:i}){if(J(r)||t.has(r))return;let a=i,o=a.getXmlFragment(`default`),s=a.getText(`source`),c=()=>{try{let n=$y({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),kn(`a`),kn(`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 tb=ln(`conflict-storage`);var nb=class{storePath;projectDir;branch;conflicts=[];constructor(e,t,n=`main`){this.storePath=V(e,`.open-knowledge`,`conflicts.json`),this.projectDir=t,this.branch=n,this.load()}load(){if(!R(this.storePath)){this.conflicts=[];return}try{let e=z(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){tb.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){tb.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=Se(this.storePath);R(e)||ue(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};B(this.storePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){tb.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=H(this.projectDir),r=H(t,e);if(r!==t&&!r.startsWith(`${t}/`))throw Error(`[conflicts] file path escapes project directory: ${e}`);B(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`]),tb.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(`
85
+ `).map(e=>e.trim()).filter(Boolean);for(let t of e)this.addConflict({file:t,detectedAt:n});r=e.length>0}catch(e){tb.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}),tb.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`)}}};function rb(e){return e.git?.toString()??e.message??``}function ib(e,t){return t.some(t=>t.test(e))}const ab=[/\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],ob=[/insufficient scopes/i,/missing.*scope/i,/required scope/i],sb=[/non-fast-forward/i,/rejected.*non-fast-forward/i,/would overwrite.*commits/i,/\[rejected\]/,/fetch first/i,/updates were rejected/i],cb=[/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],lb=[/\bmerge conflict\b/i,/automatic merge failed/i,/CONFLICT \(/,/\bconflict\b.*\bmerge\b/i,/(?:^|\n)CONFLICTS:\s/i],ub=[/lfs.*quota/i,/exceeded.*bandwidth/i,/lfs storage/i],db=[/file.*too large/i,/exceeded.*file size/i,/push file size limit/i],fb=[/pre-receive hook/i,/remote:.*rejected/i,/hook declined/i],pb=[/secret.*detected/i,/push.*secret/i,/secret scanning/i,/leaking.*credentials/i,/token.*detected/i],mb=[/\.git\/index\.lock/i,/another git process/i,/unable to create.*\.lock/i],hb=[/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],gb=[/no space left on device/i,/disk quota exceeded/i,/ENOSPC/],_b=[/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],vb=[/\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],yb=[/\bHTTP[\s/]*429\b/i,/\bstatus:?\s*429\b/i,/\berror\s*429\b/i,/rate.?limit/i,/too many requests/i];function bb(e){let t=e instanceof Error?e:Error(String(e)),n=rb(t),r=`${t.message}\n${n}`.toLowerCase();return ib(r,mb)?{class:`local`,subclass:`index-lock`,retryable:!0,message:`Git index locked by another process`,rawStderr:n}:ib(r,hb)?{class:`local`,subclass:`dirty-tree`,retryable:!0,message:`Working tree has uncommitted changes`,rawStderr:n}:ib(r,gb)?{class:`local`,subclass:`disk-full`,retryable:!0,message:`Disk full or quota exceeded`,rawStderr:n}:ib(r,ob)?{class:`auth`,subclass:`scope-mismatch`,retryable:!1,message:`GitHub token missing required scopes`,rawStderr:n}:ib(r,ab)?/\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)?ib(r,cb)?{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}:ib(r,cb)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:ib(r,sb)?{class:`semantic`,subclass:`non-fast-forward`,retryable:!1,message:`Push rejected — remote has diverged (non-fast-forward)`,rawStderr:n}:ib(r,lb)?{class:`semantic`,subclass:`merge-conflict`,retryable:!1,message:`Merge conflict — manual resolution required`,rawStderr:n}:ib(r,ub)?{class:`structural`,subclass:`lfs-quota`,retryable:!1,message:`Git LFS quota exceeded`,rawStderr:n}:ib(r,db)?{class:`structural`,subclass:`large-file`,retryable:!1,message:`File exceeds size limit`,rawStderr:n}:ib(r,pb)?{class:`structural`,subclass:`secret-detected`,retryable:!1,message:`Push blocked — secret or credential detected in content`,rawStderr:n}:ib(r,fb)?{class:`structural`,subclass:`pre-receive-hook`,retryable:!1,message:`Push rejected by server pre-receive hook`,rawStderr:n}:ib(r,yb)?{class:`network`,subclass:`429`,retryable:!0,message:`Rate limited — too many requests`,rawStderr:n}:ib(r,vb)?{class:`network`,subclass:`5xx`,retryable:!0,message:`Server error (5xx)`,rawStderr:n}:ib(r,_b)?/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 xb(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 $=ln(`sync-engine`),Sb=/^[0-9a-f]{40}$/i;function Cb(e){let t=e*1e3,n=t*.15*(2*Math.random()-1);return Math.round(t+n)}function wb(e){try{let t=V(e,`.git`,`HEAD`);if(!R(t))return!1;let n=z(t,`utf-8`).trim(),r=/^ref:\s+(refs\/.+)$/.exec(n);if(!r)return!1;let i=r[1];if(R(V(e,`.git`,i)))return!1;let a=V(e,`.git`,`packed-refs`);if(R(a)){let e=z(a,`utf-8`);if(RegExp(`^[0-9a-f]+\\s+${i}$`,`m`).test(e))return!1}return!0}catch{return!1}}function Tb(e){return e>=8?3600*1e3:e>=5?900*1e3:e>=3?300*1e3:0}var Eb=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=H(this.contentDir,`.open-knowledge`,`sync-state.json`),this.conflictStore=new nb(this.contentDir,this.projectDir,this.currentBranch)}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=L(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=R(V(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 L(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim(),t=new Set(e?e.split(`
86
+ `).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 L(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=xb(this.lastFetchUtc,this.pullIntervalSeconds),r=xb(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 L(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 kh(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??Cb(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=Tb(e);return t>0?t:Cb(this.pullIntervalSeconds)}async runPullCycle(){if(!this.pullInFlight&&!(this.state===`dormant`||this.state===`disabled`)){if(this.state===`conflict`){this.schedulePull();return}if(wb(this.projectDir)){this.schedulePull();return}this.pullInFlight=!0;try{await this.doPullCycle()}finally{this.pullInFlight=!1,this.schedulePull()}}}async doPullCycle(){let e=L(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(bb(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=bb(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=bb(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(wb(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=V(xe(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),r=null;this.transitionTo(`pushing`);try{await oe(async()=>{let e=L(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:n});if(wb(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(bb(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(`
86
87
  `):[]){let t=e.trim();if(!t)continue;let n=V(this.projectDir,t),r=Te(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(`
87
- `)){let n=t.trim();if(!n)continue;let r=e.get(n)??Te(this.contentDir,V(this.projectDir,n));r&&!r.startsWith(`..`)&&u.push(r)}}}catch{u=t.map(e=>e.contentRelPath)}let d=this.buildCommitMessage(u),f=await yh(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||!fb.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=L(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=ub(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=L(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=ub(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{_e(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=V(xe(),`ok-sync-retry-idx-${process.pid}-${Date.now()}.idx`),i=L(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 yh(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||!fb.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{_e(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(`
88
+ `)){let n=t.trim();if(!n)continue;let r=e.get(n)??Te(this.contentDir,V(this.projectDir,n));r&&!r.startsWith(`..`)&&u.push(r)}}}catch{u=t.map(e=>e.contentRelPath)}let d=this.buildCommitMessage(u),f=await kh(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||!Sb.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=L(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=bb(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=L(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=bb(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{_e(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=V(xe(),`ok-sync-retry-idx-${process.pid}-${Date.now()}.idx`),i=L(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 kh(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||!Sb.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{_e(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(`
88
89
  `).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=fe(n,{withFileTypes:!0})}catch{return}for(let i of r){let r=V(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=Te(this.contentDir,r);if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t)){let n=Te(this.projectDir,r);e.push({contentRelPath:t,projectRelPath:n})}}}};return R(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=L(this.projectDir,{credentialArgs:this.credentialArgs}),t=[];try{let n=(await e.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();t=n?n.split(`
89
- `).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=V(this.projectDir,e),i=Te(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=L(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};B(this.statePath,JSON.stringify(e,null,2),`utf-8`)}catch(e){$.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(R(this.statePath))try{let e=z(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`)}}};const _b=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function vb(e){let{contentDir:t,projectDir:n=t,quiet:r=!0,debounce:i=2e3,maxDebounce:a=1e4,gitEnabled:o=!0,commitDebounceMs:s=3e4,wipRef:c=`refs/wip/main`,enableTestRoutes:l=!1,shadowRepo:u,contentRoot:d,includePatterns:f=[`**/*.md`,`**/*.mdx`],excludePatterns:p=[],destroyTimeoutMs:m=1e4,localOpCliArgs:h}=e,g=ln(`server`),_=H(t,`.open-knowledge`);re(_,{port:e.port??0,worktreeRoot:n});let v,y,x,S,C,w,T=null,E=null,D=null,O=null;function k(e){T?.signal(e)}try{v=wy({projectDir:n,contentDir:t,includePatterns:f,excludePatterns:p}),y=new cm({projectDir:n,contentDir:t,contentFilter:v}),x={current:u},S=Km({contentDir:t,projectDir:n,gitEnabled:o,commitDebounceMs:s,wipRef:c,shadowRef:x,contentRoot:d,backlinkIndex:y,getCurrentBranch:()=>oe?.getLastKnownBranch()??null,getPrincipal:()=>O}),C=new oy({quiet:r,debounce:i,maxDebounce:a,extensions:[S.extension]}),T=new Cl(C),E=new un(C),D=new zn(C),w=new jl(C);let m=Ly({backlinkIndex:y,signalChannel:k});C.configuration.extensions.push(m),C.configuration.extensions.push({async onAuthenticate(e){try{let t=e.token;if(!t)return;let n=JSON.parse(t),r=e.context;typeof n.principalId==`string`&&(O&&n.principalId===O.id?r.principalId=O.id:O?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:O.id})):r.principalId=n.principalId),typeof n.tabSessionId==`string`&&(r.tabSessionId=n.tabSessionId),r.kind=`human`}catch{}}});let g=a_({hocuspocus:C,sessionManager:w,contentDir:t,getFileIndex:()=>I?I.getFileIndex():new Map,getAliasMap:()=>I?I.getAliasMap():new Map,enableTestRoutes:l,shadowRef:x,flushGitCommit:()=>S.flushPendingGitCommit(),getCurrentBranch:()=>oe?.getLastKnownBranch()??null,contentRoot:d,backlinkIndex:y,signalChannel:k,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>L,localOpCliArgs:h,projectDir:n,getPrincipal:()=>O});C.configuration.extensions.push(g),C.configuration.extensions.push(Wy({mdManager:wl,schema:Tl,shadowRef:x,contentRoot:d,getCurrentBranch:()=>oe?.getLastKnownBranch()??null}))}catch(e){throw te(_),e}let A=null;function j(e,t){let n=H(e,`rescue`),r=H(n,`${t}${Np(t)}`);return r.startsWith(`${n}/`)?r:null}function N(e){let t=C.documents.get(e);if(!t)return null;let n=Sl(t.getXmlFragment(`default`),Tl).toJSON(),r=wl.serialize(n),i=t.getMap(`metadata`).get(`frontmatter`);return M(typeof i==`string`?i:``,r)}let P=(e,t)=>ky(C,e,t);function ee(e){return e.kind===`rename`?e.newDocName:e.docName}async function ne(e){try{switch(e.kind){case`create`:g.info({docName:e.docName},`[reconcile] create: ${e.docName}`),y.updateDocumentFromMarkdown(e.docName,e.content),y.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist create for ${e.docName}:`,t)}),k(`files`),k(`backlinks`),k(`graph`);break;case`update`:{let{docName:t,content:n}=e,r=C.documents.get(t);if(!r){y.updateDocumentFromMarkdown(t,n),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc update for ${t}:`,e)}),k(`backlinks`),k(`graph`);return}let i=Bm(t)??``,a=N(t)??i,o=Xm({docName:t,base:i,ours:a,theirs:n}),s=ih(i).slice(0,6),c=ih(a).slice(0,6),l=ih(n).slice(0,6);switch(g.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`:y.updateDocumentFromMarkdown(t,n),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist noop update for ${t}:`,e)}),k(`backlinks`),k(`graph`);break;case`clean`:try{P(t,o.newContent),Vm(t,o.newContent),hn(),y.updateDocumentFromMarkdown(t,n),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist clean update for ${t}:`,e)}),k(`backlinks`),k(`graph`)}catch(e){g.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),Vm(t,n)}break;case`merged`:try{P(t,o.newContent),Vm(t,o.newContent),hn(),y.updateDocumentFromMarkdown(t,n),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist merged update for ${t}:`,e)}),k(`backlinks`),k(`graph`)}catch(e){g.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),Vm(t,n)}break;case`conflicts`:try{P(t,o.newContent),Vm(t,o.newContent),hn(),gn(),y.updateDocumentFromMarkdown(t,n),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist conflict update for ${t}:`,e)}),k(`backlinks`),k(`graph`)}catch(e){g.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),Vm(t,n)}break;case`refused`:{gn();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=C.documents.get(t);if(!n){y.deleteDocument(t),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc delete for ${t}:`,e)}),k(`files`),k(`backlinks`),k(`graph`);return}let r=Bm(t)??``,i=N(t)??``,a=i!==r;if(a&&x.current){let e=x.current,n=oe?.getLastKnownBranch()??`main`;queueMicrotask(()=>{Dm(e,d??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{yn(),g.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{g.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),Hm(t),y.deleteDocument(t),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist delete for ${t}:`,e)}),g.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),C.closeConnections(t),await C.unloadDocument(n),k(`files`),k(`backlinks`),k(`graph`);break}case`rename`:{let{oldDocName:t,newDocName:n,content:r}=e,i=C.documents.get(t);if(Hm(t),Vm(n,r),y.renameDocument(t,n,r),y.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)}g.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),k(`files`),k(`backlinks`),k(`graph`);break}case`conflict`:{let{docName:t}=e,n=C.documents.get(t);if(!n)return;let r=n.getMap(`lifecycle`);r.set(`status`,`conflict`),r.set(`reason`,`conflict-markers`),g.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}}}catch(t){g.error({err:t,kind:e.kind,docName:ee(e)},`[reconcile] failed to handle ${e.kind} for ${ee(e)}`)}}let F=[];async function ie(e){if(Gm()){F.push(e);return}await ne(e)}async function ae(){let e=F.splice(0,F.length);for(let t of e)await ne(t)}let I=null,oe=null,L=null,se=null;async function ce(e){if(C.documents.size===0)return;let t=!1,n=new Promise(e=>{C.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(C.documents.keys());C.closeConnections(),C.flushPendingStores();let i,a=new Promise((n,a)=>{i=setTimeout(()=>{t=!0;let n=Array.from(C.documents.keys()),i=[],o=[];if(x.current){for(let e of n)if(!J(e))try{let t=N(e);if(t===null){g.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=j(x.current.gitDir,e);if(!n){g.warn({docName:e,gitDir:x.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}ue(Se(n),{recursive:!0}),B(n,t,`utf-8`),yn(),i.push(e),g.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),g.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else g.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 le(){return se||(se=(async()=>{let e=Date.now(),t=[],r,i=await Promise.race([pe.then(()=>`completed`,e=>(g.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{r=setTimeout(()=>e(`timeout`),5e3)})]);r!==void 0&&clearTimeout(r),i===`timeout`&&g.warn({},`[server] init did not complete within 5s during shutdown`);let a=C.documents.size;try{try{try{oe&&=(await oe.unsubscribe(),null),I&&=(await I.unsubscribe(),null)}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{T?.destroy(),D?.destroy(),A&&=(await A.disconnect(),null)}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await w.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await ce(m)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await S.flushPendingGitCommit(),await S.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),m)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{L&&=(await L.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(x.current){try{let e=(await Fe({baseDir:n,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&B(H(x.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{mm(x.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let r=Date.now()-e;t.length===0?g.info({documentCount:a,durationMs:r},`[server] shutdown flushed ${a} documents in ${r}ms`):g.warn({documentCount:a,durationMs:r,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${r}ms with ${t.length} phase error(s)`)}}finally{try{te(_)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}}})(),se)}let de=[];async function fe(){try{O=await zy(t),g.info({principalId:O.id},`[server] principal loaded`)}catch(e){g.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!x.current)try{x.current=await pm(n),g.info({gitDir:x.current.gitDir},`[server] history repo initialized at ${x.current.gitDir}`)}catch(e){g.error({err:e},`[server] history repo init failed`),de.push(`shadow-repo`)}if(x.current)try{await fm(x.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`)){g.warn({},`[server] history repo appears corrupted — reinitializing`);try{x.current=await pm(n)}catch(e){g.error({err:e},`[server] history repo reinit failed`),x.current=void 0,de.includes(`shadow-repo`)||de.push(`shadow-repo`)}}else g.error({err:e},`[server] history repo check failed (transient?)`)}if(x.current)try{let e=H(x.current.gitDir,`last-known-head`),t=null;try{t=z(e,`utf-8`).trim()||null}catch{}let r=null;try{r=(await Fe({baseDir:n,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(r!==null){if(r!==t){let e=`main`;try{let t=(await Fe({baseDir:n,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}g.info({lastKnownHead:t,currentHead:r,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=import`);try{await wm(x.current,d??``,t,r,e),vn()}catch(e){g.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else g.info({currentHead:r},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=noop`);try{B(e,r,`utf-8`)}catch(e){g.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){g.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=Hh(t);e.recovered&&e.journal&&g.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){g.error({err:e},`[server] managed rename recovery failed`),de.push(`managed-rename-recovery`)}try{A=await C.openDirectConnection(b)}catch(e){g.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),de.push(`cc1-push`)}try{I=await _h(t,ie,v),y.rebuildFromDisk(zm()),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist startup cache for ${zm()}:`,e)})}catch(e){g.error({err:e},`[server] disk bridge watcher failed to start`),de.push(`file-watcher`)}try{oe=await Py(n,async({trigger:e})=>{if(g.info({trigger:e},`[batch] begin trigger=${e}`),_n(),C.flushPendingStores(),await S.flushPendingGitCommit(),Wm(!0),x.current){let e=zm(),t=jy(n),r=t?Ny(t)??e:e,i=[];for(let[e,t]of C.documents){if(J(e))continue;let n=null;if(t.transact(()=>{n=N(e)},_b),n===null)continue;let r=Bm(e)??n;i.push({docName:e,markdown:n,diskSnapshot:r})}if(i.length>0)try{let t=await km(x.current,e,Sm.id,i,r);t&&(xn(),g.info({count:i.length,branch:e,sha:t.slice(0,8)},`[history] parked ${i.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){g.error({err:e},`[shadow] park failed`)}}},async e=>{let n=F.length,r=e.newBranch??`main`;if(Wm(!1),g.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 ae();else{bn(),F.splice(0,F.length),Rm(r),y.switchBranch(r);for(let[e,n]of C.documents)if(!J(e))try{let i=Pm(e,t);if(!R(i)){let t=Bm(e)??``,i=N(e)??``;if(i!==t&&x.current){let t=x.current;queueMicrotask(()=>{Dm(t,d??``,{kind:`external-change-rescue`,docName:e,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:r,metadata:{incomingDiskSha:``}}).then(()=>{yn(),g.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{g.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),g.info({docName:e,branch:r},`[branch-switch] tombstone: ${e} (not on ${r})`);continue}let a=z(i,`utf-8`);P(e,a),Vm(e,a),g.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){g.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}if(g.info({branch:r,docCount:C.documents.size},`[branch-switch] loaded branch ${r} (${C.documents.size} docs)`),y.rebuildFromDisk(r),y.saveToDisk(r).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${r}:`,e)}),x.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of C.documents)if(!J(t))try{let n=await Am(x.current,r,Sm.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let i=Bm(t);if(!i)continue;let a=Xm({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:i});switch(a.kind){case`merged`:case`clean`:P(t,a.newContent),Vm(t,a.newContent),e++;break;case`conflicts`:P(t,a.newContent),Vm(t,a.newContent),gn(),e++;break;case`noop`:case`refused`:break}}catch(e){g.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&g.info({count:e,branch:r},`[branch-switch] restored ${e} parked docs on ${r}`)}if(e.oldBranch?.startsWith(`detached-`)&&x.current)try{let t=fm(x.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(n){for(let e of n.split(`
90
- `))e&&await t.raw(`update-ref`,`-d`,e);g.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){g.error({err:e},`[branch-switch] detached cleanup failed`)}}if(e.headMoved&&e.newHead&&x.current&&n>0){let t=d??`content`;try{let n=await wm(x.current,t,e.oldHead,e.newHead,r);vn(),g.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){g.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){g.error({err:e},`[server] HEAD watcher failed to start`),de.push(`head-watcher`)}let e=h?.[0]??`open-knowledge`,r=[`-c`,`credential.helper=!${h&&h.length>1?h.join(` `):e} auth git-credential`];try{L=new gb({projectDir:n,contentDir:t,contentFilter:v,contentRoot:d,credentialArgs:r,cc1Broadcaster:T,setBatchInProgress:Wm,onStateChange:e=>{g.info({state:e},`[sync] state → ${e}`)}}),await L.start()}catch(e){g.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),L=null}}let pe=fe();return{hocuspocus:C,sessionManager:w,cc1Broadcaster:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,contentFilter:v,destroy:le,ready:pe,degraded:de,lockDir:_,get syncEngine(){return L}}}async function yb(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.idleShutdownMs,i=e.log??ln(`boot`),{createServer:a}=await import(`node:http`),{WebSocketServer:o}=await import(`./wrapper-_sZfvZ-v.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=vb({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,agentPresenceBroadcaster:g}=u,_=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??`/`}))}),v=new o({noServer:!0});v.on(`error`,e=>{i.error({err:e},`WebSocketServer error`)});let y=e.keepaliveGraceMs??1e4,b=new Map,x=new Set,S=!1;_.on(`upgrade`,(e,t,n)=>{if(e.url?.startsWith(`/collab/keepalive`)){t.on(`error`,e=>{In(e)||i.error({err:e},`MCP keepalive socket error`)}),v.handleUpgrade(e,t,n,t=>{let n=bb(e.url);if(n){let e=b.get(n);e!==void 0&&(clearTimeout(e),b.delete(n),i.info({connectionId:n},`[keepalive] reconnect during grace — timer cancelled`))}let r=setInterval(()=>{try{t.ping()}catch{}},3e4);r.unref?.();let a=n?setInterval(()=>{g?.bumpPresenceTs(mn(n))},3e3):null;a?.unref?.(),t.on(`close`,()=>{if(clearInterval(r),a!==null&&clearInterval(a),!n)return;let e=setTimeout(()=>{if(b.delete(n),S)return;let e=(async()=>{i.info({connectionId:n},`[keepalive] grace expired — cleaning up sessions`);try{await u.sessionManager.closeAllForAgent(n)}catch(e){i.error({err:e,connectionId:n},`[keepalive] closeAllForAgent failed`)}try{u.agentFocusBroadcaster?.clearFocus(n)}catch(e){i.error({err:e,connectionId:n},`[keepalive] clearFocus failed`)}try{g?.clearPresence(mn(n))}catch(e){i.error({err:e,connectionId:n},`[keepalive] clearPresence failed`)}})();x.add(e),e.finally(()=>x.delete(e))},y);e.unref?.(),b.set(n,e),i.info({connectionId:n,graceMs:y},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{In(e)||i.error({err:e},`MCP keepalive WS error`),t.terminate()})});return}e.url?.startsWith(`/collab`)&&(t.on(`error`,e=>{In(e)||i.error({err:e},`Upgrade socket error`)}),v.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=>{In(e)||i.error({err:e},`WebSocket error`),t.terminate()})}))});let C=null;r!==null&&(C=o_({httpServer:_,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);_.once(`error`,r),_.listen(e.port,e.host,()=>{_.removeListener(`error`,r),t()})});let w=_.address(),T=typeof w==`object`&&w?w.port:e.port??0;if(s(h,T),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:h,log:i})}catch(e){i.warn({err:e},`spawnUiSiblingFn failed`)}let E=!1;return{httpServer:_,destroy:async()=>{if(!E){E=!0,S=!0,C?.detach();for(let e of b.values())clearTimeout(e);b.clear(),x.size>0&&await Promise.allSettled([...x]),await new Promise(e=>{_.close(()=>e())}),await f()}},lockDir:h,contentDir:e.contentDir,port:T,ready:p,degraded:m,didAutoInit:l,didGitInit:c,serverInstance:u}}function bb(e){if(!e)return null;try{return pn(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}const xb=He(Me);var Sb=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function Cb(e){let t=H(e),n=H(t,`.git`);if(R(n))return{didInit:!1};let r=``;try{r=(await xb(`git`,[`init`,`--initial-branch=main`,t])).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new Sb(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!R(H(n,`HEAD`)))throw new Sb(`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{Sp as $,ch as A,Sm as B,rh as C,sn as Ct,nh as D,ah as E,Ym as F,pm as G,wm as H,Km as I,Dm as J,Om as K,Pm as L,qm as M,Jm as N,lh as O,Xm as P,nm as Q,bm as R,ih as S,un as St,sh as T,cn as Tt,gm as U,vm as V,ym as W,fm as X,jm as Y,cm as Z,a_ as _,Mn as _t,Wy as a,Uf as at,$h as b,mn as bt,zy as c,Il as ct,Oy as d,Dl as dt,Cp as et,ky as f,Cl as ft,Lg as g,In as gt,Rg as h,Rn as ht,vb as i,qf as it,eh as j,_h as k,Ly as l,Jl as lt,o_ as m,zn as mt,Cb as n,Ep as nt,By as o,Pl as ot,wy as p,J as pt,Em as q,yb as r,wp as rt,Vy as s,Fl as st,Sb as t,Tp as tt,Ny as u,jl as ut,Kg as v,Dn as vt,dh as w,ln as wt,uh as x,pn as xt,eg as y,fn as yt,xm as z};
91
- //# sourceMappingURL=src-y0OBZgkE.mjs.map
90
+ `).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=V(this.projectDir,e),i=Te(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=L(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};B(this.statePath,JSON.stringify(e,null,2),`utf-8`)}catch(e){$.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(R(this.statePath))try{let e=z(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`)}}};const Db=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function Ob(e){let{contentDir:t,projectDir:n=t,quiet:r=!0,debounce:i=2e3,maxDebounce:a=1e4,gitEnabled:o=!0,commitDebounceMs:s=3e4,wipRef:c=`refs/wip/main`,enableTestRoutes:l=!1,shadowRepo:u,contentRoot:d,includePatterns:f=[`**/*.md`,`**/*.mdx`],excludePatterns:p=[],destroyTimeoutMs:m=1e4,localOpCliArgs:h}=e,g=ln(`server`),_=H(t,`.open-knowledge`);re(_,{port:e.port??0,worktreeRoot:n});let v,y,x,S,C,w,T=null,E=null,D=null,O=null;function k(e){T?.signal(e)}try{v=Py({projectDir:n,contentDir:t,includePatterns:f,excludePatterns:p}),y=new vm({projectDir:n,contentDir:t,contentFilter:v}),x={current:u},S=nh({contentDir:t,projectDir:n,gitEnabled:o,commitDebounceMs:s,wipRef:c,shadowRef:x,contentRoot:d,backlinkIndex:y,getCurrentBranch:()=>oe?.getLastKnownBranch()??null,getPrincipal:()=>O}),C=new gy({quiet:r,debounce:i,maxDebounce:a,extensions:[S.extension]}),T=new El(C),E=new un(C),D=new Hn(C),w=new Pl(C);let m=qy({backlinkIndex:y,signalChannel:k});C.configuration.extensions.push(m),C.configuration.extensions.push({async onAuthenticate(e){try{let t=e.token;if(!t)return;let n=JSON.parse(t),r=e.context;typeof n.principalId==`string`&&(O&&n.principalId===O.id?r.principalId=O.id:O?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:O.id})):r.principalId=n.principalId),typeof n.tabSessionId==`string`&&(r.tabSessionId=n.tabSessionId),r.kind=`human`}catch{}}});let g=h_({hocuspocus:C,sessionManager:w,contentDir:t,getFileIndex:()=>I?I.getFileIndex():new Map,getAliasMap:()=>I?I.getAliasMap():new Map,enableTestRoutes:l,shadowRef:x,flushGitCommit:()=>S.flushPendingGitCommit(),getCurrentBranch:()=>oe?.getLastKnownBranch()??null,contentRoot:d,backlinkIndex:y,signalChannel:k,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>L,localOpCliArgs:h,projectDir:n,getPrincipal:()=>O});C.configuration.extensions.push(g),C.configuration.extensions.push(eb({mdManager:Dl,schema:Ol,shadowRef:x,contentRoot:d,getCurrentBranch:()=>oe?.getLastKnownBranch()??null}))}catch(e){throw te(_),e}let A=null;function j(e,t){let n=H(e,`rescue`),r=H(n,`${t}${Up(t)}`);return r.startsWith(`${n}/`)?r:null}function N(e){let t=C.documents.get(e);if(!t)return null;let n=Tl(t.getXmlFragment(`default`),Ol).toJSON(),r=Dl.serialize(n),i=t.getMap(`metadata`).get(`frontmatter`);return M(typeof i==`string`?i:``,r)}let P=(e,t)=>zy(C,e,t);function ee(e){return e.kind===`rename`?e.newDocName:e.docName}async function ne(e){try{switch(e.kind){case`create`:g.info({docName:e.docName},`[reconcile] create: ${e.docName}`),y.updateDocumentFromMarkdown(e.docName,e.content),y.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist create for ${e.docName}:`,t)}),k(`files`),k(`backlinks`),k(`graph`);break;case`update`:{let{docName:t,content:n}=e,r=C.documents.get(t);if(!r){y.updateDocumentFromMarkdown(t,n),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc update for ${t}:`,e)}),k(`backlinks`),k(`graph`);return}let i=Xm(t)??``,a=N(t)??i,o=oh({docName:t,base:i,ours:a,theirs:n}),s=mh(i).slice(0,6),c=mh(a).slice(0,6),l=mh(n).slice(0,6);switch(g.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`:y.updateDocumentFromMarkdown(t,n),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist noop update for ${t}:`,e)}),k(`backlinks`),k(`graph`);break;case`clean`:try{P(t,o.newContent),Zm(t,o.newContent),hn(),y.updateDocumentFromMarkdown(t,n),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist clean update for ${t}:`,e)}),k(`backlinks`),k(`graph`)}catch(e){g.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),Zm(t,n)}break;case`merged`:try{P(t,o.newContent),Zm(t,o.newContent),hn(),y.updateDocumentFromMarkdown(t,n),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist merged update for ${t}:`,e)}),k(`backlinks`),k(`graph`)}catch(e){g.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),Zm(t,n)}break;case`conflicts`:try{P(t,o.newContent),Zm(t,o.newContent),hn(),gn(),y.updateDocumentFromMarkdown(t,n),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist conflict update for ${t}:`,e)}),k(`backlinks`),k(`graph`)}catch(e){g.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),Zm(t,n)}break;case`refused`:{gn();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=C.documents.get(t);if(!n){y.deleteDocument(t),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist closed-doc delete for ${t}:`,e)}),k(`files`),k(`backlinks`),k(`graph`);return}let r=Xm(t)??``,i=N(t)??``,a=i!==r;if(a&&x.current){let e=x.current,n=oe?.getLastKnownBranch()??`main`;queueMicrotask(()=>{Lm(e,d??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{yn(),g.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{g.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),Qm(t),y.deleteDocument(t),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist delete for ${t}:`,e)}),g.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),C.closeConnections(t),await C.unloadDocument(n),k(`files`),k(`backlinks`),k(`graph`);break}case`rename`:{let{oldDocName:t,newDocName:n,content:r}=e,i=C.documents.get(t);if(Qm(t),Zm(n,r),y.renameDocument(t,n,r),y.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)}g.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),k(`files`),k(`backlinks`),k(`graph`);break}case`conflict`:{let{docName:t}=e,n=C.documents.get(t);if(!n)return;let r=n.getMap(`lifecycle`);r.set(`status`,`conflict`),r.set(`reason`,`conflict-markers`),g.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}}}catch(t){g.error({err:t,kind:e.kind,docName:ee(e)},`[reconcile] failed to handle ${e.kind} for ${ee(e)}`)}}let F=[];async function ie(e){if(th()){F.push(e);return}await ne(e)}async function ae(){let e=F.splice(0,F.length);for(let t of e)await ne(t)}let I=null,oe=null,L=null,se=null;async function ce(e){if(C.documents.size===0)return;let t=!1,n=new Promise(e=>{C.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(C.documents.keys());C.closeConnections(),C.flushPendingStores();let i,a=new Promise((n,a)=>{i=setTimeout(()=>{t=!0;let n=Array.from(C.documents.keys()),i=[],o=[];if(x.current){for(let e of n)if(!J(e))try{let t=N(e);if(t===null){g.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=j(x.current.gitDir,e);if(!n){g.warn({docName:e,gitDir:x.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}ue(Se(n),{recursive:!0}),B(n,t,`utf-8`),yn(),i.push(e),g.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),g.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else g.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 le(){return se||(se=(async()=>{let e=Date.now(),t=[],r,i=await Promise.race([pe.then(()=>`completed`,e=>(g.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{r=setTimeout(()=>e(`timeout`),5e3)})]);r!==void 0&&clearTimeout(r),i===`timeout`&&g.warn({},`[server] init did not complete within 5s during shutdown`);let a=C.documents.size;try{try{try{oe&&=(await oe.unsubscribe(),null),I&&=(await I.unsubscribe(),null)}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{T?.destroy(),D?.destroy(),A&&=(await A.disconnect(),null)}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await w.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await ce(m)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await S.flushPendingGitCommit(),await S.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),m)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{L&&=(await L.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(x.current){try{let e=(await Fe({baseDir:n,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&B(H(x.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{wm(x.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let r=Date.now()-e;t.length===0?g.info({documentCount:a,durationMs:r},`[server] shutdown flushed ${a} documents in ${r}ms`):g.warn({documentCount:a,durationMs:r,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${r}ms with ${t.length} phase error(s)`)}}finally{try{te(_)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),g.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}}})(),se)}let de=[];async function fe(){try{O=await Yy(t),g.info({principalId:O.id},`[server] principal loaded`)}catch(e){g.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!x.current)try{x.current=await Cm(n),g.info({gitDir:x.current.gitDir},`[server] history repo initialized at ${x.current.gitDir}`)}catch(e){g.error({err:e},`[server] history repo init failed`),de.push(`shadow-repo`)}if(x.current)try{await Sm(x.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`)){g.warn({},`[server] history repo appears corrupted — reinitializing`);try{x.current=await Cm(n)}catch(e){g.error({err:e},`[server] history repo reinit failed`),x.current=void 0,de.includes(`shadow-repo`)||de.push(`shadow-repo`)}}else g.error({err:e},`[server] history repo check failed (transient?)`)}if(x.current)try{let e=H(x.current.gitDir,`last-known-head`),t=null;try{t=z(e,`utf-8`).trim()||null}catch{}let r=null;try{r=(await Fe({baseDir:n,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(r!==null){if(r!==t){let e=`main`;try{let t=(await Fe({baseDir:n,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}g.info({lastKnownHead:t,currentHead:r,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=import`);try{await Pm(x.current,d??``,t,r,e),vn()}catch(e){g.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else g.info({currentHead:r},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=noop`);try{B(e,r,`utf-8`)}catch(e){g.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){g.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=Qh(t);e.recovered&&e.journal&&g.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){g.error({err:e},`[server] managed rename recovery failed`),de.push(`managed-rename-recovery`)}try{A=await C.openDirectConnection(b)}catch(e){g.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),de.push(`cc1-push`)}try{I=await Dh(t,ie,v),y.rebuildFromDisk(Ym()),y.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist startup cache for ${Ym()}:`,e)})}catch(e){g.error({err:e},`[server] disk bridge watcher failed to start`),de.push(`file-watcher`)}try{oe=await Wy(n,async({trigger:e})=>{if(g.info({trigger:e},`[batch] begin trigger=${e}`),_n(),C.flushPendingStores(),await S.flushPendingGitCommit(),eh(!0),x.current){let e=Ym(),t=Vy(n),r=t?Uy(t)??e:e,i=[];for(let[e,t]of C.documents){if(J(e))continue;let n=null;if(t.transact(()=>{n=N(e)},Db),n===null)continue;let r=Xm(e)??n;i.push({docName:e,markdown:n,diskSnapshot:r})}if(i.length>0)try{let t=await zm(x.current,e,Mm.id,i,r);t&&(xn(),g.info({count:i.length,branch:e,sha:t.slice(0,8)},`[history] parked ${i.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){g.error({err:e},`[shadow] park failed`)}}},async e=>{let n=F.length,r=e.newBranch??`main`;if(eh(!1),g.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 ae();else{bn(),F.splice(0,F.length),Jm(r),y.switchBranch(r);for(let[e,n]of C.documents)if(!J(e))try{let i=Wm(e,t);if(!R(i)){let t=Xm(e)??``,i=N(e)??``;if(i!==t&&x.current){let t=x.current;queueMicrotask(()=>{Lm(t,d??``,{kind:`external-change-rescue`,docName:e,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:r,metadata:{incomingDiskSha:``}}).then(()=>{yn(),g.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{g.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),g.info({docName:e,branch:r},`[branch-switch] tombstone: ${e} (not on ${r})`);continue}let a=z(i,`utf-8`);P(e,a),Zm(e,a),g.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){g.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}if(g.info({branch:r,docCount:C.documents.size},`[branch-switch] loaded branch ${r} (${C.documents.size} docs)`),y.rebuildFromDisk(r),y.saveToDisk(r).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${r}:`,e)}),x.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of C.documents)if(!J(t))try{let n=await Bm(x.current,r,Mm.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let i=Xm(t);if(!i)continue;let a=oh({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:i});switch(a.kind){case`merged`:case`clean`:P(t,a.newContent),Zm(t,a.newContent),e++;break;case`conflicts`:P(t,a.newContent),Zm(t,a.newContent),gn(),e++;break;case`noop`:case`refused`:break}}catch(e){g.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&g.info({count:e,branch:r},`[branch-switch] restored ${e} parked docs on ${r}`)}if(e.oldBranch?.startsWith(`detached-`)&&x.current)try{let t=Sm(x.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(n){for(let e of n.split(`
91
+ `))e&&await t.raw(`update-ref`,`-d`,e);g.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){g.error({err:e},`[branch-switch] detached cleanup failed`)}}if(e.headMoved&&e.newHead&&x.current&&n>0){let t=d??`content`;try{let n=await Pm(x.current,t,e.oldHead,e.newHead,r);vn(),g.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){g.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){g.error({err:e},`[server] HEAD watcher failed to start`),de.push(`head-watcher`)}let e=h?.[0]??`open-knowledge`,r=[`-c`,`credential.helper=!${h&&h.length>1?h.join(` `):e} auth git-credential`];try{L=new Eb({projectDir:n,contentDir:t,contentFilter:v,contentRoot:d,credentialArgs:r,cc1Broadcaster:T,setBatchInProgress:eh,onStateChange:e=>{g.info({state:e},`[sync] state → ${e}`)}}),await L.start()}catch(e){g.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),L=null}}let pe=fe();return{hocuspocus:C,sessionManager:w,cc1Broadcaster:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,contentFilter:v,destroy:le,ready:pe,degraded:de,lockDir:_,get syncEngine(){return L}}}async function kb(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.idleShutdownMs,i=e.log??ln(`boot`),{createServer:a}=await import(`node:http`),{WebSocketServer:o}=await import(`./wrapper-_sZfvZ-v.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=Ob({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,agentPresenceBroadcaster:g}=u,_=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??`/`}))}),v=new o({noServer:!0});v.on(`error`,e=>{i.error({err:e},`WebSocketServer error`)});let y=e.keepaliveGraceMs??1e4,b=new Map,x=new Set,S=!1;_.on(`upgrade`,(e,t,n)=>{if(e.url?.startsWith(`/collab/keepalive`)){t.on(`error`,e=>{zn(e)||i.error({err:e},`MCP keepalive socket error`)}),v.handleUpgrade(e,t,n,t=>{let n=Ab(e.url);if(n){let e=b.get(n);e!==void 0&&(clearTimeout(e),b.delete(n),i.info({connectionId:n},`[keepalive] reconnect during grace — timer cancelled`))}let r=setInterval(()=>{try{t.ping()}catch{}},3e4);r.unref?.();let a=n?setInterval(()=>{g?.bumpPresenceTs(mn(n))},3e3):null;a?.unref?.(),t.on(`close`,()=>{if(clearInterval(r),a!==null&&clearInterval(a),!n)return;let e=setTimeout(()=>{if(b.delete(n),S)return;let e=(async()=>{i.info({connectionId:n},`[keepalive] grace expired — cleaning up sessions`);try{await u.sessionManager.closeAllForAgent(n)}catch(e){i.error({err:e,connectionId:n},`[keepalive] closeAllForAgent failed`)}try{u.agentFocusBroadcaster?.clearFocus(n)}catch(e){i.error({err:e,connectionId:n},`[keepalive] clearFocus failed`)}try{g?.clearPresence(mn(n))}catch(e){i.error({err:e,connectionId:n},`[keepalive] clearPresence failed`)}})();x.add(e),e.finally(()=>x.delete(e))},y);e.unref?.(),b.set(n,e),i.info({connectionId:n,graceMs:y},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{zn(e)||i.error({err:e},`MCP keepalive WS error`),t.terminate()})});return}e.url?.startsWith(`/collab`)&&(t.on(`error`,e=>{zn(e)||i.error({err:e},`Upgrade socket error`)}),v.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=>{zn(e)||i.error({err:e},`WebSocket error`),t.terminate()})}))});let C=null;r!==null&&(C=g_({httpServer:_,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);_.once(`error`,r),_.listen(e.port,e.host,()=>{_.removeListener(`error`,r),t()})});let w=_.address(),T=typeof w==`object`&&w?w.port:e.port??0;if(s(h,T),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:h,log:i})}catch(e){i.warn({err:e},`spawnUiSiblingFn failed`)}let E=!1;return{httpServer:_,destroy:async()=>{if(!E){E=!0,S=!0,C?.detach();for(let e of b.values())clearTimeout(e);b.clear(),x.size>0&&await Promise.allSettled([...x]),await new Promise(e=>{_.close(()=>e())}),await f()}},lockDir:h,contentDir:e.contentDir,port:T,ready:p,degraded:m,didAutoInit:l,didGitInit:c,serverInstance:u}}function Ab(e){if(!e)return null;try{return pn(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}const jb=He(Me);var Mb=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function Nb(e){let t=H(e),n=H(t,`.git`);if(R(n))return{didInit:!1};let r=``;try{r=(await jb(`git`,[`init`,`--initial-branch=main`,t])).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new Mb(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!R(H(n,`HEAD`)))throw new Mb(`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{Mp as $,vh as A,Mm as B,ph as C,sn as Ct,fh as D,hh as E,ah as F,Cm as G,Pm as H,nh as I,Lm as J,Rm as K,Wm as L,rh as M,ih as N,yh as O,oh as P,fm as Q,Am as R,mh as S,un as St,_h as T,cn as Tt,Em as U,Om as V,km as W,Sm as X,Vm as Y,vm as Z,h_ as _,Fn as _t,eb as a,$f as at,lg as b,mn as bt,Yy as c,ru as ct,Ry as d,Al as dt,Np as et,zy as f,El as ft,qg as g,zn as gt,Jg as h,Vn as ht,Ob as i,rp as it,uh as j,Dh as k,qy as l,Jl as lt,g_ as m,Hn as mt,Nb as n,Ip as nt,Xy as o,Ll as ot,Py as p,J as pt,Im as q,kb as r,Pp as rt,Zy as s,Rl as st,Mb as t,Fp as tt,Uy as u,Pl as ut,n_ as v,Dn as vt,xh as w,ln as wt,bh as x,pn as xt,ug as y,fn as yt,jm as z};
92
+ //# sourceMappingURL=src-4QBkn9Bx.mjs.map