@0xmonaco/mcp-server 1.0.62 → 1.0.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/bin.js +6 -6
  2. package/package.json +3 -3
package/dist/bin.js CHANGED
@@ -64,7 +64,7 @@ ${W3(m)}`;super(e.shortMessage,{cause:e,docsPath:r,metaMessages:[...e.metaMessag
64
64
  `),{cause:e,metaMessages:["This error could arise when the account does not have enough funds to:"," - pay for the total gas fee,"," - pay for the value to send."," ","The cost of the transaction is calculated as `gas * gas fee + value`, where:"," - `gas` is the amount of gas needed for transaction to execute,"," - `gas fee` is the gas fee,"," - `value` is the amount of ether to send to the recipient."],name:"InsufficientFundsError"})}};Object.defineProperty(dm,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});lm=class lm extends C{constructor({cause:e,gas:t}={}){super(`The amount of gas ${t?`(${t}) `:""}provided for the transaction exceeds the limit allowed for the block.`,{cause:e,name:"IntrinsicGasTooHighError"})}};Object.defineProperty(lm,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});pm=class pm extends C{constructor({cause:e,gas:t}={}){super(`The amount of gas ${t?`(${t}) `:""}provided for the transaction is too low.`,{cause:e,name:"IntrinsicGasTooLowError"})}};Object.defineProperty(pm,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});fm=class fm extends C{constructor({cause:e}){super("The transaction type is not supported for this chain.",{cause:e,name:"TransactionTypeNotSupportedError"})}};Object.defineProperty(fm,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});ds=class ds extends C{constructor({cause:e,maxPriorityFeePerGas:t,maxFeePerGas:r}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${t?` = ${mr(t)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${r?` = ${mr(r)} gwei`:""}).`].join(`
65
65
  `),{cause:e,name:"TipAboveFeeCapError"})}};Object.defineProperty(ds,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});Co=class Co extends C{constructor({cause:e}){super(`An error occurred while executing: ${e?.shortMessage}`,{cause:e,name:"UnknownNodeError"})}}});function ha(e,t){let r=(e.details||"").toLowerCase(),n=e instanceof C?e.walk((o)=>o?.code===ai.code):e;if(n instanceof C)return new ai({cause:e,message:n.details});if(ai.nodeMessage.test(r))return new ai({cause:e,message:e.details});if(Oo.nodeMessage.test(r))return new Oo({cause:e,maxFeePerGas:t?.maxFeePerGas});if(sm.nodeMessage.test(r))return new sm({cause:e,maxFeePerGas:t?.maxFeePerGas});if(am.nodeMessage.test(r))return new am({cause:e,nonce:t?.nonce});if(cm.nodeMessage.test(r))return new cm({cause:e,nonce:t?.nonce});if(um.nodeMessage.test(r))return new um({cause:e,nonce:t?.nonce});if(dm.nodeMessage.test(r))return new dm({cause:e});if(lm.nodeMessage.test(r))return new lm({cause:e,gas:t?.gas});if(pm.nodeMessage.test(r))return new pm({cause:e,gas:t?.gas});if(fm.nodeMessage.test(r))return new fm({cause:e});if(ds.nodeMessage.test(r))return new ds({cause:e,maxFeePerGas:t?.maxFeePerGas,maxPriorityFeePerGas:t?.maxPriorityFeePerGas});return new Co({cause:e})}var mm=V(()=>{Ge();ls()});function jy(e,{docsPath:t,...r}){let n=(()=>{let o=ha(e,r);if(o instanceof Co)return e;return o})();return new Oc(n,{docsPath:t,...r})}var QE=V(()=>{os();ls();mm()});function ro(e,{format:t}){if(!t)return{};let r={};function n(i){let s=Object.keys(i);for(let a of s){if(a in e)r[a]=e[a];if(i[a]&&typeof i[a]==="object"&&!Array.isArray(i[a]))n(i[a])}}let o=t(e||{});return n(o),r}function jr(e,t){let r={};if(typeof e.authorizationList<"u")r.authorizationList=sce(e.authorizationList);if(typeof e.accessList<"u")r.accessList=e.accessList;if(typeof e.blobVersionedHashes<"u")r.blobVersionedHashes=e.blobVersionedHashes;if(typeof e.blobs<"u")if(typeof e.blobs[0]!=="string")r.blobs=e.blobs.map((n)=>mt(n));else r.blobs=e.blobs;if(typeof e.data<"u")r.data=e.data;if(e.account)r.from=e.account.address;if(typeof e.from<"u")r.from=e.from;if(typeof e.gas<"u")r.gas=G(e.gas);if(typeof e.gasPrice<"u")r.gasPrice=G(e.gasPrice);if(typeof e.maxFeePerBlobGas<"u")r.maxFeePerBlobGas=G(e.maxFeePerBlobGas);if(typeof e.maxFeePerGas<"u")r.maxFeePerGas=G(e.maxFeePerGas);if(typeof e.maxPriorityFeePerGas<"u")r.maxPriorityFeePerGas=G(e.maxPriorityFeePerGas);if(typeof e.nonce<"u")r.nonce=G(e.nonce);if(typeof e.to<"u")r.to=e.to;if(typeof e.type<"u")r.type=ice[e.type];if(typeof e.value<"u")r.value=G(e.value);return r}function sce(e){return e.map((t)=>({address:t.address,r:t.r?G(BigInt(t.r)):t.r,s:t.s?G(BigInt(t.s)):t.s,chainId:G(t.chainId),nonce:G(t.nonce),...typeof t.yParity<"u"?{yParity:G(t.yParity)}:{},...typeof t.v<"u"&&typeof t.yParity>"u"?{v:G(t.v)}:{}}))}var ice;var ps=V(()=>{Fe();ice={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"}});function Vd(){let e=()=>{return},t=()=>{return};return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}function Zd({fn:e,id:t,shouldSplitBatch:r,wait:n=0,sort:o}){let i=async()=>{let l=c();s();let p=l.map(({args:m})=>m);if(p.length===0)return;e(p).then((m)=>{if(o&&Array.isArray(m))m.sort(o);for(let h=0;h<l.length;h++){let{resolve:b}=l[h];b?.([m[h],m])}}).catch((m)=>{for(let h=0;h<l.length;h++){let{reject:b}=l[h];b?.(m)}})},s=()=>XE.delete(t),a=()=>c().map(({args:l})=>l),c=()=>XE.get(t)||[],d=(l)=>XE.set(t,[...c(),l]);return{flush:s,async schedule(l){let{promise:p,resolve:m,reject:h}=Vd();if(r?.([...a(),l]))i();if(c().length>0)return d({args:l,resolve:m,reject:h}),p;return d({args:l,resolve:m,reject:h}),setTimeout(i,n),p}}}var XE;var qy=V(()=>{XE=new Map});function kL(e){if(!e||e.length===0)return;return e.reduce((t,{slot:r,value:n})=>{if(r.length!==66)throw new ty({size:r.length,targetSize:66,type:"hex"});if(n.length!==66)throw new ty({size:n.length,targetSize:66,type:"hex"});return t[r]=n,t},{})}function ace(e){let{balance:t,nonce:r,state:n,stateDiff:o,code:i}=e,s={};if(i!==void 0)s.code=i;if(t!==void 0)s.balance=G(t);if(r!==void 0)s.nonce=G(r);if(n!==void 0)s.state=kL(n);if(o!==void 0){if(s.state)throw new SE;s.stateDiff=kL(o)}return s}function Wd(e){if(!e)return;let t={};for(let{address:r,...n}of e){if(!ht(r,{strict:!1}))throw new Ft({address:r});if(t[r])throw new wE({address:r});t[r]=ace(n)}return t}var Hy=V(()=>{ei();ry();vE();Mn();Fe()});var cIe,uIe,dIe,lIe,pIe,fIe,mIe,hIe,gIe,yIe,bIe,xIe,_Ie,wIe,SIe,vIe,TIe,EIe,PIe,AIe,IIe,kIe,RIe,OIe,CIe,MIe,$Ie,NIe,zIe,BIe,LIe,DIe,UIe,FIe,jIe,qIe,HIe,GIe,VIe,ZIe,WIe,KIe,YIe,JIe,QIe,XIe,eke,tke,rke,nke,oke,ike,ske,ake,cke,uke,dke,lke,pke,fke,mke,hke,gke,yke,bke,xke,_ke,wke,Ske,vke,Tke,Eke,Pke,Ake,Ike,kke,Rke,Oke,Cke,Mke,$ke,Nke,zke,Bke,Lke,Dke,Uke,Fke,jke,qke,Hke,Gke,Vke,Zke,Wke,Kd;var eP=V(()=>{cIe=2n**(8n-1n)-1n,uIe=2n**(16n-1n)-1n,dIe=2n**(24n-1n)-1n,lIe=2n**(32n-1n)-1n,pIe=2n**(40n-1n)-1n,fIe=2n**(48n-1n)-1n,mIe=2n**(56n-1n)-1n,hIe=2n**(64n-1n)-1n,gIe=2n**(72n-1n)-1n,yIe=2n**(80n-1n)-1n,bIe=2n**(88n-1n)-1n,xIe=2n**(96n-1n)-1n,_Ie=2n**(104n-1n)-1n,wIe=2n**(112n-1n)-1n,SIe=2n**(120n-1n)-1n,vIe=2n**(128n-1n)-1n,TIe=2n**(136n-1n)-1n,EIe=2n**(144n-1n)-1n,PIe=2n**(152n-1n)-1n,AIe=2n**(160n-1n)-1n,IIe=2n**(168n-1n)-1n,kIe=2n**(176n-1n)-1n,RIe=2n**(184n-1n)-1n,OIe=2n**(192n-1n)-1n,CIe=2n**(200n-1n)-1n,MIe=2n**(208n-1n)-1n,$Ie=2n**(216n-1n)-1n,NIe=2n**(224n-1n)-1n,zIe=2n**(232n-1n)-1n,BIe=2n**(240n-1n)-1n,LIe=2n**(248n-1n)-1n,DIe=2n**(256n-1n)-1n,UIe=-(2n**(8n-1n)),FIe=-(2n**(16n-1n)),jIe=-(2n**(24n-1n)),qIe=-(2n**(32n-1n)),HIe=-(2n**(40n-1n)),GIe=-(2n**(48n-1n)),VIe=-(2n**(56n-1n)),ZIe=-(2n**(64n-1n)),WIe=-(2n**(72n-1n)),KIe=-(2n**(80n-1n)),YIe=-(2n**(88n-1n)),JIe=-(2n**(96n-1n)),QIe=-(2n**(104n-1n)),XIe=-(2n**(112n-1n)),eke=-(2n**(120n-1n)),tke=-(2n**(128n-1n)),rke=-(2n**(136n-1n)),nke=-(2n**(144n-1n)),oke=-(2n**(152n-1n)),ike=-(2n**(160n-1n)),ske=-(2n**(168n-1n)),ake=-(2n**(176n-1n)),cke=-(2n**(184n-1n)),uke=-(2n**(192n-1n)),dke=-(2n**(200n-1n)),lke=-(2n**(208n-1n)),pke=-(2n**(216n-1n)),fke=-(2n**(224n-1n)),mke=-(2n**(232n-1n)),hke=-(2n**(240n-1n)),gke=-(2n**(248n-1n)),yke=-(2n**(256n-1n)),bke=2n**8n-1n,xke=2n**16n-1n,_ke=2n**24n-1n,wke=2n**32n-1n,Ske=2n**40n-1n,vke=2n**48n-1n,Tke=2n**56n-1n,Eke=2n**64n-1n,Pke=2n**72n-1n,Ake=2n**80n-1n,Ike=2n**88n-1n,kke=2n**96n-1n,Rke=2n**104n-1n,Oke=2n**112n-1n,Cke=2n**120n-1n,Mke=2n**128n-1n,$ke=2n**136n-1n,Nke=2n**144n-1n,zke=2n**152n-1n,Bke=2n**160n-1n,Lke=2n**168n-1n,Dke=2n**176n-1n,Uke=2n**184n-1n,Fke=2n**192n-1n,jke=2n**200n-1n,qke=2n**208n-1n,Hke=2n**216n-1n,Gke=2n**224n-1n,Vke=2n**232n-1n,Zke=2n**240n-1n,Wke=2n**248n-1n,Kd=2n**256n-1n});function Sr(e){let{account:t,maxFeePerGas:r,maxPriorityFeePerGas:n,to:o}=e,i=t?ze(t):void 0;if(i&&!ht(i.address))throw new Ft({address:i.address});if(o&&!ht(o))throw new Ft({address:o});if(r&&r>Kd)throw new Oo({maxFeePerGas:r});if(n&&r&&n>r)throw new ds({maxFeePerGas:r,maxPriorityFeePerGas:n})}var ci=V(()=>{eP();ei();ls();Mn()});var tP,rP,nP;var RL=V(()=>{Ge();tP=class tP extends C{constructor({callbackSelector:e,cause:t,data:r,extraData:n,sender:o,urls:i}){super(t.shortMessage||"An error occurred while fetching for an offchain result.",{cause:t,metaMessages:[...t.metaMessages||[],t.metaMessages?.length?"":[],"Offchain Gateway Call:",i&&[" Gateway URL(s):",...i.map((s)=>` ${Rc(s)}`)],` Sender: ${o}`,` Data: ${r}`,` Callback selector: ${e}`,` Extra data: ${n}`].flat(),name:"OffchainLookupError"})}};rP=class rP extends C{constructor({result:e,url:t}){super("Offchain gateway response is malformed. Response data must be a hex value.",{metaMessages:[`Gateway URL: ${Rc(t)}`,`Response: ${Je(e)}`],name:"OffchainLookupResponseMalformedError"})}};nP=class nP extends C{constructor({sender:e,to:t}){super("Reverted sender address does not match target contract address (`to`).",{metaMessages:[`Contract address: ${t}`,`OffchainLookup sender address: ${e}`],name:"OffchainLookupSenderMismatchError"})}}});async function CL(e,{blockNumber:t,blockTag:r,data:n,requestOptions:o,to:i}){let{args:s}=Py({data:n,abi:[cce]}),[a,c,d,l,p]=s,{ccipRead:m}=e,h=m&&typeof m?.request==="function"?m.request:uce;try{if(!wr(i,a))throw new nP({sender:a,to:i});let b=c.includes(is)?await $E({data:d,ccipRequest:(_)=>h({..._,requestOptions:o})}):await h({data:d,requestOptions:o,sender:a,urls:c}),{data:x}=await Sn(e,{blockNumber:t,blockTag:r,data:fr([l,nn([{type:"bytes"},{type:"bytes"}],[b,p])]),requestOptions:o,to:i});return x}catch(b){if(o?.signal?.aborted)throw Nr(o.signal);if(_n(b))throw b;throw new tP({callbackSelector:l,cause:b,data:n,extraData:p,sender:a,urls:c})}}async function uce({data:e,requestOptions:t,sender:r,urls:n}){let o=Error("An unknown error occurred.");for(let i=0;i<n.length;i++){if(t?.signal?.aborted)throw Nr(t.signal);let s=n[i],a=s.includes("{data}")?"GET":"POST",c=a==="POST"?{data:e,sender:r}:void 0,d=a==="POST"?{"Content-Type":"application/json"}:{};try{let l=await fetch(s.replace("{sender}",r.toLowerCase()).replace("{data}",e),{body:JSON.stringify(c),headers:d,method:a,...t?.signal?{signal:t.signal}:{}}),p;if(l.headers.get("Content-Type")?.startsWith("application/json"))p=(await l.json()).data;else p=await l.text();if(!l.ok){o=new ko({body:c,details:p?.error?Je(p.error):l.statusText,headers:l.headers,status:l.status,url:s});continue}if(!Kt(p)){o=new rP({result:p,url:s});continue}return p}catch(l){if(t?.signal?.aborted)throw Nr(t.signal);if(_n(l))throw l;o=new ko({body:c,details:l.message,url:s})}}throw o}var OL="0x556f1830",cce;var ML=V(()=>{ga();RL();Mc();bE();Qi();us();nm();cce={name:"OffchainLookup",type:"error",inputs:[{name:"sender",type:"address"},{name:"urls",type:"string[]"},{name:"callData",type:"bytes"},{name:"callbackFunction",type:"bytes4"},{name:"extraData",type:"bytes"}]}});async function Sn(e,t){let{account:r=e.account,authorizationList:n,batch:o=Boolean(e.batch?.multicall),blockHash:i,blockNumber:s,blockTag:a=e.experimental_blockTag??"latest",requireCanonical:c,accessList:d,blobs:l,blockOverrides:p,code:m,data:h,factory:b,factoryData:x,gas:_,gasPrice:w,maxFeePerBlobGas:A,maxFeePerGas:v,maxPriorityFeePerGas:T,nonce:P,requestOptions:k,to:O,value:N,stateOverride:j,...R}=t,K=r?ze(r):void 0;if(m&&(b||x))throw new C("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(m&&O)throw new C("Cannot provide both `code` & `to` as parameters.");let Z=m&&h,re=b&&x&&O&&h,pe=Z||re,U=(()=>{if(Z)return zL({code:m,data:h});if(re)return hce({data:h,factory:b,factoryData:x,to:O});return h})();try{Sr(t);let ee=Bn({blockHash:i,blockNumber:s,blockTag:a,requireCanonical:c}),me=p?Dy(p):void 0,z=Wd(j),F=e.chain?.formatters?.transactionRequest?.format,we=(F||jr)({...ro(R,{format:F}),accessList:d,account:K,authorizationList:n,blobs:l,data:U,gas:_,gasPrice:w,maxFeePerBlobGas:A,maxFeePerGas:v,maxPriorityFeePerGas:T,nonce:P,to:pe?void 0:O,value:N},"call");if(o&&dce({request:we})&&!me&&i===void 0)try{let{deployless:Ee=!1}=typeof e.batch?.multicall==="object"?e.batch.multicall:{},Ae=NL(e,{blockNumber:s,deployless:Ee});if(!Ae||!mce(z,Ae))return await fce(e,{...we,blockHash:i,blockNumber:s,blockTag:a,multicallAddress:Ae,requestOptions:k,requireCanonical:c,rpcStateOverride:z})}catch(Ee){if(!(Ee instanceof vy)&&!(Ee instanceof fd))throw Ee}let te=(()=>{let Ee=[we,ee];if(z&&me)return[...Ee,z,me];if(z)return[...Ee,z];if(me)return[...Ee,{},me];return Ee})(),$e=await e.request({method:"eth_call",params:te},k);if($e==="0x")return{data:void 0};return{data:$e}}catch(ee){if(k?.signal?.aborted)throw Nr(k.signal);if(_n(ee))throw ee;let me=gce(ee);await Promise.resolve().then(() => ML());if(e.ccipRead!==!1&&me?.slice(0,10)===OL&&O)return{data:await CL(e,{data:me,requestOptions:k,to:O})};if(pe&&me?.slice(0,10)==="0x101bb98d")throw new RE({factory:b});throw jy(ee,{...t,account:K,chain:e.chain})}}function dce({request:e}){let{data:t,to:r,...n}=e;if(!t)return!1;if(t.startsWith(PL))return!1;if(!r)return!1;if(Object.values(n).filter((o)=>typeof o<"u").length>0)return!1;return!0}function pce(e){if(!e)return"default";let t=$L.get(e);if(t!==void 0)return t;let r=lce++;return $L.set(e,r),r}async function fce(e,t){let{batchSize:r=1024,deployless:n=!1,wait:o=0}=typeof e.batch?.multicall==="object"?e.batch.multicall:{},{blockHash:i,blockNumber:s,blockTag:a=e.experimental_blockTag??"latest",requireCanonical:c,data:d,multicallAddress:l,requestOptions:p,rpcStateOverride:m,to:h}=t,b=l!==void 0?l:NL(e,{blockNumber:s,deployless:n}),x=Bn({blockHash:i,blockNumber:s,blockTag:a,requireCanonical:c}),_=typeof x==="string"?x:JSON.stringify(x),w=m?`.${JSON.stringify(m)}`:"",{schedule:A}=Zd({id:`${e.uid}.${_}.${pce(p)}${w}`,wait:o,shouldSplitBatch(P){return P.reduce((O,{data:N})=>O+(N.length-2),0)>r*2},fn:async(P)=>{let k=P.map((R)=>({allowFailure:!0,callData:R.data,target:R.to})),O=It({abi:Kn,args:[k],functionName:"aggregate3"}),N={...b===null?{data:zL({code:zc,data:O})}:{to:b,data:O}},j=await e.request({method:"eth_call",params:m?[N,x,m]:[N,x]},p);return Dr({abi:Kn,args:[k],functionName:"aggregate3",data:j||"0x"})}}),[{returnData:v,success:T}]=await A({data:d,to:h});if(!T)throw new ns({data:v});if(v==="0x")return{data:void 0};return{data:v}}function NL(e,t){let{blockNumber:r,deployless:n}=t;if(n)return null;if(e.chain)return Qn({blockNumber:r,chain:e.chain,contract:"multicall3"});throw new vy}function mce(e,t){if(!e)return!1;return Object.keys(e).some((r)=>wr(r,t))}function zL(e){let{code:t,data:r}=e;return Bc({abi:xy(["constructor(bytes, bytes)"]),bytecode:Uy,args:[t,r]})}function hce(e){let{data:t,factory:r,factoryData:n,to:o}=e;return Bc({abi:xy(["constructor(address, bytes, address, bytes)"]),bytecode:AL,args:[o,t,r,n]})}function gce(e){if(!(e instanceof C))return;let t=e.walk();return typeof t?.data==="object"?t.data?.data:t.data}var lce=0,$L;var ga=V(()=>{Yf();YE();Mr();Ge();Qf();os();rs();Fy();xn();us();Lc();Ac();QE();ps();qy();Hy();ci();$L=new WeakMap});var uP,dP=(e,t,r)=>new uP(e,t).update(r).digest();var YL=V(()=>{hc();uP=class uP extends vf{constructor(e,t){super();this.finished=!1,this.destroyed=!1,t8(e);let r=Sf(t);if(this.iHash=e.create(),typeof this.iHash.update!=="function")throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?e.create().update(r).digest():r);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=e.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),Ui(o)}update(e){return Yu(this),this.iHash.update(e),this}digestInto(e){Yu(this),mc(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:r,finished:n,destroyed:o,blockLen:i,outputLen:s}=this;return e=e,e.finished=n,e.destroyed=o,e.blockLen=i,e.outputLen=s,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};dP.create=(e,t)=>new uP(e,t)});function JL(e){if(e.lowS!==void 0)Yo("lowS",e.lowS);if(e.prehash!==void 0)Yo("prehash",e.prehash)}function Tce(e){let t=kf(e);Hi(t,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:r,Fp:n,a:o}=t;if(r){if(!n.eql(o,n.ZERO))throw Error("invalid endo: CURVE.a must be 0");if(typeof r!=="object"||typeof r.beta!=="bigint"||typeof r.splitScalar!=="function")throw Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...t})}function lP(e,t){return ra(xc(e,t))}function Pce(e){let t=Tce(e),{Fp:r}=t,n=Gi(t.n,t.nBitLength),o=t.toBytes||((v,T,P)=>{let k=T.toAffine();return na(Uint8Array.from([4]),r.toBytes(k.x),r.toBytes(k.y))}),i=t.fromBytes||((v)=>{let T=v.subarray(1),P=r.fromBytes(T.subarray(0,r.BYTES)),k=r.fromBytes(T.subarray(r.BYTES,2*r.BYTES));return{x:P,y:k}});function s(v){let{a:T,b:P}=t,k=r.sqr(v),O=r.mul(k,v);return r.add(r.add(O,r.mul(v,T)),P)}function a(v,T){let P=r.sqr(T),k=s(v);return r.eql(P,k)}if(!a(t.Gx,t.Gy))throw Error("bad curve params: generator point");let c=r.mul(r.pow(t.a,pP),Ece),d=r.mul(r.sqr(t.b),BigInt(27));if(r.is0(r.add(c,d)))throw Error("bad curve params: a or b");function l(v){return C0(v,vr,t.n)}function p(v){let{allowedPrivateKeyLengths:T,nByteLength:P,wrapPrivateKey:k,n:O}=t;if(T&&typeof v!=="bigint"){if(Ju(v))v=ra(v);if(typeof v!=="string"||!T.includes(v.length))throw Error("invalid private key");v=v.padStart(P*2,"0")}let N;try{N=typeof v==="bigint"?v:qi(Gt("private key",v,P))}catch(j){throw Error("invalid private key, expected hex or "+P+" bytes, got "+typeof v)}if(k)N=Pt(N,O);return On("private key",N,vr,O),N}function m(v){if(!(v instanceof x))throw Error("ProjectivePoint expected")}let h=Xu((v,T)=>{let{px:P,py:k,pz:O}=v;if(r.eql(O,r.ONE))return{x:P,y:k};let N=v.is0();if(T==null)T=N?r.ONE:r.inv(O);let j=r.mul(P,T),R=r.mul(k,T),K=r.mul(O,T);if(N)return{x:r.ZERO,y:r.ZERO};if(!r.eql(K,r.ONE))throw Error("invZ was invalid");return{x:j,y:R}}),b=Xu((v)=>{if(v.is0()){if(t.allowInfinityPoint&&!r.is0(v.py))return;throw Error("bad point: ZERO")}let{x:T,y:P}=v.toAffine();if(!r.isValid(T)||!r.isValid(P))throw Error("bad point: x or y not FE");if(!a(T,P))throw Error("bad point: equation left != right");if(!v.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0});class x{constructor(v,T,P){if(v==null||!r.isValid(v))throw Error("x required");if(T==null||!r.isValid(T)||r.is0(T))throw Error("y required");if(P==null||!r.isValid(P))throw Error("z required");this.px=v,this.py=T,this.pz=P,Object.freeze(this)}static fromAffine(v){let{x:T,y:P}=v||{};if(!v||!r.isValid(T)||!r.isValid(P))throw Error("invalid affine point");if(v instanceof x)throw Error("projective point not allowed");let k=(O)=>r.eql(O,r.ZERO);if(k(T)&&k(P))return x.ZERO;return new x(T,P,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(v){let T=ed(r,v.map((P)=>P.pz));return v.map((P,k)=>P.toAffine(T[k])).map(x.fromAffine)}static fromHex(v){let T=x.fromAffine(i(Gt("pointHex",v)));return T.assertValidity(),T}static fromPrivateKey(v){return x.BASE.multiply(p(v))}static msm(v,T){return N0(x,n,v,T)}_setWindowSize(v){A.setWindowSize(this,v)}assertValidity(){b(this)}hasEvenY(){let{y:v}=this.toAffine();if(r.isOdd)return!r.isOdd(v);throw Error("Field doesn't support isOdd")}equals(v){m(v);let{px:T,py:P,pz:k}=this,{px:O,py:N,pz:j}=v,R=r.eql(r.mul(T,j),r.mul(O,k)),K=r.eql(r.mul(P,j),r.mul(N,k));return R&&K}negate(){return new x(this.px,r.neg(this.py),this.pz)}double(){let{a:v,b:T}=t,P=r.mul(T,pP),{px:k,py:O,pz:N}=this,{ZERO:j,ZERO:R,ZERO:K}=r,Z=r.mul(k,k),re=r.mul(O,O),pe=r.mul(N,N),U=r.mul(k,O);return U=r.add(U,U),K=r.mul(k,N),K=r.add(K,K),j=r.mul(v,K),R=r.mul(P,pe),R=r.add(j,R),j=r.sub(re,R),R=r.add(re,R),R=r.mul(j,R),j=r.mul(U,j),K=r.mul(P,K),pe=r.mul(v,pe),U=r.sub(Z,pe),U=r.mul(v,U),U=r.add(U,K),K=r.add(Z,Z),Z=r.add(K,Z),Z=r.add(Z,pe),Z=r.mul(Z,U),R=r.add(R,Z),pe=r.mul(O,N),pe=r.add(pe,pe),Z=r.mul(pe,U),j=r.sub(j,Z),K=r.mul(pe,re),K=r.add(K,K),K=r.add(K,K),new x(j,R,K)}add(v){m(v);let{px:T,py:P,pz:k}=this,{px:O,py:N,pz:j}=v,{ZERO:R,ZERO:K,ZERO:Z}=r,re=t.a,pe=r.mul(t.b,pP),U=r.mul(T,O),ee=r.mul(P,N),me=r.mul(k,j),z=r.add(T,P),F=r.add(O,N);z=r.mul(z,F),F=r.add(U,ee),z=r.sub(z,F),F=r.add(T,k);let Y=r.add(O,j);return F=r.mul(F,Y),Y=r.add(U,me),F=r.sub(F,Y),Y=r.add(P,k),R=r.add(N,j),Y=r.mul(Y,R),R=r.add(ee,me),Y=r.sub(Y,R),Z=r.mul(re,F),R=r.mul(pe,me),Z=r.add(R,Z),R=r.sub(ee,Z),Z=r.add(ee,Z),K=r.mul(R,Z),ee=r.add(U,U),ee=r.add(ee,U),me=r.mul(re,me),F=r.mul(pe,F),ee=r.add(ee,me),me=r.sub(U,me),me=r.mul(re,me),F=r.add(F,me),U=r.mul(ee,F),K=r.add(K,U),U=r.mul(Y,F),R=r.mul(z,R),R=r.sub(R,U),U=r.mul(z,ee),Z=r.mul(Y,Z),Z=r.add(Z,U),new x(R,K,Z)}subtract(v){return this.add(v.negate())}is0(){return this.equals(x.ZERO)}wNAF(v){return A.wNAFCached(this,v,x.normalizeZ)}multiplyUnsafe(v){let{endo:T,n:P}=t;On("scalar",v,ms,P);let k=x.ZERO;if(v===ms)return k;if(this.is0()||v===vr)return this;if(!T||A.hasPrecomputes(this))return A.wNAFCachedUnsafe(this,v,x.normalizeZ);let{k1neg:O,k1:N,k2neg:j,k2:R}=T.splitScalar(v),K=k,Z=k,re=this;while(N>ms||R>ms){if(N&vr)K=K.add(re);if(R&vr)Z=Z.add(re);re=re.double(),N>>=vr,R>>=vr}if(O)K=K.negate();if(j)Z=Z.negate();return Z=new x(r.mul(Z.px,T.beta),Z.py,Z.pz),K.add(Z)}multiply(v){let{endo:T,n:P}=t;On("scalar",v,vr,P);let k,O;if(T){let{k1neg:N,k1:j,k2neg:R,k2:K}=T.splitScalar(v),{p:Z,f:re}=this.wNAF(j),{p:pe,f:U}=this.wNAF(K);Z=A.constTimeNegate(N,Z),pe=A.constTimeNegate(R,pe),pe=new x(r.mul(pe.px,T.beta),pe.py,pe.pz),k=Z.add(pe),O=re.add(U)}else{let{p:N,f:j}=this.wNAF(v);k=N,O=j}return x.normalizeZ([k,O])[0]}multiplyAndAddUnsafe(v,T,P){let k=x.BASE,O=(j,R)=>R===ms||R===vr||!j.equals(k)?j.multiplyUnsafe(R):j.multiply(R),N=O(this,T).add(O(v,P));return N.is0()?void 0:N}toAffine(v){return h(this,v)}isTorsionFree(){let{h:v,isTorsionFree:T}=t;if(v===vr)return!0;if(T)return T(x,this);throw Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:v,clearCofactor:T}=t;if(v===vr)return this;if(T)return T(x,this);return this.multiplyUnsafe(t.h)}toRawBytes(v=!0){return Yo("isCompressed",v),this.assertValidity(),o(x,this,v)}toHex(v=!0){return Yo("isCompressed",v),ra(this.toRawBytes(v))}}x.BASE=new x(t.Gx,t.Gy,r.ONE),x.ZERO=new x(r.ZERO,r.ONE,r.ZERO);let{endo:_,nBitLength:w}=t,A=$0(x,_?Math.ceil(w/2):w);return{CURVE:t,ProjectivePoint:x,normPrivateKeyToScalar:p,weierstrassEquation:s,isWithinCurveOrder:l}}function Ace(e){let t=kf(e);return Hi(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function XL(e){let t=Ace(e),{Fp:r,n,nByteLength:o,nBitLength:i}=t,s=r.BYTES+1,a=2*r.BYTES+1;function c(U){return Pt(U,n)}function d(U){return M0(U,n)}let{ProjectivePoint:l,normPrivateKeyToScalar:p,weierstrassEquation:m,isWithinCurveOrder:h}=Pce({...t,toBytes(U,ee,me){let z=ee.toAffine(),F=r.toBytes(z.x),Y=na;if(Yo("isCompressed",me),me)return Y(Uint8Array.from([ee.hasEvenY()?2:3]),F);else return Y(Uint8Array.from([4]),F,r.toBytes(z.y))},fromBytes(U){let ee=U.length,me=U[0],z=U.subarray(1);if(ee===s&&(me===2||me===3)){let F=qi(z);if(!C0(F,vr,r.ORDER))throw Error("Point is not on curve");let Y=m(F),we;try{we=r.sqrt(Y)}catch(Ee){let Ae=Ee instanceof Error?": "+Ee.message:"";throw Error("Point is not on curve"+Ae)}let te=(we&vr)===vr;if((me&1)===1!==te)we=r.neg(we);return{x:F,y:we}}else if(ee===a&&me===4){let F=r.fromBytes(z.subarray(0,r.BYTES)),Y=r.fromBytes(z.subarray(r.BYTES,2*r.BYTES));return{x:F,y:Y}}else{let F=s,Y=a;throw Error("invalid Point, expected length of "+F+", or uncompressed "+Y+", got "+ee)}}});function b(U){let ee=n>>vr;return U>ee}function x(U){return b(U)?c(-U):U}let _=(U,ee,me)=>qi(U.slice(ee,me));class w{constructor(U,ee,me){if(On("r",U,vr,n),On("s",ee,vr,n),this.r=U,this.s=ee,me!=null)this.recovery=me;Object.freeze(this)}static fromCompact(U){let ee=o;return U=Gt("compactSignature",U,ee*2),new w(_(U,0,ee),_(U,ee,2*ee))}static fromDER(U){let{r:ee,s:me}=fs.toSig(Gt("DER",U));return new w(ee,me)}assertValidity(){}addRecoveryBit(U){return new w(this.r,this.s,U)}recoverPublicKey(U){let{r:ee,s:me,recovery:z}=this,F=O(Gt("msgHash",U));if(z==null||![0,1,2,3].includes(z))throw Error("recovery id invalid");let Y=z===2||z===3?ee+t.n:ee;if(Y>=r.ORDER)throw Error("recovery id 2 or 3 invalid");let we=(z&1)===0?"02":"03",te=l.fromHex(we+lP(Y,r.BYTES)),$e=d(Y),Ee=c(-F*$e),Ae=c(me*$e),tt=l.BASE.multiplyAndAddUnsafe(te,Ee,Ae);if(!tt)throw Error("point at infinify");return tt.assertValidity(),tt}hasHighS(){return b(this.s)}normalizeS(){return this.hasHighS()?new w(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return Af(this.toDERHex())}toDERHex(){return fs.hexFromSig(this)}toCompactRawBytes(){return Af(this.toCompactHex())}toCompactHex(){let U=o;return lP(this.r,U)+lP(this.s,U)}}let A={isValidPrivateKey(U){try{return p(U),!0}catch(ee){return!1}},normPrivateKeyToScalar:p,randomPrivateKey:()=>{let U=Vv(t.n);return $8(t.randomBytes(U),t.n)},precompute(U=8,ee=l.BASE){return ee._setWindowSize(U),ee.multiply(BigInt(3)),ee}};function v(U,ee=!0){return l.fromPrivateKey(U).toRawBytes(ee)}function T(U){if(typeof U==="bigint")return!1;if(U instanceof l)return!0;let me=Gt("key",U).length,z=r.BYTES,F=z+1,Y=2*z+1;if(t.allowedPrivateKeyLengths||o===F)return;else return me===F||me===Y}function P(U,ee,me=!0){if(T(U)===!0)throw Error("first arg must be private key");if(T(ee)===!1)throw Error("second arg must be public key");return l.fromHex(ee).multiply(p(U)).toRawBytes(me)}let k=t.bits2int||function(U){if(U.length>8192)throw Error("input is too large");let ee=qi(U),me=U.length*8-i;return me>0?ee>>BigInt(me):ee},O=t.bits2int_modN||function(U){return c(k(U))},N=_c(i);function j(U){return On("num < 2^"+i,U,ms,N),xc(U,o)}function R(U,ee,me=K){if(["recovered","canonical"].some((q)=>(q in me)))throw Error("sign() legacy options not supported");let{hash:z,randomBytes:F}=t,{lowS:Y,prehash:we,extraEntropy:te}=me;if(Y==null)Y=!0;if(U=Gt("msgHash",U),JL(me),we)U=Gt("prehashed msgHash",z(U));let $e=O(U),Ee=p(ee),Ae=[j(Ee),j($e)];if(te!=null&&te!==!1){let q=te===!0?F(r.BYTES):te;Ae.push(Gt("extraEntropy",q))}let tt=na(...Ae),yt=$e;function ft(q){let ne=k(q);if(!h(ne))return;let ce=d(ne),he=l.BASE.multiply(ne).toAffine(),Q=c(he.x);if(Q===ms)return;let Be=c(ce*c(yt+Q*Ee));if(Be===ms)return;let bt=(he.x===Q?0:2)|Number(he.y&vr),xt=Be;if(Y&&b(Be))xt=x(Be),bt^=1;return new w(Q,xt,bt)}return{seed:tt,k2sig:ft}}let K={lowS:t.lowS,prehash:!1},Z={lowS:t.lowS,prehash:!1};function re(U,ee,me=K){let{seed:z,k2sig:F}=R(U,ee,me),Y=t;return P8(Y.hash.outputLen,Y.nByteLength,Y.hmac)(z,F)}l.BASE._setWindowSize(8);function pe(U,ee,me,z=Z){let F=U;ee=Gt("msgHash",ee),me=Gt("publicKey",me);let{lowS:Y,prehash:we,format:te}=z;if(JL(z),"strict"in z)throw Error("options.strict was renamed to lowS");if(te!==void 0&&te!=="compact"&&te!=="der")throw Error("format must be compact or der");let $e=typeof F==="string"||Ju(F),Ee=!$e&&!te&&typeof F==="object"&&F!==null&&typeof F.r==="bigint"&&typeof F.s==="bigint";if(!$e&&!Ee)throw Error("invalid signature, expected Uint8Array, hex string or Signature instance");let Ae=void 0,tt;try{if(Ee)Ae=new w(F.r,F.s);if($e){try{if(te!=="compact")Ae=w.fromDER(F)}catch(bt){if(!(bt instanceof fs.Err))throw bt}if(!Ae&&te!=="der")Ae=w.fromCompact(F)}tt=l.fromHex(me)}catch(bt){return!1}if(!Ae)return!1;if(Y&&Ae.hasHighS())return!1;if(we)ee=t.hash(ee);let{r:yt,s:ft}=Ae,q=O(ee),ne=d(ft),ce=c(q*ne),he=c(yt*ne),Q=l.BASE.multiplyAndAddUnsafe(tt,ce,he)?.toAffine();if(!Q)return!1;return c(Q.x)===yt}return{CURVE:t,getPublicKey:v,getSharedSecret:P,sign:re,verify:pe,ProjectivePoint:l,Signature:w,utils:A}}var QL,fs,ms,vr,k6e,pP,Ece;var e9=V(()=>{Qv();td();If();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */QL=class QL extends Error{constructor(e=""){super(e)}};fs={Err:QL,_tlv:{encode:(e,t)=>{let{Err:r}=fs;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,o=Pf(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let i=n>127?Pf(o.length/2|128):"";return Pf(e)+i+o+t},decode(e,t){let{Err:r}=fs,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");let o=t[n++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let d=t.subarray(n,n+c);if(d.length!==c)throw new r("tlv.decode: length bytes not complete");if(d[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let l of d)s=s<<8|l;if(n+=c,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+s)}}},_int:{encode(e){let{Err:t}=fs;if(e<ms)throw new t("integer: negative integers are not allowed");let r=Pf(e);if(Number.parseInt(r[0],16)&8)r="00"+r;if(r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){let{Err:t}=fs;if(e[0]&128)throw new t("invalid signature integer: negative");if(e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return qi(e)}},toSig(e){let{Err:t,_int:r,_tlv:n}=fs,o=Gt("signature",e),{v:i,l:s}=n.decode(48,o);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,i),{v:d,l}=n.decode(2,c);if(l.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(d)}},hexFromSig(e){let{_tlv:t,_int:r}=fs,n=t.encode(2,r.encode(e.r)),o=t.encode(2,r.encode(e.s)),i=n+o;return t.encode(48,i)}};ms=BigInt(0),vr=BigInt(1),k6e=BigInt(2),pP=BigInt(3),Ece=BigInt(4)});function Ice(e){return{hash:e,hmac:(t,...r)=>dP(e,t,$v(...r)),randomBytes:k0}}function t9(e,t){let r=(n)=>XL({...e,...Ice(n)});return{...r(t),create:r}}var r9=V(()=>{YL();hc();e9();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */});function Oce(e){let t=i9,r=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),d=e*e*e%t,l=d*d*e%t,p=Vt(l,r,t)*l%t,m=Vt(p,r,t)*l%t,h=Vt(m,fP,t)*d%t,b=Vt(h,o,t)*h%t,x=Vt(b,i,t)*b%t,_=Vt(x,a,t)*x%t,w=Vt(_,c,t)*_%t,A=Vt(w,a,t)*x%t,v=Vt(A,r,t)*l%t,T=Vt(v,s,t)*b%t,P=Vt(T,n,t)*d%t,k=Vt(P,fP,t);if(!mP.eql(mP.sqr(k),e))throw Error("Cannot find square root");return k}var i9,n9,kce,Rce,fP,o9=(e,t)=>(e+t/fP)/t,mP,hs;var gm=V(()=>{Lv();r9();td();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */i9=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n9=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),kce=BigInt(0),Rce=BigInt(1),fP=BigInt(2);mP=Gi(i9,void 0,void 0,{sqrt:Oce}),hs=t9({a:kce,b:BigInt(7),Fp:mP,n:n9,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:(e)=>{let t=n9,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Rce*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=r,s=BigInt("0x100000000000000000000000000000000"),a=o9(i*e,t),c=o9(-n*e,t),d=Pt(e-a*r-c*o,t),l=Pt(-a*n-c*i,t),p=d>s,m=l>s;if(p)d=t-d;if(m)l=t-l;if(d>s||l>s)throw Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:p,k1:d,k2neg:m,k2:l}}}},x8)});import{webcrypto as Ope}from"node:crypto";import xG from"node:http";import _G from"node:https";import uu from"node:zlib";import Wk,{PassThrough as Kk,pipeline as du}from"node:stream";import{Buffer as xh}from"node:buffer";function KH(e){if(!/^data:/i.test(e))throw TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');e=e.replace(/\r?\n/g,"");let t=e.indexOf(",");if(t===-1||t<=4)throw TypeError("malformed data: URI");let r=e.substring(5,t).split(";"),n="",o=!1,i=r[0]||"text/plain",s=i;for(let l=1;l<r.length;l++)if(r[l]==="base64")o=!0;else if(r[l]){if(s+=`;${r[l]}`,r[l].indexOf("charset=")===0)n=r[l].substring(8)}if(!r[0]&&!n.length)s+=";charset=US-ASCII",n="US-ASCII";let a=o?"base64":"ascii",c=unescape(e.substring(t+1)),d=Buffer.from(c,a);return d.type=i,d.typeFull=s,d.charset=n,d}var gk=KH;Wl();lh();import ks,{PassThrough as $k}from"node:stream";import{types as Nk,deprecate as n1,promisify as dG}from"node:util";import{Buffer as Un}from"node:buffer";class As extends Error{constructor(e,t){super(e);Error.captureStackTrace(this,this.constructor),this.type=t}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}class Tn extends As{constructor(e,t,r){super(e,t);if(r)this.code=this.errno=r.code,this.erroredSysCall=r.syscall}}var ph=Symbol.toStringTag,e1=(e)=>typeof e==="object"&&typeof e.append==="function"&&typeof e.delete==="function"&&typeof e.get==="function"&&typeof e.getAll==="function"&&typeof e.has==="function"&&typeof e.set==="function"&&typeof e.sort==="function"&&e[ph]==="URLSearchParams",Yl=(e)=>e&&typeof e==="object"&&typeof e.arrayBuffer==="function"&&typeof e.type==="string"&&typeof e.stream==="function"&&typeof e.constructor==="function"&&/^(Blob|File)$/.test(e[ph]),Ek=(e)=>typeof e==="object"&&(e[ph]==="AbortSignal"||e[ph]==="EventTarget"),Pk=(e,t)=>{let r=new URL(t).hostname,n=new URL(e).hostname;return r===n||r.endsWith(`.${n}`)},Ak=(e,t)=>{let r=new URL(t).protocol,n=new URL(e).protocol;return r===n};var lG=dG(ks.pipeline),un=Symbol("Body internals");class vi{constructor(e,{size:t=0}={}){let r=null;if(e===null)e=null;else if(e1(e))e=Un.from(e.toString());else if(Yl(e));else if(Un.isBuffer(e));else if(Nk.isAnyArrayBuffer(e))e=Un.from(e);else if(ArrayBuffer.isView(e))e=Un.from(e.buffer,e.byteOffset,e.byteLength);else if(e instanceof ks);else if(e instanceof Ua)e=Tk(e),r=e.type.split("=")[1];else e=Un.from(String(e));let n=e;if(Un.isBuffer(e))n=ks.Readable.from(e);else if(Yl(e))n=ks.Readable.from(e.stream());if(this[un]={body:e,stream:n,boundary:r,disturbed:!1,error:null},this.size=t,e instanceof ks)e.on("error",(o)=>{let i=o instanceof As?o:new Tn(`Invalid response body while trying to fetch ${this.url}: ${o.message}`,"system",o);this[un].error=i})}get body(){return this[un].stream}get bodyUsed(){return this[un].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:t,byteLength:r}=await r1(this);return e.slice(t,t+r)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let r=new Ua,n=new URLSearchParams(await this.text());for(let[o,i]of n)r.append(o,i);return r}await Promise.resolve().then(() => Mk());return Ck(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[un].body&&this[un].body.type||"",t=await this.arrayBuffer();return new Si([t],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await r1(this);return new TextDecoder().decode(e)}buffer(){return r1(this)}}vi.prototype.buffer=n1(vi.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(vi.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:n1(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});async function r1(e){if(e[un].disturbed)throw TypeError(`body used already for: ${e.url}`);if(e[un].disturbed=!0,e[un].error)throw e[un].error;let{body:t}=e;if(t===null)return Un.alloc(0);if(!(t instanceof ks))return Un.alloc(0);let r=[],n=0;try{for await(let o of t){if(e.size>0&&n+o.length>e.size){let i=new Tn(`content size at ${e.url} over limit: ${e.size}`,"max-size");throw t.destroy(i),i}n+=o.length,r.push(o)}}catch(o){throw o instanceof As?o:new Tn(`Invalid response body while trying to fetch ${e.url}: ${o.message}`,"system",o)}if(t.readableEnded===!0||t._readableState.ended===!0)try{if(r.every((o)=>typeof o==="string"))return Un.from(r.join(""));return Un.concat(r,n)}catch(o){throw new Tn(`Could not create Buffer from response body for ${e.url}: ${o.message}`,"system",o)}else throw new Tn(`Premature close of server response while trying to fetch ${e.url}`)}var au=(e,t)=>{let r,n,{body:o}=e[un];if(e.bodyUsed)throw Error("cannot clone body after it is used");if(o instanceof ks&&typeof o.getBoundary!=="function")r=new $k({highWaterMark:t}),n=new $k({highWaterMark:t}),o.pipe(r),o.pipe(n),e[un].stream=r,o=n;return o},pG=n1((e)=>e.getBoundary(),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),hh=(e,t)=>{if(e===null)return null;if(typeof e==="string")return"text/plain;charset=UTF-8";if(e1(e))return"application/x-www-form-urlencoded;charset=UTF-8";if(Yl(e))return e.type||null;if(Un.isBuffer(e)||Nk.isAnyArrayBuffer(e)||ArrayBuffer.isView(e))return null;if(e instanceof Ua)return`multipart/form-data; boundary=${t[un].boundary}`;if(e&&typeof e.getBoundary==="function")return`multipart/form-data;boundary=${pG(e)}`;if(e instanceof ks)return null;return"text/plain;charset=UTF-8"},zk=(e)=>{let{body:t}=e[un];if(t===null)return 0;if(Yl(t))return t.size;if(Un.isBuffer(t))return t.length;if(t&&typeof t.getLengthSync==="function")return t.hasKnownLength&&t.hasKnownLength()?t.getLengthSync():null;return null},Bk=async(e,{body:t})=>{if(t===null)e.end();else await lG(t,e)};import{types as Lk}from"node:util";import yh from"node:http";var gh=typeof yh.validateHeaderName==="function"?yh.validateHeaderName:(e)=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(e)){let t=TypeError(`Header name must be a valid HTTP token [${e}]`);throw Object.defineProperty(t,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),t}},o1=typeof yh.validateHeaderValue==="function"?yh.validateHeaderValue:(e,t)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(t)){let r=TypeError(`Invalid character in header content ["${e}"]`);throw Object.defineProperty(r,"code",{value:"ERR_INVALID_CHAR"}),r}};class Zr extends URLSearchParams{constructor(e){let t=[];if(e instanceof Zr){let r=e.raw();for(let[n,o]of Object.entries(r))t.push(...o.map((i)=>[n,i]))}else if(e==null);else if(typeof e==="object"&&!Lk.isBoxedPrimitive(e)){let r=e[Symbol.iterator];if(r==null)t.push(...Object.entries(e));else{if(typeof r!=="function")throw TypeError("Header pairs must be iterable");t=[...e].map((n)=>{if(typeof n!=="object"||Lk.isBoxedPrimitive(n))throw TypeError("Each header pair must be an iterable object");return[...n]}).map((n)=>{if(n.length!==2)throw TypeError("Each header pair must be a name/value tuple");return[...n]})}}else throw TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");t=t.length>0?t.map(([r,n])=>(gh(r),o1(r,String(n)),[String(r).toLowerCase(),String(n)])):void 0;super(t);return new Proxy(this,{get(r,n,o){switch(n){case"append":case"set":return(i,s)=>(gh(i),o1(i,String(s)),URLSearchParams.prototype[n].call(r,String(i).toLowerCase(),String(s)));case"delete":case"has":case"getAll":return(i)=>(gh(i),URLSearchParams.prototype[n].call(r,String(i).toLowerCase()));case"keys":return()=>(r.sort(),new Set(URLSearchParams.prototype.keys.call(r)).keys());default:return Reflect.get(r,n,o)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let t=this.getAll(e);if(t.length===0)return null;let r=t.join(", ");if(/^content-encoding$/i.test(e))r=r.toLowerCase();return r}forEach(e,t=void 0){for(let r of this.keys())Reflect.apply(e,t,[this.get(r),r,this])}*values(){for(let e of this.keys())yield this.get(e)}*entries(){for(let e of this.keys())yield[e,this.get(e)]}[Symbol.iterator](){return this.entries()}raw(){return[...this.keys()].reduce((e,t)=>(e[t]=this.getAll(t),e),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((e,t)=>{let r=this.getAll(t);if(t==="host")e[t]=r[0];else e[t]=r.length>1?r:r[0];return e},{})}}Object.defineProperties(Zr.prototype,["get","entries","forEach","values"].reduce((e,t)=>(e[t]={enumerable:!0},e),{}));function Dk(e=[]){return new Zr(e.reduce((t,r,n,o)=>{if(n%2===0)t.push(o.slice(n,n+2));return t},[]).filter(([t,r])=>{try{return gh(t),o1(t,String(r)),!0}catch{return!1}}))}var fG=new Set([301,302,303,307,308]),bh=(e)=>fG.has(e);var ao=Symbol("Response internals");class Ar extends vi{constructor(e=null,t={}){super(e,t);let r=t.status!=null?t.status:200,n=new Zr(t.headers);if(e!==null&&!n.has("Content-Type")){let o=hh(e,this);if(o)n.append("Content-Type",o)}this[ao]={type:"default",url:t.url,status:r,statusText:t.statusText||"",headers:n,counter:t.counter,highWaterMark:t.highWaterMark}}get type(){return this[ao].type}get url(){return this[ao].url||""}get status(){return this[ao].status}get ok(){return this[ao].status>=200&&this[ao].status<300}get redirected(){return this[ao].counter>0}get statusText(){return this[ao].statusText}get headers(){return this[ao].headers}get highWaterMark(){return this[ao].highWaterMark}clone(){return new Ar(au(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(e,t=302){if(!bh(t))throw RangeError('Failed to execute "redirect" on "response": Invalid status code');return new Ar(null,{headers:{location:new URL(e).toString()},status:t})}static error(){let e=new Ar(null,{status:0,statusText:""});return e[ao].type="error",e}static json(e=void 0,t={}){let r=JSON.stringify(e);if(r===void 0)throw TypeError("data is not JSON serializable");let n=new Zr(t&&t.headers);if(!n.has("content-type"))n.set("content-type","application/json");return new Ar(r,{...t,headers:n})}get[Symbol.toStringTag](){return"Response"}}Object.defineProperties(Ar.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});import{format as gG}from"node:url";import{deprecate as yG}from"node:util";var Uk=(e)=>{if(e.search)return e.search;let t=e.href.length-1,r=e.hash||(e.href[t]==="#"?"#":"");return e.href[t-r.length]==="?"?"?":""};import{isIP as mG}from"node:net";function Fk(e,t=!1){if(e==null)return"no-referrer";if(e=new URL(e),/^(about|blob|data):$/.test(e.protocol))return"no-referrer";if(e.username="",e.password="",e.hash="",t)e.pathname="",e.search="";return e}var jk=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),qk="strict-origin-when-cross-origin";function Hk(e){if(!jk.has(e))throw TypeError(`Invalid referrerPolicy: ${e}`);return e}function hG(e){if(/^(http|ws)s:$/.test(e.protocol))return!0;let t=e.host.replace(/(^\[)|(]$)/g,""),r=mG(t);if(r===4&&/^127\./.test(t))return!0;if(r===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(t))return!0;if(e.host==="localhost"||e.host.endsWith(".localhost"))return!1;if(e.protocol==="file:")return!0;return!1}function cu(e){if(/^about:(blank|srcdoc)$/.test(e))return!0;if(e.protocol==="data:")return!0;if(/^(blob|filesystem):$/.test(e.protocol))return!0;return hG(e)}function Gk(e,{referrerURLCallback:t,referrerOriginCallback:r}={}){if(e.referrer==="no-referrer"||e.referrerPolicy==="")return null;let n=e.referrerPolicy;if(e.referrer==="about:client")return"no-referrer";let o=e.referrer,i=Fk(o),s=Fk(o,!0);if(i.toString().length>4096)i=s;if(t)i=t(i);if(r)s=r(s);let a=new URL(e.url);switch(n){case"no-referrer":return"no-referrer";case"origin":return s;case"unsafe-url":return i;case"strict-origin":if(cu(i)&&!cu(a))return"no-referrer";return s.toString();case"strict-origin-when-cross-origin":if(i.origin===a.origin)return i;if(cu(i)&&!cu(a))return"no-referrer";return s;case"same-origin":if(i.origin===a.origin)return i;return"no-referrer";case"origin-when-cross-origin":if(i.origin===a.origin)return i;return s;case"no-referrer-when-downgrade":if(cu(i)&&!cu(a))return"no-referrer";return i;default:throw TypeError(`Invalid referrerPolicy: ${n}`)}}function Vk(e){let t=(e.get("referrer-policy")||"").split(/[,\s]+/),r="";for(let n of t)if(n&&jk.has(n))r=n;return r}var hr=Symbol("Request internals"),Ql=(e)=>typeof e==="object"&&typeof e[hr]==="object",bG=yG(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)");class Ti extends vi{constructor(e,t={}){let r;if(Ql(e))r=new URL(e.url);else r=new URL(e),e={};if(r.username!==""||r.password!=="")throw TypeError(`${r} is an url with embedded credentials.`);let n=t.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(n))n=n.toUpperCase();if(!Ql(t)&&"data"in t)bG();if((t.body!=null||Ql(e)&&e.body!==null)&&(n==="GET"||n==="HEAD"))throw TypeError("Request with GET/HEAD method cannot have body");let o=t.body?t.body:Ql(e)&&e.body!==null?au(e):null;super(o,{size:t.size||e.size||0});let i=new Zr(t.headers||e.headers||{});if(o!==null&&!i.has("Content-Type")){let c=hh(o,this);if(c)i.set("Content-Type",c)}let s=Ql(e)?e.signal:null;if("signal"in t)s=t.signal;if(s!=null&&!Ek(s))throw TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let a=t.referrer==null?e.referrer:t.referrer;if(a==="")a="no-referrer";else if(a){let c=new URL(a);a=/^about:(\/\/)?client$/.test(c)?"client":c}else a=void 0;this[hr]={method:n,redirect:t.redirect||e.redirect||"follow",headers:i,parsedURL:r,signal:s,referrer:a},this.follow=t.follow===void 0?e.follow===void 0?20:e.follow:t.follow,this.compress=t.compress===void 0?e.compress===void 0?!0:e.compress:t.compress,this.counter=t.counter||e.counter||0,this.agent=t.agent||e.agent,this.highWaterMark=t.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=t.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=t.referrerPolicy||e.referrerPolicy||""}get method(){return this[hr].method}get url(){return gG(this[hr].parsedURL)}get headers(){return this[hr].headers}get redirect(){return this[hr].redirect}get signal(){return this[hr].signal}get referrer(){if(this[hr].referrer==="no-referrer")return"";if(this[hr].referrer==="client")return"about:client";if(this[hr].referrer)return this[hr].referrer.toString();return}get referrerPolicy(){return this[hr].referrerPolicy}set referrerPolicy(e){this[hr].referrerPolicy=Hk(e)}clone(){return new Ti(this)}get[Symbol.toStringTag](){return"Request"}}Object.defineProperties(Ti.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}});var Zk=(e)=>{let{parsedURL:t}=e[hr],r=new Zr(e[hr].headers);if(!r.has("Accept"))r.set("Accept","*/*");let n=null;if(e.body===null&&/^(post|put)$/i.test(e.method))n="0";if(e.body!==null){let a=zk(e);if(typeof a==="number"&&!Number.isNaN(a))n=String(a)}if(n)r.set("Content-Length",n);if(e.referrerPolicy==="")e.referrerPolicy=qk;if(e.referrer&&e.referrer!=="no-referrer")e[hr].referrer=Gk(e);else e[hr].referrer="no-referrer";if(e[hr].referrer instanceof URL)r.set("Referer",e.referrer);if(!r.has("User-Agent"))r.set("User-Agent","node-fetch");if(e.compress&&!r.has("Accept-Encoding"))r.set("Accept-Encoding","gzip, deflate, br");let{agent:o}=e;if(typeof o==="function")o=o(t);let i=Uk(t),s={path:t.pathname+i,method:e.method,headers:r[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:e.insecureHTTPParser,agent:o};return{parsedURL:t,options:s}};class i1 extends As{constructor(e,t="aborted"){super(e,t)}}lh();t1();var wG=new Set(["data:","http:","https:"]);async function _h(e,t){return new Promise((r,n)=>{let o=new Ti(e,t),{parsedURL:i,options:s}=Zk(o);if(!wG.has(i.protocol))throw TypeError(`node-fetch cannot load ${e}. URL scheme "${i.protocol.replace(/:$/,"")}" is not supported.`);if(i.protocol==="data:"){let b=gk(o.url),x=new Ar(b,{headers:{"Content-Type":b.typeFull}});r(x);return}let a=(i.protocol==="https:"?_G:xG).request,{signal:c}=o,d=null,l=()=>{let b=new i1("The operation was aborted.");if(n(b),o.body&&o.body instanceof Wk.Readable)o.body.destroy(b);if(!d||!d.body)return;d.body.emit("error",b)};if(c&&c.aborted){l();return}let p=()=>{l(),h()},m=a(i.toString(),s);if(c)c.addEventListener("abort",p);let h=()=>{if(m.abort(),c)c.removeEventListener("abort",p)};if(m.on("error",(b)=>{n(new Tn(`request to ${o.url} failed, reason: ${b.message}`,"system",b)),h()}),SG(m,(b)=>{if(d&&d.body)d.body.destroy(b)}),process.version<"v14")m.on("socket",(b)=>{let x;b.prependListener("end",()=>{x=b._eventsCount}),b.prependListener("close",(_)=>{if(d&&x<b._eventsCount&&!_){let w=Error("Premature close");w.code="ERR_STREAM_PREMATURE_CLOSE",d.body.emit("error",w)}})});m.on("response",(b)=>{m.setTimeout(0);let x=Dk(b.rawHeaders);if(bh(b.statusCode)){let T=x.get("Location"),P=null;try{P=T===null?null:new URL(T,o.url)}catch{if(o.redirect!=="manual"){n(new Tn(`uri requested responds with an invalid redirect URL: ${T}`,"invalid-redirect")),h();return}}switch(o.redirect){case"error":n(new Tn(`uri requested responds with a redirect, redirect mode is set to error: ${o.url}`,"no-redirect")),h();return;case"manual":break;case"follow":{if(P===null)break;if(o.counter>=o.follow){n(new Tn(`maximum redirect reached at: ${o.url}`,"max-redirect")),h();return}let k={headers:new Zr(o.headers),follow:o.follow,counter:o.counter+1,agent:o.agent,compress:o.compress,method:o.method,body:au(o),signal:o.signal,size:o.size,referrer:o.referrer,referrerPolicy:o.referrerPolicy};if(!Pk(o.url,P)||!Ak(o.url,P))for(let N of["authorization","www-authenticate","cookie","cookie2"])k.headers.delete(N);if(b.statusCode!==303&&o.body&&t.body instanceof Wk.Readable){n(new Tn("Cannot follow redirect with body being a readable stream","unsupported-redirect")),h();return}if(b.statusCode===303||(b.statusCode===301||b.statusCode===302)&&o.method==="POST")k.method="GET",k.body=void 0,k.headers.delete("content-length");let O=Vk(x);if(O)k.referrerPolicy=O;r(_h(new Ti(P,k))),h();return}default:return n(TypeError(`Redirect option '${o.redirect}' is not a valid value of RequestRedirect`))}}if(c)b.once("end",()=>{c.removeEventListener("abort",p)});let _=du(b,new Kk,(T)=>{if(T)n(T)});if(process.version<"v12.10")b.on("aborted",p);let w={url:o.url,status:b.statusCode,statusText:b.statusMessage,headers:x,size:o.size,counter:o.counter,highWaterMark:o.highWaterMark},A=x.get("Content-Encoding");if(!o.compress||o.method==="HEAD"||A===null||b.statusCode===204||b.statusCode===304){d=new Ar(_,w),r(d);return}let v={flush:uu.Z_SYNC_FLUSH,finishFlush:uu.Z_SYNC_FLUSH};if(A==="gzip"||A==="x-gzip"){_=du(_,uu.createGunzip(v),(T)=>{if(T)n(T)}),d=new Ar(_,w),r(d);return}if(A==="deflate"||A==="x-deflate"){let T=du(b,new Kk,(P)=>{if(P)n(P)});T.once("data",(P)=>{if((P[0]&15)===8)_=du(_,uu.createInflate(),(k)=>{if(k)n(k)});else _=du(_,uu.createInflateRaw(),(k)=>{if(k)n(k)});d=new Ar(_,w),r(d)}),T.once("end",()=>{if(!d)d=new Ar(_,w),r(d)});return}if(A==="br"){_=du(_,uu.createBrotliDecompress(),(T)=>{if(T)n(T)}),d=new Ar(_,w),r(d);return}d=new Ar(_,w),r(d)}),Bk(m,o).catch(n)})}function SG(e,t){let r=xh.from(`0\r
66
66
  \r
67
- `),n=!1,o=!1,i;e.on("response",(s)=>{let{headers:a}=s;n=a["transfer-encoding"]==="chunked"&&!a["content-length"]}),e.on("socket",(s)=>{let a=()=>{if(n&&!o){let d=Error("Premature close");d.code="ERR_STREAM_PREMATURE_CLOSE",t(d)}},c=(d)=>{if(o=xh.compare(d.slice(-5),r)===0,!o&&i)o=xh.compare(i.slice(-3),r.slice(0,3))===0&&xh.compare(d.slice(-2),r.slice(3))===0;i=d};s.prependListener("close",a),s.on("data",c),e.on("close",()=>{s.removeListener("close",a),s.removeListener("data",c)})})}var qV=Vr(HR(),1),HV=Vr(Ih(),1),GV=Vr(fu(),1),VV=Vr(l1(),1),ZV=Vr(f1(),1),WV=Vr(x1(),1),_1=Vr(Ch(),1),KV=Vr(YR(),1);var it;(function(e){e.assertEqual=(o)=>{};function t(o){}e.assertIs=t;function r(o){throw Error()}e.assertNever=r,e.arrayToEnum=(o)=>{let i={};for(let s of o)i[s]=s;return i},e.getValidEnumValues=(o)=>{let i=e.objectKeys(o).filter((a)=>typeof o[o[a]]!=="number"),s={};for(let a of i)s[a]=o[a];return e.objectValues(s)},e.objectValues=(o)=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys==="function"?(o)=>Object.keys(o):(o)=>{let i=[];for(let s in o)if(Object.prototype.hasOwnProperty.call(o,s))i.push(s);return i},e.find=(o,i)=>{for(let s of o)if(i(s))return s;return},e.isInteger=typeof Number.isInteger==="function"?(o)=>Number.isInteger(o):(o)=>typeof o==="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,i=" | "){return o.map((s)=>typeof s==="string"?`'${s}'`:s).join(i)}e.joinValues=n,e.jsonStringifyReplacer=(o,i)=>{if(typeof i==="bigint")return i.toString();return i}})(it||(it={}));var JR;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(JR||(JR={}));var ge=it.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ii=(e)=>{switch(typeof e){case"undefined":return ge.undefined;case"string":return ge.string;case"number":return Number.isNaN(e)?ge.nan:ge.number;case"boolean":return ge.boolean;case"function":return ge.function;case"bigint":return ge.bigint;case"symbol":return ge.symbol;case"object":if(Array.isArray(e))return ge.array;if(e===null)return ge.null;if(e.then&&typeof e.then==="function"&&e.catch&&typeof e.catch==="function")return ge.promise;if(typeof Map<"u"&&e instanceof Map)return ge.map;if(typeof Set<"u"&&e instanceof Set)return ge.set;if(typeof Date<"u"&&e instanceof Date)return ge.date;return ge.object;default:return ge.unknown}};var oe=it.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"]);class Pn extends Error{get errors(){return this.issues}constructor(e){super();this.issues=[],this.addIssue=(r)=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let t=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,t);else this.__proto__=t;this.name="ZodError",this.issues=e}format(e){let t=e||function(o){return o.message},r={_errors:[]},n=(o)=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(n);else if(i.code==="invalid_return_type")n(i.returnTypeError);else if(i.code==="invalid_arguments")n(i.argumentsError);else if(i.path.length===0)r._errors.push(t(i));else{let s=r,a=0;while(a<i.path.length){let c=i.path[a];if(a!==i.path.length-1)s[c]=s[c]||{_errors:[]};else s[c]=s[c]||{_errors:[]},s[c]._errors.push(t(i));s=s[c],a++}}};return n(this),r}static assert(e){if(!(e instanceof Pn))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,it.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=(t)=>t.message){let t=Object.create(null),r=[];for(let n of this.issues)if(n.path.length>0){let o=n.path[0];t[o]=t[o]||[],t[o].push(e(n))}else r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}Pn.create=(e)=>new Pn(e);var YV=(e,t)=>{let r;switch(e.code){case oe.invalid_type:if(e.received===ge.undefined)r="Required";else r=`Expected ${e.expected}, received ${e.received}`;break;case oe.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,it.jsonStringifyReplacer)}`;break;case oe.unrecognized_keys:r=`Unrecognized key(s) in object: ${it.joinValues(e.keys,", ")}`;break;case oe.invalid_union:r="Invalid input";break;case oe.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${it.joinValues(e.options)}`;break;case oe.invalid_enum_value:r=`Invalid enum value. Expected ${it.joinValues(e.options)}, received '${e.received}'`;break;case oe.invalid_arguments:r="Invalid function arguments";break;case oe.invalid_return_type:r="Invalid function return type";break;case oe.invalid_date:r="Invalid date";break;case oe.invalid_string:if(typeof e.validation==="object")if("includes"in e.validation){if(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==="number")r=`${r} at one or more positions greater than or equal to ${e.validation.position}`}else if("startsWith"in e.validation)r=`Invalid input: must start with "${e.validation.startsWith}"`;else if("endsWith"in e.validation)r=`Invalid input: must end with "${e.validation.endsWith}"`;else it.assertNever(e.validation);else if(e.validation!=="regex")r=`Invalid ${e.validation}`;else r="Invalid";break;case oe.too_small:if(e.type==="array")r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`;else if(e.type==="string")r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`;else if(e.type==="number")r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="bigint")r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="date")r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`;else r="Invalid input";break;case oe.too_big:if(e.type==="array")r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`;else if(e.type==="string")r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`;else if(e.type==="number")r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="bigint")r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="date")r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`;else r="Invalid input";break;case oe.custom:r="Invalid input";break;case oe.invalid_intersection_types:r="Intersection results could not be merged";break;case oe.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case oe.not_finite:r="Number must be finite";break;default:r=t.defaultError,it.assertNever(e)}return{message:r}},$s=YV;var JV=$s;function sp(){return JV}var $h=(e)=>{let{data:t,path:r,errorMaps:n,issueData:o}=e,i=[...r,...o.path||[]],s={...o,path:i};if(o.message!==void 0)return{...o,path:i,message:o.message};let a="",c=n.filter((d)=>!!d).slice().reverse();for(let d of c)a=d(s,{data:t,defaultError:a}).message;return{...o,path:i,message:a}};function fe(e,t){let r=sp(),n=$h({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===$s?void 0:$s].filter((o)=>!!o)});e.common.issues.push(n)}class Br{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(e,t){let r=[];for(let n of t){if(n.status==="aborted")return Le;if(n.status==="dirty")e.dirty();r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let n of t){let o=await n.key,i=await n.value;r.push({key:o,value:i})}return Br.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let n of t){let{key:o,value:i}=n;if(o.status==="aborted")return Le;if(i.status==="aborted")return Le;if(o.status==="dirty")e.dirty();if(i.status==="dirty")e.dirty();if(o.value!=="__proto__"&&(typeof i.value<"u"||n.alwaysSet))r[o.value]=i.value}return{status:e.value,value:r}}}var Le=Object.freeze({status:"aborted"}),xu=(e)=>({status:"dirty",value:e}),Wr=(e)=>({status:"valid",value:e}),w1=(e)=>e.status==="aborted",S1=(e)=>e.status==="dirty",Va=(e)=>e.status==="valid",ap=(e)=>typeof Promise<"u"&&e instanceof Promise;var Se;(function(e){e.errToObj=(t)=>typeof t==="string"?{message:t}:t||{},e.toString=(t)=>typeof t==="string"?t:t?.message})(Se||(Se={}));class uo{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var QR=(e,t)=>{if(Va(t))return{success:!0,data:t.value};else{if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Pn(e.common.issues);return this._error=r,this._error}}}};function We(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:o}=e;if(t&&(r||n))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(t)return{errorMap:t,description:o};return{errorMap:(s,a)=>{let{message:c}=e;if(s.code==="invalid_enum_value")return{message:c??a.defaultError};if(typeof a.data>"u")return{message:c??n??a.defaultError};if(s.code!=="invalid_type")return{message:a.defaultError};return{message:c??r??a.defaultError}},description:o}}class Xe{get description(){return this._def.description}_getType(e){return Ii(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Ii(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Br,ctx:{common:e.parent.common,data:e.data,parsedType:Ii(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(ap(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ii(e)},n=this._parseSync({data:e,path:r.path,parent:r});return QR(r,n)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ii(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return Va(r)?{value:r.value}:{issues:t.common.issues}}catch(r){if(r?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then((r)=>Va(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ii(e)},n=this._parse({data:e,path:r.path,parent:r}),o=await(ap(n)?n:Promise.resolve(n));return QR(r,o)}refine(e,t){let r=(n)=>{if(typeof t==="string"||typeof t>"u")return{message:t};else if(typeof t==="function")return t(n);else return t};return this._refinement((n,o)=>{let i=e(n),s=()=>o.addIssue({code:oe.custom,...r(n)});if(typeof Promise<"u"&&i instanceof Promise)return i.then((a)=>{if(!a)return s(),!1;else return!0});if(!i)return s(),!1;else return!0})}refinement(e,t){return this._refinement((r,n)=>{if(!e(r))return n.addIssue(typeof t==="function"?t(r,n):t),!1;else return!0})}_refinement(e){return new qo({schema:this,typeName:se.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:(t)=>this["~validate"](t)}}optional(){return jo.create(this,this._def)}nullable(){return Ns.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Fo.create(this)}promise(){return Tu.create(this,this._def)}or(e){return pp.create([this,e],this._def)}and(e){return fp.create(this,e,this._def)}transform(e){return new qo({...We(this._def),schema:this,typeName:se.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e==="function"?e:()=>e;return new yp({...We(this._def),innerType:this,defaultValue:t,typeName:se.ZodDefault})}brand(){return new P1({typeName:se.ZodBranded,type:this,...We(this._def)})}catch(e){let t=typeof e==="function"?e:()=>e;return new bp({...We(this._def),innerType:this,catchValue:t,typeName:se.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return jh.create(this,e)}readonly(){return xp.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var QV=/^c[^\s-]{8,}$/i,XV=/^[0-9a-z]+$/,eZ=/^[0-9A-HJKMNP-TV-Z]{26}$/i,tZ=/^[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,rZ=/^[a-z0-9_-]{21}$/i,nZ=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,oZ=/^[-+]?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)?)??$/,iZ=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,sZ="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",v1,aZ=/^(?:(?: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])$/,cZ=/^(?:(?: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])$/,uZ=/^(([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]))$/,dZ=/^(([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])$/,lZ=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,pZ=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,XR="((\\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])))",fZ=new RegExp(`^${XR}$`);function e2(e){let t="[0-5]\\d";if(e.precision)t=`${t}\\.\\d{${e.precision}}`;else if(e.precision==null)t=`${t}(\\.\\d+)?`;let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function mZ(e){return new RegExp(`^${e2(e)}$`)}function hZ(e){let t=`${XR}T${e2(e)}`,r=[];if(r.push(e.local?"Z?":"Z"),e.offset)r.push("([+-]\\d{2}:?\\d{2})");return t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function gZ(e,t){if((t==="v4"||!t)&&aZ.test(e))return!0;if((t==="v6"||!t)&&uZ.test(e))return!0;return!1}function yZ(e,t){if(!nZ.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));if(typeof o!=="object"||o===null)return!1;if("typ"in o&&o?.typ!=="JWT")return!1;if(!o.alg)return!1;if(t&&o.alg!==t)return!1;return!0}catch{return!1}}function bZ(e,t){if((t==="v4"||!t)&&cZ.test(e))return!0;if((t==="v6"||!t)&&dZ.test(e))return!0;return!1}class Ri extends Xe{_parse(e){if(this._def.coerce)e.data=String(e.data);if(this._getType(e)!==ge.string){let o=this._getOrReturnCtx(e);return fe(o,{code:oe.invalid_type,expected:ge.string,received:o.parsedType}),Le}let r=new Br,n=void 0;for(let o of this._def.checks)if(o.kind==="min"){if(e.data.length<o.value)n=this._getOrReturnCtx(e,n),fe(n,{code:oe.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty()}else if(o.kind==="max"){if(e.data.length>o.value)n=this._getOrReturnCtx(e,n),fe(n,{code:oe.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty()}else if(o.kind==="length"){let i=e.data.length>o.value,s=e.data.length<o.value;if(i||s){if(n=this._getOrReturnCtx(e,n),i)fe(n,{code:oe.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message});else if(s)fe(n,{code:oe.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message});r.dirty()}}else if(o.kind==="email"){if(!iZ.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"email",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="emoji"){if(!v1)v1=new RegExp(sZ,"u");if(!v1.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"emoji",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="uuid"){if(!tZ.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"uuid",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="nanoid"){if(!rZ.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"nanoid",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="cuid"){if(!QV.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"cuid",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="cuid2"){if(!XV.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"cuid2",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="ulid"){if(!eZ.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"ulid",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),fe(n,{validation:"url",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="regex"){if(o.regex.lastIndex=0,!o.regex.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"regex",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="trim")e.data=e.data.trim();else if(o.kind==="includes"){if(!e.data.includes(o.value,o.position))n=this._getOrReturnCtx(e,n),fe(n,{code:oe.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()}else if(o.kind==="toLowerCase")e.data=e.data.toLowerCase();else if(o.kind==="toUpperCase")e.data=e.data.toUpperCase();else if(o.kind==="startsWith"){if(!e.data.startsWith(o.value))n=this._getOrReturnCtx(e,n),fe(n,{code:oe.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()}else if(o.kind==="endsWith"){if(!e.data.endsWith(o.value))n=this._getOrReturnCtx(e,n),fe(n,{code:oe.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()}else if(o.kind==="datetime"){if(!hZ(o).test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{code:oe.invalid_string,validation:"datetime",message:o.message}),r.dirty()}else if(o.kind==="date"){if(!fZ.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{code:oe.invalid_string,validation:"date",message:o.message}),r.dirty()}else if(o.kind==="time"){if(!mZ(o).test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{code:oe.invalid_string,validation:"time",message:o.message}),r.dirty()}else if(o.kind==="duration"){if(!oZ.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"duration",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="ip"){if(!gZ(e.data,o.version))n=this._getOrReturnCtx(e,n),fe(n,{validation:"ip",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="jwt"){if(!yZ(e.data,o.alg))n=this._getOrReturnCtx(e,n),fe(n,{validation:"jwt",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="cidr"){if(!bZ(e.data,o.version))n=this._getOrReturnCtx(e,n),fe(n,{validation:"cidr",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="base64"){if(!lZ.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"base64",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="base64url"){if(!pZ.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"base64url",code:oe.invalid_string,message:o.message}),r.dirty()}else it.assertNever(o);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement((n)=>e.test(n),{validation:t,code:oe.invalid_string,...Se.errToObj(r)})}_addCheck(e){return new Ri({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Se.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Se.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Se.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Se.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Se.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Se.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Se.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Se.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Se.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Se.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Se.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Se.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Se.errToObj(e)})}datetime(e){if(typeof e==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e});return this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Se.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){if(typeof e==="string")return this._addCheck({kind:"time",precision:null,message:e});return this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...Se.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Se.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...Se.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...Se.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...Se.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...Se.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...Se.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...Se.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...Se.errToObj(t)})}nonempty(e){return this.min(1,Se.errToObj(e))}trim(){return new Ri({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ri({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ri({...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)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxLength(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}}Ri.create=(e)=>new Ri({checks:[],typeName:se.ZodString,coerce:e?.coerce??!1,...We(e)});function xZ(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,i=Number.parseInt(e.toFixed(o).replace(".","")),s=Number.parseInt(t.toFixed(o).replace(".",""));return i%s/10**o}class wu extends Xe{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);if(this._getType(e)!==ge.number){let o=this._getOrReturnCtx(e);return fe(o,{code:oe.invalid_type,expected:ge.number,received:o.parsedType}),Le}let r=void 0,n=new Br;for(let o of this._def.checks)if(o.kind==="int"){if(!it.isInteger(e.data))r=this._getOrReturnCtx(e,r),fe(r,{code:oe.invalid_type,expected:"integer",received:"float",message:o.message}),n.dirty()}else if(o.kind==="min"){if(o.inclusive?e.data<o.value:e.data<=o.value)r=this._getOrReturnCtx(e,r),fe(r,{code:oe.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),n.dirty()}else if(o.kind==="max"){if(o.inclusive?e.data>o.value:e.data>=o.value)r=this._getOrReturnCtx(e,r),fe(r,{code:oe.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),n.dirty()}else if(o.kind==="multipleOf"){if(xZ(e.data,o.value)!==0)r=this._getOrReturnCtx(e,r),fe(r,{code:oe.not_multiple_of,multipleOf:o.value,message:o.message}),n.dirty()}else if(o.kind==="finite"){if(!Number.isFinite(e.data))r=this._getOrReturnCtx(e,r),fe(r,{code:oe.not_finite,message:o.message}),n.dirty()}else it.assertNever(o);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,Se.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Se.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Se.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Se.toString(t))}setLimit(e,t,r,n){return new wu({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Se.toString(n)}]})}_addCheck(e){return new wu({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Se.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Se.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Se.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Se.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Se.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Se.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:Se.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Se.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Se.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}get isInt(){return!!this._def.checks.find((e)=>e.kind==="int"||e.kind==="multipleOf"&&it.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks)if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;else if(r.kind==="min"){if(t===null||r.value>t)t=r.value}else if(r.kind==="max"){if(e===null||r.value<e)e=r.value}return Number.isFinite(t)&&Number.isFinite(e)}}wu.create=(e)=>new wu({checks:[],typeName:se.ZodNumber,coerce:e?.coerce||!1,...We(e)});class Su extends Xe{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)!==ge.bigint)return this._getInvalidInput(e);let r=void 0,n=new Br;for(let o of this._def.checks)if(o.kind==="min"){if(o.inclusive?e.data<o.value:e.data<=o.value)r=this._getOrReturnCtx(e,r),fe(r,{code:oe.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),n.dirty()}else if(o.kind==="max"){if(o.inclusive?e.data>o.value:e.data>=o.value)r=this._getOrReturnCtx(e,r),fe(r,{code:oe.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),n.dirty()}else if(o.kind==="multipleOf"){if(e.data%o.value!==BigInt(0))r=this._getOrReturnCtx(e,r),fe(r,{code:oe.not_multiple_of,multipleOf:o.value,message:o.message}),n.dirty()}else it.assertNever(o);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return fe(t,{code:oe.invalid_type,expected:ge.bigint,received:t.parsedType}),Le}gte(e,t){return this.setLimit("min",e,!0,Se.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Se.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Se.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Se.toString(t))}setLimit(e,t,r,n){return new Su({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Se.toString(n)}]})}_addCheck(e){return new Su({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Se.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Se.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Se.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Se.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Se.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}}Su.create=(e)=>new Su({checks:[],typeName:se.ZodBigInt,coerce:e?.coerce??!1,...We(e)});class Nh extends Xe{_parse(e){if(this._def.coerce)e.data=Boolean(e.data);if(this._getType(e)!==ge.boolean){let r=this._getOrReturnCtx(e);return fe(r,{code:oe.invalid_type,expected:ge.boolean,received:r.parsedType}),Le}return Wr(e.data)}}Nh.create=(e)=>new Nh({typeName:se.ZodBoolean,coerce:e?.coerce||!1,...We(e)});class up extends Xe{_parse(e){if(this._def.coerce)e.data=new Date(e.data);if(this._getType(e)!==ge.date){let o=this._getOrReturnCtx(e);return fe(o,{code:oe.invalid_type,expected:ge.date,received:o.parsedType}),Le}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return fe(o,{code:oe.invalid_date}),Le}let r=new Br,n=void 0;for(let o of this._def.checks)if(o.kind==="min"){if(e.data.getTime()<o.value)n=this._getOrReturnCtx(e,n),fe(n,{code:oe.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()}else if(o.kind==="max"){if(e.data.getTime()>o.value)n=this._getOrReturnCtx(e,n),fe(n,{code:oe.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()}else it.assertNever(o);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new up({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:Se.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:Se.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e!=null?new Date(e):null}}up.create=(e)=>new up({checks:[],coerce:e?.coerce||!1,typeName:se.ZodDate,...We(e)});class zh extends Xe{_parse(e){if(this._getType(e)!==ge.symbol){let r=this._getOrReturnCtx(e);return fe(r,{code:oe.invalid_type,expected:ge.symbol,received:r.parsedType}),Le}return Wr(e.data)}}zh.create=(e)=>new zh({typeName:se.ZodSymbol,...We(e)});class dp extends Xe{_parse(e){if(this._getType(e)!==ge.undefined){let r=this._getOrReturnCtx(e);return fe(r,{code:oe.invalid_type,expected:ge.undefined,received:r.parsedType}),Le}return Wr(e.data)}}dp.create=(e)=>new dp({typeName:se.ZodUndefined,...We(e)});class lp extends Xe{_parse(e){if(this._getType(e)!==ge.null){let r=this._getOrReturnCtx(e);return fe(r,{code:oe.invalid_type,expected:ge.null,received:r.parsedType}),Le}return Wr(e.data)}}lp.create=(e)=>new lp({typeName:se.ZodNull,...We(e)});class Bh extends Xe{constructor(){super(...arguments);this._any=!0}_parse(e){return Wr(e.data)}}Bh.create=(e)=>new Bh({typeName:se.ZodAny,...We(e)});class Za extends Xe{constructor(){super(...arguments);this._unknown=!0}_parse(e){return Wr(e.data)}}Za.create=(e)=>new Za({typeName:se.ZodUnknown,...We(e)});class Oi extends Xe{_parse(e){let t=this._getOrReturnCtx(e);return fe(t,{code:oe.invalid_type,expected:ge.never,received:t.parsedType}),Le}}Oi.create=(e)=>new Oi({typeName:se.ZodNever,...We(e)});class Lh extends Xe{_parse(e){if(this._getType(e)!==ge.undefined){let r=this._getOrReturnCtx(e);return fe(r,{code:oe.invalid_type,expected:ge.void,received:r.parsedType}),Le}return Wr(e.data)}}Lh.create=(e)=>new Lh({typeName:se.ZodVoid,...We(e)});class Fo extends Xe{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==ge.array)return fe(t,{code:oe.invalid_type,expected:ge.array,received:t.parsedType}),Le;if(n.exactLength!==null){let i=t.data.length>n.exactLength.value,s=t.data.length<n.exactLength.value;if(i||s)fe(t,{code:i?oe.too_big:oe.too_small,minimum:s?n.exactLength.value:void 0,maximum:i?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty()}if(n.minLength!==null){if(t.data.length<n.minLength.value)fe(t,{code:oe.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()}if(n.maxLength!==null){if(t.data.length>n.maxLength.value)fe(t,{code:oe.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()}if(t.common.async)return Promise.all([...t.data].map((i,s)=>n.type._parseAsync(new uo(t,i,t.path,s)))).then((i)=>Br.mergeArray(r,i));let o=[...t.data].map((i,s)=>n.type._parseSync(new uo(t,i,t.path,s)));return Br.mergeArray(r,o)}get element(){return this._def.type}min(e,t){return new Fo({...this._def,minLength:{value:e,message:Se.toString(t)}})}max(e,t){return new Fo({...this._def,maxLength:{value:e,message:Se.toString(t)}})}length(e,t){return new Fo({...this._def,exactLength:{value:e,message:Se.toString(t)}})}nonempty(e){return this.min(1,e)}}Fo.create=(e,t)=>new Fo({type:e,minLength:null,maxLength:null,exactLength:null,typeName:se.ZodArray,...We(t)});function _u(e){if(e instanceof Xt){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=jo.create(_u(n))}return new Xt({...e._def,shape:()=>t})}else if(e instanceof Fo)return new Fo({...e._def,type:_u(e.element)});else if(e instanceof jo)return jo.create(_u(e.unwrap()));else if(e instanceof Ns)return Ns.create(_u(e.unwrap()));else if(e instanceof Ci)return Ci.create(e.items.map((t)=>_u(t)));else return e}class Xt extends Xe{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(),t=it.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==ge.object){let c=this._getOrReturnCtx(e);return fe(c,{code:oe.invalid_type,expected:ge.object,received:c.parsedType}),Le}let{status:r,ctx:n}=this._processInputParams(e),{shape:o,keys:i}=this._getCached(),s=[];if(!(this._def.catchall instanceof Oi&&this._def.unknownKeys==="strip")){for(let c in n.data)if(!i.includes(c))s.push(c)}let a=[];for(let c of i){let d=o[c],l=n.data[c];a.push({key:{status:"valid",value:c},value:d._parse(new uo(n,l,n.path,c)),alwaysSet:c in n.data})}if(this._def.catchall instanceof Oi){let c=this._def.unknownKeys;if(c==="passthrough")for(let d of s)a.push({key:{status:"valid",value:d},value:{status:"valid",value:n.data[d]}});else if(c==="strict"){if(s.length>0)fe(n,{code:oe.unrecognized_keys,keys:s}),r.dirty()}else if(c==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let d of s){let l=n.data[d];a.push({key:{status:"valid",value:d},value:c._parse(new uo(n,l,n.path,d)),alwaysSet:d in n.data})}}if(n.common.async)return Promise.resolve().then(async()=>{let c=[];for(let d of a){let l=await d.key,p=await d.value;c.push({key:l,value:p,alwaysSet:d.alwaysSet})}return c}).then((c)=>Br.mergeObjectSync(r,c));else return Br.mergeObjectSync(r,a)}get shape(){return this._def.shape()}strict(e){return Se.errToObj,new Xt({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{let n=this._def.errorMap?.(t,r).message??r.defaultError;if(t.code==="unrecognized_keys")return{message:Se.errToObj(e).message??n};return{message:n}}}:{}})}strip(){return new Xt({...this._def,unknownKeys:"strip"})}passthrough(){return new Xt({...this._def,unknownKeys:"passthrough"})}extend(e){return new Xt({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Xt({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:se.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Xt({...this._def,catchall:e})}pick(e){let t={};for(let r of it.objectKeys(e))if(e[r]&&this.shape[r])t[r]=this.shape[r];return new Xt({...this._def,shape:()=>t})}omit(e){let t={};for(let r of it.objectKeys(this.shape))if(!e[r])t[r]=this.shape[r];return new Xt({...this._def,shape:()=>t})}deepPartial(){return _u(this)}partial(e){let t={};for(let r of it.objectKeys(this.shape)){let n=this.shape[r];if(e&&!e[r])t[r]=n;else t[r]=n.optional()}return new Xt({...this._def,shape:()=>t})}required(e){let t={};for(let r of it.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let o=this.shape[r];while(o instanceof jo)o=o._def.innerType;t[r]=o}return new Xt({...this._def,shape:()=>t})}keyof(){return t2(it.objectKeys(this.shape))}}Xt.create=(e,t)=>new Xt({shape:()=>e,unknownKeys:"strip",catchall:Oi.create(),typeName:se.ZodObject,...We(t)});Xt.strictCreate=(e,t)=>new Xt({shape:()=>e,unknownKeys:"strict",catchall:Oi.create(),typeName:se.ZodObject,...We(t)});Xt.lazycreate=(e,t)=>new Xt({shape:e,unknownKeys:"strip",catchall:Oi.create(),typeName:se.ZodObject,...We(t)});class pp extends Xe{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function n(o){for(let s of o)if(s.result.status==="valid")return s.result;for(let s of o)if(s.result.status==="dirty")return t.common.issues.push(...s.ctx.common.issues),s.result;let i=o.map((s)=>new Pn(s.ctx.common.issues));return fe(t,{code:oe.invalid_union,unionErrors:i}),Le}if(t.common.async)return Promise.all(r.map(async(o)=>{let i={...t,common:{...t.common,issues:[]},parent:null};return{result:await o._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(n);else{let o=void 0,i=[];for(let a of r){let c={...t,common:{...t.common,issues:[]},parent:null},d=a._parseSync({data:t.data,path:t.path,parent:c});if(d.status==="valid")return d;else if(d.status==="dirty"&&!o)o={result:d,ctx:c};if(c.common.issues.length)i.push(c.common.issues)}if(o)return t.common.issues.push(...o.ctx.common.issues),o.result;let s=i.map((a)=>new Pn(a));return fe(t,{code:oe.invalid_union,unionErrors:s}),Le}}get options(){return this._def.options}}pp.create=(e,t)=>new pp({options:e,typeName:se.ZodUnion,...We(t)});var ki=(e)=>{if(e instanceof mp)return ki(e.schema);else if(e instanceof qo)return ki(e.innerType());else if(e instanceof hp)return[e.value];else if(e instanceof Wa)return e.options;else if(e instanceof gp)return it.objectValues(e.enum);else if(e instanceof yp)return ki(e._def.innerType);else if(e instanceof dp)return[void 0];else if(e instanceof lp)return[null];else if(e instanceof jo)return[void 0,...ki(e.unwrap())];else if(e instanceof Ns)return[null,...ki(e.unwrap())];else if(e instanceof P1)return ki(e.unwrap());else if(e instanceof xp)return ki(e.unwrap());else if(e instanceof bp)return ki(e._def.innerType);else return[]};class E1 extends Xe{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==ge.object)return fe(t,{code:oe.invalid_type,expected:ge.object,received:t.parsedType}),Le;let r=this.discriminator,n=t.data[r],o=this.optionsMap.get(n);if(!o)return fe(t,{code:oe.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Le;if(t.common.async)return o._parseAsync({data:t.data,path:t.path,parent:t});else return o._parseSync({data:t.data,path:t.path,parent:t})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let n=new Map;for(let o of t){let i=ki(o.shape[e]);if(!i.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let s of i){if(n.has(s))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);n.set(s,o)}}return new E1({typeName:se.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...We(r)})}}function T1(e,t){let r=Ii(e),n=Ii(t);if(e===t)return{valid:!0,data:e};else if(r===ge.object&&n===ge.object){let o=it.objectKeys(t),i=it.objectKeys(e).filter((a)=>o.indexOf(a)!==-1),s={...e,...t};for(let a of i){let c=T1(e[a],t[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===ge.array&&n===ge.array){if(e.length!==t.length)return{valid:!1};let o=[];for(let i=0;i<e.length;i++){let s=e[i],a=t[i],c=T1(s,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else if(r===ge.date&&n===ge.date&&+e===+t)return{valid:!0,data:e};else return{valid:!1}}class fp extends Xe{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=(o,i)=>{if(w1(o)||w1(i))return Le;let s=T1(o.value,i.value);if(!s.valid)return fe(r,{code:oe.invalid_intersection_types}),Le;if(S1(o)||S1(i))t.dirty();return{status:t.value,value:s.data}};if(r.common.async)return Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,i])=>n(o,i));else return n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}fp.create=(e,t,r)=>new fp({left:e,right:t,typeName:se.ZodIntersection,...We(r)});class Ci extends Xe{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ge.array)return fe(r,{code:oe.invalid_type,expected:ge.array,received:r.parsedType}),Le;if(r.data.length<this._def.items.length)return fe(r,{code:oe.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Le;if(!this._def.rest&&r.data.length>this._def.items.length)fe(r,{code:oe.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty();let o=[...r.data].map((i,s)=>{let a=this._def.items[s]||this._def.rest;if(!a)return null;return a._parse(new uo(r,i,r.path,s))}).filter((i)=>!!i);if(r.common.async)return Promise.all(o).then((i)=>Br.mergeArray(t,i));else return Br.mergeArray(t,o)}get items(){return this._def.items}rest(e){return new Ci({...this._def,rest:e})}}Ci.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ci({items:e,typeName:se.ZodTuple,rest:null,...We(t)})};class Dh extends Xe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ge.object)return fe(r,{code:oe.invalid_type,expected:ge.object,received:r.parsedType}),Le;let n=[],o=this._def.keyType,i=this._def.valueType;for(let s in r.data)n.push({key:o._parse(new uo(r,s,r.path,s)),value:i._parse(new uo(r,r.data[s],r.path,s)),alwaysSet:s in r.data});if(r.common.async)return Br.mergeObjectAsync(t,n);else return Br.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){if(t instanceof Xe)return new Dh({keyType:e,valueType:t,typeName:se.ZodRecord,...We(r)});return new Dh({keyType:Ri.create(),valueType:e,typeName:se.ZodRecord,...We(t)})}}class Uh extends Xe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ge.map)return fe(r,{code:oe.invalid_type,expected:ge.map,received:r.parsedType}),Le;let n=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map(([s,a],c)=>({key:n._parse(new uo(r,s,r.path,[c,"key"])),value:o._parse(new uo(r,a,r.path,[c,"value"]))}));if(r.common.async){let s=new Map;return Promise.resolve().then(async()=>{for(let a of i){let c=await a.key,d=await a.value;if(c.status==="aborted"||d.status==="aborted")return Le;if(c.status==="dirty"||d.status==="dirty")t.dirty();s.set(c.value,d.value)}return{status:t.value,value:s}})}else{let s=new Map;for(let a of i){let{key:c,value:d}=a;if(c.status==="aborted"||d.status==="aborted")return Le;if(c.status==="dirty"||d.status==="dirty")t.dirty();s.set(c.value,d.value)}return{status:t.value,value:s}}}}Uh.create=(e,t,r)=>new Uh({valueType:t,keyType:e,typeName:se.ZodMap,...We(r)});class vu extends Xe{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ge.set)return fe(r,{code:oe.invalid_type,expected:ge.set,received:r.parsedType}),Le;let n=this._def;if(n.minSize!==null){if(r.data.size<n.minSize.value)fe(r,{code:oe.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()}if(n.maxSize!==null){if(r.data.size>n.maxSize.value)fe(r,{code:oe.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty()}let o=this._def.valueType;function i(a){let c=new Set;for(let d of a){if(d.status==="aborted")return Le;if(d.status==="dirty")t.dirty();c.add(d.value)}return{status:t.value,value:c}}let s=[...r.data.values()].map((a,c)=>o._parse(new uo(r,a,r.path,c)));if(r.common.async)return Promise.all(s).then((a)=>i(a));else return i(s)}min(e,t){return new vu({...this._def,minSize:{value:e,message:Se.toString(t)}})}max(e,t){return new vu({...this._def,maxSize:{value:e,message:Se.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}vu.create=(e,t)=>new vu({valueType:e,minSize:null,maxSize:null,typeName:se.ZodSet,...We(t)});class cp extends Xe{constructor(){super(...arguments);this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==ge.function)return fe(t,{code:oe.invalid_type,expected:ge.function,received:t.parsedType}),Le;function r(s,a){return $h({data:s,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,sp(),$s].filter((c)=>!!c),issueData:{code:oe.invalid_arguments,argumentsError:a}})}function n(s,a){return $h({data:s,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,sp(),$s].filter((c)=>!!c),issueData:{code:oe.invalid_return_type,returnTypeError:a}})}let o={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof Tu){let s=this;return Wr(async function(...a){let c=new Pn([]),d=await s._def.args.parseAsync(a,o).catch((m)=>{throw c.addIssue(r(a,m)),c}),l=await Reflect.apply(i,this,d);return await s._def.returns._def.type.parseAsync(l,o).catch((m)=>{throw c.addIssue(n(l,m)),c})})}else{let s=this;return Wr(function(...a){let c=s._def.args.safeParse(a,o);if(!c.success)throw new Pn([r(a,c.error)]);let d=Reflect.apply(i,this,c.data),l=s._def.returns.safeParse(d,o);if(!l.success)throw new Pn([n(d,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new cp({...this._def,args:Ci.create(e).rest(Za.create())})}returns(e){return new cp({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new cp({args:e?e:Ci.create([]).rest(Za.create()),returns:t||Za.create(),typeName:se.ZodFunction,...We(r)})}}class mp extends Xe{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})}}mp.create=(e,t)=>new mp({getter:e,typeName:se.ZodLazy,...We(t)});class hp extends Xe{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return fe(t,{received:t.data,code:oe.invalid_literal,expected:this._def.value}),Le}return{status:"valid",value:e.data}}get value(){return this._def.value}}hp.create=(e,t)=>new hp({value:e,typeName:se.ZodLiteral,...We(t)});function t2(e,t){return new Wa({values:e,typeName:se.ZodEnum,...We(t)})}class Wa extends Xe{_parse(e){if(typeof e.data!=="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return fe(t,{expected:it.joinValues(r),received:t.parsedType,code:oe.invalid_type}),Le}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return fe(t,{received:t.data,code:oe.invalid_enum_value,options:r}),Le}return Wr(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(e,t=this._def){return Wa.create(e,{...this._def,...t})}exclude(e,t=this._def){return Wa.create(this.options.filter((r)=>!e.includes(r)),{...this._def,...t})}}Wa.create=t2;class gp extends Xe{_parse(e){let t=it.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==ge.string&&r.parsedType!==ge.number){let n=it.objectValues(t);return fe(r,{expected:it.joinValues(n),received:r.parsedType,code:oe.invalid_type}),Le}if(!this._cache)this._cache=new Set(it.getValidEnumValues(this._def.values));if(!this._cache.has(e.data)){let n=it.objectValues(t);return fe(r,{received:r.data,code:oe.invalid_enum_value,options:n}),Le}return Wr(e.data)}get enum(){return this._def.values}}gp.create=(e,t)=>new gp({values:e,typeName:se.ZodNativeEnum,...We(t)});class Tu extends Xe{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==ge.promise&&t.common.async===!1)return fe(t,{code:oe.invalid_type,expected:ge.promise,received:t.parsedType}),Le;let r=t.parsedType===ge.promise?t.data:Promise.resolve(t.data);return Wr(r.then((n)=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Tu.create=(e,t)=>new Tu({type:e,typeName:se.ZodPromise,...We(t)});class qo extends Xe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===se.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,o={addIssue:(i)=>{if(fe(r,i),i.fatal)t.abort();else t.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),n.type==="preprocess"){let i=n.transform(r.data,o);if(r.common.async)return Promise.resolve(i).then(async(s)=>{if(t.value==="aborted")return Le;let a=await this._def.schema._parseAsync({data:s,path:r.path,parent:r});if(a.status==="aborted")return Le;if(a.status==="dirty")return xu(a.value);if(t.value==="dirty")return xu(a.value);return a});else{if(t.value==="aborted")return Le;let s=this._def.schema._parseSync({data:i,path:r.path,parent:r});if(s.status==="aborted")return Le;if(s.status==="dirty")return xu(s.value);if(t.value==="dirty")return xu(s.value);return s}}if(n.type==="refinement"){let i=(s)=>{let a=n.refinement(s,o);if(r.common.async)return Promise.resolve(a);if(a instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(r.common.async===!1){let s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(s.status==="aborted")return Le;if(s.status==="dirty")t.dirty();return i(s.value),{status:t.value,value:s.value}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((s)=>{if(s.status==="aborted")return Le;if(s.status==="dirty")t.dirty();return i(s.value).then(()=>({status:t.value,value:s.value}))})}if(n.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Va(i))return Le;let s=n.transform(i.value,o);if(s instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:s}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((i)=>{if(!Va(i))return Le;return Promise.resolve(n.transform(i.value,o)).then((s)=>({status:t.value,value:s}))});it.assertNever(n)}}qo.create=(e,t,r)=>new qo({schema:e,typeName:se.ZodEffects,effect:t,...We(r)});qo.createWithPreprocess=(e,t,r)=>new qo({schema:t,effect:{type:"preprocess",transform:e},typeName:se.ZodEffects,...We(r)});class jo extends Xe{_parse(e){if(this._getType(e)===ge.undefined)return Wr(void 0);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}jo.create=(e,t)=>new jo({innerType:e,typeName:se.ZodOptional,...We(t)});class Ns extends Xe{_parse(e){if(this._getType(e)===ge.null)return Wr(null);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ns.create=(e,t)=>new Ns({innerType:e,typeName:se.ZodNullable,...We(t)});class yp extends Xe{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;if(t.parsedType===ge.undefined)r=this._def.defaultValue();return this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}yp.create=(e,t)=>new yp({innerType:e,typeName:se.ZodDefault,defaultValue:typeof t.default==="function"?t.default:()=>t.default,...We(t)});class bp extends Xe{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});if(ap(n))return n.then((o)=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Pn(r.common.issues)},input:r.data})}));else return{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new Pn(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}bp.create=(e,t)=>new bp({innerType:e,typeName:se.ZodCatch,catchValue:typeof t.catch==="function"?t.catch:()=>t.catch,...We(t)});class Fh extends Xe{_parse(e){if(this._getType(e)!==ge.nan){let r=this._getOrReturnCtx(e);return fe(r,{code:oe.invalid_type,expected:ge.nan,received:r.parsedType}),Le}return{status:"valid",value:e.data}}}Fh.create=(e)=>new Fh({typeName:se.ZodNaN,...We(e)});var Ume=Symbol("zod_brand");class P1 extends Xe{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class jh extends Xe{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});if(o.status==="aborted")return Le;if(o.status==="dirty")return t.dirty(),xu(o.value);else return this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();else{let n=this._def.in._parseSync({data:r.data,path:r.path,parent:r});if(n.status==="aborted")return Le;if(n.status==="dirty")return t.dirty(),{status:"dirty",value:n.value};else return this._def.out._parseSync({data:n.value,path:r.path,parent:r})}}static create(e,t){return new jh({in:e,out:t,typeName:se.ZodPipeline})}}class xp extends Xe{_parse(e){let t=this._def.innerType._parse(e),r=(n)=>{if(Va(n))n.value=Object.freeze(n.value);return n};return ap(t)?t.then((n)=>r(n)):r(t)}unwrap(){return this._def.innerType}}xp.create=(e,t)=>new xp({innerType:e,typeName:se.ZodReadonly,...We(t)});var Fme={object:Xt.lazycreate},se;(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"})(se||(se={}));var jme=Ri.create,qme=wu.create,Hme=Fh.create,Gme=Su.create,Vme=Nh.create,Zme=up.create,Wme=zh.create,Kme=dp.create,Yme=lp.create,Jme=Bh.create,Qme=Za.create,Xme=Oi.create,ehe=Lh.create,the=Fo.create,{create:r2,strictCreate:rhe}=Xt,nhe=pp.create,ohe=E1.create,ihe=fp.create,she=Ci.create,ahe=Dh.create,che=Uh.create,uhe=vu.create,dhe=cp.create,lhe=mp.create,phe=hp.create,fhe=Wa.create,mhe=gp.create,hhe=Tu.create,ghe=qo.create,yhe=jo.create,bhe=Ns.create,xhe=qo.createWithPreprocess,_he=jh.create;var n2;function D(e,t,r){function n(a,c){if(!a._zod)Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1});if(a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,c);let d=s.prototype,l=Object.keys(d);for(let p=0;p<l.length;p++){let m=l[p];if(!(m in a))a[m]=d[m].bind(a)}}let o=r?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(a){var c;let d=r?.Parent?new i:this;n(d,a),(c=d._zod).deferred??(c.deferred=[]);for(let l of d._zod.deferred)l();return d}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:(a)=>{if(r?.Parent&&a instanceof r.Parent)return!0;return a?._zod?.traits?.has(e)}}),Object.defineProperty(s,"name",{value:e}),s}var She=Symbol("zod_brand");class Mi extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class _p extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(n2=globalThis).__zod_globalConfig??(n2.__zod_globalConfig={});var Eu=globalThis.__zod_globalConfig;function An(e){if(e)Object.assign(Eu,e);return Eu}function Hh(e){let t=Object.values(e).filter((n)=>typeof n==="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function I1(e,t="|"){return e.map((r)=>O1(r)).join(t)}function wp(e,t){if(typeof t==="bigint")return t.toString();return t}function Sp(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw Error("cached value already set")}}}function Gh(e){return e===null||e===void 0}function Vh(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function i2(e,t){let r=e/t,n=Math.round(r),o=Number.EPSILON*Math.max(Math.abs(r),1);if(Math.abs(r-n)<o)return 0;return r-n}var o2=Symbol("evaluating");function _t(e,t,r){let n=void 0;Object.defineProperty(e,t,{get(){if(n===o2)return;if(n===void 0)n=o2,n=r();return n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Ka(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function zs(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function k1(e){return JSON.stringify(e)}function s2(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var R1="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Pu(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var a2=Sp(()=>{if(Eu.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Ya(e){if(Pu(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let r=t.prototype;if(Pu(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)return!1;return!0}function Zh(e){if(Ya(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var c2=new Set(["string","number","symbol"]);function Bs(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jn(e,t,r){let n=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)n._zod.parent=e;return n}function xe(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function O1(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function u2(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var d2={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function l2(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let i=zs(e._zod.def,{get shape(){let s={};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;s[a]=r.shape[a]}return Ka(this,"shape",s),s},checks:[]});return jn(e,i)}function p2(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let i=zs(e._zod.def,{get shape(){let s={...e._zod.def.shape};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;delete s[a]}return Ka(this,"shape",s),s},checks:[]});return jn(e,i)}function f2(e,t){if(!Ya(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let i=e._zod.def.shape;for(let s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=zs(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return Ka(this,"shape",i),i}});return jn(e,o)}function m2(e,t){if(!Ya(t))throw Error("Invalid input to safeExtend: expected a plain object");let r=zs(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Ka(this,"shape",n),n}});return jn(e,r)}function _Z(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=zs(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Ka(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return jn(e,r)}function h2(e,t,r){let o=t._zod.def.checks;if(o&&o.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let s=zs(t._zod.def,{get shape(){let a=t._zod.def.shape,c={...a};if(r)for(let d in r){if(!(d in a))throw Error(`Unrecognized key: "${d}"`);if(!r[d])continue;c[d]=e?new e({type:"optional",innerType:a[d]}):a[d]}else for(let d in a)c[d]=e?new e({type:"optional",innerType:a[d]}):a[d];return Ka(this,"shape",c),c},checks:[]});return jn(t,s)}function g2(e,t,r){let n=zs(t._zod.def,{get shape(){let o=t._zod.def.shape,i={...o};if(r)for(let s in r){if(!(s in i))throw Error(`Unrecognized key: "${s}"`);if(!r[s])continue;i[s]=new e({type:"nonoptional",innerType:o[s]})}else for(let s in o)i[s]=new e({type:"nonoptional",innerType:o[s]});return Ka(this,"shape",i),i}});return jn(t,n)}function Ja(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function y2(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function Ls(e,t){return t.map((r)=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function qh(e){return typeof e==="string"?e:e?.message}function lo(e,t,r){let n=e.message?e.message:qh(e.inst?._zod.def?.error?.(e))??qh(t?.error?.(e))??qh(r.customError?.(e))??qh(r.localeError?.(e))??"Invalid input",{inst:o,continue:i,input:s,...a}=e;if(a.path??(a.path=[]),a.message=n,t?.reportInput)a.input=s;return a}function Wh(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function b2(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function Qa(...e){let[t,r,n]=e;if(typeof t==="string")return{message:t,code:"custom",input:r,inst:n};return{...t}}var x2=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,wp,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Kh=D("$ZodError",x2),vp=D("$ZodError",x2,{Parent:Error});function _2(e,t=(r)=>r.message){let r={},n=[];for(let o of e.issues)if(o.path.length>0)r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o));else n.push(t(o));return{formErrors:n,fieldErrors:r}}function w2(e,t=(r)=>r.message){let r={_errors:[]},n=(o,i=[])=>{for(let s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map((a)=>n({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")n({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")n({issues:s.issues},[...i,...s.path]);else{let a=[...i,...s.path];if(a.length===0)r._errors.push(t(s));else{let c=r,d=0;while(d<a.length){let l=a[d];if(d!==a.length-1)c[l]=c[l]||{_errors:[]};else c[l]=c[l]||{_errors:[]},c[l]._errors.push(t(s));c=c[l],d++}}}};return n(e),r}var Tp=(e)=>(t,r,n,o)=>{let i=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new Mi;if(s.issues.length){let a=new(o?.Err??e)(s.issues.map((c)=>lo(c,i,An())));throw R1(a,o?.callee),a}return s.value},Yh=Tp(vp),Ep=(e)=>async(t,r,n,o)=>{let i=n?{...n,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)s=await s;if(s.issues.length){let a=new(o?.Err??e)(s.issues.map((c)=>lo(c,i,An())));throw R1(a,o?.callee),a}return s.value},Jh=Ep(vp),Pp=(e)=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new Mi;return i.issues.length?{success:!1,error:new(e??Kh)(i.issues.map((s)=>lo(s,o,An())))}:{success:!0,data:i.value}},Xa=Pp(vp),Ap=(e)=>async(t,r,n)=>{let o=n?{...n,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)i=await i;return i.issues.length?{success:!1,error:new e(i.issues.map((s)=>lo(s,o,An())))}:{success:!0,data:i.value}},ec=Ap(vp),S2=(e)=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Tp(e)(t,r,o)};var v2=(e)=>(t,r,n)=>Tp(e)(t,r,n);var T2=(e)=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Ep(e)(t,r,o)};var E2=(e)=>async(t,r,n)=>Ep(e)(t,r,n);var P2=(e)=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Pp(e)(t,r,o)};var A2=(e)=>(t,r,n)=>Pp(e)(t,r,n);var I2=(e)=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Ap(e)(t,r,o)};var k2=(e)=>async(t,r,n)=>Ap(e)(t,r,n);var R2=/^[cC][0-9a-z]{6,}$/,O2=/^[0-9a-z]+$/,C2=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,M2=/^[0-9a-vA-V]{20}$/,$2=/^[A-Za-z0-9]{27}$/,N2=/^[a-zA-Z0-9_-]{21}$/,z2=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var B2=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,C1=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var L2=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var SZ="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function D2(){return new RegExp(SZ,"u")}var U2=/^(?:(?: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])$/,F2=/^(([0-9a-fA-F]{1,4}:){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}|:))$/;var j2=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,q2=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,H2=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,M1=/^[A-Za-z0-9_-]*$/;var G2=/^https?$/,V2=/^\+[1-9]\d{6,14}$/,Z2="(?:(?:\\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])))",W2=new RegExp(`^${Z2}$`);function K2(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function Y2(e){return new RegExp(`^${K2(e)}$`)}function J2(e){let t=K2({precision:e.precision}),r=["Z"];if(e.local)r.push("");if(e.offset)r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${Z2}T(?:${n})$`)}var Q2=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},X2=/^-?\d+n?$/,e6=/^-?\d+$/,$1=/^-?\d+(?:\.\d+)?$/,t6=/^(?:true|false)$/i,r6=/^null$/i;var n6=/^[^A-Z]*$/,o6=/^[^a-z]*$/;var yr=D("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),i6={number:"number",bigint:"bigint",object:"date"},N1=D("$ZodCheckLessThan",(e,t)=>{yr.init(e,t);let r=i6[typeof t.value];e._zod.onattach.push((n)=>{let o=n._zod.bag,i=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<i)if(t.inclusive)o.maximum=t.value;else o.exclusiveMaximum=t.value}),e._zod.check=(n)=>{if(t.inclusive?n.value<=t.value:n.value<t.value)return;n.issues.push({origin:r,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),z1=D("$ZodCheckGreaterThan",(e,t)=>{yr.init(e,t);let r=i6[typeof t.value];e._zod.onattach.push((n)=>{let o=n._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>i)if(t.inclusive)o.minimum=t.value;else o.exclusiveMinimum=t.value}),e._zod.check=(n)=>{if(t.inclusive?n.value>=t.value:n.value>t.value)return;n.issues.push({origin:r,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),s6=D("$ZodCheckMultipleOf",(e,t)=>{yr.init(e,t),e._zod.onattach.push((r)=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=(r)=>{if(typeof r.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof r.value==="bigint"?r.value%t.value===BigInt(0):i2(r.value,t.value)===0)return;r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),a6=D("$ZodCheckNumberFormat",(e,t)=>{yr.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,i]=d2[t.format];e._zod.onattach.push((s)=>{let a=s._zod.bag;if(a.format=t.format,a.minimum=o,a.maximum=i,r)a.pattern=e6}),e._zod.check=(s)=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});else s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}if(a<o)s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort});if(a>i)s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}});var c6=D("$ZodCheckMaxLength",(e,t)=>{var r;yr.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!Gh(o)&&o.length!==void 0}),e._zod.onattach.push((n)=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<o)n._zod.bag.maximum=t.maximum}),e._zod.check=(n)=>{let o=n.value;if(o.length<=t.maximum)return;let s=Wh(o);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),u6=D("$ZodCheckMinLength",(e,t)=>{var r;yr.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!Gh(o)&&o.length!==void 0}),e._zod.onattach.push((n)=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>o)n._zod.bag.minimum=t.minimum}),e._zod.check=(n)=>{let o=n.value;if(o.length>=t.minimum)return;let s=Wh(o);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),d6=D("$ZodCheckLengthEquals",(e,t)=>{var r;yr.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!Gh(o)&&o.length!==void 0}),e._zod.onattach.push((n)=>{let o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=(n)=>{let o=n.value,i=o.length;if(i===t.length)return;let s=Wh(o),a=i>t.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),kp=D("$ZodCheckStringFormat",(e,t)=>{var r,n;if(yr.init(e,t),e._zod.onattach.push((o)=>{let i=o._zod.bag;if(i.format=t.format,t.pattern)i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern)}),t.pattern)(r=e._zod).check??(r.check=(o)=>{if(t.pattern.lastIndex=0,t.pattern.test(o.value))return;o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(n=e._zod).check??(n.check=()=>{})}),l6=D("$ZodCheckRegex",(e,t)=>{kp.init(e,t),e._zod.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),p6=D("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=n6),kp.init(e,t)}),f6=D("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=o6),kp.init(e,t)}),m6=D("$ZodCheckIncludes",(e,t)=>{yr.init(e,t);let r=Bs(t.includes),n=new RegExp(typeof t.position==="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push((o)=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=(o)=>{if(o.value.includes(t.includes,t.position))return;o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),h6=D("$ZodCheckStartsWith",(e,t)=>{yr.init(e,t);let r=new RegExp(`^${Bs(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push((n)=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=(n)=>{if(n.value.startsWith(t.prefix))return;n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),g6=D("$ZodCheckEndsWith",(e,t)=>{yr.init(e,t);let r=new RegExp(`.*${Bs(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push((n)=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=(n)=>{if(n.value.endsWith(t.suffix))return;n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});var y6=D("$ZodCheckOverwrite",(e,t)=>{yr.init(e,t),e._zod.check=(r)=>{r.value=t.tx(r.value)}});class B1{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
67
+ `),n=!1,o=!1,i;e.on("response",(s)=>{let{headers:a}=s;n=a["transfer-encoding"]==="chunked"&&!a["content-length"]}),e.on("socket",(s)=>{let a=()=>{if(n&&!o){let d=Error("Premature close");d.code="ERR_STREAM_PREMATURE_CLOSE",t(d)}},c=(d)=>{if(o=xh.compare(d.slice(-5),r)===0,!o&&i)o=xh.compare(i.slice(-3),r.slice(0,3))===0&&xh.compare(d.slice(-2),r.slice(3))===0;i=d};s.prependListener("close",a),s.on("data",c),e.on("close",()=>{s.removeListener("close",a),s.removeListener("data",c)})})}var qV=Vr(HR(),1),HV=Vr(Ih(),1),GV=Vr(fu(),1),VV=Vr(l1(),1),ZV=Vr(f1(),1),WV=Vr(x1(),1),_1=Vr(Ch(),1),KV=Vr(YR(),1);var it;(function(e){e.assertEqual=(o)=>{};function t(o){}e.assertIs=t;function r(o){throw Error()}e.assertNever=r,e.arrayToEnum=(o)=>{let i={};for(let s of o)i[s]=s;return i},e.getValidEnumValues=(o)=>{let i=e.objectKeys(o).filter((a)=>typeof o[o[a]]!=="number"),s={};for(let a of i)s[a]=o[a];return e.objectValues(s)},e.objectValues=(o)=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys==="function"?(o)=>Object.keys(o):(o)=>{let i=[];for(let s in o)if(Object.prototype.hasOwnProperty.call(o,s))i.push(s);return i},e.find=(o,i)=>{for(let s of o)if(i(s))return s;return},e.isInteger=typeof Number.isInteger==="function"?(o)=>Number.isInteger(o):(o)=>typeof o==="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,i=" | "){return o.map((s)=>typeof s==="string"?`'${s}'`:s).join(i)}e.joinValues=n,e.jsonStringifyReplacer=(o,i)=>{if(typeof i==="bigint")return i.toString();return i}})(it||(it={}));var JR;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(JR||(JR={}));var ge=it.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ii=(e)=>{switch(typeof e){case"undefined":return ge.undefined;case"string":return ge.string;case"number":return Number.isNaN(e)?ge.nan:ge.number;case"boolean":return ge.boolean;case"function":return ge.function;case"bigint":return ge.bigint;case"symbol":return ge.symbol;case"object":if(Array.isArray(e))return ge.array;if(e===null)return ge.null;if(e.then&&typeof e.then==="function"&&e.catch&&typeof e.catch==="function")return ge.promise;if(typeof Map<"u"&&e instanceof Map)return ge.map;if(typeof Set<"u"&&e instanceof Set)return ge.set;if(typeof Date<"u"&&e instanceof Date)return ge.date;return ge.object;default:return ge.unknown}};var oe=it.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"]);class Pn extends Error{get errors(){return this.issues}constructor(e){super();this.issues=[],this.addIssue=(r)=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let t=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,t);else this.__proto__=t;this.name="ZodError",this.issues=e}format(e){let t=e||function(o){return o.message},r={_errors:[]},n=(o)=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(n);else if(i.code==="invalid_return_type")n(i.returnTypeError);else if(i.code==="invalid_arguments")n(i.argumentsError);else if(i.path.length===0)r._errors.push(t(i));else{let s=r,a=0;while(a<i.path.length){let c=i.path[a];if(a!==i.path.length-1)s[c]=s[c]||{_errors:[]};else s[c]=s[c]||{_errors:[]},s[c]._errors.push(t(i));s=s[c],a++}}};return n(this),r}static assert(e){if(!(e instanceof Pn))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,it.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=(t)=>t.message){let t=Object.create(null),r=[];for(let n of this.issues)if(n.path.length>0){let o=n.path[0];t[o]=t[o]||[],t[o].push(e(n))}else r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}Pn.create=(e)=>new Pn(e);var YV=(e,t)=>{let r;switch(e.code){case oe.invalid_type:if(e.received===ge.undefined)r="Required";else r=`Expected ${e.expected}, received ${e.received}`;break;case oe.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,it.jsonStringifyReplacer)}`;break;case oe.unrecognized_keys:r=`Unrecognized key(s) in object: ${it.joinValues(e.keys,", ")}`;break;case oe.invalid_union:r="Invalid input";break;case oe.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${it.joinValues(e.options)}`;break;case oe.invalid_enum_value:r=`Invalid enum value. Expected ${it.joinValues(e.options)}, received '${e.received}'`;break;case oe.invalid_arguments:r="Invalid function arguments";break;case oe.invalid_return_type:r="Invalid function return type";break;case oe.invalid_date:r="Invalid date";break;case oe.invalid_string:if(typeof e.validation==="object")if("includes"in e.validation){if(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==="number")r=`${r} at one or more positions greater than or equal to ${e.validation.position}`}else if("startsWith"in e.validation)r=`Invalid input: must start with "${e.validation.startsWith}"`;else if("endsWith"in e.validation)r=`Invalid input: must end with "${e.validation.endsWith}"`;else it.assertNever(e.validation);else if(e.validation!=="regex")r=`Invalid ${e.validation}`;else r="Invalid";break;case oe.too_small:if(e.type==="array")r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`;else if(e.type==="string")r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`;else if(e.type==="number")r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="bigint")r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="date")r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`;else r="Invalid input";break;case oe.too_big:if(e.type==="array")r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`;else if(e.type==="string")r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`;else if(e.type==="number")r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="bigint")r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="date")r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`;else r="Invalid input";break;case oe.custom:r="Invalid input";break;case oe.invalid_intersection_types:r="Intersection results could not be merged";break;case oe.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case oe.not_finite:r="Number must be finite";break;default:r=t.defaultError,it.assertNever(e)}return{message:r}},$s=YV;var JV=$s;function sp(){return JV}var $h=(e)=>{let{data:t,path:r,errorMaps:n,issueData:o}=e,i=[...r,...o.path||[]],s={...o,path:i};if(o.message!==void 0)return{...o,path:i,message:o.message};let a="",c=n.filter((d)=>!!d).slice().reverse();for(let d of c)a=d(s,{data:t,defaultError:a}).message;return{...o,path:i,message:a}};function fe(e,t){let r=sp(),n=$h({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===$s?void 0:$s].filter((o)=>!!o)});e.common.issues.push(n)}class Br{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(e,t){let r=[];for(let n of t){if(n.status==="aborted")return Le;if(n.status==="dirty")e.dirty();r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let n of t){let o=await n.key,i=await n.value;r.push({key:o,value:i})}return Br.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let n of t){let{key:o,value:i}=n;if(o.status==="aborted")return Le;if(i.status==="aborted")return Le;if(o.status==="dirty")e.dirty();if(i.status==="dirty")e.dirty();if(o.value!=="__proto__"&&(typeof i.value<"u"||n.alwaysSet))r[o.value]=i.value}return{status:e.value,value:r}}}var Le=Object.freeze({status:"aborted"}),xu=(e)=>({status:"dirty",value:e}),Wr=(e)=>({status:"valid",value:e}),w1=(e)=>e.status==="aborted",S1=(e)=>e.status==="dirty",Va=(e)=>e.status==="valid",ap=(e)=>typeof Promise<"u"&&e instanceof Promise;var ve;(function(e){e.errToObj=(t)=>typeof t==="string"?{message:t}:t||{},e.toString=(t)=>typeof t==="string"?t:t?.message})(ve||(ve={}));class uo{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var QR=(e,t)=>{if(Va(t))return{success:!0,data:t.value};else{if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Pn(e.common.issues);return this._error=r,this._error}}}};function We(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:o}=e;if(t&&(r||n))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(t)return{errorMap:t,description:o};return{errorMap:(s,a)=>{let{message:c}=e;if(s.code==="invalid_enum_value")return{message:c??a.defaultError};if(typeof a.data>"u")return{message:c??n??a.defaultError};if(s.code!=="invalid_type")return{message:a.defaultError};return{message:c??r??a.defaultError}},description:o}}class Xe{get description(){return this._def.description}_getType(e){return Ii(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Ii(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Br,ctx:{common:e.parent.common,data:e.data,parsedType:Ii(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(ap(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ii(e)},n=this._parseSync({data:e,path:r.path,parent:r});return QR(r,n)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ii(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return Va(r)?{value:r.value}:{issues:t.common.issues}}catch(r){if(r?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then((r)=>Va(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ii(e)},n=this._parse({data:e,path:r.path,parent:r}),o=await(ap(n)?n:Promise.resolve(n));return QR(r,o)}refine(e,t){let r=(n)=>{if(typeof t==="string"||typeof t>"u")return{message:t};else if(typeof t==="function")return t(n);else return t};return this._refinement((n,o)=>{let i=e(n),s=()=>o.addIssue({code:oe.custom,...r(n)});if(typeof Promise<"u"&&i instanceof Promise)return i.then((a)=>{if(!a)return s(),!1;else return!0});if(!i)return s(),!1;else return!0})}refinement(e,t){return this._refinement((r,n)=>{if(!e(r))return n.addIssue(typeof t==="function"?t(r,n):t),!1;else return!0})}_refinement(e){return new qo({schema:this,typeName:se.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:(t)=>this["~validate"](t)}}optional(){return jo.create(this,this._def)}nullable(){return Ns.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Fo.create(this)}promise(){return Tu.create(this,this._def)}or(e){return pp.create([this,e],this._def)}and(e){return fp.create(this,e,this._def)}transform(e){return new qo({...We(this._def),schema:this,typeName:se.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e==="function"?e:()=>e;return new yp({...We(this._def),innerType:this,defaultValue:t,typeName:se.ZodDefault})}brand(){return new P1({typeName:se.ZodBranded,type:this,...We(this._def)})}catch(e){let t=typeof e==="function"?e:()=>e;return new bp({...We(this._def),innerType:this,catchValue:t,typeName:se.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return jh.create(this,e)}readonly(){return xp.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var QV=/^c[^\s-]{8,}$/i,XV=/^[0-9a-z]+$/,eZ=/^[0-9A-HJKMNP-TV-Z]{26}$/i,tZ=/^[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,rZ=/^[a-z0-9_-]{21}$/i,nZ=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,oZ=/^[-+]?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)?)??$/,iZ=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,sZ="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",v1,aZ=/^(?:(?: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])$/,cZ=/^(?:(?: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])$/,uZ=/^(([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]))$/,dZ=/^(([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])$/,lZ=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,pZ=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,XR="((\\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])))",fZ=new RegExp(`^${XR}$`);function e2(e){let t="[0-5]\\d";if(e.precision)t=`${t}\\.\\d{${e.precision}}`;else if(e.precision==null)t=`${t}(\\.\\d+)?`;let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function mZ(e){return new RegExp(`^${e2(e)}$`)}function hZ(e){let t=`${XR}T${e2(e)}`,r=[];if(r.push(e.local?"Z?":"Z"),e.offset)r.push("([+-]\\d{2}:?\\d{2})");return t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function gZ(e,t){if((t==="v4"||!t)&&aZ.test(e))return!0;if((t==="v6"||!t)&&uZ.test(e))return!0;return!1}function yZ(e,t){if(!nZ.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));if(typeof o!=="object"||o===null)return!1;if("typ"in o&&o?.typ!=="JWT")return!1;if(!o.alg)return!1;if(t&&o.alg!==t)return!1;return!0}catch{return!1}}function bZ(e,t){if((t==="v4"||!t)&&cZ.test(e))return!0;if((t==="v6"||!t)&&dZ.test(e))return!0;return!1}class Ri extends Xe{_parse(e){if(this._def.coerce)e.data=String(e.data);if(this._getType(e)!==ge.string){let o=this._getOrReturnCtx(e);return fe(o,{code:oe.invalid_type,expected:ge.string,received:o.parsedType}),Le}let r=new Br,n=void 0;for(let o of this._def.checks)if(o.kind==="min"){if(e.data.length<o.value)n=this._getOrReturnCtx(e,n),fe(n,{code:oe.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty()}else if(o.kind==="max"){if(e.data.length>o.value)n=this._getOrReturnCtx(e,n),fe(n,{code:oe.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty()}else if(o.kind==="length"){let i=e.data.length>o.value,s=e.data.length<o.value;if(i||s){if(n=this._getOrReturnCtx(e,n),i)fe(n,{code:oe.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message});else if(s)fe(n,{code:oe.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message});r.dirty()}}else if(o.kind==="email"){if(!iZ.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"email",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="emoji"){if(!v1)v1=new RegExp(sZ,"u");if(!v1.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"emoji",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="uuid"){if(!tZ.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"uuid",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="nanoid"){if(!rZ.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"nanoid",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="cuid"){if(!QV.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"cuid",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="cuid2"){if(!XV.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"cuid2",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="ulid"){if(!eZ.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"ulid",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),fe(n,{validation:"url",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="regex"){if(o.regex.lastIndex=0,!o.regex.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"regex",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="trim")e.data=e.data.trim();else if(o.kind==="includes"){if(!e.data.includes(o.value,o.position))n=this._getOrReturnCtx(e,n),fe(n,{code:oe.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()}else if(o.kind==="toLowerCase")e.data=e.data.toLowerCase();else if(o.kind==="toUpperCase")e.data=e.data.toUpperCase();else if(o.kind==="startsWith"){if(!e.data.startsWith(o.value))n=this._getOrReturnCtx(e,n),fe(n,{code:oe.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()}else if(o.kind==="endsWith"){if(!e.data.endsWith(o.value))n=this._getOrReturnCtx(e,n),fe(n,{code:oe.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()}else if(o.kind==="datetime"){if(!hZ(o).test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{code:oe.invalid_string,validation:"datetime",message:o.message}),r.dirty()}else if(o.kind==="date"){if(!fZ.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{code:oe.invalid_string,validation:"date",message:o.message}),r.dirty()}else if(o.kind==="time"){if(!mZ(o).test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{code:oe.invalid_string,validation:"time",message:o.message}),r.dirty()}else if(o.kind==="duration"){if(!oZ.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"duration",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="ip"){if(!gZ(e.data,o.version))n=this._getOrReturnCtx(e,n),fe(n,{validation:"ip",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="jwt"){if(!yZ(e.data,o.alg))n=this._getOrReturnCtx(e,n),fe(n,{validation:"jwt",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="cidr"){if(!bZ(e.data,o.version))n=this._getOrReturnCtx(e,n),fe(n,{validation:"cidr",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="base64"){if(!lZ.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"base64",code:oe.invalid_string,message:o.message}),r.dirty()}else if(o.kind==="base64url"){if(!pZ.test(e.data))n=this._getOrReturnCtx(e,n),fe(n,{validation:"base64url",code:oe.invalid_string,message:o.message}),r.dirty()}else it.assertNever(o);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement((n)=>e.test(n),{validation:t,code:oe.invalid_string,...ve.errToObj(r)})}_addCheck(e){return new Ri({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...ve.errToObj(e)})}url(e){return this._addCheck({kind:"url",...ve.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...ve.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...ve.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...ve.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...ve.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...ve.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...ve.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...ve.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...ve.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...ve.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...ve.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...ve.errToObj(e)})}datetime(e){if(typeof e==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e});return this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...ve.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){if(typeof e==="string")return this._addCheck({kind:"time",precision:null,message:e});return this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...ve.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...ve.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...ve.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...ve.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...ve.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...ve.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...ve.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...ve.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...ve.errToObj(t)})}nonempty(e){return this.min(1,ve.errToObj(e))}trim(){return new Ri({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ri({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ri({...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)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxLength(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}}Ri.create=(e)=>new Ri({checks:[],typeName:se.ZodString,coerce:e?.coerce??!1,...We(e)});function xZ(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,i=Number.parseInt(e.toFixed(o).replace(".","")),s=Number.parseInt(t.toFixed(o).replace(".",""));return i%s/10**o}class wu extends Xe{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);if(this._getType(e)!==ge.number){let o=this._getOrReturnCtx(e);return fe(o,{code:oe.invalid_type,expected:ge.number,received:o.parsedType}),Le}let r=void 0,n=new Br;for(let o of this._def.checks)if(o.kind==="int"){if(!it.isInteger(e.data))r=this._getOrReturnCtx(e,r),fe(r,{code:oe.invalid_type,expected:"integer",received:"float",message:o.message}),n.dirty()}else if(o.kind==="min"){if(o.inclusive?e.data<o.value:e.data<=o.value)r=this._getOrReturnCtx(e,r),fe(r,{code:oe.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),n.dirty()}else if(o.kind==="max"){if(o.inclusive?e.data>o.value:e.data>=o.value)r=this._getOrReturnCtx(e,r),fe(r,{code:oe.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),n.dirty()}else if(o.kind==="multipleOf"){if(xZ(e.data,o.value)!==0)r=this._getOrReturnCtx(e,r),fe(r,{code:oe.not_multiple_of,multipleOf:o.value,message:o.message}),n.dirty()}else if(o.kind==="finite"){if(!Number.isFinite(e.data))r=this._getOrReturnCtx(e,r),fe(r,{code:oe.not_finite,message:o.message}),n.dirty()}else it.assertNever(o);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,ve.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ve.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ve.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ve.toString(t))}setLimit(e,t,r,n){return new wu({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:ve.toString(n)}]})}_addCheck(e){return new wu({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:ve.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ve.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ve.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ve.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ve.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ve.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:ve.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ve.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ve.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}get isInt(){return!!this._def.checks.find((e)=>e.kind==="int"||e.kind==="multipleOf"&&it.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks)if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;else if(r.kind==="min"){if(t===null||r.value>t)t=r.value}else if(r.kind==="max"){if(e===null||r.value<e)e=r.value}return Number.isFinite(t)&&Number.isFinite(e)}}wu.create=(e)=>new wu({checks:[],typeName:se.ZodNumber,coerce:e?.coerce||!1,...We(e)});class Su extends Xe{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)!==ge.bigint)return this._getInvalidInput(e);let r=void 0,n=new Br;for(let o of this._def.checks)if(o.kind==="min"){if(o.inclusive?e.data<o.value:e.data<=o.value)r=this._getOrReturnCtx(e,r),fe(r,{code:oe.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),n.dirty()}else if(o.kind==="max"){if(o.inclusive?e.data>o.value:e.data>=o.value)r=this._getOrReturnCtx(e,r),fe(r,{code:oe.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),n.dirty()}else if(o.kind==="multipleOf"){if(e.data%o.value!==BigInt(0))r=this._getOrReturnCtx(e,r),fe(r,{code:oe.not_multiple_of,multipleOf:o.value,message:o.message}),n.dirty()}else it.assertNever(o);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return fe(t,{code:oe.invalid_type,expected:ge.bigint,received:t.parsedType}),Le}gte(e,t){return this.setLimit("min",e,!0,ve.toString(t))}gt(e,t){return this.setLimit("min",e,!1,ve.toString(t))}lte(e,t){return this.setLimit("max",e,!0,ve.toString(t))}lt(e,t){return this.setLimit("max",e,!1,ve.toString(t))}setLimit(e,t,r,n){return new Su({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:ve.toString(n)}]})}_addCheck(e){return new Su({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ve.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ve.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ve.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ve.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:ve.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}}Su.create=(e)=>new Su({checks:[],typeName:se.ZodBigInt,coerce:e?.coerce??!1,...We(e)});class Nh extends Xe{_parse(e){if(this._def.coerce)e.data=Boolean(e.data);if(this._getType(e)!==ge.boolean){let r=this._getOrReturnCtx(e);return fe(r,{code:oe.invalid_type,expected:ge.boolean,received:r.parsedType}),Le}return Wr(e.data)}}Nh.create=(e)=>new Nh({typeName:se.ZodBoolean,coerce:e?.coerce||!1,...We(e)});class up extends Xe{_parse(e){if(this._def.coerce)e.data=new Date(e.data);if(this._getType(e)!==ge.date){let o=this._getOrReturnCtx(e);return fe(o,{code:oe.invalid_type,expected:ge.date,received:o.parsedType}),Le}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return fe(o,{code:oe.invalid_date}),Le}let r=new Br,n=void 0;for(let o of this._def.checks)if(o.kind==="min"){if(e.data.getTime()<o.value)n=this._getOrReturnCtx(e,n),fe(n,{code:oe.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()}else if(o.kind==="max"){if(e.data.getTime()>o.value)n=this._getOrReturnCtx(e,n),fe(n,{code:oe.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()}else it.assertNever(o);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new up({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:ve.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:ve.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e!=null?new Date(e):null}}up.create=(e)=>new up({checks:[],coerce:e?.coerce||!1,typeName:se.ZodDate,...We(e)});class zh extends Xe{_parse(e){if(this._getType(e)!==ge.symbol){let r=this._getOrReturnCtx(e);return fe(r,{code:oe.invalid_type,expected:ge.symbol,received:r.parsedType}),Le}return Wr(e.data)}}zh.create=(e)=>new zh({typeName:se.ZodSymbol,...We(e)});class dp extends Xe{_parse(e){if(this._getType(e)!==ge.undefined){let r=this._getOrReturnCtx(e);return fe(r,{code:oe.invalid_type,expected:ge.undefined,received:r.parsedType}),Le}return Wr(e.data)}}dp.create=(e)=>new dp({typeName:se.ZodUndefined,...We(e)});class lp extends Xe{_parse(e){if(this._getType(e)!==ge.null){let r=this._getOrReturnCtx(e);return fe(r,{code:oe.invalid_type,expected:ge.null,received:r.parsedType}),Le}return Wr(e.data)}}lp.create=(e)=>new lp({typeName:se.ZodNull,...We(e)});class Bh extends Xe{constructor(){super(...arguments);this._any=!0}_parse(e){return Wr(e.data)}}Bh.create=(e)=>new Bh({typeName:se.ZodAny,...We(e)});class Za extends Xe{constructor(){super(...arguments);this._unknown=!0}_parse(e){return Wr(e.data)}}Za.create=(e)=>new Za({typeName:se.ZodUnknown,...We(e)});class Oi extends Xe{_parse(e){let t=this._getOrReturnCtx(e);return fe(t,{code:oe.invalid_type,expected:ge.never,received:t.parsedType}),Le}}Oi.create=(e)=>new Oi({typeName:se.ZodNever,...We(e)});class Lh extends Xe{_parse(e){if(this._getType(e)!==ge.undefined){let r=this._getOrReturnCtx(e);return fe(r,{code:oe.invalid_type,expected:ge.void,received:r.parsedType}),Le}return Wr(e.data)}}Lh.create=(e)=>new Lh({typeName:se.ZodVoid,...We(e)});class Fo extends Xe{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==ge.array)return fe(t,{code:oe.invalid_type,expected:ge.array,received:t.parsedType}),Le;if(n.exactLength!==null){let i=t.data.length>n.exactLength.value,s=t.data.length<n.exactLength.value;if(i||s)fe(t,{code:i?oe.too_big:oe.too_small,minimum:s?n.exactLength.value:void 0,maximum:i?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty()}if(n.minLength!==null){if(t.data.length<n.minLength.value)fe(t,{code:oe.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()}if(n.maxLength!==null){if(t.data.length>n.maxLength.value)fe(t,{code:oe.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()}if(t.common.async)return Promise.all([...t.data].map((i,s)=>n.type._parseAsync(new uo(t,i,t.path,s)))).then((i)=>Br.mergeArray(r,i));let o=[...t.data].map((i,s)=>n.type._parseSync(new uo(t,i,t.path,s)));return Br.mergeArray(r,o)}get element(){return this._def.type}min(e,t){return new Fo({...this._def,minLength:{value:e,message:ve.toString(t)}})}max(e,t){return new Fo({...this._def,maxLength:{value:e,message:ve.toString(t)}})}length(e,t){return new Fo({...this._def,exactLength:{value:e,message:ve.toString(t)}})}nonempty(e){return this.min(1,e)}}Fo.create=(e,t)=>new Fo({type:e,minLength:null,maxLength:null,exactLength:null,typeName:se.ZodArray,...We(t)});function _u(e){if(e instanceof Xt){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=jo.create(_u(n))}return new Xt({...e._def,shape:()=>t})}else if(e instanceof Fo)return new Fo({...e._def,type:_u(e.element)});else if(e instanceof jo)return jo.create(_u(e.unwrap()));else if(e instanceof Ns)return Ns.create(_u(e.unwrap()));else if(e instanceof Ci)return Ci.create(e.items.map((t)=>_u(t)));else return e}class Xt extends Xe{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(),t=it.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==ge.object){let c=this._getOrReturnCtx(e);return fe(c,{code:oe.invalid_type,expected:ge.object,received:c.parsedType}),Le}let{status:r,ctx:n}=this._processInputParams(e),{shape:o,keys:i}=this._getCached(),s=[];if(!(this._def.catchall instanceof Oi&&this._def.unknownKeys==="strip")){for(let c in n.data)if(!i.includes(c))s.push(c)}let a=[];for(let c of i){let d=o[c],l=n.data[c];a.push({key:{status:"valid",value:c},value:d._parse(new uo(n,l,n.path,c)),alwaysSet:c in n.data})}if(this._def.catchall instanceof Oi){let c=this._def.unknownKeys;if(c==="passthrough")for(let d of s)a.push({key:{status:"valid",value:d},value:{status:"valid",value:n.data[d]}});else if(c==="strict"){if(s.length>0)fe(n,{code:oe.unrecognized_keys,keys:s}),r.dirty()}else if(c==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let d of s){let l=n.data[d];a.push({key:{status:"valid",value:d},value:c._parse(new uo(n,l,n.path,d)),alwaysSet:d in n.data})}}if(n.common.async)return Promise.resolve().then(async()=>{let c=[];for(let d of a){let l=await d.key,p=await d.value;c.push({key:l,value:p,alwaysSet:d.alwaysSet})}return c}).then((c)=>Br.mergeObjectSync(r,c));else return Br.mergeObjectSync(r,a)}get shape(){return this._def.shape()}strict(e){return ve.errToObj,new Xt({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{let n=this._def.errorMap?.(t,r).message??r.defaultError;if(t.code==="unrecognized_keys")return{message:ve.errToObj(e).message??n};return{message:n}}}:{}})}strip(){return new Xt({...this._def,unknownKeys:"strip"})}passthrough(){return new Xt({...this._def,unknownKeys:"passthrough"})}extend(e){return new Xt({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Xt({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:se.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Xt({...this._def,catchall:e})}pick(e){let t={};for(let r of it.objectKeys(e))if(e[r]&&this.shape[r])t[r]=this.shape[r];return new Xt({...this._def,shape:()=>t})}omit(e){let t={};for(let r of it.objectKeys(this.shape))if(!e[r])t[r]=this.shape[r];return new Xt({...this._def,shape:()=>t})}deepPartial(){return _u(this)}partial(e){let t={};for(let r of it.objectKeys(this.shape)){let n=this.shape[r];if(e&&!e[r])t[r]=n;else t[r]=n.optional()}return new Xt({...this._def,shape:()=>t})}required(e){let t={};for(let r of it.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let o=this.shape[r];while(o instanceof jo)o=o._def.innerType;t[r]=o}return new Xt({...this._def,shape:()=>t})}keyof(){return t2(it.objectKeys(this.shape))}}Xt.create=(e,t)=>new Xt({shape:()=>e,unknownKeys:"strip",catchall:Oi.create(),typeName:se.ZodObject,...We(t)});Xt.strictCreate=(e,t)=>new Xt({shape:()=>e,unknownKeys:"strict",catchall:Oi.create(),typeName:se.ZodObject,...We(t)});Xt.lazycreate=(e,t)=>new Xt({shape:e,unknownKeys:"strip",catchall:Oi.create(),typeName:se.ZodObject,...We(t)});class pp extends Xe{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function n(o){for(let s of o)if(s.result.status==="valid")return s.result;for(let s of o)if(s.result.status==="dirty")return t.common.issues.push(...s.ctx.common.issues),s.result;let i=o.map((s)=>new Pn(s.ctx.common.issues));return fe(t,{code:oe.invalid_union,unionErrors:i}),Le}if(t.common.async)return Promise.all(r.map(async(o)=>{let i={...t,common:{...t.common,issues:[]},parent:null};return{result:await o._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(n);else{let o=void 0,i=[];for(let a of r){let c={...t,common:{...t.common,issues:[]},parent:null},d=a._parseSync({data:t.data,path:t.path,parent:c});if(d.status==="valid")return d;else if(d.status==="dirty"&&!o)o={result:d,ctx:c};if(c.common.issues.length)i.push(c.common.issues)}if(o)return t.common.issues.push(...o.ctx.common.issues),o.result;let s=i.map((a)=>new Pn(a));return fe(t,{code:oe.invalid_union,unionErrors:s}),Le}}get options(){return this._def.options}}pp.create=(e,t)=>new pp({options:e,typeName:se.ZodUnion,...We(t)});var ki=(e)=>{if(e instanceof mp)return ki(e.schema);else if(e instanceof qo)return ki(e.innerType());else if(e instanceof hp)return[e.value];else if(e instanceof Wa)return e.options;else if(e instanceof gp)return it.objectValues(e.enum);else if(e instanceof yp)return ki(e._def.innerType);else if(e instanceof dp)return[void 0];else if(e instanceof lp)return[null];else if(e instanceof jo)return[void 0,...ki(e.unwrap())];else if(e instanceof Ns)return[null,...ki(e.unwrap())];else if(e instanceof P1)return ki(e.unwrap());else if(e instanceof xp)return ki(e.unwrap());else if(e instanceof bp)return ki(e._def.innerType);else return[]};class E1 extends Xe{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==ge.object)return fe(t,{code:oe.invalid_type,expected:ge.object,received:t.parsedType}),Le;let r=this.discriminator,n=t.data[r],o=this.optionsMap.get(n);if(!o)return fe(t,{code:oe.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Le;if(t.common.async)return o._parseAsync({data:t.data,path:t.path,parent:t});else return o._parseSync({data:t.data,path:t.path,parent:t})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let n=new Map;for(let o of t){let i=ki(o.shape[e]);if(!i.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let s of i){if(n.has(s))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);n.set(s,o)}}return new E1({typeName:se.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...We(r)})}}function T1(e,t){let r=Ii(e),n=Ii(t);if(e===t)return{valid:!0,data:e};else if(r===ge.object&&n===ge.object){let o=it.objectKeys(t),i=it.objectKeys(e).filter((a)=>o.indexOf(a)!==-1),s={...e,...t};for(let a of i){let c=T1(e[a],t[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===ge.array&&n===ge.array){if(e.length!==t.length)return{valid:!1};let o=[];for(let i=0;i<e.length;i++){let s=e[i],a=t[i],c=T1(s,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else if(r===ge.date&&n===ge.date&&+e===+t)return{valid:!0,data:e};else return{valid:!1}}class fp extends Xe{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=(o,i)=>{if(w1(o)||w1(i))return Le;let s=T1(o.value,i.value);if(!s.valid)return fe(r,{code:oe.invalid_intersection_types}),Le;if(S1(o)||S1(i))t.dirty();return{status:t.value,value:s.data}};if(r.common.async)return Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,i])=>n(o,i));else return n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}fp.create=(e,t,r)=>new fp({left:e,right:t,typeName:se.ZodIntersection,...We(r)});class Ci extends Xe{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ge.array)return fe(r,{code:oe.invalid_type,expected:ge.array,received:r.parsedType}),Le;if(r.data.length<this._def.items.length)return fe(r,{code:oe.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Le;if(!this._def.rest&&r.data.length>this._def.items.length)fe(r,{code:oe.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty();let o=[...r.data].map((i,s)=>{let a=this._def.items[s]||this._def.rest;if(!a)return null;return a._parse(new uo(r,i,r.path,s))}).filter((i)=>!!i);if(r.common.async)return Promise.all(o).then((i)=>Br.mergeArray(t,i));else return Br.mergeArray(t,o)}get items(){return this._def.items}rest(e){return new Ci({...this._def,rest:e})}}Ci.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ci({items:e,typeName:se.ZodTuple,rest:null,...We(t)})};class Dh extends Xe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ge.object)return fe(r,{code:oe.invalid_type,expected:ge.object,received:r.parsedType}),Le;let n=[],o=this._def.keyType,i=this._def.valueType;for(let s in r.data)n.push({key:o._parse(new uo(r,s,r.path,s)),value:i._parse(new uo(r,r.data[s],r.path,s)),alwaysSet:s in r.data});if(r.common.async)return Br.mergeObjectAsync(t,n);else return Br.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){if(t instanceof Xe)return new Dh({keyType:e,valueType:t,typeName:se.ZodRecord,...We(r)});return new Dh({keyType:Ri.create(),valueType:e,typeName:se.ZodRecord,...We(t)})}}class Uh extends Xe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ge.map)return fe(r,{code:oe.invalid_type,expected:ge.map,received:r.parsedType}),Le;let n=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map(([s,a],c)=>({key:n._parse(new uo(r,s,r.path,[c,"key"])),value:o._parse(new uo(r,a,r.path,[c,"value"]))}));if(r.common.async){let s=new Map;return Promise.resolve().then(async()=>{for(let a of i){let c=await a.key,d=await a.value;if(c.status==="aborted"||d.status==="aborted")return Le;if(c.status==="dirty"||d.status==="dirty")t.dirty();s.set(c.value,d.value)}return{status:t.value,value:s}})}else{let s=new Map;for(let a of i){let{key:c,value:d}=a;if(c.status==="aborted"||d.status==="aborted")return Le;if(c.status==="dirty"||d.status==="dirty")t.dirty();s.set(c.value,d.value)}return{status:t.value,value:s}}}}Uh.create=(e,t,r)=>new Uh({valueType:t,keyType:e,typeName:se.ZodMap,...We(r)});class vu extends Xe{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ge.set)return fe(r,{code:oe.invalid_type,expected:ge.set,received:r.parsedType}),Le;let n=this._def;if(n.minSize!==null){if(r.data.size<n.minSize.value)fe(r,{code:oe.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()}if(n.maxSize!==null){if(r.data.size>n.maxSize.value)fe(r,{code:oe.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty()}let o=this._def.valueType;function i(a){let c=new Set;for(let d of a){if(d.status==="aborted")return Le;if(d.status==="dirty")t.dirty();c.add(d.value)}return{status:t.value,value:c}}let s=[...r.data.values()].map((a,c)=>o._parse(new uo(r,a,r.path,c)));if(r.common.async)return Promise.all(s).then((a)=>i(a));else return i(s)}min(e,t){return new vu({...this._def,minSize:{value:e,message:ve.toString(t)}})}max(e,t){return new vu({...this._def,maxSize:{value:e,message:ve.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}vu.create=(e,t)=>new vu({valueType:e,minSize:null,maxSize:null,typeName:se.ZodSet,...We(t)});class cp extends Xe{constructor(){super(...arguments);this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==ge.function)return fe(t,{code:oe.invalid_type,expected:ge.function,received:t.parsedType}),Le;function r(s,a){return $h({data:s,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,sp(),$s].filter((c)=>!!c),issueData:{code:oe.invalid_arguments,argumentsError:a}})}function n(s,a){return $h({data:s,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,sp(),$s].filter((c)=>!!c),issueData:{code:oe.invalid_return_type,returnTypeError:a}})}let o={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof Tu){let s=this;return Wr(async function(...a){let c=new Pn([]),d=await s._def.args.parseAsync(a,o).catch((m)=>{throw c.addIssue(r(a,m)),c}),l=await Reflect.apply(i,this,d);return await s._def.returns._def.type.parseAsync(l,o).catch((m)=>{throw c.addIssue(n(l,m)),c})})}else{let s=this;return Wr(function(...a){let c=s._def.args.safeParse(a,o);if(!c.success)throw new Pn([r(a,c.error)]);let d=Reflect.apply(i,this,c.data),l=s._def.returns.safeParse(d,o);if(!l.success)throw new Pn([n(d,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new cp({...this._def,args:Ci.create(e).rest(Za.create())})}returns(e){return new cp({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new cp({args:e?e:Ci.create([]).rest(Za.create()),returns:t||Za.create(),typeName:se.ZodFunction,...We(r)})}}class mp extends Xe{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})}}mp.create=(e,t)=>new mp({getter:e,typeName:se.ZodLazy,...We(t)});class hp extends Xe{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return fe(t,{received:t.data,code:oe.invalid_literal,expected:this._def.value}),Le}return{status:"valid",value:e.data}}get value(){return this._def.value}}hp.create=(e,t)=>new hp({value:e,typeName:se.ZodLiteral,...We(t)});function t2(e,t){return new Wa({values:e,typeName:se.ZodEnum,...We(t)})}class Wa extends Xe{_parse(e){if(typeof e.data!=="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return fe(t,{expected:it.joinValues(r),received:t.parsedType,code:oe.invalid_type}),Le}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return fe(t,{received:t.data,code:oe.invalid_enum_value,options:r}),Le}return Wr(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(e,t=this._def){return Wa.create(e,{...this._def,...t})}exclude(e,t=this._def){return Wa.create(this.options.filter((r)=>!e.includes(r)),{...this._def,...t})}}Wa.create=t2;class gp extends Xe{_parse(e){let t=it.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==ge.string&&r.parsedType!==ge.number){let n=it.objectValues(t);return fe(r,{expected:it.joinValues(n),received:r.parsedType,code:oe.invalid_type}),Le}if(!this._cache)this._cache=new Set(it.getValidEnumValues(this._def.values));if(!this._cache.has(e.data)){let n=it.objectValues(t);return fe(r,{received:r.data,code:oe.invalid_enum_value,options:n}),Le}return Wr(e.data)}get enum(){return this._def.values}}gp.create=(e,t)=>new gp({values:e,typeName:se.ZodNativeEnum,...We(t)});class Tu extends Xe{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==ge.promise&&t.common.async===!1)return fe(t,{code:oe.invalid_type,expected:ge.promise,received:t.parsedType}),Le;let r=t.parsedType===ge.promise?t.data:Promise.resolve(t.data);return Wr(r.then((n)=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Tu.create=(e,t)=>new Tu({type:e,typeName:se.ZodPromise,...We(t)});class qo extends Xe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===se.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,o={addIssue:(i)=>{if(fe(r,i),i.fatal)t.abort();else t.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),n.type==="preprocess"){let i=n.transform(r.data,o);if(r.common.async)return Promise.resolve(i).then(async(s)=>{if(t.value==="aborted")return Le;let a=await this._def.schema._parseAsync({data:s,path:r.path,parent:r});if(a.status==="aborted")return Le;if(a.status==="dirty")return xu(a.value);if(t.value==="dirty")return xu(a.value);return a});else{if(t.value==="aborted")return Le;let s=this._def.schema._parseSync({data:i,path:r.path,parent:r});if(s.status==="aborted")return Le;if(s.status==="dirty")return xu(s.value);if(t.value==="dirty")return xu(s.value);return s}}if(n.type==="refinement"){let i=(s)=>{let a=n.refinement(s,o);if(r.common.async)return Promise.resolve(a);if(a instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(r.common.async===!1){let s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(s.status==="aborted")return Le;if(s.status==="dirty")t.dirty();return i(s.value),{status:t.value,value:s.value}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((s)=>{if(s.status==="aborted")return Le;if(s.status==="dirty")t.dirty();return i(s.value).then(()=>({status:t.value,value:s.value}))})}if(n.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Va(i))return Le;let s=n.transform(i.value,o);if(s instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:s}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((i)=>{if(!Va(i))return Le;return Promise.resolve(n.transform(i.value,o)).then((s)=>({status:t.value,value:s}))});it.assertNever(n)}}qo.create=(e,t,r)=>new qo({schema:e,typeName:se.ZodEffects,effect:t,...We(r)});qo.createWithPreprocess=(e,t,r)=>new qo({schema:t,effect:{type:"preprocess",transform:e},typeName:se.ZodEffects,...We(r)});class jo extends Xe{_parse(e){if(this._getType(e)===ge.undefined)return Wr(void 0);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}jo.create=(e,t)=>new jo({innerType:e,typeName:se.ZodOptional,...We(t)});class Ns extends Xe{_parse(e){if(this._getType(e)===ge.null)return Wr(null);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ns.create=(e,t)=>new Ns({innerType:e,typeName:se.ZodNullable,...We(t)});class yp extends Xe{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;if(t.parsedType===ge.undefined)r=this._def.defaultValue();return this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}yp.create=(e,t)=>new yp({innerType:e,typeName:se.ZodDefault,defaultValue:typeof t.default==="function"?t.default:()=>t.default,...We(t)});class bp extends Xe{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});if(ap(n))return n.then((o)=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Pn(r.common.issues)},input:r.data})}));else return{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new Pn(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}bp.create=(e,t)=>new bp({innerType:e,typeName:se.ZodCatch,catchValue:typeof t.catch==="function"?t.catch:()=>t.catch,...We(t)});class Fh extends Xe{_parse(e){if(this._getType(e)!==ge.nan){let r=this._getOrReturnCtx(e);return fe(r,{code:oe.invalid_type,expected:ge.nan,received:r.parsedType}),Le}return{status:"valid",value:e.data}}}Fh.create=(e)=>new Fh({typeName:se.ZodNaN,...We(e)});var Ume=Symbol("zod_brand");class P1 extends Xe{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class jh extends Xe{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});if(o.status==="aborted")return Le;if(o.status==="dirty")return t.dirty(),xu(o.value);else return this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();else{let n=this._def.in._parseSync({data:r.data,path:r.path,parent:r});if(n.status==="aborted")return Le;if(n.status==="dirty")return t.dirty(),{status:"dirty",value:n.value};else return this._def.out._parseSync({data:n.value,path:r.path,parent:r})}}static create(e,t){return new jh({in:e,out:t,typeName:se.ZodPipeline})}}class xp extends Xe{_parse(e){let t=this._def.innerType._parse(e),r=(n)=>{if(Va(n))n.value=Object.freeze(n.value);return n};return ap(t)?t.then((n)=>r(n)):r(t)}unwrap(){return this._def.innerType}}xp.create=(e,t)=>new xp({innerType:e,typeName:se.ZodReadonly,...We(t)});var Fme={object:Xt.lazycreate},se;(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"})(se||(se={}));var jme=Ri.create,qme=wu.create,Hme=Fh.create,Gme=Su.create,Vme=Nh.create,Zme=up.create,Wme=zh.create,Kme=dp.create,Yme=lp.create,Jme=Bh.create,Qme=Za.create,Xme=Oi.create,ehe=Lh.create,the=Fo.create,{create:r2,strictCreate:rhe}=Xt,nhe=pp.create,ohe=E1.create,ihe=fp.create,she=Ci.create,ahe=Dh.create,che=Uh.create,uhe=vu.create,dhe=cp.create,lhe=mp.create,phe=hp.create,fhe=Wa.create,mhe=gp.create,hhe=Tu.create,ghe=qo.create,yhe=jo.create,bhe=Ns.create,xhe=qo.createWithPreprocess,_he=jh.create;var n2;function D(e,t,r){function n(a,c){if(!a._zod)Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1});if(a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,c);let d=s.prototype,l=Object.keys(d);for(let p=0;p<l.length;p++){let m=l[p];if(!(m in a))a[m]=d[m].bind(a)}}let o=r?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(a){var c;let d=r?.Parent?new i:this;n(d,a),(c=d._zod).deferred??(c.deferred=[]);for(let l of d._zod.deferred)l();return d}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:(a)=>{if(r?.Parent&&a instanceof r.Parent)return!0;return a?._zod?.traits?.has(e)}}),Object.defineProperty(s,"name",{value:e}),s}var She=Symbol("zod_brand");class Mi extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class _p extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(n2=globalThis).__zod_globalConfig??(n2.__zod_globalConfig={});var Eu=globalThis.__zod_globalConfig;function An(e){if(e)Object.assign(Eu,e);return Eu}function Hh(e){let t=Object.values(e).filter((n)=>typeof n==="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function I1(e,t="|"){return e.map((r)=>O1(r)).join(t)}function wp(e,t){if(typeof t==="bigint")return t.toString();return t}function Sp(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw Error("cached value already set")}}}function Gh(e){return e===null||e===void 0}function Vh(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function i2(e,t){let r=e/t,n=Math.round(r),o=Number.EPSILON*Math.max(Math.abs(r),1);if(Math.abs(r-n)<o)return 0;return r-n}var o2=Symbol("evaluating");function _t(e,t,r){let n=void 0;Object.defineProperty(e,t,{get(){if(n===o2)return;if(n===void 0)n=o2,n=r();return n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Ka(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function zs(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function k1(e){return JSON.stringify(e)}function s2(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var R1="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Pu(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var a2=Sp(()=>{if(Eu.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Ya(e){if(Pu(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let r=t.prototype;if(Pu(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)return!1;return!0}function Zh(e){if(Ya(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var c2=new Set(["string","number","symbol"]);function Bs(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jn(e,t,r){let n=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)n._zod.parent=e;return n}function xe(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function O1(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function u2(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var d2={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function l2(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let i=zs(e._zod.def,{get shape(){let s={};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;s[a]=r.shape[a]}return Ka(this,"shape",s),s},checks:[]});return jn(e,i)}function p2(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let i=zs(e._zod.def,{get shape(){let s={...e._zod.def.shape};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;delete s[a]}return Ka(this,"shape",s),s},checks:[]});return jn(e,i)}function f2(e,t){if(!Ya(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let i=e._zod.def.shape;for(let s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=zs(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return Ka(this,"shape",i),i}});return jn(e,o)}function m2(e,t){if(!Ya(t))throw Error("Invalid input to safeExtend: expected a plain object");let r=zs(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Ka(this,"shape",n),n}});return jn(e,r)}function _Z(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=zs(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Ka(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return jn(e,r)}function h2(e,t,r){let o=t._zod.def.checks;if(o&&o.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let s=zs(t._zod.def,{get shape(){let a=t._zod.def.shape,c={...a};if(r)for(let d in r){if(!(d in a))throw Error(`Unrecognized key: "${d}"`);if(!r[d])continue;c[d]=e?new e({type:"optional",innerType:a[d]}):a[d]}else for(let d in a)c[d]=e?new e({type:"optional",innerType:a[d]}):a[d];return Ka(this,"shape",c),c},checks:[]});return jn(t,s)}function g2(e,t,r){let n=zs(t._zod.def,{get shape(){let o=t._zod.def.shape,i={...o};if(r)for(let s in r){if(!(s in i))throw Error(`Unrecognized key: "${s}"`);if(!r[s])continue;i[s]=new e({type:"nonoptional",innerType:o[s]})}else for(let s in o)i[s]=new e({type:"nonoptional",innerType:o[s]});return Ka(this,"shape",i),i}});return jn(t,n)}function Ja(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function y2(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function Ls(e,t){return t.map((r)=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function qh(e){return typeof e==="string"?e:e?.message}function lo(e,t,r){let n=e.message?e.message:qh(e.inst?._zod.def?.error?.(e))??qh(t?.error?.(e))??qh(r.customError?.(e))??qh(r.localeError?.(e))??"Invalid input",{inst:o,continue:i,input:s,...a}=e;if(a.path??(a.path=[]),a.message=n,t?.reportInput)a.input=s;return a}function Wh(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function b2(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function Qa(...e){let[t,r,n]=e;if(typeof t==="string")return{message:t,code:"custom",input:r,inst:n};return{...t}}var x2=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,wp,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Kh=D("$ZodError",x2),vp=D("$ZodError",x2,{Parent:Error});function _2(e,t=(r)=>r.message){let r={},n=[];for(let o of e.issues)if(o.path.length>0)r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o));else n.push(t(o));return{formErrors:n,fieldErrors:r}}function w2(e,t=(r)=>r.message){let r={_errors:[]},n=(o,i=[])=>{for(let s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map((a)=>n({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")n({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")n({issues:s.issues},[...i,...s.path]);else{let a=[...i,...s.path];if(a.length===0)r._errors.push(t(s));else{let c=r,d=0;while(d<a.length){let l=a[d];if(d!==a.length-1)c[l]=c[l]||{_errors:[]};else c[l]=c[l]||{_errors:[]},c[l]._errors.push(t(s));c=c[l],d++}}}};return n(e),r}var Tp=(e)=>(t,r,n,o)=>{let i=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new Mi;if(s.issues.length){let a=new(o?.Err??e)(s.issues.map((c)=>lo(c,i,An())));throw R1(a,o?.callee),a}return s.value},Yh=Tp(vp),Ep=(e)=>async(t,r,n,o)=>{let i=n?{...n,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)s=await s;if(s.issues.length){let a=new(o?.Err??e)(s.issues.map((c)=>lo(c,i,An())));throw R1(a,o?.callee),a}return s.value},Jh=Ep(vp),Pp=(e)=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new Mi;return i.issues.length?{success:!1,error:new(e??Kh)(i.issues.map((s)=>lo(s,o,An())))}:{success:!0,data:i.value}},Xa=Pp(vp),Ap=(e)=>async(t,r,n)=>{let o=n?{...n,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)i=await i;return i.issues.length?{success:!1,error:new e(i.issues.map((s)=>lo(s,o,An())))}:{success:!0,data:i.value}},ec=Ap(vp),S2=(e)=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Tp(e)(t,r,o)};var v2=(e)=>(t,r,n)=>Tp(e)(t,r,n);var T2=(e)=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Ep(e)(t,r,o)};var E2=(e)=>async(t,r,n)=>Ep(e)(t,r,n);var P2=(e)=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Pp(e)(t,r,o)};var A2=(e)=>(t,r,n)=>Pp(e)(t,r,n);var I2=(e)=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Ap(e)(t,r,o)};var k2=(e)=>async(t,r,n)=>Ap(e)(t,r,n);var R2=/^[cC][0-9a-z]{6,}$/,O2=/^[0-9a-z]+$/,C2=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,M2=/^[0-9a-vA-V]{20}$/,$2=/^[A-Za-z0-9]{27}$/,N2=/^[a-zA-Z0-9_-]{21}$/,z2=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var B2=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,C1=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var L2=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var SZ="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function D2(){return new RegExp(SZ,"u")}var U2=/^(?:(?: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])$/,F2=/^(([0-9a-fA-F]{1,4}:){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}|:))$/;var j2=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,q2=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,H2=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,M1=/^[A-Za-z0-9_-]*$/;var G2=/^https?$/,V2=/^\+[1-9]\d{6,14}$/,Z2="(?:(?:\\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])))",W2=new RegExp(`^${Z2}$`);function K2(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function Y2(e){return new RegExp(`^${K2(e)}$`)}function J2(e){let t=K2({precision:e.precision}),r=["Z"];if(e.local)r.push("");if(e.offset)r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${Z2}T(?:${n})$`)}var Q2=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},X2=/^-?\d+n?$/,e6=/^-?\d+$/,$1=/^-?\d+(?:\.\d+)?$/,t6=/^(?:true|false)$/i,r6=/^null$/i;var n6=/^[^A-Z]*$/,o6=/^[^a-z]*$/;var yr=D("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),i6={number:"number",bigint:"bigint",object:"date"},N1=D("$ZodCheckLessThan",(e,t)=>{yr.init(e,t);let r=i6[typeof t.value];e._zod.onattach.push((n)=>{let o=n._zod.bag,i=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<i)if(t.inclusive)o.maximum=t.value;else o.exclusiveMaximum=t.value}),e._zod.check=(n)=>{if(t.inclusive?n.value<=t.value:n.value<t.value)return;n.issues.push({origin:r,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),z1=D("$ZodCheckGreaterThan",(e,t)=>{yr.init(e,t);let r=i6[typeof t.value];e._zod.onattach.push((n)=>{let o=n._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>i)if(t.inclusive)o.minimum=t.value;else o.exclusiveMinimum=t.value}),e._zod.check=(n)=>{if(t.inclusive?n.value>=t.value:n.value>t.value)return;n.issues.push({origin:r,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),s6=D("$ZodCheckMultipleOf",(e,t)=>{yr.init(e,t),e._zod.onattach.push((r)=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=(r)=>{if(typeof r.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof r.value==="bigint"?r.value%t.value===BigInt(0):i2(r.value,t.value)===0)return;r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),a6=D("$ZodCheckNumberFormat",(e,t)=>{yr.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,i]=d2[t.format];e._zod.onattach.push((s)=>{let a=s._zod.bag;if(a.format=t.format,a.minimum=o,a.maximum=i,r)a.pattern=e6}),e._zod.check=(s)=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});else s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}if(a<o)s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort});if(a>i)s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}});var c6=D("$ZodCheckMaxLength",(e,t)=>{var r;yr.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!Gh(o)&&o.length!==void 0}),e._zod.onattach.push((n)=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<o)n._zod.bag.maximum=t.maximum}),e._zod.check=(n)=>{let o=n.value;if(o.length<=t.maximum)return;let s=Wh(o);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),u6=D("$ZodCheckMinLength",(e,t)=>{var r;yr.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!Gh(o)&&o.length!==void 0}),e._zod.onattach.push((n)=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>o)n._zod.bag.minimum=t.minimum}),e._zod.check=(n)=>{let o=n.value;if(o.length>=t.minimum)return;let s=Wh(o);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),d6=D("$ZodCheckLengthEquals",(e,t)=>{var r;yr.init(e,t),(r=e._zod.def).when??(r.when=(n)=>{let o=n.value;return!Gh(o)&&o.length!==void 0}),e._zod.onattach.push((n)=>{let o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=(n)=>{let o=n.value,i=o.length;if(i===t.length)return;let s=Wh(o),a=i>t.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),kp=D("$ZodCheckStringFormat",(e,t)=>{var r,n;if(yr.init(e,t),e._zod.onattach.push((o)=>{let i=o._zod.bag;if(i.format=t.format,t.pattern)i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern)}),t.pattern)(r=e._zod).check??(r.check=(o)=>{if(t.pattern.lastIndex=0,t.pattern.test(o.value))return;o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(n=e._zod).check??(n.check=()=>{})}),l6=D("$ZodCheckRegex",(e,t)=>{kp.init(e,t),e._zod.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),p6=D("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=n6),kp.init(e,t)}),f6=D("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=o6),kp.init(e,t)}),m6=D("$ZodCheckIncludes",(e,t)=>{yr.init(e,t);let r=Bs(t.includes),n=new RegExp(typeof t.position==="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push((o)=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=(o)=>{if(o.value.includes(t.includes,t.position))return;o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),h6=D("$ZodCheckStartsWith",(e,t)=>{yr.init(e,t);let r=new RegExp(`^${Bs(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push((n)=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=(n)=>{if(n.value.startsWith(t.prefix))return;n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),g6=D("$ZodCheckEndsWith",(e,t)=>{yr.init(e,t);let r=new RegExp(`.*${Bs(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push((n)=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=(n)=>{if(n.value.endsWith(t.suffix))return;n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});var y6=D("$ZodCheckOverwrite",(e,t)=>{yr.init(e,t),e._zod.check=(r)=>{r.value=t.tx(r.value)}});class B1{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
68
68
  `).filter((i)=>i),n=Math.min(...r.map((i)=>i.length-i.trimStart().length)),o=r.map((i)=>i.slice(n)).map((i)=>" ".repeat(this.indent*2)+i);for(let i of o)this.content.push(i)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[""]).map((o)=>` ${o}`)];return new e(...t,n.join(`
69
69
  `))}}var x6={major:4,minor:4,patch:3};var Tt=D("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=x6;let n=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck"))n.unshift(e);for(let o of n)for(let i of o._zod.onattach)i(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(s,a,c)=>{let d=Ja(s),l;for(let p of a){if(p._zod.def.when){if(y2(s))continue;if(!p._zod.def.when(s))continue}else if(d)continue;let m=s.issues.length,h=p._zod.check(s);if(h instanceof Promise&&c?.async===!1)throw new Mi;if(l||h instanceof Promise)l=(l??Promise.resolve()).then(async()=>{if(await h,s.issues.length===m)return;if(!d)d=Ja(s,m)});else{if(s.issues.length===m)continue;if(!d)d=Ja(s,m)}}if(l)return l.then(()=>s);return s},i=(s,a,c)=>{if(Ja(s))return s.aborted=!0,s;let d=o(a,n,c);if(d instanceof Promise){if(c.async===!1)throw new Mi;return d.then((l)=>e._zod.parse(l,c))}return e._zod.parse(d,c)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){let d=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});if(d instanceof Promise)return d.then((l)=>i(l,s,a));return i(d,s,a)}let c=e._zod.parse(s,a);if(c instanceof Promise){if(a.async===!1)throw new Mi;return c.then((d)=>o(d,n,a))}return o(c,n,a)}}_t(e,"~standard",()=>({validate:(o)=>{try{let i=Xa(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch(i){return ec(e,o).then((s)=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Rp=D("$ZodString",(e,t)=>{Tt.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Q2(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch(o){}if(typeof r.value==="string")return r;return r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),Nt=D("$ZodStringFormat",(e,t)=>{kp.init(e,t),Rp.init(e,t)}),D1=D("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=B2),Nt.init(e,t)}),U1=D("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=C1(n))}else t.pattern??(t.pattern=C1());Nt.init(e,t)}),F1=D("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=L2),Nt.init(e,t)}),j1=D("$ZodURL",(e,t)=>{Nt.init(e,t),e._zod.check=(r)=>{try{let n=r.value.trim();if(!t.normalize&&t.protocol?.source===G2.source){if(!/^https?:\/\//i.test(n)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}}let o=new URL(n);if(t.hostname){if(t.hostname.lastIndex=0,!t.hostname.test(o.hostname))r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})}if(t.protocol){if(t.protocol.lastIndex=0,!t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol))r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})}if(t.normalize)r.value=o.href;else r.value=n;return}catch(n){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),q1=D("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=D2()),Nt.init(e,t)}),H1=D("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=N2),Nt.init(e,t)}),G1=D("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=R2),Nt.init(e,t)}),V1=D("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=O2),Nt.init(e,t)}),Z1=D("$ZodULID",(e,t)=>{t.pattern??(t.pattern=C2),Nt.init(e,t)}),W1=D("$ZodXID",(e,t)=>{t.pattern??(t.pattern=M2),Nt.init(e,t)}),K1=D("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=$2),Nt.init(e,t)}),I6=D("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=J2(t)),Nt.init(e,t)}),k6=D("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=W2),Nt.init(e,t)}),R6=D("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Y2(t)),Nt.init(e,t)}),O6=D("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=z2),Nt.init(e,t)}),Y1=D("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=U2),Nt.init(e,t),e._zod.bag.format="ipv4"}),J1=D("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=F2),Nt.init(e,t),e._zod.bag.format="ipv6",e._zod.check=(r)=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}});var Q1=D("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=j2),Nt.init(e,t)}),X1=D("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=q2),Nt.init(e,t),e._zod.check=(r)=>{let n=r.value.split("/");try{if(n.length!==2)throw Error();let[o,i]=n;if(!i)throw Error();let s=Number(i);if(`${s}`!==i)throw Error();if(s<0||s>128)throw Error();new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function C6(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var e_=D("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=H2),Nt.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(r)=>{if(C6(r.value))return;r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function vZ(e){if(!M1.test(e))return!1;let t=e.replace(/[-_]/g,(n)=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return C6(r)}var t_=D("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=M1),Nt.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(r)=>{if(vZ(r.value))return;r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),r_=D("$ZodE164",(e,t)=>{t.pattern??(t.pattern=V2),Nt.init(e,t)});function TZ(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));if("typ"in o&&o?.typ!=="JWT")return!1;if(!o.alg)return!1;if(t&&(!("alg"in o)||o.alg!==t))return!1;return!0}catch{return!1}}var n_=D("$ZodJWT",(e,t)=>{Nt.init(e,t),e._zod.check=(r)=>{if(TZ(r.value,t.alg))return;r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var eg=D("$ZodNumber",(e,t)=>{Tt.init(e,t),e._zod.pattern=e._zod.bag.pattern??$1,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch(s){}let o=r.value;if(typeof o==="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let i=typeof o==="number"?Number.isNaN(o)?"NaN":!Number.isFinite(o)?"Infinity":void 0:void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),r}}),o_=D("$ZodNumberFormat",(e,t)=>{a6.init(e,t),eg.init(e,t)}),i_=D("$ZodBoolean",(e,t)=>{Tt.init(e,t),e._zod.pattern=t6,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(i){}let o=r.value;if(typeof o==="boolean")return r;return r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}}),s_=D("$ZodBigInt",(e,t)=>{Tt.init(e,t),e._zod.pattern=X2,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch(o){}if(typeof r.value==="bigint")return r;return r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}});var a_=D("$ZodNull",(e,t)=>{Tt.init(e,t),e._zod.pattern=r6,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let o=r.value;if(o===null)return r;return r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}});var c_=D("$ZodUnknown",(e,t)=>{Tt.init(e,t),e._zod.parse=(r)=>r}),u_=D("$ZodNever",(e,t)=>{Tt.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function _6(e,t,r){if(e.issues.length)t.issues.push(...Ls(r,e.issues));t.value[r]=e.value}var d_=D("$ZodArray",(e,t)=>{Tt.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);let i=[];for(let s=0;s<o.length;s++){let a=o[s],c=t.element._zod.run({value:a,issues:[]},n);if(c instanceof Promise)i.push(c.then((d)=>_6(d,r,s)));else _6(c,r,s)}if(i.length)return Promise.all(i).then(()=>r);return r}});function Xh(e,t,r,n,o,i){let s=r in n;if(e.issues.length){if(o&&i&&!s)return;t.issues.push(...Ls(r,e.issues))}if(!s&&!o){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}if(e.value===void 0){if(s)t.value[r]=void 0}else t.value[r]=e.value}function M6(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let r=u2(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function $6(e,t,r,n,o,i){let s=[],a=o.keySet,c=o.catchall._zod,d=c.def.type,l=c.optin==="optional",p=c.optout==="optional";for(let m in t){if(m==="__proto__")continue;if(a.has(m))continue;if(d==="never"){s.push(m);continue}let h=c.run({value:t[m],issues:[]},n);if(h instanceof Promise)e.push(h.then((b)=>Xh(b,r,m,t,l,p)));else Xh(h,r,m,t,l,p)}if(s.length)r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i});if(!e.length)return r;return Promise.all(e).then(()=>r)}var l_=D("$ZodObject",(e,t)=>{if(Tt.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let a=t.shape;Object.defineProperty(t,"shape",{get:()=>{let c={...a};return Object.defineProperty(t,"shape",{value:c}),c}})}let n=Sp(()=>M6(t));_t(e._zod,"propValues",()=>{let a=t.shape,c={};for(let d in a){let l=a[d]._zod;if(l.values){c[d]??(c[d]=new Set);for(let p of l.values)c[d].add(p)}}return c});let o=Pu,i=t.catchall,s;e._zod.parse=(a,c)=>{s??(s=n.value);let d=a.value;if(!o(d))return a.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),a;a.value={};let l=[],p=s.shape;for(let m of s.keys){let h=p[m],b=h._zod.optin==="optional",x=h._zod.optout==="optional",_=h._zod.run({value:d[m],issues:[]},c);if(_ instanceof Promise)l.push(_.then((w)=>Xh(w,a,m,d,b,x)));else Xh(_,a,m,d,b,x)}if(!i)return l.length?Promise.all(l).then(()=>a):a;return $6(l,d,a,c,n.value,e)}}),N6=D("$ZodObjectJIT",(e,t)=>{l_.init(e,t);let r=e._zod.parse,n=Sp(()=>M6(t)),o=(m)=>{let h=new B1(["shape","payload","ctx"]),b=n.value,x=(v)=>{let T=k1(v);return`shape[${T}]._zod.run({ value: input[${T}], issues: [] }, ctx)`};h.write("const input = payload.value;");let _=Object.create(null),w=0;for(let v of b.keys)_[v]=`key_${w++}`;h.write("const newResult = {};");for(let v of b.keys){let T=_[v],P=k1(v),k=m[v],O=k?._zod?.optin==="optional",N=k?._zod?.optout==="optional";if(h.write(`const ${T} = ${x(v)};`),O&&N)h.write(`
70
70
  if (${T}.issues.length) {
@@ -127,18 +127,18 @@ ${W3(m)}`;super(e.shortMessage,{cause:e,docsPath:r,metaMessages:[...e.metaMessag
127
127
 
128
128
  `)}h.write("payload.value = newResult;"),h.write("return payload;");let A=h.compile();return(v,T)=>A(m,v,T)},i,s=Pu,a=!Eu.jitless,d=a&&a2.value,l=t.catchall,p;e._zod.parse=(m,h)=>{p??(p=n.value);let b=m.value;if(!s(b))return m.issues.push({expected:"object",code:"invalid_type",input:b,inst:e}),m;if(a&&d&&h?.async===!1&&h.jitless!==!0){if(!i)i=o(t.shape);if(m=i(m,h),!l)return m;return $6([],b,m,h,p,e)}return r(m,h)}});function w6(e,t,r,n){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;let o=e.filter((i)=>!Ja(i));if(o.length===1)return t.value=o[0].value,o[0];return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map((i)=>i.issues.map((s)=>lo(s,n,An())))}),t}var tg=D("$ZodUnion",(e,t)=>{Tt.init(e,t),_t(e._zod,"optin",()=>t.options.some((n)=>n._zod.optin==="optional")?"optional":void 0),_t(e._zod,"optout",()=>t.options.some((n)=>n._zod.optout==="optional")?"optional":void 0),_t(e._zod,"values",()=>{if(t.options.every((n)=>n._zod.values))return new Set(t.options.flatMap((n)=>Array.from(n._zod.values)));return}),_t(e._zod,"pattern",()=>{if(t.options.every((n)=>n._zod.pattern)){let n=t.options.map((o)=>o._zod.pattern);return new RegExp(`^(${n.map((o)=>Vh(o.source)).join("|")})$`)}return});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,o)=>{if(r)return r(n,o);let i=!1,s=[];for(let a of t.options){let c=a._zod.run({value:n.value,issues:[]},o);if(c instanceof Promise)s.push(c),i=!0;else{if(c.issues.length===0)return c;s.push(c)}}if(!i)return w6(s,n,e,o);return Promise.all(s).then((a)=>w6(a,n,e,o))}});var p_=D("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,tg.init(e,t);let r=e._zod.parse;_t(e._zod,"propValues",()=>{let o={};for(let i of t.options){let s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let[a,c]of Object.entries(s)){if(!o[a])o[a]=new Set;for(let d of c)o[a].add(d)}}return o});let n=Sp(()=>{let o=t.options,i=new Map;for(let s of o){let a=s._zod.propValues?.[t.discriminator];if(!a||a.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let c of a){if(i.has(c))throw Error(`Duplicate discriminator value "${String(c)}"`);i.set(c,s)}}return i});e._zod.parse=(o,i)=>{let s=o.value;if(!Pu(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),o;let a=n.value.get(s?.[t.discriminator]);if(a)return a._zod.run(o,i);if(t.unionFallback||i.direction==="backward")return r(o,i);return o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(n.value.keys()),input:s,path:[t.discriminator],inst:e}),o}}),f_=D("$ZodIntersection",(e,t)=>{Tt.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,i=t.left._zod.run({value:o,issues:[]},n),s=t.right._zod.run({value:o,issues:[]},n);if(i instanceof Promise||s instanceof Promise)return Promise.all([i,s]).then(([c,d])=>S6(r,c,d));return S6(r,i,s)}});function L1(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(Ya(e)&&Ya(t)){let r=Object.keys(t),n=Object.keys(e).filter((i)=>r.indexOf(i)!==-1),o={...e,...t};for(let i of n){let s=L1(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let o=e[n],i=t[n],s=L1(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function S6(e,t,r){let n=new Map,o;for(let a of t.issues)if(a.code==="unrecognized_keys"){o??(o=a);for(let c of a.keys){if(!n.has(c))n.set(c,{});n.get(c).l=!0}}else e.issues.push(a);for(let a of r.issues)if(a.code==="unrecognized_keys")for(let c of a.keys){if(!n.has(c))n.set(c,{});n.get(c).r=!0}else e.issues.push(a);let i=[...n].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(i.length&&o)e.issues.push({...o,keys:i});if(Ja(e))return e;let s=L1(t.value,r.value);if(!s.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}var m_=D("$ZodRecord",(e,t)=>{Tt.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Ya(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let i=[],s=t.keyType._zod.values;if(s){r.value={};let a=new Set;for(let d of s)if(typeof d==="string"||typeof d==="number"||typeof d==="symbol"){a.add(typeof d==="number"?d.toString():d);let l=t.keyType._zod.run({value:d,issues:[]},n);if(l instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(l.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map((h)=>lo(h,n,An())),input:d,path:[d],inst:e});continue}let p=l.value,m=t.valueType._zod.run({value:o[d],issues:[]},n);if(m instanceof Promise)i.push(m.then((h)=>{if(h.issues.length)r.issues.push(...Ls(d,h.issues));r.value[p]=h.value}));else{if(m.issues.length)r.issues.push(...Ls(d,m.issues));r.value[p]=m.value}}let c;for(let d in o)if(!a.has(d))c=c??[],c.push(d);if(c&&c.length>0)r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:c})}else{r.value={};for(let a of Reflect.ownKeys(o)){if(a==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(o,a))continue;let c=t.keyType._zod.run({value:a,issues:[]},n);if(c instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof a==="string"&&$1.test(a)&&c.issues.length){let p=t.keyType._zod.run({value:Number(a),issues:[]},n);if(p instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(p.issues.length===0)c=p}if(c.issues.length){if(t.mode==="loose")r.value[a]=o[a];else r.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map((p)=>lo(p,n,An())),input:a,path:[a],inst:e});continue}let l=t.valueType._zod.run({value:o[a],issues:[]},n);if(l instanceof Promise)i.push(l.then((p)=>{if(p.issues.length)r.issues.push(...Ls(a,p.issues));r.value[c.value]=p.value}));else{if(l.issues.length)r.issues.push(...Ls(a,l.issues));r.value[c.value]=l.value}}}if(i.length)return Promise.all(i).then(()=>r);return r}});var h_=D("$ZodEnum",(e,t)=>{Tt.init(e,t);let r=Hh(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter((o)=>c2.has(typeof o)).map((o)=>typeof o==="string"?Bs(o):o.toString()).join("|")})$`),e._zod.parse=(o,i)=>{let s=o.value;if(n.has(s))return o;return o.issues.push({code:"invalid_value",values:r,input:s,inst:e}),o}}),g_=D("$ZodLiteral",(e,t)=>{if(Tt.init(e,t),t.values.length===0)throw Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map((n)=>typeof n==="string"?Bs(n):n?Bs(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,o)=>{let i=n.value;if(r.has(i))return n;return n.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),n}});var y_=D("$ZodTransform",(e,t)=>{Tt.init(e,t),e._zod.optin="optional",e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new _p(e.constructor.name);let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then((s)=>(r.value=s,r.fallback=!0,r));if(o instanceof Promise)throw new Mi;return r.value=o,r.fallback=!0,r}});function v6(e,t){if(t===void 0&&(e.issues.length||e.fallback))return{issues:[],value:void 0};return e}var rg=D("$ZodOptional",(e,t)=>{Tt.init(e,t),e._zod.optin="optional",e._zod.optout="optional",_t(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),_t(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Vh(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(t.innerType._zod.optin==="optional"){let o=r.value,i=t.innerType._zod.run(r,n);if(i instanceof Promise)return i.then((s)=>v6(s,o));return v6(i,o)}if(r.value===void 0)return r;return t.innerType._zod.run(r,n)}}),b_=D("$ZodExactOptional",(e,t)=>{rg.init(e,t),_t(e._zod,"values",()=>t.innerType._zod.values),_t(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),x_=D("$ZodNullable",(e,t)=>{Tt.init(e,t),_t(e._zod,"optin",()=>t.innerType._zod.optin),_t(e._zod,"optout",()=>t.innerType._zod.optout),_t(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Vh(r.source)}|null)$`):void 0}),_t(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>{if(r.value===null)return r;return t.innerType._zod.run(r,n)}}),__=D("$ZodDefault",(e,t)=>{Tt.init(e,t),e._zod.optin="optional",_t(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then((i)=>T6(i,t));return T6(o,t)}});function T6(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var w_=D("$ZodPrefault",(e,t)=>{Tt.init(e,t),e._zod.optin="optional",_t(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)r.value=t.defaultValue;return t.innerType._zod.run(r,n)}}),S_=D("$ZodNonOptional",(e,t)=>{Tt.init(e,t),_t(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter((n)=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then((i)=>E6(i,e));return E6(o,e)}});function E6(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}var v_=D("$ZodCatch",(e,t)=>{Tt.init(e,t),e._zod.optin="optional",_t(e._zod,"optout",()=>t.innerType._zod.optout),_t(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then((i)=>{if(r.value=i.value,i.issues.length)r.value=t.catchValue({...r,error:{issues:i.issues.map((s)=>lo(s,n,An()))},input:r.value}),r.issues=[],r.fallback=!0;return r});if(r.value=o.value,o.issues.length)r.value=t.catchValue({...r,error:{issues:o.issues.map((i)=>lo(i,n,An()))},input:r.value}),r.issues=[],r.fallback=!0;return r}});var ng=D("$ZodPipe",(e,t)=>{Tt.init(e,t),_t(e._zod,"values",()=>t.in._zod.values),_t(e._zod,"optin",()=>t.in._zod.optin),_t(e._zod,"optout",()=>t.out._zod.optout),_t(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){let i=t.out._zod.run(r,n);if(i instanceof Promise)return i.then((s)=>Qh(s,t.in,n));return Qh(i,t.in,n)}let o=t.in._zod.run(r,n);if(o instanceof Promise)return o.then((i)=>Qh(i,t.out,n));return Qh(o,t.out,n)}});function Qh(e,t,r){if(e.issues.length)return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}var z6=D("$ZodPreprocess",(e,t)=>{ng.init(e,t)}),T_=D("$ZodReadonly",(e,t)=>{Tt.init(e,t),_t(e._zod,"propValues",()=>t.innerType._zod.propValues),_t(e._zod,"values",()=>t.innerType._zod.values),_t(e._zod,"optin",()=>t.innerType?._zod?.optin),_t(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then(P6);return P6(o)}});function P6(e){return e.value=Object.freeze(e.value),e}var E_=D("$ZodCustom",(e,t)=>{yr.init(e,t),Tt.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=(r)=>{let n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then((i)=>A6(i,r,n,e));A6(o,r,n,e);return}});function A6(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};if(n._zod.def.params)o.params=n._zod.def.params;t.issues.push(Qa(o))}}var EZ=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(o){return e[o]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};return(o)=>{switch(o.code){case"invalid_type":{let i=n[o.expected]??o.expected,s=b2(o.input),a=n[s]??s;return`Invalid input: expected ${i}, received ${a}`}case"invalid_value":if(o.values.length===1)return`Invalid input: expected ${O1(o.values[0])}`;return`Invalid option: expected one of ${I1(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=t(o.origin);if(s)return`Too big: expected ${o.origin??"value"} to have ${i}${o.maximum.toString()} ${s.unit??"elements"}`;return`Too big: expected ${o.origin??"value"} to be ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=t(o.origin);if(s)return`Too small: expected ${o.origin} to have ${i}${o.minimum.toString()} ${s.unit}`;return`Too small: expected ${o.origin} to be ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;if(i.format==="starts_with")return`Invalid string: must start with "${i.prefix}"`;if(i.format==="ends_with")return`Invalid string: must end with "${i.suffix}"`;if(i.format==="includes")return`Invalid string: must include "${i.includes}"`;if(i.format==="regex")return`Invalid string: must match pattern ${i.pattern}`;return`Invalid ${r[i.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${I1(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":if(o.options&&Array.isArray(o.options)&&o.options.length>0)return`Invalid discriminator value. Expected ${o.options.map((s)=>`'${s}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}};function P_(){return{localeError:EZ()}}var B6,Uhe=Symbol("ZodOutput"),Fhe=Symbol("ZodInput");class L6{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let r=t[0];if(this._map.set(e,r),r&&typeof r==="object"&&"id"in r)this._idmap.set(r.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};delete r.id;let n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function PZ(){return new L6}(B6=globalThis).__zod_globalRegistry??(B6.__zod_globalRegistry=PZ());var tc=globalThis.__zod_globalRegistry;function A_(e,t){return new e({type:"string",...xe(t)})}function I_(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...xe(t)})}function og(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...xe(t)})}function ig(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...xe(t)})}function k_(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...xe(t)})}function R_(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...xe(t)})}function O_(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...xe(t)})}function C_(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...xe(t)})}function M_(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...xe(t)})}function $_(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...xe(t)})}function N_(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...xe(t)})}function z_(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...xe(t)})}function B_(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...xe(t)})}function L_(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...xe(t)})}function D_(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...xe(t)})}function U_(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...xe(t)})}function F_(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...xe(t)})}function j_(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...xe(t)})}function q_(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...xe(t)})}function H_(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...xe(t)})}function G_(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...xe(t)})}function V_(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...xe(t)})}function Z_(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...xe(t)})}function D6(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...xe(t)})}function U6(e,t){return new e({type:"string",format:"date",check:"string_format",...xe(t)})}function F6(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...xe(t)})}function j6(e,t){return new e({type:"string",format:"duration",check:"string_format",...xe(t)})}function W_(e,t){return new e({type:"number",checks:[],...xe(t)})}function K_(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...xe(t)})}function Y_(e,t){return new e({type:"boolean",...xe(t)})}function J_(e,t){return new e({type:"bigint",...xe(t)})}function Q_(e,t){return new e({type:"null",...xe(t)})}function X_(e){return new e({type:"unknown"})}function ew(e,t){return new e({type:"never",...xe(t)})}function Au(e,t){return new N1({check:"less_than",...xe(t),value:e,inclusive:!1})}function Ds(e,t){return new N1({check:"less_than",...xe(t),value:e,inclusive:!0})}function Iu(e,t){return new z1({check:"greater_than",...xe(t),value:e,inclusive:!1})}function Go(e,t){return new z1({check:"greater_than",...xe(t),value:e,inclusive:!0})}function Op(e,t){return new s6({check:"multiple_of",...xe(t),value:e})}function sg(e,t){return new c6({check:"max_length",...xe(t),maximum:e})}function ku(e,t){return new u6({check:"min_length",...xe(t),minimum:e})}function ag(e,t){return new d6({check:"length_equals",...xe(t),length:e})}function tw(e,t){return new l6({check:"string_format",format:"regex",...xe(t),pattern:e})}function rw(e){return new p6({check:"string_format",format:"lowercase",...xe(e)})}function nw(e){return new f6({check:"string_format",format:"uppercase",...xe(e)})}function ow(e,t){return new m6({check:"string_format",format:"includes",...xe(t),includes:e})}function iw(e,t){return new h6({check:"string_format",format:"starts_with",...xe(t),prefix:e})}function sw(e,t){return new g6({check:"string_format",format:"ends_with",...xe(t),suffix:e})}function Us(e){return new y6({check:"overwrite",tx:e})}function aw(e){return Us((t)=>t.normalize(e))}function cw(){return Us((e)=>e.trim())}function uw(){return Us((e)=>e.toLowerCase())}function dw(){return Us((e)=>e.toUpperCase())}function lw(){return Us((e)=>s2(e))}function q6(e,t,r){return new e({type:"array",element:t,...xe(r)})}function pw(e,t,r){let n=xe(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function fw(e,t,r){return new e({type:"custom",check:"custom",fn:t,...xe(r)})}function mw(e,t){let r=AZ((n)=>(n.addIssue=(o)=>{if(typeof o==="string")n.issues.push(Qa(o,n.value,r._zod.def));else{let i=o;if(i.fatal)i.continue=!1;i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=r),i.continue??(i.continue=!r._zod.def.abort),n.issues.push(Qa(i))}},e(n.value,n)),t);return r}function AZ(e,t){let r=new yr({check:"custom",...xe(t)});return r._zod.check=e,r}function Mp(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??tc,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Rt(e,t,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,i=t.seen.get(e);if(i){if(i.count++,r.schemaPath.includes(e))i.cycle=r.path;return i.schema}let s={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,s);let a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{let l={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,l);else{let m=s.schema,h=t.processors[o.type];if(!h)throw Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);h(e,t,m,l)}let p=e._zod.parent;if(p){if(!s.ref)s.ref=p;Rt(p,t,l),t.seen.get(p).isParent=!0}}let c=t.metadataRegistry.get(e);if(c)Object.assign(s.schema,c);if(t.io==="input"&&Kr(e))delete s.schema.examples,delete s.schema.default;if(t.io==="input"&&"_prefault"in s.schema)(n=s.schema).default??(n.default=s.schema._prefault);return delete s.schema._prefault,t.seen.get(e).schema}function $p(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let n=new Map;for(let s of e.seen.entries()){let a=e.metadataRegistry.get(s[0])?.id;if(a){let c=n.get(a);if(c&&c!==s[0])throw Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,s[0])}}let o=(s)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let p=e.external.registry.get(s[0])?.id,m=e.external.uri??((b)=>b);if(p)return{ref:m(p)};let h=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=h,{defId:h,ref:`${m("__shared")}#/${a}/${h}`}}if(s[1]===r)return{ref:"#"};let d=`${"#"}/${a}/`,l=s[1].schema.id??`__schema${e.counter++}`;return{defId:l,ref:d+l}},i=(s)=>{if(s[1].schema.$ref)return;let a=s[1],{ref:c,defId:d}=o(s);if(a.def={...a.schema},d)a.defId=d;let l=a.schema;for(let p in l)delete l[p];l.$ref=c};if(e.cycles==="throw")for(let s of e.seen.entries()){let a=s[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
129
129
 
130
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of e.seen.entries()){let a=s[1];if(t===s[0]){i(s);continue}if(e.external){let d=e.external.registry.get(s[0])?.id;if(t!==s[0]&&d){i(s);continue}}if(e.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}if(a.count>1){if(e.reused==="ref"){i(s);continue}}}}function Np(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let n=(a)=>{let c=e.seen.get(a);if(c.ref===null)return;let d=c.def??c.schema,l={...d},p=c.ref;if(c.ref=null,p){n(p);let h=e.seen.get(p),b=h.schema;if(b.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))d.allOf=d.allOf??[],d.allOf.push(b);else Object.assign(d,b);if(Object.assign(d,l),a._zod.parent===p)for(let _ in d){if(_==="$ref"||_==="allOf")continue;if(!(_ in l))delete d[_]}if(b.$ref&&h.def)for(let _ in d){if(_==="$ref"||_==="allOf")continue;if(_ in h.def&&JSON.stringify(d[_])===JSON.stringify(h.def[_]))delete d[_]}}let m=a._zod.parent;if(m&&m!==p){n(m);let h=e.seen.get(m);if(h?.schema.$ref){if(d.$ref=h.schema.$ref,h.def)for(let b in d){if(b==="$ref"||b==="allOf")continue;if(b in h.def&&JSON.stringify(d[b])===JSON.stringify(h.def[b]))delete d[b]}}}e.override({zodSchema:a,jsonSchema:d,path:c.path??[]})};for(let a of[...e.seen.entries()].reverse())n(a[0]);let o={};if(e.target==="draft-2020-12")o.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")o.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")o.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");o.$id=e.external.uri(a)}Object.assign(o,r.def??r.schema);let i=e.metadataRegistry.get(t)?.id;if(i!==void 0&&o.id===i)delete o.id;let s=e.external?.defs??{};for(let a of e.seen.entries()){let c=a[1];if(c.def&&c.defId){if(c.def.id===c.defId)delete c.def.id;s[c.defId]=c.def}}if(e.external);else if(Object.keys(s).length>0)if(e.target==="draft-2020-12")o.$defs=s;else o.definitions=s;try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Cp(t,"input",e.processors),output:Cp(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function Kr(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return Kr(n.element,r);if(n.type==="set")return Kr(n.valueType,r);if(n.type==="lazy")return Kr(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return Kr(n.innerType,r);if(n.type==="intersection")return Kr(n.left,r)||Kr(n.right,r);if(n.type==="record"||n.type==="map")return Kr(n.keyType,r)||Kr(n.valueType,r);if(n.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return Kr(n.in,r)||Kr(n.out,r)}if(n.type==="object"){for(let o in n.shape)if(Kr(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(Kr(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(Kr(o,r))return!0;if(n.rest&&Kr(n.rest,r))return!0;return!1}return!1}var H6=(e,t={})=>(r)=>{let n=Mp({...r,processors:t});return Rt(e,n),$p(n,e),Np(n,e)},Cp=(e,t,r={})=>(n)=>{let{libraryOptions:o,target:i}=n??{},s=Mp({...o??{},target:i,io:t,processors:r});return Rt(e,s),$p(s,e),Np(s,e)};var IZ={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},hw=(e,t,r,n)=>{let o=r;o.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:d}=e._zod.bag;if(typeof i==="number")o.minLength=i;if(typeof s==="number")o.maxLength=s;if(a){if(o.format=IZ[a]??a,o.format==="")delete o.format;if(a==="time")delete o.format}if(d)o.contentEncoding=d;if(c&&c.size>0){let l=[...c];if(l.length===1)o.pattern=l[0].source;else if(l.length>1)o.allOf=[...l.map((p)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))]}},gw=(e,t,r,n)=>{let o=r,{minimum:i,maximum:s,format:a,multipleOf:c,exclusiveMaximum:d,exclusiveMinimum:l}=e._zod.bag;if(typeof a==="string"&&a.includes("int"))o.type="integer";else o.type="number";let p=typeof l==="number"&&l>=(i??Number.NEGATIVE_INFINITY),m=typeof d==="number"&&d<=(s??Number.POSITIVE_INFINITY),h=t.target==="draft-04"||t.target==="openapi-3.0";if(p)if(h)o.minimum=l,o.exclusiveMinimum=!0;else o.exclusiveMinimum=l;else if(typeof i==="number")o.minimum=i;if(m)if(h)o.maximum=d,o.exclusiveMaximum=!0;else o.exclusiveMaximum=d;else if(typeof s==="number")o.maximum=s;if(typeof c==="number")o.multipleOf=c},yw=(e,t,r,n)=>{r.type="boolean"},bw=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},V6=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},xw=(e,t,r,n)=>{if(t.target==="openapi-3.0")r.type="string",r.nullable=!0,r.enum=[null];else r.type="null"},Z6=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},W6=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},_w=(e,t,r,n)=>{r.not={}},K6=(e,t,r,n)=>{},ww=(e,t,r,n)=>{},Y6=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},Sw=(e,t,r,n)=>{let o=e._zod.def,i=Hh(o.entries);if(i.every((s)=>typeof s==="number"))r.type="number";if(i.every((s)=>typeof s==="string"))r.type="string";r.enum=i},vw=(e,t,r,n)=>{let o=e._zod.def,i=[];for(let s of o.values)if(s===void 0){if(t.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s==="bigint")if(t.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else i.push(Number(s));else i.push(s);if(i.length===0);else if(i.length===1){let s=i[0];if(r.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0")r.enum=[s];else r.const=s}else{if(i.every((s)=>typeof s==="number"))r.type="number";if(i.every((s)=>typeof s==="string"))r.type="string";if(i.every((s)=>typeof s==="boolean"))r.type="boolean";if(i.every((s)=>s===null))r.type="null";r.enum=i}},J6=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},Q6=(e,t,r,n)=>{let o=r,i=e._zod.pattern;if(!i)throw Error("Pattern not found in template literal");o.type="string",o.pattern=i.source},X6=(e,t,r,n)=>{let o=r,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:a,mime:c}=e._zod.bag;if(s!==void 0)i.minLength=s;if(a!==void 0)i.maxLength=a;if(c)if(c.length===1)i.contentMediaType=c[0],Object.assign(o,i);else Object.assign(o,i),o.anyOf=c.map((d)=>({contentMediaType:d}));else Object.assign(o,i)},e5=(e,t,r,n)=>{r.type="boolean"},Tw=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},t5=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},Ew=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},r5=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},n5=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},Pw=(e,t,r,n)=>{let o=r,i=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;if(typeof s==="number")o.minItems=s;if(typeof a==="number")o.maxItems=a;o.type="array",o.items=Rt(i.element,t,{...n,path:[...n.path,"items"]})},Aw=(e,t,r,n)=>{let o=r,i=e._zod.def;o.type="object",o.properties={};let s=i.shape;for(let d in s)o.properties[d]=Rt(s[d],t,{...n,path:[...n.path,"properties",d]});let a=new Set(Object.keys(s)),c=new Set([...a].filter((d)=>{let l=i.shape[d]._zod;if(t.io==="input")return l.optin===void 0;else return l.optout===void 0}));if(c.size>0)o.required=Array.from(c);if(i.catchall?._zod.def.type==="never")o.additionalProperties=!1;else if(!i.catchall){if(t.io==="output")o.additionalProperties=!1}else if(i.catchall)o.additionalProperties=Rt(i.catchall,t,{...n,path:[...n.path,"additionalProperties"]})},Iw=(e,t,r,n)=>{let o=e._zod.def,i=o.inclusive===!1,s=o.options.map((a,c)=>Rt(a,t,{...n,path:[...n.path,i?"oneOf":"anyOf",c]}));if(i)r.oneOf=s;else r.anyOf=s},kw=(e,t,r,n)=>{let o=e._zod.def,i=Rt(o.left,t,{...n,path:[...n.path,"allOf",0]}),s=Rt(o.right,t,{...n,path:[...n.path,"allOf",1]}),a=(d)=>("allOf"in d)&&Object.keys(d).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=c},o5=(e,t,r,n)=>{let o=r,i=e._zod.def;o.type="array";let s=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"?"items":t.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((m,h)=>Rt(m,t,{...n,path:[...n.path,s,h]})),d=i.rest?Rt(i.rest,t,{...n,path:[...n.path,a,...t.target==="openapi-3.0"?[i.items.length]:[]]}):null;if(t.target==="draft-2020-12"){if(o.prefixItems=c,d)o.items=d}else if(t.target==="openapi-3.0"){if(o.items={anyOf:c},d)o.items.anyOf.push(d);if(o.minItems=c.length,!d)o.maxItems=c.length}else if(o.items=c,d)o.additionalItems=d;let{minimum:l,maximum:p}=e._zod.bag;if(typeof l==="number")o.minItems=l;if(typeof p==="number")o.maxItems=p},Rw=(e,t,r,n)=>{let o=r,i=e._zod.def;o.type="object";let s=i.keyType,c=s._zod.bag?.patterns;if(i.mode==="loose"&&c&&c.size>0){let l=Rt(i.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(let p of c)o.patternProperties[p.source]=l}else{if(t.target==="draft-07"||t.target==="draft-2020-12")o.propertyNames=Rt(i.keyType,t,{...n,path:[...n.path,"propertyNames"]});o.additionalProperties=Rt(i.valueType,t,{...n,path:[...n.path,"additionalProperties"]})}let d=s._zod.values;if(d){let l=[...d].filter((p)=>typeof p==="string"||typeof p==="number");if(l.length>0)o.required=l}},Ow=(e,t,r,n)=>{let o=e._zod.def,i=Rt(o.innerType,t,n),s=t.seen.get(e);if(t.target==="openapi-3.0")s.ref=o.innerType,r.nullable=!0;else r.anyOf=[i,{type:"null"}]},Cw=(e,t,r,n)=>{let o=e._zod.def;Rt(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType},Mw=(e,t,r,n)=>{let o=e._zod.def;Rt(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},$w=(e,t,r,n)=>{let o=e._zod.def;Rt(o.innerType,t,n);let i=t.seen.get(e);if(i.ref=o.innerType,t.io==="input")r._prefault=JSON.parse(JSON.stringify(o.defaultValue))},Nw=(e,t,r,n)=>{let o=e._zod.def;Rt(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType;let s;try{s=o.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}r.default=s},zw=(e,t,r,n)=>{let o=e._zod.def,i=o.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?i?o.out:o.in:o.out;Rt(s,t,n);let a=t.seen.get(e);a.ref=s},Bw=(e,t,r,n)=>{let o=e._zod.def;Rt(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType,r.readOnly=!0},i5=(e,t,r,n)=>{let o=e._zod.def;Rt(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType},cg=(e,t,r,n)=>{let o=e._zod.def;Rt(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType},s5=(e,t,r,n)=>{let o=e._zod.innerType;Rt(o,t,n);let i=t.seen.get(e);i.ref=o},G6={string:hw,number:gw,boolean:yw,bigint:bw,symbol:V6,null:xw,undefined:Z6,void:W6,never:_w,any:K6,unknown:ww,date:Y6,enum:Sw,literal:vw,nan:J6,template_literal:Q6,file:X6,success:e5,custom:Tw,function:t5,transform:Ew,map:r5,set:n5,array:Pw,object:Aw,union:Iw,intersection:kw,tuple:o5,record:Rw,nullable:Ow,nonoptional:Cw,default:Mw,prefault:$w,catch:Nw,pipe:zw,readonly:Bw,promise:i5,optional:cg,lazy:s5};function Lw(e,t){if("_idmap"in e){let n=e,o=Mp({...t,processors:G6}),i={};for(let c of n._idmap.entries()){let[d,l]=c;Rt(l,o)}let s={},a={registry:n,uri:t?.uri,defs:i};o.external=a;for(let c of n._idmap.entries()){let[d,l]=c;$p(o,l),s[d]=Np(o,l)}if(Object.keys(i).length>0){let c=o.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[c]:i}}return{schemas:s}}let r=Mp({...t,processors:G6});return Rt(e,r),$p(r,e),Np(r,e)}var hW=D("ZodMiniType",(e,t)=>{if(!e._zod)throw Error("Uninitialized schema in ZodMiniType.");Tt.init(e,t),e.def=t,e.type=t.type,e.parse=(r,n)=>Yh(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Xa(e,r,n),e.parseAsync=async(r,n)=>Jh(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>ec(e,r,n),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map((n)=>typeof n==="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]},{parent:!0}),e.with=e.check,e.clone=(r,n)=>jn(e,r,n),e.brand=()=>e,e.register=(r,n)=>(r.add(e,n),e),e.apply=(r)=>r(e)});var gW=D("ZodMiniObject",(e,t)=>{l_.init(e,t),hW.init(e,t),_t(e,"shape",()=>t.shape)});function Dw(e,t){let r={type:"object",shape:e??{},...xe(t)};return new gW(r)}function qn(e){return!!e._zod}function nc(e){let t=Object.values(e);if(t.length===0)return Dw({});let r=t.every(qn),n=t.every((o)=>!qn(o));if(r)return Dw(e);if(n)return r2(e);throw Error("Mixed Zod versions detected in object shape.")}function Fs(e,t){if(qn(e))return Xa(e,t);return e.safeParse(t)}async function ug(e,t){if(qn(e))return await ec(e,t);return await e.safeParseAsync(t)}function js(e){if(!e)return;let t;if(qn(e))t=e._zod?.def?.shape;else t=e.shape;if(!t)return;if(typeof t==="function")try{return t()}catch{return}return t}function Ru(e){if(!e)return;if(typeof e==="object"){let t=e,r=e;if(!t._def&&!r._zod){let n=Object.values(e);if(n.length>0&&n.every((o)=>typeof o==="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse==="function")))return nc(e)}}if(qn(e)){let r=e._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return e}else if(e.shape!==void 0)return e;return}function dg(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 c5(e){return e.description}function u5(e){if(qn(e))return e._zod?.def?.type==="optional";let t=e;if(typeof e.isOptional==="function")return e.isOptional();return t._def?.typeName==="ZodOptional"}function lg(e){if(qn(e)){let i=e._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}let r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=e.value;if(n!==void 0)return n;return}var Ou={};ZH(Ou,{ZodISODate:()=>l5,ZodISODateTime:()=>d5,ZodISODuration:()=>f5,ZodISOTime:()=>p5,date:()=>Uw,datetime:()=>pg,duration:()=>jw,time:()=>Fw});var d5=D("ZodISODateTime",(e,t)=>{I6.init(e,t),jt.init(e,t)});function pg(e){return D6(d5,e)}var l5=D("ZodISODate",(e,t)=>{k6.init(e,t),jt.init(e,t)});function Uw(e){return U6(l5,e)}var p5=D("ZodISOTime",(e,t)=>{R6.init(e,t),jt.init(e,t)});function Fw(e){return F6(p5,e)}var f5=D("ZodISODuration",(e,t)=>{O6.init(e,t),jt.init(e,t)});function jw(e){return j6(f5,e)}var TW=(e,t)=>{Kh.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(r)=>w2(e,r)},flatten:{value:(r)=>_2(e,r)},addIssue:{value:(r)=>{e.issues.push(r),e.message=JSON.stringify(e.issues,wp,2)}},addIssues:{value:(r)=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,wp,2)}},isEmpty:{get(){return e.issues.length===0}}})};var In=D("ZodError",TW,{Parent:Error});var m5=Tp(In),h5=Ep(In),g5=Pp(In),y5=Ap(In),b5=S2(In),x5=v2(In),_5=T2(In),w5=E2(In),S5=P2(In),v5=A2(In),T5=I2(In),E5=k2(In);var P5=new WeakMap;function Bp(e,t,r){let n=Object.getPrototypeOf(e),o=P5.get(n);if(!o)o=new Set,P5.set(n,o);if(o.has(t))return;o.add(t);for(let i in r){let s=r[i];Object.defineProperty(n,i,{configurable:!0,enumerable:!1,get(){let a=s.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}var Dt=D("ZodType",(e,t)=>(Tt.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Cp(e,"input"),output:Cp(e,"output")}}),e.toJSONSchema=H6(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(r,n)=>m5(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>g5(e,r,n),e.parseAsync=async(r,n)=>h5(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>y5(e,r,n),e.spa=e.safeParseAsync,e.encode=(r,n)=>b5(e,r,n),e.decode=(r,n)=>x5(e,r,n),e.encodeAsync=async(r,n)=>_5(e,r,n),e.decodeAsync=async(r,n)=>w5(e,r,n),e.safeEncode=(r,n)=>S5(e,r,n),e.safeDecode=(r,n)=>v5(e,r,n),e.safeEncodeAsync=async(r,n)=>T5(e,r,n),e.safeDecodeAsync=async(r,n)=>E5(e,r,n),Bp(e,"ZodType",{check(...r){let n=this.def;return this.clone(zs(n,{checks:[...n.checks??[],...r.map((o)=>typeof o==="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,n){return jn(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(mK(r,n))},superRefine(r,n){return this.check(hK(r,n))},overwrite(r){return this.check(Us(r))},optional(){return qt(this)},exactOptional(){return rK(this)},nullable(){return R5(this)},nullish(){return qt(R5(this))},nonoptional(r){return cK(this,r)},array(){return Ie(this)},or(r){return st([this,r])},and(r){return fg(this,r)},transform(r){return O5(this,D5(r))},default(r){return iK(this,r)},prefault(r){return aK(this,r)},catch(r){return dK(this,r)},pipe(r){return O5(this,r)},readonly(){return fK(this)},describe(r){let n=this.clone();return tc.add(n,{description:r}),n},meta(...r){if(r.length===0)return tc.get(this);let n=this.clone();return tc.add(n,r[0]),n},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(e,"description",{get(){return tc.get(e)?.description},configurable:!0}),e)),C5=D("_ZodString",(e,t)=>{Rp.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>hw(e,n,o,i);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,Bp(e,"_ZodString",{regex(...n){return this.check(tw(...n))},includes(...n){return this.check(ow(...n))},startsWith(...n){return this.check(iw(...n))},endsWith(...n){return this.check(sw(...n))},min(...n){return this.check(ku(...n))},max(...n){return this.check(sg(...n))},length(...n){return this.check(ag(...n))},nonempty(...n){return this.check(ku(1,...n))},lowercase(n){return this.check(rw(n))},uppercase(n){return this.check(nw(n))},trim(){return this.check(cw())},normalize(...n){return this.check(aw(...n))},toLowerCase(){return this.check(uw())},toUpperCase(){return this.check(dw())},slugify(){return this.check(lw())}})}),PW=D("ZodString",(e,t)=>{Rp.init(e,t),C5.init(e,t),e.email=(r)=>e.check(I_(AW,r)),e.url=(r)=>e.check(C_(IW,r)),e.jwt=(r)=>e.check(Z_(qW,r)),e.emoji=(r)=>e.check(M_(kW,r)),e.guid=(r)=>e.check(og(A5,r)),e.uuid=(r)=>e.check(ig(zp,r)),e.uuidv4=(r)=>e.check(k_(zp,r)),e.uuidv6=(r)=>e.check(R_(zp,r)),e.uuidv7=(r)=>e.check(O_(zp,r)),e.nanoid=(r)=>e.check($_(RW,r)),e.guid=(r)=>e.check(og(A5,r)),e.cuid=(r)=>e.check(N_(OW,r)),e.cuid2=(r)=>e.check(z_(CW,r)),e.ulid=(r)=>e.check(B_(MW,r)),e.base64=(r)=>e.check(H_(UW,r)),e.base64url=(r)=>e.check(G_(FW,r)),e.xid=(r)=>e.check(L_($W,r)),e.ksuid=(r)=>e.check(D_(NW,r)),e.ipv4=(r)=>e.check(U_(zW,r)),e.ipv6=(r)=>e.check(F_(BW,r)),e.cidrv4=(r)=>e.check(j_(LW,r)),e.cidrv6=(r)=>e.check(q_(DW,r)),e.e164=(r)=>e.check(V_(jW,r)),e.datetime=(r)=>e.check(pg(r)),e.date=(r)=>e.check(Uw(r)),e.time=(r)=>e.check(Fw(r)),e.duration=(r)=>e.check(jw(r))});function y(e){return A_(PW,e)}var jt=D("ZodStringFormat",(e,t)=>{Nt.init(e,t),C5.init(e,t)}),AW=D("ZodEmail",(e,t)=>{F1.init(e,t),jt.init(e,t)});var A5=D("ZodGUID",(e,t)=>{D1.init(e,t),jt.init(e,t)});var zp=D("ZodUUID",(e,t)=>{U1.init(e,t),jt.init(e,t)});function M5(e){return ig(zp,e)}var IW=D("ZodURL",(e,t)=>{j1.init(e,t),jt.init(e,t)});var kW=D("ZodEmoji",(e,t)=>{q1.init(e,t),jt.init(e,t)});var RW=D("ZodNanoID",(e,t)=>{H1.init(e,t),jt.init(e,t)});var OW=D("ZodCUID",(e,t)=>{G1.init(e,t),jt.init(e,t)});var CW=D("ZodCUID2",(e,t)=>{V1.init(e,t),jt.init(e,t)});var MW=D("ZodULID",(e,t)=>{Z1.init(e,t),jt.init(e,t)});var $W=D("ZodXID",(e,t)=>{W1.init(e,t),jt.init(e,t)});var NW=D("ZodKSUID",(e,t)=>{K1.init(e,t),jt.init(e,t)});var zW=D("ZodIPv4",(e,t)=>{Y1.init(e,t),jt.init(e,t)});var BW=D("ZodIPv6",(e,t)=>{J1.init(e,t),jt.init(e,t)});var LW=D("ZodCIDRv4",(e,t)=>{Q1.init(e,t),jt.init(e,t)});var DW=D("ZodCIDRv6",(e,t)=>{X1.init(e,t),jt.init(e,t)});var UW=D("ZodBase64",(e,t)=>{e_.init(e,t),jt.init(e,t)});var FW=D("ZodBase64URL",(e,t)=>{t_.init(e,t),jt.init(e,t)});var jW=D("ZodE164",(e,t)=>{r_.init(e,t),jt.init(e,t)});var qW=D("ZodJWT",(e,t)=>{n_.init(e,t),jt.init(e,t)});var $5=D("ZodNumber",(e,t)=>{eg.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>gw(e,n,o,i),Bp(e,"ZodNumber",{gt(n,o){return this.check(Iu(n,o))},gte(n,o){return this.check(Go(n,o))},min(n,o){return this.check(Go(n,o))},lt(n,o){return this.check(Au(n,o))},lte(n,o){return this.check(Ds(n,o))},max(n,o){return this.check(Ds(n,o))},int(n){return this.check(I5(n))},safe(n){return this.check(I5(n))},positive(n){return this.check(Iu(0,n))},nonnegative(n){return this.check(Go(0,n))},negative(n){return this.check(Au(0,n))},nonpositive(n){return this.check(Ds(0,n))},multipleOf(n,o){return this.check(Op(n,o))},step(n,o){return this.check(Op(n,o))},finite(){return this}});let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??0.5),e.isFinite=!0,e.format=r.format??null});function M(e){return W_($5,e)}var HW=D("ZodNumberFormat",(e,t)=>{o_.init(e,t),$5.init(e,t)});function I5(e){return K_(HW,e)}var GW=D("ZodBoolean",(e,t)=>{i_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>yw(e,r,n,o)});function ue(e){return Y_(GW,e)}var VW=D("ZodBigInt",(e,t)=>{s_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>bw(e,n,o,i),e.gte=(n,o)=>e.check(Go(n,o)),e.min=(n,o)=>e.check(Go(n,o)),e.gt=(n,o)=>e.check(Iu(n,o)),e.gte=(n,o)=>e.check(Go(n,o)),e.min=(n,o)=>e.check(Go(n,o)),e.lt=(n,o)=>e.check(Au(n,o)),e.lte=(n,o)=>e.check(Ds(n,o)),e.max=(n,o)=>e.check(Ds(n,o)),e.positive=(n)=>e.check(Iu(BigInt(0),n)),e.negative=(n)=>e.check(Au(BigInt(0),n)),e.nonpositive=(n)=>e.check(Ds(BigInt(0),n)),e.nonnegative=(n)=>e.check(Go(BigInt(0),n)),e.multipleOf=(n,o)=>e.check(Op(n,o));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});function N5(e){return J_(VW,e)}var ZW=D("ZodNull",(e,t)=>{a_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>xw(e,r,n,o)});function z5(e){return Q_(ZW,e)}var WW=D("ZodUnknown",(e,t)=>{c_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ww(e,r,n,o)});function Et(){return X_(WW)}var KW=D("ZodNever",(e,t)=>{u_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>_w(e,r,n,o)});function kn(e){return ew(KW,e)}var YW=D("ZodArray",(e,t)=>{d_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Pw(e,r,n,o),e.element=t.element,Bp(e,"ZodArray",{min(r,n){return this.check(ku(r,n))},nonempty(r){return this.check(ku(1,r))},max(r,n){return this.check(sg(r,n))},length(r,n){return this.check(ag(r,n))},unwrap(){return this.element}})});function Ie(e,t){return q6(YW,e,t)}var B5=D("ZodObject",(e,t)=>{N6.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Aw(e,r,n,o),_t(e,"shape",()=>t.shape),Bp(e,"ZodObject",{keyof(){return H(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:Et()})},loose(){return this.clone({...this._zod.def,catchall:Et()})},strict(){return this.clone({...this._zod.def,catchall:kn()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return f2(this,r)},safeExtend(r){return m2(this,r)},merge(r){return _Z(this,r)},pick(r){return l2(this,r)},omit(r){return p2(this,r)},partial(...r){return h2(mg,this,r[0])},required(...r){return g2(U5,this,r[0])}})});function S(e,t){let r={type:"object",shape:e??{},...xe(t)};return new B5(r)}function Yr(e,t){return new B5({type:"object",shape:e,catchall:Et(),...xe(t)})}var L5=D("ZodUnion",(e,t)=>{tg.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Iw(e,r,n,o),e.options=t.options});function st(e,t){return new L5({type:"union",options:e,...xe(t)})}var JW=D("ZodDiscriminatedUnion",(e,t)=>{L5.init(e,t),p_.init(e,t)});function Hw(e,t,r){return new JW({type:"union",options:t,discriminator:e,...xe(r)})}var QW=D("ZodIntersection",(e,t)=>{f_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>kw(e,r,n,o)});function fg(e,t){return new QW({type:"intersection",left:e,right:t})}var k5=D("ZodRecord",(e,t)=>{m_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Rw(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType});function zt(e,t,r){if(!t||!t._zod)return new k5({type:"record",keyType:y(),valueType:e,...xe(t)});return new k5({type:"record",keyType:e,valueType:t,...xe(r)})}var qw=D("ZodEnum",(e,t)=>{h_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Sw(e,n,o,i),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let i={};for(let s of n)if(r.has(s))i[s]=t.entries[s];else throw Error(`Key ${s} not found in enum`);return new qw({...t,checks:[],...xe(o),entries:i})},e.exclude=(n,o)=>{let i={...t.entries};for(let s of n)if(r.has(s))delete i[s];else throw Error(`Key ${s} not found in enum`);return new qw({...t,checks:[],...xe(o),entries:i})}});function H(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((n)=>[n,n])):e;return new qw({type:"enum",entries:r,...xe(t)})}var XW=D("ZodLiteral",(e,t)=>{g_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>vw(e,r,n,o),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function _e(e,t){return new XW({type:"literal",values:Array.isArray(e)?e:[e],...xe(t)})}var eK=D("ZodTransform",(e,t)=>{y_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Ew(e,r,n,o),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new _p(e.constructor.name);r.addIssue=(i)=>{if(typeof i==="string")r.issues.push(Qa(i,r.value,t));else{let s=i;if(s.fatal)s.continue=!1;s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),r.issues.push(Qa(s))}};let o=t.transform(r.value,r);if(o instanceof Promise)return o.then((i)=>(r.value=i,r.fallback=!0,r));return r.value=o,r.fallback=!0,r}});function D5(e){return new eK({type:"transform",transform:e})}var mg=D("ZodOptional",(e,t)=>{rg.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>cg(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function qt(e){return new mg({type:"optional",innerType:e})}var tK=D("ZodExactOptional",(e,t)=>{b_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>cg(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function rK(e){return new tK({type:"optional",innerType:e})}var nK=D("ZodNullable",(e,t)=>{x_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Ow(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function R5(e){return new nK({type:"nullable",innerType:e})}var oK=D("ZodDefault",(e,t)=>{__.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Mw(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function iK(e,t){return new oK({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Zh(t)}})}var sK=D("ZodPrefault",(e,t)=>{w_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>$w(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function aK(e,t){return new sK({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Zh(t)}})}var U5=D("ZodNonOptional",(e,t)=>{S_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Cw(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function cK(e,t){return new U5({type:"nonoptional",innerType:e,...xe(t)})}var uK=D("ZodCatch",(e,t)=>{v_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Nw(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function dK(e,t){return new uK({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}var F5=D("ZodPipe",(e,t)=>{ng.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>zw(e,r,n,o),e.in=t.in,e.out=t.out});function O5(e,t){return new F5({type:"pipe",in:e,out:t})}var lK=D("ZodPreprocess",(e,t)=>{F5.init(e,t),z6.init(e,t)}),pK=D("ZodReadonly",(e,t)=>{T_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Bw(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function fK(e){return new pK({type:"readonly",innerType:e})}var j5=D("ZodCustom",(e,t)=>{E_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Tw(e,r,n,o)});function q5(e,t){return pw(j5,e??(()=>!0),t)}function mK(e,t={}){return fw(j5,e,t)}function hK(e,t){return mw(e,t)}function Lp(e,t){return new lK({type:"pipe",in:D5(e),out:t})}var Hn={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var H5;(function(e){})(H5||(H5={}));An(P_());var Gw="2025-11-25";var G5=[Gw,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],qs="io.modelcontextprotocol/related-task",gg="2.0",ur=q5((e)=>e!==null&&(typeof e==="object"||typeof e==="function")),V5=st([y(),M().int()]),Z5=y(),Yge=Yr({ttl:M().optional(),pollInterval:M().optional()}),gK=S({ttl:M().optional()}),yK=S({taskId:y()}),Vw=Yr({progressToken:V5.optional(),[qs]:yK.optional()}),Rn=S({_meta:Vw.optional()}),Dp=Rn.extend({task:gK.optional()}),W5=(e)=>Dp.safeParse(e).success,Ir=S({method:y(),params:Rn.loose().optional()}),Gn=S({_meta:Vw.optional()}),Vn=S({method:y(),params:Gn.loose().optional()}),kr=Yr({_meta:Vw.optional()}),yg=st([y(),M().int()]),K5=S({jsonrpc:_e(gg),id:yg,...Ir.shape}).strict(),Zw=(e)=>K5.safeParse(e).success,Y5=S({jsonrpc:_e(gg),...Vn.shape}).strict(),J5=(e)=>Y5.safeParse(e).success,Ww=S({jsonrpc:_e(gg),id:yg,result:kr}).strict(),Up=(e)=>Ww.safeParse(e).success;var Me;(function(e){e[e.ConnectionClosed=-32000]="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"})(Me||(Me={}));var Kw=S({jsonrpc:_e(gg),id:yg.optional(),error:S({code:M().int(),message:y(),data:Et().optional()})}).strict();var Q5=(e)=>Kw.safeParse(e).success;var X5=st([K5,Y5,Ww,Kw]),Jge=st([Ww,Kw]),bg=kr.strict(),bK=Gn.extend({requestId:yg.optional(),reason:y().optional()}),xg=Vn.extend({method:_e("notifications/cancelled"),params:bK}),xK=S({src:y(),mimeType:y().optional(),sizes:Ie(y()).optional(),theme:H(["light","dark"]).optional()}),Fp=S({icons:Ie(xK).optional()}),Cu=S({name:y(),title:y().optional()}),eO=Cu.extend({...Cu.shape,...Fp.shape,version:y(),websiteUrl:y().optional(),description:y().optional()}),_K=fg(S({applyDefaults:ue().optional()}),zt(y(),Et())),wK=Lp((e)=>{if(e&&typeof e==="object"&&!Array.isArray(e)){if(Object.keys(e).length===0)return{form:{}}}return e},fg(S({form:_K.optional(),url:ur.optional()}),zt(y(),Et()).optional())),SK=Yr({list:ur.optional(),cancel:ur.optional(),requests:Yr({sampling:Yr({createMessage:ur.optional()}).optional(),elicitation:Yr({create:ur.optional()}).optional()}).optional()}),vK=Yr({list:ur.optional(),cancel:ur.optional(),requests:Yr({tools:Yr({call:ur.optional()}).optional()}).optional()}),TK=S({experimental:zt(y(),ur).optional(),sampling:S({context:ur.optional(),tools:ur.optional()}).optional(),elicitation:wK.optional(),roots:S({listChanged:ue().optional()}).optional(),tasks:SK.optional(),extensions:zt(y(),ur).optional()}),EK=Rn.extend({protocolVersion:y(),capabilities:TK,clientInfo:eO}),Yw=Ir.extend({method:_e("initialize"),params:EK});var PK=S({experimental:zt(y(),ur).optional(),logging:ur.optional(),completions:ur.optional(),prompts:S({listChanged:ue().optional()}).optional(),resources:S({subscribe:ue().optional(),listChanged:ue().optional()}).optional(),tools:S({listChanged:ue().optional()}).optional(),tasks:vK.optional(),extensions:zt(y(),ur).optional()}),AK=kr.extend({protocolVersion:y(),capabilities:PK,serverInfo:eO,instructions:y().optional()}),Jw=Vn.extend({method:_e("notifications/initialized"),params:Gn.optional()});var _g=Ir.extend({method:_e("ping"),params:Rn.optional()}),IK=S({progress:M(),total:qt(M()),message:qt(y())}),kK=S({...Gn.shape,...IK.shape,progressToken:V5}),wg=Vn.extend({method:_e("notifications/progress"),params:kK}),RK=Rn.extend({cursor:Z5.optional()}),jp=Ir.extend({params:RK.optional()}),qp=kr.extend({nextCursor:Z5.optional()}),OK=H(["working","input_required","completed","failed","cancelled"]),Hp=S({taskId:y(),status:OK,ttl:st([M(),z5()]),createdAt:y(),lastUpdatedAt:y(),pollInterval:qt(M()),statusMessage:qt(y())}),Mu=kr.extend({task:Hp}),CK=Gn.merge(Hp),Gp=Vn.extend({method:_e("notifications/tasks/status"),params:CK}),Sg=Ir.extend({method:_e("tasks/get"),params:Rn.extend({taskId:y()})}),vg=kr.merge(Hp),Tg=Ir.extend({method:_e("tasks/result"),params:Rn.extend({taskId:y()})}),Qge=kr.loose(),Eg=jp.extend({method:_e("tasks/list")}),Pg=qp.extend({tasks:Ie(Hp)}),Ag=Ir.extend({method:_e("tasks/cancel"),params:Rn.extend({taskId:y()})}),tO=kr.merge(Hp),rO=S({uri:y(),mimeType:qt(y()),_meta:zt(y(),Et()).optional()}),nO=rO.extend({text:y()}),Qw=y().refine((e)=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),oO=rO.extend({blob:Qw}),Vp=H(["user","assistant"]),$u=S({audience:Ie(Vp).optional(),priority:M().min(0).max(1).optional(),lastModified:pg({offset:!0}).optional()}),iO=S({...Cu.shape,...Fp.shape,uri:y(),description:qt(y()),mimeType:qt(y()),size:qt(M()),annotations:$u.optional(),_meta:qt(Yr({}))}),MK=S({...Cu.shape,...Fp.shape,uriTemplate:y(),description:qt(y()),mimeType:qt(y()),annotations:$u.optional(),_meta:qt(Yr({}))}),Ig=jp.extend({method:_e("resources/list")}),$K=qp.extend({resources:Ie(iO)}),kg=jp.extend({method:_e("resources/templates/list")}),NK=qp.extend({resourceTemplates:Ie(MK)}),Xw=Rn.extend({uri:y()}),zK=Xw,Rg=Ir.extend({method:_e("resources/read"),params:zK}),BK=kr.extend({contents:Ie(st([nO,oO]))}),LK=Vn.extend({method:_e("notifications/resources/list_changed"),params:Gn.optional()}),DK=Xw,UK=Ir.extend({method:_e("resources/subscribe"),params:DK}),FK=Xw,jK=Ir.extend({method:_e("resources/unsubscribe"),params:FK}),qK=Gn.extend({uri:y()}),HK=Vn.extend({method:_e("notifications/resources/updated"),params:qK}),GK=S({name:y(),description:qt(y()),required:qt(ue())}),VK=S({...Cu.shape,...Fp.shape,description:qt(y()),arguments:qt(Ie(GK)),_meta:qt(Yr({}))}),Og=jp.extend({method:_e("prompts/list")}),ZK=qp.extend({prompts:Ie(VK)}),WK=Rn.extend({name:y(),arguments:zt(y(),y()).optional()}),Cg=Ir.extend({method:_e("prompts/get"),params:WK}),eS=S({type:_e("text"),text:y(),annotations:$u.optional(),_meta:zt(y(),Et()).optional()}),tS=S({type:_e("image"),data:Qw,mimeType:y(),annotations:$u.optional(),_meta:zt(y(),Et()).optional()}),rS=S({type:_e("audio"),data:Qw,mimeType:y(),annotations:$u.optional(),_meta:zt(y(),Et()).optional()}),KK=S({type:_e("tool_use"),name:y(),id:y(),input:zt(y(),Et()),_meta:zt(y(),Et()).optional()}),YK=S({type:_e("resource"),resource:st([nO,oO]),annotations:$u.optional(),_meta:zt(y(),Et()).optional()}),JK=iO.extend({type:_e("resource_link")}),nS=st([eS,tS,rS,JK,YK]),QK=S({role:Vp,content:nS}),XK=kr.extend({description:y().optional(),messages:Ie(QK)}),eY=Vn.extend({method:_e("notifications/prompts/list_changed"),params:Gn.optional()}),tY=S({title:y().optional(),readOnlyHint:ue().optional(),destructiveHint:ue().optional(),idempotentHint:ue().optional(),openWorldHint:ue().optional()}),rY=S({taskSupport:H(["required","optional","forbidden"]).optional()}),sO=S({...Cu.shape,...Fp.shape,description:y().optional(),inputSchema:S({type:_e("object"),properties:zt(y(),ur).optional(),required:Ie(y()).optional()}).catchall(Et()),outputSchema:S({type:_e("object"),properties:zt(y(),ur).optional(),required:Ie(y()).optional()}).catchall(Et()).optional(),annotations:tY.optional(),execution:rY.optional(),_meta:zt(y(),Et()).optional()}),Mg=jp.extend({method:_e("tools/list")}),nY=qp.extend({tools:Ie(sO)}),$g=kr.extend({content:Ie(nS).default([]),structuredContent:zt(y(),Et()).optional(),isError:ue().optional()}),Xge=$g.or(kr.extend({toolResult:Et()})),oY=Dp.extend({name:y(),arguments:zt(y(),Et()).optional()}),Nu=Ir.extend({method:_e("tools/call"),params:oY}),iY=Vn.extend({method:_e("notifications/tools/list_changed"),params:Gn.optional()}),e0e=S({autoRefresh:ue().default(!0),debounceMs:M().int().nonnegative().default(300)}),Zp=H(["debug","info","notice","warning","error","critical","alert","emergency"]),sY=Rn.extend({level:Zp}),oS=Ir.extend({method:_e("logging/setLevel"),params:sY}),aY=Gn.extend({level:Zp,logger:y().optional(),data:Et()}),cY=Vn.extend({method:_e("notifications/message"),params:aY}),uY=S({name:y().optional()}),dY=S({hints:Ie(uY).optional(),costPriority:M().min(0).max(1).optional(),speedPriority:M().min(0).max(1).optional(),intelligencePriority:M().min(0).max(1).optional()}),lY=S({mode:H(["auto","required","none"]).optional()}),pY=S({type:_e("tool_result"),toolUseId:y().describe("The unique identifier for the corresponding tool call."),content:Ie(nS).default([]),structuredContent:S({}).loose().optional(),isError:ue().optional(),_meta:zt(y(),Et()).optional()}),fY=Hw("type",[eS,tS,rS]),hg=Hw("type",[eS,tS,rS,KK,pY]),mY=S({role:Vp,content:st([hg,Ie(hg)]),_meta:zt(y(),Et()).optional()}),hY=Dp.extend({messages:Ie(mY),modelPreferences:dY.optional(),systemPrompt:y().optional(),includeContext:H(["none","thisServer","allServers"]).optional(),temperature:M().optional(),maxTokens:M().int(),stopSequences:Ie(y()).optional(),metadata:ur.optional(),tools:Ie(sO).optional(),toolChoice:lY.optional()}),gY=Ir.extend({method:_e("sampling/createMessage"),params:hY}),Wp=kr.extend({model:y(),stopReason:qt(H(["endTurn","stopSequence","maxTokens"]).or(y())),role:Vp,content:fY}),iS=kr.extend({model:y(),stopReason:qt(H(["endTurn","stopSequence","maxTokens","toolUse"]).or(y())),role:Vp,content:st([hg,Ie(hg)])}),yY=S({type:_e("boolean"),title:y().optional(),description:y().optional(),default:ue().optional()}),bY=S({type:_e("string"),title:y().optional(),description:y().optional(),minLength:M().optional(),maxLength:M().optional(),format:H(["email","uri","date","date-time"]).optional(),default:y().optional()}),xY=S({type:H(["number","integer"]),title:y().optional(),description:y().optional(),minimum:M().optional(),maximum:M().optional(),default:M().optional()}),_Y=S({type:_e("string"),title:y().optional(),description:y().optional(),enum:Ie(y()),default:y().optional()}),wY=S({type:_e("string"),title:y().optional(),description:y().optional(),oneOf:Ie(S({const:y(),title:y()})),default:y().optional()}),SY=S({type:_e("string"),title:y().optional(),description:y().optional(),enum:Ie(y()),enumNames:Ie(y()).optional(),default:y().optional()}),vY=st([_Y,wY]),TY=S({type:_e("array"),title:y().optional(),description:y().optional(),minItems:M().optional(),maxItems:M().optional(),items:S({type:_e("string"),enum:Ie(y())}),default:Ie(y()).optional()}),EY=S({type:_e("array"),title:y().optional(),description:y().optional(),minItems:M().optional(),maxItems:M().optional(),items:S({anyOf:Ie(S({const:y(),title:y()}))}),default:Ie(y()).optional()}),PY=st([TY,EY]),AY=st([SY,vY,PY]),IY=st([AY,yY,bY,xY]),kY=Dp.extend({mode:_e("form").optional(),message:y(),requestedSchema:S({type:_e("object"),properties:zt(y(),IY),required:Ie(y()).optional()})}),RY=Dp.extend({mode:_e("url"),message:y(),elicitationId:y(),url:y().url()}),OY=st([kY,RY]),CY=Ir.extend({method:_e("elicitation/create"),params:OY}),MY=Gn.extend({elicitationId:y()}),$Y=Vn.extend({method:_e("notifications/elicitation/complete"),params:MY}),zu=kr.extend({action:H(["accept","decline","cancel"]),content:Lp((e)=>e===null?void 0:e,zt(y(),st([y(),M(),ue(),Ie(y())])).optional())}),NY=S({type:_e("ref/resource"),uri:y()});var zY=S({type:_e("ref/prompt"),name:y()}),BY=Rn.extend({ref:st([zY,NY]),argument:S({name:y(),value:y()}),context:S({arguments:zt(y(),y()).optional()}).optional()}),Ng=Ir.extend({method:_e("completion/complete"),params:BY});function aO(e){if(e.params.ref.type!=="ref/prompt")throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function cO(e){if(e.params.ref.type!=="ref/resource")throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}var LY=kr.extend({completion:Yr({values:Ie(y()).max(100),total:qt(M().int()),hasMore:qt(ue())})}),DY=S({uri:y().startsWith("file://"),name:y().optional(),_meta:zt(y(),Et()).optional()}),UY=Ir.extend({method:_e("roots/list"),params:Rn.optional()}),sS=kr.extend({roots:Ie(DY)}),FY=Vn.extend({method:_e("notifications/roots/list_changed"),params:Gn.optional()}),t0e=st([_g,Yw,Ng,oS,Cg,Og,Ig,kg,Rg,UK,jK,Nu,Mg,Sg,Tg,Eg,Ag]),r0e=st([xg,wg,Jw,FY,Gp]),n0e=st([bg,Wp,iS,zu,sS,vg,Pg,Mu]),o0e=st([_g,gY,CY,UY,Sg,Tg,Eg,Ag]),i0e=st([xg,wg,cY,HK,LK,iY,eY,Gp,$Y]),s0e=st([bg,AK,LY,XK,ZK,$K,NK,BK,$g,nY,vg,Pg,Mu]);class ve extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`);this.code=e,this.data=r,this.name="McpError"}static fromError(e,t,r){if(e===Me.UrlElicitationRequired&&r){let n=r;if(n.elicitations)return new uO(n.elicitations,t)}return new ve(e,t,r)}}class uO extends ve{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(Me.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}function Hs(e){return e==="completed"||e==="failed"||e==="cancelled"}var lO=Symbol("Let zodToJsonSchema decide on which parser to use");var dO={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"},pO=(e)=>typeof e==="string"?{...dO,name:e}:{...dO,...e};var fO=(e)=>{let t=pO(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}};function aS(e,t,r,n){if(!n?.errorMessages)return;if(r)e.errorMessage={...e.errorMessage,[t]:r}}function at(e,t,r,n,o){e[t]=r,aS(e,t,n,o)}var zg=(e,t)=>{let r=0;for(;r<e.length&&r<t.length;r++)if(e[r]!==t[r])break;return[(e.length-r).toString(),...t.slice(r)].join("/")};function Ht(e){if(e.target!=="openAi")return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?zg(t,e.currentPath):t.join("/")}}function mO(e,t){let r={type:"array"};if(e.type?._def&&e.type?._def?.typeName!==se.ZodAny)r.items=De(e.type._def,{...t,currentPath:[...t.currentPath,"items"]});if(e.minLength)at(r,"minItems",e.minLength.value,e.minLength.message,t);if(e.maxLength)at(r,"maxItems",e.maxLength.value,e.maxLength.message,t);if(e.exactLength)at(r,"minItems",e.exactLength.value,e.exactLength.message,t),at(r,"maxItems",e.exactLength.value,e.exactLength.message,t);return r}function hO(e,t){let r={type:"integer",format:"int64"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"min":if(t.target==="jsonSchema7")if(n.inclusive)at(r,"minimum",n.value,n.message,t);else at(r,"exclusiveMinimum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMinimum=!0;at(r,"minimum",n.value,n.message,t)}break;case"max":if(t.target==="jsonSchema7")if(n.inclusive)at(r,"maximum",n.value,n.message,t);else at(r,"exclusiveMaximum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMaximum=!0;at(r,"maximum",n.value,n.message,t)}break;case"multipleOf":at(r,"multipleOf",n.value,n.message,t);break}return r}function gO(){return{type:"boolean"}}function Bg(e,t){return De(e.type._def,t)}var yO=(e,t)=>De(e.innerType._def,t);function cS(e,t,r){let n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>cS(e,t,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return jY(e,t)}}var jY=(e,t)=>{let r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(let n of e.checks)switch(n.kind){case"min":at(r,"minimum",n.value,n.message,t);break;case"max":at(r,"maximum",n.value,n.message,t);break}return r};function bO(e,t){return{...De(e.innerType._def,t),default:e.defaultValue()}}function xO(e,t){return t.effectStrategy==="input"?De(e.schema._def,t):Ht(t)}function _O(e){return{type:"string",enum:Array.from(e.values)}}var qY=(e)=>{if("type"in e&&e.type==="string")return!1;return"allOf"in e};function wO(e,t){let r=[De(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),De(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter((i)=>!!i),n=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach((i)=>{if(qY(i)){if(o.push(...i.allOf),i.unevaluatedProperties===void 0)n=void 0}else{let s=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:a,...c}=i;s=c}else n=void 0;o.push(s)}}),o.length?{allOf:o,...n}:void 0}function SO(e,t){let r=typeof e.value;if(r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string")return{type:Array.isArray(e.value)?"array":"object"};if(t.target==="openApi3")return{type:r==="bigint"?"integer":r,enum:[e.value]};return{type:r==="bigint"?"integer":r,const:e.value}}var uS=void 0,po={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:()=>{if(uS===void 0)uS=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return uS},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 Lg(e,t){let r={type:"string"};if(e.checks)for(let n of e.checks)switch(n.kind){case"min":at(r,"minLength",typeof r.minLength==="number"?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":at(r,"maxLength",typeof r.maxLength==="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":fo(r,"email",n.message,t);break;case"format:idn-email":fo(r,"idn-email",n.message,t);break;case"pattern:zod":Jr(r,po.email,n.message,t);break}break;case"url":fo(r,"uri",n.message,t);break;case"uuid":fo(r,"uuid",n.message,t);break;case"regex":Jr(r,n.regex,n.message,t);break;case"cuid":Jr(r,po.cuid,n.message,t);break;case"cuid2":Jr(r,po.cuid2,n.message,t);break;case"startsWith":Jr(r,RegExp(`^${dS(n.value,t)}`),n.message,t);break;case"endsWith":Jr(r,RegExp(`${dS(n.value,t)}$`),n.message,t);break;case"datetime":fo(r,"date-time",n.message,t);break;case"date":fo(r,"date",n.message,t);break;case"time":fo(r,"time",n.message,t);break;case"duration":fo(r,"duration",n.message,t);break;case"length":at(r,"minLength",typeof r.minLength==="number"?Math.max(r.minLength,n.value):n.value,n.message,t),at(r,"maxLength",typeof r.maxLength==="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":{Jr(r,RegExp(dS(n.value,t)),n.message,t);break}case"ip":{if(n.version!=="v6")fo(r,"ipv4",n.message,t);if(n.version!=="v4")fo(r,"ipv6",n.message,t);break}case"base64url":Jr(r,po.base64url,n.message,t);break;case"jwt":Jr(r,po.jwt,n.message,t);break;case"cidr":{if(n.version!=="v6")Jr(r,po.ipv4Cidr,n.message,t);if(n.version!=="v4")Jr(r,po.ipv6Cidr,n.message,t);break}case"emoji":Jr(r,po.emoji(),n.message,t);break;case"ulid":{Jr(r,po.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{fo(r,"binary",n.message,t);break}case"contentEncoding:base64":{at(r,"contentEncoding","base64",n.message,t);break}case"pattern:zod":{Jr(r,po.base64,n.message,t);break}}break}case"nanoid":Jr(r,po.nanoid,n.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:((o)=>{})(n)}return r}function dS(e,t){return t.patternStrategy==="escape"?GY(e):e}var HY=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function GY(e){let t="";for(let r=0;r<e.length;r++){if(!HY.has(e[r]))t+="\\";t+=e[r]}return t}function fo(e,t,r,n){if(e.format||e.anyOf?.some((o)=>o.format)){if(!e.anyOf)e.anyOf=[];if(e.format){if(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage){if(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0)delete e.errorMessage}}e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})}else at(e,"format",t,r,n)}function Jr(e,t,r,n){if(e.pattern||e.allOf?.some((o)=>o.pattern)){if(!e.allOf)e.allOf=[];if(e.pattern){if(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage){if(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0)delete e.errorMessage}}e.allOf.push({pattern:vO(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})}else at(e,"pattern",vO(t,n),r,n)}function vO(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},n=r.i?e.source.toLowerCase():e.source,o="",i=!1,s=!1,a=!1;for(let c=0;c<n.length;c++){if(i){o+=n[c],i=!1;continue}if(r.i){if(s){if(n[c].match(/[a-z]/)){if(a)o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1;else if(n[c+1]==="-"&&n[c+2]?.match(/[a-z]/))o+=n[c],a=!0;else o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
130
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of e.seen.entries()){let a=s[1];if(t===s[0]){i(s);continue}if(e.external){let d=e.external.registry.get(s[0])?.id;if(t!==s[0]&&d){i(s);continue}}if(e.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}if(a.count>1){if(e.reused==="ref"){i(s);continue}}}}function Np(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let n=(a)=>{let c=e.seen.get(a);if(c.ref===null)return;let d=c.def??c.schema,l={...d},p=c.ref;if(c.ref=null,p){n(p);let h=e.seen.get(p),b=h.schema;if(b.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))d.allOf=d.allOf??[],d.allOf.push(b);else Object.assign(d,b);if(Object.assign(d,l),a._zod.parent===p)for(let _ in d){if(_==="$ref"||_==="allOf")continue;if(!(_ in l))delete d[_]}if(b.$ref&&h.def)for(let _ in d){if(_==="$ref"||_==="allOf")continue;if(_ in h.def&&JSON.stringify(d[_])===JSON.stringify(h.def[_]))delete d[_]}}let m=a._zod.parent;if(m&&m!==p){n(m);let h=e.seen.get(m);if(h?.schema.$ref){if(d.$ref=h.schema.$ref,h.def)for(let b in d){if(b==="$ref"||b==="allOf")continue;if(b in h.def&&JSON.stringify(d[b])===JSON.stringify(h.def[b]))delete d[b]}}}e.override({zodSchema:a,jsonSchema:d,path:c.path??[]})};for(let a of[...e.seen.entries()].reverse())n(a[0]);let o={};if(e.target==="draft-2020-12")o.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")o.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")o.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");o.$id=e.external.uri(a)}Object.assign(o,r.def??r.schema);let i=e.metadataRegistry.get(t)?.id;if(i!==void 0&&o.id===i)delete o.id;let s=e.external?.defs??{};for(let a of e.seen.entries()){let c=a[1];if(c.def&&c.defId){if(c.def.id===c.defId)delete c.def.id;s[c.defId]=c.def}}if(e.external);else if(Object.keys(s).length>0)if(e.target==="draft-2020-12")o.$defs=s;else o.definitions=s;try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Cp(t,"input",e.processors),output:Cp(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function Kr(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return Kr(n.element,r);if(n.type==="set")return Kr(n.valueType,r);if(n.type==="lazy")return Kr(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return Kr(n.innerType,r);if(n.type==="intersection")return Kr(n.left,r)||Kr(n.right,r);if(n.type==="record"||n.type==="map")return Kr(n.keyType,r)||Kr(n.valueType,r);if(n.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return Kr(n.in,r)||Kr(n.out,r)}if(n.type==="object"){for(let o in n.shape)if(Kr(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(Kr(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(Kr(o,r))return!0;if(n.rest&&Kr(n.rest,r))return!0;return!1}return!1}var H6=(e,t={})=>(r)=>{let n=Mp({...r,processors:t});return Rt(e,n),$p(n,e),Np(n,e)},Cp=(e,t,r={})=>(n)=>{let{libraryOptions:o,target:i}=n??{},s=Mp({...o??{},target:i,io:t,processors:r});return Rt(e,s),$p(s,e),Np(s,e)};var IZ={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},hw=(e,t,r,n)=>{let o=r;o.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:d}=e._zod.bag;if(typeof i==="number")o.minLength=i;if(typeof s==="number")o.maxLength=s;if(a){if(o.format=IZ[a]??a,o.format==="")delete o.format;if(a==="time")delete o.format}if(d)o.contentEncoding=d;if(c&&c.size>0){let l=[...c];if(l.length===1)o.pattern=l[0].source;else if(l.length>1)o.allOf=[...l.map((p)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))]}},gw=(e,t,r,n)=>{let o=r,{minimum:i,maximum:s,format:a,multipleOf:c,exclusiveMaximum:d,exclusiveMinimum:l}=e._zod.bag;if(typeof a==="string"&&a.includes("int"))o.type="integer";else o.type="number";let p=typeof l==="number"&&l>=(i??Number.NEGATIVE_INFINITY),m=typeof d==="number"&&d<=(s??Number.POSITIVE_INFINITY),h=t.target==="draft-04"||t.target==="openapi-3.0";if(p)if(h)o.minimum=l,o.exclusiveMinimum=!0;else o.exclusiveMinimum=l;else if(typeof i==="number")o.minimum=i;if(m)if(h)o.maximum=d,o.exclusiveMaximum=!0;else o.exclusiveMaximum=d;else if(typeof s==="number")o.maximum=s;if(typeof c==="number")o.multipleOf=c},yw=(e,t,r,n)=>{r.type="boolean"},bw=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},V6=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},xw=(e,t,r,n)=>{if(t.target==="openapi-3.0")r.type="string",r.nullable=!0,r.enum=[null];else r.type="null"},Z6=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},W6=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},_w=(e,t,r,n)=>{r.not={}},K6=(e,t,r,n)=>{},ww=(e,t,r,n)=>{},Y6=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},Sw=(e,t,r,n)=>{let o=e._zod.def,i=Hh(o.entries);if(i.every((s)=>typeof s==="number"))r.type="number";if(i.every((s)=>typeof s==="string"))r.type="string";r.enum=i},vw=(e,t,r,n)=>{let o=e._zod.def,i=[];for(let s of o.values)if(s===void 0){if(t.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s==="bigint")if(t.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else i.push(Number(s));else i.push(s);if(i.length===0);else if(i.length===1){let s=i[0];if(r.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0")r.enum=[s];else r.const=s}else{if(i.every((s)=>typeof s==="number"))r.type="number";if(i.every((s)=>typeof s==="string"))r.type="string";if(i.every((s)=>typeof s==="boolean"))r.type="boolean";if(i.every((s)=>s===null))r.type="null";r.enum=i}},J6=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},Q6=(e,t,r,n)=>{let o=r,i=e._zod.pattern;if(!i)throw Error("Pattern not found in template literal");o.type="string",o.pattern=i.source},X6=(e,t,r,n)=>{let o=r,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:a,mime:c}=e._zod.bag;if(s!==void 0)i.minLength=s;if(a!==void 0)i.maxLength=a;if(c)if(c.length===1)i.contentMediaType=c[0],Object.assign(o,i);else Object.assign(o,i),o.anyOf=c.map((d)=>({contentMediaType:d}));else Object.assign(o,i)},e5=(e,t,r,n)=>{r.type="boolean"},Tw=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},t5=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},Ew=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},r5=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},n5=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},Pw=(e,t,r,n)=>{let o=r,i=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;if(typeof s==="number")o.minItems=s;if(typeof a==="number")o.maxItems=a;o.type="array",o.items=Rt(i.element,t,{...n,path:[...n.path,"items"]})},Aw=(e,t,r,n)=>{let o=r,i=e._zod.def;o.type="object",o.properties={};let s=i.shape;for(let d in s)o.properties[d]=Rt(s[d],t,{...n,path:[...n.path,"properties",d]});let a=new Set(Object.keys(s)),c=new Set([...a].filter((d)=>{let l=i.shape[d]._zod;if(t.io==="input")return l.optin===void 0;else return l.optout===void 0}));if(c.size>0)o.required=Array.from(c);if(i.catchall?._zod.def.type==="never")o.additionalProperties=!1;else if(!i.catchall){if(t.io==="output")o.additionalProperties=!1}else if(i.catchall)o.additionalProperties=Rt(i.catchall,t,{...n,path:[...n.path,"additionalProperties"]})},Iw=(e,t,r,n)=>{let o=e._zod.def,i=o.inclusive===!1,s=o.options.map((a,c)=>Rt(a,t,{...n,path:[...n.path,i?"oneOf":"anyOf",c]}));if(i)r.oneOf=s;else r.anyOf=s},kw=(e,t,r,n)=>{let o=e._zod.def,i=Rt(o.left,t,{...n,path:[...n.path,"allOf",0]}),s=Rt(o.right,t,{...n,path:[...n.path,"allOf",1]}),a=(d)=>("allOf"in d)&&Object.keys(d).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=c},o5=(e,t,r,n)=>{let o=r,i=e._zod.def;o.type="array";let s=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"?"items":t.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((m,h)=>Rt(m,t,{...n,path:[...n.path,s,h]})),d=i.rest?Rt(i.rest,t,{...n,path:[...n.path,a,...t.target==="openapi-3.0"?[i.items.length]:[]]}):null;if(t.target==="draft-2020-12"){if(o.prefixItems=c,d)o.items=d}else if(t.target==="openapi-3.0"){if(o.items={anyOf:c},d)o.items.anyOf.push(d);if(o.minItems=c.length,!d)o.maxItems=c.length}else if(o.items=c,d)o.additionalItems=d;let{minimum:l,maximum:p}=e._zod.bag;if(typeof l==="number")o.minItems=l;if(typeof p==="number")o.maxItems=p},Rw=(e,t,r,n)=>{let o=r,i=e._zod.def;o.type="object";let s=i.keyType,c=s._zod.bag?.patterns;if(i.mode==="loose"&&c&&c.size>0){let l=Rt(i.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(let p of c)o.patternProperties[p.source]=l}else{if(t.target==="draft-07"||t.target==="draft-2020-12")o.propertyNames=Rt(i.keyType,t,{...n,path:[...n.path,"propertyNames"]});o.additionalProperties=Rt(i.valueType,t,{...n,path:[...n.path,"additionalProperties"]})}let d=s._zod.values;if(d){let l=[...d].filter((p)=>typeof p==="string"||typeof p==="number");if(l.length>0)o.required=l}},Ow=(e,t,r,n)=>{let o=e._zod.def,i=Rt(o.innerType,t,n),s=t.seen.get(e);if(t.target==="openapi-3.0")s.ref=o.innerType,r.nullable=!0;else r.anyOf=[i,{type:"null"}]},Cw=(e,t,r,n)=>{let o=e._zod.def;Rt(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType},Mw=(e,t,r,n)=>{let o=e._zod.def;Rt(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},$w=(e,t,r,n)=>{let o=e._zod.def;Rt(o.innerType,t,n);let i=t.seen.get(e);if(i.ref=o.innerType,t.io==="input")r._prefault=JSON.parse(JSON.stringify(o.defaultValue))},Nw=(e,t,r,n)=>{let o=e._zod.def;Rt(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType;let s;try{s=o.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}r.default=s},zw=(e,t,r,n)=>{let o=e._zod.def,i=o.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?i?o.out:o.in:o.out;Rt(s,t,n);let a=t.seen.get(e);a.ref=s},Bw=(e,t,r,n)=>{let o=e._zod.def;Rt(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType,r.readOnly=!0},i5=(e,t,r,n)=>{let o=e._zod.def;Rt(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType},cg=(e,t,r,n)=>{let o=e._zod.def;Rt(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType},s5=(e,t,r,n)=>{let o=e._zod.innerType;Rt(o,t,n);let i=t.seen.get(e);i.ref=o},G6={string:hw,number:gw,boolean:yw,bigint:bw,symbol:V6,null:xw,undefined:Z6,void:W6,never:_w,any:K6,unknown:ww,date:Y6,enum:Sw,literal:vw,nan:J6,template_literal:Q6,file:X6,success:e5,custom:Tw,function:t5,transform:Ew,map:r5,set:n5,array:Pw,object:Aw,union:Iw,intersection:kw,tuple:o5,record:Rw,nullable:Ow,nonoptional:Cw,default:Mw,prefault:$w,catch:Nw,pipe:zw,readonly:Bw,promise:i5,optional:cg,lazy:s5};function Lw(e,t){if("_idmap"in e){let n=e,o=Mp({...t,processors:G6}),i={};for(let c of n._idmap.entries()){let[d,l]=c;Rt(l,o)}let s={},a={registry:n,uri:t?.uri,defs:i};o.external=a;for(let c of n._idmap.entries()){let[d,l]=c;$p(o,l),s[d]=Np(o,l)}if(Object.keys(i).length>0){let c=o.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[c]:i}}return{schemas:s}}let r=Mp({...t,processors:G6});return Rt(e,r),$p(r,e),Np(r,e)}var hW=D("ZodMiniType",(e,t)=>{if(!e._zod)throw Error("Uninitialized schema in ZodMiniType.");Tt.init(e,t),e.def=t,e.type=t.type,e.parse=(r,n)=>Yh(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Xa(e,r,n),e.parseAsync=async(r,n)=>Jh(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>ec(e,r,n),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map((n)=>typeof n==="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]},{parent:!0}),e.with=e.check,e.clone=(r,n)=>jn(e,r,n),e.brand=()=>e,e.register=(r,n)=>(r.add(e,n),e),e.apply=(r)=>r(e)});var gW=D("ZodMiniObject",(e,t)=>{l_.init(e,t),hW.init(e,t),_t(e,"shape",()=>t.shape)});function Dw(e,t){let r={type:"object",shape:e??{},...xe(t)};return new gW(r)}function qn(e){return!!e._zod}function nc(e){let t=Object.values(e);if(t.length===0)return Dw({});let r=t.every(qn),n=t.every((o)=>!qn(o));if(r)return Dw(e);if(n)return r2(e);throw Error("Mixed Zod versions detected in object shape.")}function Fs(e,t){if(qn(e))return Xa(e,t);return e.safeParse(t)}async function ug(e,t){if(qn(e))return await ec(e,t);return await e.safeParseAsync(t)}function js(e){if(!e)return;let t;if(qn(e))t=e._zod?.def?.shape;else t=e.shape;if(!t)return;if(typeof t==="function")try{return t()}catch{return}return t}function Ru(e){if(!e)return;if(typeof e==="object"){let t=e,r=e;if(!t._def&&!r._zod){let n=Object.values(e);if(n.length>0&&n.every((o)=>typeof o==="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse==="function")))return nc(e)}}if(qn(e)){let r=e._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return e}else if(e.shape!==void 0)return e;return}function dg(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 c5(e){return e.description}function u5(e){if(qn(e))return e._zod?.def?.type==="optional";let t=e;if(typeof e.isOptional==="function")return e.isOptional();return t._def?.typeName==="ZodOptional"}function lg(e){if(qn(e)){let i=e._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}let r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=e.value;if(n!==void 0)return n;return}var Ou={};ZH(Ou,{ZodISODate:()=>l5,ZodISODateTime:()=>d5,ZodISODuration:()=>f5,ZodISOTime:()=>p5,date:()=>Uw,datetime:()=>pg,duration:()=>jw,time:()=>Fw});var d5=D("ZodISODateTime",(e,t)=>{I6.init(e,t),jt.init(e,t)});function pg(e){return D6(d5,e)}var l5=D("ZodISODate",(e,t)=>{k6.init(e,t),jt.init(e,t)});function Uw(e){return U6(l5,e)}var p5=D("ZodISOTime",(e,t)=>{R6.init(e,t),jt.init(e,t)});function Fw(e){return F6(p5,e)}var f5=D("ZodISODuration",(e,t)=>{O6.init(e,t),jt.init(e,t)});function jw(e){return j6(f5,e)}var TW=(e,t)=>{Kh.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(r)=>w2(e,r)},flatten:{value:(r)=>_2(e,r)},addIssue:{value:(r)=>{e.issues.push(r),e.message=JSON.stringify(e.issues,wp,2)}},addIssues:{value:(r)=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,wp,2)}},isEmpty:{get(){return e.issues.length===0}}})};var In=D("ZodError",TW,{Parent:Error});var m5=Tp(In),h5=Ep(In),g5=Pp(In),y5=Ap(In),b5=S2(In),x5=v2(In),_5=T2(In),w5=E2(In),S5=P2(In),v5=A2(In),T5=I2(In),E5=k2(In);var P5=new WeakMap;function Bp(e,t,r){let n=Object.getPrototypeOf(e),o=P5.get(n);if(!o)o=new Set,P5.set(n,o);if(o.has(t))return;o.add(t);for(let i in r){let s=r[i];Object.defineProperty(n,i,{configurable:!0,enumerable:!1,get(){let a=s.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}var Dt=D("ZodType",(e,t)=>(Tt.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Cp(e,"input"),output:Cp(e,"output")}}),e.toJSONSchema=H6(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(r,n)=>m5(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>g5(e,r,n),e.parseAsync=async(r,n)=>h5(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>y5(e,r,n),e.spa=e.safeParseAsync,e.encode=(r,n)=>b5(e,r,n),e.decode=(r,n)=>x5(e,r,n),e.encodeAsync=async(r,n)=>_5(e,r,n),e.decodeAsync=async(r,n)=>w5(e,r,n),e.safeEncode=(r,n)=>S5(e,r,n),e.safeDecode=(r,n)=>v5(e,r,n),e.safeEncodeAsync=async(r,n)=>T5(e,r,n),e.safeDecodeAsync=async(r,n)=>E5(e,r,n),Bp(e,"ZodType",{check(...r){let n=this.def;return this.clone(zs(n,{checks:[...n.checks??[],...r.map((o)=>typeof o==="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,n){return jn(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(mK(r,n))},superRefine(r,n){return this.check(hK(r,n))},overwrite(r){return this.check(Us(r))},optional(){return qt(this)},exactOptional(){return rK(this)},nullable(){return R5(this)},nullish(){return qt(R5(this))},nonoptional(r){return cK(this,r)},array(){return Ie(this)},or(r){return st([this,r])},and(r){return fg(this,r)},transform(r){return O5(this,D5(r))},default(r){return iK(this,r)},prefault(r){return aK(this,r)},catch(r){return dK(this,r)},pipe(r){return O5(this,r)},readonly(){return fK(this)},describe(r){let n=this.clone();return tc.add(n,{description:r}),n},meta(...r){if(r.length===0)return tc.get(this);let n=this.clone();return tc.add(n,r[0]),n},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(e,"description",{get(){return tc.get(e)?.description},configurable:!0}),e)),C5=D("_ZodString",(e,t)=>{Rp.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>hw(e,n,o,i);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,Bp(e,"_ZodString",{regex(...n){return this.check(tw(...n))},includes(...n){return this.check(ow(...n))},startsWith(...n){return this.check(iw(...n))},endsWith(...n){return this.check(sw(...n))},min(...n){return this.check(ku(...n))},max(...n){return this.check(sg(...n))},length(...n){return this.check(ag(...n))},nonempty(...n){return this.check(ku(1,...n))},lowercase(n){return this.check(rw(n))},uppercase(n){return this.check(nw(n))},trim(){return this.check(cw())},normalize(...n){return this.check(aw(...n))},toLowerCase(){return this.check(uw())},toUpperCase(){return this.check(dw())},slugify(){return this.check(lw())}})}),PW=D("ZodString",(e,t)=>{Rp.init(e,t),C5.init(e,t),e.email=(r)=>e.check(I_(AW,r)),e.url=(r)=>e.check(C_(IW,r)),e.jwt=(r)=>e.check(Z_(qW,r)),e.emoji=(r)=>e.check(M_(kW,r)),e.guid=(r)=>e.check(og(A5,r)),e.uuid=(r)=>e.check(ig(zp,r)),e.uuidv4=(r)=>e.check(k_(zp,r)),e.uuidv6=(r)=>e.check(R_(zp,r)),e.uuidv7=(r)=>e.check(O_(zp,r)),e.nanoid=(r)=>e.check($_(RW,r)),e.guid=(r)=>e.check(og(A5,r)),e.cuid=(r)=>e.check(N_(OW,r)),e.cuid2=(r)=>e.check(z_(CW,r)),e.ulid=(r)=>e.check(B_(MW,r)),e.base64=(r)=>e.check(H_(UW,r)),e.base64url=(r)=>e.check(G_(FW,r)),e.xid=(r)=>e.check(L_($W,r)),e.ksuid=(r)=>e.check(D_(NW,r)),e.ipv4=(r)=>e.check(U_(zW,r)),e.ipv6=(r)=>e.check(F_(BW,r)),e.cidrv4=(r)=>e.check(j_(LW,r)),e.cidrv6=(r)=>e.check(q_(DW,r)),e.e164=(r)=>e.check(V_(jW,r)),e.datetime=(r)=>e.check(pg(r)),e.date=(r)=>e.check(Uw(r)),e.time=(r)=>e.check(Fw(r)),e.duration=(r)=>e.check(jw(r))});function y(e){return A_(PW,e)}var jt=D("ZodStringFormat",(e,t)=>{Nt.init(e,t),C5.init(e,t)}),AW=D("ZodEmail",(e,t)=>{F1.init(e,t),jt.init(e,t)});var A5=D("ZodGUID",(e,t)=>{D1.init(e,t),jt.init(e,t)});var zp=D("ZodUUID",(e,t)=>{U1.init(e,t),jt.init(e,t)});function M5(e){return ig(zp,e)}var IW=D("ZodURL",(e,t)=>{j1.init(e,t),jt.init(e,t)});var kW=D("ZodEmoji",(e,t)=>{q1.init(e,t),jt.init(e,t)});var RW=D("ZodNanoID",(e,t)=>{H1.init(e,t),jt.init(e,t)});var OW=D("ZodCUID",(e,t)=>{G1.init(e,t),jt.init(e,t)});var CW=D("ZodCUID2",(e,t)=>{V1.init(e,t),jt.init(e,t)});var MW=D("ZodULID",(e,t)=>{Z1.init(e,t),jt.init(e,t)});var $W=D("ZodXID",(e,t)=>{W1.init(e,t),jt.init(e,t)});var NW=D("ZodKSUID",(e,t)=>{K1.init(e,t),jt.init(e,t)});var zW=D("ZodIPv4",(e,t)=>{Y1.init(e,t),jt.init(e,t)});var BW=D("ZodIPv6",(e,t)=>{J1.init(e,t),jt.init(e,t)});var LW=D("ZodCIDRv4",(e,t)=>{Q1.init(e,t),jt.init(e,t)});var DW=D("ZodCIDRv6",(e,t)=>{X1.init(e,t),jt.init(e,t)});var UW=D("ZodBase64",(e,t)=>{e_.init(e,t),jt.init(e,t)});var FW=D("ZodBase64URL",(e,t)=>{t_.init(e,t),jt.init(e,t)});var jW=D("ZodE164",(e,t)=>{r_.init(e,t),jt.init(e,t)});var qW=D("ZodJWT",(e,t)=>{n_.init(e,t),jt.init(e,t)});var $5=D("ZodNumber",(e,t)=>{eg.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>gw(e,n,o,i),Bp(e,"ZodNumber",{gt(n,o){return this.check(Iu(n,o))},gte(n,o){return this.check(Go(n,o))},min(n,o){return this.check(Go(n,o))},lt(n,o){return this.check(Au(n,o))},lte(n,o){return this.check(Ds(n,o))},max(n,o){return this.check(Ds(n,o))},int(n){return this.check(I5(n))},safe(n){return this.check(I5(n))},positive(n){return this.check(Iu(0,n))},nonnegative(n){return this.check(Go(0,n))},negative(n){return this.check(Au(0,n))},nonpositive(n){return this.check(Ds(0,n))},multipleOf(n,o){return this.check(Op(n,o))},step(n,o){return this.check(Op(n,o))},finite(){return this}});let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??0.5),e.isFinite=!0,e.format=r.format??null});function M(e){return W_($5,e)}var HW=D("ZodNumberFormat",(e,t)=>{o_.init(e,t),$5.init(e,t)});function I5(e){return K_(HW,e)}var GW=D("ZodBoolean",(e,t)=>{i_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>yw(e,r,n,o)});function ue(e){return Y_(GW,e)}var VW=D("ZodBigInt",(e,t)=>{s_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>bw(e,n,o,i),e.gte=(n,o)=>e.check(Go(n,o)),e.min=(n,o)=>e.check(Go(n,o)),e.gt=(n,o)=>e.check(Iu(n,o)),e.gte=(n,o)=>e.check(Go(n,o)),e.min=(n,o)=>e.check(Go(n,o)),e.lt=(n,o)=>e.check(Au(n,o)),e.lte=(n,o)=>e.check(Ds(n,o)),e.max=(n,o)=>e.check(Ds(n,o)),e.positive=(n)=>e.check(Iu(BigInt(0),n)),e.negative=(n)=>e.check(Au(BigInt(0),n)),e.nonpositive=(n)=>e.check(Ds(BigInt(0),n)),e.nonnegative=(n)=>e.check(Go(BigInt(0),n)),e.multipleOf=(n,o)=>e.check(Op(n,o));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});function N5(e){return J_(VW,e)}var ZW=D("ZodNull",(e,t)=>{a_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>xw(e,r,n,o)});function z5(e){return Q_(ZW,e)}var WW=D("ZodUnknown",(e,t)=>{c_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ww(e,r,n,o)});function Et(){return X_(WW)}var KW=D("ZodNever",(e,t)=>{u_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>_w(e,r,n,o)});function kn(e){return ew(KW,e)}var YW=D("ZodArray",(e,t)=>{d_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Pw(e,r,n,o),e.element=t.element,Bp(e,"ZodArray",{min(r,n){return this.check(ku(r,n))},nonempty(r){return this.check(ku(1,r))},max(r,n){return this.check(sg(r,n))},length(r,n){return this.check(ag(r,n))},unwrap(){return this.element}})});function Ie(e,t){return q6(YW,e,t)}var B5=D("ZodObject",(e,t)=>{N6.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Aw(e,r,n,o),_t(e,"shape",()=>t.shape),Bp(e,"ZodObject",{keyof(){return H(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:Et()})},loose(){return this.clone({...this._zod.def,catchall:Et()})},strict(){return this.clone({...this._zod.def,catchall:kn()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return f2(this,r)},safeExtend(r){return m2(this,r)},merge(r){return _Z(this,r)},pick(r){return l2(this,r)},omit(r){return p2(this,r)},partial(...r){return h2(mg,this,r[0])},required(...r){return g2(U5,this,r[0])}})});function S(e,t){let r={type:"object",shape:e??{},...xe(t)};return new B5(r)}function Yr(e,t){return new B5({type:"object",shape:e,catchall:Et(),...xe(t)})}var L5=D("ZodUnion",(e,t)=>{tg.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Iw(e,r,n,o),e.options=t.options});function st(e,t){return new L5({type:"union",options:e,...xe(t)})}var JW=D("ZodDiscriminatedUnion",(e,t)=>{L5.init(e,t),p_.init(e,t)});function Hw(e,t,r){return new JW({type:"union",options:t,discriminator:e,...xe(r)})}var QW=D("ZodIntersection",(e,t)=>{f_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>kw(e,r,n,o)});function fg(e,t){return new QW({type:"intersection",left:e,right:t})}var k5=D("ZodRecord",(e,t)=>{m_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Rw(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType});function zt(e,t,r){if(!t||!t._zod)return new k5({type:"record",keyType:y(),valueType:e,...xe(t)});return new k5({type:"record",keyType:e,valueType:t,...xe(r)})}var qw=D("ZodEnum",(e,t)=>{h_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Sw(e,n,o,i),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let i={};for(let s of n)if(r.has(s))i[s]=t.entries[s];else throw Error(`Key ${s} not found in enum`);return new qw({...t,checks:[],...xe(o),entries:i})},e.exclude=(n,o)=>{let i={...t.entries};for(let s of n)if(r.has(s))delete i[s];else throw Error(`Key ${s} not found in enum`);return new qw({...t,checks:[],...xe(o),entries:i})}});function H(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((n)=>[n,n])):e;return new qw({type:"enum",entries:r,...xe(t)})}var XW=D("ZodLiteral",(e,t)=>{g_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>vw(e,r,n,o),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function _e(e,t){return new XW({type:"literal",values:Array.isArray(e)?e:[e],...xe(t)})}var eK=D("ZodTransform",(e,t)=>{y_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Ew(e,r,n,o),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new _p(e.constructor.name);r.addIssue=(i)=>{if(typeof i==="string")r.issues.push(Qa(i,r.value,t));else{let s=i;if(s.fatal)s.continue=!1;s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),r.issues.push(Qa(s))}};let o=t.transform(r.value,r);if(o instanceof Promise)return o.then((i)=>(r.value=i,r.fallback=!0,r));return r.value=o,r.fallback=!0,r}});function D5(e){return new eK({type:"transform",transform:e})}var mg=D("ZodOptional",(e,t)=>{rg.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>cg(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function qt(e){return new mg({type:"optional",innerType:e})}var tK=D("ZodExactOptional",(e,t)=>{b_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>cg(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function rK(e){return new tK({type:"optional",innerType:e})}var nK=D("ZodNullable",(e,t)=>{x_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Ow(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function R5(e){return new nK({type:"nullable",innerType:e})}var oK=D("ZodDefault",(e,t)=>{__.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Mw(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function iK(e,t){return new oK({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Zh(t)}})}var sK=D("ZodPrefault",(e,t)=>{w_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>$w(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function aK(e,t){return new sK({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Zh(t)}})}var U5=D("ZodNonOptional",(e,t)=>{S_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Cw(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function cK(e,t){return new U5({type:"nonoptional",innerType:e,...xe(t)})}var uK=D("ZodCatch",(e,t)=>{v_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Nw(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function dK(e,t){return new uK({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}var F5=D("ZodPipe",(e,t)=>{ng.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>zw(e,r,n,o),e.in=t.in,e.out=t.out});function O5(e,t){return new F5({type:"pipe",in:e,out:t})}var lK=D("ZodPreprocess",(e,t)=>{F5.init(e,t),z6.init(e,t)}),pK=D("ZodReadonly",(e,t)=>{T_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Bw(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function fK(e){return new pK({type:"readonly",innerType:e})}var j5=D("ZodCustom",(e,t)=>{E_.init(e,t),Dt.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Tw(e,r,n,o)});function q5(e,t){return pw(j5,e??(()=>!0),t)}function mK(e,t={}){return fw(j5,e,t)}function hK(e,t){return mw(e,t)}function Lp(e,t){return new lK({type:"pipe",in:D5(e),out:t})}var Hn={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var H5;(function(e){})(H5||(H5={}));An(P_());var Gw="2025-11-25";var G5=[Gw,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],qs="io.modelcontextprotocol/related-task",gg="2.0",ur=q5((e)=>e!==null&&(typeof e==="object"||typeof e==="function")),V5=st([y(),M().int()]),Z5=y(),Yge=Yr({ttl:M().optional(),pollInterval:M().optional()}),gK=S({ttl:M().optional()}),yK=S({taskId:y()}),Vw=Yr({progressToken:V5.optional(),[qs]:yK.optional()}),Rn=S({_meta:Vw.optional()}),Dp=Rn.extend({task:gK.optional()}),W5=(e)=>Dp.safeParse(e).success,Ir=S({method:y(),params:Rn.loose().optional()}),Gn=S({_meta:Vw.optional()}),Vn=S({method:y(),params:Gn.loose().optional()}),kr=Yr({_meta:Vw.optional()}),yg=st([y(),M().int()]),K5=S({jsonrpc:_e(gg),id:yg,...Ir.shape}).strict(),Zw=(e)=>K5.safeParse(e).success,Y5=S({jsonrpc:_e(gg),...Vn.shape}).strict(),J5=(e)=>Y5.safeParse(e).success,Ww=S({jsonrpc:_e(gg),id:yg,result:kr}).strict(),Up=(e)=>Ww.safeParse(e).success;var Me;(function(e){e[e.ConnectionClosed=-32000]="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"})(Me||(Me={}));var Kw=S({jsonrpc:_e(gg),id:yg.optional(),error:S({code:M().int(),message:y(),data:Et().optional()})}).strict();var Q5=(e)=>Kw.safeParse(e).success;var X5=st([K5,Y5,Ww,Kw]),Jge=st([Ww,Kw]),bg=kr.strict(),bK=Gn.extend({requestId:yg.optional(),reason:y().optional()}),xg=Vn.extend({method:_e("notifications/cancelled"),params:bK}),xK=S({src:y(),mimeType:y().optional(),sizes:Ie(y()).optional(),theme:H(["light","dark"]).optional()}),Fp=S({icons:Ie(xK).optional()}),Cu=S({name:y(),title:y().optional()}),eO=Cu.extend({...Cu.shape,...Fp.shape,version:y(),websiteUrl:y().optional(),description:y().optional()}),_K=fg(S({applyDefaults:ue().optional()}),zt(y(),Et())),wK=Lp((e)=>{if(e&&typeof e==="object"&&!Array.isArray(e)){if(Object.keys(e).length===0)return{form:{}}}return e},fg(S({form:_K.optional(),url:ur.optional()}),zt(y(),Et()).optional())),SK=Yr({list:ur.optional(),cancel:ur.optional(),requests:Yr({sampling:Yr({createMessage:ur.optional()}).optional(),elicitation:Yr({create:ur.optional()}).optional()}).optional()}),vK=Yr({list:ur.optional(),cancel:ur.optional(),requests:Yr({tools:Yr({call:ur.optional()}).optional()}).optional()}),TK=S({experimental:zt(y(),ur).optional(),sampling:S({context:ur.optional(),tools:ur.optional()}).optional(),elicitation:wK.optional(),roots:S({listChanged:ue().optional()}).optional(),tasks:SK.optional(),extensions:zt(y(),ur).optional()}),EK=Rn.extend({protocolVersion:y(),capabilities:TK,clientInfo:eO}),Yw=Ir.extend({method:_e("initialize"),params:EK});var PK=S({experimental:zt(y(),ur).optional(),logging:ur.optional(),completions:ur.optional(),prompts:S({listChanged:ue().optional()}).optional(),resources:S({subscribe:ue().optional(),listChanged:ue().optional()}).optional(),tools:S({listChanged:ue().optional()}).optional(),tasks:vK.optional(),extensions:zt(y(),ur).optional()}),AK=kr.extend({protocolVersion:y(),capabilities:PK,serverInfo:eO,instructions:y().optional()}),Jw=Vn.extend({method:_e("notifications/initialized"),params:Gn.optional()});var _g=Ir.extend({method:_e("ping"),params:Rn.optional()}),IK=S({progress:M(),total:qt(M()),message:qt(y())}),kK=S({...Gn.shape,...IK.shape,progressToken:V5}),wg=Vn.extend({method:_e("notifications/progress"),params:kK}),RK=Rn.extend({cursor:Z5.optional()}),jp=Ir.extend({params:RK.optional()}),qp=kr.extend({nextCursor:Z5.optional()}),OK=H(["working","input_required","completed","failed","cancelled"]),Hp=S({taskId:y(),status:OK,ttl:st([M(),z5()]),createdAt:y(),lastUpdatedAt:y(),pollInterval:qt(M()),statusMessage:qt(y())}),Mu=kr.extend({task:Hp}),CK=Gn.merge(Hp),Gp=Vn.extend({method:_e("notifications/tasks/status"),params:CK}),Sg=Ir.extend({method:_e("tasks/get"),params:Rn.extend({taskId:y()})}),vg=kr.merge(Hp),Tg=Ir.extend({method:_e("tasks/result"),params:Rn.extend({taskId:y()})}),Qge=kr.loose(),Eg=jp.extend({method:_e("tasks/list")}),Pg=qp.extend({tasks:Ie(Hp)}),Ag=Ir.extend({method:_e("tasks/cancel"),params:Rn.extend({taskId:y()})}),tO=kr.merge(Hp),rO=S({uri:y(),mimeType:qt(y()),_meta:zt(y(),Et()).optional()}),nO=rO.extend({text:y()}),Qw=y().refine((e)=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),oO=rO.extend({blob:Qw}),Vp=H(["user","assistant"]),$u=S({audience:Ie(Vp).optional(),priority:M().min(0).max(1).optional(),lastModified:pg({offset:!0}).optional()}),iO=S({...Cu.shape,...Fp.shape,uri:y(),description:qt(y()),mimeType:qt(y()),size:qt(M()),annotations:$u.optional(),_meta:qt(Yr({}))}),MK=S({...Cu.shape,...Fp.shape,uriTemplate:y(),description:qt(y()),mimeType:qt(y()),annotations:$u.optional(),_meta:qt(Yr({}))}),Ig=jp.extend({method:_e("resources/list")}),$K=qp.extend({resources:Ie(iO)}),kg=jp.extend({method:_e("resources/templates/list")}),NK=qp.extend({resourceTemplates:Ie(MK)}),Xw=Rn.extend({uri:y()}),zK=Xw,Rg=Ir.extend({method:_e("resources/read"),params:zK}),BK=kr.extend({contents:Ie(st([nO,oO]))}),LK=Vn.extend({method:_e("notifications/resources/list_changed"),params:Gn.optional()}),DK=Xw,UK=Ir.extend({method:_e("resources/subscribe"),params:DK}),FK=Xw,jK=Ir.extend({method:_e("resources/unsubscribe"),params:FK}),qK=Gn.extend({uri:y()}),HK=Vn.extend({method:_e("notifications/resources/updated"),params:qK}),GK=S({name:y(),description:qt(y()),required:qt(ue())}),VK=S({...Cu.shape,...Fp.shape,description:qt(y()),arguments:qt(Ie(GK)),_meta:qt(Yr({}))}),Og=jp.extend({method:_e("prompts/list")}),ZK=qp.extend({prompts:Ie(VK)}),WK=Rn.extend({name:y(),arguments:zt(y(),y()).optional()}),Cg=Ir.extend({method:_e("prompts/get"),params:WK}),eS=S({type:_e("text"),text:y(),annotations:$u.optional(),_meta:zt(y(),Et()).optional()}),tS=S({type:_e("image"),data:Qw,mimeType:y(),annotations:$u.optional(),_meta:zt(y(),Et()).optional()}),rS=S({type:_e("audio"),data:Qw,mimeType:y(),annotations:$u.optional(),_meta:zt(y(),Et()).optional()}),KK=S({type:_e("tool_use"),name:y(),id:y(),input:zt(y(),Et()),_meta:zt(y(),Et()).optional()}),YK=S({type:_e("resource"),resource:st([nO,oO]),annotations:$u.optional(),_meta:zt(y(),Et()).optional()}),JK=iO.extend({type:_e("resource_link")}),nS=st([eS,tS,rS,JK,YK]),QK=S({role:Vp,content:nS}),XK=kr.extend({description:y().optional(),messages:Ie(QK)}),eY=Vn.extend({method:_e("notifications/prompts/list_changed"),params:Gn.optional()}),tY=S({title:y().optional(),readOnlyHint:ue().optional(),destructiveHint:ue().optional(),idempotentHint:ue().optional(),openWorldHint:ue().optional()}),rY=S({taskSupport:H(["required","optional","forbidden"]).optional()}),sO=S({...Cu.shape,...Fp.shape,description:y().optional(),inputSchema:S({type:_e("object"),properties:zt(y(),ur).optional(),required:Ie(y()).optional()}).catchall(Et()),outputSchema:S({type:_e("object"),properties:zt(y(),ur).optional(),required:Ie(y()).optional()}).catchall(Et()).optional(),annotations:tY.optional(),execution:rY.optional(),_meta:zt(y(),Et()).optional()}),Mg=jp.extend({method:_e("tools/list")}),nY=qp.extend({tools:Ie(sO)}),$g=kr.extend({content:Ie(nS).default([]),structuredContent:zt(y(),Et()).optional(),isError:ue().optional()}),Xge=$g.or(kr.extend({toolResult:Et()})),oY=Dp.extend({name:y(),arguments:zt(y(),Et()).optional()}),Nu=Ir.extend({method:_e("tools/call"),params:oY}),iY=Vn.extend({method:_e("notifications/tools/list_changed"),params:Gn.optional()}),e0e=S({autoRefresh:ue().default(!0),debounceMs:M().int().nonnegative().default(300)}),Zp=H(["debug","info","notice","warning","error","critical","alert","emergency"]),sY=Rn.extend({level:Zp}),oS=Ir.extend({method:_e("logging/setLevel"),params:sY}),aY=Gn.extend({level:Zp,logger:y().optional(),data:Et()}),cY=Vn.extend({method:_e("notifications/message"),params:aY}),uY=S({name:y().optional()}),dY=S({hints:Ie(uY).optional(),costPriority:M().min(0).max(1).optional(),speedPriority:M().min(0).max(1).optional(),intelligencePriority:M().min(0).max(1).optional()}),lY=S({mode:H(["auto","required","none"]).optional()}),pY=S({type:_e("tool_result"),toolUseId:y().describe("The unique identifier for the corresponding tool call."),content:Ie(nS).default([]),structuredContent:S({}).loose().optional(),isError:ue().optional(),_meta:zt(y(),Et()).optional()}),fY=Hw("type",[eS,tS,rS]),hg=Hw("type",[eS,tS,rS,KK,pY]),mY=S({role:Vp,content:st([hg,Ie(hg)]),_meta:zt(y(),Et()).optional()}),hY=Dp.extend({messages:Ie(mY),modelPreferences:dY.optional(),systemPrompt:y().optional(),includeContext:H(["none","thisServer","allServers"]).optional(),temperature:M().optional(),maxTokens:M().int(),stopSequences:Ie(y()).optional(),metadata:ur.optional(),tools:Ie(sO).optional(),toolChoice:lY.optional()}),gY=Ir.extend({method:_e("sampling/createMessage"),params:hY}),Wp=kr.extend({model:y(),stopReason:qt(H(["endTurn","stopSequence","maxTokens"]).or(y())),role:Vp,content:fY}),iS=kr.extend({model:y(),stopReason:qt(H(["endTurn","stopSequence","maxTokens","toolUse"]).or(y())),role:Vp,content:st([hg,Ie(hg)])}),yY=S({type:_e("boolean"),title:y().optional(),description:y().optional(),default:ue().optional()}),bY=S({type:_e("string"),title:y().optional(),description:y().optional(),minLength:M().optional(),maxLength:M().optional(),format:H(["email","uri","date","date-time"]).optional(),default:y().optional()}),xY=S({type:H(["number","integer"]),title:y().optional(),description:y().optional(),minimum:M().optional(),maximum:M().optional(),default:M().optional()}),_Y=S({type:_e("string"),title:y().optional(),description:y().optional(),enum:Ie(y()),default:y().optional()}),wY=S({type:_e("string"),title:y().optional(),description:y().optional(),oneOf:Ie(S({const:y(),title:y()})),default:y().optional()}),SY=S({type:_e("string"),title:y().optional(),description:y().optional(),enum:Ie(y()),enumNames:Ie(y()).optional(),default:y().optional()}),vY=st([_Y,wY]),TY=S({type:_e("array"),title:y().optional(),description:y().optional(),minItems:M().optional(),maxItems:M().optional(),items:S({type:_e("string"),enum:Ie(y())}),default:Ie(y()).optional()}),EY=S({type:_e("array"),title:y().optional(),description:y().optional(),minItems:M().optional(),maxItems:M().optional(),items:S({anyOf:Ie(S({const:y(),title:y()}))}),default:Ie(y()).optional()}),PY=st([TY,EY]),AY=st([SY,vY,PY]),IY=st([AY,yY,bY,xY]),kY=Dp.extend({mode:_e("form").optional(),message:y(),requestedSchema:S({type:_e("object"),properties:zt(y(),IY),required:Ie(y()).optional()})}),RY=Dp.extend({mode:_e("url"),message:y(),elicitationId:y(),url:y().url()}),OY=st([kY,RY]),CY=Ir.extend({method:_e("elicitation/create"),params:OY}),MY=Gn.extend({elicitationId:y()}),$Y=Vn.extend({method:_e("notifications/elicitation/complete"),params:MY}),zu=kr.extend({action:H(["accept","decline","cancel"]),content:Lp((e)=>e===null?void 0:e,zt(y(),st([y(),M(),ue(),Ie(y())])).optional())}),NY=S({type:_e("ref/resource"),uri:y()});var zY=S({type:_e("ref/prompt"),name:y()}),BY=Rn.extend({ref:st([zY,NY]),argument:S({name:y(),value:y()}),context:S({arguments:zt(y(),y()).optional()}).optional()}),Ng=Ir.extend({method:_e("completion/complete"),params:BY});function aO(e){if(e.params.ref.type!=="ref/prompt")throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function cO(e){if(e.params.ref.type!=="ref/resource")throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}var LY=kr.extend({completion:Yr({values:Ie(y()).max(100),total:qt(M().int()),hasMore:qt(ue())})}),DY=S({uri:y().startsWith("file://"),name:y().optional(),_meta:zt(y(),Et()).optional()}),UY=Ir.extend({method:_e("roots/list"),params:Rn.optional()}),sS=kr.extend({roots:Ie(DY)}),FY=Vn.extend({method:_e("notifications/roots/list_changed"),params:Gn.optional()}),t0e=st([_g,Yw,Ng,oS,Cg,Og,Ig,kg,Rg,UK,jK,Nu,Mg,Sg,Tg,Eg,Ag]),r0e=st([xg,wg,Jw,FY,Gp]),n0e=st([bg,Wp,iS,zu,sS,vg,Pg,Mu]),o0e=st([_g,gY,CY,UY,Sg,Tg,Eg,Ag]),i0e=st([xg,wg,cY,HK,LK,iY,eY,Gp,$Y]),s0e=st([bg,AK,LY,XK,ZK,$K,NK,BK,$g,nY,vg,Pg,Mu]);class Te extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`);this.code=e,this.data=r,this.name="McpError"}static fromError(e,t,r){if(e===Me.UrlElicitationRequired&&r){let n=r;if(n.elicitations)return new uO(n.elicitations,t)}return new Te(e,t,r)}}class uO extends Te{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(Me.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}function Hs(e){return e==="completed"||e==="failed"||e==="cancelled"}var lO=Symbol("Let zodToJsonSchema decide on which parser to use");var dO={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"},pO=(e)=>typeof e==="string"?{...dO,name:e}:{...dO,...e};var fO=(e)=>{let t=pO(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}};function aS(e,t,r,n){if(!n?.errorMessages)return;if(r)e.errorMessage={...e.errorMessage,[t]:r}}function at(e,t,r,n,o){e[t]=r,aS(e,t,n,o)}var zg=(e,t)=>{let r=0;for(;r<e.length&&r<t.length;r++)if(e[r]!==t[r])break;return[(e.length-r).toString(),...t.slice(r)].join("/")};function Ht(e){if(e.target!=="openAi")return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?zg(t,e.currentPath):t.join("/")}}function mO(e,t){let r={type:"array"};if(e.type?._def&&e.type?._def?.typeName!==se.ZodAny)r.items=De(e.type._def,{...t,currentPath:[...t.currentPath,"items"]});if(e.minLength)at(r,"minItems",e.minLength.value,e.minLength.message,t);if(e.maxLength)at(r,"maxItems",e.maxLength.value,e.maxLength.message,t);if(e.exactLength)at(r,"minItems",e.exactLength.value,e.exactLength.message,t),at(r,"maxItems",e.exactLength.value,e.exactLength.message,t);return r}function hO(e,t){let r={type:"integer",format:"int64"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"min":if(t.target==="jsonSchema7")if(n.inclusive)at(r,"minimum",n.value,n.message,t);else at(r,"exclusiveMinimum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMinimum=!0;at(r,"minimum",n.value,n.message,t)}break;case"max":if(t.target==="jsonSchema7")if(n.inclusive)at(r,"maximum",n.value,n.message,t);else at(r,"exclusiveMaximum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMaximum=!0;at(r,"maximum",n.value,n.message,t)}break;case"multipleOf":at(r,"multipleOf",n.value,n.message,t);break}return r}function gO(){return{type:"boolean"}}function Bg(e,t){return De(e.type._def,t)}var yO=(e,t)=>De(e.innerType._def,t);function cS(e,t,r){let n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>cS(e,t,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return jY(e,t)}}var jY=(e,t)=>{let r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(let n of e.checks)switch(n.kind){case"min":at(r,"minimum",n.value,n.message,t);break;case"max":at(r,"maximum",n.value,n.message,t);break}return r};function bO(e,t){return{...De(e.innerType._def,t),default:e.defaultValue()}}function xO(e,t){return t.effectStrategy==="input"?De(e.schema._def,t):Ht(t)}function _O(e){return{type:"string",enum:Array.from(e.values)}}var qY=(e)=>{if("type"in e&&e.type==="string")return!1;return"allOf"in e};function wO(e,t){let r=[De(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),De(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter((i)=>!!i),n=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach((i)=>{if(qY(i)){if(o.push(...i.allOf),i.unevaluatedProperties===void 0)n=void 0}else{let s=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:a,...c}=i;s=c}else n=void 0;o.push(s)}}),o.length?{allOf:o,...n}:void 0}function SO(e,t){let r=typeof e.value;if(r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string")return{type:Array.isArray(e.value)?"array":"object"};if(t.target==="openApi3")return{type:r==="bigint"?"integer":r,enum:[e.value]};return{type:r==="bigint"?"integer":r,const:e.value}}var uS=void 0,po={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:()=>{if(uS===void 0)uS=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return uS},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 Lg(e,t){let r={type:"string"};if(e.checks)for(let n of e.checks)switch(n.kind){case"min":at(r,"minLength",typeof r.minLength==="number"?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":at(r,"maxLength",typeof r.maxLength==="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":fo(r,"email",n.message,t);break;case"format:idn-email":fo(r,"idn-email",n.message,t);break;case"pattern:zod":Jr(r,po.email,n.message,t);break}break;case"url":fo(r,"uri",n.message,t);break;case"uuid":fo(r,"uuid",n.message,t);break;case"regex":Jr(r,n.regex,n.message,t);break;case"cuid":Jr(r,po.cuid,n.message,t);break;case"cuid2":Jr(r,po.cuid2,n.message,t);break;case"startsWith":Jr(r,RegExp(`^${dS(n.value,t)}`),n.message,t);break;case"endsWith":Jr(r,RegExp(`${dS(n.value,t)}$`),n.message,t);break;case"datetime":fo(r,"date-time",n.message,t);break;case"date":fo(r,"date",n.message,t);break;case"time":fo(r,"time",n.message,t);break;case"duration":fo(r,"duration",n.message,t);break;case"length":at(r,"minLength",typeof r.minLength==="number"?Math.max(r.minLength,n.value):n.value,n.message,t),at(r,"maxLength",typeof r.maxLength==="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":{Jr(r,RegExp(dS(n.value,t)),n.message,t);break}case"ip":{if(n.version!=="v6")fo(r,"ipv4",n.message,t);if(n.version!=="v4")fo(r,"ipv6",n.message,t);break}case"base64url":Jr(r,po.base64url,n.message,t);break;case"jwt":Jr(r,po.jwt,n.message,t);break;case"cidr":{if(n.version!=="v6")Jr(r,po.ipv4Cidr,n.message,t);if(n.version!=="v4")Jr(r,po.ipv6Cidr,n.message,t);break}case"emoji":Jr(r,po.emoji(),n.message,t);break;case"ulid":{Jr(r,po.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{fo(r,"binary",n.message,t);break}case"contentEncoding:base64":{at(r,"contentEncoding","base64",n.message,t);break}case"pattern:zod":{Jr(r,po.base64,n.message,t);break}}break}case"nanoid":Jr(r,po.nanoid,n.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:((o)=>{})(n)}return r}function dS(e,t){return t.patternStrategy==="escape"?GY(e):e}var HY=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function GY(e){let t="";for(let r=0;r<e.length;r++){if(!HY.has(e[r]))t+="\\";t+=e[r]}return t}function fo(e,t,r,n){if(e.format||e.anyOf?.some((o)=>o.format)){if(!e.anyOf)e.anyOf=[];if(e.format){if(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage){if(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0)delete e.errorMessage}}e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})}else at(e,"format",t,r,n)}function Jr(e,t,r,n){if(e.pattern||e.allOf?.some((o)=>o.pattern)){if(!e.allOf)e.allOf=[];if(e.pattern){if(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage){if(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0)delete e.errorMessage}}e.allOf.push({pattern:vO(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})}else at(e,"pattern",vO(t,n),r,n)}function vO(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},n=r.i?e.source.toLowerCase():e.source,o="",i=!1,s=!1,a=!1;for(let c=0;c<n.length;c++){if(i){o+=n[c],i=!1;continue}if(r.i){if(s){if(n[c].match(/[a-z]/)){if(a)o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1;else if(n[c+1]==="-"&&n[c+2]?.match(/[a-z]/))o+=n[c],a=!0;else o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
131
131
  ]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
132
132
  ]))`;continue}}if(r.s&&n[c]==="."){o+=s?`${n[c]}\r
133
133
  `:`[${n[c]}\r
134
- ]`;continue}if(o+=n[c],n[c]==="\\")i=!0;else if(s&&n[c]==="]")s=!1;else if(!s&&n[c]==="[")s=!0}try{new RegExp(o)}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 o}function Dg(e,t){if(t.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(t.target==="openApi3"&&e.keyType?._def.typeName===se.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,o)=>({...n,[o]:De(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??Ht(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:De(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===se.ZodString&&e.keyType._def.checks?.length){let{type:n,...o}=Lg(e.keyType._def,t);return{...r,propertyNames:o}}else if(e.keyType?._def.typeName===se.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===se.ZodBranded&&e.keyType._def.type._def.typeName===se.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...o}=Bg(e.keyType._def,t);return{...r,propertyNames:o}}return r}function TO(e,t){if(t.mapStrategy==="record")return Dg(e,t);let r=De(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Ht(t),n=De(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Ht(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function EO(e){let t=e.values,n=Object.keys(e.values).filter((i)=>typeof t[t[i]]!=="number").map((i)=>t[i]),o=Array.from(new Set(n.map((i)=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function PO(e){return e.target==="openAi"?void 0:{not:Ht({...e,currentPath:[...e.currentPath,"not"]})}}function AO(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Kp={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function kO(e,t){if(t.target==="openApi3")return IO(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every((n)=>(n._def.typeName in Kp)&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let s=Kp[i._def.typeName];return s&&!o.includes(s)?[...o,s]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every((n)=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let s=typeof i._def.value;switch(s){case"string":case"number":case"boolean":return[...o,s];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((i,s,a)=>a.indexOf(i)===s);return{type:o.length>1?o:o[0],enum:r.reduce((i,s)=>i.includes(s._def.value)?i:[...i,s._def.value],[])}}}else if(r.every((n)=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter((i)=>!n.includes(i))],[])};return IO(e,t)}var IO=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>De(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter((n)=>!!n&&(!t.strictUnions||typeof n==="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function RO(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length)){if(t.target==="openApi3")return{type:Kp[e.innerType._def.typeName],nullable:!0};return{type:[Kp[e.innerType._def.typeName],"null"]}}if(t.target==="openApi3"){let n=De(e.innerType._def,{...t,currentPath:[...t.currentPath]});if(n&&"$ref"in n)return{allOf:[n],nullable:!0};return n&&{...n,nullable:!0}}let r=De(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function OO(e,t){let r={type:"number"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"int":r.type="integer",aS(r,"type",n.message,t);break;case"min":if(t.target==="jsonSchema7")if(n.inclusive)at(r,"minimum",n.value,n.message,t);else at(r,"exclusiveMinimum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMinimum=!0;at(r,"minimum",n.value,n.message,t)}break;case"max":if(t.target==="jsonSchema7")if(n.inclusive)at(r,"maximum",n.value,n.message,t);else at(r,"exclusiveMaximum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMaximum=!0;at(r,"maximum",n.value,n.message,t)}break;case"multipleOf":at(r,"multipleOf",n.value,n.message,t);break}return r}function CO(e,t){let r=t.target==="openAi",n={type:"object",properties:{}},o=[],i=e.shape();for(let a in i){let c=i[a];if(c===void 0||c._def===void 0)continue;let d=ZY(c);if(d&&r){if(c._def.typeName==="ZodOptional")c=c._def.innerType;if(!c.isNullable())c=c.nullable();d=!1}let l=De(c._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});if(l===void 0)continue;if(n.properties[a]=l,!d)o.push(a)}if(o.length)n.required=o;let s=VY(e,t);if(s!==void 0)n.additionalProperties=s;return n}function VY(e,t){if(e.catchall._def.typeName!=="ZodNever")return De(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 ZY(e){try{return e.isOptional()}catch{return!0}}var MO=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return De(e.innerType._def,t);let r=De(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ht(t)},r]}:Ht(t)};var $O=(e,t)=>{if(t.pipeStrategy==="input")return De(e.in._def,t);else if(t.pipeStrategy==="output")return De(e.out._def,t);let r=De(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=De(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter((o)=>o!==void 0)}};function NO(e,t){return De(e.type._def,t)}function zO(e,t){let n={type:"array",uniqueItems:!0,items:De(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};if(e.minSize)at(n,"minItems",e.minSize.value,e.minSize.message,t);if(e.maxSize)at(n,"maxItems",e.maxSize.value,e.maxSize.message,t);return n}function BO(e,t){if(e.rest)return{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>De(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:De(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})};else return{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>De(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function LO(e){return{not:Ht(e)}}function DO(e){return Ht(e)}var UO=(e,t)=>De(e.innerType._def,t);var FO=(e,t,r)=>{switch(t){case se.ZodString:return Lg(e,r);case se.ZodNumber:return OO(e,r);case se.ZodObject:return CO(e,r);case se.ZodBigInt:return hO(e,r);case se.ZodBoolean:return gO();case se.ZodDate:return cS(e,r);case se.ZodUndefined:return LO(r);case se.ZodNull:return AO(r);case se.ZodArray:return mO(e,r);case se.ZodUnion:case se.ZodDiscriminatedUnion:return kO(e,r);case se.ZodIntersection:return wO(e,r);case se.ZodTuple:return BO(e,r);case se.ZodRecord:return Dg(e,r);case se.ZodLiteral:return SO(e,r);case se.ZodEnum:return _O(e);case se.ZodNativeEnum:return EO(e);case se.ZodNullable:return RO(e,r);case se.ZodOptional:return MO(e,r);case se.ZodMap:return TO(e,r);case se.ZodSet:return zO(e,r);case se.ZodLazy:return()=>e.getter()._def;case se.ZodPromise:return NO(e,r);case se.ZodNaN:case se.ZodNever:return PO(r);case se.ZodEffects:return xO(e,r);case se.ZodAny:return Ht(r);case se.ZodUnknown:return DO(r);case se.ZodDefault:return bO(e,r);case se.ZodBranded:return Bg(e,r);case se.ZodReadonly:return UO(e,r);case se.ZodCatch:return yO(e,r);case se.ZodPipeline:return $O(e,r);case se.ZodFunction:case se.ZodVoid:case se.ZodSymbol:return;default:return((n)=>{return})(t)}};function De(e,t,r=!1){let n=t.seen.get(e);if(t.override){let a=t.override?.(e,t,n,r);if(a!==lO)return a}if(n&&!r){let a=WY(n,t);if(a!==void 0)return a}let o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);let i=FO(e,e.typeName,t),s=typeof i==="function"?De(i(),t):i;if(s)KY(e,t,s);if(t.postProcess){let a=t.postProcess(s,e,t);return o.jsonSchema=s,a}return o.jsonSchema=s,s}var WY=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:zg(t.currentPath,e.path)};case"none":case"seen":{if(e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Ht(t);return t.$refStrategy==="seen"?Ht(t):void 0}}},KY=(e,t,r)=>{if(e.description){if(r.description=e.description,t.markdownDescription)r.markdownDescription=e.description}return r};var lS=(e,t)=>{let r=fO(t),n=typeof t==="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[d,l])=>({...c,[d]:De(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,d]},!0)??Ht(r)}),{}):void 0,o=typeof t==="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=De(e._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Ht(r),s=typeof t==="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;if(s!==void 0)i.title=s;if(r.flags.hasReferencedOpenAiAnyType){if(!n)n={};if(!n[r.openAiAnyTypeName])n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}}let a=o===void 0?n?{...i,[r.definitionPath]:n}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:i}};if(r.target==="jsonSchema7")a.$schema="http://json-schema.org/draft-07/schema#";else if(r.target==="jsonSchema2019-09"||r.target==="openAi")a.$schema="https://json-schema.org/draft/2019-09/schema#";if(r.target==="openAi"&&(("anyOf"in a)||("oneOf"in a)||("allOf"in a)||("type"in a)&&Array.isArray(a.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return a};function YY(e){if(!e)return"draft-7";if(e==="jsonSchema7"||e==="draft-7")return"draft-7";if(e==="jsonSchema2019-09"||e==="draft-2020-12")return"draft-2020-12";return"draft-7"}function pS(e,t){if(qn(e))return Lw(e,{target:YY(t?.target),io:t?.pipeStrategy??"input"});return lS(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function fS(e){let r=js(e)?.method;if(!r)throw Error("Schema is missing a method literal");let n=lg(r);if(typeof n!=="string")throw Error("Schema method literal must be a string");return n}function mS(e,t){let r=Fs(e,t);if(!r.success)throw r.error;return r.data}var JY=60000;class hS{constructor(e){if(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(xg,(t)=>{this._oncancel(t)}),this.setNotificationHandler(wg,(t)=>{this._onprogress(t)}),this.setRequestHandler(_g,(t)=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore)this.setRequestHandler(Sg,async(t,r)=>{let n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new ve(Me.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Tg,async(t,r)=>{let n=async()=>{let o=t.params.taskId;if(this._taskMessageQueue){let s;while(s=await this._taskMessageQueue.dequeue(o,r.sessionId)){if(s.type==="response"||s.type==="error"){let a=s.message,c=a.id,d=this._requestResolvers.get(c);if(d)if(this._requestResolvers.delete(c),s.type==="response")d(a);else{let l=a,p=new ve(l.error.code,l.error.message,l.error.data);d(p)}else{let l=s.type==="response"?"Response":"Error";this._onerror(Error(`${l} handler missing for request ${c}`))}continue}await this._transport?.send(s.message,{relatedRequestId:r.requestId})}}let i=await this._taskStore.getTask(o,r.sessionId);if(!i)throw new ve(Me.InvalidParams,`Task not found: ${o}`);if(!Hs(i.status))return await this._waitForTaskUpdate(o,r.signal),await n();if(Hs(i.status)){let s=await this._taskStore.getTaskResult(o,r.sessionId);return this._clearTaskQueue(o),{...s,_meta:{...s._meta,[qs]:{taskId:o}}}}return await n()};return await n()}),this.setRequestHandler(Eg,async(t,r)=>{try{let{tasks:n,nextCursor:o}=await this._taskStore.listTasks(t.params?.cursor,r.sessionId);return{tasks:n,nextCursor:o,_meta:{}}}catch(n){throw new ve(Me.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(Ag,async(t,r)=>{try{let n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new ve(Me.InvalidParams,`Task not found: ${t.params.taskId}`);if(Hs(n.status))throw new ve(Me.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(t.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(t.params.taskId);let o=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!o)throw new ve(Me.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...o}}catch(n){if(n instanceof ve)throw n;throw new ve(Me.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}})}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,n,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),ve.fromError(Me.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);if(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 r=this.transport?.onerror;this._transport.onerror=(o)=>{r?.(o),this._onerror(o)};let n=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{if(n?.(o,i),Up(o)||Q5(o))this._onresponse(o);else if(Zw(o))this._onrequest(o,i);else if(J5(o))this._onnotification(o);else this._onerror(Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(let r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();let t=ve.fromError(Me.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let r of e.values())r(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;if(t===void 0)return;Promise.resolve().then(()=>t(e)).catch((r)=>this._onerror(Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,t){let r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,o=e.params?._meta?.[qs]?.taskId;if(r===void 0){let d={jsonrpc:"2.0",id:e.id,error:{code:Me.MethodNotFound,message:"Method not found"}};if(o&&this._taskMessageQueue)this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},n?.sessionId).catch((l)=>this._onerror(Error(`Failed to enqueue error response: ${l}`)));else n?.send(d).catch((l)=>this._onerror(Error(`Failed to send an error response: ${l}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let s=W5(e.params)?e.params.task:void 0,a=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,c={signal:i.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async(d)=>{if(i.signal.aborted)return;let l={relatedRequestId:e.id};if(o)l.relatedTask={taskId:o};await this.notification(d,l)},sendRequest:async(d,l,p)=>{if(i.signal.aborted)throw new ve(Me.ConnectionClosed,"Request was cancelled");let m={...p,relatedRequestId:e.id};if(o&&!m.relatedTask)m.relatedTask={taskId:o};let h=m.relatedTask?.taskId??o;if(h&&a)await a.updateTaskStatus(h,"input_required");return await this.request(d,l,m)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:o,taskStore:a,taskRequestedTtl:s?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(s)this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,c)).then(async(d)=>{if(i.signal.aborted)return;let l={result:d,jsonrpc:"2.0",id:e.id};if(o&&this._taskMessageQueue)await this._enqueueTaskMessage(o,{type:"response",message:l,timestamp:Date.now()},n?.sessionId);else await n?.send(l)},async(d)=>{if(i.signal.aborted)return;let l={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:Me.InternalError,message:d.message??"Internal error",...d.data!==void 0&&{data:d.data}}};if(o&&this._taskMessageQueue)await this._enqueueTaskMessage(o,{type:"error",message:l,timestamp:Date.now()},n?.sessionId);else await n?.send(l)}).catch((d)=>this._onerror(Error(`Failed to send response: ${d}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(e.id)===i)this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,n=Number(t),o=this._progressHandlers.get(n);if(!o){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&i&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(a){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),i(a);return}o(r)}_onresponse(e){let t=Number(e.id),r=this._requestResolvers.get(t);if(r){if(this._requestResolvers.delete(t),Up(e))r(e);else{let i=new ve(e.error.code,e.error.message,e.error.data);r(i)}return}let n=this._responseHandlers.get(t);if(n===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 o=!1;if(Up(e)&&e.result&&typeof e.result==="object"){let i=e.result;if(i.task&&typeof i.task==="object"){let s=i.task;if(typeof s.taskId==="string")o=!0,this._taskProgressTokens.set(s.taskId,t)}}if(!o)this._progressHandlers.delete(t);if(Up(e))n(e);else{let i=ve.fromError(e.error.code,e.error.message,e.error.data);n(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,r){let{task:n}=r??{};if(!n){try{yield{type:"result",result:await this.request(e,t,r)}}catch(i){yield{type:"error",error:i instanceof ve?i:new ve(Me.InternalError,String(i))}}return}let o;try{let i=await this.request(e,Mu,r);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new ve(Me.InternalError,"Task creation did not return a task");while(!0){let s=await this.getTask({taskId:o},r);if(yield{type:"taskStatus",task:s},Hs(s.status)){if(s.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)};else if(s.status==="failed")yield{type:"error",error:new ve(Me.InternalError,`Task ${o} failed`)};else if(s.status==="cancelled")yield{type:"error",error:new ve(Me.InternalError,`Task ${o} was cancelled`)};return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)};return}let a=s.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((c)=>setTimeout(c,a)),r?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof ve?i:new ve(Me.InternalError,String(i))}}}request(e,t,r){let{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i,task:s,relatedTask:a}=r??{};return new Promise((c,d)=>{let l=(w)=>{d(w)};if(!this._transport){l(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(e.method),s)this.assertTaskCapability(e.method)}catch(w){l(w);return}r?.signal?.throwIfAborted();let p=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:p};if(r?.onprogress)this._progressHandlers.set(p,r.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}};if(s)m.params={...m.params,task:s};if(a)m.params={...m.params,_meta:{...m.params?._meta||{},[qs]:a}};let h=(w)=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(w)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i}).catch((v)=>this._onerror(Error(`Failed to send cancellation: ${v}`)));let A=w instanceof ve?w:new ve(Me.RequestTimeout,String(w));d(A)};this._responseHandlers.set(p,(w)=>{if(r?.signal?.aborted)return;if(w instanceof Error)return d(w);try{let A=Fs(t,w.result);if(!A.success)d(A.error);else c(A.data)}catch(A){d(A)}}),r?.signal?.addEventListener("abort",()=>{h(r?.signal?.reason)});let b=r?.timeout??JY,x=()=>h(ve.fromError(Me.RequestTimeout,"Request timed out",{timeout:b}));this._setupTimeout(p,b,r?.maxTotalTimeout,x,r?.resetTimeoutOnProgress??!1);let _=a?.taskId;if(_){let w=(A)=>{let v=this._responseHandlers.get(p);if(v)v(A);else this._onerror(Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,w),this._enqueueTaskMessage(_,{type:"request",message:m,timestamp:Date.now()}).catch((A)=>{this._cleanupTimeout(p),d(A)})}else this._transport.send(m,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i}).catch((w)=>{this._cleanupTimeout(p),d(w)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},vg,t)}async getTaskResult(e,t,r){return this.request({method:"tasks/result",params:e},t,r)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},Pg,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},tO,t)}async notification(e,t){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(e.method);let r=t?.relatedTask?.taskId;if(r){let s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[qs]:t.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:s,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"};if(t?.relatedTask)s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[qs]:t.relatedTask}}};this._transport?.send(s,t).catch((a)=>this._onerror(a))});return}let i={...e,jsonrpc:"2.0"};if(t?.relatedTask)i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[qs]:t.relatedTask}}};await this._transport.send(i,t)}setRequestHandler(e,t){let r=fS(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(n,o)=>{let i=mS(e,n);return Promise.resolve(t(i,o))})}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 r=fS(e);this._notificationHandlers.set(r,(n)=>{let o=mS(e,n);return Promise.resolve(t(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);if(t!==void 0)this._progressHandlers.delete(t),this._taskProgressTokens.delete(e)}async _enqueueTaskMessage(e,t,r){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,r,n)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,t);for(let n of r)if(n.type==="request"&&Zw(n.message)){let o=n.message.id,i=this._requestResolvers.get(o);if(i)i(new ve(Me.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o);else this._onerror(Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let r=this._options?.defaultTaskPollInterval??1000;try{let n=await this._taskStore?.getTask(e);if(n?.pollInterval)r=n.pollInterval}catch{}return new Promise((n,o)=>{if(t.aborted){o(new ve(Me.InvalidRequest,"Request cancelled"));return}let i=setTimeout(n,r);t.addEventListener("abort",()=>{clearTimeout(i),o(new ve(Me.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){let r=this._taskStore;if(!r)throw Error("No task store configured");return{createTask:async(n)=>{if(!e)throw Error("No request provided");return await r.createTask(n,e.id,{method:e.method,params:e.params},t)},getTask:async(n)=>{let o=await r.getTask(n,t);if(!o)throw new ve(Me.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(n,o,i)=>{await r.storeTaskResult(n,o,i,t);let s=await r.getTask(n,t);if(s){let a=Gp.parse({method:"notifications/tasks/status",params:s});if(await this.notification(a),Hs(s.status))this._cleanupTaskProgressHandler(n)}},getTaskResult:(n)=>r.getTaskResult(n,t),updateTaskStatus:async(n,o,i)=>{let s=await r.getTask(n,t);if(!s)throw new ve(Me.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Hs(s.status))throw new ve(Me.InvalidParams,`Cannot update task "${n}" from terminal status "${s.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(n,o,i,t);let a=await r.getTask(n,t);if(a){let c=Gp.parse({method:"notifications/tasks/status",params:a});if(await this.notification(c),Hs(a.status))this._cleanupTaskProgressHandler(n)}},listTasks:(n)=>r.listTasks(n,t)}}}function jO(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function qO(e,t){let r={...e};for(let n in t){let o=n,i=t[o];if(i===void 0)continue;let s=r[o];if(jO(s)&&jO(i))r[o]={...s,...i};else r[o]=i}return r}var E4=Vr(dv(),1),P4=Vr(T4(),1);function xie(){let e=new E4.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return P4.default(e),e}class _v{constructor(e){this._ajv=e??xie()}getValidator(e){let t="$id"in e&&typeof e.$id==="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return(r)=>{if(t(r))return{valid:!0,data:r,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}}class wv{constructor(e){this._server=e}requestStream(e,t,r){return this._server.requestStream(e,t,r)}createMessageStream(e,t){let r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],i=o.some((d)=>d.type==="tool_result"),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],c=a.some((d)=>d.type==="tool_use");if(i){if(o.some((d)=>d.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!c)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let d=new Set(a.filter((p)=>p.type==="tool_use").map((p)=>p.id)),l=new Set(o.filter((p)=>p.type==="tool_result").map((p)=>p.toolUseId));if(d.size!==l.size||![...d].every((p)=>l.has(p)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Wp,t)}elicitInputStream(e,t){let r=this._server.getClientCapabilities(),n=e.mode??"form";switch(n){case"url":{if(!r?.elicitation?.url)throw Error("Client does not support url elicitation.");break}case"form":{if(!r?.elicitation?.form)throw Error("Client does not support form elicitation.");break}}let o=n==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},zu,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._server.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}}function A4(e,t,r){if(!e)throw Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function I4(e,t,r){if(!e)throw Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}class Sv extends hS{constructor(e,t){super(t);if(this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Zp.options.map((r,n)=>[r,n])),this.isMessageIgnored=(r,n)=>{let o=this._loggingLevels.get(n);return o?this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new _v,this.setRequestHandler(Yw,(r)=>this._oninitialize(r)),this.setNotificationHandler(Jw,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(oS,async(r,n)=>{let o=n.sessionId||n.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,s=Zp.safeParse(i);if(s.success)this._loggingLevels.set(o,s.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new wv(this)};return this._experimental}registerCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=qO(this._capabilities,e)}setRequestHandler(e,t){let n=js(e)?.method;if(!n)throw Error("Schema is missing a method literal");let o;if(qn(n)){let s=n;o=s._zod?.def?.value??s.value}else{let s=n;o=s._def?.value??s.value}if(typeof o!=="string")throw Error("Schema method literal must be a string");if(o==="tools/call"){let s=async(a,c)=>{let d=Fs(Nu,a);if(!d.success){let h=d.error instanceof Error?d.error.message:String(d.error);throw new ve(Me.InvalidParams,`Invalid tools/call request: ${h}`)}let{params:l}=d.data,p=await Promise.resolve(t(a,c));if(l.task){let h=Fs(Mu,p);if(!h.success){let b=h.error instanceof Error?h.error.message:String(h.error);throw new ve(Me.InvalidParams,`Invalid task creation result: ${b}`)}return h.data}let m=Fs($g,p);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new ve(Me.InvalidParams,`Invalid tools/call result: ${h}`)}return m.data};return super.setRequestHandler(e,s)}return super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(!this._capabilities)return;switch(e){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){I4(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){if(!this._capabilities)return;A4(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:G5.includes(t)?t:Gw,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},bg)}async createMessage(e,t){if(e.tools||e.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(e.messages.length>0){let r=e.messages[e.messages.length-1],n=Array.isArray(r.content)?r.content:[r.content],o=n.some((c)=>c.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,s=i?Array.isArray(i.content)?i.content:[i.content]:[],a=s.some((c)=>c.type==="tool_use");if(o){if(n.some((c)=>c.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!a)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(a){let c=new Set(s.filter((l)=>l.type==="tool_use").map((l)=>l.id)),d=new Set(n.filter((l)=>l.type==="tool_result").map((l)=>l.toolUseId));if(c.size!==d.size||![...c].every((l)=>d.has(l)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(e.tools)return this.request({method:"sampling/createMessage",params:e},iS,t);return this.request({method:"sampling/createMessage",params:e},Wp,t)}async elicitInput(e,t){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let n=e;return this.request({method:"elicitation/create",params:n},zu,t)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let n=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:n},zu,t);if(o.action==="accept"&&o.content&&n.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(n.requestedSchema)(o.content);if(!s.valid)throw new ve(Me.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(i){if(i instanceof ve)throw i;throw new ve(Me.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return o}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},sS,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging){if(!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var R4=Symbol.for("mcp.completable");function vv(e){return!!e&&typeof e==="object"&&R4 in e}function O4(e){return e[R4]?.complete}var k4;(function(e){e.Completable="McpCompletable"})(k4||(k4={}));var _ie=/^[A-Za-z0-9._-]{1,128}$/;function wie(e){let t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" "))t.push("Tool name contains spaces, which may cause parsing issues");if(e.includes(","))t.push("Tool name contains commas, which may cause parsing issues");if(e.startsWith("-")||e.endsWith("-"))t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if(e.startsWith(".")||e.endsWith("."))t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!_ie.test(e)){let r=e.split("").filter((n)=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,i)=>i.indexOf(n)===o);return t.push(`Tool name contains invalid characters: ${r.map((n)=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function Sie(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let r of t)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function Tv(e){let t=wie(e);return Sie(e,t.warnings),t.isValid}class Ev{constructor(e){this._mcpServer=e}registerToolTask(e,t,r){let n={taskSupport:"required",...t.execution};if(n.taskSupport==="forbidden")throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,n,t._meta,r)}}class Av{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Sv(e,t)}get experimental(){if(!this._experimental)this._experimental={tasks:new Ev(this)};return this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){if(this._toolHandlersInitialized)return;this.server.assertCanSetRequestHandler(Qs(Mg)),this.server.assertCanSetRequestHandler(Qs(Nu)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Mg,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let r={name:e,title:t.title,description:t.description,inputSchema:(()=>{let n=Ru(t.inputSchema);return n?pS(n,{strictUnions:!0,pipeStrategy:"input"}):vie})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let n=Ru(t.outputSchema);if(n)r.outputSchema=pS(n,{strictUnions:!0,pipeStrategy:"output"})}return r})})),this.server.setRequestHandler(Nu,async(e,t)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new ve(Me.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new ve(Me.InvalidParams,`Tool ${e.params.name} disabled`);let n=!!e.params.task,o=r.execution?.taskSupport,i="createTask"in r.handler;if((o==="required"||o==="optional")&&!i)throw new ve(Me.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!n)throw new ve(Me.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!n&&i)return await this.handleAutomaticTaskPolling(r,e,t);let s=await this.validateToolInput(r,e.params.arguments,e.params.name),a=await this.executeToolHandler(r,s,t);if(n)return a;return await this.validateToolOutput(r,a,e.params.name),a}catch(r){if(r instanceof ve){if(r.code===Me.UrlElicitationRequired)throw r}return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,r){if(!e.inputSchema)return;let o=Ru(e.inputSchema)??e.inputSchema,i=await ug(o,t);if(!i.success){let s="error"in i?i.error:"Unknown error",a=dg(s);throw new ve(Me.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${a}`)}return i.data}async validateToolOutput(e,t,r){if(!e.outputSchema)return;if(!("content"in t))return;if(t.isError)return;if(!t.structuredContent)throw new ve(Me.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let n=Ru(e.outputSchema),o=await ug(n,t.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",s=dg(i);throw new ve(Me.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${s}`)}}async executeToolHandler(e,t,r){let n=e.handler;if("createTask"in n){if(!r.taskStore)throw Error("No task store provided.");let i={...r,taskStore:r.taskStore};if(e.inputSchema)return await Promise.resolve(n.createTask(t,i));else return await Promise.resolve(n.createTask(i))}if(e.inputSchema)return await Promise.resolve(n(t,r));else return await Promise.resolve(n(r))}async handleAutomaticTaskPolling(e,t,r){if(!r.taskStore)throw Error("No task store provided for task-capable tool.");let n=await this.validateToolInput(e,t.params.arguments,t.params.name),o=e.handler,i={...r,taskStore:r.taskStore},s=n?await Promise.resolve(o.createTask(n,i)):await Promise.resolve(o.createTask(i)),a=s.task.taskId,c=s.task,d=c.pollInterval??5000;while(c.status!=="completed"&&c.status!=="failed"&&c.status!=="cancelled"){await new Promise((p)=>setTimeout(p,d));let l=await r.taskStore.getTask(a);if(!l)throw new ve(Me.InternalError,`Task ${a} not found during polling`);c=l}return await r.taskStore.getTaskResult(a)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(Qs(Ng)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ng,async(e)=>{switch(e.params.ref.type){case"ref/prompt":return aO(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return cO(e),this.handleResourceCompletion(e,e.params.ref);default:throw new ve(Me.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new ve(Me.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new ve(Me.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return _f;let o=js(r.argsSchema)?.[e.params.argument.name];if(!vv(o))return _f;let i=O4(o);if(!i)return _f;let s=await i(e.params.argument.value,e.params.context);return M4(s)}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find((i)=>i.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return _f;throw new ve(Me.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let n=r.resourceTemplate.completeCallback(e.params.argument.name);if(!n)return _f;let o=await n(e.params.argument.value,e.params.context);return M4(o)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(Qs(Ig)),this.server.assertCanSetRequestHandler(Qs(kg)),this.server.assertCanSetRequestHandler(Qs(Rg)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ig,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([o,i])=>i.enabled).map(([o,i])=>({uri:o,name:i.name,...i.metadata})),n=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let i=await o.resourceTemplate.listCallback(t);for(let s of i.resources)n.push({...o.metadata,...s})}return{resources:[...r,...n]}}),this.server.setRequestHandler(kg,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(Rg,async(e,t)=>{let r=new URL(e.params.uri),n=this._registeredResources[r.toString()];if(n){if(!n.enabled)throw new ve(Me.InvalidParams,`Resource ${r} disabled`);return n.readCallback(r,t)}for(let o of Object.values(this._registeredResourceTemplates)){let i=o.resourceTemplate.uriTemplate.match(r.toString());if(i)return o.readCallback(r,i,t)}throw new ve(Me.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(Qs(Og)),this.server.assertCanSetRequestHandler(Qs(Cg)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Og,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Tie(t.argsSchema):void 0}))})),this.server.setRequestHandler(Cg,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new ve(Me.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new ve(Me.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let n=Ru(r.argsSchema),o=await ug(n,e.params.arguments);if(!o.success){let a="error"in o?o.error:"Unknown error",c=dg(a);throw new ve(Me.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${c}`)}let i=o.data,s=r.callback;return await Promise.resolve(s(i,t))}else{let n=r.callback;return await Promise.resolve(n(t))}}),this._promptHandlersInitialized=!0}resource(e,t,...r){let n;if(typeof r[0]==="object")n=r.shift();let o=r[0];if(typeof t==="string"){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,void 0,t,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,t,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,t,r,n){if(typeof t==="string"){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let o=this._createRegisteredResource(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,t,r,n,o){let i={name:e,title:t,metadata:n,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:(s)=>{if(typeof s.uri<"u"&&s.uri!==r){if(delete this._registeredResources[r],s.uri)this._registeredResources[s.uri]=i}if(typeof s.name<"u")i.name=s.name;if(typeof s.title<"u")i.title=s.title;if(typeof s.metadata<"u")i.metadata=s.metadata;if(typeof s.callback<"u")i.readCallback=s.callback;if(typeof s.enabled<"u")i.enabled=s.enabled;this.sendResourceListChanged()}};return this._registeredResources[r]=i,i}_createRegisteredResourceTemplate(e,t,r,n,o){let i={resourceTemplate:r,title:t,metadata:n,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:(c)=>{if(typeof c.name<"u"&&c.name!==e){if(delete this._registeredResourceTemplates[e],c.name)this._registeredResourceTemplates[c.name]=i}if(typeof c.title<"u")i.title=c.title;if(typeof c.template<"u")i.resourceTemplate=c.template;if(typeof c.metadata<"u")i.metadata=c.metadata;if(typeof c.callback<"u")i.readCallback=c.callback;if(typeof c.enabled<"u")i.enabled=c.enabled;this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let s=r.uriTemplate.variableNames;if(Array.isArray(s)&&s.some((c)=>!!r.completeCallback(c)))this.setCompletionRequestHandler();return i}_createRegisteredPrompt(e,t,r,n,o){let i={title:t,description:r,argsSchema:n===void 0?void 0:nc(n),callback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:(s)=>{if(typeof s.name<"u"&&s.name!==e){if(delete this._registeredPrompts[e],s.name)this._registeredPrompts[s.name]=i}if(typeof s.title<"u")i.title=s.title;if(typeof s.description<"u")i.description=s.description;if(typeof s.argsSchema<"u")i.argsSchema=nc(s.argsSchema);if(typeof s.callback<"u")i.callback=s.callback;if(typeof s.enabled<"u")i.enabled=s.enabled;this.sendPromptListChanged()}};if(this._registeredPrompts[e]=i,n){if(Object.values(n).some((a)=>{let c=a instanceof mg?a._def?.innerType:a;return vv(c)}))this.setCompletionRequestHandler()}return i}_createRegisteredTool(e,t,r,n,o,i,s,a,c){Tv(e);let d={title:t,description:r,inputSchema:C4(n),outputSchema:C4(o),annotations:i,execution:s,_meta:a,handler:c,enabled:!0,disable:()=>d.update({enabled:!1}),enable:()=>d.update({enabled:!0}),remove:()=>d.update({name:null}),update:(l)=>{if(typeof l.name<"u"&&l.name!==e){if(typeof l.name==="string")Tv(l.name);if(delete this._registeredTools[e],l.name)this._registeredTools[l.name]=d}if(typeof l.title<"u")d.title=l.title;if(typeof l.description<"u")d.description=l.description;if(typeof l.paramsSchema<"u")d.inputSchema=nc(l.paramsSchema);if(typeof l.outputSchema<"u")d.outputSchema=nc(l.outputSchema);if(typeof l.callback<"u")d.handler=l.callback;if(typeof l.annotations<"u")d.annotations=l.annotations;if(typeof l._meta<"u")d._meta=l._meta;if(typeof l.enabled<"u")d.enabled=l.enabled;this.sendToolListChanged()}};return this._registeredTools[e]=d,this.setToolRequestHandlers(),this.sendToolListChanged(),d}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r,n,o,i;if(typeof t[0]==="string")r=t.shift();if(t.length>1){let a=t[0];if(Pv(a)){if(n=t.shift(),t.length>1&&typeof t[0]==="object"&&t[0]!==null&&!Pv(t[0]))i=t.shift()}else if(typeof a==="object"&&a!==null){if(Object.values(a).some((c)=>typeof c==="object"&&c!==null))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=t.shift()}}let s=t[0];return this._createRegisteredTool(e,void 0,r,n,o,i,{taskSupport:"forbidden"},void 0,s)}registerTool(e,t,r){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:n,description:o,inputSchema:i,outputSchema:s,annotations:a,_meta:c}=t;return this._createRegisteredTool(e,n,o,i,s,a,{taskSupport:"forbidden"},c,r)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let r;if(typeof t[0]==="string")r=t.shift();let n;if(t.length>1)n=t.shift();let o=t[0],i=this._createRegisteredPrompt(e,void 0,r,n,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,t,r){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:n,description:o,argsSchema:i}=t,s=this._createRegisteredPrompt(e,n,o,i,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){if(this.isConnected())this.server.sendResourceListChanged()}sendToolListChanged(){if(this.isConnected())this.server.sendToolListChanged()}sendPromptListChanged(){if(this.isConnected())this.server.sendPromptListChanged()}}var vie={type:"object",properties:{}};function $4(e){return e!==null&&typeof e==="object"&&"parse"in e&&typeof e.parse==="function"&&"safeParse"in e&&typeof e.safeParse==="function"}function N4(e){return"_def"in e||"_zod"in e||$4(e)}function Pv(e){if(typeof e!=="object"||e===null)return!1;if(N4(e))return!1;if(Object.keys(e).length===0)return!0;return Object.values(e).some($4)}function C4(e){if(!e)return;if(Pv(e))return nc(e);if(!N4(e))throw Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}function Tie(e){let t=js(e);if(!t)return[];return Object.entries(t).map(([r,n])=>{let o=c5(n),i=u5(n);return{name:r,description:o,required:!i}})}function Qs(e){let r=js(e)?.method;if(!r)throw Error("Schema is missing a method literal");let n=lg(r);if(typeof n==="string")return n;throw Error("Schema method literal must be a string")}function M4(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var _f={completion:{values:[],hasMore:!1}};import B4 from"node:process";class Iv{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
134
+ ]`;continue}if(o+=n[c],n[c]==="\\")i=!0;else if(s&&n[c]==="]")s=!1;else if(!s&&n[c]==="[")s=!0}try{new RegExp(o)}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 o}function Dg(e,t){if(t.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(t.target==="openApi3"&&e.keyType?._def.typeName===se.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,o)=>({...n,[o]:De(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??Ht(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:De(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===se.ZodString&&e.keyType._def.checks?.length){let{type:n,...o}=Lg(e.keyType._def,t);return{...r,propertyNames:o}}else if(e.keyType?._def.typeName===se.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===se.ZodBranded&&e.keyType._def.type._def.typeName===se.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...o}=Bg(e.keyType._def,t);return{...r,propertyNames:o}}return r}function TO(e,t){if(t.mapStrategy==="record")return Dg(e,t);let r=De(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Ht(t),n=De(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Ht(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function EO(e){let t=e.values,n=Object.keys(e.values).filter((i)=>typeof t[t[i]]!=="number").map((i)=>t[i]),o=Array.from(new Set(n.map((i)=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function PO(e){return e.target==="openAi"?void 0:{not:Ht({...e,currentPath:[...e.currentPath,"not"]})}}function AO(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Kp={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function kO(e,t){if(t.target==="openApi3")return IO(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every((n)=>(n._def.typeName in Kp)&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let s=Kp[i._def.typeName];return s&&!o.includes(s)?[...o,s]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every((n)=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let s=typeof i._def.value;switch(s){case"string":case"number":case"boolean":return[...o,s];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((i,s,a)=>a.indexOf(i)===s);return{type:o.length>1?o:o[0],enum:r.reduce((i,s)=>i.includes(s._def.value)?i:[...i,s._def.value],[])}}}else if(r.every((n)=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter((i)=>!n.includes(i))],[])};return IO(e,t)}var IO=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>De(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter((n)=>!!n&&(!t.strictUnions||typeof n==="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function RO(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length)){if(t.target==="openApi3")return{type:Kp[e.innerType._def.typeName],nullable:!0};return{type:[Kp[e.innerType._def.typeName],"null"]}}if(t.target==="openApi3"){let n=De(e.innerType._def,{...t,currentPath:[...t.currentPath]});if(n&&"$ref"in n)return{allOf:[n],nullable:!0};return n&&{...n,nullable:!0}}let r=De(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function OO(e,t){let r={type:"number"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"int":r.type="integer",aS(r,"type",n.message,t);break;case"min":if(t.target==="jsonSchema7")if(n.inclusive)at(r,"minimum",n.value,n.message,t);else at(r,"exclusiveMinimum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMinimum=!0;at(r,"minimum",n.value,n.message,t)}break;case"max":if(t.target==="jsonSchema7")if(n.inclusive)at(r,"maximum",n.value,n.message,t);else at(r,"exclusiveMaximum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMaximum=!0;at(r,"maximum",n.value,n.message,t)}break;case"multipleOf":at(r,"multipleOf",n.value,n.message,t);break}return r}function CO(e,t){let r=t.target==="openAi",n={type:"object",properties:{}},o=[],i=e.shape();for(let a in i){let c=i[a];if(c===void 0||c._def===void 0)continue;let d=ZY(c);if(d&&r){if(c._def.typeName==="ZodOptional")c=c._def.innerType;if(!c.isNullable())c=c.nullable();d=!1}let l=De(c._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});if(l===void 0)continue;if(n.properties[a]=l,!d)o.push(a)}if(o.length)n.required=o;let s=VY(e,t);if(s!==void 0)n.additionalProperties=s;return n}function VY(e,t){if(e.catchall._def.typeName!=="ZodNever")return De(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 ZY(e){try{return e.isOptional()}catch{return!0}}var MO=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return De(e.innerType._def,t);let r=De(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ht(t)},r]}:Ht(t)};var $O=(e,t)=>{if(t.pipeStrategy==="input")return De(e.in._def,t);else if(t.pipeStrategy==="output")return De(e.out._def,t);let r=De(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=De(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter((o)=>o!==void 0)}};function NO(e,t){return De(e.type._def,t)}function zO(e,t){let n={type:"array",uniqueItems:!0,items:De(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};if(e.minSize)at(n,"minItems",e.minSize.value,e.minSize.message,t);if(e.maxSize)at(n,"maxItems",e.maxSize.value,e.maxSize.message,t);return n}function BO(e,t){if(e.rest)return{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>De(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:De(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})};else return{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>De(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function LO(e){return{not:Ht(e)}}function DO(e){return Ht(e)}var UO=(e,t)=>De(e.innerType._def,t);var FO=(e,t,r)=>{switch(t){case se.ZodString:return Lg(e,r);case se.ZodNumber:return OO(e,r);case se.ZodObject:return CO(e,r);case se.ZodBigInt:return hO(e,r);case se.ZodBoolean:return gO();case se.ZodDate:return cS(e,r);case se.ZodUndefined:return LO(r);case se.ZodNull:return AO(r);case se.ZodArray:return mO(e,r);case se.ZodUnion:case se.ZodDiscriminatedUnion:return kO(e,r);case se.ZodIntersection:return wO(e,r);case se.ZodTuple:return BO(e,r);case se.ZodRecord:return Dg(e,r);case se.ZodLiteral:return SO(e,r);case se.ZodEnum:return _O(e);case se.ZodNativeEnum:return EO(e);case se.ZodNullable:return RO(e,r);case se.ZodOptional:return MO(e,r);case se.ZodMap:return TO(e,r);case se.ZodSet:return zO(e,r);case se.ZodLazy:return()=>e.getter()._def;case se.ZodPromise:return NO(e,r);case se.ZodNaN:case se.ZodNever:return PO(r);case se.ZodEffects:return xO(e,r);case se.ZodAny:return Ht(r);case se.ZodUnknown:return DO(r);case se.ZodDefault:return bO(e,r);case se.ZodBranded:return Bg(e,r);case se.ZodReadonly:return UO(e,r);case se.ZodCatch:return yO(e,r);case se.ZodPipeline:return $O(e,r);case se.ZodFunction:case se.ZodVoid:case se.ZodSymbol:return;default:return((n)=>{return})(t)}};function De(e,t,r=!1){let n=t.seen.get(e);if(t.override){let a=t.override?.(e,t,n,r);if(a!==lO)return a}if(n&&!r){let a=WY(n,t);if(a!==void 0)return a}let o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);let i=FO(e,e.typeName,t),s=typeof i==="function"?De(i(),t):i;if(s)KY(e,t,s);if(t.postProcess){let a=t.postProcess(s,e,t);return o.jsonSchema=s,a}return o.jsonSchema=s,s}var WY=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:zg(t.currentPath,e.path)};case"none":case"seen":{if(e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Ht(t);return t.$refStrategy==="seen"?Ht(t):void 0}}},KY=(e,t,r)=>{if(e.description){if(r.description=e.description,t.markdownDescription)r.markdownDescription=e.description}return r};var lS=(e,t)=>{let r=fO(t),n=typeof t==="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[d,l])=>({...c,[d]:De(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,d]},!0)??Ht(r)}),{}):void 0,o=typeof t==="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=De(e._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Ht(r),s=typeof t==="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;if(s!==void 0)i.title=s;if(r.flags.hasReferencedOpenAiAnyType){if(!n)n={};if(!n[r.openAiAnyTypeName])n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}}let a=o===void 0?n?{...i,[r.definitionPath]:n}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:i}};if(r.target==="jsonSchema7")a.$schema="http://json-schema.org/draft-07/schema#";else if(r.target==="jsonSchema2019-09"||r.target==="openAi")a.$schema="https://json-schema.org/draft/2019-09/schema#";if(r.target==="openAi"&&(("anyOf"in a)||("oneOf"in a)||("allOf"in a)||("type"in a)&&Array.isArray(a.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return a};function YY(e){if(!e)return"draft-7";if(e==="jsonSchema7"||e==="draft-7")return"draft-7";if(e==="jsonSchema2019-09"||e==="draft-2020-12")return"draft-2020-12";return"draft-7"}function pS(e,t){if(qn(e))return Lw(e,{target:YY(t?.target),io:t?.pipeStrategy??"input"});return lS(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function fS(e){let r=js(e)?.method;if(!r)throw Error("Schema is missing a method literal");let n=lg(r);if(typeof n!=="string")throw Error("Schema method literal must be a string");return n}function mS(e,t){let r=Fs(e,t);if(!r.success)throw r.error;return r.data}var JY=60000;class hS{constructor(e){if(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(xg,(t)=>{this._oncancel(t)}),this.setNotificationHandler(wg,(t)=>{this._onprogress(t)}),this.setRequestHandler(_g,(t)=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore)this.setRequestHandler(Sg,async(t,r)=>{let n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new Te(Me.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Tg,async(t,r)=>{let n=async()=>{let o=t.params.taskId;if(this._taskMessageQueue){let s;while(s=await this._taskMessageQueue.dequeue(o,r.sessionId)){if(s.type==="response"||s.type==="error"){let a=s.message,c=a.id,d=this._requestResolvers.get(c);if(d)if(this._requestResolvers.delete(c),s.type==="response")d(a);else{let l=a,p=new Te(l.error.code,l.error.message,l.error.data);d(p)}else{let l=s.type==="response"?"Response":"Error";this._onerror(Error(`${l} handler missing for request ${c}`))}continue}await this._transport?.send(s.message,{relatedRequestId:r.requestId})}}let i=await this._taskStore.getTask(o,r.sessionId);if(!i)throw new Te(Me.InvalidParams,`Task not found: ${o}`);if(!Hs(i.status))return await this._waitForTaskUpdate(o,r.signal),await n();if(Hs(i.status)){let s=await this._taskStore.getTaskResult(o,r.sessionId);return this._clearTaskQueue(o),{...s,_meta:{...s._meta,[qs]:{taskId:o}}}}return await n()};return await n()}),this.setRequestHandler(Eg,async(t,r)=>{try{let{tasks:n,nextCursor:o}=await this._taskStore.listTasks(t.params?.cursor,r.sessionId);return{tasks:n,nextCursor:o,_meta:{}}}catch(n){throw new Te(Me.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(Ag,async(t,r)=>{try{let n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new Te(Me.InvalidParams,`Task not found: ${t.params.taskId}`);if(Hs(n.status))throw new Te(Me.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(t.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(t.params.taskId);let o=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!o)throw new Te(Me.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...o}}catch(n){if(n instanceof Te)throw n;throw new Te(Me.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}})}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,n,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Te.fromError(Me.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);if(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 r=this.transport?.onerror;this._transport.onerror=(o)=>{r?.(o),this._onerror(o)};let n=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{if(n?.(o,i),Up(o)||Q5(o))this._onresponse(o);else if(Zw(o))this._onrequest(o,i);else if(J5(o))this._onnotification(o);else this._onerror(Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(let r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();let t=Te.fromError(Me.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let r of e.values())r(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;if(t===void 0)return;Promise.resolve().then(()=>t(e)).catch((r)=>this._onerror(Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,t){let r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,o=e.params?._meta?.[qs]?.taskId;if(r===void 0){let d={jsonrpc:"2.0",id:e.id,error:{code:Me.MethodNotFound,message:"Method not found"}};if(o&&this._taskMessageQueue)this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},n?.sessionId).catch((l)=>this._onerror(Error(`Failed to enqueue error response: ${l}`)));else n?.send(d).catch((l)=>this._onerror(Error(`Failed to send an error response: ${l}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let s=W5(e.params)?e.params.task:void 0,a=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,c={signal:i.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async(d)=>{if(i.signal.aborted)return;let l={relatedRequestId:e.id};if(o)l.relatedTask={taskId:o};await this.notification(d,l)},sendRequest:async(d,l,p)=>{if(i.signal.aborted)throw new Te(Me.ConnectionClosed,"Request was cancelled");let m={...p,relatedRequestId:e.id};if(o&&!m.relatedTask)m.relatedTask={taskId:o};let h=m.relatedTask?.taskId??o;if(h&&a)await a.updateTaskStatus(h,"input_required");return await this.request(d,l,m)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:o,taskStore:a,taskRequestedTtl:s?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(s)this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,c)).then(async(d)=>{if(i.signal.aborted)return;let l={result:d,jsonrpc:"2.0",id:e.id};if(o&&this._taskMessageQueue)await this._enqueueTaskMessage(o,{type:"response",message:l,timestamp:Date.now()},n?.sessionId);else await n?.send(l)},async(d)=>{if(i.signal.aborted)return;let l={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:Me.InternalError,message:d.message??"Internal error",...d.data!==void 0&&{data:d.data}}};if(o&&this._taskMessageQueue)await this._enqueueTaskMessage(o,{type:"error",message:l,timestamp:Date.now()},n?.sessionId);else await n?.send(l)}).catch((d)=>this._onerror(Error(`Failed to send response: ${d}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(e.id)===i)this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,n=Number(t),o=this._progressHandlers.get(n);if(!o){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&i&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(a){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),i(a);return}o(r)}_onresponse(e){let t=Number(e.id),r=this._requestResolvers.get(t);if(r){if(this._requestResolvers.delete(t),Up(e))r(e);else{let i=new Te(e.error.code,e.error.message,e.error.data);r(i)}return}let n=this._responseHandlers.get(t);if(n===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 o=!1;if(Up(e)&&e.result&&typeof e.result==="object"){let i=e.result;if(i.task&&typeof i.task==="object"){let s=i.task;if(typeof s.taskId==="string")o=!0,this._taskProgressTokens.set(s.taskId,t)}}if(!o)this._progressHandlers.delete(t);if(Up(e))n(e);else{let i=Te.fromError(e.error.code,e.error.message,e.error.data);n(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,r){let{task:n}=r??{};if(!n){try{yield{type:"result",result:await this.request(e,t,r)}}catch(i){yield{type:"error",error:i instanceof Te?i:new Te(Me.InternalError,String(i))}}return}let o;try{let i=await this.request(e,Mu,r);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new Te(Me.InternalError,"Task creation did not return a task");while(!0){let s=await this.getTask({taskId:o},r);if(yield{type:"taskStatus",task:s},Hs(s.status)){if(s.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)};else if(s.status==="failed")yield{type:"error",error:new Te(Me.InternalError,`Task ${o} failed`)};else if(s.status==="cancelled")yield{type:"error",error:new Te(Me.InternalError,`Task ${o} was cancelled`)};return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)};return}let a=s.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((c)=>setTimeout(c,a)),r?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof Te?i:new Te(Me.InternalError,String(i))}}}request(e,t,r){let{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i,task:s,relatedTask:a}=r??{};return new Promise((c,d)=>{let l=(w)=>{d(w)};if(!this._transport){l(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(e.method),s)this.assertTaskCapability(e.method)}catch(w){l(w);return}r?.signal?.throwIfAborted();let p=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:p};if(r?.onprogress)this._progressHandlers.set(p,r.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}};if(s)m.params={...m.params,task:s};if(a)m.params={...m.params,_meta:{...m.params?._meta||{},[qs]:a}};let h=(w)=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(w)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i}).catch((v)=>this._onerror(Error(`Failed to send cancellation: ${v}`)));let A=w instanceof Te?w:new Te(Me.RequestTimeout,String(w));d(A)};this._responseHandlers.set(p,(w)=>{if(r?.signal?.aborted)return;if(w instanceof Error)return d(w);try{let A=Fs(t,w.result);if(!A.success)d(A.error);else c(A.data)}catch(A){d(A)}}),r?.signal?.addEventListener("abort",()=>{h(r?.signal?.reason)});let b=r?.timeout??JY,x=()=>h(Te.fromError(Me.RequestTimeout,"Request timed out",{timeout:b}));this._setupTimeout(p,b,r?.maxTotalTimeout,x,r?.resetTimeoutOnProgress??!1);let _=a?.taskId;if(_){let w=(A)=>{let v=this._responseHandlers.get(p);if(v)v(A);else this._onerror(Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,w),this._enqueueTaskMessage(_,{type:"request",message:m,timestamp:Date.now()}).catch((A)=>{this._cleanupTimeout(p),d(A)})}else this._transport.send(m,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i}).catch((w)=>{this._cleanupTimeout(p),d(w)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},vg,t)}async getTaskResult(e,t,r){return this.request({method:"tasks/result",params:e},t,r)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},Pg,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},tO,t)}async notification(e,t){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(e.method);let r=t?.relatedTask?.taskId;if(r){let s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[qs]:t.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:s,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"};if(t?.relatedTask)s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[qs]:t.relatedTask}}};this._transport?.send(s,t).catch((a)=>this._onerror(a))});return}let i={...e,jsonrpc:"2.0"};if(t?.relatedTask)i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[qs]:t.relatedTask}}};await this._transport.send(i,t)}setRequestHandler(e,t){let r=fS(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(n,o)=>{let i=mS(e,n);return Promise.resolve(t(i,o))})}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 r=fS(e);this._notificationHandlers.set(r,(n)=>{let o=mS(e,n);return Promise.resolve(t(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);if(t!==void 0)this._progressHandlers.delete(t),this._taskProgressTokens.delete(e)}async _enqueueTaskMessage(e,t,r){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,r,n)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,t);for(let n of r)if(n.type==="request"&&Zw(n.message)){let o=n.message.id,i=this._requestResolvers.get(o);if(i)i(new Te(Me.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o);else this._onerror(Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let r=this._options?.defaultTaskPollInterval??1000;try{let n=await this._taskStore?.getTask(e);if(n?.pollInterval)r=n.pollInterval}catch{}return new Promise((n,o)=>{if(t.aborted){o(new Te(Me.InvalidRequest,"Request cancelled"));return}let i=setTimeout(n,r);t.addEventListener("abort",()=>{clearTimeout(i),o(new Te(Me.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){let r=this._taskStore;if(!r)throw Error("No task store configured");return{createTask:async(n)=>{if(!e)throw Error("No request provided");return await r.createTask(n,e.id,{method:e.method,params:e.params},t)},getTask:async(n)=>{let o=await r.getTask(n,t);if(!o)throw new Te(Me.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(n,o,i)=>{await r.storeTaskResult(n,o,i,t);let s=await r.getTask(n,t);if(s){let a=Gp.parse({method:"notifications/tasks/status",params:s});if(await this.notification(a),Hs(s.status))this._cleanupTaskProgressHandler(n)}},getTaskResult:(n)=>r.getTaskResult(n,t),updateTaskStatus:async(n,o,i)=>{let s=await r.getTask(n,t);if(!s)throw new Te(Me.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Hs(s.status))throw new Te(Me.InvalidParams,`Cannot update task "${n}" from terminal status "${s.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(n,o,i,t);let a=await r.getTask(n,t);if(a){let c=Gp.parse({method:"notifications/tasks/status",params:a});if(await this.notification(c),Hs(a.status))this._cleanupTaskProgressHandler(n)}},listTasks:(n)=>r.listTasks(n,t)}}}function jO(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function qO(e,t){let r={...e};for(let n in t){let o=n,i=t[o];if(i===void 0)continue;let s=r[o];if(jO(s)&&jO(i))r[o]={...s,...i};else r[o]=i}return r}var E4=Vr(dv(),1),P4=Vr(T4(),1);function xie(){let e=new E4.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return P4.default(e),e}class _v{constructor(e){this._ajv=e??xie()}getValidator(e){let t="$id"in e&&typeof e.$id==="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return(r)=>{if(t(r))return{valid:!0,data:r,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}}class wv{constructor(e){this._server=e}requestStream(e,t,r){return this._server.requestStream(e,t,r)}createMessageStream(e,t){let r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],i=o.some((d)=>d.type==="tool_result"),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],c=a.some((d)=>d.type==="tool_use");if(i){if(o.some((d)=>d.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!c)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let d=new Set(a.filter((p)=>p.type==="tool_use").map((p)=>p.id)),l=new Set(o.filter((p)=>p.type==="tool_result").map((p)=>p.toolUseId));if(d.size!==l.size||![...d].every((p)=>l.has(p)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Wp,t)}elicitInputStream(e,t){let r=this._server.getClientCapabilities(),n=e.mode??"form";switch(n){case"url":{if(!r?.elicitation?.url)throw Error("Client does not support url elicitation.");break}case"form":{if(!r?.elicitation?.form)throw Error("Client does not support form elicitation.");break}}let o=n==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},zu,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._server.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}}function A4(e,t,r){if(!e)throw Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function I4(e,t,r){if(!e)throw Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}class Sv extends hS{constructor(e,t){super(t);if(this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Zp.options.map((r,n)=>[r,n])),this.isMessageIgnored=(r,n)=>{let o=this._loggingLevels.get(n);return o?this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new _v,this.setRequestHandler(Yw,(r)=>this._oninitialize(r)),this.setNotificationHandler(Jw,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(oS,async(r,n)=>{let o=n.sessionId||n.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,s=Zp.safeParse(i);if(s.success)this._loggingLevels.set(o,s.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new wv(this)};return this._experimental}registerCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=qO(this._capabilities,e)}setRequestHandler(e,t){let n=js(e)?.method;if(!n)throw Error("Schema is missing a method literal");let o;if(qn(n)){let s=n;o=s._zod?.def?.value??s.value}else{let s=n;o=s._def?.value??s.value}if(typeof o!=="string")throw Error("Schema method literal must be a string");if(o==="tools/call"){let s=async(a,c)=>{let d=Fs(Nu,a);if(!d.success){let h=d.error instanceof Error?d.error.message:String(d.error);throw new Te(Me.InvalidParams,`Invalid tools/call request: ${h}`)}let{params:l}=d.data,p=await Promise.resolve(t(a,c));if(l.task){let h=Fs(Mu,p);if(!h.success){let b=h.error instanceof Error?h.error.message:String(h.error);throw new Te(Me.InvalidParams,`Invalid task creation result: ${b}`)}return h.data}let m=Fs($g,p);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new Te(Me.InvalidParams,`Invalid tools/call result: ${h}`)}return m.data};return super.setRequestHandler(e,s)}return super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(!this._capabilities)return;switch(e){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){I4(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){if(!this._capabilities)return;A4(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:G5.includes(t)?t:Gw,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},bg)}async createMessage(e,t){if(e.tools||e.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(e.messages.length>0){let r=e.messages[e.messages.length-1],n=Array.isArray(r.content)?r.content:[r.content],o=n.some((c)=>c.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,s=i?Array.isArray(i.content)?i.content:[i.content]:[],a=s.some((c)=>c.type==="tool_use");if(o){if(n.some((c)=>c.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!a)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(a){let c=new Set(s.filter((l)=>l.type==="tool_use").map((l)=>l.id)),d=new Set(n.filter((l)=>l.type==="tool_result").map((l)=>l.toolUseId));if(c.size!==d.size||![...c].every((l)=>d.has(l)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(e.tools)return this.request({method:"sampling/createMessage",params:e},iS,t);return this.request({method:"sampling/createMessage",params:e},Wp,t)}async elicitInput(e,t){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let n=e;return this.request({method:"elicitation/create",params:n},zu,t)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let n=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:n},zu,t);if(o.action==="accept"&&o.content&&n.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(n.requestedSchema)(o.content);if(!s.valid)throw new Te(Me.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(i){if(i instanceof Te)throw i;throw new Te(Me.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return o}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},sS,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging){if(!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var R4=Symbol.for("mcp.completable");function vv(e){return!!e&&typeof e==="object"&&R4 in e}function O4(e){return e[R4]?.complete}var k4;(function(e){e.Completable="McpCompletable"})(k4||(k4={}));var _ie=/^[A-Za-z0-9._-]{1,128}$/;function wie(e){let t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" "))t.push("Tool name contains spaces, which may cause parsing issues");if(e.includes(","))t.push("Tool name contains commas, which may cause parsing issues");if(e.startsWith("-")||e.endsWith("-"))t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if(e.startsWith(".")||e.endsWith("."))t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!_ie.test(e)){let r=e.split("").filter((n)=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,i)=>i.indexOf(n)===o);return t.push(`Tool name contains invalid characters: ${r.map((n)=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function Sie(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let r of t)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function Tv(e){let t=wie(e);return Sie(e,t.warnings),t.isValid}class Ev{constructor(e){this._mcpServer=e}registerToolTask(e,t,r){let n={taskSupport:"required",...t.execution};if(n.taskSupport==="forbidden")throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,n,t._meta,r)}}class Av{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Sv(e,t)}get experimental(){if(!this._experimental)this._experimental={tasks:new Ev(this)};return this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){if(this._toolHandlersInitialized)return;this.server.assertCanSetRequestHandler(Qs(Mg)),this.server.assertCanSetRequestHandler(Qs(Nu)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Mg,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let r={name:e,title:t.title,description:t.description,inputSchema:(()=>{let n=Ru(t.inputSchema);return n?pS(n,{strictUnions:!0,pipeStrategy:"input"}):vie})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let n=Ru(t.outputSchema);if(n)r.outputSchema=pS(n,{strictUnions:!0,pipeStrategy:"output"})}return r})})),this.server.setRequestHandler(Nu,async(e,t)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new Te(Me.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new Te(Me.InvalidParams,`Tool ${e.params.name} disabled`);let n=!!e.params.task,o=r.execution?.taskSupport,i="createTask"in r.handler;if((o==="required"||o==="optional")&&!i)throw new Te(Me.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!n)throw new Te(Me.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!n&&i)return await this.handleAutomaticTaskPolling(r,e,t);let s=await this.validateToolInput(r,e.params.arguments,e.params.name),a=await this.executeToolHandler(r,s,t);if(n)return a;return await this.validateToolOutput(r,a,e.params.name),a}catch(r){if(r instanceof Te){if(r.code===Me.UrlElicitationRequired)throw r}return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,r){if(!e.inputSchema)return;let o=Ru(e.inputSchema)??e.inputSchema,i=await ug(o,t);if(!i.success){let s="error"in i?i.error:"Unknown error",a=dg(s);throw new Te(Me.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${a}`)}return i.data}async validateToolOutput(e,t,r){if(!e.outputSchema)return;if(!("content"in t))return;if(t.isError)return;if(!t.structuredContent)throw new Te(Me.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let n=Ru(e.outputSchema),o=await ug(n,t.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",s=dg(i);throw new Te(Me.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${s}`)}}async executeToolHandler(e,t,r){let n=e.handler;if("createTask"in n){if(!r.taskStore)throw Error("No task store provided.");let i={...r,taskStore:r.taskStore};if(e.inputSchema)return await Promise.resolve(n.createTask(t,i));else return await Promise.resolve(n.createTask(i))}if(e.inputSchema)return await Promise.resolve(n(t,r));else return await Promise.resolve(n(r))}async handleAutomaticTaskPolling(e,t,r){if(!r.taskStore)throw Error("No task store provided for task-capable tool.");let n=await this.validateToolInput(e,t.params.arguments,t.params.name),o=e.handler,i={...r,taskStore:r.taskStore},s=n?await Promise.resolve(o.createTask(n,i)):await Promise.resolve(o.createTask(i)),a=s.task.taskId,c=s.task,d=c.pollInterval??5000;while(c.status!=="completed"&&c.status!=="failed"&&c.status!=="cancelled"){await new Promise((p)=>setTimeout(p,d));let l=await r.taskStore.getTask(a);if(!l)throw new Te(Me.InternalError,`Task ${a} not found during polling`);c=l}return await r.taskStore.getTaskResult(a)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(Qs(Ng)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ng,async(e)=>{switch(e.params.ref.type){case"ref/prompt":return aO(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return cO(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Te(Me.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new Te(Me.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new Te(Me.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return _f;let o=js(r.argsSchema)?.[e.params.argument.name];if(!vv(o))return _f;let i=O4(o);if(!i)return _f;let s=await i(e.params.argument.value,e.params.context);return M4(s)}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find((i)=>i.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return _f;throw new Te(Me.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let n=r.resourceTemplate.completeCallback(e.params.argument.name);if(!n)return _f;let o=await n(e.params.argument.value,e.params.context);return M4(o)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(Qs(Ig)),this.server.assertCanSetRequestHandler(Qs(kg)),this.server.assertCanSetRequestHandler(Qs(Rg)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ig,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([o,i])=>i.enabled).map(([o,i])=>({uri:o,name:i.name,...i.metadata})),n=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let i=await o.resourceTemplate.listCallback(t);for(let s of i.resources)n.push({...o.metadata,...s})}return{resources:[...r,...n]}}),this.server.setRequestHandler(kg,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(Rg,async(e,t)=>{let r=new URL(e.params.uri),n=this._registeredResources[r.toString()];if(n){if(!n.enabled)throw new Te(Me.InvalidParams,`Resource ${r} disabled`);return n.readCallback(r,t)}for(let o of Object.values(this._registeredResourceTemplates)){let i=o.resourceTemplate.uriTemplate.match(r.toString());if(i)return o.readCallback(r,i,t)}throw new Te(Me.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(Qs(Og)),this.server.assertCanSetRequestHandler(Qs(Cg)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Og,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Tie(t.argsSchema):void 0}))})),this.server.setRequestHandler(Cg,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new Te(Me.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new Te(Me.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let n=Ru(r.argsSchema),o=await ug(n,e.params.arguments);if(!o.success){let a="error"in o?o.error:"Unknown error",c=dg(a);throw new Te(Me.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${c}`)}let i=o.data,s=r.callback;return await Promise.resolve(s(i,t))}else{let n=r.callback;return await Promise.resolve(n(t))}}),this._promptHandlersInitialized=!0}resource(e,t,...r){let n;if(typeof r[0]==="object")n=r.shift();let o=r[0];if(typeof t==="string"){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,void 0,t,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,t,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,t,r,n){if(typeof t==="string"){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let o=this._createRegisteredResource(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,t,r,n,o){let i={name:e,title:t,metadata:n,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:(s)=>{if(typeof s.uri<"u"&&s.uri!==r){if(delete this._registeredResources[r],s.uri)this._registeredResources[s.uri]=i}if(typeof s.name<"u")i.name=s.name;if(typeof s.title<"u")i.title=s.title;if(typeof s.metadata<"u")i.metadata=s.metadata;if(typeof s.callback<"u")i.readCallback=s.callback;if(typeof s.enabled<"u")i.enabled=s.enabled;this.sendResourceListChanged()}};return this._registeredResources[r]=i,i}_createRegisteredResourceTemplate(e,t,r,n,o){let i={resourceTemplate:r,title:t,metadata:n,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:(c)=>{if(typeof c.name<"u"&&c.name!==e){if(delete this._registeredResourceTemplates[e],c.name)this._registeredResourceTemplates[c.name]=i}if(typeof c.title<"u")i.title=c.title;if(typeof c.template<"u")i.resourceTemplate=c.template;if(typeof c.metadata<"u")i.metadata=c.metadata;if(typeof c.callback<"u")i.readCallback=c.callback;if(typeof c.enabled<"u")i.enabled=c.enabled;this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let s=r.uriTemplate.variableNames;if(Array.isArray(s)&&s.some((c)=>!!r.completeCallback(c)))this.setCompletionRequestHandler();return i}_createRegisteredPrompt(e,t,r,n,o){let i={title:t,description:r,argsSchema:n===void 0?void 0:nc(n),callback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:(s)=>{if(typeof s.name<"u"&&s.name!==e){if(delete this._registeredPrompts[e],s.name)this._registeredPrompts[s.name]=i}if(typeof s.title<"u")i.title=s.title;if(typeof s.description<"u")i.description=s.description;if(typeof s.argsSchema<"u")i.argsSchema=nc(s.argsSchema);if(typeof s.callback<"u")i.callback=s.callback;if(typeof s.enabled<"u")i.enabled=s.enabled;this.sendPromptListChanged()}};if(this._registeredPrompts[e]=i,n){if(Object.values(n).some((a)=>{let c=a instanceof mg?a._def?.innerType:a;return vv(c)}))this.setCompletionRequestHandler()}return i}_createRegisteredTool(e,t,r,n,o,i,s,a,c){Tv(e);let d={title:t,description:r,inputSchema:C4(n),outputSchema:C4(o),annotations:i,execution:s,_meta:a,handler:c,enabled:!0,disable:()=>d.update({enabled:!1}),enable:()=>d.update({enabled:!0}),remove:()=>d.update({name:null}),update:(l)=>{if(typeof l.name<"u"&&l.name!==e){if(typeof l.name==="string")Tv(l.name);if(delete this._registeredTools[e],l.name)this._registeredTools[l.name]=d}if(typeof l.title<"u")d.title=l.title;if(typeof l.description<"u")d.description=l.description;if(typeof l.paramsSchema<"u")d.inputSchema=nc(l.paramsSchema);if(typeof l.outputSchema<"u")d.outputSchema=nc(l.outputSchema);if(typeof l.callback<"u")d.handler=l.callback;if(typeof l.annotations<"u")d.annotations=l.annotations;if(typeof l._meta<"u")d._meta=l._meta;if(typeof l.enabled<"u")d.enabled=l.enabled;this.sendToolListChanged()}};return this._registeredTools[e]=d,this.setToolRequestHandlers(),this.sendToolListChanged(),d}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r,n,o,i;if(typeof t[0]==="string")r=t.shift();if(t.length>1){let a=t[0];if(Pv(a)){if(n=t.shift(),t.length>1&&typeof t[0]==="object"&&t[0]!==null&&!Pv(t[0]))i=t.shift()}else if(typeof a==="object"&&a!==null){if(Object.values(a).some((c)=>typeof c==="object"&&c!==null))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=t.shift()}}let s=t[0];return this._createRegisteredTool(e,void 0,r,n,o,i,{taskSupport:"forbidden"},void 0,s)}registerTool(e,t,r){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:n,description:o,inputSchema:i,outputSchema:s,annotations:a,_meta:c}=t;return this._createRegisteredTool(e,n,o,i,s,a,{taskSupport:"forbidden"},c,r)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let r;if(typeof t[0]==="string")r=t.shift();let n;if(t.length>1)n=t.shift();let o=t[0],i=this._createRegisteredPrompt(e,void 0,r,n,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,t,r){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:n,description:o,argsSchema:i}=t,s=this._createRegisteredPrompt(e,n,o,i,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){if(this.isConnected())this.server.sendResourceListChanged()}sendToolListChanged(){if(this.isConnected())this.server.sendToolListChanged()}sendPromptListChanged(){if(this.isConnected())this.server.sendPromptListChanged()}}var vie={type:"object",properties:{}};function $4(e){return e!==null&&typeof e==="object"&&"parse"in e&&typeof e.parse==="function"&&"safeParse"in e&&typeof e.safeParse==="function"}function N4(e){return"_def"in e||"_zod"in e||$4(e)}function Pv(e){if(typeof e!=="object"||e===null)return!1;if(N4(e))return!1;if(Object.keys(e).length===0)return!0;return Object.values(e).some($4)}function C4(e){if(!e)return;if(Pv(e))return nc(e);if(!N4(e))throw Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}function Tie(e){let t=js(e);if(!t)return[];return Object.entries(t).map(([r,n])=>{let o=c5(n),i=u5(n);return{name:r,description:o,required:!i}})}function Qs(e){let r=js(e)?.method;if(!r)throw Error("Schema is missing a method literal");let n=lg(r);if(typeof n==="string")return n;throw Error("Schema method literal must be a string")}function M4(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var _f={completion:{values:[],hasMore:!1}};import B4 from"node:process";class Iv{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
135
135
  `);if(e===-1)return null;let t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Eie(t)}clear(){this._buffer=void 0}}function Eie(e){return X5.parse(JSON.parse(e))}function z4(e){return JSON.stringify(e)+`
136
- `}class kv{constructor(e=B4.stdin,t=B4.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new Iv,this._started=!1,this._ondata=(r)=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=(r)=>{this.onerror?.(r)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise((t)=>{let r=z4(e);if(this._stdout.write(r))t();else this._stdout.once("drain",t)})}}var S0={name:"@0xmonaco/mcp-server",version:"1.0.62",type:"module",homepage:"https://docs.0xmonaco.com/sdk/typescript",description:"MCP server for the Monaco SDK",engines:{node:">=18"},bin:"./dist/bin.js",files:["dist"],scripts:{build:"bun build src/bin.ts --outdir dist --target node --format esm --minify",dev:"bun --watch src/bin.ts",start:"bun dist/bin.js",clean:"rm -rf dist",lint:"biome lint .",test:"bun test"},author:"@codebycarson",dependencies:{"@0xmonaco/core":"1.0.62","@0xmonaco/types":"1.0.62","@modelcontextprotocol/sdk":"^1.29.0","node-fetch":"^3.3.2",viem:"^2.56.3",ws:"^8.21.0",zod:"^4.4.3"},devDependencies:{"@types/bun":"latest","@types/ws":"^8.18.1"}};var v0=["read","market-maker","full"],Wo=[{name:"search_docs",description:"Search the Monaco documentation for protocol, SDK, trading, and development guides.",category:"search",authMode:"public",sideEffect:"read-only"},{name:"get_trading_pairs",description:"List trading pairs with optional filters (market type, base/quote token, active status).",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_trading_pair_by_symbol",description:"Look up a trading pair by symbol (e.g. `BTC/USDC`).",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_candlesticks",description:"Fetch OHLCV candlestick data for a trading pair.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_market_metadata",description:"Get tick size, minimum order size, and trading rules for a pair.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_screener",description:"Screen trading pairs with market stats (price, volume, change), filtered by market type, category, and active status.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_market_stats",description:"Get exchange-wide life-to-date cumulative volume and trade count across all markets.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_perp_market_config",description:"Get a perpetual market's configuration (leverage limits, margin requirements, funding parameters).",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_perp_market_summary",description:"Get a perpetual market's live summary (mark/index price, funding rate, open interest, 24h stats).",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_mark_price",description:"Get the current mark price for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_index_price",description:"Get the current index (oracle) price for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_funding_state",description:"Get the current funding rate and next funding time for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_open_interest",description:"Get the current open interest for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_funding_history",description:"List historical funding-rate records for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_all_funding_history",description:"List historical funding-rate records across all perpetual markets.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_orderbook",description:"Fetch a current orderbook snapshot with bids and asks.",category:"orderbook",authMode:"public",sideEffect:"read-only"},{name:"get_trades",description:"Fetch historical trades for a trading pair.",category:"trades",authMode:"public",sideEffect:"read-only"},{name:"place_limit_order",description:"Place a limit order with price, quantity, and time-in-force. The SDK supplies an idempotency key if omitted. Retain an explicit key to retry the same submission within 24 hours of acceptance. Calling again without the original key is not idempotent; never retry an ambiguous failure with a new key. If the original key is unavailable, report the ambiguity.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"place_market_order",description:"Place a market order — executes immediately inside a mandatory 1,000 bps protective price band, so it may partially fill or be rejected. The SDK supplies an idempotency key if omitted. Retain an explicit key to retry the same submission within 24 hours of acceptance. Calling again without the original key is not idempotent; never retry an ambiguous failure with a new key. If the original key is unavailable, report the ambiguity.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"replace_order",description:"Modify an existing order's price and/or quantity. Not idempotent — an ambiguous failure (timeout/network error/5xx with no order) cannot be resolved from inside MCP, which has no order-stream tool; never retry, and report the ambiguity instead.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"cancel_order",description:"Cancel a single order by ID.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_cancel_orders",description:"Cancel multiple orders by ID (non-atomic — a failed leg does not stop the others).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_cancel_all_orders",description:"Cancel all open orders, optionally filtered to a trading pair (unfiltered, it cancels your entire open-order book).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_close_all_positions",description:"Close all open perpetual positions with market reduce-only orders (best-effort, optional pair filter).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_orders",description:"List your orders with optional filters.",category:"trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_order",description:"Get details for a specific order by ID.",category:"trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_positions",description:"List your perpetual positions with optional filters (margin account, trading pair, status).",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position",description:"Get details for a specific perpetual position by ID.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_risk",description:"Get liquidation price, margin ratio, and risk metrics for a perpetual position.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_history",description:"List historical (closed/reduced) perpetual position records with optional filters.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_pnl_history",description:"Get the PnL history time series for a perpetual position over an interval.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"close_position",description:"Close a perpetual position with a market, limit, or IOC reduce order.",category:"positions",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_profile",description:"Fetch your core profile (address, username, account type, withdrawal status).",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_balances",description:"List token balances with pagination.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_balance_by_asset",description:"Get balance for a specific asset.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_movements",description:"Fetch transaction and movement history with optional filters.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_user_trades",description:"List your own trade fills with optional filters and cursor pagination.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_funding_payments",description:"List your perpetual funding payments with optional filters (trading pair, position, margin account).",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_summary",description:"Get your authoritative portfolio summary (equity, PnL, exposure) over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_performance",description:"Get your portfolio performance time series over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_realized_pnl",description:"Get your realized PnL breakdown over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_assets",description:"Get your per-asset portfolio allocation and balances over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_margin",description:"Get your portfolio margin overview (collateral, maintenance margin, health).",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_margin_accounts",description:"List your margin accounts with optional filters (state, trading pair).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_parent_margin_account_summary",description:"Get your parent (cross) margin account summary.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_available_collateral",description:"Get available (unlocked) collateral for allocating to margin accounts or risk buckets.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_parent_margin_account_movements",description:"List collateral movements for your parent (cross) margin account.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"simulate_parent_margin_order_risk",description:"Preview the risk impact of a prospective order against your parent (cross) margin account (read-only simulation).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"simulate_risk_bucket_order_risk",description:"Preview the risk impact of a prospective order for a new or existing risk bucket (read-only simulation).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_collateral_to_parent_margin_account",description:"Move collateral from spot into your parent (cross) margin account.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_from_parent_margin_account",description:"Move collateral out of your parent (cross) margin account back to spot.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_to_risk_bucket",description:"Allocate collateral into an isolated or cross risk bucket.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"simulate_fees",description:"Simulate fees for an order before placing it.",category:"fees",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_my_fee_tier",description:"Get your current fee tier, rolling 14-day volumes, and a pair's fee schedule.",category:"fees",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"vault_approve",description:"Approve the vault contract to spend a token.",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_deposit",description:"Deposit tokens into the vault (optional `target`: `spot` default, or `margin` to route into collateral).",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_withdraw",description:"Withdraw tokens from the vault.",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_get_allowance",description:"Check current token allowance for the vault.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"vault_needs_approval",description:"Check whether an approval transaction is needed before depositing.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_pending_withdrawals",description:"List your pending withdrawals still awaiting on-chain root confirmation.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"request_faucet",description:"Request test tokens for all trading pairs.",category:"faucet",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating",excludedOnMainnet:!0},{name:"get_faucet_info",description:"Check remaining faucet quota, next-request time, and recent mint history.",category:"faucet",authMode:"authenticated",capability:"read",sideEffect:"read-only",excludedOnMainnet:!0},{name:"get_trader_code_info",description:"Look up a trader code's details (no credentials required).",category:"pitpass",authMode:"public",sideEffect:"read-only"},{name:"check_trader_code_availability",description:"Public advisory check of whether a custom PitPass TraderCode handle is available (no credentials required).",category:"pitpass",authMode:"public",sideEffect:"read-only"},{name:"get_my_trader_code",description:"Fetch your own trader code.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"set_trader_code",description:"Claim or edit your custom (vanity) PitPass TraderCode handle.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"clear_trader_code",description:"Clear your custom PitPass TraderCode handle, reverting to the wallet-derived default.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_rewards_balance",description:"Fetch your PitPass rewards-bucket balances across reward tokens.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_rewards",description:"Move your earned PitPass rewards from the rewards bucket into your own tradeable balance (ledger-only).",category:"pitpass",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"get_pulse",description:"Get the latest market-pulse news feed: AI-synthesized, per-asset headlines with sentiment tags.",category:"pulse",authMode:"public",sideEffect:"read-only"}],k_e=Wo.map((e)=>e.name),L4=Wo.filter((e)=>e.authMode==="public").map((e)=>e.name),R_e=Wo.filter((e)=>e.authMode==="authenticated"&&e.capability==="read").map((e)=>e.name),O_e=Wo.filter((e)=>e.authMode==="authenticated"&&e.capability==="market-maker").map((e)=>e.name),C_e=Wo.filter((e)=>e.authMode==="authenticated"&&e.capability==="full").map((e)=>e.name),M_e=Wo.filter((e)=>e.excludedOnMainnet).map((e)=>e.name),D4=Wo.filter((e)=>e.sideEffect==="fund-movement").map((e)=>e.name);var Aie=new Map(Wo.map((e)=>[e.name,e.sideEffect]));function U4(e){let t=Aie.get(e);if(!t)return;let r=t==="read-only";return{readOnlyHint:r,destructiveHint:!r}}var F4={read:0,"market-maker":1,full:2},Rv=L4,Ov=Object.fromEntries(Wo.filter((e)=>e.authMode==="authenticated").map((e)=>[e.name,{capability:e.capability??"full",...e.sideEffect==="fund-movement"?{fundMovement:!0}:{},...e.excludedOnMainnet?{excludedOnMainnet:!0}:{}}])),j4=Object.fromEntries(Object.entries(Ov).map(([e,t])=>[e,t.capability])),z_e=new Set(D4);function q4(e){let t=Ov[e];if(!t)return"full";if(t.fundMovement)return"full";return t.capability}function H4(e){return q4(e)==="read"}function G4(e,t){if(t.network==="mainnet"&&Ov[e]?.excludedOnMainnet)return!1;if(t.deny.includes(e))return!1;if(Rv.includes(e))return!0;if(!t.authenticated)return!1;if(t.allow.includes(e))return!0;return F4[t.capability]>=F4[q4(e)]}var Iie=new Set([...Rv,...Object.keys(j4)]),kie={mainnet:"https://evm-rpc.sei-apis.com",development:"https://evm-rpc-testnet.sei-apis.com",staging:"https://evm-rpc-testnet.sei-apis.com",local:"http://localhost:8545"};function V4(e){if(!e)return[];return e.split(",").map((t)=>t.trim()).filter(Boolean)}function lc(e=process.env){let t=e.MONACO_PRIVATE_KEY||null;if(t&&!t.startsWith("0x"))throw Error("MONACO_PRIVATE_KEY must start with '0x'.");let r=e.MONACO_CLIENT_ID||null;if(t&&!r)throw Error("MONACO_CLIENT_ID is required when MONACO_PRIVATE_KEY is set.");let n=["mainnet","development","staging","local"],o=e.MONACO_NETWORK;if(t&&!o)throw Error(`MONACO_NETWORK must be set explicitly (one of: ${n.join(", ")}) when MONACO_PRIVATE_KEY is configured. Refusing to default to mainnet for an authenticated session.`);let i=o||"mainnet";if(!n.includes(i))throw Error(`MONACO_NETWORK must be one of: ${n.join(", ")}.`);let s=i,a=e.MONACO_CAPABILITY;if(a&&!v0.includes(a))throw Error(`MONACO_CAPABILITY must be one of: ${v0.join(", ")}.`);let c=a||"read",d=V4(e.MONACO_TOOL_ALLOWLIST),l=V4(e.MONACO_TOOL_DENYLIST),p=[...d,...l].filter((b)=>!Iie.has(b)).length;if(p>0)throw Error(`${p} unknown tool name(s) in MONACO_TOOL_ALLOWLIST/MONACO_TOOL_DENYLIST. Check them against the documented tool list.`);let m=e.MONACO_RPC_URL||kie[s],h=null;if(e.MONACO_DELEGATED_OWNER_USER_ID!==void 0){let b=e.MONACO_DELEGATED_OWNER_USER_ID.trim();if(!b)throw Error("MONACO_DELEGATED_OWNER_USER_ID must be a non-empty owner user id when set.");if(!t||!r)throw Error("MONACO_DELEGATED_OWNER_USER_ID requires MONACO_PRIVATE_KEY and MONACO_CLIENT_ID (the agent authenticates as itself before adopting the owner).");h=b}return{privateKey:t,clientId:r,network:s,seiRpcUrl:m,capability:c,allow:d,deny:l,delegatedOwnerUserId:h}}function Rie(e){return e.replace(/_([a-z])/g,(t,r)=>r.toUpperCase())}function en(e){if(e===null||e===void 0)return e;if(typeof e!=="object")return e;if(Array.isArray(e))return e.map((r)=>en(r));let t={};for(let[r,n]of Object.entries(e))t[Rie(r)]=typeof n==="object"&&n!==null?en(n):n;return t}function Z4(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var Cv=(e)=>e?`"${e}" `:"";function Oie(e,t=""){if(typeof e!=="number")throw TypeError(Cv(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(Cv(t)+"expected integer >= 0, got "+e);return e}function T0(e,t,r=""){if(Z4(e)&&(t===void 0||e.length===t))return e;if(t!==void 0)Oie(t,"length");let n=Z4(e),o=t!==void 0?` of length ${t}`:"",i=n?`length=${e.length}`:`type=${typeof e}`,s=Cv(r)+"expected Uint8Array"+o+", got "+i;if(!n)throw TypeError(s);throw RangeError(s)}var Cie=(e,t)=>{if(e===null||typeof e!=="object"||Array.isArray(e))throw TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},W4=(e,t)=>{Cie(e,t);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw TypeError(`"${t}.__proto__" is not allowed`)};function Mv(e,t=!0){if(e.destroyed)throw Error("hash was destroyed");if(t&&e.finished)throw Error("digest() was already called")}function Y4(e,t){T0(e,void 0,"output");let r=t.outputLen;if(!(e.length>=r))throw RangeError('"output" expected length >= '+r)}function E0(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function P0(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function _o(e,t){return e<<32-t|e>>>t}var J4=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),Mie=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Li(e){if(T0(e),J4)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=Mie[e[r]];return t}function K4(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function wf(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);if(J4)try{return Uint8Array.fromHex(e)}catch(o){if(o instanceof SyntaxError)throw RangeError(o.message);throw o}let t=e.length,r=t/2;if(t%2)throw RangeError("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,i=0;o<r;o++,i+=2){let s=K4(e.charCodeAt(i)),a=K4(e.charCodeAt(i+1));if(s===void 0||a===void 0){let c=e[i]+e[i+1];throw RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function pc(e){if(typeof e!=="string")throw TypeError("string expected");let t=new TextEncoder().encode(e);try{return new Uint8Array(t)}finally{E0(t)}}function $ie(e,t,r="opts"){if(W4(e,"defaults"),t!==void 0)W4(t,r);return Object.assign(Object.create(null),e,t)}function Q4(e,t={}){if(typeof e!=="function")throw TypeError('"hashCons" expected function, got type='+typeof e);t=$ie({},t,"info");let r=(o,i)=>e(i).update(o).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=(o)=>e(o),Object.assign(r,t),Object.freeze(r)}var X4=(e)=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});Lv();hc();Qv();td();If();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Jo=BigInt(0),rn=BigInt(1),D8=BigInt(2),Qie=BigInt(8),Xie={zip215:!0};function ese(e){let t=kf(e);return Hi(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function U8(e){let t=ese(e),{Fp:r,n,prehash:o,hash:i,randomBytes:s,nByteLength:a,h:c}=t,d=D8<<BigInt(a*8)-rn,l=r.create,p=Gi(t.n,t.nBitLength);function m(z,F){let Y=r.sqr(z),we=r.sqr(F),te=r.add(r.mul(t.a,Y),we),$e=r.add(r.ONE,r.mul(t.d,r.mul(Y,we)));return r.eql(te,$e)}if(!m(t.Gx,t.Gy))throw Error("bad curve params: generator point");let h=t.uvRatio||((z,F)=>{try{return{isValid:!0,value:r.sqrt(z*r.inv(F))}}catch(Y){return{isValid:!1,value:Jo}}}),b=t.adjustScalarBytes||((z)=>z),x=t.domain||((z,F,Y)=>{if(Yo("phflag",Y),F.length||Y)throw Error("Contexts/pre-hash are not supported");return z});function _(z,F,Y=!1){let we=Y?rn:Jo;On("coordinate "+z,F,we,d)}function w(z){if(!(z instanceof T))throw Error("ExtendedPoint expected")}let A=Xu((z,F)=>{let{ex:Y,ey:we,ez:te}=z,$e=z.is0();if(F==null)F=$e?Qie:r.inv(te);let Ee=l(Y*F),Ae=l(we*F),tt=l(te*F);if($e)return{x:Jo,y:rn};if(tt!==rn)throw Error("invZ was invalid");return{x:Ee,y:Ae}}),v=Xu((z)=>{let{a:F,d:Y}=t;if(z.is0())throw Error("bad point: ZERO");let{ex:we,ey:te,ez:$e,et:Ee}=z,Ae=l(we*we),tt=l(te*te),yt=l($e*$e),ft=l(yt*yt),q=l(Ae*F),ne=l(yt*l(q+tt)),ce=l(ft+l(Y*l(Ae*tt)));if(ne!==ce)throw Error("bad point: equation left != right (1)");let he=l(we*te),Q=l($e*Ee);if(he!==Q)throw Error("bad point: equation left != right (2)");return!0});class T{constructor(z,F,Y,we){_("x",z),_("y",F),_("z",Y,!0),_("t",we),this.ex=z,this.ey=F,this.ez=Y,this.et=we,Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(z){if(z instanceof T)throw Error("extended point not allowed");let{x:F,y:Y}=z||{};return _("x",F),_("y",Y),new T(F,Y,rn,l(F*Y))}static normalizeZ(z){let F=ed(r,z.map((Y)=>Y.ez));return z.map((Y,we)=>Y.toAffine(F[we])).map(T.fromAffine)}static msm(z,F){return N0(T,p,z,F)}_setWindowSize(z){O.setWindowSize(this,z)}assertValidity(){v(this)}equals(z){w(z);let{ex:F,ey:Y,ez:we}=this,{ex:te,ey:$e,ez:Ee}=z,Ae=l(F*Ee),tt=l(te*we),yt=l(Y*Ee),ft=l($e*we);return Ae===tt&&yt===ft}is0(){return this.equals(T.ZERO)}negate(){return new T(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){let{a:z}=t,{ex:F,ey:Y,ez:we}=this,te=l(F*F),$e=l(Y*Y),Ee=l(D8*l(we*we)),Ae=l(z*te),tt=F+Y,yt=l(l(tt*tt)-te-$e),ft=Ae+$e,q=ft-Ee,ne=Ae-$e,ce=l(yt*q),he=l(ft*ne),Q=l(yt*ne),Be=l(q*ft);return new T(ce,he,Be,Q)}add(z){w(z);let{a:F,d:Y}=t,{ex:we,ey:te,ez:$e,et:Ee}=this,{ex:Ae,ey:tt,ez:yt,et:ft}=z,q=l(we*Ae),ne=l(te*tt),ce=l(Ee*Y*ft),he=l($e*yt),Q=l((we+te)*(Ae+tt)-q-ne),Be=he-ce,bt=he+ce,xt=l(ne-F*q),Qe=l(Q*Be),vt=l(bt*xt),wt=l(Q*xt),Hr=l(Be*bt);return new T(Qe,vt,Hr,wt)}subtract(z){return this.add(z.negate())}wNAF(z){return O.wNAFCached(this,z,T.normalizeZ)}multiply(z){let F=z;On("scalar",F,rn,n);let{p:Y,f:we}=this.wNAF(F);return T.normalizeZ([Y,we])[0]}multiplyUnsafe(z,F=T.ZERO){let Y=z;if(On("scalar",Y,Jo,n),Y===Jo)return k;if(this.is0()||Y===rn)return this;return O.wNAFCachedUnsafe(this,Y,T.normalizeZ,F)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return O.unsafeLadder(this,n).is0()}toAffine(z){return A(this,z)}clearCofactor(){let{h:z}=t;if(z===rn)return this;return this.multiplyUnsafe(z)}static fromHex(z,F=!1){let{d:Y,a:we}=t,te=r.BYTES;z=Gt("pointHex",z,te),Yo("zip215",F);let $e=z.slice(),Ee=z[te-1];$e[te-1]=Ee&-129;let Ae=bc($e),tt=F?d:r.ORDER;On("pointHex.y",Ae,Jo,tt);let yt=l(Ae*Ae),ft=l(yt-rn),q=l(Y*yt-we),{isValid:ne,value:ce}=h(ft,q);if(!ne)throw Error("Point.fromHex: invalid y coordinate");let he=(ce&rn)===rn,Q=(Ee&128)!==0;if(!F&&ce===Jo&&Q)throw Error("Point.fromHex: x=0 and x_0=1");if(Q!==he)ce=l(-ce);return T.fromAffine({x:ce,y:Ae})}static fromPrivateKey(z){let{scalar:F}=R(z);return P.multiply(F)}toRawBytes(){let{x:z,y:F}=this.toAffine(),Y=Qu(F,r.BYTES);return Y[Y.length-1]|=z&rn?128:0,Y}toHex(){return ra(this.toRawBytes())}}T.BASE=new T(t.Gx,t.Gy,rn,l(t.Gx*t.Gy)),T.ZERO=new T(Jo,rn,rn,Jo);let{BASE:P,ZERO:k}=T,O=$0(T,a*8);function N(z){return Pt(z,n)}function j(z){return N(bc(z))}function R(z){let F=r.BYTES;z=Gt("private key",z,F);let Y=Gt("hashed private key",i(z),2*F),we=b(Y.slice(0,F)),te=Y.slice(F,2*F),$e=j(we);return{head:we,prefix:te,scalar:$e}}function K(z){let{head:F,prefix:Y,scalar:we}=R(z),te=P.multiply(we),$e=te.toRawBytes();return{head:F,prefix:Y,scalar:we,point:te,pointBytes:$e}}function Z(z){return K(z).pointBytes}function re(z=Uint8Array.of(),...F){let Y=na(...F);return j(i(x(Y,Gt("context",z),!!o)))}function pe(z,F,Y={}){if(z=Gt("message",z),o)z=o(z);let{prefix:we,scalar:te,pointBytes:$e}=K(F),Ee=re(Y.context,we,z),Ae=P.multiply(Ee).toRawBytes(),tt=re(Y.context,Ae,$e,z),yt=N(Ee+tt*te);On("signature.s",yt,Jo,n);let ft=na(Ae,Qu(yt,r.BYTES));return Gt("result",ft,r.BYTES*2)}let U=Xie;function ee(z,F,Y,we=U){let{context:te,zip215:$e}=we,Ee=r.BYTES;if(z=Gt("signature",z,2*Ee),F=Gt("message",F),Y=Gt("publicKey",Y,Ee),$e!==void 0)Yo("zip215",$e);if(o)F=o(F);let Ae=bc(z.slice(Ee,2*Ee)),tt,yt,ft;try{tt=T.fromHex(Y,$e),yt=T.fromHex(z.slice(0,Ee),$e),ft=P.multiplyUnsafe(Ae)}catch(ce){return!1}if(!$e&&tt.isSmallOrder())return!1;let q=re(te,yt.toRawBytes(),tt.toRawBytes(),F);return yt.add(tt.multiplyUnsafe(q)).subtract(ft).clearCofactor().equals(T.ZERO)}return P._setWindowSize(8),{CURVE:t,getPublicKey:Z,sign:pe,verify:ee,ExtendedPoint:T,utils:{getExtendedPublicKey:K,randomPrivateKey:()=>s(r.BYTES),precompute(z=8,F=T.BASE){return F._setWindowSize(z),F.multiply(BigInt(3)),F}}}}td();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Xv=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),F8=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),gwe=BigInt(0),tse=BigInt(1),j8=BigInt(2),ywe=BigInt(3),rse=BigInt(5),nse=BigInt(8);function ose(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),i=Xv,a=e*e%i*e%i,c=Vt(a,j8,i)*a%i,d=Vt(c,tse,i)*e%i,l=Vt(d,rse,i)*d%i,p=Vt(l,t,i)*l%i,m=Vt(p,r,i)*p%i,h=Vt(m,n,i)*m%i,b=Vt(h,o,i)*h%i,x=Vt(b,o,i)*h%i,_=Vt(x,t,i)*l%i;return{pow_p_5_8:Vt(_,j8,i)*e%i,b2:a}}function ise(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function sse(e,t){let r=Xv,n=Pt(t*t*t,r),o=Pt(n*n*t,r),i=ose(e*o).pow_p_5_8,s=Pt(e*n*i,r),a=Pt(t*s*s,r),c=s,d=Pt(s*F8,r),l=a===e,p=a===Pt(-e,r),m=a===Pt(-e*F8,r);if(l)s=c;if(p||m)s=d;if(C8(s,r))s=Pt(-s,r);return{isValid:l||p,value:s}}var q8=(()=>Gi(Xv,void 0,!0))(),ase=(()=>({a:q8.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:q8,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:nse,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:_8,randomBytes:k0,adjustScalarBytes:ise,uvRatio:sse}))(),rd=(()=>U8(ase))();var cse=(e)=>e/4294967296|0,use=(e)=>e>>>0;function H8(e,t,r,n){let o=cse(r),i=use(r);e.setUint32(t,n?i:o,n),e.setUint32(t+4,n?o:i,n)}function G8(e,t,r){return e&t^~e&r}function V8(e,t,r){return e&t^e&r^t&r}class eT{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,n){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=P0(this.buffer)}update(e){Mv(this),T0(e);let{view:t,buffer:r,blockLen:n}=this,o=e.length,i=!1;for(let s=0;s<o;){let a=Math.min(n-this.pos,o-s);if(a===n){let c=P0(e);for(;n<=o-s;s+=n)this.process(c,s);i=!0;continue}if(r.set(s===0&&a===o?e:e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===n)this.process(t,0),this.pos=0,i=!0}if(this.length+=e.length,i)this.roundClean();return this}digestInto(e){Mv(this),Y4(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:o}=this,{pos:i}=this;if(t[i++]=128,t.fill(0,i),this.padOffset>n-i)this.process(r,0),t.fill(0);H8(r,n-8,this.length*8,o),this.process(r,0),this.roundClean();let s=e===t?r:P0(e),a=this.outputLen,c=a/4,d=this.get();if(a%4||c>d.length)throw Error("invalid outputLen");for(let l=0;l<c;l++)s.setUint32(4*l,d[l],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneIntoMeta(e){let{buffer:t,length:r,finished:n,destroyed:o,pos:i}=this;if(e.destroyed=o,e.finished=n,e.length=r,e.pos=i,i)e.buffer.set(t);return e}clone(){return this._cloneInto()}}var Z8=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var dse=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),oa=new Uint32Array(64);class W8 extends eT{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1);this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:r,D:n,E:o,F:i,G:s,H:a}=this;return[e,t,r,n,o,i,s,a]}set(e,t,r,n,o,i,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=s|0,this.H=a|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let l=0;l<16;l++,t+=4)oa[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let p=oa[l-15],m=oa[l-2],h=_o(p,7)^_o(p,18)^p>>>3,b=_o(m,17)^_o(m,19)^m>>>10;oa[l]=b+oa[l-7]+h+oa[l-16]|0}let{A:r,B:n,C:o,D:i,E:s,F:a,G:c,H:d}=this;for(let l=0;l<64;l++){let p=_o(s,6)^_o(s,11)^_o(s,25),m=d+p+G8(s,a,c)+dse[l]+oa[l]|0,b=(_o(r,2)^_o(r,13)^_o(r,22))+V8(r,n,o)|0;d=c,c=a,a=s,s=i+m|0,i=o,o=n,n=r,r=m+b|0}r=r+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,d=d+this.H|0,this.set(r,n,o,i,s,a,c,d)}roundClean(){E0(oa)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),E0(this.buffer)}}class K8 extends W8{constructor(){super(32,Z8)}}var z0=Q4(()=>new K8,X4(1));function B0(){if(typeof globalThis.crypto?.getRandomValues!=="function")throw Error("Secure randomness (crypto.getRandomValues) is unavailable; cannot generate a session keypair.");let e=rd.utils.randomPrivateKey();return{publicKey:rd.getPublicKey(e),privateKey:e}}function L0(e){return Li(e.publicKey)}function D0(e){return Li(e.privateKey)}function Y8(e,t){return{publicKey:wf(e),privateKey:wf(t)}}function J8(e){return Li(z0(e))}function Q8(e,t,r,n){return`${e.toUpperCase()}
136
+ `}class kv{constructor(e=B4.stdin,t=B4.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new Iv,this._started=!1,this._ondata=(r)=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=(r)=>{this.onerror?.(r)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise((t)=>{let r=z4(e);if(this._stdout.write(r))t();else this._stdout.once("drain",t)})}}var S0={name:"@0xmonaco/mcp-server",version:"1.0.65",type:"module",homepage:"https://docs.0xmonaco.com/sdk/typescript",description:"MCP server for the Monaco SDK",engines:{node:">=18"},bin:"./dist/bin.js",files:["dist"],scripts:{build:"bun build src/bin.ts --outdir dist --target node --format esm --minify",dev:"bun --watch src/bin.ts",start:"bun dist/bin.js",clean:"rm -rf dist",lint:"biome lint .",test:"bun test"},author:"@codebycarson",dependencies:{"@0xmonaco/core":"1.0.65","@0xmonaco/types":"1.0.65","@modelcontextprotocol/sdk":"^1.29.0","node-fetch":"^3.3.2",viem:"^2.56.3",ws:"^8.21.0",zod:"^4.4.3"},devDependencies:{"@types/bun":"latest","@types/ws":"^8.18.1"}};var v0=["read","market-maker","full"],Wo=[{name:"search_docs",description:"Search the Monaco documentation for protocol, SDK, trading, and development guides.",category:"search",authMode:"public",sideEffect:"read-only"},{name:"get_trading_pairs",description:"List trading pairs with optional filters (market type, base/quote token, active status).",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_trading_pair_by_symbol",description:"Look up a trading pair by symbol (e.g. `BTC/USDC`).",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_candlesticks",description:"Fetch OHLCV candlestick data for a trading pair.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_market_metadata",description:"Get tick size, minimum order size, and trading rules for a pair.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_screener",description:"Screen trading pairs with market stats (price, volume, change), filtered by market type, category, and active status.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_market_stats",description:"Get exchange-wide life-to-date cumulative volume and trade count across all markets.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_perp_market_config",description:"Get a perpetual market's configuration (leverage limits, margin requirements, funding parameters).",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_perp_market_summary",description:"Get a perpetual market's live summary (mark/index price, funding rate, open interest, 24h stats).",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_mark_price",description:"Get the current mark price for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_index_price",description:"Get the current index (oracle) price for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_funding_state",description:"Get the current funding rate and next funding time for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_open_interest",description:"Get the current open interest for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_funding_history",description:"List historical funding-rate records for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_all_funding_history",description:"List historical funding-rate records across all perpetual markets.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_orderbook",description:"Fetch a current orderbook snapshot with bids and asks.",category:"orderbook",authMode:"public",sideEffect:"read-only"},{name:"get_trades",description:"Fetch historical trades for a trading pair.",category:"trades",authMode:"public",sideEffect:"read-only"},{name:"place_limit_order",description:"Place a limit order with price, quantity, and time-in-force. The SDK supplies an idempotency key if omitted. Retain an explicit key to retry the same submission within 24 hours of acceptance. Calling again without the original key is not idempotent; never retry an ambiguous failure with a new key. If the original key is unavailable, report the ambiguity.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"place_market_order",description:"Place a market order — executes immediately inside a mandatory 1,000 bps protective price band, so it may partially fill or be rejected. The SDK supplies an idempotency key if omitted. Retain an explicit key to retry the same submission within 24 hours of acceptance. Calling again without the original key is not idempotent; never retry an ambiguous failure with a new key. If the original key is unavailable, report the ambiguity.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"replace_order",description:"Modify an existing order's price and/or quantity. Not idempotent — an ambiguous failure (timeout/network error/5xx with no order) cannot be resolved from inside MCP, which has no order-stream tool; never retry, and report the ambiguity instead.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"cancel_order",description:"Cancel a single order by ID.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_cancel_orders",description:"Cancel multiple orders by ID (non-atomic — a failed leg does not stop the others).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_cancel_all_orders",description:"Cancel all open orders, optionally filtered to a trading pair (unfiltered, it cancels your entire open-order book).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_close_all_positions",description:"Close all open perpetual positions with market reduce-only orders (best-effort, optional pair filter).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_orders",description:"List your orders with optional filters.",category:"trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_order",description:"Get details for a specific order by ID.",category:"trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_positions",description:"List your perpetual positions with optional filters (margin account, trading pair, status).",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position",description:"Get details for a specific perpetual position by ID.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_risk",description:"Get liquidation price, margin ratio, and risk metrics for a perpetual position.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_history",description:"List historical (closed/reduced) perpetual position records with optional filters.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_pnl_history",description:"Get the PnL history time series for a perpetual position over an interval.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"close_position",description:"Close a perpetual position with a market, limit, or IOC reduce order.",category:"positions",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_profile",description:"Fetch your core profile (address, username, account type, withdrawal status).",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_balances",description:"List token balances with pagination.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_balance_by_asset",description:"Get balance for a specific asset.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_movements",description:"Fetch transaction and movement history with optional filters.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_user_trades",description:"List your own trade fills with optional filters and cursor pagination.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_funding_payments",description:"List your perpetual funding payments with optional filters (trading pair, position, margin account).",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_summary",description:"Get your authoritative portfolio summary (equity, PnL, exposure) over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_performance",description:"Get your portfolio performance time series over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_realized_pnl",description:"Get your realized PnL breakdown over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_assets",description:"Get your per-asset portfolio allocation and balances over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_margin",description:"Get your portfolio margin overview (collateral, maintenance margin, health).",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_margin_accounts",description:"List your margin accounts with optional filters (state, trading pair).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_parent_margin_account_summary",description:"Get your parent (cross) margin account summary.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_available_collateral",description:"Get available (unlocked) collateral for allocating to margin accounts or risk buckets.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_parent_margin_account_movements",description:"List collateral movements for your parent (cross) margin account.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"simulate_parent_margin_order_risk",description:"Preview the risk impact of a prospective order against your parent (cross) margin account (read-only simulation).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"simulate_risk_bucket_order_risk",description:"Preview the risk impact of a prospective order for a new or existing risk bucket (read-only simulation).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_collateral_to_parent_margin_account",description:"Move collateral from spot into your parent (cross) margin account.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_from_parent_margin_account",description:"Move collateral out of your parent (cross) margin account back to spot.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_to_risk_bucket",description:"Allocate collateral into an isolated or cross risk bucket.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"simulate_fees",description:"Simulate fees for an order before placing it.",category:"fees",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_my_fee_tier",description:"Get your current fee tier, rolling 14-day volumes, and a pair's fee schedule.",category:"fees",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"vault_approve",description:"Approve the vault contract to spend a token.",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_deposit",description:"Deposit tokens into the vault (optional `target`: `spot` default, or `margin` to route into collateral).",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_withdraw",description:"Withdraw tokens from the vault.",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_get_allowance",description:"Check current token allowance for the vault.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"vault_needs_approval",description:"Check whether an approval transaction is needed before depositing.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_pending_withdrawals",description:"List your pending withdrawals still awaiting on-chain root confirmation.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"request_faucet",description:"Request test tokens for all trading pairs.",category:"faucet",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating",excludedOnMainnet:!0},{name:"get_faucet_info",description:"Check remaining faucet quota, next-request time, and recent mint history.",category:"faucet",authMode:"authenticated",capability:"read",sideEffect:"read-only",excludedOnMainnet:!0},{name:"get_trader_code_info",description:"Look up a trader code's details (no credentials required).",category:"pitpass",authMode:"public",sideEffect:"read-only"},{name:"check_trader_code_availability",description:"Public advisory check of whether a custom PitPass TraderCode handle is available (no credentials required).",category:"pitpass",authMode:"public",sideEffect:"read-only"},{name:"get_my_trader_code",description:"Fetch your own trader code.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"set_trader_code",description:"Claim or edit your custom (vanity) PitPass TraderCode handle.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"clear_trader_code",description:"Clear your custom PitPass TraderCode handle, reverting to the wallet-derived default.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_rewards_balance",description:"Fetch your PitPass rewards-bucket balances across reward tokens.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_rewards",description:"Move your earned PitPass rewards from the rewards bucket into your own tradeable balance (ledger-only).",category:"pitpass",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"get_pulse",description:"Get the latest market-pulse news feed: AI-synthesized, per-asset headlines with sentiment tags.",category:"pulse",authMode:"public",sideEffect:"read-only"}],k_e=Wo.map((e)=>e.name),L4=Wo.filter((e)=>e.authMode==="public").map((e)=>e.name),R_e=Wo.filter((e)=>e.authMode==="authenticated"&&e.capability==="read").map((e)=>e.name),O_e=Wo.filter((e)=>e.authMode==="authenticated"&&e.capability==="market-maker").map((e)=>e.name),C_e=Wo.filter((e)=>e.authMode==="authenticated"&&e.capability==="full").map((e)=>e.name),M_e=Wo.filter((e)=>e.excludedOnMainnet).map((e)=>e.name),D4=Wo.filter((e)=>e.sideEffect==="fund-movement").map((e)=>e.name);var Aie=new Map(Wo.map((e)=>[e.name,e.sideEffect]));function U4(e){let t=Aie.get(e);if(!t)return;let r=t==="read-only";return{readOnlyHint:r,destructiveHint:!r}}var F4={read:0,"market-maker":1,full:2},Rv=L4,Ov=Object.fromEntries(Wo.filter((e)=>e.authMode==="authenticated").map((e)=>[e.name,{capability:e.capability??"full",...e.sideEffect==="fund-movement"?{fundMovement:!0}:{},...e.excludedOnMainnet?{excludedOnMainnet:!0}:{}}])),j4=Object.fromEntries(Object.entries(Ov).map(([e,t])=>[e,t.capability])),z_e=new Set(D4);function q4(e){let t=Ov[e];if(!t)return"full";if(t.fundMovement)return"full";return t.capability}function H4(e){return q4(e)==="read"}function G4(e,t){if(t.network==="mainnet"&&Ov[e]?.excludedOnMainnet)return!1;if(t.deny.includes(e))return!1;if(Rv.includes(e))return!0;if(!t.authenticated)return!1;if(t.allow.includes(e))return!0;return F4[t.capability]>=F4[q4(e)]}var Iie=new Set([...Rv,...Object.keys(j4)]),kie={mainnet:"https://evm-rpc.sei-apis.com",development:"https://evm-rpc-testnet.sei-apis.com",staging:"https://evm-rpc-testnet.sei-apis.com",local:"http://localhost:8545"};function V4(e){if(!e)return[];return e.split(",").map((t)=>t.trim()).filter(Boolean)}function lc(e=process.env){let t=e.MONACO_PRIVATE_KEY||null;if(t&&!t.startsWith("0x"))throw Error("MONACO_PRIVATE_KEY must start with '0x'.");let r=e.MONACO_CLIENT_ID||null;if(t&&!r)throw Error("MONACO_CLIENT_ID is required when MONACO_PRIVATE_KEY is set.");let n=["mainnet","development","staging","local"],o=e.MONACO_NETWORK;if(t&&!o)throw Error(`MONACO_NETWORK must be set explicitly (one of: ${n.join(", ")}) when MONACO_PRIVATE_KEY is configured. Refusing to default to mainnet for an authenticated session.`);let i=o||"mainnet";if(!n.includes(i))throw Error(`MONACO_NETWORK must be one of: ${n.join(", ")}.`);let s=i,a=e.MONACO_CAPABILITY;if(a&&!v0.includes(a))throw Error(`MONACO_CAPABILITY must be one of: ${v0.join(", ")}.`);let c=a||"read",d=V4(e.MONACO_TOOL_ALLOWLIST),l=V4(e.MONACO_TOOL_DENYLIST),p=[...d,...l].filter((b)=>!Iie.has(b)).length;if(p>0)throw Error(`${p} unknown tool name(s) in MONACO_TOOL_ALLOWLIST/MONACO_TOOL_DENYLIST. Check them against the documented tool list.`);let m=e.MONACO_RPC_URL||kie[s],h=null;if(e.MONACO_DELEGATED_OWNER_USER_ID!==void 0){let b=e.MONACO_DELEGATED_OWNER_USER_ID.trim();if(!b)throw Error("MONACO_DELEGATED_OWNER_USER_ID must be a non-empty owner user id when set.");if(!t||!r)throw Error("MONACO_DELEGATED_OWNER_USER_ID requires MONACO_PRIVATE_KEY and MONACO_CLIENT_ID (the agent authenticates as itself before adopting the owner).");h=b}return{privateKey:t,clientId:r,network:s,seiRpcUrl:m,capability:c,allow:d,deny:l,delegatedOwnerUserId:h}}function Rie(e){return e.replace(/_([a-z])/g,(t,r)=>r.toUpperCase())}function en(e){if(e===null||e===void 0)return e;if(typeof e!=="object")return e;if(Array.isArray(e))return e.map((r)=>en(r));let t={};for(let[r,n]of Object.entries(e))t[Rie(r)]=typeof n==="object"&&n!==null?en(n):n;return t}function Z4(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var Cv=(e)=>e?`"${e}" `:"";function Oie(e,t=""){if(typeof e!=="number")throw TypeError(Cv(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(Cv(t)+"expected integer >= 0, got "+e);return e}function T0(e,t,r=""){if(Z4(e)&&(t===void 0||e.length===t))return e;if(t!==void 0)Oie(t,"length");let n=Z4(e),o=t!==void 0?` of length ${t}`:"",i=n?`length=${e.length}`:`type=${typeof e}`,s=Cv(r)+"expected Uint8Array"+o+", got "+i;if(!n)throw TypeError(s);throw RangeError(s)}var Cie=(e,t)=>{if(e===null||typeof e!=="object"||Array.isArray(e))throw TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},W4=(e,t)=>{Cie(e,t);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw TypeError(`"${t}.__proto__" is not allowed`)};function Mv(e,t=!0){if(e.destroyed)throw Error("hash was destroyed");if(t&&e.finished)throw Error("digest() was already called")}function Y4(e,t){T0(e,void 0,"output");let r=t.outputLen;if(!(e.length>=r))throw RangeError('"output" expected length >= '+r)}function E0(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function P0(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function _o(e,t){return e<<32-t|e>>>t}var J4=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),Mie=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Li(e){if(T0(e),J4)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=Mie[e[r]];return t}function K4(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function wf(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);if(J4)try{return Uint8Array.fromHex(e)}catch(o){if(o instanceof SyntaxError)throw RangeError(o.message);throw o}let t=e.length,r=t/2;if(t%2)throw RangeError("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,i=0;o<r;o++,i+=2){let s=K4(e.charCodeAt(i)),a=K4(e.charCodeAt(i+1));if(s===void 0||a===void 0){let c=e[i]+e[i+1];throw RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function pc(e){if(typeof e!=="string")throw TypeError("string expected");let t=new TextEncoder().encode(e);try{return new Uint8Array(t)}finally{E0(t)}}function $ie(e,t,r="opts"){if(W4(e,"defaults"),t!==void 0)W4(t,r);return Object.assign(Object.create(null),e,t)}function Q4(e,t={}){if(typeof e!=="function")throw TypeError('"hashCons" expected function, got type='+typeof e);t=$ie({},t,"info");let r=(o,i)=>e(i).update(o).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=(o)=>e(o),Object.assign(r,t),Object.freeze(r)}var X4=(e)=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});Lv();hc();Qv();td();If();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Jo=BigInt(0),rn=BigInt(1),D8=BigInt(2),Qie=BigInt(8),Xie={zip215:!0};function ese(e){let t=kf(e);return Hi(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function U8(e){let t=ese(e),{Fp:r,n,prehash:o,hash:i,randomBytes:s,nByteLength:a,h:c}=t,d=D8<<BigInt(a*8)-rn,l=r.create,p=Gi(t.n,t.nBitLength);function m(z,F){let Y=r.sqr(z),we=r.sqr(F),te=r.add(r.mul(t.a,Y),we),$e=r.add(r.ONE,r.mul(t.d,r.mul(Y,we)));return r.eql(te,$e)}if(!m(t.Gx,t.Gy))throw Error("bad curve params: generator point");let h=t.uvRatio||((z,F)=>{try{return{isValid:!0,value:r.sqrt(z*r.inv(F))}}catch(Y){return{isValid:!1,value:Jo}}}),b=t.adjustScalarBytes||((z)=>z),x=t.domain||((z,F,Y)=>{if(Yo("phflag",Y),F.length||Y)throw Error("Contexts/pre-hash are not supported");return z});function _(z,F,Y=!1){let we=Y?rn:Jo;On("coordinate "+z,F,we,d)}function w(z){if(!(z instanceof T))throw Error("ExtendedPoint expected")}let A=Xu((z,F)=>{let{ex:Y,ey:we,ez:te}=z,$e=z.is0();if(F==null)F=$e?Qie:r.inv(te);let Ee=l(Y*F),Ae=l(we*F),tt=l(te*F);if($e)return{x:Jo,y:rn};if(tt!==rn)throw Error("invZ was invalid");return{x:Ee,y:Ae}}),v=Xu((z)=>{let{a:F,d:Y}=t;if(z.is0())throw Error("bad point: ZERO");let{ex:we,ey:te,ez:$e,et:Ee}=z,Ae=l(we*we),tt=l(te*te),yt=l($e*$e),ft=l(yt*yt),q=l(Ae*F),ne=l(yt*l(q+tt)),ce=l(ft+l(Y*l(Ae*tt)));if(ne!==ce)throw Error("bad point: equation left != right (1)");let he=l(we*te),Q=l($e*Ee);if(he!==Q)throw Error("bad point: equation left != right (2)");return!0});class T{constructor(z,F,Y,we){_("x",z),_("y",F),_("z",Y,!0),_("t",we),this.ex=z,this.ey=F,this.ez=Y,this.et=we,Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(z){if(z instanceof T)throw Error("extended point not allowed");let{x:F,y:Y}=z||{};return _("x",F),_("y",Y),new T(F,Y,rn,l(F*Y))}static normalizeZ(z){let F=ed(r,z.map((Y)=>Y.ez));return z.map((Y,we)=>Y.toAffine(F[we])).map(T.fromAffine)}static msm(z,F){return N0(T,p,z,F)}_setWindowSize(z){O.setWindowSize(this,z)}assertValidity(){v(this)}equals(z){w(z);let{ex:F,ey:Y,ez:we}=this,{ex:te,ey:$e,ez:Ee}=z,Ae=l(F*Ee),tt=l(te*we),yt=l(Y*Ee),ft=l($e*we);return Ae===tt&&yt===ft}is0(){return this.equals(T.ZERO)}negate(){return new T(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){let{a:z}=t,{ex:F,ey:Y,ez:we}=this,te=l(F*F),$e=l(Y*Y),Ee=l(D8*l(we*we)),Ae=l(z*te),tt=F+Y,yt=l(l(tt*tt)-te-$e),ft=Ae+$e,q=ft-Ee,ne=Ae-$e,ce=l(yt*q),he=l(ft*ne),Q=l(yt*ne),Be=l(q*ft);return new T(ce,he,Be,Q)}add(z){w(z);let{a:F,d:Y}=t,{ex:we,ey:te,ez:$e,et:Ee}=this,{ex:Ae,ey:tt,ez:yt,et:ft}=z,q=l(we*Ae),ne=l(te*tt),ce=l(Ee*Y*ft),he=l($e*yt),Q=l((we+te)*(Ae+tt)-q-ne),Be=he-ce,bt=he+ce,xt=l(ne-F*q),Qe=l(Q*Be),vt=l(bt*xt),wt=l(Q*xt),Hr=l(Be*bt);return new T(Qe,vt,Hr,wt)}subtract(z){return this.add(z.negate())}wNAF(z){return O.wNAFCached(this,z,T.normalizeZ)}multiply(z){let F=z;On("scalar",F,rn,n);let{p:Y,f:we}=this.wNAF(F);return T.normalizeZ([Y,we])[0]}multiplyUnsafe(z,F=T.ZERO){let Y=z;if(On("scalar",Y,Jo,n),Y===Jo)return k;if(this.is0()||Y===rn)return this;return O.wNAFCachedUnsafe(this,Y,T.normalizeZ,F)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return O.unsafeLadder(this,n).is0()}toAffine(z){return A(this,z)}clearCofactor(){let{h:z}=t;if(z===rn)return this;return this.multiplyUnsafe(z)}static fromHex(z,F=!1){let{d:Y,a:we}=t,te=r.BYTES;z=Gt("pointHex",z,te),Yo("zip215",F);let $e=z.slice(),Ee=z[te-1];$e[te-1]=Ee&-129;let Ae=bc($e),tt=F?d:r.ORDER;On("pointHex.y",Ae,Jo,tt);let yt=l(Ae*Ae),ft=l(yt-rn),q=l(Y*yt-we),{isValid:ne,value:ce}=h(ft,q);if(!ne)throw Error("Point.fromHex: invalid y coordinate");let he=(ce&rn)===rn,Q=(Ee&128)!==0;if(!F&&ce===Jo&&Q)throw Error("Point.fromHex: x=0 and x_0=1");if(Q!==he)ce=l(-ce);return T.fromAffine({x:ce,y:Ae})}static fromPrivateKey(z){let{scalar:F}=R(z);return P.multiply(F)}toRawBytes(){let{x:z,y:F}=this.toAffine(),Y=Qu(F,r.BYTES);return Y[Y.length-1]|=z&rn?128:0,Y}toHex(){return ra(this.toRawBytes())}}T.BASE=new T(t.Gx,t.Gy,rn,l(t.Gx*t.Gy)),T.ZERO=new T(Jo,rn,rn,Jo);let{BASE:P,ZERO:k}=T,O=$0(T,a*8);function N(z){return Pt(z,n)}function j(z){return N(bc(z))}function R(z){let F=r.BYTES;z=Gt("private key",z,F);let Y=Gt("hashed private key",i(z),2*F),we=b(Y.slice(0,F)),te=Y.slice(F,2*F),$e=j(we);return{head:we,prefix:te,scalar:$e}}function K(z){let{head:F,prefix:Y,scalar:we}=R(z),te=P.multiply(we),$e=te.toRawBytes();return{head:F,prefix:Y,scalar:we,point:te,pointBytes:$e}}function Z(z){return K(z).pointBytes}function re(z=Uint8Array.of(),...F){let Y=na(...F);return j(i(x(Y,Gt("context",z),!!o)))}function pe(z,F,Y={}){if(z=Gt("message",z),o)z=o(z);let{prefix:we,scalar:te,pointBytes:$e}=K(F),Ee=re(Y.context,we,z),Ae=P.multiply(Ee).toRawBytes(),tt=re(Y.context,Ae,$e,z),yt=N(Ee+tt*te);On("signature.s",yt,Jo,n);let ft=na(Ae,Qu(yt,r.BYTES));return Gt("result",ft,r.BYTES*2)}let U=Xie;function ee(z,F,Y,we=U){let{context:te,zip215:$e}=we,Ee=r.BYTES;if(z=Gt("signature",z,2*Ee),F=Gt("message",F),Y=Gt("publicKey",Y,Ee),$e!==void 0)Yo("zip215",$e);if(o)F=o(F);let Ae=bc(z.slice(Ee,2*Ee)),tt,yt,ft;try{tt=T.fromHex(Y,$e),yt=T.fromHex(z.slice(0,Ee),$e),ft=P.multiplyUnsafe(Ae)}catch(ce){return!1}if(!$e&&tt.isSmallOrder())return!1;let q=re(te,yt.toRawBytes(),tt.toRawBytes(),F);return yt.add(tt.multiplyUnsafe(q)).subtract(ft).clearCofactor().equals(T.ZERO)}return P._setWindowSize(8),{CURVE:t,getPublicKey:Z,sign:pe,verify:ee,ExtendedPoint:T,utils:{getExtendedPublicKey:K,randomPrivateKey:()=>s(r.BYTES),precompute(z=8,F=T.BASE){return F._setWindowSize(z),F.multiply(BigInt(3)),F}}}}td();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Xv=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),F8=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),gwe=BigInt(0),tse=BigInt(1),j8=BigInt(2),ywe=BigInt(3),rse=BigInt(5),nse=BigInt(8);function ose(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),i=Xv,a=e*e%i*e%i,c=Vt(a,j8,i)*a%i,d=Vt(c,tse,i)*e%i,l=Vt(d,rse,i)*d%i,p=Vt(l,t,i)*l%i,m=Vt(p,r,i)*p%i,h=Vt(m,n,i)*m%i,b=Vt(h,o,i)*h%i,x=Vt(b,o,i)*h%i,_=Vt(x,t,i)*l%i;return{pow_p_5_8:Vt(_,j8,i)*e%i,b2:a}}function ise(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function sse(e,t){let r=Xv,n=Pt(t*t*t,r),o=Pt(n*n*t,r),i=ose(e*o).pow_p_5_8,s=Pt(e*n*i,r),a=Pt(t*s*s,r),c=s,d=Pt(s*F8,r),l=a===e,p=a===Pt(-e,r),m=a===Pt(-e*F8,r);if(l)s=c;if(p||m)s=d;if(C8(s,r))s=Pt(-s,r);return{isValid:l||p,value:s}}var q8=(()=>Gi(Xv,void 0,!0))(),ase=(()=>({a:q8.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:q8,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:nse,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:_8,randomBytes:k0,adjustScalarBytes:ise,uvRatio:sse}))(),rd=(()=>U8(ase))();var cse=(e)=>e/4294967296|0,use=(e)=>e>>>0;function H8(e,t,r,n){let o=cse(r),i=use(r);e.setUint32(t,n?i:o,n),e.setUint32(t+4,n?o:i,n)}function G8(e,t,r){return e&t^~e&r}function V8(e,t,r){return e&t^e&r^t&r}class eT{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,n){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=P0(this.buffer)}update(e){Mv(this),T0(e);let{view:t,buffer:r,blockLen:n}=this,o=e.length,i=!1;for(let s=0;s<o;){let a=Math.min(n-this.pos,o-s);if(a===n){let c=P0(e);for(;n<=o-s;s+=n)this.process(c,s);i=!0;continue}if(r.set(s===0&&a===o?e:e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===n)this.process(t,0),this.pos=0,i=!0}if(this.length+=e.length,i)this.roundClean();return this}digestInto(e){Mv(this),Y4(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:o}=this,{pos:i}=this;if(t[i++]=128,t.fill(0,i),this.padOffset>n-i)this.process(r,0),t.fill(0);H8(r,n-8,this.length*8,o),this.process(r,0),this.roundClean();let s=e===t?r:P0(e),a=this.outputLen,c=a/4,d=this.get();if(a%4||c>d.length)throw Error("invalid outputLen");for(let l=0;l<c;l++)s.setUint32(4*l,d[l],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneIntoMeta(e){let{buffer:t,length:r,finished:n,destroyed:o,pos:i}=this;if(e.destroyed=o,e.finished=n,e.length=r,e.pos=i,i)e.buffer.set(t);return e}clone(){return this._cloneInto()}}var Z8=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var dse=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),oa=new Uint32Array(64);class W8 extends eT{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1);this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:r,D:n,E:o,F:i,G:s,H:a}=this;return[e,t,r,n,o,i,s,a]}set(e,t,r,n,o,i,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=s|0,this.H=a|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let l=0;l<16;l++,t+=4)oa[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let p=oa[l-15],m=oa[l-2],h=_o(p,7)^_o(p,18)^p>>>3,b=_o(m,17)^_o(m,19)^m>>>10;oa[l]=b+oa[l-7]+h+oa[l-16]|0}let{A:r,B:n,C:o,D:i,E:s,F:a,G:c,H:d}=this;for(let l=0;l<64;l++){let p=_o(s,6)^_o(s,11)^_o(s,25),m=d+p+G8(s,a,c)+dse[l]+oa[l]|0,b=(_o(r,2)^_o(r,13)^_o(r,22))+V8(r,n,o)|0;d=c,c=a,a=s,s=i+m|0,i=o,o=n,n=r,r=m+b|0}r=r+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,d=d+this.H|0,this.set(r,n,o,i,s,a,c,d)}roundClean(){E0(oa)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),E0(this.buffer)}}class K8 extends W8{constructor(){super(32,Z8)}}var z0=Q4(()=>new K8,X4(1));function B0(){if(typeof globalThis.crypto?.getRandomValues!=="function")throw Error("Secure randomness (crypto.getRandomValues) is unavailable; cannot generate a session keypair.");let e=rd.utils.randomPrivateKey();return{publicKey:rd.getPublicKey(e),privateKey:e}}function L0(e){return Li(e.publicKey)}function D0(e){return Li(e.privateKey)}function Y8(e,t){return{publicKey:wf(e),privateKey:wf(t)}}function J8(e){return Li(z0(e))}function Q8(e,t,r,n){return`${e.toUpperCase()}
137
137
  ${t}
138
138
  ${r}
139
139
  ${n}`}function X8(e,t){return`WS-AUTH
140
140
  ${e}
141
- ${t}`}function U0(e,t){return Li(rd.sign(pc(t),e))}var Rf=[0.0001,0.001,0.01,0.1,1,10,100,1000,1e4];var lse=1e4,pse=15000,fse=30000,mse=1000;function or(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function le(e,t){let r=e[t];if(typeof r!=="string"||r.length===0)throw Error(`Invalid WebSocket event: ${t} must be a non-empty string`);return r}function Te(e,t){let r=e[t];if(r===void 0||r===null)return;if(typeof r!=="string")throw Error(`Invalid WebSocket event: ${t} must be a string`);return r}function vo(e,t){if(!Object.hasOwn(e,t))throw Error(`Invalid WebSocket event: ${t} is missing`);let r=e[t];if(r===null||r===void 0)return null;if(typeof r!=="string")throw Error(`Invalid WebSocket event: ${t} must be a string`);return r}function tT(e,t){let r=e[t];if(typeof r!=="boolean")throw Error(`Invalid WebSocket event: ${t} must be a boolean`);return r}function hse(e,t){let r=e[t];if(typeof r!=="number"||!Number.isSafeInteger(r)||r<0)throw Error(`Invalid WebSocket event: ${t} must be a non-negative safe integer`);return r}function Of(e,t){let r=e[t];if(r===void 0||r===null)return;if(typeof r!=="number"||!Number.isFinite(r))throw Error(`Invalid WebSocket event: ${t} must be a finite number`);return r}function rT(e,t){let r=e[t];if(r===void 0||r===null)return;return hse(e,t)}function gse(e,t){let r=e[t];if(!Array.isArray(r)||r.some((n)=>typeof n!=="string"))throw Error(`Invalid WebSocket event: ${t} must be an array of strings`);return r}function F0(e,t,r){let n=le(e,t);if(!r.includes(n))throw Error(`Invalid WebSocket event: ${t} must be one of ${r.join(", ")}`);return n}function ez(e,t){let r=Te(e,t);return r===void 0||r.length===0?void 0:r}function rz(e){if(!or(e))throw Error("Invalid conditional order event: data must be an object");let t=en(e);return{conditionalOrderId:le(t,"conditionalOrderId"),tradingPairId:le(t,"tradingPairId"),marginAccountId:le(t,"marginAccountId"),positionId:Te(t,"positionId"),parentOrderId:Te(t,"parentOrderId"),associationType:ez(t,"associationType"),linkedGroupId:Te(t,"linkedGroupId"),conditionType:le(t,"conditionType"),triggerSource:le(t,"triggerSource"),triggerPrice:le(t,"triggerPrice"),side:le(t,"side"),positionSide:le(t,"positionSide"),orderType:le(t,"orderType"),limitPrice:Te(t,"limitPrice"),quantity:Te(t,"quantity"),slippageToleranceBps:Of(t,"slippageToleranceBps"),reduceOnly:tT(t,"reduceOnly"),timeInForce:ez(t,"timeInForce"),state:le(t,"state"),triggeredOrderId:Te(t,"triggeredOrderId"),triggeredAt:Te(t,"triggeredAt"),activatedAt:Te(t,"activatedAt"),cancelledAt:Te(t,"cancelledAt"),expiresAt:Te(t,"expiresAt"),failureReason:Te(t,"failureReason"),reason:le(t,"reason"),updatedAt:le(t,"updatedAt"),version:Of(t,"version")}}function yse(e){if(!or(e))throw Error("Invalid conditional order event: payload must be an object");return{eventType:F0(e,"event_type",["conditional_order_update"]),userId:le(e,"user_id"),data:rz(e.data)}}function nz(e){if(!or(e))throw Error("Invalid position event: data must be an object");let t=en(e);return{positionId:le(t,"positionId"),marginAccountId:le(t,"marginAccountId"),tradingPairId:le(t,"tradingPairId"),side:le(t,"side"),status:le(t,"status"),size:le(t,"size"),entryPrice:le(t,"entryPrice"),markPrice:Te(t,"markPrice"),unrealizedPnl:Te(t,"unrealizedPnl"),liquidationPrice:Te(t,"liquidationPrice"),isolatedMargin:le(t,"isolatedMargin"),leverage:le(t,"leverage"),riskBucketId:Te(t,"riskBucketId"),marginMode:Te(t,"marginMode"),maintenanceMarginRequired:Te(t,"maintenanceMarginRequired"),initialMarginRequired:Te(t,"initialMarginRequired"),tradeId:Te(t,"tradeId"),orderId:Te(t,"orderId"),reason:le(t,"reason"),updatedAt:le(t,"updatedAt"),version:rT(t,"version")}}function bse(e){if(!or(e))throw Error("Invalid position event: payload must be an object");return{eventType:F0(e,"event_type",["position_update"]),userId:le(e,"user_id"),data:nz(e.data)}}function oz(e){if(!or(e))throw Error("Invalid liquidation event: data must be an object");let t=en(e);return{liquidationId:le(t,"liquidationId"),marginAccountId:le(t,"marginAccountId"),positionId:Te(t,"positionId"),tradingPairId:Te(t,"tradingPairId"),status:le(t,"status"),accountState:le(t,"accountState"),liquidationPrice:Te(t,"liquidationPrice"),markPrice:Te(t,"markPrice"),estimatedShortfall:le(t,"estimatedShortfall"),message:le(t,"message"),triggeredAt:le(t,"triggeredAt")}}function xse(e){if(!or(e))throw Error("Invalid liquidation event: payload must be an object");return{eventType:F0(e,"event_type",["liquidation_alert"]),userId:le(e,"user_id"),data:oz(e.data)}}function iz(e){if(!or(e))throw Error("Invalid account event: data must be an object");let t=en(e);return{marginAccountId:le(t,"marginAccountId"),sequence:rT(t,"sequence"),equity:le(t,"equity"),collateral:le(t,"collateral"),freeCollateral:le(t,"freeCollateral"),marginRatio:le(t,"marginRatio"),maintenanceRequirement:le(t,"maintenanceRequirement"),updatedAt:le(t,"updatedAt")}}function _se(e){if(!or(e))throw Error("Invalid account event: payload must be an object");return{eventType:F0(e,"event_type",["account_update"]),userId:le(e,"user_id"),data:iz(e.data)}}function sz(e){if(!or(e))throw Error("Invalid market stats event: data must be an object");let t=en(e);return{symbol:le(t,"symbol"),tradingPairId:le(t,"tradingPairId"),indexPrice:Te(t,"indexPrice"),markPrice:Te(t,"markPrice"),midPrice:Te(t,"midPrice"),bestBidPrice:Te(t,"bestBidPrice"),bestAskPrice:Te(t,"bestAskPrice"),openInterest:Te(t,"openInterest"),openInterestLimit:Te(t,"openInterestLimit"),lastTradePrice:Te(t,"lastTradePrice"),dailyBaseTokenVolume:Te(t,"dailyBaseTokenVolume"),dailyQuoteTokenVolume:Te(t,"dailyQuoteTokenVolume"),dailyPriceLow:Te(t,"dailyPriceLow"),dailyPriceHigh:Te(t,"dailyPriceHigh"),dailyPriceChange:Te(t,"dailyPriceChange"),dailyPriceChangePercent:Te(t,"dailyPriceChangePercent"),currentFundingRate:Te(t,"currentFundingRate"),fundingRate:Te(t,"fundingRate"),fundingTimestamp:Of(t,"fundingTimestamp"),premium:Te(t,"premium"),baseInterestRate:Te(t,"baseInterestRate"),fundingClampSmall:Te(t,"fundingClampSmall"),fundingClampBig:Te(t,"fundingClampBig")}}function wse(e){if(!or(e))throw Error("Invalid market stats event: payload must be an object");return{tradingPairId:le(e,"trading_pair_id"),data:sz(e.data)}}function az(e){if(!or(e))throw Error("Invalid market stats summary: entry must be an object");let t=en(e);return{tradingPairId:le(t,"tradingPairId"),symbol:le(t,"symbol"),lastTradePrice:Te(t,"lastTradePrice"),markPrice:Te(t,"markPrice"),dailyPriceChange:Te(t,"dailyPriceChange"),dailyPriceChangePercent:Te(t,"dailyPriceChangePercent"),dailyBaseTokenVolume:Te(t,"dailyBaseTokenVolume"),dailyQuoteTokenVolume:Te(t,"dailyQuoteTokenVolume"),dailyPriceHigh:Te(t,"dailyPriceHigh"),dailyPriceLow:Te(t,"dailyPriceLow"),openInterest:Te(t,"openInterest"),currentFundingRate:Te(t,"currentFundingRate"),fundingTimestamp:Of(t,"fundingTimestamp"),marketStatus:le(t,"marketStatus")}}function Sse(e){if(!or(e)||!Array.isArray(e.markets))throw Error("Invalid market stats all event: markets must be an array");return{markets:e.markets.map(az)}}function cz(e){if(!or(e))throw Error("Invalid instrument event: data must be an object");let t=en(e);return{change:le(t,"change"),tradingPairId:le(t,"tradingPairId"),symbol:le(t,"symbol"),isActive:tT(t,"isActive"),tickSize:le(t,"tickSize"),quantityStepSize:le(t,"quantityStepSize"),minOrderSize:le(t,"minOrderSize"),maxOrderSize:le(t,"maxOrderSize"),marketType:le(t,"marketType"),category:le(t,"category"),maxLeverage:Te(t,"maxLeverage"),initialMarginRate:Te(t,"initialMarginRate"),maintenanceMarginRate:Te(t,"maintenanceMarginRate"),changedFields:gse(t,"changedFields"),updatedAt:le(t,"updatedAt")}}function vse(e){if(!or(e))throw Error("Invalid instrument event: payload must be an object");return{tradingPairId:le(e,"trading_pair_id"),data:cz(e.data)}}function Tse(e){if(!or(e))throw Error("Invalid TWAP order event: payload must be an object");if(!or(e.data))throw Error("Invalid TWAP order event: data must be an object");if(e.event_type!=="twap_order_update")throw Error("Invalid TWAP order event: event_type must be twap_order_update");let r=e.user_id;if(typeof r!=="string"||r.length===0)throw Error("Invalid TWAP order event: user_id must be a non-empty string");return{eventType:"twap_order_update",userId:r,data:uz(e.data)}}function uz(e){if(!or(e))throw Error("Invalid TWAP order event: data must be an object");let t=en(e);for(let o of Object.keys(t))if(t[o]===null)delete t[o];let r=t.twapOrderId;if(typeof r!=="string"||r.length===0)throw Error("Invalid TWAP order event: twapOrderId must be a non-empty string");let n=t.state;if(typeof n!=="string"||n.length===0)throw Error("Invalid TWAP order event: state must be a non-empty string");return t}function dz(e){if(!or(e))throw Error("Invalid balance event: data must be an object");let t=en(e);return{tokenAddress:le(t,"tokenAddress"),tokenSymbol:vo(t,"tokenSymbol"),available:le(t,"available"),availableRaw:le(t,"availableRaw"),locked:le(t,"locked"),lockedRaw:le(t,"lockedRaw"),total:le(t,"total"),totalRaw:le(t,"totalRaw"),version:rT(t,"version"),reason:le(t,"reason"),referenceId:vo(t,"referenceId"),updatedAt:le(t,"updatedAt")}}function Ese(e){return dz(e)}function tz(e){if(!or(e))throw Error("Invalid order snapshot: item must be an object");let t=en(e),r=Te(t,"clientOrderId"),n=Te(t,"selfTradePreventionMode"),o=Of(t,"version");return{orderId:le(t,"orderId"),userId:le(t,"userId"),applicationId:le(t,"applicationId"),tradingPairId:le(t,"tradingPairId"),tradingPair:le(t,"tradingPair"),tradingMode:le(t,"tradingMode"),side:le(t,"side"),orderType:le(t,"orderType"),price:vo(t,"price"),quantity:le(t,"quantity"),quantityRaw:le(t,"quantityRaw"),filledQuantity:le(t,"filledQuantity"),filledQuantityRaw:le(t,"filledQuantityRaw"),remainingQuantity:vo(t,"remainingQuantity"),remainingQuantityRaw:vo(t,"remainingQuantityRaw"),status:le(t,"status"),timeInForce:vo(t,"timeInForce"),averageFillPrice:vo(t,"averageFillPrice"),createdAt:le(t,"createdAt"),updatedAt:vo(t,"updatedAt"),marginAccountId:vo(t,"marginAccountId"),positionId:vo(t,"positionId"),leverage:vo(t,"leverage"),reduceOnly:tT(t,"reduceOnly"),...r===void 0?{}:{clientOrderId:r},...n===void 0?{}:{selfTradePreventionMode:n},...o===void 0?{}:{version:o}}}function So(e,t,r){return(n)=>{try{if(!Array.isArray(n))throw Error(`Invalid ${e} snapshot: data must be an array`);let o=n.map(t);r(o)}catch(o){console.error(`WebSocket: Error processing ${e} snapshot`,o)}}}function nT(e,t={}){let r=null,n=t.session,o=0,i=null,s=null,a=t.autoReconnect??!0,c=t.maxReconnectAttempts??Number.POSITIVE_INFINITY,d=Number.isFinite(t.reconnectBaseDelayMs)&&t.reconnectBaseDelayMs>0?t.reconnectBaseDelayMs:mse,l=Number.isFinite(t.connectionTimeoutMs)&&t.connectionTimeoutMs>0?t.connectionTimeoutMs:lse,p=null,m=new Map,h=new Map,b=new Map,x=()=>{if(!r)return i?"reconnecting":"disconnected";switch(r.readyState){case WebSocket.CONNECTING:return"connecting";case WebSocket.OPEN:return"connected";default:return i?"reconnecting":"disconnected"}},_=()=>e,w=()=>{if(!n||r?.readyState!==WebSocket.OPEN)return;let q=Date.now(),ne=U0(wf(n.privateKey),X8(n.publicKey,q));r.send(JSON.stringify({type:"Authenticate",public_key:n.publicKey,timestamp:q,signature:ne}))},A=()=>{if(s)clearInterval(s),s=null},v=()=>{A(),s=setInterval(()=>{if(r?.readyState===WebSocket.OPEN)r.send(JSON.stringify({type:"Ping"}))},pse)},T=()=>{if(i)clearTimeout(i),i=null},P=()=>{if(i)return;if(!a||o>=c){console.error("WebSocket: Max reconnect attempts reached");return}let q=Math.min(d*2**o,fse);o++;let ne=Math.random()*q;i=setTimeout(()=>{if(i=null,!a)return;K().catch((ce)=>{console.warn("WebSocket: Failed to reconnect:",ce),P()})},ne),t.onStatusChange?.("reconnecting")},k=(q)=>{if(r?.readyState===WebSocket.OPEN)r.send(JSON.stringify(q))},O=()=>{b.clear();let q=Array.from(m.keys());if(q.length>0)k({type:"Subscribe",channels:q})},N=(q)=>q.startsWith("ohlcv:")&&q.split(":").length===4,j=(q,ne)=>{if(q.endsWith(":*"))return ne.startsWith(q.slice(0,-1));if(N(q))return ne===q||ne===`${q}:trade`;return ne===q||ne.startsWith(`${q}:`)},R=(q)=>{if(q.type==="Error"){if(typeof q.code==="string"&&typeof q.message==="string")t.onError?.({code:q.code,message:q.message});return}if(!q.channel)return;if(q.type==="Snapshot"){for(let ne of h.get(q.channel)??[])ne(q.data);return}if(q.type!=="Event")return;for(let[ne,ce]of m)if(j(ne,q.channel))for(let he of ce)he(q.data)},K=()=>new Promise((q,ne)=>{if(r?.readyState===WebSocket.CONNECTING||r?.readyState===WebSocket.OPEN){q();return}try{let ce=new WebSocket(_());r=ce;let he=setTimeout(()=>{if(r!==ce){q();return}if(ce.readyState===WebSocket.CONNECTING)ce.close(1000,"Connection timeout"),ne(Error("WebSocket connection timeout"))},l);ce.onopen=()=>{if(clearTimeout(he),r!==ce){q();return}if(o=0,T(),v(),w(),O(),t.onStatusChange?.("connected"),p!==null){let Q=p;p=null,t.onResync?.({code:Q,slowClient:Q===1013})}q()},ce.onmessage=(Q)=>{if(r!==ce)return;try{let Be=JSON.parse(Q.data);if(Be.type==="Pong")return;if(Be.type==="Ping"){k({type:"Pong"});return}R(Be)}catch(Be){console.warn("WebSocket: Failed to parse message",Be)}},ce.onclose=(Q)=>{if(clearTimeout(he),r!==ce){q();return}if(r=null,A(),a&&Q.code!==1000){if(p===null||Q.code===1013)p=Q.code;P()}if(!i)t.onStatusChange?.("disconnected")},ce.onerror=()=>clearTimeout(he)}catch(ce){t.onStatusChange?.("disconnected"),ne(ce)}}),Z=()=>{a=!1,T(),A(),p=null,m.clear(),h.clear(),b.clear(),r?.close(1000,"Client disconnect"),r=null,t.onStatusChange?.("disconnected")},re=(q,ne,ce)=>{let he=!m.has(q);if(!m.has(q))m.set(q,new Set);if(m.get(q)?.add(ne),ce){if(!h.has(q))h.set(q,new Set);h.get(q)?.add(ce)}if(he&&r?.readyState===WebSocket.OPEN)k({type:"Subscribe",channels:[q]});return()=>{if(ce){let Be=h.get(q);if(Be?.delete(ce),Be?.size===0)h.delete(q)}let Q=m.get(q);if(Q){if(Q.delete(ne),Q.size===0){if(m.delete(q),r?.readyState===WebSocket.OPEN)k({type:"Unsubscribe",channels:[q]})}}}};return{connect:K,disconnect:Z,isConnected:()=>r?.readyState===WebSocket.OPEN,getStatus:x,setSessionKeypair:(q)=>{if(n=q??void 0,n&&r?.readyState===WebSocket.OPEN)w();else if(n&&(!r||r.readyState===WebSocket.CLOSED))K().catch((ne)=>{console.warn("WebSocket: Failed to connect after session update:",ne)})},orders:(q,ne,ce,he)=>{let Q=`orders:${q}:${ne}`;return re(Q,(Be)=>{try{let bt=Be,xt={orderId:bt.order_id,eventType:bt.event_type,timestamp:bt.timestamp,data:en(bt.data)};ce(xt)}catch(bt){console.error("WebSocket: Error processing order event",bt)}},he&&So("orders",tz,he))},orderbook:(q,ne,ce,he,Q)=>{if(!q||!ne||ce===void 0||!he)throw Error(`orderbook subscription requires all params: tradingPairId="${q}", tradingMode="${ne}", magnitude=${ce} (valid: ${Rf.join(", ")}), quotationMode="${he}" (valid: "BASE", "QUOTE")`);if(!Rf.includes(ce))throw Error(`Invalid magnitude: ${ce}. Must be one of: ${Rf.join(", ")}`);let Be=`orderbook:${q}:${ne}:${ce}:${he.toLowerCase()}`;return re(Be,(bt)=>{try{let xt=bt,Qe=xt.data,vt={tradingPairId:xt.trading_pair_id,tradingMode:xt.trading_mode,bids:(Qe?.bids||[]).map((wt)=>({price:wt.price,quantity:wt.quantity,orderCount:wt.order_count||0})),asks:(Qe?.asks||[]).map((wt)=>({price:wt.price,quantity:wt.quantity,orderCount:wt.order_count||0})),bestBid:Qe?.best_bid??void 0,bestAsk:Qe?.best_ask??void 0,bidVolume:Qe?.bid_volume||void 0,askVolume:Qe?.ask_volume||void 0,priceChange:Qe?.price_change?{side:Qe.price_change.side,oldPrice:Qe.price_change.old_price??void 0,newPrice:Qe.price_change.new_price??void 0,levelRemoved:Qe.price_change.level_removed||!1,levelAdded:Qe.price_change.level_added||!1}:void 0,baseDecimals:xt.base_decimals||0,quoteDecimals:xt.quote_decimals||0,timestamp:xt.timestamp||new Date().toISOString(),sequence:xt.sequence_number||0};Q(vt)}catch(xt){console.error("WebSocket: Error processing orderbook event",xt)}})},ohlcv:(q,ne,ce,he,Q)=>{let Be=Q===void 0?`ohlcv:${q}:${ne}:${ce}`:`ohlcv:${q}:${ne}:${ce}:${Q}`;return re(Be,(bt)=>{try{let xt=bt,{data:Qe,price_type:vt}=xt,wt=typeof vt==="string"&&vt!==""?vt:void 0,Hr={tradingPairId:xt.trading_pair_id,tradingMode:xt.trading_mode,interval:xt.interval,priceType:wt,candlestick:{T:Qe.period_start||0,t:Qe.period_end||0,o:Qe.open||"0",h:Qe.high||"0",l:Qe.low||"0",c:Qe.close||"0",v:Qe.volume||"0",s:xt.symbol,i:xt.interval,n:Qe.trades_count||0}};he(Hr)}catch(xt){console.error("WebSocket: Error processing OHLCV event",xt)}})},trades:(q,ne)=>{let ce=`trades:${q}`;return re(ce,(he)=>{try{let Q=he,Be=Q.data,bt={eventType:"trade",tradingPairId:Q.trading_pair_id,tradingMode:Q.trading_mode.toUpperCase(),data:{tradeId:Be.trade_id,price:Be.price,quantity:Be.quantity,makerSide:Be.maker_side.toUpperCase(),executedAt:Be.executed_at}};ne(bt)}catch(Q){console.error("WebSocket: Error processing trade event",Q)}})},movements:(q)=>re("movements",(ce)=>{try{let he=ce,Q=he.data,Be={eventType:"movement",userId:he.user_id,data:{id:Q.id,entryType:Q.entry_type,transactionType:Q.transaction_type,status:Q.status,token:Q.token??Q.token_address,tokenAddress:Q.token??Q.token_address,assetId:Q.asset_id,symbol:Q.symbol,amount:String(Q.amount),amountRaw:Q.amount_raw,balanceBefore:Q.balance_before!=null?String(Q.balance_before):void 0,balanceBeforeRaw:Q.balance_before_raw,balanceAfter:Q.balance_after!=null?String(Q.balance_after):void 0,balanceAfterRaw:Q.balance_after_raw,lockedBefore:Q.locked_before!=null?String(Q.locked_before):void 0,lockedBeforeRaw:Q.locked_before_raw,lockedAfter:Q.locked_after!=null?String(Q.locked_after):void 0,lockedAfterRaw:Q.locked_after_raw,referenceId:Q.reference_id,referenceType:Q.reference_type,description:Q.description,txHash:Q.tx_hash,blockNumber:Q.block_number,createdAt:Q.created_at,decimals:Q.decimals}};q(Be)}catch(he){console.error("WebSocket: Error processing movement event",he)}}),userOrders:(q,ne)=>re("orders",(he)=>{try{let Q=he,Be={orderId:Q.order_id,eventType:Q.event_type,timestamp:Q.timestamp,data:en(Q.data)};q(Be)}catch(Q){console.error("WebSocket: Error processing user order event",Q)}},ne&&So("orders",tz,ne)),balances:(q,ne)=>re("balances",(he)=>{try{if(!or(he))throw Error("Invalid balance event: payload must be an object");let Q={eventType:"balance_update",userId:le(he,"user_id"),data:dz(he.data)};q(Q)}catch(Q){console.error("WebSocket: Error processing balance event",Q)}},ne&&So("balances",Ese,ne)),conditionalOrders:(q,ne,ce)=>{if(!q)throw Error("conditionalOrders subscription requires a handler");if(ne!==void 0&&ne.length===0)throw Error("conditionalOrders tradingPairId cannot be empty");let he=ne?`conditional_orders:${ne}`:"conditional_orders";return re(he,(Q)=>{try{q(yse(Q))}catch(Be){console.error("WebSocket: Error processing conditional order event",Be)}},ce&&So("conditional orders",rz,ce))},twapOrders:(q,ne,ce)=>{if(!q)throw Error("twapOrders subscription requires a handler");if(ne!==void 0&&ne.length===0)throw Error("twapOrders tradingPairId cannot be empty");let he=ne?`twap_orders:${ne}`:"twap_orders";return re(he,(Q)=>{try{q(Tse(Q))}catch(Be){console.error("WebSocket: Error processing TWAP order event",Be)}},ce&&So("TWAP orders",uz,ce))},positions:(q,ne,ce)=>{if(!q)throw Error("positions subscription requires a handler");if(ne!==void 0&&ne.length===0)throw Error("positions tradingPairId cannot be empty");let he=ne?`positions:${ne}`:"positions";return re(he,(Q)=>{try{q(bse(Q))}catch(Be){console.error("WebSocket: Error processing position event",Be)}},ce&&So("positions",nz,ce))},liquidations:(q,ne,ce)=>{if(!q)throw Error("liquidations subscription requires a handler");if(ne!==void 0&&ne.length===0)throw Error("liquidations tradingPairId cannot be empty");let he=ne?`liquidations:${ne}`:"liquidations";return re(he,(Q)=>{try{q(xse(Q))}catch(Be){console.error("WebSocket: Error processing liquidation event",Be)}},ce&&So("liquidations",oz,ce))},account:(q,ne)=>{if(!q)throw Error("account subscription requires a handler");return re("account",(ce)=>{try{q(_se(ce))}catch(he){console.error("WebSocket: Error processing account event",he)}},ne&&So("account",iz,ne))},instruments:(q,ne,ce)=>{if(!q)throw Error("instruments subscription requires a handler");if(ne!==void 0&&ne.length===0)throw Error("instruments tradingPairId cannot be empty");let he=ne?`instrument:${ne}`:"instrument",Q=(Qe)=>{let vt=b.get(he);if(!vt)vt=new Map,b.set(he,vt);vt.set(Qe.tradingPairId,Qe)},Be=m.has(he),bt=!1,xt=re(he,(Qe)=>{try{let vt=vse(Qe);Q(vt),q(vt)}catch(vt){console.error("WebSocket: Error processing instrument event",vt)}},So("instrument",cz,(Qe)=>{let vt=Qe.map((wt)=>({tradingPairId:wt.tradingPairId,data:wt}));if(b.set(he,new Map(vt.map((wt)=>[wt.tradingPairId,wt]))),ce){ce(Qe);return}for(let wt of vt)q(wt)}));if(Be&&r?.readyState===WebSocket.OPEN){if(b.has(he))queueMicrotask(()=>{if(bt)return;let Qe=b.get(he);if(!Qe||r?.readyState!==WebSocket.OPEN)return;let vt=[...Qe.values()];if(ce){try{ce(vt.filter((wt)=>wt.data.isActive).map((wt)=>wt.data))}catch(wt){console.error("WebSocket: Error processing instrument baseline replay",wt)}return}for(let wt of vt)try{q(wt)}catch(Hr){console.error("WebSocket: Error processing instrument baseline replay",Hr)}})}return()=>{if(bt=!0,xt(),!m.has(he))b.delete(he)}},marketStats:(q,ne,ce)=>{if(!q)throw Error("marketStats subscription requires a tradingPairId");if(!ne)throw Error("marketStats subscription requires a handler");return re(`market_stats:${q}`,(he)=>{try{ne(wse(he))}catch(Q){console.error("WebSocket: Error processing market stats event",Q)}},ce&&So("market stats",sz,ce))},marketStatsAll:(q,ne)=>{if(!q)throw Error("marketStatsAll subscription requires a handler");return re("market_stats",(ce)=>{if(!or(ce)||!Array.isArray(ce.markets))return;try{q(Sse(ce))}catch(he){console.error("WebSocket: Error processing market stats all event",he)}},ne&&So("all-markets stats",az,ne))}}}var ia=Vr(q0(),1),SB=["token","accessToken","access_token","refreshToken","refresh_token","authToken","auth_token","bearerToken","bearer_token","jwtToken","jwt_token","apiKey","api_key","apikey","clientSecret","client_secret","clientId","client_id","secret","password","authorization","bearer","auth","credentials","credential","email","phone","phoneNumber","phone_number","ssn","socialSecurity","social_security","address","passport","passportNumber","passport_number","driversLicense","drivers_license","cardNumber","card_number","creditCard","credit_card","cvv","pin","signature","privateKey","private_key","publicKey","public_key","mnemonic","seed","salt","hash","certificate","cert","fingerprint","cookie","session","sessionId","session_id","sessionToken","session_token","ipAddress","ip_address","deviceId","device_id","userId","user_id","accountId","account_id"];function nd(e,t=5,r=0){if(r>=t)return"[Max depth reached]";if(e===null||e===void 0)return e;if(Array.isArray(e)){let o=e.slice(0,10).map((i)=>nd(i,t,r+1));if(e.length>10)o.push(`[... ${e.length-10} more items]`);return o}if(typeof e==="object"){let n={};for(let[o,i]of Object.entries(e)){let s=o.toLowerCase();if(SB.some((c)=>s.includes(c.toLowerCase())))n[o]="[REDACTED]";else if(typeof i==="string"&&i.length>500)n[o]=`${i.substring(0,500)}... [truncated]`;else n[o]=nd(i,t,r+1)}return n}if(typeof e==="string"){if(e.length>1000)return`${e.substring(0,1000)}... [truncated]`;return e}return e}class od extends Error{cause;suggestion;retryable=!1;timestamp;constructor(e,t){super(e);if(this.name=this.constructor.name,this.timestamp=Date.now(),t?.cause)this.cause=t.cause;if(t?.suggestion)this.suggestion=t.suggestion;if(t?.retryable!==void 0)this.retryable=t.retryable}toJSON(){return{name:this.name,code:this.code,message:this.message,suggestion:this.suggestion,retryable:this.retryable,timestamp:this.timestamp,cause:this.cause instanceof Error?this.cause.message:this.cause}}}class At extends od{code="INVALID_CONFIG";field;value;constructor(e,t,r,n){let o=t?`Check the '${t}' configuration parameter. ${Use(t)}`:"Review your SDK configuration and ensure all required fields are provided correctly.";super(e,{cause:n,suggestion:o,retryable:!1});this.field=t,this.value=r}toJSON(){let e;if(this.field){let t=this.field.toLowerCase();if(SB.some((n)=>t.includes(n.toLowerCase())))e="[REDACTED]";else e=nd(this.value)}else e=nd(this.value);return{...super.toJSON(),field:this.field,value:e}}}function Use(e){switch(e.toLowerCase()){case"walletclient":return"Ensure you're creating the wallet client with a valid account and chain configuration.";case"seirpcurl":return"Use 'https://evm-rpc-testnet.sei-apis.com' for testnet or 'https://evm-rpc.sei-apis.com' for mainnet.";case"wsurl":return"Use 'wss://ws-develop.apimonaco.xyz/ws' for testnet or 'wss://ws.apimonaco.xyz/ws' for mainnet.";case"network":return"Valid networks are: 'mainnet', 'development', 'staging', 'local'.";default:return"Refer to the SDK documentation for correct configuration format."}}class Cf extends od{code="INVALID_STATE";currentState;expectedState;constructor(e,t,r,n){let o=r?`${t?`Current state is '${t}', `:""}Expected state is '${r}'. Ensure operations are performed in the correct order.`:"Check that prerequisites are met before calling this method.";super(e,{cause:n,suggestion:o,retryable:!1});this.currentState=t,this.expectedState=r}toJSON(){return{...super.toJSON(),currentState:this.currentState,expectedState:this.expectedState}}}class Zt extends od{code="API_ERROR";endpoint;statusCode;responseBody;requestBody;requestId;retryAfter;constructor(e,t){let{suggestion:r,retryable:n}=Fse(t?.statusCode,e,t?.responseBody);super(e,{cause:t?.cause,suggestion:r,retryable:n});this.endpoint=t?.endpoint,this.statusCode=t?.statusCode,this.responseBody=t?.responseBody,this.requestBody=t?.requestBody,this.requestId=t?.requestId,this.retryAfter=t?.retryAfter}toJSON(){return{...super.toJSON(),endpoint:this.endpoint,statusCode:this.statusCode,responseBody:nd(this.responseBody),requestBody:nd(this.requestBody),requestId:this.requestId,retryAfter:this.retryAfter}}}function Fse(e,t,r){if(!e)return{suggestion:"Network request failed. Check your internet connection and try again.",retryable:!0};if(e===ia.StatusCodes.UNAUTHORIZED){if(t?.toLowerCase().includes("expired"))return{suggestion:"Access token has expired. Call sdk.refreshAuth() to get a new token, or call sdk.login() to re-authenticate.",retryable:!1};return{suggestion:"Authentication required. Call sdk.login(clientId) to authenticate before making this request.",retryable:!1}}if(e===ia.StatusCodes.FORBIDDEN)return{suggestion:"Access denied. Ensure your application has the required permissions and your client ID is valid.",retryable:!1};if(e===ia.StatusCodes.NOT_FOUND)return{suggestion:"Resource not found. Check that the ID or identifier is correct and the resource exists.",retryable:!1};if(e===ia.StatusCodes.CONFLICT)return{suggestion:"Resource conflict. The resource may have been modified. Refresh and try again.",retryable:!0};if(e===ia.StatusCodes.BAD_REQUEST){if(t?.toLowerCase().includes("insufficient balance"))return{suggestion:"Insufficient balance. Deposit more funds using sdk.vault.deposit() or reduce the order size.",retryable:!1};if(t?.toLowerCase().includes("invalid"))return{suggestion:"Invalid request parameters. Check the API documentation for correct parameter format and values.",retryable:!1};return{suggestion:"Bad request. Verify that all required parameters are provided and correctly formatted.",retryable:!1}}if(e===ia.StatusCodes.TOO_MANY_REQUESTS){let n;if(typeof r==="object"&&r!==null&&"retry_after"in r&&r.retry_after){let o=r.retry_after;n=` Wait ${String(o)} seconds before retrying.`}else n=" Wait a moment before retrying.";return{suggestion:`Rate limit exceeded.${n} Consider implementing exponential backoff for retries.`,retryable:!0}}if(e>=ia.StatusCodes.INTERNAL_SERVER_ERROR&&e<600)return{suggestion:"Server error occurred. This is likely a temporary issue. Try again in a few moments.",retryable:!0};return{suggestion:void 0,retryable:!1}}class Vi extends od{code="CONTRACT_ERROR";revertReason;transactionHash;contractAddress;constructor(e,t){let r=jse(t?.revertReason);super(e,{cause:t?.cause,suggestion:r,retryable:!1});this.revertReason=t?.revertReason,this.transactionHash=t?.transactionHash,this.contractAddress=t?.contractAddress}toJSON(){return{...super.toJSON(),revertReason:this.revertReason,transactionHash:this.transactionHash,contractAddress:this.contractAddress}}}function jse(e){if(!e)return"Smart contract execution failed. Check transaction parameters and try again.";let t=e.toLowerCase();if(t.includes("insufficient allowance"))return"Token allowance is insufficient. Call sdk.vault.approve() to increase the token allowance for the vault contract.";if(t.includes("insufficient balance"))return"Wallet balance is insufficient for this transaction. Ensure you have enough tokens and native currency for gas fees.";if(t.includes("nonce"))return"Transaction nonce error. This may be due to a pending transaction. Wait for pending transactions to complete or reset your account nonce.";if(t.includes("gas"))return"Transaction ran out of gas. Try increasing the gas limit for this transaction.";return}var qse={local:"http://localhost:8080",development:"https://develop.apimonaco.xyz",staging:"https://staging.apimonaco.xyz",mainnet:"https://api.monaco.xyz"},Hse={local:"ws://localhost:8085/ws",development:"wss://ws-develop.apimonaco.xyz/ws",staging:"wss://ws-staging.apimonaco.xyz/ws",mainnet:"wss://ws.apimonaco.xyz/ws"};function dT(e){return qse[e]}function lT(e){return Hse[e]}var ZA=Vr(q0(),1);var H0=256,G0;function V0(e=11){if(!G0||H0+e>512){G0="",H0=0;for(let t=0;t<256;t++)G0+=(256+Math.random()*256|0).toString(16).substring(1)}return G0.substring(H0,H0+++e)}function Z0(e){let{batch:t,chain:r,ccipRead:n,dataSuffix:o,key:i="base",name:s="Base Client",tokens:a,type:c="base"}=e,d=e.experimental_blockTag??(typeof r?.experimental_preconfirmationTime==="number"?"pending":void 0),l=r?.blockTime??12000,p=Math.min(Math.max(Math.floor(l/2),500),4000),m=e.pollingInterval??p,h=e.cacheTime??m,b=e.account?ze(e.account):void 0,{config:x,request:_,value:w}=e.transport({account:b,chain:r,pollingInterval:m}),A={...x,...w},v={account:b,batch:t,cacheTime:h,ccipRead:n,chain:r,dataSuffix:o,key:i,name:s,pollingInterval:m,request:_,tokens:a,transport:A,type:c,uid:V0(),...d?{experimental_blockTag:d}:{}};function T(P){return(k)=>{let O=k(P);for(let j in v)delete O[j];let N={...P,...O};for(let j in O){let R=P[j],K=O[j];if(vB(R)&&vB(K))N[j]={...R,...K}}return Object.assign(N,{extend:T(N)})}}return Object.assign(v,{extend:T(v)})}function vB(e){if(typeof e!=="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Qo(e,t){let r=(n={})=>t(e,n);for(let n of["call","calls","callWithPeriod","estimateGas","prepare","prepareRecipient","predict","simulate"])if(Object.hasOwn(t,n)){let o=t[n];r[n]=(i={})=>{if(o.length===1)return o(i);return o(e,i)}}for(let n of["extractEvent","extractEvents"])if(Object.hasOwn(t,n))r[n]=t[n];return r}Mr();rs();xn();ri();Ac();mn();Fe();Ge();os();function xd(e){if(!(e instanceof C))return!1;let t=e.walk((r)=>r instanceof bd);if(!(t instanceof bd))return!1;if(t.data?.errorName==="HttpError")return!0;if(t.data?.errorName==="ResolverError")return!0;if(t.data?.errorName==="ResolverNotContract")return!0;if(t.data?.errorName==="ResolverNotFound")return!0;if(t.data?.errorName==="ReverseAddressMismatch")return!0;if(t.data?.errorName==="UnsupportedResolverProfile")return!0;return!1}nm();xr();Fe();Jn();function Oy(e){if(e.length!==66)return null;if(e.indexOf("[")!==0)return null;if(e.indexOf("]")!==65)return null;let t=`0x${e.slice(1,65)}`;if(!Kt(t))return null;return t}function om(e){let t=new Uint8Array(32).fill(0);if(!e)return mt(t);let r=e.split(".");for(let n=r.length-1;n>=0;n-=1){let o=Oy(r[n]),i=o?Yn(o):St(Eo(r[n]),"bytes");t=St(fr([t,i]),"bytes")}return mt(t)}xr();function tL(e){return`[${e.slice(2)}]`}xr();Fe();Jn();function rL(e){let t=new Uint8Array(32).fill(0);if(!e)return mt(t);return Oy(e)||St(Eo(e))}function _d(e){let t=e.replace(/^\.|\.$/gm,"");if(t.length===0)return new Uint8Array(1);let r=new Uint8Array(Eo(t).byteLength+2),n=0,o=t.split(".");for(let i=0;i<o.length;i++){let s=Eo(o[i]);if(s.byteLength>255)s=Eo(tL(rL(o[i])));r[n]=s.length,r.set(s,n+1),n+=s.length+1}if(r.byteLength!==n+1)return r.slice(0,n+1);return r}function J(e,t,r){let n=e[t.name];if(typeof n==="function")return n;let o=e[r];if(typeof o==="function")return o;return(i)=>t(e,i)}rs();xn();ir();Ge();os();Mc();Fd();var Wae=3;function Nn(e,{abi:t,address:r,args:n,docsPath:o,functionName:i,sender:s}){let a=e instanceof ns?e:e instanceof C?e.walk((b)=>("data"in b))||e.walk():{},{code:c,data:d,details:l,message:p,shortMessage:m}=a,h=(()=>{if(e instanceof To)return new kE({functionName:i,cause:e});if([Wae,ss.code].includes(c)&&(d||l||p||m)||c===Xn.code&&l==="execution reverted"&&d)return new bd({abi:t,data:typeof d==="object"?d.data:d,functionName:i,message:a instanceof Cc?l:m??p,cause:e});return e})();return new rm(h,{abi:t,args:n,contractAddress:r,docsPath:o,functionName:i,sender:s})}ga();async function gt(e,t){let{abi:r,address:n,args:o,functionName:i,...s}=t,a=It({abi:r,args:o,functionName:i});try{let{data:c}=await J(e,Sn,"call")({...s,data:a,to:n});return Dr({abi:r,args:o,functionName:i,data:c||"0x"})}catch(c){throw Nn(c,{abi:r,address:n,args:o,docsPath:"/docs/contract/readContract",functionName:i})}}async function BL(e,t){let{blockNumber:r,blockTag:n,coinType:o,name:i,gatewayUrls:s,strict:a}=t,{chain:c}=e,d=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw Error("client chain not configured. universalResolverAddress is required.");return Qn({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),l=c?.ensTlds;if(l&&!l.some((m)=>i.endsWith(m)))return null;let p=(()=>{if(o!=null)return[om(i),BigInt(o)];return[om(i)]})();try{let m=It({abi:fT,functionName:"addr",args:p}),h={address:d,abi:K0,functionName:"resolveWithGateways",args:[Jt(_d(i)),m,s??[is]],blockNumber:r,blockTag:n},x=await J(e,gt,"readContract")(h);if(x[0]==="0x")return null;let _=yce({coinType:o,data:x[0],args:p});if(_==="0x")return null;if($r(_)==="0x00")return null;return _}catch(m){if(a)throw m;if(xd(m))return null;throw m}}function yce({coinType:e,data:t,args:r}){try{return Dr({abi:fT,args:r,functionName:"addr",data:t})}catch(n){if(e==null)throw n;let o=$r(t);if(et(o)===20)return Ao(o);throw n}}Ge();class oP extends C{constructor({data:e}){super("Unable to extract image from metadata. The metadata may be malformed or invalid.",{metaMessages:["- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.","",`Provided data: ${JSON.stringify(e)}`],name:"EnsAvatarInvalidMetadataError"})}}class Dc extends C{constructor({reason:e}){super(`ENS NFT avatar URI is invalid. ${e}`,{name:"EnsAvatarInvalidNftUriError"})}}class hm extends C{constructor({uri:e}){super(`Unable to resolve ENS avatar URI "${e}". The URI may be malformed, invalid, or does not respond with a valid image.`,{name:"EnsAvatarUriResolutionError"})}}class iP extends C{constructor({namespace:e}){super(`ENS NFT avatar namespace "${e}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}}var bce=/(?<protocol>https?:\/\/[^/]*|ipfs:\/|ipns:\/|ar:\/)?(?<root>\/)?(?<subpath>ipfs\/|ipns\/)?(?<target>[\w\-.]+)(?<subtarget>\/.*)?/,xce=/^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?<target>[\w\-.]+))?(?<subtarget>\/.*)?$/,_ce=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,wce=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;async function Sce(e){try{let t=await fetch(e,{method:"HEAD"});if(t.status===200)return t.headers.get("content-type")?.startsWith("image/");return!1}catch(t){if(typeof t==="object"&&typeof t.response<"u")return!1;if(!Object.hasOwn(globalThis,"Image"))return!1;return new Promise((r)=>{let n=new Image;n.onload=()=>{r(!0)},n.onerror=()=>{r(!1)},n.src=e})}}function LL(e,t){if(!e)return t;if(e.endsWith("/"))return e.slice(0,-1);return e}function sP({uri:e,gatewayUrls:t}){let r=_ce.test(e);if(r)return{uri:e,isOnChain:!0,isEncoded:r};let n=LL(t?.ipfs,"https://ipfs.io"),o=LL(t?.arweave,"https://arweave.net"),i=e.match(bce),{protocol:s,subpath:a,target:c,subtarget:d=""}=i?.groups||{},l=s==="ipns:/"||a==="ipns/",p=s==="ipfs:/"||a==="ipfs/"||xce.test(e);if(e.startsWith("http")&&!l&&!p){let h=e;if(t?.arweave)h=e.replace(/https:\/\/arweave.net/g,t?.arweave);return{uri:h,isOnChain:!1,isEncoded:!1}}if((l||p)&&c)return{uri:`${n}/${l?"ipns":"ipfs"}/${c}${d}`,isOnChain:!1,isEncoded:!1};if(s==="ar:/"&&c)return{uri:`${o}/${c}${d||""}`,isOnChain:!1,isEncoded:!1};let m=e.replace(wce,"");if(m.startsWith("<svg"))m=`data:image/svg+xml;base64,${btoa(m)}`;if(m.startsWith("data:")||m.startsWith("{"))return{uri:m,isOnChain:!0,isEncoded:!1};throw new hm({uri:e})}function aP(e){if(typeof e!=="object"||!("image"in e)&&!("image_url"in e)&&!("image_data"in e))throw new oP({data:e});return e.image||e.image_url||e.image_data}async function DL({gatewayUrls:e,uri:t}){try{let r=await fetch(t).then((o)=>o.json());return await Gy({gatewayUrls:e,uri:aP(r)})}catch{throw new hm({uri:t})}}async function Gy({gatewayUrls:e,uri:t}){let{uri:r,isOnChain:n}=sP({uri:t,gatewayUrls:e});if(n)return r;if(await Sce(r))return r;throw new hm({uri:t})}function UL(e){let t=e;if(t.startsWith("did:nft:"))t=t.replace("did:nft:","").replace(/_/g,"/");let[r,n,o]=t.split("/"),[i,s]=r.split(":"),[a,c]=n.split(":");if(!i||i.toLowerCase()!=="eip155")throw new Dc({reason:"Only EIP-155 supported"});if(!s)throw new Dc({reason:"Chain ID not found"});if(!c)throw new Dc({reason:"Contract address not found"});if(!o)throw new Dc({reason:"Token ID not found"});if(!a)throw new Dc({reason:"ERC namespace not found"});return{chainID:Number.parseInt(s,10),namespace:a.toLowerCase(),contractAddress:c,tokenID:o}}async function FL(e,{nft:t}){if(t.namespace==="erc721")return gt(e,{address:t.contractAddress,abi:[{name:"tokenURI",type:"function",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"tokenURI",args:[BigInt(t.tokenID)]});if(t.namespace==="erc1155")return gt(e,{address:t.contractAddress,abi:[{name:"uri",type:"function",stateMutability:"view",inputs:[{name:"_id",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"uri",args:[BigInt(t.tokenID)]});throw new iP({namespace:t.namespace})}async function jL(e,{gatewayUrls:t,record:r}){if(/eip155:/i.test(r))return vce(e,{gatewayUrls:t,record:r});return Gy({uri:r,gatewayUrls:t})}async function vce(e,{gatewayUrls:t,record:r}){let n=UL(r),o=await FL(e,{nft:n}),{uri:i,isOnChain:s,isEncoded:a}=sP({uri:o,gatewayUrls:t});if(s&&(i.includes("data:application/json;base64,")||i.startsWith("{"))){let d=a?atob(i.replace("data:application/json;base64,","")):i,l=JSON.parse(d);return Gy({uri:aP(l),gatewayUrls:t})}let c=n.tokenID;if(n.namespace==="erc1155")c=c.replace("0x","").padStart(64,"0");return DL({gatewayUrls:t,uri:i.replace(/(?:0x)?{id}/,c)})}Mr();rs();xn();Ac();Fe();nm();async function Vy(e,t){let{blockNumber:r,blockTag:n,key:o,name:i,gatewayUrls:s,strict:a}=t,{chain:c}=e,d=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw Error("client chain not configured. universalResolverAddress is required.");return Qn({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),l=c?.ensTlds;if(l&&!l.some((p)=>i.endsWith(p)))return null;try{let p={address:d,abi:K0,args:[Jt(_d(i)),It({abi:pT,functionName:"text",args:[om(i),o]}),s??[is]],functionName:"resolveWithGateways",blockNumber:r,blockTag:n},h=await J(e,gt,"readContract")(p);if(h[0]==="0x")return null;let b=Dr({abi:pT,functionName:"text",data:h[0]});return b===""?null:b}catch(p){if(a)throw p;if(xd(p))return null;throw p}}async function qL(e,{blockNumber:t,blockTag:r,assetGatewayUrls:n,name:o,gatewayUrls:i,strict:s,universalResolverAddress:a}){let c=await J(e,Vy,"getEnsText")({blockNumber:t,blockTag:r,key:"avatar",name:o,universalResolverAddress:a,gatewayUrls:i,strict:s});if(!c)return null;try{return await jL(e,{record:c,gatewayUrls:n})}catch{return null}}Mr();Ac();nm();async function HL(e,t){let{address:r,blockNumber:n,blockTag:o,coinType:i=60n,gatewayUrls:s,strict:a}=t,{chain:c}=e,d=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw Error("client chain not configured. universalResolverAddress is required.");return Qn({blockNumber:n,chain:c,contract:"ensUniversalResolver"})})();try{let l={address:d,abi:EB,args:[r,i,s??[is]],functionName:"reverseWithGateways",blockNumber:n,blockTag:o},p=J(e,gt,"readContract"),[m]=await p(l);return m||null}catch(l){if(a)throw l;if(xd(l))return null;throw l}}Ac();Fe();async function GL(e,t){let{blockNumber:r,blockTag:n,name:o}=t,{chain:i}=e,s=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!i)throw Error("client chain not configured. universalResolverAddress is required.");return Qn({blockNumber:r,chain:i,contract:"ensUniversalResolver"})})(),a=i?.ensTlds;if(a&&!a.some((d)=>o.endsWith(d)))throw Error(`${o} is not a valid ENS TLD (${a?.join(", ")}) for chain "${i.name}" (id: ${i.id}).`);let[c]=await J(e,gt,"readContract")({address:s,abi:[{inputs:[{type:"bytes"}],name:"findResolver",outputs:[{type:"address"},{type:"bytes32"},{type:"uint256"}],stateMutability:"view",type:"function"}],functionName:"findResolver",args:[Jt(_d(o))],blockNumber:r,blockTag:n});return c}ga();Ge();Fe();QE();ps();ci();async function VL(e,t){let{account:r=e.account,blockNumber:n,blockTag:o="latest",blobs:i,data:s,gas:a,gasPrice:c,maxFeePerBlobGas:d,maxFeePerGas:l,maxPriorityFeePerGas:p,to:m,value:h,...b}=t,x=r?ze(r):void 0;try{Sr(t);let w=(typeof n==="bigint"?G(n):void 0)||o,A=e.chain?.formatters?.transactionRequest?.format,T=(A||jr)({...ro(b,{format:A}),account:x,blobs:i,data:s,gas:a,gasPrice:c,maxFeePerBlobGas:d,maxFeePerGas:l,maxPriorityFeePerGas:p,to:m,value:h},"createAccessList"),P=await e.request({method:"eth_createAccessList",params:[T,w]});if(P.error)throw new C(P.error,{details:P.error});return{accessList:P.accessList,gasUsed:BigInt(P.gasUsed)}}catch(_){throw jy(_,{...t,account:x,chain:e.chain})}}function ya(e,{method:t}){let r={};if(e.transport.type==="fallback")e.transport.onResponse?.(({method:n,response:o,status:i,transport:s})=>{if(i==="success"&&t===n)r[o]=s.request});return(n)=>r[n]||e.request}async function ZL(e){let t=ya(e,{method:"eth_newBlockFilter"}),r=await e.request({method:"eth_newBlockFilter"});return{id:r,request:t(r),type:"block"}}ir();Ge();class cP extends C{constructor(e){super(`Filter type "${e}" is not supported.`,{name:"FilterTypeNotSupportedError"})}}xr();Jn();Jf();Qi();Zi();la();var WL="/docs/contract/encodeEventTopics";function ui(e){let{abi:t,eventName:r,args:n}=e,o=t[0];if(r){let c=bn({abi:t,name:r});if(!c)throw new Q0(r,{docsPath:WL});o=c}if(o.type!=="event")throw new Q0(void 0,{docsPath:WL});let i=[];if(n&&"inputs"in o){let c=o.inputs?.filter((l)=>("indexed"in l)&&l.indexed),d=Array.isArray(n)?n:Object.values(n).length>0?c?.map((l)=>n[l.name])??[]:[];if(d.length>0)i=c?.map((l,p)=>{if(Array.isArray(d[p]))return d[p].map((m,h)=>KL({param:l,value:d[p][h]}));return typeof d[p]<"u"&&d[p]!==null?KL({param:l,value:d[p]}):null})??[]}if(o.anonymous)return i;let s=dr(o);return[da(s),...i]}function KL({param:e,value:t}){if(e.type==="string"||e.type==="bytes")return St(Yn(t));if(e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/))throw new cP(e.type);return nn([e],[t])}Fe();async function Zy(e,t){let{address:r,abi:n,args:o,eventName:i,fromBlock:s,strict:a,toBlock:c}=t,d=ya(e,{method:"eth_newFilter"}),l=i?ui({abi:n,args:o,eventName:i}):void 0,p=await e.request({method:"eth_newFilter",params:[{address:r,fromBlock:typeof s==="bigint"?G(s):s,toBlock:typeof c==="bigint"?G(c):c,topics:l}]});return{abi:n,args:o,eventName:i,id:p,request:d(p),strict:Boolean(a),type:"event"}}Fe();async function Wy(e,{address:t,args:r,event:n,events:o,fromBlock:i,strict:s,toBlock:a}={}){let c=o??(n?[n]:void 0),d=ya(e,{method:"eth_newFilter"}),l=[];if(c){if(l=[c.flatMap((h)=>ui({abi:[h],eventName:h.name,args:r}))],n)l=l[0]}let p=await e.request({method:"eth_newFilter",params:[{address:t,fromBlock:typeof i==="bigint"?G(i):i,toBlock:typeof a==="bigint"?G(a):a,...l.length?{topics:l}:{}}]});return{abi:c,args:r,eventName:n?n.name:void 0,fromBlock:i,id:p,request:d(p),strict:Boolean(s),toBlock:a,type:"event"}}async function Ky(e){let t=ya(e,{method:"eth_newPendingTransactionFilter"}),r=await e.request({method:"eth_newPendingTransactionFilter"});return{id:r,request:t(r),type:"transaction"}}xn();Ge();ri();Jn();function Yy(e){let t=St(`0x${e.substring(4)}`).substring(26);return Yi(`0x${t}`)}mn();lr();Fe();async function a9({hash:e,signature:t}){let r=Kt(e)?e:Jt(e);await Promise.resolve().then(() => gm());return`0x${(()=>{if(typeof t==="object"&&"r"in t&&"s"in t){let{r:d,s:l,v:p,yParity:m}=t,h=Number(m??p),b=s9(h);return new hs.Signature(er(d),er(l)).addRecoveryBit(b)}let s=Kt(t)?t:Jt(t);if(et(s)!==65)throw Error("invalid signature length");let a=Yt(`0x${s.slice(130)}`),c=s9(a);return hs.Signature.fromCompact(s.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function s9(e){if(e===0||e===1)return e;if(e===27)return 0;if(e===28)return 1;throw Error("Invalid yParityOrV value")}async function ym({hash:e,signature:t}){return Yy(await a9({hash:e,signature:t}))}xr();Fe();Ge();uy();xr();Fe();function gs(e,t="hex"){let r=c9(e),n=sd(new Uint8Array(r.length));if(r.encode(n),t==="hex")return mt(n.bytes);return n.bytes}function c9(e){if(Array.isArray(e))return Cce(e.map((t)=>c9(t)));return Mce(e)}function Cce(e){let t=e.reduce((o,i)=>o+i.length,0),r=u9(t);return{length:(()=>{if(t<=55)return 1+t;return 1+r+t})(),encode(o){if(t<=55)o.pushByte(192+t);else if(o.pushByte(247+r),r===1)o.pushUint8(t);else if(r===2)o.pushUint16(t);else if(r===3)o.pushUint24(t);else o.pushUint32(t);for(let{encode:i}of e)i(o)}}}function Mce(e){let t=typeof e==="string"?pr(e):e,r=u9(t.length);return{length:(()=>{if(t.length===1&&t[0]<128)return 1;if(t.length<=55)return 1+t.length;return 1+r+t.length})(),encode(o){if(t.length===1&&t[0]<128)o.pushBytes(t);else if(t.length<=55)o.pushByte(128+t.length),o.pushBytes(t);else{if(o.pushByte(183+r),r===1)o.pushUint8(t.length);else if(r===2)o.pushUint16(t.length);else if(r===3)o.pushUint24(t.length);else o.pushUint32(t.length);o.pushBytes(t)}}}}function u9(e){if(e<256)return 1;if(e<65536)return 2;if(e<16777216)return 3;if(e<4294967296)return 4;throw new C("Length is too large.")}Jn();function Jy(e){let{chainId:t,nonce:r,to:n}=e,o=e.contractAddress??e.address,i=St(Qt(["0x05",gs([t?G(t):"0x",o,r?G(r):"0x"])]));if(n==="bytes")return pr(i);return i}async function ba(e){let{authorization:t,signature:r}=e;return ym({hash:Jy(t),signature:r??t})}Fe();Ry();gd();Ge();on();class hP extends C{constructor(e,{account:t,docsPath:r,chain:n,data:o,gas:i,gasPrice:s,maxFeePerGas:a,maxPriorityFeePerGas:c,nonce:d,to:l,value:p}){let m=Ic({from:t?.address,to:l,value:typeof p<"u"&&`${hd(p)} ${n?.nativeCurrency?.symbol||"ETH"}`,data:o,gas:i,gasPrice:typeof s<"u"&&`${mr(s)} gwei`,maxFeePerGas:typeof a<"u"&&`${mr(a)} gwei`,maxPriorityFeePerGas:typeof c<"u"&&`${mr(c)} gwei`,nonce:d});super(e.shortMessage,{cause:e,docsPath:r,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Estimate Gas Arguments:",m].filter(Boolean),name:"EstimateGasExecutionError"});Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}ls();mm();function d9(e,{docsPath:t,...r}){let n=(()=>{let o=ha(e,r);if(o instanceof Co)return e;return o})();return new hP(n,{docsPath:t,...r})}ps();Hy();ci();gd();Ge();class bm extends C{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class Uc extends C{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class gP extends C{constructor({maxPriorityFeePerGas:e}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${mr(e)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}lr();Ge();class Fc extends C{constructor({blockHash:e,blockNumber:t}){let r="Block";if(e)r=`Block at hash "${e}"`;if(t)r=`Block at number "${t}"`;super(`${r} could not be found.`,{name:"BlockNotFoundError"})}}Fe();lr();var yP={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function Yd(e,t){let r={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,...e.blockTimestamp!=null&&{blockTimestamp:BigInt(e.blockTimestamp)},chainId:e.chainId?Yt(e.chainId):void 0,gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,maxFeePerBlobGas:e.maxFeePerBlobGas?BigInt(e.maxFeePerBlobGas):void 0,maxFeePerGas:e.maxFeePerGas?BigInt(e.maxFeePerGas):void 0,maxPriorityFeePerGas:e.maxPriorityFeePerGas?BigInt(e.maxPriorityFeePerGas):void 0,nonce:e.nonce?Yt(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?yP[e.type]:void 0,typeHex:e.type?e.type:void 0,value:e.value?BigInt(e.value):void 0,v:e.v?BigInt(e.v):void 0};if(e.authorizationList)r.authorizationList=$ce(e.authorizationList);if(r.yParity=(()=>{if(e.yParity)return Number(e.yParity);if(typeof r.v==="bigint"){if(r.v===0n||r.v===27n)return 0;if(r.v===1n||r.v===28n)return 1;if(r.v>=35n)return r.v%2n===0n?1:0}return})(),r.type==="legacy")delete r.accessList,delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas,delete r.yParity;if(r.type==="eip2930")delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas;if(r.type==="eip1559")delete r.maxFeePerBlobGas;return r}function $ce(e){return e.map((t)=>({address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce),r:t.r,s:t.s,yParity:Number(t.yParity)}))}function Jd(e,t){let r=(e.transactions??[]).map((n)=>{if(typeof n==="string")return n;return Yd(n)});return{...e,baseFeePerGas:e.baseFeePerGas?BigInt(e.baseFeePerGas):null,blobGasUsed:e.blobGasUsed?BigInt(e.blobGasUsed):void 0,difficulty:e.difficulty?BigInt(e.difficulty):void 0,excessBlobGas:e.excessBlobGas?BigInt(e.excessBlobGas):void 0,gasLimit:e.gasLimit?BigInt(e.gasLimit):void 0,gasUsed:e.gasUsed?BigInt(e.gasUsed):void 0,hash:e.hash?e.hash:null,logsBloom:e.logsBloom?e.logsBloom:null,nonce:e.nonce?e.nonce:null,number:e.number?BigInt(e.number):null,size:e.size?BigInt(e.size):void 0,timestamp:e.timestamp?BigInt(e.timestamp):void 0,transactions:r,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}async function ar(e,{blockHash:t,blockNumber:r,blockTag:n=e.experimental_blockTag??"latest",includeTransactions:o}={}){let i=o??!1,s=r!==void 0?G(r):void 0,a=null;if(t)a=await e.request({method:"eth_getBlockByHash",params:[t,i]},{dedupe:!0});else a=await e.request({method:"eth_getBlockByNumber",params:[s||n,i]},{dedupe:Boolean(s)});if(!a)throw new Fc({blockHash:t,blockNumber:r});return(e.chain?.formatters?.block?.format||Jd)(a,"getBlock")}async function Qd(e){let t=await e.request({method:"eth_gasPrice"});return BigInt(t)}async function l9(e,t){return bP(e,t)}async function bP(e,t){let{block:r,chain:n=e.chain,request:o}=t||{};try{let i=n?.fees?.maxPriorityFeePerGas??n?.fees?.defaultPriorityFee;if(typeof i==="function"){let a=r||await J(e,ar,"getBlock")({}),c=await i({block:a,client:e,request:o});if(c===null)throw Error();return c}if(typeof i<"u")return i;let s=await e.request({method:"eth_maxPriorityFeePerGas"});return er(s)}catch{let[i,s]=await Promise.all([r?Promise.resolve(r):J(e,ar,"getBlock")({}),J(e,Qd,"getGasPrice")({})]);if(typeof i.baseFeePerGas!=="bigint")throw new Uc;let a=s-i.baseFeePerGas;if(a<0n)return 0n;return a}}async function p9(e,t){return Qy(e,t)}async function Qy(e,t){let{block:r,chain:n=e.chain,request:o,type:i="eip1559"}=t||{},s=await(async()=>{if(typeof n?.fees?.baseFeeMultiplier==="function")return n.fees.baseFeeMultiplier({block:r,client:e,request:o});return n?.fees?.baseFeeMultiplier??1.2})();if(s<1)throw new bm;let c=10**(s.toString().split(".")[1]?.length??0),d=(m)=>m*BigInt(Math.round(s*c))/BigInt(c),l=r?r:await J(e,ar,"getBlock")({});if(typeof n?.fees?.estimateFeesPerGas==="function"){let m=await n.fees.estimateFeesPerGas({block:r,client:e,multiply:d,request:o,type:i});if(m!==null)return m}if(i==="eip1559"){if(typeof l.baseFeePerGas!=="bigint")throw new Uc;let m=typeof o?.maxPriorityFeePerGas==="bigint"?o.maxPriorityFeePerGas:await bP(e,{block:l,chain:n,request:o}),h=d(l.baseFeePerGas);return{maxFeePerGas:o?.maxFeePerGas??h+m,maxPriorityFeePerGas:m}}return{gasPrice:o?.gasPrice??d(await J(e,Qd,"getGasPrice")({}))}}Lc();lr();async function Xd(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:i}){let s=Bn({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:i}),a=await e.request({method:"eth_getTransactionCount",params:[t,s]},{dedupe:typeof n==="bigint"||r!==void 0});return Yt(a)}on();xr();Fe();function el(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]==="string"?"hex":"bytes"),n=typeof e.blobs[0]==="string"?e.blobs.map((i)=>pr(i)):e.blobs,o=[];for(let i of n)o.push(Uint8Array.from(t.blobToKzgCommitment(i)));return r==="bytes"?o:o.map((i)=>mt(i))}xr();Fe();function tl(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]==="string"?"hex":"bytes"),n=typeof e.blobs[0]==="string"?e.blobs.map((s)=>pr(s)):e.blobs,o=typeof e.commitments[0]==="string"?e.commitments.map((s)=>pr(s)):e.commitments,i=[];for(let s=0;s<n.length;s++){let a=n[s],c=o[s];i.push(Uint8Array.from(t.computeBlobKzgProof(a,c)))}return r==="bytes"?i:i.map((s)=>mt(s))}Fe();ay();function Nce(e,t,r,n){if(typeof e.setBigUint64==="function")return e.setBigUint64(t,r,n);let o=BigInt(32),i=BigInt(4294967295),s=Number(r>>o&i),a=Number(r&i),c=n?4:0,d=n?0:4;e.setUint32(t+c,s,n),e.setUint32(t+d,a,n)}function f9(e,t,r){return e&t^~e&r}function m9(e,t,r){return e&t^e&r^t&r}class xP extends jf{constructor(e,t,r,n){super();this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=iy(this.buffer)}update(e){id(this),e=Ff(e),Tc(e);let{view:t,buffer:r,blockLen:n}=this,o=e.length;for(let i=0;i<o;){let s=Math.min(n-this.pos,o-i);if(s===n){let a=iy(e);for(;n<=o-i;i+=n)this.process(a,i);continue}if(r.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===n)this.process(t,0),this.pos=0}return this.length+=e.length,this.roundClean(),this}digestInto(e){id(this),oy(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:o}=this,{pos:i}=this;if(t[i++]=128,ca(this.buffer.subarray(i)),this.padOffset>n-i)this.process(r,0),i=0;for(let l=i;l<n;l++)t[l]=0;Nce(r,n-8,BigInt(this.length*8),o),this.process(r,0);let s=iy(e),a=this.outputLen;if(a%4)throw Error("_sha2: outputLen should be aligned to 32bit");let c=a/4,d=this.get();if(c>d.length)throw Error("_sha2: outputLen bigger than state");for(let l=0;l<c;l++)s.setUint32(4*l,d[l],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:r,length:n,finished:o,destroyed:i,pos:s}=this;if(e.destroyed=i,e.finished=o,e.length=n,e.pos=s,n%t)e.buffer.set(r);return e}clone(){return this._cloneInto()}}var ys=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);ay();var zce=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),xa=new Uint32Array(64);class _P extends xP{constructor(e=32){super(64,e,8,!1);this.A=ys[0]|0,this.B=ys[1]|0,this.C=ys[2]|0,this.D=ys[3]|0,this.E=ys[4]|0,this.F=ys[5]|0,this.G=ys[6]|0,this.H=ys[7]|0}get(){let{A:e,B:t,C:r,D:n,E:o,F:i,G:s,H:a}=this;return[e,t,r,n,o,i,s,a]}set(e,t,r,n,o,i,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=s|0,this.H=a|0}process(e,t){for(let l=0;l<16;l++,t+=4)xa[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let p=xa[l-15],m=xa[l-2],h=Po(p,7)^Po(p,18)^p>>>3,b=Po(m,17)^Po(m,19)^m>>>10;xa[l]=b+xa[l-7]+h+xa[l-16]|0}let{A:r,B:n,C:o,D:i,E:s,F:a,G:c,H:d}=this;for(let l=0;l<64;l++){let p=Po(s,6)^Po(s,11)^Po(s,25),m=d+p+f9(s,a,c)+zce[l]+xa[l]|0,b=(Po(r,2)^Po(r,13)^Po(r,22))+m9(r,n,o)|0;d=c,c=a,a=s,s=i+m|0,i=o,o=n,n=r,r=m+b|0}r=r+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,d=d+this.H|0,this.set(r,n,o,i,s,a,c,d)}roundClean(){ca(xa)}destroy(){this.set(0,0,0,0,0,0,0,0),ca(this.buffer)}}var h9=sy(()=>new _P);var g9=h9;xr();Fe();function y9(e,t){let r=t||"hex",n=g9(Kt(e,{strict:!1})?Yn(e):e);if(r==="bytes")return n;return Jt(n)}function b9(e){let{commitment:t,version:r=1}=e,n=e.to??(typeof t==="string"?"hex":"bytes"),o=y9(t,"bytes");return o.set([r],0),n==="bytes"?o:mt(o)}function Xy(e){let{commitments:t,version:r}=e,n=e.to??(typeof t[0]==="string"?"hex":"bytes"),o=[];for(let i of t)o.push(b9({commitment:i,to:n,version:r}));return o}var x9=32,_9=4096,w9=131072,wP=761855;var eb=1;Ge();class SP extends C{constructor({maxSize:e,size:t}){super("Blob size is too large.",{metaMessages:[`Max: ${e} bytes`,`Given: ${t} bytes`],name:"BlobSizeTooLargeError"})}}class xm extends C{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class vP extends C{constructor({hash:e,size:t}){super(`Versioned hash "${e}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${t}`],name:"InvalidVersionedHashSizeError"})}}class TP extends C{constructor({hash:e,version:t}){super(`Versioned hash "${e}" version is invalid.`,{metaMessages:[`Expected: ${eb}`,`Received: ${t}`],name:"InvalidVersionedHashVersionError"})}}uy();mn();xr();Fe();function S9(e){let t=e.to??(typeof e.data==="string"?"hex":"bytes"),r=typeof e.data==="string"?pr(e.data):e.data,n=et(r);if(!n)throw new xm;if(n>wP)throw new SP({maxSize:wP,size:n});let o=[],i=!0,s=0;while(i){let a=sd(new Uint8Array(w9)),c=0;while(c<_9){let d=r.slice(s,s+(x9-1));if(a.pushByte(0),a.pushBytes(d),d.length<31){a.pushByte(128),i=!1;break}c++,s+=31}o.push(a)}return t==="bytes"?o.map((a)=>a.bytes):o.map((a)=>mt(a.bytes))}function tb(e){let{data:t,kzg:r,to:n}=e,o=e.blobs??S9({data:t,to:n}),i=e.commitments??el({blobs:o,kzg:r,to:n}),s=e.proofs??tl({blobs:o,commitments:i,kzg:r,to:n}),a=[];for(let c=0;c<o.length;c++)a.push({blob:o[c],commitment:i[c],proof:s[c]});return a}Ec();ci();on();function rb(e){if(e.type)return e.type;if(typeof e.authorizationList<"u")return"eip7702";if(typeof e.blobs<"u"||typeof e.blobVersionedHashes<"u"||typeof e.maxFeePerBlobGas<"u"||typeof e.sidecars<"u")return"eip4844";if(typeof e.maxFeePerGas<"u"||typeof e.maxPriorityFeePerGas<"u")return"eip1559";if(typeof e.gasPrice<"u"){if(typeof e.accessList<"u")return"eip2930";return"legacy"}throw new EE({transaction:e})}on();ls();on();mm();function _a(e,{docsPath:t,...r}){let n=(()=>{let o=ha(e,r);if(o instanceof Co)return e;return o})();return new AE(n,{docsPath:t,...r})}ps();ci();lr();async function qr(e){let t=await e.request({method:"eth_chainId"},{dedupe:!0});return Yt(t)}async function rl(e,t){let{account:r=e.account,accessList:n,authorizationList:o,chain:i=e.chain,blobVersionedHashes:s,blobs:a,data:c,gas:d,gasPrice:l,maxFeePerBlobGas:p,maxFeePerGas:m,maxPriorityFeePerGas:h,nonce:b,nonceManager:x,to:_,type:w,value:A,...v}=t,T=await(async()=>{if(!r)return b;if(!x)return b;if(typeof b<"u")return b;let N=ze(r),j=i?i.id:await J(e,qr,"getChainId")({});return await x.consume({address:N.address,chainId:j,client:e})})();Sr(t);let P=i?.formatters?.transactionRequest?.format,O=(P||jr)({...ro(v,{format:P}),account:r?ze(r):void 0,accessList:n,authorizationList:o,blobs:a,blobVersionedHashes:s,data:c,gas:d,gasPrice:l,maxFeePerBlobGas:p,maxFeePerGas:m,maxPriorityFeePerGas:h,nonce:T,to:_,type:w,value:A},"fillTransaction");try{let N=await e.request({method:"eth_fillTransaction",params:[O]}),R=(i?.formatters?.transaction?.format||Yd)(N.tx);delete R.blockHash,delete R.blockNumber,delete R.r,delete R.s,delete R.transactionIndex,delete R.v,delete R.yParity,R.data=R.input;let K=typeof R.feePayerSignature<"u"&&R.feePayerSignature!==null;if(K&&typeof T<"u"&&R.nonce!==T)throw new em({filledNonce:R.nonce,requestedNonce:T});if(!K){if(R.gas)R.gas=t.gas??R.gas;if(R.gasPrice)R.gasPrice=t.gasPrice??R.gasPrice;if(R.maxFeePerBlobGas)R.maxFeePerBlobGas=t.maxFeePerBlobGas??R.maxFeePerBlobGas;if(R.maxFeePerGas)R.maxFeePerGas=t.maxFeePerGas??R.maxFeePerGas;if(R.maxPriorityFeePerGas)R.maxPriorityFeePerGas=t.maxPriorityFeePerGas??R.maxPriorityFeePerGas;if(typeof R.nonce<"u")R.nonce=t.nonce??R.nonce;let Z=await(async()=>{if(typeof i?.fees?.baseFeeMultiplier==="function"){let ee=await J(e,ar,"getBlock")({});return i.fees.baseFeeMultiplier({block:ee,client:e,request:t})}return i?.fees?.baseFeeMultiplier??1.2})();if(Z<1)throw new bm;let pe=10**(Z.toString().split(".")[1]?.length??0),U=(ee)=>ee*BigInt(Math.round(Z*pe))/BigInt(pe);if(R.maxFeePerGas&&!t.maxFeePerGas)R.maxFeePerGas=U(R.maxFeePerGas);if(R.gasPrice&&!t.gasPrice)R.gasPrice=U(R.gasPrice)}return{raw:N.raw,transaction:{from:O.from,...R},...N.capabilities?{capabilities:N.capabilities}:{}}}catch(N){throw _a(N,{...t,chain:e.chain})}}var _m=["blobVersionedHashes","chainId","fees","gas","nonce","type"],v9=new Map,EP=new Cn(128);async function di(e,t){let r=t;r.account??=e.account,r.parameters??=_m;let{account:n,chain:o=e.chain,nonceManager:i,parameters:s}=r,a=(()=>{if(typeof o?.prepareTransactionRequest==="function")return{fn:o.prepareTransactionRequest,runAt:["beforeFillTransaction"]};if(Array.isArray(o?.prepareTransactionRequest))return{fn:o.prepareTransactionRequest[0],runAt:o.prepareTransactionRequest[1].runAt};return})(),c;async function d(){if(c)return c;if(typeof r.chainId<"u")return r.chainId;if(o)return o.id;return c=await J(e,qr,"getChainId")({}),c}let l=n?ze(n):n,p=r.nonce;if(a?.fn&&a.runAt?.includes("beforeFillTransaction")){r=await a.fn({...r,chain:o},{client:e,phase:"beforeFillTransaction"}),p??=r.nonce;let T=r.account??r.from;l=T?ze(T):void 0}if(s.includes("nonce")&&typeof p>"u"&&l&&i){let T=await d();p=await i.consume({address:l.address,chainId:T,client:e})}let h=(()=>{if((s.includes("blobVersionedHashes")||s.includes("sidecars"))&&r.kzg&&r.blobs)return!1;if(s.length>0&&"feePayer"in r&&r.feePayer&&!(("feePayerSignature"in r)&&r.feePayerSignature))return!0;if(EP.get(e.uid)===!1)return!1;if(!["fees","gas"].some((P)=>s.includes(P)))return!1;if(s.includes("chainId")&&typeof r.chainId!=="number")return!0;if(s.includes("nonce")&&typeof p!=="number")return!0;if(s.includes("fees")&&typeof r.gasPrice!=="bigint"&&(typeof r.maxFeePerGas!=="bigint"||typeof r.maxPriorityFeePerGas!=="bigint"))return!0;if(s.includes("gas")&&typeof r.gas!=="bigint")return!0;return!1})()?await J(e,rl,"fillTransaction")({...r,nonce:p}).then((T)=>{let{chainId:P,from:k,gas:O,gasPrice:N,nonce:j,maxFeePerBlobGas:R,maxFeePerGas:K,maxPriorityFeePerGas:Z,type:re,...pe}=T.transaction,U="feeToken"in pe?pe.feeToken:void 0,ee="feePayerSignature"in pe&&pe.feePayerSignature!==null&&typeof pe.feePayerSignature<"u",me=typeof U<"u"&&U!==null&&(!("feeToken"in r)||ee);return EP.set(e.uid,!0),{...r,...k?{from:k}:{},...re&&!r.type?{type:re}:{},...typeof P<"u"?{chainId:P}:{},...typeof O<"u"?{gas:O}:{},...typeof N<"u"?{gasPrice:N}:{},...typeof j<"u"?{nonce:j}:{},...typeof R<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxFeePerBlobGas:R}:{},...typeof K<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxFeePerGas:K}:{},...typeof Z<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxPriorityFeePerGas:Z}:{},..."nonceKey"in pe&&typeof pe.nonceKey<"u"?{nonceKey:pe.nonceKey}:{},..."keyAuthorization"in pe&&typeof pe.keyAuthorization<"u"&&pe.keyAuthorization!==null&&!("keyAuthorization"in r)?{keyAuthorization:pe.keyAuthorization}:{},..."feePayerSignature"in pe&&typeof pe.feePayerSignature<"u"&&pe.feePayerSignature!==null?{feePayerSignature:pe.feePayerSignature}:{},...me?{feeToken:U}:{},...T.capabilities?{_capabilities:T.capabilities}:{}}}).catch((T)=>{let P=T;if(P.name!=="TransactionExecutionError")return r;if(P.walk?.((j)=>j instanceof em))throw T;if(P.walk?.((j)=>j.name==="ExecutionRevertedError"))throw T;if(P.walk?.((j)=>{let R=j;return R.name==="MethodNotFoundRpcError"||R.name==="MethodNotSupportedRpcError"||R.message?.includes("eth_fillTransaction is not available")}))EP.set(e.uid,!1);return r}):r;p??=h.nonce,r={...h,...l?{from:l?.address}:{},...typeof p<"u"?{nonce:p}:{}};let{blobs:b,gas:x,kzg:_,type:w}=r;if(a?.fn&&a.runAt?.includes("beforeFillParameters"))r=await a.fn({...r,chain:o},{client:e,phase:"beforeFillParameters"});let A;async function v(){if(A)return A;return A=await J(e,ar,"getBlock")({blockTag:"latest"}),A}if(s.includes("nonce")&&typeof p>"u"&&l&&!i)r.nonce=await J(e,Xd,"getTransactionCount")({address:l.address,blockTag:"pending"});if((s.includes("blobVersionedHashes")||s.includes("sidecars"))&&b&&_){let T=el({blobs:b,kzg:_});if(s.includes("blobVersionedHashes")){let P=Xy({commitments:T,to:"hex"});r.blobVersionedHashes=P}if(s.includes("sidecars")){let P=tl({blobs:b,commitments:T,kzg:_}),k=tb({blobs:b,commitments:T,proofs:P,to:"hex"});r.sidecars=k}}if(s.includes("chainId"))r.chainId=await d();if((s.includes("fees")||s.includes("type"))&&typeof w>"u")try{r.type=rb(r)}catch{let T=v9.get(e.uid);if(typeof T>"u")T=typeof(await v())?.baseFeePerGas==="bigint",v9.set(e.uid,T);r.type=T?"eip1559":"legacy"}if(s.includes("fees"))if(r.type!=="legacy"&&r.type!=="eip2930"){if(typeof r.maxFeePerGas>"u"||typeof r.maxPriorityFeePerGas>"u"){let T=await v(),{maxFeePerGas:P,maxPriorityFeePerGas:k}=await Qy(e,{block:T,chain:o,request:r});if(typeof r.maxPriorityFeePerGas>"u"&&r.maxFeePerGas&&r.maxFeePerGas<k)throw new gP({maxPriorityFeePerGas:k});r.maxPriorityFeePerGas=k,r.maxFeePerGas=P}}else{if(typeof r.maxFeePerGas<"u"||typeof r.maxPriorityFeePerGas<"u")throw new Uc;if(typeof r.gasPrice>"u"){let T=await v(),{gasPrice:P}=await Qy(e,{block:T,chain:o,request:r,type:"legacy"});r.gasPrice=P}}if(s.includes("gas")&&typeof x>"u")r.gas=await J(e,nl,"estimateGas")({...r,account:l,prepare:l?.type==="local"?[]:["blobVersionedHashes"]});if(a?.fn&&a.runAt?.includes("afterFillParameters"))r=await a.fn({...r,chain:o},{client:e,phase:"afterFillParameters"});return Sr(r),delete r.parameters,r}async function nl(e,t){let{account:r=e.account,prepare:n=!0}=t,o=r?ze(r):void 0,i=(()=>{if(Array.isArray(n))return n;if(o?.type!=="local")return["blobVersionedHashes"];return})();try{let s=await(async()=>{if(t.to)return t.to;if(t.authorizationList&&t.authorizationList.length>0)return await ba({authorization:t.authorizationList[0]}).catch(()=>{throw new C("`to` is required. Could not infer from `authorizationList`")});return})(),{accessList:a,authorizationList:c,blobs:d,blobVersionedHashes:l,blockNumber:p,blockTag:m,data:h,gas:b,gasPrice:x,maxFeePerBlobGas:_,maxFeePerGas:w,maxPriorityFeePerGas:A,nonce:v,value:T,stateOverride:P,...k}=n?await di(e,{...t,parameters:i,to:s}):t;if(b&&t.gas!==b)return b;let N=(typeof p==="bigint"?G(p):void 0)||m,j=Wd(P);Sr(t);let R=e.chain?.formatters?.transactionRequest?.format,Z=(R||jr)({...ro(k,{format:R}),account:o,accessList:a,authorizationList:c,blobs:d,blobVersionedHashes:l,data:h,gasPrice:x,maxFeePerBlobGas:_,maxFeePerGas:w,maxPriorityFeePerGas:A,nonce:v,to:s,value:T},"estimateGas");return BigInt(await e.request({method:"eth_estimateGas",params:j?[Z,N??e.experimental_blockTag??"latest",j]:N?[Z,N]:[Z]}))}catch(s){throw d9(s,{...t,account:o,chain:e.chain})}}async function ol(e,t){let{abi:r,address:n,args:o,functionName:i,dataSuffix:s=typeof e.dataSuffix==="string"?e.dataSuffix:e.dataSuffix?.value,...a}=t,c=It({abi:r,args:o,functionName:i});try{return await J(e,nl,"estimateGas")({data:`${c}${s?s.replace("0x",""):""}`,to:n,...a})}catch(d){let l=a.account?ze(a.account):void 0;throw Nn(d,{abi:r,address:n,args:o,docsPath:"/docs/contract/estimateContractGas",functionName:i,sender:l?.address})}}Mr();rs();xn();Lc();ga();async function T9(e,{address:t,blockHash:r,blockNumber:n,blockTag:o=e.experimental_blockTag??"latest",requireCanonical:i}){let s=Bn({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:i});if(e.batch?.multicall&&e.chain?.contracts?.multicall3){let c=e.chain.contracts.multicall3.address,d=It({abi:Kn,functionName:"getEthBalance",args:[t]}),{data:l}=await J(e,Sn,"call")({to:c,data:d,blockHash:r,blockNumber:n,blockTag:o,requireCanonical:i});return Dr({abi:Kn,functionName:"getEthBalance",args:[t],data:l||"0x"})}let a=await e.request({method:"eth_getBalance",params:[t,s]});return BigInt(a)}async function E9(e){let t=await e.request({method:"eth_blobBaseFee"});return BigInt(t)}var Bce=new Map,Lce=new Map;function P9(e){let t=(o,i)=>({clear:()=>i.delete(o),get:()=>i.get(o),set:(s)=>i.set(o,s)}),r=t(e,Bce),n=t(e,Lce);return{clear:()=>{r.clear(),n.clear()},promise:r,response:n}}async function A9(e,{cacheKey:t,cacheTime:r=Number.POSITIVE_INFINITY}){let n=P9(t),o=n.response.get();if(o&&r>0){if(Date.now()-o.created.getTime()<r)return o.data}let i=n.promise.get();if(!i)i=e(),n.promise.set(i);try{let s=await i;return n.response.set({created:new Date,data:s}),s}finally{n.promise.clear()}}var Dce=(e)=>`blockNumber.${e}`;async function no(e,{cacheTime:t=e.cacheTime}={}){let r=await A9(()=>e.request({method:"eth_blockNumber"}),{cacheKey:Dce(e.uid),cacheTime:t});return BigInt(r)}Fe();lr();function Tr(e,{args:t,eventName:r}={}){return{...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,blockTimestamp:e.blockTimestamp?BigInt(e.blockTimestamp):e.blockTimestamp===null?null:void 0,logIndex:e.logIndex?Number(e.logIndex):null,transactionHash:e.transactionHash?e.transactionHash:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,...r?{args:t,eventName:r}:{}}}var PP={"0x0":"reverted","0x1":"success"};function il(e,t){let r={...e,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,contractAddress:e.contractAddress?e.contractAddress:null,cumulativeGasUsed:e.cumulativeGasUsed?BigInt(e.cumulativeGasUsed):null,effectiveGasPrice:e.effectiveGasPrice?BigInt(e.effectiveGasPrice):null,gasUsed:e.gasUsed?BigInt(e.gasUsed):null,logs:e.logs?e.logs.map((n)=>Tr(n)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Yt(e.transactionIndex):null,status:e.status?PP[e.status]:null,type:e.type?yP[e.type]||e.type:null};if(e.blobGasPrice)r.blobGasPrice=BigInt(e.blobGasPrice);if(e.blobGasUsed)r.blobGasUsed=BigInt(e.blobGasUsed);return r}async function I9(e,{blockHash:t,blockNumber:r,blockTag:n=e.experimental_blockTag??"latest"}={}){let o=r!==void 0?G(r):void 0,i=await e.request({method:"eth_getBlockReceipts",params:[t||o||n]},{dedupe:Boolean(t||o)});if(!i)throw new Fc({blockHash:t,blockNumber:r});let s=e.chain?.formatters?.transactionReceipt?.format||il;return i.map((a)=>s(a,"getBlockReceipts"))}lr();Fe();async function k9(e,{blockHash:t,blockNumber:r,blockTag:n="latest"}={}){let o=r!==void 0?G(r):void 0,i;if(t)i=await e.request({method:"eth_getBlockTransactionCountByHash",params:[t]},{dedupe:!0});else i=await e.request({method:"eth_getBlockTransactionCountByNumber",params:[o||n]},{dedupe:Boolean(o)});return Yt(i)}Lc();async function jc(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:i}){let s=Bn({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:i}),a=await e.request({method:"eth_getCode",params:[t,s]},{dedupe:typeof n==="bigint"||r!==void 0});if(a==="0x")return;return a}la();us();xr();Jn();Jf();ir();FT();mn();Jf();Zf();Zi();var R9="/docs/contract/decodeEventLog";function qc(e){let{abi:t,data:r,strict:n,topics:o}=e,i=n??!0,[s,...a]=o;if(!s)throw new vT({docsPath:R9});let c=t.find((w)=>w.type==="event"&&s===da(dr(w)));if(!(c&&("name"in c))||c.type!=="event")throw new TT(s,{docsPath:R9});let{name:d,inputs:l}=c,p=l?.some((w)=>!(("name"in w)&&w.name)),m=p?[]:{},h=l.map((w,A)=>[w,A]).filter(([w])=>("indexed"in w)&&w.indexed),b=[];for(let w=0;w<h.length;w++){let[A,v]=h[w],T=a[w];if(!T){if(i)throw new Sc({abiItem:c,param:A});b.push([A,v]);continue}m[p?v:A.name||v]=Uce({param:A,value:T})}let x=l.filter((w)=>!(("indexed"in w)&&w.indexed)),_=i?x:[...b.map(([w])=>w),...x];if(_.length>0){if(r&&r!=="0x")try{let w=Xi(_,r);if(w){let A=0;if(!i)for(let[v,T]of b)m[p?T:v.name||T]=w[A++];if(p){for(let v=0;v<l.length;v++)if(m[v]===void 0&&A<w.length)m[v]=w[A++]}else for(let v=0;v<x.length;v++)m[x[v].name]=w[A++]}}catch(w){if(i){if(w instanceof Nf||w instanceof Hf)throw new sa({abiItem:c,data:r,params:_,size:et(r)});throw w}}else if(i)throw new sa({abiItem:c,data:"0x",params:_,size:0})}return{eventName:d,args:Object.values(m).length>0?m:void 0}}function Uce({param:e,value:t}){if(e.type==="string"||e.type==="bytes"||e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/))return t;return(Xi([e],t)||[])[0]}function li(e){let{abi:t,args:r,logs:n,strict:o=!0}=e,i=(()=>{if(!e.eventName)return;if(Array.isArray(e.eventName))return e.eventName;return[e.eventName]})(),s=t.filter((a)=>a.type==="event").map((a)=>({abi:a,selector:da(a)}));return n.map((a)=>{let c=typeof a.blockNumber==="string"?Tr(a):a,d=s.filter((m)=>c.topics[0]===m.selector);if(d.length===0)return null;let l,p;for(let m of d)try{l=qc({...c,abi:[m.abi],strict:!0}),p=m;break}catch{}if(!l&&!o){p=d[0];try{l=qc({data:c.data,topics:c.topics,abi:[p.abi],strict:!1})}catch{let m=p.abi.inputs?.some((h)=>!(("name"in h)&&h.name));return{...c,args:m?[]:{},eventName:p.abi.name}}}if(!l||!p)return null;if(i&&!i.includes(l.eventName))return null;if(!Fce({args:l.args,inputs:p.abi.inputs,matchArgs:r}))return null;return{...l,...c}}).filter(Boolean)}function Fce(e){let{args:t,inputs:r,matchArgs:n}=e;if(!n)return!0;if(!t)return!1;function o(i,s,a){try{if(i.type==="address")return wr(s,a);if(i.type==="string"||i.type==="bytes")return St(Yn(s))===a;return s===a}catch{return!1}}if(Array.isArray(t)&&Array.isArray(n))return n.every((i,s)=>{if(i===null||i===void 0)return!0;let a=r[s];if(!a)return!1;return(Array.isArray(i)?i:[i]).some((d)=>o(a,d,t[s]))});if(typeof t==="object"&&!Array.isArray(t)&&typeof n==="object"&&!Array.isArray(n))return Object.entries(n).every(([i,s])=>{if(s===null||s===void 0)return!0;let a=r.find((d)=>d.name===i);if(!a)return!1;return(Array.isArray(s)?s:[s]).some((d)=>o(a,d,t[i]))});return!1}Fe();async function sl(e,{address:t,blockHash:r,fromBlock:n,toBlock:o,event:i,events:s,args:a,strict:c}={}){let d=c??!1,l=s??(i?[i]:void 0),p=[];if(l){if(p=[l.flatMap((x)=>ui({abi:[x],eventName:x.name,args:s?void 0:a}))],i)p=p[0]}let m;if(r)m=await e.request({method:"eth_getLogs",params:[{address:t,topics:p,blockHash:r}]});else m=await e.request({method:"eth_getLogs",params:[{address:t,topics:p,fromBlock:typeof n==="bigint"?G(n):n,toBlock:typeof o==="bigint"?G(o):o}]});let h=m.map((b)=>Tr(b));if(!l)return h;return li({abi:l,args:a,logs:h,strict:d})}async function nb(e,t){let{abi:r,address:n,args:o,blockHash:i,eventName:s,fromBlock:a,toBlock:c,strict:d}=t,l=s?bn({abi:r,name:s}):void 0,p=!l?r.filter((m)=>m.type==="event"):void 0;return J(e,sl,"getLogs")({address:n,args:o,blockHash:i,event:l,events:p,fromBlock:a,toBlock:c,strict:d})}ri();mn();Ji();async function O9(e,{address:t,blockNumber:r,blockTag:n="latest"}){let o=await jc(e,{address:t,...r!==void 0?{blockNumber:r}:{blockTag:n}});if(!o)return;if(et(o)!==23)return;if(!o.startsWith("0xef0100"))return;return Ao(gn(o,3,23))}Ge();class AP extends C{constructor({address:e}){super(`No EIP-712 domain found on contract "${e}".`,{metaMessages:["Ensure that:",`- The contract is deployed at the address "${e}".`,"- `eip712Domain()` function exists on the contract.","- `eip712Domain()` function matches signature to ERC-5267 specification."],name:"Eip712DomainNotFoundError"})}}async function C9(e,t){let{address:r,factory:n,factoryData:o}=t;try{let[i,s,a,c,d,l,p]=await J(e,gt,"readContract")({abi:jce,address:r,functionName:"eip712Domain",factory:n,factoryData:o});return{domain:{name:s,version:a,chainId:Number(c),verifyingContract:d,salt:l},extensions:p,fields:i}}catch(i){let s=i;if(s.name==="ContractFunctionExecutionError"&&s.cause.name==="ContractFunctionZeroDataError")throw new AP({address:r});throw s}}var jce=[{inputs:[],name:"eip712Domain",outputs:[{name:"fields",type:"bytes1"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"},{name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"}];Fe();function M9(e){return{baseFeePerGas:e.baseFeePerGas.map((t)=>BigInt(t)),gasUsedRatio:e.gasUsedRatio,oldestBlock:BigInt(e.oldestBlock),reward:e.reward?.map((t)=>t.map((r)=>BigInt(r)))}}async function $9(e,{blockCount:t,blockNumber:r,blockTag:n="latest",rewardPercentiles:o}){let i=typeof r==="bigint"?G(r):void 0,s=await e.request({method:"eth_feeHistory",params:[G(t),i||n,o]},{dedupe:Boolean(i)});return M9(s)}async function wa(e,{filter:t}){let r="strict"in t&&t.strict,n=await t.request({method:"eth_getFilterChanges",params:[t.id]});if(typeof n[0]==="string")return n;let o=n.map((i)=>Tr(i));if(!("abi"in t)||!t.abi)return o;return li({abi:t.abi,logs:o,strict:r})}async function N9(e,{filter:t}){let r=t.strict??!1,o=(await t.request({method:"eth_getFilterLogs",params:[t.id]})).map((i)=>Tr(i));if(!t.abi)return o;return li({abi:t.abi,logs:o,strict:r})}Lc();xn();lr();function qce(e){return e.map((t)=>({...t,value:BigInt(t.value)}))}function z9(e){return{...e,balance:e.balance?BigInt(e.balance):void 0,nonce:e.nonce?Yt(e.nonce):void 0,storageProof:e.storageProof?qce(e.storageProof):void 0}}async function B9(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:i,storageKeys:s}){let a=Bn({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:i}),c=await e.request({method:"eth_getProof",params:[t,s,a]});return z9(c)}on();async function L9(e,{hash:t}){let r=await e.request({method:"eth_getRawTransactionByHash",params:[t]},{dedupe:!0});if(!r)throw new kc({hash:t});return r}Lc();async function D9(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:i,slot:s}){let a=Bn({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:i});return await e.request({method:"eth_getStorageAt",params:[t,s,a]})}on();Fe();async function al(e,{blockHash:t,blockNumber:r,blockTag:n,hash:o,index:i,sender:s,nonce:a}){let c=n||"latest",d=r!==void 0?G(r):void 0,l=null;if(o)l=await e.request({method:"eth_getTransactionByHash",params:[o]},{dedupe:!0});else if(t)l=await e.request({method:"eth_getTransactionByBlockHashAndIndex",params:[t,G(i)]},{dedupe:!0});else if((d||c)&&typeof i==="number")l=await e.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[d||c,G(i)]},{dedupe:Boolean(d)});else if(s&&typeof a==="number")l=await e.request({method:"eth_getTransactionBySenderAndNonce",params:[s,G(a)]},{dedupe:!0});if(!l)throw new kc({blockHash:t,blockNumber:r,blockTag:c,hash:o,index:i});return(e.chain?.formatters?.transaction?.format||Yd)(l,"getTransaction")}async function U9(e,{hash:t,transactionReceipt:r}){let[n,o]=await Promise.all([J(e,no,"getBlockNumber")({}),t?J(e,al,"getTransaction")({hash:t}):void 0]),i=r?.blockNumber||o?.blockNumber;if(!i)return 0n;return n-i+1n}on();async function cl(e,{hash:t}){let r=await e.request({method:"eth_getTransactionReceipt",params:[t]},{dedupe:!0});if(!r)throw new tm({hash:t});return(e.chain?.formatters?.transactionReceipt?.format||il)(r,"getTransactionReceipt")}Mr();ir();Ge();os();rs();xn();Ac();qy();async function F9(e,t){let{account:r,authorizationList:n,allowFailure:o=!0,blockHash:i,blockNumber:s,blockOverrides:a,blockTag:c,requireCanonical:d,stateOverride:l}=t,p=t.contracts,m=typeof e.batch?.multicall==="object"?e.batch.multicall:{},h=t.batchSize??m.batchSize??1024,b=t.deployless??m.deployless??!1,x=(()=>{if(t.multicallAddress)return t.multicallAddress;if(b)return null;if(e.chain)return Qn({blockNumber:s,chain:e.chain,contract:"multicall3"});throw Error("client chain not configured. multicallAddress is required.")})(),_=[[]],w=0,A=0;for(let O=0;O<p.length;O++){let{abi:N,address:j,args:R,functionName:K}=p[O];try{let Z=It({abi:N,args:R,functionName:K});if(A+=(Z.length-2)/2,h>0&&A>h&&_[w].length>0)w++,A=(Z.length-2)/2,_[w]=[];_[w]=[..._[w],{allowFailure:!0,callData:Z,target:j}]}catch(Z){let re=Nn(Z,{abi:N,address:j,args:R,docsPath:"/docs/contract/multicall",functionName:K,sender:r});if(!o)throw re;_[w]=[..._[w],{allowFailure:!0,callData:"0x",target:j}]}}let v=Boolean(e.batch?.multicall),T=v?_.flatMap((O)=>O.map((N)=>[N])):_,P=await Promise.allSettled(T.map((O)=>{if(v)return Hce(e,{account:r,authorizationList:n,batchSize:h,blockHash:i,blockNumber:s,blockOverrides:a,blockTag:c,call:O[0],multicallAddress:x,requireCanonical:d,stateOverride:l}).then((N)=>[N]);return J(e,gt,"readContract")({...x===null?{code:zc}:{address:x},abi:Kn,account:r,args:[O],authorizationList:n,blockHash:i,blockNumber:s,blockOverrides:a,blockTag:c,functionName:"aggregate3",requireCanonical:d,stateOverride:l})})),k=[];for(let O=0;O<P.length;O++){let N=P[O];if(N.status==="rejected"){if(!o)throw N.reason;for(let R=0;R<T[O].length;R++)k.push({status:"failure",error:N.reason,result:void 0});continue}let j=N.value;for(let R=0;R<j.length;R++){let{returnData:K,success:Z}=j[R],{callData:re}=T[O][R],{abi:pe,address:U,functionName:ee,args:me}=p[k.length];try{if(re==="0x")throw new To;if(!Z)throw new ns({data:K});let z=Dr({abi:pe,args:me,data:K,functionName:ee});k.push(o?{result:z,status:"success"}:z)}catch(z){let F=Nn(z,{abi:pe,address:U,args:me,docsPath:"/docs/contract/multicall",functionName:ee});if(!o)throw F;k.push({error:F,result:void 0,status:"failure"})}}}if(k.length!==p.length)throw new C("multicall results mismatch");return k}async function Hce(e,t){let{batchSize:r,call:n,multicallAddress:o,...i}=t,{wait:s=0}=typeof e.batch?.multicall==="object"?e.batch.multicall:{},{schedule:a}=Zd({id:Je(["multicall",e.uid,r,o,i]),wait:s,shouldSplitBatch(d){if(r===0)return!1;return d.reduce((p,{callData:m})=>p+(m.length-2)/2,0)>r},fn:(d)=>J(e,gt,"readContract")({...o===null?{code:zc}:{address:o},...i,abi:Kn,args:[d],functionName:"aggregate3"})}),[c]=await a(n);return c}YE();ir();os();ls();rs();xn();Fe();mm();ps();Hy();ci();async function ul(e,t){let{blockNumber:r,blockTag:n=e.experimental_blockTag??"latest",blocks:o,returnFullTransactions:i,traceTransfers:s,validation:a}=t;try{let c=[];for(let m of o){let h=m.blockOverrides?Dy(m.blockOverrides):void 0,b=m.calls.map((_)=>{let w=_,A=w.account?ze(w.account):void 0,v=w.abi?It(w):w.data,T={...w,account:A,data:w.dataSuffix?fr([v||"0x",w.dataSuffix]):v,from:w.from??A?.address};return Sr(T),jr(T)}),x=m.stateOverrides?Wd(m.stateOverrides):void 0;c.push({blockOverrides:h,calls:b,stateOverrides:x})}let l=(typeof r==="bigint"?G(r):void 0)||n;return(await e.request({method:"eth_simulateV1",params:[{blockStateCalls:c,returnFullTransactions:i,traceTransfers:s,validation:a},l]})).map((m,h)=>({...Jd(m),calls:m.calls.map((b,x)=>{let{abi:_,args:w,functionName:A,to:v}=o[h].calls[x],T=b.error?.data??b.returnData,P=BigInt(b.gasUsed),k=b.logs?.map((R)=>Tr(R)),O=b.status==="0x1"?"success":"failure",N=_&&O==="success"&&T!=="0x"?Dr({abi:_,data:T,functionName:A}):null,j=(()=>{if(O==="success")return;let R;if(T==="0x")R=new To;else if(T)R=new ns({data:T});if(!R)return;return Nn(R,{abi:_??[],address:v??"0x",args:w,functionName:A??"<unknown>"})})();return{data:T,gasUsed:P,logs:k,status:O,...O==="success"?{result:N}:{error:j}}})}))}catch(c){let d=c,l=ha(d,{});if(l instanceof Co)throw d;throw l}}Yf();eo();/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Gce(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function IP(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, got "+e)}function wm(e,...t){if(!Gce(e))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw Error("Uint8Array expected of length "+t+", got length="+e.length)}function kP(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function j9(e,t){wm(e);let r=t.outputLen;if(e.length<r)throw Error("digestInto() expects output buffer of length at least "+r)}function q9(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function RP(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}var Vce=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function Zce(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function Wce(e){for(let t=0;t<e.length;t++)e[t]=Zce(e[t]);return e}var OP=Vce?(e)=>e:Wce;function Kce(e){if(typeof e!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function CP(e){if(typeof e==="string")e=Kce(e);return wm(e),e}class MP{}function H9(e){let t=(n)=>e().update(CP(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}var ob=BigInt(4294967295),G9=BigInt(32);function Yce(e,t=!1){if(t)return{h:Number(e&ob),l:Number(e>>G9&ob)};return{h:Number(e>>G9&ob)|0,l:Number(e&ob)|0}}function V9(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let i=0;i<r;i++){let{h:s,l:a}=Yce(e[i],t);[n[i],o[i]]=[s,a]}return[n,o]}var Z9=(e,t,r)=>e<<r|t>>>32-r,W9=(e,t,r)=>t<<r|e>>>32-r,K9=(e,t,r)=>t<<r-32|e>>>64-r,Y9=(e,t,r)=>e<<r-32|t>>>64-r;var Jce=BigInt(0),Sm=BigInt(1),Qce=BigInt(2),Xce=BigInt(7),eue=BigInt(256),tue=BigInt(113),X9=[],eD=[],tD=[];for(let e=0,t=Sm,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],X9.push(2*(5*n+r)),eD.push((e+1)*(e+2)/2%64);let o=Jce;for(let i=0;i<7;i++)if(t=(t<<Sm^(t>>Xce)*tue)%eue,t&Qce)o^=Sm<<(Sm<<BigInt(i))-Sm;tD.push(o)}var rD=V9(tD,!0),rue=rD[0],nue=rD[1],J9=(e,t,r)=>r>32?K9(e,t,r):Z9(e,t,r),Q9=(e,t,r)=>r>32?Y9(e,t,r):W9(e,t,r);function oue(e,t=24){let r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let s=0;s<10;s++)r[s]=e[s]^e[s+10]^e[s+20]^e[s+30]^e[s+40];for(let s=0;s<10;s+=2){let a=(s+8)%10,c=(s+2)%10,d=r[c],l=r[c+1],p=J9(d,l,1)^r[a],m=Q9(d,l,1)^r[a+1];for(let h=0;h<50;h+=10)e[s+h]^=p,e[s+h+1]^=m}let o=e[2],i=e[3];for(let s=0;s<24;s++){let a=eD[s],c=J9(o,i,a),d=Q9(o,i,a),l=X9[s];o=e[l],i=e[l+1],e[l]=c,e[l+1]=d}for(let s=0;s<50;s+=10){for(let a=0;a<10;a++)r[a]=e[s+a];for(let a=0;a<10;a++)e[s+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=rue[n],e[1]^=nue[n]}RP(r)}class $P extends MP{constructor(e,t,r,n=!1,o=24){super();if(this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=n,this.rounds=o,IP(r),!(0<e&&e<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=q9(this.state)}clone(){return this._cloneInto()}keccak(){OP(this.state32),oue(this.state32,this.rounds),OP(this.state32),this.posOut=0,this.pos=0}update(e){kP(this),e=CP(e),wm(e);let{blockLen:t,state:r}=this,n=e.length;for(let o=0;o<n;){let i=Math.min(t-this.pos,n-o);for(let s=0;s<i;s++)r[this.pos++]^=e[o++];if(this.pos===t)this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:r,blockLen:n}=this;if(e[r]^=t,(t&128)!==0&&r===n-1)this.keccak();e[n-1]^=128,this.keccak()}writeInto(e){kP(this,!1),wm(e),this.finish();let t=this.state,{blockLen:r}=this;for(let n=0,o=e.length;n<o;){if(this.posOut>=r)this.keccak();let i=Math.min(r-this.posOut,o-n);e.set(t.subarray(this.posOut,this.posOut+i),n),this.posOut+=i,n+=i}return e}xofInto(e){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return IP(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(j9(e,this),this.finished)throw Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,RP(this.state)}_cloneInto(e){let{blockLen:t,suffix:r,outputLen:n,rounds:o,enableXOF:i}=this;return e||(e=new $P(t,r,n,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=n,e.enableXOF=i,e.destroyed=this.destroyed,e}}var iue=(e,t,r)=>H9(()=>new $P(t,e,r));var nD=(()=>iue(1,136,32))();qd();wn();function ib(e,t={}){let{as:r=typeof e==="string"?"Hex":"Bytes"}=t,n=nD(hL(e));if(r==="Bytes")return n;return Ur(n)}wn();qd();class NP extends Map{constructor(e){super();Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){let t=super.get(e);if(super.has(e)&&t!==void 0)this.delete(e),super.set(e,t);return t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){let r=this.keys().next().value;if(r)this.delete(r)}return this}}var sue={checksum:new NP(8192)},sb=sue.checksum;eo();var cue=/^0x[a-fA-F0-9]{40}$/;function dl(e,t={}){let{strict:r=!0}=t;if(!cue.test(e))throw new zP({address:e,cause:new iD});if(r){if(e.toLowerCase()===e)return;if(BP(e)!==e)throw new zP({address:e,cause:new sD})}}function BP(e){if(sb.has(e))return sb.get(e);dl(e,{strict:!1});let t=e.substring(2).toLowerCase(),r=ib(gL(t),{as:"Bytes"}),n=t.split("");for(let i=0;i<40;i+=2){if(r[i>>1]>>4>=8&&n[i])n[i]=n[i].toUpperCase();if((r[i>>1]&15)>=8&&n[i+1])n[i+1]=n[i+1].toUpperCase()}let o=`0x${n.join("")}`;return sb.set(e,o),o}function ab(e,t={}){let{strict:r=!0}=t??{};try{return dl(e,{strict:r}),!0}catch{return!1}}class zP extends Pe{constructor({address:e,cause:t}){super(`Address "${e}" is invalid.`,{cause:t});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class iD extends Pe{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value.");Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}}class sD extends Pe{constructor(){super("Address does not match its checksum counterpart.");Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}eo();function ub(e){let t=!0,r="",n=0,o="",i=!1;for(let s=0;s<e.length;s++){let a=e[s];if(["(",")",","].includes(a))t=!0;if(a==="(")n++;if(a===")")n--;if(!t)continue;if(n===0){if(a===" "&&["event","function","error",""].includes(o))o="";else if(o+=a,a===")"){i=!0;break}continue}if(a===" "){if(e[s-1]!==","&&r!==","&&r!==",(")r="",t=!1;continue}o+=a,r+=a}if(!i)throw new Pe("Unable to normalize signature.");return o}function cb(e,t){let r=typeof e,n=t.type;switch(n){case"address":return ab(e,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:{if(n==="tuple"&&"components"in t)return Object.values(t.components).every((o,i)=>cb(Object.values(e)[i],o));if(/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n))return r==="number"||r==="bigint";if(/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n))return r==="string"||e instanceof Uint8Array;if(/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n))return Array.isArray(e)&&e.every((o)=>cb(o,{...t,type:n.replace(/(\[[0-9]{0,}\])$/,"")}));return!1}}}function DP(e,t,r){for(let n in e){let o=e[n],i=t[n];if(o.type==="tuple"&&i.type==="tuple"&&"components"in o&&"components"in i)return DP(o.components,i.components,r[n]);let s=[o.type,i.type];if((()=>{if(s.includes("address")&&s.includes("bytes20"))return!0;if(s.includes("address")&&s.includes("string"))return ab(r[n],{strict:!1});if(s.includes("address")&&s.includes("bytes"))return ab(r[n],{strict:!1});return!1})())return s}return}function ll(e,t={}){let{prepare:r=!0}=t,n=(()=>{if(Array.isArray(e))return _y(e);if(typeof e==="string")return _y(e);return e})();return{...n,...r?{hash:Sa(n)}:{}}}function pl(e,t,r){let{args:n=[],prepare:o=!0}=r??{},i=KE(t,{strict:!1}),s=e.filter((d)=>{if(i){if(d.type==="function"||d.type==="error")return UP(d)===Fr(t,0,4);if(d.type==="event")return Sa(d)===t;return!1}return"name"in d&&d.name===t});if(s.length===0)throw new va({name:t});if(s.length===1)return{...s[0],...o?{hash:Sa(s[0])}:{}};let a;for(let d of s){if(!("inputs"in d))continue;if(!n||n.length===0){if(!d.inputs||d.inputs.length===0)return{...d,...o?{hash:Sa(d)}:{}};continue}if(!d.inputs)continue;if(d.inputs.length===0)continue;if(d.inputs.length!==n.length)continue;if(n.every((p,m)=>{let h="inputs"in d&&d.inputs[m];if(!h)return!1;return cb(p,h)})){if(a&&"inputs"in a&&a.inputs){let p=DP(d.inputs,a.inputs,n);if(p)throw new aD({abiItem:d,type:p[0]},{abiItem:a,type:p[1]})}a=d}}let c=(()=>{if(a)return a;let[d,...l]=s;return{...d,overloads:l}})();if(!c)throw new va({name:t});return{...c,...o?{hash:Sa(c)}:{}}}function UP(...e){let t=(()=>{if(Array.isArray(e[0])){let[r,n]=e;return pl(r,n)}return e[0]})();return Fr(Sa(t),0,4)}function due(...e){let t=(()=>{if(Array.isArray(e[0])){let[n,o]=e;return pl(n,o)}return e[0]})(),r=(()=>{if(typeof t==="string")return t;return Pc(t)})();return ub(r)}function Sa(...e){let t=(()=>{if(Array.isArray(e[0])){let[r,n]=e;return pl(r,n)}return e[0]})();if(typeof t!=="string"&&"hash"in t&&t.hash)return t.hash;return ib(Gd(due(t)))}class aD extends Pe{constructor(e,t){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${e.type}\` in \`${ub(Pc(e.abiItem))}\`, and`,`\`${t.type}\` in \`${ub(Pc(t.abiItem))}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.AmbiguityError"})}}class va extends Pe{constructor({name:e,data:t,type:r="item"}){let n=(()=>{if(e)return` with name "${e}"`;if(t)return` with data "${t}"`;return""})();super(`ABI ${r}${n} not found.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.NotFoundError"})}}Yf();qd();eo();wn();qd();eo();wn();var cD=/^(.*)\[([0-9]*)\]$/,uD=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,db=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,WBe=2n**(8n-1n)-1n,KBe=2n**(16n-1n)-1n,YBe=2n**(24n-1n)-1n,JBe=2n**(32n-1n)-1n,QBe=2n**(40n-1n)-1n,XBe=2n**(48n-1n)-1n,e3e=2n**(56n-1n)-1n,t3e=2n**(64n-1n)-1n,r3e=2n**(72n-1n)-1n,n3e=2n**(80n-1n)-1n,o3e=2n**(88n-1n)-1n,i3e=2n**(96n-1n)-1n,s3e=2n**(104n-1n)-1n,a3e=2n**(112n-1n)-1n,c3e=2n**(120n-1n)-1n,u3e=2n**(128n-1n)-1n,d3e=2n**(136n-1n)-1n,l3e=2n**(144n-1n)-1n,p3e=2n**(152n-1n)-1n,f3e=2n**(160n-1n)-1n,m3e=2n**(168n-1n)-1n,h3e=2n**(176n-1n)-1n,g3e=2n**(184n-1n)-1n,y3e=2n**(192n-1n)-1n,b3e=2n**(200n-1n)-1n,x3e=2n**(208n-1n)-1n,_3e=2n**(216n-1n)-1n,w3e=2n**(224n-1n)-1n,S3e=2n**(232n-1n)-1n,v3e=2n**(240n-1n)-1n,T3e=2n**(248n-1n)-1n,E3e=2n**(256n-1n)-1n,P3e=-(2n**(8n-1n)),A3e=-(2n**(16n-1n)),I3e=-(2n**(24n-1n)),k3e=-(2n**(32n-1n)),R3e=-(2n**(40n-1n)),O3e=-(2n**(48n-1n)),C3e=-(2n**(56n-1n)),M3e=-(2n**(64n-1n)),$3e=-(2n**(72n-1n)),N3e=-(2n**(80n-1n)),z3e=-(2n**(88n-1n)),B3e=-(2n**(96n-1n)),L3e=-(2n**(104n-1n)),D3e=-(2n**(112n-1n)),U3e=-(2n**(120n-1n)),F3e=-(2n**(128n-1n)),j3e=-(2n**(136n-1n)),q3e=-(2n**(144n-1n)),H3e=-(2n**(152n-1n)),G3e=-(2n**(160n-1n)),V3e=-(2n**(168n-1n)),Z3e=-(2n**(176n-1n)),W3e=-(2n**(184n-1n)),K3e=-(2n**(192n-1n)),Y3e=-(2n**(200n-1n)),J3e=-(2n**(208n-1n)),Q3e=-(2n**(216n-1n)),X3e=-(2n**(224n-1n)),eLe=-(2n**(232n-1n)),tLe=-(2n**(240n-1n)),rLe=-(2n**(248n-1n)),nLe=-(2n**(256n-1n)),oLe=2n**8n-1n,iLe=2n**16n-1n,sLe=2n**24n-1n,aLe=2n**32n-1n,cLe=2n**40n-1n,uLe=2n**48n-1n,dLe=2n**56n-1n,lLe=2n**64n-1n,pLe=2n**72n-1n,fLe=2n**80n-1n,mLe=2n**88n-1n,hLe=2n**96n-1n,gLe=2n**104n-1n,yLe=2n**112n-1n,bLe=2n**120n-1n,xLe=2n**128n-1n,_Le=2n**136n-1n,wLe=2n**144n-1n,SLe=2n**152n-1n,vLe=2n**160n-1n,TLe=2n**168n-1n,ELe=2n**176n-1n,PLe=2n**184n-1n,ALe=2n**192n-1n,ILe=2n**200n-1n,kLe=2n**208n-1n,RLe=2n**216n-1n,OLe=2n**224n-1n,CLe=2n**232n-1n,MLe=2n**240n-1n,$Le=2n**248n-1n,jP=2n**256n-1n;function Hc(e,t,r){let{checksumAddress:n,staticPosition:o}=r,i=GP(t.type);if(i){let[s,a]=i;return pue(e,{...t,type:a},{checksumAddress:n,length:s,staticPosition:o})}if(t.type==="tuple")return gue(e,t,{checksumAddress:n,staticPosition:o});if(t.type==="address")return lue(e,{checksum:n});if(t.type==="bool")return fue(e);if(t.type.startsWith("bytes"))return mue(e,t,{staticPosition:o});if(t.type.startsWith("uint")||t.type.startsWith("int"))return hue(e,t);if(t.type==="string")return yue(e,{staticPosition:o});throw new vm(t.type)}var lD=32,qP=32;function lue(e,t={}){let{checksum:r=!1}=t,n=e.readBytes(32);return[((i)=>r?BP(i):i)(Ur(yL(n,-20))),32]}function pue(e,t,r){let{checksumAddress:n,length:o,staticPosition:i}=r;if(o===null){let c=ii(e.readBytes(qP)),d=i+c,l=d+lD;e.setPosition(d);let p=ii(e.readBytes(lD)),m=fl(t),h=0,b=[];for(let x=0;x<p;++x){e.setPosition(l+(m?x*32:h));let[_,w]=Hc(e,t,{checksumAddress:n,staticPosition:l});if(h+=w,b.push(_),w===0)e.assertReadLimit(),e._touch()}return e.setPosition(i+32),[b,32]}if(fl(t)){let c=ii(e.readBytes(qP)),d=i+c,l=[];for(let p=0;p<o;++p){e.setPosition(d+p*32);let[m]=Hc(e,t,{checksumAddress:n,staticPosition:d});l.push(m)}return e.setPosition(i+32),[l,32]}let s=0,a=[];for(let c=0;c<o;++c){let[d,l]=Hc(e,t,{checksumAddress:n,staticPosition:i+s});if(s+=l,a.push(d),l===0)e.assertReadLimit(),e._touch()}return[a,s]}function fue(e){return[xL(e.readBytes(32),{size:32}),32]}function mue(e,t,{staticPosition:r}){let[n,o]=t.type.split("bytes");if(!o){let s=ii(e.readBytes(32));e.setPosition(r+s);let a=ii(e.readBytes(32));if(a===0)return e.setPosition(r+32),["0x",32];let c=e.readBytes(a);return e.setPosition(r+32),[Ur(c),32]}return[Ur(e.readBytes(Number.parseInt(o,10),32)),32]}function hue(e,t){let r=t.type.startsWith("int"),n=Number.parseInt(t.type.split("int")[1]||"256",10),o=e.readBytes(32);return[n>48?bL(o,{signed:r}):ii(o,{signed:r}),32]}function gue(e,t,r){let{checksumAddress:n,staticPosition:o}=r,i=t.components.length===0||t.components.some(({name:c})=>!c),s=i?[]:{},a=0;if(fl(t)){let c=ii(e.readBytes(qP)),d=o+c;for(let l=0;l<t.components.length;++l){let p=t.components[l];e.setPosition(d+a);let[m,h]=Hc(e,p,{checksumAddress:n,staticPosition:d});a+=h,s[i?l:p?.name]=m}return e.setPosition(o+32),[s,32]}for(let c=0;c<t.components.length;++c){let d=t.components[c],[l,p]=Hc(e,d,{checksumAddress:n,staticPosition:o});s[i?c:d?.name]=l,a+=p}return[s,a]}function yue(e,{staticPosition:t}){let r=ii(e.readBytes(32)),n=t+r;e.setPosition(n);let o=ii(e.readBytes(32));if(o===0)return e.setPosition(t+32),["",32];let i=e.readBytes(o,32),s=_L(GE(i));return e.setPosition(t+32),[s,32]}function pD({checksumAddress:e,parameters:t,values:r}){let n=[];for(let o=0;o<t.length;o++)n.push(HP({checksumAddress:e,parameter:t[o],value:r[o]}));return n}function HP({checksumAddress:e=!1,parameter:t,value:r}){let n=t,o=GP(n.type);if(o){let[i,s]=o;return xue(r,{checksumAddress:e,length:i,parameter:{...n,type:s}})}if(n.type==="tuple")return Tue(r,{checksumAddress:e,parameter:n});if(n.type==="address")return bue(r,{checksum:e});if(n.type==="bool")return wue(r);if(n.type.startsWith("uint")||n.type.startsWith("int")){let i=n.type.startsWith("int"),[,,s="256"]=db.exec(n.type)??[];return Sue(r,{signed:i,size:Number(s)})}if(n.type.startsWith("bytes"))return _ue(r,{type:n.type});if(n.type==="string")return vue(r);throw new vm(n.type)}function lb(e){let t=0;for(let i=0;i<e.length;i++){let{dynamic:s,encoded:a}=e[i];if(s)t+=32;else t+=sr(a)}let r=[],n=[],o=0;for(let i=0;i<e.length;i++){let{dynamic:s,encoded:a}=e[i];if(s)r.push(rr(t+o,{size:32})),n.push(a),o+=sr(a);else r.push(a)}return _r(...r,...n)}function bue(e,t){let{checksum:r=!1}=t;return dl(e,{strict:r}),{dynamic:!1,encoded:cs(e.toLowerCase())}}function xue(e,t){let{checksumAddress:r,length:n,parameter:o}=t,i=n===null;if(!Array.isArray(e))throw new ZP(e);if(!i&&e.length!==n)throw new VP({expectedLength:n,givenLength:e.length,type:`${o.type}[${n}]`});let s=e.length===0&&fl(o),a=[];for(let c=0;c<e.length;c++){let d=HP({checksumAddress:r,parameter:o,value:e[c]});if(d.dynamic)s=!0;a.push(d)}if(i||s){let c=lb(a);if(i){let d=rr(a.length,{size:32});return{dynamic:!0,encoded:a.length>0?_r(d,c):d}}if(s)return{dynamic:!0,encoded:c}}return{dynamic:!1,encoded:_r(...a.map(({encoded:c})=>c))}}function _ue(e,{type:t}){let[,r]=t.split("bytes"),n=sr(e);if(!r){let o=e;if(n%32!==0)o=si(o,Math.ceil((e.length-2)/2/32)*32);return{dynamic:!0,encoded:_r(cs(rr(n,{size:32})),o)}}if(n!==Number.parseInt(r,10))throw new pb({expectedSize:Number.parseInt(r,10),value:e});return{dynamic:!1,encoded:si(e)}}function wue(e){if(typeof e!=="boolean")throw new Pe(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:cs(By(e))}}function Sue(e,{signed:t,size:r}){if(typeof r==="number"){let n=2n**(BigInt(r)-(t?1n:0n))-1n,o=t?-n-1n:0n;if(e>n||e<o)throw new Ly({max:n.toString(),min:o.toString(),signed:t,size:r/8,value:e.toString()})}return{dynamic:!1,encoded:rr(e,{size:32,signed:t})}}function vue(e){let t=Gd(e),r=Math.ceil(sr(t)/32),n=[];for(let o=0;o<r;o++)n.push(si(Fr(t,o*32,(o+1)*32)));return{dynamic:!0,encoded:_r(si(rr(sr(t),{size:32})),...n)}}function Tue(e,t){let{checksumAddress:r,parameter:n}=t,o=!1,i=[];for(let s=0;s<n.components.length;s++){let a=n.components[s],c=Array.isArray(e)?s:a.name,d=HP({checksumAddress:r,parameter:a,value:e[c]});if(i.push(d),d.dynamic)o=!0}return{dynamic:o,encoded:o?lb(i):_r(...i.map(({encoded:s})=>s))}}function GP(e){let t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}function fl(e){let{type:t}=e;if(t==="string")return!0;if(t==="bytes")return!0;if(t.endsWith("[]"))return!0;if(t==="tuple")return e.components?.some(fl);let r=GP(e.type);if(r&&fl({...e,type:r[1]}))return!0;return!1}eo();var Pue={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new hD({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new mD({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new WP({offset:e});let t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new WP({offset:e});let t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){let r=t??this.position;return this.assertPosition(r+e-1),this.bytes.subarray(r,r+e)},inspectUint8(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){let t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){let t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){let t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,e&255),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();let e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();let r=this.inspectBytes(e);return this.position+=t??e,r},readUint8(){this.assertReadLimit(),this._touch();let e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();let e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();let e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();let e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){let t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;let e=this.getReadCount();if(this.positionReadCount.set(this.position,e+1),e>0)this.recursiveReadCount++}};function fD(e,{recursiveReadLimit:t=8192}={}){let r=Object.create(Pue);return r.bytes=e,r.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=t,r}class WP extends Pe{constructor({offset:e}){super(`Offset \`${e}\` cannot be negative.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.NegativeOffsetError"})}}class mD extends Pe{constructor({length:e,position:t}){super(`Position \`${t}\` is out of bounds (\`0 < position < ${e}\`).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.PositionOutOfBoundsError"})}}class hD extends Pe{constructor({count:e,limit:t}){super(`Recursive read limit of \`${t}\` exceeded (recursive read count: \`${e}\`).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.RecursiveReadLimitExceededError"})}}function ml(e,t,r={}){let{as:n="Array",checksumAddress:o=!1}=r,i=typeof t==="string"?HE(t):t,s=fD(i);if(to(i)===0&&e.length>0)throw new yD;if(to(i)&&to(i)<32)throw new gD({data:typeof t==="string"?t:Ur(t),parameters:e,size:to(i)});let a=0,c=n==="Array"?[]:{};for(let d=0;d<e.length;++d){let l=e[d];if(a<i.length)s.setPosition(a);let[p,m]=Hc(s,l,{checksumAddress:o,staticPosition:0});if(a+=m,n==="Array")c.push(p);else c[l.name??d]=p}return c}function Gc(e,t,r){let{checksumAddress:n=!1}=r??{};if(e.length!==t.length)throw new YP({expectedLength:e.length,givenLength:t.length});let o=pD({checksumAddress:n,parameters:e,values:t}),i=lb(o);if(i.length===0)return"0x";return i}function KP(e,t){if(e.length!==t.length)throw new YP({expectedLength:e.length,givenLength:t.length});let r=[];for(let n=0;n<e.length;n++){let o=e[n],i=t[n];r.push(KP.encode(o,i))}return _r(...r)}(function(e){function t(r,n,o=!1){if(r==="address"){let c=n;return dl(c),cs(c.toLowerCase(),o?32:0)}if(r==="string")return Gd(n);if(r==="bytes")return n;if(r==="bool")return cs(By(n),o?32:1);let i=r.match(db);if(i){let[c,d,l="256"]=i,p=Number.parseInt(l,10)/8;return rr(n,{size:o?32:p,signed:d==="int"})}let s=r.match(uD);if(s){let[c,d]=s;if(Number.parseInt(d,10)!==(n.length-2)/2)throw new pb({expectedSize:Number.parseInt(d,10),value:n});return si(n,o?32:0)}let a=r.match(cD);if(a&&Array.isArray(n)){let[c,d]=a,l=[];for(let p=0;p<n.length;p++)l.push(t(d,n[p],!0));if(l.length===0)return"0x";return _r(...l)}throw new vm(r)}e.encode=t})(KP||(KP={}));function fb(e){if(Array.isArray(e)&&typeof e[0]==="string")return wy(e);if(typeof e==="string")return wy(e);return e}class gD extends Pe{constructor({data:e,parameters:t,size:r}){super(`Data size of ${r} bytes is too small for given parameters.`,{metaMessages:[`Params: (${es(t)})`,`Data: ${e} (${r} bytes)`]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.DataSizeTooSmallError"})}}class yD extends Pe{constructor(){super('Cannot decode zero data ("0x") with ABI parameters.');Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ZeroDataError"})}}class VP extends Pe{constructor({expectedLength:e,givenLength:t,type:r}){super(`Array length mismatch for type \`${r}\`. Expected: \`${e}\`. Given: \`${t}\`.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ArrayLengthMismatchError"})}}class pb extends Pe{constructor({expectedSize:e,value:t}){super(`Size of bytes "${t}" (bytes${sr(t)}) does not match expected size (bytes${e}).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class YP extends Pe{constructor({expectedLength:e,givenLength:t}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${e}`,`Given length (values): ${t}`].join(`
141
+ ${t}`}function U0(e,t){return Li(rd.sign(pc(t),e))}var Rf=[0.0001,0.001,0.01,0.1,1,10,100,1000,1e4];var lse=1e4,pse=15000,fse=30000,mse=1000;function or(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function le(e,t){let r=e[t];if(typeof r!=="string"||r.length===0)throw Error(`Invalid WebSocket event: ${t} must be a non-empty string`);return r}function Se(e,t){let r=e[t];if(r===void 0||r===null)return;if(typeof r!=="string")throw Error(`Invalid WebSocket event: ${t} must be a string`);return r}function vo(e,t){if(!Object.hasOwn(e,t))throw Error(`Invalid WebSocket event: ${t} is missing`);let r=e[t];if(r===null||r===void 0)return null;if(typeof r!=="string")throw Error(`Invalid WebSocket event: ${t} must be a string`);return r}function tT(e,t){let r=e[t];if(typeof r!=="boolean")throw Error(`Invalid WebSocket event: ${t} must be a boolean`);return r}function hse(e,t){let r=e[t];if(typeof r!=="number"||!Number.isSafeInteger(r)||r<0)throw Error(`Invalid WebSocket event: ${t} must be a non-negative safe integer`);return r}function Of(e,t){let r=e[t];if(r===void 0||r===null)return;if(typeof r!=="number"||!Number.isFinite(r))throw Error(`Invalid WebSocket event: ${t} must be a finite number`);return r}function rT(e,t){let r=e[t];if(r===void 0||r===null)return;return hse(e,t)}function gse(e,t){let r=e[t];if(!Array.isArray(r)||r.some((n)=>typeof n!=="string"))throw Error(`Invalid WebSocket event: ${t} must be an array of strings`);return r}function F0(e,t,r){let n=le(e,t);if(!r.includes(n))throw Error(`Invalid WebSocket event: ${t} must be one of ${r.join(", ")}`);return n}function ez(e,t){let r=Se(e,t);return r===void 0||r.length===0?void 0:r}function rz(e){if(!or(e))throw Error("Invalid conditional order event: data must be an object");let t=en(e);return{conditionalOrderId:le(t,"conditionalOrderId"),tradingPairId:le(t,"tradingPairId"),marginAccountId:le(t,"marginAccountId"),positionId:Se(t,"positionId"),parentOrderId:Se(t,"parentOrderId"),associationType:ez(t,"associationType"),linkedGroupId:Se(t,"linkedGroupId"),conditionType:le(t,"conditionType"),triggerSource:le(t,"triggerSource"),triggerPrice:le(t,"triggerPrice"),side:le(t,"side"),positionSide:le(t,"positionSide"),orderType:le(t,"orderType"),limitPrice:Se(t,"limitPrice"),quantity:Se(t,"quantity"),slippageToleranceBps:Of(t,"slippageToleranceBps"),reduceOnly:tT(t,"reduceOnly"),timeInForce:ez(t,"timeInForce"),state:le(t,"state"),triggeredOrderId:Se(t,"triggeredOrderId"),triggeredAt:Se(t,"triggeredAt"),activatedAt:Se(t,"activatedAt"),cancelledAt:Se(t,"cancelledAt"),expiresAt:Se(t,"expiresAt"),failureReason:Se(t,"failureReason"),reason:le(t,"reason"),updatedAt:le(t,"updatedAt"),version:Of(t,"version")}}function yse(e){if(!or(e))throw Error("Invalid conditional order event: payload must be an object");return{eventType:F0(e,"event_type",["conditional_order_update"]),userId:le(e,"user_id"),data:rz(e.data)}}function nz(e){if(!or(e))throw Error("Invalid position event: data must be an object");let t=en(e);return{positionId:le(t,"positionId"),marginAccountId:le(t,"marginAccountId"),tradingPairId:le(t,"tradingPairId"),side:le(t,"side"),status:le(t,"status"),size:le(t,"size"),entryPrice:le(t,"entryPrice"),markPrice:Se(t,"markPrice"),unrealizedPnl:Se(t,"unrealizedPnl"),liquidationPrice:Se(t,"liquidationPrice"),isolatedMargin:le(t,"isolatedMargin"),leverage:le(t,"leverage"),riskBucketId:Se(t,"riskBucketId"),marginMode:Se(t,"marginMode"),maintenanceMarginRequired:Se(t,"maintenanceMarginRequired"),initialMarginRequired:Se(t,"initialMarginRequired"),tradeId:Se(t,"tradeId"),orderId:Se(t,"orderId"),reason:le(t,"reason"),updatedAt:le(t,"updatedAt"),version:rT(t,"version")}}function bse(e){if(!or(e))throw Error("Invalid position event: payload must be an object");return{eventType:F0(e,"event_type",["position_update"]),userId:le(e,"user_id"),data:nz(e.data)}}function oz(e){if(!or(e))throw Error("Invalid liquidation event: data must be an object");let t=en(e);return{liquidationId:le(t,"liquidationId"),marginAccountId:le(t,"marginAccountId"),positionId:Se(t,"positionId"),tradingPairId:Se(t,"tradingPairId"),status:le(t,"status"),accountState:le(t,"accountState"),liquidationPrice:Se(t,"liquidationPrice"),markPrice:Se(t,"markPrice"),estimatedShortfall:le(t,"estimatedShortfall"),message:le(t,"message"),triggeredAt:le(t,"triggeredAt")}}function xse(e){if(!or(e))throw Error("Invalid liquidation event: payload must be an object");return{eventType:F0(e,"event_type",["liquidation_alert"]),userId:le(e,"user_id"),data:oz(e.data)}}function iz(e){if(!or(e))throw Error("Invalid account event: data must be an object");let t=en(e);return{marginAccountId:le(t,"marginAccountId"),sequence:rT(t,"sequence"),equity:le(t,"equity"),collateral:le(t,"collateral"),freeCollateral:le(t,"freeCollateral"),marginRatio:le(t,"marginRatio"),maintenanceRequirement:le(t,"maintenanceRequirement"),updatedAt:le(t,"updatedAt")}}function _se(e){if(!or(e))throw Error("Invalid account event: payload must be an object");return{eventType:F0(e,"event_type",["account_update"]),userId:le(e,"user_id"),data:iz(e.data)}}function sz(e){if(!or(e))throw Error("Invalid market stats event: data must be an object");let t=en(e);return{symbol:le(t,"symbol"),tradingPairId:le(t,"tradingPairId"),indexPrice:Se(t,"indexPrice"),markPrice:Se(t,"markPrice"),midPrice:Se(t,"midPrice"),bestBidPrice:Se(t,"bestBidPrice"),bestAskPrice:Se(t,"bestAskPrice"),openInterest:Se(t,"openInterest"),openInterestLimit:Se(t,"openInterestLimit"),lastTradePrice:Se(t,"lastTradePrice"),dailyBaseTokenVolume:Se(t,"dailyBaseTokenVolume"),dailyQuoteTokenVolume:Se(t,"dailyQuoteTokenVolume"),dailyPriceLow:Se(t,"dailyPriceLow"),dailyPriceHigh:Se(t,"dailyPriceHigh"),dailyPriceChange:Se(t,"dailyPriceChange"),dailyPriceChangePercent:Se(t,"dailyPriceChangePercent"),currentFundingRate:Se(t,"currentFundingRate"),fundingRate:Se(t,"fundingRate"),fundingTimestamp:Of(t,"fundingTimestamp"),premium:Se(t,"premium"),baseInterestRate:Se(t,"baseInterestRate"),fundingClampSmall:Se(t,"fundingClampSmall"),fundingClampBig:Se(t,"fundingClampBig")}}function wse(e){if(!or(e))throw Error("Invalid market stats event: payload must be an object");return{tradingPairId:le(e,"trading_pair_id"),data:sz(e.data)}}function az(e){if(!or(e))throw Error("Invalid market stats summary: entry must be an object");let t=en(e);return{tradingPairId:le(t,"tradingPairId"),symbol:le(t,"symbol"),lastTradePrice:Se(t,"lastTradePrice"),markPrice:Se(t,"markPrice"),dailyPriceChange:Se(t,"dailyPriceChange"),dailyPriceChangePercent:Se(t,"dailyPriceChangePercent"),dailyBaseTokenVolume:Se(t,"dailyBaseTokenVolume"),dailyQuoteTokenVolume:Se(t,"dailyQuoteTokenVolume"),dailyPriceHigh:Se(t,"dailyPriceHigh"),dailyPriceLow:Se(t,"dailyPriceLow"),openInterest:Se(t,"openInterest"),currentFundingRate:Se(t,"currentFundingRate"),fundingTimestamp:Of(t,"fundingTimestamp"),marketStatus:le(t,"marketStatus")}}function Sse(e){if(!or(e)||!Array.isArray(e.markets))throw Error("Invalid market stats all event: markets must be an array");return{markets:e.markets.map(az)}}function cz(e){if(!or(e))throw Error("Invalid instrument event: data must be an object");let t=en(e);return{change:le(t,"change"),tradingPairId:le(t,"tradingPairId"),symbol:le(t,"symbol"),isActive:tT(t,"isActive"),tickSize:le(t,"tickSize"),quantityStepSize:le(t,"quantityStepSize"),minOrderSize:le(t,"minOrderSize"),maxOrderSize:le(t,"maxOrderSize"),marketType:le(t,"marketType"),category:le(t,"category"),baseIconUrl:Se(t,"baseIconUrl")??null,quoteIconUrl:Se(t,"quoteIconUrl")??null,maxLeverage:Se(t,"maxLeverage"),initialMarginRate:Se(t,"initialMarginRate"),maintenanceMarginRate:Se(t,"maintenanceMarginRate"),changedFields:gse(t,"changedFields"),updatedAt:le(t,"updatedAt")}}function vse(e){if(!or(e))throw Error("Invalid instrument event: payload must be an object");return{tradingPairId:le(e,"trading_pair_id"),data:cz(e.data)}}function Tse(e){if(!or(e))throw Error("Invalid TWAP order event: payload must be an object");if(!or(e.data))throw Error("Invalid TWAP order event: data must be an object");if(e.event_type!=="twap_order_update")throw Error("Invalid TWAP order event: event_type must be twap_order_update");let r=e.user_id;if(typeof r!=="string"||r.length===0)throw Error("Invalid TWAP order event: user_id must be a non-empty string");return{eventType:"twap_order_update",userId:r,data:uz(e.data)}}function uz(e){if(!or(e))throw Error("Invalid TWAP order event: data must be an object");let t=en(e);for(let o of Object.keys(t))if(t[o]===null)delete t[o];let r=t.twapOrderId;if(typeof r!=="string"||r.length===0)throw Error("Invalid TWAP order event: twapOrderId must be a non-empty string");let n=t.state;if(typeof n!=="string"||n.length===0)throw Error("Invalid TWAP order event: state must be a non-empty string");return t}function dz(e){if(!or(e))throw Error("Invalid balance event: data must be an object");let t=en(e);return{tokenAddress:le(t,"tokenAddress"),tokenSymbol:vo(t,"tokenSymbol"),available:le(t,"available"),availableRaw:le(t,"availableRaw"),locked:le(t,"locked"),lockedRaw:le(t,"lockedRaw"),total:le(t,"total"),totalRaw:le(t,"totalRaw"),version:rT(t,"version"),reason:le(t,"reason"),referenceId:vo(t,"referenceId"),updatedAt:le(t,"updatedAt")}}function Ese(e){return dz(e)}function tz(e){if(!or(e))throw Error("Invalid order snapshot: item must be an object");let t=en(e),r=Se(t,"clientOrderId"),n=Se(t,"selfTradePreventionMode"),o=Of(t,"version");return{orderId:le(t,"orderId"),userId:le(t,"userId"),applicationId:le(t,"applicationId"),tradingPairId:le(t,"tradingPairId"),tradingPair:le(t,"tradingPair"),tradingMode:le(t,"tradingMode"),side:le(t,"side"),orderType:le(t,"orderType"),price:vo(t,"price"),quantity:le(t,"quantity"),quantityRaw:le(t,"quantityRaw"),filledQuantity:le(t,"filledQuantity"),filledQuantityRaw:le(t,"filledQuantityRaw"),remainingQuantity:vo(t,"remainingQuantity"),remainingQuantityRaw:vo(t,"remainingQuantityRaw"),status:le(t,"status"),timeInForce:vo(t,"timeInForce"),averageFillPrice:vo(t,"averageFillPrice"),createdAt:le(t,"createdAt"),updatedAt:vo(t,"updatedAt"),marginAccountId:vo(t,"marginAccountId"),positionId:vo(t,"positionId"),leverage:vo(t,"leverage"),reduceOnly:tT(t,"reduceOnly"),...r===void 0?{}:{clientOrderId:r},...n===void 0?{}:{selfTradePreventionMode:n},...o===void 0?{}:{version:o}}}function So(e,t,r){return(n)=>{try{if(!Array.isArray(n))throw Error(`Invalid ${e} snapshot: data must be an array`);let o=n.map(t);r(o)}catch(o){console.error(`WebSocket: Error processing ${e} snapshot`,o)}}}function nT(e,t={}){let r=null,n=t.session,o=0,i=null,s=null,a=t.autoReconnect??!0,c=t.maxReconnectAttempts??Number.POSITIVE_INFINITY,d=Number.isFinite(t.reconnectBaseDelayMs)&&t.reconnectBaseDelayMs>0?t.reconnectBaseDelayMs:mse,l=Number.isFinite(t.connectionTimeoutMs)&&t.connectionTimeoutMs>0?t.connectionTimeoutMs:lse,p=null,m=new Map,h=new Map,b=new Map,x=()=>{if(!r)return i?"reconnecting":"disconnected";switch(r.readyState){case WebSocket.CONNECTING:return"connecting";case WebSocket.OPEN:return"connected";default:return i?"reconnecting":"disconnected"}},_=()=>e,w=()=>{if(!n||r?.readyState!==WebSocket.OPEN)return;let q=Date.now(),ne=U0(wf(n.privateKey),X8(n.publicKey,q));r.send(JSON.stringify({type:"Authenticate",public_key:n.publicKey,timestamp:q,signature:ne}))},A=()=>{if(s)clearInterval(s),s=null},v=()=>{A(),s=setInterval(()=>{if(r?.readyState===WebSocket.OPEN)r.send(JSON.stringify({type:"Ping"}))},pse)},T=()=>{if(i)clearTimeout(i),i=null},P=()=>{if(i)return;if(!a||o>=c){console.error("WebSocket: Max reconnect attempts reached");return}let q=Math.min(d*2**o,fse);o++;let ne=Math.random()*q;i=setTimeout(()=>{if(i=null,!a)return;K().catch((ce)=>{console.warn("WebSocket: Failed to reconnect:",ce),P()})},ne),t.onStatusChange?.("reconnecting")},k=(q)=>{if(r?.readyState===WebSocket.OPEN)r.send(JSON.stringify(q))},O=()=>{b.clear();let q=Array.from(m.keys());if(q.length>0)k({type:"Subscribe",channels:q})},N=(q)=>q.startsWith("ohlcv:")&&q.split(":").length===4,j=(q,ne)=>{if(q.endsWith(":*"))return ne.startsWith(q.slice(0,-1));if(N(q))return ne===q||ne===`${q}:trade`;return ne===q||ne.startsWith(`${q}:`)},R=(q)=>{if(q.type==="Error"){if(typeof q.code==="string"&&typeof q.message==="string")t.onError?.({code:q.code,message:q.message});return}if(!q.channel)return;if(q.type==="Snapshot"){for(let ne of h.get(q.channel)??[])ne(q.data);return}if(q.type!=="Event")return;for(let[ne,ce]of m)if(j(ne,q.channel))for(let he of ce)he(q.data)},K=()=>new Promise((q,ne)=>{if(r?.readyState===WebSocket.CONNECTING||r?.readyState===WebSocket.OPEN){q();return}try{let ce=new WebSocket(_());r=ce;let he=setTimeout(()=>{if(r!==ce){q();return}if(ce.readyState===WebSocket.CONNECTING)ce.close(1000,"Connection timeout"),ne(Error("WebSocket connection timeout"))},l);ce.onopen=()=>{if(clearTimeout(he),r!==ce){q();return}if(o=0,T(),v(),w(),O(),t.onStatusChange?.("connected"),p!==null){let Q=p;p=null,t.onResync?.({code:Q,slowClient:Q===1013})}q()},ce.onmessage=(Q)=>{if(r!==ce)return;try{let Be=JSON.parse(Q.data);if(Be.type==="Pong")return;if(Be.type==="Ping"){k({type:"Pong"});return}R(Be)}catch(Be){console.warn("WebSocket: Failed to parse message",Be)}},ce.onclose=(Q)=>{if(clearTimeout(he),r!==ce){q();return}if(r=null,A(),a&&Q.code!==1000){if(p===null||Q.code===1013)p=Q.code;P()}if(!i)t.onStatusChange?.("disconnected")},ce.onerror=()=>clearTimeout(he)}catch(ce){t.onStatusChange?.("disconnected"),ne(ce)}}),Z=()=>{a=!1,T(),A(),p=null,m.clear(),h.clear(),b.clear(),r?.close(1000,"Client disconnect"),r=null,t.onStatusChange?.("disconnected")},re=(q,ne,ce)=>{let he=!m.has(q);if(!m.has(q))m.set(q,new Set);if(m.get(q)?.add(ne),ce){if(!h.has(q))h.set(q,new Set);h.get(q)?.add(ce)}if(he&&r?.readyState===WebSocket.OPEN)k({type:"Subscribe",channels:[q]});return()=>{if(ce){let Be=h.get(q);if(Be?.delete(ce),Be?.size===0)h.delete(q)}let Q=m.get(q);if(Q){if(Q.delete(ne),Q.size===0){if(m.delete(q),r?.readyState===WebSocket.OPEN)k({type:"Unsubscribe",channels:[q]})}}}};return{connect:K,disconnect:Z,isConnected:()=>r?.readyState===WebSocket.OPEN,getStatus:x,setSessionKeypair:(q)=>{if(n=q??void 0,n&&r?.readyState===WebSocket.OPEN)w();else if(n&&(!r||r.readyState===WebSocket.CLOSED))K().catch((ne)=>{console.warn("WebSocket: Failed to connect after session update:",ne)})},orders:(q,ne,ce,he)=>{let Q=`orders:${q}:${ne}`;return re(Q,(Be)=>{try{let bt=Be,xt={orderId:bt.order_id,eventType:bt.event_type,timestamp:bt.timestamp,data:en(bt.data)};ce(xt)}catch(bt){console.error("WebSocket: Error processing order event",bt)}},he&&So("orders",tz,he))},orderbook:(q,ne,ce,he,Q)=>{if(!q||!ne||ce===void 0||!he)throw Error(`orderbook subscription requires all params: tradingPairId="${q}", tradingMode="${ne}", magnitude=${ce} (valid: ${Rf.join(", ")}), quotationMode="${he}" (valid: "BASE", "QUOTE")`);if(!Rf.includes(ce))throw Error(`Invalid magnitude: ${ce}. Must be one of: ${Rf.join(", ")}`);let Be=`orderbook:${q}:${ne}:${ce}:${he.toLowerCase()}`;return re(Be,(bt)=>{try{let xt=bt,Qe=xt.data,vt={tradingPairId:xt.trading_pair_id,tradingMode:xt.trading_mode,bids:(Qe?.bids||[]).map((wt)=>({price:wt.price,quantity:wt.quantity,orderCount:wt.order_count||0})),asks:(Qe?.asks||[]).map((wt)=>({price:wt.price,quantity:wt.quantity,orderCount:wt.order_count||0})),bestBid:Qe?.best_bid??void 0,bestAsk:Qe?.best_ask??void 0,bidVolume:Qe?.bid_volume||void 0,askVolume:Qe?.ask_volume||void 0,priceChange:Qe?.price_change?{side:Qe.price_change.side,oldPrice:Qe.price_change.old_price??void 0,newPrice:Qe.price_change.new_price??void 0,levelRemoved:Qe.price_change.level_removed||!1,levelAdded:Qe.price_change.level_added||!1}:void 0,baseDecimals:xt.base_decimals||0,quoteDecimals:xt.quote_decimals||0,timestamp:xt.timestamp||new Date().toISOString(),sequence:xt.sequence_number||0};Q(vt)}catch(xt){console.error("WebSocket: Error processing orderbook event",xt)}})},ohlcv:(q,ne,ce,he,Q)=>{let Be=Q===void 0?`ohlcv:${q}:${ne}:${ce}`:`ohlcv:${q}:${ne}:${ce}:${Q}`;return re(Be,(bt)=>{try{let xt=bt,{data:Qe,price_type:vt}=xt,wt=typeof vt==="string"&&vt!==""?vt:void 0,Hr={tradingPairId:xt.trading_pair_id,tradingMode:xt.trading_mode,interval:xt.interval,priceType:wt,candlestick:{T:Qe.period_start||0,t:Qe.period_end||0,o:Qe.open||"0",h:Qe.high||"0",l:Qe.low||"0",c:Qe.close||"0",v:Qe.volume||"0",s:xt.symbol,i:xt.interval,n:Qe.trades_count||0}};he(Hr)}catch(xt){console.error("WebSocket: Error processing OHLCV event",xt)}})},trades:(q,ne)=>{let ce=`trades:${q}`;return re(ce,(he)=>{try{let Q=he,Be=Q.data,bt={eventType:"trade",tradingPairId:Q.trading_pair_id,tradingMode:Q.trading_mode.toUpperCase(),data:{tradeId:Be.trade_id,price:Be.price,quantity:Be.quantity,makerSide:Be.maker_side.toUpperCase(),executedAt:Be.executed_at}};ne(bt)}catch(Q){console.error("WebSocket: Error processing trade event",Q)}})},movements:(q)=>re("movements",(ce)=>{try{let he=ce,Q=he.data,Be={eventType:"movement",userId:he.user_id,data:{id:Q.id,entryType:Q.entry_type,transactionType:Q.transaction_type,status:Q.status,token:Q.token??Q.token_address,tokenAddress:Q.token??Q.token_address,assetId:Q.asset_id,symbol:Q.symbol,amount:String(Q.amount),amountRaw:Q.amount_raw,balanceBefore:Q.balance_before!=null?String(Q.balance_before):void 0,balanceBeforeRaw:Q.balance_before_raw,balanceAfter:Q.balance_after!=null?String(Q.balance_after):void 0,balanceAfterRaw:Q.balance_after_raw,lockedBefore:Q.locked_before!=null?String(Q.locked_before):void 0,lockedBeforeRaw:Q.locked_before_raw,lockedAfter:Q.locked_after!=null?String(Q.locked_after):void 0,lockedAfterRaw:Q.locked_after_raw,referenceId:Q.reference_id,referenceType:Q.reference_type,description:Q.description,txHash:Q.tx_hash,blockNumber:Q.block_number,createdAt:Q.created_at,decimals:Q.decimals}};q(Be)}catch(he){console.error("WebSocket: Error processing movement event",he)}}),userOrders:(q,ne)=>re("orders",(he)=>{try{let Q=he,Be={orderId:Q.order_id,eventType:Q.event_type,timestamp:Q.timestamp,data:en(Q.data)};q(Be)}catch(Q){console.error("WebSocket: Error processing user order event",Q)}},ne&&So("orders",tz,ne)),balances:(q,ne)=>re("balances",(he)=>{try{if(!or(he))throw Error("Invalid balance event: payload must be an object");let Q={eventType:"balance_update",userId:le(he,"user_id"),data:dz(he.data)};q(Q)}catch(Q){console.error("WebSocket: Error processing balance event",Q)}},ne&&So("balances",Ese,ne)),conditionalOrders:(q,ne,ce)=>{if(!q)throw Error("conditionalOrders subscription requires a handler");if(ne!==void 0&&ne.length===0)throw Error("conditionalOrders tradingPairId cannot be empty");let he=ne?`conditional_orders:${ne}`:"conditional_orders";return re(he,(Q)=>{try{q(yse(Q))}catch(Be){console.error("WebSocket: Error processing conditional order event",Be)}},ce&&So("conditional orders",rz,ce))},twapOrders:(q,ne,ce)=>{if(!q)throw Error("twapOrders subscription requires a handler");if(ne!==void 0&&ne.length===0)throw Error("twapOrders tradingPairId cannot be empty");let he=ne?`twap_orders:${ne}`:"twap_orders";return re(he,(Q)=>{try{q(Tse(Q))}catch(Be){console.error("WebSocket: Error processing TWAP order event",Be)}},ce&&So("TWAP orders",uz,ce))},positions:(q,ne,ce)=>{if(!q)throw Error("positions subscription requires a handler");if(ne!==void 0&&ne.length===0)throw Error("positions tradingPairId cannot be empty");let he=ne?`positions:${ne}`:"positions";return re(he,(Q)=>{try{q(bse(Q))}catch(Be){console.error("WebSocket: Error processing position event",Be)}},ce&&So("positions",nz,ce))},liquidations:(q,ne,ce)=>{if(!q)throw Error("liquidations subscription requires a handler");if(ne!==void 0&&ne.length===0)throw Error("liquidations tradingPairId cannot be empty");let he=ne?`liquidations:${ne}`:"liquidations";return re(he,(Q)=>{try{q(xse(Q))}catch(Be){console.error("WebSocket: Error processing liquidation event",Be)}},ce&&So("liquidations",oz,ce))},account:(q,ne)=>{if(!q)throw Error("account subscription requires a handler");return re("account",(ce)=>{try{q(_se(ce))}catch(he){console.error("WebSocket: Error processing account event",he)}},ne&&So("account",iz,ne))},instruments:(q,ne,ce)=>{if(!q)throw Error("instruments subscription requires a handler");if(ne!==void 0&&ne.length===0)throw Error("instruments tradingPairId cannot be empty");let he=ne?`instrument:${ne}`:"instrument",Q=(Qe)=>{let vt=b.get(he);if(!vt)vt=new Map,b.set(he,vt);vt.set(Qe.tradingPairId,Qe)},Be=m.has(he),bt=!1,xt=re(he,(Qe)=>{try{let vt=vse(Qe);Q(vt),q(vt)}catch(vt){console.error("WebSocket: Error processing instrument event",vt)}},So("instrument",cz,(Qe)=>{let vt=Qe.map((wt)=>({tradingPairId:wt.tradingPairId,data:wt}));if(b.set(he,new Map(vt.map((wt)=>[wt.tradingPairId,wt]))),ce){ce(Qe);return}for(let wt of vt)q(wt)}));if(Be&&r?.readyState===WebSocket.OPEN){if(b.has(he))queueMicrotask(()=>{if(bt)return;let Qe=b.get(he);if(!Qe||r?.readyState!==WebSocket.OPEN)return;let vt=[...Qe.values()];if(ce){try{ce(vt.filter((wt)=>wt.data.isActive).map((wt)=>wt.data))}catch(wt){console.error("WebSocket: Error processing instrument baseline replay",wt)}return}for(let wt of vt)try{q(wt)}catch(Hr){console.error("WebSocket: Error processing instrument baseline replay",Hr)}})}return()=>{if(bt=!0,xt(),!m.has(he))b.delete(he)}},marketStats:(q,ne,ce)=>{if(!q)throw Error("marketStats subscription requires a tradingPairId");if(!ne)throw Error("marketStats subscription requires a handler");return re(`market_stats:${q}`,(he)=>{try{ne(wse(he))}catch(Q){console.error("WebSocket: Error processing market stats event",Q)}},ce&&So("market stats",sz,ce))},marketStatsAll:(q,ne)=>{if(!q)throw Error("marketStatsAll subscription requires a handler");return re("market_stats",(ce)=>{if(!or(ce)||!Array.isArray(ce.markets))return;try{q(Sse(ce))}catch(he){console.error("WebSocket: Error processing market stats all event",he)}},ne&&So("all-markets stats",az,ne))}}}var ia=Vr(q0(),1),SB=["token","accessToken","access_token","refreshToken","refresh_token","authToken","auth_token","bearerToken","bearer_token","jwtToken","jwt_token","apiKey","api_key","apikey","clientSecret","client_secret","clientId","client_id","secret","password","authorization","bearer","auth","credentials","credential","email","phone","phoneNumber","phone_number","ssn","socialSecurity","social_security","address","passport","passportNumber","passport_number","driversLicense","drivers_license","cardNumber","card_number","creditCard","credit_card","cvv","pin","signature","privateKey","private_key","publicKey","public_key","mnemonic","seed","salt","hash","certificate","cert","fingerprint","cookie","session","sessionId","session_id","sessionToken","session_token","ipAddress","ip_address","deviceId","device_id","userId","user_id","accountId","account_id"];function nd(e,t=5,r=0){if(r>=t)return"[Max depth reached]";if(e===null||e===void 0)return e;if(Array.isArray(e)){let o=e.slice(0,10).map((i)=>nd(i,t,r+1));if(e.length>10)o.push(`[... ${e.length-10} more items]`);return o}if(typeof e==="object"){let n={};for(let[o,i]of Object.entries(e)){let s=o.toLowerCase();if(SB.some((c)=>s.includes(c.toLowerCase())))n[o]="[REDACTED]";else if(typeof i==="string"&&i.length>500)n[o]=`${i.substring(0,500)}... [truncated]`;else n[o]=nd(i,t,r+1)}return n}if(typeof e==="string"){if(e.length>1000)return`${e.substring(0,1000)}... [truncated]`;return e}return e}class od extends Error{cause;suggestion;retryable=!1;timestamp;constructor(e,t){super(e);if(this.name=this.constructor.name,this.timestamp=Date.now(),t?.cause)this.cause=t.cause;if(t?.suggestion)this.suggestion=t.suggestion;if(t?.retryable!==void 0)this.retryable=t.retryable}toJSON(){return{name:this.name,code:this.code,message:this.message,suggestion:this.suggestion,retryable:this.retryable,timestamp:this.timestamp,cause:this.cause instanceof Error?this.cause.message:this.cause}}}class At extends od{code="INVALID_CONFIG";field;value;constructor(e,t,r,n){let o=t?`Check the '${t}' configuration parameter. ${Use(t)}`:"Review your SDK configuration and ensure all required fields are provided correctly.";super(e,{cause:n,suggestion:o,retryable:!1});this.field=t,this.value=r}toJSON(){let e;if(this.field){let t=this.field.toLowerCase();if(SB.some((n)=>t.includes(n.toLowerCase())))e="[REDACTED]";else e=nd(this.value)}else e=nd(this.value);return{...super.toJSON(),field:this.field,value:e}}}function Use(e){switch(e.toLowerCase()){case"walletclient":return"Ensure you're creating the wallet client with a valid account and chain configuration.";case"seirpcurl":return"Use 'https://evm-rpc-testnet.sei-apis.com' for testnet or 'https://evm-rpc.sei-apis.com' for mainnet.";case"wsurl":return"Use 'wss://ws-develop.apimonaco.xyz/ws' for testnet or 'wss://ws.apimonaco.xyz/ws' for mainnet.";case"network":return"Valid networks are: 'mainnet', 'development', 'staging', 'local'.";default:return"Refer to the SDK documentation for correct configuration format."}}class Cf extends od{code="INVALID_STATE";currentState;expectedState;constructor(e,t,r,n){let o=r?`${t?`Current state is '${t}', `:""}Expected state is '${r}'. Ensure operations are performed in the correct order.`:"Check that prerequisites are met before calling this method.";super(e,{cause:n,suggestion:o,retryable:!1});this.currentState=t,this.expectedState=r}toJSON(){return{...super.toJSON(),currentState:this.currentState,expectedState:this.expectedState}}}class Zt extends od{code="API_ERROR";endpoint;statusCode;responseBody;requestBody;requestId;retryAfter;constructor(e,t){let{suggestion:r,retryable:n}=Fse(t?.statusCode,e,t?.responseBody);super(e,{cause:t?.cause,suggestion:r,retryable:n});this.endpoint=t?.endpoint,this.statusCode=t?.statusCode,this.responseBody=t?.responseBody,this.requestBody=t?.requestBody,this.requestId=t?.requestId,this.retryAfter=t?.retryAfter}toJSON(){return{...super.toJSON(),endpoint:this.endpoint,statusCode:this.statusCode,responseBody:nd(this.responseBody),requestBody:nd(this.requestBody),requestId:this.requestId,retryAfter:this.retryAfter}}}function Fse(e,t,r){if(!e)return{suggestion:"Network request failed. Check your internet connection and try again.",retryable:!0};if(e===ia.StatusCodes.UNAUTHORIZED){if(t?.toLowerCase().includes("expired"))return{suggestion:"Access token has expired. Call sdk.refreshAuth() to get a new token, or call sdk.login() to re-authenticate.",retryable:!1};return{suggestion:"Authentication required. Call sdk.login(clientId) to authenticate before making this request.",retryable:!1}}if(e===ia.StatusCodes.FORBIDDEN)return{suggestion:"Access denied. Ensure your application has the required permissions and your client ID is valid.",retryable:!1};if(e===ia.StatusCodes.NOT_FOUND)return{suggestion:"Resource not found. Check that the ID or identifier is correct and the resource exists.",retryable:!1};if(e===ia.StatusCodes.CONFLICT)return{suggestion:"Resource conflict. The resource may have been modified. Refresh and try again.",retryable:!0};if(e===ia.StatusCodes.BAD_REQUEST){if(t?.toLowerCase().includes("insufficient balance"))return{suggestion:"Insufficient balance. Deposit more funds using sdk.vault.deposit() or reduce the order size.",retryable:!1};if(t?.toLowerCase().includes("invalid"))return{suggestion:"Invalid request parameters. Check the API documentation for correct parameter format and values.",retryable:!1};return{suggestion:"Bad request. Verify that all required parameters are provided and correctly formatted.",retryable:!1}}if(e===ia.StatusCodes.TOO_MANY_REQUESTS){let n;if(typeof r==="object"&&r!==null&&"retry_after"in r&&r.retry_after){let o=r.retry_after;n=` Wait ${String(o)} seconds before retrying.`}else n=" Wait a moment before retrying.";return{suggestion:`Rate limit exceeded.${n} Consider implementing exponential backoff for retries.`,retryable:!0}}if(e>=ia.StatusCodes.INTERNAL_SERVER_ERROR&&e<600)return{suggestion:"Server error occurred. This is likely a temporary issue. Try again in a few moments.",retryable:!0};return{suggestion:void 0,retryable:!1}}class Vi extends od{code="CONTRACT_ERROR";revertReason;transactionHash;contractAddress;constructor(e,t){let r=jse(t?.revertReason);super(e,{cause:t?.cause,suggestion:r,retryable:!1});this.revertReason=t?.revertReason,this.transactionHash=t?.transactionHash,this.contractAddress=t?.contractAddress}toJSON(){return{...super.toJSON(),revertReason:this.revertReason,transactionHash:this.transactionHash,contractAddress:this.contractAddress}}}function jse(e){if(!e)return"Smart contract execution failed. Check transaction parameters and try again.";let t=e.toLowerCase();if(t.includes("insufficient allowance"))return"Token allowance is insufficient. Call sdk.vault.approve() to increase the token allowance for the vault contract.";if(t.includes("insufficient balance"))return"Wallet balance is insufficient for this transaction. Ensure you have enough tokens and native currency for gas fees.";if(t.includes("nonce"))return"Transaction nonce error. This may be due to a pending transaction. Wait for pending transactions to complete or reset your account nonce.";if(t.includes("gas"))return"Transaction ran out of gas. Try increasing the gas limit for this transaction.";return}var qse={local:"http://localhost:8080",development:"https://develop.apimonaco.xyz",staging:"https://staging.apimonaco.xyz",mainnet:"https://api.monaco.xyz"},Hse={local:"ws://localhost:8085/ws",development:"wss://ws-develop.apimonaco.xyz/ws",staging:"wss://ws-staging.apimonaco.xyz/ws",mainnet:"wss://ws.apimonaco.xyz/ws"};function dT(e){return qse[e]}function lT(e){return Hse[e]}var ZA=Vr(q0(),1);var H0=256,G0;function V0(e=11){if(!G0||H0+e>512){G0="",H0=0;for(let t=0;t<256;t++)G0+=(256+Math.random()*256|0).toString(16).substring(1)}return G0.substring(H0,H0+++e)}function Z0(e){let{batch:t,chain:r,ccipRead:n,dataSuffix:o,key:i="base",name:s="Base Client",tokens:a,type:c="base"}=e,d=e.experimental_blockTag??(typeof r?.experimental_preconfirmationTime==="number"?"pending":void 0),l=r?.blockTime??12000,p=Math.min(Math.max(Math.floor(l/2),500),4000),m=e.pollingInterval??p,h=e.cacheTime??m,b=e.account?ze(e.account):void 0,{config:x,request:_,value:w}=e.transport({account:b,chain:r,pollingInterval:m}),A={...x,...w},v={account:b,batch:t,cacheTime:h,ccipRead:n,chain:r,dataSuffix:o,key:i,name:s,pollingInterval:m,request:_,tokens:a,transport:A,type:c,uid:V0(),...d?{experimental_blockTag:d}:{}};function T(P){return(k)=>{let O=k(P);for(let j in v)delete O[j];let N={...P,...O};for(let j in O){let R=P[j],K=O[j];if(vB(R)&&vB(K))N[j]={...R,...K}}return Object.assign(N,{extend:T(N)})}}return Object.assign(v,{extend:T(v)})}function vB(e){if(typeof e!=="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Qo(e,t){let r=(n={})=>t(e,n);for(let n of["call","calls","callWithPeriod","estimateGas","prepare","prepareRecipient","predict","simulate"])if(Object.hasOwn(t,n)){let o=t[n];r[n]=(i={})=>{if(o.length===1)return o(i);return o(e,i)}}for(let n of["extractEvent","extractEvents"])if(Object.hasOwn(t,n))r[n]=t[n];return r}Mr();rs();xn();ri();Ac();mn();Fe();Ge();os();function xd(e){if(!(e instanceof C))return!1;let t=e.walk((r)=>r instanceof bd);if(!(t instanceof bd))return!1;if(t.data?.errorName==="HttpError")return!0;if(t.data?.errorName==="ResolverError")return!0;if(t.data?.errorName==="ResolverNotContract")return!0;if(t.data?.errorName==="ResolverNotFound")return!0;if(t.data?.errorName==="ReverseAddressMismatch")return!0;if(t.data?.errorName==="UnsupportedResolverProfile")return!0;return!1}nm();xr();Fe();Jn();function Oy(e){if(e.length!==66)return null;if(e.indexOf("[")!==0)return null;if(e.indexOf("]")!==65)return null;let t=`0x${e.slice(1,65)}`;if(!Kt(t))return null;return t}function om(e){let t=new Uint8Array(32).fill(0);if(!e)return mt(t);let r=e.split(".");for(let n=r.length-1;n>=0;n-=1){let o=Oy(r[n]),i=o?Yn(o):St(Eo(r[n]),"bytes");t=St(fr([t,i]),"bytes")}return mt(t)}xr();function tL(e){return`[${e.slice(2)}]`}xr();Fe();Jn();function rL(e){let t=new Uint8Array(32).fill(0);if(!e)return mt(t);return Oy(e)||St(Eo(e))}function _d(e){let t=e.replace(/^\.|\.$/gm,"");if(t.length===0)return new Uint8Array(1);let r=new Uint8Array(Eo(t).byteLength+2),n=0,o=t.split(".");for(let i=0;i<o.length;i++){let s=Eo(o[i]);if(s.byteLength>255)s=Eo(tL(rL(o[i])));r[n]=s.length,r.set(s,n+1),n+=s.length+1}if(r.byteLength!==n+1)return r.slice(0,n+1);return r}function J(e,t,r){let n=e[t.name];if(typeof n==="function")return n;let o=e[r];if(typeof o==="function")return o;return(i)=>t(e,i)}rs();xn();ir();Ge();os();Mc();Fd();var Wae=3;function Nn(e,{abi:t,address:r,args:n,docsPath:o,functionName:i,sender:s}){let a=e instanceof ns?e:e instanceof C?e.walk((b)=>("data"in b))||e.walk():{},{code:c,data:d,details:l,message:p,shortMessage:m}=a,h=(()=>{if(e instanceof To)return new kE({functionName:i,cause:e});if([Wae,ss.code].includes(c)&&(d||l||p||m)||c===Xn.code&&l==="execution reverted"&&d)return new bd({abi:t,data:typeof d==="object"?d.data:d,functionName:i,message:a instanceof Cc?l:m??p,cause:e});return e})();return new rm(h,{abi:t,args:n,contractAddress:r,docsPath:o,functionName:i,sender:s})}ga();async function gt(e,t){let{abi:r,address:n,args:o,functionName:i,...s}=t,a=It({abi:r,args:o,functionName:i});try{let{data:c}=await J(e,Sn,"call")({...s,data:a,to:n});return Dr({abi:r,args:o,functionName:i,data:c||"0x"})}catch(c){throw Nn(c,{abi:r,address:n,args:o,docsPath:"/docs/contract/readContract",functionName:i})}}async function BL(e,t){let{blockNumber:r,blockTag:n,coinType:o,name:i,gatewayUrls:s,strict:a}=t,{chain:c}=e,d=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw Error("client chain not configured. universalResolverAddress is required.");return Qn({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),l=c?.ensTlds;if(l&&!l.some((m)=>i.endsWith(m)))return null;let p=(()=>{if(o!=null)return[om(i),BigInt(o)];return[om(i)]})();try{let m=It({abi:fT,functionName:"addr",args:p}),h={address:d,abi:K0,functionName:"resolveWithGateways",args:[Jt(_d(i)),m,s??[is]],blockNumber:r,blockTag:n},x=await J(e,gt,"readContract")(h);if(x[0]==="0x")return null;let _=yce({coinType:o,data:x[0],args:p});if(_==="0x")return null;if($r(_)==="0x00")return null;return _}catch(m){if(a)throw m;if(xd(m))return null;throw m}}function yce({coinType:e,data:t,args:r}){try{return Dr({abi:fT,args:r,functionName:"addr",data:t})}catch(n){if(e==null)throw n;let o=$r(t);if(et(o)===20)return Ao(o);throw n}}Ge();class oP extends C{constructor({data:e}){super("Unable to extract image from metadata. The metadata may be malformed or invalid.",{metaMessages:["- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.","",`Provided data: ${JSON.stringify(e)}`],name:"EnsAvatarInvalidMetadataError"})}}class Dc extends C{constructor({reason:e}){super(`ENS NFT avatar URI is invalid. ${e}`,{name:"EnsAvatarInvalidNftUriError"})}}class hm extends C{constructor({uri:e}){super(`Unable to resolve ENS avatar URI "${e}". The URI may be malformed, invalid, or does not respond with a valid image.`,{name:"EnsAvatarUriResolutionError"})}}class iP extends C{constructor({namespace:e}){super(`ENS NFT avatar namespace "${e}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}}var bce=/(?<protocol>https?:\/\/[^/]*|ipfs:\/|ipns:\/|ar:\/)?(?<root>\/)?(?<subpath>ipfs\/|ipns\/)?(?<target>[\w\-.]+)(?<subtarget>\/.*)?/,xce=/^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?<target>[\w\-.]+))?(?<subtarget>\/.*)?$/,_ce=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,wce=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;async function Sce(e){try{let t=await fetch(e,{method:"HEAD"});if(t.status===200)return t.headers.get("content-type")?.startsWith("image/");return!1}catch(t){if(typeof t==="object"&&typeof t.response<"u")return!1;if(!Object.hasOwn(globalThis,"Image"))return!1;return new Promise((r)=>{let n=new Image;n.onload=()=>{r(!0)},n.onerror=()=>{r(!1)},n.src=e})}}function LL(e,t){if(!e)return t;if(e.endsWith("/"))return e.slice(0,-1);return e}function sP({uri:e,gatewayUrls:t}){let r=_ce.test(e);if(r)return{uri:e,isOnChain:!0,isEncoded:r};let n=LL(t?.ipfs,"https://ipfs.io"),o=LL(t?.arweave,"https://arweave.net"),i=e.match(bce),{protocol:s,subpath:a,target:c,subtarget:d=""}=i?.groups||{},l=s==="ipns:/"||a==="ipns/",p=s==="ipfs:/"||a==="ipfs/"||xce.test(e);if(e.startsWith("http")&&!l&&!p){let h=e;if(t?.arweave)h=e.replace(/https:\/\/arweave.net/g,t?.arweave);return{uri:h,isOnChain:!1,isEncoded:!1}}if((l||p)&&c)return{uri:`${n}/${l?"ipns":"ipfs"}/${c}${d}`,isOnChain:!1,isEncoded:!1};if(s==="ar:/"&&c)return{uri:`${o}/${c}${d||""}`,isOnChain:!1,isEncoded:!1};let m=e.replace(wce,"");if(m.startsWith("<svg"))m=`data:image/svg+xml;base64,${btoa(m)}`;if(m.startsWith("data:")||m.startsWith("{"))return{uri:m,isOnChain:!0,isEncoded:!1};throw new hm({uri:e})}function aP(e){if(typeof e!=="object"||!("image"in e)&&!("image_url"in e)&&!("image_data"in e))throw new oP({data:e});return e.image||e.image_url||e.image_data}async function DL({gatewayUrls:e,uri:t}){try{let r=await fetch(t).then((o)=>o.json());return await Gy({gatewayUrls:e,uri:aP(r)})}catch{throw new hm({uri:t})}}async function Gy({gatewayUrls:e,uri:t}){let{uri:r,isOnChain:n}=sP({uri:t,gatewayUrls:e});if(n)return r;if(await Sce(r))return r;throw new hm({uri:t})}function UL(e){let t=e;if(t.startsWith("did:nft:"))t=t.replace("did:nft:","").replace(/_/g,"/");let[r,n,o]=t.split("/"),[i,s]=r.split(":"),[a,c]=n.split(":");if(!i||i.toLowerCase()!=="eip155")throw new Dc({reason:"Only EIP-155 supported"});if(!s)throw new Dc({reason:"Chain ID not found"});if(!c)throw new Dc({reason:"Contract address not found"});if(!o)throw new Dc({reason:"Token ID not found"});if(!a)throw new Dc({reason:"ERC namespace not found"});return{chainID:Number.parseInt(s,10),namespace:a.toLowerCase(),contractAddress:c,tokenID:o}}async function FL(e,{nft:t}){if(t.namespace==="erc721")return gt(e,{address:t.contractAddress,abi:[{name:"tokenURI",type:"function",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"tokenURI",args:[BigInt(t.tokenID)]});if(t.namespace==="erc1155")return gt(e,{address:t.contractAddress,abi:[{name:"uri",type:"function",stateMutability:"view",inputs:[{name:"_id",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"uri",args:[BigInt(t.tokenID)]});throw new iP({namespace:t.namespace})}async function jL(e,{gatewayUrls:t,record:r}){if(/eip155:/i.test(r))return vce(e,{gatewayUrls:t,record:r});return Gy({uri:r,gatewayUrls:t})}async function vce(e,{gatewayUrls:t,record:r}){let n=UL(r),o=await FL(e,{nft:n}),{uri:i,isOnChain:s,isEncoded:a}=sP({uri:o,gatewayUrls:t});if(s&&(i.includes("data:application/json;base64,")||i.startsWith("{"))){let d=a?atob(i.replace("data:application/json;base64,","")):i,l=JSON.parse(d);return Gy({uri:aP(l),gatewayUrls:t})}let c=n.tokenID;if(n.namespace==="erc1155")c=c.replace("0x","").padStart(64,"0");return DL({gatewayUrls:t,uri:i.replace(/(?:0x)?{id}/,c)})}Mr();rs();xn();Ac();Fe();nm();async function Vy(e,t){let{blockNumber:r,blockTag:n,key:o,name:i,gatewayUrls:s,strict:a}=t,{chain:c}=e,d=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw Error("client chain not configured. universalResolverAddress is required.");return Qn({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),l=c?.ensTlds;if(l&&!l.some((p)=>i.endsWith(p)))return null;try{let p={address:d,abi:K0,args:[Jt(_d(i)),It({abi:pT,functionName:"text",args:[om(i),o]}),s??[is]],functionName:"resolveWithGateways",blockNumber:r,blockTag:n},h=await J(e,gt,"readContract")(p);if(h[0]==="0x")return null;let b=Dr({abi:pT,functionName:"text",data:h[0]});return b===""?null:b}catch(p){if(a)throw p;if(xd(p))return null;throw p}}async function qL(e,{blockNumber:t,blockTag:r,assetGatewayUrls:n,name:o,gatewayUrls:i,strict:s,universalResolverAddress:a}){let c=await J(e,Vy,"getEnsText")({blockNumber:t,blockTag:r,key:"avatar",name:o,universalResolverAddress:a,gatewayUrls:i,strict:s});if(!c)return null;try{return await jL(e,{record:c,gatewayUrls:n})}catch{return null}}Mr();Ac();nm();async function HL(e,t){let{address:r,blockNumber:n,blockTag:o,coinType:i=60n,gatewayUrls:s,strict:a}=t,{chain:c}=e,d=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw Error("client chain not configured. universalResolverAddress is required.");return Qn({blockNumber:n,chain:c,contract:"ensUniversalResolver"})})();try{let l={address:d,abi:EB,args:[r,i,s??[is]],functionName:"reverseWithGateways",blockNumber:n,blockTag:o},p=J(e,gt,"readContract"),[m]=await p(l);return m||null}catch(l){if(a)throw l;if(xd(l))return null;throw l}}Ac();Fe();async function GL(e,t){let{blockNumber:r,blockTag:n,name:o}=t,{chain:i}=e,s=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!i)throw Error("client chain not configured. universalResolverAddress is required.");return Qn({blockNumber:r,chain:i,contract:"ensUniversalResolver"})})(),a=i?.ensTlds;if(a&&!a.some((d)=>o.endsWith(d)))throw Error(`${o} is not a valid ENS TLD (${a?.join(", ")}) for chain "${i.name}" (id: ${i.id}).`);let[c]=await J(e,gt,"readContract")({address:s,abi:[{inputs:[{type:"bytes"}],name:"findResolver",outputs:[{type:"address"},{type:"bytes32"},{type:"uint256"}],stateMutability:"view",type:"function"}],functionName:"findResolver",args:[Jt(_d(o))],blockNumber:r,blockTag:n});return c}ga();Ge();Fe();QE();ps();ci();async function VL(e,t){let{account:r=e.account,blockNumber:n,blockTag:o="latest",blobs:i,data:s,gas:a,gasPrice:c,maxFeePerBlobGas:d,maxFeePerGas:l,maxPriorityFeePerGas:p,to:m,value:h,...b}=t,x=r?ze(r):void 0;try{Sr(t);let w=(typeof n==="bigint"?G(n):void 0)||o,A=e.chain?.formatters?.transactionRequest?.format,T=(A||jr)({...ro(b,{format:A}),account:x,blobs:i,data:s,gas:a,gasPrice:c,maxFeePerBlobGas:d,maxFeePerGas:l,maxPriorityFeePerGas:p,to:m,value:h},"createAccessList"),P=await e.request({method:"eth_createAccessList",params:[T,w]});if(P.error)throw new C(P.error,{details:P.error});return{accessList:P.accessList,gasUsed:BigInt(P.gasUsed)}}catch(_){throw jy(_,{...t,account:x,chain:e.chain})}}function ya(e,{method:t}){let r={};if(e.transport.type==="fallback")e.transport.onResponse?.(({method:n,response:o,status:i,transport:s})=>{if(i==="success"&&t===n)r[o]=s.request});return(n)=>r[n]||e.request}async function ZL(e){let t=ya(e,{method:"eth_newBlockFilter"}),r=await e.request({method:"eth_newBlockFilter"});return{id:r,request:t(r),type:"block"}}ir();Ge();class cP extends C{constructor(e){super(`Filter type "${e}" is not supported.`,{name:"FilterTypeNotSupportedError"})}}xr();Jn();Jf();Qi();Zi();la();var WL="/docs/contract/encodeEventTopics";function ui(e){let{abi:t,eventName:r,args:n}=e,o=t[0];if(r){let c=bn({abi:t,name:r});if(!c)throw new Q0(r,{docsPath:WL});o=c}if(o.type!=="event")throw new Q0(void 0,{docsPath:WL});let i=[];if(n&&"inputs"in o){let c=o.inputs?.filter((l)=>("indexed"in l)&&l.indexed),d=Array.isArray(n)?n:Object.values(n).length>0?c?.map((l)=>n[l.name])??[]:[];if(d.length>0)i=c?.map((l,p)=>{if(Array.isArray(d[p]))return d[p].map((m,h)=>KL({param:l,value:d[p][h]}));return typeof d[p]<"u"&&d[p]!==null?KL({param:l,value:d[p]}):null})??[]}if(o.anonymous)return i;let s=dr(o);return[da(s),...i]}function KL({param:e,value:t}){if(e.type==="string"||e.type==="bytes")return St(Yn(t));if(e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/))throw new cP(e.type);return nn([e],[t])}Fe();async function Zy(e,t){let{address:r,abi:n,args:o,eventName:i,fromBlock:s,strict:a,toBlock:c}=t,d=ya(e,{method:"eth_newFilter"}),l=i?ui({abi:n,args:o,eventName:i}):void 0,p=await e.request({method:"eth_newFilter",params:[{address:r,fromBlock:typeof s==="bigint"?G(s):s,toBlock:typeof c==="bigint"?G(c):c,topics:l}]});return{abi:n,args:o,eventName:i,id:p,request:d(p),strict:Boolean(a),type:"event"}}Fe();async function Wy(e,{address:t,args:r,event:n,events:o,fromBlock:i,strict:s,toBlock:a}={}){let c=o??(n?[n]:void 0),d=ya(e,{method:"eth_newFilter"}),l=[];if(c){if(l=[c.flatMap((h)=>ui({abi:[h],eventName:h.name,args:r}))],n)l=l[0]}let p=await e.request({method:"eth_newFilter",params:[{address:t,fromBlock:typeof i==="bigint"?G(i):i,toBlock:typeof a==="bigint"?G(a):a,...l.length?{topics:l}:{}}]});return{abi:c,args:r,eventName:n?n.name:void 0,fromBlock:i,id:p,request:d(p),strict:Boolean(s),toBlock:a,type:"event"}}async function Ky(e){let t=ya(e,{method:"eth_newPendingTransactionFilter"}),r=await e.request({method:"eth_newPendingTransactionFilter"});return{id:r,request:t(r),type:"transaction"}}xn();Ge();ri();Jn();function Yy(e){let t=St(`0x${e.substring(4)}`).substring(26);return Yi(`0x${t}`)}mn();lr();Fe();async function a9({hash:e,signature:t}){let r=Kt(e)?e:Jt(e);await Promise.resolve().then(() => gm());return`0x${(()=>{if(typeof t==="object"&&"r"in t&&"s"in t){let{r:d,s:l,v:p,yParity:m}=t,h=Number(m??p),b=s9(h);return new hs.Signature(er(d),er(l)).addRecoveryBit(b)}let s=Kt(t)?t:Jt(t);if(et(s)!==65)throw Error("invalid signature length");let a=Yt(`0x${s.slice(130)}`),c=s9(a);return hs.Signature.fromCompact(s.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function s9(e){if(e===0||e===1)return e;if(e===27)return 0;if(e===28)return 1;throw Error("Invalid yParityOrV value")}async function ym({hash:e,signature:t}){return Yy(await a9({hash:e,signature:t}))}xr();Fe();Ge();uy();xr();Fe();function gs(e,t="hex"){let r=c9(e),n=sd(new Uint8Array(r.length));if(r.encode(n),t==="hex")return mt(n.bytes);return n.bytes}function c9(e){if(Array.isArray(e))return Cce(e.map((t)=>c9(t)));return Mce(e)}function Cce(e){let t=e.reduce((o,i)=>o+i.length,0),r=u9(t);return{length:(()=>{if(t<=55)return 1+t;return 1+r+t})(),encode(o){if(t<=55)o.pushByte(192+t);else if(o.pushByte(247+r),r===1)o.pushUint8(t);else if(r===2)o.pushUint16(t);else if(r===3)o.pushUint24(t);else o.pushUint32(t);for(let{encode:i}of e)i(o)}}}function Mce(e){let t=typeof e==="string"?pr(e):e,r=u9(t.length);return{length:(()=>{if(t.length===1&&t[0]<128)return 1;if(t.length<=55)return 1+t.length;return 1+r+t.length})(),encode(o){if(t.length===1&&t[0]<128)o.pushBytes(t);else if(t.length<=55)o.pushByte(128+t.length),o.pushBytes(t);else{if(o.pushByte(183+r),r===1)o.pushUint8(t.length);else if(r===2)o.pushUint16(t.length);else if(r===3)o.pushUint24(t.length);else o.pushUint32(t.length);o.pushBytes(t)}}}}function u9(e){if(e<256)return 1;if(e<65536)return 2;if(e<16777216)return 3;if(e<4294967296)return 4;throw new C("Length is too large.")}Jn();function Jy(e){let{chainId:t,nonce:r,to:n}=e,o=e.contractAddress??e.address,i=St(Qt(["0x05",gs([t?G(t):"0x",o,r?G(r):"0x"])]));if(n==="bytes")return pr(i);return i}async function ba(e){let{authorization:t,signature:r}=e;return ym({hash:Jy(t),signature:r??t})}Fe();Ry();gd();Ge();on();class hP extends C{constructor(e,{account:t,docsPath:r,chain:n,data:o,gas:i,gasPrice:s,maxFeePerGas:a,maxPriorityFeePerGas:c,nonce:d,to:l,value:p}){let m=Ic({from:t?.address,to:l,value:typeof p<"u"&&`${hd(p)} ${n?.nativeCurrency?.symbol||"ETH"}`,data:o,gas:i,gasPrice:typeof s<"u"&&`${mr(s)} gwei`,maxFeePerGas:typeof a<"u"&&`${mr(a)} gwei`,maxPriorityFeePerGas:typeof c<"u"&&`${mr(c)} gwei`,nonce:d});super(e.shortMessage,{cause:e,docsPath:r,metaMessages:[...e.metaMessages?[...e.metaMessages," "]:[],"Estimate Gas Arguments:",m].filter(Boolean),name:"EstimateGasExecutionError"});Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=e}}ls();mm();function d9(e,{docsPath:t,...r}){let n=(()=>{let o=ha(e,r);if(o instanceof Co)return e;return o})();return new hP(n,{docsPath:t,...r})}ps();Hy();ci();gd();Ge();class bm extends C{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class Uc extends C{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class gP extends C{constructor({maxPriorityFeePerGas:e}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${mr(e)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}lr();Ge();class Fc extends C{constructor({blockHash:e,blockNumber:t}){let r="Block";if(e)r=`Block at hash "${e}"`;if(t)r=`Block at number "${t}"`;super(`${r} could not be found.`,{name:"BlockNotFoundError"})}}Fe();lr();var yP={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function Yd(e,t){let r={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,...e.blockTimestamp!=null&&{blockTimestamp:BigInt(e.blockTimestamp)},chainId:e.chainId?Yt(e.chainId):void 0,gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,maxFeePerBlobGas:e.maxFeePerBlobGas?BigInt(e.maxFeePerBlobGas):void 0,maxFeePerGas:e.maxFeePerGas?BigInt(e.maxFeePerGas):void 0,maxPriorityFeePerGas:e.maxPriorityFeePerGas?BigInt(e.maxPriorityFeePerGas):void 0,nonce:e.nonce?Yt(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?yP[e.type]:void 0,typeHex:e.type?e.type:void 0,value:e.value?BigInt(e.value):void 0,v:e.v?BigInt(e.v):void 0};if(e.authorizationList)r.authorizationList=$ce(e.authorizationList);if(r.yParity=(()=>{if(e.yParity)return Number(e.yParity);if(typeof r.v==="bigint"){if(r.v===0n||r.v===27n)return 0;if(r.v===1n||r.v===28n)return 1;if(r.v>=35n)return r.v%2n===0n?1:0}return})(),r.type==="legacy")delete r.accessList,delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas,delete r.yParity;if(r.type==="eip2930")delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas;if(r.type==="eip1559")delete r.maxFeePerBlobGas;return r}function $ce(e){return e.map((t)=>({address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce),r:t.r,s:t.s,yParity:Number(t.yParity)}))}function Jd(e,t){let r=(e.transactions??[]).map((n)=>{if(typeof n==="string")return n;return Yd(n)});return{...e,baseFeePerGas:e.baseFeePerGas?BigInt(e.baseFeePerGas):null,blobGasUsed:e.blobGasUsed?BigInt(e.blobGasUsed):void 0,difficulty:e.difficulty?BigInt(e.difficulty):void 0,excessBlobGas:e.excessBlobGas?BigInt(e.excessBlobGas):void 0,gasLimit:e.gasLimit?BigInt(e.gasLimit):void 0,gasUsed:e.gasUsed?BigInt(e.gasUsed):void 0,hash:e.hash?e.hash:null,logsBloom:e.logsBloom?e.logsBloom:null,nonce:e.nonce?e.nonce:null,number:e.number?BigInt(e.number):null,size:e.size?BigInt(e.size):void 0,timestamp:e.timestamp?BigInt(e.timestamp):void 0,transactions:r,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}async function ar(e,{blockHash:t,blockNumber:r,blockTag:n=e.experimental_blockTag??"latest",includeTransactions:o}={}){let i=o??!1,s=r!==void 0?G(r):void 0,a=null;if(t)a=await e.request({method:"eth_getBlockByHash",params:[t,i]},{dedupe:!0});else a=await e.request({method:"eth_getBlockByNumber",params:[s||n,i]},{dedupe:Boolean(s)});if(!a)throw new Fc({blockHash:t,blockNumber:r});return(e.chain?.formatters?.block?.format||Jd)(a,"getBlock")}async function Qd(e){let t=await e.request({method:"eth_gasPrice"});return BigInt(t)}async function l9(e,t){return bP(e,t)}async function bP(e,t){let{block:r,chain:n=e.chain,request:o}=t||{};try{let i=n?.fees?.maxPriorityFeePerGas??n?.fees?.defaultPriorityFee;if(typeof i==="function"){let a=r||await J(e,ar,"getBlock")({}),c=await i({block:a,client:e,request:o});if(c===null)throw Error();return c}if(typeof i<"u")return i;let s=await e.request({method:"eth_maxPriorityFeePerGas"});return er(s)}catch{let[i,s]=await Promise.all([r?Promise.resolve(r):J(e,ar,"getBlock")({}),J(e,Qd,"getGasPrice")({})]);if(typeof i.baseFeePerGas!=="bigint")throw new Uc;let a=s-i.baseFeePerGas;if(a<0n)return 0n;return a}}async function p9(e,t){return Qy(e,t)}async function Qy(e,t){let{block:r,chain:n=e.chain,request:o,type:i="eip1559"}=t||{},s=await(async()=>{if(typeof n?.fees?.baseFeeMultiplier==="function")return n.fees.baseFeeMultiplier({block:r,client:e,request:o});return n?.fees?.baseFeeMultiplier??1.2})();if(s<1)throw new bm;let c=10**(s.toString().split(".")[1]?.length??0),d=(m)=>m*BigInt(Math.round(s*c))/BigInt(c),l=r?r:await J(e,ar,"getBlock")({});if(typeof n?.fees?.estimateFeesPerGas==="function"){let m=await n.fees.estimateFeesPerGas({block:r,client:e,multiply:d,request:o,type:i});if(m!==null)return m}if(i==="eip1559"){if(typeof l.baseFeePerGas!=="bigint")throw new Uc;let m=typeof o?.maxPriorityFeePerGas==="bigint"?o.maxPriorityFeePerGas:await bP(e,{block:l,chain:n,request:o}),h=d(l.baseFeePerGas);return{maxFeePerGas:o?.maxFeePerGas??h+m,maxPriorityFeePerGas:m}}return{gasPrice:o?.gasPrice??d(await J(e,Qd,"getGasPrice")({}))}}Lc();lr();async function Xd(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:i}){let s=Bn({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:i}),a=await e.request({method:"eth_getTransactionCount",params:[t,s]},{dedupe:typeof n==="bigint"||r!==void 0});return Yt(a)}on();xr();Fe();function el(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]==="string"?"hex":"bytes"),n=typeof e.blobs[0]==="string"?e.blobs.map((i)=>pr(i)):e.blobs,o=[];for(let i of n)o.push(Uint8Array.from(t.blobToKzgCommitment(i)));return r==="bytes"?o:o.map((i)=>mt(i))}xr();Fe();function tl(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]==="string"?"hex":"bytes"),n=typeof e.blobs[0]==="string"?e.blobs.map((s)=>pr(s)):e.blobs,o=typeof e.commitments[0]==="string"?e.commitments.map((s)=>pr(s)):e.commitments,i=[];for(let s=0;s<n.length;s++){let a=n[s],c=o[s];i.push(Uint8Array.from(t.computeBlobKzgProof(a,c)))}return r==="bytes"?i:i.map((s)=>mt(s))}Fe();ay();function Nce(e,t,r,n){if(typeof e.setBigUint64==="function")return e.setBigUint64(t,r,n);let o=BigInt(32),i=BigInt(4294967295),s=Number(r>>o&i),a=Number(r&i),c=n?4:0,d=n?0:4;e.setUint32(t+c,s,n),e.setUint32(t+d,a,n)}function f9(e,t,r){return e&t^~e&r}function m9(e,t,r){return e&t^e&r^t&r}class xP extends jf{constructor(e,t,r,n){super();this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=iy(this.buffer)}update(e){id(this),e=Ff(e),Tc(e);let{view:t,buffer:r,blockLen:n}=this,o=e.length;for(let i=0;i<o;){let s=Math.min(n-this.pos,o-i);if(s===n){let a=iy(e);for(;n<=o-i;i+=n)this.process(a,i);continue}if(r.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===n)this.process(t,0),this.pos=0}return this.length+=e.length,this.roundClean(),this}digestInto(e){id(this),oy(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:o}=this,{pos:i}=this;if(t[i++]=128,ca(this.buffer.subarray(i)),this.padOffset>n-i)this.process(r,0),i=0;for(let l=i;l<n;l++)t[l]=0;Nce(r,n-8,BigInt(this.length*8),o),this.process(r,0);let s=iy(e),a=this.outputLen;if(a%4)throw Error("_sha2: outputLen should be aligned to 32bit");let c=a/4,d=this.get();if(c>d.length)throw Error("_sha2: outputLen bigger than state");for(let l=0;l<c;l++)s.setUint32(4*l,d[l],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:r,length:n,finished:o,destroyed:i,pos:s}=this;if(e.destroyed=i,e.finished=o,e.length=n,e.pos=s,n%t)e.buffer.set(r);return e}clone(){return this._cloneInto()}}var ys=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);ay();var zce=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),xa=new Uint32Array(64);class _P extends xP{constructor(e=32){super(64,e,8,!1);this.A=ys[0]|0,this.B=ys[1]|0,this.C=ys[2]|0,this.D=ys[3]|0,this.E=ys[4]|0,this.F=ys[5]|0,this.G=ys[6]|0,this.H=ys[7]|0}get(){let{A:e,B:t,C:r,D:n,E:o,F:i,G:s,H:a}=this;return[e,t,r,n,o,i,s,a]}set(e,t,r,n,o,i,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=s|0,this.H=a|0}process(e,t){for(let l=0;l<16;l++,t+=4)xa[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let p=xa[l-15],m=xa[l-2],h=Po(p,7)^Po(p,18)^p>>>3,b=Po(m,17)^Po(m,19)^m>>>10;xa[l]=b+xa[l-7]+h+xa[l-16]|0}let{A:r,B:n,C:o,D:i,E:s,F:a,G:c,H:d}=this;for(let l=0;l<64;l++){let p=Po(s,6)^Po(s,11)^Po(s,25),m=d+p+f9(s,a,c)+zce[l]+xa[l]|0,b=(Po(r,2)^Po(r,13)^Po(r,22))+m9(r,n,o)|0;d=c,c=a,a=s,s=i+m|0,i=o,o=n,n=r,r=m+b|0}r=r+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,d=d+this.H|0,this.set(r,n,o,i,s,a,c,d)}roundClean(){ca(xa)}destroy(){this.set(0,0,0,0,0,0,0,0),ca(this.buffer)}}var h9=sy(()=>new _P);var g9=h9;xr();Fe();function y9(e,t){let r=t||"hex",n=g9(Kt(e,{strict:!1})?Yn(e):e);if(r==="bytes")return n;return Jt(n)}function b9(e){let{commitment:t,version:r=1}=e,n=e.to??(typeof t==="string"?"hex":"bytes"),o=y9(t,"bytes");return o.set([r],0),n==="bytes"?o:mt(o)}function Xy(e){let{commitments:t,version:r}=e,n=e.to??(typeof t[0]==="string"?"hex":"bytes"),o=[];for(let i of t)o.push(b9({commitment:i,to:n,version:r}));return o}var x9=32,_9=4096,w9=131072,wP=761855;var eb=1;Ge();class SP extends C{constructor({maxSize:e,size:t}){super("Blob size is too large.",{metaMessages:[`Max: ${e} bytes`,`Given: ${t} bytes`],name:"BlobSizeTooLargeError"})}}class xm extends C{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class vP extends C{constructor({hash:e,size:t}){super(`Versioned hash "${e}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${t}`],name:"InvalidVersionedHashSizeError"})}}class TP extends C{constructor({hash:e,version:t}){super(`Versioned hash "${e}" version is invalid.`,{metaMessages:[`Expected: ${eb}`,`Received: ${t}`],name:"InvalidVersionedHashVersionError"})}}uy();mn();xr();Fe();function S9(e){let t=e.to??(typeof e.data==="string"?"hex":"bytes"),r=typeof e.data==="string"?pr(e.data):e.data,n=et(r);if(!n)throw new xm;if(n>wP)throw new SP({maxSize:wP,size:n});let o=[],i=!0,s=0;while(i){let a=sd(new Uint8Array(w9)),c=0;while(c<_9){let d=r.slice(s,s+(x9-1));if(a.pushByte(0),a.pushBytes(d),d.length<31){a.pushByte(128),i=!1;break}c++,s+=31}o.push(a)}return t==="bytes"?o.map((a)=>a.bytes):o.map((a)=>mt(a.bytes))}function tb(e){let{data:t,kzg:r,to:n}=e,o=e.blobs??S9({data:t,to:n}),i=e.commitments??el({blobs:o,kzg:r,to:n}),s=e.proofs??tl({blobs:o,commitments:i,kzg:r,to:n}),a=[];for(let c=0;c<o.length;c++)a.push({blob:o[c],commitment:i[c],proof:s[c]});return a}Ec();ci();on();function rb(e){if(e.type)return e.type;if(typeof e.authorizationList<"u")return"eip7702";if(typeof e.blobs<"u"||typeof e.blobVersionedHashes<"u"||typeof e.maxFeePerBlobGas<"u"||typeof e.sidecars<"u")return"eip4844";if(typeof e.maxFeePerGas<"u"||typeof e.maxPriorityFeePerGas<"u")return"eip1559";if(typeof e.gasPrice<"u"){if(typeof e.accessList<"u")return"eip2930";return"legacy"}throw new EE({transaction:e})}on();ls();on();mm();function _a(e,{docsPath:t,...r}){let n=(()=>{let o=ha(e,r);if(o instanceof Co)return e;return o})();return new AE(n,{docsPath:t,...r})}ps();ci();lr();async function qr(e){let t=await e.request({method:"eth_chainId"},{dedupe:!0});return Yt(t)}async function rl(e,t){let{account:r=e.account,accessList:n,authorizationList:o,chain:i=e.chain,blobVersionedHashes:s,blobs:a,data:c,gas:d,gasPrice:l,maxFeePerBlobGas:p,maxFeePerGas:m,maxPriorityFeePerGas:h,nonce:b,nonceManager:x,to:_,type:w,value:A,...v}=t,T=await(async()=>{if(!r)return b;if(!x)return b;if(typeof b<"u")return b;let N=ze(r),j=i?i.id:await J(e,qr,"getChainId")({});return await x.consume({address:N.address,chainId:j,client:e})})();Sr(t);let P=i?.formatters?.transactionRequest?.format,O=(P||jr)({...ro(v,{format:P}),account:r?ze(r):void 0,accessList:n,authorizationList:o,blobs:a,blobVersionedHashes:s,data:c,gas:d,gasPrice:l,maxFeePerBlobGas:p,maxFeePerGas:m,maxPriorityFeePerGas:h,nonce:T,to:_,type:w,value:A},"fillTransaction");try{let N=await e.request({method:"eth_fillTransaction",params:[O]}),R=(i?.formatters?.transaction?.format||Yd)(N.tx);delete R.blockHash,delete R.blockNumber,delete R.r,delete R.s,delete R.transactionIndex,delete R.v,delete R.yParity,R.data=R.input;let K=typeof R.feePayerSignature<"u"&&R.feePayerSignature!==null;if(K&&typeof T<"u"&&R.nonce!==T)throw new em({filledNonce:R.nonce,requestedNonce:T});if(!K){if(R.gas)R.gas=t.gas??R.gas;if(R.gasPrice)R.gasPrice=t.gasPrice??R.gasPrice;if(R.maxFeePerBlobGas)R.maxFeePerBlobGas=t.maxFeePerBlobGas??R.maxFeePerBlobGas;if(R.maxFeePerGas)R.maxFeePerGas=t.maxFeePerGas??R.maxFeePerGas;if(R.maxPriorityFeePerGas)R.maxPriorityFeePerGas=t.maxPriorityFeePerGas??R.maxPriorityFeePerGas;if(typeof R.nonce<"u")R.nonce=t.nonce??R.nonce;let Z=await(async()=>{if(typeof i?.fees?.baseFeeMultiplier==="function"){let ee=await J(e,ar,"getBlock")({});return i.fees.baseFeeMultiplier({block:ee,client:e,request:t})}return i?.fees?.baseFeeMultiplier??1.2})();if(Z<1)throw new bm;let pe=10**(Z.toString().split(".")[1]?.length??0),U=(ee)=>ee*BigInt(Math.round(Z*pe))/BigInt(pe);if(R.maxFeePerGas&&!t.maxFeePerGas)R.maxFeePerGas=U(R.maxFeePerGas);if(R.gasPrice&&!t.gasPrice)R.gasPrice=U(R.gasPrice)}return{raw:N.raw,transaction:{from:O.from,...R},...N.capabilities?{capabilities:N.capabilities}:{}}}catch(N){throw _a(N,{...t,chain:e.chain})}}var _m=["blobVersionedHashes","chainId","fees","gas","nonce","type"],v9=new Map,EP=new Cn(128);async function di(e,t){let r=t;r.account??=e.account,r.parameters??=_m;let{account:n,chain:o=e.chain,nonceManager:i,parameters:s}=r,a=(()=>{if(typeof o?.prepareTransactionRequest==="function")return{fn:o.prepareTransactionRequest,runAt:["beforeFillTransaction"]};if(Array.isArray(o?.prepareTransactionRequest))return{fn:o.prepareTransactionRequest[0],runAt:o.prepareTransactionRequest[1].runAt};return})(),c;async function d(){if(c)return c;if(typeof r.chainId<"u")return r.chainId;if(o)return o.id;return c=await J(e,qr,"getChainId")({}),c}let l=n?ze(n):n,p=r.nonce;if(a?.fn&&a.runAt?.includes("beforeFillTransaction")){r=await a.fn({...r,chain:o},{client:e,phase:"beforeFillTransaction"}),p??=r.nonce;let T=r.account??r.from;l=T?ze(T):void 0}if(s.includes("nonce")&&typeof p>"u"&&l&&i){let T=await d();p=await i.consume({address:l.address,chainId:T,client:e})}let h=(()=>{if((s.includes("blobVersionedHashes")||s.includes("sidecars"))&&r.kzg&&r.blobs)return!1;if(s.length>0&&"feePayer"in r&&r.feePayer&&!(("feePayerSignature"in r)&&r.feePayerSignature))return!0;if(EP.get(e.uid)===!1)return!1;if(!["fees","gas"].some((P)=>s.includes(P)))return!1;if(s.includes("chainId")&&typeof r.chainId!=="number")return!0;if(s.includes("nonce")&&typeof p!=="number")return!0;if(s.includes("fees")&&typeof r.gasPrice!=="bigint"&&(typeof r.maxFeePerGas!=="bigint"||typeof r.maxPriorityFeePerGas!=="bigint"))return!0;if(s.includes("gas")&&typeof r.gas!=="bigint")return!0;return!1})()?await J(e,rl,"fillTransaction")({...r,nonce:p}).then((T)=>{let{chainId:P,from:k,gas:O,gasPrice:N,nonce:j,maxFeePerBlobGas:R,maxFeePerGas:K,maxPriorityFeePerGas:Z,type:re,...pe}=T.transaction,U="feeToken"in pe?pe.feeToken:void 0,ee="feePayerSignature"in pe&&pe.feePayerSignature!==null&&typeof pe.feePayerSignature<"u",me=typeof U<"u"&&U!==null&&(!("feeToken"in r)||ee);return EP.set(e.uid,!0),{...r,...k?{from:k}:{},...re&&!r.type?{type:re}:{},...typeof P<"u"?{chainId:P}:{},...typeof O<"u"?{gas:O}:{},...typeof N<"u"?{gasPrice:N}:{},...typeof j<"u"?{nonce:j}:{},...typeof R<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxFeePerBlobGas:R}:{},...typeof K<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxFeePerGas:K}:{},...typeof Z<"u"&&r.type!=="legacy"&&r.type!=="eip2930"?{maxPriorityFeePerGas:Z}:{},..."nonceKey"in pe&&typeof pe.nonceKey<"u"?{nonceKey:pe.nonceKey}:{},..."keyAuthorization"in pe&&typeof pe.keyAuthorization<"u"&&pe.keyAuthorization!==null&&!("keyAuthorization"in r)?{keyAuthorization:pe.keyAuthorization}:{},..."feePayerSignature"in pe&&typeof pe.feePayerSignature<"u"&&pe.feePayerSignature!==null?{feePayerSignature:pe.feePayerSignature}:{},...me?{feeToken:U}:{},...T.capabilities?{_capabilities:T.capabilities}:{}}}).catch((T)=>{let P=T;if(P.name!=="TransactionExecutionError")return r;if(P.walk?.((j)=>j instanceof em))throw T;if(P.walk?.((j)=>j.name==="ExecutionRevertedError"))throw T;if(P.walk?.((j)=>{let R=j;return R.name==="MethodNotFoundRpcError"||R.name==="MethodNotSupportedRpcError"||R.message?.includes("eth_fillTransaction is not available")}))EP.set(e.uid,!1);return r}):r;p??=h.nonce,r={...h,...l?{from:l?.address}:{},...typeof p<"u"?{nonce:p}:{}};let{blobs:b,gas:x,kzg:_,type:w}=r;if(a?.fn&&a.runAt?.includes("beforeFillParameters"))r=await a.fn({...r,chain:o},{client:e,phase:"beforeFillParameters"});let A;async function v(){if(A)return A;return A=await J(e,ar,"getBlock")({blockTag:"latest"}),A}if(s.includes("nonce")&&typeof p>"u"&&l&&!i)r.nonce=await J(e,Xd,"getTransactionCount")({address:l.address,blockTag:"pending"});if((s.includes("blobVersionedHashes")||s.includes("sidecars"))&&b&&_){let T=el({blobs:b,kzg:_});if(s.includes("blobVersionedHashes")){let P=Xy({commitments:T,to:"hex"});r.blobVersionedHashes=P}if(s.includes("sidecars")){let P=tl({blobs:b,commitments:T,kzg:_}),k=tb({blobs:b,commitments:T,proofs:P,to:"hex"});r.sidecars=k}}if(s.includes("chainId"))r.chainId=await d();if((s.includes("fees")||s.includes("type"))&&typeof w>"u")try{r.type=rb(r)}catch{let T=v9.get(e.uid);if(typeof T>"u")T=typeof(await v())?.baseFeePerGas==="bigint",v9.set(e.uid,T);r.type=T?"eip1559":"legacy"}if(s.includes("fees"))if(r.type!=="legacy"&&r.type!=="eip2930"){if(typeof r.maxFeePerGas>"u"||typeof r.maxPriorityFeePerGas>"u"){let T=await v(),{maxFeePerGas:P,maxPriorityFeePerGas:k}=await Qy(e,{block:T,chain:o,request:r});if(typeof r.maxPriorityFeePerGas>"u"&&r.maxFeePerGas&&r.maxFeePerGas<k)throw new gP({maxPriorityFeePerGas:k});r.maxPriorityFeePerGas=k,r.maxFeePerGas=P}}else{if(typeof r.maxFeePerGas<"u"||typeof r.maxPriorityFeePerGas<"u")throw new Uc;if(typeof r.gasPrice>"u"){let T=await v(),{gasPrice:P}=await Qy(e,{block:T,chain:o,request:r,type:"legacy"});r.gasPrice=P}}if(s.includes("gas")&&typeof x>"u")r.gas=await J(e,nl,"estimateGas")({...r,account:l,prepare:l?.type==="local"?[]:["blobVersionedHashes"]});if(a?.fn&&a.runAt?.includes("afterFillParameters"))r=await a.fn({...r,chain:o},{client:e,phase:"afterFillParameters"});return Sr(r),delete r.parameters,r}async function nl(e,t){let{account:r=e.account,prepare:n=!0}=t,o=r?ze(r):void 0,i=(()=>{if(Array.isArray(n))return n;if(o?.type!=="local")return["blobVersionedHashes"];return})();try{let s=await(async()=>{if(t.to)return t.to;if(t.authorizationList&&t.authorizationList.length>0)return await ba({authorization:t.authorizationList[0]}).catch(()=>{throw new C("`to` is required. Could not infer from `authorizationList`")});return})(),{accessList:a,authorizationList:c,blobs:d,blobVersionedHashes:l,blockNumber:p,blockTag:m,data:h,gas:b,gasPrice:x,maxFeePerBlobGas:_,maxFeePerGas:w,maxPriorityFeePerGas:A,nonce:v,value:T,stateOverride:P,...k}=n?await di(e,{...t,parameters:i,to:s}):t;if(b&&t.gas!==b)return b;let N=(typeof p==="bigint"?G(p):void 0)||m,j=Wd(P);Sr(t);let R=e.chain?.formatters?.transactionRequest?.format,Z=(R||jr)({...ro(k,{format:R}),account:o,accessList:a,authorizationList:c,blobs:d,blobVersionedHashes:l,data:h,gasPrice:x,maxFeePerBlobGas:_,maxFeePerGas:w,maxPriorityFeePerGas:A,nonce:v,to:s,value:T},"estimateGas");return BigInt(await e.request({method:"eth_estimateGas",params:j?[Z,N??e.experimental_blockTag??"latest",j]:N?[Z,N]:[Z]}))}catch(s){throw d9(s,{...t,account:o,chain:e.chain})}}async function ol(e,t){let{abi:r,address:n,args:o,functionName:i,dataSuffix:s=typeof e.dataSuffix==="string"?e.dataSuffix:e.dataSuffix?.value,...a}=t,c=It({abi:r,args:o,functionName:i});try{return await J(e,nl,"estimateGas")({data:`${c}${s?s.replace("0x",""):""}`,to:n,...a})}catch(d){let l=a.account?ze(a.account):void 0;throw Nn(d,{abi:r,address:n,args:o,docsPath:"/docs/contract/estimateContractGas",functionName:i,sender:l?.address})}}Mr();rs();xn();Lc();ga();async function T9(e,{address:t,blockHash:r,blockNumber:n,blockTag:o=e.experimental_blockTag??"latest",requireCanonical:i}){let s=Bn({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:i});if(e.batch?.multicall&&e.chain?.contracts?.multicall3){let c=e.chain.contracts.multicall3.address,d=It({abi:Kn,functionName:"getEthBalance",args:[t]}),{data:l}=await J(e,Sn,"call")({to:c,data:d,blockHash:r,blockNumber:n,blockTag:o,requireCanonical:i});return Dr({abi:Kn,functionName:"getEthBalance",args:[t],data:l||"0x"})}let a=await e.request({method:"eth_getBalance",params:[t,s]});return BigInt(a)}async function E9(e){let t=await e.request({method:"eth_blobBaseFee"});return BigInt(t)}var Bce=new Map,Lce=new Map;function P9(e){let t=(o,i)=>({clear:()=>i.delete(o),get:()=>i.get(o),set:(s)=>i.set(o,s)}),r=t(e,Bce),n=t(e,Lce);return{clear:()=>{r.clear(),n.clear()},promise:r,response:n}}async function A9(e,{cacheKey:t,cacheTime:r=Number.POSITIVE_INFINITY}){let n=P9(t),o=n.response.get();if(o&&r>0){if(Date.now()-o.created.getTime()<r)return o.data}let i=n.promise.get();if(!i)i=e(),n.promise.set(i);try{let s=await i;return n.response.set({created:new Date,data:s}),s}finally{n.promise.clear()}}var Dce=(e)=>`blockNumber.${e}`;async function no(e,{cacheTime:t=e.cacheTime}={}){let r=await A9(()=>e.request({method:"eth_blockNumber"}),{cacheKey:Dce(e.uid),cacheTime:t});return BigInt(r)}Fe();lr();function Tr(e,{args:t,eventName:r}={}){return{...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,blockTimestamp:e.blockTimestamp?BigInt(e.blockTimestamp):e.blockTimestamp===null?null:void 0,logIndex:e.logIndex?Number(e.logIndex):null,transactionHash:e.transactionHash?e.transactionHash:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,...r?{args:t,eventName:r}:{}}}var PP={"0x0":"reverted","0x1":"success"};function il(e,t){let r={...e,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,contractAddress:e.contractAddress?e.contractAddress:null,cumulativeGasUsed:e.cumulativeGasUsed?BigInt(e.cumulativeGasUsed):null,effectiveGasPrice:e.effectiveGasPrice?BigInt(e.effectiveGasPrice):null,gasUsed:e.gasUsed?BigInt(e.gasUsed):null,logs:e.logs?e.logs.map((n)=>Tr(n)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Yt(e.transactionIndex):null,status:e.status?PP[e.status]:null,type:e.type?yP[e.type]||e.type:null};if(e.blobGasPrice)r.blobGasPrice=BigInt(e.blobGasPrice);if(e.blobGasUsed)r.blobGasUsed=BigInt(e.blobGasUsed);return r}async function I9(e,{blockHash:t,blockNumber:r,blockTag:n=e.experimental_blockTag??"latest"}={}){let o=r!==void 0?G(r):void 0,i=await e.request({method:"eth_getBlockReceipts",params:[t||o||n]},{dedupe:Boolean(t||o)});if(!i)throw new Fc({blockHash:t,blockNumber:r});let s=e.chain?.formatters?.transactionReceipt?.format||il;return i.map((a)=>s(a,"getBlockReceipts"))}lr();Fe();async function k9(e,{blockHash:t,blockNumber:r,blockTag:n="latest"}={}){let o=r!==void 0?G(r):void 0,i;if(t)i=await e.request({method:"eth_getBlockTransactionCountByHash",params:[t]},{dedupe:!0});else i=await e.request({method:"eth_getBlockTransactionCountByNumber",params:[o||n]},{dedupe:Boolean(o)});return Yt(i)}Lc();async function jc(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:i}){let s=Bn({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:i}),a=await e.request({method:"eth_getCode",params:[t,s]},{dedupe:typeof n==="bigint"||r!==void 0});if(a==="0x")return;return a}la();us();xr();Jn();Jf();ir();FT();mn();Jf();Zf();Zi();var R9="/docs/contract/decodeEventLog";function qc(e){let{abi:t,data:r,strict:n,topics:o}=e,i=n??!0,[s,...a]=o;if(!s)throw new vT({docsPath:R9});let c=t.find((w)=>w.type==="event"&&s===da(dr(w)));if(!(c&&("name"in c))||c.type!=="event")throw new TT(s,{docsPath:R9});let{name:d,inputs:l}=c,p=l?.some((w)=>!(("name"in w)&&w.name)),m=p?[]:{},h=l.map((w,A)=>[w,A]).filter(([w])=>("indexed"in w)&&w.indexed),b=[];for(let w=0;w<h.length;w++){let[A,v]=h[w],T=a[w];if(!T){if(i)throw new Sc({abiItem:c,param:A});b.push([A,v]);continue}m[p?v:A.name||v]=Uce({param:A,value:T})}let x=l.filter((w)=>!(("indexed"in w)&&w.indexed)),_=i?x:[...b.map(([w])=>w),...x];if(_.length>0){if(r&&r!=="0x")try{let w=Xi(_,r);if(w){let A=0;if(!i)for(let[v,T]of b)m[p?T:v.name||T]=w[A++];if(p){for(let v=0;v<l.length;v++)if(m[v]===void 0&&A<w.length)m[v]=w[A++]}else for(let v=0;v<x.length;v++)m[x[v].name]=w[A++]}}catch(w){if(i){if(w instanceof Nf||w instanceof Hf)throw new sa({abiItem:c,data:r,params:_,size:et(r)});throw w}}else if(i)throw new sa({abiItem:c,data:"0x",params:_,size:0})}return{eventName:d,args:Object.values(m).length>0?m:void 0}}function Uce({param:e,value:t}){if(e.type==="string"||e.type==="bytes"||e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/))return t;return(Xi([e],t)||[])[0]}function li(e){let{abi:t,args:r,logs:n,strict:o=!0}=e,i=(()=>{if(!e.eventName)return;if(Array.isArray(e.eventName))return e.eventName;return[e.eventName]})(),s=t.filter((a)=>a.type==="event").map((a)=>({abi:a,selector:da(a)}));return n.map((a)=>{let c=typeof a.blockNumber==="string"?Tr(a):a,d=s.filter((m)=>c.topics[0]===m.selector);if(d.length===0)return null;let l,p;for(let m of d)try{l=qc({...c,abi:[m.abi],strict:!0}),p=m;break}catch{}if(!l&&!o){p=d[0];try{l=qc({data:c.data,topics:c.topics,abi:[p.abi],strict:!1})}catch{let m=p.abi.inputs?.some((h)=>!(("name"in h)&&h.name));return{...c,args:m?[]:{},eventName:p.abi.name}}}if(!l||!p)return null;if(i&&!i.includes(l.eventName))return null;if(!Fce({args:l.args,inputs:p.abi.inputs,matchArgs:r}))return null;return{...l,...c}}).filter(Boolean)}function Fce(e){let{args:t,inputs:r,matchArgs:n}=e;if(!n)return!0;if(!t)return!1;function o(i,s,a){try{if(i.type==="address")return wr(s,a);if(i.type==="string"||i.type==="bytes")return St(Yn(s))===a;return s===a}catch{return!1}}if(Array.isArray(t)&&Array.isArray(n))return n.every((i,s)=>{if(i===null||i===void 0)return!0;let a=r[s];if(!a)return!1;return(Array.isArray(i)?i:[i]).some((d)=>o(a,d,t[s]))});if(typeof t==="object"&&!Array.isArray(t)&&typeof n==="object"&&!Array.isArray(n))return Object.entries(n).every(([i,s])=>{if(s===null||s===void 0)return!0;let a=r.find((d)=>d.name===i);if(!a)return!1;return(Array.isArray(s)?s:[s]).some((d)=>o(a,d,t[i]))});return!1}Fe();async function sl(e,{address:t,blockHash:r,fromBlock:n,toBlock:o,event:i,events:s,args:a,strict:c}={}){let d=c??!1,l=s??(i?[i]:void 0),p=[];if(l){if(p=[l.flatMap((x)=>ui({abi:[x],eventName:x.name,args:s?void 0:a}))],i)p=p[0]}let m;if(r)m=await e.request({method:"eth_getLogs",params:[{address:t,topics:p,blockHash:r}]});else m=await e.request({method:"eth_getLogs",params:[{address:t,topics:p,fromBlock:typeof n==="bigint"?G(n):n,toBlock:typeof o==="bigint"?G(o):o}]});let h=m.map((b)=>Tr(b));if(!l)return h;return li({abi:l,args:a,logs:h,strict:d})}async function nb(e,t){let{abi:r,address:n,args:o,blockHash:i,eventName:s,fromBlock:a,toBlock:c,strict:d}=t,l=s?bn({abi:r,name:s}):void 0,p=!l?r.filter((m)=>m.type==="event"):void 0;return J(e,sl,"getLogs")({address:n,args:o,blockHash:i,event:l,events:p,fromBlock:a,toBlock:c,strict:d})}ri();mn();Ji();async function O9(e,{address:t,blockNumber:r,blockTag:n="latest"}){let o=await jc(e,{address:t,...r!==void 0?{blockNumber:r}:{blockTag:n}});if(!o)return;if(et(o)!==23)return;if(!o.startsWith("0xef0100"))return;return Ao(gn(o,3,23))}Ge();class AP extends C{constructor({address:e}){super(`No EIP-712 domain found on contract "${e}".`,{metaMessages:["Ensure that:",`- The contract is deployed at the address "${e}".`,"- `eip712Domain()` function exists on the contract.","- `eip712Domain()` function matches signature to ERC-5267 specification."],name:"Eip712DomainNotFoundError"})}}async function C9(e,t){let{address:r,factory:n,factoryData:o}=t;try{let[i,s,a,c,d,l,p]=await J(e,gt,"readContract")({abi:jce,address:r,functionName:"eip712Domain",factory:n,factoryData:o});return{domain:{name:s,version:a,chainId:Number(c),verifyingContract:d,salt:l},extensions:p,fields:i}}catch(i){let s=i;if(s.name==="ContractFunctionExecutionError"&&s.cause.name==="ContractFunctionZeroDataError")throw new AP({address:r});throw s}}var jce=[{inputs:[],name:"eip712Domain",outputs:[{name:"fields",type:"bytes1"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"},{name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"}];Fe();function M9(e){return{baseFeePerGas:e.baseFeePerGas.map((t)=>BigInt(t)),gasUsedRatio:e.gasUsedRatio,oldestBlock:BigInt(e.oldestBlock),reward:e.reward?.map((t)=>t.map((r)=>BigInt(r)))}}async function $9(e,{blockCount:t,blockNumber:r,blockTag:n="latest",rewardPercentiles:o}){let i=typeof r==="bigint"?G(r):void 0,s=await e.request({method:"eth_feeHistory",params:[G(t),i||n,o]},{dedupe:Boolean(i)});return M9(s)}async function wa(e,{filter:t}){let r="strict"in t&&t.strict,n=await t.request({method:"eth_getFilterChanges",params:[t.id]});if(typeof n[0]==="string")return n;let o=n.map((i)=>Tr(i));if(!("abi"in t)||!t.abi)return o;return li({abi:t.abi,logs:o,strict:r})}async function N9(e,{filter:t}){let r=t.strict??!1,o=(await t.request({method:"eth_getFilterLogs",params:[t.id]})).map((i)=>Tr(i));if(!t.abi)return o;return li({abi:t.abi,logs:o,strict:r})}Lc();xn();lr();function qce(e){return e.map((t)=>({...t,value:BigInt(t.value)}))}function z9(e){return{...e,balance:e.balance?BigInt(e.balance):void 0,nonce:e.nonce?Yt(e.nonce):void 0,storageProof:e.storageProof?qce(e.storageProof):void 0}}async function B9(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:i,storageKeys:s}){let a=Bn({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:i}),c=await e.request({method:"eth_getProof",params:[t,s,a]});return z9(c)}on();async function L9(e,{hash:t}){let r=await e.request({method:"eth_getRawTransactionByHash",params:[t]},{dedupe:!0});if(!r)throw new kc({hash:t});return r}Lc();async function D9(e,{address:t,blockHash:r,blockNumber:n,blockTag:o="latest",requireCanonical:i,slot:s}){let a=Bn({blockHash:r,blockNumber:n,blockTag:o,requireCanonical:i});return await e.request({method:"eth_getStorageAt",params:[t,s,a]})}on();Fe();async function al(e,{blockHash:t,blockNumber:r,blockTag:n,hash:o,index:i,sender:s,nonce:a}){let c=n||"latest",d=r!==void 0?G(r):void 0,l=null;if(o)l=await e.request({method:"eth_getTransactionByHash",params:[o]},{dedupe:!0});else if(t)l=await e.request({method:"eth_getTransactionByBlockHashAndIndex",params:[t,G(i)]},{dedupe:!0});else if((d||c)&&typeof i==="number")l=await e.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[d||c,G(i)]},{dedupe:Boolean(d)});else if(s&&typeof a==="number")l=await e.request({method:"eth_getTransactionBySenderAndNonce",params:[s,G(a)]},{dedupe:!0});if(!l)throw new kc({blockHash:t,blockNumber:r,blockTag:c,hash:o,index:i});return(e.chain?.formatters?.transaction?.format||Yd)(l,"getTransaction")}async function U9(e,{hash:t,transactionReceipt:r}){let[n,o]=await Promise.all([J(e,no,"getBlockNumber")({}),t?J(e,al,"getTransaction")({hash:t}):void 0]),i=r?.blockNumber||o?.blockNumber;if(!i)return 0n;return n-i+1n}on();async function cl(e,{hash:t}){let r=await e.request({method:"eth_getTransactionReceipt",params:[t]},{dedupe:!0});if(!r)throw new tm({hash:t});return(e.chain?.formatters?.transactionReceipt?.format||il)(r,"getTransactionReceipt")}Mr();ir();Ge();os();rs();xn();Ac();qy();async function F9(e,t){let{account:r,authorizationList:n,allowFailure:o=!0,blockHash:i,blockNumber:s,blockOverrides:a,blockTag:c,requireCanonical:d,stateOverride:l}=t,p=t.contracts,m=typeof e.batch?.multicall==="object"?e.batch.multicall:{},h=t.batchSize??m.batchSize??1024,b=t.deployless??m.deployless??!1,x=(()=>{if(t.multicallAddress)return t.multicallAddress;if(b)return null;if(e.chain)return Qn({blockNumber:s,chain:e.chain,contract:"multicall3"});throw Error("client chain not configured. multicallAddress is required.")})(),_=[[]],w=0,A=0;for(let O=0;O<p.length;O++){let{abi:N,address:j,args:R,functionName:K}=p[O];try{let Z=It({abi:N,args:R,functionName:K});if(A+=(Z.length-2)/2,h>0&&A>h&&_[w].length>0)w++,A=(Z.length-2)/2,_[w]=[];_[w]=[..._[w],{allowFailure:!0,callData:Z,target:j}]}catch(Z){let re=Nn(Z,{abi:N,address:j,args:R,docsPath:"/docs/contract/multicall",functionName:K,sender:r});if(!o)throw re;_[w]=[..._[w],{allowFailure:!0,callData:"0x",target:j}]}}let v=Boolean(e.batch?.multicall),T=v?_.flatMap((O)=>O.map((N)=>[N])):_,P=await Promise.allSettled(T.map((O)=>{if(v)return Hce(e,{account:r,authorizationList:n,batchSize:h,blockHash:i,blockNumber:s,blockOverrides:a,blockTag:c,call:O[0],multicallAddress:x,requireCanonical:d,stateOverride:l}).then((N)=>[N]);return J(e,gt,"readContract")({...x===null?{code:zc}:{address:x},abi:Kn,account:r,args:[O],authorizationList:n,blockHash:i,blockNumber:s,blockOverrides:a,blockTag:c,functionName:"aggregate3",requireCanonical:d,stateOverride:l})})),k=[];for(let O=0;O<P.length;O++){let N=P[O];if(N.status==="rejected"){if(!o)throw N.reason;for(let R=0;R<T[O].length;R++)k.push({status:"failure",error:N.reason,result:void 0});continue}let j=N.value;for(let R=0;R<j.length;R++){let{returnData:K,success:Z}=j[R],{callData:re}=T[O][R],{abi:pe,address:U,functionName:ee,args:me}=p[k.length];try{if(re==="0x")throw new To;if(!Z)throw new ns({data:K});let z=Dr({abi:pe,args:me,data:K,functionName:ee});k.push(o?{result:z,status:"success"}:z)}catch(z){let F=Nn(z,{abi:pe,address:U,args:me,docsPath:"/docs/contract/multicall",functionName:ee});if(!o)throw F;k.push({error:F,result:void 0,status:"failure"})}}}if(k.length!==p.length)throw new C("multicall results mismatch");return k}async function Hce(e,t){let{batchSize:r,call:n,multicallAddress:o,...i}=t,{wait:s=0}=typeof e.batch?.multicall==="object"?e.batch.multicall:{},{schedule:a}=Zd({id:Je(["multicall",e.uid,r,o,i]),wait:s,shouldSplitBatch(d){if(r===0)return!1;return d.reduce((p,{callData:m})=>p+(m.length-2)/2,0)>r},fn:(d)=>J(e,gt,"readContract")({...o===null?{code:zc}:{address:o},...i,abi:Kn,args:[d],functionName:"aggregate3"})}),[c]=await a(n);return c}YE();ir();os();ls();rs();xn();Fe();mm();ps();Hy();ci();async function ul(e,t){let{blockNumber:r,blockTag:n=e.experimental_blockTag??"latest",blocks:o,returnFullTransactions:i,traceTransfers:s,validation:a}=t;try{let c=[];for(let m of o){let h=m.blockOverrides?Dy(m.blockOverrides):void 0,b=m.calls.map((_)=>{let w=_,A=w.account?ze(w.account):void 0,v=w.abi?It(w):w.data,T={...w,account:A,data:w.dataSuffix?fr([v||"0x",w.dataSuffix]):v,from:w.from??A?.address};return Sr(T),jr(T)}),x=m.stateOverrides?Wd(m.stateOverrides):void 0;c.push({blockOverrides:h,calls:b,stateOverrides:x})}let l=(typeof r==="bigint"?G(r):void 0)||n;return(await e.request({method:"eth_simulateV1",params:[{blockStateCalls:c,returnFullTransactions:i,traceTransfers:s,validation:a},l]})).map((m,h)=>({...Jd(m),calls:m.calls.map((b,x)=>{let{abi:_,args:w,functionName:A,to:v}=o[h].calls[x],T=b.error?.data??b.returnData,P=BigInt(b.gasUsed),k=b.logs?.map((R)=>Tr(R)),O=b.status==="0x1"?"success":"failure",N=_&&O==="success"&&T!=="0x"?Dr({abi:_,data:T,functionName:A}):null,j=(()=>{if(O==="success")return;let R;if(T==="0x")R=new To;else if(T)R=new ns({data:T});if(!R)return;return Nn(R,{abi:_??[],address:v??"0x",args:w,functionName:A??"<unknown>"})})();return{data:T,gasUsed:P,logs:k,status:O,...O==="success"?{result:N}:{error:j}}})}))}catch(c){let d=c,l=ha(d,{});if(l instanceof Co)throw d;throw l}}Yf();eo();/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Gce(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function IP(e){if(!Number.isSafeInteger(e)||e<0)throw Error("positive integer expected, got "+e)}function wm(e,...t){if(!Gce(e))throw Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw Error("Uint8Array expected of length "+t+", got length="+e.length)}function kP(e,t=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(t&&e.finished)throw Error("Hash#digest() has already been called")}function j9(e,t){wm(e);let r=t.outputLen;if(e.length<r)throw Error("digestInto() expects output buffer of length at least "+r)}function q9(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function RP(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}var Vce=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function Zce(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function Wce(e){for(let t=0;t<e.length;t++)e[t]=Zce(e[t]);return e}var OP=Vce?(e)=>e:Wce;function Kce(e){if(typeof e!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function CP(e){if(typeof e==="string")e=Kce(e);return wm(e),e}class MP{}function H9(e){let t=(n)=>e().update(CP(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}var ob=BigInt(4294967295),G9=BigInt(32);function Yce(e,t=!1){if(t)return{h:Number(e&ob),l:Number(e>>G9&ob)};return{h:Number(e>>G9&ob)|0,l:Number(e&ob)|0}}function V9(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let i=0;i<r;i++){let{h:s,l:a}=Yce(e[i],t);[n[i],o[i]]=[s,a]}return[n,o]}var Z9=(e,t,r)=>e<<r|t>>>32-r,W9=(e,t,r)=>t<<r|e>>>32-r,K9=(e,t,r)=>t<<r-32|e>>>64-r,Y9=(e,t,r)=>e<<r-32|t>>>64-r;var Jce=BigInt(0),Sm=BigInt(1),Qce=BigInt(2),Xce=BigInt(7),eue=BigInt(256),tue=BigInt(113),X9=[],eD=[],tD=[];for(let e=0,t=Sm,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],X9.push(2*(5*n+r)),eD.push((e+1)*(e+2)/2%64);let o=Jce;for(let i=0;i<7;i++)if(t=(t<<Sm^(t>>Xce)*tue)%eue,t&Qce)o^=Sm<<(Sm<<BigInt(i))-Sm;tD.push(o)}var rD=V9(tD,!0),rue=rD[0],nue=rD[1],J9=(e,t,r)=>r>32?K9(e,t,r):Z9(e,t,r),Q9=(e,t,r)=>r>32?Y9(e,t,r):W9(e,t,r);function oue(e,t=24){let r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let s=0;s<10;s++)r[s]=e[s]^e[s+10]^e[s+20]^e[s+30]^e[s+40];for(let s=0;s<10;s+=2){let a=(s+8)%10,c=(s+2)%10,d=r[c],l=r[c+1],p=J9(d,l,1)^r[a],m=Q9(d,l,1)^r[a+1];for(let h=0;h<50;h+=10)e[s+h]^=p,e[s+h+1]^=m}let o=e[2],i=e[3];for(let s=0;s<24;s++){let a=eD[s],c=J9(o,i,a),d=Q9(o,i,a),l=X9[s];o=e[l],i=e[l+1],e[l]=c,e[l+1]=d}for(let s=0;s<50;s+=10){for(let a=0;a<10;a++)r[a]=e[s+a];for(let a=0;a<10;a++)e[s+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=rue[n],e[1]^=nue[n]}RP(r)}class $P extends MP{constructor(e,t,r,n=!1,o=24){super();if(this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=n,this.rounds=o,IP(r),!(0<e&&e<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=q9(this.state)}clone(){return this._cloneInto()}keccak(){OP(this.state32),oue(this.state32,this.rounds),OP(this.state32),this.posOut=0,this.pos=0}update(e){kP(this),e=CP(e),wm(e);let{blockLen:t,state:r}=this,n=e.length;for(let o=0;o<n;){let i=Math.min(t-this.pos,n-o);for(let s=0;s<i;s++)r[this.pos++]^=e[o++];if(this.pos===t)this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:r,blockLen:n}=this;if(e[r]^=t,(t&128)!==0&&r===n-1)this.keccak();e[n-1]^=128,this.keccak()}writeInto(e){kP(this,!1),wm(e),this.finish();let t=this.state,{blockLen:r}=this;for(let n=0,o=e.length;n<o;){if(this.posOut>=r)this.keccak();let i=Math.min(r-this.posOut,o-n);e.set(t.subarray(this.posOut,this.posOut+i),n),this.posOut+=i,n+=i}return e}xofInto(e){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return IP(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(j9(e,this),this.finished)throw Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,RP(this.state)}_cloneInto(e){let{blockLen:t,suffix:r,outputLen:n,rounds:o,enableXOF:i}=this;return e||(e=new $P(t,r,n,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=n,e.enableXOF=i,e.destroyed=this.destroyed,e}}var iue=(e,t,r)=>H9(()=>new $P(t,e,r));var nD=(()=>iue(1,136,32))();qd();wn();function ib(e,t={}){let{as:r=typeof e==="string"?"Hex":"Bytes"}=t,n=nD(hL(e));if(r==="Bytes")return n;return Ur(n)}wn();qd();class NP extends Map{constructor(e){super();Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){let t=super.get(e);if(super.has(e)&&t!==void 0)this.delete(e),super.set(e,t);return t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){let r=this.keys().next().value;if(r)this.delete(r)}return this}}var sue={checksum:new NP(8192)},sb=sue.checksum;eo();var cue=/^0x[a-fA-F0-9]{40}$/;function dl(e,t={}){let{strict:r=!0}=t;if(!cue.test(e))throw new zP({address:e,cause:new iD});if(r){if(e.toLowerCase()===e)return;if(BP(e)!==e)throw new zP({address:e,cause:new sD})}}function BP(e){if(sb.has(e))return sb.get(e);dl(e,{strict:!1});let t=e.substring(2).toLowerCase(),r=ib(gL(t),{as:"Bytes"}),n=t.split("");for(let i=0;i<40;i+=2){if(r[i>>1]>>4>=8&&n[i])n[i]=n[i].toUpperCase();if((r[i>>1]&15)>=8&&n[i+1])n[i+1]=n[i+1].toUpperCase()}let o=`0x${n.join("")}`;return sb.set(e,o),o}function ab(e,t={}){let{strict:r=!0}=t??{};try{return dl(e,{strict:r}),!0}catch{return!1}}class zP extends Pe{constructor({address:e,cause:t}){super(`Address "${e}" is invalid.`,{cause:t});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class iD extends Pe{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value.");Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}}class sD extends Pe{constructor(){super("Address does not match its checksum counterpart.");Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}eo();function ub(e){let t=!0,r="",n=0,o="",i=!1;for(let s=0;s<e.length;s++){let a=e[s];if(["(",")",","].includes(a))t=!0;if(a==="(")n++;if(a===")")n--;if(!t)continue;if(n===0){if(a===" "&&["event","function","error",""].includes(o))o="";else if(o+=a,a===")"){i=!0;break}continue}if(a===" "){if(e[s-1]!==","&&r!==","&&r!==",(")r="",t=!1;continue}o+=a,r+=a}if(!i)throw new Pe("Unable to normalize signature.");return o}function cb(e,t){let r=typeof e,n=t.type;switch(n){case"address":return ab(e,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:{if(n==="tuple"&&"components"in t)return Object.values(t.components).every((o,i)=>cb(Object.values(e)[i],o));if(/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n))return r==="number"||r==="bigint";if(/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n))return r==="string"||e instanceof Uint8Array;if(/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n))return Array.isArray(e)&&e.every((o)=>cb(o,{...t,type:n.replace(/(\[[0-9]{0,}\])$/,"")}));return!1}}}function DP(e,t,r){for(let n in e){let o=e[n],i=t[n];if(o.type==="tuple"&&i.type==="tuple"&&"components"in o&&"components"in i)return DP(o.components,i.components,r[n]);let s=[o.type,i.type];if((()=>{if(s.includes("address")&&s.includes("bytes20"))return!0;if(s.includes("address")&&s.includes("string"))return ab(r[n],{strict:!1});if(s.includes("address")&&s.includes("bytes"))return ab(r[n],{strict:!1});return!1})())return s}return}function ll(e,t={}){let{prepare:r=!0}=t,n=(()=>{if(Array.isArray(e))return _y(e);if(typeof e==="string")return _y(e);return e})();return{...n,...r?{hash:Sa(n)}:{}}}function pl(e,t,r){let{args:n=[],prepare:o=!0}=r??{},i=KE(t,{strict:!1}),s=e.filter((d)=>{if(i){if(d.type==="function"||d.type==="error")return UP(d)===Fr(t,0,4);if(d.type==="event")return Sa(d)===t;return!1}return"name"in d&&d.name===t});if(s.length===0)throw new va({name:t});if(s.length===1)return{...s[0],...o?{hash:Sa(s[0])}:{}};let a;for(let d of s){if(!("inputs"in d))continue;if(!n||n.length===0){if(!d.inputs||d.inputs.length===0)return{...d,...o?{hash:Sa(d)}:{}};continue}if(!d.inputs)continue;if(d.inputs.length===0)continue;if(d.inputs.length!==n.length)continue;if(n.every((p,m)=>{let h="inputs"in d&&d.inputs[m];if(!h)return!1;return cb(p,h)})){if(a&&"inputs"in a&&a.inputs){let p=DP(d.inputs,a.inputs,n);if(p)throw new aD({abiItem:d,type:p[0]},{abiItem:a,type:p[1]})}a=d}}let c=(()=>{if(a)return a;let[d,...l]=s;return{...d,overloads:l}})();if(!c)throw new va({name:t});return{...c,...o?{hash:Sa(c)}:{}}}function UP(...e){let t=(()=>{if(Array.isArray(e[0])){let[r,n]=e;return pl(r,n)}return e[0]})();return Fr(Sa(t),0,4)}function due(...e){let t=(()=>{if(Array.isArray(e[0])){let[n,o]=e;return pl(n,o)}return e[0]})(),r=(()=>{if(typeof t==="string")return t;return Pc(t)})();return ub(r)}function Sa(...e){let t=(()=>{if(Array.isArray(e[0])){let[r,n]=e;return pl(r,n)}return e[0]})();if(typeof t!=="string"&&"hash"in t&&t.hash)return t.hash;return ib(Gd(due(t)))}class aD extends Pe{constructor(e,t){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${e.type}\` in \`${ub(Pc(e.abiItem))}\`, and`,`\`${t.type}\` in \`${ub(Pc(t.abiItem))}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.AmbiguityError"})}}class va extends Pe{constructor({name:e,data:t,type:r="item"}){let n=(()=>{if(e)return` with name "${e}"`;if(t)return` with data "${t}"`;return""})();super(`ABI ${r}${n} not found.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.NotFoundError"})}}Yf();qd();eo();wn();qd();eo();wn();var cD=/^(.*)\[([0-9]*)\]$/,uD=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,db=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/,WBe=2n**(8n-1n)-1n,KBe=2n**(16n-1n)-1n,YBe=2n**(24n-1n)-1n,JBe=2n**(32n-1n)-1n,QBe=2n**(40n-1n)-1n,XBe=2n**(48n-1n)-1n,e3e=2n**(56n-1n)-1n,t3e=2n**(64n-1n)-1n,r3e=2n**(72n-1n)-1n,n3e=2n**(80n-1n)-1n,o3e=2n**(88n-1n)-1n,i3e=2n**(96n-1n)-1n,s3e=2n**(104n-1n)-1n,a3e=2n**(112n-1n)-1n,c3e=2n**(120n-1n)-1n,u3e=2n**(128n-1n)-1n,d3e=2n**(136n-1n)-1n,l3e=2n**(144n-1n)-1n,p3e=2n**(152n-1n)-1n,f3e=2n**(160n-1n)-1n,m3e=2n**(168n-1n)-1n,h3e=2n**(176n-1n)-1n,g3e=2n**(184n-1n)-1n,y3e=2n**(192n-1n)-1n,b3e=2n**(200n-1n)-1n,x3e=2n**(208n-1n)-1n,_3e=2n**(216n-1n)-1n,w3e=2n**(224n-1n)-1n,S3e=2n**(232n-1n)-1n,v3e=2n**(240n-1n)-1n,T3e=2n**(248n-1n)-1n,E3e=2n**(256n-1n)-1n,P3e=-(2n**(8n-1n)),A3e=-(2n**(16n-1n)),I3e=-(2n**(24n-1n)),k3e=-(2n**(32n-1n)),R3e=-(2n**(40n-1n)),O3e=-(2n**(48n-1n)),C3e=-(2n**(56n-1n)),M3e=-(2n**(64n-1n)),$3e=-(2n**(72n-1n)),N3e=-(2n**(80n-1n)),z3e=-(2n**(88n-1n)),B3e=-(2n**(96n-1n)),L3e=-(2n**(104n-1n)),D3e=-(2n**(112n-1n)),U3e=-(2n**(120n-1n)),F3e=-(2n**(128n-1n)),j3e=-(2n**(136n-1n)),q3e=-(2n**(144n-1n)),H3e=-(2n**(152n-1n)),G3e=-(2n**(160n-1n)),V3e=-(2n**(168n-1n)),Z3e=-(2n**(176n-1n)),W3e=-(2n**(184n-1n)),K3e=-(2n**(192n-1n)),Y3e=-(2n**(200n-1n)),J3e=-(2n**(208n-1n)),Q3e=-(2n**(216n-1n)),X3e=-(2n**(224n-1n)),eLe=-(2n**(232n-1n)),tLe=-(2n**(240n-1n)),rLe=-(2n**(248n-1n)),nLe=-(2n**(256n-1n)),oLe=2n**8n-1n,iLe=2n**16n-1n,sLe=2n**24n-1n,aLe=2n**32n-1n,cLe=2n**40n-1n,uLe=2n**48n-1n,dLe=2n**56n-1n,lLe=2n**64n-1n,pLe=2n**72n-1n,fLe=2n**80n-1n,mLe=2n**88n-1n,hLe=2n**96n-1n,gLe=2n**104n-1n,yLe=2n**112n-1n,bLe=2n**120n-1n,xLe=2n**128n-1n,_Le=2n**136n-1n,wLe=2n**144n-1n,SLe=2n**152n-1n,vLe=2n**160n-1n,TLe=2n**168n-1n,ELe=2n**176n-1n,PLe=2n**184n-1n,ALe=2n**192n-1n,ILe=2n**200n-1n,kLe=2n**208n-1n,RLe=2n**216n-1n,OLe=2n**224n-1n,CLe=2n**232n-1n,MLe=2n**240n-1n,$Le=2n**248n-1n,jP=2n**256n-1n;function Hc(e,t,r){let{checksumAddress:n,staticPosition:o}=r,i=GP(t.type);if(i){let[s,a]=i;return pue(e,{...t,type:a},{checksumAddress:n,length:s,staticPosition:o})}if(t.type==="tuple")return gue(e,t,{checksumAddress:n,staticPosition:o});if(t.type==="address")return lue(e,{checksum:n});if(t.type==="bool")return fue(e);if(t.type.startsWith("bytes"))return mue(e,t,{staticPosition:o});if(t.type.startsWith("uint")||t.type.startsWith("int"))return hue(e,t);if(t.type==="string")return yue(e,{staticPosition:o});throw new vm(t.type)}var lD=32,qP=32;function lue(e,t={}){let{checksum:r=!1}=t,n=e.readBytes(32);return[((i)=>r?BP(i):i)(Ur(yL(n,-20))),32]}function pue(e,t,r){let{checksumAddress:n,length:o,staticPosition:i}=r;if(o===null){let c=ii(e.readBytes(qP)),d=i+c,l=d+lD;e.setPosition(d);let p=ii(e.readBytes(lD)),m=fl(t),h=0,b=[];for(let x=0;x<p;++x){e.setPosition(l+(m?x*32:h));let[_,w]=Hc(e,t,{checksumAddress:n,staticPosition:l});if(h+=w,b.push(_),w===0)e.assertReadLimit(),e._touch()}return e.setPosition(i+32),[b,32]}if(fl(t)){let c=ii(e.readBytes(qP)),d=i+c,l=[];for(let p=0;p<o;++p){e.setPosition(d+p*32);let[m]=Hc(e,t,{checksumAddress:n,staticPosition:d});l.push(m)}return e.setPosition(i+32),[l,32]}let s=0,a=[];for(let c=0;c<o;++c){let[d,l]=Hc(e,t,{checksumAddress:n,staticPosition:i+s});if(s+=l,a.push(d),l===0)e.assertReadLimit(),e._touch()}return[a,s]}function fue(e){return[xL(e.readBytes(32),{size:32}),32]}function mue(e,t,{staticPosition:r}){let[n,o]=t.type.split("bytes");if(!o){let s=ii(e.readBytes(32));e.setPosition(r+s);let a=ii(e.readBytes(32));if(a===0)return e.setPosition(r+32),["0x",32];let c=e.readBytes(a);return e.setPosition(r+32),[Ur(c),32]}return[Ur(e.readBytes(Number.parseInt(o,10),32)),32]}function hue(e,t){let r=t.type.startsWith("int"),n=Number.parseInt(t.type.split("int")[1]||"256",10),o=e.readBytes(32);return[n>48?bL(o,{signed:r}):ii(o,{signed:r}),32]}function gue(e,t,r){let{checksumAddress:n,staticPosition:o}=r,i=t.components.length===0||t.components.some(({name:c})=>!c),s=i?[]:{},a=0;if(fl(t)){let c=ii(e.readBytes(qP)),d=o+c;for(let l=0;l<t.components.length;++l){let p=t.components[l];e.setPosition(d+a);let[m,h]=Hc(e,p,{checksumAddress:n,staticPosition:d});a+=h,s[i?l:p?.name]=m}return e.setPosition(o+32),[s,32]}for(let c=0;c<t.components.length;++c){let d=t.components[c],[l,p]=Hc(e,d,{checksumAddress:n,staticPosition:o});s[i?c:d?.name]=l,a+=p}return[s,a]}function yue(e,{staticPosition:t}){let r=ii(e.readBytes(32)),n=t+r;e.setPosition(n);let o=ii(e.readBytes(32));if(o===0)return e.setPosition(t+32),["",32];let i=e.readBytes(o,32),s=_L(GE(i));return e.setPosition(t+32),[s,32]}function pD({checksumAddress:e,parameters:t,values:r}){let n=[];for(let o=0;o<t.length;o++)n.push(HP({checksumAddress:e,parameter:t[o],value:r[o]}));return n}function HP({checksumAddress:e=!1,parameter:t,value:r}){let n=t,o=GP(n.type);if(o){let[i,s]=o;return xue(r,{checksumAddress:e,length:i,parameter:{...n,type:s}})}if(n.type==="tuple")return Tue(r,{checksumAddress:e,parameter:n});if(n.type==="address")return bue(r,{checksum:e});if(n.type==="bool")return wue(r);if(n.type.startsWith("uint")||n.type.startsWith("int")){let i=n.type.startsWith("int"),[,,s="256"]=db.exec(n.type)??[];return Sue(r,{signed:i,size:Number(s)})}if(n.type.startsWith("bytes"))return _ue(r,{type:n.type});if(n.type==="string")return vue(r);throw new vm(n.type)}function lb(e){let t=0;for(let i=0;i<e.length;i++){let{dynamic:s,encoded:a}=e[i];if(s)t+=32;else t+=sr(a)}let r=[],n=[],o=0;for(let i=0;i<e.length;i++){let{dynamic:s,encoded:a}=e[i];if(s)r.push(rr(t+o,{size:32})),n.push(a),o+=sr(a);else r.push(a)}return _r(...r,...n)}function bue(e,t){let{checksum:r=!1}=t;return dl(e,{strict:r}),{dynamic:!1,encoded:cs(e.toLowerCase())}}function xue(e,t){let{checksumAddress:r,length:n,parameter:o}=t,i=n===null;if(!Array.isArray(e))throw new ZP(e);if(!i&&e.length!==n)throw new VP({expectedLength:n,givenLength:e.length,type:`${o.type}[${n}]`});let s=e.length===0&&fl(o),a=[];for(let c=0;c<e.length;c++){let d=HP({checksumAddress:r,parameter:o,value:e[c]});if(d.dynamic)s=!0;a.push(d)}if(i||s){let c=lb(a);if(i){let d=rr(a.length,{size:32});return{dynamic:!0,encoded:a.length>0?_r(d,c):d}}if(s)return{dynamic:!0,encoded:c}}return{dynamic:!1,encoded:_r(...a.map(({encoded:c})=>c))}}function _ue(e,{type:t}){let[,r]=t.split("bytes"),n=sr(e);if(!r){let o=e;if(n%32!==0)o=si(o,Math.ceil((e.length-2)/2/32)*32);return{dynamic:!0,encoded:_r(cs(rr(n,{size:32})),o)}}if(n!==Number.parseInt(r,10))throw new pb({expectedSize:Number.parseInt(r,10),value:e});return{dynamic:!1,encoded:si(e)}}function wue(e){if(typeof e!=="boolean")throw new Pe(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:cs(By(e))}}function Sue(e,{signed:t,size:r}){if(typeof r==="number"){let n=2n**(BigInt(r)-(t?1n:0n))-1n,o=t?-n-1n:0n;if(e>n||e<o)throw new Ly({max:n.toString(),min:o.toString(),signed:t,size:r/8,value:e.toString()})}return{dynamic:!1,encoded:rr(e,{size:32,signed:t})}}function vue(e){let t=Gd(e),r=Math.ceil(sr(t)/32),n=[];for(let o=0;o<r;o++)n.push(si(Fr(t,o*32,(o+1)*32)));return{dynamic:!0,encoded:_r(si(rr(sr(t),{size:32})),...n)}}function Tue(e,t){let{checksumAddress:r,parameter:n}=t,o=!1,i=[];for(let s=0;s<n.components.length;s++){let a=n.components[s],c=Array.isArray(e)?s:a.name,d=HP({checksumAddress:r,parameter:a,value:e[c]});if(i.push(d),d.dynamic)o=!0}return{dynamic:o,encoded:o?lb(i):_r(...i.map(({encoded:s})=>s))}}function GP(e){let t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}function fl(e){let{type:t}=e;if(t==="string")return!0;if(t==="bytes")return!0;if(t.endsWith("[]"))return!0;if(t==="tuple")return e.components?.some(fl);let r=GP(e.type);if(r&&fl({...e,type:r[1]}))return!0;return!1}eo();var Pue={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new hD({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new mD({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new WP({offset:e});let t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new WP({offset:e});let t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){let r=t??this.position;return this.assertPosition(r+e-1),this.bytes.subarray(r,r+e)},inspectUint8(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){let t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){let t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){let t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,e&255),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();let e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();let r=this.inspectBytes(e);return this.position+=t??e,r},readUint8(){this.assertReadLimit(),this._touch();let e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();let e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();let e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();let e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){let t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;let e=this.getReadCount();if(this.positionReadCount.set(this.position,e+1),e>0)this.recursiveReadCount++}};function fD(e,{recursiveReadLimit:t=8192}={}){let r=Object.create(Pue);return r.bytes=e,r.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=t,r}class WP extends Pe{constructor({offset:e}){super(`Offset \`${e}\` cannot be negative.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.NegativeOffsetError"})}}class mD extends Pe{constructor({length:e,position:t}){super(`Position \`${t}\` is out of bounds (\`0 < position < ${e}\`).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.PositionOutOfBoundsError"})}}class hD extends Pe{constructor({count:e,limit:t}){super(`Recursive read limit of \`${t}\` exceeded (recursive read count: \`${e}\`).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Cursor.RecursiveReadLimitExceededError"})}}function ml(e,t,r={}){let{as:n="Array",checksumAddress:o=!1}=r,i=typeof t==="string"?HE(t):t,s=fD(i);if(to(i)===0&&e.length>0)throw new yD;if(to(i)&&to(i)<32)throw new gD({data:typeof t==="string"?t:Ur(t),parameters:e,size:to(i)});let a=0,c=n==="Array"?[]:{};for(let d=0;d<e.length;++d){let l=e[d];if(a<i.length)s.setPosition(a);let[p,m]=Hc(s,l,{checksumAddress:o,staticPosition:0});if(a+=m,n==="Array")c.push(p);else c[l.name??d]=p}return c}function Gc(e,t,r){let{checksumAddress:n=!1}=r??{};if(e.length!==t.length)throw new YP({expectedLength:e.length,givenLength:t.length});let o=pD({checksumAddress:n,parameters:e,values:t}),i=lb(o);if(i.length===0)return"0x";return i}function KP(e,t){if(e.length!==t.length)throw new YP({expectedLength:e.length,givenLength:t.length});let r=[];for(let n=0;n<e.length;n++){let o=e[n],i=t[n];r.push(KP.encode(o,i))}return _r(...r)}(function(e){function t(r,n,o=!1){if(r==="address"){let c=n;return dl(c),cs(c.toLowerCase(),o?32:0)}if(r==="string")return Gd(n);if(r==="bytes")return n;if(r==="bool")return cs(By(n),o?32:1);let i=r.match(db);if(i){let[c,d,l="256"]=i,p=Number.parseInt(l,10)/8;return rr(n,{size:o?32:p,signed:d==="int"})}let s=r.match(uD);if(s){let[c,d]=s;if(Number.parseInt(d,10)!==(n.length-2)/2)throw new pb({expectedSize:Number.parseInt(d,10),value:n});return si(n,o?32:0)}let a=r.match(cD);if(a&&Array.isArray(n)){let[c,d]=a,l=[];for(let p=0;p<n.length;p++)l.push(t(d,n[p],!0));if(l.length===0)return"0x";return _r(...l)}throw new vm(r)}e.encode=t})(KP||(KP={}));function fb(e){if(Array.isArray(e)&&typeof e[0]==="string")return wy(e);if(typeof e==="string")return wy(e);return e}class gD extends Pe{constructor({data:e,parameters:t,size:r}){super(`Data size of ${r} bytes is too small for given parameters.`,{metaMessages:[`Params: (${es(t)})`,`Data: ${e} (${r} bytes)`]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.DataSizeTooSmallError"})}}class yD extends Pe{constructor(){super('Cannot decode zero data ("0x") with ABI parameters.');Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ZeroDataError"})}}class VP extends Pe{constructor({expectedLength:e,givenLength:t,type:r}){super(`Array length mismatch for type \`${r}\`. Expected: \`${e}\`. Given: \`${t}\`.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ArrayLengthMismatchError"})}}class pb extends Pe{constructor({expectedSize:e,value:t}){super(`Size of bytes "${t}" (bytes${sr(t)}) does not match expected size (bytes${e}).`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class YP extends Pe{constructor({expectedLength:e,givenLength:t}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${e}`,`Given length (values): ${t}`].join(`
142
142
  `));Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class ZP extends Pe{constructor(e){super(`Value \`${e}\` is not a valid array.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidArrayError"})}}class vm extends Pe{constructor(e){super(`Type \`${e}\` is not a valid ABI Type.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"})}}wn();function bD(...e){let[t,r]=(()=>{if(Array.isArray(e[0])){let[i,s]=e;return[Iue(i),s]}return e})(),{bytecode:n,args:o}=r;return _r(n,t.inputs?.length&&o?.length?Gc(t.inputs,o):"0x")}function xD(e){return ll(e)}function Iue(e){let t=e.find((r)=>r.type==="constructor");if(!t)throw new va({name:"constructor"});return t}function _D(e,t={}){return ll(e,t)}function wD(e){return Sa(e)}wn();function SD(...e){let[t,r,n={}]=(()=>{if(Array.isArray(e[0])){let[i,s,a,c]=e;return[JP(i,s),a,c]}return e})(),o=ml(t.outputs,r,n);if(o&&Object.keys(o).length===0)return;if(o&&Object.keys(o).length===1){if(Array.isArray(o))return o[0];return Object.values(o)[0]}return o}function Ta(...e){let[t,r=[]]=(()=>{if(Array.isArray(e[0])){let[d,l,p]=e;return[JP(d,l,{args:p}),p]}let[a,c]=e;return[a,c]})(),{overloads:n}=t,o=n?JP([t,...n],t.name,{args:r}):t,i=Oue(o),s=r.length>0?Gc(o.inputs,r):void 0;return s?_r(i,s):i}function Vc(e,t={}){return ll(e,t)}function JP(e,t,r){let n=pl(e,t,r);if(n.type!=="function")throw new va({name:t,type:"function"});return n}function Oue(e){return UP(e)}var mb="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",hb="0x0000000000000000000000000000000000000000";Ge();os();ls();Df();lr();ga();var Mue="0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033",kD="0x608060405234801561000f575f5ffd5b5060043610610029575f3560e01c8063fd00430c1461002d575b5f5ffd5b6100476004803603810190610042919061012b565b610049565b005b80825f375f5f825f865afa610060573d5f5f3e3d5ffd5b3d5f5f3e3d5ff35b5f5ffd5b5f5ffd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f61009982610070565b9050919050565b6100a98161008f565b81146100b3575f5ffd5b50565b5f813590506100c4816100a0565b92915050565b5f5ffd5b5f5ffd5b5f5ffd5b5f5f83601f8401126100eb576100ea6100ca565b5b8235905067ffffffffffffffff811115610108576101076100ce565b5b602083019150836001820283011115610124576101236100d2565b5b9250929050565b5f5f5f6040848603121561014257610141610068565b5b5f61014f868287016100b6565b935050602084013567ffffffffffffffff8111156101705761016f61006c565b5b61017c868287016100d6565b9250925050925092509256fea2646970667358221220635ed99185cacf3f2acba6921f23687c969cec2bbaf5f9ad599f507e6e105e6964736f6c63430008230033",$ue=0x00000000000000000000000000000000deadbeefn,Nue=wD(_D("event Transfer(address indexed from, address indexed to, uint256 value)")),vD=Vc("function balanceOf(address) returns (uint256)"),TD=Vc("function decimals() returns (uint256)"),ED=Vc("function tokenURI(uint256) returns (string)"),PD=Vc("function symbol() returns (string)"),zue=Vc("function query(address target, bytes data)");async function RD(e,t){let{blockNumber:r,blockTag:n,calls:o,stateOverrides:i,traceAssetChanges:s,traceTransfers:a,validation:c}=t,d=t.account?ze(t.account):void 0;if(s&&!d)throw new C("`account` is required when `traceAssetChanges` is true");let l=d?bD(xD("constructor(bytes, bytes)"),{bytecode:Uy,args:[Mue,Ta(Vc("function getBalance(address)"),[d.address])]}):void 0,p=n??e.experimental_blockTag??"latest",m=r;if(s&&typeof m!=="bigint"&&p!=="earliest"&&p!=="pending")if(p==="latest")m=await no(e,{cacheTime:0});else{let te=await ar(e,{blockTag:p});if(typeof te.number!=="bigint")throw new C(`Block tag \`${p}\` did not resolve to a number.`);m=te.number}let h=typeof m==="bigint"?{blockNumber:m}:{blockTag:p},b=s?await ul(e,{...h,blocks:[{calls:o.map((te)=>({...te,from:d.address})),stateOverrides:i}],traceTransfers:a,validation:c}):void 0,x=b?[...new Set([...Bue(b[0].calls.flatMap((te)=>te.logs??[]),d.address),...t.calls.map((te)=>te.to?.toLowerCase())])].filter((te)=>Boolean(te)&&te!==mb&&te!==hb):[],_=Lue([...d?[d.address]:[],...x,...i?.map(({address:te})=>te)??[]]),w=[{address:_,code:kD}],[A,v]=await Promise.all([s?Promise.all([ID(e,{account:d.address,...h,data:l,stateOverride:i}),...x.map((te)=>ID(e,{account:d.address,address:te,...h,data:Ta(vD,[d.address]),staticCallAddress:_,stateOverride:i}))]):[],ul(e,{...h,blocks:[{calls:[...o,{to:hb}].map((te)=>({...te,from:d?.address})),stateOverrides:i},...s?[{calls:[{data:l}]},{calls:x.map((te)=>({to:_,data:Em(te,Ta(vD,[d.address]))})),stateOverrides:w},{calls:x.map((te)=>({to:_,data:Em(te,Ta(TD))})),stateOverrides:w},{calls:x.map((te)=>({to:_,data:Em(te,Ta(ED,[0n]))})),stateOverrides:w},{calls:x.map((te)=>({to:_,data:Em(te,Ta(PD))})),stateOverrides:w}]:[]],traceTransfers:a,validation:c})]),T=v[0],[P,k,O,N,j]=s?v.slice(1):[],{calls:R,...K}=T,Z=R.slice(0,-1),re=A.map((te)=>AD(te)?er(te.data):null),pe=P?.calls??[],U=k?.calls??[],me=[...pe,...U].map((te)=>AD(te)?er(te.data):null),z=(O?.calls??[]).map((te)=>QP(te,TD)),F=(j?.calls??[]).map((te)=>QP(te,PD)),Y=(N?.calls??[]).map((te)=>QP(te,ED)),we=[];for(let[te,$e]of me.entries()){let Ee=re[te],Ae=A[te],tt=typeof Ee==="bigint"?Ee:te>0&&Ae?.status==="success"&&Ae.data==="0x"?0n:null;if(typeof $e!=="bigint")continue;if(typeof tt!=="bigint")continue;let yt=z[te-1],ft=F[te-1],q=Y[te-1],ne=(()=>{if(te===0)return{address:mb,decimals:18,symbol:"ETH"};return{address:x[te-1],decimals:q||yt?Number(yt??1):void 0,symbol:ft??void 0}})();we.push({token:ne,value:{pre:tt,post:$e,diff:$e-tt}})}return{assetChanges:we,block:K,results:Z}}function Em(e,t){return Ta(zue,[e,t])}function Bue(e,t){let r=ti(t.toLowerCase(),{size:32});return e.filter((n)=>{if(n.topics[0]?.toLowerCase()!==Nue)return!1;if(n.address.toLowerCase()===mb)return!1;return n.topics[1]?.toLowerCase()===r||n.topics[2]?.toLowerCase()===r}).map((n)=>n.address.toLowerCase())}function AD(e){return e.status==="success"&&/^0x[\da-f]{64}$/i.test(e.data)}function QP(e,t){if(e.status==="failure"||e.data==="0x")return null;try{return SD(t,e.data)}catch{return null}}async function ID(e,t){let{account:r,address:n,blockNumber:o,blockTag:i,data:s,staticCallAddress:a,stateOverride:c}=t;try{return{data:(await Sn({...e,ccipRead:!1},{account:n?hb:r,data:n?Em(n,s):s,stateOverride:n&&a?[...c??[],{address:a,code:kD}]:c,...n?{to:a}:{},...typeof o==="bigint"?{blockNumber:o}:{blockTag:i}})).data??"0x",status:"success"}}catch(d){if(!(d instanceof Oc)||!(d.cause instanceof ai))throw d;return{data:"0x",status:"failure"}}}function Lue(e){let t=new Set(e.map((n)=>n.toLowerCase())),r=$ue;while(t.has(`0x${r.toString(16).padStart(40,"0")}`))r++;return`0x${r.toString(16).padStart(40,"0")}`}rs();xn();ga();async function hl(e,t){let{abi:r,address:n,args:o,functionName:i,dataSuffix:s=typeof e.dataSuffix==="string"?e.dataSuffix:e.dataSuffix?.value,...a}=t,c=a.account?ze(a.account):e.account,d=It({abi:r,args:o,functionName:i});try{let{data:l}=await J(e,Sn,"call")({batch:!1,data:`${d}${s?s.replace("0x",""):""}`,to:n,...a,account:c}),p=Dr({abi:r,args:o,functionName:i,data:l||"0x"}),m=r.filter((h)=>("name"in h)&&h.name===t.functionName);return{result:p,request:{abi:m,address:n,args:o,dataSuffix:s,functionName:i,...a,account:c}}}catch(l){throw Nn(l,{abi:r,address:n,args:o,docsPath:"/docs/contract/simulateContract",functionName:i,sender:c?.address})}}async function Ea(e,{filter:t}){return t.request({method:"eth_uninstallFilter",params:[t.id]})}eo();wn();var OD="0x6492649264926492649264926492649264926492649264926492649264926492";function Due(e){if(Fr(e,-32)!==OD)throw new CD(e)}function Uue(e){let{data:t,signature:r,to:n}=e;return _r(Gc(fb("address, bytes, bytes"),[n,t,r]),OD)}function Fue(e){try{return Due(e),!0}catch{return!1}}class CD extends Pe{constructor(e){super(`Value \`${e}\` is an invalid ERC-6492 wrapped signature.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc6492.InvalidWrappedSignatureError"})}}eo();wn();function XP(e,t={}){let{recovered:r}=t;if(typeof e.r>"u")throw new gb({signature:e});if(typeof e.s>"u")throw new gb({signature:e});if(r&&typeof e.yParity>"u")throw new gb({signature:e});if(e.r<0n||e.r>jP)throw new LD({value:e.r});if(e.s<0n||e.s>jP)throw new DD({value:e.s});if(typeof e.yParity==="number"&&e.yParity!==0&&e.yParity!==1)throw new yb({value:e.yParity})}function jue(e){return $D(Ur(e))}function $D(e){if(e.length!==130&&e.length!==132)throw new BD({signature:e});let t=BigInt(Fr(e,0,32)),r=BigInt(Fr(e,32,64)),n=(()=>{let o=Number(`0x${e.slice(130)}`);if(Number.isNaN(o))return;try{return eA(o)}catch{throw new yb({value:o})}})();if(typeof n>"u")return{r:t,s:r};return{r:t,s:r,yParity:n}}function ND(e){if(typeof e.r>"u")return;if(typeof e.s>"u")return;return zD(e)}function zD(e){let t=(()=>{if(typeof e==="string")return $D(e);if(e instanceof Uint8Array)return jue(e);if(typeof e.r==="string")return Hue(e);if(e.v)return que(e);return{r:e.r,s:e.s,...typeof e.yParity<"u"?{yParity:e.yParity}:{}}})();return XP(t),t}function que(e){return{r:e.r,s:e.s,yParity:eA(e.v)}}function Hue(e){let t=(()=>{let r=e.v?Number(e.v):void 0,n=e.yParity?Number(e.yParity):void 0;if(typeof r==="number"&&typeof n!=="number")n=eA(r);if(typeof n!=="number")throw new yb({value:e.yParity});return n})();return{r:BigInt(e.r),s:BigInt(e.s),yParity:t}}function eA(e){if(e===0||e===27)return 0;if(e===1||e===28)return 1;if(e>=35)return e%2===0?1:0;throw new UD({value:e})}class BD extends Pe{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${sr(SL(e))} bytes.`]});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class gb extends Pe{constructor({signature:e}){super(`Signature \`${Ny(e)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.MissingPropertiesError"})}}class LD extends Pe{constructor({value:e}){super(`Value \`${e}\` is an invalid r value. r must be a positive integer less than 2^256.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidRError"})}}class DD extends Pe{constructor({value:e}){super(`Value \`${e}\` is an invalid s value. s must be a positive integer less than 2^256.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSError"})}}class yb extends Pe{constructor({value:e}){super(`Value \`${e}\` is an invalid y-parity value. Y-parity must be 0 or 1.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}}class UD extends Pe{constructor({value:e}){super(`Value \`${e}\` is an invalid v value. v must be 27, 28 or >=35.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}function jD(e,t={}){if(typeof e.chainId==="string")return Gue(e);return{...e,...t.signature}}function Gue(e){let{address:t,chainId:r,nonce:n}=e,o=ND(e);return{address:t,chainId:Number(r),nonce:BigInt(n),...o}}eo();wn();var Zue="0x8010801080108010801080108010801080108010801080108010801080108010",Wue=fb("(uint256 chainId, address delegation, uint256 nonce, uint8 yParity, uint256 r, uint256 s), address to, bytes data");function qD(e){if(typeof e==="string"){if(Fr(e,-32)!==Zue)throw new HD(e)}else XP(e.authorization)}function Kue(e){qD(e);let t=zy(Fr(e,-64,-32)),r=Fr(e,-t-64,-64),n=Fr(e,0,-t-64),[o,i,s]=ml(Wue,r);return{authorization:jD({address:o.delegation,chainId:Number(o.chainId),nonce:o.nonce,yParity:o.yParity,r:o.r,s:o.s}),signature:n,...s&&s!=="0x"?{data:s,to:i}:{}}}function Yue(e){try{return qD(e),!0}catch{return!1}}class HD extends Pe{constructor(e){super(`Value \`${e}\` is an invalid ERC-8010 wrapped signature.`);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SignatureErc8010.InvalidWrappedSignatureError"})}}Mr();os();Fy();xn();ri();us();ri();us();async function VD({address:e,authorization:t,signature:r}){return wr(Ao(e),await ba({authorization:t,signature:r}))}lr();Fe();gm();lr();xr();function bb({r:e,s:t,to:r="hex",v:n,yParity:o}){let i=(()=>{if(o===0||o===1)return o;if(n&&(n===27n||n===28n||n>=35n))return n%2n===0n?1:0;throw Error("Invalid `v` or `yParity` value")})(),s=`0x${new hs.Signature(er(e),er(t)).toCompactHex()}${i===0?"1b":"1c"}`;if(r==="hex")return s;return pr(s)}ga();async function Aa(e,t){let{address:r,chain:n=e.chain,hash:o,erc6492VerifierAddress:i=t.universalSignatureVerifierAddress??n?.contracts?.erc6492Verifier?.address,multicallAddress:s=t.multicallAddress??n?.contracts?.multicall3?.address,mode:a="auto"}=t;if(n?.verifyHash)return await n.verifyHash(e,t);let c=(()=>{let d=t.signature;if(Kt(d))return d;if(typeof d==="object"&&"r"in d&&"s"in d)return bb(d);return mt(d)})();try{if(a==="eoa")try{if(wr(Ao(r),await ym({hash:o,signature:c})))return!0}catch{}if(Yue(c))return await Jue(e,{...t,multicallAddress:s,signature:c});return await Que(e,{...t,verifierAddress:i,signature:c})}catch(d){if(a!=="eoa")try{if(wr(Ao(r),await ym({hash:o,signature:c})))return!0}catch{}if(d instanceof Pa)return!1;throw d}}async function Jue(e,t){let{address:r,blockHash:n,blockNumber:o,blockTag:i,hash:s,multicallAddress:a,requireCanonical:c}=t,{authorization:d,data:l,signature:p,to:m}=Kue(t.signature);if(await jc(e,{address:r,blockHash:n,blockNumber:o,blockTag:i,requireCanonical:c})===Qt(["0xef0100",d.address]))return await Xue(e,{...t,signature:p});let b={address:d.address,chainId:Number(d.chainId),nonce:Number(d.nonce),r:G(d.r,{size:32}),s:G(d.s,{size:32}),yParity:d.yParity};if(!await VD({address:r,authorization:b}))throw new Pa;let _=await J(e,gt,"readContract")({...a?{address:a}:{code:zc},authorizationList:[b],abi:Kn,blockHash:n,blockNumber:o,blockTag:"pending",functionName:"aggregate3",requireCanonical:c,args:[[...l?[{allowFailure:!0,target:m??r,callData:l}]:[],{allowFailure:!0,target:r,callData:It({abi:mT,functionName:"isValidSignature",args:[s,p]})}]]});if(_[_.length-1]?.returnData?.startsWith("0x1626ba7e"))return!0;throw new Pa}async function Que(e,t){let{address:r,factory:n,factoryData:o,hash:i,signature:s,verifierAddress:a,...c}=t,d=await(async()=>{if(!n&&!o)return s;if(Fue(s))return s;return Uue({data:o,signature:s,to:n})})(),l=a?{to:a,data:It({abi:Mf,functionName:"isValidSig",args:[r,i,d]}),...c}:{data:Bc({abi:Mf,args:[r,i,d],bytecode:IL}),...c},{data:p}=await J(e,Sn,"call")(l).catch((m)=>{if(m instanceof Oc)throw new Pa;throw m});if(MT(p??"0x0"))return!0;throw new Pa}async function Xue(e,t){let{address:r,blockHash:n,blockNumber:o,blockTag:i,hash:s,requireCanonical:a,signature:c}=t;if((await J(e,gt,"readContract")({address:r,abi:mT,args:[s,c],blockHash:n,blockNumber:o,blockTag:i,functionName:"isValidSignature",requireCanonical:a}).catch((l)=>{if(l instanceof rm)throw new Pa;throw l})).startsWith("0x1626ba7e"))return!0;throw new Pa}class Pa extends Error{}Jn();var ZD=`\x19Ethereum Signed Message:
143
143
  `;mn();Fe();function WD(e){let t=(()=>{if(typeof e==="string")return aa(e);if(typeof e.raw==="string")return e.raw;return mt(e.raw)})(),r=aa(`${ZD}${et(t)}`);return fr([r,t])}function gl(e,t){return St(WD(e),t)}async function KD(e,{address:t,message:r,factory:n,factoryData:o,signature:i,...s}){let a=gl(r);return J(e,Aa,"verifyHash")({address:t,factory:n,factoryData:o,hash:a,signature:i,...s})}Qi();Fe();Jn();ir();ei();Ge();class tA extends C{constructor({domain:e}){super(`Invalid domain "${Je(e)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class rA extends C{constructor({primaryType:e,types:t}){super(`Invalid primary type \`${e}\` must be one of \`${JSON.stringify(Object.keys(t))}\`.`,{docsPath:"/api/glossary/Errors#typeddatainvalidprimarytypeerror",metaMessages:["Check that the primary type is a key in `types`."]})}}class nA extends C{constructor({type:e}){super(`Struct type "${e}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}class oA extends C{constructor({type:e}){let t=e.replace(/^(u?int)/,"$&256");super(`Type "${e}" is not a valid EIP-712 type.`,{metaMessages:[`Use "${t}" instead.`],name:"InvalidTypedDataTypeError"})}}Mn();mn();Fe();qT();function YD(e){let{domain:t,message:r,primaryType:n,types:o}=e,i=(c,d)=>{let l={...d};for(let p of c){let{name:m,type:h}=p;if(h==="address")l[m]=l[m].toLowerCase()}return l},s=(()=>{if(!o.EIP712Domain)return{};if(!t)return{};return i(o.EIP712Domain,t)})(),a=(()=>{if(n==="EIP712Domain")return;return i(o[n],r)})();return Je({domain:s,message:a,primaryType:n,types:o})}function xb(e){let{domain:t,message:r,primaryType:n,types:o}=e,i=(s,a)=>{for(let c of s){let{name:d,type:l}=c,p=a[d],m=l.replace(/(\[[0-9]*\])+$/,"");if(m==="int"||m==="uint")throw new oA({type:l});let h=l.match(ly);if(h&&(typeof p==="number"||typeof p==="bigint")){let[_,w,A]=h;G(p,{signed:w==="int",size:Number.parseInt(A,10)/8})}if(l==="address"&&typeof p==="string"&&!ht(p))throw new Ft({address:p});let b=l.match(YB);if(b){let[_,w]=b;if(w&&et(p)!==Number.parseInt(w,10))throw new AT({expectedSize:Number.parseInt(w,10),givenSize:et(p)})}let x=o[l];if(x)ede(l),i(x,p)}};if(o.EIP712Domain&&t){if(typeof t!=="object")throw new tA({domain:t});i(o.EIP712Domain,t)}if(n!=="EIP712Domain")if(o[n])i(o[n],r);else throw new rA({primaryType:n,types:o})}function _b({domain:e}){return[typeof e?.name==="string"&&{name:"name",type:"string"},e?.version&&{name:"version",type:"string"},(typeof e?.chainId==="number"||typeof e?.chainId==="bigint")&&{name:"chainId",type:"uint256"},e?.verifyingContract&&{name:"verifyingContract",type:"address"},e?.salt&&{name:"salt",type:"bytes32"}].filter(Boolean)}function ede(e){if(e==="address"||e==="bool"||e==="string"||e.startsWith("bytes")||e.startsWith("uint")||e.startsWith("int"))throw new nA({type:e})}function wb(e){let{domain:t={},message:r,primaryType:n}=e,o={EIP712Domain:_b({domain:t}),...e.types};xb({domain:t,message:r,primaryType:n,types:o});let i=["0x1901"];if(t)i.push(tde({domain:t,types:o}));if(n!=="EIP712Domain")i.push(JD({data:r,primaryType:n,types:o}));return St(fr(i))}function tde({domain:e,types:t}){return JD({data:e,primaryType:"EIP712Domain",types:t})}function JD({data:e,primaryType:t,types:r}){let n=QD({data:e,primaryType:t,types:r});return St(n)}function QD({data:e,primaryType:t,types:r}){let n=[{type:"bytes32"}],o=[rde({primaryType:t,types:r})];for(let i of r[t]){let[s,a]=eU({types:r,name:i.name,type:i.type,value:e[i.name]});n.push(s),o.push(a)}return nn(n,o)}function rde({primaryType:e,types:t}){let r=Jt(nde({primaryType:e,types:t}));return St(r)}function nde({primaryType:e,types:t}){let r="",n=XD({primaryType:e,types:t});n.delete(e);let o=[e,...Array.from(n).sort()];for(let i of o)r+=`${i}(${t[i].map(({name:s,type:a})=>`${a} ${s}`).join(",")})`;return r}function XD({primaryType:e,types:t},r=new Set){let o=e.match(/^\w*/u)?.[0];if(r.has(o)||t[o]===void 0)return r;r.add(o);for(let i of t[o])XD({primaryType:i.type,types:t},r);return r}function eU({types:e,name:t,type:r,value:n}){if(e[r]!==void 0)return[{type:"bytes32"},St(QD({data:n,primaryType:r,types:e}))];if(r==="bytes")return[{type:"bytes32"},St(n)];if(r==="string")return[{type:"bytes32"},St(Jt(n))];if(r.lastIndexOf("]")===r.length-1){let o=r.slice(0,r.lastIndexOf("[")),i=n.map((s)=>eU({name:t,type:o,types:e,value:s}));return[{type:"bytes32"},St(nn(i.map(([s])=>s),i.map(([,s])=>s)))]}return[{type:r},n]}async function tU(e,t){let{address:r,factory:n,factoryData:o,signature:i,message:s,primaryType:a,types:c,domain:d,...l}=t,p=wb({message:s,primaryType:a,types:c,domain:d});return J(e,Aa,"verifyHash")({address:r,factory:n,factoryData:o,hash:p,signature:i,...l})}on();var Sb=new Map,iA=new Map,ode=0;function Er(e,t,r){let n=++ode,o=()=>Sb.get(e)||[],i=()=>{let p=o().filter((m)=>m.id!==n);if(p.length===0){Sb.delete(e),iA.delete(e);return}Sb.set(e,p)},s=()=>{let l=o();if(!l.some((m)=>m.id===n))return;let p=iA.get(e);if(l.length===1&&p){let m=p();if(m instanceof Promise)m.catch(()=>{})}i()},a=o();if(Sb.set(e,[...a,{id:n,fns:t}]),a&&a.length>0)return s;let c={};for(let l in t)c[l]=(...p)=>{let m=o();if(m.length===0)return;for(let h of m)h.fns[l]?.(...p)};let d=r(c);if(typeof d==="function")iA.set(e,d);return s}async function Pm(e,{signal:t}={}){return new Promise((r,n)=>{if(t?.aborted){n(Nr(t));return}let o=()=>t?.removeEventListener("abort",s),i=setTimeout(()=>{o(),r()},e),s=()=>{clearTimeout(i),o(),n(Nr(t))};t?.addEventListener("abort",s,{once:!0})})}function Zc(e,{delay:t=100,retryCount:r=2,shouldRetry:n=()=>!0,signal:o}={}){return new Promise((i,s)=>{let a=async({count:c=0}={})=>{if(o?.aborted){s(Nr(o));return}let d=async({error:l})=>{let p=typeof t==="function"?t({count:c,error:l}):t;if(p)try{await Pm(p,{signal:o})}catch(m){s(m);return}return a({count:c+1})};try{let l=await e();i(l)}catch(l){if(o?.aborted){s(Nr(o));return}if(_n(l)){s(l);return}if(c<r&&await n({count:c,error:l}))return d({error:l});s(l)}};a().catch(s)})}lr();function oo(e,{emitOnBegin:t,initialWaitTime:r,interval:n}){let o=!0,i=()=>o=!1;return(async()=>{let a;if(t)a=await e({unpoll:i});let c=await r?.(a)??n;await Pm(c);let d=async()=>{if(!o)return;await e({unpoll:i}),await Pm(n),d()};d()})(),i}function vb(e,{emitOnBegin:t=!1,emitMissed:r=!1,onBlockNumber:n,onError:o,poll:i,pollingInterval:s=e.pollingInterval}){let a=(()=>{if(typeof i<"u")return i;if(e.transport.type==="webSocket"||e.transport.type==="ipc")return!1;if(e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc"))return!1;return!0})(),c;return a?(()=>{let p=Je(["watchBlockNumber",e.uid,t,r,s]);return Er(p,{onBlockNumber:n,onError:o},(m)=>oo(async()=>{try{let h=await J(e,no,"getBlockNumber")({cacheTime:0});if(c!==void 0){if(h===c)return;if(h-c>1&&r)for(let b=c+1n;b<h;b++)m.onBlockNumber(b,c),c=b}if(c===void 0||h>c)m.onBlockNumber(h,c),c=h}catch(h){m.onError?.(h)}},{emitOnBegin:t,interval:s}))})():(()=>{let p=Je(["watchBlockNumber",e.uid,t,r]);return Er(p,{onBlockNumber:n,onError:o},(m)=>{let h=!0,b=()=>h=!1;return(async()=>{try{let x=(()=>{if(e.transport.type==="fallback"){let w=e.transport.transports.find((A)=>A.config.type==="webSocket"||A.config.type==="ipc");if(!w)return e.transport;return w.value}return e.transport})(),{unsubscribe:_}=await x.subscribe({params:["newHeads"],onData(w){if(!h)return;let A=er(w.result?.number);m.onBlockNumber(A,c),c=A},onError(w){m.onError?.(w)}});if(b=_,!h)b()}catch(x){o?.(x)}})(),()=>b()})})()}async function Tb(e,t){let{checkReplacement:r=e.chain?.supportsTransactionReplacementDetection??!0,confirmations:n=1,hash:o,onReplaced:i,retryCount:s=6,retryDelay:a=({count:P})=>~~(1<<P)*200,timeout:c=180000}=t,d=Je(["waitForTransactionReceipt",e.uid,o]),l=(()=>{if(t.pollingInterval)return t.pollingInterval;if(e.chain?.experimental_preconfirmationTime)return e.chain.experimental_preconfirmationTime;return e.pollingInterval})(),p,m,h,b=!1,x,_,{promise:w,resolve:A,reject:v}=Vd(),T=c?setTimeout(()=>{_?.(),x?.(),v(new IE({hash:o}))},c):void 0;return x=Er(d,{onReplaced:i,resolve:A,reject:v},async(P)=>{if(h=await J(e,cl,"getTransactionReceipt")({hash:o}).catch(()=>{return}),h&&n<=1){clearTimeout(T),P.resolve(h),x?.();return}_=J(e,vb,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:l,async onBlockNumber(k){let O=(j)=>{clearTimeout(T),_?.(),j(),x?.()},N=k;if(b)return;try{if(h){if(n>1&&(!h.blockNumber||N-h.blockNumber+1n<n))return;O(()=>P.resolve(h));return}if(r&&!p)b=!0,await Zc(async()=>{if(p=await J(e,al,"getTransaction")({hash:o}),p.blockNumber)N=p.blockNumber},{delay:a,retryCount:s}),b=!1;if(h=await J(e,cl,"getTransactionReceipt")({hash:o}),n>1&&(!h.blockNumber||N-h.blockNumber+1n<n))return;O(()=>P.resolve(h))}catch(j){if(j instanceof kc||j instanceof tm){if(!p){b=!1;return}try{m=p,b=!0;let R=await Zc(()=>J(e,ar,"getBlock")({blockNumber:N,includeTransactions:!0}),{delay:a,retryCount:s,shouldRetry:({error:re})=>re instanceof Fc});b=!1;let K=R.transactions.find(({from:re,nonce:pe})=>re===m.from&&pe===m.nonce);if(!K)return;if(h=await J(e,cl,"getTransactionReceipt")({hash:K.hash}),n>1&&(!h.blockNumber||N-h.blockNumber+1n<n))return;let Z="replaced";if(K.to===m.to&&K.value===m.value&&K.input===m.input)Z="repriced";else if(K.from===K.to&&K.value===0n)Z="cancelled";O(()=>{P.onReplaced?.({reason:Z,replacedTransaction:m,transaction:K,transactionReceipt:h}),P.resolve(h)})}catch(R){O(()=>P.reject(R))}}else O(()=>P.reject(j))}}})}),w}var ide=["size","totalDifficulty","transactions","uncles","withdrawals"];function rU(e,{onBlockHeader:t,onError:r}){let n,o=Je(["watchBlockHeaders",e.uid]);return Er(o,{onBlockHeader:t,onError:r},(i)=>{let s=!0,a=!1,c=()=>s=!1;return(async()=>{try{let d=(()=>{if(e.transport.type==="fallback"){let p=e.transport.transports.find((m)=>m.config.type==="webSocket"||m.config.type==="ipc");if(!p)return e.transport;return p.value}return e.transport})(),{unsubscribe:l}=await d.subscribe({params:["newHeads"],onData(p){if(!s)return;let m=(e.chain?.formatters?.block?.format||Jd)(p.result,"watchBlockHeaders");for(let h of ide)delete m[h];i.onBlockHeader(m,n),n=m},onError(p){if(a)i.onError?.(p)}});if(a=!0,c=l,!s)c()}catch(d){i.onError?.(d)}})(),()=>c()})}function nU(e,{blockTag:t=e.experimental_blockTag??"latest",emitMissed:r=!1,emitOnBegin:n=!1,onBlock:o,onError:i,includeTransactions:s,poll:a,pollingInterval:c=e.pollingInterval}){let d=(()=>{if(typeof a<"u")return a;if(e.transport.type==="webSocket"||e.transport.type==="ipc")return!1;if(e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc"))return!1;return!0})(),l=s??!1,p;return d?(()=>{let b=Je(["watchBlocks",e.uid,t,r,n,l,c]);return Er(b,{onBlock:o,onError:i},(x)=>oo(async()=>{try{let _=await J(e,ar,"getBlock")({blockTag:t,includeTransactions:l});if(_.number!==null&&p?.number!=null){if(_.number===p.number)return;if(_.number-p.number>1&&r)for(let w=p?.number+1n;w<_.number;w++){let A=await J(e,ar,"getBlock")({blockNumber:w,includeTransactions:l});x.onBlock(A,p),p=A}}if(p?.number==null||t==="pending"&&_?.number==null||_.number!==null&&_.number>p.number)x.onBlock(_,p),p=_}catch(_){x.onError?.(_)}},{emitOnBegin:n,interval:c}))})():(()=>{let b=!0,x=!0,_=()=>b=!1;return(async()=>{try{if(n)J(e,ar,"getBlock")({blockTag:t,includeTransactions:l}).then((v)=>{if(!b)return;if(!x)return;o(v,void 0),x=!1}).catch(i);let w=(()=>{if(e.transport.type==="fallback"){let v=e.transport.transports.find((T)=>T.config.type==="webSocket"||T.config.type==="ipc");if(!v)return e.transport;return v.value}return e.transport})(),{unsubscribe:A}=await w.subscribe({params:["newHeads"],async onData(v){if(!b)return;let T=await J(e,ar,"getBlock")({blockNumber:v.result?.number,includeTransactions:l}).catch(()=>{});if(!b)return;o(T,p),x=!1,p=T},onError(v){i?.(v)}});if(_=A,!b)_()}catch(w){i?.(w)}})(),()=>_()})()}ir();Fd();function oU(e,t){let{abi:r,address:n,args:o,batch:i=!0,eventName:s,fromBlock:a,onError:c,onLogs:d,poll:l,pollingInterval:p=e.pollingInterval,strict:m}=t;return(()=>{if(typeof l<"u")return l;if(typeof a==="bigint")return!0;if(e.transport.type==="webSocket"||e.transport.type==="ipc")return!1;if(e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc"))return!1;return!0})()?(()=>{let _=m??!1,w=Je(["watchContractEvent",n,o,i,e.uid,s,p,_,a]);return Er(w,{onLogs:d,onError:c},(A)=>{let v;if(a!==void 0)v=a-1n;let T,P=!1,k=oo(async()=>{if(!P){try{T=await J(e,Zy,"createContractEventFilter")({abi:r,address:n,args:o,eventName:s,strict:_,fromBlock:a})}catch{}P=!0;return}try{let O;if(T)O=await J(e,wa,"getFilterChanges")({filter:T});else{let N=await J(e,no,"getBlockNumber")({});if(v&&v<N)O=await J(e,nb,"getContractEvents")({abi:r,address:n,args:o,eventName:s,fromBlock:v+1n,toBlock:N,strict:_});else O=[];v=N}if(O.length===0)return;if(i)A.onLogs(O);else for(let N of O)A.onLogs([N])}catch(O){if(T&&O instanceof Xn)P=!1;A.onError?.(O)}},{emitOnBegin:!0,interval:p});return async()=>{if(T)await J(e,Ea,"uninstallFilter")({filter:T});k()}})})():(()=>{let _=m??!1,w=Je(["watchContractEvent",n,o,i,e.uid,s,p,_]),A=!0,v=()=>A=!1;return Er(w,{onLogs:d,onError:c},(T)=>((async()=>{try{let P=(()=>{if(e.transport.type==="fallback"){let N=e.transport.transports.find((j)=>j.config.type==="webSocket"||j.config.type==="ipc");if(!N)return e.transport;return N.value}return e.transport})(),k=s?ui({abi:r,eventName:s,args:o}):[],{unsubscribe:O}=await P.subscribe({params:["logs",{address:n,topics:k}],onData(N){if(!A)return;let j=N.result;try{let{eventName:R,args:K}=qc({abi:r,data:j.data,topics:j.topics,strict:m}),Z=Tr(j,{args:K,eventName:R});T.onLogs([Z])}catch(R){let K,Z;if(R instanceof sa||R instanceof Sc){if(m)return;K=R.abiItem.name,Z=R.abiItem.inputs?.some((pe)=>!(("name"in pe)&&pe.name))}let re=Tr(j,{args:Z?[]:{},eventName:K});T.onLogs([re])}},onError(N){T.onError?.(N)}});if(v=O,!A)v()}catch(P){c?.(P)}})(),()=>v()))})()}ir();Fd();function iU(e,{address:t,args:r,batch:n=!0,event:o,events:i,fromBlock:s,onError:a,onLogs:c,poll:d,pollingInterval:l=e.pollingInterval,strict:p}){let m=(()=>{if(typeof d<"u")return d;if(typeof s==="bigint")return!0;if(e.transport.type==="webSocket"||e.transport.type==="ipc")return!1;if(e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc"))return!1;return!0})(),h=p??!1;return m?(()=>{let _=Je(["watchEvent",t,r,n,e.uid,o,l,s]);return Er(_,{onLogs:c,onError:a},(w)=>{let A;if(s!==void 0)A=s-1n;let v,T=!1,P=oo(async()=>{if(!T){try{v=await J(e,Wy,"createEventFilter")({address:t,args:r,event:o,events:i,strict:h,fromBlock:s})}catch{}T=!0;return}try{let k;if(v)k=await J(e,wa,"getFilterChanges")({filter:v});else{let O=await J(e,no,"getBlockNumber")({});if(A&&A!==O)k=await J(e,sl,"getLogs")({address:t,args:r,event:o,events:i,fromBlock:A+1n,toBlock:O});else k=[];A=O}if(k.length===0)return;if(n)w.onLogs(k);else for(let O of k)w.onLogs([O])}catch(k){if(v&&k instanceof Xn)T=!1;w.onError?.(k)}},{emitOnBegin:!0,interval:l});return async()=>{if(v)await J(e,Ea,"uninstallFilter")({filter:v});P()}})})():(()=>{let _=!0,w=()=>_=!1;return(async()=>{try{let A=(()=>{if(e.transport.type==="fallback"){let k=e.transport.transports.find((O)=>O.config.type==="webSocket"||O.config.type==="ipc");if(!k)return e.transport;return k.value}return e.transport})(),v=i??(o?[o]:void 0),T=[];if(v){if(T=[v.flatMap((O)=>ui({abi:[O],eventName:O.name,args:r}))],o)T=T[0]}let{unsubscribe:P}=await A.subscribe({params:["logs",{address:t,topics:T}],onData(k){if(!_)return;let O=k.result;try{let{eventName:N,args:j}=qc({abi:v??[],data:O.data,topics:O.topics,strict:h}),R=Tr(O,{args:j,eventName:N});c([R])}catch(N){let j,R;if(N instanceof sa||N instanceof Sc){if(p)return;j=N.abiItem.name,R=N.abiItem.inputs?.some((Z)=>!(("name"in Z)&&Z.name))}let K=Tr(O,{args:R?[]:{},eventName:j});c([K])}},onError(k){a?.(k)}});if(w=P,!_)w()}catch(A){a?.(A)}})(),()=>w()})()}function sU(e,{batch:t=!0,onError:r,onTransactions:n,poll:o,pollingInterval:i=e.pollingInterval}){return(typeof o<"u"?o:e.transport.type!=="webSocket"&&e.transport.type!=="ipc")?(()=>{let d=Je(["watchPendingTransactions",e.uid,t,i]);return Er(d,{onTransactions:n,onError:r},(l)=>{let p,m=oo(async()=>{try{if(!p)try{p=await J(e,Ky,"createPendingTransactionFilter")({});return}catch(b){throw m(),b}let h=await J(e,wa,"getFilterChanges")({filter:p});if(h.length===0)return;if(t)l.onTransactions(h);else for(let b of h)l.onTransactions([b])}catch(h){l.onError?.(h)}},{emitOnBegin:!0,interval:i});return async()=>{if(p)await J(e,Ea,"uninstallFilter")({filter:p});m()}})})():(()=>{let d=!0,l=()=>d=!1;return(async()=>{try{let{unsubscribe:p}=await e.transport.subscribe({params:["newPendingTransactions"],onData(m){if(!d)return;let h=m.result;n([h])},onError(m){r?.(m)}});if(l=p,!d)l()}catch(p){r?.(p)}})(),()=>l()})()}var sde=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;function ade(e){if(!sde.test(e))return!1;return!Number.isNaN(new Date(e).getTime())}function sA(e){if(!ade(e))return new Date(Number.NaN);return new Date(e)}function aU(e){let{scheme:t,statement:r,...n}=e.match(cde)?.groups??{},{chainId:o,expirationTime:i,issuedAt:s,notBefore:a,requestId:c,...d}=e.match(ude)?.groups??{},l=e.split("Resources:")[1]?.split(`
144
144
  - `).slice(1);return{...n,...d,...o?{chainId:Number(o)}:{},...i?{expirationTime:sA(i)}:{},...s?{issuedAt:sA(s)}:{},...a?{notBefore:sA(a)}:{},...c?{requestId:c}:{},...l?{resources:l}:{},...t?{scheme:t}:{},...r?{statement:r}:{}}}var cde=/^(?:(?<scheme>[a-zA-Z][a-zA-Z0-9+-.]*):\/\/)?(?<domain>[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\n)(?<address>0x[a-fA-F0-9]{40})\n\n(?:(?<statement>.*)\n\n)?/,ude=/(?:URI: (?<uri>.+))\n(?:Version: (?<version>.+))\n(?:Chain ID: (?<chainId>\d+))\n(?:Nonce: (?<nonce>[a-zA-Z0-9]+))\n(?:Issued At: (?<issuedAt>.+))(?:\nExpiration Time: (?<expirationTime>.+))?(?:\nNot Before: (?<notBefore>.+))?(?:\nRequest ID: (?<requestId>.+))?/;Mn();us();function cU(e){let{address:t,domain:r,message:n,nonce:o,scheme:i,time:s=new Date}=e;if(r&&n.domain!==r)return!1;if(o&&n.nonce!==o)return!1;if(i&&n.scheme!==i)return!1;if(Number.isNaN(s.getTime()))return!1;if(n.expirationTime){if(Number.isNaN(n.expirationTime.getTime()))return!1;if(s>=n.expirationTime)return!1}if(n.notBefore){if(Number.isNaN(n.notBefore.getTime()))return!1;if(s<n.notBefore)return!1}try{if(!n.address)return!1;if(!ht(n.address,{strict:!1}))return!1;if(t&&!wr(n.address,t))return!1}catch{return!1}return!0}async function uU(e,t){let{address:r,domain:n,message:o,nonce:i,scheme:s,signature:a,time:c=new Date,...d}=t,l=aU(o);if(!l.address)return!1;if(!cU({address:r,domain:n,message:l,nonce:i,scheme:s,time:c}))return!1;let m=gl(o);return Aa(e,{address:l.address,hash:m,signature:a,...d})}Mr();Ge();class cr extends C{constructor({docsPath:e}={}){super(["Could not find an Account to execute with this Action.","Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client."].join(`
@@ -149,4 +149,4 @@ ${t}`}function U0(e,t){return Li(rd.sign(pc(t),e))}var Rf=[0.0001,0.001,0.01,0.1
149
149
  "@signature-params": ${d}`;return{"Signature-Input":`monaco=${d}`,Signature:`monaco=:${NU(rd.sign(pc(l),e.privateKey))}:`,"Content-Digest":c}}var Tde="@0xmonaco/core",wA={Jan:0,Feb:1,Mar:2,Apr:3,May:4,Jun:5,Jul:6,Aug:7,Sep:8,Oct:9,Nov:10,Dec:11},SA="Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec",Ede=new RegExp(`^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\\d{2}) (${SA}) (\\d{4}) (\\d{2}):(\\d{2}):(\\d{2}) GMT$`),Pde=new RegExp(`^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\\d{2})-(${SA})-(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2}) GMT$`),Ade=new RegExp(`^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (${SA}) ([ \\d]\\d) (\\d{2}):(\\d{2}):(\\d{2}) (\\d{4})$`);function Ide(e,t,r,n,o,i){let s=new Date(Date.now()),a=Math.floor(s.getUTCFullYear()/100)*100+e,c=Date.UTC(a,t,r,n,o,i),d=Date.UTC(s.getUTCFullYear()+50,s.getUTCMonth(),s.getUTCDate(),s.getUTCHours(),s.getUTCMinutes(),s.getUTCSeconds());return c>d?a-100:a}function kde(e){let t,r,n,o,i,s,a=Ede.exec(e),c=Pde.exec(e),d=Ade.exec(e);if(a)t=Number(a[1]),r=wA[a[2]],n=Number(a[3]),o=Number(a[4]),i=Number(a[5]),s=Number(a[6]);else if(c){if(t=Number(c[1]),r=wA[c[2]],o=Number(c[4]),i=Number(c[5]),s=Number(c[6]),r===void 0)return;n=Ide(Number(c[3]),r,t,o,i,s)}else if(d)r=wA[d[1]],t=Number((d[2]??"").trim()),o=Number(d[3]),i=Number(d[4]),s=Number(d[5]),n=Number(d[6]);else return;if(r===void 0)return;let l=Date.UTC(n,r,t,o,i,s),p=new Date(l);if(p.getUTCFullYear()!==n||p.getUTCMonth()!==r||p.getUTCDate()!==t||p.getUTCHours()!==o||p.getUTCMinutes()!==i||p.getUTCSeconds()!==s)return;return l}class qe{apiUrl;sessionKeypair;serverKey;requestSigning="legacy";setRequestSigning(e){if(e!=="legacy"&&e!=="rfc9421")throw Error("Unsupported request signing protocol");this.requestSigning=e}retryOptions;constructor(e,t){this.apiUrl=e,this.retryOptions={maxRetries:t?.maxRetries??3,baseDelayMs:t?.baseDelayMs??1000}}setSessionKeypair(e){this.sessionKeypair=e?Y8(e.publicKey,e.privateKey):void 0}setServerKey(e){this.serverKey=e}parseRequestBody(e){if(!e)return;if(typeof e==="string")try{return JSON.parse(e)}catch{return e}if(e instanceof FormData){let t={};return e.forEach((r,n)=>{t[n]=r instanceof File?`[File: ${r.name}]`:r}),t}if(e instanceof URLSearchParams){let t={};return e.forEach((r,n)=>{t[n]=r}),t}if(e instanceof Blob)return{type:"[Blob]",size:e.size,contentType:e.type};if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return{type:"[ArrayBuffer]",size:e instanceof ArrayBuffer?e.byteLength:e.byteLength};if(typeof ReadableStream<"u"&&e instanceof ReadableStream)return{type:"[ReadableStream]",note:"Stream body not captured for logging"};return{type:"[Unknown]",bodyType:typeof e}}extractResponseMetadata(e){if(!e)return{};let t=e.get("x-request-id")||e.get("request-id")||e.get("x-correlation-id")||void 0,r=e.get("retry-after"),n;if(r!==null){let o=r.trim();if(/^\d+$/.test(o))n=Number.parseInt(o,10);else{let i=kde(o);if(i!==void 0)n=Math.max(0,Math.ceil((i-Date.now())/1000))}}return{requestId:t,retryAfter:n}}async executeRequest(e,t,r,n){let o,i={"User-Agent":Tde,...r.headers};try{o=await fetch(e,{...r,headers:i})}catch(d){throw new Zt(`Network request failed for ${t}`,{endpoint:e,cause:d instanceof Error?d:Error(String(d)),requestBody:n})}let s,a=o.headers?.get("content-type")||"unknown",c=o.clone?o.clone():o;try{s=await o.json()}catch(d){let l;try{l=await c.text()}catch{l="[Unable to read response body]"}if(!o.ok){let p=`API request failed: ${o.status}. Response is not JSON (Content-Type: ${a})`,{requestId:m,retryAfter:h}=this.extractResponseMetadata(o.headers);throw new Zt(p,{endpoint:e,statusCode:o.status,responseBody:{rawResponse:l.substring(0,500),contentType:a,parseError:d instanceof Error?d.message:String(d)},cause:d instanceof Error?d:void 0,requestBody:n,requestId:m,retryAfter:h})}if(l.trim()==="")return;throw new Zt(`Expected JSON response but received ${a}`,{endpoint:e,statusCode:o.status,responseBody:{rawResponse:l.substring(0,500),contentType:a},cause:d instanceof Error?d:void 0,requestBody:n})}if(!o.ok){let d=s!==null&&typeof s==="object"?s:void 0,l=(typeof d?.message==="string"?d.message:void 0)||(typeof d?.error==="string"?d.error:void 0)||`API request failed: ${o.status}`,{requestId:p,retryAfter:m}=this.extractResponseMetadata(o.headers);throw new Zt(l,{endpoint:e,statusCode:o.status,responseBody:s,requestBody:n,requestId:p,retryAfter:m})}return s}async makeAuthenticatedRequest(e,t={}){if(!this.sessionKeypair)throw new Zt("Session keypair not set. Authenticate (login) first.",{endpoint:`${this.apiUrl}${e}`,statusCode:$b.StatusCodes.UNAUTHORIZED});let r=`${this.apiUrl}${e}`,n=this.parseRequestBody(t.body),o=this.buildSignatureHeaders(e,t),i=t.headers;if(this.requestSigning==="rfc9421"){let s={};new Headers(t.headers).forEach((a,c)=>{s[c]=a}),i=s}return this.executeRequest(r,e,{...t,...this.requestSigning==="rfc9421"?{redirect:"error"}:{},headers:{"Content-Type":"application/json",...i,...o}},n)}buildSignatureHeaders(e,t){if(!this.sessionKeypair)throw new Zt("Session keypair not set. Authenticate (login) first.",{endpoint:`${this.apiUrl}${e}`,statusCode:$b.StatusCodes.UNAUTHORIZED});let r=(t.method??"GET").toUpperCase();if(this.requestSigning==="rfc9421"){if(t.body!=null&&typeof t.body!=="string")throw Error("Signed requests require a string body");let c=new Headers(t.headers);for(let l of["signature","signature-input","content-digest","x-monaco-publickey","x-monaco-timestamp","x-monaco-signature"])if(c.has(l))throw Error("Signature headers are managed by the SDK");let d=new URL(`${this.apiUrl}${e}`);return zU(this.sessionKeypair,r,d.pathname+d.search,pc(t.body??""),Math.floor(Date.now()/1000))}let n=Date.now(),o=typeof t.body==="string"?pc(t.body):new Uint8Array(0),i=J8(o),s=Q8(r,e,n,i),a=U0(this.sessionKeypair.privateKey,s);return{"X-Monaco-PublicKey":Li(this.sessionKeypair.publicKey),"X-Monaco-Timestamp":String(n),"X-Monaco-Signature":a}}async makeBackendRequest(e,t={}){if(!this.serverKey)throw new Zt("Server key not set. Call setServerKey(sk_...) first.",{endpoint:`${this.apiUrl}${e}`,statusCode:$b.StatusCodes.UNAUTHORIZED});let r=`${this.apiUrl}${e}`,n=this.parseRequestBody(t.body);return this.executeRequest(r,e,{...t,headers:{"Content-Type":"application/json","x-server-key":this.serverKey,...t.headers}},n)}async makePublicRequest(e,t={}){let r=`${this.apiUrl}${e}`,n=this.parseRequestBody(t.body);return this.executeRequest(r,e,{...t,headers:{"Content-Type":"application/json",...t.headers}},n)}}function nt(e){return encodeURIComponent(e)}function Bt(e,t){if(!t)return e;let r=new URLSearchParams;for(let[o,i]of Object.entries(t))if(i!==void 0)r.set(o,String(i));let n=r.toString();return n?`${e}?${n}`:e}var ae={orders:{create:()=>"/api/v1/orders",list:(e)=>Bt("/api/v1/orders",e),get:(e)=>`/api/v1/orders/${nt(e)}`,replace:(e)=>`/api/v1/orders/${nt(e)}`,cancel:()=>"/api/v1/orders/cancel",batchCancel:()=>"/api/v1/orders/batch-cancel",batchCancelAll:()=>"/api/v1/orders/batch-cancel-all",batchCancelAllByPair:(e)=>`/api/v1/orders/batch-cancel-all/${nt(e)}`,batchCreate:()=>"/api/v1/orders/batch-create",batchReplace:()=>"/api/v1/orders/batch-replace",listConditional:(e)=>Bt("/api/v1/orders/conditional",e),cancelConditional:(e)=>`/api/v1/orders/conditional/${nt(e)}`,getConditional:(e)=>`/api/v1/orders/conditional/${nt(e)}`,createTwap:()=>"/api/v1/orders/twap",listTwap:(e)=>Bt("/api/v1/orders/twap",e),getTwap:(e)=>`/api/v1/orders/twap/${nt(e)}`,getTwapTca:(e)=>`/api/v1/orders/twap/${nt(e)}/tca`,cancelTwap:(e)=>`/api/v1/orders/twap/${nt(e)}/cancel`},delegatedAgents:{list:()=>"/api/v1/delegated-agents",owners:()=>"/api/v1/delegated-agents/owners",byId:(e)=>`/api/v1/delegated-agents/${nt(e)}`,sessions:()=>"/api/v1/delegated-agents/sessions"},withdrawals:{initiate:()=>"/api/v1/withdrawals",byIndex:(e)=>`/api/v1/withdrawals/${nt(String(e))}`,list:(e)=>Bt("/api/v1/withdrawals",e)},market:{listTradingPairs:(e)=>Bt("/api/v1/market/pairs",e),getTradingPair:(e)=>`/api/v1/market/pairs/${nt(e)}`,getCandles:(e,t,r)=>Bt(`/api/v1/market/pairs/charts/candlestick/${nt(e)}/${nt(t)}`,r),getMarketMetadata:(e)=>`/api/v1/market/pairs/${nt(e)}/metadata`,getPerpMarketConfig:(e)=>`/api/v1/market/pairs/${nt(e)}/perp/config`,getPerpMarketSummary:(e)=>`/api/v1/market/pairs/${nt(e)}/perp/summary`,getMarkPrice:(e)=>`/api/v1/market/pairs/${nt(e)}/mark-price`,getIndexPrice:(e)=>`/api/v1/market/pairs/${nt(e)}/index-price`,getFundingState:(e)=>`/api/v1/market/pairs/${nt(e)}/funding`,listFundingHistory:(e,t)=>Bt(`/api/v1/market/pairs/${nt(e)}/funding/history`,t),listAllFundingHistory:(e)=>Bt("/api/v1/market/funding/history",e),getOpenInterest:(e)=>`/api/v1/market/pairs/${nt(e)}/open-interest`,getScreener:(e)=>Bt("/api/v1/market/screener",e),getMarketStats:()=>"/api/v1/market/stats"},orderbook:{get:(e,t)=>Bt(`/api/v1/orderbook/${nt(e)}`,t)},trades:{publicByPair:(e,t)=>Bt(`/api/v1/trades/${nt(e)}`,t),byId:(e)=>`/api/v1/trades/by-id/${nt(e)}`,user:(e)=>Bt("/api/v1/accounts/trades",e)},applications:{orders:(e)=>Bt("/api/v1/applications/orders",e),users:(e)=>Bt("/api/v1/applications/users",e),movements:(e)=>Bt("/api/v1/applications/movements",e),balances:(e)=>Bt("/api/v1/applications/balances",e),stats:(e)=>Bt("/api/v1/applications/stats",e)},subAccounts:{list:()=>"/api/v1/accounts/sub-accounts",createLimit:()=>"/api/v1/accounts/sub-accounts/limits",getLimits:(e)=>`/api/v1/accounts/sub-accounts/${nt(e)}/limits`,limit:(e,t)=>`/api/v1/accounts/sub-accounts/${nt(e)}/limits/${nt(t)}`},faucet:{mint:()=>"/api/v1/faucet/mint",info:()=>"/api/v1/faucet/info"},sweeper:{register:()=>"/api/v1/sweeper/register",chains:()=>"/api/v1/sweeper/chains"},whitelist:{submit:()=>"/api/v1/whitelist"},positions:{list:(e)=>Bt("/api/v1/positions",e),get:(e)=>`/api/v1/positions/${nt(e)}`,close:(e)=>`/api/v1/positions/${nt(e)}/close`,batchCloseAll:()=>"/api/v1/positions/batch-close-all",risk:(e)=>`/api/v1/positions/${nt(e)}/risk`,attachTpSl:(e)=>`/api/v1/positions/${nt(e)}/tp-sl`,history:(e)=>Bt("/api/v1/positions/history",e),pnlHistory:(e,t)=>Bt(`/api/v1/positions/${nt(e)}/pnl/history`,t)},marginAccounts:{list:(e)=>Bt("/api/v1/margin/accounts",e),parentSummary:(e)=>Bt("/api/v1/margin/parent-margin-account",e),summary:(e,t)=>Bt(`/api/v1/margin/accounts/${nt(e)}`,t),availableCollateral:(e)=>Bt("/api/v1/margin/collateral/available",e),transferIn:(e)=>`/api/v1/margin/accounts/${nt(e)}/collateral/transfer-in`,transferInParent:()=>"/api/v1/margin/parent-margin-account/collateral/transfer-in",transferInRiskBucket:()=>"/api/v1/margin/risk-buckets/collateral/transfer-in",transferOut:(e)=>`/api/v1/margin/accounts/${nt(e)}/collateral/transfer-out`,transferOutParent:()=>"/api/v1/margin/parent-margin-account/collateral/transfer-out",movements:(e,t)=>Bt(`/api/v1/margin/accounts/${nt(e)}/movements`,t),parentMovements:(e)=>Bt("/api/v1/margin/parent-margin-account/movements",e),simulateParentMarginOrderRisk:()=>"/api/v1/margin/parent-margin-account/simulate-order-risk",simulateOrderRisk:(e)=>`/api/v1/margin/accounts/${nt(e)}/simulate-order-risk`,simulateRiskBucketOrderRisk:()=>"/api/v1/margin/risk-buckets/simulate-order-risk"},streams:{orderbook:()=>"/api/v1/streaming/orderbook",trades:()=>"/api/v1/streaming/trades",perpMarketSummaries:()=>"/api/v1/streaming/perp-market-summaries",markPrices:()=>"/api/v1/streaming/mark-prices",privateTrades:()=>"/api/v1/streaming/private-trades",orders:()=>"/api/v1/streaming/orders",positions:()=>"/api/v1/streaming/positions",funding:()=>"/api/v1/streaming/funding",liquidationAlerts:()=>"/api/v1/streaming/liquidation-alerts"}};class Nb extends qe{async getApplicationConfig(){let e=await this.makeAuthenticatedRequest("/api/v1/applications/config",{method:"GET"});return{id:e.id,name:e.name,allowedOrigins:e.allowedOrigins,webhookUrl:e.webhookUrl,vaultContractAddress:e.vaultContractAddress,clientId:e.clientId}}async listApplicationOrders(e){return await this.makeBackendRequest(ae.applications.orders(e))}async listApplicationUsers(e){return await this.makeBackendRequest(ae.applications.users(e))}async listApplicationMovements(e){return await this.makeBackendRequest(ae.applications.movements(e))}async listApplicationBalances(e){return await this.makeBackendRequest(ae.applications.balances(e))}async getApplicationStats(e){return await this.makeBackendRequest(ae.applications.stats(e))}}var Rde=S({applicationId:y().uuid(),enrolled:ue(),payoutAddress:y().nullable().optional(),buildercodesEnabled:ue(),buildercodesBudgetBps:M().int().min(0).max(1e4)}),vA=S({page:M().int().min(1).max(1e4).optional(),pageSize:M().int().min(1).max(100).optional()}),BU=S({tradeId:y().uuid(),payoutAddress:y(),token:y(),amount:y(),appliedBps:M().int(),createdAt:y()}),Ode=S({payouts:Ie(BU),total:M().int().nonnegative(),page:M().int().positive(),pageSize:M().int().positive(),totalPages:M().int().nonnegative()}),LU=S({token:y(),totalAmount:y(),payoutCount:M().int().nonnegative(),lastCreditedAt:y()}),Cde=S({totalPayouts:M().int().nonnegative(),lastCreditedAt:y().nullable().optional(),byToken:Ie(LU)}),DU=S({token:y(),available:y()}),Mde=S({balances:Ie(DU)}),TA=S({token:y().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:y().trim().min(1,"amount is required").refine((e)=>/^\d+$/.test(e)&&BigInt(e)>0n,"amount must be a positive integer string")}),$de=S({payoutBalance:y(),tradingBalance:y()});var EA=S({tradingPairId:y().trim().min(1,"Trading pair ID is required and cannot be empty"),side:H(["BUY","SELL"],{message:"Order side is required and must be either 'BUY' or 'SELL'"}),price:y().trim().min(1,"Price is required and cannot be empty").refine((e)=>!Number.isNaN(Number(e)),"Price must be a valid number").refine((e)=>Number(e)>0,"Price must be greater than 0"),quantity:y().trim().min(1,"Quantity is required and cannot be empty").refine((e)=>!Number.isNaN(Number(e)),"Quantity must be a valid number").refine((e)=>Number(e)>0,"Quantity must be greater than 0"),orderType:H(["LIMIT","MARKET"]).optional(),slippageToleranceBps:M().int().min(0,"Slippage tolerance must be between 0 and 1000 bps").max(1000,"Slippage tolerance must be between 0 and 1000 bps").optional()}).superRefine((e,t)=>{if(e.slippageToleranceBps!==void 0&&e.orderType!=="MARKET")t.addIssue({code:Hn.custom,message:"slippageToleranceBps is only valid when orderType is MARKET",path:["slippageToleranceBps"]})}),Nde=S({applicationName:y().nullable().optional(),applicationTakerFee:y(),applicationTakerFeeBps:M(),buyOrderLockAmount:y().nullable().optional(),makerTotalReceipt:y(),monacoMakerRebate:y(),monacoMakerRebateBps:M(),monacoMakerRebateBpsExact:y(),monacoTakerFee:y(),monacoTakerFeeBps:M(),monacoTakerFeeBpsExact:y(),notional:y(),takerTotalPayment:y(),totalTakerFees:y(),maxQuantity:y().nullable(),maxQuantityRaw:y().nullable(),slippageToleranceBps:M().nullable()}),PA=S({tradingPairId:y().trim().min(1,"Trading pair ID is required and cannot be empty")}),UU=S({tierLevel:M().int(),minVolumeThreshold:y(),makerFeeBps:y(),takerFeeBps:y()}),zde=S({currentTierLevel:M().int(),weightedVolume14d:y(),spotVolume14d:y(),perpVolume14d:y(),volumeToNextTier:y().nullable().optional(),nextTierLevel:M().int().nullable().optional(),feeSchedule:Ie(UU)});var FU=S({token:y(),available:y()}),Bde=S({balances:Ie(FU)}),Lde=S({code:y(),createdAt:y(),customCode:y(),isCustom:ue(),display:y()}),jU=H(["taken","too_short","too_long","reserved","invalid_char","looks_like_address"]),Dde=S({available:ue(),reason:Lp((e)=>e===""||e===null?void 0:e,jU.optional())}),AA=S({code:y().trim().min(1,"code is required").regex(/^[A-Za-z][A-Za-z0-9_]{4,19}$/,"code must start with a letter and be 5–20 chars of letters, digits, or underscores")}),Ude=S({code:y()}),IA=S({token:y().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:y().trim().min(1,"amount is required").refine((e)=>/^\d+$/.test(e)&&BigInt(e)>0n,"amount must be a positive integer string")}),Fde=S({rewardsBalance:y(),tradingBalance:y()}),qU=S({source:y(),sourceDisplay:y(),level:M(),amount:y(),token:y(),rateApplied:y(),createdAt:y()}),jde=S({referrer:y(),referrerDisplay:y(),totalEarned:y(),rewards:Ie(qU)}),HU=S({source:y(),sourceDisplay:y(),level:M(),totalEarned:y(),token:y()}),GU=S({wallet:y(),display:y(),referredAt:y(),totalEarned:y()}),VU=S({totalEarned:y(),level1Earned:y(),level2Earned:y(),level3Earned:y()}),qde=S({earningsBySource:Ie(HU),directReferees:Ie(GU),summary:VU});var zb=["SUBMITTED","PARTIALLY_FILLED","FILLED","SETTLED_ON_CHAIN","SETTLED","CANCELLED","REJECTED","EXPIRED"];class ZU extends Error{issues;constructor(e){let t=e.issues.map((r)=>{let n=r.path.join(".");return`${n?`${n}: `:""}${r.message}`});super(`Validation failed:
150
150
  - ${t.join(`
151
151
  - `)}`);this.name="ValidationError",this.issues=e.issues}getErrors(){let e={};for(let t of this.issues){let r=t.path.join(".");e[r||"root"]=t.message}return e}}function ye(e,t){let r=e.safeParse(t);if(!r.success)throw new ZU(r.error);return r.data}var Il=H(["BUY","SELL"],{message:'Order side must be "BUY" or "SELL"'}),Rm=H(["SPOT","MARGIN"],{message:'Trading mode must be "SPOT" or "MARGIN"'}),Ub=H(["ISOLATED","CROSS"],{message:'Margin mode must be "ISOLATED" or "CROSS"'}),Om=H(["LONG","SHORT","NONE"],{message:'Position side must be "LONG", "SHORT", or "NONE"'}),WU=H(["GTC","IOC","FOK"],{message:'Time in force must be "GTC", "IOC", or "FOK"'}),kA=H(["GTC","IOC"],{message:'Conditional order time in force must be "GTC" or "IOC"'}),Wc=H(["CANCEL_MAKER","CANCEL_TAKER","CANCEL_BOTH","SKIP"],{message:'Self-trade prevention mode must be "CANCEL_MAKER", "CANCEL_TAKER", "CANCEL_BOTH", or "SKIP"'}),kl=H(["LIMIT","MARKET"],{message:'Order type must be "LIMIT" or "MARKET"'}),ut=y().trim().min(1,"Value cannot be empty").regex(/^\d+(\.\d+)?$/,"Value must be a positive decimal number (e.g., '1.5', '100')").refine((e)=>Number.parseFloat(e)>0,{message:"Value must be greater than 0"}),Re=M5({message:"Must be a valid UUID (e.g., '123e4567-e89b-12d3-a456-426614174000')"}),ka=Ou.datetime({message:"Must be a valid ISO 8601 date string (e.g., '2024-12-31T23:59:59Z')"}),KU=M().min(0,"Slippage tolerance must be at least 0 (no slippage)").max(1,"Slippage tolerance cannot exceed 1 (100%)").optional(),Cm=M().int().min(0,"Slippage tolerance must be at least 0 bps").max(1e4,"Slippage tolerance cannot exceed 10000 bps"),YU=M().int().min(0,"Slippage tolerance must be at least 0 bps").max(1000,"Slippage tolerance cannot exceed 1000 bps"),Hde=M().int().min(0,"Slippage tolerance must be at least 0 bps").max(500,"TWAP slippage tolerance cannot exceed 500 bps (5%)"),Bb=S({triggerPrice:ut,orderType:kl,limitPrice:ut.optional(),quantity:ut.optional(),closePosition:ue().optional(),timeInForce:kA.optional(),slippageToleranceBps:Cm.optional(),expiresAt:ka.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.limitPrice!==void 0,{message:"limitPrice is required for LIMIT parent TP/SL",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.limitPrice===void 0,{message:"limitPrice must not be provided for MARKET parent TP/SL",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce is only allowed for LIMIT parent TP/SL",path:["timeInForce"]}).refine((e)=>e.orderType!=="LIMIT"||e.slippageToleranceBps===void 0,{message:"slippageToleranceBps is only allowed for MARKET parent TP/SL",path:["slippageToleranceBps"]}).refine((e)=>e.closePosition!==!0||e.quantity===void 0,{message:"quantity must be omitted when closePosition is true",path:["quantity"]}).refine((e)=>e.quantity!==void 0||e.closePosition!==!1,{message:"quantity is required when closePosition is false",path:["closePosition"]}),Lb=(e)=>e?.takeProfit!==void 0||e?.stopLoss!==void 0,RA=(e,t)=>t===void 0||t!=="NONE"&&(e==="BUY"&&t==="LONG"||e==="SELL"&&t==="SHORT"),OA=y().min(1).max(64).regex(/^[A-Za-z0-9._:-]+$/,"idempotencyKey must contain only letters, digits, or . _ : -"),JU=S({tradingPairId:Re,side:Il,quantity:ut,price:ut,options:S({idempotencyKey:OA.optional(),tradingMode:Rm.optional(),useMasterBalance:ue().optional(),expirationDate:ka.optional(),timeInForce:WU.optional(),marginAccountId:Re.optional(),marginMode:Ub.optional(),riskBucketId:Re.optional(),riskBucketCollateral:ut.optional(),strategyKey:y().min(1).max(128).optional(),positionSide:Om.optional(),leverage:ut.optional(),reduceOnly:ue().optional(),postOnly:ue().optional(),selfTradePreventionMode:Wc.optional(),takeProfit:Bb.optional(),stopLoss:Bb.optional()}).optional()}).refine((e)=>RA(e.side,e.options?.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["options","positionSide"]}).refine((e)=>e.options?.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["options","leverage"]}).refine((e)=>!Lb(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss are only supported for MARGIN orders",path:["options"]}).refine((e)=>!Lb(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}).refine((e)=>e.options?.postOnly!==!0||e.options?.timeInForce===void 0||e.options.timeInForce!=="IOC"&&e.options.timeInForce!=="FOK",{message:"postOnly cannot be combined with IOC/FOK time in force",path:["options","timeInForce"]}),QU=S({tradingPairId:Re,side:Il,quantity:ut,options:S({idempotencyKey:OA.optional(),tradingMode:Rm.optional(),slippageTolerance:KU,marginAccountId:Re.optional(),marginMode:Ub.optional(),riskBucketId:Re.optional(),riskBucketCollateral:ut.optional(),strategyKey:y().min(1).max(128).optional(),positionSide:Om.optional(),leverage:ut.optional(),reduceOnly:ue().optional(),selfTradePreventionMode:Wc.optional(),takeProfit:Bb.optional(),stopLoss:Bb.optional()}).optional()}).refine((e)=>RA(e.side,e.options?.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["options","positionSide"]}).refine((e)=>e.options?.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["options","leverage"]}).refine((e)=>!Lb(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss are only supported for MARGIN orders",path:["options"]}).refine((e)=>!Lb(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}),XU=S({orderId:Re,remainingQuantityTarget:ut.optional()}),eF=S({orderId:Re,newOrder:S({price:ut.optional(),quantity:ut.optional(),useMasterBalance:ue().optional(),postOnly:ue().optional(),selfTradePreventionMode:Wc.optional()})}),tF=S({status:st([H(zb),Ie(H(zb)).min(1,"Status filter must list at least one status")]).optional(),tradingPairId:Re.optional(),tradingMode:Rm.optional(),marginAccountId:Re.optional(),page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:y().optional()}).superRefine((e,t)=>{if(e.page!==void 0&&e.pageToken===void 0&&e.pageSize!==void 0&&e.pageSize>100)t.addIssue({code:Hn.custom,message:"Page size cannot exceed 100 in page-number mode (page without pageToken)",path:["pageSize"]})}),xIt=H(["STOP_LOSS","TAKE_PROFIT"],{message:'conditionType must be "STOP_LOSS" or "TAKE_PROFIT"'}),_It=H(["MARK_PRICE"],{message:'triggerSource must be "MARK_PRICE"'}),Gde=H(["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],{message:"Invalid conditional order state"}),wIt=H(["LONG","SHORT"],{message:'Position side must be "LONG" or "SHORT"'}),CA=S({conditionalOrderId:Re}),rF=S({marginAccountId:Re.optional(),tradingPairId:Re.optional(),state:Gde.optional(),page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),Vde=H(["PENDING","ACTIVE","COMPLETED","CANCELLED"],{message:"Invalid TWAP order state"}),Zde=st([M().int("durationSeconds must be a whole number of seconds").positive("durationSeconds must be greater than 0"),y().regex(/^[1-9]\d*$/,"durationSeconds must be a positive integer string (e.g., '3600')")]),Wde=2592000000,nF=S({tradingPairId:Re,side:Il,quantity:ut,options:S({durationSeconds:Zde.optional(),startTime:ka.optional(),endTime:ka.optional(),limitPrice:ut.optional(),slippageToleranceBps:Hde.optional(),randomize:ue().optional(),executionStyle:H(["TAKER","PASSIVE"]).optional(),reduceOnly:ue().optional(),tradingMode:Rm.optional(),marginAccountId:Re.optional(),riskBucketId:Re.optional(),marginMode:Ub.optional(),leverage:ut.optional(),strategyKey:y().min(1).max(128).optional(),useMasterBalance:ue().optional(),clientTwapId:y().min(1).max(36,"clientTwapId cannot exceed 36 characters").optional(),triggerPrice:ut.optional(),triggerDirection:H(["ABOVE","BELOW"]).optional(),conditionalExpiry:ka.optional()})}).refine((e)=>e.options.durationSeconds!==void 0!==(e.options.endTime!==void 0),{message:"Exactly one of durationSeconds or endTime must be set",path:["options","durationSeconds"]}).refine((e)=>e.options.startTime===void 0||e.options.endTime!==void 0,{message:"startTime is only valid together with endTime",path:["options","startTime"]}).refine((e)=>e.options.marginMode===void 0||e.options.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.riskBucketId===void 0||e.options.tradingMode==="MARGIN",{message:"riskBucketId is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.marginMode!=="CROSS"||e.options.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options.marginMode!=="CROSS"||e.options.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN TWAP orders",path:["options","leverage"]}).refine((e)=>e.options.triggerPrice!==void 0===(e.options.triggerDirection!==void 0),{message:"triggerPrice and triggerDirection are both-or-neither",path:["options","triggerDirection"]}).refine((e)=>e.options.triggerPrice===void 0||e.options.durationSeconds!==void 0,{message:"conditional TWAP (triggerPrice) requires durationSeconds — the window floats from the trigger instant",path:["options","durationSeconds"]}).refine((e)=>e.options.triggerPrice===void 0||e.options.startTime===void 0&&e.options.endTime===void 0,{message:"triggerPrice is incompatible with startTime/endTime",path:["options","triggerPrice"]}).refine((e)=>e.options.conditionalExpiry===void 0||e.options.triggerPrice!==void 0,{message:"conditionalExpiry is only valid together with triggerPrice",path:["options","conditionalExpiry"]}).refine((e)=>{let t=e.options.conditionalExpiry;if(t===void 0)return!0;let r=Date.parse(t);return Number.isNaN(r)||r>Date.now()},{message:"conditionalExpiry must be in the future",path:["options","conditionalExpiry"]}).refine((e)=>{let t=e.options.conditionalExpiry;if(t===void 0)return!0;let r=Date.parse(t);return Number.isNaN(r)||r-Date.now()<=Wde},{message:"conditionalExpiry cannot be more than 30 days after creation (the maximum window)",path:["options","conditionalExpiry"]}),Fb=S({twapOrderId:Re}),oF=S({state:Vde.optional(),tradingPairId:Re.optional(),page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),Kde=S({tradingPairId:Re,orderType:kl,side:Il,price:ut.optional(),quantity:ut,idempotencyKey:OA.optional(),tradingMode:Rm.optional(),slippageTolerance:KU,useMasterBalance:ue().optional(),expirationDate:ka.optional(),timeInForce:WU.optional(),marginAccountId:Re.optional(),marginMode:Ub.optional(),riskBucketId:Re.optional(),riskBucketCollateral:ut.optional(),strategyKey:y().min(1).max(128).optional(),positionSide:Om.optional(),leverage:ut.optional(),reduceOnly:ue().optional(),postOnly:ue().optional(),selfTradePreventionMode:Wc.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.price!==void 0,{message:"Price is required for LIMIT orders",path:["price"]}).refine((e)=>e.orderType!=="MARKET"||e.price===void 0,{message:"Price must not be provided for MARKET orders",path:["price"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce must not be provided for MARKET orders",path:["timeInForce"]}).refine((e)=>e.orderType!=="MARKET"||e.postOnly!==!0,{message:"postOnly must not be provided for MARKET orders",path:["postOnly"]}).refine((e)=>e.postOnly!==!0||e.timeInForce===void 0||e.timeInForce!=="IOC"&&e.timeInForce!=="FOK",{message:"postOnly cannot be combined with IOC/FOK time in force",path:["postOnly"]}).refine((e)=>e.riskBucketCollateral===void 0||e.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode===void 0||e.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode!=="CROSS"||e.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["marginAccountId"]}).refine((e)=>e.marginMode!=="CROSS"||e.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["riskBucketId"]}).refine((e)=>e.marginMode!=="CROSS"||e.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["riskBucketCollateral"]}).refine((e)=>e.marginMode!=="CROSS"||e.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["strategyKey"]}).refine((e)=>e.riskBucketCollateral===void 0||e.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["riskBucketId"]}).refine((e)=>e.riskBucketCollateral===void 0||e.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["reduceOnly"]}).refine((e)=>RA(e.side,e.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["positionSide"]}).refine((e)=>e.tradingMode!=="MARGIN"||e.reduceOnly===!0||e.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["leverage"]}),Db=100,iF=S({orders:Ie(Kde).min(1,"At least one order is required").max(Db,`At most ${Db} orders per batch request`)}),Yde=S({orderId:Re,price:ut.optional(),quantity:ut.optional(),useMasterBalance:ue().optional(),postOnly:ue().optional(),selfTradePreventionMode:Wc.optional()}).refine((e)=>e.price!==void 0||e.quantity!==void 0,{message:"At least one of price or quantity must be provided"}),sF=S({orders:Ie(Yde).min(1,"At least one order is required").max(Db,`At most ${Db} orders per batch request`)});var MA=S({page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),aF=MA.extend({state:y().trim().min(1,"State cannot be empty").optional(),tradingPairId:Re.optional()}),cF=S({marginAccountId:Re,tradingPairId:Re.optional()}),uF=S({tradingPairId:Re.optional()}).optional(),dF=S({asset:y().trim().min(1,"Asset cannot be empty").optional()}).optional(),Jde=S({asset:y().trim().min(1,"Asset cannot be empty"),amount:ut,tradingPairId:Re.optional(),strategyKey:y().trim().min(1,"Strategy key cannot be empty").optional(),marginMode:H(["ISOLATED","CROSS"]).optional()}).refine((e)=>!(e.marginMode==="CROSS"&&e.tradingPairId!==void 0),{message:"tradingPairId is not supported for CROSS risk buckets",path:["tradingPairId"]}),jb=S({asset:y().trim().min(1,"Asset cannot be empty"),amount:ut}),Qde=S({tradingPairId:Re,strategyKey:y().trim().min(1,"Strategy key cannot be empty").optional()}),lF=Qde.extend({marginMode:_e("ISOLATED").optional(),selectedTradingPairIds:kn().optional(),applyToPositionMargin:ue().optional()}),Xde=S({marginMode:_e("CROSS"),selectedTradingPairIds:kn().optional(),strategyKey:kn().optional()}),ele=S({marginMode:_e("CROSS"),selectedTradingPairIds:kn().optional(),strategyKey:kn().optional(),tradingPairId:kn().optional()}),$A=S({marginAccountId:Re,request:Jde}),pF=S({request:jb}),tle=S({marginMode:H(["ISOLATED","CROSS"]).optional(),selectedTradingPairIds:Et().optional()}).loose().superRefine((e,t)=>{if(e.selectedTradingPairIds===void 0)return;t.addIssue({code:"custom",path:["selectedTradingPairIds"],message:e.marginMode==="CROSS"?"selectedTradingPairIds is not accepted on a CROSS transfer: cross scope is derived from trading, so a funding call has nothing to declare":"selectedTradingPairIds is not supported for ISOLATED risk buckets"})}),fF=S({request:tle.pipe(st([jb.merge(lF).strict(),jb.merge(ele).strict()]))}),mF=S({request:jb}),hF=MA.extend({marginAccountId:Re,movementType:y().trim().min(1,"Movement type cannot be empty").optional()}),gF=MA.extend({movementType:y().trim().min(1,"Movement type cannot be empty").optional()}).optional(),NA=S({tradingPairId:Re,side:Il,positionSide:Om.optional(),orderType:kl,price:ut.optional(),quantity:ut,leverage:ut.optional(),reduceOnly:ue().optional(),slippageToleranceBps:YU.optional()}),zA=(e,t)=>{if(e.orderType!=="MARKET"&&e.slippageToleranceBps!==void 0)t.addIssue({code:Hn.custom,message:"slippageToleranceBps is only supported for MARKET orders",path:["slippageToleranceBps"]});if(e.positionSide!==void 0){let r=e.side==="BUY"?"LONG":"SHORT";if(e.positionSide!==r)t.addIssue({code:Hn.custom,message:"positionSide must match side when provided (BUY=LONG, SELL=SHORT)",path:["positionSide"]})}if(e.reduceOnly!==!0&&e.leverage===void 0)t.addIssue({code:Hn.custom,message:"leverage is required for normal margin orders",path:["leverage"]})},yF=NA.strict().superRefine(zA),rle=NA.merge(lF).strict().superRefine(zA),nle=NA.merge(Xde).strict().superRefine(zA),ole=S({marginMode:H(["ISOLATED","CROSS"]).optional(),selectedTradingPairIds:Et().optional()}).loose().superRefine((e,t)=>{if(e.selectedTradingPairIds===void 0)return;t.addIssue({code:"custom",path:["selectedTradingPairIds"],message:e.marginMode==="CROSS"?"selectedTradingPairIds is not accepted on a CROSS preview: cross scope is derived from trading, so a preview has nothing to declare":"selectedTradingPairIds is not supported for ISOLATED risk buckets"})}),ile=ole.pipe(st([rle,nle])),bF=S({marginAccountId:Re,request:yF}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),xF=S({request:yF}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),_F=S({request:ile}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]});var wF=H(["1m","5m","15m","30m","1h","4h","1d","1w","1M"],{message:'Interval must be one of: "1m", "5m", "15m", "30m", "1h", "4h", "1d", "1w", "1M"'}),sle=31536000000,ale=946684800000,qb=M().int().positive({message:"Timestamp must be a positive integer (milliseconds since epoch)"}).min(ale,{message:"Timestamp must be at least Jan 1, 2000 (946684800000 ms). Did you pass seconds instead of milliseconds?"}).max(Number.MAX_SAFE_INTEGER,{message:"Timestamp must not exceed JavaScript's maximum safe integer"}).refine((e)=>e<=Date.now()+sle,{message:"Timestamp must not be unreasonably far in the future (max 1 year ahead)"}),IIt=S({tradingPairId:Re,interval:wF,startTime:qb,endTime:qb}).refine((e)=>e.startTime<e.endTime,{message:"startTime must be less than endTime",path:["endTime"]}),kIt=y().min(1,"Trading pair symbol cannot be empty").regex(/^[A-Za-z0-9]{1,10}\/[A-Za-z0-9]{1,10}$/,{message:'Trading pair symbol must be in format "BASE/QUOTE" (e.g., "BTC/USDT", "ETH/USD")'}),cle=M().int().positive({message:"Limit must be a positive integer"}).max(500,{message:"Limit cannot exceed 500 bars per request"}).optional(),SF=S({tradingPairId:Re,interval:wF,startTime:qb.optional(),endTime:qb.optional(),limit:cle,priceType:H(["trade","mark"]).optional()}).refine((e)=>{if(e.startTime!==void 0&&e.endTime!==void 0)return e.startTime<e.endTime;return!0},{message:"startTime must be less than endTime",path:["endTime"]});var RIt=S({tradingPairId:Re}),OIt=S({query:y().min(1,"Search query cannot be empty").optional(),pageSize:M().int().min(1).max(100).optional(),page:M().int().min(1).optional()}),fi=S({tradingPairId:Re});var TF=S({page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),ule=H(["OPEN","CLOSED","LIQUIDATING","LIQUIDATED"],{message:'Position status must be "OPEN", "CLOSED", "LIQUIDATING", or "LIQUIDATED"'}),dle=H(["MARKET","LIMIT","IOC"],{message:'Close type must be "MARKET", "LIMIT", or "IOC"'}),Mm=S({positionId:Re}),EF=TF.extend({marginAccountId:Re.optional(),tradingPairId:Re.optional(),status:ule.optional()}),PF=Mm,AF=Mm.extend({request:S({closeType:dle,limitPrice:ut.optional(),slippageToleranceBps:Cm.optional(),quantity:ut.optional()})}).refine((e)=>e.request.closeType==="MARKET"||e.request.limitPrice!==void 0,{message:"limitPrice is required for LIMIT and IOC close requests",path:["request","limitPrice"]}).refine((e)=>e.request.closeType!=="MARKET"||e.request.limitPrice===void 0,{message:"limitPrice is not allowed for MARKET close requests",path:["request","limitPrice"]}),IF=S({tradingPairId:Re.optional(),slippageToleranceBps:Cm.optional()}),kF=Mm,vF=S({triggerPrice:ut,orderType:kl,limitPrice:ut.optional(),quantity:ut.optional(),closePosition:ue().optional(),timeInForce:kA.optional(),slippageToleranceBps:Cm.optional(),expiresAt:ka.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.limitPrice!==void 0,{message:"limitPrice is required for LIMIT TP/SL legs",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.limitPrice===void 0,{message:"limitPrice must not be provided for MARKET TP/SL legs",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce is only allowed for LIMIT TP/SL legs",path:["timeInForce"]}).refine((e)=>e.orderType!=="LIMIT"||e.slippageToleranceBps===void 0,{message:"slippageToleranceBps is only allowed for MARKET TP/SL legs",path:["slippageToleranceBps"]}).refine((e)=>e.closePosition!==!0||e.quantity===void 0,{message:"quantity must be omitted when closePosition is true",path:["quantity"]}).refine((e)=>e.quantity!==void 0||e.closePosition!==!1,{message:"quantity is required when closePosition is false",path:["closePosition"]}),RF=Mm.extend({request:S({takeProfit:vF.optional(),stopLoss:vF.optional(),oco:ue().optional()}).refine((e)=>e.takeProfit!==void 0||e.stopLoss!==void 0,{message:"At least one of takeProfit or stopLoss is required"}).refine((e)=>e.oco!==!0||e.takeProfit!==void 0&&e.stopLoss!==void 0,{message:"oco=true requires both takeProfit and stopLoss",path:["oco"]})}),OF=TF.extend({positionId:Re.optional(),marginAccountId:Re.optional(),tradingPairId:Re.optional(),reductionOnly:ue().optional()}),lle=H(["1m","5m","15m","1h","4h","1d"],{message:'Interval must be one of "1m", "5m", "15m", "1h", "4h", "1d"'}),CF=Mm.extend({params:S({interval:lle,startTime:M().int().min(0,"startTime must be a non-negative millisecond timestamp").optional(),endTime:M().int().min(0,"endTime must be a non-negative millisecond timestamp").optional()}).refine((e)=>e.startTime===void 0||e.endTime===void 0||e.startTime<e.endTime,{message:"startTime must be less than endTime",path:["startTime"]})});var ple=H(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"],{message:'Entry type must be "CREDIT", "DEBIT", "LOCK", "UNLOCK", or "FEE"'}),fle=H(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"],{message:'Transaction type must be "DEPOSIT", "WITHDRAWAL", "TRADE", "FEE", "FUNDING", "LIQUIDATION", "INTEREST", or "REWARD"'}),MF=S({mode:Wc}),$F=S({page:M().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:M().int("Page size must be an integer").min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional(),entryType:ple.optional(),transactionType:fle.optional(),assetId:Re.optional()}),NF=S({page:M().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:M().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),tradingPairId:Re.optional(),pageToken:y().optional()}).superRefine((e,t)=>{if(e.page!==void 0&&e.pageToken===void 0&&e.pageSize!==void 0&&e.pageSize>100)t.addIssue({code:Hn.custom,message:"Page size cannot exceed 100 in page-number mode (page without pageToken)",path:["pageSize"]})}),zF=S({page:M().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:M().int("Page size must be an integer").min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional(),tradingPairId:Re.optional(),positionId:Re.optional(),marginAccountId:Re.optional()});var FIt=y().regex(/^0x[a-fA-F0-9]{40}$/,{message:"Must be a valid Ethereum address (e.g., '0x1234...5678')"}),BA=st([y().regex(/^\d+$/,"Must be a positive integer string").refine((e)=>BigInt(e)>0n,{message:"Amount must be greater than 0"}),N5().refine((e)=>e>0n,{message:"Amount must be greater than 0"})]),BF=S({assetId:Re,amount:BA,autoWait:ue().optional()}),LF=S({assetId:Re,amount:BA,autoWait:ue().optional(),target:H(["spot","margin"]).optional(),options:S({asErc20:ue().optional()}).optional()}),DF=S({assetId:Re,amount:BA,destination:y().regex(/^0x[a-fA-F0-9]{40}$/,"destination must be a 0x-prefixed 20-byte hex address"),autoWait:ue().optional(),source:H(["spot","margin"]).optional()}),jIt=S({assetId:Re});var mle="OPERATIONS_BLOCKED",hle="OVERLOADED";function gle(e){if(!(e instanceof Zt)||!e.retryable)return e;if(!(e.statusCode===void 0||e.statusCode>=500)||yle(e))return e;return e.retryable=!1,e.suggestion="The claim's outcome is unknown: it may have committed after this failure. Do not retry automatically, and do not rely on a balance read to decide — an admitted claim can still be queued, so an unchanged balance does not prove it will not commit. Treat the claim as pending and reconcile before issuing another; this endpoint has no idempotency key, so a retry can claim a second time.",e}function yle(e){let t=e.responseBody;if(t===null||typeof t!=="object")return!1;let{error:r,code:n}=t;return r===mle||n===hle}class Hb extends qe{async getConfig(){return this.makeAuthenticatedRequest("/api/v1/buildercodes/config",{method:"GET"})}async listPayouts(e){if(e)ye(vA,e);let t=new URLSearchParams;if(e?.page!==void 0)t.append("page",e.page.toString());if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());let r=t.toString(),n=r?`/api/v1/buildercodes/payouts?${r}`:"/api/v1/buildercodes/payouts";return this.makeAuthenticatedRequest(n,{method:"GET"})}async getPayoutSummary(){return this.makeAuthenticatedRequest("/api/v1/buildercodes/payouts/summary",{method:"GET"})}async getRewardsBalance(){return this.makeAuthenticatedRequest("/api/v1/buildercodes/rewards/balance",{method:"GET"})}async claimBuildercodeRewards(e){let t=ye(TA,e);try{return await this.makeAuthenticatedRequest("/api/v1/buildercodes/rewards/claim",{method:"POST",body:JSON.stringify({token:t.token,amount:t.amount})})}catch(r){throw gle(r)}}}class LA extends qe{async upsertDelegatedAgent(e){return this.makeAuthenticatedRequest(ae.delegatedAgents.list(),{method:"POST",body:JSON.stringify({agentAddress:e.agentAddress,name:e.name,expiresAt:e.expiresAt,allowedActions:e.allowedActions,allowedTradingPairIds:e.allowedTradingPairIds,allowedMarginAccountIds:e.allowedMarginAccountIds,allowedOrderTypes:e.allowedOrderTypes,allowedTimeInForce:e.allowedTimeInForce,maxLeverage:e.maxLeverage,maxOrderNotional:e.maxOrderNotional,maxOpenOrders:e.maxOpenOrders})})}async listDelegatedAgents(){return this.makeAuthenticatedRequest(ae.delegatedAgents.list())}async listDelegatedOwners(){return this.makeAuthenticatedRequest(ae.delegatedAgents.owners())}async revokeDelegatedAgent(e){return this.makeAuthenticatedRequest(ae.delegatedAgents.byId(e),{method:"DELETE"})}async createDelegatedSession(e){return this.makeAuthenticatedRequest(ae.delegatedAgents.sessions(),{method:"POST",body:JSON.stringify({ownerUserId:e.ownerUserId,sessionPublicKey:e.sessionPublicKey})})}}class Gb extends qe{async mint(e){return await this.makeAuthenticatedRequest(ae.faucet.mint(),{method:"POST",body:JSON.stringify({turnstileToken:e.turnstileToken})})}async getInfo(){return await this.makeAuthenticatedRequest(ae.faucet.info(),{method:"GET"})}}class Vb extends qe{async simulateFees(e){let t=ye(EA,e),r=new URLSearchParams;if(r.append("tradingPairId",t.tradingPairId),r.append("side",t.side),r.append("price",t.price),r.append("quantity",t.quantity),t.orderType!==void 0)r.append("orderType",t.orderType);if(t.slippageToleranceBps!==void 0)r.append("slippageToleranceBps",String(t.slippageToleranceBps));let n=`/api/v1/fees/simulate?${r.toString()}`;return await this.makeAuthenticatedRequest(n,{method:"GET"})}async getMyFeeTier(e){let t=ye(PA,e),r=new URLSearchParams;r.append("tradingPairId",t.tradingPairId);let n=`/api/v1/fees/tier?${r.toString()}`;return await this.makeAuthenticatedRequest(n,{method:"GET"})}}class DA extends qe{async listAssignments(e={}){let t=new URLSearchParams;if(e.page!==void 0)t.set("page",String(e.page));if(e.pageSize!==void 0)t.set("pageSize",String(e.pageSize));return this.makeAuthenticatedRequest(`/api/v1/managed-markets/assignments${t.size?`?${t}`:""}`)}async claimLease(e,t){return this.makeAuthenticatedRequest(`/api/v1/managed-markets/${encodeURIComponent(e)}/lease`,{method:"POST",body:JSON.stringify(t)})}async refreshQuotes(e,t){return this.makeAuthenticatedRequest(`/api/v1/managed-markets/${encodeURIComponent(e)}/quotes`,{method:"POST",body:JSON.stringify(t)})}}class Zb extends qe{async listMarginAccounts(e){if(e)ye(aF,e);return await this.makeAuthenticatedRequest(ae.marginAccounts.list(e?{page:e.page,pageSize:e.pageSize,state:e.state,tradingPairId:e.tradingPairId}:void 0))}async getMarginAccountSummary(e,t){return ye(cF,{marginAccountId:e,...t}),await this.makeAuthenticatedRequest(ae.marginAccounts.summary(e,{tradingPairId:t?.tradingPairId}))}async getParentMarginAccountSummary(e){return ye(uF,e),await this.makeAuthenticatedRequest(ae.marginAccounts.parentSummary({tradingPairId:e?.tradingPairId}))}async getAvailableCollateral(e){return ye(dF,e),await this.makeAuthenticatedRequest(ae.marginAccounts.availableCollateral(e))}async transferCollateralToMarginAccount(e,t){return ye($A,{marginAccountId:e,request:t}),await this.makeAuthenticatedRequest(ae.marginAccounts.transferIn(e),{method:"POST",body:JSON.stringify({asset:t.asset,amount:t.amount,tradingPairId:t.tradingPairId,strategyKey:t.strategyKey})})}async transferCollateralToParentMarginAccount(e){return ye(pF,{request:e}),await this.makeAuthenticatedRequest(ae.marginAccounts.transferInParent(),{method:"POST",body:JSON.stringify({asset:e.asset,amount:e.amount})})}async transferCollateralToRiskBucket(e){return ye(fF,{request:e}),await this.makeAuthenticatedRequest(ae.marginAccounts.transferInRiskBucket(),{method:"POST",body:JSON.stringify({asset:e.asset,amount:e.amount,tradingPairId:e.tradingPairId,strategyKey:e.strategyKey,marginMode:e.marginMode,applyToPositionMargin:e.applyToPositionMargin})})}async transferCollateralFromMarginAccount(e,t){return ye($A,{marginAccountId:e,request:t}),await this.makeAuthenticatedRequest(ae.marginAccounts.transferOut(e),{method:"POST",body:JSON.stringify({asset:t.asset,amount:t.amount,tradingPairId:t.tradingPairId,strategyKey:t.strategyKey,marginMode:t.marginMode})})}async transferCollateralFromParentMarginAccount(e){return ye(mF,{request:e}),await this.makeAuthenticatedRequest(ae.marginAccounts.transferOutParent(),{method:"POST",body:JSON.stringify({asset:e.asset,amount:e.amount})})}async getMarginAccountMovements(e,t){return ye(hF,{marginAccountId:e,...t}),await this.makeAuthenticatedRequest(ae.marginAccounts.movements(e,t))}async getParentMarginAccountMovements(e){return ye(gF,e),await this.makeAuthenticatedRequest(ae.marginAccounts.parentMovements(e))}async simulateOrderRisk(e,t){return ye(bF,{marginAccountId:e,request:t}),await this.makeAuthenticatedRequest(ae.marginAccounts.simulateOrderRisk(e),{method:"POST",body:JSON.stringify({tradingPairId:t.tradingPairId,side:t.side,positionSide:t.positionSide,orderType:t.orderType,price:t.price,quantity:t.quantity,leverage:t.leverage,reduceOnly:t.reduceOnly,slippageToleranceBps:t.slippageToleranceBps})})}async simulateParentMarginOrderRisk(e){return ye(xF,{request:e}),await this.makeAuthenticatedRequest(ae.marginAccounts.simulateParentMarginOrderRisk(),{method:"POST",body:JSON.stringify({tradingPairId:e.tradingPairId,side:e.side,positionSide:e.positionSide,orderType:e.orderType,price:e.price,quantity:e.quantity,leverage:e.leverage,reduceOnly:e.reduceOnly,slippageToleranceBps:e.slippageToleranceBps})})}async simulateRiskBucketOrderRisk(e){return ye(_F,{request:e}),await this.makeAuthenticatedRequest(ae.marginAccounts.simulateRiskBucketOrderRisk(),{method:"POST",body:JSON.stringify({tradingPairId:e.tradingPairId,strategyKey:e.strategyKey,marginMode:e.marginMode,side:e.side,positionSide:e.positionSide,orderType:e.orderType,price:e.price,quantity:e.quantity,leverage:e.leverage,reduceOnly:e.reduceOnly,slippageToleranceBps:e.slippageToleranceBps})})}}class Wb extends qe{async getPaginatedTradingPairs(e){let t=new URLSearchParams;if(e?.page!==void 0)t.append("page",e.page.toString());if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.marketType)t.append("marketType",e.marketType);if(e?.baseToken)t.append("baseToken",e.baseToken);if(e?.quoteToken)t.append("quoteToken",e.quoteToken);if(e?.isActive!==void 0)t.append("isActive",e.isActive.toString());if(e?.category)t.append("category",e.category);let r=t.toString(),n=r?`/api/v1/market/pairs?${r}`:"/api/v1/market/pairs";return await this.makePublicRequest(n)}async getTradingPair(e){return ye(fi,{tradingPairId:e}),(await this.makePublicRequest(ae.market.getTradingPair(e))).tradingPair}async getTradingPairBySymbol(e,t){return(await this.getPaginatedTradingPairs({pageSize:100,marketType:t})).tradingPairs.find((n)=>n.symbol===e)}async getCandlesticks(e,t,r){ye(SF,{tradingPairId:e,interval:t,startTime:r?.startTime,endTime:r?.endTime,limit:r?.limit,priceType:r?.priceType});let n=new URLSearchParams;if(r?.startTime!==void 0)n.append("startTime",r.startTime.toString());if(r?.endTime!==void 0)n.append("endTime",r.endTime.toString());if(r?.limit!==void 0)n.append("limit",r.limit.toString());if(r?.priceType!==void 0)n.append("priceType",r.priceType);let o=n.toString(),i=o?`/api/v1/market/pairs/charts/candlestick/${encodeURIComponent(e)}/${t}?${o}`:`/api/v1/market/pairs/charts/candlestick/${encodeURIComponent(e)}/${t}`;return(await this.makePublicRequest(i)).data||[]}async getMarketMetadata(e){return ye(fi,{tradingPairId:e}),await this.makePublicRequest(ae.market.getMarketMetadata(e))}async getPerpMarketConfig(e){return ye(fi,{tradingPairId:e}),await this.makePublicRequest(ae.market.getPerpMarketConfig(e))}async getPerpMarketSummary(e){return ye(fi,{tradingPairId:e}),await this.makePublicRequest(ae.market.getPerpMarketSummary(e))}async getMarkPrice(e){return ye(fi,{tradingPairId:e}),await this.makePublicRequest(ae.market.getMarkPrice(e))}async getIndexPrice(e){return ye(fi,{tradingPairId:e}),await this.makePublicRequest(ae.market.getIndexPrice(e))}async getFundingState(e){return ye(fi,{tradingPairId:e}),await this.makePublicRequest(ae.market.getFundingState(e))}async listFundingHistory(e,t){return ye(fi,{tradingPairId:e}),await this.makePublicRequest(ae.market.listFundingHistory(e,t))}async listAllFundingHistory(e){return await this.makePublicRequest(ae.market.listAllFundingHistory(e))}async getOpenInterest(e){return ye(fi,{tradingPairId:e}),await this.makePublicRequest(ae.market.getOpenInterest(e))}async getScreener(e){return await this.makePublicRequest(ae.market.getScreener(e))}async getMarketStats(){return await this.makePublicRequest(ae.market.getMarketStats())}}class Kb extends qe{async getOrderbook(e,t={}){let{depth:r=10,tradingMode:n,magnitude:o,denomination:i}=t,s=new URLSearchParams;if(s.set("levels",String(r)),n)s.set("tradingMode",n);if(o!==void 0)s.set("magnitude",String(o));if(i)s.set("denomination",i.toLowerCase());let a=await this.makePublicRequest(`/api/v1/orderbook/${encodeURIComponent(e)}?${s.toString()}`);return{tradingPairId:a.tradingPairId,tradingMode:a.tradingMode,bids:a.data.bids.map((c)=>({price:c.price,quantity:c.quantity,orderCount:c.orderCount})),asks:a.data.asks.map((c)=>({price:c.price,quantity:c.quantity,orderCount:c.orderCount})),bestBid:a.data.bestBid,bestAsk:a.data.bestAsk,bidVolume:a.data.bidVolume,askVolume:a.data.askVolume,baseDecimals:a.baseDecimals,quoteDecimals:a.quoteDecimals,timestamp:a.timestamp,sequence:a.sequenceNumber}}}class Yb extends qe{async getMyTraderCode(){return await this.makeAuthenticatedRequest("/api/v1/pitpass/codes/me",{method:"GET"})}async setTraderCode(e){let t=ye(AA,{code:e});return await this.makeAuthenticatedRequest("/api/v1/pitpass/codes/me/custom",{method:"PUT",body:JSON.stringify({code:t.code})})}async clearTraderCode(){return await this.makeAuthenticatedRequest("/api/v1/pitpass/codes/me/custom",{method:"DELETE"})}async checkTraderCodeAvailability(e){let t=new URLSearchParams({code:e.trim()}).toString(),r=await this.makePublicRequest(`/api/v1/pitpass/codes/available?${t}`,{method:"GET"});return{available:r.available,reason:r.reason?r.reason:void 0}}async getTraderCodeInfo(e){let t=encodeURIComponent(e.trim());return await this.makePublicRequest(`/api/v1/pitpass/codes/${t}`,{method:"GET"})}async getRewardsBalance(){return await this.makeAuthenticatedRequest("/api/v1/pitpass/rewards/balance",{method:"GET"})}async transferRewards(e){let t=ye(IA,e);return await this.makeAuthenticatedRequest("/api/v1/pitpass/rewards/transfer",{method:"POST",body:JSON.stringify({token:t.token,amount:t.amount})})}async getMyReferralPosition(){return await this.makeAuthenticatedRequest("/api/v1/pitpass/referrals/me",{method:"GET"})}async getMyReferralDownline(){return await this.makeAuthenticatedRequest("/api/v1/pitpass/referrals/me/downline",{method:"GET"})}}var $m="/api/v1/accounts/me/portfolio";function Jb(e,t){if(!t?.period)return e;return`${e}?${new URLSearchParams({period:t.period})}`}class Qb extends qe{async getSummary(e){return await this.makeAuthenticatedRequest(Jb(`${$m}/summary`,e))}async getPerformance(e){return await this.makeAuthenticatedRequest(Jb(`${$m}/performance`,e))}async getRealizedPnl(e){return await this.makeAuthenticatedRequest(Jb(`${$m}/realized-pnl`,e))}async getAssets(e){return await this.makeAuthenticatedRequest(Jb(`${$m}/assets`,e))}async getMargin(){return await this.makeAuthenticatedRequest(`${$m}/margin`)}}class Xb extends qe{async listPositions(e){if(e)ye(EF,e);return await this.makeAuthenticatedRequest(ae.positions.list(e))}async getPosition(e){return ye(PF,{positionId:e}),await this.makeAuthenticatedRequest(ae.positions.get(e))}async closePosition(e,t){return ye(AF,{positionId:e,request:t}),await this.makeAuthenticatedRequest(ae.positions.close(e),{method:"POST",body:JSON.stringify({closeType:t.closeType,limitPrice:t.limitPrice,slippageToleranceBps:t.slippageToleranceBps,quantity:t.quantity})})}async batchCloseAllPositions(e){if(e)ye(IF,e);return await this.makeAuthenticatedRequest(ae.positions.batchCloseAll(),{method:"POST",body:JSON.stringify({tradingPairId:e?.tradingPairId,slippageToleranceBps:e?.slippageToleranceBps})})}async getPositionRisk(e){return ye(kF,{positionId:e}),await this.makeAuthenticatedRequest(ae.positions.risk(e))}async attachPositionTpSl(e,t){return ye(RF,{positionId:e,request:t}),await this.makeAuthenticatedRequest(ae.positions.attachTpSl(e),{method:"POST",body:JSON.stringify({takeProfit:t.takeProfit?{triggerPrice:t.takeProfit.triggerPrice,orderType:t.takeProfit.orderType,limitPrice:t.takeProfit.limitPrice,quantity:t.takeProfit.quantity,closePosition:t.takeProfit.closePosition,timeInForce:t.takeProfit.timeInForce,slippageToleranceBps:t.takeProfit.slippageToleranceBps,expiresAt:t.takeProfit.expiresAt}:void 0,stopLoss:t.stopLoss?{triggerPrice:t.stopLoss.triggerPrice,orderType:t.stopLoss.orderType,limitPrice:t.stopLoss.limitPrice,quantity:t.stopLoss.quantity,closePosition:t.stopLoss.closePosition,timeInForce:t.stopLoss.timeInForce,slippageToleranceBps:t.stopLoss.slippageToleranceBps,expiresAt:t.stopLoss.expiresAt}:void 0,oco:t.oco})})}async listPositionHistory(e){if(e)ye(OF,e);return await this.makeAuthenticatedRequest(ae.positions.history(e))}async getPositionPnlHistory(e,t){return ye(CF,{positionId:e,params:t}),await this.makeAuthenticatedRequest(ae.positions.pnlHistory(e,t))}}class UA extends qe{async getProfile(){return await this.makeAuthenticatedRequest("/api/v1/accounts/me")}async getPaginatedUserMovements(e){if(e)ye($F,e);let t=new URLSearchParams;if(e?.page!==void 0)t.append("page",e.page.toString());if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.entryType!==void 0)t.append("entryType",e.entryType);if(e?.transactionType!==void 0)t.append("transactionType",e.transactionType);if(e?.assetId!==void 0)t.append("assetId",e.assetId);let r=t.toString(),n=r?`/api/v1/accounts/movements?${r}`:"/api/v1/accounts/movements";return await this.makeAuthenticatedRequest(n)}async getUserBalances(e){let t=new URLSearchParams;if(e?.page!==void 0)t.append("page",e.page.toString());if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());let r=t.toString(),n=r?`/api/v1/accounts/balances?${r}`:"/api/v1/accounts/balances";return await this.makeAuthenticatedRequest(n)}async getUserBalanceByAssetId(e){if(!e||e.trim()==="")throw new Zt("assetId is required and cannot be empty",{endpoint:"/api/v1/accounts/balances/{assetId}"});let t=`/api/v1/accounts/balances/${e}`;return await this.makeAuthenticatedRequest(t)}async getPortfolioStats(e){let t=new URLSearchParams({period:e});return await this.makeAuthenticatedRequest(`/api/v1/accounts/me/portfolio?${t}`)}async getPortfolioChart(e,t){let r=new URLSearchParams({period:e,metric:t});return await this.makeAuthenticatedRequest(`/api/v1/accounts/me/portfolio/chart?${r}`)}async getUserTrades(e){if(e)ye(NF,e);let t=e?.page!==void 0&&e?.pageToken===void 0,r=new URLSearchParams;if(t&&e?.page!==void 0)r.append("page",e.page.toString());if(e?.pageSize!==void 0)r.append("pageSize",e.pageSize.toString());if(e?.tradingPairId!==void 0)r.append("tradingPairId",e.tradingPairId);if(!t)r.append("pageToken",e?.pageToken??"");let n=r.toString(),o=n?`/api/v1/accounts/trades?${n}`:"/api/v1/accounts/trades";return await this.makeAuthenticatedRequest(o)}async*iterateUserTrades(e){let t="";for(;;){let r=await this.getUserTrades({...e,pageToken:t});if(yield*r.trades,!r.nextPageToken)return;t=r.nextPageToken}}async listFundingPayments(e){if(e)ye(zF,e);let t=new URLSearchParams;if(e?.page!==void 0)t.append("page",e.page.toString());if(e?.pageSize!==void 0)t.append("pageSize",e.pageSize.toString());if(e?.tradingPairId!==void 0)t.append("tradingPairId",e.tradingPairId);if(e?.positionId!==void 0)t.append("positionId",e.positionId);if(e?.marginAccountId!==void 0)t.append("marginAccountId",e.marginAccountId);let r=t.toString(),n=r?`/api/v1/accounts/funding-payments?${r}`:"/api/v1/accounts/funding-payments";return await this.makeAuthenticatedRequest(n)}async getSelfTradePreventionDefault(){return await this.makeAuthenticatedRequest("/api/v1/accounts/self-trade-prevention")}async setSelfTradePreventionDefault(e){let t=ye(MF,{mode:e});return await this.makeAuthenticatedRequest("/api/v1/accounts/self-trade-prevention",{method:"PUT",body:JSON.stringify(t)})}}class ex extends qe{async getPulse(){return await this.makePublicRequest("/api/v1/pulse",{method:"GET"})}}class tx extends qe{async list(){return await this.makeAuthenticatedRequest(ae.subAccounts.list())}async createLimit(e){return await this.makeAuthenticatedRequest(ae.subAccounts.createLimit(),{method:"POST",body:JSON.stringify(e)})}async getLimits(e){return await this.makeAuthenticatedRequest(ae.subAccounts.getLimits(e))}async updateLimit(e,t,r){return await this.makeAuthenticatedRequest(ae.subAccounts.limit(e,t),{method:"PUT",body:JSON.stringify(r)})}async deleteLimit(e,t){await this.makeAuthenticatedRequest(ae.subAccounts.limit(e,t),{method:"DELETE"})}}function ble(e){if(e==="spot")return"SPOT";if(e==="margin")return"MARGIN";throw new At(`Invalid deposit target: ${JSON.stringify(e)}. Expected "spot" or "margin".`)}class rx extends qe{async register(e={}){let{depositTarget:t,...r}=e,n=t===void 0?r:{...r,depositTarget:ble(t)};return await this.makeAuthenticatedRequest(ae.sweeper.register(),{method:"POST",body:JSON.stringify(n)})}async getChains(){return await this.makePublicRequest(ae.sweeper.chains(),{method:"GET"})}}function UF(e){return{eventType:"trade",tradingPairId:e.tradingPairId,tradingMode:e.tradingMode.toUpperCase(),data:{tradeId:e.data.tradeId,price:e.data.price,quantity:e.data.quantity,makerSide:e.data.makerSide.toUpperCase(),executedAt:e.data.executedAt??""}}}class FA extends qe{async getTrades(e,t={}){let{page:r=1}=t,n=t.pageSize!=null&&t.pageSize>0?Math.min(t.pageSize,100):25,o=new URLSearchParams;if(r>1)o.set("page",String(r));return o.set("pageSize",String(n)),(await this.makePublicRequest(`/api/v1/trades/${encodeURIComponent(e)}?${o.toString()}`)).trades.map(UF)}async getTradeById(e){let t=await this.makePublicRequest(ae.trades.byId(e));return UF(t)}}function nx(e){if(!e)return;return{triggerPrice:e.triggerPrice,orderType:e.orderType,limitPrice:e.limitPrice,timeInForce:e.timeInForce,slippageToleranceBps:e.slippageToleranceBps,expiresAt:e.expiresAt,quantity:e.quantity,closePosition:e.closePosition}}class ox extends qe{async placeLimitOrder(e,t,r,n,o){ye(JU,{tradingPairId:e,side:t,quantity:r,price:n,options:o});let i={tradingPairId:e,orderType:"LIMIT",side:t,price:n,quantity:r,tradingMode:o?.tradingMode||"SPOT",useMasterBalance:o?.useMasterBalance,expirationDate:o?.expirationDate,timeInForce:o?.timeInForce,marginAccountId:o?.marginAccountId,marginMode:o?.marginMode,riskBucketId:o?.riskBucketId,riskBucketCollateral:o?.riskBucketCollateral,strategyKey:o?.strategyKey,positionSide:o?.positionSide,leverage:o?.leverage,reduceOnly:o?.reduceOnly,postOnly:o?.postOnly,selfTradePreventionMode:o?.selfTradePreventionMode,clientOrderId:o?.clientOrderId,idempotencyKey:o?.idempotencyKey===void 0?crypto.randomUUID():o.idempotencyKey,takeProfit:nx(o?.takeProfit),stopLoss:nx(o?.stopLoss)};return await this.makeAuthenticatedRequest(ae.orders.create(),{method:"POST",body:JSON.stringify(i)})}async placeMarketOrder(e,t,r,n){ye(QU,{tradingPairId:e,side:t,quantity:r,options:n});let o={tradingPairId:e,orderType:"MARKET",side:t,slippageToleranceBps:n?.slippageTolerance!==void 0?Math.round(n.slippageTolerance*1e4):void 0,price:null,quantity:r,tradingMode:n?.tradingMode||"SPOT",marginAccountId:n?.marginAccountId,marginMode:n?.marginMode,riskBucketId:n?.riskBucketId,riskBucketCollateral:n?.riskBucketCollateral,strategyKey:n?.strategyKey,positionSide:n?.positionSide,leverage:n?.leverage,reduceOnly:n?.reduceOnly,selfTradePreventionMode:n?.selfTradePreventionMode,takeProfit:nx(n?.takeProfit),stopLoss:nx(n?.stopLoss),clientOrderId:n?.clientOrderId,idempotencyKey:n?.idempotencyKey===void 0?crypto.randomUUID():n.idempotencyKey};return await this.makeAuthenticatedRequest(ae.orders.create(),{method:"POST",body:JSON.stringify(o)})}async cancelOrder(e,t){ye(XU,{orderId:e,remainingQuantityTarget:t?.remainingQuantityTarget});let r={orderId:e,...t?.remainingQuantityTarget!==void 0&&{remainingQuantityTarget:t.remainingQuantityTarget}};return await this.makeAuthenticatedRequest(ae.orders.cancel(),{method:"POST",body:JSON.stringify(r)})}async cancelConditionalOrder(e){return ye(CA,{conditionalOrderId:e}),await this.makeAuthenticatedRequest(ae.orders.cancelConditional(e),{method:"DELETE"})}async getConditionalOrder(e){return ye(CA,{conditionalOrderId:e}),await this.makeAuthenticatedRequest(ae.orders.getConditional(e),{method:"GET"})}async listConditionalOrders(e){if(e)ye(rF,e);let{page:t=1,pageSize:r=20,marginAccountId:n,tradingPairId:o,state:i}=e||{};return await this.makeAuthenticatedRequest(ae.orders.listConditional({page:t,pageSize:Math.min(Math.max(r,1),100),marginAccountId:n,tradingPairId:o,state:i}),{method:"GET"})}async batchCancel(e){if(!e||e.length===0)throw Error("orderIds is required and must not be empty");return this.makeAuthenticatedRequest(ae.orders.batchCancel(),{method:"POST",body:JSON.stringify({orderIds:e})})}async batchCancelAll(e){let t=e?ae.orders.batchCancelAllByPair(e):ae.orders.batchCancelAll();return this.makeAuthenticatedRequest(t,{method:"POST"})}async replaceOrder(e,t){ye(eF,{orderId:e,newOrder:t});let r={useMasterBalance:t.useMasterBalance??!1};if(t.price!==void 0)r.price=t.price;if(t.quantity!==void 0)r.quantity=t.quantity;if(t.postOnly!==void 0)r.postOnly=t.postOnly;if(t.selfTradePreventionMode!==void 0)r.selfTradePreventionMode=t.selfTradePreventionMode;if(t.clientOrderId!==void 0)r.clientOrderId=t.clientOrderId;return await this.makeAuthenticatedRequest(ae.orders.replace(e),{method:"PUT",body:JSON.stringify(r)})}async batchCreate(e){ye(iF,{orders:e});let t={orders:e.map((r)=>({tradingPairId:r.tradingPairId,orderType:r.orderType,side:r.side,price:r.price,quantity:r.quantity,tradingMode:r.tradingMode||"SPOT",slippageToleranceBps:r.slippageTolerance!==void 0?Math.round(r.slippageTolerance*1e4):void 0,useMasterBalance:r.useMasterBalance,expirationDate:r.expirationDate,timeInForce:r.timeInForce,marginAccountId:r.marginAccountId,marginMode:r.marginMode,riskBucketId:r.riskBucketId,riskBucketCollateral:r.riskBucketCollateral,strategyKey:r.strategyKey,positionSide:r.positionSide,leverage:r.leverage,reduceOnly:r.reduceOnly,postOnly:r.postOnly,selfTradePreventionMode:r.selfTradePreventionMode,clientOrderId:r.clientOrderId,idempotencyKey:r.idempotencyKey===void 0?crypto.randomUUID():r.idempotencyKey}))};return this.makeAuthenticatedRequest(ae.orders.batchCreate(),{method:"POST",body:JSON.stringify(t)})}async batchReplace(e){ye(sF,{orders:e});let t={orders:e.map((r)=>({orderId:r.orderId,price:r.price,quantity:r.quantity,useMasterBalance:r.useMasterBalance,postOnly:r.postOnly,selfTradePreventionMode:r.selfTradePreventionMode,clientOrderId:r.clientOrderId}))};return this.makeAuthenticatedRequest(ae.orders.batchReplace(),{method:"POST",body:JSON.stringify(t)})}async getPaginatedOrders(e){if(e)ye(tF,e);let{page:t,pageSize:r=10,status:n,tradingPairId:o,tradingMode:i,marginAccountId:s,pageToken:a}=e||{},c=r>0?r:10,d=t!==void 0&&a===void 0,l=Math.min(c,d?100:1000),p=new URLSearchParams;if(d){let b=t>0?t:1;p.append("page",b.toString())}p.append("pageSize",l.toString());let m=typeof n==="string"?n:n?.join(",");if(m)p.append("status",m);if(o)p.append("tradingPairId",o);if(i)p.append("tradingMode",i);if(s)p.append("marginAccountId",s);if(!d)p.append("pageToken",a??"");let h=`/api/v1/orders?${p.toString()}`;return await this.makeAuthenticatedRequest(h,{method:"GET"})}async*iterateOrders(e){let t="";for(;;){let r=await this.getPaginatedOrders({...e,pageToken:t});if(yield*r.orders,!r.nextPageToken)return;t=r.nextPageToken}}async getOrder(e){return{order:await this.makeAuthenticatedRequest(ae.orders.get(e),{method:"GET"}),status:"SUCCESS"}}async createTwapOrder(e,t,r,n){ye(nF,{tradingPairId:e,side:t,quantity:r,options:n});let o={tradingPairId:e,side:t,quantity:r,durationSeconds:n.durationSeconds!==void 0?Number(n.durationSeconds):void 0,startTime:n.startTime,endTime:n.endTime,limitPrice:n.limitPrice,slippageToleranceBps:n.slippageToleranceBps,randomize:n.randomize,reduceOnly:n.reduceOnly,tradingMode:n.tradingMode||"SPOT",marginAccountId:n.marginAccountId,riskBucketId:n.riskBucketId,marginMode:n.marginMode,leverage:n.leverage,strategyKey:n.strategyKey,useMasterBalance:n.useMasterBalance,clientTwapId:n.clientTwapId,executionStyle:n.executionStyle,triggerPrice:n.triggerPrice,triggerDirection:n.triggerDirection,conditionalExpiry:n.conditionalExpiry};return await this.makeAuthenticatedRequest(ae.orders.createTwap(),{method:"POST",body:JSON.stringify(o)})}async cancelTwapOrder(e){return ye(Fb,{twapOrderId:e}),await this.makeAuthenticatedRequest(ae.orders.cancelTwap(e),{method:"POST"})}async getTwapOrder(e){return ye(Fb,{twapOrderId:e}),await this.makeAuthenticatedRequest(ae.orders.getTwap(e),{method:"GET"})}async getTwapOrderTca(e){return ye(Fb,{twapOrderId:e}),await this.makeAuthenticatedRequest(ae.orders.getTwapTca(e),{method:"GET"})}async listTwapOrders(e){if(e)ye(oF,e);let{page:t=1,pageSize:r=20,state:n,tradingPairId:o}=e||{};return await this.makeAuthenticatedRequest(ae.orders.listTwap({page:t,pageSize:Math.min(Math.max(r,1),100),state:n,tradingPairId:o}),{method:"GET"})}}var jA=[{inputs:[{internalType:"address",name:"factory_",type:"address"},{internalType:"address",name:"unwrapHelper_",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"BridgeFeeTooHigh",type:"error"},{inputs:[],name:"ChainNotConfigured",type:"error"},{inputs:[],name:"ComposeNotSupported",type:"error"},{inputs:[],name:"ComposeSourceMismatch",type:"error"},{inputs:[],name:"InvalidAddress",type:"error"},{inputs:[],name:"NativeNotAccepted",type:"error"},{inputs:[],name:"NativeTransferFailed",type:"error"},{inputs:[],name:"NoRoute",type:"error"},{inputs:[],name:"NotExecutor",type:"error"},{inputs:[],name:"NotHub",type:"error"},{inputs:[],name:"NotRemote",type:"error"},{inputs:[],name:"NothingToSweep",type:"error"},{inputs:[],name:"OftCannotUnwrap",type:"error"},{inputs:[],name:"OnlyClone",type:"error"},{inputs:[],name:"QuoteNotBound",type:"error"},{inputs:[],name:"RoutedToken",type:"error"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"SafeERC20FailedOperation",type:"error"},{inputs:[],name:"StaleQuote",type:"error"},{inputs:[],name:"SweepParamsRequired",type:"error"},{inputs:[],name:"UnexpectedBridgeDebit",type:"error"},{inputs:[],name:"UnexpectedParams",type:"error"},{inputs:[],name:"UnexpectedValue",type:"error"},{inputs:[],name:"UnswapPathMissing",type:"error"},{inputs:[],name:"UntrustedComposeCaller",type:"error"},{inputs:[],name:"UntrustedComposeSource",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"uint256",name:"amountIn",type:"uint256"},{indexed:!1,internalType:"address",name:"bridgeToken",type:"address"},{indexed:!1,internalType:"uint256",name:"amountBridged",type:"uint256"},{indexed:!1,internalType:"address",name:"destination",type:"address"}],name:"Bridged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Refunded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"RefundedNative",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Swept",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"tokenIn",type:"address"},{indexed:!0,internalType:"address",name:"tokenOut",type:"address"},{indexed:!1,internalType:"uint256",name:"amountIn",type:"uint256"},{indexed:!1,internalType:"uint256",name:"amountOut",type:"uint256"}],name:"Unswapped",type:"event"},{inputs:[],name:"config",outputs:[{internalType:"address",name:"user",type:"address"},{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"hubToken",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"factory",outputs:[{internalType:"contract ISweeperFactory",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"bytes32",name:"",type:"bytes32"},{internalType:"bytes",name:"message",type:"bytes"},{internalType:"address",name:"",type:"address"},{internalType:"bytes",name:"",type:"bytes"}],name:"lzCompose",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"refund",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"refundNative",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"sweep",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"},{components:[{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"minSwapOut",type:"uint256"},{internalType:"uint256",name:"minBridgeOut",type:"uint256"},{internalType:"bytes",name:"lzExtraOptions",type:"bytes"}],internalType:"struct SweepParams",name:"params",type:"tuple"}],name:"sweep",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"},{internalType:"address",name:"feeRefundAddress",type:"address"}],name:"sweepWithRefund",outputs:[],stateMutability:"payable",type:"function"},{inputs:[],name:"unwrapHelper",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{stateMutability:"payable",type:"receive"}];var qA=[{inputs:[],stateMutability:"nonpayable",type:"constructor"},{inputs:[{internalType:"address",name:"target",type:"address"}],name:"AddressEmptyCode",type:"error"},{inputs:[],name:"CloneArgumentsTooLong",type:"error"},{inputs:[],name:"Create2EmptyBytecode",type:"error"},{inputs:[{internalType:"address",name:"implementation",type:"address"}],name:"ERC1967InvalidImplementation",type:"error"},{inputs:[],name:"ERC1967NonPayable",type:"error"},{inputs:[],name:"FailedCall",type:"error"},{inputs:[],name:"FailedDeployment",type:"error"},{inputs:[],name:"ImplementationNotSet",type:"error"},{inputs:[{internalType:"uint256",name:"balance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"InsufficientBalance",type:"error"},{inputs:[],name:"InvalidAddress",type:"error"},{inputs:[],name:"InvalidFeeCap",type:"error"},{inputs:[],name:"InvalidInitialization",type:"error"},{inputs:[],name:"NotExecutor",type:"error"},{inputs:[],name:"NotInitializing",type:"error"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"OwnableInvalidOwner",type:"error"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"OwnableUnauthorizedAccount",type:"error"},{inputs:[],name:"UUPSUnauthorizedCallContext",type:"error"},{inputs:[{internalType:"bytes32",name:"slot",type:"bytes32"}],name:"UUPSUnsupportedProxiableUUID",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousExecutor",type:"address"},{indexed:!0,internalType:"address",name:"newExecutor",type:"address"}],name:"ExecutorUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"rollup",type:"address"},{indexed:!1,internalType:"address",name:"bridgedStable",type:"address"},{indexed:!1,internalType:"address",name:"swapRouter",type:"address"},{indexed:!1,internalType:"address",name:"lzEndpoint",type:"address"}],name:"HubConfigured",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint64",name:"version",type:"uint64"}],name:"Initialized",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferStarted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint16",name:"previousCapBps",type:"uint16"},{indexed:!1,internalType:"uint16",name:"newCapBps",type:"uint16"}],name:"PermissionlessBridgeFeeCapUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"swapRouter",type:"address"},{indexed:!1,internalType:"uint32",name:"cctpDestinationDomain",type:"uint32"},{indexed:!1,internalType:"uint32",name:"stargateDestinationEid",type:"uint32"}],name:"RemoteConfigured",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"token",type:"address"},{components:[{internalType:"enum RouteKind",name:"kind",type:"uint8"},{internalType:"address",name:"bridge",type:"address"},{internalType:"bool",name:"unwrapNative",type:"bool"},{internalType:"bool",name:"compose",type:"bool"},{internalType:"uint32",name:"dstEid",type:"uint32"},{internalType:"address",name:"bridgeToken",type:"address"},{internalType:"address",name:"hubToken",type:"address"},{internalType:"bytes",name:"swapPath",type:"bytes"}],indexed:!1,internalType:"struct BridgeRoute",name:"route",type:"tuple"}],name:"RouteSet",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"sweeper",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!1,internalType:"string",name:"applicationId",type:"string"},{indexed:!1,internalType:"address",name:"hubToken",type:"address"}],name:"SweeperDeployed",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousImplementation",type:"address"},{indexed:!0,internalType:"address",name:"newImplementation",type:"address"}],name:"SweeperImplementationUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"stargate",type:"address"},{indexed:!1,internalType:"address",name:"token",type:"address"}],name:"TrustedStargateSet",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"hubToken",type:"address"},{indexed:!1,internalType:"bytes",name:"path",type:"bytes"}],name:"UnswapPathSet",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"implementation",type:"address"}],name:"Upgraded",type:"event"},{inputs:[],name:"UPGRADE_INTERFACE_VERSION",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"acceptOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"bridgedStable",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"cctpDestinationDomain",outputs:[{internalType:"uint32",name:"",type:"uint32"}],stateMutability:"view",type:"function"},{inputs:[],name:"chainMode",outputs:[{internalType:"enum ChainMode",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"rollup_",type:"address"},{internalType:"address",name:"bridgedStable_",type:"address"},{internalType:"address",name:"swapRouter_",type:"address"},{internalType:"address",name:"lzEndpoint_",type:"address"}],name:"configureHub",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"swapRouter_",type:"address"},{internalType:"uint32",name:"cctpDestinationDomain_",type:"uint32"},{internalType:"uint32",name:"stargateDestinationEid_",type:"uint32"}],name:"configureRemote",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"deploy",outputs:[{internalType:"address",name:"sweeper",type:"address"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"hubToken",type:"address"}],name:"deployReceiver",outputs:[{internalType:"address",name:"sweeper",type:"address"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"executor",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"forwarder",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner_",type:"address"}],name:"initialize",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"isDeployed",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"lzEndpoint",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"pendingOwner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"permissionlessBridgeFeeCapBps",outputs:[{internalType:"uint16",name:"",type:"uint16"}],stateMutability:"view",type:"function"},{inputs:[],name:"proxiableUUID",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"hubToken",type:"address"}],name:"receiverFor",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"refundNative",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"token",type:"address"}],name:"refundToken",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"rollup",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"}],name:"route",outputs:[{components:[{internalType:"enum RouteKind",name:"kind",type:"uint8"},{internalType:"address",name:"bridge",type:"address"},{internalType:"bool",name:"unwrapNative",type:"bool"},{internalType:"bool",name:"compose",type:"bool"},{internalType:"uint32",name:"dstEid",type:"uint32"},{internalType:"address",name:"bridgeToken",type:"address"},{internalType:"address",name:"hubToken",type:"address"},{internalType:"bytes",name:"swapPath",type:"bytes"}],internalType:"struct BridgeRoute",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"executor_",type:"address"}],name:"setExecutor",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint16",name:"capBps",type:"uint16"}],name:"setPermissionlessBridgeFeeCapBps",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"},{components:[{internalType:"enum RouteKind",name:"kind",type:"uint8"},{internalType:"address",name:"bridge",type:"address"},{internalType:"bool",name:"unwrapNative",type:"bool"},{internalType:"bool",name:"compose",type:"bool"},{internalType:"uint32",name:"dstEid",type:"uint32"},{internalType:"address",name:"bridgeToken",type:"address"},{internalType:"address",name:"hubToken",type:"address"},{internalType:"bytes",name:"swapPath",type:"bytes"}],internalType:"struct BridgeRoute",name:"route_",type:"tuple"}],name:"setRoute",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"implementation",type:"address"}],name:"setSweeperImplementation",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"stargate",type:"address"},{internalType:"address",name:"token",type:"address"}],name:"setTrustedStargate",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"hubToken",type:"address"},{internalType:"bytes",name:"path",type:"bytes"}],name:"setUnswapPath",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"stargateDestinationEid",outputs:[{internalType:"uint32",name:"",type:"uint32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"stargate",type:"address"}],name:"stargateToken",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"swapRouter",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"token",type:"address"}],name:"sweep",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"hubToken",type:"address"},{internalType:"address",name:"token",type:"address"},{components:[{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"minSwapOut",type:"uint256"},{internalType:"uint256",name:"minBridgeOut",type:"uint256"},{internalType:"bytes",name:"lzExtraOptions",type:"bytes"}],internalType:"struct SweepParams",name:"params",type:"tuple"}],name:"sweepWithParams",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"user",type:"address"}],name:"sweeperFor",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"sweeperImplementation",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"hubToken",type:"address"}],name:"unswapPath",outputs:[{internalType:"bytes",name:"",type:"bytes"}],stateMutability:"view",type:"function"},{inputs:[],name:"unwrapHelper",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"newImplementation",type:"address"},{internalType:"bytes",name:"data",type:"bytes"}],name:"upgradeToAndCall",outputs:[],stateMutability:"payable",type:"function"}];var HA=[{inputs:[],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"AccessControlBadConfirmation",type:"error"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"bytes32",name:"neededRole",type:"bytes32"}],name:"AccessControlUnauthorizedAccount",type:"error"},{inputs:[{internalType:"address",name:"target",type:"address"}],name:"AddressEmptyCode",type:"error"},{inputs:[],name:"ECDSAInvalidSignature",type:"error"},{inputs:[{internalType:"uint256",name:"length",type:"uint256"}],name:"ECDSAInvalidSignatureLength",type:"error"},{inputs:[{internalType:"bytes32",name:"s",type:"bytes32"}],name:"ECDSAInvalidSignatureS",type:"error"},{inputs:[{internalType:"address",name:"implementation",type:"address"}],name:"ERC1967InvalidImplementation",type:"error"},{inputs:[],name:"ERC1967NonPayable",type:"error"},{inputs:[],name:"EnforcedPause",type:"error"},{inputs:[],name:"ExpectedPause",type:"error"},{inputs:[],name:"FailedCall",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"balance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"ERC20InsufficientBalance",type:"error"},{inputs:[],name:"InsufficientBalance",type:"error"},{inputs:[],name:"InvalidAddress",type:"error"},{inputs:[],name:"InvalidInitialization",type:"error"},{inputs:[],name:"InvalidSeed",type:"error"},{inputs:[],name:"InvalidSignature",type:"error"},{inputs:[],name:"InvalidTimestamp",type:"error"},{inputs:[],name:"NonceAlreadyUsed",type:"error"},{inputs:[],name:"NotInitializing",type:"error"},{inputs:[],name:"ReentrancyGuardReentrantCall",type:"error"},{inputs:[],name:"TransferFailed",type:"error"},{inputs:[],name:"UUPSUnauthorizedCallContext",type:"error"},{inputs:[{internalType:"bytes32",name:"slot",type:"bytes32"}],name:"UUPSUnsupportedProxiableUUID",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Deposit",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"newFeeCollector",type:"address"}],name:"FeeCollectorChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint64",name:"version",type:"uint64"}],name:"Initialized",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Paused",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"role",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"previousAdminRole",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"newAdminRole",type:"bytes32"}],name:"RoleAdminChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"role",type:"bytes32"},{indexed:!0,internalType:"address",name:"account",type:"address"},{indexed:!0,internalType:"address",name:"sender",type:"address"}],name:"RoleGranted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"role",type:"bytes32"},{indexed:!0,internalType:"address",name:"account",type:"address"},{indexed:!0,internalType:"address",name:"sender",type:"address"}],name:"RoleRevoked",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"newSettlementContract",type:"address"}],name:"SettlementContractChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"maker",type:"address"},{indexed:!0,internalType:"address",name:"taker",type:"address"},{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"uint256",name:"fee",type:"uint256"}],name:"SettlementTransfer",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Unpaused",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"implementation",type:"address"}],name:"Upgraded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"token",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdrawal",type:"event"},{inputs:[],name:"DEBUGGER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"DEFAULT_ADMIN_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"FEE_MANAGER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"PAUSER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"SETTLEMENT_MANAGER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"UPGRADER_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"UPGRADE_INTERFACE_VERSION",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"},{internalType:"address",name:"token",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"seed",type:"bytes"}],name:"decodeSeed",outputs:[{internalType:"address",name:"",type:"address"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"destination",type:"address"},{internalType:"string",name:"applicationId",type:"string"},{internalType:"address",name:"token",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"}],name:"depositERC20",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"destination",type:"address"},{internalType:"string",name:"applicationId",type:"string"}],name:"depositNative",outputs:[],stateMutability:"payable",type:"function"},{inputs:[],name:"feeCollector",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getChainID",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"}],name:"getRoleAdmin",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"account",type:"address"}],name:"grantRole",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"account",type:"address"}],name:"hasRole",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"_admin",type:"address"}],name:"initialize",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"pause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"paused",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"proxiableUUID",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"callerConfirmation",type:"address"}],name:"renounceRole",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"account",type:"address"}],name:"revokeRole",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_newFeeCollector",type:"address"}],name:"setFeeCollector",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_settlementContract",type:"address"}],name:"setSettlementContract",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"settlementContract",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"maker",type:"address"},{internalType:"address",name:"taker",type:"address"},{internalType:"address",name:"token",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"fee",type:"uint256"}],name:"transferOnSettlement",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"unpause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newImplementation",type:"address"},{internalType:"bytes",name:"data",type:"bytes"}],name:"upgradeToAndCall",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address",name:"token",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes",name:"seed",type:"bytes"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"withdraw",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes",name:"seed",type:"bytes"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"withdrawNative",outputs:[],stateMutability:"nonpayable",type:"function"}];var k2t=new Uint8Array(32);function ix(e,t){return xle(t),t==="margin"?JSON.stringify({clientId:e,depositTarget:"MARGIN"}):e}function xle(e){if(e!=="spot"&&e!=="margin")throw Error(`Invalid deposit target: ${JSON.stringify(e)}. `+'Expected "spot" or "margin" — lowercase, not the wire form "SPOT"/"MARGIN".')}var GA={vault:HA,sweeper:jA,sweeperFactory:qA};var _le=5000,wle=300000,Sle=(e)=>new Promise((t)=>setTimeout(t,e));class sx extends qe{publicClient;chain;applicationsAPI;profileAPI;walletClient;constructor(e,t,r,n,o,i){super(i);this.publicClient=e,this.chain=r,this.walletClient=t,this.applicationsAPI=n,this.profileAPI=o}setWalletClient(e){this.walletClient=e}async getVaultAddress(){return(await this.applicationsAPI.getApplicationConfig()).vaultContractAddress}async getClientId(){return(await this.applicationsAPI.getApplicationConfig()).clientId}async resolveAsset(e){let t,r;try{let n=await this.profileAPI.getUserBalanceByAssetId(e);t=n.token,r=n.wrappedNative===!0}catch(n){if(n instanceof Zt){if(n.statusCode===404)throw new Vi(`Asset ID '${e}' does not exist`,{revertReason:"ASSET_NOT_FOUND",cause:n});throw new Vi(`Failed to resolve asset ID '${e}': ${n.retryable?"Network error occurred":"API request failed"}`,{revertReason:n.retryable?"NETWORK_ERROR":"API_ERROR",cause:n})}throw new Vi(`Failed to resolve asset ID '${e}': Unexpected error`,{revertReason:"UNKNOWN_ERROR",cause:n instanceof Error?n:void 0})}return{tokenAddress:t,isWrappedNative:r}}async approve(e,t,r=!0){if(!this.walletClient)throw new At("Wallet client not set. Connect a wallet first.","walletClient");ye(BF,{assetId:e,amount:t,autoWait:r});let n=await this.getVaultAddress(),{tokenAddress:o}=await this.resolveAsset(e),i=this.walletClient.account;if(!i)throw new At("No account available in wallet client","account");let s=i.getNonce?await i.getNonce():0n,a=await this.walletClient.writeContract({address:o,abi:Wt,functionName:"approve",args:[n,t],chain:this.chain,account:i}),c={nonce:s,hash:a,status:"pending"};return await this.waitForTransaction(c,r)}async deposit(e,t,r=!0,n="spot",o={}){if(!this.walletClient)throw new At("Wallet client not set. Connect a wallet first.","walletClient");ye(LF,{assetId:e,amount:t,autoWait:r,target:n,options:o});let i=await this.getVaultAddress(),s=await this.getClientId(),a=ix(s,n),{tokenAddress:c,isWrappedNative:d}=await this.resolveAsset(e),l=d&&o.asErc20!==!0;if(!l){if(await this.needsApproval(e,t,o))throw new Vi(`Approval required before deposit. Please invoke approve() first for asset ${e} (token address: ${c}).`,{revertReason:"APPROVAL_REQUIRED"})}let p=this.walletClient.account;if(!p)throw new At("No account available in wallet client","account");let m;if(l)m=await this.walletClient.writeContract({address:i,abi:GA.vault,functionName:"depositNative",args:[p.address,a],account:p,chain:this.chain,value:t});else m=await this.walletClient.writeContract({address:i,abi:GA.vault,functionName:"depositERC20",args:[p.address,a,c,t],account:p,chain:this.chain});let h=p.getNonce?await p.getNonce():0n,b={hash:m,status:"pending",nonce:h};return await this.waitForTransaction(b,r)}async pollWithdrawalCalldata(e,t){let r=t?.pollIntervalMs??_le,n=t?.timeoutMs??wle,o=Date.now()+n;for(;;){try{let{vaultAddress:i,calldata:s}=await this.makePublicRequest(`/api/v1/withdrawals/${e}`);if(s&&s!=="0x")return{vaultAddress:i,calldata:s}}catch(i){if(!(i instanceof Zt&&(i.statusCode===404||i.statusCode===409)))throw i}if(Date.now()+r>o)return null;await Sle(r)}}async withdraw(e,t,r=!0,n,o){if(!this.walletClient)throw new At("Wallet client not set. Connect a wallet first.","walletClient");let i=this.walletClient.account;if(!i)throw new At("No account available in wallet client","account");let s=i.address.toLowerCase(),a=typeof n==="string"?n:"spot",c=typeof n==="string"?o:n;ye(DF,{assetId:e,amount:t,destination:s,autoWait:r,source:a});let{withdrawalIndex:d}=await this.makeAuthenticatedRequest("/api/v1/withdrawals",{method:"POST",body:JSON.stringify({assetId:e,amount:t.toString(),destination:s,source:a})});if(!r)return{withdrawalIndex:d,status:"awaiting_proof"};let l=await this.pollWithdrawalCalldata(d,c);if(!l)return{withdrawalIndex:d,status:"awaiting_proof"};let{vaultAddress:p,calldata:m}=l,h;try{h=await this.walletClient.sendTransaction({to:p,data:m,account:i,chain:this.chain})}catch(w){throw new Vi(`Failed to submit executeWithdrawal for withdrawal ${d}: ${w instanceof Error?w.message:"unknown error"}`,{cause:w instanceof Error?w:void 0})}let b=i.getNonce?await i.getNonce():0n,x={hash:h,status:"pending",nonce:b};return{...await this.waitForTransaction(x,r),withdrawalIndex:d}}async retryWithdrawal(e,t=!0,r){if(!this.walletClient)throw new At("Wallet client not set. Connect a wallet first.","walletClient");let n=this.walletClient.account;if(!n)throw new At("No account available in wallet client","account");let o=await this.pollWithdrawalCalldata(e,r);if(!o)return{withdrawalIndex:e,status:"awaiting_proof"};let{vaultAddress:i,calldata:s}=o,a;try{a=await this.walletClient.sendTransaction({to:i,data:s,account:n,chain:this.chain})}catch(p){throw new Vi(`Failed to resubmit executeWithdrawal for withdrawal ${e}: ${p instanceof Error?p.message:"unknown error"}`,{cause:p instanceof Error?p:void 0})}let c=n.getNonce?await n.getNonce():0n,d={hash:a,status:"pending",nonce:c};return{...await this.waitForTransaction(d,t),withdrawalIndex:e}}async getBalance(e){throw new Zt("getBalance() is deprecated and no longer supported. Please use profileAPI.getUserBalances() or profileAPI.getUserBalanceByAssetId() instead for balance data.",{statusCode:410})}async getAllowance(e){if(!this.walletClient)throw new At("Wallet client not set. Connect a wallet first.","walletClient");let t=await this.getVaultAddress(),n=(await this.walletClient.getAddresses())[0];if(!n)throw new At("No account found in wallet client.","walletClient");let{tokenAddress:o}=await this.resolveAsset(e);return await this.publicClient.readContract({address:o,abi:Wt,functionName:"allowance",args:[n,t]})}async needsApproval(e,t,r={}){let{isWrappedNative:n}=await this.resolveAsset(e);if(n&&r.asErc20!==!0)return!1;return await this.getAllowance(e)<t}async waitForTransaction(e,t=!0,r={}){if(!t)return e;let{confirmations:n=1,timeout:o=60000}=r;try{let i=await this.publicClient.waitForTransactionReceipt({hash:e.hash,confirmations:n,timeout:o});return{...e,status:i.status==="success"?"confirmed":"failed",receipt:i}}catch{return{...e,status:"failed"}}}}class ax extends qe{async submit(e){return await this.makePublicRequest(ae.whitelist.submit(),{method:"POST",body:JSON.stringify(e)})}}class VA extends qe{async initiateWithdrawal(e){return this.makeAuthenticatedRequest(ae.withdrawals.initiate(),{method:"POST",body:JSON.stringify({assetId:e.assetId,amount:e.amount,destination:e.destination,source:e.source??"spot"})})}async getWithdrawal(e){return this.makePublicRequest(ae.withdrawals.byIndex(e))}async listPendingWithdrawals(e){return this.makeAuthenticatedRequest(ae.withdrawals.list({page:e?.page,pageSize:e?.pageSize}))}}class cx extends qe{chain;walletClient;constructor(e,t,r){super(r);this.chain=t,this.walletClient=e}setWalletClient(e){this.walletClient=e}async authenticate(e,t){if(!this.walletClient)throw new At("Wallet client not set. Connect a wallet first.","walletClient");let r=this.walletClient.account;if(!r)throw new At("No account available in wallet client","account");let n=B0(),o={publicKey:L0(n),privateKey:D0(n)},i=await this.createChallenge(r.address,e,o.publicKey),s=await this.signChallenge(i.message);return await this.verifySignature(r.address,s,i.nonce,e,o,t)}async signChallenge(e){if(!this.walletClient)throw new At("Wallet client not set. Connect a wallet first.","walletClient");let t=this.walletClient.account;if(!t)throw new At("No account available in wallet client","account");return await this.walletClient.signMessage({account:t,message:e})}async createChallenge(e,t,r){let n=await this.makePublicRequest("/api/v1/auth/challenge",{method:"POST",body:JSON.stringify({address:e,clientId:t,chainId:this.chain.id,sessionPublicKey:r})});return{nonce:n.nonce,message:n.message,expiresAt:n.expiresAt}}async verifySignature(e,t,r,n,o,i){let s=await this.makePublicRequest("/api/v1/auth/verify",{method:"POST",body:JSON.stringify({address:e,signature:t,nonce:r,clientId:n,chainId:this.chain.id,sessionPublicKey:o.publicKey,...i?{referralCode:i}:{}})});return{sessionPublicKey:o.publicKey,sessionPrivateKey:o.privateKey,expiresAt:s.expiresAt,user:{id:s.user.id,address:s.user.address,username:s.user.username},...s.isNewUser!==void 0?{isNewUser:s.isNewUser}:{},...s.referralApplied!==void 0?{referralApplied:s.referralApplied}:{}}}async refreshSession(){return{expiresAt:(await this.makeAuthenticatedRequest("/api/v1/auth/refresh",{method:"POST"})).expiresAt}}async revokeSession(){await this.makeAuthenticatedRequest("/api/v1/auth/revoke",{method:"POST"})}}var vle=750;function FF(e,t){try{new URL(e)}catch(r){throw new At(`${t} must be a valid URL, got: ${e}`,t)}return e}class WA{auth;delegatedAgents;applications;fees;buildercodes;pitpass;vault;withdrawals;trading;market;marginAccounts;positions;portfolio;subAccounts;faucet;sweeper;managedMarkets;whitelist;profile;pulse;orderbook;trades;ws;walletClient;publicClient;authState;network;chain;propagateSession(e){this.auth.setSessionKeypair(e),this.delegatedAgents.setSessionKeypair(e),this.applications.setSessionKeypair(e),this.fees.setSessionKeypair(e),this.buildercodes.setSessionKeypair(e),this.pitpass.setSessionKeypair(e),this.vault.setSessionKeypair(e),this.withdrawals.setSessionKeypair(e),this.trading.setSessionKeypair(e),this.market.setSessionKeypair(e),this.marginAccounts.setSessionKeypair(e),this.positions.setSessionKeypair(e),this.portfolio.setSessionKeypair(e),this.subAccounts.setSessionKeypair(e),this.faucet.setSessionKeypair(e),this.sweeper.setSessionKeypair(e),this.managedMarkets.setSessionKeypair(e),this.whitelist.setSessionKeypair(e),this.pulse.setSessionKeypair(e),this.profile.setSessionKeypair(e),this.orderbook.setSessionKeypair(e),this.trades.setSessionKeypair(e),this.ws.setSessionKeypair(e)}setServerKey(e){this.auth.setServerKey(e),this.delegatedAgents.setServerKey(e),this.applications.setServerKey(e),this.fees.setServerKey(e),this.buildercodes.setServerKey(e),this.pitpass.setServerKey(e),this.vault.setServerKey(e),this.withdrawals.setServerKey(e),this.trading.setServerKey(e),this.market.setServerKey(e),this.marginAccounts.setServerKey(e),this.positions.setServerKey(e),this.portfolio.setServerKey(e),this.subAccounts.setServerKey(e),this.faucet.setServerKey(e),this.sweeper.setServerKey(e),this.managedMarkets.setServerKey(e),this.whitelist.setServerKey(e),this.pulse.setServerKey(e),this.profile.setServerKey(e),this.orderbook.setServerKey(e),this.trades.setServerKey(e)}sessionFromAuthState(e){return{publicKey:e.sessionPublicKey,privateKey:e.sessionPrivateKey}}constructor(e){let t=["mainnet","development","staging","local"];if(!e.network||!t.includes(e.network))throw new At(`network must be one of: ${t.join(", ")}. Got: ${e.network}`,"network");if(this.network=e.network,!e.seiRpcUrl)throw new At("seiRpcUrl is required","seiRpcUrl");try{new URL(e.seiRpcUrl)}catch(a){throw new At(`seiRpcUrl must be a valid URL, got: ${e.seiRpcUrl}`,"seiRpcUrl")}let r=e.wsUrl?FF(e.wsUrl,"wsUrl"):lT(this.network),n=this.network==="mainnet"?Im:km;if(this.chain=n,e.pollingInterval!==void 0&&(!Number.isFinite(e.pollingInterval)||e.pollingInterval<=0))throw new At(`pollingInterval must be a positive number of milliseconds, got: ${e.pollingInterval}`,"pollingInterval");let o=Am(e.seiRpcUrl);this.publicClient=mA({chain:n,transport:o,pollingInterval:e.pollingInterval??vle});let i=e.apiUrl?FF(e.apiUrl,"apiUrl"):dT(this.network);if(e.walletClient){if(e.walletClient.chain?.id!==n.id)throw new At(`Wallet client chain mismatch. Expected ${n.id}, got ${e.walletClient.chain?.id}`,"walletClient");this.walletClient=e.walletClient}let s=(a)=>(a.setRequestSigning(e.requestSigning??"legacy"),a);this.applications=s(new Nb(i)),this.market=s(new Wb(i)),this.marginAccounts=s(new Zb(i)),this.positions=s(new Xb(i)),this.portfolio=s(new Qb(i)),this.subAccounts=s(new tx(i)),this.faucet=s(new Gb(i)),this.sweeper=s(new rx(i)),this.managedMarkets=s(new DA(i)),this.whitelist=s(new ax(i)),this.pulse=s(new ex(i)),this.auth=s(new cx(this.walletClient,this.chain,i)),this.delegatedAgents=s(new LA(i)),this.fees=s(new Vb(i)),this.buildercodes=s(new Hb(i)),this.pitpass=s(new Yb(i)),this.profile=s(new UA(i)),this.vault=s(new sx(this.publicClient,this.walletClient,this.chain,this.applications,this.profile,i)),this.withdrawals=s(new VA(i)),this.trading=s(new ox(i)),this.orderbook=s(new Kb(i)),this.trades=s(new FA(i)),this.ws=nT(r,e.ws),this.ws.connect().catch(console.error)}async login(e,t){if(this.authState=await this.auth.authenticate(e),this.propagateSession(this.sessionFromAuthState(this.authState)),t?.connectWebSocket)await this.ws.connect();return this.authState}async loginAsDelegatedOwner(e){if(!this.authState)throw new Zt("No active agent session to create delegated session",{endpoint:"delegated-agents/sessions",statusCode:ZA.StatusCodes.UNAUTHORIZED});let t=B0(),r={publicKey:L0(t),privateKey:D0(t)},n=await this.delegatedAgents.createDelegatedSession({ownerUserId:e,sessionPublicKey:r.publicKey});return this.authState={sessionPublicKey:r.publicKey,sessionPrivateKey:r.privateKey,expiresAt:n.expiresAt,user:{id:n.ownerUserId,address:n.agentAddress}},this.propagateSession(this.sessionFromAuthState(this.authState)),this.authState}getAuthState(){return this.authState}setAuthState(e){this.authState=e,this.propagateSession(this.sessionFromAuthState(e))}async logout(){if(this.authState)try{await this.auth.revokeSession()}catch(e){console.warn("Failed to revoke session on logout:",e)}this.authState=void 0,this.propagateSession(void 0),this.ws.disconnect()}async refreshAuth(){if(!this.authState)throw new Zt("No active session to refresh",{endpoint:"auth/refresh",statusCode:ZA.StatusCodes.UNAUTHORIZED});try{let e=await this.auth.refreshSession();return this.authState={...this.authState,expiresAt:e.expiresAt},this.authState}catch(e){throw this.authState=void 0,this.propagateSession(void 0),e}}isAuthenticated(){return!!this.authState}isConnected(){return!!this.walletClient&&!!this.publicClient}setWalletClient(e){if(e.chain?.id!==this.chain.id)throw new At(`Wallet client chain mismatch. Expected ${this.chain.id}, got ${e.chain?.id}`,"walletClient");this.walletClient=e,this.auth.setWalletClient(e),this.vault.setWalletClient(e)}getAccountAddress(){if(!this.walletClient)throw new Cf("Wallet client not set","walletClient");if(this.walletClient.account)return this.walletClient.account.address;throw new Cf("No account available","account")}getNetwork(){return this.network}getChainId(){return this.chain.id}async waitForTransaction(e,t,r){return this.publicClient.waitForTransactionReceipt({hash:e,confirmations:t,timeout:r})}}function KA(e){return new WA(e)}gm();Fe();ei();Mn();function jF(e){if(typeof e==="string"){if(!ht(e,{strict:!1}))throw new Ft({address:e});return{address:e,type:"json-rpc"}}if(!ht(e.address,{strict:!1}))throw new Ft({address:e.address});return{address:e.address,nonceManager:e.nonceManager,sign:e.sign,signAuthorization:e.signAuthorization,signMessage:e.signMessage,signTransaction:e.signTransaction,signTypedData:e.signTypedData,source:"custom",type:"local"}}gm();xr();Fe();var YA=!1;async function mi({hash:e,privateKey:t,to:r="object"}){let{r:n,s:o,recovery:i}=hs.sign(e.slice(2),t.slice(2),{lowS:!0,extraEntropy:Kt(YA,{strict:!1})?pr(YA):YA}),s={r:G(n,{size:32}),s:G(o,{size:32}),v:i?28n:27n,yParity:i};return(()=>{if(r==="bytes"||r==="hex")return bb({...s,to:r});return s})()}async function qF(e){let{chainId:t,nonce:r,privateKey:n,to:o="object"}=e,i=e.contractAddress??e.address,s=await mi({hash:Jy({address:i,chainId:t,nonce:r}),privateKey:n,to:o});if(o==="object")return{address:i,chainId:t,nonce:r,...s};return s}async function HF({message:e,privateKey:t}){return await mi({hash:gl(e),privateKey:t,to:"hex"})}Jn();on();Fe();function GF(e){if(!e||e.length===0)return[];let t=[];for(let r of e){let{chainId:n,nonce:o,...i}=r,s=r.address;t.push([n?Jt(n):"0x",s,o?Jt(o):"0x",...Rl({},i)])}return t}Fe();eP();ei();Ge();Qf();ls();Mn();mn();Ji();lr();function VF(e){let{authorizationList:t}=e;if(t)for(let r of t){let{chainId:n}=r,o=r.address;if(!ht(o))throw new Ft({address:o});if(n<0)throw new md({chainId:n})}ux(e)}function ZF(e){let{blobVersionedHashes:t}=e;if(t){if(t.length===0)throw new xm;for(let r of t){let n=et(r),o=Yt(gn(r,0,1));if(n!==32)throw new vP({hash:r,size:n});if(o!==eb)throw new TP({hash:r,version:o})}}ux(e)}function ux(e){let{chainId:t,maxPriorityFeePerGas:r,maxFeePerGas:n,to:o}=e;if(t<=0)throw new md({chainId:t});if(o&&!ht(o))throw new Ft({address:o});if(n&&n>Kd)throw new Oo({maxFeePerGas:n});if(r&&n&&r>n)throw new ds({maxFeePerGas:n,maxPriorityFeePerGas:r})}function WF(e){let{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:o,to:i}=e;if(t<=0)throw new md({chainId:t});if(i&&!ht(i))throw new Ft({address:i});if(r||o)throw new C("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>Kd)throw new Oo({maxFeePerGas:n})}function KF(e){let{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:o,to:i}=e;if(i&&!ht(i))throw new Ft({address:i});if(typeof t<"u"&&t<=0)throw new md({chainId:t});if(r||o)throw new C("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>Kd)throw new Oo({maxFeePerGas:n})}ei();on();Mn();function Nm(e){if(!e||e.length===0)return[];let t=[];for(let r=0;r<e.length;r++){let{address:n,storageKeys:o}=e[r];for(let i=0;i<o.length;i++)if(o[i].length-2!==64)throw new PE({storageKey:o[i]});if(!ht(n,{strict:!1}))throw new Ft({address:n});t.push([n,o])}return t}function YF(e,t){let r=rb(e);if(r==="eip1559")return Ple(e,t);if(r==="eip2930")return Ale(e,t);if(r==="eip4844")return Ele(e,t);if(r==="eip7702")return Tle(e,t);return Ile(e,t)}function Tle(e,t){let{authorizationList:r,chainId:n,gas:o,nonce:i,to:s,value:a,maxFeePerGas:c,maxPriorityFeePerGas:d,accessList:l,data:p}=e;VF(e);let m=Nm(l),h=GF(r);return Qt(["0x04",gs([G(n),i?G(i):"0x",d?G(d):"0x",c?G(c):"0x",o?G(o):"0x",s??"0x",a?G(a):"0x",p??"0x",m,h,...Rl(e,t)])])}function Ele(e,t){let{chainId:r,gas:n,nonce:o,to:i,value:s,maxFeePerBlobGas:a,maxFeePerGas:c,maxPriorityFeePerGas:d,accessList:l,data:p}=e;ZF(e);let{blobVersionedHashes:m,sidecars:h}=e;if(e.blobs&&(typeof m>"u"||typeof h>"u")){let v=typeof e.blobs[0]==="string"?e.blobs:e.blobs.map((k)=>mt(k)),T=e.kzg,P=el({blobs:v,kzg:T});if(typeof m>"u")m=Xy({commitments:P});if(typeof h>"u"){let k=tl({blobs:v,commitments:P,kzg:T});h=tb({blobs:v,commitments:P,proofs:k})}}let b=Nm(l),x=[G(r),o?G(o):"0x",d?G(d):"0x",c?G(c):"0x",n?G(n):"0x",i??"0x",s?G(s):"0x",p??"0x",b,a?G(a):"0x",m??[],...Rl(e,t)],_=[],w=[],A=[];if(h)for(let v=0;v<h.length;v++){let{blob:T,commitment:P,proof:k}=h[v];_.push(T),w.push(P),A.push(k)}return Qt(["0x03",h?gs([x,_,w,A]):gs(x)])}function Ple(e,t){let{chainId:r,gas:n,nonce:o,to:i,value:s,maxFeePerGas:a,maxPriorityFeePerGas:c,accessList:d,data:l}=e;ux(e);let p=Nm(d),m=[G(r),o?G(o):"0x",c?G(c):"0x",a?G(a):"0x",n?G(n):"0x",i??"0x",s?G(s):"0x",l??"0x",p,...Rl(e,t)];return Qt(["0x02",gs(m)])}function Ale(e,t){let{chainId:r,gas:n,data:o,nonce:i,to:s,value:a,accessList:c,gasPrice:d}=e;WF(e);let l=Nm(c),p=[G(r),i?G(i):"0x",d?G(d):"0x",n?G(n):"0x",s??"0x",a?G(a):"0x",o??"0x",l,...Rl(e,t)];return Qt(["0x01",gs(p)])}function Ile(e,t){let{chainId:r=0,gas:n,data:o,nonce:i,to:s,value:a,gasPrice:c}=e;KF(e);let d=[i?G(i):"0x",c?G(c):"0x",n?G(n):"0x",s??"0x",a?G(a):"0x",o??"0x"];if(t){let l=(()=>{if(t.v>=35n){if((t.v-35n)/2n>0)return t.v;return 27n+(t.v===35n?0n:1n)}if(r>0)return BigInt(r*2)+BigInt(35n+t.v-27n);let h=27n+(t.v===27n?0n:1n);if(t.v!==h)throw new TE({v:t.v});return h})(),p=$r(t.r),m=$r(t.s);d=[...d,G(l),p==="0x00"?"0x":p,m==="0x00"?"0x":m]}else if(r>0)d=[...d,G(r),"0x","0x"];return gs(d)}function Rl(e,t){let r=t??e,{v:n,yParity:o}=r;if(typeof r.r>"u")return[];if(typeof r.s>"u")return[];if(typeof n>"u"&&typeof o>"u")return[];let i=$r(r.r),s=$r(r.s);return[(()=>{if(typeof o==="number")return o?G(1):"0x";if(n===0n)return"0x";if(n===1n)return G(1);return n===27n?"0x":G(1)})(),i==="0x00"?"0x":i,s==="0x00"?"0x":s]}async function JF(e){let{privateKey:t,transaction:r,serializer:n=YF}=e,o=(()=>{if(r.type==="eip4844")return{...r,sidecars:!1};return r})(),i=await mi({hash:St(await n(o)),privateKey:t});return await n(r,i)}async function QF(e){let{privateKey:t,...r}=e;return await mi({hash:wb(r),privateKey:t,to:"hex"})}function JA(e,t={}){let{nonceManager:r}=t,n=Jt(hs.getPublicKey(e.slice(2),!1)),o=Yy(n);return{...jF({address:o,nonceManager:r,async sign({hash:s}){return mi({hash:s,privateKey:e,to:"hex"})},async signAuthorization(s){return qF({...s,privateKey:e})},async signMessage({message:s}){return HF({message:s,privateKey:e})},async signTransaction(s,{serializer:a}={}){return JF({privateKey:e,transaction:s,serializer:a})},async signTypedData(s){return QF({...s,privateKey:e})}}),publicKey:n,source:"privateKey"}}var QA=null;var kle={privateKeyToAccount:JA,createWalletClient:bA,http:Am,createMonacoSDK:KA,sei:Im,seiTestnet:km};function Rle(e,t=kle){let r=e.network==="mainnet"?t.sei:t.seiTestnet,n;if(e.privateKey){let o=t.privateKeyToAccount(e.privateKey);n=t.createWalletClient({account:o,chain:r,transport:t.http(e.seiRpcUrl)})}return t.createMonacoSDK({walletClient:n,network:e.network,seiRpcUrl:e.seiRpcUrl})}function Ze(e){if(!QA){let t=e??lc();QA=Rle(t)}return QA}var Ole=60,dx=null;function Cle(){return Math.floor(Date.now()/1000)}function XF(e){return e-Ole<=Cle()}function Mle(e){for(let t=e,r=0;t instanceof Error&&r<5;r++){if(t instanceof Zt&&t.statusCode===401)return!0;t=t.cause}return!1}function XA(e){if(!dx)dx=e().finally(()=>{dx=null});return dx}async function ej(e,t){if(await e.login(t.clientId),t.delegatedOwnerUserId){try{let r=await e.loginAsDelegatedOwner(t.delegatedOwnerUserId);console.error(`Adopted delegated owner ${r.user.id} (session expires at ${new Date(r.expiresAt*1000).toISOString()})`)}catch(r){throw await e.logout().catch(()=>{}),r}return}console.error(`Authenticated as ${e.getAccountAddress()}`)}async function tj(e,t){try{await e.refreshAuth()}catch{await ej(e,t)}}async function X(e){let t=Ze(e),r=e??lc(),n=t.getAuthState(),o=r.delegatedOwnerUserId!=null&&n?.user?.id!==r.delegatedOwnerUserId;if(!n||o)return await XA(()=>ej(t,r)),t;if(XF(n.expiresAt))await XA(()=>tj(t,r));return t}async function $le(e){let t=e??lc();if(!t.privateKey)return!1;let r=Ze(e);return await XA(()=>tj(r,t)),!0}function rj(e,t){async function r(...n){let o=Ze(t).getAuthState(),i=o!==void 0&&!XF(o.expiresAt);try{return await e(...n)}catch(s){if(!Mle(s))throw s;if(!(i&&Ze(t).getAuthState()!==o)){if(!await $le(t))throw s}return await e(...n)}}return r}function L(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function lx(e){return{content:[{type:"text",text:e}]}}function nj(e,t){if(t.network==="mainnet")return;e.registerTool("get_faucet_info",{description:"Get the authenticated wallet's faucet quota: remaining requests in the rolling 24h window, when the next request becomes available, and the 5 most recent faucet requests. Check this before request_faucet to avoid rate-limit errors. Only available on non-mainnet networks (development, staging, local).",inputSchema:{}},async()=>{let n=await(await X()).faucet.getInfo();return L(n)})}function oj(e,t){if(t.network==="mainnet")return;e.registerTool("request_faucet",{description:"Request test funds from the faucet for all active trading pairs. Requires a Cloudflare Turnstile token (the faucet rejects requests without one). Only available on non-mainnet networks (development, staging, local).",inputSchema:S({turnstileToken:y().describe("Cloudflare Turnstile token proving the request came from a real client (required by the faucet).")})},async({turnstileToken:r})=>{let o=await(await X()).faucet.mint({turnstileToken:r});return L(o)})}function ij(e,t){oj(e,t),nj(e,t)}function sj(e){e.registerTool("get_my_fee_tier",{description:"Get the authenticated user's current fee tier, rolling 14-day volumes (with spot/perp breakdown), the volume needed to reach the next tier, and the requested pair's six-row fee schedule.",inputSchema:S({tradingPairId:y().describe("Trading pair UUID whose fee schedule to return")})},async({tradingPairId:t})=>{let n=await(await X()).fees.getMyFeeTier({tradingPairId:t});return L(n)})}function aj(e){e.registerTool("simulate_fees",{description:"Simulate the fees for an order before placing it. Returns Monaco protocol fees, application fees, and total amounts.",inputSchema:S({tradingPairId:y().describe("Trading pair UUID"),side:H(["BUY","SELL"]).describe("Order side"),price:y().describe("Price per unit as a decimal string"),quantity:y().describe("Quantity to trade as a decimal string")})},async({tradingPairId:t,side:r,price:n,quantity:o})=>{let s=await(await X()).fees.simulateFees({tradingPairId:t,side:r,price:n,quantity:o});return L(s)})}function cj(e){aj(e),sj(e)}function uj(e){e.registerTool("get_available_collateral",{description:"Get available (unlocked) collateral for allocating to margin accounts or risk buckets.",inputSchema:S({asset:y().optional().describe("Optional collateral asset symbol or ID to scope the query")})},async({asset:t})=>{let n=await(await X()).marginAccounts.getAvailableCollateral({asset:t});return L(n)})}function dj(e){e.registerTool("get_margin_accounts",{description:"List your margin accounts with optional filters (state, trading pair).",inputSchema:S({page:M().optional().describe("Page number (1-based)"),pageSize:M().optional().describe("Items per page"),state:y().optional().describe("Filter by margin account state"),tradingPairId:y().optional().describe("Filter by trading pair UUID")})},async({page:t,pageSize:r,state:n,tradingPairId:o})=>{let s=await(await X()).marginAccounts.listMarginAccounts({page:t,pageSize:r,state:n,tradingPairId:o});return L(s)})}function lj(e){e.registerTool("get_parent_margin_account_movements",{description:"List collateral movements for your parent (cross) margin account.",inputSchema:S({movementType:y().optional().describe("Filter by movement type"),page:M().optional().describe("Page number (1-based)"),pageSize:M().optional().describe("Items per page")})},async({movementType:t,page:r,pageSize:n})=>{let i=await(await X()).marginAccounts.getParentMarginAccountMovements({movementType:t,page:r,pageSize:n});return L(i)})}function pj(e){e.registerTool("get_parent_margin_account_summary",{description:"Get your parent (cross) margin account summary.",inputSchema:S({tradingPairId:y().optional().describe("Optional trading pair UUID to scope the summary")})},async({tradingPairId:t})=>{let n=await(await X()).marginAccounts.getParentMarginAccountSummary({tradingPairId:t});return L(n)})}var Nle=S({applicationId:y().uuid(),enrolled:ue(),payoutAddress:y().nullable().optional(),buildercodesEnabled:ue(),buildercodesBudgetBps:M().int().min(0).max(1e4)}),zle=S({page:M().int().min(1).max(1e4).optional(),pageSize:M().int().min(1).max(100).optional()}),fj=S({tradeId:y().uuid(),payoutAddress:y(),token:y(),amount:y(),appliedBps:M().int(),createdAt:y()}),Ble=S({payouts:Ie(fj),total:M().int().nonnegative(),page:M().int().positive(),pageSize:M().int().positive(),totalPages:M().int().nonnegative()}),mj=S({token:y(),totalAmount:y(),payoutCount:M().int().nonnegative(),lastCreditedAt:y()}),Lle=S({totalPayouts:M().int().nonnegative(),lastCreditedAt:y().nullable().optional(),byToken:Ie(mj)}),hj=S({token:y(),available:y()}),Dle=S({balances:Ie(hj)}),Ule=S({token:y().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:y().trim().min(1,"amount is required").refine((e)=>/^\d+$/.test(e)&&BigInt(e)>0n,"amount must be a positive integer string")}),Fle=S({payoutBalance:y(),tradingBalance:y()});var jle=S({tradingPairId:y().trim().min(1,"Trading pair ID is required and cannot be empty"),side:H(["BUY","SELL"],{message:"Order side is required and must be either 'BUY' or 'SELL'"}),price:y().trim().min(1,"Price is required and cannot be empty").refine((e)=>!Number.isNaN(Number(e)),"Price must be a valid number").refine((e)=>Number(e)>0,"Price must be greater than 0"),quantity:y().trim().min(1,"Quantity is required and cannot be empty").refine((e)=>!Number.isNaN(Number(e)),"Quantity must be a valid number").refine((e)=>Number(e)>0,"Quantity must be greater than 0"),orderType:H(["LIMIT","MARKET"]).optional(),slippageToleranceBps:M().int().min(0,"Slippage tolerance must be between 0 and 1000 bps").max(1000,"Slippage tolerance must be between 0 and 1000 bps").optional()}).superRefine((e,t)=>{if(e.slippageToleranceBps!==void 0&&e.orderType!=="MARKET")t.addIssue({code:Hn.custom,message:"slippageToleranceBps is only valid when orderType is MARKET",path:["slippageToleranceBps"]})}),qle=S({applicationName:y().nullable().optional(),applicationTakerFee:y(),applicationTakerFeeBps:M(),buyOrderLockAmount:y().nullable().optional(),makerTotalReceipt:y(),monacoMakerRebate:y(),monacoMakerRebateBps:M(),monacoMakerRebateBpsExact:y(),monacoTakerFee:y(),monacoTakerFeeBps:M(),monacoTakerFeeBpsExact:y(),notional:y(),takerTotalPayment:y(),totalTakerFees:y(),maxQuantity:y().nullable(),maxQuantityRaw:y().nullable(),slippageToleranceBps:M().nullable()}),Hle=S({tradingPairId:y().trim().min(1,"Trading pair ID is required and cannot be empty")}),gj=S({tierLevel:M().int(),minVolumeThreshold:y(),makerFeeBps:y(),takerFeeBps:y()}),Gle=S({currentTierLevel:M().int(),weightedVolume14d:y(),spotVolume14d:y(),perpVolume14d:y(),volumeToNextTier:y().nullable().optional(),nextTierLevel:M().int().nullable().optional(),feeSchedule:Ie(gj)});var yj=S({token:y(),available:y()}),Vle=S({balances:Ie(yj)}),Zle=S({code:y(),createdAt:y(),customCode:y(),isCustom:ue(),display:y()}),bj=H(["taken","too_short","too_long","reserved","invalid_char","looks_like_address"]),Wle=S({available:ue(),reason:Lp((e)=>e===""||e===null?void 0:e,bj.optional())}),Kle=S({code:y().trim().min(1,"code is required").regex(/^[A-Za-z][A-Za-z0-9_]{4,19}$/,"code must start with a letter and be 5–20 chars of letters, digits, or underscores")}),Yle=S({code:y()}),Jle=S({token:y().trim().min(1,"token is required").regex(/^0x[0-9a-fA-F]{40}$/,"token must be a 0x-prefixed EVM address"),amount:y().trim().min(1,"amount is required").refine((e)=>/^\d+$/.test(e)&&BigInt(e)>0n,"amount must be a positive integer string")}),Qle=S({rewardsBalance:y(),tradingBalance:y()}),xj=S({source:y(),sourceDisplay:y(),level:M(),amount:y(),token:y(),rateApplied:y(),createdAt:y()}),Xle=S({referrer:y(),referrerDisplay:y(),totalEarned:y(),rewards:Ie(xj)}),_j=S({source:y(),sourceDisplay:y(),level:M(),totalEarned:y(),token:y()}),wj=S({wallet:y(),display:y(),referredAt:y(),totalEarned:y()}),Sj=S({totalEarned:y(),level1Earned:y(),level2Earned:y(),level3Earned:y()}),epe=S({earningsBySource:Ie(_j),directReferees:Ie(wj),summary:Sj});var Ol=["SUBMITTED","PARTIALLY_FILLED","FILLED","SETTLED_ON_CHAIN","SETTLED","CANCELLED","REJECTED","EXPIRED"];var Cl=H(["BUY","SELL"],{message:'Order side must be "BUY" or "SELL"'}),zm=H(["SPOT","MARGIN"],{message:'Trading mode must be "SPOT" or "MARGIN"'}),hx=H(["ISOLATED","CROSS"],{message:'Margin mode must be "ISOLATED" or "CROSS"'}),Bm=H(["LONG","SHORT","NONE"],{message:'Position side must be "LONG", "SHORT", or "NONE"'}),vj=H(["GTC","IOC","FOK"],{message:'Time in force must be "GTC", "IOC", or "FOK"'}),eI=H(["GTC","IOC"],{message:'Conditional order time in force must be "GTC" or "IOC"'}),Kc=H(["CANCEL_MAKER","CANCEL_TAKER","CANCEL_BOTH","SKIP"],{message:'Self-trade prevention mode must be "CANCEL_MAKER", "CANCEL_TAKER", "CANCEL_BOTH", or "SKIP"'}),Ml=H(["LIMIT","MARKET"],{message:'Order type must be "LIMIT" or "MARKET"'}),dt=y().trim().min(1,"Value cannot be empty").regex(/^\d+(\.\d+)?$/,"Value must be a positive decimal number (e.g., '1.5', '100')").refine((e)=>Number.parseFloat(e)>0,{message:"Value must be greater than 0"}),Oe=M5({message:"Must be a valid UUID (e.g., '123e4567-e89b-12d3-a456-426614174000')"}),Ra=Ou.datetime({message:"Must be a valid ISO 8601 date string (e.g., '2024-12-31T23:59:59Z')"}),Tj=M().min(0,"Slippage tolerance must be at least 0 (no slippage)").max(1,"Slippage tolerance cannot exceed 1 (100%)").optional(),Lm=M().int().min(0,"Slippage tolerance must be at least 0 bps").max(1e4,"Slippage tolerance cannot exceed 10000 bps"),$l=M().int().min(0,"Slippage tolerance must be at least 0 bps").max(1000,"Slippage tolerance cannot exceed 1000 bps"),tpe=M().int().min(0,"Slippage tolerance must be at least 0 bps").max(500,"TWAP slippage tolerance cannot exceed 500 bps (5%)"),px=S({triggerPrice:dt,orderType:Ml,limitPrice:dt.optional(),quantity:dt.optional(),closePosition:ue().optional(),timeInForce:eI.optional(),slippageToleranceBps:Lm.optional(),expiresAt:Ra.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.limitPrice!==void 0,{message:"limitPrice is required for LIMIT parent TP/SL",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.limitPrice===void 0,{message:"limitPrice must not be provided for MARKET parent TP/SL",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce is only allowed for LIMIT parent TP/SL",path:["timeInForce"]}).refine((e)=>e.orderType!=="LIMIT"||e.slippageToleranceBps===void 0,{message:"slippageToleranceBps is only allowed for MARKET parent TP/SL",path:["slippageToleranceBps"]}).refine((e)=>e.closePosition!==!0||e.quantity===void 0,{message:"quantity must be omitted when closePosition is true",path:["quantity"]}).refine((e)=>e.quantity!==void 0||e.closePosition!==!1,{message:"quantity is required when closePosition is false",path:["closePosition"]}),fx=(e)=>e?.takeProfit!==void 0||e?.stopLoss!==void 0,tI=(e,t)=>t===void 0||t!=="NONE"&&(e==="BUY"&&t==="LONG"||e==="SELL"&&t==="SHORT"),rI=y().min(1).max(64).regex(/^[A-Za-z0-9._:-]+$/,"idempotencyKey must contain only letters, digits, or . _ : -"),jMt=S({tradingPairId:Oe,side:Cl,quantity:dt,price:dt,options:S({idempotencyKey:rI.optional(),tradingMode:zm.optional(),useMasterBalance:ue().optional(),expirationDate:Ra.optional(),timeInForce:vj.optional(),marginAccountId:Oe.optional(),marginMode:hx.optional(),riskBucketId:Oe.optional(),riskBucketCollateral:dt.optional(),strategyKey:y().min(1).max(128).optional(),positionSide:Bm.optional(),leverage:dt.optional(),reduceOnly:ue().optional(),postOnly:ue().optional(),selfTradePreventionMode:Kc.optional(),takeProfit:px.optional(),stopLoss:px.optional()}).optional()}).refine((e)=>tI(e.side,e.options?.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["options","positionSide"]}).refine((e)=>e.options?.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["options","leverage"]}).refine((e)=>!fx(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss are only supported for MARGIN orders",path:["options"]}).refine((e)=>!fx(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}).refine((e)=>e.options?.postOnly!==!0||e.options?.timeInForce===void 0||e.options.timeInForce!=="IOC"&&e.options.timeInForce!=="FOK",{message:"postOnly cannot be combined with IOC/FOK time in force",path:["options","timeInForce"]}),qMt=S({tradingPairId:Oe,side:Cl,quantity:dt,options:S({idempotencyKey:rI.optional(),tradingMode:zm.optional(),slippageTolerance:Tj,marginAccountId:Oe.optional(),marginMode:hx.optional(),riskBucketId:Oe.optional(),riskBucketCollateral:dt.optional(),strategyKey:y().min(1).max(128).optional(),positionSide:Bm.optional(),leverage:dt.optional(),reduceOnly:ue().optional(),selfTradePreventionMode:Kc.optional(),takeProfit:px.optional(),stopLoss:px.optional()}).optional()}).refine((e)=>tI(e.side,e.options?.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["options","positionSide"]}).refine((e)=>e.options?.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["options","leverage"]}).refine((e)=>!fx(e.options)||e.options?.tradingMode==="MARGIN",{message:"takeProfit/stopLoss are only supported for MARGIN orders",path:["options"]}).refine((e)=>!fx(e.options)||e.options?.reduceOnly!==!0,{message:"takeProfit/stopLoss cannot be attached to reduce-only orders",path:["options"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode===void 0||e.options?.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["options","marginAccountId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["options","riskBucketCollateral"]}).refine((e)=>e.options?.marginMode!=="CROSS"||e.options?.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options?.riskBucketCollateral===void 0||e.options?.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["options","reduceOnly"]}),HMt=S({orderId:Oe,remainingQuantityTarget:dt.optional()}),GMt=S({orderId:Oe,newOrder:S({price:dt.optional(),quantity:dt.optional(),useMasterBalance:ue().optional(),postOnly:ue().optional(),selfTradePreventionMode:Kc.optional()})}),VMt=S({status:st([H(Ol),Ie(H(Ol)).min(1,"Status filter must list at least one status")]).optional(),tradingPairId:Oe.optional(),tradingMode:zm.optional(),marginAccountId:Oe.optional(),page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),pageToken:y().optional()}).superRefine((e,t)=>{if(e.page!==void 0&&e.pageToken===void 0&&e.pageSize!==void 0&&e.pageSize>100)t.addIssue({code:Hn.custom,message:"Page size cannot exceed 100 in page-number mode (page without pageToken)",path:["pageSize"]})}),ZMt=H(["STOP_LOSS","TAKE_PROFIT"],{message:'conditionType must be "STOP_LOSS" or "TAKE_PROFIT"'}),WMt=H(["MARK_PRICE"],{message:'triggerSource must be "MARK_PRICE"'}),rpe=H(["PENDING_PARENT","ACTIVE","TRIGGERING","TRIGGERED","CANCELLED","EXPIRED","FAILED"],{message:"Invalid conditional order state"}),KMt=H(["LONG","SHORT"],{message:'Position side must be "LONG" or "SHORT"'}),YMt=S({conditionalOrderId:Oe}),JMt=S({marginAccountId:Oe.optional(),tradingPairId:Oe.optional(),state:rpe.optional(),page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),npe=H(["PENDING","ACTIVE","COMPLETED","CANCELLED"],{message:"Invalid TWAP order state"}),ope=st([M().int("durationSeconds must be a whole number of seconds").positive("durationSeconds must be greater than 0"),y().regex(/^[1-9]\d*$/,"durationSeconds must be a positive integer string (e.g., '3600')")]),ipe=2592000000,QMt=S({tradingPairId:Oe,side:Cl,quantity:dt,options:S({durationSeconds:ope.optional(),startTime:Ra.optional(),endTime:Ra.optional(),limitPrice:dt.optional(),slippageToleranceBps:tpe.optional(),randomize:ue().optional(),executionStyle:H(["TAKER","PASSIVE"]).optional(),reduceOnly:ue().optional(),tradingMode:zm.optional(),marginAccountId:Oe.optional(),riskBucketId:Oe.optional(),marginMode:hx.optional(),leverage:dt.optional(),strategyKey:y().min(1).max(128).optional(),useMasterBalance:ue().optional(),clientTwapId:y().min(1).max(36,"clientTwapId cannot exceed 36 characters").optional(),triggerPrice:dt.optional(),triggerDirection:H(["ABOVE","BELOW"]).optional(),conditionalExpiry:Ra.optional()})}).refine((e)=>e.options.durationSeconds!==void 0!==(e.options.endTime!==void 0),{message:"Exactly one of durationSeconds or endTime must be set",path:["options","durationSeconds"]}).refine((e)=>e.options.startTime===void 0||e.options.endTime!==void 0,{message:"startTime is only valid together with endTime",path:["options","startTime"]}).refine((e)=>e.options.marginMode===void 0||e.options.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.riskBucketId===void 0||e.options.tradingMode==="MARGIN",{message:"riskBucketId is only supported for MARGIN orders",path:["options","tradingMode"]}).refine((e)=>e.options.marginMode!=="CROSS"||e.options.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["options","riskBucketId"]}).refine((e)=>e.options.marginMode!=="CROSS"||e.options.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["options","strategyKey"]}).refine((e)=>e.options.tradingMode!=="MARGIN"||e.options.reduceOnly===!0||e.options.leverage!==void 0,{message:"leverage is required for normal MARGIN TWAP orders",path:["options","leverage"]}).refine((e)=>e.options.triggerPrice!==void 0===(e.options.triggerDirection!==void 0),{message:"triggerPrice and triggerDirection are both-or-neither",path:["options","triggerDirection"]}).refine((e)=>e.options.triggerPrice===void 0||e.options.durationSeconds!==void 0,{message:"conditional TWAP (triggerPrice) requires durationSeconds — the window floats from the trigger instant",path:["options","durationSeconds"]}).refine((e)=>e.options.triggerPrice===void 0||e.options.startTime===void 0&&e.options.endTime===void 0,{message:"triggerPrice is incompatible with startTime/endTime",path:["options","triggerPrice"]}).refine((e)=>e.options.conditionalExpiry===void 0||e.options.triggerPrice!==void 0,{message:"conditionalExpiry is only valid together with triggerPrice",path:["options","conditionalExpiry"]}).refine((e)=>{let t=e.options.conditionalExpiry;if(t===void 0)return!0;let r=Date.parse(t);return Number.isNaN(r)||r>Date.now()},{message:"conditionalExpiry must be in the future",path:["options","conditionalExpiry"]}).refine((e)=>{let t=e.options.conditionalExpiry;if(t===void 0)return!0;let r=Date.parse(t);return Number.isNaN(r)||r-Date.now()<=ipe},{message:"conditionalExpiry cannot be more than 30 days after creation (the maximum window)",path:["options","conditionalExpiry"]}),XMt=S({twapOrderId:Oe}),e$t=S({state:npe.optional(),tradingPairId:Oe.optional(),page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),spe=S({tradingPairId:Oe,orderType:Ml,side:Cl,price:dt.optional(),quantity:dt,idempotencyKey:rI.optional(),tradingMode:zm.optional(),slippageTolerance:Tj,useMasterBalance:ue().optional(),expirationDate:Ra.optional(),timeInForce:vj.optional(),marginAccountId:Oe.optional(),marginMode:hx.optional(),riskBucketId:Oe.optional(),riskBucketCollateral:dt.optional(),strategyKey:y().min(1).max(128).optional(),positionSide:Bm.optional(),leverage:dt.optional(),reduceOnly:ue().optional(),postOnly:ue().optional(),selfTradePreventionMode:Kc.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.price!==void 0,{message:"Price is required for LIMIT orders",path:["price"]}).refine((e)=>e.orderType!=="MARKET"||e.price===void 0,{message:"Price must not be provided for MARKET orders",path:["price"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce must not be provided for MARKET orders",path:["timeInForce"]}).refine((e)=>e.orderType!=="MARKET"||e.postOnly!==!0,{message:"postOnly must not be provided for MARKET orders",path:["postOnly"]}).refine((e)=>e.postOnly!==!0||e.timeInForce===void 0||e.timeInForce!=="IOC"&&e.timeInForce!=="FOK",{message:"postOnly cannot be combined with IOC/FOK time in force",path:["postOnly"]}).refine((e)=>e.riskBucketCollateral===void 0||e.tradingMode==="MARGIN",{message:"riskBucketCollateral is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode===void 0||e.tradingMode==="MARGIN",{message:"marginMode is only supported for MARGIN orders",path:["tradingMode"]}).refine((e)=>e.marginMode!=="CROSS"||e.marginAccountId!==void 0,{message:"marginAccountId is required for CROSS margin orders",path:["marginAccountId"]}).refine((e)=>e.marginMode!=="CROSS"||e.riskBucketId===void 0,{message:"marginMode CROSS cannot be combined with riskBucketId",path:["riskBucketId"]}).refine((e)=>e.marginMode!=="CROSS"||e.riskBucketCollateral===void 0,{message:"marginMode CROSS cannot be combined with riskBucketCollateral",path:["riskBucketCollateral"]}).refine((e)=>e.marginMode!=="CROSS"||e.strategyKey===void 0,{message:"marginMode CROSS cannot be combined with strategyKey",path:["strategyKey"]}).refine((e)=>e.riskBucketCollateral===void 0||e.riskBucketId===void 0,{message:"riskBucketCollateral creates a new risk bucket and cannot be combined with riskBucketId",path:["riskBucketId"]}).refine((e)=>e.riskBucketCollateral===void 0||e.reduceOnly!==!0,{message:"reduceOnly orders cannot create a new risk bucket",path:["reduceOnly"]}).refine((e)=>tI(e.side,e.positionSide),{message:"positionSide is deprecated; when supplied BUY requires LONG and SELL requires SHORT",path:["positionSide"]}).refine((e)=>e.tradingMode!=="MARGIN"||e.reduceOnly===!0||e.leverage!==void 0,{message:"leverage is required for normal MARGIN orders",path:["leverage"]}),mx=100,t$t=S({orders:Ie(spe).min(1,"At least one order is required").max(mx,`At most ${mx} orders per batch request`)}),ape=S({orderId:Oe,price:dt.optional(),quantity:dt.optional(),useMasterBalance:ue().optional(),postOnly:ue().optional(),selfTradePreventionMode:Kc.optional()}).refine((e)=>e.price!==void 0||e.quantity!==void 0,{message:"At least one of price or quantity must be provided"}),r$t=S({orders:Ie(ape).min(1,"At least one order is required").max(mx,`At most ${mx} orders per batch request`)});var nI=S({page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),s$t=nI.extend({state:y().trim().min(1,"State cannot be empty").optional(),tradingPairId:Oe.optional()}),a$t=S({marginAccountId:Oe,tradingPairId:Oe.optional()}),c$t=S({tradingPairId:Oe.optional()}).optional(),u$t=S({asset:y().trim().min(1,"Asset cannot be empty").optional()}).optional(),cpe=S({asset:y().trim().min(1,"Asset cannot be empty"),amount:dt,tradingPairId:Oe.optional(),strategyKey:y().trim().min(1,"Strategy key cannot be empty").optional(),marginMode:H(["ISOLATED","CROSS"]).optional()}).refine((e)=>!(e.marginMode==="CROSS"&&e.tradingPairId!==void 0),{message:"tradingPairId is not supported for CROSS risk buckets",path:["tradingPairId"]}),gx=S({asset:y().trim().min(1,"Asset cannot be empty"),amount:dt}),upe=S({tradingPairId:Oe,strategyKey:y().trim().min(1,"Strategy key cannot be empty").optional()}),Ej=upe.extend({marginMode:_e("ISOLATED").optional(),selectedTradingPairIds:kn().optional(),applyToPositionMargin:ue().optional()}),dpe=S({marginMode:_e("CROSS"),selectedTradingPairIds:kn().optional(),strategyKey:kn().optional()}),lpe=S({marginMode:_e("CROSS"),selectedTradingPairIds:kn().optional(),strategyKey:kn().optional(),tradingPairId:kn().optional()}),d$t=S({marginAccountId:Oe,request:cpe}),l$t=S({request:gx}),ppe=S({marginMode:H(["ISOLATED","CROSS"]).optional(),selectedTradingPairIds:Et().optional()}).loose().superRefine((e,t)=>{if(e.selectedTradingPairIds===void 0)return;t.addIssue({code:"custom",path:["selectedTradingPairIds"],message:e.marginMode==="CROSS"?"selectedTradingPairIds is not accepted on a CROSS transfer: cross scope is derived from trading, so a funding call has nothing to declare":"selectedTradingPairIds is not supported for ISOLATED risk buckets"})}),p$t=S({request:ppe.pipe(st([gx.merge(Ej).strict(),gx.merge(lpe).strict()]))}),f$t=S({request:gx}),m$t=nI.extend({marginAccountId:Oe,movementType:y().trim().min(1,"Movement type cannot be empty").optional()}),h$t=nI.extend({movementType:y().trim().min(1,"Movement type cannot be empty").optional()}).optional(),oI=S({tradingPairId:Oe,side:Cl,positionSide:Bm.optional(),orderType:Ml,price:dt.optional(),quantity:dt,leverage:dt.optional(),reduceOnly:ue().optional(),slippageToleranceBps:$l.optional()}),iI=(e,t)=>{if(e.orderType!=="MARKET"&&e.slippageToleranceBps!==void 0)t.addIssue({code:Hn.custom,message:"slippageToleranceBps is only supported for MARKET orders",path:["slippageToleranceBps"]});if(e.positionSide!==void 0){let r=e.side==="BUY"?"LONG":"SHORT";if(e.positionSide!==r)t.addIssue({code:Hn.custom,message:"positionSide must match side when provided (BUY=LONG, SELL=SHORT)",path:["positionSide"]})}if(e.reduceOnly!==!0&&e.leverage===void 0)t.addIssue({code:Hn.custom,message:"leverage is required for normal margin orders",path:["leverage"]})},Pj=oI.strict().superRefine(iI),fpe=oI.merge(Ej).strict().superRefine(iI),mpe=oI.merge(dpe).strict().superRefine(iI),hpe=S({marginMode:H(["ISOLATED","CROSS"]).optional(),selectedTradingPairIds:Et().optional()}).loose().superRefine((e,t)=>{if(e.selectedTradingPairIds===void 0)return;t.addIssue({code:"custom",path:["selectedTradingPairIds"],message:e.marginMode==="CROSS"?"selectedTradingPairIds is not accepted on a CROSS preview: cross scope is derived from trading, so a preview has nothing to declare":"selectedTradingPairIds is not supported for ISOLATED risk buckets"})}),gpe=hpe.pipe(st([fpe,mpe])),g$t=S({marginAccountId:Oe,request:Pj}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),y$t=S({request:Pj}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]}),b$t=S({request:gpe}).refine((e)=>e.request.orderType!=="LIMIT"||e.request.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["request","price"]});var Aj=H(["1m","5m","15m","30m","1h","4h","1d","1w","1M"],{message:'Interval must be one of: "1m", "5m", "15m", "30m", "1h", "4h", "1d", "1w", "1M"'}),ype=31536000000,bpe=946684800000,yx=M().int().positive({message:"Timestamp must be a positive integer (milliseconds since epoch)"}).min(bpe,{message:"Timestamp must be at least Jan 1, 2000 (946684800000 ms). Did you pass seconds instead of milliseconds?"}).max(Number.MAX_SAFE_INTEGER,{message:"Timestamp must not exceed JavaScript's maximum safe integer"}).refine((e)=>e<=Date.now()+ype,{message:"Timestamp must not be unreasonably far in the future (max 1 year ahead)"}),S$t=S({tradingPairId:Oe,interval:Aj,startTime:yx,endTime:yx}).refine((e)=>e.startTime<e.endTime,{message:"startTime must be less than endTime",path:["endTime"]}),v$t=y().min(1,"Trading pair symbol cannot be empty").regex(/^[A-Za-z0-9]{1,10}\/[A-Za-z0-9]{1,10}$/,{message:'Trading pair symbol must be in format "BASE/QUOTE" (e.g., "BTC/USDT", "ETH/USD")'}),xpe=M().int().positive({message:"Limit must be a positive integer"}).max(500,{message:"Limit cannot exceed 500 bars per request"}).optional(),T$t=S({tradingPairId:Oe,interval:Aj,startTime:yx.optional(),endTime:yx.optional(),limit:xpe,priceType:H(["trade","mark"]).optional()}).refine((e)=>{if(e.startTime!==void 0&&e.endTime!==void 0)return e.startTime<e.endTime;return!0},{message:"startTime must be less than endTime",path:["endTime"]});var E$t=S({tradingPairId:Oe}),P$t=S({query:y().min(1,"Search query cannot be empty").optional(),pageSize:M().int().min(1).max(100).optional(),page:M().int().min(1).optional()}),A$t=S({tradingPairId:Oe});var kj=S({page:M().int().min(1,"Page must be at least 1").optional(),pageSize:M().int().min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional()}),_pe=H(["OPEN","CLOSED","LIQUIDATING","LIQUIDATED"],{message:'Position status must be "OPEN", "CLOSED", "LIQUIDATING", or "LIQUIDATED"'}),wpe=H(["MARKET","LIMIT","IOC"],{message:'Close type must be "MARKET", "LIMIT", or "IOC"'}),sI=S({positionId:Oe}),O$t=kj.extend({marginAccountId:Oe.optional(),tradingPairId:Oe.optional(),status:_pe.optional()});var C$t=sI.extend({request:S({closeType:wpe,limitPrice:dt.optional(),slippageToleranceBps:Lm.optional(),quantity:dt.optional()})}).refine((e)=>e.request.closeType==="MARKET"||e.request.limitPrice!==void 0,{message:"limitPrice is required for LIMIT and IOC close requests",path:["request","limitPrice"]}).refine((e)=>e.request.closeType!=="MARKET"||e.request.limitPrice===void 0,{message:"limitPrice is not allowed for MARKET close requests",path:["request","limitPrice"]}),M$t=S({tradingPairId:Oe.optional(),slippageToleranceBps:Lm.optional()});var Ij=S({triggerPrice:dt,orderType:Ml,limitPrice:dt.optional(),quantity:dt.optional(),closePosition:ue().optional(),timeInForce:eI.optional(),slippageToleranceBps:Lm.optional(),expiresAt:Ra.optional()}).refine((e)=>e.orderType!=="LIMIT"||e.limitPrice!==void 0,{message:"limitPrice is required for LIMIT TP/SL legs",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.limitPrice===void 0,{message:"limitPrice must not be provided for MARKET TP/SL legs",path:["limitPrice"]}).refine((e)=>e.orderType!=="MARKET"||e.timeInForce===void 0,{message:"timeInForce is only allowed for LIMIT TP/SL legs",path:["timeInForce"]}).refine((e)=>e.orderType!=="LIMIT"||e.slippageToleranceBps===void 0,{message:"slippageToleranceBps is only allowed for MARKET TP/SL legs",path:["slippageToleranceBps"]}).refine((e)=>e.closePosition!==!0||e.quantity===void 0,{message:"quantity must be omitted when closePosition is true",path:["quantity"]}).refine((e)=>e.quantity!==void 0||e.closePosition!==!1,{message:"quantity is required when closePosition is false",path:["closePosition"]}),$$t=sI.extend({request:S({takeProfit:Ij.optional(),stopLoss:Ij.optional(),oco:ue().optional()}).refine((e)=>e.takeProfit!==void 0||e.stopLoss!==void 0,{message:"At least one of takeProfit or stopLoss is required"}).refine((e)=>e.oco!==!0||e.takeProfit!==void 0&&e.stopLoss!==void 0,{message:"oco=true requires both takeProfit and stopLoss",path:["oco"]})}),N$t=kj.extend({positionId:Oe.optional(),marginAccountId:Oe.optional(),tradingPairId:Oe.optional(),reductionOnly:ue().optional()}),Spe=H(["1m","5m","15m","1h","4h","1d"],{message:'Interval must be one of "1m", "5m", "15m", "1h", "4h", "1d"'}),z$t=sI.extend({params:S({interval:Spe,startTime:M().int().min(0,"startTime must be a non-negative millisecond timestamp").optional(),endTime:M().int().min(0,"endTime must be a non-negative millisecond timestamp").optional()}).refine((e)=>e.startTime===void 0||e.endTime===void 0||e.startTime<e.endTime,{message:"startTime must be less than endTime",path:["startTime"]})});var vpe=H(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"],{message:'Entry type must be "CREDIT", "DEBIT", "LOCK", "UNLOCK", or "FEE"'}),Tpe=H(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"],{message:'Transaction type must be "DEPOSIT", "WITHDRAWAL", "TRADE", "FEE", "FUNDING", "LIQUIDATION", "INTEREST", or "REWARD"'}),U$t=S({mode:Kc}),F$t=S({page:M().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:M().int("Page size must be an integer").min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional(),entryType:vpe.optional(),transactionType:Tpe.optional(),assetId:Oe.optional()}),j$t=S({page:M().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:M().int("Page size must be an integer").min(1,"Page size must be at least 1").max(1000,"Page size cannot exceed 1000").optional(),tradingPairId:Oe.optional(),pageToken:y().optional()}).superRefine((e,t)=>{if(e.page!==void 0&&e.pageToken===void 0&&e.pageSize!==void 0&&e.pageSize>100)t.addIssue({code:Hn.custom,message:"Page size cannot exceed 100 in page-number mode (page without pageToken)",path:["pageSize"]})}),q$t=S({page:M().int("Page must be an integer").min(1,"Page must be at least 1").optional(),pageSize:M().int("Page size must be an integer").min(1,"Page size must be at least 1").max(100,"Page size cannot exceed 100").optional(),tradingPairId:Oe.optional(),positionId:Oe.optional(),marginAccountId:Oe.optional()});var Z$t=y().regex(/^0x[a-fA-F0-9]{40}$/,{message:"Must be a valid Ethereum address (e.g., '0x1234...5678')"}),aI=st([y().regex(/^\d+$/,"Must be a positive integer string").refine((e)=>BigInt(e)>0n,{message:"Amount must be greater than 0"}),N5().refine((e)=>e>0n,{message:"Amount must be greater than 0"})]),W$t=S({assetId:Oe,amount:aI,autoWait:ue().optional()}),K$t=S({assetId:Oe,amount:aI,autoWait:ue().optional(),target:H(["spot","margin"]).optional(),options:S({asErc20:ue().optional()}).optional()}),Y$t=S({assetId:Oe,amount:aI,destination:y().regex(/^0x[a-fA-F0-9]{40}$/,"destination must be a 0x-prefixed 20-byte hex address"),autoWait:ue().optional(),source:H(["spot","margin"]).optional()}),J$t=S({assetId:Oe});function Rj(e){e.registerTool("simulate_parent_margin_order_risk",{description:"Preview the risk impact of a prospective order against your parent (cross) margin account (read-only simulation).",inputSchema:S({tradingPairId:y().describe("Trading pair UUID"),side:H(["BUY","SELL"]).describe("Order side (authoritative: BUY=LONG, SELL=SHORT)"),orderType:H(["LIMIT","MARKET"]).describe("Order type"),quantity:y().describe("Order quantity as a decimal string"),price:y().optional().describe("Limit price as a decimal string — required for LIMIT"),leverage:y().optional().describe("Leverage as a decimal string — required unless reduceOnly is true"),reduceOnly:ue().optional().describe("Whether the order can only reduce exposure"),slippageToleranceBps:$l.optional().describe("MARKET only: slippage tolerance in bps (0..1000), tightening the previewed walk to the band placement will use; the response's expectedMatchResult (the engine's simulated fill, in the same shape as a placement's matchResult) and estimatedFee price under it")}).refine((t)=>t.orderType!=="LIMIT"||t.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["price"]}).refine((t)=>t.reduceOnly===!0||t.leverage!==void 0,{message:"leverage is required for normal (non-reduce-only) margin orders",path:["leverage"]}).refine((t)=>t.orderType==="MARKET"||t.slippageToleranceBps===void 0,{message:"slippageToleranceBps is only supported for MARKET orders",path:["slippageToleranceBps"]})},async({tradingPairId:t,side:r,orderType:n,quantity:o,price:i,leverage:s,reduceOnly:a,slippageToleranceBps:c})=>{let l=await(await X()).marginAccounts.simulateParentMarginOrderRisk({tradingPairId:t,side:r,orderType:n,quantity:o,price:i,leverage:s,reduceOnly:a,slippageToleranceBps:c});return L(l)})}function Oj(e){e.registerTool("simulate_risk_bucket_order_risk",{description:"Preview the risk impact of a prospective order for a new or existing risk bucket (read-only simulation). A CROSS preview names no pairs: cross scope is derived from trading (a pair joins the cross risk bucket when a cross order on it succeeds and, once its positions close, stays listed until a later successful cross order on another pair reconciles the bucket), and the response's selectedTradingPairIds reports the derived scope the preview ran against. Unknown input keys are rejected.",inputSchema:S({tradingPairId:y().describe("Trading pair UUID"),side:H(["BUY","SELL"]).describe("Order side (authoritative: BUY=LONG, SELL=SHORT)"),positionSide:H(["LONG","SHORT"]).optional().describe("Deprecated compatibility field; order side is authoritative (BUY=LONG, SELL=SHORT)"),orderType:H(["LIMIT","MARKET"]).describe("Order type"),quantity:y().describe("Order quantity as a decimal string"),price:y().optional().describe("Limit price as a decimal string — required for LIMIT"),leverage:y().optional().describe("Leverage as a decimal string — required unless reduceOnly is true"),reduceOnly:ue().optional().describe("Whether the order can only reduce exposure"),slippageToleranceBps:$l.optional().describe("MARKET only: slippage tolerance in bps (0..1000), tightening the previewed walk to the band placement will use; the response's expectedMatchResult (the engine's simulated fill, in the same shape as a placement's matchResult) and estimatedFee price under it"),marginMode:H(["ISOLATED","CROSS"]).optional().describe("Risk bucket margin mode (default ISOLATED)"),strategyKey:y().optional().describe("Isolated risk bucket strategy key (ISOLATED only)")}).strict().refine((t)=>t.orderType!=="LIMIT"||t.price!==void 0,{message:"price is required for LIMIT risk simulations",path:["price"]}).refine((t)=>t.reduceOnly===!0||t.leverage!==void 0,{message:"leverage is required for normal (non-reduce-only) margin orders",path:["leverage"]}).refine((t)=>t.orderType==="MARKET"||t.slippageToleranceBps===void 0,{message:"slippageToleranceBps is only supported for MARKET orders",path:["slippageToleranceBps"]}).refine((t)=>t.marginMode!=="CROSS"||t.strategyKey===void 0,{message:"strategyKey is not allowed for CROSS risk buckets",path:["strategyKey"]})},async({tradingPairId:t,side:r,positionSide:n,orderType:o,quantity:i,price:s,leverage:a,reduceOnly:c,slippageToleranceBps:d,marginMode:l,strategyKey:p})=>{let m=await X(),h={tradingPairId:t,side:r,positionSide:n,orderType:o,quantity:i,price:s,leverage:a,reduceOnly:c,slippageToleranceBps:d},b=l==="CROSS"?await m.marginAccounts.simulateRiskBucketOrderRisk({...h,marginMode:l}):await m.marginAccounts.simulateRiskBucketOrderRisk({...h,marginMode:l,strategyKey:p});return L(b)})}function Cj(e){e.registerTool("transfer_collateral_from_parent_margin_account",{description:"Move collateral out of your parent (cross) margin account back to spot.",inputSchema:S({asset:y().describe("Collateral asset symbol or ID"),amount:y().describe("Amount to transfer as a decimal string")})},async({asset:t,amount:r})=>{let o=await(await X()).marginAccounts.transferCollateralFromParentMarginAccount({asset:t,amount:r});return L(o)})}function Mj(e){e.registerTool("transfer_collateral_to_parent_margin_account",{description:"Move collateral from spot into your parent (cross) margin account.",inputSchema:S({asset:y().describe("Collateral asset symbol or ID"),amount:y().describe("Amount to transfer as a decimal string")})},async({asset:t,amount:r})=>{let o=await(await X()).marginAccounts.transferCollateralToParentMarginAccount({asset:t,amount:r});return L(o)})}function $j(e){e.registerTool("transfer_collateral_to_risk_bucket",{description:"Allocate collateral into an isolated or cross risk bucket. A cross transfer names no pairs: cross scope is derived from trading (a pair joins the cross bucket when a cross order on it succeeds and leaves when its positions close).",inputSchema:S({asset:y().describe("Collateral asset symbol or ID"),amount:y().describe("Amount to transfer as a decimal string"),marginMode:H(["ISOLATED","CROSS"]).optional().describe("Risk bucket margin mode (default ISOLATED)"),tradingPairId:y().optional().describe("Trading pair UUID (required for ISOLATED; not allowed for CROSS)"),strategyKey:y().optional().describe("Isolated risk bucket strategy key (ISOLATED only)"),applyToPositionMargin:ue().optional().describe("ISOLATED only. Omitted/true (Adjust Margin, the default): commit the amount to the sole open position's stored margin — leverage drops and stays down, initial margin required rises, free collateral is unchanged. false: plain allocation — free collateral rises and the next order can spend it; funding loops targeting free collateral MUST pass false.")}).strict().refine((t)=>t.marginMode==="CROSS"||t.tradingPairId!==void 0,{message:"tradingPairId is required for ISOLATED risk buckets",path:["tradingPairId"]}).refine((t)=>t.marginMode!=="CROSS"||t.tradingPairId===void 0,{message:"tradingPairId is not allowed for CROSS risk buckets",path:["tradingPairId"]}).refine((t)=>t.marginMode!=="CROSS"||t.strategyKey===void 0,{message:"strategyKey is not allowed for CROSS risk buckets",path:["strategyKey"]}).refine((t)=>t.marginMode!=="CROSS"||t.applyToPositionMargin===void 0,{message:"applyToPositionMargin is only allowed for ISOLATED risk buckets",path:["applyToPositionMargin"]})},async({asset:t,amount:r,marginMode:n,tradingPairId:o,strategyKey:i,applyToPositionMargin:s})=>{let a=await X(),c=n==="CROSS"?await a.marginAccounts.transferCollateralToRiskBucket({asset:t,amount:r,marginMode:n}):await a.marginAccounts.transferCollateralToRiskBucket({asset:t,amount:r,marginMode:n,tradingPairId:o??"",strategyKey:i,applyToPositionMargin:s});return L(c)})}function Nj(e){dj(e),pj(e),uj(e),lj(e),Rj(e),Oj(e),Mj(e),Cj(e),$j(e)}function zj(e){e.registerTool("get_candlesticks",{description:"Get OHLCV candlestick data for a trading pair. Useful for charting and price analysis.",inputSchema:S({tradingPairId:y().describe("Trading pair UUID"),interval:H(["1m","5m","15m","1h","4h","1d"]).describe("Candlestick interval"),startTime:M().optional().describe("Start time as Unix timestamp (seconds)"),endTime:M().optional().describe("End time as Unix timestamp (seconds)"),limit:M().optional().describe("Max number of candlesticks to return")})},async({tradingPairId:t,interval:r,startTime:n,endTime:o,limit:i})=>{let a=await Ze().market.getCandlesticks(t,r,{startTime:n,endTime:o,limit:i});return L(a)})}function Bj(e){e.registerTool("get_market_metadata",{description:"Get metadata for a specific trading pair including tick size, min order size, and trading rules.",inputSchema:S({tradingPairId:y().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ze().market.getMarketMetadata(t);return L(n)})}function Lj(e){e.registerTool("get_market_stats",{description:"Get exchange-wide life-to-date cumulative volume and trade count across all markets."},async()=>{let r=await Ze().market.getMarketStats();return L(r)})}function Dj(e){e.registerTool("get_screener",{description:"Screen trading pairs with market stats (price, volume, change), filtered by market type, category, and active status.",inputSchema:S({page:M().optional().describe("Page number (1-based)"),pageSize:M().optional().describe("Items per page"),marketType:H(["SPOT","MARGIN"]).optional().describe("Filter by market type"),isActive:ue().optional().describe("Filter by active status"),category:y().optional().describe("Filter by category (e.g. crypto, equities, commodities)")})},async({page:t,pageSize:r,marketType:n,isActive:o,category:i})=>{let a=await Ze().market.getScreener({page:t,pageSize:r,marketType:n,isActive:o,category:i});return L(a)})}function Uj(e){e.registerTool("get_trading_pair_by_symbol",{description:"Look up a specific trading pair by its symbol (e.g. 'BTC/USDC'). Returns the pair's full details including its UUID.",inputSchema:S({symbol:y().describe("Trading pair symbol (e.g. 'BTC/USDC')")})},async({symbol:t})=>{let n=await Ze().market.getTradingPairBySymbol(t);if(!n)return lx(`Trading pair '${t}' not found.`);return L(n)})}function Fj(e){e.registerTool("get_trading_pairs",{description:"Get a paginated list of trading pairs available on Monaco. Returns pair IDs, symbols, base/quote tokens, and status.",inputSchema:S({page:M().optional().describe("Page number (starts from 1)"),pageSize:M().optional().describe("Number of items per page (max 100)"),marketType:H(["SPOT","MARGIN"]).optional().describe("Filter by market type"),baseToken:y().optional().describe("Filter by base token"),quoteToken:y().optional().describe("Filter by quote token"),isActive:ue().optional().describe("Filter by active status"),category:y().optional().describe("Filter by category (e.g. crypto, equities, commodities)")})},async(t)=>{let n=await Ze().market.getPaginatedTradingPairs(t);return L(n)})}function jj(e){Fj(e),Uj(e),zj(e),Bj(e),Dj(e),Lj(e)}function qj(e){e.registerTool("get_orderbook",{description:"Get the current orderbook snapshot for a trading pair. Shows bids, asks, best bid/ask, and volumes.",inputSchema:S({tradingPairId:y().describe("Trading pair UUID"),depth:M().optional().describe("Number of price levels to return (max 100, default 10)"),tradingMode:H(["SPOT"]).optional().describe("Trading mode (default: SPOT)"),magnitude:M().optional().describe("Price grouping magnitude (e.g. 0.01, 0.1, 1, 10, 100)"),denomination:H(["BASE","QUOTE"]).optional().describe("Quantity denomination: BASE or QUOTE")})},async({tradingPairId:t,depth:r,tradingMode:n,magnitude:o,denomination:i})=>{let a=await Ze().orderbook.getOrderbook(t,{depth:r,tradingMode:n,magnitude:o,denomination:i});return L(a)})}function Hj(e){qj(e)}function Gj(e){e.registerTool("get_all_funding_history",{description:"List historical funding-rate records across all perpetual markets.",inputSchema:S({startTime:y().optional().describe('Start time as a Unix millisecond-epoch timestamp string (e.g. "1717200000000"); ISO 8601 is rejected by the API'),endTime:y().optional().describe('End time as a Unix millisecond-epoch timestamp string (e.g. "1717200000000"); ISO 8601 is rejected by the API'),page:M().optional().describe("Page number (1-based)"),pageSize:M().optional().describe("Items per page"),orderBy:H(["ASC","DESC"]).optional().describe("Sort order by time")})},async({startTime:t,endTime:r,page:n,pageSize:o,orderBy:i})=>{let a=await Ze().market.listAllFundingHistory({startTime:t,endTime:r,page:n,pageSize:o,orderBy:i});return L(a)})}function Vj(e){e.registerTool("get_funding_history",{description:"List historical funding-rate records for a perpetual market.",inputSchema:S({tradingPairId:y().describe("Trading pair UUID"),startTime:y().optional().describe('Start time as a Unix millisecond-epoch timestamp string (e.g. "1717200000000"); ISO 8601 is rejected by the API'),endTime:y().optional().describe('End time as a Unix millisecond-epoch timestamp string (e.g. "1717200000000"); ISO 8601 is rejected by the API'),page:M().optional().describe("Page number (1-based)"),pageSize:M().optional().describe("Items per page"),orderBy:H(["ASC","DESC"]).optional().describe("Sort order by time")})},async({tradingPairId:t,startTime:r,endTime:n,page:o,pageSize:i,orderBy:s})=>{let c=await Ze().market.listFundingHistory(t,{startTime:r,endTime:n,page:o,pageSize:i,orderBy:s});return L(c)})}function Zj(e){e.registerTool("get_funding_state",{description:"Get the current funding rate and next funding time for a perpetual market.",inputSchema:S({tradingPairId:y().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ze().market.getFundingState(t);return L(n)})}function Wj(e){e.registerTool("get_index_price",{description:"Get the current index (oracle) price for a perpetual market.",inputSchema:S({tradingPairId:y().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ze().market.getIndexPrice(t);return L(n)})}function Kj(e){e.registerTool("get_mark_price",{description:"Get the current mark price for a perpetual market.",inputSchema:S({tradingPairId:y().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ze().market.getMarkPrice(t);return L(n)})}function Yj(e){e.registerTool("get_open_interest",{description:"Get the current open interest for a perpetual market.",inputSchema:S({tradingPairId:y().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ze().market.getOpenInterest(t);return L(n)})}function Jj(e){e.registerTool("get_perp_market_config",{description:"Get a perpetual market's configuration (leverage limits, margin requirements, funding parameters).",inputSchema:S({tradingPairId:y().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ze().market.getPerpMarketConfig(t);return L(n)})}function Qj(e){e.registerTool("get_perp_market_summary",{description:"Get a perpetual market's live summary (mark/index price, funding rate, open interest, 24h stats).",inputSchema:S({tradingPairId:y().describe("Trading pair UUID")})},async({tradingPairId:t})=>{let n=await Ze().market.getPerpMarketSummary(t);return L(n)})}function Xj(e){Jj(e),Qj(e),Kj(e),Wj(e),Zj(e),Yj(e),Vj(e),Gj(e)}function eq(e){e.registerTool("check_trader_code_availability",{description:"Public advisory check of whether a custom PitPass TraderCode handle is available. Returns `available` and, when unavailable, a `reason` (one of taken, too_short, too_long, reserved, invalid_char, looks_like_address). Advisory only — the authoritative gate is the atomic claim in set_trader_code, so a positive result is not a reservation.",inputSchema:S({code:y().describe("The custom handle to check for availability.")})},async({code:t})=>{let n=await Ze().pitpass.checkTraderCodeAvailability(t);return L(n)})}function tq(e){e.registerTool("clear_trader_code",{description:"Clear the authenticated caller's custom PitPass TraderCode handle, reverting to the wallet-derived default. The freed handle enters a cooldown before anyone else can claim it. Returns the caller's TraderCode identity after the revert.",inputSchema:S({})},async()=>{let r=await(await X()).pitpass.clearTraderCode();return L(r)})}function rq(e){e.registerTool("get_my_trader_code",{description:"Return the authenticated caller's PitPass TraderCode — their normalized wallet address. Clients render it as `Monaco - <address>`. Never 404s; ensures the backing row so referrals attributed to this wallet link correctly.",inputSchema:S({})},async()=>{let r=await(await X()).pitpass.getMyTraderCode();return L(r)})}function nq(e){e.registerTool("get_rewards_balance",{description:"Return the authenticated caller's current PitPass rewards-bucket balances across all reward tokens. Returns an empty list when no rewards have been earned yet. Use transfer_rewards to move earned rewards into a tradeable balance.",inputSchema:S({})},async()=>{let r=await(await X()).pitpass.getRewardsBalance();return L(r)})}function oq(e){e.registerTool("get_trader_code_info",{description:"Public lookup of a PitPass TraderCode (wallet address or 'Monaco - <address>' form). Returns the resolved normalized code when it belongs to a known wallet, or a 404 error if not found. Use this to validate a referral code before sign-up.",inputSchema:S({code:y().describe("The TraderCode to look up — a wallet address (0x-prefixed) or the 'Monaco - <address>' display form.")})},async({code:t})=>{let n=await Ze().pitpass.getTraderCodeInfo(t);return L(n)})}function iq(e){e.registerTool("set_trader_code",{description:"Claim or edit the authenticated caller's custom (vanity) PitPass TraderCode handle. Stored exactly as entered (case preserved); uniqueness is case-insensitive. Must start with a letter and be 5–20 characters of letters, digits, or underscores. The server is the authoritative gate: 409 if the handle is taken, 422 on validation failure, 429 when the per-hour edit limit is hit, 403 when the feature is disabled.",inputSchema:S({code:y().describe("The custom handle to claim or edit to — letter-first [A-Za-z0-9_], 5–20 characters. Case is preserved.")})},async({code:t})=>{let n=await(await X()).pitpass.setTraderCode(t);return L(n)})}function sq(e){e.registerTool("transfer_rewards",{description:"Transfer earned PitPass rewards from your rewards bucket into your trading balance, making them immediately tradeable. Ledger-only — no on-chain transaction. Fails if the rewards balance is insufficient.",inputSchema:S({token:y().describe("Reward token contract address (0x-prefixed EVM address) to transfer."),amount:y().describe("Amount to transfer in RAW atomic units of the token (positive integer string).")})},async({token:t,amount:r})=>{let o=await(await X()).pitpass.transferRewards({token:t,amount:r});return L(o)})}function aq(e){oq(e),eq(e)}function cq(e){rq(e),nq(e),sq(e),iq(e),tq(e)}function uq(e){e.registerTool("get_portfolio_assets",{description:"Get your per-asset portfolio allocation and balances over a period.",inputSchema:S({period:H(["1d","1w","1m","all"]).optional().describe("Analytics period (default: all)")})},async({period:t})=>{let n=await(await X()).portfolio.getAssets({period:t});return L(n)})}function dq(e){e.registerTool("get_portfolio_margin",{description:"Get your portfolio margin overview (collateral, maintenance margin, health)."},async()=>{let r=await(await X()).portfolio.getMargin();return L(r)})}function lq(e){e.registerTool("get_portfolio_performance",{description:"Get your portfolio performance time series over a period.",inputSchema:S({period:H(["1d","1w","1m","all"]).optional().describe("Analytics period (default: all)")})},async({period:t})=>{let n=await(await X()).portfolio.getPerformance({period:t});return L(n)})}function pq(e){e.registerTool("get_portfolio_realized_pnl",{description:"Get your realized PnL breakdown over a period.",inputSchema:S({period:H(["1d","1w","1m","all"]).optional().describe("Analytics period (default: all)")})},async({period:t})=>{let n=await(await X()).portfolio.getRealizedPnl({period:t});return L(n)})}function fq(e){e.registerTool("get_portfolio_summary",{description:"Get your authoritative portfolio summary (equity, PnL, exposure) over a period.",inputSchema:S({period:H(["1d","1w","1m","all"]).optional().describe("Analytics period (default: all)")})},async({period:t})=>{let n=await(await X()).portfolio.getSummary({period:t});return L(n)})}function mq(e){fq(e),lq(e),pq(e),uq(e),dq(e)}function hq(e){e.registerTool("close_position",{description:"Close a perpetual position with a market, limit, or IOC reduce order.",inputSchema:S({positionId:y().describe("Position UUID"),closeType:H(["MARKET","LIMIT","IOC"]).describe("Close order type"),limitPrice:y().optional().describe("Limit price as a decimal string — required for LIMIT and IOC, not allowed for MARKET"),slippageToleranceBps:M().optional().describe("Slippage tolerance in basis points (MARKET/IOC)"),quantity:y().optional().describe("Quantity to close as a decimal string (defaults to full position)")}).refine((t)=>t.closeType==="MARKET"||t.limitPrice!==void 0,{message:"limitPrice is required for LIMIT and IOC close requests",path:["limitPrice"]}).refine((t)=>t.closeType!=="MARKET"||t.limitPrice===void 0,{message:"limitPrice is not allowed for MARKET close requests",path:["limitPrice"]})},async({positionId:t,closeType:r,limitPrice:n,slippageToleranceBps:o,quantity:i})=>{let a=await(await X()).positions.closePosition(t,{closeType:r,limitPrice:n,slippageToleranceBps:o,quantity:i});return L(a)})}function gq(e){e.registerTool("get_position",{description:"Get details for a specific perpetual position by ID.",inputSchema:S({positionId:y().describe("Position UUID")})},async({positionId:t})=>{let n=await(await X()).positions.getPosition(t);return L(n)})}function yq(e){e.registerTool("get_position_history",{description:"List historical (closed/reduced) perpetual position records with optional filters.",inputSchema:S({positionId:y().optional().describe("Filter by position UUID"),marginAccountId:y().optional().describe("Filter by margin account UUID"),tradingPairId:y().optional().describe("Filter by trading pair UUID"),page:M().optional().describe("Page number (1-based)"),pageSize:M().optional().describe("Items per page"),reductionOnly:ue().optional().describe("Only include reduction events")})},async({positionId:t,marginAccountId:r,tradingPairId:n,page:o,pageSize:i,reductionOnly:s})=>{let c=await(await X()).positions.listPositionHistory({positionId:t,marginAccountId:r,tradingPairId:n,page:o,pageSize:i,reductionOnly:s});return L(c)})}function bq(e){e.registerTool("get_position_pnl_history",{description:"Get the PnL history time series for a perpetual position over an interval.",inputSchema:S({positionId:y().describe("Position UUID"),interval:H(["1m","5m","15m","1h","4h","1d"]).describe("Sampling interval"),startTime:M().int().min(0).optional().describe("Start time as a Unix timestamp in milliseconds"),endTime:M().int().min(0).optional().describe("End time as a Unix timestamp in milliseconds")}).refine((t)=>t.startTime===void 0||t.endTime===void 0||t.startTime<t.endTime,{message:"startTime must be less than endTime",path:["startTime"]})},async({positionId:t,interval:r,startTime:n,endTime:o})=>{let s=await(await X()).positions.getPositionPnlHistory(t,{interval:r,startTime:n,endTime:o});return L(s)})}function xq(e){e.registerTool("get_position_risk",{description:"Get liquidation price, margin ratio, and risk metrics for a perpetual position.",inputSchema:S({positionId:y().describe("Position UUID")})},async({positionId:t})=>{let n=await(await X()).positions.getPositionRisk(t);return L(n)})}function _q(e){e.registerTool("get_positions",{description:"List your perpetual positions with optional filters (margin account, trading pair, status).",inputSchema:S({marginAccountId:y().optional().describe("Filter by margin account UUID"),tradingPairId:y().optional().describe("Filter by trading pair UUID"),status:H(["OPEN","CLOSED","LIQUIDATING","LIQUIDATED"]).optional().describe("Filter by position status"),page:M().optional().describe("Page number (1-based)"),pageSize:M().optional().describe("Items per page")})},async({marginAccountId:t,tradingPairId:r,status:n,page:o,pageSize:i})=>{let a=await(await X()).positions.listPositions({marginAccountId:t,tradingPairId:r,status:n,page:o,pageSize:i});return L(a)})}function wq(e){_q(e),gq(e),xq(e),yq(e),bq(e),hq(e)}function Sq(e){e.registerTool("get_balance_by_asset",{description:"Get the authenticated user's balance for a specific asset by its UUID.",inputSchema:S({assetId:y().describe("The asset UUID")})},async({assetId:t})=>{let n=await(await X()).profile.getUserBalanceByAssetId(t);return L(n)})}function vq(e){e.registerTool("get_balances",{description:"Get the authenticated user's token balances with pagination.",inputSchema:S({page:M().optional().describe("Page number (starts from 1, default: 1)"),pageSize:M().optional().describe("Number of items per page (default: 20, max: 100)")})},async({page:t,pageSize:r})=>{let o=await(await X()).profile.getUserBalances({page:t,pageSize:r});return L(o)})}function Tq(e){e.registerTool("get_funding_payments",{description:"List your perpetual funding payments with optional filters (trading pair, position, margin account).",inputSchema:S({tradingPairId:y().optional().describe("Filter by trading pair UUID"),positionId:y().optional().describe("Filter by position UUID"),marginAccountId:y().optional().describe("Filter by margin account UUID"),page:M().optional().describe("Page number (1-based)"),pageSize:M().optional().describe("Items per page")})},async({tradingPairId:t,positionId:r,marginAccountId:n,page:o,pageSize:i})=>{let a=await(await X()).profile.listFundingPayments({tradingPairId:t,positionId:r,marginAccountId:n,page:o,pageSize:i});return L(a)})}function Eq(e){e.registerTool("get_movements",{description:"Get the authenticated user's ledger movements (transaction history) with pagination.",inputSchema:S({page:M().int().min(1).optional().describe("Page number (starts from 1, default: 1)"),pageSize:M().int().min(1).max(100).optional().describe("Items per page (default: 20, max: 100)"),entryType:H(["CREDIT","DEBIT","LOCK","UNLOCK","FEE"]).optional().describe("Filter by entry type (e.g. CREDIT, DEBIT, LOCK, UNLOCK, FEE)"),transactionType:H(["DEPOSIT","WITHDRAWAL","TRADE","FEE","FUNDING","LIQUIDATION","INTEREST","REWARD"]).optional().describe("Filter by transaction type (e.g. DEPOSIT, WITHDRAWAL, TRADE, FEE, FUNDING, LIQUIDATION, INTEREST, REWARD)"),assetId:y().uuid().optional().describe("Filter by asset ID (UUID)")})},async({page:t,pageSize:r,entryType:n,transactionType:o,assetId:i})=>{let a=await(await X()).profile.getPaginatedUserMovements({page:t,pageSize:r,entryType:n,transactionType:o,assetId:i});return L(a)})}function Pq(e){e.registerTool("get_profile",{description:"Get the authenticated user's profile including address, username, account type, and withdrawal status. Use get_balances, get_movements, and get_orders for detailed account data."},async()=>{let r=await(await X()).profile.getProfile();return L(r)})}function Aq(e){e.registerTool("get_user_trades",{description:"List your own trade fills with optional filters and cursor pagination.",inputSchema:S({tradingPairId:y().optional().describe("Filter by trading pair UUID"),pageSize:M().optional().describe("Items per page"),pageToken:y().optional().describe("Cursor for the next page"),page:M().optional().describe("Page number (legacy offset mode; prefer pageToken)")})},async({tradingPairId:t,pageSize:r,pageToken:n,page:o})=>{let s=await(await X()).profile.getUserTrades({tradingPairId:t,pageSize:r,pageToken:n,page:o});return L(s)})}function Iq(e){Pq(e),vq(e),Sq(e),Eq(e),Aq(e),Tq(e)}function kq(e){e.registerTool("get_pulse",{description:"Get the latest market-pulse news feed: AI-synthesized, per-asset headlines with sentiment tags."},async()=>{let r=await Ze().pulse.getPulse();return L(r)})}function Rq(e){kq(e)}var Epe="https://docs.0xmonaco.com/mcp",Ppe="SearchMonacoDocs",bx=null;async function Oq(e,t,r){let n=await fetch(Epe,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream",...bx?{"Mcp-Session-Id":bx}:{}},body:JSON.stringify({jsonrpc:"2.0",id:r,method:e,params:t})});if(!n.ok)throw Error(`Mintlify MCP error: ${n.status}`);let o=n.headers.get("mcp-session-id");if(o)bx=o;let s=(await n.text()).split(`
152
- `).find((a)=>a.startsWith("data: "));if(!s)throw Error("No data in Mintlify MCP response");return JSON.parse(s.slice(6))}async function Ape(){if(bx)return;await Oq("initialize",{protocolVersion:"2025-03-26",capabilities:{},clientInfo:{name:"monaco-mcp-server",version:S0.version}},0)}async function Ipe(e){return await Ape(),(await Oq("tools/call",{name:Ppe,arguments:{query:e}},1))?.result}function Cq(e){e.registerTool("search_docs",{description:"Search the Monaco documentation for information about the protocol, SDK, trading, and development guides.",inputSchema:S({query:y().describe("The search query")})},async({query:t})=>{try{let r=await Ipe(t);if(r?.content&&Array.isArray(r.content))return{content:r.content};return L(r)}catch(r){return lx(`Search failed: ${r instanceof Error?r.message:String(r)}`)}})}function Mq(e){Cq(e)}function $q(e){e.registerTool("get_trades",{description:"Get historical trades for a trading pair. Returns recent trades sorted by execution time (newest first).",inputSchema:S({tradingPairId:y().describe("Trading pair UUID"),page:M().optional().describe("Page number (starts from 1, default: 1)"),pageSize:M().optional().describe("Max number of records to return (default: 25, max: 100)")})},async({tradingPairId:t,page:r,pageSize:n})=>{let i=await Ze().trades.getTrades(t,{page:r,pageSize:n});return L(i)})}function Nq(e){$q(e)}function zq(e){e.registerTool("batch_cancel_all_orders",{description:"Cancel EVERY one of your open orders in one call. Destructive and unfiltered by default — with no tradingPairId it cancels your entire open-order book across all pairs; pass a tradingPairId to limit it to that pair.",inputSchema:S({tradingPairId:y().optional().describe("Optional trading pair UUID to limit cancellation to")})},async({tradingPairId:t})=>{let n=await(await X()).trading.batchCancelAll(t);return L(n)})}function Bq(e){e.registerTool("batch_cancel_orders",{description:"Cancel multiple orders by their IDs in a single request. Non-atomic and best-effort: each order is cancelled independently, so a failed leg does not stop the others. Inspect the per-order results and reconcile (retry or re-check) any that did not cancel.",inputSchema:S({orderIds:Ie(y()).describe("Array of order IDs to cancel")})},async({orderIds:t})=>{let n=await(await X()).trading.batchCancel(t);return L(n)})}function Lq(e){e.registerTool("batch_close_all_positions",{description:"Close all open perpetual positions with MARKET reduce-only orders ('panic close'), optionally filtered to a specific trading pair. Best-effort: each position closes independently and per-position failures are reported in the result.",inputSchema:S({tradingPairId:y().optional().describe("Optional trading pair UUID to limit the close to"),slippageToleranceBps:M().int().optional().describe("Optional slippage tolerance (basis points) applied to each close")})},async({tradingPairId:t,slippageToleranceBps:r})=>{let o=await(await X()).positions.batchCloseAllPositions({tradingPairId:t,slippageToleranceBps:r});return L(o)})}function Dq(e){e.registerTool("cancel_order",{description:"Cancel an open order by its ID.",inputSchema:S({orderId:y().describe("The order ID to cancel")})},async({orderId:t})=>{let n=await(await X()).trading.cancelOrder(t);return L(n)})}function Uq(e){e.registerTool("get_order",{description:"Get detailed information about a specific order by its ID.",inputSchema:S({orderId:y().describe("The order ID to look up")})},async({orderId:t})=>{let n=await(await X()).trading.getOrder(t);return L(n)})}function Fq(e){e.registerTool("get_orders",{description:"Get a cursor-paginated list of orders with optional filters by status and trading pair. Omit both page and pageToken for the newest orders; pass the previous response's nextPageToken to fetch the next page. A response with zero orders and an empty nextPageToken means the walk is exhausted. Cursor responses have no exact totals (total/totalPages are 0).",inputSchema:S({status:H(Ol).optional().describe("Filter by order status (e.g. SUBMITTED, FILLED, CANCELLED)"),tradingPairId:y().optional().describe("Filter by trading pair UUID"),page:M().optional().describe("Deprecated: page number for legacy offset pagination, which only sees recent history. Use pageToken instead."),pageSize:M().optional().describe("Orders per page (default: 10; max 100 in legacy page mode, up to 1000 with pageToken)"),pageToken:y().optional().describe("Pagination cursor from a previous response's nextPageToken. Omit it (and page) to start from the newest orders.")})},async({status:t,tradingPairId:r,page:n,pageSize:o,pageToken:i})=>{let a=await(await X()).trading.getPaginatedOrders({status:t,tradingPairId:r,page:n,pageSize:o,pageToken:i});return L(a)})}function jq(e){e.registerTool("place_limit_order",{description:"Place a limit order on Monaco. With idempotencyKey, retry the same submission safely within 24 hours of acceptance; different order details conflict. Limit orders execute only when the market reaches the specified price. The SDK generates a key if omitted. Calling this tool again without the original key starts a new submission and is not idempotent: do NOT retry an ambiguous outcome with a new key. Supply and retain your own idempotencyKey to recover across tool calls. get_orders/get_order are replica-backed; a missing row does not prove that an order failed. If the original key is unavailable, report the ambiguity.",inputSchema:S({tradingPairId:y().describe("Trading pair UUID"),side:H(["BUY","SELL"]).describe("Order side"),quantity:y().describe("Order quantity as a decimal string"),price:y().describe("Limit price as a decimal string"),tradingMode:H(["SPOT","MARGIN"]).optional().describe("Trading mode (default: SPOT)"),timeInForce:H(["GTC","IOC","FOK"]).optional().describe("Time in force (default: GTC)"),expirationDate:y().optional().describe("Expiration date for GTC orders (ISO 8601)"),marginAccountId:y().optional().describe("Parent margin account UUID for MARGIN orders"),marginMode:H(["ISOLATED","CROSS"]).optional().describe("Risk bucket mode for MARGIN orders: ISOLATED (default) or CROSS"),riskBucketId:y().optional().describe("Existing isolated risk bucket UUID for risk-bucket-scoped MARGIN orders"),riskBucketCollateral:y().optional().describe("Collateral to allocate into a new isolated risk bucket"),strategyKey:y().optional().describe("Optional client strategy key"),positionSide:H(["LONG","SHORT"]).optional().describe("Deprecated compatibility field; order side is authoritative (BUY=LONG, SELL=SHORT)"),leverage:y().optional().describe("Leverage as a decimal string, required for normal MARGIN orders (ignored for reduce-only)"),reduceOnly:ue().optional().describe("Whether the order can only reduce existing exposure"),postOnly:ue().optional().describe("Maker-only: rejected with a 400 carrying the structured error code 'POST_ONLY_WOULD_CROSS' if this order would cross the book. GTC time in force only; rejected with IOC/FOK."),selfTradePreventionMode:H(["CANCEL_MAKER","CANCEL_TAKER","CANCEL_BOTH","SKIP"]).optional().describe("Per-order self-trade-prevention override for matches against your own resting orders. CANCEL_MAKER cancels your resting orders and keeps matching; CANCEL_TAKER cancels this order's remainder at the first self-touch; CANCEL_BOTH does both; SKIP trades around your orders and cancels a remainder that would cross them. Omitted, your wallet default applies, else the platform default CANCEL_MAKER. Echoed back as selfTradePreventionMode on order reads."),idempotencyKey:y().min(1).max(64).regex(/^[A-Za-z0-9._:-]+$/).optional().describe("Stable identity for this submission; the SDK generates a key if omitted. Supply and retain a key for recovery across tool calls. Reuse with the same order details to safely retry a lost response within 24 hours of acceptance, including after a fill. Use a fresh key for each new order. Different details conflict; after 24 hours this key may execute again. Separate from clientOrderId."),clientOrderId:y().optional().describe("Client-assigned correlation handle, echoed back on order reads and order WebSocket events. Up to 64 characters from A-Za-z0-9._:-. Not an idempotency key: it is claimed only while the order rests, and is released on fill/cancel/expiry/rejection, so a marketable order that fills on arrival never takes it. Never resubmit on a lost response without the original idempotencyKey — a resubmission can execute a second time. Reconciling a lost response needs the order WebSocket stream (it carries the handle even for orders that never rested), which is outside MCP — this server exposes no stream tool, and get_orders is replica-backed and can omit an order that did land.")})},async({tradingPairId:t,side:r,quantity:n,price:o,tradingMode:i,timeInForce:s,expirationDate:a,marginAccountId:c,marginMode:d,riskBucketId:l,riskBucketCollateral:p,strategyKey:m,positionSide:h,leverage:b,reduceOnly:x,postOnly:_,selfTradePreventionMode:w,clientOrderId:A,idempotencyKey:v})=>{let P=await(await X()).trading.placeLimitOrder(t,r,n,o,{tradingMode:i,timeInForce:s,expirationDate:a,marginAccountId:c,marginMode:d,riskBucketId:l,riskBucketCollateral:p,strategyKey:m,positionSide:h,leverage:b,reduceOnly:x,postOnly:_,selfTradePreventionMode:w,clientOrderId:A,idempotencyKey:v});return L(P)})}function qq(e){e.registerTool("place_market_order",{description:"Place a market order on Monaco. With idempotencyKey, retry the same submission safely within 24 hours of acceptance; different order details conflict. It executes immediately against resting liquidity, but only inside a mandatory 1,000 bps (10%) server-side protective price band anchored to the mark/last-trade reference price. Fills stop at the edge of the band, so a market order may partially fill and cancel the remainder, be rejected when no liquidity sits inside the band, or be rejected when the market has no trustworthy price anchor. Optional slippageTolerance is merged tighter-wins with this band: it can only TIGHTEN execution, never widen past the mandatory band; omitting it applies the full 1,000 bps band. The SDK generates a key if omitted. Calling this tool again without the original key starts a new submission and is not idempotent: do NOT retry an ambiguous outcome with a new key. Supply and retain your own idempotencyKey to recover across tool calls. get_orders/get_order are replica-backed; a missing row does not prove that an order failed. If the original key is unavailable, report the ambiguity.",inputSchema:S({tradingPairId:y().describe("Trading pair UUID"),side:H(["BUY","SELL"]).describe("Order side"),quantity:y().describe("Order quantity as a decimal string"),tradingMode:H(["SPOT","MARGIN"]).optional().describe("Trading mode (default: SPOT)"),slippageTolerance:M().optional().describe("Tightens the mandatory 1,000 bps band, as a decimal (e.g. 0.01 for 1%; 0 for best price only). Can only tighten, never widen; omit to apply the full band."),marginAccountId:y().optional().describe("Parent margin account UUID for MARGIN orders"),marginMode:H(["ISOLATED","CROSS"]).optional().describe("Risk bucket mode for MARGIN orders: ISOLATED (default) or CROSS"),riskBucketId:y().optional().describe("Existing isolated risk bucket UUID for risk-bucket-scoped MARGIN orders"),riskBucketCollateral:y().optional().describe("Collateral to allocate into a new isolated risk bucket"),strategyKey:y().optional().describe("Optional client strategy key"),positionSide:H(["LONG","SHORT"]).optional().describe("Deprecated compatibility field; order side is authoritative (BUY=LONG, SELL=SHORT)"),leverage:y().optional().describe("Leverage as a decimal string, required for normal MARGIN orders (ignored for reduce-only)"),reduceOnly:ue().optional().describe("Whether the order can only reduce existing exposure"),idempotencyKey:y().min(1).max(64).regex(/^[A-Za-z0-9._:-]+$/).optional().describe("Stable identity for this submission; the SDK generates a key if omitted. Supply and retain a key for recovery across tool calls. Reuse with the same order details to safely retry a lost response within 24 hours of acceptance, including after a fill. Use a fresh key for each new order. Different details conflict; after 24 hours this key may execute again. Separate from clientOrderId."),clientOrderId:y().optional().describe("Client-assigned correlation handle, echoed back on order reads and order WebSocket events. Up to 64 characters from A-Za-z0-9._:-. Not an idempotency key. A market order never rests, so it never claims the handle and no duplicate-submission guard can fire for it: Without idempotencyKey, NEVER resubmit a market order on a lost response — it can execute again and increase your exposure (or reject, or fill at a different price; you cannot tell which in advance). Reconciling a lost response needs the order WebSocket stream (it carries the handle even for orders that never rested), which is outside MCP — this server exposes no stream tool, and get_orders is replica-backed and can omit an order that did land.")})},async({tradingPairId:t,side:r,quantity:n,tradingMode:o,slippageTolerance:i,marginAccountId:s,marginMode:a,riskBucketId:c,riskBucketCollateral:d,strategyKey:l,positionSide:p,leverage:m,reduceOnly:h,clientOrderId:b,idempotencyKey:x})=>{let w=await(await X()).trading.placeMarketOrder(t,r,n,{tradingMode:o,slippageTolerance:i,marginAccountId:s,marginMode:a,riskBucketId:c,riskBucketCollateral:d,strategyKey:l,positionSide:p,leverage:m,reduceOnly:h,clientOrderId:b,idempotencyKey:x});return L(w)})}function Hq(e){e.registerTool("replace_order",{description:"Replace an existing order with new price and/or quantity. The order must be open. "+"Not idempotent, and MCP has no order-stream tool, so an ambiguous outcome (timeout, network error, or a 5xx with no order returned) CANNOT be resolved from inside MCP: do NOT retry. get_orders/get_order are replica-backed and an order rejected before acceptance is never written to them, so a missing row is not evidence the order failed. Check whether the position or balance moved, and otherwise report the ambiguity to the user rather than resubmitting. A retry here cannot double your exposure — replace names the original order id and a second attempt returns ORDER_NOT_FOUND once the first succeeded — but that code does not distinguish a landed replacement from an original that filled or was cancelled, so retrying still reports the wrong state.",inputSchema:S({orderId:y().describe("The order ID to replace"),price:y().optional().describe("New price as a decimal string"),quantity:y().optional().describe("New quantity as a decimal string"),postOnly:ue().optional().describe("Re-states maker-only intent for the replacement (nothing is inherited from the original order): rejected with a 400 carrying the structured error code 'POST_ONLY_WOULD_CROSS' if it would cross the book."),selfTradePreventionMode:H(["CANCEL_MAKER","CANCEL_TAKER","CANCEL_BOTH","SKIP"]).optional().describe("Re-states the per-order self-trade-prevention override for the replacement (nothing is inherited from the original order). Omitted, your wallet default applies, else the platform default CANCEL_MAKER."),clientOrderId:y().optional().describe("Client-assigned correlation handle for the replacement order, echoed back on order reads and order WebSocket events. Nothing is inherited from the original order — re-state it here to keep the handle across a requote. Up to 64 characters from A-Za-z0-9._:-. Not an idempotency key: it is claimed only while the order rests and is released on fill/cancel/expiry/rejection, so it cannot make a lost-response retry safe. Reconciling a lost response needs the order WebSocket stream, which is outside MCP — this server exposes no stream tool.")})},async({orderId:t,price:r,quantity:n,postOnly:o,selfTradePreventionMode:i,clientOrderId:s})=>{let c=await(await X()).trading.replaceOrder(t,{price:r,quantity:n,postOnly:o,selfTradePreventionMode:i,clientOrderId:s});return L(c)})}function Gq(e){jq(e),qq(e),Dq(e),Bq(e),zq(e),Lq(e),Hq(e),Fq(e),Uq(e)}function Vq(e){e.registerTool("vault_get_allowance",{description:"Check the current token allowance granted to the Monaco vault for a specific asset.",inputSchema:S({assetId:y().describe("The asset UUID to check allowance for")})},async({assetId:t})=>{let n=await(await X()).vault.getAllowance(t);return L({assetId:t,allowance:n.toString()})})}function Zq(e){e.registerTool("vault_approve",{description:"Approve the Monaco vault contract to spend tokens on your behalf. Required before depositing ERC20 tokens.",inputSchema:S({assetId:y().describe("The asset UUID to approve"),amount:y().regex(/^\d+$/,"Must be a non-negative integer string").describe("Max amount to approve as a raw integer string (e.g. '1000000' for 1 USDC with 6 decimals)")})},async({assetId:t,amount:r})=>{let o=await(await X()).vault.approve(t,BigInt(r));return L({hash:o.hash,status:o.status})})}function Wq(e){e.registerTool("vault_deposit",{description:"Deposit tokens into the Monaco vault. Requires prior approval for ERC20 tokens (use vault_approve first). Set target to 'margin' to route the deposit straight into margin collateral instead of the spot wallet.",inputSchema:S({assetId:y().describe("The asset UUID to deposit"),amount:y().regex(/^\d+$/,"Must be a non-negative integer string").describe("Amount to deposit as a raw integer string (e.g. '1000000' for 1 USDC with 6 decimals)"),target:H(["spot","margin"]).optional().describe("Destination ledger: 'spot' (default) or 'margin' to route into margin collateral")})},async({assetId:t,amount:r,target:n})=>{let i=await(await X()).vault.deposit(t,BigInt(r),void 0,n);return L({hash:i.hash,status:i.status})})}function Kq(e){e.registerTool("get_pending_withdrawals",{description:"List your pending withdrawals still awaiting on-chain root confirmation.",inputSchema:S({page:M().optional().describe("Page number (1-based)"),pageSize:M().optional().describe("Items per page")})},async({page:t,pageSize:r})=>{let o=await(await X()).withdrawals.listPendingWithdrawals({page:t,pageSize:r});return L(o)})}function Yq(e){e.registerTool("vault_needs_approval",{description:"Check if approval is needed before depositing a specific amount of tokens.",inputSchema:S({assetId:y().describe("The asset UUID to check"),amount:y().regex(/^\d+$/,"Must be a non-negative integer string").describe("Amount to check as a raw integer string")})},async({assetId:t,amount:r})=>{let o=await(await X()).vault.needsApproval(t,BigInt(r));return L({assetId:t,amount:r,needs_approval:o})})}function Jq(e){e.registerTool("vault_withdraw",{description:"Withdraw tokens from the Monaco vault back to your wallet.",inputSchema:S({assetId:y().describe("The asset UUID to withdraw"),amount:y().regex(/^\d+$/,"Must be a non-negative integer string").describe("Amount to withdraw as a raw integer string (e.g. '1000000' for 1 USDC with 6 decimals)")})},async({assetId:t,amount:r})=>{let o=await(await X()).vault.withdraw(t,BigInt(r));return L({withdrawalIndex:o.withdrawalIndex,status:o.status,hash:o.hash})})}function Qq(e){Zq(e),Wq(e),Jq(e),Vq(e),Yq(e),Kq(e)}function kpe(e){let t=e.length-1,r=e[t];if(typeof r!=="function")return e;let n=rj(r);return[...e.slice(0,t),n]}function Rpe(e,t){let[r,...n]=t;if(!r||typeof r!=="object")return t;let o=U4(e);if(!o)return t;let i=r.annotations;return[{...r,annotations:{...o,...i}},...n]}function Xq(e,t,r){return new Proxy(e,{get(n,o,i){if(o==="registerTool")return(a,...c)=>{if(!G4(a,t))return;let d=Rpe(a,c);if(r&&H4(a))d=kpe(d);return n.registerTool(a,...d)};let s=Reflect.get(n,o,i);return typeof s==="function"?s.bind(n):s}})}function e7(e,t){let r={authenticated:t.authenticated,capability:t.capability,allow:t.allow??[],deny:t.deny??[],network:t.network},n=Xq(e,r,!1);if(Mq(n),jj(n),Xj(n),Hj(n),Nq(n),aq(n),Rq(n),t.authenticated){let o=Xq(e,r,!0);Gq(o),wq(o),Iq(o),mq(o),Nj(o),cj(o),Qq(o),ij(o,{network:t.network}),cq(o)}}if(typeof globalThis.crypto?.getRandomValues!=="function")globalThis.crypto=Ope;if(!globalThis.fetch)globalThis.fetch=_h,globalThis.Headers=Zr,globalThis.Request=Ti,globalThis.Response=Ar;if(!globalThis.WebSocket)globalThis.WebSocket=_1.default;async function Cpe(){let e=lc(),t=e.privateKey!==null,r=new Av({name:"monaco-mcp-server",version:S0.version});e7(r,{authenticated:t,network:e.network,capability:e.capability,allow:e.allow,deny:e.deny});let n=new kv;await r.connect(n),console.error(t?`Monaco MCP server running on stdio (network=${e.network}, capability=${e.capability}). Fund-movement and privilege tools require MONACO_CAPABILITY=full or an explicit MONACO_TOOL_ALLOWLIST entry.`:"Monaco MCP server running on stdio (public read-only mode — set MONACO_PRIVATE_KEY, MONACO_CLIENT_ID and MONACO_NETWORK to enable authenticated tools).")}Cpe().catch((e)=>{console.error("Fatal error:",e),process.exit(1)});
152
+ `).find((a)=>a.startsWith("data: "));if(!s)throw Error("No data in Mintlify MCP response");return JSON.parse(s.slice(6))}async function Ape(){if(bx)return;await Oq("initialize",{protocolVersion:"2025-03-26",capabilities:{},clientInfo:{name:"monaco-mcp-server",version:S0.version}},0)}async function Ipe(e){return await Ape(),(await Oq("tools/call",{name:Ppe,arguments:{query:e}},1))?.result}function Cq(e){e.registerTool("search_docs",{description:"Search the Monaco documentation for information about the protocol, SDK, trading, and development guides.",inputSchema:S({query:y().describe("The search query")})},async({query:t})=>{try{let r=await Ipe(t);if(r?.content&&Array.isArray(r.content))return{content:r.content};return L(r)}catch(r){return lx(`Search failed: ${r instanceof Error?r.message:String(r)}`)}})}function Mq(e){Cq(e)}function $q(e){e.registerTool("get_trades",{description:"Get historical trades for a trading pair. Returns recent trades sorted by execution time (newest first).",inputSchema:S({tradingPairId:y().describe("Trading pair UUID"),page:M().optional().describe("Page number (starts from 1, default: 1)"),pageSize:M().optional().describe("Max number of records to return (default: 25, max: 100)")})},async({tradingPairId:t,page:r,pageSize:n})=>{let i=await Ze().trades.getTrades(t,{page:r,pageSize:n});return L(i)})}function Nq(e){$q(e)}function zq(e){e.registerTool("batch_cancel_all_orders",{description:"Cancel EVERY one of your open orders in one call. Destructive and unfiltered by default — with no tradingPairId it cancels your entire open-order book across all pairs; pass a tradingPairId to limit it to that pair.",inputSchema:S({tradingPairId:y().optional().describe("Optional trading pair UUID to limit cancellation to")})},async({tradingPairId:t})=>{let n=await(await X()).trading.batchCancelAll(t);return L(n)})}function Bq(e){e.registerTool("batch_cancel_orders",{description:"Cancel multiple orders by their IDs in a single request. Non-atomic and best-effort: each order is cancelled independently, so a failed leg does not stop the others. Inspect the per-order results and reconcile (retry or re-check) any that did not cancel.",inputSchema:S({orderIds:Ie(y()).describe("Array of order IDs to cancel")})},async({orderIds:t})=>{let n=await(await X()).trading.batchCancel(t);return L(n)})}function Lq(e){e.registerTool("batch_close_all_positions",{description:"Close all open perpetual positions with MARKET reduce-only orders ('panic close'), optionally filtered to a specific trading pair. Best-effort: each position closes independently and per-position failures are reported in the result.",inputSchema:S({tradingPairId:y().optional().describe("Optional trading pair UUID to limit the close to"),slippageToleranceBps:M().int().optional().describe("Optional slippage tolerance (basis points) applied to each close")})},async({tradingPairId:t,slippageToleranceBps:r})=>{let o=await(await X()).positions.batchCloseAllPositions({tradingPairId:t,slippageToleranceBps:r});return L(o)})}function Dq(e){e.registerTool("cancel_order",{description:"Cancel an open order by its ID.",inputSchema:S({orderId:y().describe("The order ID to cancel")})},async({orderId:t})=>{let n=await(await X()).trading.cancelOrder(t);return L(n)})}function Uq(e){e.registerTool("get_order",{description:"Get detailed information about a specific order by its ID.",inputSchema:S({orderId:y().describe("The order ID to look up")})},async({orderId:t})=>{let n=await(await X()).trading.getOrder(t);return L(n)})}function Fq(e){e.registerTool("get_orders",{description:"Get a cursor-paginated list of orders with optional filters by status and trading pair. Omit both page and pageToken for the newest orders; pass the previous response's nextPageToken to fetch the next page. A response with zero orders and an empty nextPageToken means the walk is exhausted. Both modes return a bounded item count: total and totalPages are populated, exact up to a server ceiling and then reported as the ceiling with totalCapped=true (a lower bound). Only page is 0 in cursor mode.",inputSchema:S({status:H(Ol).optional().describe("Filter by order status (e.g. SUBMITTED, FILLED, CANCELLED)"),tradingPairId:y().optional().describe("Filter by trading pair UUID"),page:M().optional().describe("Deprecated: page number for legacy offset pagination, which only sees recent history. Use pageToken instead."),pageSize:M().optional().describe("Orders per page (default: 10; max 100 in legacy page mode, up to 1000 with pageToken)"),pageToken:y().optional().describe("Pagination cursor from a previous response's nextPageToken. Omit it (and page) to start from the newest orders.")})},async({status:t,tradingPairId:r,page:n,pageSize:o,pageToken:i})=>{let a=await(await X()).trading.getPaginatedOrders({status:t,tradingPairId:r,page:n,pageSize:o,pageToken:i});return L(a)})}function jq(e){e.registerTool("place_limit_order",{description:"Place a limit order on Monaco. With idempotencyKey, retry the same submission safely within 24 hours of acceptance; different order details conflict. Limit orders execute only when the market reaches the specified price. The SDK generates a key if omitted. Calling this tool again without the original key starts a new submission and is not idempotent: do NOT retry an ambiguous outcome with a new key. Supply and retain your own idempotencyKey to recover across tool calls. get_orders/get_order are replica-backed; a missing row does not prove that an order failed. If the original key is unavailable, report the ambiguity.",inputSchema:S({tradingPairId:y().describe("Trading pair UUID"),side:H(["BUY","SELL"]).describe("Order side"),quantity:y().describe("Order quantity as a decimal string"),price:y().describe("Limit price as a decimal string"),tradingMode:H(["SPOT","MARGIN"]).optional().describe("Trading mode (default: SPOT)"),timeInForce:H(["GTC","IOC","FOK"]).optional().describe("Time in force (default: GTC)"),expirationDate:y().optional().describe("Expiration date for GTC orders (ISO 8601)"),marginAccountId:y().optional().describe("Parent margin account UUID for MARGIN orders"),marginMode:H(["ISOLATED","CROSS"]).optional().describe("Risk bucket mode for MARGIN orders: ISOLATED (default) or CROSS"),riskBucketId:y().optional().describe("Existing isolated risk bucket UUID for risk-bucket-scoped MARGIN orders"),riskBucketCollateral:y().optional().describe("Collateral to allocate into a new isolated risk bucket"),strategyKey:y().optional().describe("Optional client strategy key"),positionSide:H(["LONG","SHORT"]).optional().describe("Deprecated compatibility field; order side is authoritative (BUY=LONG, SELL=SHORT)"),leverage:y().optional().describe("Leverage as a decimal string, required for normal MARGIN orders (ignored for reduce-only)"),reduceOnly:ue().optional().describe("Whether the order can only reduce existing exposure"),postOnly:ue().optional().describe("Maker-only: rejected with a 400 carrying the structured error code 'POST_ONLY_WOULD_CROSS' if this order would cross the book. GTC time in force only; rejected with IOC/FOK."),selfTradePreventionMode:H(["CANCEL_MAKER","CANCEL_TAKER","CANCEL_BOTH","SKIP"]).optional().describe("Per-order self-trade-prevention override for matches against your own resting orders. CANCEL_MAKER cancels your resting orders and keeps matching; CANCEL_TAKER cancels this order's remainder at the first self-touch; CANCEL_BOTH does both; SKIP trades around your orders and cancels a remainder that would cross them. Omitted, your wallet default applies, else the platform default CANCEL_MAKER. Echoed back as selfTradePreventionMode on order reads."),idempotencyKey:y().min(1).max(64).regex(/^[A-Za-z0-9._:-]+$/).optional().describe("Stable identity for this submission; the SDK generates a key if omitted. Supply and retain a key for recovery across tool calls. Reuse with the same order details to safely retry a lost response within 24 hours of acceptance, including after a fill. Use a fresh key for each new order. Different details conflict; after 24 hours this key may execute again. Separate from clientOrderId."),clientOrderId:y().optional().describe("Client-assigned correlation handle, echoed back on order reads and order WebSocket events. Up to 64 characters from A-Za-z0-9._:-. Not an idempotency key: it is claimed only while the order rests, and is released on fill/cancel/expiry/rejection, so a marketable order that fills on arrival never takes it. Never resubmit on a lost response without the original idempotencyKey — a resubmission can execute a second time. Reconciling a lost response needs the order WebSocket stream (it carries the handle even for orders that never rested), which is outside MCP — this server exposes no stream tool, and get_orders is replica-backed and can omit an order that did land.")})},async({tradingPairId:t,side:r,quantity:n,price:o,tradingMode:i,timeInForce:s,expirationDate:a,marginAccountId:c,marginMode:d,riskBucketId:l,riskBucketCollateral:p,strategyKey:m,positionSide:h,leverage:b,reduceOnly:x,postOnly:_,selfTradePreventionMode:w,clientOrderId:A,idempotencyKey:v})=>{let P=await(await X()).trading.placeLimitOrder(t,r,n,o,{tradingMode:i,timeInForce:s,expirationDate:a,marginAccountId:c,marginMode:d,riskBucketId:l,riskBucketCollateral:p,strategyKey:m,positionSide:h,leverage:b,reduceOnly:x,postOnly:_,selfTradePreventionMode:w,clientOrderId:A,idempotencyKey:v});return L(P)})}function qq(e){e.registerTool("place_market_order",{description:"Place a market order on Monaco. With idempotencyKey, retry the same submission safely within 24 hours of acceptance; different order details conflict. It executes immediately against resting liquidity, but only inside a mandatory 1,000 bps (10%) server-side protective price band anchored to the mark/last-trade reference price. Fills stop at the edge of the band, so a market order may partially fill and cancel the remainder, be rejected when no liquidity sits inside the band, or be rejected when the market has no trustworthy price anchor. Optional slippageTolerance is merged tighter-wins with this band: it can only TIGHTEN execution, never widen past the mandatory band; omitting it applies the full 1,000 bps band. The SDK generates a key if omitted. Calling this tool again without the original key starts a new submission and is not idempotent: do NOT retry an ambiguous outcome with a new key. Supply and retain your own idempotencyKey to recover across tool calls. get_orders/get_order are replica-backed; a missing row does not prove that an order failed. If the original key is unavailable, report the ambiguity.",inputSchema:S({tradingPairId:y().describe("Trading pair UUID"),side:H(["BUY","SELL"]).describe("Order side"),quantity:y().describe("Order quantity as a decimal string"),tradingMode:H(["SPOT","MARGIN"]).optional().describe("Trading mode (default: SPOT)"),slippageTolerance:M().optional().describe("Tightens the mandatory 1,000 bps band, as a decimal (e.g. 0.01 for 1%; 0 for best price only). Can only tighten, never widen; omit to apply the full band."),marginAccountId:y().optional().describe("Parent margin account UUID for MARGIN orders"),marginMode:H(["ISOLATED","CROSS"]).optional().describe("Risk bucket mode for MARGIN orders: ISOLATED (default) or CROSS"),riskBucketId:y().optional().describe("Existing isolated risk bucket UUID for risk-bucket-scoped MARGIN orders"),riskBucketCollateral:y().optional().describe("Collateral to allocate into a new isolated risk bucket"),strategyKey:y().optional().describe("Optional client strategy key"),positionSide:H(["LONG","SHORT"]).optional().describe("Deprecated compatibility field; order side is authoritative (BUY=LONG, SELL=SHORT)"),leverage:y().optional().describe("Leverage as a decimal string, required for normal MARGIN orders (ignored for reduce-only)"),reduceOnly:ue().optional().describe("Whether the order can only reduce existing exposure"),idempotencyKey:y().min(1).max(64).regex(/^[A-Za-z0-9._:-]+$/).optional().describe("Stable identity for this submission; the SDK generates a key if omitted. Supply and retain a key for recovery across tool calls. Reuse with the same order details to safely retry a lost response within 24 hours of acceptance, including after a fill. Use a fresh key for each new order. Different details conflict; after 24 hours this key may execute again. Separate from clientOrderId."),clientOrderId:y().optional().describe("Client-assigned correlation handle, echoed back on order reads and order WebSocket events. Up to 64 characters from A-Za-z0-9._:-. Not an idempotency key. A market order never rests, so it never claims the handle and no duplicate-submission guard can fire for it: Without idempotencyKey, NEVER resubmit a market order on a lost response — it can execute again and increase your exposure (or reject, or fill at a different price; you cannot tell which in advance). Reconciling a lost response needs the order WebSocket stream (it carries the handle even for orders that never rested), which is outside MCP — this server exposes no stream tool, and get_orders is replica-backed and can omit an order that did land.")})},async({tradingPairId:t,side:r,quantity:n,tradingMode:o,slippageTolerance:i,marginAccountId:s,marginMode:a,riskBucketId:c,riskBucketCollateral:d,strategyKey:l,positionSide:p,leverage:m,reduceOnly:h,clientOrderId:b,idempotencyKey:x})=>{let w=await(await X()).trading.placeMarketOrder(t,r,n,{tradingMode:o,slippageTolerance:i,marginAccountId:s,marginMode:a,riskBucketId:c,riskBucketCollateral:d,strategyKey:l,positionSide:p,leverage:m,reduceOnly:h,clientOrderId:b,idempotencyKey:x});return L(w)})}function Hq(e){e.registerTool("replace_order",{description:"Replace an existing order with new price and/or quantity. The order must be open. "+"Not idempotent, and MCP has no order-stream tool, so an ambiguous outcome (timeout, network error, or a 5xx with no order returned) CANNOT be resolved from inside MCP: do NOT retry. get_orders/get_order are replica-backed and an order rejected before acceptance is never written to them, so a missing row is not evidence the order failed. Check whether the position or balance moved, and otherwise report the ambiguity to the user rather than resubmitting. A retry here cannot double your exposure — replace names the original order id and a second attempt returns ORDER_NOT_FOUND once the first succeeded — but that code does not distinguish a landed replacement from an original that filled or was cancelled, so retrying still reports the wrong state.",inputSchema:S({orderId:y().describe("The order ID to replace"),price:y().optional().describe("New price as a decimal string"),quantity:y().optional().describe("New quantity as a decimal string"),postOnly:ue().optional().describe("Re-states maker-only intent for the replacement (nothing is inherited from the original order): rejected with a 400 carrying the structured error code 'POST_ONLY_WOULD_CROSS' if it would cross the book."),selfTradePreventionMode:H(["CANCEL_MAKER","CANCEL_TAKER","CANCEL_BOTH","SKIP"]).optional().describe("Re-states the per-order self-trade-prevention override for the replacement (nothing is inherited from the original order). Omitted, your wallet default applies, else the platform default CANCEL_MAKER."),clientOrderId:y().optional().describe("Client-assigned correlation handle for the replacement order, echoed back on order reads and order WebSocket events. Nothing is inherited from the original order — re-state it here to keep the handle across a requote. Up to 64 characters from A-Za-z0-9._:-. Not an idempotency key: it is claimed only while the order rests and is released on fill/cancel/expiry/rejection, so it cannot make a lost-response retry safe. Reconciling a lost response needs the order WebSocket stream, which is outside MCP — this server exposes no stream tool.")})},async({orderId:t,price:r,quantity:n,postOnly:o,selfTradePreventionMode:i,clientOrderId:s})=>{let c=await(await X()).trading.replaceOrder(t,{price:r,quantity:n,postOnly:o,selfTradePreventionMode:i,clientOrderId:s});return L(c)})}function Gq(e){jq(e),qq(e),Dq(e),Bq(e),zq(e),Lq(e),Hq(e),Fq(e),Uq(e)}function Vq(e){e.registerTool("vault_get_allowance",{description:"Check the current token allowance granted to the Monaco vault for a specific asset.",inputSchema:S({assetId:y().describe("The asset UUID to check allowance for")})},async({assetId:t})=>{let n=await(await X()).vault.getAllowance(t);return L({assetId:t,allowance:n.toString()})})}function Zq(e){e.registerTool("vault_approve",{description:"Approve the Monaco vault contract to spend tokens on your behalf. Required before depositing ERC20 tokens.",inputSchema:S({assetId:y().describe("The asset UUID to approve"),amount:y().regex(/^\d+$/,"Must be a non-negative integer string").describe("Max amount to approve as a raw integer string (e.g. '1000000' for 1 USDC with 6 decimals)")})},async({assetId:t,amount:r})=>{let o=await(await X()).vault.approve(t,BigInt(r));return L({hash:o.hash,status:o.status})})}function Wq(e){e.registerTool("vault_deposit",{description:"Deposit tokens into the Monaco vault. Requires prior approval for ERC20 tokens (use vault_approve first). Set target to 'margin' to route the deposit straight into margin collateral instead of the spot wallet.",inputSchema:S({assetId:y().describe("The asset UUID to deposit"),amount:y().regex(/^\d+$/,"Must be a non-negative integer string").describe("Amount to deposit as a raw integer string (e.g. '1000000' for 1 USDC with 6 decimals)"),target:H(["spot","margin"]).optional().describe("Destination ledger: 'spot' (default) or 'margin' to route into margin collateral")})},async({assetId:t,amount:r,target:n})=>{let i=await(await X()).vault.deposit(t,BigInt(r),void 0,n);return L({hash:i.hash,status:i.status})})}function Kq(e){e.registerTool("get_pending_withdrawals",{description:"List your pending withdrawals still awaiting on-chain root confirmation.",inputSchema:S({page:M().optional().describe("Page number (1-based)"),pageSize:M().optional().describe("Items per page")})},async({page:t,pageSize:r})=>{let o=await(await X()).withdrawals.listPendingWithdrawals({page:t,pageSize:r});return L(o)})}function Yq(e){e.registerTool("vault_needs_approval",{description:"Check if approval is needed before depositing a specific amount of tokens.",inputSchema:S({assetId:y().describe("The asset UUID to check"),amount:y().regex(/^\d+$/,"Must be a non-negative integer string").describe("Amount to check as a raw integer string")})},async({assetId:t,amount:r})=>{let o=await(await X()).vault.needsApproval(t,BigInt(r));return L({assetId:t,amount:r,needs_approval:o})})}function Jq(e){e.registerTool("vault_withdraw",{description:"Withdraw tokens from the Monaco vault back to your wallet.",inputSchema:S({assetId:y().describe("The asset UUID to withdraw"),amount:y().regex(/^\d+$/,"Must be a non-negative integer string").describe("Amount to withdraw as a raw integer string (e.g. '1000000' for 1 USDC with 6 decimals)")})},async({assetId:t,amount:r})=>{let o=await(await X()).vault.withdraw(t,BigInt(r));return L({withdrawalIndex:o.withdrawalIndex,status:o.status,hash:o.hash})})}function Qq(e){Zq(e),Wq(e),Jq(e),Vq(e),Yq(e),Kq(e)}function kpe(e){let t=e.length-1,r=e[t];if(typeof r!=="function")return e;let n=rj(r);return[...e.slice(0,t),n]}function Rpe(e,t){let[r,...n]=t;if(!r||typeof r!=="object")return t;let o=U4(e);if(!o)return t;let i=r.annotations;return[{...r,annotations:{...o,...i}},...n]}function Xq(e,t,r){return new Proxy(e,{get(n,o,i){if(o==="registerTool")return(a,...c)=>{if(!G4(a,t))return;let d=Rpe(a,c);if(r&&H4(a))d=kpe(d);return n.registerTool(a,...d)};let s=Reflect.get(n,o,i);return typeof s==="function"?s.bind(n):s}})}function e7(e,t){let r={authenticated:t.authenticated,capability:t.capability,allow:t.allow??[],deny:t.deny??[],network:t.network},n=Xq(e,r,!1);if(Mq(n),jj(n),Xj(n),Hj(n),Nq(n),aq(n),Rq(n),t.authenticated){let o=Xq(e,r,!0);Gq(o),wq(o),Iq(o),mq(o),Nj(o),cj(o),Qq(o),ij(o,{network:t.network}),cq(o)}}if(typeof globalThis.crypto?.getRandomValues!=="function")globalThis.crypto=Ope;if(!globalThis.fetch)globalThis.fetch=_h,globalThis.Headers=Zr,globalThis.Request=Ti,globalThis.Response=Ar;if(!globalThis.WebSocket)globalThis.WebSocket=_1.default;async function Cpe(){let e=lc(),t=e.privateKey!==null,r=new Av({name:"monaco-mcp-server",version:S0.version});e7(r,{authenticated:t,network:e.network,capability:e.capability,allow:e.allow,deny:e.deny});let n=new kv;await r.connect(n),console.error(t?`Monaco MCP server running on stdio (network=${e.network}, capability=${e.capability}). Fund-movement and privilege tools require MONACO_CAPABILITY=full or an explicit MONACO_TOOL_ALLOWLIST entry.`:"Monaco MCP server running on stdio (public read-only mode — set MONACO_PRIVATE_KEY, MONACO_CLIENT_ID and MONACO_NETWORK to enable authenticated tools).")}Cpe().catch((e)=>{console.error("Fatal error:",e),process.exit(1)});