@inkeep/open-knowledge 0.7.0-beta.2 → 0.7.0-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/skills/discovery/SKILL.md +1 -1
- package/dist/assets/skills/project/SKILL.md +1 -1
- package/dist/cli.mjs +34 -34
- package/dist/constants-B5EPB7No.mjs +2 -0
- package/dist/dist-CYAFvCEc.mjs +1 -0
- package/dist/{dist-Di8PRueX.mjs → dist-DdtB66Zm.mjs} +6 -6
- package/dist/index.mjs +1 -1
- package/dist/init-B0m02OwN.mjs +409 -0
- package/dist/init-Cc4ZOjxr.mjs +1 -0
- package/dist/loader-DRzUzGIP.mjs +1 -0
- package/dist/{loader-Cur5BKFJ.mjs → loader-l7m2UlKq.mjs} +3 -3
- package/dist/preview-CTU5vD2g.mjs +1 -0
- package/dist/{preview-BgmpSibC.mjs → preview-CUbWk4Qg.mjs} +2 -2
- package/dist/public/assets/{index-BTZc5KsG.js → index-WnuLXsr7.js} +3 -3
- package/dist/public/index.html +1 -1
- package/dist/{repair-launch-json-CHlzQe0b.mjs → repair-launch-json-CM9n5djt.mjs} +2 -2
- package/dist/{repair-mcp-configs-VWGpMR1J.mjs → repair-mcp-configs-CI2NG5qR.mjs} +2 -2
- package/dist/{src-CnfM5ak2.mjs → src-C2h-AepF.mjs} +2 -2
- package/dist/start-BSER_dyP.mjs +1 -0
- package/dist/{start-sd88l8zT.mjs → start-CIegAN8x.mjs} +2 -2
- package/package.json +1 -1
- package/dist/constants-CiPK2C2S.mjs +0 -2
- package/dist/dist-CnCjIzK3.mjs +0 -1
- package/dist/init-54ZYUY8w.mjs +0 -1
- package/dist/init-BMI-tqua.mjs +0 -409
- package/dist/loader-ZOb_N4CJ.mjs +0 -1
- package/dist/preview-D3rGX6Pl.mjs +0 -1
- package/dist/start-DiK17vCi.mjs +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as __toCommonJS,i as __require$1,n as __esmMin,o as __toESM$1,r as __exportAll,t as __commonJSMin$1}from"./chunk-FK9Q3tQk.mjs";import{a as metrics$1,c as SpanStatusCode,i as propagation,l as SpanKind,n as init_esm$2,o as diag,r as trace,s as context,t as esm_exports$2}from"./esm-BbkJd7ro.mjs";import{a as acquireProcessLock,c as isValidLockPid,f as readServerLock,g as updateProcessLockPort,m as releaseServerLock,n as RUNTIME_VERSION,o as acquireServerLock,p as releaseProcessLock,s as isProcessAlive,t as ProcessLockCollisionError,u as readProcessLock}from"./server-lock-BniQ3qki-CadPGoZN.mjs";import{a as simpleGit,i as esm_default,o as require_src$15,r as withParentLock,t as createGitInstance}from"./git-handle-CjyGVy33-CK0dYQ8y.mjs";import{r as diffLines,t as createPatch}from"./libesm-Cfo1LhlX.mjs";import{n as mimes,t as build_default}from"./build-BZeImWox.mjs";import{t as b1}from"./chunk-YNYSPYQ5-DesxOVHh.mjs";import{a as c$1,c as h$2,d as m,f as p,h as x,i as b,l as i$1,m as v$1,n as C$1,o as d,p as u,r as a,s as f,t as $$2,u as l}from"./chunk-GFQRA5P5-DnjwTqP3.mjs";import{A as gt,B as wt,C as _i$1,D as da$1,E as bt,F as pe,H as zi$1,I as qi,L as us$1,M as ma$1,N as mt$1,O as di$1,P as pa$1,S as X$1,T as bl,V as xi$1,_ as Ti$1,a as Fi$1,b as W$1,c as M,d as P,f as Pt$1,g as T,h as Sl,i as En$1,j as he,k as ga$1,l as Nl,m as Se,n as Bi$1,o as Fs$1,p as R,r as Ci$1,s as G$1,t as Al,u as Oi$1,v as V,w as be,x as Wi$1,y as Vi$1,z as wl}from"./chunk-FEIOJCZD-C25Und0M.mjs";import{a as d$1,c as m$1,d as y,i as c$2,l as p$1,n as N,o as f$1,r as P$1,s as h$3,t as $$3,u as v$2}from"./chunk-XHM67O4N-akBjDPaR.mjs";import{n as l$1,r as o,t as h$4}from"./chunk-R6VWJ2ZL-FwG_Za20.mjs";import{r as o$1}from"./chunk-CWQS3NFK-Co4ALolT.mjs";import"./chunk-DXB73IDG-DIKSLkPq.mjs";import{n as d$2,t as _$1}from"./chunk-5QMZ5MUS-CAp625aG.mjs";import{n as u$1,t as b$1}from"./chunk-A5O5YHGN-DvJz5Cpw.mjs";import{n,r,t as c$3}from"./chunk-OJDRYQWQ-ikvLWpfV.mjs";import{r as x$1,t as a$1}from"./chunk-24IMIIXA-B6yIPkk2.mjs";import{n as n$1}from"./chunk-3THT3N7L-DztAF386.mjs";import{t as n$2}from"./chunk-44UOCSGV-CaFxJDHm.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import*as U from"node:path";import minpath,{basename,dirname,extname,isAbsolute,join,normalize,posix,relative,resolve,sep,win32}from"node:path";import*as I from"node:fs";import{appendFileSync,closeSync,cpSync,createReadStream,createWriteStream,existsSync,linkSync,lstatSync,mkdirSync,openSync,readFile,readFileSync,readSync,readdirSync,realpathSync,renameSync,rmSync,rmdirSync,statSync,unlinkSync,writeFileSync}from"node:fs";import minproc from"node:process";import{homedir,hostname,platform,tmpdir}from"node:os";import{URLSearchParams as URLSearchParams$1,fileURLToPath,fileURLToPath as urlToPath}from"node:url";import{AsyncLocalStorage}from"node:async_hooks";import{promisify}from"node:util";import{Readable}from"stream";import{Transform}from"node:stream";import crypto$1,{createHash,randomUUID,webcrypto}from"node:crypto";import crypto$2 from"crypto";import*as zlib$2 from"zlib";import{access,constants,mkdir,readFile as readFile$1,readdir,realpath,rename,stat as stat$1,writeFile}from"node:fs/promises";import{pipeline}from"node:stream/promises";import{setTimeout as setTimeout$1}from"node:timers/promises";import{Http2ServerRequest,constants as constants$1}from"http2";import{lookup}from"node:dns";import{createServer}from"node:http";var require_identity=__commonJSMin$1((e=>{let t=Symbol.for(`yaml.alias`),S=Symbol.for(`yaml.document`),w=Symbol.for(`yaml.map`),E=Symbol.for(`yaml.pair`),D=Symbol.for(`yaml.scalar`),O=Symbol.for(`yaml.seq`),k=Symbol.for(`yaml.node.type`),j=e=>!!e&&typeof e==`object`&&e[k]===t,F=e=>!!e&&typeof e==`object`&&e[k]===S,L=e=>!!e&&typeof e==`object`&&e[k]===w,B=e=>!!e&&typeof e==`object`&&e[k]===E,H=e=>!!e&&typeof e==`object`&&e[k]===D,q=e=>!!e&&typeof e==`object`&&e[k]===O;function J(e){if(e&&typeof e==`object`)switch(e[k]){case w:case O:return!0}return!1}function Y(e){if(e&&typeof e==`object`)switch(e[k]){case t:case w:case D:case O:return!0}return!1}e.ALIAS=t,e.DOC=S,e.MAP=w,e.NODE_TYPE=k,e.PAIR=E,e.SCALAR=D,e.SEQ=O,e.hasAnchor=e=>(H(e)||J(e))&&!!e.anchor,e.isAlias=j,e.isCollection=J,e.isDocument=F,e.isMap=L,e.isNode=Y,e.isPair=B,e.isScalar=H,e.isSeq=q})),require_visit=__commonJSMin$1((e=>{var t=require_identity();let S=Symbol(`break visit`),w=Symbol(`skip children`),E=Symbol(`remove node`);function D(e,S){let w=F(S);t.isDocument(e)?O(null,e.contents,w,Object.freeze([e]))===E&&(e.contents=null):O(null,e,w,Object.freeze([]))}D.BREAK=S,D.SKIP=w,D.REMOVE=E;function O(e,w,D,k){let j=L(e,w,D,k);if(t.isNode(j)||t.isPair(j))return B(e,k,j),O(e,j,D,k);if(typeof j!=`symbol`){if(t.isCollection(w)){k=Object.freeze(k.concat(w));for(let e=0;e<w.items.length;++e){let t=O(e,w.items[e],D,k);if(typeof t==`number`)e=t-1;else if(t===S)return S;else t===E&&(w.items.splice(e,1),--e)}}else if(t.isPair(w)){k=Object.freeze(k.concat(w));let e=O(`key`,w.key,D,k);if(e===S)return S;e===E&&(w.key=null);let t=O(`value`,w.value,D,k);if(t===S)return S;t===E&&(w.value=null)}}return j}async function k(e,S){let w=F(S);t.isDocument(e)?await j(null,e.contents,w,Object.freeze([e]))===E&&(e.contents=null):await j(null,e,w,Object.freeze([]))}k.BREAK=S,k.SKIP=w,k.REMOVE=E;async function j(e,w,D,O){let k=await L(e,w,D,O);if(t.isNode(k)||t.isPair(k))return B(e,O,k),j(e,k,D,O);if(typeof k!=`symbol`){if(t.isCollection(w)){O=Object.freeze(O.concat(w));for(let e=0;e<w.items.length;++e){let t=await j(e,w.items[e],D,O);if(typeof t==`number`)e=t-1;else if(t===S)return S;else t===E&&(w.items.splice(e,1),--e)}}else if(t.isPair(w)){O=Object.freeze(O.concat(w));let e=await j(`key`,w.key,D,O);if(e===S)return S;e===E&&(w.key=null);let t=await j(`value`,w.value,D,O);if(t===S)return S;t===E&&(w.value=null)}}return k}function F(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function L(e,S,w,E){if(typeof w==`function`)return w(e,S,E);if(t.isMap(S))return w.Map?.(e,S,E);if(t.isSeq(S))return w.Seq?.(e,S,E);if(t.isPair(S))return w.Pair?.(e,S,E);if(t.isScalar(S))return w.Scalar?.(e,S,E);if(t.isAlias(S))return w.Alias?.(e,S,E)}function B(e,S,w){let E=S[S.length-1];if(t.isCollection(E))E.items[e]=w;else if(t.isPair(E))e===`key`?E.key=w:E.value=w;else if(t.isDocument(E))E.contents=w;else{let e=t.isAlias(E)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=D,e.visitAsync=k})),require_directives=__commonJSMin$1((e=>{var t=require_identity(),S=require_visit();let w={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},E=e=>e.replace(/[!,[\]{}]/g,e=>w[e]);var D=class e{constructor(t,S){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,S)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,S){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let w=t.trim().split(/[ \t]+/),E=w.shift();switch(E){case`%TAG`:{if(w.length!==2&&(S(0,`%TAG directive should contain exactly two parts`),w.length<2))return!1;let[e,t]=w;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,w.length!==1)return S(0,`%YAML directive should contain exactly one part`),!1;let[e]=w;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return S(6,`Unsupported YAML version ${e}`,t),!1}}default:return S(0,`Unknown directive ${E}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let S=e.slice(2,-1);return S===`!`||S===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),S)}let[,S,w]=e.match(/^(.*!)([^!]*)$/s);w||t(`The ${e} tag has no suffix`);let E=this.tags[S];if(E)try{return E+decodeURIComponent(w)}catch(e){return t(String(e)),null}return S===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,S]of Object.entries(this.tags))if(e.startsWith(S))return t+E(e.substring(S.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let w=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],E=Object.entries(this.tags),D;if(e&&E.length>0&&t.isNode(e.contents)){let w={};S.visit(e.contents,(e,S)=>{t.isNode(S)&&S.tag&&(w[S.tag]=!0)}),D=Object.keys(w)}else D=[];for(let[t,S]of E)t===`!!`&&S===`tag:yaml.org,2002:`||(!e||D.some(e=>e.startsWith(S)))&&w.push(`%TAG ${t} ${S}`);return w.join(`
|
|
1
|
+
import{a as __toCommonJS,i as __require$1,n as __esmMin,o as __toESM$1,r as __exportAll,t as __commonJSMin$1}from"./chunk-FK9Q3tQk.mjs";import{a as metrics$1,c as SpanStatusCode,i as propagation,l as SpanKind,n as init_esm$2,o as diag,r as trace,s as context,t as esm_exports$2}from"./esm-BbkJd7ro.mjs";import{a as acquireProcessLock,c as isValidLockPid,f as readServerLock,g as updateProcessLockPort,m as releaseServerLock,n as RUNTIME_VERSION,o as acquireServerLock,p as releaseProcessLock,s as isProcessAlive,t as ProcessLockCollisionError,u as readProcessLock}from"./server-lock-BniQ3qki-CadPGoZN.mjs";import{a as simpleGit,i as esm_default,o as require_src$15,r as withParentLock,t as createGitInstance}from"./git-handle-CjyGVy33-CK0dYQ8y.mjs";import{r as diffLines,t as createPatch}from"./libesm-Cfo1LhlX.mjs";import{n as mimes,t as build_default}from"./build-BZeImWox.mjs";import{t as b1}from"./chunk-YNYSPYQ5-DesxOVHh.mjs";import{a as c$1,c as h$2,d as m,f as p,h as x,i as b,l as i$1,m as v$1,n as C$1,o as d,p as u,r as a,s as f,t as $$2,u as l}from"./chunk-GFQRA5P5-DnjwTqP3.mjs";import{A as gt,B as wt,C as _i$1,D as da$1,E as bt,F as pe,H as zi$1,I as qi,L as us$1,M as ma$1,N as mt$1,O as di$1,P as pa$1,S as X$1,T as bl,V as xi$1,_ as Ti$1,a as Fi$1,b as W$1,c as M,d as P,f as Pt$1,g as T,h as Sl,i as En$1,j as he,k as ga$1,l as Nl,m as Se,n as Bi$1,o as Fs$1,p as R,r as Ci$1,s as G$1,t as Al,u as Oi$1,v as V,w as be,x as Wi$1,y as Vi$1,z as wl}from"./chunk-FEIOJCZD-C25Und0M.mjs";import{a as d$1,c as m$1,d as y,i as c$2,l as p$1,n as N,o as f$1,r as P$1,s as h$3,t as $$3,u as v$2}from"./chunk-XHM67O4N-akBjDPaR.mjs";import{n as l$1,r as o,t as h$4}from"./chunk-R6VWJ2ZL-FwG_Za20.mjs";import{r as o$1}from"./chunk-CWQS3NFK-Co4ALolT.mjs";import"./chunk-DXB73IDG-DIKSLkPq.mjs";import{n as d$2,t as _$1}from"./chunk-5QMZ5MUS-CAp625aG.mjs";import{n as u$1,t as b$1}from"./chunk-A5O5YHGN-DvJz5Cpw.mjs";import{n,r,t as c$3}from"./chunk-OJDRYQWQ-ikvLWpfV.mjs";import{r as x$1,t as a$1}from"./chunk-24IMIIXA-B6yIPkk2.mjs";import{n as n$1}from"./chunk-3THT3N7L-DztAF386.mjs";import{t as n$2}from"./chunk-44UOCSGV-CaFxJDHm.mjs";import{createRequire}from"node:module";import{execFile,spawn,spawnSync}from"node:child_process";import*as U from"node:path";import minpath,{basename,dirname,extname,isAbsolute,join,normalize,posix,relative,resolve,sep,win32}from"node:path";import*as I from"node:fs";import{appendFileSync,closeSync,cpSync,createReadStream,createWriteStream,existsSync,linkSync,lstatSync,mkdirSync,openSync,readFile,readFileSync,readSync,readdirSync,realpathSync,renameSync,rmSync,rmdirSync,statSync,unlinkSync,writeFileSync}from"node:fs";import minproc from"node:process";import{homedir,hostname,platform,tmpdir}from"node:os";import{URLSearchParams as URLSearchParams$1,fileURLToPath,fileURLToPath as urlToPath}from"node:url";import{AsyncLocalStorage}from"node:async_hooks";import{promisify}from"node:util";import{Readable}from"stream";import{Transform}from"node:stream";import crypto$1,{createHash,randomUUID,webcrypto}from"node:crypto";import crypto$2 from"crypto";import*as zlib$2 from"zlib";import{access,constants,mkdir,readFile as readFile$1,readdir,realpath,rename,stat as stat$1,unlink,writeFile}from"node:fs/promises";import{pipeline}from"node:stream/promises";import{setTimeout as setTimeout$1}from"node:timers/promises";import{Http2ServerRequest,constants as constants$1}from"http2";import{lookup}from"node:dns";import{createServer}from"node:http";var require_identity=__commonJSMin$1((e=>{let t=Symbol.for(`yaml.alias`),S=Symbol.for(`yaml.document`),w=Symbol.for(`yaml.map`),E=Symbol.for(`yaml.pair`),D=Symbol.for(`yaml.scalar`),O=Symbol.for(`yaml.seq`),k=Symbol.for(`yaml.node.type`),j=e=>!!e&&typeof e==`object`&&e[k]===t,F=e=>!!e&&typeof e==`object`&&e[k]===S,L=e=>!!e&&typeof e==`object`&&e[k]===w,B=e=>!!e&&typeof e==`object`&&e[k]===E,H=e=>!!e&&typeof e==`object`&&e[k]===D,q=e=>!!e&&typeof e==`object`&&e[k]===O;function J(e){if(e&&typeof e==`object`)switch(e[k]){case w:case O:return!0}return!1}function Y(e){if(e&&typeof e==`object`)switch(e[k]){case t:case w:case D:case O:return!0}return!1}e.ALIAS=t,e.DOC=S,e.MAP=w,e.NODE_TYPE=k,e.PAIR=E,e.SCALAR=D,e.SEQ=O,e.hasAnchor=e=>(H(e)||J(e))&&!!e.anchor,e.isAlias=j,e.isCollection=J,e.isDocument=F,e.isMap=L,e.isNode=Y,e.isPair=B,e.isScalar=H,e.isSeq=q})),require_visit=__commonJSMin$1((e=>{var t=require_identity();let S=Symbol(`break visit`),w=Symbol(`skip children`),E=Symbol(`remove node`);function D(e,S){let w=F(S);t.isDocument(e)?O(null,e.contents,w,Object.freeze([e]))===E&&(e.contents=null):O(null,e,w,Object.freeze([]))}D.BREAK=S,D.SKIP=w,D.REMOVE=E;function O(e,w,D,k){let j=L(e,w,D,k);if(t.isNode(j)||t.isPair(j))return B(e,k,j),O(e,j,D,k);if(typeof j!=`symbol`){if(t.isCollection(w)){k=Object.freeze(k.concat(w));for(let e=0;e<w.items.length;++e){let t=O(e,w.items[e],D,k);if(typeof t==`number`)e=t-1;else if(t===S)return S;else t===E&&(w.items.splice(e,1),--e)}}else if(t.isPair(w)){k=Object.freeze(k.concat(w));let e=O(`key`,w.key,D,k);if(e===S)return S;e===E&&(w.key=null);let t=O(`value`,w.value,D,k);if(t===S)return S;t===E&&(w.value=null)}}return j}async function k(e,S){let w=F(S);t.isDocument(e)?await j(null,e.contents,w,Object.freeze([e]))===E&&(e.contents=null):await j(null,e,w,Object.freeze([]))}k.BREAK=S,k.SKIP=w,k.REMOVE=E;async function j(e,w,D,O){let k=await L(e,w,D,O);if(t.isNode(k)||t.isPair(k))return B(e,O,k),j(e,k,D,O);if(typeof k!=`symbol`){if(t.isCollection(w)){O=Object.freeze(O.concat(w));for(let e=0;e<w.items.length;++e){let t=await j(e,w.items[e],D,O);if(typeof t==`number`)e=t-1;else if(t===S)return S;else t===E&&(w.items.splice(e,1),--e)}}else if(t.isPair(w)){O=Object.freeze(O.concat(w));let e=await j(`key`,w.key,D,O);if(e===S)return S;e===E&&(w.key=null);let t=await j(`value`,w.value,D,O);if(t===S)return S;t===E&&(w.value=null)}}return k}function F(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function L(e,S,w,E){if(typeof w==`function`)return w(e,S,E);if(t.isMap(S))return w.Map?.(e,S,E);if(t.isSeq(S))return w.Seq?.(e,S,E);if(t.isPair(S))return w.Pair?.(e,S,E);if(t.isScalar(S))return w.Scalar?.(e,S,E);if(t.isAlias(S))return w.Alias?.(e,S,E)}function B(e,S,w){let E=S[S.length-1];if(t.isCollection(E))E.items[e]=w;else if(t.isPair(E))e===`key`?E.key=w:E.value=w;else if(t.isDocument(E))E.contents=w;else{let e=t.isAlias(E)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=D,e.visitAsync=k})),require_directives=__commonJSMin$1((e=>{var t=require_identity(),S=require_visit();let w={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},E=e=>e.replace(/[!,[\]{}]/g,e=>w[e]);var D=class e{constructor(t,S){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,S)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,S){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let w=t.trim().split(/[ \t]+/),E=w.shift();switch(E){case`%TAG`:{if(w.length!==2&&(S(0,`%TAG directive should contain exactly two parts`),w.length<2))return!1;let[e,t]=w;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,w.length!==1)return S(0,`%YAML directive should contain exactly one part`),!1;let[e]=w;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return S(6,`Unsupported YAML version ${e}`,t),!1}}default:return S(0,`Unknown directive ${E}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let S=e.slice(2,-1);return S===`!`||S===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),S)}let[,S,w]=e.match(/^(.*!)([^!]*)$/s);w||t(`The ${e} tag has no suffix`);let E=this.tags[S];if(E)try{return E+decodeURIComponent(w)}catch(e){return t(String(e)),null}return S===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,S]of Object.entries(this.tags))if(e.startsWith(S))return t+E(e.substring(S.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let w=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],E=Object.entries(this.tags),D;if(e&&E.length>0&&t.isNode(e.contents)){let w={};S.visit(e.contents,(e,S)=>{t.isNode(S)&&S.tag&&(w[S.tag]=!0)}),D=Object.keys(w)}else D=[];for(let[t,S]of E)t===`!!`&&S===`tag:yaml.org,2002:`||(!e||D.some(e=>e.startsWith(S)))&&w.push(`%TAG ${t} ${S}`);return w.join(`
|
|
2
2
|
`)}};D.defaultYaml={explicit:!1,version:`1.2`},D.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=D})),require_anchors=__commonJSMin$1((e=>{var t=require_identity(),S=require_visit();function w(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function E(e){let t=new Set;return S.visit(e,{Value(e,S){S.anchor&&t.add(S.anchor)}}),t}function D(e,t){for(let S=1;;++S){let w=`${e}${S}`;if(!t.has(w))return w}}function O(e,S){let w=[],O=new Map,k=null;return{onAnchor:t=>{w.push(t),k??=E(e);let O=D(S,k);return k.add(O),O},setAnchors:()=>{for(let e of w){let S=O.get(e);if(typeof S==`object`&&S.anchor&&(t.isScalar(S.node)||t.isCollection(S.node)))S.node.anchor=S.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:O}}e.anchorIsValid=w,e.anchorNames=E,e.createNodeAnchors=O,e.findNewAnchor=D})),require_applyReviver=__commonJSMin$1((e=>{function t(e,S,w,E){if(E&&typeof E==`object`)if(Array.isArray(E))for(let S=0,w=E.length;S<w;++S){let w=E[S],D=t(e,E,String(S),w);D===void 0?delete E[S]:D!==w&&(E[S]=D)}else if(E instanceof Map)for(let S of Array.from(E.keys())){let w=E.get(S),D=t(e,E,S,w);D===void 0?E.delete(S):D!==w&&E.set(S,D)}else if(E instanceof Set)for(let S of Array.from(E)){let w=t(e,E,S,S);w===void 0?E.delete(S):w!==S&&(E.delete(S),E.add(w))}else for(let[S,w]of Object.entries(E)){let D=t(e,E,S,w);D===void 0?delete E[S]:D!==w&&(E[S]=D)}return e.call(S,w,E)}e.applyReviver=t})),require_toJS=__commonJSMin$1((e=>{var t=require_identity();function S(e,w,E){if(Array.isArray(e))return e.map((e,t)=>S(e,String(t),E));if(e&&typeof e.toJSON==`function`){if(!E||!t.hasAnchor(e))return e.toJSON(w,E);let S={aliasCount:0,count:1,res:void 0};E.anchors.set(e,S),E.onCreate=e=>{S.res=e,delete E.onCreate};let D=e.toJSON(w,E);return E.onCreate&&E.onCreate(D),D}return typeof e==`bigint`&&!E?.keep?Number(e):e}e.toJS=S})),require_Node=__commonJSMin$1((e=>{var t=require_applyReviver(),S=require_identity(),w=require_toJS();e.NodeBase=class{constructor(e){Object.defineProperty(this,S.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:E,maxAliasCount:D,onAnchor:O,reviver:k}={}){if(!S.isDocument(e))throw TypeError(`A document argument is required`);let j={anchors:new Map,doc:e,keep:!0,mapAsMap:E===!0,mapKeyWarned:!1,maxAliasCount:typeof D==`number`?D:100},F=w.toJS(this,``,j);if(typeof O==`function`)for(let{count:e,res:t}of j.anchors.values())O(t,e);return typeof k==`function`?t.applyReviver(k,{"":F},``,F):F}}})),require_Alias=__commonJSMin$1((e=>{var t=require_anchors(),S=require_visit(),w=require_identity(),E=require_Node(),D=require_toJS(),O=class extends E.NodeBase{constructor(e){super(w.ALIAS),this.source=e,Object.defineProperty(this,`tag`,{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let E;t?.aliasResolveCache?E=t.aliasResolveCache:(E=[],S.visit(e,{Node:(e,t)=>{(w.isAlias(t)||w.hasAnchor(t))&&E.push(t)}}),t&&(t.aliasResolveCache=E));let D;for(let e of E){if(e===this)break;e.anchor===this.source&&(D=e)}return D}toJSON(e,t){if(!t)return{source:this.source};let{anchors:S,doc:w,maxAliasCount:E}=t,O=this.resolve(w,t);if(!O){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}let j=S.get(O);if(j||=(D.toJS(O,null,t),S.get(O)),j?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(E>=0&&(j.count+=1,j.aliasCount===0&&(j.aliasCount=k(w,O,S)),j.count*j.aliasCount>E))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`);return j.res}toString(e,S,w){let E=`*${this.source}`;if(e){if(t.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${E} `}return E}};function k(e,t,S){if(w.isAlias(t)){let w=t.resolve(e),E=S&&w&&S.get(w);return E?E.count*E.aliasCount:0}else if(w.isCollection(t)){let w=0;for(let E of t.items){let t=k(e,E,S);t>w&&(w=t)}return w}else if(w.isPair(t)){let w=k(e,t.key,S),E=k(e,t.value,S);return Math.max(w,E)}return 1}e.Alias=O})),require_Scalar=__commonJSMin$1((e=>{var t=require_identity(),S=require_Node(),w=require_toJS();let E=e=>!e||typeof e!=`function`&&typeof e!=`object`;var D=class extends S.NodeBase{constructor(e){super(t.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:w.toJS(this.value,e,t)}toString(){return String(this.value)}};D.BLOCK_FOLDED=`BLOCK_FOLDED`,D.BLOCK_LITERAL=`BLOCK_LITERAL`,D.PLAIN=`PLAIN`,D.QUOTE_DOUBLE=`QUOTE_DOUBLE`,D.QUOTE_SINGLE=`QUOTE_SINGLE`,e.Scalar=D,e.isScalarValue=E})),require_createNode=__commonJSMin$1((e=>{var t=require_Alias(),S=require_identity(),w=require_Scalar();let E=`tag:yaml.org,2002:`;function D(e,t,S){if(t){let e=S.filter(e=>e.tag===t),w=e.find(e=>!e.format)??e[0];if(!w)throw Error(`Tag ${t} not found`);return w}return S.find(t=>t.identify?.(e)&&!t.format)}function O(e,E,O){if(S.isDocument(e)&&(e=e.contents),S.isNode(e))return e;if(S.isPair(e)){let t=O.schema[S.MAP].createNode?.(O.schema,null,O);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:k,onAnchor:j,onTagObj:F,schema:L,sourceObjects:B}=O,H;if(k&&e&&typeof e==`object`){if(H=B.get(e),H)return H.anchor??=j(e),new t.Alias(H.anchor);H={anchor:null,node:null},B.set(e,H)}E?.startsWith(`!!`)&&(E=`tag:yaml.org,2002:`+E.slice(2));let q=D(e,E,L.tags);if(!q){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new w.Scalar(e);return H&&(H.node=t),t}q=e instanceof Map?L[S.MAP]:Symbol.iterator in Object(e)?L[S.SEQ]:L[S.MAP]}F&&(F(q),delete O.onTagObj);let J=q?.createNode?q.createNode(O.schema,e,O):typeof q?.nodeClass?.from==`function`?q.nodeClass.from(O.schema,e,O):new w.Scalar(e);return E?J.tag=E:q.default||(J.tag=q.tag),H&&(H.node=J),J}e.createNode=O})),require_Collection=__commonJSMin$1((e=>{var t=require_createNode(),S=require_identity(),w=require_Node();function E(e,S,w){let E=w;for(let e=S.length-1;e>=0;--e){let t=S[e];if(typeof t==`number`&&Number.isInteger(t)&&t>=0){let e=[];e[t]=E,E=e}else E=new Map([[t,E]])}return t.createNode(E,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}let D=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done;e.Collection=class extends w.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,`schema`,{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>S.isNode(t)||S.isPair(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(D(e))this.add(t);else{let[w,...D]=e,O=this.get(w,!0);if(S.isCollection(O))O.addIn(D,t);else if(O===void 0&&this.schema)this.set(w,E(this.schema,D,t));else throw Error(`Expected YAML collection at ${w}. Remaining path: ${D}`)}}deleteIn(e){let[t,...w]=e;if(w.length===0)return this.delete(t);let E=this.get(t,!0);if(S.isCollection(E))return E.deleteIn(w);throw Error(`Expected YAML collection at ${t}. Remaining path: ${w}`)}getIn(e,t){let[w,...E]=e,D=this.get(w,!0);return E.length===0?!t&&S.isScalar(D)?D.value:D:S.isCollection(D)?D.getIn(E,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!S.isPair(t))return!1;let w=t.value;return w==null||e&&S.isScalar(w)&&w.value==null&&!w.commentBefore&&!w.comment&&!w.tag})}hasIn(e){let[t,...w]=e;if(w.length===0)return this.has(t);let E=this.get(t,!0);return S.isCollection(E)?E.hasIn(w):!1}setIn(e,t){let[w,...D]=e;if(D.length===0)this.set(w,t);else{let e=this.get(w,!0);if(S.isCollection(e))e.setIn(D,t);else if(e===void 0&&this.schema)this.set(w,E(this.schema,D,t));else throw Error(`Expected YAML collection at ${w}. Remaining path: ${D}`)}}},e.collectionFromPath=E,e.isEmptyPath=D})),require_stringifyComment=__commonJSMin$1((e=>{let t=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function S(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}e.indentComment=S,e.lineComment=(e,t,w)=>e.endsWith(`
|
|
3
3
|
`)?S(w,t):w.includes(`
|
|
4
4
|
`)?`
|
|
@@ -469,7 +469,7 @@ To resolve the conflict:`,(0,w.getConflictResolutionRecipe)(E,e))),D=O):S.diag.w
|
|
|
469
469
|
`),B=Buffer.from(`\r`),H=Buffer.from(`-`);function q(){}let J=2e3,Y=16*1024,ee=0,te=1,ne=2;var ae=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,S){let w=t;for(;t<S;)switch(this.state){case 0:{let E=!1;for(;t<S;++t){if(this.byteCount===Y)return-1;++this.byteCount;let S=e[t];if(ge[S]!==1){if(S!==58||(this.name+=e.latin1Slice(w,t),this.name.length===0))return-1;++t,E=!0,this.state=1;break}}if(!E){this.name+=e.latin1Slice(w,t);break}}case 1:{let E=!1;for(;t<S;++t){if(this.byteCount===Y)return-1;++this.byteCount;let S=e[t];if(S!==32&&S!==9){w=t,E=!0,this.state=2;break}}if(!E)break}case 2:switch(this.crlf){case 0:for(;t<S;++t){if(this.byteCount===Y)return-1;++this.byteCount;let S=e[t];if(_e[S]!==1){if(S!==13)return-1;++this.crlf;break}}this.value+=e.latin1Slice(w,t++);break;case 1:if(this.byteCount===Y||(++this.byteCount,e[t++]!==10))return-1;++this.crlf;break;case 2:{if(this.byteCount===Y)return-1;++this.byteCount;let S=e[t];S===32||S===9?(w=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)),S===13?(++this.crlf,++t):(w=t,this.crlf=0,this.state=0,this.name=``,this.value=``));break}case 3:{if(this.byteCount===Y||(++this.byteCount,e[t++]!==10))return-1;let S=this.header;return this.reset(),this.cb(S),t}}break}return t}},oe=class extends S{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 se={push:(e,t)=>{},destroy:()=>{}};function ce(e,t){let S=e._writecb;e._writecb=null,t?e.destroy(t):S&&S()}function ue(e,t){return e}var de=class extends w{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 S=e.conType.params.boundary,w=typeof e.defParamCharset==`string`&&e.defParamCharset?k(e.defParamCharset):ue,J=e.defCharset||`utf8`,Y=e.preservePath,ee={autoDestroy:!0,emitClose:!0,highWaterMark:typeof e.fileHwm==`number`?e.fileHwm:void 0},te=e.limits,ne=te&&typeof te.fieldSize==`number`?te.fieldSize:1*1024*1024,ce=te&&typeof te.fileSize==`number`?te.fileSize:1/0,de=te&&typeof te.files==`number`?te.files:1/0,fe=te&&typeof te.fields==`number`?te.fields:1/0,me=te&&typeof te.parts==`number`?te.parts:1/0,ge=-1,_e=0,ve=0,ye=!1;this._fileEndsLeft=0,this._fileStream=void 0,this._complete=!1;let Ce=0,we,Te=0,De,je,Me,Pe,Ie=!1,Re=!1,ze=!1;this._hparser=null;let Be=new ae(e=>{this._hparser=null,ye=!1,Me=`text/plain`,De=J,je=`7bit`,Pe=void 0,Ie=!1;let t;if(!e[`content-disposition`]){ye=!0;return}let S=F(e[`content-disposition`][0],w);if(!S||S.type!==`form-data`){ye=!0;return}if(S.params&&(S.params.name&&(Pe=S.params.name),S.params[`filename*`]?t=S.params[`filename*`]:S.params.filename&&(t=S.params.filename),t!==void 0&&!Y&&(t=D(t))),e[`content-type`]){let t=j(e[`content-type`][0]);t&&(Me=`${t.type}/${t.subtype}`,t.params&&typeof t.params.charset==`string`&&(De=t.params.charset.toLowerCase()))}if(e[`content-transfer-encoding`]&&(je=e[`content-transfer-encoding`][0].toLowerCase()),Me===`application/octet-stream`||t!==void 0){if(ve===de){Re||(Re=!0,this.emit(`filesLimit`)),ye=!0;return}if(++ve,this.listenerCount(`file`)===0){ye=!0;return}Ce=0,this._fileStream=new oe(ee,this),++this._fileEndsLeft,this.emit(`file`,Pe,this._fileStream,{filename:t,encoding:je,mimeType:Me})}else{if(_e===fe){ze||(ze=!0,this.emit(`fieldsLimit`)),ye=!0;return}if(++_e,this.listenerCount(`field`)===0){ye=!0;return}we=[],Te=0}}),Ve=0,Ue=(e,t,S,w,E)=>{retrydata:for(;t;){if(this._hparser!==null){let e=this._hparser.push(t,S,w);if(e===-1){this._hparser=null,Be.reset(),this.emit(`error`,Error(`Malformed part header`));break}S=e}if(S===w)break;if(Ve!==0){if(Ve===1){switch(t[S]){case 45:Ve=2,++S;break;case 13:Ve=3,++S;break;default:Ve=0}if(S===w)return}if(Ve===2){if(Ve=0,t[S]===45){this._complete=!0,this._bparser=se;return}let e=this._writecb;this._writecb=q,Ue(!1,H,0,1,!1),this._writecb=e}else if(Ve===3)if(Ve=0,t[S]===10){if(++S,ge>=me||(this._hparser=Be,S===w))break;continue retrydata}else{let e=this._writecb;this._writecb=q,Ue(!1,B,0,1,!1),this._writecb=e}}if(!ye){if(this._fileStream){let e,D=Math.min(w-S,ce-Ce);E?e=t.slice(S,S+D):(e=Buffer.allocUnsafe(D),t.copy(e,0,S,S+D)),Ce+=e.length,Ce===ce?(e.length>0&&this._fileStream.push(e),this._fileStream.emit(`limit`),this._fileStream.truncated=!0,ye=!0):this._fileStream.push(e)||(this._writecb&&(this._fileStream._readcb=this._writecb),this._writecb=null)}else if(we!==void 0){let e,D=Math.min(w-S,ne-Te);E?e=t.slice(S,S+D):(e=Buffer.allocUnsafe(D),t.copy(e,0,S,S+D)),Te+=D,we.push(e),Te===ne&&(ye=!0,Ie=!0)}}break}if(e){if(Ve=1,this._fileStream)this._fileStream.push(null),this._fileStream=null;else if(we!==void 0){let e;switch(we.length){case 0:e=``;break;case 1:e=O(we[0],De,0);break;default:e=O(Buffer.concat(we,Te),De,0)}we=void 0,Te=0,this.emit(`field`,Pe,e,{nameTruncated:!1,valueTruncated:Ie,encoding:je,mimeType:Me})}++ge===me&&this.emit(`partsLimit`)}};this._bparser=new E(`\r\n--${S}`,Ue),this._writecb=null,this._finalcb=null,this.write(L)}static detect(e){return e.type===`multipart`&&e.subtype===`form-data`}_write(e,t,S){this._writecb=S,this._bparser.push(e,0),this._writecb&&ce(this)}_destroy(e,t){this._hparser=null,this._bparser=se,e||=me(this);let S=this._fileStream;S&&(this._fileStream=null,S.destroy(e)),t(e)}_final(e){if(this._bparser.destroy(),!this._complete)return e(Error(`Unexpected end of form`));this._fileEndsLeft?this._finalcb=fe.bind(null,this,e):fe(this,e)}};function fe(e,t,S){if(S)return t(S);S=me(e),t(S)}function me(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 ge=[0,0,0,0,0,0,0,0,0,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],_e=[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];t.exports=de})),require_urlencoded=__commonJSMin$1(((e,t)=>{let{Writable:S}=__require$1(`stream`),{getDecoder:w}=require_utils$1();var E=class extends S{constructor(e){let t={autoDestroy:!0,emitClose:!0,highWaterMark:typeof e.highWaterMark==`number`?e.highWaterMark:void 0};super(t);let S=e.defCharset||`utf8`;e.conType.params&&typeof e.conType.params.charset==`string`&&(S=e.conType.params.charset),this.charset=S;let E=e.limits;this.fieldSizeLimit=E&&typeof E.fieldSize==`number`?E.fieldSize:1*1024*1024,this.fieldsLimit=E&&typeof E.fields==`number`?E.fields:1/0,this.fieldNameSizeLimit=E&&typeof E.fieldNameSize==`number`?E.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=w(S)}static detect(e){return e.type===`application`&&e.subtype===`x-www-form-urlencoded`}_write(e,t,S){if(this._fields>=this.fieldsLimit)return S();let w=0,E=e.length;if(this._lastPos=0,this._byte!==-2){if(w=D(this,e,w,E),w===-1)return S(Error(`Malformed urlencoded form`));if(w>=E)return S();this._inKey?++this._bytesKey:++this._bytesVal}main:for(;w<E;)if(this._inKey){for(w=O(this,e,w,E);w<E;){switch(e[w]){case 61:this._lastPos<w&&(this._key+=e.latin1Slice(this._lastPos,w)),this._lastPos=++w,this._key=this._decoder(this._key,this._encode),this._encode=0,this._inKey=!1;continue main;case 38:if(this._lastPos<w&&(this._key+=e.latin1Slice(this._lastPos,w)),this._lastPos=++w,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`),S();continue;case 43:this._lastPos<w&&(this._key+=e.latin1Slice(this._lastPos,w)),this._key+=` `,this._lastPos=w+1;break;case 37:if(this._encode===0&&(this._encode=1),this._lastPos<w&&(this._key+=e.latin1Slice(this._lastPos,w)),this._lastPos=w+1,this._byte=-1,w=D(this,e,w+1,E),w===-1)return S(Error(`Malformed urlencoded form`));if(w>=E)return S();++this._bytesKey,w=O(this,e,w,E);continue}++w,++this._bytesKey,w=O(this,e,w,E)}this._lastPos<w&&(this._key+=e.latin1Slice(this._lastPos,w))}else{for(w=k(this,e,w,E);w<E;){switch(e[w]){case 38:if(this._lastPos<w&&(this._val+=e.latin1Slice(this._lastPos,w)),this._lastPos=++w,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`),S();continue main;case 43:this._lastPos<w&&(this._val+=e.latin1Slice(this._lastPos,w)),this._val+=` `,this._lastPos=w+1;break;case 37:if(this._encode===0&&(this._encode=1),this._lastPos<w&&(this._val+=e.latin1Slice(this._lastPos,w)),this._lastPos=w+1,this._byte=-1,w=D(this,e,w+1,E),w===-1)return S(Error(`Malformed urlencoded form`));if(w>=E)return S();++this._bytesVal,w=k(this,e,w,E);continue}++w,++this._bytesVal,w=k(this,e,w,E)}this._lastPos<w&&(this._val+=e.latin1Slice(this._lastPos,w))}S()}_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 D(e,t,S,w){if(S>=w)return w;if(e._byte===-1){let E=j[t[S++]];if(E===-1)return-1;if(E>=8&&(e._encode=2),S<w){let w=j[t[S++]];if(w===-1)return-1;e._inKey?e._key+=String.fromCharCode((E<<4)+w):e._val+=String.fromCharCode((E<<4)+w),e._byte=-2,e._lastPos=S}else e._byte=E}else{let w=j[t[S++]];if(w===-1)return-1;e._inKey?e._key+=String.fromCharCode((e._byte<<4)+w):e._val+=String.fromCharCode((e._byte<<4)+w),e._byte=-2,e._lastPos=S}return S}function O(e,t,S,w){if(e._bytesKey>e.fieldNameSizeLimit){for(e._keyTrunc||e._lastPos<S&&(e._key+=t.latin1Slice(e._lastPos,S-1)),e._keyTrunc=!0;S<w;++S){let w=t[S];if(w===61||w===38)break;++e._bytesKey}e._lastPos=S}return S}function k(e,t,S,w){if(e._bytesVal>e.fieldSizeLimit){for(e._valTrunc||e._lastPos<S&&(e._val+=t.latin1Slice(e._lastPos,S-1)),e._valTrunc=!0;S<w&&t[S]!==38;++S)++e._bytesVal;e._lastPos=S}return S}let j=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-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=E})),require_lib=__commonJSMin$1(((e,t)=>{let{parseContentType:S}=require_utils$1();function w(e){let t=e.headers,w=S(t[`content-type`]);if(!w)throw Error(`Malformed content type`);for(let S of E){if(!S.detect(w))continue;let E={limits:e.limits,headers:t,conType:w,highWaterMark:void 0,fileHwm:void 0,defCharset:void 0,defParamCharset:void 0,preservePath:!1};return e.highWaterMark&&(E.highWaterMark=e.highWaterMark),e.fileHwm&&(E.fileHwm=e.fileHwm),E.defCharset=e.defCharset,E.defParamCharset=e.defParamCharset,E.preservePath=e.preservePath,new S(E)}throw Error(`Unsupported content type: ${t[`content-type`]}`)}let E=[require_multipart(),require_urlencoded()].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 w(e)}}));const WINDOWS_1252_EXTRA={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:`Ÿ`},WINDOWS_1252_REVERSE={};for(let[e,t]of Object.entries(WINDOWS_1252_EXTRA))WINDOWS_1252_REVERSE[t]=Number.parseInt(e,10);let _utf8Decoder;function utf8Decoder(){if(globalThis.TextDecoder!==void 0)return _utf8Decoder??=new globalThis.TextDecoder(`utf-8`)}const CHUNK=32*1024,REPLACEMENT=65533;function textDecode(e,t=`utf-8`){switch(t.toLowerCase()){case`utf-8`:case`utf8`:{let t=utf8Decoder();return t?t.decode(e):decodeUTF8(e)}case`utf-16le`:return decodeUTF16LE(e);case`us-ascii`:case`ascii`:return decodeASCII(e);case`latin1`:case`iso-8859-1`:return decodeLatin1(e);case`windows-1252`:return decodeWindows1252(e);default:throw RangeError(`Encoding '${t}' not supported`)}}function flushChunk(e,t){t.length!==0&&(e.push(String.fromCharCode.apply(null,t)),t.length=0)}function pushCodeUnit(e,t,S){t.push(S),t.length>=CHUNK&&flushChunk(e,t)}function pushCodePoint(e,t,S){if(S<=65535){pushCodeUnit(e,t,S);return}S-=65536,pushCodeUnit(e,t,55296+(S>>10)),pushCodeUnit(e,t,56320+(S&1023))}function decodeUTF8(e){let t=[],S=[],w=0;for(e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191&&(w=3);w<e.length;){let E=e[w];if(E<=127){pushCodeUnit(t,S,E),w++;continue}if(E<194||E>244){pushCodeUnit(t,S,REPLACEMENT),w++;continue}if(E<=223){if(w+1>=e.length){pushCodeUnit(t,S,REPLACEMENT),w++;continue}let D=e[w+1];if((D&192)!=128){pushCodeUnit(t,S,REPLACEMENT),w++;continue}pushCodeUnit(t,S,(E&31)<<6|D&63),w+=2;continue}if(E<=239){if(w+2>=e.length){pushCodeUnit(t,S,REPLACEMENT),w++;continue}let D=e[w+1],O=e[w+2];if(!((D&192)==128&&(O&192)==128&&!(E===224&&D<160)&&!(E===237&&D>=160))){pushCodeUnit(t,S,REPLACEMENT),w++;continue}pushCodeUnit(t,S,(E&15)<<12|(D&63)<<6|O&63),w+=3;continue}if(w+3>=e.length){pushCodeUnit(t,S,REPLACEMENT),w++;continue}let D=e[w+1],O=e[w+2],k=e[w+3];if(!((D&192)==128&&(O&192)==128&&(k&192)==128&&!(E===240&&D<144)&&!(E===244&&D>143))){pushCodeUnit(t,S,REPLACEMENT),w++;continue}pushCodePoint(t,S,(E&7)<<18|(D&63)<<12|(O&63)<<6|k&63),w+=4}return flushChunk(t,S),t.join(``)}function decodeUTF16LE(e){let t=[],S=[],w=e.length,E=0;for(;E+1<w;){let D=e[E]|e[E+1]<<8;if(E+=2,D>=55296&&D<=56319){if(E+1<w){let w=e[E]|e[E+1]<<8;w>=56320&&w<=57343?(pushCodeUnit(t,S,D),pushCodeUnit(t,S,w),E+=2):pushCodeUnit(t,S,REPLACEMENT)}else pushCodeUnit(t,S,REPLACEMENT);continue}if(D>=56320&&D<=57343){pushCodeUnit(t,S,REPLACEMENT);continue}pushCodeUnit(t,S,D)}return E<w&&pushCodeUnit(t,S,REPLACEMENT),flushChunk(t,S),t.join(``)}function decodeASCII(e){let t=[];for(let S=0;S<e.length;S+=CHUNK){let w=Math.min(e.length,S+CHUNK),E=Array(w-S);for(let t=S,D=0;t<w;t++,D++)E[D]=e[t]&127;t.push(String.fromCharCode.apply(null,E))}return t.join(``)}function decodeLatin1(e){let t=[];for(let S=0;S<e.length;S+=CHUNK){let w=Math.min(e.length,S+CHUNK),E=Array(w-S);for(let t=S,D=0;t<w;t++,D++)E[D]=e[t];t.push(String.fromCharCode.apply(null,E))}return t.join(``)}function decodeWindows1252(e){let t=[],S=``;for(let w=0;w<e.length;w++){let E=e[w],D=E>=128&&E<=159?WINDOWS_1252_EXTRA[E]:void 0;S+=D??String.fromCharCode(E),S.length>=CHUNK&&(t.push(S),S=``)}return S&&t.push(S),t.join(``)}function dv(e){return new DataView(e.buffer,e.byteOffset)}const UINT8={len:1,get(e,t){return dv(e).getUint8(t)},put(e,t,S){return dv(e).setUint8(t,S),t+1}},UINT16_LE={len:2,get(e,t){return dv(e).getUint16(t,!0)},put(e,t,S){return dv(e).setUint16(t,S,!0),t+2}},UINT16_BE={len:2,get(e,t){return dv(e).getUint16(t)},put(e,t,S){return dv(e).setUint16(t,S),t+2}},UINT32_LE={len:4,get(e,t){return dv(e).getUint32(t,!0)},put(e,t,S){return dv(e).setUint32(t,S,!0),t+4}},UINT32_BE={len:4,get(e,t){return dv(e).getUint32(t)},put(e,t,S){return dv(e).setUint32(t,S),t+4}},INT32_BE={len:4,get(e,t){return dv(e).getInt32(t)},put(e,t,S){return dv(e).setInt32(t,S),t+4}},UINT64_LE={len:8,get(e,t){return dv(e).getBigUint64(t,!0)},put(e,t,S){return dv(e).setBigUint64(t,S,!0),t+8}};var StringType=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){return textDecode(e.subarray(t,t+this.len),this.encoding)}};const defaultMessages=`End-Of-Stream`;var EndOfStreamError=class extends Error{constructor(){super(defaultMessages),this.name=`EndOfStreamError`}},AbortError=class extends Error{constructor(e=`The operation was aborted`){super(e),this.name=`AbortError`}},AbstractStreamReader=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){let S=await this.read(e,t);return this.peekQueue.push(e.subarray(0,S)),S}async read(e,t=!1){if(e.length===0)return 0;let S=this.readFromPeekBuffer(e);if(this.endOfStream||(S+=await this.readRemainderFromStream(e.subarray(S),t)),S===0&&!t)throw new EndOfStreamError;return S}readFromPeekBuffer(e){let t=e.length,S=0;for(;this.peekQueue.length>0&&t>0;){let w=this.peekQueue.pop();if(!w)throw Error(`peekData should be defined`);let E=Math.min(w.length,t);e.set(w.subarray(0,E),S),S+=E,t-=E,E<w.length&&this.peekQueue.push(w.subarray(E))}return S}async readRemainderFromStream(e,t){let S=0;for(;S<e.length&&!this.endOfStream;){if(this.interrupted)throw new AbortError;let w=await this.readFromStream(e.subarray(S),t);if(w===0)break;S+=w}if(!t&&S<e.length)throw new EndOfStreamError;return S}},WebStreamReader=class extends AbstractStreamReader{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}},WebStreamByobReader=class extends WebStreamReader{async readFromStream(e,t){if(e.length===0)return 0;let S=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return S.done&&(this.endOfStream=S.done),S.value?(e.set(S.value),S.value.length):0}},WebStreamDefaultReader=class extends AbstractStreamReader{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){let S=Math.min(t.length,e.length);return e.set(t.subarray(0,S)),S<t.length?this.buffer=t.subarray(S):this.buffer=null,S}async readFromStream(e,t){if(e.length===0)return 0;let S=0;for(this.buffer&&(S+=this.writeChunk(e,this.buffer));S<e.length&&!this.endOfStream;){let t=await this.reader.read();if(t.done){this.endOfStream=!0;break}t.value&&(S+=this.writeChunk(e.subarray(S),t.value))}if(!t&&S===0&&this.endOfStream)throw new EndOfStreamError;return S}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function makeWebStreamReader(e){try{let t=e.getReader({mode:`byob`});return t instanceof ReadableStreamDefaultReader?new WebStreamDefaultReader(t):new WebStreamByobReader(t)}catch(t){if(t instanceof TypeError)return new WebStreamDefaultReader(e.getReader());throw t}}var AbstractTokenizer=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 S=new Uint8Array(e.len);if(await this.readBuffer(S,{position:t})<e.len)throw new EndOfStreamError;return e.get(S,0)}async peekToken(e,t=this.position){let S=new Uint8Array(e.len);if(await this.peekBuffer(S,{position:t})<e.len)throw new EndOfStreamError;return e.get(S,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new EndOfStreamError;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new EndOfStreamError;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()}};const maxBufferSize=256e3;var ReadStreamTokenizer=class extends AbstractTokenizer{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let S=this.normalizeOptions(e,t),w=S.position-this.position;if(w>0)return await this.ignore(w),this.readBuffer(e,t);if(w<0)throw Error("`options.position` must be equal or greater than `tokenizer.position`");if(S.length===0)return 0;let E=await this.streamReader.read(e.subarray(0,S.length),S.mayBeLess);if(this.position+=E,(!t||!t.mayBeLess)&&E<S.length)throw new EndOfStreamError;return E}async peekBuffer(e,t){let S=this.normalizeOptions(e,t),w=0;if(S.position){let t=S.position-this.position;if(t>0){let E=new Uint8Array(S.length+t);return w=await this.peekBuffer(E,{mayBeLess:S.mayBeLess}),e.set(E.subarray(t)),w-t}if(t<0)throw Error(`Cannot peek from a negative offset in a stream`)}if(S.length>0){try{w=await this.streamReader.peek(e.subarray(0,S.length),S.mayBeLess)}catch(e){if(t?.mayBeLess&&e instanceof EndOfStreamError)return 0;throw e}if(!S.mayBeLess&&w<S.length)throw new EndOfStreamError}return w}async ignore(e){if(e<0)throw RangeError(`ignore length must be ≥ 0 bytes`);let t=Math.min(maxBufferSize,e),S=new Uint8Array(t),w=0;for(;w<e;){let E=e-w,D=await this.readBuffer(S,{length:Math.min(t,E)});if(D<0)return D;w+=D}return w}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}},BufferTokenizer=class extends AbstractTokenizer{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 S=await this.peekBuffer(e,t);return this.position+=S,S}async peekBuffer(e,t){let S=this.normalizeOptions(e,t),w=Math.min(this.uint8Array.length-S.position,S.length);if(!S.mayBeLess&&w<S.length)throw new EndOfStreamError;return e.set(this.uint8Array.subarray(S.position,S.position+w)),w}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}},BlobTokenizer=class extends AbstractTokenizer{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 S=await this.peekBuffer(e,t);return this.position+=S,S}async peekBuffer(e,t){let S=this.normalizeOptions(e,t),w=Math.min(this.blob.size-S.position,S.length);if(!S.mayBeLess&&w<S.length)throw new EndOfStreamError;let E=await this.blob.slice(S.position,S.position+w).arrayBuffer();return e.set(new Uint8Array(E)),w}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};function fromWebStream(e,t){let S=makeWebStreamReader(e),w=t??{},E=w.onClose;return w.onClose=async()=>{if(await S.close(),E)return E()},new ReadStreamTokenizer(S,w)}function fromBuffer(e,t){return new BufferTokenizer(e,t)}function fromBlob(e,t){return new BlobTokenizer(e,t)}const Signature={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},DataDescriptor={get(e){return{signature:UINT32_LE.get(e,0),compressedSize:UINT32_LE.get(e,8),uncompressedSize:UINT32_LE.get(e,12)}},len:16},LocalFileHeaderToken={get(e){let t=UINT16_LE.get(e,6);return{signature:UINT32_LE.get(e,0),minVersion:UINT16_LE.get(e,4),dataDescriptor:!!(t&8),compressedMethod:UINT16_LE.get(e,8),compressedSize:UINT32_LE.get(e,18),uncompressedSize:UINT32_LE.get(e,22),filenameLength:UINT16_LE.get(e,26),extraFieldLength:UINT16_LE.get(e,28),filename:null}},len:30},EndOfCentralDirectoryRecordToken={get(e){return{signature:UINT32_LE.get(e,0),nrOfThisDisk:UINT16_LE.get(e,4),nrOfThisDiskWithTheStart:UINT16_LE.get(e,6),nrOfEntriesOnThisDisk:UINT16_LE.get(e,8),nrOfEntriesOfSize:UINT16_LE.get(e,10),sizeOfCd:UINT32_LE.get(e,12),offsetOfStartOfCd:UINT32_LE.get(e,16),zipFileCommentLength:UINT16_LE.get(e,20)}},len:22},FileHeader={get(e){let t=UINT16_LE.get(e,8);return{signature:UINT32_LE.get(e,0),minVersion:UINT16_LE.get(e,6),dataDescriptor:!!(t&8),compressedMethod:UINT16_LE.get(e,10),compressedSize:UINT32_LE.get(e,20),uncompressedSize:UINT32_LE.get(e,24),filenameLength:UINT16_LE.get(e,28),extraFieldLength:UINT16_LE.get(e,30),fileCommentLength:UINT16_LE.get(e,32),relativeOffsetOfLocalHeader:UINT32_LE.get(e,42),filename:null}},len:46};var import_src$7=__toESM$1(require_src$15(),1);function signatureToArray(e){let t=new Uint8Array(UINT32_LE.len);return UINT32_LE.put(t,0,e),t}const debug=(0,import_src$7.default)(`tokenizer:inflate`),syncBufferSize=256*1024,ddSignatureArray=signatureToArray(Signature.DataDescriptor),eocdSignatureBytes=signatureToArray(Signature.EndOfCentralDirectory);var ZipHandler=class e{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(syncBufferSize)}async isZip(){return await this.peekSignature()===Signature.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(UINT32_LE)}async findEndOfCentralDirectoryLocator(){let e=this.tokenizer,t=Math.min(16*1024,e.fileInfo.size),S=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(S,{position:e.fileInfo.size-t});for(let w=S.length-4;w>=0;w--)if(S[w]===eocdSignatureBytes[0]&&S[w+1]===eocdSignatureBytes[1]&&S[w+2]===eocdSignatureBytes[2]&&S[w+3]===eocdSignatureBytes[3])return e.fileInfo.size-t+w;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){debug(`Cannot reading central-directory without random-read support`);return}debug(`Reading central-directory...`);let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){debug(`Central-directory 32-bit signature found`);let S=await this.tokenizer.readToken(EndOfCentralDirectoryRecordToken,t),w=[];this.tokenizer.setPosition(S.offsetOfStartOfCd);for(let e=0;e<S.nrOfEntriesOfSize;++e){let t=await this.tokenizer.readToken(FileHeader);if(t.signature!==Signature.CentralFileHeader)throw Error(`Expected Central-File-Header signature`);t.filename=await this.tokenizer.readToken(new StringType(t.filenameLength,`utf-8`)),await this.tokenizer.ignore(t.extraFieldLength),await this.tokenizer.ignore(t.fileCommentLength),w.push(t),debug(`Add central-directory file-entry: n=${e+1}/${w.length}: filename=${w[e].filename}`)}return this.tokenizer.setPosition(e),w}this.tokenizer.setPosition(e)}async unzip(e){let t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let S=!1;do{let t=await this.readLocalFileHeader();if(!t)break;let w=e(t);S=!!w.stop;let E;if(await this.tokenizer.ignore(t.extraFieldLength),t.dataDescriptor&&t.compressedSize===0){let e=[],S=syncBufferSize;debug(`Compressed-file-size unknown, scanning for next data-descriptor-signature....`);let E=-1;for(;E<0&&S===syncBufferSize;){S=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),E=indexOf(this.syncBuffer.subarray(0,S),ddSignatureArray);let t=E>=0?E:S;if(w.handler){let S=new Uint8Array(t);await this.tokenizer.readBuffer(S),e.push(S)}else await this.tokenizer.ignore(t)}debug(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),w.handler&&await this.inflate(t,mergeArrays(e),w.handler)}else w.handler?(debug(`Reading compressed-file-data: ${t.compressedSize} bytes`),E=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(E),await this.inflate(t,E,w.handler)):(debug(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(debug(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor&&(await this.tokenizer.readToken(DataDescriptor)).signature!==134695760)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-DataDescriptor.len}`)}while(!S)}async iterateOverCentralDirectory(e,t){for(let S of e){let e=t(S);if(e.handler){this.tokenizer.setPosition(S.relativeOffsetOfLocalHeader);let t=await this.readLocalFileHeader();if(t){await this.tokenizer.ignore(t.extraFieldLength);let w=new Uint8Array(S.compressedSize);await this.tokenizer.readBuffer(w),await this.inflate(t,w,e.handler)}}if(e.stop)break}}async inflate(t,S,w){if(t.compressedMethod===0)return w(S);if(t.compressedMethod!==8)throw Error(`Unsupported ZIP compression method: ${t.compressedMethod}`);return debug(`Decompress filename=${t.filename}, compressed-size=${S.length}`),w(await e.decompressDeflateRaw(S))}static async decompressDeflateRaw(e){let t=new ReadableStream({start(t){t.enqueue(e),t.close()}}),S=new DecompressionStream(`deflate-raw`),w=t.pipeThrough(S);try{let e=await new Response(w).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(UINT32_LE);if(e===Signature.LocalFileHeader){let e=await this.tokenizer.readToken(LocalFileHeaderToken);return e.filename=await this.tokenizer.readToken(new StringType(e.filenameLength,`utf-8`)),e}if(e===Signature.CentralFileHeader)return!1;throw Error(e===3759263696?`Encrypted ZIP`:`Unexpected signature`)}};function indexOf(e,t){let S=e.length,w=t.length;if(w>S)return-1;for(let E=0;E<=S-w;E++){let S=!0;for(let D=0;D<w;D++)if(e[E+D]!==t[D]){S=!1;break}if(S)return E}return-1}function mergeArrays(e){let t=e.reduce((e,t)=>e+t.length,0),S=new Uint8Array(t),w=0;for(let t of e)S.set(t,w),w+=t.length;return S}var GzipHandler=class{constructor(e){this.tokenizer=e}inflate(){let e=this.tokenizer;return new ReadableStream({async pull(t){let S=new Uint8Array(1024),w=await e.readBuffer(S,{mayBeLess:!0});if(w===0){t.close();return}t.enqueue(S.subarray(0,w))}}).pipeThrough(new DecompressionStream(`gzip`))}};const objectToString=Object.prototype.toString,uint8ArrayStringified=`[object Uint8Array]`;function isType(e,t,S){return e?e.constructor===t?!0:objectToString.call(e)===S:!1}function isUint8Array(e){return isType(e,Uint8Array,uint8ArrayStringified)}function assertUint8Array(e){if(!isUint8Array(e))throw TypeError(`Expected \`Uint8Array\`, got \`${typeof e}\``)}function concatUint8Arrays(e,t){if(e.length===0)return new Uint8Array;t??=e.reduce((e,t)=>e+t.length,0);let S=new Uint8Array(t),w=0;for(let t of e)assertUint8Array(t),S.set(t,w),w+=t.length;return S}const cachedDecoders={utf8:new globalThis.TextDecoder(`utf8`)},cachedEncoder=new globalThis.TextEncoder,byteToHexLookupTable=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function getUintBE(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 stringToBytes(e,t){if(t===`utf-16le`){let t=[];for(let S=0;S<e.length;S++){let w=e.charCodeAt(S);t.push(w&255,w>>8&255)}return t}if(t===`utf-16be`){let t=[];for(let S=0;S<e.length;S++){let w=e.charCodeAt(S);t.push(w>>8&255,w&255)}return t}return[...e].map(e=>e.charCodeAt(0))}function tarHeaderChecksumMatches(e,t=0){let S=Number.parseInt(new StringType(6).get(e,148).replace(/\0.*$/v,``).trim(),8);if(Number.isNaN(S))return!1;let w=256;for(let S=t;S<t+148;S++)w+=e[S];for(let S=t+156;S<t+512;S++)w+=e[S];return S===w}const uint32SyncSafeToken={get:(e,t)=>e[t+3]&127|(e[t+2]&127)<<7|(e[t+1]&127)<<14|(e[t]&127)<<21,len:4},extensions=`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(`,`),mimeTypes=`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(`,`),maximumUntrustedSkipSizeInBytes=16*1024*1024;var ParserHardLimitError=class extends Error{};function getSafeBound(e,t,S){if(!Number.isFinite(e)||e<0||e>t)throw new ParserHardLimitError(`${S} has invalid size ${e} (maximum ${t} bytes)`);return e}async function safeIgnore(e,t,{maximumLength:S=maximumUntrustedSkipSizeInBytes,reason:w=`skip`}={}){let E=getSafeBound(t,S,w);await e.ignore(E)}async function safeReadBuffer(e,t,S,{maximumLength:w=t.length,reason:E=`read`}={}){let D=getSafeBound(S?.length??t.length,w,E);return e.readBuffer(t,{...S,length:D})}function checkBytes(e,t,S){S={offset:0,...S};for(let[w,E]of t.entries())if(S.mask){if(E!==(S.mask[w]&e[w+S.offset]))return!1}else if(E!==e[w+S.offset])return!1;return!0}function hasUnknownFileSize(e){let t=e.fileInfo.size;return!Number.isFinite(t)||t===2**53-1}function hasExceededUnknownSizeScanBudget(e,t,S){return hasUnknownFileSize(e)&&e.position-t>S}const maximumZipEntrySizeInBytes=1024*1024,maximumZipEntryCount=1024,maximumZipBufferedReadSizeInBytes=2**31-1,maximumZipTextEntrySizeInBytes=maximumZipEntrySizeInBytes,recoverableZipErrorMessages=new Set([`Unexpected signature`,`Encrypted ZIP`,`Expected Central-File-Header signature`]),recoverableZipErrorMessagePrefixes=[`ZIP entry count exceeds `,`Unsupported ZIP compression method:`,`ZIP entry compressed data exceeds `,`ZIP entry decompressed data exceeds `,`Expected data-descriptor-signature at position `],recoverableZipErrorCodes=new Set([`Z_BUF_ERROR`,`Z_DATA_ERROR`,`ERR_INVALID_STATE`]);async function decompressDeflateRawWithLimit(e,{maximumLength:t=maximumZipEntrySizeInBytes}={}){let S=new ReadableStream({start(t){t.enqueue(e),t.close()}}).pipeThrough(new DecompressionStream(`deflate-raw`)).getReader(),w=[],E=0;try{for(;;){let{done:e,value:D}=await S.read();if(e)break;if(E+=D.length,E>t)throw await S.cancel(),Error(`ZIP entry decompressed data exceeds ${t} bytes`);w.push(D)}}finally{S.releaseLock()}let D=new Uint8Array(E),O=0;for(let e of w)D.set(e,O),O+=e.length;return D}function mergeByteChunks(e,t){let S=new Uint8Array(t),w=0;for(let t of e)S.set(t,w),w+=t.length;return S}function getMaximumZipBufferedReadLength(e){let t=e.fileInfo.size,S=Number.isFinite(t)?Math.max(0,t-e.position):2**53-1;return Math.min(S,maximumZipBufferedReadSizeInBytes)}function isRecoverableZipError(e){if(e instanceof EndOfStreamError||e instanceof ParserHardLimitError)return!0;if(!(e instanceof Error))return!1;if(recoverableZipErrorMessages.has(e.message)||recoverableZipErrorCodes.has(e.code))return!0;for(let t of recoverableZipErrorMessagePrefixes)if(e.message.startsWith(t))return!0;return!1}function canReadZipEntryForDetection(e,t=maximumZipEntrySizeInBytes){let S=[e.compressedSize,e.uncompressedSize];for(let e of S)if(!Number.isFinite(e)||e<0||e>t)return!1;return!0}function createIWorkZipDetectionState(){return{hasDocumentEntry:!1,hasMasterSlideEntry:!1,hasTablesEntry:!1,hasCalculationEngineEntry:!1}}function updateIWorkZipDetectionStateFromFilename(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 getIWorkFileTypeFromZipEntries(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 getFileTypeFromMimeType(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 createOpenXmlZipDetectionState(){return{hasContentTypesEntry:!1,hasParsedContentTypesEntry:!1,isParsingContentTypes:!1,hasUnparseableContentTypes:!1,hasWordDirectory:!1,hasPresentationDirectory:!1,hasSpreadsheetDirectory:!1,hasThreeDimensionalModelEntry:!1}}function updateOpenXmlZipDetectionStateFromFilename(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 getOpenXmlFileTypeFromDirectoryNames(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 getOpenXmlFileTypeFromZipEntries(e){if(!(!e.hasContentTypesEntry||e.hasUnparseableContentTypes||e.isParsingContentTypes||e.hasParsedContentTypesEntry))return getOpenXmlFileTypeFromDirectoryNames(e)}function getOpenXmlMimeTypeFromContentTypesXml(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 S=e.slice(0,t),w=S.lastIndexOf(`"`);return S.slice(w+1)}const zipDataDescriptorSignature=134695760,zipDataDescriptorLengthInBytes=16,zipDataDescriptorOverlapLengthInBytes=zipDataDescriptorLengthInBytes-1;function findZipDataDescriptorOffset(e,t){if(e.length<zipDataDescriptorLengthInBytes)return-1;let S=e.length-zipDataDescriptorLengthInBytes;for(let w=0;w<=S;w++)if(UINT32_LE.get(e,w)===zipDataDescriptorSignature&&UINT32_LE.get(e,w+8)===t+w)return w;return-1}async function readZipDataDescriptorEntryWithLimit(e,{shouldBuffer:t,maximumLength:S=maximumZipEntrySizeInBytes}={}){let{syncBuffer:w}=e,{length:E}=w,D=[],O=0;for(;;){let k=await e.tokenizer.peekBuffer(w,{mayBeLess:!0}),j=findZipDataDescriptorOffset(w.subarray(0,k),O),F=j>=0?0:k===E?Math.min(zipDataDescriptorOverlapLengthInBytes,k-1):0,L=j>=0?j:k-F;if(L===0)break;if(O+=L,O>S)throw Error(`ZIP entry compressed data exceeds ${S} bytes`);if(t){let t=new Uint8Array(L);await e.tokenizer.readBuffer(t),D.push(t)}else await e.tokenizer.ignore(L);if(j>=0)break}if(hasUnknownFileSize(e.tokenizer)||(e.knownSizeDescriptorScannedBytes+=O),t)return mergeByteChunks(D,O)}function getRemainingZipScanBudget(e,t){return hasUnknownFileSize(e.tokenizer)?Math.max(0,maximumUntrustedSkipSizeInBytes-(e.tokenizer.position-t)):Math.max(0,maximumZipEntrySizeInBytes-e.knownSizeDescriptorScannedBytes)}async function readZipEntryData(e,t,{shouldBuffer:S,maximumDescriptorLength:w=maximumZipEntrySizeInBytes}={}){if(t.dataDescriptor&&t.compressedSize===0)return readZipDataDescriptorEntryWithLimit(e,{shouldBuffer:S,maximumLength:w});if(!S){await safeIgnore(e.tokenizer,t.compressedSize,{maximumLength:hasUnknownFileSize(e.tokenizer)?maximumZipEntrySizeInBytes:e.tokenizer.fileInfo.size,reason:`ZIP entry compressed data`});return}let E=getMaximumZipBufferedReadLength(e.tokenizer);if(!Number.isFinite(t.compressedSize)||t.compressedSize<0||t.compressedSize>E)throw Error(`ZIP entry compressed data exceeds ${E} bytes`);let D=new Uint8Array(t.compressedSize);return await e.tokenizer.readBuffer(D),D}ZipHandler.prototype.inflate=async function(e,t,S){if(e.compressedMethod===0)return S(t);if(e.compressedMethod!==8)throw Error(`Unsupported ZIP compression method: ${e.compressedMethod}`);return S(await decompressDeflateRawWithLimit(t,{maximumLength:maximumZipEntrySizeInBytes}))},ZipHandler.prototype.unzip=async function(e){let t=!1,S=0,w=this.tokenizer.position;this.knownSizeDescriptorScannedBytes=0;do{if(hasExceededUnknownSizeScanBudget(this.tokenizer,w,16777216))throw new ParserHardLimitError(`ZIP stream probing exceeds ${maximumUntrustedSkipSizeInBytes} bytes`);let E=await this.readLocalFileHeader();if(!E)break;if(S++,S>maximumZipEntryCount)throw Error(`ZIP entry count exceeds ${maximumZipEntryCount}`);let D=e(E);t=!!D.stop,await this.tokenizer.ignore(E.extraFieldLength);let O=await readZipEntryData(this,E,{shouldBuffer:!!D.handler,maximumDescriptorLength:Math.min(maximumZipEntrySizeInBytes,getRemainingZipScanBudget(this,w))});if(D.handler&&await this.inflate(E,O,D.handler),E.dataDescriptor){let e=new Uint8Array(zipDataDescriptorLengthInBytes);if(await this.tokenizer.readBuffer(e),UINT32_LE.get(e,0)!==zipDataDescriptorSignature)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-e.length}`)}if(hasExceededUnknownSizeScanBudget(this.tokenizer,w,16777216))throw new ParserHardLimitError(`ZIP stream probing exceeds ${maximumUntrustedSkipSizeInBytes} bytes`)}while(!t)};async function detectZip(e){let t,S=createOpenXmlZipDetectionState(),w=createIWorkZipDetectionState();try{await new ZipHandler(e).unzip(e=>{if(updateOpenXmlZipDetectionStateFromFilename(S,e.filename),updateIWorkZipDetectionStateFromFilename(w,e.filename),w.hasDocumentEntry&&(w.hasMasterSlideEntry||w.hasTablesEntry))return t=getIWorkFileTypeFromZipEntries(w),{stop:!0};let E=e.filename===`[Content_Types].xml`,D=getOpenXmlFileTypeFromZipEntries(S);if(!E&&D)return t=D,{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 canReadZipEntryForDetection(e,maximumZipTextEntrySizeInBytes)?{async handler(e){t=getFileTypeFromMimeType(new TextDecoder(`utf-8`).decode(e).trim())},stop:!0}:{};case`[Content_Types].xml`:return S.hasContentTypesEntry=!0,canReadZipEntryForDetection(e,maximumZipTextEntrySizeInBytes)?(S.isParsingContentTypes=!0,{async handler(e){let w=getOpenXmlMimeTypeFromContentTypesXml(new TextDecoder(`utf-8`).decode(e));w&&(t=getFileTypeFromMimeType(w)),S.hasParsedContentTypesEntry=!0,S.isParsingContentTypes=!1},stop:!0}):(S.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(!isRecoverableZipError(e))throw e;S.isParsingContentTypes&&(S.isParsingContentTypes=!1,S.hasUnparseableContentTypes=!0),!t&&e instanceof EndOfStreamError&&!S.hasContentTypesEntry&&(t=getOpenXmlFileTypeFromDirectoryNames(S))}let E=hasUnknownFileSize(e)&&w.hasDocumentEntry&&!w.hasMasterSlideEntry&&!w.hasTablesEntry&&!w.hasCalculationEngineEntry?void 0:getIWorkFileTypeFromZipEntries(w);return t??getOpenXmlFileTypeFromZipEntries(S)??E??{ext:`zip`,mime:`application/zip`}}const maximumEbmlDocumentTypeSizeInBytes=64,maximumEbmlElementPayloadSizeInBytes=1024*1024,maximumEbmlElementCount=256;async function detectEbml(e){async function t(){let t=await e.peekNumber(UINT8),S=128,w=0;for(;(t&S)===0&&S!==0;)++w,S>>=1;let E=new Uint8Array(w+1);return await safeReadBuffer(e,E,void 0,{maximumLength:E.length,reason:`EBML field`}),E}async function S(){let e=await t(),S=await t();S[0]^=128>>S.length-1;let w=Math.min(6,S.length),E=new DataView(e.buffer),D=new DataView(S.buffer,S.length-w,w);return{id:getUintBE(E),len:getUintBE(D)}}async function w(t){let w=0;for(;t>0;){if(w++,w>maximumEbmlElementCount||hasExceededUnknownSizeScanBudget(e,D,16777216))return;let E=e.position,O=await S();if(O.id===17026){if(O.len>maximumEbmlDocumentTypeSizeInBytes)return;let t=getSafeBound(O.len,maximumEbmlDocumentTypeSizeInBytes,`EBML DocType`);return(await e.readToken(new StringType(t))).replaceAll(/\0.*$/gv,``)}if(hasUnknownFileSize(e)&&(!Number.isFinite(O.len)||O.len<0||O.len>maximumEbmlElementPayloadSizeInBytes)||(await safeIgnore(e,O.len,{maximumLength:hasUnknownFileSize(e)?maximumEbmlElementPayloadSizeInBytes:e.fileInfo.size,reason:`EBML payload`}),--t,e.position<=E))return}}let E=await S(),D=e.position;switch(await w(E.len)){case`webm`:return{ext:`webm`,mime:`video/webm`};case`matroska`:return{ext:`mkv`,mime:`video/matroska`};default:}}const maximumPngChunkCount=512,maximumPngStreamScanBudgetInBytes=16*1024*1024,maximumPngChunkSizeInBytes=1024*1024;function isPngAncillaryChunk(e){return(e.codePointAt(0)&32)!=0}async function detectPng(e){let t={ext:`png`,mime:`image/png`},S={ext:`apng`,mime:`image/apng`};await e.ignore(8);async function w(){return{length:await e.readToken(INT32_BE),type:await e.readToken(new StringType(4,`latin1`))}}let E=hasUnknownFileSize(e),D=e.position,O=0,k=!1;do{if(O++,O>maximumPngChunkCount||hasExceededUnknownSizeScanBudget(e,D,maximumPngStreamScanBudgetInBytes))break;let j=e.position,F=await w();if(F.length<0)return;if(F.type===`IHDR`){if(F.length!==13)return;k=!0}switch(F.type){case`IDAT`:return t;case`acTL`:return S;default:if(!k&&F.type!==`CgBI`)return;if(E&&F.length>maximumPngChunkSizeInBytes)return k&&isPngAncillaryChunk(F.type)?t:void 0;try{await safeIgnore(e,F.length+4,{maximumLength:E?maximumPngChunkSizeInBytes+4:e.fileInfo.size,reason:`PNG chunk payload`})}catch(e){if(!E&&(e instanceof ParserHardLimitError||e instanceof EndOfStreamError))return t;throw e}}if(e.position<=j)break}while(e.position+8<e.fileInfo.size);return t}const maximumAsfHeaderObjectCount=512,maximumAsfHeaderPayloadSizeInBytes=1024*1024;async function detectAsf(e){let t=!1;try{async function S(){let t=new Uint8Array(16);return await safeReadBuffer(e,t,void 0,{maximumLength:t.length,reason:`ASF header GUID`}),{id:t,size:Number(await e.readToken(UINT64_LE))}}await safeIgnore(e,30,{maximumLength:30,reason:`ASF header prelude`});let w=hasUnknownFileSize(e),E=e.position,D=0;for(;e.position+24<e.fileInfo.size&&(D++,!(D>maximumAsfHeaderObjectCount||hasExceededUnknownSizeScanBudget(e,E,16777216)));){let E=e.position,D=await S(),O=D.size-24;if(!Number.isFinite(O)||O<0){t=!0;break}if(checkBytes(D.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 safeReadBuffer(e,t,void 0,{maximumLength:t.length,reason:`ASF stream type GUID`}),checkBytes(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(checkBytes(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(w&&O>maximumAsfHeaderPayloadSizeInBytes){t=!0;break}if(await safeIgnore(e,O,{maximumLength:w?maximumAsfHeaderPayloadSizeInBytes:e.fileInfo.size,reason:`ASF header payload`}),e.position<=E){t=!0;break}}}catch(S){if(S instanceof EndOfStreamError||S instanceof ParserHardLimitError)hasUnknownFileSize(e)&&(t=!0);else throw S}if(!t)return{ext:`asf`,mime:`application/vnd.ms-asf`}}const reasonableDetectionSizeInBytes=4100,maximumMpegOffsetTolerance=reasonableDetectionSizeInBytes-2,maximumNestedGzipDetectionSizeInBytes=maximumUntrustedSkipSizeInBytes,maximumNestedGzipProbeDepth=1,unknownSizeGzipProbeTimeoutInMilliseconds=100,maximumId3HeaderSizeInBytes=maximumUntrustedSkipSizeInBytes,maximumTiffTagCount=512,maximumDetectionReentryCount=256,maximumTiffStreamIfdOffsetInBytes=1024*1024,maximumTiffIfdOffsetInBytes=maximumUntrustedSkipSizeInBytes;function normalizeSampleSize(e){return Number.isFinite(e)?Math.max(1,Math.trunc(e)):reasonableDetectionSizeInBytes}function normalizeMpegOffsetTolerance(e){return Number.isFinite(e)?Math.max(0,Math.min(maximumMpegOffsetTolerance,Math.trunc(e))):0}function getKnownFileSizeOrMaximum(e){return Number.isFinite(e)?Math.max(0,e):2**53-1}function importAtRuntime(e){return import(e)}function toDefaultStream(e){return e.pipeThrough(new TransformStream)}function readWithSignal(e,t){return t===void 0?e.read():(t.throwIfAborted(),Promise.race([e.read(),new Promise((S,w)=>{t.addEventListener(`abort`,()=>{w(t.reason),e.cancel(t.reason).catch(()=>{})},{once:!0})})]))}function createByteLimitedReadableStream(e,t){let S=e.getReader(),w=0,E=!1,D=!1,O=async e=>{E||D||(D=!0,await S.cancel(e))};return new ReadableStream({async pull(e){if(w>=t){e.close(),await O();return}let{done:D,value:k}=await S.read();if(D||!k){E=!0,e.close();return}let j=t-w;if(k.length>j){e.enqueue(k.subarray(0,j)),w+=j,e.close(),await O();return}e.enqueue(k),w+=k.length},async cancel(e){await O(e)}})}var FileTypeParser=class e{constructor(e){let t=normalizeMpegOffsetTolerance(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 fromWebStream(toDefaultStream(e),this.getTokenizerOptions())}async parseTokenizer(e,t=0){this.detectionReentryCount=t;let S=e.position;for(let t of this.detectors){let w;try{w=await t.detect(e)}catch(e){if(e instanceof EndOfStreamError||e instanceof ParserHardLimitError)return;throw e}if(w)return w;if(S!==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(fromBuffer(t,this.getTokenizerOptions()))}async fromBlob(e){this.options.signal?.throwIfAborted();let t=fromBlob(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:S}]=await Promise.all([importAtRuntime(`node:fs/promises`),importAtRuntime(`strtok3`)]),w=await t.open(e,t.constants.O_RDONLY|t.constants.O_NONBLOCK),E=await w.stat();if(!E.isFile()){await w.close();return}let D=new S(w,{...this.getTokenizerOptions(),fileInfo:{path:e,size:E.size}});return this.fromTokenizer(D)}async toDetectionStream(e,t){this.options.signal?.throwIfAborted();let S=normalizeSampleSize(t?.sampleSize??4100),w,E=!1,D=e.getReader(),O=[],k=0;try{for(;k<S;){let{value:e,done:t}=await readWithSignal(D,this.options.signal);if(t||!e){E=!0;break}O.push(e),k+=e.length}if(!E&&k===S){let{value:e,done:t}=await readWithSignal(D,this.options.signal);t||!e?E=!0:(O.push(e),k+=e.length)}}finally{D.releaseLock()}if(k>0){let e=O.length===1?O[0]:concatUint8Arrays(O);try{w=await this.fromBuffer(e.subarray(0,S))}catch(e){if(!(e instanceof EndOfStreamError))throw e;w=void 0}!E&&w?.ext===`pages`&&(w={ext:`zip`,mime:`application/zip`})}let j=new TransformStream({start(e){for(let t of O)e.enqueue(t)},transform(e,t){t.enqueue(e)}}),F=e.pipeThrough(j);return F.fileType=w,F}async detectGzip(t){if(this.gzipProbeDepth>=maximumNestedGzipProbeDepth)return{ext:`gz`,mime:`application/gzip`};let S=createByteLimitedReadableStream(new GzipHandler(t).inflate(),maximumNestedGzipDetectionSizeInBytes),w=hasUnknownFileSize(t),E,D,O,k;if(w){let t=new AbortController;E=setTimeout(()=>{t.abort(new DOMException(`Operation timed out after ${unknownSizeGzipProbeTimeoutInMilliseconds} ms`,`TimeoutError`))},unknownSizeGzipProbeTimeoutInMilliseconds),D=this.options.signal===void 0?t.signal:AbortSignal.any([this.options.signal,t.signal]),O=new e({...this.options,signal:D}),O.gzipProbeDepth=this.gzipProbeDepth+1}else this.gzipProbeDepth++;try{k=await(O??this).fromStream(S)}catch(e){if(e?.name===`AbortError`&&D?.reason?.name!==`TimeoutError`)throw e}finally{clearTimeout(E),w||this.gzipProbeDepth--}return k?.ext===`tar`?{ext:`tar.gz`,mime:`application/gzip`}:{ext:`gz`,mime:`application/gzip`}}check(e,t){return checkBytes(this.buffer,e,t)}checkString(e,t){return this.check(stringToBytes(e,t?.encoding),t)}detectConfident=async e=>{if(this.buffer=new Uint8Array(reasonableDetectionSizeInBytes),e.fileInfo.size===void 0&&(e.fileInfo.size=2**53-1),this.tokenizer=e,hasUnknownFileSize(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>=maximumDetectionReentryCount?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 safeIgnore(e,6,{maximumLength:6,reason:`ID3 header prefix`});let t=await e.readToken(uint32SyncSafeToken),S=hasUnknownFileSize(e);if(!Number.isFinite(t)||t<0||S&&(t>maximumId3HeaderSizeInBytes||e.position+t>maximumId3HeaderSizeInBytes))return;if(e.position+t>e.fileInfo.size)return S?void 0:{ext:`mp3`,mime:`audio/mpeg`};try{await safeIgnore(e,t,{maximumLength:S?maximumId3HeaderSizeInBytes:e.fileInfo.size,reason:`ID3 payload`})}catch(e){if(e instanceof EndOfStreamError)return;throw e}return this.detectionReentryCount>=maximumDetectionReentryCount?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 detectZip(e);if(this.checkString(`OggS`)){await e.ignore(28);let t=new Uint8Array(8);return await e.readBuffer(t),checkBytes(t,[79,112,117,115,72,101,97,100])?{ext:`opus`,mime:`audio/ogg; codecs=opus`}:checkBytes(t,[128,116,104,101,111,114,97])?{ext:`ogv`,mime:`video/ogg`}:checkBytes(t,[1,118,105,100,101,111,0])?{ext:`ogm`,mime:`video/ogg`}:checkBytes(t,[127,70,76,65,67])?{ext:`oga`,mime:`audio/ogg`}:checkBytes(t,[83,112,101,101,120,32,32])?{ext:`spx`,mime:`audio/ogg`}:checkBytes(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 detectEbml(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=UINT32_BE.get(this.buffer,4),t=UINT16_BE.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 StringType(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 StringType(13,`ascii`))===`debian-binary`?{ext:`deb`,mime:`application/x-deb`}:{ext:`ar`,mime:`application/x-unix-archive`};if(this.checkString(`WEBVTT`)&&[`
|
|
470
470
|
`,`\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 detectPng(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 StringType(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
|
|
471
471
|
`))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 detectAsf(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 StringType(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})&&tarHeaderChecksumMatches(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
|
|
472
|
-
`,{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(reasonableDetectionSizeInBytes);let t=getKnownFileSizeOrMaximum(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?UINT16_BE:UINT16_LE);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?UINT16_BE:UINT16_LE);if(!(t>maximumTiffTagCount)&&!(hasUnknownFileSize(this.tokenizer)&&2+t*12>maximumTiffIfdOffsetInBytes))for(let S=0;S<t;++S){let t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){let t={ext:`tif`,mime:`image/tiff`},S=(e?UINT16_BE:UINT16_LE).get(this.buffer,2),w=(e?UINT32_BE:UINT32_LE).get(this.buffer,4);if(S===42){if(w>=6){if(this.checkString(`CR`,{offset:8}))return{ext:`cr2`,mime:`image/x-canon-cr2`};if(w>=8){let t=(e?UINT16_BE:UINT16_LE).get(this.buffer,8),S=(e?UINT16_BE:UINT16_LE).get(this.buffer,10);if(t===28&&S===254||t===31&&S===11)return{ext:`nef`,mime:`image/x-nikon-nef`}}}if(hasUnknownFileSize(this.tokenizer)&&w>maximumTiffStreamIfdOffsetInBytes)return t;let S=hasUnknownFileSize(this.tokenizer)?maximumTiffIfdOffsetInBytes:this.tokenizer.fileInfo.size;try{await safeIgnore(this.tokenizer,w,{maximumLength:S,reason:`TIFF IFD offset`})}catch(e){if(e instanceof EndOfStreamError)return;throw e}let E;try{E=await this.readTiffIFD(e)}catch(e){if(e instanceof EndOfStreamError)return;throw e}return E??t}if(S===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`}}}};const supportedExtensions=new Set(extensions),supportedMimeTypes=new Set(mimeTypes);async function fileTypeFromFile(e,t){return new FileTypeParser(t).fromFile(e)}const DEFAULT_FS={writeFile:(e,t,S)=>writeFile(e,t,S),rename:(e,t)=>rename(e,t)};async function atomicWriteFile(e,t,S={}){let w=S.fs??DEFAULT_FS,E=`${e}.tmp.${crypto.randomUUID()}`;try{await w.writeFile(E,t,{encoding:`utf-8`,mode:S.mode??420}),await w.rename(E,e)}catch(e){try{unlinkSync(E)}catch{}throw e}}var FileLockTimeoutError=class extends Error{code=`LOCK_TIMEOUT`;lockPath;timeoutMs;constructor(e,t){super(`Could not acquire file lock at ${e} within ${t}ms`),this.name=`FileLockTimeoutError`,this.lockPath=e,this.timeoutMs=t}};const sleep=e=>new Promise(t=>{setTimeout(t,e)});async function withFileLock(e,t,S={}){let w=S.timeoutMs??5e3,E=S.retryIntervalMs??25,D=w*2,O=Date.now()+w;for(;;){let k;try{k=openSync(e,`wx`,384)}catch(t){if(t.code!==`EEXIST`)throw t;let k
|
|
472
|
+
`,{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(reasonableDetectionSizeInBytes);let t=getKnownFileSizeOrMaximum(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?UINT16_BE:UINT16_LE);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?UINT16_BE:UINT16_LE);if(!(t>maximumTiffTagCount)&&!(hasUnknownFileSize(this.tokenizer)&&2+t*12>maximumTiffIfdOffsetInBytes))for(let S=0;S<t;++S){let t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){let t={ext:`tif`,mime:`image/tiff`},S=(e?UINT16_BE:UINT16_LE).get(this.buffer,2),w=(e?UINT32_BE:UINT32_LE).get(this.buffer,4);if(S===42){if(w>=6){if(this.checkString(`CR`,{offset:8}))return{ext:`cr2`,mime:`image/x-canon-cr2`};if(w>=8){let t=(e?UINT16_BE:UINT16_LE).get(this.buffer,8),S=(e?UINT16_BE:UINT16_LE).get(this.buffer,10);if(t===28&&S===254||t===31&&S===11)return{ext:`nef`,mime:`image/x-nikon-nef`}}}if(hasUnknownFileSize(this.tokenizer)&&w>maximumTiffStreamIfdOffsetInBytes)return t;let S=hasUnknownFileSize(this.tokenizer)?maximumTiffIfdOffsetInBytes:this.tokenizer.fileInfo.size;try{await safeIgnore(this.tokenizer,w,{maximumLength:S,reason:`TIFF IFD offset`})}catch(e){if(e instanceof EndOfStreamError)return;throw e}let E;try{E=await this.readTiffIFD(e)}catch(e){if(e instanceof EndOfStreamError)return;throw e}return E??t}if(S===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`}}}};const supportedExtensions=new Set(extensions),supportedMimeTypes=new Set(mimeTypes);async function fileTypeFromFile(e,t){return new FileTypeParser(t).fromFile(e)}const STALE_TMP_AGE_MS=3e4,DEFAULT_FS={writeFile:(e,t,S)=>writeFile(e,t,S),rename:(e,t)=>rename(e,t)};async function sweepStaleTmps(e){try{let t=dirname(e),S=`${basename(e)}.tmp.`,w=Date.now()-STALE_TMP_AGE_MS,E=await readdir(t);await Promise.all(E.map(async e=>{if(!e.startsWith(S))return;let E=join(t,e);try{(await stat$1(E)).mtimeMs<w&&await unlink(E)}catch{}}))}catch{}}function sweepStaleTmpsSync(e){try{let t=dirname(e),S=`${basename(e)}.tmp.`,w=Date.now()-STALE_TMP_AGE_MS;for(let e of readdirSync(t)){if(!e.startsWith(S))continue;let E=join(t,e);try{statSync(E).mtimeMs<w&&unlinkSync(E)}catch{}}}catch{}}async function atomicWriteFile(e,t,S={}){await sweepStaleTmps(e);let w=S.fs??DEFAULT_FS,E=`${e}.tmp.${crypto.randomUUID()}`;try{await w.writeFile(E,t,{encoding:`utf-8`,mode:S.mode??420}),await w.rename(E,e)}catch(e){try{unlinkSync(E)}catch{}throw e}}function atomicWriteFileSync(e,t,S={}){sweepStaleTmpsSync(e);let w=`${e}.tmp.${crypto.randomUUID()}`;try{writeFileSync(w,t,{encoding:`utf-8`,mode:S.mode??420}),renameSync(w,e)}catch(e){try{unlinkSync(w)}catch{}throw e}}var FileLockTimeoutError=class extends Error{code=`LOCK_TIMEOUT`;lockPath;timeoutMs;constructor(e,t){super(`Could not acquire file lock at ${e} within ${t}ms`),this.name=`FileLockTimeoutError`,this.lockPath=e,this.timeoutMs=t}};const sleep=e=>new Promise(t=>{setTimeout(t,e)});async function withFileLock(e,t,S={}){let w=S.timeoutMs??5e3,E=S.retryIntervalMs??25,D=w*2,O=Date.now()+w;for(;;){let k;try{k=openSync(e,`wx`,384)}catch(t){if(t.code!==`EEXIST`)throw t;let k;try{let t=statSync(e);k=Date.now()-t.mtimeMs}catch{continue}let j=!1;if(k>D){S.onWarn?.(`cleared stale file lock`,{lockPath:e,ageMs:k,staleThresholdMs:D});try{unlinkSync(e),j=!0}catch{}}if(j)continue;if(Date.now()>=O)throw new FileLockTimeoutError(e,w);await sleep(E);continue}try{return await t()}finally{try{closeSync(k)}catch{}try{unlinkSync(e)}catch{}}}}function sleepSyncBusy(e){let t=Date.now()+e;for(;Date.now()<t;);}function withFileLockSync(e,t,S={}){let w=S.timeoutMs??5e3,E=S.retryIntervalMs??25,D=w*2,O=Date.now()+w;for(;;){let k;try{k=openSync(e,`wx`,384)}catch(t){if(t.code!==`EEXIST`)throw t;let k;try{let t=statSync(e);k=Date.now()-t.mtimeMs}catch{continue}let j=!1;if(k>D){S.onWarn?.(`cleared stale file lock`,{lockPath:e,ageMs:k,staleThresholdMs:D});try{unlinkSync(e),j=!0}catch{}}if(j)continue;if(Date.now()>=O)throw new FileLockTimeoutError(e,w);sleepSyncBusy(E);continue}try{return t()}finally{try{closeSync(k)}catch{}try{unlinkSync(e)}catch{}}}}const CONFIG_FILENAME=`config.yml`,USER_CONFIG_FILENAME=`global.yml`;function schemaUrl(e){return`https://unpkg.com/@inkeep/open-knowledge@latest/dist/schemas/${CONFIG_SCHEMA_MAJOR_PATH}/${e===`user`?`config.user.schema.json`:e===`project-local`?`config.project-local.schema.json`:`config.project.schema.json`}`}function defaultFirstWriteHeader(e){return`# yaml-language-server: $schema=${schemaUrl(e)}\n`}function resolveConfigPath(e,t,S){if(e===`user`)return resolve(S??homedir(),`.ok`,USER_CONFIG_FILENAME);let w=isAbsolute(t)?t:resolve(t);return e===`project-local`?resolve(w,`.ok`,LOCAL_DIR,CONFIG_FILENAME):resolve(w,`.ok`,CONFIG_FILENAME)}function err(e){return{ok:!1,error:e}}function ok(e){return{ok:!0,...e}}async function writeConfigPatch(e){return withConfigSpan(`config.patch`,{"config.scope":e.scope,"config.transport":`fs`},async t=>{let S=await writeConfigPatchInner(e);return t.setAttribute(`config.outcome`,S.ok?`success`:`rejected`),S.ok||t.setAttribute(`config.error.code`,S.error.code),S})}async function writeConfigPatchInner(e){let{cwd:t,scope:S,patch:w,homedirOverride:E}=e,D=resolveConfigPath(S,t,E),O=validatePatchScopes(w,S);if(O!==null)return err(O);try{await mkdir(dirname(D),{recursive:!0})}catch(e){return err({code:`WRITE_ERROR`,detail:`Could not create parent directory for ${D}: ${e instanceof Error?e.message:String(e)}`})}try{return await withFileLock(`${D}.lock`,()=>writeConfigPatchLocked(e,D))}catch(e){if(e instanceof FileLockTimeoutError)return err({code:`WRITE_ERROR`,detail:e.message});throw e}}async function writeConfigPatchLocked(e,t){let{patch:S,scope:w,firstWriteHeader:E}=e,D=``,O=!1;if(existsSync(t)){O=!0;try{D=readFileSync(t,`utf-8`)}catch(e){return err({code:`WRITE_ERROR`,detail:`Could not read existing config: ${e instanceof Error?e.message:String(e)}`})}}let k=(0,import_dist$1.parseDocument)(D);if(k.errors.length>0)return err({code:`YAML_PARSE`,detail:k.errors.map(e=>e.message).join(`; `)});if(k.contents===null)k.contents=k.createNode({});else if(!(0,import_dist$1.isMap)(k.contents))return err({code:`YAML_PARSE`,detail:`Top-level YAML value must be a mapping (object), got ${(0,import_dist$1.isSeq)(k.contents)?`sequence`:`scalar`}`});let j=applyPatchToDocument(k,S),F=k.toJSON(),L=withConfigSpanSync(`config.validate`,{"config.scope":w,"config.validation.layer":`L2`},e=>{let t=ConfigSchema$1.safeParse(F);if(e.setAttribute(`config.outcome`,t.success?`success`:`rejected`),!t.success)for(let e of t.error.issues)addConfigSpanEvent(`config.validation.issue`,{"issue.path":e.path.map(e=>String(e)).join(`.`),"issue.message":e.message});return t});if(!L.success)return err({code:`SCHEMA_INVALID`,issues:L.error.issues.map(toConfigIssue)});let B=k.toString();if(!O){let e=E===void 0?defaultFirstWriteHeader(w):E??``;e.length>0&&(B=`${e.endsWith(`
|
|
473
473
|
`)?e:`${e}\n`}${B}`)}try{await mkdir(dirname(t),{recursive:!0})}catch(e){return err({code:`WRITE_ERROR`,detail:`Could not create parent directory for ${t}: ${e instanceof Error?e.message:String(e)}`})}try{await atomicWriteFile(t,B)}catch(e){return err({code:`WRITE_ERROR`,detail:`Could not write ${t}: ${e instanceof Error?e.message:String(e)}`})}return ok({effective:L.data,appliedPaths:j,path:t,created:!O})}function buildSchemaInvalidError(e,t,S,w){return e.success?{code:`UNKNOWN`,message:`unexpected success in error path`}:{code:`SCHEMA_INVALID`,issues:e.error.issues.map(e=>{let E=e.path.map(e=>typeof e==`symbol`?String(e):e),D=locateIssue({file:w,source:S,doc:t,path:E});return{path:E,message:e.message,issueCode:e.code,...D===void 0?{}:{source:D}}})}}function attemptSideline(e,t,S){let w=`${e}.invalid-${t.replace(/[:.]/g,`-`)}`;try{return renameSync(e,w),w}catch(t){S(`[config] Could not sideline invalid config file ${e} → ${w}: ${t instanceof Error?t.message:String(t)}. File left in place; using schema defaults.`);return}}function readConfigSafely(e){let{absPath:t,sideline:S=!0,timestamp:w=new Date().toISOString()}=e,E=e.warn??(e=>console.warn(e)),D=ConfigSchema$1.parse({});if(!existsSync(t))return{valid:!0,value:D,source:void 0};let O;try{O=readFileSync(t,`utf-8`)}catch(e){let S=e instanceof Error?e.message:String(e);return E(`[config] Could not read ${t}: ${S}. Using schema defaults.`),{valid:!1,value:D,error:{code:`UNKNOWN`,message:`Read failed: ${S}`}}}let k=(0,import_dist$1.parseDocument)(O);if(k.errors.length>0){let e=k.errors.map(e=>e.message).join(`; `);E(`[config] ${t} contains invalid YAML (${e}). Using schema defaults.`+(S?``:` Pass-through mode: file left in place.`));let O=S?attemptSideline(t,w,E):void 0;return{valid:!1,value:D,error:{code:`YAML_PARSE`,detail:e},...O===void 0?{}:{sidelinedTo:O}}}let j=k.toJSON()??{},F=ConfigSchema$1.safeParse(j);if(!F.success){let e=buildSchemaInvalidError(F,k,O,t);E(`[config] ${t} fails schema validation (${F.error.issues.length} issue(s)). Using schema defaults.`+(S?``:` Pass-through mode: file left in place.`));let j=S?attemptSideline(t,w,E):void 0;return{valid:!1,value:D,error:e,...j===void 0?{}:{sidelinedTo:j}}}return{valid:!0,value:F.data,source:t}}var require_dist$1=__commonJSMin$1(((e,t)=>{function S(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}let w=new Int32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]);function E(e){if(Buffer.isBuffer(e))return e;if(typeof e==`number`)return Buffer.alloc(e);if(typeof e==`string`)return Buffer.from(e);throw Error(`input must be buffer, number, or string, received `+typeof e)}function D(e){let t=E(4);return t.writeInt32BE(e,0),t}function O(e,t){e=E(e),Buffer.isBuffer(t)&&(t=t.readUInt32BE(0));let S=~~t^-1;for(var D=0;D<e.length;D++)S=w[(S^e[D])&255]^S>>>8;return S^-1}function k(){return D(O.apply(null,arguments))}k.signed=function(){return O.apply(null,arguments)},k.unsigned=function(){return O.apply(null,arguments)>>>0},t.exports=S(k)})),require_yazl=__commonJSMin$1((e=>{var t=__require$1(`fs`),S=__require$1(`stream`).Transform,w=__require$1(`stream`).PassThrough,E=__require$1(`zlib`),D=__require$1(`util`),O=__require$1(`events`).EventEmitter,k=__require$1(`events`).errorMonitor,j=require_dist$1();e.ZipFile=F,D.inherits(F,O);function F(){this.outputStream=new w,this.entries=[],this.outputStreamCursor=0,this.ended=!1,this.allDone=!1,this.forceZip64Eocd=!1,this.errored=!1,this.on(k,function(){this.errored=!0})}F.prototype.addFile=function(e,S,w){var E=this;if(S=se(S,!1),w??={},!ee(E)){var D=new ue(S,!1,w);E.entries.push(D),t.stat(e,function(S,O){if(S)return E.emit(`error`,S);if(!O.isFile())return E.emit(`error`,Error(`not a file: `+e));D.uncompressedSize=O.size,w.mtime??D.setLastModDate(O.mtime),w.mode??D.setFileAttributesMode(O.mode),D.setFileDataPumpFunction(function(){var S=t.createReadStream(e);D.state=ue.FILE_DATA_IN_PROGRESS,S.on(`error`,function(e){E.emit(`error`,e)}),H(E,D,S)}),J(E)})}},F.prototype.addReadStream=function(e,t,S){this.addReadStreamLazy(t,S,function(t){t(null,e)})},F.prototype.addReadStreamLazy=function(e,t,S){var w=this;if(typeof t==`function`&&(S=t,t=null),t??={},e=se(e,!1),!ee(w)){var E=new ue(e,!1,t);w.entries.push(E),E.setFileDataPumpFunction(function(){E.state=ue.FILE_DATA_IN_PROGRESS,S(function(e,t){if(e)return w.emit(`error`,e);H(w,E,t)})}),J(w)}},F.prototype.addBuffer=function(e,t,S){var w=this;if(t=se(t,!1),e.length>1073741823)throw Error(`buffer too large: `+e.length+` > 1073741823`);if(S??={},S.size!=null)throw Error(`options.size not allowed`);if(ee(w))return;var D=new ue(t,!1,S);D.uncompressedSize=e.length,D.crc32=j.unsigned(e),D.crcAndFileSizeKnown=!0,w.entries.push(D),D.compressionLevel===0?O(e):E.deflateRaw(e,{level:D.compressionLevel},function(e,t){O(t)});function O(e){D.compressedSize=e.length,D.setFileDataPumpFunction(function(){B(w,e),B(w,D.getDataDescriptor()),D.state=ue.FILE_DATA_DONE,setImmediate(function(){J(w)})}),J(w)}},F.prototype.addEmptyDirectory=function(e,t){var S=this;if(e=se(e,!0),t??={},t.size!=null)throw Error(`options.size not allowed`);if(t.compress!=null)throw Error(`options.compress not allowed`);if(t.compressionLevel!=null)throw Error(`options.compressionLevel not allowed`);if(!ee(S)){var w=new ue(e,!0,t);S.entries.push(w),w.setFileDataPumpFunction(function(){B(S,w.getDataDescriptor()),w.state=ue.FILE_DATA_DONE,J(S)}),J(S)}};var L=Ge([80,75,5,6]);F.prototype.end=function(e,t){if(typeof e==`function`&&(t=e,e=null),e??={},!this.ended&&(this.ended=!0,!this.errored)){if(this.calculatedTotalSizeCallback=t,this.forceZip64Eocd=!!e.forceZip64Format,e.comment){if(typeof e.comment==`string`?this.comment=Ue(e.comment):this.comment=e.comment,this.comment.length>65535)throw Error(`comment is too large`);if(Ke(this.comment,L))throw Error(`comment contains end of central directory record signature`)}else this.comment=ce;J(this)}};function B(e,t){e.outputStream.write(t),e.outputStreamCursor+=t.length}function H(e,t,S){var D=new ze,O=new Re,k=t.compressionLevel===0?new w:new E.DeflateRaw({level:t.compressionLevel}),j=new Re;S.pipe(D).pipe(O).pipe(k).pipe(j).pipe(e.outputStream,{end:!1}),j.on(`end`,function(){if(t.crc32=D.crc32,t.uncompressedSize==null)t.uncompressedSize=O.byteCount;else if(t.uncompressedSize!==O.byteCount)return e.emit(`error`,Error(`file data stream has unexpected number of bytes`));t.compressedSize=j.byteCount,e.outputStreamCursor+=t.compressedSize,B(e,t.getDataDescriptor()),t.state=ue.FILE_DATA_DONE,J(e)})}function q(e){if(e.compress!=null&&e.compressionLevel!=null&&!!e.compress!=!!e.compressionLevel)throw Error(`conflicting settings for compress and compressionLevel`);return e.compressionLevel==null?e.compress===!1?0:6:e.compressionLevel}function J(e){if(e.allDone||e.errored)return;if(e.ended&&e.calculatedTotalSizeCallback!=null){var t=Y(e);t!=null&&(e.calculatedTotalSizeCallback(t),e.calculatedTotalSizeCallback=null)}var S=w();function w(){for(var t=0;t<e.entries.length;t++){var S=e.entries[t];if(S.state<ue.FILE_DATA_DONE)return S}return null}if(S!=null){if(S.state<ue.READY_TO_PUMP_FILE_DATA||S.state===ue.FILE_DATA_IN_PROGRESS)return;S.relativeOffsetOfLocalHeader=e.outputStreamCursor,B(e,S.getLocalFileHeader()),S.doFileDataPump()}else e.ended&&(e.offsetOfStartOfCentralDirectory=e.outputStreamCursor,e.entries.forEach(function(t){B(e,t.getCentralDirectoryRecord())}),B(e,oe(e)),e.outputStream.end(),e.allDone=!0)}function Y(e){for(var t=0,S=0,w=0;w<e.entries.length;w++){var E=e.entries[w];if(E.compressionLevel!==0)return-1;if(E.state>=ue.READY_TO_PUMP_FILE_DATA){if(E.uncompressedSize==null)return-1}else if(E.uncompressedSize==null)return null;E.relativeOffsetOfLocalHeader=t;var D=E.useZip64Format();t+=de+E.utf8FileName.length,t+=E.uncompressedSize,E.crcAndFileSizeKnown||(D?t+=Ce:t+=ye),S+=we+E.utf8FileName.length+E.fileComment.length,E.forceDosTimestamp||(S+=Te),D&&(S+=De)}var O=0;return(e.forceZip64Eocd||e.entries.length>=65535||S>=65535||t>=4294967295)&&(O+=te+ne),O+=ae+e.comment.length,t+S+O}function ee(e){if(e.ended)throw Error(`cannot add entries after calling end()`);return!!e.errored}var te=56,ne=20,ae=22;function oe(e,t){var S=!1,w=e.entries.length;(e.forceZip64Eocd||e.entries.length>=65535)&&(w=65535,S=!0);var E=e.outputStreamCursor-e.offsetOfStartOfCentralDirectory,D=E;(e.forceZip64Eocd||E>=4294967295)&&(D=4294967295,S=!0);var O=e.offsetOfStartOfCentralDirectory;if((e.forceZip64Eocd||e.offsetOfStartOfCentralDirectory>=4294967295)&&(O=4294967295,S=!0),t)return S?te+ne+ae:ae;var k=We(ae+e.comment.length);if(k.writeUInt32LE(101010256,0),k.writeUInt16LE(0,4),k.writeUInt16LE(0,6),k.writeUInt16LE(w,8),k.writeUInt16LE(w,10),k.writeUInt32LE(D,12),k.writeUInt32LE(O,16),k.writeUInt16LE(e.comment.length,20),e.comment.copy(k,22),!S)return k;var j=We(te);j.writeUInt32LE(101075792,0),Ie(j,te-12,4),j.writeUInt16LE(ge,12),j.writeUInt16LE(me,14),j.writeUInt32LE(0,16),j.writeUInt32LE(0,20),Ie(j,e.entries.length,24),Ie(j,e.entries.length,32),Ie(j,E,40),Ie(j,e.offsetOfStartOfCentralDirectory,48);var F=We(ne);return F.writeUInt32LE(117853008,0),F.writeUInt32LE(0,4),Ie(F,e.outputStreamCursor,8),F.writeUInt32LE(1,16),Buffer.concat([j,F,k])}function se(e,t){if(e===``)throw Error(`empty metadataPath`);if(e=e.replace(/\\/g,`/`),/^[a-zA-Z]:/.test(e)||/^\//.test(e))throw Error(`absolute path: `+e);if(e.split(`/`).indexOf(`..`)!==-1)throw Error(`invalid relative path: `+e);var S=/\/$/.test(e);if(t)S||(e+=`/`);else if(S)throw Error(`file path cannot end with '/': `+e);return e}var ce=We(0);function ue(e,t,S){if(this.utf8FileName=Ge(e),this.utf8FileName.length>65535)throw Error(`utf8 file name too long. `+utf8FileName.length+` > 65535`);if(this.isDirectory=t,this.state=ue.WAITING_FOR_METADATA,this.setLastModDate(S.mtime==null?new Date:S.mtime),this.forceDosTimestamp=!!S.forceDosTimestamp,S.mode==null?this.setFileAttributesMode(t?16893:33204):this.setFileAttributesMode(S.mode),t?(this.crcAndFileSizeKnown=!0,this.crc32=0,this.uncompressedSize=0,this.compressedSize=0):(this.crcAndFileSizeKnown=!1,this.crc32=null,this.uncompressedSize=null,this.compressedSize=null,S.size!=null&&(this.uncompressedSize=S.size)),t?this.compressionLevel=0:this.compressionLevel=q(S),this.forceZip64Format=!!S.forceZip64Format,S.fileComment){if(typeof S.fileComment==`string`?this.fileComment=Ge(S.fileComment,`utf-8`):this.fileComment=S.fileComment,this.fileComment.length>65535)throw Error(`fileComment is too large`)}else this.fileComment=ce}ue.WAITING_FOR_METADATA=0,ue.READY_TO_PUMP_FILE_DATA=1,ue.FILE_DATA_IN_PROGRESS=2,ue.FILE_DATA_DONE=3,ue.prototype.setLastModDate=function(e){this.mtime=e;var t=Pe(e);this.lastModFileTime=t.time,this.lastModFileDate=t.date},ue.prototype.setFileAttributesMode=function(e){if((e&65535)!==e)throw Error(`invalid mode. expected: 0 <= `+e+` <= 65535`);this.externalFileAttributes=e<<16>>>0},ue.prototype.setFileDataPumpFunction=function(e){this.doFileDataPump=e,this.state=ue.READY_TO_PUMP_FILE_DATA},ue.prototype.useZip64Format=function(){return this.forceZip64Format||this.uncompressedSize!=null&&this.uncompressedSize>4294967294||this.compressedSize!=null&&this.compressedSize>4294967294||this.relativeOffsetOfLocalHeader!=null&&this.relativeOffsetOfLocalHeader>4294967294};var de=30,fe=20,me=45,ge=831,_e=2048,ve=8;ue.prototype.getLocalFileHeader=function(){var e=0,t=0,S=0;this.crcAndFileSizeKnown&&(e=this.crc32,t=this.compressedSize,S=this.uncompressedSize);var w=We(de),E=_e;return this.crcAndFileSizeKnown||(E|=ve),w.writeUInt32LE(67324752,0),w.writeUInt16LE(fe,4),w.writeUInt16LE(E,6),w.writeUInt16LE(this.getCompressionMethod(),8),w.writeUInt16LE(this.lastModFileTime,10),w.writeUInt16LE(this.lastModFileDate,12),w.writeUInt32LE(e,14),w.writeUInt32LE(t,18),w.writeUInt32LE(S,22),w.writeUInt16LE(this.utf8FileName.length,26),w.writeUInt16LE(0,28),Buffer.concat([w,this.utf8FileName])};var ye=16,Ce=24;ue.prototype.getDataDescriptor=function(){if(this.crcAndFileSizeKnown)return ce;if(this.useZip64Format()){var e=We(Ce);return e.writeUInt32LE(134695760,0),e.writeUInt32LE(this.crc32,4),Ie(e,this.compressedSize,8),Ie(e,this.uncompressedSize,16),e}else{var e=We(ye);return e.writeUInt32LE(134695760,0),e.writeUInt32LE(this.crc32,4),e.writeUInt32LE(this.compressedSize,8),e.writeUInt32LE(this.uncompressedSize,12),e}};var we=46,Te=9,De=28;ue.prototype.getCentralDirectoryRecord=function(){var e=We(we),t=_e;this.crcAndFileSizeKnown||(t|=ve);var S=ce;if(!this.forceDosTimestamp){S=We(Te),S.writeUInt16LE(21589,0),S.writeUInt16LE(Te-4,2),S.writeUInt8(3,4);var w=Math.floor(this.mtime.getTime()/1e3);w<-2147483648&&(w=-2147483648),w>2147483647&&(w=2147483647),S.writeUInt32LE(w,5)}var E=this.compressedSize,D=this.uncompressedSize,O=this.relativeOffsetOfLocalHeader,k=fe,j=ce;return this.useZip64Format()&&(E=4294967295,D=4294967295,O=4294967295,k=me,j=We(De),j.writeUInt16LE(1,0),j.writeUInt16LE(De-4,2),Ie(j,this.uncompressedSize,4),Ie(j,this.compressedSize,12),Ie(j,this.relativeOffsetOfLocalHeader,20)),e.writeUInt32LE(33639248,0),e.writeUInt16LE(ge,4),e.writeUInt16LE(k,6),e.writeUInt16LE(t,8),e.writeUInt16LE(this.getCompressionMethod(),10),e.writeUInt16LE(this.lastModFileTime,12),e.writeUInt16LE(this.lastModFileDate,14),e.writeUInt32LE(this.crc32,16),e.writeUInt32LE(E,20),e.writeUInt32LE(D,24),e.writeUInt16LE(this.utf8FileName.length,28),e.writeUInt16LE(S.length+j.length,30),e.writeUInt16LE(this.fileComment.length,32),e.writeUInt16LE(0,34),e.writeUInt16LE(0,36),e.writeUInt32LE(this.externalFileAttributes,38),e.writeUInt32LE(O,42),Buffer.concat([e,this.utf8FileName,S,j,this.fileComment])},ue.prototype.getCompressionMethod=function(){return this.compressionLevel===0?0:8};var je=new Date(1980,0,1),Me=new Date(2107,11,31,23,59,58);function Pe(e){e<je?e=je:e>Me&&(e=Me);var t=0;t|=e.getDate()&31,t|=(e.getMonth()+1&15)<<5,t|=(e.getFullYear()-1980&127)<<9;var S=0;return S|=Math.floor(e.getSeconds()/2),S|=(e.getMinutes()&63)<<5,S|=(e.getHours()&31)<<11,{date:t,time:S}}function Ie(e,t,S){var w=Math.floor(t/4294967296),E=t%4294967296;e.writeUInt32LE(E,S),e.writeUInt32LE(w,S+4)}D.inherits(Re,S);function Re(e){S.call(this,e),this.byteCount=0}Re.prototype._transform=function(e,t,S){this.byteCount+=e.length,S(null,e)},D.inherits(ze,S);function ze(e){S.call(this,e),this.crc32=0}ze.prototype._transform=function(e,t,S){this.crc32=j.unsigned(e,this.crc32),S(null,e)};var Be=`\0☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\xA0`;if(Be.length!==256)throw Error(`assertion failure`);var Ve=null;function Ue(e){if(/^[\x20-\x7e]*$/.test(e))return Ge(e,`utf-8`);if(Ve==null){Ve={};for(var t=0;t<Be.length;t++)Ve[Be[t]]=t}for(var S=We(e.length),t=0;t<e.length;t++){var w=Ve[e[t]];if(w==null)throw Error(`character not encodable in CP437: `+JSON.stringify(e[t]));S[t]=w}return S}function We(e){We=t;try{return We(e)}catch{return We=S,We(e)}function t(e){return Buffer.allocUnsafe(e)}function S(e){return new Buffer(e)}}function Ge(e,t){Ge=S;try{return Ge(e,t)}catch{return Ge=w,Ge(e,t)}function S(e,t){return Buffer.from(e,t)}function w(e,t){return new Buffer(e,t)}}function Ke(e,t){Ke=S;try{return Ke(e,t)}catch{return Ke=w,Ke(e,t)}function S(e,t){return e.includes(t)}function w(e,t){for(var S=0;S<=e.length-t.length;S++)for(var w=0;;w++){if(w===t.length)return!0;if(e[S+w]!==t[w])break}return!1}}})),util;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function S(e){throw Error()}e.assertNever=S,e.arrayToEnum=e=>{let t={};for(let S of e)t[S]=S;return t},e.getValidEnumValues=t=>{let S=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),w={};for(let e of S)w[e]=t[e];return e.objectValues(w)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let S in e)Object.prototype.hasOwnProperty.call(e,S)&&t.push(S);return t},e.find=(e,t)=>{for(let S of e)if(t(S))return S},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function w(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=w,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(util||={});var objectUtil;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(objectUtil||={});const ZodParsedType=util.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),getParsedType=e=>{switch(typeof e){case`undefined`:return ZodParsedType.undefined;case`string`:return ZodParsedType.string;case`number`:return Number.isNaN(e)?ZodParsedType.nan:ZodParsedType.number;case`boolean`:return ZodParsedType.boolean;case`function`:return ZodParsedType.function;case`bigint`:return ZodParsedType.bigint;case`symbol`:return ZodParsedType.symbol;case`object`:return Array.isArray(e)?ZodParsedType.array:e===null?ZodParsedType.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?ZodParsedType.promise:typeof Map<`u`&&e instanceof Map?ZodParsedType.map:typeof Set<`u`&&e instanceof Set?ZodParsedType.set:typeof Date<`u`&&e instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]);var ZodError=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},S={_errors:[]},w=e=>{for(let E of e.issues)if(E.code===`invalid_union`)E.unionErrors.map(w);else if(E.code===`invalid_return_type`)w(E.returnTypeError);else if(E.code===`invalid_arguments`)w(E.argumentsError);else if(E.path.length===0)S._errors.push(t(E));else{let e=S,w=0;for(;w<E.path.length;){let S=E.path[w];w===E.path.length-1?(e[S]=e[S]||{_errors:[]},e[S]._errors.push(t(E))):e[S]=e[S]||{_errors:[]},e=e[S],w++}}};return w(this),S}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),S=[];for(let w of this.issues)if(w.path.length>0){let S=w.path[0];t[S]=t[S]||[],t[S].push(e(w))}else S.push(e(w));return{formErrors:S,fieldErrors:t}}get formErrors(){return this.flatten()}};ZodError.create=e=>new ZodError(e);const errorMap=(e,t)=>{let S;switch(e.code){case ZodIssueCode.invalid_type:S=e.received===ZodParsedType.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case ZodIssueCode.invalid_literal:S=`Invalid literal value, expected ${JSON.stringify(e.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:S=`Unrecognized key(s) in object: ${util.joinValues(e.keys,`, `)}`;break;case ZodIssueCode.invalid_union:S=`Invalid input`;break;case ZodIssueCode.invalid_union_discriminator:S=`Invalid discriminator value. Expected ${util.joinValues(e.options)}`;break;case ZodIssueCode.invalid_enum_value:S=`Invalid enum value. Expected ${util.joinValues(e.options)}, received '${e.received}'`;break;case ZodIssueCode.invalid_arguments:S=`Invalid function arguments`;break;case ZodIssueCode.invalid_return_type:S=`Invalid function return type`;break;case ZodIssueCode.invalid_date:S=`Invalid date`;break;case ZodIssueCode.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(S=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(S=`${S} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?S=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?S=`Invalid input: must end with "${e.validation.endsWith}"`:util.assertNever(e.validation):S=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case ZodIssueCode.too_small:S=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case ZodIssueCode.too_big:S=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case ZodIssueCode.custom:S=`Invalid input`;break;case ZodIssueCode.invalid_intersection_types:S=`Intersection results could not be merged`;break;case ZodIssueCode.not_multiple_of:S=`Number must be a multiple of ${e.multipleOf}`;break;case ZodIssueCode.not_finite:S=`Number must be finite`;break;default:S=t.defaultError,util.assertNever(e)}return{message:S}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=e=>{let{data:t,path:S,errorMaps:w,issueData:E}=e,D=[...S,...E.path||[]],O={...E,path:D};if(E.message!==void 0)return{...E,path:D,message:E.message};let k=``,j=w.filter(e=>!!e).slice().reverse();for(let e of j)k=e(O,{data:t,defaultError:k}).message;return{...E,path:D,message:k}};function addIssueToContext(e,t){let S=getErrorMap(),w=makeIssue({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,S,S===errorMap?void 0:errorMap].filter(e=>!!e)});e.common.issues.push(w)}var ParseStatus=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let S=[];for(let w of t){if(w.status===`aborted`)return INVALID;w.status===`dirty`&&e.dirty(),S.push(w.value)}return{status:e.value,value:S}}static async mergeObjectAsync(t,S){let w=[];for(let e of S){let t=await e.key,S=await e.value;w.push({key:t,value:S})}return e.mergeObjectSync(t,w)}static mergeObjectSync(e,t){let S={};for(let w of t){let{key:t,value:E}=w;if(t.status===`aborted`||E.status===`aborted`)return INVALID;t.status===`dirty`&&e.dirty(),E.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(E.value!==void 0||w.alwaysSet)&&(S[t.value]=E.value)}return{status:e.value,value:S}}};const INVALID=Object.freeze({status:`aborted`}),DIRTY=e=>({status:`dirty`,value:e}),OK=e=>({status:`valid`,value:e}),isAborted=e=>e.status===`aborted`,isDirty=e=>e.status===`dirty`,isValid=e=>e.status===`valid`,isAsync=e=>typeof Promise<`u`&&e instanceof Promise;var errorUtil;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(errorUtil||={});var ParseInputLazyPath=class{constructor(e,t,S,w){this._cachedPath=[],this.parent=e,this.data=t,this._path=S,this._key=w}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const handleResult=(e,t)=>{if(isValid(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){return this._error||=new ZodError(e.common.issues),this._error}}};function processCreateParams(e){if(!e)return{};let{errorMap:t,invalid_type_error:S,required_error:w,description:E}=e;if(t&&(S||w))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:E}:{errorMap:(t,E)=>{let{message:D}=e;return t.code===`invalid_enum_value`?{message:D??E.defaultError}:E.data===void 0?{message:D??w??E.defaultError}:t.code===`invalid_type`?{message:D??S??E.defaultError}:{message:E.defaultError}},description:E}}var ZodType=class{get description(){return this._def.description}_getType(e){return getParsedType(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(isAsync(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let S=this.safeParse(e,t);if(S.success)return S.data;throw S.error}safeParse(e,t){let S={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};return handleResult(S,this._parseSync({data:e,path:S.path,parent:S}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};if(!this[`~standard`].async)try{let S=this._parseSync({data:e,path:[],parent:t});return isValid(S)?{value:S.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>isValid(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let S=await this.safeParseAsync(e,t);if(S.success)return S.data;throw S.error}async safeParseAsync(e,t){let S={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},w=this._parse({data:e,path:S.path,parent:S});return handleResult(S,await(isAsync(w)?w:Promise.resolve(w)))}refine(e,t){let S=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,w)=>{let E=e(t),D=()=>w.addIssue({code:ZodIssueCode.custom,...S(t)});return typeof Promise<`u`&&E instanceof Promise?E.then(e=>e?!0:(D(),!1)):E?!0:(D(),!1)})}refinement(e,t){return this._refinement((S,w)=>e(S)?!0:(w.addIssue(typeof t==`function`?t(S,w):t),!1))}_refinement(e){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(e){return ZodUnion.create([this,e],this._def)}and(e){return ZodIntersection.create(this,e,this._def)}transform(e){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:t,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:t,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ZodPipeline.create(this,e)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;let emojiRegex$1;const ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,dateRegex=RegExp(`^${dateRegexSource}$`);function timeRegexSource(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let S=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${S}`}function timeRegex(e){return RegExp(`^${timeRegexSource(e)}$`)}function datetimeRegex(e){let t=`${dateRegexSource}T${timeRegexSource(e)}`,S=[];return S.push(e.local?`Z?`:`Z`),e.offset&&S.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${S.join(`|`)})`,RegExp(`^${t}$`)}function isValidIP(e,t){return!!((t===`v4`||!t)&&ipv4Regex.test(e)||(t===`v6`||!t)&&ipv6Regex.test(e))}function isValidJWT(e,t){if(!jwtRegex.test(e))return!1;try{let[S]=e.split(`.`);if(!S)return!1;let w=S.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(S.length+(4-S.length%4)%4,`=`),E=JSON.parse(atob(w));return!(typeof E!=`object`||!E||`typ`in E&&E?.typ!==`JWT`||!E.alg||t&&E.alg!==t)}catch{return!1}}function isValidCidr(e,t){return!!((t===`v4`||!t)&&ipv4CidrRegex.test(e)||(t===`v6`||!t)&&ipv6CidrRegex.test(e))}var ZodString=class e extends ZodType{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ZodParsedType.string){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:t.parsedType}),INVALID}let t=new ParseStatus,S;for(let w of this._def.checks)if(w.kind===`min`)e.data.length<w.value&&(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.too_small,minimum:w.value,type:`string`,inclusive:!0,exact:!1,message:w.message}),t.dirty());else if(w.kind===`max`)e.data.length>w.value&&(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.too_big,maximum:w.value,type:`string`,inclusive:!0,exact:!1,message:w.message}),t.dirty());else if(w.kind===`length`){let E=e.data.length>w.value,D=e.data.length<w.value;(E||D)&&(S=this._getOrReturnCtx(e,S),E?addIssueToContext(S,{code:ZodIssueCode.too_big,maximum:w.value,type:`string`,inclusive:!0,exact:!0,message:w.message}):D&&addIssueToContext(S,{code:ZodIssueCode.too_small,minimum:w.value,type:`string`,inclusive:!0,exact:!0,message:w.message}),t.dirty())}else if(w.kind===`email`)emailRegex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`email`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty());else if(w.kind===`emoji`)emojiRegex$1||=new RegExp(_emojiRegex,`u`),emojiRegex$1.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`emoji`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty());else if(w.kind===`uuid`)uuidRegex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`uuid`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty());else if(w.kind===`nanoid`)nanoidRegex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`nanoid`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty());else if(w.kind===`cuid`)cuidRegex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`cuid`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty());else if(w.kind===`cuid2`)cuid2Regex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`cuid2`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty());else if(w.kind===`ulid`)ulidRegex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`ulid`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty());else if(w.kind===`url`)try{new URL(e.data)}catch{S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`url`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty()}else w.kind===`regex`?(w.regex.lastIndex=0,w.regex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`regex`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty())):w.kind===`trim`?e.data=e.data.trim():w.kind===`includes`?e.data.includes(w.value,w.position)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.invalid_string,validation:{includes:w.value,position:w.position},message:w.message}),t.dirty()):w.kind===`toLowerCase`?e.data=e.data.toLowerCase():w.kind===`toUpperCase`?e.data=e.data.toUpperCase():w.kind===`startsWith`?e.data.startsWith(w.value)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.invalid_string,validation:{startsWith:w.value},message:w.message}),t.dirty()):w.kind===`endsWith`?e.data.endsWith(w.value)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.invalid_string,validation:{endsWith:w.value},message:w.message}),t.dirty()):w.kind===`datetime`?datetimeRegex(w).test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.invalid_string,validation:`datetime`,message:w.message}),t.dirty()):w.kind===`date`?dateRegex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.invalid_string,validation:`date`,message:w.message}),t.dirty()):w.kind===`time`?timeRegex(w).test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.invalid_string,validation:`time`,message:w.message}),t.dirty()):w.kind===`duration`?durationRegex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`duration`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty()):w.kind===`ip`?isValidIP(e.data,w.version)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`ip`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty()):w.kind===`jwt`?isValidJWT(e.data,w.alg)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`jwt`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty()):w.kind===`cidr`?isValidCidr(e.data,w.version)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`cidr`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty()):w.kind===`base64`?base64Regex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`base64`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty()):w.kind===`base64url`?base64urlRegex.test(e.data)||(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{validation:`base64url`,code:ZodIssueCode.invalid_string,message:w.message}),t.dirty()):util.assertNever(w);return{status:t.value,value:e.data}}_regex(e,t,S){return this.refinement(t=>e.test(t),{validation:t,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(S)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...errorUtil.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...errorUtil.errToObj(t)})}nonempty(e){return this.min(1,errorUtil.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};ZodString.create=e=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:e?.coerce??!1,...processCreateParams(e)});function floatSafeRemainder(e,t){let S=(e.toString().split(`.`)[1]||``).length,w=(t.toString().split(`.`)[1]||``).length,E=S>w?S:w;return Number.parseInt(e.toFixed(E).replace(`.`,``))%Number.parseInt(t.toFixed(E).replace(`.`,``))/10**E}var ZodNumber=class e extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ZodParsedType.number){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:t.parsedType}),INVALID}let t,S=new ParseStatus;for(let w of this._def.checks)w.kind===`int`?util.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:`integer`,received:`float`,message:w.message}),S.dirty()):w.kind===`min`?(w.inclusive?e.data<w.value:e.data<=w.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:w.value,type:`number`,inclusive:w.inclusive,exact:!1,message:w.message}),S.dirty()):w.kind===`max`?(w.inclusive?e.data>w.value:e.data>=w.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:w.value,type:`number`,inclusive:w.inclusive,exact:!1,message:w.message}),S.dirty()):w.kind===`multipleOf`?floatSafeRemainder(e.data,w.value)!==0&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_multiple_of,multipleOf:w.value,message:w.message}),S.dirty()):w.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_finite,message:w.message}),S.dirty()):util.assertNever(w);return{status:S.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,errorUtil.toString(t))}setLimit(t,S,w,E){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:S,inclusive:w,message:errorUtil.toString(E)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:errorUtil.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:errorUtil.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:errorUtil.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:errorUtil.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:errorUtil.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let S of this._def.checks)if(S.kind===`finite`||S.kind===`int`||S.kind===`multipleOf`)return!0;else S.kind===`min`?(t===null||S.value>t)&&(t=S.value):S.kind===`max`&&(e===null||S.value<e)&&(e=S.value);return Number.isFinite(t)&&Number.isFinite(e)}};ZodNumber.create=e=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:e?.coerce||!1,...processCreateParams(e)});var ZodBigInt=class e extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ZodParsedType.bigint)return this._getInvalidInput(e);let t,S=new ParseStatus;for(let w of this._def.checks)w.kind===`min`?(w.inclusive?e.data<w.value:e.data<=w.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_small,type:`bigint`,minimum:w.value,inclusive:w.inclusive,message:w.message}),S.dirty()):w.kind===`max`?(w.inclusive?e.data>w.value:e.data>=w.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_big,type:`bigint`,maximum:w.value,inclusive:w.inclusive,message:w.message}),S.dirty()):w.kind===`multipleOf`?e.data%w.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_multiple_of,multipleOf:w.value,message:w.message}),S.dirty()):util.assertNever(w);return{status:S.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:t.parsedType}),INVALID}gte(e,t){return this.setLimit(`min`,e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,errorUtil.toString(t))}setLimit(t,S,w,E){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:S,inclusive:w,message:errorUtil.toString(E)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:errorUtil.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};ZodBigInt.create=e=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:e?.coerce??!1,...processCreateParams(e)});var ZodBoolean=class extends ZodType{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ZodParsedType.boolean){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:t.parsedType}),INVALID}return OK(e.data)}};ZodBoolean.create=e=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:e?.coerce||!1,...processCreateParams(e)});var ZodDate=class e extends ZodType{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ZodParsedType.date){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:t.parsedType}),INVALID}if(Number.isNaN(e.data.getTime()))return addIssueToContext(this._getOrReturnCtx(e),{code:ZodIssueCode.invalid_date}),INVALID;let t=new ParseStatus,S;for(let w of this._def.checks)w.kind===`min`?e.data.getTime()<w.value&&(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.too_small,message:w.message,inclusive:!0,exact:!1,minimum:w.value,type:`date`}),t.dirty()):w.kind===`max`?e.data.getTime()>w.value&&(S=this._getOrReturnCtx(e,S),addIssueToContext(S,{code:ZodIssueCode.too_big,message:w.message,inclusive:!0,exact:!1,maximum:w.value,type:`date`}),t.dirty()):util.assertNever(w);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:errorUtil.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};ZodDate.create=e=>new ZodDate({checks:[],coerce:e?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(e)});var ZodSymbol=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.symbol){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:t.parsedType}),INVALID}return OK(e.data)}};ZodSymbol.create=e=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(e)});var ZodUndefined=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:t.parsedType}),INVALID}return OK(e.data)}};ZodUndefined.create=e=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(e)});var ZodNull=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.null){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:t.parsedType}),INVALID}return OK(e.data)}};ZodNull.create=e=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(e)});var ZodAny=class extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(e){return OK(e.data)}};ZodAny.create=e=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(e)});var ZodUnknown=class extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OK(e.data)}};ZodUnknown.create=e=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(e)});var ZodNever=class extends ZodType{_parse(e){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:t.parsedType}),INVALID}};ZodNever.create=e=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(e)});var ZodVoid=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:t.parsedType}),INVALID}return OK(e.data)}};ZodVoid.create=e=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(e)});var ZodArray=class e extends ZodType{_parse(e){let{ctx:t,status:S}=this._processInputParams(e),w=this._def;if(t.parsedType!==ZodParsedType.array)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:t.parsedType}),INVALID;if(w.exactLength!==null){let e=t.data.length>w.exactLength.value,E=t.data.length<w.exactLength.value;(e||E)&&(addIssueToContext(t,{code:e?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:E?w.exactLength.value:void 0,maximum:e?w.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:w.exactLength.message}),S.dirty())}if(w.minLength!==null&&t.data.length<w.minLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:w.minLength.value,type:`array`,inclusive:!0,exact:!1,message:w.minLength.message}),S.dirty()),w.maxLength!==null&&t.data.length>w.maxLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:w.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:w.maxLength.message}),S.dirty()),t.common.async)return Promise.all([...t.data].map((e,S)=>w.type._parseAsync(new ParseInputLazyPath(t,e,t.path,S)))).then(e=>ParseStatus.mergeArray(S,e));let E=[...t.data].map((e,S)=>w.type._parseSync(new ParseInputLazyPath(t,e,t.path,S)));return ParseStatus.mergeArray(S,E)}get element(){return this._def.type}min(t,S){return new e({...this._def,minLength:{value:t,message:errorUtil.toString(S)}})}max(t,S){return new e({...this._def,maxLength:{value:t,message:errorUtil.toString(S)}})}length(t,S){return new e({...this._def,exactLength:{value:t,message:errorUtil.toString(S)}})}nonempty(e){return this.min(1,e)}};ZodArray.create=(e,t)=>new ZodArray({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(t)});function deepPartialify(e){if(e instanceof ZodObject){let t={};for(let S in e.shape){let w=e.shape[S];t[S]=ZodOptional.create(deepPartialify(w))}return new ZodObject({...e._def,shape:()=>t})}else if(e instanceof ZodArray)return new ZodArray({...e._def,type:deepPartialify(e.element)});else if(e instanceof ZodOptional)return ZodOptional.create(deepPartialify(e.unwrap()));else if(e instanceof ZodNullable)return ZodNullable.create(deepPartialify(e.unwrap()));else if(e instanceof ZodTuple)return ZodTuple.create(e.items.map(e=>deepPartialify(e)));else return e}var ZodObject=class e extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape();return this._cached={shape:e,keys:util.objectKeys(e)},this._cached}_parse(e){if(this._getType(e)!==ZodParsedType.object){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:t.parsedType}),INVALID}let{status:t,ctx:S}=this._processInputParams(e),{shape:w,keys:E}=this._getCached(),D=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys===`strip`))for(let e in S.data)E.includes(e)||D.push(e);let O=[];for(let e of E){let t=w[e],E=S.data[e];O.push({key:{status:`valid`,value:e},value:t._parse(new ParseInputLazyPath(S,E,S.path,e)),alwaysSet:e in S.data})}if(this._def.catchall instanceof ZodNever){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of D)O.push({key:{status:`valid`,value:e},value:{status:`valid`,value:S.data[e]}});else if(e===`strict`)D.length>0&&(addIssueToContext(S,{code:ZodIssueCode.unrecognized_keys,keys:D}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of D){let w=S.data[t];O.push({key:{status:`valid`,value:t},value:e._parse(new ParseInputLazyPath(S,w,S.path,t)),alwaysSet:t in S.data})}}return S.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of O){let S=await t.key,w=await t.value;e.push({key:S,value:w,alwaysSet:t.alwaysSet})}return e}).then(e=>ParseStatus.mergeObjectSync(t,e)):ParseStatus.mergeObjectSync(t,O)}get shape(){return this._def.shape()}strict(t){return errorUtil.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,S)=>{let w=this._def.errorMap?.(e,S).message??S.defaultError;return e.code===`unrecognized_keys`?{message:errorUtil.errToObj(t).message??w}:{message:w}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let S={};for(let e of util.objectKeys(t))t[e]&&this.shape[e]&&(S[e]=this.shape[e]);return new e({...this._def,shape:()=>S})}omit(t){let S={};for(let e of util.objectKeys(this.shape))t[e]||(S[e]=this.shape[e]);return new e({...this._def,shape:()=>S})}deepPartial(){return deepPartialify(this)}partial(t){let S={};for(let e of util.objectKeys(this.shape)){let w=this.shape[e];t&&!t[e]?S[e]=w:S[e]=w.optional()}return new e({...this._def,shape:()=>S})}required(t){let S={};for(let e of util.objectKeys(this.shape))if(t&&!t[e])S[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof ZodOptional;)t=t._def.innerType;S[e]=t}return new e({...this._def,shape:()=>S})}keyof(){return createZodEnum(util.objectKeys(this.shape))}};ZodObject.create=(e,t)=>new ZodObject({shape:()=>e,unknownKeys:`strip`,catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)}),ZodObject.strictCreate=(e,t)=>new ZodObject({shape:()=>e,unknownKeys:`strict`,catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)}),ZodObject.lazycreate=(e,t)=>new ZodObject({shape:e,unknownKeys:`strip`,catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)});var ZodUnion=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),S=this._def.options;function w(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let S of e)if(S.result.status===`dirty`)return t.common.issues.push(...S.ctx.common.issues),S.result;let S=e.map(e=>new ZodError(e.ctx.common.issues));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:S}),INVALID}if(t.common.async)return Promise.all(S.map(async e=>{let S={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:S}),ctx:S}})).then(w);{let e,w=[];for(let E of S){let S={...t,common:{...t.common,issues:[]},parent:null},D=E._parseSync({data:t.data,path:t.path,parent:S});if(D.status===`valid`)return D;D.status===`dirty`&&!e&&(e={result:D,ctx:S}),S.common.issues.length&&w.push(S.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let E=w.map(e=>new ZodError(e));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:E}),INVALID}}get options(){return this._def.options}};ZodUnion.create=(e,t)=>new ZodUnion({options:e,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(t)});const getDiscriminator=e=>e instanceof ZodLazy?getDiscriminator(e.schema):e instanceof ZodEffects?getDiscriminator(e.innerType()):e instanceof ZodLiteral?[e.value]:e instanceof ZodEnum?e.options:e instanceof ZodNativeEnum?util.objectValues(e.enum):e instanceof ZodDefault?getDiscriminator(e._def.innerType):e instanceof ZodUndefined?[void 0]:e instanceof ZodNull?[null]:e instanceof ZodOptional?[void 0,...getDiscriminator(e.unwrap())]:e instanceof ZodNullable?[null,...getDiscriminator(e.unwrap())]:e instanceof ZodBranded||e instanceof ZodReadonly?getDiscriminator(e.unwrap()):e instanceof ZodCatch?getDiscriminator(e._def.innerType):[];var ZodDiscriminatedUnion=class e extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.object)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:t.parsedType}),INVALID;let S=this.discriminator,w=t.data[S],E=this.optionsMap.get(w);return E?t.common.async?E._parseAsync({data:t.data,path:t.path,parent:t}):E._parseSync({data:t.data,path:t.path,parent:t}):(addIssueToContext(t,{code:ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[S]}),INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,S,w){let E=new Map;for(let e of S){let S=getDiscriminator(e.shape[t]);if(!S.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let w of S){if(E.has(w))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(w)}`);E.set(w,e)}}return new e({typeName:ZodFirstPartyTypeKind.ZodDiscriminatedUnion,discriminator:t,options:S,optionsMap:E,...processCreateParams(w)})}};function mergeValues(e,t){let S=getParsedType(e),w=getParsedType(t);if(e===t)return{valid:!0,data:e};if(S===ZodParsedType.object&&w===ZodParsedType.object){let S=util.objectKeys(t),w=util.objectKeys(e).filter(e=>S.indexOf(e)!==-1),E={...e,...t};for(let S of w){let w=mergeValues(e[S],t[S]);if(!w.valid)return{valid:!1};E[S]=w.data}return{valid:!0,data:E}}else if(S===ZodParsedType.array&&w===ZodParsedType.array){if(e.length!==t.length)return{valid:!1};let S=[];for(let w=0;w<e.length;w++){let E=e[w],D=t[w],O=mergeValues(E,D);if(!O.valid)return{valid:!1};S.push(O.data)}return{valid:!0,data:S}}else if(S===ZodParsedType.date&&w===ZodParsedType.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var ZodIntersection=class extends ZodType{_parse(e){let{status:t,ctx:S}=this._processInputParams(e),w=(e,w)=>{if(isAborted(e)||isAborted(w))return INVALID;let E=mergeValues(e.value,w.value);return E.valid?((isDirty(e)||isDirty(w))&&t.dirty(),{status:t.value,value:E.data}):(addIssueToContext(S,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return S.common.async?Promise.all([this._def.left._parseAsync({data:S.data,path:S.path,parent:S}),this._def.right._parseAsync({data:S.data,path:S.path,parent:S})]).then(([e,t])=>w(e,t)):w(this._def.left._parseSync({data:S.data,path:S.path,parent:S}),this._def.right._parseSync({data:S.data,path:S.path,parent:S}))}};ZodIntersection.create=(e,t,S)=>new ZodIntersection({left:e,right:t,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(S)});var ZodTuple=class e extends ZodType{_parse(e){let{status:t,ctx:S}=this._processInputParams(e);if(S.parsedType!==ZodParsedType.array)return addIssueToContext(S,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:S.parsedType}),INVALID;if(S.data.length<this._def.items.length)return addIssueToContext(S,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),INVALID;!this._def.rest&&S.data.length>this._def.items.length&&(addIssueToContext(S,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let w=[...S.data].map((e,t)=>{let w=this._def.items[t]||this._def.rest;return w?w._parse(new ParseInputLazyPath(S,e,S.path,t)):null}).filter(e=>!!e);return S.common.async?Promise.all(w).then(e=>ParseStatus.mergeArray(t,e)):ParseStatus.mergeArray(t,w)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};ZodTuple.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new ZodTuple({items:e,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(t)})};var ZodRecord=class e extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:S}=this._processInputParams(e);if(S.parsedType!==ZodParsedType.object)return addIssueToContext(S,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:S.parsedType}),INVALID;let w=[],E=this._def.keyType,D=this._def.valueType;for(let e in S.data)w.push({key:E._parse(new ParseInputLazyPath(S,e,S.path,e)),value:D._parse(new ParseInputLazyPath(S,S.data[e],S.path,e)),alwaysSet:e in S.data});return S.common.async?ParseStatus.mergeObjectAsync(t,w):ParseStatus.mergeObjectSync(t,w)}get element(){return this._def.valueType}static create(t,S,w){return S instanceof ZodType?new e({keyType:t,valueType:S,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(w)}):new e({keyType:ZodString.create(),valueType:t,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(S)})}},ZodMap=class extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:S}=this._processInputParams(e);if(S.parsedType!==ZodParsedType.map)return addIssueToContext(S,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:S.parsedType}),INVALID;let w=this._def.keyType,E=this._def.valueType,D=[...S.data.entries()].map(([e,t],D)=>({key:w._parse(new ParseInputLazyPath(S,e,S.path,[D,`key`])),value:E._parse(new ParseInputLazyPath(S,t,S.path,[D,`value`]))}));if(S.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let S of D){let w=await S.key,E=await S.value;if(w.status===`aborted`||E.status===`aborted`)return INVALID;(w.status===`dirty`||E.status===`dirty`)&&t.dirty(),e.set(w.value,E.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let S of D){let w=S.key,E=S.value;if(w.status===`aborted`||E.status===`aborted`)return INVALID;(w.status===`dirty`||E.status===`dirty`)&&t.dirty(),e.set(w.value,E.value)}return{status:t.value,value:e}}}};ZodMap.create=(e,t,S)=>new ZodMap({valueType:t,keyType:e,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(S)});var ZodSet=class e extends ZodType{_parse(e){let{status:t,ctx:S}=this._processInputParams(e);if(S.parsedType!==ZodParsedType.set)return addIssueToContext(S,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:S.parsedType}),INVALID;let w=this._def;w.minSize!==null&&S.data.size<w.minSize.value&&(addIssueToContext(S,{code:ZodIssueCode.too_small,minimum:w.minSize.value,type:`set`,inclusive:!0,exact:!1,message:w.minSize.message}),t.dirty()),w.maxSize!==null&&S.data.size>w.maxSize.value&&(addIssueToContext(S,{code:ZodIssueCode.too_big,maximum:w.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:w.maxSize.message}),t.dirty());let E=this._def.valueType;function D(e){let S=new Set;for(let w of e){if(w.status===`aborted`)return INVALID;w.status===`dirty`&&t.dirty(),S.add(w.value)}return{status:t.value,value:S}}let O=[...S.data.values()].map((e,t)=>E._parse(new ParseInputLazyPath(S,e,S.path,t)));return S.common.async?Promise.all(O).then(e=>D(e)):D(O)}min(t,S){return new e({...this._def,minSize:{value:t,message:errorUtil.toString(S)}})}max(t,S){return new e({...this._def,maxSize:{value:t,message:errorUtil.toString(S)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};ZodSet.create=(e,t)=>new ZodSet({valueType:e,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(t)});var ZodFunction=class e extends ZodType{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.function)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.function,received:t.parsedType}),INVALID;function S(e,S){return makeIssue({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,getErrorMap(),errorMap].filter(e=>!!e),issueData:{code:ZodIssueCode.invalid_arguments,argumentsError:S}})}function w(e,S){return makeIssue({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,getErrorMap(),errorMap].filter(e=>!!e),issueData:{code:ZodIssueCode.invalid_return_type,returnTypeError:S}})}let E={errorMap:t.common.contextualErrorMap},D=t.data;if(this._def.returns instanceof ZodPromise){let e=this;return OK(async function(...t){let O=new ZodError([]),k=await e._def.args.parseAsync(t,E).catch(e=>{throw O.addIssue(S(t,e)),O}),j=await Reflect.apply(D,this,k);return await e._def.returns._def.type.parseAsync(j,E).catch(e=>{throw O.addIssue(w(j,e)),O})})}else{let e=this;return OK(function(...t){let O=e._def.args.safeParse(t,E);if(!O.success)throw new ZodError([S(t,O.error)]);let k=Reflect.apply(D,this,O.data),j=e._def.returns.safeParse(k,E);if(!j.success)throw new ZodError([w(k,j.error)]);return j.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:ZodTuple.create(t).rest(ZodUnknown.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,S,w){return new e({args:t||ZodTuple.create([]).rest(ZodUnknown.create()),returns:S||ZodUnknown.create(),typeName:ZodFirstPartyTypeKind.ZodFunction,...processCreateParams(w)})}},ZodLazy=class extends ZodType{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};ZodLazy.create=(e,t)=>new ZodLazy({getter:e,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(t)});var ZodLiteral=class extends ZodType{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:`valid`,value:e.data}}get value(){return this._def.value}};ZodLiteral.create=(e,t)=>new ZodLiteral({value:e,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(t)});function createZodEnum(e,t){return new ZodEnum({values:e,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(t)})}var ZodEnum=class e extends ZodType{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),S=this._def.values;return addIssueToContext(t,{expected:util.joinValues(S),received:t.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),S=this._def.values;return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_enum_value,options:S}),INVALID}return OK(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,S=this._def){return e.create(t,{...this._def,...S})}exclude(t,S=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...S})}};ZodEnum.create=createZodEnum;var ZodNativeEnum=class extends ZodType{_parse(e){let t=util.getValidEnumValues(this._def.values),S=this._getOrReturnCtx(e);if(S.parsedType!==ZodParsedType.string&&S.parsedType!==ZodParsedType.number){let e=util.objectValues(t);return addIssueToContext(S,{expected:util.joinValues(e),received:S.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||=new Set(util.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=util.objectValues(t);return addIssueToContext(S,{received:S.data,code:ZodIssueCode.invalid_enum_value,options:e}),INVALID}return OK(e.data)}get enum(){return this._def.values}};ZodNativeEnum.create=(e,t)=>new ZodNativeEnum({values:e,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(t)});var ZodPromise=class extends ZodType{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==ZodParsedType.promise&&t.common.async===!1?(addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:t.parsedType}),INVALID):OK((t.parsedType===ZodParsedType.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};ZodPromise.create=(e,t)=>new ZodPromise({type:e,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(t)});var ZodEffects=class extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:S}=this._processInputParams(e),w=this._def.effect||null,E={addIssue:e=>{addIssueToContext(S,e),e.fatal?t.abort():t.dirty()},get path(){return S.path}};if(E.addIssue=E.addIssue.bind(E),w.type===`preprocess`){let e=w.transform(S.data,E);if(S.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return INVALID;let w=await this._def.schema._parseAsync({data:e,path:S.path,parent:S});return w.status===`aborted`?INVALID:w.status===`dirty`||t.value===`dirty`?DIRTY(w.value):w});{if(t.value===`aborted`)return INVALID;let w=this._def.schema._parseSync({data:e,path:S.path,parent:S});return w.status===`aborted`?INVALID:w.status===`dirty`||t.value===`dirty`?DIRTY(w.value):w}}if(w.type===`refinement`){let e=e=>{let t=w.refinement(e,E);if(S.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(S.common.async===!1){let w=this._def.schema._parseSync({data:S.data,path:S.path,parent:S});return w.status===`aborted`?INVALID:(w.status===`dirty`&&t.dirty(),e(w.value),{status:t.value,value:w.value})}else return this._def.schema._parseAsync({data:S.data,path:S.path,parent:S}).then(S=>S.status===`aborted`?INVALID:(S.status===`dirty`&&t.dirty(),e(S.value).then(()=>({status:t.value,value:S.value}))))}if(w.type===`transform`)if(S.common.async===!1){let e=this._def.schema._parseSync({data:S.data,path:S.path,parent:S});if(!isValid(e))return INVALID;let D=w.transform(e.value,E);if(D instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:D}}else return this._def.schema._parseAsync({data:S.data,path:S.path,parent:S}).then(e=>isValid(e)?Promise.resolve(w.transform(e.value,E)).then(e=>({status:t.value,value:e})):INVALID);util.assertNever(w)}};ZodEffects.create=(e,t,S)=>new ZodEffects({schema:e,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:t,...processCreateParams(S)}),ZodEffects.createWithPreprocess=(e,t,S)=>new ZodEffects({schema:t,effect:{type:`preprocess`,transform:e},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(S)});var ZodOptional=class extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ZodOptional.create=(e,t)=>new ZodOptional({innerType:e,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(t)});var ZodNullable=class extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.null?OK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ZodNullable.create=(e,t)=>new ZodNullable({innerType:e,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(t)});var ZodDefault=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),S=t.data;return t.parsedType===ZodParsedType.undefined&&(S=this._def.defaultValue()),this._def.innerType._parse({data:S,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ZodDefault.create=(e,t)=>new ZodDefault({innerType:e,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...processCreateParams(t)});var ZodCatch=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),S={...t,common:{...t.common,issues:[]}},w=this._def.innerType._parse({data:S.data,path:S.path,parent:{...S}});return isAsync(w)?w.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new ZodError(S.common.issues)},input:S.data})})):{status:`valid`,value:w.status===`valid`?w.value:this._def.catchValue({get error(){return new ZodError(S.common.issues)},input:S.data})}}removeCatch(){return this._def.innerType}};ZodCatch.create=(e,t)=>new ZodCatch({innerType:e,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...processCreateParams(t)});var ZodNaN=class extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.nan){let t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:t.parsedType}),INVALID}return{status:`valid`,value:e.data}}};ZodNaN.create=e=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(e)});var ZodBranded=class extends ZodType{_parse(e){let{ctx:t}=this._processInputParams(e),S=t.data;return this._def.type._parse({data:S,path:t.path,parent:t})}unwrap(){return this._def.type}},ZodPipeline=class e extends ZodType{_parse(e){let{status:t,ctx:S}=this._processInputParams(e);if(S.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:S.data,path:S.path,parent:S});return e.status===`aborted`?INVALID:e.status===`dirty`?(t.dirty(),DIRTY(e.value)):this._def.out._parseAsync({data:e.value,path:S.path,parent:S})})();{let e=this._def.in._parseSync({data:S.data,path:S.path,parent:S});return e.status===`aborted`?INVALID:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:S.path,parent:S})}}static create(t,S){return new e({in:t,out:S,typeName:ZodFirstPartyTypeKind.ZodPipeline})}},ZodReadonly=class extends ZodType{_parse(e){let t=this._def.innerType._parse(e),S=e=>(isValid(e)&&(e.value=Object.freeze(e.value)),e);return isAsync(t)?t.then(e=>S(e)):S(t)}unwrap(){return this._def.innerType}};ZodReadonly.create=(e,t)=>new ZodReadonly({innerType:e,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(t)});const late={object:ZodObject.lazycreate};var ZodFirstPartyTypeKind;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(ZodFirstPartyTypeKind||={});const stringType=ZodString.create,numberType=ZodNumber.create,nanType=ZodNaN.create,bigIntType=ZodBigInt.create,booleanType=ZodBoolean.create,dateType=ZodDate.create,symbolType=ZodSymbol.create,undefinedType=ZodUndefined.create,nullType=ZodNull.create,anyType=ZodAny.create,unknownType=ZodUnknown.create,neverType=ZodNever.create,voidType=ZodVoid.create,arrayType=ZodArray.create,objectType=ZodObject.create,strictObjectType=ZodObject.strictCreate,unionType=ZodUnion.create,discriminatedUnionType=ZodDiscriminatedUnion.create,intersectionType=ZodIntersection.create,tupleType=ZodTuple.create,recordType=ZodRecord.create,mapType=ZodMap.create,setType=ZodSet.create,functionType=ZodFunction.create,lazyType=ZodLazy.create,literalType=ZodLiteral.create,enumType=ZodEnum.create,nativeEnumType=ZodNativeEnum.create,promiseType=ZodPromise.create,effectsType=ZodEffects.create,optionalType=ZodOptional.create,nullableType=ZodNullable.create,preprocessType=ZodEffects.createWithPreprocess,pipelineType=ZodPipeline.create,ZodMiniType=$constructor(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);$ZodType.init(e,t),e.def=t,e.type=t.type,e.parse=(t,S)=>parse$6(e,t,S,{callee:e.parse}),e.safeParse=(t,S)=>safeParse$2(e,t,S),e.parseAsync=async(t,S)=>parseAsync$1(e,t,S,{callee:e.parseAsync}),e.safeParseAsync=async(t,S)=>safeParseAsync$2(e,t,S),e.check=(...S)=>e.clone({...t,checks:[...t.checks??[],...S.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,S)=>clone(e,t,S),e.brand=()=>e,e.register=((t,S)=>(t.add(e,S),e)),e.apply=t=>t(e)}),ZodMiniObject=$constructor(`ZodMiniObject`,(e,t)=>{$ZodObject.init(e,t),ZodMiniType.init(e,t),defineLazy(e,`shape`,()=>t.shape)});function object(e,t){return new ZodMiniObject({type:`object`,shape:e??{},...normalizeParams(t)})}const describe=describe$2,meta=meta$2;function isZ4Schema(e){return!!e._zod}function objectFromShape(e){let t=Object.values(e);if(t.length===0)return object({});let S=t.every(isZ4Schema),w=t.every(e=>!isZ4Schema(e));if(S)return object(e);if(w)return objectType(e);throw Error(`Mixed Zod versions detected in object shape.`)}function safeParse(e,t){return isZ4Schema(e)?safeParse$2(e,t):e.safeParse(t)}async function safeParseAsync(e,t){return isZ4Schema(e)?await safeParseAsync$2(e,t):await e.safeParseAsync(t)}function getObjectShape(e){if(!e)return;let t;if(t=isZ4Schema(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function normalizeObjectSchema(e){if(e){if(typeof e==`object`){let t=e,S=e;if(!t._def&&!S._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return objectFromShape(e)}}if(isZ4Schema(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function getParseErrorMessage(e){if(e&&typeof e==`object`){if(`message`in e&&typeof e.message==`string`)return e.message;if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&typeof t==`object`&&`message`in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function getSchemaDescription(e){return e.description}function isSchemaOptional(e){if(isZ4Schema(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function getLiteralValue(e){if(isZ4Schema(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let S=e.value;if(S!==void 0)return S}const LATEST_PROTOCOL_VERSION=`2025-11-25`,DEFAULT_NEGOTIATED_PROTOCOL_VERSION=`2025-03-26`,SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],RELATED_TASK_META_KEY=`io.modelcontextprotocol/related-task`,JSONRPC_VERSION=`2.0`,AssertObjectSchema=custom(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),ProgressTokenSchema=union([string$2(),number$1().int()]),CursorSchema=string$2(),TaskCreationParamsSchema=looseObject({ttl:number$1().optional(),pollInterval:number$1().optional()}),TaskMetadataSchema=object$1({ttl:number$1().optional()}),RelatedTaskMetadataSchema=object$1({taskId:string$2()}),RequestMetaSchema=looseObject({progressToken:ProgressTokenSchema.optional(),[RELATED_TASK_META_KEY]:RelatedTaskMetadataSchema.optional()}),BaseRequestParamsSchema=object$1({_meta:RequestMetaSchema.optional()}),TaskAugmentedRequestParamsSchema=BaseRequestParamsSchema.extend({task:TaskMetadataSchema.optional()}),isTaskAugmentedRequestParams=e=>TaskAugmentedRequestParamsSchema.safeParse(e).success,RequestSchema=object$1({method:string$2(),params:BaseRequestParamsSchema.loose().optional()}),NotificationsParamsSchema=object$1({_meta:RequestMetaSchema.optional()}),NotificationSchema=object$1({method:string$2(),params:NotificationsParamsSchema.loose().optional()}),ResultSchema=looseObject({_meta:RequestMetaSchema.optional()}),RequestIdSchema=union([string$2(),number$1().int()]),JSONRPCRequestSchema=object$1({jsonrpc:literal(`2.0`),id:RequestIdSchema,...RequestSchema.shape}).strict(),isJSONRPCRequest=e=>JSONRPCRequestSchema.safeParse(e).success,JSONRPCNotificationSchema=object$1({jsonrpc:literal(`2.0`),...NotificationSchema.shape}).strict(),isJSONRPCNotification=e=>JSONRPCNotificationSchema.safeParse(e).success,JSONRPCResultResponseSchema=object$1({jsonrpc:literal(`2.0`),id:RequestIdSchema,result:ResultSchema}).strict(),isJSONRPCResultResponse=e=>JSONRPCResultResponseSchema.safeParse(e).success;var ErrorCode;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(ErrorCode||={});const JSONRPCErrorResponseSchema=object$1({jsonrpc:literal(`2.0`),id:RequestIdSchema.optional(),error:object$1({code:number$1().int(),message:string$2(),data:unknown$2().optional()})}).strict(),isJSONRPCErrorResponse=e=>JSONRPCErrorResponseSchema.safeParse(e).success,JSONRPCMessageSchema=union([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),JSONRPCResponseSchema=union([JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),EmptyResultSchema=ResultSchema.strict(),CancelledNotificationParamsSchema=NotificationsParamsSchema.extend({requestId:RequestIdSchema.optional(),reason:string$2().optional()}),CancelledNotificationSchema=NotificationSchema.extend({method:literal(`notifications/cancelled`),params:CancelledNotificationParamsSchema}),IconSchema=object$1({src:string$2(),mimeType:string$2().optional(),sizes:array(string$2()).optional(),theme:_enum([`light`,`dark`]).optional()}),IconsSchema=object$1({icons:array(IconSchema).optional()}),BaseMetadataSchema=object$1({name:string$2(),title:string$2().optional()}),ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:string$2(),websiteUrl:string$2().optional(),description:string$2().optional()}),FormElicitationCapabilitySchema=intersection(object$1({applyDefaults:boolean$1().optional()}),record(string$2(),unknown$2())),ElicitationCapabilitySchema=preprocess$1(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,intersection(object$1({form:FormElicitationCapabilitySchema.optional(),url:AssertObjectSchema.optional()}),record(string$2(),unknown$2()).optional())),ClientTasksCapabilitySchema=looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:looseObject({sampling:looseObject({createMessage:AssertObjectSchema.optional()}).optional(),elicitation:looseObject({create:AssertObjectSchema.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema=looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:looseObject({tools:looseObject({call:AssertObjectSchema.optional()}).optional()}).optional()}),ClientCapabilitiesSchema=object$1({experimental:record(string$2(),AssertObjectSchema).optional(),sampling:object$1({context:AssertObjectSchema.optional(),tools:AssertObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema.optional(),roots:object$1({listChanged:boolean$1().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional(),extensions:record(string$2(),AssertObjectSchema).optional()}),InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:string$2(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema}),InitializeRequestSchema=RequestSchema.extend({method:literal(`initialize`),params:InitializeRequestParamsSchema}),isInitializeRequest=e=>InitializeRequestSchema.safeParse(e).success,ServerCapabilitiesSchema=object$1({experimental:record(string$2(),AssertObjectSchema).optional(),logging:AssertObjectSchema.optional(),completions:AssertObjectSchema.optional(),prompts:object$1({listChanged:boolean$1().optional()}).optional(),resources:object$1({subscribe:boolean$1().optional(),listChanged:boolean$1().optional()}).optional(),tools:object$1({listChanged:boolean$1().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional(),extensions:record(string$2(),AssertObjectSchema).optional()}),InitializeResultSchema=ResultSchema.extend({protocolVersion:string$2(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:string$2().optional()}),InitializedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/initialized`),params:NotificationsParamsSchema.optional()}),isInitializedNotification=e=>InitializedNotificationSchema.safeParse(e).success,PingRequestSchema=RequestSchema.extend({method:literal(`ping`),params:BaseRequestParamsSchema.optional()}),ProgressSchema=object$1({progress:number$1(),total:optional(number$1()),message:optional(string$2())}),ProgressNotificationParamsSchema=object$1({...NotificationsParamsSchema.shape,...ProgressSchema.shape,progressToken:ProgressTokenSchema}),ProgressNotificationSchema=NotificationSchema.extend({method:literal(`notifications/progress`),params:ProgressNotificationParamsSchema}),PaginatedRequestParamsSchema=BaseRequestParamsSchema.extend({cursor:CursorSchema.optional()}),PaginatedRequestSchema=RequestSchema.extend({params:PaginatedRequestParamsSchema.optional()}),PaginatedResultSchema=ResultSchema.extend({nextCursor:CursorSchema.optional()}),TaskStatusSchema=_enum([`working`,`input_required`,`completed`,`failed`,`cancelled`]),TaskSchema=object$1({taskId:string$2(),status:TaskStatusSchema,ttl:union([number$1(),_null()]),createdAt:string$2(),lastUpdatedAt:string$2(),pollInterval:optional(number$1()),statusMessage:optional(string$2())}),CreateTaskResultSchema=ResultSchema.extend({task:TaskSchema}),TaskStatusNotificationParamsSchema=NotificationsParamsSchema.merge(TaskSchema),TaskStatusNotificationSchema=NotificationSchema.extend({method:literal(`notifications/tasks/status`),params:TaskStatusNotificationParamsSchema}),GetTaskRequestSchema=RequestSchema.extend({method:literal(`tasks/get`),params:BaseRequestParamsSchema.extend({taskId:string$2()})}),GetTaskResultSchema=ResultSchema.merge(TaskSchema),GetTaskPayloadRequestSchema=RequestSchema.extend({method:literal(`tasks/result`),params:BaseRequestParamsSchema.extend({taskId:string$2()})}),GetTaskPayloadResultSchema=ResultSchema.loose(),ListTasksRequestSchema=PaginatedRequestSchema.extend({method:literal(`tasks/list`)}),ListTasksResultSchema=PaginatedResultSchema.extend({tasks:array(TaskSchema)}),CancelTaskRequestSchema=RequestSchema.extend({method:literal(`tasks/cancel`),params:BaseRequestParamsSchema.extend({taskId:string$2()})}),CancelTaskResultSchema=ResultSchema.merge(TaskSchema),ResourceContentsSchema=object$1({uri:string$2(),mimeType:optional(string$2()),_meta:record(string$2(),unknown$2()).optional()}),TextResourceContentsSchema=ResourceContentsSchema.extend({text:string$2()}),Base64Schema=string$2().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:Base64Schema}),RoleSchema=_enum([`user`,`assistant`]),AnnotationsSchema=object$1({audience:array(RoleSchema).optional(),priority:number$1().min(0).max(1).optional(),lastModified:datetime({offset:!0}).optional()}),ResourceSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:string$2(),description:optional(string$2()),mimeType:optional(string$2()),size:optional(number$1()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ResourceTemplateSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:string$2(),description:optional(string$2()),mimeType:optional(string$2()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:literal(`resources/list`)}),ListResourcesResultSchema=PaginatedResultSchema.extend({resources:array(ResourceSchema)}),ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:literal(`resources/templates/list`)}),ListResourceTemplatesResultSchema=PaginatedResultSchema.extend({resourceTemplates:array(ResourceTemplateSchema)}),ResourceRequestParamsSchema=BaseRequestParamsSchema.extend({uri:string$2()}),ReadResourceRequestParamsSchema=ResourceRequestParamsSchema,ReadResourceRequestSchema=RequestSchema.extend({method:literal(`resources/read`),params:ReadResourceRequestParamsSchema}),ReadResourceResultSchema=ResultSchema.extend({contents:array(union([TextResourceContentsSchema,BlobResourceContentsSchema]))}),ResourceListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/resources/list_changed`),params:NotificationsParamsSchema.optional()}),SubscribeRequestParamsSchema=ResourceRequestParamsSchema,SubscribeRequestSchema=RequestSchema.extend({method:literal(`resources/subscribe`),params:SubscribeRequestParamsSchema}),UnsubscribeRequestParamsSchema=ResourceRequestParamsSchema,UnsubscribeRequestSchema=RequestSchema.extend({method:literal(`resources/unsubscribe`),params:UnsubscribeRequestParamsSchema}),ResourceUpdatedNotificationParamsSchema=NotificationsParamsSchema.extend({uri:string$2()}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/resources/updated`),params:ResourceUpdatedNotificationParamsSchema}),PromptArgumentSchema=object$1({name:string$2(),description:optional(string$2()),required:optional(boolean$1())}),PromptSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,description:optional(string$2()),arguments:optional(array(PromptArgumentSchema)),_meta:optional(looseObject({}))}),ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:literal(`prompts/list`)}),ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:array(PromptSchema)}),GetPromptRequestParamsSchema=BaseRequestParamsSchema.extend({name:string$2(),arguments:record(string$2(),string$2()).optional()}),GetPromptRequestSchema=RequestSchema.extend({method:literal(`prompts/get`),params:GetPromptRequestParamsSchema}),TextContentSchema=object$1({type:literal(`text`),text:string$2(),annotations:AnnotationsSchema.optional(),_meta:record(string$2(),unknown$2()).optional()}),ImageContentSchema=object$1({type:literal(`image`),data:Base64Schema,mimeType:string$2(),annotations:AnnotationsSchema.optional(),_meta:record(string$2(),unknown$2()).optional()}),AudioContentSchema=object$1({type:literal(`audio`),data:Base64Schema,mimeType:string$2(),annotations:AnnotationsSchema.optional(),_meta:record(string$2(),unknown$2()).optional()}),ToolUseContentSchema=object$1({type:literal(`tool_use`),name:string$2(),id:string$2(),input:record(string$2(),unknown$2()),_meta:record(string$2(),unknown$2()).optional()}),EmbeddedResourceSchema=object$1({type:literal(`resource`),resource:union([TextResourceContentsSchema,BlobResourceContentsSchema]),annotations:AnnotationsSchema.optional(),_meta:record(string$2(),unknown$2()).optional()}),ResourceLinkSchema=ResourceSchema.extend({type:literal(`resource_link`)}),ContentBlockSchema=union([TextContentSchema,ImageContentSchema,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema]),PromptMessageSchema=object$1({role:RoleSchema,content:ContentBlockSchema}),GetPromptResultSchema=ResultSchema.extend({description:string$2().optional(),messages:array(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/prompts/list_changed`),params:NotificationsParamsSchema.optional()}),ToolAnnotationsSchema=object$1({title:string$2().optional(),readOnlyHint:boolean$1().optional(),destructiveHint:boolean$1().optional(),idempotentHint:boolean$1().optional(),openWorldHint:boolean$1().optional()}),ToolExecutionSchema=object$1({taskSupport:_enum([`required`,`optional`,`forbidden`]).optional()}),ToolSchema=object$1({...BaseMetadataSchema.shape,...IconsSchema.shape,description:string$2().optional(),inputSchema:object$1({type:literal(`object`),properties:record(string$2(),AssertObjectSchema).optional(),required:array(string$2()).optional()}).catchall(unknown$2()),outputSchema:object$1({type:literal(`object`),properties:record(string$2(),AssertObjectSchema).optional(),required:array(string$2()).optional()}).catchall(unknown$2()).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:record(string$2(),unknown$2()).optional()}),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:literal(`tools/list`)}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:array(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:array(ContentBlockSchema).default([]),structuredContent:record(string$2(),unknown$2()).optional(),isError:boolean$1().optional()}),CompatibilityCallToolResultSchema=CallToolResultSchema.or(ResultSchema.extend({toolResult:unknown$2()})),CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:string$2(),arguments:record(string$2(),unknown$2()).optional()}),CallToolRequestSchema=RequestSchema.extend({method:literal(`tools/call`),params:CallToolRequestParamsSchema}),ToolListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/tools/list_changed`),params:NotificationsParamsSchema.optional()}),ListChangedOptionsBaseSchema=object$1({autoRefresh:boolean$1().default(!0),debounceMs:number$1().int().nonnegative().default(300)}),LoggingLevelSchema=_enum([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),SetLevelRequestParamsSchema=BaseRequestParamsSchema.extend({level:LoggingLevelSchema}),SetLevelRequestSchema=RequestSchema.extend({method:literal(`logging/setLevel`),params:SetLevelRequestParamsSchema}),LoggingMessageNotificationParamsSchema=NotificationsParamsSchema.extend({level:LoggingLevelSchema,logger:string$2().optional(),data:unknown$2()}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:literal(`notifications/message`),params:LoggingMessageNotificationParamsSchema}),ModelHintSchema=object$1({name:string$2().optional()}),ModelPreferencesSchema=object$1({hints:array(ModelHintSchema).optional(),costPriority:number$1().min(0).max(1).optional(),speedPriority:number$1().min(0).max(1).optional(),intelligencePriority:number$1().min(0).max(1).optional()}),ToolChoiceSchema=object$1({mode:_enum([`auto`,`required`,`none`]).optional()}),ToolResultContentSchema=object$1({type:literal(`tool_result`),toolUseId:string$2().describe(`The unique identifier for the corresponding tool call.`),content:array(ContentBlockSchema).default([]),structuredContent:object$1({}).loose().optional(),isError:boolean$1().optional(),_meta:record(string$2(),unknown$2()).optional()}),SamplingContentSchema=discriminatedUnion(`type`,[TextContentSchema,ImageContentSchema,AudioContentSchema]),SamplingMessageContentBlockSchema=discriminatedUnion(`type`,[TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,ToolResultContentSchema]),SamplingMessageSchema=object$1({role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)]),_meta:record(string$2(),unknown$2()).optional()}),CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:array(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:string$2().optional(),includeContext:_enum([`none`,`thisServer`,`allServers`]).optional(),temperature:number$1().optional(),maxTokens:number$1().int(),stopSequences:array(string$2()).optional(),metadata:AssertObjectSchema.optional(),tools:array(ToolSchema).optional(),toolChoice:ToolChoiceSchema.optional()}),CreateMessageRequestSchema=RequestSchema.extend({method:literal(`sampling/createMessage`),params:CreateMessageRequestParamsSchema}),CreateMessageResultSchema=ResultSchema.extend({model:string$2(),stopReason:optional(_enum([`endTurn`,`stopSequence`,`maxTokens`]).or(string$2())),role:RoleSchema,content:SamplingContentSchema}),CreateMessageResultWithToolsSchema=ResultSchema.extend({model:string$2(),stopReason:optional(_enum([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(string$2())),role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)])}),BooleanSchemaSchema=object$1({type:literal(`boolean`),title:string$2().optional(),description:string$2().optional(),default:boolean$1().optional()}),StringSchemaSchema=object$1({type:literal(`string`),title:string$2().optional(),description:string$2().optional(),minLength:number$1().optional(),maxLength:number$1().optional(),format:_enum([`email`,`uri`,`date`,`date-time`]).optional(),default:string$2().optional()}),NumberSchemaSchema=object$1({type:_enum([`number`,`integer`]),title:string$2().optional(),description:string$2().optional(),minimum:number$1().optional(),maximum:number$1().optional(),default:number$1().optional()}),UntitledSingleSelectEnumSchemaSchema=object$1({type:literal(`string`),title:string$2().optional(),description:string$2().optional(),enum:array(string$2()),default:string$2().optional()}),TitledSingleSelectEnumSchemaSchema=object$1({type:literal(`string`),title:string$2().optional(),description:string$2().optional(),oneOf:array(object$1({const:string$2(),title:string$2()})),default:string$2().optional()}),LegacyTitledEnumSchemaSchema=object$1({type:literal(`string`),title:string$2().optional(),description:string$2().optional(),enum:array(string$2()),enumNames:array(string$2()).optional(),default:string$2().optional()}),SingleSelectEnumSchemaSchema=union([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]),UntitledMultiSelectEnumSchemaSchema=object$1({type:literal(`array`),title:string$2().optional(),description:string$2().optional(),minItems:number$1().optional(),maxItems:number$1().optional(),items:object$1({type:literal(`string`),enum:array(string$2())}),default:array(string$2()).optional()}),TitledMultiSelectEnumSchemaSchema=object$1({type:literal(`array`),title:string$2().optional(),description:string$2().optional(),minItems:number$1().optional(),maxItems:number$1().optional(),items:object$1({anyOf:array(object$1({const:string$2(),title:string$2()}))}),default:array(string$2()).optional()}),MultiSelectEnumSchemaSchema=union([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema]),EnumSchemaSchema=union([LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema]),PrimitiveSchemaDefinitionSchema=union([EnumSchemaSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema]),ElicitRequestFormParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal(`form`).optional(),message:string$2(),requestedSchema:object$1({type:literal(`object`),properties:record(string$2(),PrimitiveSchemaDefinitionSchema),required:array(string$2()).optional()})}),ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal(`url`),message:string$2(),elicitationId:string$2(),url:string$2().url()}),ElicitRequestParamsSchema=union([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]),ElicitRequestSchema=RequestSchema.extend({method:literal(`elicitation/create`),params:ElicitRequestParamsSchema}),ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:string$2()}),ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:literal(`notifications/elicitation/complete`),params:ElicitationCompleteNotificationParamsSchema}),ElicitResultSchema=ResultSchema.extend({action:_enum([`accept`,`decline`,`cancel`]),content:preprocess$1(e=>e===null?void 0:e,record(string$2(),union([string$2(),number$1(),boolean$1(),array(string$2())])).optional())}),ResourceTemplateReferenceSchema=object$1({type:literal(`ref/resource`),uri:string$2()}),PromptReferenceSchema=object$1({type:literal(`ref/prompt`),name:string$2()}),CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:union([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:object$1({name:string$2(),value:string$2()}),context:object$1({arguments:record(string$2(),string$2()).optional()}).optional()}),CompleteRequestSchema=RequestSchema.extend({method:literal(`completion/complete`),params:CompleteRequestParamsSchema});function assertCompleteRequestPrompt(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function assertCompleteRequestResourceTemplate(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const CompleteResultSchema=ResultSchema.extend({completion:looseObject({values:array(string$2()).max(100),total:optional(number$1().int()),hasMore:optional(boolean$1())})}),RootSchema=object$1({uri:string$2().startsWith(`file://`),name:string$2().optional(),_meta:record(string$2(),unknown$2()).optional()}),ListRootsRequestSchema=RequestSchema.extend({method:literal(`roots/list`),params:BaseRequestParamsSchema.optional()}),ListRootsResultSchema=ResultSchema.extend({roots:array(RootSchema)}),RootsListChangedNotificationSchema=NotificationSchema.extend({method:literal(`notifications/roots/list_changed`),params:NotificationsParamsSchema.optional()}),ClientRequestSchema=union([PingRequestSchema,InitializeRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,CallToolRequestSchema,ListToolsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ClientNotificationSchema=union([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema,TaskStatusNotificationSchema]),ClientResultSchema=union([EmptyResultSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,ElicitResultSchema,ListRootsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),ServerRequestSchema=union([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ServerNotificationSchema=union([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema,TaskStatusNotificationSchema,ElicitationCompleteNotificationSchema]),ServerResultSchema=union([EmptyResultSchema,InitializeResultSchema,CompleteResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListResourceTemplatesResultSchema,ReadResourceResultSchema,CallToolResultSchema,ListToolsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]);var McpError=class e extends Error{constructor(e,t,S){super(`MCP error ${e}: ${t}`),this.code=e,this.data=S,this.name=`McpError`}static fromError(t,S,w){if(t===ErrorCode.UrlElicitationRequired&&w){let e=w;if(e.elicitations)return new UrlElicitationRequiredError(e.elicitations,S)}return new e(t,S,w)}},UrlElicitationRequiredError=class extends McpError{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(ErrorCode.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function isTerminal(e){return e===`completed`||e===`failed`||e===`cancelled`}const ignoreOverride=Symbol(`Let zodToJsonSchema decide on which parser to use`),defaultOptions={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},getDefaultOptions=e=>typeof e==`string`?{...defaultOptions,name:e}:{...defaultOptions,...e},getRefs=e=>{let t=getDefaultOptions(e),S=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:S,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,S])=>[S._def,{def:S._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function addErrorMessage(e,t,S,w){w?.errorMessages&&S&&(e.errorMessage={...e.errorMessage,[t]:S})}function setResponseValueAndErrors(e,t,S,w,E){e[t]=S,addErrorMessage(e,t,w,E)}const getRelativePath=(e,t)=>{let S=0;for(;S<e.length&&S<t.length&&e[S]===t[S];S++);return[(e.length-S).toString(),...t.slice(S)].join(`/`)};function parseAnyDef(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?getRelativePath(t,e.currentPath):t.join(`/`)}}function parseArrayDef(e,t){let S={type:`array`};return e.type?._def&&e.type?._def?.typeName!==ZodFirstPartyTypeKind.ZodAny&&(S.items=parseDef(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&setResponseValueAndErrors(S,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&setResponseValueAndErrors(S,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(setResponseValueAndErrors(S,`minItems`,e.exactLength.value,e.exactLength.message,t),setResponseValueAndErrors(S,`maxItems`,e.exactLength.value,e.exactLength.message,t)),S}function parseBigintDef(e,t){let S={type:`integer`,format:`int64`};if(!e.checks)return S;for(let w of e.checks)switch(w.kind){case`min`:t.target===`jsonSchema7`?w.inclusive?setResponseValueAndErrors(S,`minimum`,w.value,w.message,t):setResponseValueAndErrors(S,`exclusiveMinimum`,w.value,w.message,t):(w.inclusive||(S.exclusiveMinimum=!0),setResponseValueAndErrors(S,`minimum`,w.value,w.message,t));break;case`max`:t.target===`jsonSchema7`?w.inclusive?setResponseValueAndErrors(S,`maximum`,w.value,w.message,t):setResponseValueAndErrors(S,`exclusiveMaximum`,w.value,w.message,t):(w.inclusive||(S.exclusiveMaximum=!0),setResponseValueAndErrors(S,`maximum`,w.value,w.message,t));break;case`multipleOf`:setResponseValueAndErrors(S,`multipleOf`,w.value,w.message,t);break}return S}function parseBooleanDef(){return{type:`boolean`}}function parseBrandedDef(e,t){return parseDef(e.type._def,t)}const parseCatchDef=(e,t)=>parseDef(e.innerType._def,t);function parseDateDef(e,t,S){let w=S??t.dateStrategy;if(Array.isArray(w))return{anyOf:w.map((S,w)=>parseDateDef(e,t,S))};switch(w){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return integerDateParser(e,t)}}const integerDateParser=(e,t)=>{let S={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return S;for(let w of e.checks)switch(w.kind){case`min`:setResponseValueAndErrors(S,`minimum`,w.value,w.message,t);break;case`max`:setResponseValueAndErrors(S,`maximum`,w.value,w.message,t);break}return S};function parseDefaultDef(e,t){return{...parseDef(e.innerType._def,t),default:e.defaultValue()}}function parseEffectsDef(e,t){return t.effectStrategy===`input`?parseDef(e.schema._def,t):parseAnyDef(t)}function parseEnumDef(e){return{type:`string`,enum:Array.from(e.values)}}const isJsonSchema7AllOfType=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function parseIntersectionDef(e,t){let S=[parseDef(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),parseDef(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),w=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,E=[];return S.forEach(e=>{if(isJsonSchema7AllOfType(e))E.push(...e.allOf),e.unevaluatedProperties===void 0&&(w=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:S,...w}=e;t=w}else w=void 0;E.push(t)}}),E.length?{allOf:E,...w}:void 0}function parseLiteralDef(e,t){let S=typeof e.value;return S!==`bigint`&&S!==`number`&&S!==`boolean`&&S!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:S===`bigint`?`integer`:S,enum:[e.value]}:{type:S===`bigint`?`integer`:S,const:e.value}}let emojiRegex;const zodPatterns={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(emojiRegex===void 0&&(emojiRegex=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),emojiRegex),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function parseStringDef(e,t){let S={type:`string`};if(e.checks)for(let w of e.checks)switch(w.kind){case`min`:setResponseValueAndErrors(S,`minLength`,typeof S.minLength==`number`?Math.max(S.minLength,w.value):w.value,w.message,t);break;case`max`:setResponseValueAndErrors(S,`maxLength`,typeof S.maxLength==`number`?Math.min(S.maxLength,w.value):w.value,w.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:addFormat(S,`email`,w.message,t);break;case`format:idn-email`:addFormat(S,`idn-email`,w.message,t);break;case`pattern:zod`:addPattern(S,zodPatterns.email,w.message,t);break}break;case`url`:addFormat(S,`uri`,w.message,t);break;case`uuid`:addFormat(S,`uuid`,w.message,t);break;case`regex`:addPattern(S,w.regex,w.message,t);break;case`cuid`:addPattern(S,zodPatterns.cuid,w.message,t);break;case`cuid2`:addPattern(S,zodPatterns.cuid2,w.message,t);break;case`startsWith`:addPattern(S,RegExp(`^${escapeLiteralCheckValue(w.value,t)}`),w.message,t);break;case`endsWith`:addPattern(S,RegExp(`${escapeLiteralCheckValue(w.value,t)}$`),w.message,t);break;case`datetime`:addFormat(S,`date-time`,w.message,t);break;case`date`:addFormat(S,`date`,w.message,t);break;case`time`:addFormat(S,`time`,w.message,t);break;case`duration`:addFormat(S,`duration`,w.message,t);break;case`length`:setResponseValueAndErrors(S,`minLength`,typeof S.minLength==`number`?Math.max(S.minLength,w.value):w.value,w.message,t),setResponseValueAndErrors(S,`maxLength`,typeof S.maxLength==`number`?Math.min(S.maxLength,w.value):w.value,w.message,t);break;case`includes`:addPattern(S,RegExp(escapeLiteralCheckValue(w.value,t)),w.message,t);break;case`ip`:w.version!==`v6`&&addFormat(S,`ipv4`,w.message,t),w.version!==`v4`&&addFormat(S,`ipv6`,w.message,t);break;case`base64url`:addPattern(S,zodPatterns.base64url,w.message,t);break;case`jwt`:addPattern(S,zodPatterns.jwt,w.message,t);break;case`cidr`:w.version!==`v6`&&addPattern(S,zodPatterns.ipv4Cidr,w.message,t),w.version!==`v4`&&addPattern(S,zodPatterns.ipv6Cidr,w.message,t);break;case`emoji`:addPattern(S,zodPatterns.emoji(),w.message,t);break;case`ulid`:addPattern(S,zodPatterns.ulid,w.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:addFormat(S,`binary`,w.message,t);break;case`contentEncoding:base64`:setResponseValueAndErrors(S,`contentEncoding`,`base64`,w.message,t);break;case`pattern:zod`:addPattern(S,zodPatterns.base64,w.message,t);break}break;case`nanoid`:addPattern(S,zodPatterns.nanoid,w.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(w)}return S}function escapeLiteralCheckValue(e,t){return t.patternStrategy===`escape`?escapeNonAlphaNumeric(e):e}const ALPHA_NUMERIC=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function escapeNonAlphaNumeric(e){let t=``;for(let S=0;S<e.length;S++)ALPHA_NUMERIC.has(e[S])||(t+=`\\`),t+=e[S];return t}function addFormat(e,t,S,w){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&w.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...S&&w.errorMessages&&{errorMessage:{format:S}}})):setResponseValueAndErrors(e,`format`,t,S,w)}function addPattern(e,t,S,w){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&w.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:stringifyRegExpWithFlags(t,w),...S&&w.errorMessages&&{errorMessage:{pattern:S}}})):setResponseValueAndErrors(e,`pattern`,stringifyRegExpWithFlags(t,w),S,w)}function stringifyRegExpWithFlags(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let S={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},w=S.i?e.source.toLowerCase():e.source,E=``,D=!1,O=!1,k=!1;for(let e=0;e<w.length;e++){if(D){E+=w[e],D=!1;continue}if(S.i){if(O){if(w[e].match(/[a-z]/)){k?(E+=w[e],E+=`${w[e-2]}-${w[e]}`.toUpperCase(),k=!1):w[e+1]===`-`&&w[e+2]?.match(/[a-z]/)?(E+=w[e],k=!0):E+=`${w[e]}${w[e].toUpperCase()}`;continue}}else if(w[e].match(/[a-z]/)){E+=`[${w[e]}${w[e].toUpperCase()}]`;continue}}if(S.m){if(w[e]===`^`){E+=`(^|(?<=[\r
|
|
474
474
|
]))`;continue}else if(w[e]===`$`){E+=`($|(?=[\r
|
|
475
475
|
]))`;continue}}if(S.s&&w[e]===`.`){E+=O?`${w[e]}\r\n`:`[${w[e]}\r\n]`;continue}E+=w[e],w[e]===`\\`?D=!0:O&&w[e]===`]`?O=!1:!O&&w[e]===`[`&&(O=!0)}try{new RegExp(E)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return E}function parseRecordDef(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((S,w)=>({...S,[w]:parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,w]})??parseAnyDef(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let S={type:`object`,additionalProperties:parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return S;if(e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodString&&e.keyType._def.checks?.length){let{type:w,...E}=parseStringDef(e.keyType._def,t);return{...S,propertyNames:E}}else if(e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum)return{...S,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodBranded&&e.keyType._def.type._def.typeName===ZodFirstPartyTypeKind.ZodString&&e.keyType._def.type._def.checks?.length){let{type:w,...E}=parseBrandedDef(e.keyType._def,t);return{...S,propertyNames:E}}return S}function parseMapDef(e,t){return t.mapStrategy===`record`?parseRecordDef(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[parseDef(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||parseAnyDef(t),parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||parseAnyDef(t)],minItems:2,maxItems:2}}}function parseNativeEnumDef(e){let t=e.values,S=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),w=Array.from(new Set(S.map(e=>typeof e)));return{type:w.length===1?w[0]===`string`?`string`:`number`:[`string`,`number`],enum:S}}function parseNeverDef(e){return e.target===`openAi`?void 0:{not:parseAnyDef({...e,currentPath:[...e.currentPath,`not`]})}}function parseNullDef(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const primitiveMappings={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function parseUnionDef(e,t){if(t.target===`openApi3`)return asAnyOf(e,t);let S=e.options instanceof Map?Array.from(e.options.values()):e.options;if(S.every(e=>e._def.typeName in primitiveMappings&&(!e._def.checks||!e._def.checks.length))){let e=S.reduce((e,t)=>{let S=primitiveMappings[t._def.typeName];return S&&!e.includes(S)?[...e,S]:e},[]);return{type:e.length>1?e:e[0]}}else if(S.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=S.reduce((e,t)=>{let S=typeof t._def.value;switch(S){case`string`:case`number`:case`boolean`:return[...e,S];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===S.length){let t=e.filter((e,t,S)=>S.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:S.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(S.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:S.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return asAnyOf(e,t)}const asAnyOf=(e,t)=>{let S=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,S)=>parseDef(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${S}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return S.length?{anyOf:S}:void 0};function parseNullableDef(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:primitiveMappings[e.innerType._def.typeName],nullable:!0}:{type:[primitiveMappings[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let S=parseDef(e.innerType._def,{...t,currentPath:[...t.currentPath]});return S&&`$ref`in S?{allOf:[S],nullable:!0}:S&&{...S,nullable:!0}}let S=parseDef(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return S&&{anyOf:[S,{type:`null`}]}}function parseNumberDef(e,t){let S={type:`number`};if(!e.checks)return S;for(let w of e.checks)switch(w.kind){case`int`:S.type=`integer`,addErrorMessage(S,`type`,w.message,t);break;case`min`:t.target===`jsonSchema7`?w.inclusive?setResponseValueAndErrors(S,`minimum`,w.value,w.message,t):setResponseValueAndErrors(S,`exclusiveMinimum`,w.value,w.message,t):(w.inclusive||(S.exclusiveMinimum=!0),setResponseValueAndErrors(S,`minimum`,w.value,w.message,t));break;case`max`:t.target===`jsonSchema7`?w.inclusive?setResponseValueAndErrors(S,`maximum`,w.value,w.message,t):setResponseValueAndErrors(S,`exclusiveMaximum`,w.value,w.message,t):(w.inclusive||(S.exclusiveMaximum=!0),setResponseValueAndErrors(S,`maximum`,w.value,w.message,t));break;case`multipleOf`:setResponseValueAndErrors(S,`multipleOf`,w.value,w.message,t);break}return S}function parseObjectDef(e,t){let S=t.target===`openAi`,w={type:`object`,properties:{}},E=[],D=e.shape();for(let e in D){let O=D[e];if(O===void 0||O._def===void 0)continue;let k=safeIsOptional(O);k&&S&&(O._def.typeName===`ZodOptional`&&(O=O._def.innerType),O.isNullable()||(O=O.nullable()),k=!1);let j=parseDef(O._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});j!==void 0&&(w.properties[e]=j,k||E.push(e))}E.length&&(w.required=E);let O=decideAdditionalProperties(e,t);return O!==void 0&&(w.additionalProperties=O),w}function decideAdditionalProperties(e,t){if(e.catchall._def.typeName!==`ZodNever`)return parseDef(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function safeIsOptional(e){try{return e.isOptional()}catch{return!0}}const parseOptionalDef=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return parseDef(e.innerType._def,t);let S=parseDef(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return S?{anyOf:[{not:parseAnyDef(t)},S]}:parseAnyDef(t)},parsePipelineDef=(e,t)=>{if(t.pipeStrategy===`input`)return parseDef(e.in._def,t);if(t.pipeStrategy===`output`)return parseDef(e.out._def,t);let S=parseDef(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[S,parseDef(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,S?`1`:`0`]})].filter(e=>e!==void 0)}};function parsePromiseDef(e,t){return parseDef(e.type._def,t)}function parseSetDef(e,t){let S={type:`array`,uniqueItems:!0,items:parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&setResponseValueAndErrors(S,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&setResponseValueAndErrors(S,`maxItems`,e.maxSize.value,e.maxSize.message,t),S}function parseTupleDef(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,S)=>parseDef(e._def,{...t,currentPath:[...t.currentPath,`items`,`${S}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:parseDef(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,S)=>parseDef(e._def,{...t,currentPath:[...t.currentPath,`items`,`${S}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function parseUndefinedDef(e){return{not:parseAnyDef(e)}}function parseUnknownDef(e){return parseAnyDef(e)}const parseReadonlyDef=(e,t)=>parseDef(e.innerType._def,t),selectParser=(e,t,S)=>{switch(t){case ZodFirstPartyTypeKind.ZodString:return parseStringDef(e,S);case ZodFirstPartyTypeKind.ZodNumber:return parseNumberDef(e,S);case ZodFirstPartyTypeKind.ZodObject:return parseObjectDef(e,S);case ZodFirstPartyTypeKind.ZodBigInt:return parseBigintDef(e,S);case ZodFirstPartyTypeKind.ZodBoolean:return parseBooleanDef();case ZodFirstPartyTypeKind.ZodDate:return parseDateDef(e,S);case ZodFirstPartyTypeKind.ZodUndefined:return parseUndefinedDef(S);case ZodFirstPartyTypeKind.ZodNull:return parseNullDef(S);case ZodFirstPartyTypeKind.ZodArray:return parseArrayDef(e,S);case ZodFirstPartyTypeKind.ZodUnion:case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return parseUnionDef(e,S);case ZodFirstPartyTypeKind.ZodIntersection:return parseIntersectionDef(e,S);case ZodFirstPartyTypeKind.ZodTuple:return parseTupleDef(e,S);case ZodFirstPartyTypeKind.ZodRecord:return parseRecordDef(e,S);case ZodFirstPartyTypeKind.ZodLiteral:return parseLiteralDef(e,S);case ZodFirstPartyTypeKind.ZodEnum:return parseEnumDef(e);case ZodFirstPartyTypeKind.ZodNativeEnum:return parseNativeEnumDef(e);case ZodFirstPartyTypeKind.ZodNullable:return parseNullableDef(e,S);case ZodFirstPartyTypeKind.ZodOptional:return parseOptionalDef(e,S);case ZodFirstPartyTypeKind.ZodMap:return parseMapDef(e,S);case ZodFirstPartyTypeKind.ZodSet:return parseSetDef(e,S);case ZodFirstPartyTypeKind.ZodLazy:return()=>e.getter()._def;case ZodFirstPartyTypeKind.ZodPromise:return parsePromiseDef(e,S);case ZodFirstPartyTypeKind.ZodNaN:case ZodFirstPartyTypeKind.ZodNever:return parseNeverDef(S);case ZodFirstPartyTypeKind.ZodEffects:return parseEffectsDef(e,S);case ZodFirstPartyTypeKind.ZodAny:return parseAnyDef(S);case ZodFirstPartyTypeKind.ZodUnknown:return parseUnknownDef(S);case ZodFirstPartyTypeKind.ZodDefault:return parseDefaultDef(e,S);case ZodFirstPartyTypeKind.ZodBranded:return parseBrandedDef(e,S);case ZodFirstPartyTypeKind.ZodReadonly:return parseReadonlyDef(e,S);case ZodFirstPartyTypeKind.ZodCatch:return parseCatchDef(e,S);case ZodFirstPartyTypeKind.ZodPipeline:return parsePipelineDef(e,S);case ZodFirstPartyTypeKind.ZodFunction:case ZodFirstPartyTypeKind.ZodVoid:case ZodFirstPartyTypeKind.ZodSymbol:return;default:return(e=>void 0)(t)}};function parseDef(e,t,S=!1){let w=t.seen.get(e);if(t.override){let E=t.override?.(e,t,w,S);if(E!==ignoreOverride)return E}if(w&&!S){let e=get$ref(w,t);if(e!==void 0)return e}let E={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,E);let D=selectParser(e,e.typeName,t),O=typeof D==`function`?parseDef(D(),t):D;if(O&&addMeta(e,t,O),t.postProcess){let S=t.postProcess(O,e,t);return E.jsonSchema=O,S}return E.jsonSchema=O,O}const get$ref=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:getRelativePath(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,S)=>t.currentPath[S]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),parseAnyDef(t)):t.$refStrategy===`seen`?parseAnyDef(t):void 0}},addMeta=(e,t,S)=>(e.description&&(S.description=e.description,t.markdownDescription&&(S.markdownDescription=e.description)),S),zodToJsonSchema=(e,t)=>{let S=getRefs(t),w=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,w])=>({...e,[t]:parseDef(w._def,{...S,currentPath:[...S.basePath,S.definitionPath,t]},!0)??parseAnyDef(S)}),{}):void 0,E=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,D=parseDef(e._def,E===void 0?S:{...S,currentPath:[...S.basePath,S.definitionPath,E]},!1)??parseAnyDef(S),O=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;O!==void 0&&(D.title=O),S.flags.hasReferencedOpenAiAnyType&&(w||={},w[S.openAiAnyTypeName]||(w[S.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:S.$refStrategy===`relative`?`1`:[...S.basePath,S.definitionPath,S.openAiAnyTypeName].join(`/`)}}));let k=E===void 0?w?{...D,[S.definitionPath]:w}:D:{$ref:[...S.$refStrategy===`relative`?[]:S.basePath,S.definitionPath,E].join(`/`),[S.definitionPath]:{...w,[E]:D}};return S.target===`jsonSchema7`?k.$schema=`http://json-schema.org/draft-07/schema#`:(S.target===`jsonSchema2019-09`||S.target===`openAi`)&&(k.$schema=`https://json-schema.org/draft/2019-09/schema#`),S.target===`openAi`&&(`anyOf`in k||`oneOf`in k||`allOf`in k||`type`in k&&Array.isArray(k.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),k};function mapMiniTarget(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function toJsonSchemaCompat(e,t){return isZ4Schema(e)?toJSONSchema(e,{target:mapMiniTarget(t?.target),io:t?.pipeStrategy??`input`}):zodToJsonSchema(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function getMethodLiteral(e){let t=getObjectShape(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let S=getLiteralValue(t);if(typeof S!=`string`)throw Error(`Schema method literal must be a string`);return S}function parseWithCompat(e,t){let S=safeParse(e,t);if(!S.success)throw S.error;return S.data}const DEFAULT_REQUEST_TIMEOUT_MSEC=6e4;var Protocol=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(CancelledNotificationSchema,e=>{this._oncancel(e)}),this.setNotificationHandler(ProgressNotificationSchema,e=>{this._onprogress(e)}),this.setRequestHandler(PingRequestSchema,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(GetTaskRequestSchema,async(e,t)=>{let S=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!S)throw new McpError(ErrorCode.InvalidParams,`Failed to retrieve task: Task not found`);return{...S}}),this.setRequestHandler(GetTaskPayloadRequestSchema,async(e,t)=>{let S=async()=>{let w=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(w,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,S=t.id,w=this._requestResolvers.get(S);if(w)if(this._requestResolvers.delete(S),e.type===`response`)w(t);else{let e=t;w(new McpError(e.error.code,e.error.message,e.error.data))}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(Error(`${t} handler missing for request ${S}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let E=await this._taskStore.getTask(w,t.sessionId);if(!E)throw new McpError(ErrorCode.InvalidParams,`Task not found: ${w}`);if(!isTerminal(E.status))return await this._waitForTaskUpdate(w,t.signal),await S();if(isTerminal(E.status)){let e=await this._taskStore.getTaskResult(w,t.sessionId);return this._clearTaskQueue(w),{...e,_meta:{...e._meta,[RELATED_TASK_META_KEY]:{taskId:w}}}}return await S()};return await S()}),this.setRequestHandler(ListTasksRequestSchema,async(e,t)=>{try{let{tasks:S,nextCursor:w}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:S,nextCursor:w,_meta:{}}}catch(e){throw new McpError(ErrorCode.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(CancelTaskRequestSchema,async(e,t)=>{try{let S=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!S)throw new McpError(ErrorCode.InvalidParams,`Task not found: ${e.params.taskId}`);if(isTerminal(S.status))throw new McpError(ErrorCode.InvalidParams,`Cannot cancel task in terminal status: ${S.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId);let w=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!w)throw new McpError(ErrorCode.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...w}}catch(e){throw e instanceof McpError?e:new McpError(ErrorCode.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,S,w,E=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(w,t),startTime:Date.now(),timeout:t,maxTotalTimeout:S,resetTimeoutOnProgress:E,onTimeout:w})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let S=Date.now()-t.startTime;if(t.maxTotalTimeout&&S>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),McpError.fromError(ErrorCode.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:S});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let S=this.transport?.onerror;this._transport.onerror=e=>{S?.(e),this._onerror(e)};let w=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{w?.(e,t),isJSONRPCResultResponse(e)||isJSONRPCErrorResponse(e)?this._onresponse(e):isJSONRPCRequest(e)?this._onrequest(e,t):isJSONRPCNotification(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=McpError.fromError(ErrorCode.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let S of e.values())S(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let S=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,w=this._transport,E=e.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;if(S===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:ErrorCode.MethodNotFound,message:`Method not found`}};E&&this._taskMessageQueue?this._enqueueTaskMessage(E,{type:`error`,message:t,timestamp:Date.now()},w?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):w?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let D=new AbortController;this._requestHandlerAbortControllers.set(e.id,D);let O=isTaskAugmentedRequestParams(e.params)?e.params.task:void 0,k=this._taskStore?this.requestTaskStore(e,w?.sessionId):void 0,j={signal:D.signal,sessionId:w?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(D.signal.aborted)return;let S={relatedRequestId:e.id};E&&(S.relatedTask={taskId:E}),await this.notification(t,S)},sendRequest:async(t,S,w)=>{if(D.signal.aborted)throw new McpError(ErrorCode.ConnectionClosed,`Request was cancelled`);let O={...w,relatedRequestId:e.id};E&&!O.relatedTask&&(O.relatedTask={taskId:E});let j=O.relatedTask?.taskId??E;return j&&k&&await k.updateTaskStatus(j,`input_required`),await this.request(t,S,O)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:E,taskStore:k,taskRequestedTtl:O?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{O&&this.assertTaskHandlerCapability(e.method)}).then(()=>S(e,j)).then(async t=>{if(D.signal.aborted)return;let S={result:t,jsonrpc:`2.0`,id:e.id};E&&this._taskMessageQueue?await this._enqueueTaskMessage(E,{type:`response`,message:S,timestamp:Date.now()},w?.sessionId):await w?.send(S)},async t=>{if(D.signal.aborted)return;let S={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:ErrorCode.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};E&&this._taskMessageQueue?await this._enqueueTaskMessage(E,{type:`error`,message:S,timestamp:Date.now()},w?.sessionId):await w?.send(S)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===D&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...S}=e.params,w=Number(t),E=this._progressHandlers.get(w);if(!E){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let D=this._responseHandlers.get(w),O=this._timeoutInfo.get(w);if(O&&D&&O.resetTimeoutOnProgress)try{this._resetTimeout(w)}catch(e){this._responseHandlers.delete(w),this._progressHandlers.delete(w),this._cleanupTimeout(w),D(e);return}E(S)}_onresponse(e){let t=Number(e.id),S=this._requestResolvers.get(t);if(S){this._requestResolvers.delete(t),isJSONRPCResultResponse(e)?S(e):S(new McpError(e.error.code,e.error.message,e.error.data));return}let w=this._responseHandlers.get(t);if(w===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let E=!1;if(isJSONRPCResultResponse(e)&&e.result&&typeof e.result==`object`){let S=e.result;if(S.task&&typeof S.task==`object`){let e=S.task;typeof e.taskId==`string`&&(E=!0,this._taskProgressTokens.set(e.taskId,t))}}E||this._progressHandlers.delete(t),isJSONRPCResultResponse(e)?w(e):w(McpError.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,S){let{task:w}=S??{};if(!w){try{yield{type:`result`,result:await this.request(e,t,S)}}catch(e){yield{type:`error`,error:e instanceof McpError?e:new McpError(ErrorCode.InternalError,String(e))}}return}let E;try{let w=await this.request(e,CreateTaskResultSchema,S);if(w.task)E=w.task.taskId,yield{type:`taskCreated`,task:w.task};else throw new McpError(ErrorCode.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:E},S);if(yield{type:`taskStatus`,task:e},isTerminal(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:E},t,S)}:e.status===`failed`?yield{type:`error`,error:new McpError(ErrorCode.InternalError,`Task ${E} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new McpError(ErrorCode.InternalError,`Task ${E} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:E},t,S)};return}let w=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,w)),S?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof McpError?e:new McpError(ErrorCode.InternalError,String(e))}}}request(e,t,S){let{relatedRequestId:w,resumptionToken:E,onresumptiontoken:D,task:O,relatedTask:k}=S??{};return new Promise((j,F)=>{let L=e=>{F(e)};if(!this._transport){L(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),O&&this.assertTaskCapability(e.method)}catch(e){L(e);return}S?.signal?.throwIfAborted();let B=this._requestMessageId++,H={...e,jsonrpc:`2.0`,id:B};S?.onprogress&&(this._progressHandlers.set(B,S.onprogress),H.params={...e.params,_meta:{...e.params?._meta||{},progressToken:B}}),O&&(H.params={...H.params,task:O}),k&&(H.params={...H.params,_meta:{...H.params?._meta||{},[RELATED_TASK_META_KEY]:k}});let q=e=>{this._responseHandlers.delete(B),this._progressHandlers.delete(B),this._cleanupTimeout(B),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:B,reason:String(e)}},{relatedRequestId:w,resumptionToken:E,onresumptiontoken:D}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),F(e instanceof McpError?e:new McpError(ErrorCode.RequestTimeout,String(e)))};this._responseHandlers.set(B,e=>{if(!S?.signal?.aborted){if(e instanceof Error)return F(e);try{let S=safeParse(t,e.result);S.success?j(S.data):F(S.error)}catch(e){F(e)}}}),S?.signal?.addEventListener(`abort`,()=>{q(S?.signal?.reason)});let J=S?.timeout??6e4;this._setupTimeout(B,J,S?.maxTotalTimeout,()=>q(McpError.fromError(ErrorCode.RequestTimeout,`Request timed out`,{timeout:J})),S?.resetTimeoutOnProgress??!1);let Y=k?.taskId;Y?(this._requestResolvers.set(B,e=>{let t=this._responseHandlers.get(B);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${B}`))}),this._enqueueTaskMessage(Y,{type:`request`,message:H,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(B),F(e)})):this._transport.send(H,{relatedRequestId:w,resumptionToken:E,onresumptiontoken:D}).catch(e=>{this._cleanupTimeout(B),F(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},GetTaskResultSchema,t)}async getTaskResult(e,t,S){return this.request({method:`tasks/result`,params:e},t,S)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},ListTasksResultSchema,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},CancelTaskResultSchema,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let S=t?.relatedTask?.taskId;if(S){let w={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[RELATED_TASK_META_KEY]:t.relatedTask}}};await this._enqueueTaskMessage(S,{type:`notification`,message:w,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let S={...e,jsonrpc:`2.0`};t?.relatedTask&&(S={...S,params:{...S.params,_meta:{...S.params?._meta||{},[RELATED_TASK_META_KEY]:t.relatedTask}}}),this._transport?.send(S,t).catch(e=>this._onerror(e))});return}let w={...e,jsonrpc:`2.0`};t?.relatedTask&&(w={...w,params:{...w.params,_meta:{...w.params?._meta||{},[RELATED_TASK_META_KEY]:t.relatedTask}}}),await this._transport.send(w,t)}setRequestHandler(e,t){let S=getMethodLiteral(e);this.assertRequestHandlerCapability(S),this._requestHandlers.set(S,(S,w)=>{let E=parseWithCompat(e,S);return Promise.resolve(t(E,w))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let S=getMethodLiteral(e);this._notificationHandlers.set(S,S=>{let w=parseWithCompat(e,S);return Promise.resolve(t(w))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,S){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let w=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,S,w)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let S=await this._taskMessageQueue.dequeueAll(e,t);for(let t of S)if(t.type===`request`&&isJSONRPCRequest(t.message)){let S=t.message.id,w=this._requestResolvers.get(S);w?(w(new McpError(ErrorCode.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(S)):this._onerror(Error(`Resolver missing for request ${S} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let S=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e);t?.pollInterval&&(S=t.pollInterval)}catch{}return new Promise((e,w)=>{if(t.aborted){w(new McpError(ErrorCode.InvalidRequest,`Request cancelled`));return}let E=setTimeout(e,S);t.addEventListener(`abort`,()=>{clearTimeout(E),w(new McpError(ErrorCode.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let S=this._taskStore;if(!S)throw Error(`No task store configured`);return{createTask:async w=>{if(!e)throw Error(`No request provided`);return await S.createTask(w,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let w=await S.getTask(e,t);if(!w)throw new McpError(ErrorCode.InvalidParams,`Failed to retrieve task: Task not found`);return w},storeTaskResult:async(e,w,E)=>{await S.storeTaskResult(e,w,E,t);let D=await S.getTask(e,t);if(D){let t=TaskStatusNotificationSchema.parse({method:`notifications/tasks/status`,params:D});await this.notification(t),isTerminal(D.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>S.getTaskResult(e,t),updateTaskStatus:async(e,w,E)=>{let D=await S.getTask(e,t);if(!D)throw new McpError(ErrorCode.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(isTerminal(D.status))throw new McpError(ErrorCode.InvalidParams,`Cannot update task "${e}" from terminal status "${D.status}" to "${w}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await S.updateTaskStatus(e,w,E,t);let O=await S.getTask(e,t);if(O){let t=TaskStatusNotificationSchema.parse({method:`notifications/tasks/status`,params:O});await this.notification(t),isTerminal(O.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>S.listTasks(e,t)}}};function isPlainObject$1(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function mergeCapabilities(e,t){let S={...e};for(let e in t){let w=e,E=t[w];if(E===void 0)continue;let D=S[w];isPlainObject$1(D)&&isPlainObject$1(E)?S[w]={...D,...E}:S[w]=E}return S}var require_code$1=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var S=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=S;var w=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){var e;return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){var e;return this._names??=this._items.reduce((e,t)=>(t instanceof S&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=w,e.nil=new w(``);function E(e,...t){let S=[e[0]],E=0;for(;E<t.length;)k(S,t[E]),S.push(e[++E]);return new w(S)}e._=E;let D=new w(`+`);function O(e,...t){let S=[q(e[0])],E=0;for(;E<t.length;)S.push(D),k(S,t[E]),S.push(D,q(e[++E]));return j(S),new w(S)}e.str=O;function k(e,t){t instanceof w?e.push(...t._items):t instanceof S?e.push(t):e.push(B(t))}e.addCodeArg=k;function j(e){let t=1;for(;t<e.length-1;){if(e[t]===D){let S=F(e[t-1],e[t+1]);if(S!==void 0){e.splice(t-1,3,S);continue}e[t++]=`+`}t++}}function F(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof S||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof S))return`"${e}${t.slice(1)}`}function L(e,t){return t.emptyStr()?e:e.emptyStr()?t:O`${e}${t}`}e.strConcat=L;function B(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:q(Array.isArray(e)?e.join(`,`):e)}function H(e){return new w(q(e))}e.stringify=H;function q(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=q;function J(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new w(`.${t}`):E`[${t}]`}e.getProperty=J;function Y(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new w(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=Y;function ee(e){return new w(e.toString())}e.regexpCode=ee})),require_scope=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=require_code$1();var S=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},w;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(w||(e.UsedValueState=w={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var E=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){var t,S;if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=E;var D=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:S,itemIndex:w}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(S)}[${w}]`}};e.ValueScopeName=D;let O=(0,t._)`\n`;e.ValueScope=class extends E{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?O:t.nil}}get(){return this._scope}name(e){return new D(e,this._newName(e))}value(e,t){var S;if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let w=this.toName(e),{prefix:E}=w,D=t.key??t.ref,O=this._values[E];if(O){let e=O.get(D);if(e)return e}else O=this._values[E]=new Map;O.set(D,w);let k=this._scope[E]||(this._scope[E]=[]),j=k.length;return k[j]=t.ref,w.setValue(t,{property:E,itemIndex:j}),w}getValue(e,t){let S=this._values[e];if(S)return S.get(t)}scopeRefs(e,S=this._values){return this._reduceValues(S,S=>{if(S.scopePath===void 0)throw Error(`CodeGen: name "${S}" has no value`);return(0,t._)`${e}${S.scopePath}`})}scopeCode(e=this._values,t,S){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,S)}_reduceValues(E,D,O={},k){let j=t.nil;for(let F in E){let L=E[F];if(!L)continue;let B=O[F]=O[F]||new Map;L.forEach(E=>{if(B.has(E))return;B.set(E,w.Started);let O=D(E);if(O){let S=this.opts.es5?e.varKinds.var:e.varKinds.const;j=(0,t._)`${j}${S} ${E} = ${O};${this.opts._n}`}else if(O=k?.(E))j=(0,t._)`${j}${O}${this.opts._n}`;else throw new S(E);B.set(E,w.Completed)})}return j}}})),require_codegen=__commonJSMin$1((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=require_code$1(),S=require_scope();var w=require_code$1();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return w._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return w.str}}),Object.defineProperty(e,`strConcat`,{enumerable:!0,get:function(){return w.strConcat}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return w.nil}}),Object.defineProperty(e,`getProperty`,{enumerable:!0,get:function(){return w.getProperty}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return w.stringify}}),Object.defineProperty(e,`regexpCode`,{enumerable:!0,get:function(){return w.regexpCode}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return w.Name}});var E=require_scope();Object.defineProperty(e,`Scope`,{enumerable:!0,get:function(){return E.Scope}}),Object.defineProperty(e,`ValueScope`,{enumerable:!0,get:function(){return E.ValueScope}}),Object.defineProperty(e,`ValueScopeName`,{enumerable:!0,get:function(){return E.ValueScopeName}}),Object.defineProperty(e,`varKinds`,{enumerable:!0,get:function(){return E.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var D=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},O=class extends D{constructor(e,t,S){super(),this.varKind=e,this.name=t,this.rhs=S}render({es5:e,_n:t}){let w=e?S.varKinds.var:this.varKind,E=this.rhs===void 0?``:` = ${this.rhs}`;return`${w} ${this.name}${E};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=ve(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},k=class extends D{constructor(e,t,S){super(),this.lhs=e,this.rhs=t,this.sideEffects=S}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,S){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=ve(this.rhs,e,S),this}get names(){return _e(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},j=class extends k{constructor(e,t,S,w){super(e,S,w),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},F=class extends D{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},L=class extends D{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},B=class extends D{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},H=class extends D{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=ve(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},q=class extends D{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,S)=>t+S.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let S=e[t].optimizeNodes();Array.isArray(S)?e.splice(t,1,...S):S?e[t]=S:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:S}=this,w=S.length;for(;w--;){let E=S[w];E.optimizeNames(e,t)||(ye(e,E.names),S.splice(w,1))}return S.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>ge(e,t.names),{})}},J=class extends q{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},Y=class extends q{},ee=class extends J{};ee.kind=`else`;var te=class e extends J{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let S=this.else;if(S){let e=S.optimizeNodes();S=this.else=Array.isArray(e)?new ee(e):e}if(S)return t===!1?S instanceof e?S:S.nodes:this.nodes.length?this:new e(Ce(t),S instanceof e?[S]:S.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(e,t){var S;if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=ve(this.condition,e,t),this}get names(){let e=super.names;return _e(e,this.condition),this.else&&ge(e,this.else.names),e}};te.kind=`if`;var ne=class extends J{};ne.kind=`for`;var ae=class extends ne{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=ve(this.iteration,e,t),this}get names(){return ge(super.names,this.iteration.names)}},oe=class extends ne{constructor(e,t,S,w){super(),this.varKind=e,this.name=t,this.from=S,this.to=w}render(e){let t=e.es5?S.varKinds.var:this.varKind,{name:w,from:E,to:D}=this;return`for(${t} ${w}=${E}; ${w}<${D}; ${w}++)`+super.render(e)}get names(){return _e(_e(super.names,this.from),this.to)}},se=class extends ne{constructor(e,t,S,w){super(),this.loop=e,this.varKind=t,this.name=S,this.iterable=w}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=ve(this.iterable,e,t),this}get names(){return ge(super.names,this.iterable.names)}},ce=class extends J{constructor(e,t,S){super(),this.name=e,this.args=t,this.async=S}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};ce.kind=`func`;var ue=class extends q{render(e){return`return `+super.render(e)}};ue.kind=`return`;var de=class extends J{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var S,w;return super.optimizeNames(e,t),(S=this.catch)==null||S.optimizeNames(e,t),(w=this.finally)==null||w.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&ge(e,this.catch.names),this.finally&&ge(e,this.finally.names),e}},fe=class extends J{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};fe.kind=`catch`;var me=class extends J{render(e){return`finally`+super.render(e)}};me.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
|
|
@@ -3287,16 +3287,16 @@ In headless mode, write the recap into the research article's "Further reading"
|
|
|
3287
3287
|
`);if(!L&&!H&&!q&&!J&&!Y)return textResult(ae);let oe={};return L&&(oe.previewUrl=L.url,oe.previewUrlSource=L.source),H&&(oe.warning=buildPreviewAttachWarning(L)),J&&(oe.hints=J),Y&&(oe.summary=Y),textPlusStructured(ae,oe)})}function registerAllTools(e,t){let S=t.logger,w=createLoggedServer(e,{logger:t.logger,identityRef:t.identityRef}),E=e=>async w=>{try{let E=await t.resolveCwd(w);return(getCurrentMcpLogger()??S)?.debug(`tool cwd resolved`,{tool:e,cwd:E,...w?{explicit:w}:{}}),E}catch(t){throw(getCurrentMcpLogger()??S)?.warn(`tool call failed`,{tool:e,error:t instanceof Error?t.message:String(t),...w?{explicit:w}:{}}),t}};register$16(w,{resolveCwd:E(`exec`),serverUrl:t.serverUrl,config:t.config}),register$8(w,{config:t.config,resolveCwd:E(`ingest`)}),register$4(w,{config:t.config,resolveCwd:E(`research`)}),register$21(w,{config:t.config,resolveCwd:E(`consolidate`)}),register$19(w,{config:t.config,resolveCwd:E(`discover`)}),register$2(w,{resolveCwd:E(`search`),config:t.config,serverUrl:t.serverUrl}),register$7(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`links`)}),register(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`write_document`),identityRef:t.identityRef}),register$18(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`edit_document`),identityRef:t.identityRef}),register$20(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`delete_document`),identityRef:t.identityRef}),register$17(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`edit_frontmatter`),identityRef:t.identityRef}),register$5(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`rename`),identityRef:t.identityRef}),register$10(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`get_history`)}),register$1(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`version`),identityRef:t.identityRef}),register$13(w,{resolveCwd:E(`get_components`),config:t.config}),register$14(w,{resolveCwd:E(`get_authoring_palette`),config:t.config}),register$12(w,{config:t.config,resolveCwd:E(`get_config`)}),register$9(w,{config:t.config,resolveCwd:E(`get_preview_url`)}),register$15(w,{config:t.config,resolveCwd:E(`folder_config`)}),register$6(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`list_conflicts`)}),register$11(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`get_conflict_content`)}),register$3(w,{serverUrl:t.serverUrl,config:t.config,resolveCwd:E(`resolve_conflict`)})}function firstHeader(e){return Array.isArray(e)?e[0]:e}function writePlain(e,t,S){e.writableEnded||(e.statusCode=t,e.setHeader(`Content-Type`,`text/plain; charset=utf-8`),e.end(S))}function createSessionServer(e,t,S){let w=e.config,E=new McpServer({name:MCP_SERVER_NAME,version:RUNTIME_VERSION},{instructions:buildInstructions(w.content)});installPrettyZodErrors(E);let D=S??randomUUID(),O={current:{connectionId:D,displayName:D,colorSeed:D}};E.server.oninitialized=()=>{let e=E.server.getClientVersion(),t=sanitizeClientName(e?.name,D);O.current={connectionId:D,clientInfo:e?{name:t,version:e.version}:void 0,displayName:displayNameFromClientName(t),colorSeed:t}};let k=e.projectDir??e.contentDir;return registerAllTools(E,{serverUrl:async()=>e.getServerUrl(),resolveCwd:async e=>{if(e===void 0)return k;let t=resolveWithinRoot(k,e);if(!t.ok)throw Error(`cwd "${e}" is not within the configured project root: ${t.reason}`);return t.abs},config:w,identityRef:O}),{server:E,transport:t}}function createMcpHttpHandler(e){let t=new Map,S=e.sessionTtlMs??1800*1e3,w=e.maxSessions??100;async function E(S,w){let E=t.get(S);if(!E)return;t.delete(S),E.ttlTimer!==void 0&&clearTimeout(E.ttlTimer);let D=await Promise.allSettled([E.server.close(),E.transport.close()]);for(let t of D)t.status===`rejected`&&e.log?.warn?.({err:t.reason,sessionId:S,reason:w},`MCP HTTP session close failed`);e.log?.info?.({sessionId:S,reason:w},`MCP HTTP session closed`)}function D(t,w){w.ttlTimer!==void 0&&clearTimeout(w.ttlTimer),w.ttlTimer=setTimeout(()=>{E(t,`ttl-expired`).catch(S=>{e.log?.warn?.({err:S,sessionId:t},`MCP HTTP session TTL cleanup failed`)})},S),w.ttlTimer.unref?.()}return{async handle(S,O){let k=firstHeader(S.headers[`mcp-session-id`]);if(k){let e=t.get(k);if(!e){writePlain(O,404,`MCP session not found`);return}D(k,e),await e.transport.handleRequest(S,O);return}if(S.method!==`POST`){writePlain(O,400,`Missing MCP session. Initialize with POST /mcp first.`);return}if(t.size>=w){e.log?.warn?.({activeSessions:t.size,maxSessions:w},`MCP HTTP session cap reached`),writePlain(O,503,`Too many active MCP sessions`);return}let j=firstHeader(S.headers[MCP_CONNECTION_ID_HEADER]),F=validateAgentId(j)??void 0;j!==void 0&&F===void 0&&e.log?.warn?.({headerLength:j.length},`MCP HTTP forwarded connectionId header failed validation; falling back to randomUUID`);let L=new StreamableHTTPServerTransport({sessionIdGenerator:()=>randomUUID(),enableJsonResponse:!0,onsessioninitialized:async S=>{try{let w=createSessionServer(e,L,F);await w.server.connect(L),t.set(S,w),D(S,w),e.log?.info?.({sessionId:S},`MCP HTTP session initialized`)}catch(w){throw t.delete(S),e.log?.error?.({err:w,sessionId:S},`MCP HTTP session initialization failed`),w}}});L.onerror=t=>{e.log?.warn?.({err:t},`MCP HTTP transport error`)},L.onclose=()=>{let t=L.sessionId;if(!t){e.log?.info?.({sessionId:t,reason:`transport-closed`},`MCP HTTP session closed`);return}E(t,`transport-closed`).catch(S=>{e.log?.warn?.({err:S,sessionId:t},`MCP HTTP transport-close cleanup failed`)})},await L.handleRequest(S,O)},async close(){let e=[...t.entries()];await Promise.allSettled(e.map(([e])=>E(e,`handler-close`)))}}}const DEFAULT_KEEPALIVE_GRACE_MS=1e4,MAX_COLLAB_MESSAGE_BYTES=1024*1024,MCP_CORS_HEADERS={"Access-Control-Allow-Methods":`GET, POST, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization, traceparent, tracestate, baggage, mcp-session-id, mcp-protocol-version`,"Access-Control-Max-Age":`86400`};function mountMcpAndApi(e){let{httpServer:t,hocuspocus:S,mcpHttpHandler:w,log:E,sessionManager:D,agentFocusBroadcaster:O,agentPresenceBroadcaster:k,contentAssetMiddleware:j,reactShellMiddleware:F}=e,L=e.keepaliveGraceMs??DEFAULT_KEEPALIVE_GRACE_MS,B=new import_websocket_server$1.default({noServer:!0,maxPayload:MAX_COLLAB_MESSAGE_BYTES});B.on(`error`,e=>{E.error({err:e},`WebSocketServer error`)});let H=new Map,q=new Set,J=!1;return t.on(`request`,(e,t)=>{let D=e.url?.split(`?`)[0];if(w!==void 0&&D===`/mcp`){let S=e.headers.origin,D=Array.isArray(e.headers[`mcp-session-id`])?e.headers[`mcp-session-id`][0]:e.headers[`mcp-session-id`];if(!isLoopbackAddress(e.socket.remoteAddress)){errorResponse(t,403,`urn:ok:error:loopback-required`,`Loopback access required.`,{handler:`mcp`});return}if(!isAllowedWorkspaceHostHeader(e.headers.host)){errorResponse(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`mcp`});return}if(S!==void 0&&!isAllowedApiOrigin(S)){errorResponse(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`mcp`});return}S!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,S),t.setHeader(`Vary`,`Origin`));for(let[e,S]of Object.entries(MCP_CORS_HEADERS))t.setHeader(e,S);if(e.method===`OPTIONS`){t.writeHead(204),t.end();return}w.handle(e,t).catch(e=>{E.error({err:e,sessionId:D},`Unhandled MCP HTTP error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp`,cause:e}):t.writableEnded||t.end()});return}if(D?.startsWith(`/api/`)){S.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`mcp-mount`,detail:`No handler for ${e.method??`GET`} ${D}`})}).catch(e=>{E.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()});return}let O=(e,t)=>{if(!(t.writableEnded||t.headersSent)){if(F!==void 0){try{F(e,t,()=>{t.writableEnded||t.headersSent||errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`No handler for ${D??`/`}`})})}catch(e){E.error({err:e},`Unhandled react-shell middleware error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()}return}errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`No handler for ${D??`/`}`})}};if(j!==void 0){try{j(e,t,()=>O(e,t))}catch(e){E.error({err:e},`Unhandled content-asset middleware error`),!t.writableEnded&&!t.headersSent?errorResponse(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()}return}if(F!==void 0){O(e,t);return}errorResponse(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`The React UI is served by \`ok ui\` (run \`ok ui\` and check \`ui.lock.port\`). No handler for ${D??`/`}`})}),t.on(`upgrade`,(e,t,w)=>{if(e.url?.startsWith(`/collab/keepalive`)){if(!isLoopbackAddress(e.socket.remoteAddress)||!isAllowedWorkspaceHostHeader(e.headers.host)){t.destroy();return}t.on(`error`,e=>{handleCollabSocketError(e)||E.error({err:e},`MCP keepalive socket error`)}),B.handleUpgrade(e,t,w,t=>{let S=parseKeepaliveConnectionId(e.url);if(S){let e=H.get(S);e!==void 0&&(clearTimeout(e),H.delete(S),E.info({connectionId:S},`[keepalive] reconnect during grace — timer cancelled`))}if(S&&k){let t=parseKeepaliveIdentity(e.url);if(t)try{let e=iconFromClientName(t.clientName),w=AGENT_ICON_COLORS[e]??colorFromSeed(t.colorSeed);k.setPresence(toBroadcasterKey(S),{displayName:t.displayName,icon:e,color:w,currentDoc:`(connected)`,mode:`idle`,ts:Date.now()})}catch(e){E.error({err:e,connectionId:S},`[keepalive] presence bootstrap failed`)}}let w=setInterval(()=>{try{t.ping()}catch{}},3e4);w.unref?.();let j=S?setInterval(()=>{k?.bumpPresenceTs(toBroadcasterKey(S))},3e3):null;j?.unref?.(),t.on(`close`,()=>{if(clearInterval(w),j!==null&&clearInterval(j),!S)return;let e=setTimeout(()=>{if(H.delete(S),J)return;let e=(async()=>{E.info({connectionId:S},`[keepalive] grace expired — cleaning up sessions`);try{await D?.closeAllForAgent(S)}catch(e){E.error({err:e,connectionId:S},`[keepalive] closeAllForAgent failed`)}try{O?.clearFocus(S)}catch(e){E.error({err:e,connectionId:S},`[keepalive] clearFocus failed`)}try{k?.clearPresence(toBroadcasterKey(S))}catch(e){E.error({err:e,connectionId:S},`[keepalive] clearPresence failed`)}})();q.add(e),e.finally(()=>q.delete(e))},L);e.unref?.(),H.set(S,e),E.info({connectionId:S,graceMs:L},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{handleCollabSocketError(e)||E.error({err:e},`MCP keepalive WS error`),t.terminate()})});return}if(e.url?.startsWith(`/collab`)){t.on(`error`,e=>{handleCollabSocketError(e)||E.error({err:e},`Upgrade socket error`)}),B.handleUpgrade(e,t,w,t=>{let w=S.handleConnection(t,e),D=!1;t.on(`message`,e=>{if(D)return;let S=e.byteLength;if(S>MAX_COLLAB_MESSAGE_BYTES){D=!0,incrementCollabMessageTooLarge(),E.warn({event:`collab-message-too-large`,bytes:S,limit:MAX_COLLAB_MESSAGE_BYTES},`Collab WebSocket message rejected before Yjs processing`),t.close(1009,`Message Too Big`);return}w.handleMessage(new Uint8Array(e))}),t.on(`close`,(e,t)=>{w.handleClose({code:e,reason:t.toString()})}),t.on(`error`,e=>{if(e.code===`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`){incrementCollabMessageTooLarge(),E.warn({event:`collab-message-too-large`,limit:MAX_COLLAB_MESSAGE_BYTES},`Collab WebSocket frame rejected by ws maxPayload before Yjs processing`),t.terminate();return}handleCollabSocketError(e)||E.error({err:e},`WebSocket error`),t.terminate()})});return}t.destroy()}),{wss:B,shutdown:async()=>{if(!J){J=!0;for(let e of H.values())clearTimeout(e);H.clear(),q.size>0&&await Promise.allSettled(q)}}}}function parseKeepaliveConnectionId(e){if(!e)return null;try{return validateAgentId(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}const MAX_KEEPALIVE_IDENTITY_LEN=256;function sanitizeIdentityField(e){return e===null||e.length===0||e.length>MAX_KEEPALIVE_IDENTITY_LEN||/[-]/.test(e)?null:e}function parseKeepaliveIdentity(e){if(!e)return null;try{let t=new URL(e,`http://localhost`),S=sanitizeIdentityField(t.searchParams.get(`displayName`)),w=sanitizeIdentityField(t.searchParams.get(`clientName`)),E=sanitizeIdentityField(t.searchParams.get(`colorSeed`));return S===null||w===null||E===null?null:{displayName:S,clientName:w,colorSeed:E}}catch{return null}}const MISSING_OK_CONFIG_MESSAGE=`Open Knowledge config not found at .ok/config.yml. Run ok init to scaffold OK in this directory.`;var MissingOkConfigError=class extends Error{kind;projectDir;constructor(e,t,S){super(MISSING_OK_CONFIG_MESSAGE,S),this.name=`MissingOkConfigError`,this.kind=e,this.projectDir=t}};async function startConfigFileWatcher(e,t){let S=getLogger(`config-file-watcher`),{watch:w}=await import(`./chokidar-CxU7f6JW.mjs`),E=dirname(e);try{tracedMkdirSync(E,{recursive:!0})}catch(e){e.code!==`EEXIST`&&S.warn({err:e,watchDir:E},`failed to create watch directory; watcher may be inert`)}let D=w(E,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:t=>t!==E&&t!==e});await new Promise(e=>{D.once(`ready`,e)});let O=null;try{O=readFileSync(e,`utf-8`)}catch{}let k=(w,E=!0)=>{if(w!==e)return;let D;try{D=readFileSync(w,`utf-8`)}catch(e){if(e.code===`ENOENT`){E&&S.debug({path:w},`config file disappeared between event and read; dropping`);return}S.warn({err:e,path:w},`config file read failed; dropping event`);return}if(D!==O){O=D;try{t(D)}catch(e){S.warn({err:e,path:w},`config file change handler threw`)}}},j=e=>k(e);D.on(`add`,j),D.on(`change`,j),D.on(`unlink`,t=>{t===e&&S.debug({path:t},`config file unlinked; Y.Text retained at current state`)}),D.on(`error`,t=>{S.warn({err:t,watchDir:E,absPath:e},`[config-file-watcher] chokidar error while watching ${e}`)});let F=0,L=setInterval(()=>{F++,k(e,!1),F>=20&&clearInterval(L)},500);L.unref?.();let B=!1;return async()=>{B||(B=!0,clearInterval(L),await D.close())}}async function startMultiPathConfigFileWatcher(e,t){if(e.length===0)throw Error(`startMultiPathConfigFileWatcher requires at least one absolute path`);let S=getLogger(`config-file-watcher`),{watch:w}=await import(`./chokidar-CxU7f6JW.mjs`),E=new Set(e),D=Array.from(new Set(Array.from(E,e=>dirname(e))));for(let e of D)try{tracedMkdirSync(e,{recursive:!0})}catch(t){t.code!==`EEXIST`&&S.warn({err:t,dir:e},`failed to create watch directory; watcher may be inert`)}let O=w(D,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:e=>!E.has(e)&&!D.includes(e)});await new Promise(e=>{O.once(`ready`,e)});let k=new Map;for(let e of E)try{k.set(e,readFileSync(e,`utf-8`))}catch{k.set(e,null)}let j=(e,w=!0)=>{if(!E.has(e))return;let D;try{D=readFileSync(e,`utf-8`)}catch(t){if(t.code===`ENOENT`){w&&S.debug({path:e},`config file disappeared between event and read; dropping`);return}S.warn({err:t,path:e},`config file read failed; dropping event`);return}if(D!==k.get(e)){k.set(e,D);try{t(e,D)}catch(t){S.warn({err:t,path:e},`config file change handler threw`)}}},F=e=>j(e);O.on(`add`,F),O.on(`change`,F),O.on(`unlink`,e=>{E.has(e)&&S.debug({path:e},`config file unlinked; downstream state retained`)}),O.on(`error`,e=>{S.warn({err:e,watchDirs:D,paths:Array.from(E)},`[config-file-watcher] chokidar error in multi-path watcher`)});let L=0,B=setInterval(()=>{L++;for(let e of E)j(e,!1);L>=20&&clearInterval(B)},500);B.unref?.();let H=!1;return async()=>{H||(H=!0,clearInterval(B),await O.close())}}const BUILTIN_SKIP_DIRS=new Set([`node_modules`,`.venv`,`venv`,`env`,`__pycache__`,`vendor`,`dist`,`build`,`out`,`output`,`.next`,`.nuxt`,`.svelte-kit`,`.astro`,`.turbo`,`.cache`,`.parcel-cache`,`coverage`,`.git`,`.ok`,`.open-knowledge`,`.openknowledge`,`Library`,`Applications`,`.Trash`]),IGNORE_FILE_NAMES=[`.gitignore`,`.okignore`];function createContentFilter(e){let{projectDir:t,contentDir:S,onAfterRebuild:w}=e,E=relative(t,S),D=E.startsWith(`..`),O,k,j,F=0,L=0,B=0;function H(){let e=(0,import_ignore.default)();e.add(`.git`);let w=[],H=0,q=0;for(let S of IGNORE_FILE_NAMES){let E=join(t,S);if(existsSync(E))try{let t=readFileSync(E,`utf-8`);H+=t.length;let S=parseIgnorePatterns(t);w.push(...S),e.add(S)}catch(e){console.warn(`[content-filter] Failed to read ${S} at ${E}:`,e)}}if(E&&!D)for(let t of IGNORE_FILE_NAMES){let w=join(S,t);if(existsSync(w))try{let t=readFileSync(w,`utf-8`);H+=t.length,q++;let S=parseIgnorePatterns(t).map(e=>prefixPattern(e,E));e.add(S)}catch(e){console.warn(`[content-filter] Failed to read ${t} at ${w}:`,e)}}let J={value:H};q+=loadNestedIgnoreFiles(S,t,e,J),H=J.value;let Y=w.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`));return O=e,k=w,j=Y,F=w.length,L=q,B=H,{patternCount:F,nestedFileCount:L,bytes:B}}H();let q=new Map;function J(e){if(D)return!1;let t=E?`${E}/${e}`:e;return O.ignores(t)}populateDirCount(S,``,J,q);function Y(e){let t=stripDocExtension(e);return isSystemDoc(t)||isConfigDoc(t)}function ee(e){for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;return D?!1:J(e)}return{isExcluded(e,t){if(Y(e))return!0;if(t?.bypassFilters)return!1;if(ee(e))return!0;if(isSupportedDocFile(e))return!1;let S=extname(e).slice(1).toLowerCase();if(ASSET_EXTENSIONS.has(S)){let t=dirname(e),S=t===`.`?``:t;if((q.get(S)??0)>0)return!1}return!0},isDirExcluded(e,t){if(t?.bypassFilters)return!1;for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;if(D)return!1;let S=E?`${E}/${e}`:e;return O.ignores(S)||O.ignores(`${S}/`)},isPathIgnored(e,t){return Y(e)?!0:t?.bypassFilters?!1:ee(e)},getWatcherIgnoreGlobs(){return j},incrementMdDir(e){let t=e===`.`?``:e;q.set(t,(q.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,S=q.get(t)??0;S<=1?q.delete(t):q.set(t,S-1)},rebuildDirCount(){let e=new Map(q);q.clear();try{populateDirCount(S,``,J,q)}catch(t){for(let[t,S]of e)q.set(t,S);getLogger(`content-filter`).warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},async rebuildIgnorePatterns(){let e=getLogger(`content-filter`),t=O,E=k,D=j,Y=F,ee=L,te=B,ne=Date.now();return withSpan(`config.ignore.rebuild`,{attributes:{}},async ae=>{try{let t=H();q.clear(),populateDirCount(S,``,J,q);let E=Date.now()-ne;if(ae.setAttributes({"ok.ignore.pattern_count":t.patternCount,"ok.ignore.nested_file_count":t.nestedFileCount,"ok.ignore.bytes":t.bytes}),e.info({patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:E},`content-filter rebuild succeeded`),w)try{w()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:t.patternCount,nestedFileCount:t.nestedFileCount,bytes:t.bytes,durationMs:E}}catch(w){O=t,k=E,j=D,F=Y,L=ee,B=te,q.clear();try{populateDirCount(S,``,J,q)}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter rollback dirCount re-walk failed — sibling-asset counts may be stale until next rebuild`)}let H=w instanceof Error?w.message:String(w);return e.warn({err:w instanceof Error?w:Error(H)},`content-filter rebuild failed — rolled back to previous state`),{ok:!1,error:{message:H}}}})}}}function populateDirCount(e,t,S,w){let E;try{E=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory for dir-count: ${e}`,t);return}for(let D of E){let E=t?`${t}/${D.name}`:D.name;if(D.isDirectory()){if(BUILTIN_SKIP_DIRS.has(D.name)||S(E)||S(`${E}/`))continue;populateDirCount(join(e,D.name),E,S,w)}else D.isFile()&&isSupportedDocFile(D.name)&&!S(E)&&w.set(t,(w.get(t)??0)+1)}}function parseIgnorePatterns(e){return e.split(`
|
|
3288
3288
|
`).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`))}function prefixPattern(e,t){return e.startsWith(`!`)?`!${t}/${e.slice(1)}`:`${t}/${e}`}function loadNestedIgnoreFiles(e,t,S,w){let E;try{E=readdirSync(e,{withFileTypes:!0})}catch(t){return console.warn(`[content-filter] Failed to read directory ${e}:`,t),0}let D=0;for(let O of E){if(!O.isDirectory()||BUILTIN_SKIP_DIRS.has(O.name))continue;let E=join(e,O.name),k=relative(t,E);if(!k.startsWith(`..`)&&!(S.ignores(k)||S.ignores(`${k}/`))){for(let e of IGNORE_FILE_NAMES){let t=join(E,e);if(existsSync(t))try{let e=readFileSync(t,`utf-8`);w.value+=e.length;let E=parseIgnorePatterns(e).map(e=>prefixPattern(e,k));S.add(E),D++}catch(S){console.warn(`[content-filter] Failed to read nested ${e} at ${t}:`,S)}}D+=loadNestedIgnoreFiles(E,t,S,w)}}return D}async function initContentDirStateAsync(e,t,S,w,E,D,O){let k;try{k=await readdir(e,{withFileTypes:!0})}catch(t){console.warn(`[content-filter] Failed to read directory ${e}:`,t);return}for(let j of k){let k=t?`${t}/${j.name}`:j.name;if(j.isDirectory()){if(BUILTIN_SKIP_DIRS.has(j.name))continue;let t=join(e,j.name);if(!D){let e=relative(S,t);if(e.startsWith(`..`)||w.ignores(e)||w.ignores(`${e}/`))continue;for(let S of IGNORE_FILE_NAMES){let E=join(t,S);if(existsSync(E))try{let t=parseIgnorePatterns(await readFile$1(E,`utf-8`));w.add(t.map(t=>prefixPattern(t,e)))}catch(e){console.warn(`[content-filter] Failed to read nested ${S} at ${E}:`,e)}}}await initContentDirStateAsync(t,k,S,w,E,D,O)}else if(j.isFile()&&isSupportedDocFile(j.name)){if(!D){let e=E?`${E}/${k}`:k;if(w.ignores(e))continue}O.set(t,(O.get(t)??0)+1)}}}async function createContentFilterAsync(e){let{projectDir:t,contentDir:S,onAfterRebuild:w}=e,E=relative(t,S),D=E.startsWith(`..`),O=(0,import_ignore.default)(),k=[],j=new Map;function F(e){if(D)return!1;let t=E?`${E}/${e}`:e;return O.ignores(t)}function L(e){let t=stripDocExtension(e);return isSystemDoc(t)||isConfigDoc(t)}function B(e){for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;return D?!1:F(e)}async function H(){let e=(0,import_ignore.default)();e.add(`.git`);let w=[];for(let S of IGNORE_FILE_NAMES){let E=join(t,S);if(existsSync(E))try{let t=parseIgnorePatterns(await readFile$1(E,`utf-8`));w.push(...t),e.add(t)}catch(e){console.warn(`[content-filter] Failed to read ${S} at ${E}:`,e)}}if(E&&!D)for(let t of IGNORE_FILE_NAMES){let w=join(S,t);if(existsSync(w))try{let t=parseIgnorePatterns(await readFile$1(w,`utf-8`));e.add(t.map(e=>prefixPattern(e,E)))}catch(e){console.warn(`[content-filter] Failed to read ${t} at ${w}:`,e)}}let F=new Map;await initContentDirStateAsync(S,``,t,e,E,D,F),O=e,k=w.filter(e=>e.length>0&&!e.startsWith(`!`)&&!e.startsWith(`#`)),j.clear();for(let[e,t]of F)j.set(e,t)}return await H(),{isExcluded(e,t){if(L(e))return!0;if(t?.bypassFilters)return!1;if(B(e))return!0;if(isSupportedDocFile(e))return!1;let S=extname(e).slice(1).toLowerCase();if(ASSET_EXTENSIONS.has(S)){let t=dirname(e),S=t===`.`?``:t;if((j.get(S)??0)>0)return!1}return!0},isDirExcluded(e,t){if(t?.bypassFilters)return!1;for(let t of e.split(`/`))if(BUILTIN_SKIP_DIRS.has(t))return!0;if(D)return!1;let S=E?`${E}/${e}`:e;return O.ignores(S)||O.ignores(`${S}/`)},isPathIgnored(e,t){return L(e)?!0:t?.bypassFilters?!1:B(e)},getWatcherIgnoreGlobs(){return k},incrementMdDir(e){let t=e===`.`?``:e;j.set(t,(j.get(t)??0)+1)},decrementMdDir(e){let t=e===`.`?``:e,S=j.get(t)??0;S<=1?j.delete(t):j.set(t,S-1)},rebuildDirCount(){let e=new Map(j);j.clear();try{populateDirCount(S,``,F,j)}catch(t){for(let[t,S]of e)j.set(t,S);getLogger(`content-filter`).warn({err:t instanceof Error?t:Error(String(t))},`content-filter rebuildDirCount walk failed — retaining previous counts`)}},async rebuildIgnorePatterns(){let e=getLogger(`content-filter`),t=O,S=k,E=new Map(j),D=Date.now();return withSpan(`config.ignore.rebuild`,{attributes:{}},async F=>{try{await H();let t=Date.now()-D;if(F.setAttributes({"ok.ignore.pattern_count":k.length,"ok.ignore.nested_file_count":0,"ok.ignore.bytes":0}),e.info({durationMs:t},`content-filter async rebuild succeeded`),w)try{w()}catch(t){e.warn({err:t instanceof Error?t:Error(String(t))},`content-filter onAfterRebuild callback threw — derived views may be stale`)}return{ok:!0,patternCount:k.length,nestedFileCount:0,bytes:0,durationMs:t}}catch(w){O=t,k=S,j.clear();for(let[e,t]of E)j.set(e,t);let D=w instanceof Error?w.message:String(w);return e.warn({err:w instanceof Error?w:Error(D)},`content-filter async rebuild failed — rolled back`),{ok:!1,error:{message:D}}}})}}}const QUIET_WINDOW_MS=100,BATCH_TIMEOUT_MS=3e4,WATCHED_FILES=new Set([`HEAD`,`MERGE_HEAD`,`ORIG_HEAD`,`index.lock`]);function readHeadSha(e){try{let t=readFileSync(resolve(e,`HEAD`),`utf-8`).trim();if(t.startsWith(`ref: `)){let S=resolve(e,t.slice(5));try{return readFileSync(S,`utf-8`).trim()}catch{try{let S=readFileSync(resolve(e,`packed-refs`),`utf-8`),w=t.slice(5),E=S.split(`
|
|
3289
3289
|
`).find(e=>e.endsWith(` ${w}`));if(E)return E.split(` `)[0]}catch{}return null}}return t.length>=40?t.slice(0,40):null}catch{return null}}function readBranchFromHead(e){try{let t=readFileSync(resolve(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 startHeadWatcher(e,t,S){let w=resolveGitDir(e);if(!w)return{unsubscribe:async()=>{},getLastKnownBranch:()=>null};let E=w,D=!1,O=null,k=null,j=null,F=null;async function L(e){if(H&&await H,!D)return;O&&=(clearTimeout(O),null),k&&=(clearTimeout(k),null);let t=readHeadSha(E),w=j!==t,L=readBranchFromHead(E),B;B=L?.startsWith(`detached-`)?`detached-head`:F===L?`within-branch`:`cross-branch`;let q=F;try{await S({headMoved:w,oldHead:j,newHead:t,timeout:e,batchKind:B,oldBranch:q,newBranch:L})}catch(e){console.error(`[head-watcher] onBatchEnd callback failed:`,e)}finally{D=!1,j=t,F=L}}function B(){O&&clearTimeout(O),O=setTimeout(()=>{O=null,L(!1)},QUIET_WINDOW_MS)}let H=null;async function q(e){if(!D){D=!0,j=readHeadSha(E);let S=(async()=>{try{await t({trigger:e})}catch(e){console.error(`[head-watcher] onBatchBegin callback failed:`,e)}})();H=S,await S,H=null,k=setTimeout(()=>{k=null,L(!0)},BATCH_TIMEOUT_MS)}B()}let J,Y;try{Y=await import(`@parcel/watcher`)}catch(e){throw Error(`@parcel/watcher unavailable for HEAD watching: ${e instanceof Error?e.message:e}`)}try{let e=await Y.subscribe(E,(e,t)=>{if(e){console.error(`[head-watcher]`,e);return}for(let e of t){let t=e.path.split(`/`).pop()??``;if(WATCHED_FILES.has(t)){q(t);break}}});J=()=>e.unsubscribe()}catch(e){throw Error(`@parcel/watcher subscribe failed for HEAD watching: ${e instanceof Error?e.message:e}`)}return j=readHeadSha(E),F=readBranchFromHead(E),console.log(`[head-watcher] Watching ${E} for HEAD changes`),{unsubscribe:async()=>{D&&await L(!1),O&&clearTimeout(O),k&&clearTimeout(k),await J()},getLastKnownBranch:()=>F}}const LIVE_DERIVED_INDEX_DEBOUNCE_MS=100;function isLocalOriginLike(e){return typeof e!=`object`||!e?!1:e.source===`local`}function serializeLiveDocument(e){return e.getText(`source`).toString()}function createLiveDerivedIndexExtension(e){let{backlinkIndex:t,tagIndex:S,signalChannel:w,debounceMs:E=100}=e,D=new Map;function O(e){let t=D.get(e);t&&(clearTimeout(t),D.delete(e))}function k(e,k){O(e),D.set(e,setTimeout(()=>{D.delete(e);try{let E=serializeLiveDocument(k);t.updateDocumentFromMarkdown(e,E),w?.(`backlinks`),w?.(`graph`),S&&(S.updateDocumentFromMarkdown(e,E),w?.(`tags`))}catch(t){console.error(`[live-derived-index] Failed to update derived views for ${e}:`,t)}},E))}return{async onChange({documentName:e,document:t,transactionOrigin:S}){isSystemDoc(e)||isConfigDoc(e)||isLocalOriginLike(S)&&S.context?.origin===`file-watcher`||k(e,t)},async beforeUnloadDocument({documentName:e}){O(e)},async onDestroy(){for(let e of D.values())clearTimeout(e);D.clear()}}}const PRINCIPAL_FILE=`principal.json`,GIT_TIMEOUT_MS=3e3;async function readGitConfig(e){try{let t=esm_default({baseDir:e,timeout:{block:GIT_TIMEOUT_MS}});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 loadPrincipal(e){let t=getLocalDir(e),S=resolve(t,PRINCIPAL_FILE),{name:w,email:E}=await readGitConfig(e);if(existsSync(S)){let e;try{e=JSON.parse(readFileSync(S,`utf-8`))}catch{e={}}let t=typeof e.id==`string`&&e.id.startsWith(`principal-`)?e.id:`principal-${randomUUID()}`,D=typeof e.created_at==`string`?e.created_at:new Date().toISOString(),O=t.slice(10,18),k={id:t,display_name:w?sanitizeGitIdentity(w):typeof e.display_name==`string`?e.display_name:`Local User`,display_email:E?sanitizeGitIdentity(E):typeof e.display_email==`string`?e.display_email:`principal-${O}@openknowledge.local`,source:w||E?`git-config`:`synthesized`,created_at:D};return writeFileSync(S,JSON.stringify(k,null,2),`utf-8`),k}mkdirSync(t,{recursive:!0});let D=`principal-${randomUUID()}`,O=D.slice(10,18),k={id:D,display_name:w?sanitizeGitIdentity(w):`Local User`,display_email:E?sanitizeGitIdentity(E):`principal-${O}@openknowledge.local`,source:w||E?`git-config`:`synthesized`,created_at:new Date().toISOString()};return writeFileSync(S,JSON.stringify(k,null,2),`utf-8`),k}const DEFAULT_CAPACITY=1e4;var RecentlyRemovedDocs=class{map=new Map;capacity;onEviction;onSizeChange;now;constructor(e=DEFAULT_CAPACITY,t={}){this.capacity=Math.max(0,Math.floor(e)),this.onEviction=t.onEviction,this.onSizeChange=t.onSizeChange,this.now=t.now??Date.now}setRenamed(e,t){this.put(e,{kind:`renamed`,newDocName:t,addedAt:this.now()})}setDeleted(e){this.put(e,{kind:`deleted`,addedAt:this.now()})}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}has(e){return this.map.has(e)}peek(e){return this.map.get(e)}delete(e){this.map.delete(e)&&this.onSizeChange?.(this.map.size)}get size(){return this.map.size}put(e,t){if(this.capacity===0){this.onSizeChange?.(0);return}for(this.map.delete(e),this.map.set(e,t);this.map.size>this.capacity;){let e=this.map.keys().next().value;if(e===void 0)break;this.map.delete(e),this.onEviction?.()}this.onSizeChange?.(this.map.size)}};function fileExistsForDocName(e,t){let S=e.resolveFilePath(t);return S!==null&&e.fileExists(S)}async function runRemovalRedirectGuard(e,t){try{if(isSystemDoc(e)||isConfigDoc(e))return;let S=t.recentlyRemovedDocs.get(e);if(S===void 0)return;if(S.kind===`deleted`){if(fileExistsForDocName(t,e)){t.recentlyRemovedDocs.delete(e);return}throw incrementAuthDocDeleted(),setActiveSpanAttributes({"auth.reason":`doc-deleted`}),new HocuspocusAuthRejection(`doc-deleted`,`removed-doc rejection for deleted ${e}`)}let w=new Set([e]),E=S.newDocName;for(;;){if(w.has(E)){incrementRemovalRedirectChainCycle(),console.warn(JSON.stringify({event:`removal-redirect-chain-cycle`,documentName:e,target:E}));return}w.add(E);let S=t.recentlyRemovedDocs.get(E);if(S===void 0)throw incrementAuthRenameRedirect(),setActiveSpanAttributes({"auth.reason":`rename-redirect`}),new HocuspocusAuthRejection(`rename-redirect`,`removed-doc redirect for ${e} → ${E}`,E);if(S.kind===`deleted`)throw fileExistsForDocName(t,E)?(t.recentlyRemovedDocs.delete(E),incrementAuthRenameRedirect(),setActiveSpanAttributes({"auth.reason":`rename-redirect`}),new HocuspocusAuthRejection(`rename-redirect`,`removed-doc redirect for ${e} → ${E}`,E)):(incrementAuthDocDeleted(),setActiveSpanAttributes({"auth.reason":`doc-deleted`}),new HocuspocusAuthRejection(`doc-deleted`,`removed-doc rejection for deleted ${e}`));E=S.newDocName}}catch(t){if(t instanceof HocuspocusAuthRejection)throw t;incrementAuthRemovalGuardError(),console.warn(JSON.stringify({event:`removal-redirect-extension-error`,documentName:e,message:t instanceof Error?t.message:String(t)}))}}function createServerObserverExtension(e){let t=new Map,S=new Map;return{async afterLoadDocument({documentName:w,document:E}){if(isSystemDoc(w)||isConfigDoc(w)||t.has(w))return;let D=E,O=D.getXmlFragment(`default`),k=D.getText(`source`),j=()=>{try{let S=setupServerObservers({doc:D,xmlFragment:O,ytext:k,mdManager:e.mdManager,schema:e.schema,docName:w,shadow:e.shadowRef?()=>e.shadowRef?.current:void 0,getBranch:e.getCurrentBranch?()=>e.getCurrentBranch?.()??`main`:void 0,contentRoot:e.contentRoot,resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize});return t.set(w,S),!0}catch(e){return console.error(`[ServerObserverExtension] Failed to attach observers for '${w}':`,e),incrementServerObserverError(`a`),incrementServerObserverError(`b`),!1}};if(!j()){let e=setTimeout(()=>{S.delete(w),!t.has(w)&&(console.warn(`[ServerObserverExtension] Retrying observer attachment for '${w}'`),j())},5e3);S.set(w,e)}},async afterUnloadDocument({documentName:e}){let w=S.get(e);w&&(clearTimeout(w),S.delete(e));let E=t.get(e);E&&(E(),t.delete(e))},async onDestroy(){for(let e of S.values())clearTimeout(e);S.clear();for(let[e,S]of t.entries())try{S()}catch(t){console.error(`[ServerObserverExtension] Cleanup failed for '${e}':`,t)}t.clear()}}}const STATE_MANIFEST_FILENAME=`state.json`;function detectProjectShape(e){return e.lockDir,existsSync(e.shadowRepoDir)?`adopt`:`fresh`}function manifestPath(e){return resolve(e,STATE_MANIFEST_FILENAME)}function isCompatibleSchema(e,t){return e===t||e===0&&t===1}var StateManifestError=class extends Error{kind;path;constructor(e){super(e.message),this.name=`StateManifestError`,this.kind=e.kind,this.path=e.path}};function isStateManifestRecord(e){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.stateSchemaVersion!=`number`||typeof t.createdAt!=`string`||!t.createdBy||typeof t.createdBy!=`object`)return!1;let S=t.createdBy;return!(typeof S.runtimeVersion!=`string`||S.protocolVersion!==void 0&&typeof S.protocolVersion!=`number`)}function readStateManifest(e){let t=manifestPath(e);if(!existsSync(t))return{status:`absent`};let S;try{S=readFileSync(t,`utf-8`)}catch(e){throw new StateManifestError({kind:`corrupt`,path:t,message:`Failed to read state manifest at ${t}: ${e instanceof Error?e.message:String(e)}`})}let w;try{w=JSON.parse(S)}catch(e){throw new StateManifestError({kind:`corrupt`,path:t,message:`State manifest at ${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`})}if(!isStateManifestRecord(w))throw new StateManifestError({kind:`corrupt`,path:t,message:`State manifest at ${t} has invalid shape (missing or wrong-typed required fields)`});return{status:`present`,manifest:w}}function writeStateManifest(e,t){let S=manifestPath(e);mkdirSync(dirname(S),{recursive:!0}),writeFileSync(S,JSON.stringify(t,null,2),{encoding:`utf-8`,mode:384})}function assertCompatibleStateManifest(e){let t=getLogger(`state-manifest`),S=e.currentStateSchemaVersion??1,w=e.currentRuntimeVersion??RUNTIME_VERSION,E=e.currentProtocolVersion??1,D=(e.now??(()=>new Date))().toISOString(),O=manifestPath(e.lockDir),k=readStateManifest(e.lockDir);if(k.status===`present`){let j=k.manifest;if(!isCompatibleSchema(j.stateSchemaVersion,S))throw new StateManifestError({kind:`incompatible`,path:O,message:`State manifest at ${O} declares stateSchemaVersion=${j.stateSchemaVersion} but this binary supports ${S}. Refusing to boot — on-the-fly migration is out of scope. (Manifest written by runtime ${j.createdBy.runtimeVersion}, protocol ${j.createdBy.protocolVersion}.)`});try{let t={...j,lastWriteBy:{runtimeVersion:w,protocolVersion:E,at:D}};return writeStateManifest(e.lockDir,t),t}catch(e){return t.warn({err:e},`[state-manifest] failed to update lastWriteBy — proceeding`),j}}if(detectProjectShape({lockDir:e.lockDir,shadowRepoDir:e.shadowRepoDir})===`fresh`){let k={stateSchemaVersion:S,createdAt:D,createdBy:{runtimeVersion:w,protocolVersion:E}};return writeStateManifest(e.lockDir,k),t.info({path:O,stateSchemaVersion:S},`[state-manifest] fresh project — wrote manifest`),k}let j={stateSchemaVersion:0,createdAt:D,createdBy:{runtimeVersion:w,protocolVersion:E,adoptedAt:D}};return writeStateManifest(e.lockDir,j),t.warn({path:O,runtimeVersion:w},`[state-manifest] adopting pre-versioned project — wrote schema-0 manifest. Future binaries with STATE_SCHEMA_VERSION>=2 may refuse if they cannot read schema-0 state.`),j}function extractStderr(e){return e.git?.toString()??e.message??``}function matchesAny(e,t){return t.some(t=>t.test(e))}const AUTH_PATTERNS=[/\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],SCOPE_MISMATCH_PATTERNS=[/insufficient scopes/i,/missing.*scope/i,/required scope/i],NON_FAST_FORWARD_PATTERNS=[/non-fast-forward/i,/rejected.*non-fast-forward/i,/would overwrite.*commits/i,/\[rejected\]/,/fetch first/i,/updates were rejected/i],PROTECTED_BRANCH_PATTERNS=[/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],MERGE_CONFLICT_PATTERNS=[/\bmerge conflict\b/i,/automatic merge failed/i,/CONFLICT \(/,/\bconflict\b.*\bmerge\b/i,/(?:^|\n)CONFLICTS:\s/i],LFS_PATTERNS=[/lfs.*quota/i,/exceeded.*bandwidth/i,/lfs storage/i],LARGE_FILE_PATTERNS=[/file.*too large/i,/exceeded.*file size/i,/push file size limit/i],PRE_RECEIVE_PATTERNS=[/pre-receive hook/i,/remote:.*rejected/i,/hook declined/i],SECRET_DETECTED_PATTERNS=[/secret.*detected/i,/push.*secret/i,/secret scanning/i,/leaking.*credentials/i,/token.*detected/i],INDEX_LOCK_PATTERNS=[/\.git\/index\.lock/i,/another git process/i,/unable to create.*\.lock/i],DIRTY_TREE_PATTERNS=[/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],DISK_FULL_PATTERNS=[/no space left on device/i,/disk quota exceeded/i,/ENOSPC/],NETWORK_PATTERNS=[/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],HTTP_5XX_PATTERNS=[/\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],HTTP_429_PATTERNS=[/\bHTTP[\s/]*429\b/i,/\bstatus:?\s*429\b/i,/\berror\s*429\b/i,/rate.?limit/i,/too many requests/i];function classifyGitError(e){let t=e instanceof Error?e:Error(String(e)),S=extractStderr(t),w=`${t.message}\n${S}`.toLowerCase();return matchesAny(w,INDEX_LOCK_PATTERNS)?{class:`local`,subclass:`index-lock`,retryable:!0,message:`Git index locked by another process`,rawStderr:S}:matchesAny(w,DIRTY_TREE_PATTERNS)?{class:`local`,subclass:`dirty-tree`,retryable:!0,message:`Working tree has uncommitted changes`,rawStderr:S}:matchesAny(w,DISK_FULL_PATTERNS)?{class:`local`,subclass:`disk-full`,retryable:!0,message:`Disk full or quota exceeded`,rawStderr:S}:matchesAny(w,SCOPE_MISMATCH_PATTERNS)?{class:`auth`,subclass:`scope-mismatch`,retryable:!1,message:`GitHub token missing required scopes`,rawStderr:S}:matchesAny(w,AUTH_PATTERNS)?/\b401\b/.test(w)||/token.*expired/i.test(w)?{class:`auth`,subclass:`401`,retryable:!1,message:`Authentication failed — token may be expired`,rawStderr:S}:/\b403\b/.test(w)?matchesAny(w,PROTECTED_BRANCH_PATTERNS)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:S}:{class:`auth`,subclass:`403`,retryable:!1,message:`Access denied (403)`,rawStderr:S}:{class:`auth`,subclass:`unknown-auth`,retryable:!1,message:`Authentication failed`,rawStderr:S}:matchesAny(w,PROTECTED_BRANCH_PATTERNS)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:S}:matchesAny(w,NON_FAST_FORWARD_PATTERNS)?{class:`semantic`,subclass:`non-fast-forward`,retryable:!1,message:`Push rejected — remote has diverged (non-fast-forward)`,rawStderr:S}:matchesAny(w,MERGE_CONFLICT_PATTERNS)?{class:`semantic`,subclass:`merge-conflict`,retryable:!1,message:`Merge conflict — manual resolution required`,rawStderr:S}:matchesAny(w,LFS_PATTERNS)?{class:`structural`,subclass:`lfs-quota`,retryable:!1,message:`Git LFS quota exceeded`,rawStderr:S}:matchesAny(w,LARGE_FILE_PATTERNS)?{class:`structural`,subclass:`large-file`,retryable:!1,message:`File exceeds size limit`,rawStderr:S}:matchesAny(w,SECRET_DETECTED_PATTERNS)?{class:`structural`,subclass:`secret-detected`,retryable:!1,message:`Push blocked — secret or credential detected in content`,rawStderr:S}:matchesAny(w,PRE_RECEIVE_PATTERNS)?{class:`structural`,subclass:`pre-receive-hook`,retryable:!1,message:`Push rejected by server pre-receive hook`,rawStderr:S}:matchesAny(w,HTTP_429_PATTERNS)?{class:`network`,subclass:`429`,retryable:!0,message:`Rate limited — too many requests`,rawStderr:S}:matchesAny(w,HTTP_5XX_PATTERNS)?{class:`network`,subclass:`5xx`,retryable:!0,message:`Server error (5xx)`,rawStderr:S}:matchesAny(w,NETWORK_PATTERNS)?/timed? out/i.test(w)?{class:`network`,subclass:`timeout`,retryable:!0,message:`Connection timed out`,rawStderr:S}:/refused/i.test(w)||/econnrefused/i.test(w)?{class:`network`,subclass:`connection-refused`,retryable:!0,message:`Connection refused`,rawStderr:S}:/resolve.*host/i.test(w)||/enotfound/i.test(w)||/getaddrinfo/i.test(w)?{class:`network`,subclass:`dns`,retryable:!0,message:`DNS resolution failed`,rawStderr:S}:{class:`network`,subclass:`unknown-network`,retryable:!0,message:`Network error`,rawStderr:S}:{class:`local`,subclass:`unknown-local`,retryable:!0,message:t.message||`Unknown git error`,rawStderr:S}}function computeRemainingMs(e,t,S=Date.now()){if(!e)return 0;let w=new Date(e).getTime();if(Number.isNaN(w))return 0;let E=w+t*1e3;return Math.max(0,E-S)}const log=getLogger(`sync-engine`),SHA_HEX_40=/^[0-9a-f]{40}$/i;function jitteredMs(e){let t=e*1e3,S=t*.15*(2*Math.random()-1);return Math.round(t+S)}function isUnbornHead(e){try{let t=join(e,`.git`,`HEAD`);if(!existsSync(t))return!1;let S=readFileSync(t,`utf-8`).trim(),w=/^ref:\s+(refs\/.+)$/.exec(S);if(!w)return!1;let E=w[1];if(existsSync(join(e,`.git`,E)))return!1;let D=join(e,`.git`,`packed-refs`);if(existsSync(D)){let e=readFileSync(D,`utf-8`);if(RegExp(`^[0-9a-f]+\\s+${E}$`,`m`).test(e))return!1}return!0}catch{return!1}}function backoffMs(e){return e>=8?3600*1e3:e>=5?900*1e3:e>=3?300*1e3:0}var SyncEngine=class{state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;pullIntervalSeconds;pushIntervalSeconds;syncEnabled;credentialArgs;cc1Broadcaster;onStateChange;setBatchInProgress;onAutoDisable;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.onAutoDisable=e.onAutoDisable,this.statePath=resolve(getLocalDir(this.projectDir),`sync-state.json`),this.conflictStore=new ConflictStore(this.projectDir,this.currentBranch)}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=createGitInstance(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){log.warn({err:e},`[sync] remote detection failed`)}if(this.syncEnabled!==!0){e&&this.transitionTo(`disabled`),log.info({hasRemote:e,syncEnabled:this.syncEnabled},`[sync] sync not enabled — staying inactive`);return}if(!e){log.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=resolveGitDir(this.projectDir),S=t?join(t,`MERGE_HEAD`):null,w=S!==null&&existsSync(S);if(this.conflictCount>0&&!w)log.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&&w)try{let e=(await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim(),t=new Set(e?e.split(`
|
|
3290
|
-
`).map(e=>e.trim()).filter(Boolean):[]),S=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<S&&log.info({cleared:S-this.conflictCount,remaining:this.conflictCount},`[sync] reconciled conflicts.json against git unmerged index`)}catch(e){log.warn({err:e},`[sync] failed to reconcile conflicts with git index`)}if(w&&this.conflictCount===0){log.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`merge`,`--abort`])}catch(e){log.warn({err:e},`[sync] git merge --abort for stale MERGE_HEAD failed`)}}if(this.conflictCount>0){this.transitionTo(`conflict`),log.warn({count:this.conflictCount},`[sync] restarted with active conflicts — sync paused`);return}let E=computeRemainingMs(this.lastFetchUtc,this.pullIntervalSeconds),D=computeRemainingMs(this.lastSyncUtc,this.pushIntervalSeconds);this.schedulePull(E>0?E:void 0),this.schedulePush(D>0?D:void 0),log.info({branch:this.currentBranch,pullDelayMs:E,pushDelayMs:D},`[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=3e4,t=Date.now();for(;this.pullInFlight||this.pushInFlight;){if(Date.now()-t>3e4){log.warn({pullInFlight:this.pullInFlight,pushInFlight:this.pushInFlight},`[sync] setEnabled(false): timed out waiting for in-flight cycle to drain`);break}await setTimeout$1(50)}this.pausedReason=void 0,this.error=void 0,this.transitionTo(this.hasRemote?`disabled`:`dormant`),this.saveStateNow();return}if(this.hasRemote=await this.probeRemote(),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`?log.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}`):log.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,remote:this.hasRemote?readSyncRemoteInfo(this.projectDir):null,error:this.error,pausedReason:this.pausedReason}}async refreshIdentity(){let e=await resolveGitIdentity(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}async refreshRemote(){this.hasRemote||await this.probeRemote()&&(this.hasRemote=!0,log.info({syncEnabled:this.syncEnabled},`[sync] remote detected post-boot — re-evaluating state`),this.syncEnabled===!0?(this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush()):this.transitionTo(`disabled`))}async probeRemote(){if(!existsSync(join(this.projectDir,`.git`)))return!1;try{return(await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw(`remote`,`-v`)).trim().length>0}catch(e){return log.warn({err:e},`[sync] remote detection failed`),!1}}getConflicts(){return this.conflictStore.list()}async reconcileConflictsFromGit(){if(this.conflictCount===0)return;let e=this.conflictCount,t=resolveGitDir(this.projectDir),S=t?join(t,`MERGE_HEAD`):null;if(!(S!==null&&existsSync(S)))log.info({cleared:e},`[sync] external resolve detected (no MERGE_HEAD) — clearing tracked conflicts`),this.conflictStore.clear(),this.conflictCount=0;else try{let t=(await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim(),S=new Set(t?t.split(`
|
|
3290
|
+
`).map(e=>e.trim()).filter(Boolean):[]),S=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<S&&log.info({cleared:S-this.conflictCount,remaining:this.conflictCount},`[sync] reconciled conflicts.json against git unmerged index`)}catch(e){log.warn({err:e},`[sync] failed to reconcile conflicts with git index`)}if(w&&this.conflictCount===0){log.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`merge`,`--abort`])}catch(e){log.warn({err:e},`[sync] git merge --abort for stale MERGE_HEAD failed`)}}if(this.conflictCount>0){this.transitionTo(`conflict`),log.warn({count:this.conflictCount},`[sync] restarted with active conflicts — sync paused`);return}let E=computeRemainingMs(this.lastFetchUtc,this.pullIntervalSeconds),D=computeRemainingMs(this.lastSyncUtc,this.pushIntervalSeconds);this.schedulePull(E>0?E:void 0),this.schedulePush(D>0?D:void 0),log.info({branch:this.currentBranch,pullDelayMs:E,pushDelayMs:D},`[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=3e4,t=Date.now();for(;this.pullInFlight||this.pushInFlight;){if(Date.now()-t>3e4){log.warn({pullInFlight:this.pullInFlight,pushInFlight:this.pushInFlight},`[sync] setEnabled(false): timed out waiting for in-flight cycle to drain`);break}await setTimeout$1(50)}this.pausedReason=void 0,this.error=void 0,this.transitionTo(this.hasRemote?`disabled`:`dormant`),this.saveStateNow();return}if(this.hasRemote=await this.probeRemote(),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===`non-content-merge-failure`)&&(this.pausedReason=void 0,this.error=void 0),this.state===`dormant`||this.state===`disabled`||this.state===`conflict`||this.state===`auth-error`?log.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}`):log.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,remote:this.hasRemote?readSyncRemoteInfo(this.projectDir):null,error:this.error,pausedReason:this.pausedReason}}async refreshIdentity(){let e=await resolveGitIdentity(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}async refreshRemote(){this.hasRemote||await this.probeRemote()&&(this.hasRemote=!0,log.info({syncEnabled:this.syncEnabled},`[sync] remote detected post-boot — re-evaluating state`),this.syncEnabled===!0?(this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush()):this.transitionTo(`disabled`))}async probeRemote(){if(!existsSync(join(this.projectDir,`.git`)))return!1;try{return(await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw(`remote`,`-v`)).trim().length>0}catch(e){return log.warn({err:e},`[sync] remote detection failed`),!1}}getConflicts(){return this.conflictStore.list()}async reconcileConflictsFromGit(){if(this.conflictCount===0)return;let e=this.conflictCount,t=resolveGitDir(this.projectDir),S=t?join(t,`MERGE_HEAD`):null;if(!(S!==null&&existsSync(S)))log.info({cleared:e},`[sync] external resolve detected (no MERGE_HEAD) — clearing tracked conflicts`),this.conflictStore.clear(),this.conflictCount=0;else try{let t=(await createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}).git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim(),S=new Set(t?t.split(`
|
|
3291
3291
|
`).map(e=>e.trim()).filter(Boolean):[]);for(let e of this.conflictStore.list())S.has(e.file)||this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<e&&log.info({cleared:e-this.conflictCount,remaining:this.conflictCount},`[sync] external resolve detected (mid-merge) — pruned resolved entries`)}catch(e){log.warn({err:e},`[sync] reconcileConflictsFromGit: git probe failed`);return}this.conflictCount!==e&&(this.conflictCount===0&&this.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState())}async resolveConflict(e,t,S){this.setBatchInProgress?.(!0);try{try{await this.conflictStore.resolveConflict(e,t,S)}catch(e){throw this.conflictCount=this.conflictStore.count(),this.scheduleSaveState(),e}this.conflictCount=this.conflictStore.count(),this.conflictCount===0&&this.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState()}finally{this.setBatchInProgress?.(!1)}}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=>{log.error({err:e},`[sync] pull cycle uncaught error`)})},t)}schedulePush(e){this.pushTimer!==null&&clearTimeout(this.pushTimer);let t=e??jitteredMs(this.pushIntervalSeconds);this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.runPushCycle().catch(e=>{log.error({err:e},`[sync] push cycle uncaught error`)})},t)}effectivePullDelayMs(){let e=this.consecutiveFailures,t=backoffMs(e);return t>0?t:jitteredMs(this.pullIntervalSeconds)}async runPullCycle(){if(!this.pullInFlight&&!(this.state===`dormant`||this.state===`disabled`)){if(this.state===`conflict`){this.schedulePull();return}if(isUnbornHead(this.projectDir)){this.schedulePull();return}this.pullInFlight=!0;try{await this.doPullCycle()}finally{this.pullInFlight=!1,this.schedulePull()}}}async doPullCycle(){let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}),t;try{let S=(await e.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();if(!S||S===`HEAD`){this.transitionTo(`disabled`),this.pausedReason=`detached-head`,log.warn({},`[sync] detached HEAD — pausing sync`);return}t=S,this.currentBranch=t}catch(e){this.handleError(classifyGitError(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=classifyGitError(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{await this.commitDirtyContentFilesToHead(e);let S=await this.prepareForMerge(e,t);if(!S.proceed)return;try{await e.git.merge([`origin/${t}`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`)}finally{S.needsStashPop&&await this.popPreMergeStash(e)}}catch(e){let t=classifyGitError(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(isUnbornHead(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(),S=join(tmpdir(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),w=null;this.transitionTo(`pushing`);try{await withParentLock(async()=>{let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:S});if(isUnbornHead(this.projectDir)){log.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}let E;try{E=(await e.git.revparse(`HEAD`)).trim()}catch(e){let t=e instanceof Error?e.message:String(e),S=`${t}\n${e.git?.toString()??t}`;if(/unknown revision or path not in the working tree/i.test(S)||/ambiguous argument 'HEAD'/i.test(S)||/does not have any commits yet/i.test(S)){log.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}this.handleError(classifyGitError(e instanceof Error?e:Error(String(e))));return}await e.git.raw([`read-tree`,E]);let D=new Set;try{let t=(await e.git.raw([`ls-tree`,`-r`,`--name-only`,E])).trim();for(let e of t?t.split(`
|
|
3292
3292
|
`):[]){let t=e.trim();if(!t)continue;let S=join(this.projectDir,t),w=relative(this.contentDir,S);!w.startsWith(`..`)&&!this.contentFilter.isExcluded(w)&&D.add(t)}}catch{}if(t.length>0){let S=100;for(let S=0;S<t.length;S+=100){let w=t.slice(S,S+100).map(e=>e.projectRelPath);await e.git.raw([`add`,`--`,...w])}}let O=new Set(t.map(e=>e.projectRelPath)),k=[...D].filter(e=>!O.has(e));k.length>0&&await e.git.raw([`rm`,`--cached`,`--`,...k]);let j=(await e.git.raw([`write-tree`])).trim(),F=``;try{F=(await e.git.raw([`rev-parse`,`${E}^{tree}`])).trim()}catch{}if(F&&F===j){let S=null;try{S=(await e.git.raw([`rev-parse`,`origin/${this.currentBranch}`])).trim()}catch{}if(S===E){log.info({contentFileCount:t.length,headSha:E},`[sync] push cycle: nothing to commit (tree unchanged, origin matches HEAD)`),this.lastPushedSha=E,this.lastSyncUtc=new Date().toISOString(),this.transitionTo(`idle`);return}log.info({headSha:E,upstreamSha:S},`[sync] push cycle: tree unchanged but local ahead of origin — pushing existing commits`);let D=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),D=!0}catch{}D?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),w=E;return}let L=[];try{let S=(await e.git.raw([`diff-tree`,`--name-only`,`-r`,E,j])).trim();if(S){let e=new Map(t.map(e=>[e.projectRelPath,e.contentRelPath]));for(let t of S.split(`
|
|
3293
3293
|
`)){let S=t.trim();if(!S)continue;let w=e.get(S)??relative(this.contentDir,join(this.projectDir,S));w&&!w.startsWith(`..`)&&L.push(w)}}}catch{L=t.map(e=>e.contentRelPath)}let B=this.buildCommitMessage(L),H=await resolveGitIdentity(this.projectDir),q=H===null;this.identityUnresolved!==q&&(this.identityUnresolved=q,this.cc1Broadcaster?.signal(`sync-status`));let J=H?.name??`Open Knowledge`,Y=H?.email??`sync@open-knowledge.local`;e.git.env({GIT_AUTHOR_NAME:J,GIT_AUTHOR_EMAIL:Y,GIT_COMMITTER_NAME:J,GIT_COMMITTER_EMAIL:Y});let ee=(await e.git.raw([`commit-tree`,j,`-p`,E,`-m`,B])).trim();if(!ee||!SHA_HEX_40.test(ee)){log.warn({raw:ee},`[sync] commit-tree returned invalid SHA — aborting push`),this.transitionTo(`idle`);return}if(await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,ee,E]),t.length>0){let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}),S=100;for(let S=0;S<t.length;S+=100){let w=t.slice(S,S+100).map(e=>e.projectRelPath);try{await e.git.raw([`reset`,`HEAD`,`--`,...w])}catch{}}}let te=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),te=!0}catch{}te?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),w=ee}),w&&(this.lastPushedSha=w,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 S=classifyGitError(t instanceof Error?t:Error(String(t)));if(S.class===`semantic`&&S.subclass===`non-fast-forward`){if(e>0){log.info({},`[sync] push rejected (non-fast-forward) — fetching, merging, retrying`);let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs});this.setBatchInProgress?.(!0);try{await e.git.fetch(`origin`),await this.commitDirtyContentFilesToHead(e);let t=await this.prepareForMerge(e,this.currentBranch);if(!t.proceed){this.setBatchInProgress?.(!1);return}try{await e.git.merge([`origin/${this.currentBranch}`])}finally{t.needsStashPop&&await this.popPreMergeStash(e)}}catch(e){let t=classifyGitError(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}log.info({},`[sync] push still rejected after retry — waiting for next pull cycle`),this.consecutiveFailures++,this.state===`pushing`&&this.transitionTo(`idle`)}else this.handleError(S)}finally{try{unlinkSync(S)}catch{}}this.scheduleSaveState()}async commitDirtyContentFilesToHead(e){if((await e.git.status()).files.length===0)return null;let t=(await e.git.revparse(`HEAD`)).trim(),S=this.gatherContentFilesSync();if(S.length===0)return null;let w=join(tmpdir(),`ok-sync-retry-idx-${process.pid}-${Date.now()}.idx`),E=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:w});try{await E.git.raw([`read-tree`,t]);let w=100;for(let e=0;e<S.length;e+=100){let t=S.slice(e,e+100).map(e=>e.projectRelPath);await E.git.raw([`add`,`--`,...t])}let D=(await E.git.raw([`write-tree`])).trim();if(D===(await E.git.raw([`rev-parse`,`${t}^{tree}`])).trim())return null;let O=await resolveGitIdentity(this.projectDir),k=O?.name??`Open Knowledge`,j=O?.email??`sync@open-knowledge.local`;E.git.env({GIT_AUTHOR_NAME:k,GIT_AUTHOR_EMAIL:j,GIT_COMMITTER_NAME:k,GIT_COMMITTER_EMAIL:j});let F=(await E.git.raw([`commit-tree`,D,`-p`,t,`-m`,`Auto-save: interim before merge`])).trim();if(!F||!SHA_HEX_40.test(F))return log.warn({raw:F},`[sync] commit-tree returned invalid SHA in commitDirtyContentFilesToHead`),null;await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,F,t]);for(let t=0;t<S.length;t+=100){let w=S.slice(t,t+100).map(e=>e.projectRelPath);try{await e.git.raw([`reset`,`HEAD`,`--`,...w])}catch{}}return F}finally{try{unlinkSync(w)}catch{}}}async prepareForMerge(e,t){let S=``;try{S=(await e.git.raw([`diff-index`,`--name-only`,`HEAD`])).trim()}catch(e){return log.warn({err:e,branch:t},`[sync] diff-index failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1}}if(!S)return{proceed:!0,needsStashPop:!1};let w=S.split(`
|
|
3294
3294
|
`).map(e=>e.trim()).filter(Boolean);if(w.length===0)return{proceed:!0,needsStashPop:!1};let E=``;try{E=(await e.git.raw([`diff`,`--name-only`,`HEAD..origin/${t}`])).trim()}catch(e){return log.warn({err:e,branch:t},`[sync] merge-path diff failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1}}let D=new Set(E.split(`
|
|
3295
3295
|
`).map(e=>e.trim()).filter(Boolean)),O=w.filter(e=>D.has(e));if(O.length>0)return this.error=`Sync paused — your local changes to ${O.slice(0,3).join(`, `)}${O.length>3?`, +${O.length-3} more`:``} conflict with incoming changes. Commit, stash, or discard them before syncing.`,this.pausedReason=`external-changes-pending`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),log.warn({files:O},`[sync] paused — dirty paths overlap incoming merge`),{proceed:!1,needsStashPop:!1};let k=`ok-sync: pre-merge stash @ ${new Date().toISOString()}`;try{await e.git.raw([`stash`,`push`,`-m`,k])}catch(e){return log.warn({err:e},`[sync] stash push failed — proceeding without stash`),{proceed:!0,needsStashPop:!1}}return{proceed:!0,needsStashPop:!0}}async popPreMergeStash(e){try{await e.git.raw([`stash`,`pop`])}catch(e){log.warn({err:e},`[sync] stash pop failed — stash remains on stack`)}}gatherContentFilesSync(){let e=[],t=S=>{let w;try{w=readdirSync(S,{withFileTypes:!0})}catch{return}for(let E of w){let w=join(S,E.name);if(E.isDirectory()){if(E.name===`node_modules`||E.name===`.git`||E.name.startsWith(`.`)&&E.name!==`.ok`)continue;t(w)}else if(E.isFile()){let t=relative(this.contentDir,w);if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t)){let S=relative(this.projectDir,w);e.push({contentRelPath:t,projectRelPath:S})}}}};return existsSync(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=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs}),t=[];try{let S=(await e.git.raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();t=S?S.split(`
|
|
3296
|
-
`).map(e=>e.trim()).filter(Boolean):[]}catch(t){log.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){log.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 S=[],w=[];for(let e of t){let t=join(this.projectDir,e),E=relative(this.contentDir,t);!E.startsWith(`..`)&&!this.contentFilter.isExcluded(E)?S.push(e):w.push(e)}for(let t of w)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),log.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){log.warn({err:e,file:t},`[sync] auto-resolve failed —
|
|
3296
|
+
`).map(e=>e.trim()).filter(Boolean):[]}catch(t){log.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){log.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 S=[],w=[];for(let e of t){let t=join(this.projectDir,e),E=relative(this.contentDir,t);!E.startsWith(`..`)&&isSupportedDocFile(E)&&!this.contentFilter.isExcluded(E)?S.push(e):w.push(e)}let E=[];for(let t of w)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),log.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){log.warn({err:e,file:t},`[sync] non-content auto-resolve failed — will abort merge and pause sync`),E.push({file:t,err:e})}if(E.length>0){let t=E.map(e=>e.file);try{await e.git.raw([`merge`,`--abort`])}catch(e){log.warn({err:e,files:t},`[sync] git merge --abort failed during non-content cleanup`)}this.error=`Sync paused — couldn't auto-resolve ${t.slice(0,3).join(`, `)}${t.length>3?`, +${t.length-3} more`:``}. Resolve in your terminal (e.g. \`git rm <file>\` or \`git checkout --ours/--theirs <file> && git add <file>\`), then retry sync.`,this.pausedReason=`non-content-merge-failure`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),log.warn({files:t},`[sync] non-content auto-resolve failed — merge aborted, sync paused`);return}if(S.length>0){for(let e of S)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`),log.warn({files:S},`[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`),log.info({},`[sync] all conflicts auto-resolved — merge committed`)}catch(t){log.warn({err:t},`[sync] failed to commit after auto-resolving conflicts — aborting merge`);try{await e.git.raw([`merge`,`--abort`])}catch(e){log.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.transitionTo(`idle`)}}async abortMerge(){let e=createGitInstance(this.projectDir,{credentialArgs:this.credentialArgs});try{await e.git.raw([`merge`,`--abort`]),log.info({},`[sync] merge aborted`)}catch(e){log.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,log.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`,this.onAutoDisable?.(`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,log.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)};writeFileSync(this.statePath,JSON.stringify(e,null,2),`utf-8`)}catch(e){log.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(existsSync(this.statePath))try{let e=readFileSync(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;let S=t.inflightConflicts??[];if(S.length>0){for(let e of S)this.conflictStore.list().some(t=>t.file===e)||this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count()}}catch(e){log.warn({err:e},`[sync] failed to load sync state`)}}};const MOUNT_ID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function createSyncHandshakeSpanExtension(){return{async afterLoadDocument({documentName:e,requestParameters:t}){if(isSystemDoc(e)||isConfigDoc(e))return;let S=t?.get(`mountId`)??void 0,w={"doc.name":e};S!==void 0&&MOUNT_ID_PATTERN.test(S)&&(w[`mount.id`]=S);try{withSpanSync(`sync.handshake`,{attributes:w},()=>{})}catch(e){console.warn(`[sync-handshake-span] emission failed:`,e instanceof Error?e:String(e))}}}}const TAG_VALUE_RE=createTagInTextRegex();function createEmptyState(){return{byTag:new Map,byDoc:new Map,byDocLiteral:new Map}}function stripInlineCodeSpans(e){return e.replace(/`[^`]*`/g,``)}function extractInlineTagsFromBody(e){let t=e.replaceAll(`\r
|
|
3297
3297
|
`,`
|
|
3298
3298
|
`).split(`
|
|
3299
3299
|
`),S=[],w=!1,E=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){w?RegExp(`^\\s{0,3}${E[0]==="`"?"`":`~`}{${E.length},}\\s*$`).test(e)&&(w=!1,E=``):(w=!0,E=t[1]);continue}if(w)continue;let D=stripInlineCodeSpans(e);for(TAG_VALUE_RE.lastIndex=0;;){let e=TAG_VALUE_RE.exec(D);if(e===null)break;let t=e[2];t&&S.push(t)}}return S}var TagIndex=class{contentDir;contentFilter;state=createEmptyState();constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter}updateDocumentFromMarkdown(e,t){if(!(isSystemDoc(e)||isConfigDoc(e)))try{let{frontmatter:S,body:w}=stripFrontmatter(t),E=extractFrontmatterTags(S?unwrapFrontmatterFences(S):``),D=extractInlineTagsFromBody(w),O=new Set([...E,...D]),k=new Set;for(let e of O)for(let t of expandTagToHierarchy(e))k.add(t);this.applyDocSnapshot(e,O,k)}catch(t){console.warn(`[tag-index] Failed to scan ${e} for tag extraction:`,t),this.deleteDocument(e)}}deleteDocument(e){if(isSystemDoc(e)||isConfigDoc(e))return;let t=this.state.byDoc.get(e);if(t){for(let S of t){let t=this.state.byTag.get(S);t&&(t.delete(e),t.size===0&&this.state.byTag.delete(S))}this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)}}renameDocument(e,t,S){this.deleteDocument(e),this.updateDocumentFromMarkdown(t,S)}getDocsForTag(e){let t=this.state.byTag.get(e);return t?[...t].sort((e,t)=>e.localeCompare(t)):[]}getDocsForTagWithMatches(e){let t=this.state.byTag.get(e);if(!t)return[];let S=[];for(let w of t){let t=this.state.byDocLiteral.get(w);if(!t)continue;let E=tagsMatchingPrefix(t,e);S.push({docName:w,matchingTags:[...E].sort((e,t)=>e.localeCompare(t))})}return S.sort((e,t)=>e.docName.localeCompare(t.docName))}getAllTags(){let e=[...this.state.byTag.entries()],t=e.map(([e])=>e),S=new Set;for(let e of t){let t=e.indexOf(`/`);t>0&&S.add(e.slice(0,t));let w=t;for(;w>0;)S.add(e.slice(0,w)),w=e.indexOf(`/`,w+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!S.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){if(this.state=createEmptyState(),!existsSync(this.contentDir))return;let e=this.listDocsWithPaths();for(let{docName:t,filePath:S}of e)try{let e=readFileSync(S,`utf-8`);this.updateDocumentFromMarkdown(t,e)}catch(e){console.warn(`[tag-index] Failed to read ${t} during init:`,e)}}applyDocSnapshot(e,t,S){let w=this.state.byDoc.get(e)??new Set;for(let t of w){if(S.has(t))continue;let w=this.state.byTag.get(t);w&&(w.delete(e),w.size===0&&this.state.byTag.delete(t))}for(let t of S){let S=this.state.byTag.get(t);S||(S=new Set,this.state.byTag.set(t,S)),S.add(e)}S.size===0?(this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)):(this.state.byDoc.set(e,S),this.state.byDocLiteral.set(e,t))}listDocsWithPaths(){let e=[];this.walkContentDir(this.contentDir,e),e.sort((e,t)=>e.docName===t.docName?t.filePath.localeCompare(e.filePath):e.docName.localeCompare(t.docName));let t=new Set;return e.filter(({docName:e})=>t.has(e)?!1:(t.add(e),!0))}walkContentDir(e,t){let S;try{S=readdirSync(e,{withFileTypes:!0})}catch(t){console.warn(`[tag-index] Failed to read directory ${e}:`,t);return}for(let w of S){let S=join(e,w.name);if(w.isDirectory()){let e=relative(this.contentDir,S);if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;this.walkContentDir(S,t);continue}if(!w.isFile()||!isSupportedDocFile(w.name))continue;let E=relative(this.contentDir,S);this.contentFilter?.isExcluded(E)||t.push({docName:stripDocExtension(E),filePath:S})}}};const PARK_SNAPSHOT_ORIGIN=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function createServer$1(e){let{contentDir:t,projectDir:S=t,quiet:w=!0,debounce:E=2e3,maxDebounce:D=1e4,gitEnabled:O=!0,commitDebounceMs:k=3e4,wipRef:j=`refs/wip/main`,configHomedirOverride:F,enableTestRoutes:L=!1,shadowRepo:B,contentRoot:H,destroyTimeoutMs:q=1e4,localOpCliArgs:J,skipStateManifestCheck:Y=!1}=e,ee=getLogger(`server`);function te(){let e=readConfigSafely({absPath:resolveConfigPath(`project-local`,S),sideline:!1,warn:e=>ee.warn({message:e},`[config] could not read project-local config`)}),t=e.value.autoSync?.enabled;return t==null?(e.valid||ee.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to project config`),readConfigSafely({absPath:resolveConfigPath(`project`,S),sideline:!1,warn:e=>ee.warn({message:e},`[config] could not read project config`)}).value.autoSync?.enabled===!0):t===!0}initTelemetry();let ne=randomUUID(),ae=getLocalDir(S);if(acquireServerLock(ae,{port:e.port??0,worktreeRoot:S,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!Y)try{assertCompatibleStateManifest({lockDir:ae,shadowRepoDir:resolveShadowDir(S)})}catch(e){throw releaseServerLock(ae),e}let oe=createBasenameIndex(),se=(e,t)=>oe.resolveEmbed(e,t),ce=(e,S)=>{let w=oe.resolveEmbed(e,S);if(!w&&e.includes(`/`)&&(w=e.replace(/^\.?\//,``)),!w)return null;let E=resolve(t,w),D=resolve(t);if(E!==D&&!E.startsWith(`${D}/`))return null;try{let e=statSync(E);return e.isFile()?e.size:null}catch{return null}},ue,de,fe,me,ge,_e,ve,ye=null,Ce=null,we=null,Te=null,De=new Set,je=!1,Me,Pe,Ie,Re=new Promise((e,t)=>{Pe=e,Ie=t});function ze(e){ye?.signal(e)}let Be=2e3,Ve=null;function Ue(){Ve!==null&&clearTimeout(Ve),Ve=setTimeout(()=>{Ve=null,de.saveToDisk().catch(e=>{console.warn(`[backlinks] Failed to persist debounced cache:`,e)})},2e3)}let We=new RecentlyRemovedDocs(void 0,{onEviction:()=>incrementRecentlyRemovedDocsEviction(),onSizeChange:e=>setRecentlyRemovedDocsSize(e)}),Ge=(e,t)=>{isSystemDoc(e)||isConfigDoc(e)||We.setRenamed(e,t)},Ke=e=>{if(!(isSystemDoc(e)||isConfigDoc(e))){if(We.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}We.setDeleted(e)}},Xe=e=>{isSystemDoc(e)||isConfigDoc(e)||We.delete(e)};try{ue=createContentFilter({projectDir:S,contentDir:t,onAfterRebuild:()=>{de.rebuildFromDisk(getActiveBranch()).catch(e=>{getLogger(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)});try{fe.init()}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}try{let e=Rt?.pruneFileIndexNowExcluded()??0,t=Rt?.pruneFolderIndexNowExcluded()??0,S=e+t;S>0&&getLogger(`server-factory`).info({pruned:S,prunedFiles:e,prunedFolders:t},`[content-filter] pruned now-excluded entries from file indexes`)}catch(e){getLogger(`server-factory`).warn({err:e},`[content-filter] file index prune failed after onAfterRebuild`)}}}),de=new BacklinkIndex({projectDir:S,contentDir:t,contentFilter:ue}),fe=new TagIndex({contentDir:t,contentFilter:ue});try{fe.init()}catch(e){console.warn(`[server-factory] tag-index init failed; continuing with empty index:`,e)}me={current:B},ge=createPersistenceExtension({contentDir:t,projectDir:S,gitEnabled:O,commitDebounceMs:k,wipRef:j,shadowRef:me,contentRoot:H,backlinkIndex:de,configHomedirOverride:F,getCurrentBranch:()=>zt?.getLastKnownBranch()??null,resolveEmbed:se,resolveSize:ce,getPrincipal:()=>Te,onAgentCommit:()=>ye?.signal(`session-activity`),onDiskFlush:(e,t)=>ye?.emitDiskAck(e,t),onConfigRejected:(e,t)=>ye?.emitConfigValidationRejected(e,t),mdManager:e.mdManager}),_e=new Hocuspocus({quiet:w,debounce:E,maxDebounce:D,extensions:[ge.extension]});let q=_e.shouldUnloadDocument.bind(_e);_e.shouldUnloadDocument=e=>{if(De.has(e)||je&&q(e))return!0;let t=e.name;return isSystemDoc(t)||isConfigDoc(t)||getReconciledBase(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:q(e)},Me=async e=>{De.add(e);try{await _e.unloadDocument(e)}finally{De.delete(e)}},ye=new CC1Broadcaster(_e),Ce=new AgentFocusBroadcaster(_e),we=new AgentPresenceBroadcaster(_e),ve=new AgentSessionManager(_e);let Y=createLiveDerivedIndexExtension({backlinkIndex:de,tagIndex:fe,signalChannel:ze});_e.configuration.extensions.push(Y),_e.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,S=parseHocuspocusAuthToken(t),w=S?.expectedServerInstanceId;if(typeof w==`string`&&w.length>0&&w!==ne)throw new HocuspocusAuthRejection(`server-instance-mismatch`,`server instance mismatch: client claimed ${w}, this server is ${ne}`);let E=S?.expectedBranch,D=getActiveBranch();if(typeof E==`string`&&E.length>0&&E!==D)throw new HocuspocusAuthRejection(`branch-mismatch`,`branch mismatch: client claimed ${E}, server is on ${D}`);if(!S)return;let O=e.context;typeof S.principalId==`string`&&(Te&&S.principalId===Te.id?O.principalId=Te.id:Te?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:S.principalId,loaded:Te.id})):O.principalId=S.principalId),typeof S.tabSessionId==`string`&&(O.tabSessionId=S.tabSessionId),O.kind=`human`}}),_e.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!isConfigDoc(e.documentName))return;let t=e.request,S=t.socket?.remoteAddress;if(S!==void 0&&!isLoopbackAddress(S))throw Error(`config-doc admission requires loopback peer (peer=${S}, doc=${e.documentName})`);let w=e.requestHeaders,E=(w&&typeof w.get==`function`?w.get(`host`):null)??t.headers?.host??void 0;if(!isAllowedWorkspaceHostHeader(E))throw Error(`config-doc admission requires loopback Host header (host=${E??`<absent>`}, doc=${e.documentName})`)}});let ee=resolve(t);function te(e){if(!isSafeDocName(e))return null;let t=resolve(ee,`${e}${getDocExtension(e)}`);return!t.startsWith(`${ee}/`)&&t!==ee?null:t}_e.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await runRemovalRedirectGuard(e.documentName,{recentlyRemovedDocs:We,resolveFilePath:te,fileExists:existsSync})}}),_e.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new IncomingMessage(e.update);if(t.readVarString(),t.readVarUint()===MessageType.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${SYSTEM_DOC_NAME} rejected — server-only channel`)}});let ae=createApiExtension({hocuspocus:_e,sessionManager:ve,contentDir:t,contentFilter:ue,serverInstanceId:ne,getFileIndex:()=>Rt?Rt.getFileIndex():new Map,getFolderIndex:()=>Rt?Rt.getFolderIndex():new Map,getAliasMap:()=>Rt?Rt.getAliasMap():new Map,rescanFiles:()=>Rt?.rescanFromDisk(),enableTestRoutes:L,shadowRef:me,flushGitCommit:()=>ge.flushPendingGitCommit(),flushContributors:()=>ge.flushContributors(),getCurrentBranch:()=>zt?.getLastKnownBranch()??null,getDiskAckSVs:()=>ye?.getLatestDiskAckSVsAsBase64()??{},contentRoot:H,backlinkIndex:de,tagIndex:fe,signalChannel:ze,agentFocusBroadcaster:Ce,agentPresenceBroadcaster:we,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>Bt,localOpCliArgs:J,projectDir:S,resolveEmbed:se,getPrincipal:()=>Te,forceUnloadDocument:Me,ready:Re,recentlyRemovedDocs:We,serializeDoc:at});_e.configuration.extensions.push(ae),_e.configuration.extensions.push(createServerObserverExtension({mdManager,schema,shadowRef:me,contentRoot:H,getCurrentBranch:()=>zt?.getLastKnownBranch()??null,resolveEmbed:se,resolveSize:ce})),_e.configuration.extensions.push(createSyncHandshakeSpanExtension())}catch(e){throw releaseServerLock(ae),e}let $e=null,nt=new Map,rt=[];function it(e,t){let S=resolve(e,`rescue`),w=resolve(S,`${t}${getDocExtension(t)}`);return w.startsWith(`${S}/`)?w:null}function at(e){let t=_e.documents.get(e);if(!t)return null;let{frontmatter:S,body:w}=stripFrontmatter(t.getText(`source`).toString());return prependFrontmatter(S,w)}let st=(e,t)=>applyExternalChange(_e,e,t,se,ce);function vt(e){if(!isDocInConflict(e))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let Tt=e=>{if(!e)return;let t=`[[${e}]]`;for(let[S]of _e.documents){if(isSystemDoc(S)||isConfigDoc(S))continue;let w=_e.documents.get(S);if(!w)continue;let E=w.getText(`source`).toString();if(E.includes(t))try{w.transact(()=>{applyDiskContentToDoc(w,E,se,S)},FILE_WATCHER_ORIGIN)}catch(t){ee.error({err:t,docName:S,assetBasename:e},`[asset-event] failed to re-render ${S} for asset basename ${e}`)}}},Et=null,Dt=e=>{e&&(Et===null&&(Et=new Set,setImmediate(()=>{let e=Et;if(Et=null,e)try{for(let t of e)Tt(t)}catch(t){ee.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Et.add(e))};function jt(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return assertNeverDiskEvent(e)}}async function Mt(e){try{switch(e.kind){case`create`:ee.info({docName:e.docName},`[reconcile] create: ${e.docName}`),de.updateDocumentFromMarkdown(e.docName,e.content),Ue(),fe.updateDocumentFromMarkdown(e.docName,e.content),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Xe(e.docName);break;case`update`:{let{docName:t,content:S}=e,w=_e.documents.get(t);if(!w){de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`);return}let E=getReconciledBase(t)??``,D=at(t)??E,O=reconcile({docName:t,base:E,ours:D,theirs:S}),k=contentHash(E).slice(0,6),j=contentHash(D).slice(0,6),F=contentHash(S).slice(0,6);switch(ee.info({docName:t,base:k,ours:j,theirs:F,result:O.kind},`[reconcile] ${t} base=${k} ours=${j} theirs=${F} result=${O.kind}`),O.kind){case`noop`:vt(w),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`);break;case`clean`:try{st(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),vt(w),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),setReconciledBase(t,S),vt(w)}break;case`merged`:try{st(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),vt(w),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),setReconciledBase(t,S),vt(w)}break;case`conflicts`:try{st(t,O.newContent),setReconciledBase(t,O.newContent),incrementReconcile(),incrementConflict(),de.updateDocumentFromMarkdown(t,S),Ue(),fe.updateDocumentFromMarkdown(t,S),ze(`backlinks`),ze(`graph`),ze(`tags`)}catch(e){ee.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),setReconciledBase(t,S)}{let e=w.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}break;case`refused`:{incrementConflict();let e=w.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,O.reason);break}}break}case`delete`:{let{docName:t}=e,S=_e.documents.get(t);if(!S){de.deleteDocument(t),Ue(),fe.deleteDocument(t),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Ke(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let w=getReconciledBase(t)??``,E=at(t)??``,D=E!==w;if(D&&me.current){let e=me.current,S=zt?.getLastKnownBranch()??`main`;queueMicrotask(()=>{saveInMemoryCheckpoint(e,H??``,{kind:`external-change-rescue`,docName:t,contents:E,label:`External change recovered @ ${new Date().toISOString()}`,branch:S,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),ee.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{ee.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}S.getMap(`lifecycle`).set(`status`,`deleted-upstream`),deleteReconciledBase(t),de.deleteDocument(t),Ue(),fe.deleteDocument(t),ee.info({docName:t,isDirty:D},`[reconcile] delete: ${t} (dirty=${D})`),_e.closeConnections(t),await Me(S),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Ke(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:S,content:w}=e,E=_e.documents.get(t);if(deleteReconciledBase(t),setReconciledBase(S,w),de.renameDocument(t,S,w),Ue(),fe.renameDocument(t,S,w),E){let e=E.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,S)}ee.info({oldDocName:t,newDocName:S},`[reconcile] rename: ${t} → ${S}`),ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`),Ge(t,S),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:S,kind:`renamed`,source:`watcher-rename`}));break}case`conflict`:{let{docName:t}=e,S=_e.documents.get(t);if(!S)return;let w=at(t);w===null?ee.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):setReconciledBase(t,w);let E=S.getMap(`lifecycle`);E.set(`status`,`conflict`),E.set(`reason`,`conflict-markers`),ee.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:oe.add(e.relativePath),ze(`files`),Dt(basename(e.relativePath));break;case`asset-delete`:oe.remove(e.relativePath),ze(`files`),Dt(basename(e.relativePath));break;case`folder-create`:case`folder-delete`:ze(`files`);break;default:assertNeverDiskEvent(e)}}catch(t){let S=jt(e);ee.error({err:t,kind:e.kind,label:S},`[reconcile] failed to handle ${e.kind} for ${S}`)}}let Ft=[];async function It(e){if(isBatchInProgress()){Ft.push(e);return}await Mt(e)}async function Lt(){let e=Ft.splice(0,Ft.length);for(let t of e)await Mt(t)}let Rt=null,zt=null,Bt=null,Vt=null;async function Ht(e){if(_e.documents.size===0)return;let t=!1,S=new Promise(e=>{_e.configuration.extensions.push({async afterUnloadDocument({instance:S}){!t&&S.getDocumentsCount()===0&&(t=!0,e())}})}),w=Array.from(_e.documents.keys());_e.closeConnections(),_e.flushPendingStores();for(let e of _e.documents.values())e.getConnectionsCount()===0&&_e.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let E,D=new Promise((S,D)=>{E=setTimeout(()=>{t=!0;let S=Array.from(_e.documents.keys()),E=[],O=[];if(me.current){for(let e of S)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let t=at(e);if(t===null){ee.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),O.push(e);continue}let S=it(me.current.gitDir,e);if(!S){ee.warn({docName:e,gitDir:me.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),O.push(e);continue}mkdirSync(dirname(S),{recursive:!0}),writeFileSync(S,t,`utf-8`),incrementRescueBuffer(),E.push(e),ee.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){O.push(e),ee.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else ee.warn({stillLoadedCount:S.length},`[rescue] shadow repo unavailable at flush timeout — ${S.length} doc(s) will be lost: [${S.join(`, `)}]`),O.push(...S);let k=E.length>0||O.length>0?` — rescued [${E.join(`, `)}]${O.length>0?`, lost [${O.join(`, `)}]`:``}`:``;D(Error(`flushAllStoresAndWait timeout after ${e}ms — ${S.length}/${w.length} docs did not unload: [${S.join(`, `)}]${k}`))},e)});try{await Promise.race([S,D])}finally{E!==void 0&&clearTimeout(E)}}async function Ut(){return Vt||(Vt=(async()=>{let e=Date.now(),t=[];je=!0,Ve!==null&&(clearTimeout(Ve),Ve=null);let w,E=await Promise.race([Re.then(()=>`completed`,e=>(ee.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{w=setTimeout(()=>e(`timeout`),5e3)})]);w!==void 0&&clearTimeout(w),E===`timeout`&&ee.warn({},`[server] init did not complete within 5s during shutdown`);let D=_e.documents.size;try{try{try{zt&&=(await zt.unsubscribe(),null),Rt&&=(await Rt.unsubscribe(),null);for(let{docName:e,cleanup:t}of rt)try{await t()}catch(t){ee.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}rt.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{ye?.destroy(),we?.destroy(),$e&&=(await $e.disconnect(),null);for(let[e,t]of nt)try{await t.disconnect()}catch(t){ee.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}nt.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await ve.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await Ht(q)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-3 flush failed`)}let e;try{await Promise.race([(async()=>{await ge.flushPendingGitCommit(),await ge.waitForPendingCommits()})(),new Promise((t,S)=>{e=setTimeout(()=>S(Error(`L2 git flush timeout`)),q)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{Bt&&=(await Bt.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(me.current){try{let e=(await esm_default({baseDir:S,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&writeFileSync(resolve(me.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{destroyShadowRepo(me.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let w=Date.now()-e;t.length===0?ee.info({documentCount:D,durationMs:w},`[server] shutdown flushed ${D} documents in ${w}ms`):ee.warn({documentCount:D,durationMs:w,phaseErrors:t},`[server] shutdown flushed ${D} documents in ${w}ms with ${t.length} phase error(s)`)}}finally{try{releaseServerLock(ae)}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),ee.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await shutdownTelemetry()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),Vt)}let Wt=[];async function Kt(){try{Te=await loadPrincipal(S),ee.info({principalId:Te.id},`[server] principal loaded`)}catch(e){ee.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!me.current)try{me.current=await initShadowRepo(S),ee.info({gitDir:me.current.gitDir},`[server] history repo initialized at ${me.current.gitDir}`)}catch(e){ee.error({err:e},`[server] history repo init failed`),Wt.push(`shadow-repo`)}if(me.current){let e=null;try{e=loadRenameLogIndex(me.current.gitDir),sweepLazyPopOrphans(me.current.gitDir,e),setRenameLogIndex(me.current.gitDir,e),ee.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){ee.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([gcRenameLog(me.current,e,{rebuild:!0}),new Promise((e,S)=>setTimeout(()=>S(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){ee.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}}if(me.current)try{await shadowGit(me.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`)){ee.warn({},`[server] history repo appears corrupted — reinitializing`);try{me.current=await initShadowRepo(S)}catch(e){ee.error({err:e},`[server] history repo reinit failed`),me.current=void 0,Wt.includes(`shadow-repo`)||Wt.push(`shadow-repo`)}}else ee.error({err:e},`[server] history repo check failed (transient?)`)}if(me.current)try{let e=resolve(me.current.gitDir,`last-known-head`),t=null;try{t=readFileSync(e,`utf-8`).trim()||null}catch{}let w=null;try{w=(await esm_default({baseDir:S,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(w!==null){if(w!==t){let e=`main`;try{let t=(await esm_default({baseDir:S,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}ee.info({lastKnownHead:t,currentHead:w,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${w}, action=import`);try{await commitUpstreamImport(me.current,H??``,t,w,e),incrementUpstreamImport()}catch(e){ee.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else ee.info({currentHead:w},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${w}, action=noop`);try{writeFileSync(e,w,`utf-8`)}catch(e){ee.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){ee.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=recoverPendingManagedRename(t,S);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,S=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;ee.warn({journalVersion:e.journal.version,fromPath:t,toPath:S,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${S}`)}}catch(e){ee.error({err:e},`[server] managed rename recovery failed`),Wt.push(`managed-rename-recovery`)}try{let e=cleanupOrphanUploadTempfiles(S);(e.deleted>0||e.errors>0)&&ee.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){ee.error({err:e},`[server] upload-tempfile sweep failed`),Wt.push(`upload-tempfile-sweep`)}try{$e=await _e.openDirectConnection(SYSTEM_DOC_NAME),ye?.emitServerInfo(ne,getActiveBranch())}catch(e){ee.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),Wt.push(`cc1-push`)}for(let e of CONFIG_DOC_NAMES)try{let t=await _e.openDirectConnection(e);nt.set(e,t)}catch(t){ee.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),Wt.push(`config-doc:${e}`)}let e=new Map([[CONFIG_DOC_NAME_PROJECT,resolveConfigPath(`project`,S)],[CONFIG_DOC_NAME_PROJECT_LOCAL,resolveConfigPath(`project-local`,S)],[CONFIG_DOC_NAME_USER,resolveConfigPath(`user`,S,F)]]);for(let t of CONFIG_DOC_NAMES){let S=e.get(t);if(S)try{ee.info({docName:t,path:S},`[config-file-watcher] starting`);let e=await startConfigFileWatcher(S,e=>{let S=_e.documents.get(t);ee.info({docName:t,hasDocument:S!==void 0,contentLength:e.length},`[config-file-watcher] file changed`);let w=applyExternalConfigChange(S??null,t,e,ge.configPersistenceCtx);if(ee.info({docName:t,outcome:w},`[config-file-watcher] applyExternalConfigChange outcome`),t===`__config__/project`||t===`__local__/project`){let e=te();Bt?.setEnabled(e).catch(t=>{ee.warn({err:t,enabled:e},`[sync] failed to apply autoSync.enabled from config`)})}});rt.push({docName:t,cleanup:e}),ee.info({docName:t,path:S},`[config-file-watcher] started`)}catch(e){ee.warn({err:e,docName:t,path:S},`[config-file-watcher] failed to start for ${t}`),Wt.push(`config-file-watcher:${t}`)}}try{let e=resolve(t,`.okignore`),w=resolve(S,`.gitignore`),E=ee;E.info({okignorePath:e,gitignorePath:w},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore`);let D=await startMultiPathConfigFileWatcher([e,w],(t,w)=>{(async()=>{if(t===e)try{let e=applyExternalConfigChange(_e.documents.get(`__config__/okignore`)??null,CONFIG_DOC_NAME_OKIGNORE,w,ge.configPersistenceCtx);E.info({docName:CONFIG_DOC_NAME_OKIGNORE,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){E.error({err:e,changedPath:relative(S,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let D=await ue.rebuildIgnorePatterns();if(D.ok)E.info({changedPath:relative(S,t),patternCount:D.patternCount,nestedFileCount:D.nestedFileCount,durationMs:D.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),ye?.signal(`files`);else{let e=relative(S,t)||`.`;E.warn({changedPath:e,error:D.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),ye?.emitConfigIgnoreNestedError(e,D.error.message)}})().catch(e=>{E.error({err:e,changedPath:relative(S,t)||`.`},`[ignore-watcher] handler threw`)})});rt.push({docName:`__ignore-files__`,cleanup:D}),E.info({okignorePath:e,gitignorePath:w},`[ignore-watcher] multi-path watcher started`)}catch(e){ee.warn({err:e,projectDir:S,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),Wt.push(`ignore-files-watcher`)}let w=resolveGitDir(S),E=w?readBranchFromHead(w)??`main`:`main`;switchReconciledBaseScope(E),de.switchBranch(E);try{{let e=getActiveBranch();try{if(await de.loadFromDisk(e)){let t=await de.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&ee.info(t,`[backlinks] startup reconcile: offline changes applied`)}else await de.rebuildFromDisk(e);de.saveToDisk().catch(t=>{console.warn(`[backlinks] Failed to persist startup cache for ${e}:`,t)})}catch(t){ee.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}}Rt=await startWatcher(t,It,ue),fe.init();let e=0;try{seedBasenameIndex({contentDir:t,contentFilter:ue,basenameIndex:oe,onSkip:(t,S,w)=>{e++,ee.warn({reason:t,code:S,path:w},`[basename-index] skipped entry during seed (${t}${S?` ${S}`:``})`)}}),e>0&&(ee.warn({count:e},`[basename-index] startup seed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve`),Wt.push(`basename-index-partial`))}catch(e){ee.error({err:e},`[basename-index] startup seed failed`),Wt.push(`basename-index`)}}catch(e){ee.error({err:e},`[server] disk bridge watcher failed to start`),Wt.push(`file-watcher`)}try{zt=await startHeadWatcher(S,async({trigger:e})=>{if(ee.info({trigger:e},`[batch] begin trigger=${e}`),incrementBatch(),_e.flushPendingStores(),await ge.flushPendingGitCommit(),setBatchInProgress(!0),me.current){let e=getActiveBranch(),t=resolveGitDir(S),w=t?readBranchFromHead(t)??e:e,E=[];for(let[e,t]of _e.documents){if(isSystemDoc(e)||isConfigDoc(e))continue;let S=null;if(t.transact(()=>{S=at(e)},PARK_SNAPSHOT_ORIGIN),S===null)continue;let w=getReconciledBase(e)??S;E.push({docName:e,markdown:S,diskSnapshot:w})}if(E.length>0)try{let t=await parkBranch(me.current,e,SERVICE_WRITER.id,E,w);t&&(incrementPark(),ee.info({count:E.length,branch:e,sha:t.slice(0,8)},`[history] parked ${E.length} docs on ${e} → ${t.slice(0,8)}`))}catch(e){ee.error({err:e},`[shadow] park failed`)}}},async e=>{let S=Ft.length,w=e.newBranch??`main`;if(ee.info({kind:e.batchKind,headMoved:e.headMoved,docs:S,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${S}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(setBatchInProgress(!1),await Lt(),await ge.flushDeferredStores(`within-branch`),Bt!==null)try{await Bt.reconcileConflictsFromGit()}catch(e){ee.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{incrementBranchSwitch(),Ft.splice(0,Ft.length),switchReconciledBaseScope(w),Ve!==null&&(clearTimeout(Ve),Ve=null),de.switchBranch(w),ue.rebuildDirCount();try{let e=0;oe.clear(),seedBasenameIndex({contentDir:t,contentFilter:ue,basenameIndex:oe,onSkip:(t,S,E)=>{e++,ee.warn({reason:t,code:S,path:E,branch:w},`[basename-index] skipped entry during branch-switch reseed (${t}${S?` ${S}`:``})`)}}),e>0&&(ee.warn({count:e,branch:w},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),Wt.includes(`basename-index-partial`)||Wt.push(`basename-index-partial`))}catch(e){ee.error({err:e,branch:w},`[basename-index] branch-switch reseed failed`)}for(let[e,S]of _e.documents)if(!(isSystemDoc(e)||isConfigDoc(e)))try{let E=safeContentPath(e,t);if(!existsSync(E)){let t=getReconciledBase(e)??``,E=at(e)??``;if(E!==t&&me.current){let t=me.current;queueMicrotask(()=>{saveInMemoryCheckpoint(t,H??``,{kind:`external-change-rescue`,docName:e,contents:E,label:`External change recovered @ ${new Date().toISOString()}`,branch:w,metadata:{incomingDiskSha:``}}).then(()=>{incrementRescueBuffer(),ee.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{ee.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}S.getMap(`lifecycle`).set(`status`,`deleted-upstream`),ee.info({docName:e,branch:w},`[branch-switch] tombstone: ${e} (not on ${w})`);continue}let D=readFileSync(E,`utf-8`);st(e,D),setReconciledBase(e,D),ee.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){ee.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}ee.info({branch:w,docCount:_e.documents.size},`[branch-switch] loaded branch ${w} (${_e.documents.size} docs)`);try{if(await de.loadFromDisk(w)){let e=await de.reconcileWithDisk(w);(e.added>0||e.updated>0||e.deleted>0)&&ee.info(e,`[backlinks] branch-switch reconcile for ${w}`)}else await de.rebuildFromDisk(w);de.saveToDisk(w).catch(e=>{console.warn(`[backlinks] Failed to persist branch cache for ${w}:`,e)})}catch(e){ee.error({err:e,branch:w},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}if(fe.init(),me.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of _e.documents)if(!(isSystemDoc(t)||isConfigDoc(t)))try{let S=await readParkedState(me.current,w,SERVICE_WRITER.id,t);if(!S||S.markdown===S.diskSnapshot)continue;let E=getReconciledBase(t);if(!E)continue;let D=reconcile({docName:t,base:S.diskSnapshot,ours:S.markdown,theirs:E});switch(D.kind){case`merged`:case`clean`:st(t,D.newContent),setReconciledBase(t,D.newContent),e++;break;case`conflicts`:st(t,D.newContent),setReconciledBase(t,D.newContent),incrementConflict(),e++;{let e=_e.documents.get(t);if(e){let t=e.getMap(`lifecycle`);t.set(`status`,`conflict`),t.set(`reason`,`merged-with-markers`)}}break;case`noop`:case`refused`:break}}catch(e){ee.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&ee.info({count:e,branch:w},`[branch-switch] restored ${e} parked docs on ${w}`)}if(e.oldBranch?.startsWith(`detached-`)&&me.current)try{let t=shadowGit(me.current),S=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();if(S){for(let e of S.split(`
|
|
3300
3300
|
`))e&&await t.raw(`update-ref`,`-d`,e);ee.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`)}}catch(e){ee.error({err:e},`[branch-switch] detached cleanup failed`)}setBatchInProgress(!1),await ge.flushDeferredStores(`discard-stale`),ye?.emitBranchSwitched(w)}if(e.headMoved&&e.newHead&&me.current&&S>0){let t=H??`.`;try{let S=await commitUpstreamImport(me.current,t,e.oldHead,e.newHead,w);incrementUpstreamImport(),ee.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:S.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${S.slice(0,8)}`)}catch(e){ee.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){ee.error({err:e},`[server] HEAD watcher failed to start`),Wt.push(`head-watcher`)}let D=J?.[0]??`open-knowledge`,O=[`-c`,`credential.helper=!${J&&J.length>1?J.join(` `):D} auth git-credential`];try{Bt=new SyncEngine({projectDir:S,contentDir:t,contentFilter:ue,contentRoot:H,syncEnabled:te(),credentialArgs:O,cc1Broadcaster:ye,setBatchInProgress:e=>{setBatchInProgress(e),e||ge.flushDeferredStores(`within-branch`).catch(e=>{ee.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{ee.info({state:e},`[sync] state → ${e}`)},onAutoDisable:async e=>{ee.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await writeConfigPatch({cwd:S,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||ee.error({result:t,reason:e,humanError:humanFormat(t.error),configPath:resolveConfigPath(`project-local`,S)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await Bt.start()}catch(e){ee.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),Bt=null}ze(`files`),ze(`backlinks`),ze(`graph`),ze(`tags`)}return Kt().then(Pe,Ie),{hocuspocus:_e,sessionManager:ve,cc1Broadcaster:ye,agentFocusBroadcaster:Ce,agentPresenceBroadcaster:we,contentFilter:ue,basenameIndex:oe,serverInstanceId:ne,destroy:Ut,ready:Re,degraded:Wt,lockDir:ae,get syncEngine(){return Bt}}}const LEGACY_RUNTIME_FILENAMES=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],LEGACY_RUNTIME_DIRNAMES=[`cache`,`tmp`];function findLegacyRuntimeFiles(e){let t=resolve(e,LOCAL_DIR);if(!(()=>{if(!existsSync(t))return!0;try{return readdirSync(t).length===0}catch{return!0}})())return[];let S=[];for(let t of LEGACY_RUNTIME_FILENAMES)existsSync(resolve(e,t))&&S.push(t);for(let t of LEGACY_RUNTIME_DIRNAMES){let w=resolve(e,t);try{existsSync(w)&&statSync(w).isDirectory()&&S.push(`${t}/`)}catch{}}return S}function computeWorktreeAttributes(e){let t=resolveGitDirDetailed(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const DEFAULT_IDLE_THRESHOLD_MS=1800*1e3,DESTROY_STEP_TIMEOUT_MS=5e3;async function bootServer(e){initTelemetry();let{kind:t,gitdir:S}=computeWorktreeAttributes(e.projectDir??e.contentDir),w={"ok.worktree.kind":t};return S!==null&&(w[`ok.worktree.gitdir`]=normalizeFsPath(S)),withSpan(`ok.boot`,{attributes:w},async()=>bootServerInner(e))}async function bootServerInner(e){let t=e.skipAutoInit??!1,S=e.attachUiSibling??!0,w=e.idleShutdownMs,E=e.log??getLogger(`boot`),D=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,O=e.lockKind??D??`interactive`,{createServer:k}=await import(`node:http`),{updateServerLockPort:j}=await import(`./server-lock-BniQ3qki-DjKtnzVr.mjs`).then(e=>e.a),F=!1;if(!t&&e.autoInitFn)try{F=!!await e.autoInitFn()}catch(e){E.warn({err:e},`autoInitFn failed`)}let L=e.projectDir??e.contentDir,B=resolve(L,`.ok`);if(!existsSync(resolve(B,`config.yml`)))throw new MissingOkConfigError(existsSync(B)?`config`:`okdir`,L);existsSync(resolve(B,`.gitignore`))||console.warn("[boot] Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let H=findLegacyRuntimeFiles(B);H.length>0&&console.warn(`[boot] Found legacy runtime files at .ok/${H.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${LOCAL_DIR}/.`);let q=createServer$1({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,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,onAgentWrite:e.onAgentWrite,lockKind:O,skipStateManifestCheck:e.skipStateManifestCheck}),{hocuspocus:J,destroy:Y,ready:ee,degraded:te,lockDir:ne,sessionManager:ae,agentFocusBroadcaster:oe,agentPresenceBroadcaster:se}=q,ce=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ue=e.port??0,de=createMcpHttpHandler({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${ce}:${ue}`,log:E}),fe=k();fe.headersTimeout=3e4,fe.requestTimeout=6e4;let me=e.serveContentAssets?createAssetServeMiddleware({contentFilter:q.contentFilter,contentSirv:build_default(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:INLINE_RENDERABLE_EXTENSIONS,assetExtensions:ASSET_EXTENSIONS,blocklistExtensions:EXECUTABLE_BLOCKLIST_EXTENSIONS}):void 0,ge=!1;if(e.reactShellDistDir)try{acquireUiLock(ne,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ge=!0}catch(e){if(e instanceof UiLockCollisionError)E.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:ne},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await Y().catch(()=>{}),e}let _e=e.reactShellDistDir?build_default(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,ve=mountMcpAndApi({httpServer:fe,hocuspocus:J,mcpHttpHandler:de,log:E,sessionManager:ae,agentFocusBroadcaster:oe,agentPresenceBroadcaster:se,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:me,reactShellMiddleware:_e}),ye=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},Ce=null;w!==null&&(Ce=attachIdleShutdown({httpServer:fe,thresholdMs:w??DEFAULT_IDLE_THRESHOLD_MS,log:E,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ye()})})),await restoreLifecycleFromConflictsJson({hocuspocus:J,projectDir:e.projectDir??e.contentDir,log:E});try{await new Promise((t,S)=>{let w=e=>S(e);fe.once(`error`,w),fe.listen(e.port,e.host,()=>{fe.removeListener(`error`,w),t()})})}catch(e){if(ge)try{releaseUiLock(ne)}catch(e){E.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await Y().catch(()=>{}),e}let we=fe.address(),Te=typeof we==`object`&&we?we.port:e.port??0;if(ue=Te,j(ne,Te),ge&&updateUiLockPort(ne,Te),S&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:ne,log:E})}catch(e){E.warn({err:e},`spawnUiSiblingFn failed`)}let De=!1,je=async(e,t)=>{let S;try{await Promise.race([t(),new Promise((t,w)=>{S=setTimeout(()=>{w(Error(`${e} timed out after ${DESTROY_STEP_TIMEOUT_MS}ms`))},DESTROY_STEP_TIMEOUT_MS),S.unref?.()})])}finally{S!==void 0&&clearTimeout(S)}};return ye=async()=>{if(De)return;De=!0;let e=[],t=async(t,S)=>{try{await je(t,S)}catch(S){e.push(S),E.warn({err:S,step:t},`bootServer destroy step failed`)}};try{Ce?.detach()}catch(t){e.push(t),E.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(await t(`mount.shutdown`,()=>ve.shutdown()),await t(`mcpHttpHandler.close`,()=>de.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ve.wss.close(S=>S?t(S):e())})),await t(`httpServer.closeAllConnections`,async()=>{fe.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{fe.close(S=>S&&S.code!==`ERR_SERVER_NOT_RUNNING`?t(S):e())})),await t(`destroyHocuspocus`,()=>Y()),ge&&await t(`releaseUiLock`,async()=>releaseUiLock(ne)),await t(`shutdownTelemetry`,()=>shutdownTelemetry()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)},{httpServer:fe,destroy:ye,lockDir:ne,contentDir:e.contentDir,port:Te,ready:ee,degraded:te,didAutoInit:F,serverInstance:q}}async function restoreLifecycleFromConflictsJson(e){let{hocuspocus:t,projectDir:S,log:w}=e,E,D;try{E=new ConflictStore(S),D=E.list()}catch(e){w.warn({err:e,projectDir:S},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(D.length===0)return;let O=null;try{let e=resolveGitDir(S),t=e?join(e,`MERGE_HEAD`):null;if(!t||!existsSync(t)){E.clear(),console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:D.length}));return}let w=(await simpleGit({baseDir:S,timeout:{block:5e3}}).raw([`diff`,`--name-only`,`--diff-filter=U`])).trim();O=new Set(w?w.split(`
|
|
3301
|
-
`).map(e=>e.trim()).filter(Boolean):[])}catch(e){w.warn({err:e,projectDir:S},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(O!==null){let e=0;for(let t of D)O.has(t.file)||(E.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:D.length-e})),D=D.filter(e=>O?.has(e.file)),D.length===0)return}for(let e of D){let S=stripDocExtension(e.file),E=null,D=!1;try{E=await t.openDirectConnection(S);let e=E.document;if(!e)continue;let w=e.getMap(`lifecycle`);w.set(`status`,`conflict`),w.set(`reason`,`conflict-markers`),D=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":S}))}catch(e){w.warn({err:e,docName:S},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(E)try{await E.disconnect()}catch(e){w.warn({err:e,docName:S,restored:D},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const ConfigSchema=ConfigSchema$1;function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),S=e.platformName??process.platform,w=e.env??process.env;return S===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):S===`win32`?existsSync(join(w.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const ANCESTOR_WALK_DEPTH_LIMIT=30,GIT_MARKER=`.git`;function findEnclosingGitRoot(e){let t=resolve(e),S=0;for(;S<ANCESTOR_WALK_DEPTH_LIMIT;){let e=!1;try{e=existsSync(resolve(t,GIT_MARKER))}catch{e=!1}if(e)return{gitRoot:t,distance:S};let w=dirname(t);if(w===t)return null;t=w,S+=1}return null}const execFileAsync=promisify(execFile);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,S){super(e,S),this.name=`ProjectGitInitError`,this.stderr=t}};async function isInsideExistingWorkTree(e){try{let{stdout:t}=await execFileAsync(`git`,[`rev-parse`,`--is-inside-work-tree`],{cwd:e});return t.trim()===`true`}catch{return!1}}async function ensureProjectGit(e){let t=resolve(e),S=resolve(t,`.git`),w=resolve(S,`HEAD`),E=!1;if(existsSync(S)){if(!statSync(S).isDirectory()||existsSync(w))return{didInit:!1};console.log(`[project-git] detected partial .git/ — running git init to repair`),E=!0}else if(await isInsideExistingWorkTree(t))return{didInit:!1};let D=``;try{D=(await execFileAsync(`git`,[`init`,`--initial-branch=main`,t])).stderr??``}catch(e){let S=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new ProjectGitInitError(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,S,{cause:e})}if(!existsSync(w))throw new ProjectGitInitError(`git init reported success but ${S}/HEAD is missing (partial init detected)`,D);return E?(console.log(`[project-git] backfilled missing .git/HEAD at ${t}`),{didInit:!0,repaired:!0}):(console.log(`[project-git] initialized .git/ at ${t} (branch: main)`),{didInit:!0})}async function resolvePackageVersion(e,t){let S;try{S=createRequire(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=dirname(S),w=0;w<32;w+=1){let S=join(t,`package.json`);if(existsSync(S))try{let t=JSON.parse(await readFile$1(S,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let w=dirname(t);if(w===t)return;t=w}}export{assertNeverDiskEvent as $,rewriteWikiLinksForDocumentRename as $n,
|
|
3302
|
-
//# sourceMappingURL=dist-
|
|
3301
|
+
`).map(e=>e.trim()).filter(Boolean):[])}catch(e){w.warn({err:e,projectDir:S},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(O!==null){let e=0;for(let t of D)O.has(t.file)||(E.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:D.length-e})),D=D.filter(e=>O?.has(e.file)),D.length===0)return}for(let e of D){let S=stripDocExtension(e.file),E=null,D=!1;try{E=await t.openDirectConnection(S);let e=E.document;if(!e)continue;let w=e.getMap(`lifecycle`);w.set(`status`,`conflict`),w.set(`reason`,`conflict-markers`),D=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":S}))}catch(e){w.warn({err:e,docName:S},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(E)try{await E.disconnect()}catch(e){w.warn({err:e,docName:S,restored:D},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const ConfigSchema=ConfigSchema$1;function detectClaudeDesktopPresence(e={}){let t=e.home??homedir(),S=e.platformName??process.platform,w=e.env??process.env;return S===`darwin`?existsSync(join(t,`Library`,`Application Support`,`Claude`)):S===`win32`?existsSync(join(w.APPDATA??join(t,`AppData`,`Roaming`),`Claude`)):!1}const ANCESTOR_WALK_DEPTH_LIMIT=30,GIT_MARKER=`.git`;function findEnclosingGitRoot(e){let t=resolve(e),S=0;for(;S<ANCESTOR_WALK_DEPTH_LIMIT;){let e=!1;try{e=existsSync(resolve(t,GIT_MARKER))}catch{e=!1}if(e)return{gitRoot:t,distance:S};let w=dirname(t);if(w===t)return null;t=w,S+=1}return null}const execFileAsync=promisify(execFile);var ProjectGitInitError=class extends Error{stderr;constructor(e,t=``,S){super(e,S),this.name=`ProjectGitInitError`,this.stderr=t}};async function isInsideExistingWorkTree(e){try{let{stdout:t}=await execFileAsync(`git`,[`rev-parse`,`--is-inside-work-tree`],{cwd:e});return t.trim()===`true`}catch{return!1}}async function ensureProjectGit(e){let t=resolve(e),S=resolve(t,`.git`),w=resolve(S,`HEAD`),E=!1;if(existsSync(S)){if(!statSync(S).isDirectory()||existsSync(w))return{didInit:!1};console.log(`[project-git] detected partial .git/ — running git init to repair`),E=!0}else if(await isInsideExistingWorkTree(t))return{didInit:!1};let D=``;try{D=(await execFileAsync(`git`,[`init`,`--initial-branch=main`,t])).stderr??``}catch(e){let S=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new ProjectGitInitError(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,S,{cause:e})}if(!existsSync(w))throw new ProjectGitInitError(`git init reported success but ${S}/HEAD is missing (partial init detected)`,D);return E?(console.log(`[project-git] backfilled missing .git/HEAD at ${t}`),{didInit:!0,repaired:!0}):(console.log(`[project-git] initialized .git/ at ${t} (branch: main)`),{didInit:!0})}async function resolvePackageVersion(e,t){let S;try{S=createRequire(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=dirname(S),w=0;w<32;w+=1){let S=join(t,`package.json`);if(existsSync(S))try{let t=JSON.parse(await readFile$1(S,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let w=dirname(t);if(w===t)return;t=w}}export{assertNeverDiskEvent as $,rewriteWikiLinksForDocumentRename as $n,GitDirAccessError as $r,initShadowRepo as $t,MissingOkConfigError as A,looseObject as Ai,readSkillInstallStateSnapshot as An,tracedWriteFile as Ar,createTestLogger as At,STARTER_PACK_IDS as B,releaseUiLock as Bn,writeTargetVersion as Br,formatContributors as Bt,LOG_MD_TEMPLATE as C,OK_PROJECT_MARKER as Ci,parseHocuspocusAuthToken as Cn,tracedMkdir as Cr,createLiveDerivedIndexExtension as Ct,MCP_SERVER_NAME as D,array as Di,readAllTargets as Dn,tracedRmSync as Dr,createServer$1 as Dt,MCP_CONNECTION_ID_HEADER as E,any$1 as Ei,planSeed as En,tracedRenameSync as Er,createPersistenceExtension as Et,SERVICE_WRITER as F,_coercedNumber as Fi,reconcile as Fn,validateCloneInputs as Fr,evictStaleTrackerEntries as Ft,StateManifestError as G,resolveCursorBinaryDefault as Gn,isInitializedNotification as Gr,getLogger as Gt,STATE_MANIFEST_FILENAME as H,resetMetrics as Hn,McpServer as Hr,gcCheckpointRefs as Ht,SKILL_INSTALL_EVENTS_FILE_REL as I,NEVER as Ii,recordContributor as In,validateSkillZip as Ir,extractWikiLinksFromMarkdown as It,acquireUiLock as J,resolvePack as Jn,atomicWriteFileSync as Jr,getTracer as Jt,TagIndex as K,resolveCursorSpawnInvocation as Kn,isJSONRPCRequest as Kr,getMeter as Kt,STARTER_FOLDERS as L,require_dist$2 as Li,recordSkillInstallEvent as Ln,withSpan as Lr,findEnclosingGitRoot as Lt,PinoLogger as M,object$1 as Mi,readTargetRecordedAt as Mn,updateLastKnownHash as Mr,detectProjectShape as Mt,ProjectGitInitError as N,string$2 as Ni,readTargetVersion as Nn,updateUiLockPort as Nr,ensureProjectGit as Nt,MISSING_OK_CONFIG_MESSAGE as O,boolean$1 as Oi,readBranchFromHead as On,tracedRmdirSync as Or,createServerObserverExtension as Ot,ROLLBACK_ORIGIN as P,url as Pi,readUiLock as Pn,validateAgentId as Pr,errorResponse as Pt,assertCompatibleStateManifest as Q,rewriteMarkdownLinksForDocumentRename as Qn,writeConfigPatch as Qr,incrementServerObserverFire as Qt,STARTER_FOLDER_FRONTMATTER_FILENAME as R,registerAllTools as Rn,withSpanSync as Rr,findEnclosingProjectRoot as Rt,LIVE_DERIVED_INDEX_DEBOUNCE_MS as S,LOCAL_DIR as Si,parseAuthRejectionWire as Sn,tracedLinkSync as Sr,createExternalChangeHandler as St,MAX_AGENT_SESSIONS as T,ZodNumber$1 as Ti,pathToDocName as Tn,tracedRename as Tr,createOsProbe as Tt,SeedPrerequisiteError as U,resolveBundledSkillDir as Un,JSONRPCMessageSchema as Ur,getCurrentMcpLogger as Ut,STARTER_TEMPLATES as V,removeLastKnownHash as Vn,writeTracker as Vr,formatContributorsFrom as Vt,SeedRootDirError as W,resolveContentDir as Wn,LATEST_PROTOCOL_VERSION as Wr,getLocalDir as Wt,applyExternalChange as X,restoreContributors as Xn,resolveConfigPath as Xr,handleSpawnCursor as Xt,applyAgentMarkdownWrite as Y,resolvePackageVersion as Yn,readConfigSafely as Yr,handleCollabSocketError as Yt,applySeed as Z,restoreLifecycleFromConflictsJson as Zn,withFileLockSync as Zr,incrementCollabSocketFilteredError as Zt,GIT_UPSTREAM_WRITER as _,humanFormat as _i,listStarterPacks as _n,startWatcher as _r,contributorCount as _t,AgentPresenceBroadcaster as a,DEFAULT_SERVER_HOST as ai,isAllowedWorkspaceHostHeader as an,safeContentPath as ar,buildSkillZip as at,HocuspocusAuthTokenSchema as b,isOrphanMode as bi,mountMcpAndApi as bn,toBroadcasterKey as br,createContentFilter as bt,BacklinkIndex as c,EXECUTABLE_BLOCKLIST_EXTENSIONS as ci,isKnownPackId as cn,sanitizeClientName as cr,classifyEvents as ct,CURSOR_BUNDLE_PATHS_BY_PLATFORM as d,ProblemDetailsSchema as di,isPathWithinDir as dn,seedBasenameIndex as dr,coercePackId as dt,MalformedGitPointerError as ei,initTelemetry as en,runAuthReposSubprocess as er,attachIdleShutdown as et,ConfigSchema as f,SKILL_STATE_TARGETS as fi,isProjectRoot as fn,setActiveSpanAttributes as fr,commitUpstreamImport as ft,FILE_WATCHER_ORIGIN as g,defaultScheduler as gi,listRescueCheckpoints as gn,splitMarkdownBlocks as gr,contentHash as gt,FILE_SYSTEM_WRITER as h,colorFromSeed as hi,lastKnownHash as hn,spawnDetached as hr,containsConflictMarkers as ht,AgentFocusBroadcaster as i,DEFAULT_GITHUB_OAUTH_CLIENT_ID as ii,isAllowedApiOrigin as in,runWithMcpLogger as ir,buildInstructions as it,OBSERVER_SYNC_ORIGIN as j,number$1 as ji,readStateManifest as jn,tracedWriteFileSync as jr,detectClaudeDesktopPresence as jt,McpLogger as k,literal as ki,readServerPackageVersion as kn,tracedUnlinkSync as kr,createStreamingErrorWriter as kt,CC1Broadcaster as l,INLINE_RENDERABLE_EXTENSIONS as li,isLoopbackAddress as ln,saveInMemoryCheckpoint as lr,classifyFsPath as lt,DEFAULT_PACK_ID as m,SYSTEM_DOC_NAME as mi,isSystemDoc as mn,shutdownTelemetry as mr,commitWipFromTree as mt,AGENT_ID_RE as n,ASSET_EXTENSIONS as ni,installTestLoggers as nn,runCloneSubprocess as nr,buildAndOpenSkill as nt,AgentSessionCapacityError as o,DEFAULT_SIGTERM_GRACE_MS as oi,isConfigDoc as on,safeSubdir as or,buildStarterFolderFrontmatterYaml as ot,DEFAULT_CHECKPOINT_RETENTION as p,SPAWN_ERROR_LOG as pi,isSelfWrite as pn,shadowGit as pr,commitWip as pt,UiLockCollisionError as q,resolveLockDir as qn,isJSONRPCResultResponse as qr,getMetrics as qt,AGENT_WRITE_ORIGIN as r,CC1_CONTRACT_VERSION as ri,installUserSkill as rn,runDeviceFlowSubprocess as rr,buildExecResult as rt,AgentSessionManager as s,EDITOR_LABELS as si,isHocuspocusAuthRejectionReason as sn,safetyCheckpoint as sr,buildWipTree as st,AGENT_ID_MAX_LEN as t,ALL_EDITOR_IDS as ti,installPrettyZodErrors as tn,runAuthStatusSubprocess as tr,bootServer as tt,CONFLICT_MARKER_RE as u,ORPHAN_MODES as ui,isPairedWriteOrigin as un,saveVersion as ur,clearContributors as ut,HOCUSPOCUS_AUTH_REJECTION_REASONS as v,iconFromClientName as vi,loadPrincipal as vn,streamingProblemEvent as vr,createApiExtension as vt,MANAGED_RENAME_ORIGIN as w,locateIssue as wi,parseKeepaliveConnectionId as wn,tracedMkdirSync as wr,createMcpHttpHandler as wt,INSTALLED_AGENTS_SCHEMES as x,CONFIG_SCHEMA_MAJOR_PATH as xi,normalizeFsPath as xn,tracedAppendFileSync as xr,createContentFilterAsync as xt,HocuspocusAuthRejection as y,isBranchNotFoundGitError as yi,loggerFactory as yn,swapContributors as yr,createAssetServeMiddleware as yt,STARTER_PACKS as z,registerWrite as zn,writeStateManifest as zr,formatAuthRejectionWire as zt};
|
|
3302
|
+
//# sourceMappingURL=dist-DdtB66Zm.mjs.map
|