@tomato414941/foundation 14.1.0 → 15.0.0

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/cli.mjs +14 -14
  2. package/package.json +1 -1
package/dist/cli.mjs CHANGED
@@ -8,7 +8,7 @@ To continue receiving updates to AWS services, bug fixes,
8
8
  and security updates please upgrade to node >=${r}.
9
9
 
10
10
  More information can be found at: https://a.co/c895JFp`))}}});var J1e,X1e,CJ,OJ=_(()=>{J1e=()=>(t,e)=>async r=>(e.__retryLongPoll=!0,t(r)),X1e={name:"longPollMiddleware",tags:["RETRY"],step:"initialize",override:!0},CJ=t=>({applyToStack:e=>{e.add(J1e(),X1e)}})});function gu(t,e,r){return t.$source||(t.$source={}),t.$source[e]=r,t}var DJ=_(()=>{});import{Readable as Y1e}from"node:stream";var Sj,NJ=_(()=>{Sj=t=>t?.body instanceof Y1e||typeof ReadableStream<"u"&&t?.body instanceof ReadableStream});var hd,yu,vu,zJ,MJ,B$=_(()=>{hd=(t,e)=>{let r=[];if(t&&r.push(t),e)for(let o of e)r.push(o);return r},yu=(t,e)=>`${t||"anonymous"}${e&&e.length>0?` (a.k.a. ${e.join(",")})`:""}`,vu=()=>{let t=[],e=[],r=!1,o=new Set,n=d=>d.sort((p,f)=>zJ[f.step]-zJ[p.step]||MJ[f.priority||"normal"]-MJ[p.priority||"normal"]),i=d=>{let p=!1,f=h=>{let y=hd(h.name,h.aliases);if(y.includes(d)){p=!0;for(let w of y)o.delete(w);return!1}return!0};return t=t.filter(f),e=e.filter(f),p},s=d=>{let p=!1,f=h=>{if(h.middleware===d){p=!0;for(let y of hd(h.name,h.aliases))o.delete(y);return!1}return!0};return t=t.filter(f),e=e.filter(f),p},a=d=>(t.forEach(p=>{d.add(p.middleware,{...p})}),e.forEach(p=>{d.addRelativeTo(p.middleware,{...p})}),d.identifyOnResolve?.(l.identifyOnResolve()),d),c=d=>{let p=[];return d.before.forEach(f=>{f.before.length===0&&f.after.length===0?p.push(f):p.push(...c(f))}),p.push(d),d.after.reverse().forEach(f=>{f.before.length===0&&f.after.length===0?p.push(f):p.push(...c(f))}),p},u=(d=!1)=>{let p=[],f=[],h={};return t.forEach(w=>{let b={...w,before:[],after:[]};for(let S of hd(b.name,b.aliases))h[S]=b;p.push(b)}),e.forEach(w=>{let b={...w,before:[],after:[]};for(let S of hd(b.name,b.aliases))h[S]=b;f.push(b)}),f.forEach(w=>{if(w.toMiddleware){let b=h[w.toMiddleware];if(b===void 0){if(d)return;throw new Error(`${w.toMiddleware} is not found when adding ${yu(w.name,w.aliases)} middleware ${w.relation} ${w.toMiddleware}`)}w.relation==="after"&&b.after.push(w),w.relation==="before"&&b.before.push(w)}}),n(p).map(c).reduce((w,b)=>(w.push(...b),w),[])},l={add:(d,p={})=>{let{name:f,override:h,aliases:y}=p,w={step:"initialize",priority:"normal",middleware:d,...p},b=hd(f,y);if(b.length>0){if(b.some(S=>o.has(S))){if(!h)throw new Error(`Duplicate middleware name '${yu(f,y)}'`);for(let S of b){let x=t.findIndex(T=>T.name===S||T.aliases?.some(M=>M===S));if(x===-1)continue;let R=t[x];if(R.step!==w.step||w.priority!==R.priority)throw new Error(`"${yu(R.name,R.aliases)}" middleware with ${R.priority} priority in ${R.step} step cannot be overridden by "${yu(f,y)}" middleware with ${w.priority} priority in ${w.step} step.`);t.splice(x,1)}}for(let S of b)o.add(S)}t.push(w)},addRelativeTo:(d,p)=>{let{name:f,override:h,aliases:y}=p,w={middleware:d,...p},b=hd(f,y);if(b.length>0){if(b.some(S=>o.has(S))){if(!h)throw new Error(`Duplicate middleware name '${yu(f,y)}'`);for(let S of b){let x=e.findIndex(T=>T.name===S||T.aliases?.some(M=>M===S));if(x===-1)continue;let R=e[x];if(R.toMiddleware!==w.toMiddleware||R.relation!==w.relation)throw new Error(`"${yu(R.name,R.aliases)}" middleware ${R.relation} "${R.toMiddleware}" middleware cannot be overridden by "${yu(f,y)}" middleware ${w.relation} "${w.toMiddleware}" middleware.`);e.splice(x,1)}}for(let S of b)o.add(S)}e.push(w)},clone:()=>a(vu()),use:d=>{d.applyToStack(l)},remove:d=>typeof d=="string"?i(d):s(d),removeByTag:d=>{let p=!1,f=h=>{let{tags:y,name:w,aliases:b}=h;if(y&&y.includes(d)){let S=hd(w,b);for(let x of S)o.delete(x);return p=!0,!1}return!0};return t=t.filter(f),e=e.filter(f),p},concat:d=>{let p=a(vu());return p.use(d),p.identifyOnResolve(r||p.identifyOnResolve()||(d.identifyOnResolve?.()??!1)),p},applyToStack:a,identify:()=>u(!0).map(d=>{let p=d.step??d.relation+" "+d.toMiddleware;return yu(d.name,d.aliases)+" - "+p}),identifyOnResolve(d){return typeof d=="boolean"&&(r=d),r},resolve:(d,p)=>{for(let f of u().map(h=>h.middleware).reverse())d=f(d,p);return r&&console.log(l.identify()),d}};return l},zJ={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},MJ={high:3,normal:2,low:1}});var js=U(Gi=>{var xj;(function(t){t.HEADER="header",t.QUERY="query"})(xj||(xj={}));var Ej;(function(t){t.HEADER="header",t.QUERY="query"})(Ej||(Ej={}));var $j;(function(t){t.HTTP="http",t.HTTPS="https"})($j||($j={}));var iv;(function(t){t.MD5="md5",t.CRC32="crc32",t.CRC32C="crc32c",t.SHA1="sha1",t.SHA256="sha256"})(iv||(iv={}));var Q1e=t=>{let e=[];return t.sha256!==void 0&&e.push({algorithmId:()=>iv.SHA256,checksumConstructor:()=>t.sha256}),t.md5!=null&&e.push({algorithmId:()=>iv.MD5,checksumConstructor:()=>t.md5}),{addChecksumAlgorithm(r){e.push(r)},checksumAlgorithms(){return e}}},eze=t=>{let e={};return t.checksumAlgorithms().forEach(r=>{e[r.algorithmId()]=r.checksumConstructor()}),e},tze=t=>Q1e(t),rze=t=>eze(t),Rj;(function(t){t[t.HEADER=0]="HEADER",t[t.TRAILER=1]="TRAILER"})(Rj||(Rj={}));var nze="__smithy_context",Ij;(function(t){t.PROFILE="profile",t.SSO_SESSION="sso-session",t.SERVICES="services"})(Ij||(Ij={}));var Aj;(function(t){t.HTTP_0_9="http/0.9",t.HTTP_1_0="http/1.0",t.TDS_8_0="tds/8.0"})(Aj||(Aj={}));Gi.AlgorithmId=iv;Gi.EndpointURLScheme=$j;Gi.FieldPosition=Rj;Gi.HttpApiKeyAuthLocation=Ej;Gi.HttpAuthLocation=xj;Gi.IniSectionType=Ij;Gi.RequestHandlerProtocol=Aj;Gi.SMITHY_CONTEXT_KEY=nze;Gi.getDefaultClientConfiguration=tze;Gi.resolveDefaultRuntimeConfig=rze});var Pj,Bt,UJ=_(()=>{Pj=Vt(js()),Bt=t=>t[Pj.SMITHY_CONTEXT_KEY]||(t[Pj.SMITHY_CONTEXT_KEY]={})});function Se(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var kj=_(()=>{});function oze(t){return Object.keys(t).reduce((e,r)=>{let o=t[r];return{...e,[r]:Array.isArray(o)?[...o]:o}},{})}var We,LJ=_(()=>{We=class t{method;protocol;hostname;port;path;query;headers;username;password;fragment;body;constructor(e){this.method=e.method||"GET",this.hostname=e.hostname||"localhost",this.port=e.port,this.query=e.query||{},this.headers=e.headers||{},this.body=e.body,this.protocol=e.protocol?e.protocol.slice(-1)!==":"?`${e.protocol}:`:e.protocol:"https:",this.path=e.path?e.path.charAt(0)!=="/"?`/${e.path}`:e.path:"/",this.username=e.username,this.password=e.password,this.fragment=e.fragment}static clone(e){let r=new t({...e,headers:{...e.headers}});return r.query&&(r.query=oze(r.query)),r}static isInstance(e){if(!e)return!1;let r=e;return"method"in r&&"protocol"in r&&"hostname"in r&&"path"in r&&typeof r.query=="object"&&typeof r.headers=="object"}clone(){return t.clone(this)}}});var Lr,jJ=_(()=>{Lr=class{statusCode;reason;headers;body;constructor(e){this.statusCode=e.statusCode,this.reason=e.reason,this.headers=e.headers||{},this.body=e.body}static isInstance(e){if(!e)return!1;let r=e;return typeof r.statusCode=="number"&&typeof r.headers=="object"}}});var ize,Hi,FJ=_(()=>{ize=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),Hi=(t,e=!1)=>{if(!e)return ize.test(t);let r=t.split(".");for(let o of r)if(!Hi(o))return!1;return!0}});function sv(t){return/^[a-z0-9][a-z0-9.-]*[a-z0-9]$/.test(t)}var qJ=_(()=>{});var jt,VJ=_(()=>{jt=t=>{if(typeof t=="function")return t;let e=Promise.resolve(t);return()=>e}});function av(t){let e={};if(t=t.replace(/^\?/,""),t)for(let r of t.split("&")){let[o,n=null]=r.split("=");o=decodeURIComponent(o),n&&(n=decodeURIComponent(n)),o in e?Array.isArray(e[o])?e[o].push(n):e[o]=[e[o],n]:e[o]=n}return e}var Tj=_(()=>{});var nn,Cj=_(()=>{Tj();nn=t=>{if(typeof t=="string")return nn(new URL(t));let{hostname:e,pathname:r,port:o,protocol:n,search:i}=t,s;return i&&(s=av(i)),{hostname:e,port:o?parseInt(o):void 0,protocol:n,path:r,query:s}}});var To,GJ=_(()=>{kj();Cj();To=t=>{if(typeof t=="object"){if("url"in t){let e=nn(t.url);if(t.headers){e.headers={};for(let r in t.headers)Se(t.headers,r)&&(e.headers[r.toLowerCase()]=t.headers[r].join(", "))}return e}return t}return nn(t)}});var Pe=_(()=>{UJ();kj();LJ();jJ();FJ();qJ();VJ();Tj();Cj();GJ()});var HJ,KJ=_(()=>{HJ=t=>()=>{throw new Error(t)}});var BJ,ZJ=_(()=>{BJ=t=>()=>Promise.reject(t)});var qf,Oj=_(()=>{qf=()=>{let t=new WeakSet;return(e,r)=>{if(typeof r=="object"&&r!==null){if(t.has(r))return"[Circular]";t.add(r)}return r}}});var WJ,JJ=_(()=>{WJ=t=>new Promise(e=>setTimeout(e,t*1e3))});var Z$,Co,XJ,W$=_(()=>{Oj();Z$={minDelay:2,maxDelay:120};(function(t){t.ABORTED="ABORTED",t.FAILURE="FAILURE",t.SUCCESS="SUCCESS",t.RETRY="RETRY",t.TIMEOUT="TIMEOUT"})(Co||(Co={}));XJ=t=>{if(t.state===Co.ABORTED){let e=new Error(`${JSON.stringify({...t,reason:"Request was aborted"},qf())}`);throw e.name="AbortError",e}else if(t.state===Co.TIMEOUT){let e=new Error(`${JSON.stringify({...t,reason:"Waiter has timed out"},qf())}`);throw e.name="TimeoutError",e}else if(t.state!==Co.SUCCESS)throw new Error(`${JSON.stringify(t,qf())}`);return t}});var YJ,sze,aze,cze,uze,QJ=_(()=>{Oj();JJ();W$();YJ=async({minDelay:t,maxDelay:e,maxWaitTime:r,abortController:o,client:n,abortSignal:i},s,a)=>{let c={},[u,l]=[t*1e3,e*1e3],d=0,p=Date.now()+r*1e3,f=Date.now()+6e4,h=!1;for(;;){if(d>0){let b=cze(u,l,d,p);if(o?.signal?.aborted||i?.aborted){let S="AbortController signal aborted.";return c[S]|=0,c[S]+=1,{state:Co.ABORTED,observedResponses:c}}if(Date.now()+b>p)return{state:Co.TIMEOUT,observedResponses:c};await WJ(b/1e3)}let{state:y,reason:w}=await a(n,s);if(w){let b=aze(w);c[b]|=0,c[b]+=1}if(y!==Co.RETRY)return{state:y,reason:w,final:w,observedResponses:c};d+=1,!h&&Date.now()>=f&&(sze(c,n),h=!0)}},sze=(t={},e)=>{let r=Object.keys(t),o=0,n=0;for(let a of r){let c=t[a]|0;o=Math.max(c,o),a.startsWith("403:")&&(n+=c)}let i=e?.config?.logger,s=typeof i?.warn=="function"&&!i.constructor?.name?.includes?.("NoOpLogger")?i:console;(n>=3||r[r.length-1]?.startsWith("403:"))&&s.warn("@smithy/util-waiter WARN - 403 status code encountered during waiter polling.")},aze=t=>{let e=t?.$response?.statusCode??t?.$metadata?.httpStatusCode;return t?.$responseBodyText?`${e?e+": ":""}Deserialization error for body: ${t.$responseBodyText}`:e?t?.$response||t?.message?`${e??"Unknown"}: ${t?.message}`:`${e}: OK`:String(t?.message??JSON.stringify(t,qf())??"Unknown")},cze=(t,e,r,o)=>{let n=Math.log(e/t)/Math.log(2)+1;if(r>n)return e;let i=t*2**(r-1),s=Math.min(i,e),a=uze(t,s);if(Date.now()+a>o){let c=o-Date.now();return Math.max(0,c-500)}return a},uze=(t,e)=>t+Math.random()*(e-t)});var e7,t7=_(()=>{e7=t=>{if(t.maxWaitTime<=0)throw new Error("WaiterConfiguration.maxWaitTime must be greater than 0");if(t.minDelay<=0)throw new Error("WaiterConfiguration.minDelay must be greater than 0");if(t.maxDelay<=0)throw new Error("WaiterConfiguration.maxDelay must be greater than 0");if(t.maxWaitTime<=t.minDelay)throw new Error(`WaiterConfiguration.maxWaitTime [${t.maxWaitTime}] must be greater than WaiterConfiguration.minDelay [${t.minDelay}] for this waiter`);if(t.maxDelay<t.minDelay)throw new Error(`WaiterConfiguration.maxDelay [${t.maxDelay}] must be greater than WaiterConfiguration.minDelay [${t.minDelay}] for this waiter`)}});var r7,n7,o7=_(()=>{QJ();t7();W$();r7=t=>{let e,r=new Promise(o=>{e=()=>o({state:Co.ABORTED}),typeof t.addEventListener=="function"?t.addEventListener("abort",e):t.onabort=e});return{clearListener(){typeof t.removeEventListener=="function"&&t.removeEventListener("abort",e)},aborted:r}},n7=async(t,e,r)=>{let o={...Z$,...t};e7(o);let n=[YJ(o,e,r)],i=[];if(t.abortSignal){let{aborted:s,clearListener:a}=r7(t.abortSignal);i.push(a),n.push(s)}if(t.abortController?.signal){let{aborted:s,clearListener:a}=r7(t.abortController.signal);i.push(a),n.push(s)}return Promise.race(n).then(s=>{for(let a of i)a();return s})}});var Rn,i7=_(()=>{B$();Rn=class{config;middlewareStack=vu();initConfig;handlers;constructor(e){this.config=e;let{protocol:r,protocolSettings:o}=e;o&&typeof r=="function"&&(e.protocol=new r(o))}send(e,r,o){let n=typeof r!="function"?r:void 0,i=typeof r=="function"?r:o,s=n===void 0&&this.config.cacheMiddleware===!0,a;if(s){this.handlers||(this.handlers=new WeakMap);let c=this.handlers;c.has(e.constructor)?a=c.get(e.constructor):(a=e.resolveMiddleware(this.middlewareStack,this.config,n),c.set(e.constructor,a))}else delete this.handlers,a=e.resolveMiddleware(this.middlewareStack,this.config,n);if(i)a(e).then(c=>i(null,c.output),c=>i(c)).catch(()=>{});else return a(e).then(c=>c.output)}destroy(){this.config?.requestHandler?.destroy?.(),delete this.handlers}}});var ii,Dj=_(()=>{ii=t=>typeof t=="function"?t():t});var Vf,J$=_(()=>{Vf=(t,e,r,o,n)=>({name:e,namespace:t,traits:r,input:o,output:n})});var s7,Nj,a7=_(()=>{Pe();J$();s7=t=>(e,r)=>async o=>{let{response:n}=await e(o),{operationSchema:i}=Bt(r),[,s,a,c,u,l]=i??[];try{let d=await t.protocol.deserializeResponse(Vf(s,a,c,u,l),{...t,...r},n);return{response:n,output:d}}catch(d){if(Object.defineProperty(d,"$response",{value:n,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in d)){let p="Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.";try{d.message+=`
11
- `+p}catch{!r.logger||r.logger?.constructor?.name==="NoOpLogger"?console.warn(p):r.logger?.warn?.(p)}typeof d.$responseBodyText<"u"&&d.$response&&(d.$response.body=d.$responseBodyText);try{if(Lr.isInstance(n)){let{headers:f={},statusCode:h}=n,y=Object.entries(f);d.$metadata={httpStatusCode:h,requestId:Nj(/^x-[\w-]+-request-?id$/,y),extendedRequestId:Nj(/^x-[\w-]+-id-2$/,y),cfId:Nj(/^x-[\w-]+-cf-id$/,y)}}}catch{}}throw d}},Nj=(t,e)=>(e.find(([r])=>r.match(t))||[void 0,void 0])[1]});var c7,u7=_(()=>{Pe();J$();c7=t=>(e,r)=>async o=>{let{operationSchema:n}=Bt(r),[,i,s,a,c,u]=n??[],l=r.endpointV2?async()=>To(r.endpointV2):t.endpoint,d=await t.protocol.serializeRequest(Vf(i,s,a,c,u),o.input,{...t,...r,endpoint:l});return e({...o,request:d})}});function Fs(t){return{applyToStack:e=>{e.add(c7(t),Mj),e.add(s7(t),zj),t.protocol.setSerdeContext(t)}}}var zj,Mj,l7=_(()=>{a7();u7();zj={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},Mj={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0}});var dr,wu=_(()=>{dr=class{name;namespace;traits;static assign(e,r){return Object.assign(e,r)}static[Symbol.hasInstance](e){let r=this.prototype.isPrototypeOf(e);return!r&&typeof e=="object"&&e!==null?e.symbol===this.symbol:r}getName(){return this.namespace+"#"+this.name}}});var cv,d7,p7=_(()=>{wu();cv=class t extends dr{static symbol=Symbol.for("@smithy/lis");valueSchema;symbol=t.symbol},d7=(t,e,r,o)=>dr.assign(new cv,{name:e,namespace:t,traits:r,valueSchema:o})});var uv,f7,m7=_(()=>{wu();uv=class t extends dr{static symbol=Symbol.for("@smithy/map");keySchema;valueSchema;symbol=t.symbol},f7=(t,e,r,o,n)=>dr.assign(new uv,{name:e,namespace:t,traits:r,keySchema:o,valueSchema:n})});var lv,h7,g7=_(()=>{wu();lv=class t extends dr{static symbol=Symbol.for("@smithy/ope");input;output;symbol=t.symbol},h7=(t,e,r,o,n)=>dr.assign(new lv,{name:e,namespace:t,traits:r,input:o,output:n})});var gd,y7,Uj=_(()=>{wu();gd=class t extends dr{static symbol=Symbol.for("@smithy/str");memberNames;memberList;symbol=t.symbol},y7=(t,e,r,o,n)=>dr.assign(new gd,{name:e,namespace:t,traits:r,memberNames:o,memberList:n})});var dv,v7,w7=_(()=>{wu();Uj();dv=class t extends gd{static symbol=Symbol.for("@smithy/err");ctor;symbol=t.symbol},v7=(t,e,r,o,n,i)=>dr.assign(new dv,{name:e,namespace:t,traits:r,memberNames:o,memberList:n,ctor:null})});function Ki(t){if(typeof t=="object")return t;if(t=t|0,pv[t])return pv[t];let e={},r=0;for(let o of["httpLabel","idempotent","idempotencyToken","sensitive","httpPayload","httpResponseCode","httpQueryParams"])(t>>r++&1)===1&&(e[o]=1);return pv[t]=e}var pv,Lj=_(()=>{pv=[]});function mv(t,e){if(t instanceof B)return Object.assign(t,{memberName:e,_isMemberSchema:!0});let r=B;return new r(t,e)}var fv,hv,gv,B,jj,Fj,_7=_(()=>{Dj();Lj();fv={it:Symbol.for("@smithy/nor-struct-it"),ns:Symbol.for("@smithy/ns")},hv=[],gv={},B=class t{ref;memberName;static symbol=Symbol.for("@smithy/nor");symbol=t.symbol;name;schema;_isMemberSchema;traits;memberTraits;normalizedTraits;constructor(e,r){this.ref=e,this.memberName=r;let o=[],n=e,i=e;for(this._isMemberSchema=!1;jj(n);)o.push(n[1]),n=n[0],i=ii(n),this._isMemberSchema=!0;if(o.length>0){this.memberTraits={};for(let s=o.length-1;s>=0;--s){let a=o[s];Object.assign(this.memberTraits,Ki(a))}}else this.memberTraits=0;if(i instanceof t){let s=this.memberTraits;Object.assign(this,i),this.memberTraits=Object.assign({},s,i.getMemberTraits(),this.getMemberTraits()),this.normalizedTraits=void 0,this.memberName=r??i.memberName;return}if(this.schema=ii(i),Fj(this.schema)?(this.name=`${this.schema[1]}#${this.schema[2]}`,this.traits=this.schema[3]):(this.name=this.memberName??String(i),this.traits=0),this._isMemberSchema&&!r)throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(!0)} missing member name.`)}static[Symbol.hasInstance](e){let r=this.prototype.isPrototypeOf(e);return!r&&typeof e=="object"&&e!==null?e.symbol===this.symbol:r}static of(e){let r=typeof e=="function"||typeof e=="object"&&e!==null;if(typeof e=="number"){if(hv[e])return hv[e]}else if(typeof e=="string"){if(gv[e])return gv[e]}else if(r&&e[fv.ns])return e[fv.ns];let o=ii(e);if(o instanceof t)return o;if(jj(o)){let[i,s]=o;if(i instanceof t)return Object.assign(i.getMergedTraits(),Ki(s)),i;throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(e,null,2)}.`)}let n=new t(o);return r?e[fv.ns]=n:typeof o=="string"?gv[o]=n:typeof o=="number"?hv[o]=n:n}getSchema(){let e=this.schema;return Array.isArray(e)&&e[0]===0?e[4]:e}getName(e=!1){let{name:r}=this;return!e&&r&&r.includes("#")?r.split("#")[1]:r||void 0}getMemberName(){return this.memberName}isMemberSchema(){return this._isMemberSchema}isListSchema(){let e=this.getSchema();return typeof e=="number"?e>=64&&e<128:e[0]===1}isMapSchema(){let e=this.getSchema();return typeof e=="number"?e>=128&&e<=255:e[0]===2}isStructSchema(){let e=this.getSchema();if(typeof e!="object")return!1;let r=e[0];return r===3||r===-3||r===4}isUnionSchema(){let e=this.getSchema();return typeof e!="object"?!1:e[0]===4}isBlobSchema(){let e=this.getSchema();return e===21||e===42}isTimestampSchema(){let e=this.getSchema();return typeof e=="number"&&e>=4&&e<=7}isUnitSchema(){return this.getSchema()==="unit"}isDocumentSchema(){return this.getSchema()===15}isStringSchema(){return this.getSchema()===0}isBooleanSchema(){return this.getSchema()===2}isNumericSchema(){return this.getSchema()===1}isBigIntegerSchema(){return this.getSchema()===17}isBigDecimalSchema(){return this.getSchema()===19}isStreaming(){let{streaming:e}=this.getMergedTraits();return!!e||this.getSchema()===42}isIdempotencyToken(){return!!this.getMergedTraits().idempotencyToken}getMergedTraits(){return this.normalizedTraits??(this.normalizedTraits={...this.getOwnTraits(),...this.getMemberTraits()})}getMemberTraits(){return Ki(this.memberTraits)}getOwnTraits(){return Ki(this.traits)}getKeySchema(){let[e,r]=[this.isDocumentSchema(),this.isMapSchema()];if(!e&&!r)throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(!0)}`);let o=this.getSchema(),n=e?15:o[4]??0;return mv([n,0],"key")}getValueSchema(){let e=this.getSchema(),[r,o,n]=[this.isDocumentSchema(),this.isMapSchema(),this.isListSchema()],i=typeof e=="number"?63&e:e&&typeof e=="object"&&(o||n)?e[3+e[0]]:r?15:void 0;if(i!=null)return mv([i,0],o?"value":"member");throw new Error(`@smithy/core/schema - ${this.getName(!0)} has no value member.`)}getMemberSchema(e){let r=this.getSchema();if(this.isStructSchema()&&r[4].includes(e)){let o=r[4].indexOf(e),n=r[5][o];return mv(jj(n)?n:[n,0],e)}if(this.isDocumentSchema())return mv([15,0],e);throw new Error(`@smithy/core/schema - ${this.getName(!0)} has no member=${e}.`)}getMemberSchemas(){let e={};try{for(let[r,o]of this.structIterator())e[r]=o}catch{}return e}getEventStreamMember(){if(this.isStructSchema()){for(let[e,r]of this.structIterator())if(r.isStreaming()&&r.isStructSchema())return e}return""}*structIterator(){if(this.isUnitSchema())return;if(!this.isStructSchema())throw new Error("@smithy/core/schema - cannot iterate non-struct schema.");let e=this.getSchema(),r=e[4].length,o=e[fv.it];if(o&&r===o.length){yield*o;return}o=Array(r);for(let n=0;n<r;++n){let i=e[4][n],s=mv([e[5][n],0],i);yield o[n]=[i,s]}e[fv.it]=o}};jj=t=>Array.isArray(t)&&t.length===2,Fj=t=>Array.isArray(t)&&t.length>=5});var Gf,b7,S7,x7=_(()=>{wu();Gf=class t extends dr{static symbol=Symbol.for("@smithy/sim");schemaRef;symbol=t.symbol},b7=(t,e,r,o)=>dr.assign(new Gf,{name:e,namespace:t,traits:o,schemaRef:r}),S7=(t,e,r,o)=>dr.assign(new Gf,{name:e,namespace:t,traits:r,schemaRef:o})});var E7,$7=_(()=>{E7={BLOB:21,STREAMING_BLOB:42,BOOLEAN:2,STRING:0,NUMERIC:1,BIG_INTEGER:17,BIG_DECIMAL:19,DOCUMENT:15,TIMESTAMP_DEFAULT:4,TIMESTAMP_DATE_TIME:5,TIMESTAMP_HTTP_DATE:6,TIMESTAMP_EPOCH_SECONDS:7,LIST_MODIFIER:64,MAP_MODIFIER:128}});var Zt,R7=_(()=>{Zt=class t{namespace;schemas;exceptions;static registries=new Map;constructor(e,r=new Map,o=new Map){this.namespace=e,this.schemas=r,this.exceptions=o,t.registries.has(e)||t.registries.set(e,this)}static for(e){return t.registries.get(e)??new t(e)}copyFrom(e){let{schemas:r,exceptions:o}=this;for(let[n,i]of e.schemas)r.has(n)||r.set(n,i);for(let[n,i]of e.exceptions)o.has(n)||o.set(n,i)}register(e,r){let o=this.normalizeShapeId(e);for(let n of[this,t.for(o.split("#")[0])])n.schemas.has(o)||n.schemas.set(o,r)}getSchema(e){let r=this.normalizeShapeId(e);if(!this.schemas.has(r)){if(!e.includes("#")){let o="#"+e,n=[];for(let[i,s]of this.schemas.entries())i.endsWith(o)&&n.push(s);if(n.length===1)return n[0]}throw new Error(`@smithy/core/schema - schema not found for ${r}`)}return this.schemas.get(r)}registerError(e,r){let o=e,n=o[1],i=n+"#"+o[2];r.hasOwnProperty?.("shapeId")||(r.shapeId=i);for(let s of[this,t.for(n)])!s.schemas.has(i)&&!s.exceptions.has(o)&&(s.schemas.set(i,o),s.exceptions.set(o,r))}getErrorCtor(e){let r=e;return this.exceptions.has(r)?this.exceptions.get(r):t.for(r[1]).exceptions.get(r)}getBaseException(){for(let e of this.exceptions.keys())if(Array.isArray(e)){let[,r,o]=e,n=r+"#"+o;if(n.startsWith("smithy.ts.sdk.synthetic.")&&n.endsWith("ServiceException"))return e}}find(e){for(let r of this.schemas.values())if(e(r))return r}clear(){this.schemas.clear(),this.exceptions.clear()}normalizeShapeId(e){return e.includes("#")?e:this.namespace+"#"+e}}});var qj={};Ht(qj,{ErrorSchema:()=>dv,ListSchema:()=>cv,MapSchema:()=>uv,NormalizedSchema:()=>B,OperationSchema:()=>lv,SCHEMA:()=>E7,Schema:()=>dr,SimpleSchema:()=>Gf,StructureSchema:()=>gd,TypeRegistry:()=>Zt,deref:()=>ii,deserializerMiddlewareOption:()=>zj,error:()=>v7,getSchemaSerdePlugin:()=>Fs,isStaticSchema:()=>Fj,list:()=>d7,map:()=>f7,op:()=>h7,operation:()=>Vf,serializerMiddlewareOption:()=>Mj,sim:()=>b7,simAdapter:()=>S7,simpleSchemaCacheN:()=>hv,simpleSchemaCacheS:()=>gv,struct:()=>y7,traitsCache:()=>pv,translateTraits:()=>Ki});var rt=_(()=>{Dj();l7();p7();m7();g7();J$();w7();_7();wu();x7();Uj();$7();Lj();R7()});function Hf(t,e){if(e==null)return e;let r=B.of(t);if(r.getMergedTraits().sensitive)return Vj;if(r.isListSchema()){if(!!r.getValueSchema().getMergedTraits().sensitive)return Vj}else if(r.isMapSchema()){if(!!r.getKeySchema().getMergedTraits().sensitive||!!r.getValueSchema().getMergedTraits().sensitive)return Vj}else if(r.isStructSchema()&&typeof e=="object"){let o=e,n={};for(let[i,s]of r.structIterator())o[i]!=null&&(n[i]=Hf(s,o[i]));return n}return e}var Vj,Gj=_(()=>{rt();Vj="***SensitiveInformation***"});var Hj,Wn,Kj,Bj=_(()=>{Hj=Vt(js());B$();Gj();Wn=class{middlewareStack=vu();schema;static classBuilder(){return new Kj}resolveMiddlewareWithContext(e,r,o,{middlewareFn:n,clientName:i,commandName:s,inputFilterSensitiveLog:a,outputFilterSensitiveLog:c,smithyContext:u,additionalContext:l,CommandCtor:d}){for(let S of n.bind(this)(d,e,r,o))this.middlewareStack.use(S);let p=e.concat(this.middlewareStack),{logger:f}=r,h=l[Hj.SMITHY_CONTEXT_KEY],y={logger:f,clientName:i,commandName:s,inputFilterSensitiveLog:a,outputFilterSensitiveLog:c,...l,[Hj.SMITHY_CONTEXT_KEY]:{...h,commandInstance:this,...u,...o?.metricsRecorder===void 0?{}:{metricsRecorder:o.metricsRecorder}}},{requestHandler:w}=r,b=o??{};return b.metricsRecorder&&(b={...b},delete b.metricsRecorder),u.eventStream&&(b={isEventStream:!0,...b}),p.resolve(S=>w.handle(S.request,b),y)}},Kj=class{_init=()=>{};_ep={};_middlewareFn=()=>[];_commandName="";_clientName="";_additionalContext={};_smithyContext={};_inputFilterSensitiveLog=void 0;_outputFilterSensitiveLog=void 0;_serializer=null;_deserializer=null;_operationSchema;init(e){this._init=e}ep(e){return this._ep=e,this}m(e){return this._middlewareFn=e,this}s(e,r,o={}){return this._smithyContext={service:e,operation:r,...o},this}c(e={}){return this._additionalContext=e,this}n(e,r){return this._clientName=e,this._commandName=r,this}f(e=o=>o,r=o=>o){return this._inputFilterSensitiveLog=e,this._outputFilterSensitiveLog=r,this}ser(e){return this._serializer=e,this}de(e){return this._deserializer=e,this}sc(e){return this._operationSchema=e,this._smithyContext.operationSchema=e,this}build(){let e=this,r;return r=class extends Wn{input;static getEndpointParameterInstructions(){return e._ep}constructor(...[o]){super(),this.input=o??{},e._init(this),this.schema=e._operationSchema}resolveMiddleware(o,n,i){let s=e._operationSchema,a=s?.[4]??s?.input,c=s?.[5]??s?.output;return this.resolveMiddlewareWithContext(o,n,i,{CommandCtor:r,middlewareFn:e._middlewareFn,clientName:e._clientName,commandName:e._commandName,inputFilterSensitiveLog:e._inputFilterSensitiveLog??(s?Hf.bind(null,a):u=>u),outputFilterSensitiveLog:e._outputFilterSensitiveLog??(s?Hf.bind(null,c):u=>u),smithyContext:e._smithyContext,additionalContext:e._additionalContext})}serialize=e._serializer;deserialize=e._deserializer}}}});var I7,A7=_(()=>{I7="***SensitiveInformation***"});var qs,P7=_(()=>{qs=(t,e,r)=>{for(let[i,s]of Object.entries(t)){let a=async function(u,l,d){let p=new s(u);if(typeof l=="function")this.send(p,l);else if(typeof d=="function"){if(typeof l!="object")throw new Error(`Expected http options but got ${typeof l}`);this.send(p,l||{},d)}else return this.send(p,l)},c=(i[0].toLowerCase()+i.slice(1)).replace(/Command$/,"");e.prototype[c]=a}let{paginators:o={},waiters:n={}}=r??{};for(let[i,s]of Object.entries(o))e.prototype[i]===void 0&&(e.prototype[i]=function(a={},c,...u){return s({...c,client:this},a,...u)});for(let[i,s]of Object.entries(n))e.prototype[i]===void 0&&(e.prototype[i]=async function(a={},c,...u){let l=c;return typeof c=="number"&&(l={maxWaitTime:c}),s({...l,client:this},a,...u)})}});var si,yd,Zj=_(()=>{si=class t extends Error{static shapeId="smithy.ts.sdk.synthetic.nonamespace.client#ServiceException";$fault;$response;$retryable;$metadata;constructor(e){super(e.message),Object.setPrototypeOf(this,Object.getPrototypeOf(this).constructor.prototype),this.name=e.name,this.$fault=e.$fault,this.$metadata=e.$metadata}static isInstance(e){if(!e)return!1;let r=e;return t.prototype.isPrototypeOf(r)||!!r.$fault&&!!r.$metadata&&(r.$fault==="client"||r.$fault==="server")}static[Symbol.hasInstance](e){if(!e)return!1;let r=e;if(this===t)return t.isInstance(e);if(t.isInstance(e)){if(this.prototype.isPrototypeOf(e))return!0;let o=Object.prototype.hasOwnProperty.call(this,"shapeId")?this.shapeId:void 0,n=!1;if(o){let s=Object.getPrototypeOf(r);for(;s&&s!==Object.prototype;){let a=s.constructor,c=a!==t&&Object.prototype.hasOwnProperty.call(a,"shapeId")?a?.shapeId:void 0;if(c&&(n=!0,c===o))return!0;s=Object.getPrototypeOf(s)}}if(o&&n)return!1;let i=this.name;if(i&&i.length>=6){if(r.name===i)return!0;let s=Object.getPrototypeOf(r);for(;s&&s!==Object.prototype;){let a=s.constructor?.name;if(a&&a!=="Error"&&a===i)return!0;s=Object.getPrototypeOf(s)}}}return!1}},yd=(t,e={})=>{Object.entries(e).filter(([,o])=>o!==void 0).forEach(([o,n])=>{(t[o]==null||t[o]==="")&&(t[o]=n)});let r=t.message||t.Message||"UnknownError";return t.message=r,delete t.Message,t}});var Wj,k7,lze,T7=_(()=>{Zj();Wj=({output:t,parsedBody:e,exceptionCtor:r,errorCode:o})=>{let n=lze(t),i=n.httpStatusCode?n.httpStatusCode+"":void 0,s=new r({name:e?.code||e?.Code||o||i||"UnknownError",$fault:"client",$metadata:n});throw yd(s,e)},k7=t=>({output:e,parsedBody:r,errorCode:o})=>{Wj({output:e,parsedBody:r,exceptionCtor:t,errorCode:o})},lze=t=>({httpStatusCode:t.statusCode,requestId:t.headers["x-amzn-requestid"]??t.headers["x-amzn-request-id"]??t.headers["x-amz-request-id"],extendedRequestId:t.headers["x-amz-id-2"],cfId:t.headers["x-amz-cf-id"]})});var Vs,C7=_(()=>{Vs=t=>{switch(t){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region":return{retryMode:"standard",connectionTimeout:3100};case"mobile":return{retryMode:"standard",connectionTimeout:3e4};default:return{}}}});var O7,Gs,D7=_(()=>{O7=!1,Gs=t=>{t&&!O7&&parseInt(t.substring(1,t.indexOf(".")))<16&&(O7=!0)}});var vd,N7,X$,Y$,Jj=_(()=>{Pe();vd=Vt(js()),N7=Object.values(vd.AlgorithmId),X$=t=>{let e=[];for(let r in vd.AlgorithmId){if(!Se(vd.AlgorithmId,r))continue;let o=vd.AlgorithmId[r];t[o]!==void 0&&e.push({algorithmId:()=>o,checksumConstructor:()=>t[o]})}for(let[r,o]of Object.entries(t.checksumAlgorithms??{}))e.push({algorithmId:()=>r,checksumConstructor:()=>o});return{addChecksumAlgorithm(r){t.checksumAlgorithms=t.checksumAlgorithms??{};let o=r.algorithmId(),n=r.checksumConstructor();N7.includes(o)?t.checksumAlgorithms[o.toUpperCase()]=n:t.checksumAlgorithms[o]=n,e.push(r)},checksumAlgorithms(){return e}}},Y$=t=>{let e={};return t.checksumAlgorithms().forEach(r=>{let o=r.algorithmId();N7.includes(o)&&(e[o]=r.checksumConstructor())}),e}});var Q$,eR,Xj=_(()=>{Q$=t=>({setRetryStrategy(e){t.retryStrategy=e},retryStrategy(){return t.retryStrategy}}),eR=t=>{let e={};return e.retryStrategy=t.retryStrategy(),e}});var Bi,z7,Hs,M7=_(()=>{Jj();Xj();Bi=t=>Object.assign(X$(t),Q$(t)),z7=Bi,Hs=t=>Object.assign(Y$(t),eR(t))});var U7,L7=_(()=>{U7=t=>Array.isArray(t)?t:[t]});var wd,j7=_(()=>{Pe();wd=t=>{let e="#text";for(let r in t)Se(t,r)&&(t[r][e]!==void 0?t[r]=t[r][e]:typeof t[r]=="object"&&t[r]!==null&&(t[r]=wd(t[r])));return t}});var F7,q7=_(()=>{F7=t=>t!=null});var mo,V7=_(()=>{mo=class{trace(){}debug(){}info(){}warn(){}error(){}}});function Yj(t,e,r){let o,n,i;if(typeof e>"u"&&typeof r>"u")o={},i=t;else{if(o=t,typeof e=="function")return n=e,i=r,dze(o,n,i);i=e}for(let s in i)if(Se(i,s)){if(!Array.isArray(i[s])){o[s]=i[s];continue}K7(o,null,i,s)}return o}var G7,H7,dze,K7,pze,fze,B7=_(()=>{Pe();G7=t=>{let e={};for(let[r,o]of Object.entries(t||{}))e[r]=[,o];return e},H7=(t,e)=>{let r={};for(let o in e)Se(e,o)&&K7(r,t,e,o);return r},dze=(t,e,r)=>Yj(t,Object.entries(r).reduce((o,[n,i])=>(Array.isArray(i)?o[n]=i:typeof i=="function"?o[n]=[e,i()]:o[n]=[e,i],o),{})),K7=(t,e,r,o)=>{if(e!==null){let s=r[o];typeof s=="function"&&(s=[,s]);let[a=pze,c=fze,u=o]=s;(typeof a=="function"&&a(e[u])||typeof a!="function"&&a)&&(t[o]=c(e[u]));return}let[n,i]=r[o];if(typeof i=="function"){let s,a=n===void 0&&(s=i())!=null,c=typeof n=="function"&&!!n(void 0)||typeof n!="function"&&!!n;a?t[o]=s:c&&(t[o]=i())}else{let s=n===void 0&&i!=null,a=typeof n=="function"&&!!n(i)||typeof n!="function"&&!!n;(s||a)&&(t[o]=i)}},pze=t=>t!=null,fze=t=>t});var Z7,W7,J7=_(()=>{Z7=t=>{if(t!==t)return"NaN";switch(t){case 1/0:return"Infinity";case-1/0:return"-Infinity";default:return t}},W7=t=>t.toISOString().replace(".000Z","Z")});var tR,X7=_(()=>{Pe();tR=t=>{if(t==null)return{};if(Array.isArray(t))return t.filter(e=>e!=null).map(tR);if(typeof t=="object"){let e={};for(let r in t)Se(t,r)&&t[r]!=null&&(e[r]=tR(t[r]));return e}return t}});function Ks(t,e,r,o){return function(i,s,a,c,u={}){let l=Object.assign({},t,i);return Wn.classBuilder().ep(l).m(function(d,p,f,h){let y=s.call(this,d,p,f,h);return y.unshift(o(f,d.getEndpointParameterInstructions())),y}).s(e,a,u).n(r,a.charAt(0).toUpperCase()+a.slice(1)+"Command").sc(c).build()}}var Y7=_(()=>{Bj()});var Kf={};Ht(Kf,{AlgorithmId:()=>vd.AlgorithmId,Client:()=>Rn,Command:()=>Wn,NoOpLogger:()=>mo,SENSITIVE_STRING:()=>I7,ServiceException:()=>si,WaiterState:()=>Co,_json:()=>tR,checkExceptions:()=>XJ,constructStack:()=>vu,convertMap:()=>G7,createAggregatedClient:()=>qs,createWaiter:()=>n7,decorateServiceException:()=>yd,emitWarningIfUnsupportedVersion:()=>Gs,getArrayIfSingleItem:()=>U7,getChecksumConfiguration:()=>X$,getDefaultClientConfiguration:()=>z7,getDefaultExtensionConfiguration:()=>Bi,getRetryConfiguration:()=>Q$,getSmithyContext:()=>Bt,getValueFromTextNode:()=>wd,invalidFunction:()=>HJ,invalidProvider:()=>BJ,isSerializableHeaderValue:()=>F7,loadConfigsForDefaultMode:()=>Vs,makeBuilder:()=>Ks,map:()=>Yj,normalizeProvider:()=>jt,resolveChecksumRuntimeConfig:()=>Y$,resolveDefaultRuntimeConfig:()=>Hs,resolveRetryRuntimeConfig:()=>eR,schemaLogFilter:()=>Hf,serializeDateTime:()=>W7,serializeFloat:()=>Z7,take:()=>H7,throwDefaultError:()=>Wj,waiterServiceDefaults:()=>Z$,withBaseException:()=>k7});var ve=_(()=>{B$();Pe();Pe();KJ();ZJ();o7();W$();i7();Bj();A7();P7();T7();C7();D7();Zj();M7();Jj();Xj();L7();j7();q7();V7();B7();Gj();J7();X7();Y7()});var rR,Qj=_(()=>{rR=t=>typeof ArrayBuffer=="function"&&t instanceof ArrayBuffer||Object.prototype.toString.call(t)==="[object ArrayBuffer]"});var Zi,_u,bu=_(()=>{Qj();Zi=(t,e=0,r=t.byteLength-e)=>{if(!rR(t))throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof t} (${t})`);return Buffer.from(t,e,r)},_u=(t,e)=>{if(typeof t!="string")throw new TypeError(`The "input" argument must be of type string. Received type ${typeof t} (${t})`);return e?Buffer.from(t,e):Buffer.from(t)}});var mze,pr,Q7=_(()=>{bu();mze=/^[A-Za-z0-9+/]*={0,2}$/,pr=t=>{if(t.length*3%4!==0)throw new TypeError("Incorrect padding on base64 string.");if(!mze.exec(t))throw new TypeError("Invalid base64 string.");let e=_u(t,"base64");return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}});var Tr,nR=_(()=>{bu();Tr=t=>{let e=_u(t,"utf8");return new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT)}});var Wt,e4=_(()=>{bu();nR();Wt=t=>{let e;if(typeof t=="string"?e=Tr(t):e=t,typeof e!="object"||typeof e.byteOffset!="number"||typeof e.byteLength!="number")throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");return Zi(e.buffer,e.byteOffset,e.byteLength).toString("base64")}});function eX(t,e,r,o){return class oR extends Uint8Array{static fromString(i,s="utf-8"){if(typeof i=="string")return s==="base64"?oR.mutate(o(i)):oR.mutate(e(i));throw new Error(`Unsupported conversion from ${typeof i} to Uint8ArrayBlobAdapter.`)}static mutate(i){return Object.setPrototypeOf(i,oR.prototype),i}transformToString(i="utf-8"){return i==="base64"?r(this):t(this)}}}var tX=_(()=>{});var ur,rX=_(()=>{bu();ur=t=>{if(typeof t=="string")return t;if(typeof t!="object"||typeof t.byteOffset!="number"||typeof t.byteLength!="number")throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return Zi(t.buffer,t.byteOffset,t.byteLength).toString("utf8")}});function nX(t){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?()=>crypto.randomUUID():()=>{let e=new Uint8Array(16);return t(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128,In[e[0]]+In[e[1]]+In[e[2]]+In[e[3]]+"-"+In[e[4]]+In[e[5]]+"-"+In[e[6]]+In[e[7]]+"-"+In[e[8]]+In[e[9]]+"-"+In[e[10]]+In[e[11]]+In[e[12]]+In[e[13]]+In[e[14]]+In[e[15]]}}var In,oX=_(()=>{In=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"))});var iX,sX=_(()=>{iX=(t,e,r=o=>o)=>t});var aX,cX,Bf,hze,yv,Zf,uX,iR,sR,aR,t4,gze,lX,r4,dX,uR,vv,pX,lR,yze,Jf,dR,fX,mX,hX,gX,n4,yX,vX,Su,pR,cR,Wf,o4=_(()=>{Pe();aX=t=>{switch(t){case"true":return!0;case"false":return!1;default:throw new Error(`Unable to parse boolean value "${t}"`)}},cX=t=>{if(t!=null){if(typeof t=="number"){if((t===0||t===1)&&Wf.warn(cR(`Expected boolean, got ${typeof t}: ${t}`)),t===0)return!1;if(t===1)return!0}if(typeof t=="string"){let e=t.toLowerCase();if((e==="false"||e==="true")&&Wf.warn(cR(`Expected boolean, got ${typeof t}: ${t}`)),e==="false")return!1;if(e==="true")return!0}if(typeof t=="boolean")return t;throw new TypeError(`Expected boolean, got ${typeof t}: ${t}`)}},Bf=t=>{if(t!=null){if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return String(e)!==String(t)&&Wf.warn(cR(`Expected number but observed string: ${t}`)),e}if(typeof t=="number")return t;throw new TypeError(`Expected number, got ${typeof t}: ${t}`)}},hze=Math.ceil(2**127*(2-2**-23)),yv=t=>{let e=Bf(t);if(e!==void 0&&!Number.isNaN(e)&&e!==1/0&&e!==-1/0&&Math.abs(e)>hze)throw new TypeError(`Expected 32-bit float, got ${t}`);return e},Zf=t=>{if(t!=null){if(Number.isInteger(t)&&!Number.isNaN(t))return t;throw new TypeError(`Expected integer, got ${typeof t}: ${t}`)}},uX=Zf,iR=t=>t4(t,32),sR=t=>t4(t,16),aR=t=>t4(t,8),t4=(t,e)=>{let r=Zf(t);if(r!==void 0&&gze(r,e)!==r)throw new TypeError(`Expected ${e}-bit integer, got ${t}`);return r},gze=(t,e)=>{switch(e){case 32:return Int32Array.of(t)[0];case 16:return Int16Array.of(t)[0];case 8:return Int8Array.of(t)[0]}},lX=(t,e)=>{if(t==null)throw e?new TypeError(`Expected a non-null value for ${e}`):new TypeError("Expected a non-null value");return t},r4=t=>{if(t==null)return;if(typeof t=="object"&&!Array.isArray(t))return t;let e=Array.isArray(t)?"array":typeof t;throw new TypeError(`Expected object, got ${e}: ${t}`)},dX=t=>{if(t!=null){if(typeof t=="string")return t;if(["boolean","number","bigint"].includes(typeof t))return Wf.warn(cR(`Expected string, got ${typeof t}: ${t}`)),String(t);throw new TypeError(`Expected string, got ${typeof t}: ${t}`)}},uR=t=>{if(t==null)return;let e=r4(t),r=[];for(let o in e)Se(e,o)&&e[o]!=null&&r.push(o);if(r.length===0)throw new TypeError("Unions must have exactly one non-null member. None were found.");if(r.length>1)throw new TypeError(`Unions must have exactly one non-null member. Keys ${r} were not null.`);return e},vv=t=>Bf(typeof t=="string"?Jf(t):t),pX=vv,lR=t=>yv(typeof t=="string"?Jf(t):t),yze=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,Jf=t=>{let e=t.match(yze);if(e===null||e[0].length!==t.length)throw new TypeError("Expected real number, got implicit NaN");return parseFloat(t)},dR=t=>typeof t=="string"?gX(t):Bf(t),fX=dR,mX=dR,hX=t=>typeof t=="string"?gX(t):yv(t),gX=t=>{switch(t){case"NaN":return NaN;case"Infinity":return 1/0;case"-Infinity":return-1/0;default:throw new Error(`Unable to parse float value: ${t}`)}},n4=t=>Zf(typeof t=="string"?Jf(t):t),yX=n4,vX=t=>iR(typeof t=="string"?Jf(t):t),Su=t=>sR(typeof t=="string"?Jf(t):t),pR=t=>aR(typeof t=="string"?Jf(t):t),cR=t=>String(new TypeError(t).stack||t).split(`
11
+ `+p}catch{!r.logger||r.logger?.constructor?.name==="NoOpLogger"?console.warn(p):r.logger?.warn?.(p)}typeof d.$responseBodyText<"u"&&d.$response&&(d.$response.body=d.$responseBodyText);try{if(Lr.isInstance(n)){let{headers:f={},statusCode:h}=n,y=Object.entries(f);d.$metadata={httpStatusCode:h,requestId:Nj(/^x-[\w-]+-request-?id$/,y),extendedRequestId:Nj(/^x-[\w-]+-id-2$/,y),cfId:Nj(/^x-[\w-]+-cf-id$/,y)}}}catch{}}throw d}},Nj=(t,e)=>(e.find(([r])=>r.match(t))||[void 0,void 0])[1]});var c7,u7=_(()=>{Pe();J$();c7=t=>(e,r)=>async o=>{let{operationSchema:n}=Bt(r),[,i,s,a,c,u]=n??[],l=r.endpointV2?async()=>To(r.endpointV2):t.endpoint,d=await t.protocol.serializeRequest(Vf(i,s,a,c,u),o.input,{...t,...r,endpoint:l});return e({...o,request:d})}});function Fs(t){return{applyToStack:e=>{e.add(c7(t),Mj),e.add(s7(t),zj),t.protocol.setSerdeContext(t)}}}var zj,Mj,l7=_(()=>{a7();u7();zj={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},Mj={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0}});var pr,wu=_(()=>{pr=class{name;namespace;traits;static assign(e,r){return Object.assign(e,r)}static[Symbol.hasInstance](e){let r=this.prototype.isPrototypeOf(e);return!r&&typeof e=="object"&&e!==null?e.symbol===this.symbol:r}getName(){return this.namespace+"#"+this.name}}});var cv,d7,p7=_(()=>{wu();cv=class t extends pr{static symbol=Symbol.for("@smithy/lis");valueSchema;symbol=t.symbol},d7=(t,e,r,o)=>pr.assign(new cv,{name:e,namespace:t,traits:r,valueSchema:o})});var uv,f7,m7=_(()=>{wu();uv=class t extends pr{static symbol=Symbol.for("@smithy/map");keySchema;valueSchema;symbol=t.symbol},f7=(t,e,r,o,n)=>pr.assign(new uv,{name:e,namespace:t,traits:r,keySchema:o,valueSchema:n})});var lv,h7,g7=_(()=>{wu();lv=class t extends pr{static symbol=Symbol.for("@smithy/ope");input;output;symbol=t.symbol},h7=(t,e,r,o,n)=>pr.assign(new lv,{name:e,namespace:t,traits:r,input:o,output:n})});var gd,y7,Uj=_(()=>{wu();gd=class t extends pr{static symbol=Symbol.for("@smithy/str");memberNames;memberList;symbol=t.symbol},y7=(t,e,r,o,n)=>pr.assign(new gd,{name:e,namespace:t,traits:r,memberNames:o,memberList:n})});var dv,v7,w7=_(()=>{wu();Uj();dv=class t extends gd{static symbol=Symbol.for("@smithy/err");ctor;symbol=t.symbol},v7=(t,e,r,o,n,i)=>pr.assign(new dv,{name:e,namespace:t,traits:r,memberNames:o,memberList:n,ctor:null})});function Ki(t){if(typeof t=="object")return t;if(t=t|0,pv[t])return pv[t];let e={},r=0;for(let o of["httpLabel","idempotent","idempotencyToken","sensitive","httpPayload","httpResponseCode","httpQueryParams"])(t>>r++&1)===1&&(e[o]=1);return pv[t]=e}var pv,Lj=_(()=>{pv=[]});function mv(t,e){if(t instanceof B)return Object.assign(t,{memberName:e,_isMemberSchema:!0});let r=B;return new r(t,e)}var fv,hv,gv,B,jj,Fj,_7=_(()=>{Dj();Lj();fv={it:Symbol.for("@smithy/nor-struct-it"),ns:Symbol.for("@smithy/ns")},hv=[],gv={},B=class t{ref;memberName;static symbol=Symbol.for("@smithy/nor");symbol=t.symbol;name;schema;_isMemberSchema;traits;memberTraits;normalizedTraits;constructor(e,r){this.ref=e,this.memberName=r;let o=[],n=e,i=e;for(this._isMemberSchema=!1;jj(n);)o.push(n[1]),n=n[0],i=ii(n),this._isMemberSchema=!0;if(o.length>0){this.memberTraits={};for(let s=o.length-1;s>=0;--s){let a=o[s];Object.assign(this.memberTraits,Ki(a))}}else this.memberTraits=0;if(i instanceof t){let s=this.memberTraits;Object.assign(this,i),this.memberTraits=Object.assign({},s,i.getMemberTraits(),this.getMemberTraits()),this.normalizedTraits=void 0,this.memberName=r??i.memberName;return}if(this.schema=ii(i),Fj(this.schema)?(this.name=`${this.schema[1]}#${this.schema[2]}`,this.traits=this.schema[3]):(this.name=this.memberName??String(i),this.traits=0),this._isMemberSchema&&!r)throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(!0)} missing member name.`)}static[Symbol.hasInstance](e){let r=this.prototype.isPrototypeOf(e);return!r&&typeof e=="object"&&e!==null?e.symbol===this.symbol:r}static of(e){let r=typeof e=="function"||typeof e=="object"&&e!==null;if(typeof e=="number"){if(hv[e])return hv[e]}else if(typeof e=="string"){if(gv[e])return gv[e]}else if(r&&e[fv.ns])return e[fv.ns];let o=ii(e);if(o instanceof t)return o;if(jj(o)){let[i,s]=o;if(i instanceof t)return Object.assign(i.getMergedTraits(),Ki(s)),i;throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(e,null,2)}.`)}let n=new t(o);return r?e[fv.ns]=n:typeof o=="string"?gv[o]=n:typeof o=="number"?hv[o]=n:n}getSchema(){let e=this.schema;return Array.isArray(e)&&e[0]===0?e[4]:e}getName(e=!1){let{name:r}=this;return!e&&r&&r.includes("#")?r.split("#")[1]:r||void 0}getMemberName(){return this.memberName}isMemberSchema(){return this._isMemberSchema}isListSchema(){let e=this.getSchema();return typeof e=="number"?e>=64&&e<128:e[0]===1}isMapSchema(){let e=this.getSchema();return typeof e=="number"?e>=128&&e<=255:e[0]===2}isStructSchema(){let e=this.getSchema();if(typeof e!="object")return!1;let r=e[0];return r===3||r===-3||r===4}isUnionSchema(){let e=this.getSchema();return typeof e!="object"?!1:e[0]===4}isBlobSchema(){let e=this.getSchema();return e===21||e===42}isTimestampSchema(){let e=this.getSchema();return typeof e=="number"&&e>=4&&e<=7}isUnitSchema(){return this.getSchema()==="unit"}isDocumentSchema(){return this.getSchema()===15}isStringSchema(){return this.getSchema()===0}isBooleanSchema(){return this.getSchema()===2}isNumericSchema(){return this.getSchema()===1}isBigIntegerSchema(){return this.getSchema()===17}isBigDecimalSchema(){return this.getSchema()===19}isStreaming(){let{streaming:e}=this.getMergedTraits();return!!e||this.getSchema()===42}isIdempotencyToken(){return!!this.getMergedTraits().idempotencyToken}getMergedTraits(){return this.normalizedTraits??(this.normalizedTraits={...this.getOwnTraits(),...this.getMemberTraits()})}getMemberTraits(){return Ki(this.memberTraits)}getOwnTraits(){return Ki(this.traits)}getKeySchema(){let[e,r]=[this.isDocumentSchema(),this.isMapSchema()];if(!e&&!r)throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(!0)}`);let o=this.getSchema(),n=e?15:o[4]??0;return mv([n,0],"key")}getValueSchema(){let e=this.getSchema(),[r,o,n]=[this.isDocumentSchema(),this.isMapSchema(),this.isListSchema()],i=typeof e=="number"?63&e:e&&typeof e=="object"&&(o||n)?e[3+e[0]]:r?15:void 0;if(i!=null)return mv([i,0],o?"value":"member");throw new Error(`@smithy/core/schema - ${this.getName(!0)} has no value member.`)}getMemberSchema(e){let r=this.getSchema();if(this.isStructSchema()&&r[4].includes(e)){let o=r[4].indexOf(e),n=r[5][o];return mv(jj(n)?n:[n,0],e)}if(this.isDocumentSchema())return mv([15,0],e);throw new Error(`@smithy/core/schema - ${this.getName(!0)} has no member=${e}.`)}getMemberSchemas(){let e={};try{for(let[r,o]of this.structIterator())e[r]=o}catch{}return e}getEventStreamMember(){if(this.isStructSchema()){for(let[e,r]of this.structIterator())if(r.isStreaming()&&r.isStructSchema())return e}return""}*structIterator(){if(this.isUnitSchema())return;if(!this.isStructSchema())throw new Error("@smithy/core/schema - cannot iterate non-struct schema.");let e=this.getSchema(),r=e[4].length,o=e[fv.it];if(o&&r===o.length){yield*o;return}o=Array(r);for(let n=0;n<r;++n){let i=e[4][n],s=mv([e[5][n],0],i);yield o[n]=[i,s]}e[fv.it]=o}};jj=t=>Array.isArray(t)&&t.length===2,Fj=t=>Array.isArray(t)&&t.length>=5});var Gf,b7,S7,x7=_(()=>{wu();Gf=class t extends pr{static symbol=Symbol.for("@smithy/sim");schemaRef;symbol=t.symbol},b7=(t,e,r,o)=>pr.assign(new Gf,{name:e,namespace:t,traits:o,schemaRef:r}),S7=(t,e,r,o)=>pr.assign(new Gf,{name:e,namespace:t,traits:r,schemaRef:o})});var E7,$7=_(()=>{E7={BLOB:21,STREAMING_BLOB:42,BOOLEAN:2,STRING:0,NUMERIC:1,BIG_INTEGER:17,BIG_DECIMAL:19,DOCUMENT:15,TIMESTAMP_DEFAULT:4,TIMESTAMP_DATE_TIME:5,TIMESTAMP_HTTP_DATE:6,TIMESTAMP_EPOCH_SECONDS:7,LIST_MODIFIER:64,MAP_MODIFIER:128}});var Zt,R7=_(()=>{Zt=class t{namespace;schemas;exceptions;static registries=new Map;constructor(e,r=new Map,o=new Map){this.namespace=e,this.schemas=r,this.exceptions=o,t.registries.has(e)||t.registries.set(e,this)}static for(e){return t.registries.get(e)??new t(e)}copyFrom(e){let{schemas:r,exceptions:o}=this;for(let[n,i]of e.schemas)r.has(n)||r.set(n,i);for(let[n,i]of e.exceptions)o.has(n)||o.set(n,i)}register(e,r){let o=this.normalizeShapeId(e);for(let n of[this,t.for(o.split("#")[0])])n.schemas.has(o)||n.schemas.set(o,r)}getSchema(e){let r=this.normalizeShapeId(e);if(!this.schemas.has(r)){if(!e.includes("#")){let o="#"+e,n=[];for(let[i,s]of this.schemas.entries())i.endsWith(o)&&n.push(s);if(n.length===1)return n[0]}throw new Error(`@smithy/core/schema - schema not found for ${r}`)}return this.schemas.get(r)}registerError(e,r){let o=e,n=o[1],i=n+"#"+o[2];r.hasOwnProperty?.("shapeId")||(r.shapeId=i);for(let s of[this,t.for(n)])!s.schemas.has(i)&&!s.exceptions.has(o)&&(s.schemas.set(i,o),s.exceptions.set(o,r))}getErrorCtor(e){let r=e;return this.exceptions.has(r)?this.exceptions.get(r):t.for(r[1]).exceptions.get(r)}getBaseException(){for(let e of this.exceptions.keys())if(Array.isArray(e)){let[,r,o]=e,n=r+"#"+o;if(n.startsWith("smithy.ts.sdk.synthetic.")&&n.endsWith("ServiceException"))return e}}find(e){for(let r of this.schemas.values())if(e(r))return r}clear(){this.schemas.clear(),this.exceptions.clear()}normalizeShapeId(e){return e.includes("#")?e:this.namespace+"#"+e}}});var qj={};Ht(qj,{ErrorSchema:()=>dv,ListSchema:()=>cv,MapSchema:()=>uv,NormalizedSchema:()=>B,OperationSchema:()=>lv,SCHEMA:()=>E7,Schema:()=>pr,SimpleSchema:()=>Gf,StructureSchema:()=>gd,TypeRegistry:()=>Zt,deref:()=>ii,deserializerMiddlewareOption:()=>zj,error:()=>v7,getSchemaSerdePlugin:()=>Fs,isStaticSchema:()=>Fj,list:()=>d7,map:()=>f7,op:()=>h7,operation:()=>Vf,serializerMiddlewareOption:()=>Mj,sim:()=>b7,simAdapter:()=>S7,simpleSchemaCacheN:()=>hv,simpleSchemaCacheS:()=>gv,struct:()=>y7,traitsCache:()=>pv,translateTraits:()=>Ki});var rt=_(()=>{Dj();l7();p7();m7();g7();J$();w7();_7();wu();x7();Uj();$7();Lj();R7()});function Hf(t,e){if(e==null)return e;let r=B.of(t);if(r.getMergedTraits().sensitive)return Vj;if(r.isListSchema()){if(!!r.getValueSchema().getMergedTraits().sensitive)return Vj}else if(r.isMapSchema()){if(!!r.getKeySchema().getMergedTraits().sensitive||!!r.getValueSchema().getMergedTraits().sensitive)return Vj}else if(r.isStructSchema()&&typeof e=="object"){let o=e,n={};for(let[i,s]of r.structIterator())o[i]!=null&&(n[i]=Hf(s,o[i]));return n}return e}var Vj,Gj=_(()=>{rt();Vj="***SensitiveInformation***"});var Hj,Wn,Kj,Bj=_(()=>{Hj=Vt(js());B$();Gj();Wn=class{middlewareStack=vu();schema;static classBuilder(){return new Kj}resolveMiddlewareWithContext(e,r,o,{middlewareFn:n,clientName:i,commandName:s,inputFilterSensitiveLog:a,outputFilterSensitiveLog:c,smithyContext:u,additionalContext:l,CommandCtor:d}){for(let S of n.bind(this)(d,e,r,o))this.middlewareStack.use(S);let p=e.concat(this.middlewareStack),{logger:f}=r,h=l[Hj.SMITHY_CONTEXT_KEY],y={logger:f,clientName:i,commandName:s,inputFilterSensitiveLog:a,outputFilterSensitiveLog:c,...l,[Hj.SMITHY_CONTEXT_KEY]:{...h,commandInstance:this,...u,...o?.metricsRecorder===void 0?{}:{metricsRecorder:o.metricsRecorder}}},{requestHandler:w}=r,b=o??{};return b.metricsRecorder&&(b={...b},delete b.metricsRecorder),u.eventStream&&(b={isEventStream:!0,...b}),p.resolve(S=>w.handle(S.request,b),y)}},Kj=class{_init=()=>{};_ep={};_middlewareFn=()=>[];_commandName="";_clientName="";_additionalContext={};_smithyContext={};_inputFilterSensitiveLog=void 0;_outputFilterSensitiveLog=void 0;_serializer=null;_deserializer=null;_operationSchema;init(e){this._init=e}ep(e){return this._ep=e,this}m(e){return this._middlewareFn=e,this}s(e,r,o={}){return this._smithyContext={service:e,operation:r,...o},this}c(e={}){return this._additionalContext=e,this}n(e,r){return this._clientName=e,this._commandName=r,this}f(e=o=>o,r=o=>o){return this._inputFilterSensitiveLog=e,this._outputFilterSensitiveLog=r,this}ser(e){return this._serializer=e,this}de(e){return this._deserializer=e,this}sc(e){return this._operationSchema=e,this._smithyContext.operationSchema=e,this}build(){let e=this,r;return r=class extends Wn{input;static getEndpointParameterInstructions(){return e._ep}constructor(...[o]){super(),this.input=o??{},e._init(this),this.schema=e._operationSchema}resolveMiddleware(o,n,i){let s=e._operationSchema,a=s?.[4]??s?.input,c=s?.[5]??s?.output;return this.resolveMiddlewareWithContext(o,n,i,{CommandCtor:r,middlewareFn:e._middlewareFn,clientName:e._clientName,commandName:e._commandName,inputFilterSensitiveLog:e._inputFilterSensitiveLog??(s?Hf.bind(null,a):u=>u),outputFilterSensitiveLog:e._outputFilterSensitiveLog??(s?Hf.bind(null,c):u=>u),smithyContext:e._smithyContext,additionalContext:e._additionalContext})}serialize=e._serializer;deserialize=e._deserializer}}}});var I7,A7=_(()=>{I7="***SensitiveInformation***"});var qs,P7=_(()=>{qs=(t,e,r)=>{for(let[i,s]of Object.entries(t)){let a=async function(u,l,d){let p=new s(u);if(typeof l=="function")this.send(p,l);else if(typeof d=="function"){if(typeof l!="object")throw new Error(`Expected http options but got ${typeof l}`);this.send(p,l||{},d)}else return this.send(p,l)},c=(i[0].toLowerCase()+i.slice(1)).replace(/Command$/,"");e.prototype[c]=a}let{paginators:o={},waiters:n={}}=r??{};for(let[i,s]of Object.entries(o))e.prototype[i]===void 0&&(e.prototype[i]=function(a={},c,...u){return s({...c,client:this},a,...u)});for(let[i,s]of Object.entries(n))e.prototype[i]===void 0&&(e.prototype[i]=async function(a={},c,...u){let l=c;return typeof c=="number"&&(l={maxWaitTime:c}),s({...l,client:this},a,...u)})}});var si,yd,Zj=_(()=>{si=class t extends Error{static shapeId="smithy.ts.sdk.synthetic.nonamespace.client#ServiceException";$fault;$response;$retryable;$metadata;constructor(e){super(e.message),Object.setPrototypeOf(this,Object.getPrototypeOf(this).constructor.prototype),this.name=e.name,this.$fault=e.$fault,this.$metadata=e.$metadata}static isInstance(e){if(!e)return!1;let r=e;return t.prototype.isPrototypeOf(r)||!!r.$fault&&!!r.$metadata&&(r.$fault==="client"||r.$fault==="server")}static[Symbol.hasInstance](e){if(!e)return!1;let r=e;if(this===t)return t.isInstance(e);if(t.isInstance(e)){if(this.prototype.isPrototypeOf(e))return!0;let o=Object.prototype.hasOwnProperty.call(this,"shapeId")?this.shapeId:void 0,n=!1;if(o){let s=Object.getPrototypeOf(r);for(;s&&s!==Object.prototype;){let a=s.constructor,c=a!==t&&Object.prototype.hasOwnProperty.call(a,"shapeId")?a?.shapeId:void 0;if(c&&(n=!0,c===o))return!0;s=Object.getPrototypeOf(s)}}if(o&&n)return!1;let i=this.name;if(i&&i.length>=6){if(r.name===i)return!0;let s=Object.getPrototypeOf(r);for(;s&&s!==Object.prototype;){let a=s.constructor?.name;if(a&&a!=="Error"&&a===i)return!0;s=Object.getPrototypeOf(s)}}}return!1}},yd=(t,e={})=>{Object.entries(e).filter(([,o])=>o!==void 0).forEach(([o,n])=>{(t[o]==null||t[o]==="")&&(t[o]=n)});let r=t.message||t.Message||"UnknownError";return t.message=r,delete t.Message,t}});var Wj,k7,lze,T7=_(()=>{Zj();Wj=({output:t,parsedBody:e,exceptionCtor:r,errorCode:o})=>{let n=lze(t),i=n.httpStatusCode?n.httpStatusCode+"":void 0,s=new r({name:e?.code||e?.Code||o||i||"UnknownError",$fault:"client",$metadata:n});throw yd(s,e)},k7=t=>({output:e,parsedBody:r,errorCode:o})=>{Wj({output:e,parsedBody:r,exceptionCtor:t,errorCode:o})},lze=t=>({httpStatusCode:t.statusCode,requestId:t.headers["x-amzn-requestid"]??t.headers["x-amzn-request-id"]??t.headers["x-amz-request-id"],extendedRequestId:t.headers["x-amz-id-2"],cfId:t.headers["x-amz-cf-id"]})});var Vs,C7=_(()=>{Vs=t=>{switch(t){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region":return{retryMode:"standard",connectionTimeout:3100};case"mobile":return{retryMode:"standard",connectionTimeout:3e4};default:return{}}}});var O7,Gs,D7=_(()=>{O7=!1,Gs=t=>{t&&!O7&&parseInt(t.substring(1,t.indexOf(".")))<16&&(O7=!0)}});var vd,N7,X$,Y$,Jj=_(()=>{Pe();vd=Vt(js()),N7=Object.values(vd.AlgorithmId),X$=t=>{let e=[];for(let r in vd.AlgorithmId){if(!Se(vd.AlgorithmId,r))continue;let o=vd.AlgorithmId[r];t[o]!==void 0&&e.push({algorithmId:()=>o,checksumConstructor:()=>t[o]})}for(let[r,o]of Object.entries(t.checksumAlgorithms??{}))e.push({algorithmId:()=>r,checksumConstructor:()=>o});return{addChecksumAlgorithm(r){t.checksumAlgorithms=t.checksumAlgorithms??{};let o=r.algorithmId(),n=r.checksumConstructor();N7.includes(o)?t.checksumAlgorithms[o.toUpperCase()]=n:t.checksumAlgorithms[o]=n,e.push(r)},checksumAlgorithms(){return e}}},Y$=t=>{let e={};return t.checksumAlgorithms().forEach(r=>{let o=r.algorithmId();N7.includes(o)&&(e[o]=r.checksumConstructor())}),e}});var Q$,eR,Xj=_(()=>{Q$=t=>({setRetryStrategy(e){t.retryStrategy=e},retryStrategy(){return t.retryStrategy}}),eR=t=>{let e={};return e.retryStrategy=t.retryStrategy(),e}});var Bi,z7,Hs,M7=_(()=>{Jj();Xj();Bi=t=>Object.assign(X$(t),Q$(t)),z7=Bi,Hs=t=>Object.assign(Y$(t),eR(t))});var U7,L7=_(()=>{U7=t=>Array.isArray(t)?t:[t]});var wd,j7=_(()=>{Pe();wd=t=>{let e="#text";for(let r in t)Se(t,r)&&(t[r][e]!==void 0?t[r]=t[r][e]:typeof t[r]=="object"&&t[r]!==null&&(t[r]=wd(t[r])));return t}});var F7,q7=_(()=>{F7=t=>t!=null});var mo,V7=_(()=>{mo=class{trace(){}debug(){}info(){}warn(){}error(){}}});function Yj(t,e,r){let o,n,i;if(typeof e>"u"&&typeof r>"u")o={},i=t;else{if(o=t,typeof e=="function")return n=e,i=r,dze(o,n,i);i=e}for(let s in i)if(Se(i,s)){if(!Array.isArray(i[s])){o[s]=i[s];continue}K7(o,null,i,s)}return o}var G7,H7,dze,K7,pze,fze,B7=_(()=>{Pe();G7=t=>{let e={};for(let[r,o]of Object.entries(t||{}))e[r]=[,o];return e},H7=(t,e)=>{let r={};for(let o in e)Se(e,o)&&K7(r,t,e,o);return r},dze=(t,e,r)=>Yj(t,Object.entries(r).reduce((o,[n,i])=>(Array.isArray(i)?o[n]=i:typeof i=="function"?o[n]=[e,i()]:o[n]=[e,i],o),{})),K7=(t,e,r,o)=>{if(e!==null){let s=r[o];typeof s=="function"&&(s=[,s]);let[a=pze,c=fze,u=o]=s;(typeof a=="function"&&a(e[u])||typeof a!="function"&&a)&&(t[o]=c(e[u]));return}let[n,i]=r[o];if(typeof i=="function"){let s,a=n===void 0&&(s=i())!=null,c=typeof n=="function"&&!!n(void 0)||typeof n!="function"&&!!n;a?t[o]=s:c&&(t[o]=i())}else{let s=n===void 0&&i!=null,a=typeof n=="function"&&!!n(i)||typeof n!="function"&&!!n;(s||a)&&(t[o]=i)}},pze=t=>t!=null,fze=t=>t});var Z7,W7,J7=_(()=>{Z7=t=>{if(t!==t)return"NaN";switch(t){case 1/0:return"Infinity";case-1/0:return"-Infinity";default:return t}},W7=t=>t.toISOString().replace(".000Z","Z")});var tR,X7=_(()=>{Pe();tR=t=>{if(t==null)return{};if(Array.isArray(t))return t.filter(e=>e!=null).map(tR);if(typeof t=="object"){let e={};for(let r in t)Se(t,r)&&t[r]!=null&&(e[r]=tR(t[r]));return e}return t}});function Ks(t,e,r,o){return function(i,s,a,c,u={}){let l=Object.assign({},t,i);return Wn.classBuilder().ep(l).m(function(d,p,f,h){let y=s.call(this,d,p,f,h);return y.unshift(o(f,d.getEndpointParameterInstructions())),y}).s(e,a,u).n(r,a.charAt(0).toUpperCase()+a.slice(1)+"Command").sc(c).build()}}var Y7=_(()=>{Bj()});var Kf={};Ht(Kf,{AlgorithmId:()=>vd.AlgorithmId,Client:()=>Rn,Command:()=>Wn,NoOpLogger:()=>mo,SENSITIVE_STRING:()=>I7,ServiceException:()=>si,WaiterState:()=>Co,_json:()=>tR,checkExceptions:()=>XJ,constructStack:()=>vu,convertMap:()=>G7,createAggregatedClient:()=>qs,createWaiter:()=>n7,decorateServiceException:()=>yd,emitWarningIfUnsupportedVersion:()=>Gs,getArrayIfSingleItem:()=>U7,getChecksumConfiguration:()=>X$,getDefaultClientConfiguration:()=>z7,getDefaultExtensionConfiguration:()=>Bi,getRetryConfiguration:()=>Q$,getSmithyContext:()=>Bt,getValueFromTextNode:()=>wd,invalidFunction:()=>HJ,invalidProvider:()=>BJ,isSerializableHeaderValue:()=>F7,loadConfigsForDefaultMode:()=>Vs,makeBuilder:()=>Ks,map:()=>Yj,normalizeProvider:()=>jt,resolveChecksumRuntimeConfig:()=>Y$,resolveDefaultRuntimeConfig:()=>Hs,resolveRetryRuntimeConfig:()=>eR,schemaLogFilter:()=>Hf,serializeDateTime:()=>W7,serializeFloat:()=>Z7,take:()=>H7,throwDefaultError:()=>Wj,waiterServiceDefaults:()=>Z$,withBaseException:()=>k7});var ve=_(()=>{B$();Pe();Pe();KJ();ZJ();o7();W$();i7();Bj();A7();P7();T7();C7();D7();Zj();M7();Jj();Xj();L7();j7();q7();V7();B7();Gj();J7();X7();Y7()});var rR,Qj=_(()=>{rR=t=>typeof ArrayBuffer=="function"&&t instanceof ArrayBuffer||Object.prototype.toString.call(t)==="[object ArrayBuffer]"});var Zi,_u,bu=_(()=>{Qj();Zi=(t,e=0,r=t.byteLength-e)=>{if(!rR(t))throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof t} (${t})`);return Buffer.from(t,e,r)},_u=(t,e)=>{if(typeof t!="string")throw new TypeError(`The "input" argument must be of type string. Received type ${typeof t} (${t})`);return e?Buffer.from(t,e):Buffer.from(t)}});var mze,fr,Q7=_(()=>{bu();mze=/^[A-Za-z0-9+/]*={0,2}$/,fr=t=>{if(t.length*3%4!==0)throw new TypeError("Incorrect padding on base64 string.");if(!mze.exec(t))throw new TypeError("Invalid base64 string.");let e=_u(t,"base64");return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}});var Tr,nR=_(()=>{bu();Tr=t=>{let e=_u(t,"utf8");return new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT)}});var Wt,e4=_(()=>{bu();nR();Wt=t=>{let e;if(typeof t=="string"?e=Tr(t):e=t,typeof e!="object"||typeof e.byteOffset!="number"||typeof e.byteLength!="number")throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");return Zi(e.buffer,e.byteOffset,e.byteLength).toString("base64")}});function eX(t,e,r,o){return class oR extends Uint8Array{static fromString(i,s="utf-8"){if(typeof i=="string")return s==="base64"?oR.mutate(o(i)):oR.mutate(e(i));throw new Error(`Unsupported conversion from ${typeof i} to Uint8ArrayBlobAdapter.`)}static mutate(i){return Object.setPrototypeOf(i,oR.prototype),i}transformToString(i="utf-8"){return i==="base64"?r(this):t(this)}}}var tX=_(()=>{});var ur,rX=_(()=>{bu();ur=t=>{if(typeof t=="string")return t;if(typeof t!="object"||typeof t.byteOffset!="number"||typeof t.byteLength!="number")throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return Zi(t.buffer,t.byteOffset,t.byteLength).toString("utf8")}});function nX(t){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?()=>crypto.randomUUID():()=>{let e=new Uint8Array(16);return t(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128,In[e[0]]+In[e[1]]+In[e[2]]+In[e[3]]+"-"+In[e[4]]+In[e[5]]+"-"+In[e[6]]+In[e[7]]+"-"+In[e[8]]+In[e[9]]+"-"+In[e[10]]+In[e[11]]+In[e[12]]+In[e[13]]+In[e[14]]+In[e[15]]}}var In,oX=_(()=>{In=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"))});var iX,sX=_(()=>{iX=(t,e,r=o=>o)=>t});var aX,cX,Bf,hze,yv,Zf,uX,iR,sR,aR,t4,gze,lX,r4,dX,uR,vv,pX,lR,yze,Jf,dR,fX,mX,hX,gX,n4,yX,vX,Su,pR,cR,Wf,o4=_(()=>{Pe();aX=t=>{switch(t){case"true":return!0;case"false":return!1;default:throw new Error(`Unable to parse boolean value "${t}"`)}},cX=t=>{if(t!=null){if(typeof t=="number"){if((t===0||t===1)&&Wf.warn(cR(`Expected boolean, got ${typeof t}: ${t}`)),t===0)return!1;if(t===1)return!0}if(typeof t=="string"){let e=t.toLowerCase();if((e==="false"||e==="true")&&Wf.warn(cR(`Expected boolean, got ${typeof t}: ${t}`)),e==="false")return!1;if(e==="true")return!0}if(typeof t=="boolean")return t;throw new TypeError(`Expected boolean, got ${typeof t}: ${t}`)}},Bf=t=>{if(t!=null){if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return String(e)!==String(t)&&Wf.warn(cR(`Expected number but observed string: ${t}`)),e}if(typeof t=="number")return t;throw new TypeError(`Expected number, got ${typeof t}: ${t}`)}},hze=Math.ceil(2**127*(2-2**-23)),yv=t=>{let e=Bf(t);if(e!==void 0&&!Number.isNaN(e)&&e!==1/0&&e!==-1/0&&Math.abs(e)>hze)throw new TypeError(`Expected 32-bit float, got ${t}`);return e},Zf=t=>{if(t!=null){if(Number.isInteger(t)&&!Number.isNaN(t))return t;throw new TypeError(`Expected integer, got ${typeof t}: ${t}`)}},uX=Zf,iR=t=>t4(t,32),sR=t=>t4(t,16),aR=t=>t4(t,8),t4=(t,e)=>{let r=Zf(t);if(r!==void 0&&gze(r,e)!==r)throw new TypeError(`Expected ${e}-bit integer, got ${t}`);return r},gze=(t,e)=>{switch(e){case 32:return Int32Array.of(t)[0];case 16:return Int16Array.of(t)[0];case 8:return Int8Array.of(t)[0]}},lX=(t,e)=>{if(t==null)throw e?new TypeError(`Expected a non-null value for ${e}`):new TypeError("Expected a non-null value");return t},r4=t=>{if(t==null)return;if(typeof t=="object"&&!Array.isArray(t))return t;let e=Array.isArray(t)?"array":typeof t;throw new TypeError(`Expected object, got ${e}: ${t}`)},dX=t=>{if(t!=null){if(typeof t=="string")return t;if(["boolean","number","bigint"].includes(typeof t))return Wf.warn(cR(`Expected string, got ${typeof t}: ${t}`)),String(t);throw new TypeError(`Expected string, got ${typeof t}: ${t}`)}},uR=t=>{if(t==null)return;let e=r4(t),r=[];for(let o in e)Se(e,o)&&e[o]!=null&&r.push(o);if(r.length===0)throw new TypeError("Unions must have exactly one non-null member. None were found.");if(r.length>1)throw new TypeError(`Unions must have exactly one non-null member. Keys ${r} were not null.`);return e},vv=t=>Bf(typeof t=="string"?Jf(t):t),pX=vv,lR=t=>yv(typeof t=="string"?Jf(t):t),yze=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,Jf=t=>{let e=t.match(yze);if(e===null||e[0].length!==t.length)throw new TypeError("Expected real number, got implicit NaN");return parseFloat(t)},dR=t=>typeof t=="string"?gX(t):Bf(t),fX=dR,mX=dR,hX=t=>typeof t=="string"?gX(t):yv(t),gX=t=>{switch(t){case"NaN":return NaN;case"Infinity":return 1/0;case"-Infinity":return-1/0;default:throw new Error(`Unable to parse float value: ${t}`)}},n4=t=>Zf(typeof t=="string"?Jf(t):t),yX=n4,vX=t=>iR(typeof t=="string"?Jf(t):t),Su=t=>sR(typeof t=="string"?Jf(t):t),pR=t=>aR(typeof t=="string"?Jf(t):t),cR=t=>String(new TypeError(t).stack||t).split(`
12
12
  `).slice(0,5).filter(e=>!e.includes("stackTraceWarning")).join(`
13
13
  `),Wf={warn:console.warn}});function Oo(t){let e=t.getUTCFullYear(),r=t.getUTCMonth(),o=t.getUTCDay(),n=t.getUTCDate(),i=t.getUTCHours(),s=t.getUTCMinutes(),a=t.getUTCSeconds(),c=n<10?`0${n}`:`${n}`,u=i<10?`0${i}`:`${i}`,l=s<10?`0${s}`:`${s}`,d=a<10?`0${a}`:`${a}`;return`${vze[o]}, ${c} ${s4[r]} ${e} ${u}:${l}:${d} GMT`}var vze,s4,wze,wX,_ze,Yf,bze,Sze,xze,xu,Qf,wv,Eze,$ze,Rze,i4,Ize,Aze,Pze,Bs,kze,Tze,Xf,_X=_(()=>{o4();vze=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],s4=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];wze=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),wX=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=wze.exec(t);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");let[r,o,n,i,s,a,c,u]=e,l=Su(Xf(o)),d=Bs(n,"month",1,12),p=Bs(i,"day",1,31);return wv(l,d,p,{hours:s,minutes:a,seconds:c,fractionalMilliseconds:u})},_ze=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}:\d{2})|[zZ])$/),Yf=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=_ze.exec(t);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");let[r,o,n,i,s,a,c,u,l]=e,d=Su(Xf(o)),p=Bs(n,"month",1,12),f=Bs(i,"day",1,31),h=wv(d,p,f,{hours:s,minutes:a,seconds:c,fractionalMilliseconds:u});return l.toUpperCase()!="Z"&&h.setTime(h.getTime()-Tze(l)),h},bze=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),Sze=new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),xze=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/),xu=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-7231 date-times must be expressed as strings");let e=bze.exec(t);if(e){let[r,o,n,i,s,a,c,u]=e;return wv(Su(Xf(i)),i4(n),Bs(o,"day",1,31),{hours:s,minutes:a,seconds:c,fractionalMilliseconds:u})}if(e=Sze.exec(t),e){let[r,o,n,i,s,a,c,u]=e;return Rze(wv(Eze(i),i4(n),Bs(o,"day",1,31),{hours:s,minutes:a,seconds:c,fractionalMilliseconds:u}))}if(e=xze.exec(t),e){let[r,o,n,i,s,a,c,u]=e;return wv(Su(Xf(u)),i4(o),Bs(n.trimLeft(),"day",1,31),{hours:i,minutes:s,seconds:a,fractionalMilliseconds:c})}throw new TypeError("Invalid RFC-7231 date-time value")},Qf=t=>{if(t==null)return;let e;if(typeof t=="number")e=t;else if(typeof t=="string")e=vv(t);else if(typeof t=="object"&&t.tag===1)e=t.value;else throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");if(Number.isNaN(e)||e===1/0||e===-1/0)throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(e*1e3))},wv=(t,e,r,o)=>{let n=e-1;return Aze(t,n,r),new Date(Date.UTC(t,n,r,Bs(o.hours,"hour",0,23),Bs(o.minutes,"minute",0,59),Bs(o.seconds,"seconds",0,60),kze(o.fractionalMilliseconds)))},Eze=t=>{let e=new Date().getUTCFullYear(),r=Math.floor(e/100)*100+Su(Xf(t));return r<e?r+100:r},$ze=50*365*24*60*60*1e3,Rze=t=>t.getTime()-new Date().getTime()>$ze?new Date(Date.UTC(t.getUTCFullYear()-100,t.getUTCMonth(),t.getUTCDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds(),t.getUTCMilliseconds())):t,i4=t=>{let e=s4.indexOf(t);if(e<0)throw new TypeError(`Invalid month: ${t}`);return e+1},Ize=[31,28,31,30,31,30,31,31,30,31,30,31],Aze=(t,e,r)=>{let o=Ize[e];if(e===1&&Pze(t)&&(o=29),r>o)throw new TypeError(`Invalid day for ${s4[e]} in ${t}: ${r}`)},Pze=t=>t%4===0&&(t%100!==0||t%400===0),Bs=(t,e,r,o)=>{let n=pR(Xf(t));if(n<r||n>o)throw new TypeError(`${e} must be between ${r} and ${o}, inclusive`);return n},kze=t=>t==null?0:lR("0."+t)*1e3,Tze=t=>{let e=t[0],r=1;if(e=="+")r=1;else if(e=="-")r=-1;else throw new TypeError(`Offset direction, ${e}, must be "+" or "-"`);let o=Number(t.substring(1,3)),n=Number(t.substring(4,6));return r*(o*60+n)*60*1e3},Xf=t=>{let e=0;for(;e<t.length-1&&t.charAt(e)==="0";)e++;return e===0?t:t.slice(e)}});var Er,bX=_(()=>{Er=function(e){return Object.assign(new String(e),{deserializeJSON(){return JSON.parse(String(e))},toString(){return String(e)},toJSON(){return String(e)}})};Er.from=t=>t&&typeof t=="object"&&(t instanceof Er||"deserializeJSON"in t)?t:typeof t=="string"||Object.getPrototypeOf(t)===String.prototype?Er(String(t)):Er(JSON.stringify(t));Er.fromObject=Er.from});function fR(t){return(t.includes(",")||t.includes('"'))&&(t=`"${t.replace(/"/g,'\\"')}"`),t}var SX=_(()=>{});function uc(t,e,r){let o=Number(t);if(o<e||o>r)throw new Error(`Value ${o} out of range [${e}, ${r}]`)}var a4,c4,u4,xX,EX,Cze,Oze,Dze,Nze,zze,Eu,mR,hR,$X=_(()=>{a4="(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?",c4="(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)",u4="(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?",xX="(\\d?\\d)",EX="(\\d{4})",Cze=new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/),Oze=new RegExp(`^${a4}, ${xX} ${c4} ${EX} ${u4} GMT$`),Dze=new RegExp(`^${a4}, ${xX}-${c4}-(\\d\\d) ${u4} GMT$`),Nze=new RegExp(`^${a4} ${c4} ( [1-9]|\\d\\d) ${u4} ${EX}$`),zze=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Eu=t=>{if(t==null)return;let e=NaN;if(typeof t=="number")e=t;else if(typeof t=="string"){if(!/^-?\d*\.?\d+$/.test(t))throw new TypeError("parseEpochTimestamp - numeric string invalid.");e=Number.parseFloat(t)}else typeof t=="object"&&t.tag===1&&(e=t.value);if(isNaN(e)||Math.abs(e)===1/0)throw new TypeError("Epoch timestamps must be valid finite numbers.");return new Date(Math.round(e*1e3))},mR=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC3339 timestamps must be strings");let e=Cze.exec(t);if(!e)throw new TypeError(`Invalid RFC3339 timestamp format ${t}`);let[,r,o,n,i,s,a,,c,u]=e;uc(o,1,12),uc(n,1,31),uc(i,0,23),uc(s,0,59),uc(a,0,60);let l=new Date(Date.UTC(Number(r),Number(o)-1,Number(n),Number(i),Number(s),Number(a),Number(c)?Math.round(parseFloat(`0.${c}`)*1e3):0));if(l.setUTCFullYear(Number(r)),u.toUpperCase()!="Z"){let[,d,p,f]=/([+-])(\d\d):(\d\d)/.exec(u)||[void 0,"+",0,0],h=d==="-"?1:-1;l.setTime(l.getTime()+h*(Number(p)*60*60*1e3+Number(f)*60*1e3))}return l},hR=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC7231 timestamps must be strings.");let e,r,o,n,i,s,a,c;if((c=Oze.exec(t))?[,e,r,o,n,i,s,a]=c:(c=Dze.exec(t))?([,e,r,o,n,i,s,a]=c,o=(Number(o)+1900).toString()):(c=Nze.exec(t))&&([,r,e,n,i,s,a,o]=c),o&&s){let u=Date.UTC(Number(o),zze.indexOf(r),Number(e),Number(n),Number(i),Number(s),a?Math.round(parseFloat(`0.${a}`)*1e3):0);uc(e,1,31),uc(n,0,23),uc(i,0,59),uc(s,0,60);let l=new Date(u);return l.setUTCFullYear(Number(o)),l}throw new TypeError(`Invalid RFC7231 date-time value ${t}.`)}});function gR(t,e,r){if(r<=0||!Number.isInteger(r))throw new Error("Invalid number of delimiters ("+r+") for splitEvery.");let o=t.split(e);if(r===1)return o;let n=[],i="";for(let s=0;s<o.length;s++)i===""?i=o[s]:i+=e+o[s],(s+1)%r===0&&(n.push(i),i="");return i!==""&&n.push(i),n}var RX=_(()=>{});var em,IX=_(()=>{em=t=>{let e=t.length,r=[],o=!1,n,i=0;for(let s=0;s<e;++s){let a=t[s];switch(a){case'"':n!=="\\"&&(o=!o);break;case",":o||(r.push(t.slice(i,s)),i=s+1);break;default:}n=a}return r.push(t.slice(i)),r.map(s=>{s=s.trim();let a=s.length;return a<2?s:(s[0]==='"'&&s[a-1]==='"'&&(s=s.slice(1,a-1)),s.replace(/\\"/g,'"'))})}});function yR(t){return new nt(String(t),"bigDecimal")}var AX,nt,PX=_(()=>{AX=/^-?((0|[1-9]\d*)(\.\d+)?|\.\d+)([eE][+-]?\d+)?$/,nt=class t{string;type;constructor(e,r){if(this.string=e,this.type=r,!AX.test(e))throw new Error(`@smithy/core/serde - NumericValue string must conform to the Smithy bigDecimal format. Received: "${e}"`)}toString(){return this.string}static[Symbol.hasInstance](e){if(!e||typeof e!="object")return!1;let r=e;return t.prototype.isPrototypeOf(e)||r.type==="bigDecimal"&&AX.test(r.string)}}});function vR(t){if(t.length%2!==0)throw new Error("Hex encoded strings must have an even number length");let e=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2){let o=t.slice(r,r+2).toLowerCase();if(o in l4)e[r/2]=l4[o];else throw new Error(`Cannot decode unrecognized sequence ${o} as hexadecimal`)}return e}function ai(t){let e="";for(let r=0;r<t.byteLength;r++)e+=kX[t[r]];return e}var kX,l4,d4=_(()=>{kX={},l4={};for(let t=0;t<256;t++){let e=t.toString(16).toLowerCase();e.length===1&&(e=`0${e}`),kX[t]=e,l4[e]=t}});import{ReadStream as Mze,fstatSync as Uze,lstatSync as Lze}from"node:fs";var Zs,TX=_(()=>{Zs=t=>{if(!t)return 0;if(typeof t=="string")return Buffer.byteLength(t);if(typeof t.byteLength=="number")return t.byteLength;if(typeof t.size=="number")return t.size;if(typeof t.start=="number"&&typeof t.end=="number")return t.end+1-t.start;if(t instanceof Mze){if(t.path!=null)return Lze(t.path).size;if(typeof t.fd=="number")return Uze(t.fd).size}throw new Error(`Body Length computation failed for ${t}`)}});var Jn,p4=_(()=>{nR();Jn=t=>t instanceof Uint8Array?t:typeof t=="string"?Tr(t):ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(t)});function Ws(t,e){if(e===void 0){e=0;for(let n of t)e+=n.byteLength}let r=new Uint8Array(e),o=0;for(let n of t)r.set(n,o),o+=n.byteLength;return r}var _v=_(()=>{});var wR,f4,m4=_(()=>{Pe();wR=(t,e)=>(r,o)=>async n=>{let{response:i}=await r(n);try{let s=await e(i,t);return{response:i,output:s}}catch(s){if(Object.defineProperty(s,"$response",{value:i,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in s)){let a="Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.";try{s.message+=`
14
14
  `+a}catch{!o.logger||o.logger?.constructor?.name==="NoOpLogger"?console.warn(a):o.logger?.warn?.(a)}typeof s.$responseBodyText<"u"&&s.$response&&(s.$response.body=s.$responseBodyText);try{if(Lr.isInstance(i)){let{headers:c={}}=i,u=Object.entries(c);s.$metadata={httpStatusCode:i.statusCode,requestId:f4(/^x-[\w-]+-request-?id$/,u),extendedRequestId:f4(/^x-[\w-]+-id-2$/,u),cfId:f4(/^x-[\w-]+-cf-id$/,u)}}}catch{}}throw s}},f4=(t,e)=>(e.find(([r])=>r.match(t))||[void 0,void 0])[1]});var Do,bv=_(()=>{Do=class t extends Error{name="ProviderError";tryNextLink;constructor(e,r=!0){let o,n=!0;typeof r=="boolean"?(o=void 0,n=r):r!=null&&typeof r=="object"&&(o=r.logger,n=r.tryNextLink??!0),super(e),this.tryNextLink=n,Object.setPrototypeOf(this,t.prototype),o?.debug?.(`@smithy/property-provider ${n?"->":"(!)"} ${e}`)}static from(e,r=!0){return Object.assign(new this(e.message,r),e)}}});var $u,_R=_(()=>{bv();$u=class t extends Do{name="CredentialsProviderError";constructor(e,r=!0){super(e,r),Object.setPrototypeOf(this,t.prototype)}}});var bR,CX=_(()=>{bv();bR=class t extends Do{name="TokenProviderError";constructor(e,r=!0){super(e,r),Object.setPrototypeOf(this,t.prototype)}}});var SR,h4=_(()=>{bv();SR=(...t)=>async()=>{if(t.length===0)throw new Do("No providers in chain");let e;for(let r of t)try{return await r()}catch(o){if(e=o,o?.tryNextLink)continue;throw o}throw e}});var xR,g4=_(()=>{xR=t=>()=>Promise.resolve(t)});var tm,ER=_(()=>{tm=(t,e,r)=>{let o,n,i,s=!1,a=async()=>{n||(n=t());try{o=await n,i=!0,s=!1}finally{n=void 0}return o};return e===void 0?async c=>((!i||c?.forceRefresh)&&(o=await a()),o):async c=>((!i||c?.forceRefresh)&&(o=await a()),s?o:r&&!r(o)?(s=!0,o):(e(o)&&await a(),o))}});var jr,$R=_(()=>{jr=(t,e,r)=>{if(e in t){if(t[e]==="true")return!0;if(t[e]==="false")return!1;throw new Error(`Cannot load ${r} "${e}". Expected "true" or "false", got ${t[e]}.`)}}});var OX,DX=_(()=>{OX=(t,e,r)=>{if(!(e in t))return;let o=parseInt(t[e],10);if(Number.isNaN(o))throw new TypeError(`Cannot load ${r} '${e}'. Expected number, got '${t[e]}'.`);return o}});var $r,RR=_(()=>{(function(t){t.ENV="env",t.CONFIG="shared config entry"})($r||($r={}))});import{homedir as jze}from"node:os";import{sep as Fze}from"node:path";var y4,qze,Js,rm=_(()=>{y4={},qze=()=>process&&process.geteuid?`${process.geteuid()}`:"DEFAULT",Js=()=>{let{HOME:t,USERPROFILE:e,HOMEPATH:r,HOMEDRIVE:o=`C:${Fze}`}=process.env;if(t)return t;if(e)return e;if(r)return`${o}${r}`;let n=qze();return y4[n]||(y4[n]=jze()),y4[n]}});var v4,w4,IR,_4=_(()=>{v4="AWS_PROFILE",w4="default",IR=t=>t.profile||process.env[v4]||w4});import{createHash as Vze}from"node:crypto";import{join as Gze}from"node:path";var AR,b4=_(()=>{rm();AR=t=>{let r=Vze("sha1").update(t).digest("hex");return Gze(Js(),".aws","sso","cache",`${r}.json`)}});import{readFile as Hze}from"node:fs/promises";var Sv,NX,S4=_(()=>{b4();Sv={},NX=async t=>{if(Sv[t])return Sv[t];let e=AR(t),r=await Hze(e,"utf8");return JSON.parse(r)}});var Xs,zX=_(()=>{Xs="."});var x4,MX,UX=_(()=>{x4=Vt(js()),MX=t=>Object.entries(t).filter(([e])=>{let r=e.indexOf(".");return r===-1?!1:Object.values(x4.IniSectionType).includes(e.substring(0,r))}).reduce((e,[r,o])=>{let n=r.indexOf("."),i=r.substring(0,n)===x4.IniSectionType.PROFILE?r.substring(n+1):r;return e[i]=o,e},{...t.default&&{default:t.default}})});import{join as Kze}from"node:path";var Bze,PR,E4=_(()=>{rm();Bze="AWS_CONFIG_FILE",PR=()=>process.env[Bze]||Kze(Js(),".aws","config")});import{join as Zze}from"node:path";var Wze,LX,jX=_(()=>{rm();Wze="AWS_SHARED_CREDENTIALS_FILE",LX=()=>process.env[Wze]||Zze(Js(),".aws","credentials")});var FX,Jze,Xze,xv,$4=_(()=>{FX=Vt(js()),Jze=/^([\w-]+)\s(["'])?([\w-@+.%:/]+)\2$/,Xze=["__proto__","profile __proto__"],xv=t=>{let e={},r,o;for(let n of t.split(/\r?\n/)){let i=n.split(/(^|\s)[;#]/)[0].trim();if(i[0]==="["&&i[i.length-1]==="]"){r=void 0,o=void 0;let a=i.substring(1,i.length-1),c=Jze.exec(a);if(c){let[,u,,l]=c;Object.values(FX.IniSectionType).includes(u)&&(r=[u,l].join("."))}else r=a;if(Xze.includes(a))throw new Error(`Found invalid profile name "${a}"`)}else if(r){let a=i.indexOf("=");if(![0,-1].includes(a)){let[c,u]=[i.substring(0,a).trim(),i.substring(a+1).trim()];if(u==="")o=c;else{o&&n.trimStart()===n&&(o=void 0),e[r]=e[r]||{};let l=o?[o,c].join("."):c;e[r][l]=u}}}}return e}});import{readFile as Yze}from"node:fs/promises";var R4,Ev,_d,$v=_(()=>{R4={},Ev={},_d=(t,e)=>Ev[t]!==void 0?Ev[t]:((!R4[t]||e?.ignoreCache)&&(R4[t]=Yze(t,"utf8")),R4[t])});import{join as qX}from"node:path";var VX,nm,kR=_(()=>{UX();E4();jX();rm();$4();$v();VX=()=>({}),nm=async(t={})=>{let{filepath:e=LX(),configFilepath:r=PR()}=t,o=Js(),n="~/",i=e;e.startsWith(n)&&(i=qX(o,e.slice(2)));let s=r;r.startsWith(n)&&(s=qX(o,r.slice(2)));let a=await Promise.all([_d(s,{ignoreCache:t.ignoreCache}).then(xv).then(MX).catch(VX),_d(i,{ignoreCache:t.ignoreCache}).then(xv).catch(VX)]);return{configFile:a[0],credentialsFile:a[1]}}});var GX,HX,KX=_(()=>{GX=Vt(js()),HX=t=>Object.entries(t).filter(([e])=>e.startsWith(GX.IniSectionType.SSO_SESSION+".")).reduce((e,[r,o])=>({...e,[r.substring(r.indexOf(".")+1)]:o}),{})});var Qze,BX,ZX=_(()=>{E4();KX();$4();$v();Qze=()=>({}),BX=async(t={})=>_d(t.configFilepath??PR()).then(xv).then(HX).catch(Qze)});var WX,JX=_(()=>{WX=(...t)=>{let e={};for(let r of t)for(let[o,n]of Object.entries(r))e[o]!==void 0?Object.assign(e[o],n):e[o]=n;return e}});var XX,YX=_(()=>{kR();JX();XX=async t=>{let e=await nm(t);return WX(e.configFile,e.credentialsFile)}});var QX,eY=_(()=>{S4();$v();QX={getFileRecord(){return Ev},interceptFile(t,e){Ev[t]=Promise.resolve(e)},getTokenRecord(){return Sv},interceptToken(t,e){Sv[t]=e}}});function TR(t){try{let e=new Set(Array.from(t.match(/([A-Z_]){3,}/g)??[]));return e.delete("CONFIG"),e.delete("CONFIG_PREFIX_SEPARATOR"),e.delete("ENV"),[...e].join(", ")}catch{return t}}var I4=_(()=>{});var tY,rY=_(()=>{_R();I4();tY=(t,e)=>async()=>{try{let r=t(process.env,e);if(r===void 0)throw new Error;return r}catch(r){throw new $u(r.message||`Not found in ENV: ${TR(t.toString())}`,{logger:e?.logger})}}});var nY,oY=_(()=>{_R();_4();kR();I4();nY=(t,{preferredFile:e="config",...r}={})=>async()=>{let o=IR(r),{configFile:n,credentialsFile:i}=await nm(r),s=i[o]||{},a=n[o]||{},c=e==="config"?{...s,...a}:{...a,...s};try{let l=t(c,e==="config"?n:i);if(l===void 0)throw new Error;return l}catch(u){throw new $u(u.message||`Not found in config files w/ profile [${o}]: ${TR(t.toString())}`,{logger:r.logger})}}});var eMe,CR,A4=_(()=>{g4();eMe=t=>typeof t=="function",CR=t=>eMe(t)?async()=>await t():xR(t)});var Ie,P4=_(()=>{h4();ER();rY();oY();A4();Ie=({environmentVariableSelector:t,configFileSelector:e,default:r},o={})=>{let{signingName:n,logger:i}=o;return tm(SR(tY(t,{signingName:n,logger:i}),nY(e,o),CR(r)))}});var OR,DR,iY,Ys,sY,aY=_(()=>{$R();RR();OR="AWS_USE_DUALSTACK_ENDPOINT",DR="use_dualstack_endpoint",iY=!1,Ys={environmentVariableSelector:t=>jr(t,OR,$r.ENV),configFileSelector:t=>jr(t,DR,$r.CONFIG),default:!1},sY={environmentVariableSelector:t=>jr(t,OR,$r.ENV),configFileSelector:t=>jr(t,DR,$r.CONFIG),default:void 0}});var NR,zR,cY,Qs,uY,lY=_(()=>{$R();RR();NR="AWS_USE_FIPS_ENDPOINT",zR="use_fips_endpoint",cY=!1,Qs={environmentVariableSelector:t=>jr(t,NR,$r.ENV),configFileSelector:t=>jr(t,zR,$r.CONFIG),default:!1},uY={environmentVariableSelector:t=>jr(t,NR,$r.ENV),configFileSelector:t=>jr(t,zR,$r.CONFIG),default:void 0}});var dY,pY=_(()=>{ve();dY=t=>{let{tls:e,endpoint:r,urlParser:o,useDualstackEndpoint:n}=t;return Object.assign(t,{tls:e??!0,endpoint:jt(typeof r=="string"?o(r):r),isCustomEndpoint:!0,useDualstackEndpoint:jt(n??!1)})}});var fY,mY=_(()=>{fY=async t=>{let{tls:e=!0}=t,r=await t.region();if(!new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/).test(r))throw new Error("Invalid region in client config");let n=await t.useDualstackEndpoint(),i=await t.useFipsEndpoint(),{hostname:s}=await t.regionInfoProvider(r,{useDualstackEndpoint:n,useFipsEndpoint:i})??{};if(!s)throw new Error("Cannot resolve hostname from client config");return t.urlParser(`${e?"https:":"http:"}//${s}`)}});var hY,gY=_(()=>{ve();mY();hY=t=>{let e=jt(t.useDualstackEndpoint??!1),{endpoint:r,useFipsEndpoint:o,urlParser:n,tls:i}=t;return Object.assign(t,{tls:i??!0,endpoint:r?jt(typeof r=="string"?n(r):r):()=>fY({...t,useDualstackEndpoint:e,useFipsEndpoint:o}),isCustomEndpoint:!!r,useDualstackEndpoint:e})}});var yY,k4,T4,vY,wY,_Y,bY,SY,xY,C4=_(()=>{yY="AWS_EXECUTION_ENV",k4="AWS_REGION",T4="AWS_DEFAULT_REGION",vY="AWS_EC2_METADATA_DISABLED",wY=["in-region","cross-region","mobile","standard","legacy"],_Y="/latest/meta-data/placement/region",bY="/latest/api/token",SY="x-aws-ec2-metadata-token",xY="x-aws-ec2-metadata-token-ttl-seconds"});var EY,tMe,IY,MR,$Y,rMe,RY,O4=_(()=>{C4();EY=1e3,tMe=6e4,IY=0,MR=async()=>{if(!process.env[vY]&&!(Date.now()<IY))try{let t=rMe(),e=(await RY({...t,path:bY,method:"PUT",headers:{[xY]:"21600"}})).toString();return(await RY({...t,path:_Y,method:"GET",headers:{[SY]:e}})).toString().trim()||$Y()}catch{return $Y()}},$Y=()=>{IY=Date.now()+tMe},rMe=()=>{let t=process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT;if(t){let e=new URL(t);return{hostname:e.hostname.replace(/^\[(.+)]$/,"$1"),port:e.port?Number(e.port):void 0}}return process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE==="IPv6"?{hostname:"fd00:ec2::254"}:{hostname:"169.254.169.254"}},RY=async t=>{let{request:e}=await import("node:http");return new Promise((r,o)=>{let n=e({hostname:t.hostname,port:t.port,path:t.path,method:t.method,headers:t.headers,timeout:EY,signal:AbortSignal.timeout(EY)});n.on("error",i=>{o(i),n.destroy()}),n.on("timeout",()=>{o(new Error("TimeoutError from instance metadata service")),n.destroy()}),n.on("response",i=>{let{statusCode:s=400}=i;if(s<200||s>=300){o(Object.assign(new Error("Error response received from instance metadata service"),{statusCode:s})),n.destroy();return}let a=[];i.on("data",c=>a.push(c)),i.on("end",()=>{r(Buffer.concat(a)),n.destroy()})}),n.end()})}});var om,im,on,Xn,D4=_(()=>{O4();om="AWS_REGION",im="region",on={environmentVariableSelector:t=>t[om],configFileSelector:t=>t[im],default:async()=>{let t=await MR();if(t)return t;throw new Error("Region is missing")}},Xn={preferredFile:"credentials"}});var AY,PY,kY=_(()=>{Pe();AY=new Set,PY=(t,e=Hi)=>{if(!AY.has(t)&&!e(t))if(t==="*")console.warn('@smithy/config-resolver WARN - Please use the caller region instead of "*". See "sigv4a" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.');else throw new Error(`Region not accepted: region="${t}" is not a valid hostname component.`);else AY.add(t)}});var UR,N4=_(()=>{UR=t=>typeof t=="string"&&(t.startsWith("fips-")||t.endsWith("-fips"))});var TY,CY=_(()=>{N4();TY=t=>UR(t)?["fips-aws-global","aws-fips"].includes(t)?"us-east-1":t.replace(/fips-(dkr-|prod-)?|-fips/,""):t});var No,OY=_(()=>{kY();CY();N4();No=t=>{let{region:e,useFipsEndpoint:r}=t;if(!e)throw new Error("Region is missing");return Object.assign(t,{region:async()=>{let o=typeof e=="function"?await e():e,n=TY(o);return PY(n),n},useFipsEndpoint:async()=>{let o=typeof e=="string"?e:await e();return UR(o)?!0:typeof r!="function"?Promise.resolve(!!r):r()}})}});var z4,DY=_(()=>{z4=(t=[],{useFipsEndpoint:e,useDualstackEndpoint:r})=>t.find(({tags:o})=>e===o.includes("fips")&&r===o.includes("dualstack"))?.hostname});var NY,zY=_(()=>{NY=(t,{regionHostname:e,partitionHostname:r})=>e||(r?r.replace("{region}",t):void 0)});var MY,UY=_(()=>{MY=(t,{partitionHash:e})=>Object.keys(e||{}).find(r=>e[r].regions.includes(t))??"aws"});var LY,jY=_(()=>{LY=(t,{signingRegion:e,regionRegex:r,useFipsEndpoint:o})=>{if(e)return e;if(o){let n=r.replace("\\\\","\\").replace(/^\^/g,"\\.").replace(/\$$/g,"\\."),i=t.match(n);if(i)return i[0].slice(1,-1)}}});var FY,qY=_(()=>{DY();zY();UY();jY();FY=(t,{useFipsEndpoint:e=!1,useDualstackEndpoint:r=!1,signingService:o,regionHash:n,partitionHash:i})=>{let s=MY(t,{partitionHash:i}),a=t in n?t:i[s]?.endpoint??t,c={useFipsEndpoint:e,useDualstackEndpoint:r},u=z4(n[a]?.variants,c),l=z4(i[s]?.variants,c),d=NY(a,{regionHostname:u,partitionHostname:l});if(d===void 0)throw new Error(`Endpoint resolution failed for: ${{resolvedRegion:a,useFipsEndpoint:e,useDualstackEndpoint:r}}`);let p=LY(d,{signingRegion:n[a]?.signingRegion,regionRegex:i[s].regionRegex,useFipsEndpoint:e});return{partition:s,signingService:o,hostname:d,...p&&{signingRegion:p},...n[a]?.signingService&&{signingService:n[a].signingService}}}});var nMe,oMe,VY,GY=_(()=>{nMe="AWS_DEFAULTS_MODE",oMe="defaults_mode",VY={environmentVariableSelector:t=>t[nMe],configFileSelector:t=>t[oMe],default:"legacy"}});var ea,iMe,sMe,HY=_(()=>{D4();O4();P4();ER();C4();GY();ea=({region:t=Ie(on),defaultsMode:e=Ie(VY)}={})=>tm(async()=>{let r=typeof e=="function"?await e():e;switch(r?.toLowerCase()){case"auto":return iMe(t);case"in-region":case"cross-region":case"mobile":case"standard":case"legacy":return Promise.resolve(r?.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw new Error(`Invalid parameter for "defaultsMode", expect ${wY.join(", ")}, got ${r}`)}}),iMe=async t=>{if(t){let e=typeof t=="function"?await t():t,r=await sMe();return r?e===r?"in-region":"cross-region":"standard"}return"standard"},sMe=async()=>process.env[yY]&&(process.env[k4]||process.env[T4])?process.env[k4]??process.env[T4]:MR()});var zo={};Ht(zo,{CONFIG_PREFIX_SEPARATOR:()=>Xs,CONFIG_USE_DUALSTACK_ENDPOINT:()=>DR,CONFIG_USE_FIPS_ENDPOINT:()=>zR,CredentialsProviderError:()=>$u,DEFAULT_PROFILE:()=>w4,DEFAULT_USE_DUALSTACK_ENDPOINT:()=>iY,DEFAULT_USE_FIPS_ENDPOINT:()=>cY,ENV_PROFILE:()=>v4,ENV_USE_DUALSTACK_ENDPOINT:()=>OR,ENV_USE_FIPS_ENDPOINT:()=>NR,NODE_REGION_CONFIG_FILE_OPTIONS:()=>Xn,NODE_REGION_CONFIG_OPTIONS:()=>on,NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS:()=>Ys,NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS:()=>Qs,ProviderError:()=>Do,REGION_ENV_NAME:()=>om,REGION_INI_NAME:()=>im,SelectorType:()=>$r,TokenProviderError:()=>bR,booleanSelector:()=>jr,chain:()=>SR,externalDataInterceptor:()=>QX,fromStatic:()=>CR,fromValue:()=>xR,getHomeDir:()=>Js,getProfileName:()=>IR,getRegionInfo:()=>FY,getSSOTokenFilepath:()=>AR,getSSOTokenFromFile:()=>NX,loadConfig:()=>Ie,loadSharedConfigFiles:()=>nm,loadSsoSessionData:()=>BX,memoize:()=>tm,nodeDualstackConfigSelectors:()=>sY,nodeFipsConfigSelectors:()=>uY,numberSelector:()=>OX,parseKnownFiles:()=>XX,readFile:()=>_d,resolveCustomEndpointsConfig:()=>dY,resolveDefaultsModeConfig:()=>ea,resolveEndpointsConfig:()=>hY,resolveRegionConfig:()=>No});var Dt=_(()=>{bv();_R();CX();h4();g4();ER();$R();DX();RR();rm();_4();b4();S4();zX();kR();ZX();YX();eY();$v();P4();A4();aY();lY();pY();gY();D4();OY();qY();HY()});var KY,BY,ZY,WY=_(()=>{KY="AWS_ENDPOINT_URL",BY="endpoint_url",ZY=t=>({environmentVariableSelector:e=>{let r=t.split(" ").map(i=>i.toUpperCase()),o=e[[KY,...r].join("_")];if(o)return o;let n=e[KY];if(n)return n},configFileSelector:(e,r)=>{if(e.services){let n=["services",e.services].join(".");if(!r||!r[n])throw new Error(`The services section "${e.services}" specified in the profile is not present in the shared configuration file.`);let i=r[n],s=t.split(" ").map(c=>c.toLowerCase()),a=i[[s.join("_"),BY].join(".")];if(a)return a}let o=e[BY];if(o)return o},default:void 0})});var aMe,cMe,JY,XY=_(()=>{Dt();aMe="AWS_IGNORE_CONFIGURED_ENDPOINT_URLS",cMe="ignore_configured_endpoint_urls",JY={environmentVariableSelector:t=>jr(t,aMe,$r.ENV),configFileSelector:t=>jr(t,cMe,$r.CONFIG),default:!1}});var Rv,YY=_(()=>{Dt();WY();XY();Rv=async t=>{if(!await Ie(JY)())return Ie(ZY(t??""))()}});var M4,uMe,lMe,dMe,QY,eQ,tQ=_(()=>{M4=async t=>{let e=t?.Bucket||"";if(typeof t.Bucket=="string"&&(t.Bucket=e.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))),eQ(e)){if(t.ForcePathStyle===!0)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!QY(e)||e.indexOf(".")!==-1&&!String(t.Endpoint).startsWith("http:")||e.toLowerCase()!==e||e.length<3)&&(t.ForcePathStyle=!0);return t.DisableMultiRegionAccessPoints&&(t.disableMultiRegionAccessPoints=!0,t.DisableMRAP=!0),t},uMe=/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/,lMe=/(\d+\.){3}\d+/,dMe=/\.\./,QY=t=>uMe.test(t)&&!lMe.test(t)&&!dMe.test(t),eQ=t=>{let[e,r,o,,,n]=t.split(":"),i=e==="arn"&&t.split(":").length>=6,s=!!(i&&r&&o&&n);if(i&&!s)throw new Error(`Invalid ARN: ${t} was an invalid ARN.`);return s}});var rQ=_(()=>{tQ()});var nQ,oQ=_(()=>{nQ=(t,e,r,o=!1)=>{let n=async()=>{let i;return o?i=r.clientContextParams?.[t]??r[t]??r[e]:i=r[t]??r[e],typeof i=="function"?i():i};return t==="credentialScope"||e==="CredentialScope"?async()=>{let i=typeof r.credentials=="function"?await r.credentials():r.credentials;return i?.credentialScope??i?.CredentialScope}:t==="accountId"||e==="AccountId"?async()=>{let i=typeof r.credentials=="function"?await r.credentials():r.credentials;return i?.accountId??i?.AccountId}:t==="endpoint"||e==="endpoint"?async()=>{if(r.isCustomEndpoint===!1)return;let i=await n();if(i&&typeof i=="object"){if("url"in i)return i.url.href;if("hostname"in i){let{protocol:s,hostname:a,port:c,path:u}=i;return`${s}//${a}${c?":"+c:""}${u}`}}return i}:n}});var LR=_(()=>{Pe()});function jR(t){return async(e,r,o,n)=>{if(!o.isCustomEndpoint&&!o.ignoreConfiguredEndpointUrls){let a;o.serviceConfiguredEndpoint?a=await o.serviceConfiguredEndpoint():a=await t(o.serviceId),a&&(o.endpoint=()=>Promise.resolve(To(a)),o.isCustomEndpoint=!0,n?.logger?.debug?.(`@smithy/core/endpoints - resolved endpoint from config: ${a}`))}let i=await Iv(e,r,o);if(typeof o.endpointProvider!="function")throw new Error("config.endpointProvider is not set.");let s=o.endpointProvider(i,n);if(o.isCustomEndpoint&&o.endpoint){let a=await o.endpoint();if(a?.headers){s.headers??={};for(let[c,u]of Object.entries(a.headers))s.headers[c]=Array.isArray(u)?u:[u]}}return s}}var Iv,FR=_(()=>{rQ();oQ();LR();Iv=async(t,e,r)=>{let o={},n=e?.getEndpointParameterInstructions?.()||{};for(let[i,s]of Object.entries(n))switch(s.type){case"staticContextParams":o[i]=s.value;break;case"contextParams":o[i]=t[s.name];break;case"clientContextParams":case"builtInParams":o[i]=await nQ(s.name,i,r,s.type!=="builtInParams")();break;case"operationContextParams":o[i]=s.get(t);break;default:throw new Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(s))}return Object.keys(n).length===0&&Object.assign(o,r),String(r.serviceId).toLowerCase()==="s3"&&await M4(o),o}});function pMe(t,e,r){t.__smithy_context?t.__smithy_context.features||(t.__smithy_context.features={}):t.__smithy_context={features:{}},t.__smithy_context.features[e]=r}function qR(t){let e=jR(t);return({config:r,instructions:o})=>(n,i)=>async s=>{r.isCustomEndpoint&&pMe(i,"ENDPOINT_OVERRIDE","N");let a=await e(s.input,{getEndpointParameterInstructions(){return o}},{...r},i);i.endpointV2=a,i.authSchemes=a.properties?.authSchemes;let c=i.authSchemes?.[0];if(c){i.signing_region=c.signingRegion,i.signing_service=c.signingName;let l=Bt(i)?.selectedHttpAuthScheme?.httpAuthOption;l&&(l.signingProperties=Object.assign(l.signingProperties||{},{signing_region:c.signingRegion,signingRegion:c.signingRegion,signing_service:c.signingName,signingName:c.signingName,signingRegionSet:c.signingRegionSet},c.properties))}return n({...s})}}var U4=_(()=>{Pe();FR()});function iQ(t){let e=qR(t);return(r,o)=>({applyToStack:n=>{n.addRelativeTo(e({config:r,instructions:o}),L4)}})}var fMe,L4,j4=_(()=>{U4();fMe={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0},L4={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:fMe.name}});function sQ(t){return e=>{let r=e.tls??!0,{endpoint:o,useDualstackEndpoint:n,useFipsEndpoint:i}=e,s=o!=null?async()=>To(await jt(o)()):void 0,c=Object.assign(e,{endpoint:s,tls:r,isCustomEndpoint:!!o,useDualstackEndpoint:jt(n??!1),useFipsEndpoint:jt(i??!1),ignoreConfiguredEndpointUrls:!!e.ignoreConfiguredEndpointUrls}),u;return c.serviceConfiguredEndpoint=async()=>(e.serviceId&&!u&&(u=t(e.serviceId)),u),c}}var aQ=_(()=>{Pe();LR()});var ci,cQ=_(()=>{ci=class t{nodes;root;conditions;results;constructor(e,r,o,n){this.nodes=e,this.root=r,this.conditions=o,this.results=n}static from(e,r,o,n){return new t(e,r,o,n)}}});var ui,uQ=_(()=>{ui=class{capacity;data=new Map;parameters=[];constructor({size:e,params:r}){this.capacity=e??50,r&&(this.parameters=r)}get(e,r){let o=this.hash(e);if(o===!1)return r();if(!this.data.has(o)){if(this.data.size>this.capacity+10){let n=this.data.keys(),i=0;for(;;){let{value:s,done:a}=n.next();if(this.data.delete(s),a||++i>10)break}}this.data.set(o,r())}return this.data.get(o)}size(){return this.data.size}hash(e){let r="",{parameters:o}=this;if(o.length===0)return!1;for(let n of o){let i=e[n],s=i==null?"\0":String(i);if(s.includes("|;"))return!1;r+=s+"|;"}return r}}});var pt,lQ=_(()=>{pt=class extends Error{constructor(e){super(e),this.name="EndpointError"}}});var Mo=_(()=>{lQ()});var ta,dQ=_(()=>{ta="endpoints"});function Uo(t){return typeof t!="object"||t==null?t:"ref"in t?`$${Uo(t.ref)}`:"fn"in t?`${t.fn}(${(t.argv||[]).map(Uo).join(", ")})`:JSON.stringify(t,null,2)}var pQ=_(()=>{});var Av=_(()=>{dQ();pQ()});var ho,F4=_(()=>{ho={}});var q4,fQ=_(()=>{q4=(t,e)=>t===e});function V4(...t){for(let e of t)if(e!=null)return e}var mQ=_(()=>{});var hQ,gQ=_(()=>{Mo();hQ=t=>{let e=t.split("."),r=[];for(let o of e){let n=o.indexOf("[");if(n!==-1){if(o.indexOf("]")!==o.length-1)throw new pt(`Path: '${t}' does not end with ']'`);let i=o.slice(n+1,-1);if(Number.isNaN(parseInt(i)))throw new pt(`Invalid array index: '${i}' in path: '${t}'`);n!==0&&r.push(o.slice(0,n)),r.push(i)}else r.push(o)}return r}});var Pv,yQ=_(()=>{Mo();gQ();Pv=(t,e)=>hQ(e).reduce((r,o)=>{if(typeof r!="object")throw new pt(`Index '${o}' in '${e}' not found in '${JSON.stringify(t)}'`);if(Array.isArray(r)){let n=parseInt(o);return r[n<0?r.length+n:n]}return r[o]},t)});var G4,vQ=_(()=>{G4=t=>t!=null});function H4(t,e,r){return t?e:r}var wQ=_(()=>{});var K4,_Q=_(()=>{K4=t=>!t});var mMe,lc,B4=_(()=>{mMe=new RegExp("^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$"),lc=t=>mMe.test(t)||t.startsWith("[")&&t.endsWith("]")});var VR,Z4,W4,bQ=_(()=>{VR=Vt(js());B4();Z4={[VR.EndpointURLScheme.HTTP]:80,[VR.EndpointURLScheme.HTTPS]:443},W4=t=>{let e=(()=>{try{if(t instanceof URL)return t;if(typeof t=="object"&&"hostname"in t){let{hostname:p,port:f,protocol:h="",path:y="",query:w={}}=t,b=new URL(`${h}//${p}${f?`:${f}`:""}${y}`);return b.search=Object.entries(w).map(([S,x])=>`${S}=${x}`).join("&"),b}return new URL(t)}catch{return null}})();if(!e)return console.error(`Unable to parse ${JSON.stringify(t)} as a whatwg URL.`),null;let r=e.href,{host:o,hostname:n,pathname:i,protocol:s,search:a}=e;if(a)return null;let c=s.slice(0,-1);if(!Object.values(VR.EndpointURLScheme).includes(c))return null;let u=lc(n),l=r.includes(`${o}:${Z4[c]}`)||typeof t=="string"&&t.includes(`${o}:${Z4[c]}`),d=`${o}${l?`:${Z4[c]}`:""}`;return{scheme:c,authority:d,path:i,normalizedPath:i.endsWith("/")?i:`${i}/`,isIp:u}}});function J4(t,e,r){if(r===1)return[t];if(t==="")return[""];let o=t.split(e);return r===0?o:o.slice(0,r-1).concat(o.slice(1).join(e))}var SQ=_(()=>{});var X4,xQ=_(()=>{X4=(t,e)=>t===e});var Y4,EQ=_(()=>{Y4=(t,e,r,o)=>t==null||e>=r||t.length<r||/[^\u0000-\u007f]/.test(t)?null:o?t.substring(t.length-r,t.length-e):t.substring(e,r)});var Q4,$Q=_(()=>{Q4=t=>encodeURIComponent(t).replace(/[!*'()]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)});var eF=_(()=>{fQ();mQ();yQ();vQ();Pe();wQ();_Q();bQ();SQ();xQ();EQ();$Q()});var RQ,IQ=_(()=>{eF();RQ={booleanEquals:q4,coalesce:V4,getAttr:Pv,isSet:G4,isValidHostLabel:Hi,ite:H4,not:K4,parseURL:W4,split:J4,stringEquals:X4,substring:Y4,uriEncode:Q4}});var GR,tF=_(()=>{eF();GR=(t,e)=>{let r=[],{referenceRecord:o,endpointParams:n}=e,i=0;for(;i<t.length;){let s=t.indexOf("{",i);if(s===-1){r.push(t.slice(i));break}r.push(t.slice(i,s));let a=t.indexOf("}",s);if(a===-1){r.push(t.slice(s));break}t[s+1]==="{"&&t[a+1]==="}"&&(r.push(t.slice(s+1,a)),i=a+2);let c=t.substring(s+1,a);if(c.includes("#")){let[u,l]=c.split("#");r.push(Pv(o[u]??n[u],l))}else r.push(o[c]??n[c]);i=a+1}return r.join("")}});var AQ,PQ=_(()=>{AQ=({ref:t},e)=>e.referenceRecord[t]??e.endpointParams[t]});var dc,HR,kQ,sm=_(()=>{Mo();F4();IQ();tF();PQ();dc=(t,e,r)=>{if(typeof t=="string")return GR(t,r);if(t.fn)return kQ.callFunction(t,r);if(t.ref)return AQ(t,r);throw new pt(`'${e}': ${String(t)} is not a string, function or reference.`)},HR=({fn:t,argv:e},r)=>{let o=Array(e.length);for(let s=0;s<o.length;++s){let a=e[s];typeof a=="boolean"||typeof a=="number"?o[s]=a:o[s]=kQ.evaluateExpression(a,"arg",r)}let n=t.indexOf(".");if(n!==-1){let a=ho[t.slice(0,n)]?.[t.slice(n+1)];if(typeof a=="function")return a(...o)}let i=RQ[t];if(typeof i=="function")return i(...o);throw new Error(`function ${t} not loaded in endpointFunctions.`)},kQ={evaluateExpression:dc,callFunction:HR}});var TQ=_(()=>{sm()});var KR,rF=_(()=>{Av();Mo();TQ();KR=(t,e)=>{let{assign:r}=t;if(r&&r in e.referenceRecord)throw new pt(`'${r}' is already defined in Reference Record.`);let o=HR(t,e);e.logger?.debug?.(`${ta} evaluateCondition: ${Uo(t)} = ${Uo(o)}`);let n=o===""?!0:!!o;return r!=null?{result:n,toAssign:{name:r,value:o}}:{result:n}}});var BR,nF=_(()=>{Mo();sm();BR=(t,e)=>Object.entries(t??{}).reduce((r,[o,n])=>(r[o]=n.map(i=>{let s=dc(i,"Header value entry",e);if(typeof s!="string")throw new pt(`Header '${o}' value '${s}' is not a string`);return s}),r),{})});var kv,CQ,OQ,oF=_(()=>{Mo();tF();kv=(t,e)=>Object.entries(t).reduce((r,[o,n])=>(r[o]=OQ.getEndpointProperty(n,e),r),{}),CQ=(t,e)=>{if(Array.isArray(t))return t.map(r=>CQ(r,e));switch(typeof t){case"string":return GR(t,e);case"object":if(t===null)throw new pt(`Unexpected endpoint property: ${t}`);return OQ.getEndpointProperties(t,e);case"boolean":return t;default:throw new pt(`Unexpected endpoint property type: ${typeof t}`)}},OQ={getEndpointProperty:CQ,getEndpointProperties:kv}});var ZR,iF=_(()=>{Mo();sm();ZR=(t,e)=>{let r=dc(t,"Endpoint URL",e);if(typeof r=="string")try{return new URL(r)}catch(o){throw console.error(`Failed to construct URL with ${r}`,o),o}throw new pt(`Endpoint URL must be a string, got ${typeof r}`)}});var sF,ra,DQ=_(()=>{Mo();rF();sm();nF();oF();iF();sF=1e8,ra=(t,e)=>{let{nodes:r,root:o,results:n,conditions:i}=t,s=o,a={},c={referenceRecord:a,endpointParams:e.endpointParams,logger:e.logger};for(;s!==1&&s!==-1&&s<sF;){let u=3*(Math.abs(s)-1),[l,d,p]=[r[u],r[u+1],r[u+2]],[f,h,y]=i[l],w=KR({fn:f,assign:y,argv:h},c);if(w.toAssign){let{name:b,value:S}=w.toAssign;a[b]=S}s=s>=0===w.result?d:p}if(s>=sF){let u=n[s-sF];if(u[0]===-1){let[,f]=u;throw new pt(dc(f,"Error",c))}let[l,d,p]=u;return{url:ZR(l,c),properties:kv(d,c),headers:BR(p??{},c)}}throw new pt("No matching endpoint.")}});var am,WR=_(()=>{Av();rF();am=(t=[],e)=>{let r={},o={...e,referenceRecord:{...e.referenceRecord}},n=!1;for(let i of t){let{result:s,toAssign:a}=KR(i,o);if(!s)return{result:s};a&&(n=!0,r[a.name]=a.value,o.referenceRecord[a.name]=a.value,e.logger?.debug?.(`${ta} assign: ${a.name} := ${Uo(a.value)}`))}return n?{result:!0,referenceRecord:r}:{result:!0}}});var NQ,zQ=_(()=>{Av();WR();nF();oF();iF();NQ=(t,e)=>{let{conditions:r,endpoint:o}=t,{result:n,referenceRecord:i}=am(r,e);if(!n)return;let s=i?{...e,referenceRecord:{...e.referenceRecord,...i}}:e,{url:a,properties:c,headers:u}=o;e.logger?.debug?.(`${ta} Resolving endpoint from template: ${Uo(o)}`);let l={url:ZR(a,s)};return u!=null&&(l.headers=BR(u,s)),c!=null&&(l.properties=kv(c,s)),l}});var MQ,UQ=_(()=>{Mo();WR();sm();MQ=(t,e)=>{let{conditions:r,error:o}=t,{result:n,referenceRecord:i}=am(r,e);if(!n)return;let s=i?{...e,referenceRecord:{...e.referenceRecord,...i}}:e;throw new pt(dc(o,"Error",s))}});var JR,LQ,aF,jQ=_(()=>{Mo();WR();zQ();UQ();JR=(t,e)=>{for(let r of t)if(r.type==="endpoint"){let o=NQ(r,e);if(o)return o}else if(r.type==="error")MQ(r,e);else if(r.type==="tree"){let o=aF.evaluateTreeRule(r,e);if(o)return o}else throw new pt(`Unknown endpoint rule: ${r}`);throw new pt("Rules evaluation failed")},LQ=(t,e)=>{let{conditions:r,rules:o}=t,{result:n,referenceRecord:i}=am(r,e);if(!n)return;let s=i?{...e,referenceRecord:{...e.referenceRecord,...i}}:e;return aF.evaluateRules(o,s)},aF={evaluateRules:JR,evaluateTreeRule:LQ}});var FQ=_(()=>{jQ()});var Tv,qQ=_(()=>{Pe();Av();Mo();FQ();Tv=(t,e)=>{let{endpointParams:r,logger:o}=e,{parameters:n,rules:i}=t;e.logger?.debug?.(`${ta} Initial EndpointParams: ${Uo(r)}`);for(let a in n){if(!Se(n,a))continue;let c=n[a],u=r[a];if(u==null&&c.default!=null){r[a]=c.default;continue}if(c.required&&u==null)throw new pt(`Missing required parameter: '${a}'`)}let s=JR(i,{endpointParams:r,logger:o,referenceRecord:{}});return e.logger?.debug?.(`${ta} Resolved endpoint: ${Uo(s)}`),s}});var VQ,GQ=_(()=>{VQ=t=>{let{endpoint:e}=t;return e===void 0&&(t.endpoint=async()=>{throw new Error("@smithy/middleware-endpoint: (default endpointRuleSet) endpoint is not set - you must configure an endpoint.")}),t}});var cF={};Ht(cF,{BinaryDecisionDiagram:()=>ci,EndpointCache:()=>ui,EndpointError:()=>pt,customEndpointFunctions:()=>ho,decideEndpoint:()=>ra,endpointMiddleware:()=>gMe,endpointMiddlewareOptions:()=>L4,getEndpointFromInstructions:()=>hMe,getEndpointPlugin:()=>fc,isIpAddress:()=>lc,isValidHostLabel:()=>Hi,middlewareEndpointToEndpointV1:()=>To,resolveEndpoint:()=>Tv,resolveEndpointConfig:()=>pc,resolveEndpointRequiredConfig:()=>VQ,resolveParams:()=>Iv,toEndpointV1:()=>To});var hMe,pc,gMe,fc,Jt=_(()=>{YY();FR();U4();j4();aQ();Pe();cQ();uQ();DQ();B4();Pe();F4();qQ();Mo();FR();LR();j4();GQ();hMe=jR(Rv),pc=sQ(Rv),gMe=qR(Rv),fc=iQ(Rv)});var XR,uF=_(()=>{Jt();XR=(t,e)=>(r,o)=>async n=>{let i=t,s=o.endpointV2?async()=>To(o.endpointV2):i.endpoint;if(!s)throw new Error("No valid endpoint provider available.");let a=await e(n.input,{...t,endpoint:s});return r({...n,request:a})}});function HQ(t,e,r){return{applyToStack:o=>{o.add(wR(t,r),lF),o.add(XR(t,e),dF)}}}var lF,dF,KQ=_(()=>{m4();uF();lF={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},dF={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0}});import{createHash as yMe,createHmac as vMe}from"node:crypto";function BQ(t,e){return Buffer.isBuffer(t)?t:typeof t=="string"?_u(t,e):ArrayBuffer.isView(t)?Zi(t.buffer,t.byteOffset,t.byteLength):Zi(t)}var YR,ZQ=_(()=>{bu();p4();YR=class{algorithmIdentifier;secret;hash;constructor(e,r){this.algorithmIdentifier=e,this.secret=r,this.reset()}update(e,r){this.hash.update(Jn(BQ(e,r)))}digest(){return Promise.resolve(this.hash.digest())}reset(){this.hash=this.secret?vMe(this.algorithmIdentifier,BQ(this.secret)):yMe(this.algorithmIdentifier)}}});import{Readable as wMe}from"node:stream";var cm,pF=_(()=>{e4();cm=class extends wMe{expectedChecksum;checksumSourceLocation;checksum;source;base64Encoder;constructor({expectedChecksum:e,checksum:r,source:o,checksumSourceLocation:n,base64Encoder:i}){if(super(),typeof o.pipe!="function")throw new Error(`@smithy/util-stream: unsupported source type ${o?.constructor?.name??o} in ChecksumStream.`);this.source=o,this.base64Encoder=i??Wt,this.expectedChecksum=e,this.checksum=r,this.checksumSourceLocation=n,this.source.on("data",this.onSourceData),this.source.on("end",this.onSourceEnd),this.source.on("error",this.onSourceError),this.source.on("close",this.onSourceClose),this.source.pause()}onSourceData=e=>{if(!this.destroyed){try{this.checksum.update(e)}catch(r){this.destroy(r);return}this.push(e)||this.source.pause()}};onSourceEnd=async()=>{if(!this.destroyed){try{let e=await this.checksum.digest(),r=this.base64Encoder(e);if(this.expectedChecksum!==r){this.destroy(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${r}" in response header "${this.checksumSourceLocation}".`));return}}catch(e){this.destroy(e);return}this.push(null)}};onSourceError=e=>{this.destroy(e)};onSourceClose=()=>{!this.destroyed&&!this.source.readableEnded&&this.destroy(new Error("Connection lost or stream closed before all data was received."))};_read(e){this.source.resume()}_destroy(e,r){this.source?.removeListener("data",this.onSourceData),this.source?.removeListener("end",this.onSourceEnd),this.source?.removeListener("error",this.onSourceError),this.source?.removeListener("close",this.onSourceClose),this.source?.destroy(),r(e)}}});var Cr,Ru,Wi=_(()=>{Cr=t=>typeof ReadableStream=="function"&&(t?.constructor?.name===ReadableStream.name||t instanceof ReadableStream),Ru=t=>typeof Blob=="function"&&(t?.constructor?.name===Blob.name||t instanceof Blob)});var WQ,JQ=_(()=>{WQ=t=>new TextEncoder().encode(t)});var XQ,eTt,YQ,QR,fF,QQ,eee=_(()=>{XQ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",eTt=Object.entries(XQ).reduce((t,[e,r])=>(t[r]=Number(e),t),{}),YQ=XQ.split(""),QR=6,fF=8,QQ=63});function eI(t){let e;typeof t=="string"?e=WQ(t):e=t;let r=typeof e=="object"&&typeof e.length=="number",o=typeof e=="object"&&typeof e.byteOffset=="number"&&typeof e.byteLength=="number";if(!r&&!o)throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");let n="";for(let i=0;i<e.length;i+=3){let s=0,a=0;for(let u=i,l=Math.min(i+3,e.length);u<l;u++)s|=e[u]<<(l-u-1)*fF,a+=fF;let c=Math.ceil(a/QR);s<<=c*QR-a;for(let u=1;u<=c;u++){let l=(c-u)*QR;n+=YQ[(s&QQ<<l)>>l]}n+="==".slice(0,4-c)}return n}var mF=_(()=>{JQ();eee()});var _Me,tI,tee=_(()=>{_Me=typeof ReadableStream=="function"?ReadableStream:function(){},tI=class extends _Me{}});var ree,nee=_(()=>{mF();Wi();tee();ree=({expectedChecksum:t,checksum:e,source:r,checksumSourceLocation:o,base64Encoder:n})=>{if(!Cr(r))throw new Error(`@smithy/util-stream: unsupported source type ${r?.constructor?.name??r} in ChecksumStream.`);let i=n??eI;if(typeof TransformStream!="function")throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream.");let s=new TransformStream({start(){},async transform(c,u){e.update(c),u.enqueue(c)},async flush(c){let u=await e.digest(),l=i(u);if(t!==l){let d=new Error(`Checksum mismatch: expected "${t}" but received "${l}" in response header "${o}".`);c.error(d)}else c.terminate()}});r.pipeThrough(s);let a=s.readable;return Object.setPrototypeOf(a,tI.prototype),a}});function oee(t){return typeof ReadableStream=="function"&&Cr(t.source)?ree(t):new cm(t)}var iee=_(()=>{Wi();pF();nee()});var bd,hF=_(()=>{bd=class{allocByteArray;byteLength=0;byteArrays=[];constructor(e){this.allocByteArray=e}push(e){this.byteArrays.push(e),this.byteLength+=e.byteLength}flush(){if(this.byteArrays.length===1){let o=this.byteArrays[0];return this.reset(),o}let e=this.allocByteArray(this.byteLength),r=0;for(let o=0;o<this.byteArrays.length;++o){let n=this.byteArrays[o];e.set(n,r),r+=n.byteLength}return this.reset(),e}reset(){this.byteArrays=[],this.byteLength=0}}});function see(t,e,r){let o=t.getReader(),n=!1,i=0,s=["",new bd(u=>new Uint8Array(u))],a=-1,c=async u=>{let{value:l,done:d}=await o.read(),p=l;if(d){if(a!==-1){let f=Sd(s,a);mc(f)>0&&u.enqueue(f)}u.close()}else{let f=yF(p,!1);if(a!==f&&(a>=0&&u.enqueue(Sd(s,a)),a=f),a===-1){u.enqueue(p);return}let h=mc(p);i+=h;let y=mc(s[a]);if(h>=e&&y===0)u.enqueue(p);else{let w=gF(s,a,p);!n&&i>e*2&&(n=!0,r?.warn(`@smithy/util-stream - stream chunk size ${h} is below threshold of ${e}, automatically buffering.`)),w>=e?u.enqueue(Sd(s,a)):await c(u)}}};return new ReadableStream({pull:c})}function gF(t,e,r){switch(e){case 0:return t[0]+=r,mc(t[0]);case 1:case 2:return t[e].push(r),mc(t[e])}}function Sd(t,e){switch(e){case 0:let r=t[0];return t[0]="",r;case 1:case 2:return t[e].flush()}throw new Error(`@smithy/util-stream - invalid index ${e} given to flush()`)}function mc(t){return t?.byteLength??t?.length??0}function yF(t,e=!0){return e&&typeof Buffer<"u"&&t instanceof Buffer?2:t instanceof Uint8Array?1:typeof t=="string"?0:-1}var aee=_(()=>{hF()});import{Readable as bMe}from"node:stream";function cee(t,e,r){if(Cr(t))return see(t,e,r);let o=new bMe({read(){}}),n=!1,i=0,s=["",new bd(c=>new Uint8Array(c)),new bd(c=>Buffer.from(new Uint8Array(c)))],a=-1;return t.on("data",c=>{let u=yF(c,!0);if(a!==u&&(a>=0&&o.push(Sd(s,a)),a=u),a===-1){o.push(c);return}let l=mc(c);i+=l;let d=mc(s[a]);if(l>=e&&d===0)o.push(c);else{let p=gF(s,a,c);!n&&i>e*2&&(n=!0,r?.warn(`@smithy/util-stream - stream chunk size ${l} is below threshold of ${e}, automatically buffering.`)),p>=e&&o.push(Sd(s,a))}}),t.on("end",()=>{if(a!==-1){let c=Sd(s,a);mc(c)>0&&o.push(c)}o.push(null)}),o}var uee=_(()=>{hF();aee();Wi()});var lee,dee=_(()=>{lee=(t,e)=>{let{base64Encoder:r,bodyLengthChecker:o,checksumAlgorithmFn:n,checksumLocationName:i,streamHasher:s}=e,a=r!==void 0&&o!==void 0&&n!==void 0&&i!==void 0&&s!==void 0,c=a?s(n,t):void 0;Promise.resolve(c).catch(()=>{});let u=t.getReader();return new ReadableStream({async pull(l){let{value:d,done:p}=await u.read();if(p){if(l.enqueue(`0\r
@@ -22,7 +22,7 @@ ${d}\r
22
22
  `),u){let p=n(await l);d.push(`${a}:${p}\r
23
23
  `),d.push(`\r
24
24
  `)}d.push(null)}catch(p){d.destroy(p)}}),d}var fee=_(()=>{dee();Wi()});async function mee(t,e){let r=0,o=[],n=t.getReader(),i=!1;for(;!i;){let{done:c,value:u}=await n.read();if(u&&(o.push(u),r+=u?.byteLength??0),r>=e)break;i=c}n.releaseLock();let s=new Uint8Array(Math.min(e,r)),a=0;for(let c of o){if(c.byteLength>s.byteLength-a){s.set(c.subarray(0,s.byteLength-a),a);break}else s.set(c,a);a+=c.length}return s}var hee=_(()=>{});import{Writable as xMe}from"node:stream";var gee,vF,yee=_(()=>{_v();hee();Wi();gee=(t,e)=>Cr(t)?mee(t,e):new Promise((r,o)=>{let n=new vF;n.limit=e,t.pipe(n),t.on("error",i=>{n.end(),o(i)}),n.on("error",o),n.on("finish",function(){let i=Ws(this.buffers);r(i)})}),vF=class extends xMe{buffers=[];limit=1/0;bytesBuffered=0;_write(e,r,o){if(this.buffers.push(e),this.bytesBuffered+=e.byteLength??0,this.bytesBuffered>=this.limit){let n=this.bytesBuffered-this.limit,i=this.buffers[this.buffers.length-1];this.buffers[this.buffers.length-1]=i.subarray(0,i.byteLength-n),this.emit("finish")}o()}}});var vee,wee=_(()=>{vee=t=>{if(typeof t=="string")return t;if(typeof t!="object"||typeof t.byteOffset!="number"||typeof t.byteLength!="number")throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return new TextDecoder("utf-8").decode(t)}});async function wF(t){return t.arrayBuffer().then(e=>new Uint8Array(e))}async function _F(t){let e=[],r=t.getReader(),o=0;for(;;){let{done:n,value:i}=await r.read();if(i&&(e.push(i),o+=i.length),n)break}return Ws(e,o)}var _ee,bF=_(()=>{_v();Wi();_ee=async t=>Ru(t)?wF(t):_F(t)});var bee,xee,See,Eee=_(()=>{mF();d4();wee();bF();Wi();bee="The stream has already been transformed.",xee=t=>{if(!See(t)&&!Cr(t)){let n=t?.__proto__?.constructor?.name||t;throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${n}`)}let e=!1,r=async()=>{if(e)throw new Error(bee);return e=!0,await _ee(t)},o=n=>{if(typeof n.stream!="function")throw new Error(`Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.
25
- If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body`);return n.stream()};return Object.assign(t,{transformToByteArray:r,transformToString:async n=>{let i=await r();if(n==="base64")return eI(i);if(n==="hex")return ai(i);if(n===void 0||n==="utf8"||n==="utf-8")return vee(i);if(typeof TextDecoder=="function")return new TextDecoder(n).decode(i);throw new Error("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(e)throw new Error(bee);if(e=!0,See(t))return o(t);if(Cr(t))return t;throw new Error(`Cannot transform payload to web stream, got ${t}`)}})},See=t=>typeof Blob=="function"&&t instanceof Blob});import{Writable as EMe}from"node:stream";var rI,SF,xF=_(()=>{_v();bF();Wi();rI=t=>Ru(t)?wF(t):Cr(t)?_F(t):new Promise((e,r)=>{let o=new SF,n=t;n.pipe(o),n.on("error",i=>{o.end(),r(i)}),o.on("error",r),o.on("finish",function(){let i=Ws(this.bufferedBytes);e(i)})}),SF=class extends EMe{bufferedBytes=[];_write(e,r,o){this.bufferedBytes.push(e),o()}}});import{Readable as EF}from"node:stream";var $ee,nI,Ree=_(()=>{bu();Eee();xF();$ee="The stream has already been transformed.",nI=t=>{if(!(t instanceof EF))try{return xee(t)}catch{let n=t?.__proto__?.constructor?.name||t;throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${n}`)}let e=!1,r=async()=>{if(e)throw new Error($ee);return e=!0,await rI(t)};return Object.assign(t,{transformToByteArray:r,transformToString:async o=>{let n=await r();return o===void 0||Buffer.isEncoding(o)?Zi(n.buffer,n.byteOffset,n.byteLength).toString(o):new TextDecoder(o).decode(n)},transformToWebStream:()=>{if(e)throw new Error($ee);if(t.readableFlowing!==null)throw new Error("The stream has been consumed by other callbacks.");if(typeof EF.toWeb!="function")throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available.");return e=!0,EF.toWeb(t)}})}});async function Iee(t){return typeof t.stream=="function"&&(t=t.stream()),t.tee()}var Aee=_(()=>{});import{PassThrough as Pee}from"node:stream";async function kee(t){if(Cr(t)||Ru(t))return Iee(t);let e=new Pee,r=new Pee;return t.pipe(e),t.pipe(r),[e,r]}var Tee=_(()=>{Aee();Wi()});var Ed={};Ht(Ed,{ChecksumStream:()=>cm,Hash:()=>YR,LazyJsonString:()=>Er,NumericValue:()=>nt,Uint8ArrayBlobAdapter:()=>xd,_parseEpochTimestamp:()=>Eu,_parseRfc3339DateTimeWithOffset:()=>mR,_parseRfc7231DateTime:()=>hR,calculateBodyLength:()=>Zs,concatBytes:()=>Ws,copyDocumentWithTransform:()=>iX,createBufferedReadable:()=>cee,createChecksumStream:()=>oee,dateToUtcString:()=>Oo,deserializerMiddleware:()=>wR,deserializerMiddlewareOption:()=>lF,expectBoolean:()=>cX,expectByte:()=>aR,expectFloat32:()=>yv,expectInt:()=>uX,expectInt32:()=>iR,expectLong:()=>Zf,expectNonNull:()=>lX,expectNumber:()=>Bf,expectObject:()=>r4,expectShort:()=>sR,expectString:()=>dX,expectUnion:()=>uR,fromArrayBuffer:()=>Zi,fromBase64:()=>pr,fromHex:()=>vR,fromString:()=>_u,fromUtf8:()=>Tr,generateIdempotencyToken:()=>Lo,getAwsChunkedEncodingStream:()=>pee,getSerdePlugin:()=>HQ,handleFloat:()=>fX,hasOwn:()=>Se,headStream:()=>gee,isArrayBuffer:()=>rR,isBlob:()=>Ru,isReadableStream:()=>Cr,limitedParseDouble:()=>dR,limitedParseFloat:()=>mX,limitedParseFloat32:()=>hX,logger:()=>Wf,nv:()=>yR,parseBoolean:()=>aX,parseEpochTimestamp:()=>Qf,parseRfc3339DateTime:()=>wX,parseRfc3339DateTimeWithOffset:()=>Yf,parseRfc7231DateTime:()=>xu,quoteHeader:()=>fR,sdkStreamMixin:()=>nI,serializerMiddleware:()=>XR,serializerMiddlewareOption:()=>dF,splitEvery:()=>gR,splitHeader:()=>em,splitStream:()=>kee,streamCollector:()=>rI,strictParseByte:()=>pR,strictParseDouble:()=>vv,strictParseFloat:()=>pX,strictParseFloat32:()=>lR,strictParseInt:()=>yX,strictParseInt32:()=>vX,strictParseLong:()=>n4,strictParseShort:()=>Su,toBase64:()=>Wt,toHex:()=>ai,toUint8Array:()=>Jn,toUtf8:()=>ur,v4:()=>um});import{getRandomValues as $Me}from"node:crypto";var xd,RMe,um,Lo,xe=_(()=>{Q7();e4();tX();nR();rX();oX();sX();_X();bX();o4();SX();$X();RX();IX();PX();d4();TX();p4();_v();bu();Qj();m4();KQ();uF();ZQ();pF();iee();uee();fee();yee();Ree();Tee();Wi();xF();Pe();xd=class extends eX(ur,Tr,Wt,pr){},RMe=$Me,um=nX(RMe),Lo=um});var sn,oI=_(()=>{xe();sn=async(t=new Uint8Array,e)=>{if(t instanceof Uint8Array)return xd.mutate(t);if(!t)return xd.mutate(new Uint8Array);let r=e.streamCollector(t);return xd.mutate(await r)}});function Ji(t){return encodeURIComponent(t).replace(/[!'()*]/g,function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})}var iI=_(()=>{});var Fr,lm=_(()=>{Fr=class{serdeContext;setSerdeContext(e){this.serdeContext=e}}});async function sI(t,e,r=1024*1024){let o=t.size,n=0;for(;n<o;){let i=t.slice(n,Math.min(o,n+r));e(new Uint8Array(await i.arrayBuffer())),n+=i.size}}var $F=_(()=>{});var Cee,Oee=_(()=>{$F();Cee=async function(e,r){let o=new e;return await sI(r,n=>{o.update(n)}),o.digest()}});import{Writable as IMe}from"node:stream";var dm,RF=_(()=>{xe();dm=class extends IMe{hash;constructor(e,r){super(r),this.hash=e}_write(e,r,o){try{this.hash.update(Jn(e))}catch(n){return o(n)}o()}}});import{createReadStream as AMe}from"node:fs";var Dee,PMe,Nee=_(()=>{RF();Dee=(t,e)=>new Promise((r,o)=>{if(!PMe(e)){o(new Error("Unable to calculate hash for non-file streams."));return}let n=AMe(e.path,{start:e.start,end:e.end}),i=new t,s=new dm(i);n.pipe(s),n.on("error",a=>{s.end(),o(a)}),s.on("error",o),s.on("finish",function(){i.digest().then(r).catch(o)})}),PMe=t=>typeof t.path=="string"});var zee,Mee=_(()=>{RF();zee=(t,e)=>{if(e.readableFlowing!==null)throw new Error("Unable to calculate hash for flowing readable stream");let r=new t,o=new dm(r);return e.pipe(o),new Promise((n,i)=>{e.on("error",s=>{o.end(),i(s)}),o.on("error",i),o.on("finish",()=>{r.digest().then(n).catch(i)})})}});function IF(t,e){let r=t[0],o=t[1],n=t[2],i=t[3];for(let s=0;s<64;++s){let a,c;s<16?(a=o&n|~o&i,c=s):s<32?(a=i&o|n&~i,c=(5*s+1)%16):s<48?(a=o^n^i,c=(3*s+5)%16):(a=n^(o|~i),c=7*s%16);let u=e.getUint32(c*4,!0),l=i;i=n,n=o;let d=kMe[(s>>4)*4+(s&3)],p=(r+a&Iu)+(u+TMe[s]&Iu)&Iu;o=o+((p<<d|p>>>32-d)>>>0)&Iu,r=l}t[0]=t[0]+r&Iu,t[1]=t[1]+o&Iu,t[2]=t[2]+n&Iu,t[3]=t[3]+i&Iu}var pm,Uee,Iu,kMe,TMe,AF=_(()=>{xe();pm=class{digestLength=16;state=Uint32Array.from(Uee);writeBuffer=new DataView(new ArrayBuffer(64));bufferLength=0;bytesHashed=0;update(e){let r=Jn(e),o=0,n=r.byteLength;for(this.bytesHashed+=n;n>0;)this.writeBuffer.setUint8(this.bufferLength++,r[o++]),--n,this.bufferLength===64&&(IF(this.state,this.writeBuffer),this.bufferLength=0)}async digest(){let e=Uint32Array.from(this.state),r=new DataView(this.writeBuffer.buffer.slice(0)),o=this.bufferLength,n=this.bytesHashed*8;if(r.setUint8(o++,128),this.bufferLength%64>=56){for(let a=o;a<64;++a)r.setUint8(a,0);IF(e,r),o=0}for(let a=o;a<56;++a)r.setUint8(a,0);r.setUint32(56,n>>>0,!0),r.setUint32(60,Math.floor(n/2**32),!0),IF(e,r);let i=new Uint8Array(16),s=new DataView(i.buffer);for(let a=0;a<4;++a)s.setUint32(a*4,e[a],!0);return i}reset(){this.state.set(Uee),this.writeBuffer=new DataView(new ArrayBuffer(64)),this.bufferLength=0,this.bytesHashed=0}},Uee=[1732584193,4023233417,2562383102,271733878],Iu=4294967295,kMe=Uint8Array.of(7,12,17,22,5,9,14,20,4,11,16,23,6,10,15,21),TMe=Array.from({length:64},(t,e)=>Math.abs(Math.sin(e+1))*2**32>>>0)});import{createHash as PF}from"node:crypto";function OMe(){return class{digestLength=16;hash=PF("md5");update(e){this.hash.update(Jn(e))}async digest(){let e=this.hash.copy().digest();return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}reset(){this.hash=PF("md5")}}}var CMe,kF,Lee=_(()=>{xe();AF();CMe=(()=>{try{return PF("md5"),!0}catch{return!1}})(),kF=CMe?OMe():pm});var jee,TF,fm,CF=_(()=>{jee=new Uint32Array(256);for(let t=0;t<256;++t){let e=t;for(let r=0;r<8;++r)e=e&1?3988292384^e>>>1:e>>>1;jee[t]=e>>>0}TF=4294967295,fm=class{digestLength=4;checksum=TF;update(e){for(let r=0;r<e.length;++r)this.checksum=this.checksum>>>8^jee[(this.checksum^e[r])&255]}digestSync(){return(this.checksum^TF)>>>0}async digest(){let e=this.digestSync(),r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,e,!1),r}reset(){this.checksum=TF}}});import*as OF from"node:zlib";function DMe(t){return class{digestLength=4;value=0;update(r){this.value=t(r,this.value)}digestSync(){return this.value>>>0}async digest(){let r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,this.digestSync(),!1),r}reset(){this.value=0}}}var Fee,$d,qee=_(()=>{CF();Fee=typeof OF.crc32=="function"?OF.crc32:void 0,$d=Fee?DMe(Fee):fm});var an,Vee,NMe,hc,Gee,zMe,aI=_(()=>{xe();an=64,Vee=32,NMe=2**53-1,hc=class t{digestLength=Vee;state=Int32Array.from(Gee);w;buffer=new Uint8Array(64);bufferLength=0;bytesHashed=0;finished=!1;inner;outer;constructor(e){if(e){let r=t.normalizeKey(e);this.inner=new t,this.outer=new t;let{inner:o,outer:n}=this,i=new Uint8Array(an*2);for(let s=0;s<an;++s)i[s]=54^r[s],i[s+an]=92^r[s];o.update(i.subarray(0,an)),n.update(i.subarray(an))}}update(e){if(this.finished)throw new Error("Attempted to update an already finished HMAC.");if(this.inner){this.inner.update(e);return}let r=Jn(e),o=0,{byteLength:n}=r;if(this.bytesHashed+=n,this.bytesHashed*8>NMe)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;n>0;)this.buffer[this.bufferLength++]=r[o++],n--,this.bufferLength===an&&(this.hashBuffer(),this.bufferLength=0)}async digest(){let{inner:e,outer:r}=this;if(e&&r){if(this.finished)throw new Error("Attempted to digest an already finished HMAC.");this.finished=!0;let o=e.digestSync();return r.update(o),r.digestSync()}return this.digestSync()}reset(){this.state=Int32Array.from(Gee),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0}digestSync(){let e=this.state.slice(),r=this.buffer.slice(),o=this.bufferLength,n=this.bytesHashed*8,i=new DataView(r.buffer,r.byteOffset,r.byteLength);if(i.setUint8(o++,128),(o-1)%an>=an-8){for(let a=o;a<an;++a)i.setUint8(a,0);this.hashBufferWith(e,r),o=0}for(let a=o;a<an-8;++a)i.setUint8(a,0);i.setUint32(an-8,Math.floor(n/4294967296),!1),i.setUint32(an-4,n,!1),this.hashBufferWith(e,r);let s=new Uint8Array(Vee);for(let a=0;a<8;++a)s[a*4]=e[a]>>>24&255,s[a*4+1]=e[a]>>>16&255,s[a*4+2]=e[a]>>>8&255,s[a*4+3]=e[a]>>>0&255;return s}static normalizeKey(e){let r=Jn(e);if(r.byteLength>an){let o=new t;o.update(r);let n=o.digestSync(),i=new Uint8Array(an);return i.set(n),i}if(r.byteLength<an){let o=new Uint8Array(an);return o.set(r),o}return r}hashBuffer(){this.hashBufferWith(this.state,this.buffer)}hashBufferWith(e,r){let o=this.w??=new Int32Array(64),n=e[0],i=e[1],s=e[2],a=e[3],c=e[4],u=e[5],l=e[6],d=e[7];for(let p=0;p<an;++p){if(p<16)o[p]=(r[p*4]&255)<<24|(r[p*4+1]&255)<<16|(r[p*4+2]&255)<<8|r[p*4+3]&255;else{let y=o[p-2],w=(y>>>17|y<<15)^(y>>>19|y<<13)^y>>>10;y=o[p-15];let b=(y>>>7|y<<25)^(y>>>18|y<<14)^y>>>3;o[p]=(w+o[p-7]|0)+(b+o[p-16]|0)}let f=(((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))+(c&u^~c&l)|0)+(d+(zMe[p]+o[p]|0)|0)|0,h=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&i^n&s^i&s)|0;d=l,l=u,u=c,c=a+f|0,a=s,s=i,i=n,n=f+h|0}e[0]+=n,e[1]+=i,e[2]+=s,e[3]+=a,e[4]+=c,e[5]+=u,e[6]+=l,e[7]+=d}},Gee=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),zMe=new Int32Array([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])});import{createHash as Hee,createHmac as MMe}from"node:crypto";function LMe(){return class{digestLength=32;secret;hash;isHmac;finished=!1;constructor(e){this.secret=e,this.isHmac=!!e,this.hash=this.createHash()}update(e){if(this.finished)throw new Error("Attempted to update an already finished hash.");this.hash.update(e)}async digest(){let e;return this.isHmac?(this.finished=!0,e=this.hash.digest()):e=this.hash.copy().digest(),new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}reset(){this.hash=this.createHash(),this.finished=!1}createHash(){return this.secret?MMe("sha256",jMe(this.secret)):Hee("sha256")}}}function jMe(t){return typeof t=="string"?t:ArrayBuffer.isView(t)?Buffer.from(t.buffer,t.byteOffset,t.byteLength):Buffer.from(t)}var UMe,Xi,Kee=_(()=>{aI();UMe=(()=>{try{return Hee("sha256"),!0}catch{return!1}})(),Xi=UMe?LMe():hc});var FMe,qMe,VMe,cI,GMe,uI,Bee=_(()=>{xe();aI();({digest:FMe,sign:qMe,importKey:VMe}=globalThis?.crypto?.subtle??{}),cI=typeof FMe=="function"&&typeof qMe=="function"&&typeof VMe=="function"?globalThis.crypto.subtle:void 0,GMe=8*1024*1024,uI=class{digestLength=32;secret;pending=[];pendingBytes=0;fallback;finished=!1;constructor(e){e&&(this.secret=Jn(e))}update(e){if(this.finished)throw new Error("Attempted to update an already finished HMAC.");if(this.fallback){this.fallback.update(e);return}this.pending.push(e.slice()),this.pendingBytes+=e.byteLength,this.pendingBytes>=GMe&&this.switchToFallback()}async digest(){if(this.fallback)return this.fallback.digest();if(this.secret&&this.finished)throw new Error("Attempted to digest an already finished HMAC.");let e=Ws(this.pending);if(cI){if(this.secret){this.finished=!0;let n=await cI.importKey("raw",this.secret,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=await cI.sign("HMAC",n,e);return new Uint8Array(i)}let o=await cI.digest("SHA-256",e);return new Uint8Array(o)}let r=new hc(this.secret);return r.update(e),r.digest()}reset(){this.pending=[],this.pendingBytes=0,this.fallback=void 0,this.finished=!1}switchToFallback(){let e=new hc(this.secret);for(let r of this.pending)e.update(r);this.fallback=e,this.pending=[],this.pendingBytes=0}}});var DF={};Ht(DF,{Crc32:()=>$d,Crc32Js:()=>fm,Crc32Node:()=>$d,Md5:()=>kF,Md5Js:()=>pm,Md5Node:()=>kF,Sha256:()=>Xi,Sha256Js:()=>hc,Sha256Node:()=>Xi,Sha256WebCrypto:()=>uI,blobHasher:()=>Cee,blobReader:()=>sI,fileStreamHasher:()=>Dee,readableStreamHasher:()=>zee});var gc=_(()=>{Oee();Nee();Mee();AF();Lee();CF();qee();aI();Kee();Bee();$F()});function Zee(t){for(let e=0;e<8;e++)t[e]^=255;for(let e=7;e>-1&&(t[e]++,t[e]===0);e--);}var Au,NF=_(()=>{xe();Au=class t{bytes;constructor(e){if(this.bytes=e,e.byteLength!==8)throw new Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(e){if(e>9223372036854776e3||e<-9223372036854776e3)throw new Error(`${e} is too large (or, if negative, too small) to represent as an Int64`);let r=new Uint8Array(8);for(let o=7,n=Math.abs(Math.round(e));o>-1&&n>0;o--,n/=256)r[o]=n;return e<0&&Zee(r),new t(r)}valueOf(){let e=this.bytes.slice(0),r=e[0]&128;return r&&Zee(e),parseInt(ai(e),16)*(r?-1:1)}toString(){return String(this.valueOf())}}});var mm,Wee,Jee,HMe,KMe,BMe,ZMe,WMe,JMe,XMe,YMe,QMe,zF=_(()=>{Pe();xe();NF();mm=class{toUtf8;fromUtf8;constructor(e,r){this.toUtf8=e,this.fromUtf8=r}format(e){let r=[];for(let i in e){if(!Se(e,i))continue;let s=this.fromUtf8(i);r.push(Uint8Array.from([s.byteLength]),s,this.formatHeaderValue(e[i]))}let o=new Uint8Array(r.reduce((i,s)=>i+s.byteLength,0)),n=0;for(let i of r)o.set(i,n),n+=i.byteLength;return o}formatHeaderValue(e){switch(e.type){case"boolean":return Uint8Array.from([e.value?0:1]);case"byte":return Uint8Array.from([2,e.value]);case"short":let r=new DataView(new ArrayBuffer(3));return r.setUint8(0,3),r.setInt16(1,e.value,!1),new Uint8Array(r.buffer);case"integer":let o=new DataView(new ArrayBuffer(5));return o.setUint8(0,4),o.setInt32(1,e.value,!1),new Uint8Array(o.buffer);case"long":let n=new Uint8Array(9);return n[0]=5,n.set(e.value.bytes,1),n;case"binary":let i=new DataView(new ArrayBuffer(3+e.value.byteLength));i.setUint8(0,6),i.setUint16(1,e.value.byteLength,!1);let s=new Uint8Array(i.buffer);return s.set(e.value,3),s;case"string":let a=this.fromUtf8(e.value),c=new DataView(new ArrayBuffer(3+a.byteLength));c.setUint8(0,7),c.setUint16(1,a.byteLength,!1);let u=new Uint8Array(c.buffer);return u.set(a,3),u;case"timestamp":let l=new Uint8Array(9);return l[0]=8,l.set(Au.fromNumber(e.value.valueOf()).bytes,1),l;case"uuid":if(!QMe.test(e.value))throw new Error(`Invalid UUID received: ${e.value}`);let d=new Uint8Array(17);return d[0]=9,d.set(vR(e.value.replace(/-/g,"")),1),d}}parse(e){let r={},o=0;for(;o<e.byteLength;){let n=e.getUint8(o++),i=this.toUtf8(new Uint8Array(e.buffer,e.byteOffset+o,n));switch(o+=n,e.getUint8(o++)){case 0:r[i]={type:Jee,value:!0};break;case 1:r[i]={type:Jee,value:!1};break;case 2:r[i]={type:HMe,value:e.getInt8(o++)};break;case 3:r[i]={type:KMe,value:e.getInt16(o,!1)},o+=2;break;case 4:r[i]={type:BMe,value:e.getInt32(o,!1)},o+=4;break;case 5:r[i]={type:ZMe,value:new Au(new Uint8Array(e.buffer,e.byteOffset+o,8))},o+=8;break;case 6:let s=e.getUint16(o,!1);o+=2,r[i]={type:WMe,value:new Uint8Array(e.buffer,e.byteOffset+o,s)},o+=s;break;case 7:let a=e.getUint16(o,!1);o+=2,r[i]={type:JMe,value:this.toUtf8(new Uint8Array(e.buffer,e.byteOffset+o,a))},o+=a;break;case 8:r[i]={type:XMe,value:new Date(new Au(new Uint8Array(e.buffer,e.byteOffset+o,8)).valueOf())},o+=8;break;case 9:let c=new Uint8Array(e.buffer,e.byteOffset+o,16);o+=16,r[i]={type:YMe,value:`${ai(c.subarray(0,4))}-${ai(c.subarray(4,6))}-${ai(c.subarray(6,8))}-${ai(c.subarray(8,10))}-${ai(c.subarray(10))}`};break;default:throw new Error("Unrecognized header type tag")}}return r}};(function(t){t[t.boolTrue=0]="boolTrue",t[t.boolFalse=1]="boolFalse",t[t.byte=2]="byte",t[t.short=3]="short",t[t.integer=4]="integer",t[t.long=5]="long",t[t.byteArray=6]="byteArray",t[t.string=7]="string",t[t.timestamp=8]="timestamp",t[t.uuid=9]="uuid"})(Wee||(Wee={}));Jee="boolean",HMe="byte",KMe="short",BMe="integer",ZMe="long",WMe="binary",JMe="string",XMe="timestamp",YMe="uuid",QMe=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/});function Yee({byteLength:t,byteOffset:e,buffer:r}){if(t<eUe)throw new Error("Provided message too short to accommodate event stream message overhead");let o=new DataView(r,e,t),n=o.getUint32(0,!1);if(t!==n)throw new Error("Reported message length does not match received message length");let i=o.getUint32(Xee,!1),s=o.getUint32(Pu,!1),a=o.getUint32(t-Rd,!1),c=new $d;if(c.update(new Uint8Array(r,e,Pu)),s!==c.digestSync())throw new Error(`The prelude checksum specified in the message (${s}) does not match the calculated CRC32 checksum (${c.digestSync()})`);if(c.update(new Uint8Array(r,e+Pu,t-(Pu+Rd))),a!==c.digestSync())throw new Error(`The message checksum (${c.digestSync()}) did not match the expected value of ${a}`);return{headers:new DataView(r,e+Pu+Rd,i),body:new Uint8Array(r,e+Pu+Rd+i,n-i-(Pu+Rd+Rd))}}var Xee,Pu,Rd,eUe,Qee=_(()=>{gc();Xee=4,Pu=Xee*2,Rd=4,eUe=Pu+Rd*2});var hm,MF=_(()=>{gc();zF();Qee();hm=class{headerMarshaller;messageBuffer;isEndOfStream;constructor(e,r){this.headerMarshaller=new mm(e,r),this.messageBuffer=[],this.isEndOfStream=!1}feed(e){this.messageBuffer.push(this.decode(e))}endOfStream(){this.isEndOfStream=!0}getMessage(){let e=this.messageBuffer.pop(),r=this.isEndOfStream;return{getMessage(){return e},isEndOfStream(){return r}}}getAvailableMessages(){let e=this.messageBuffer;this.messageBuffer=[];let r=this.isEndOfStream;return{getMessages(){return e},isEndOfStream(){return r}}}encode({headers:e,body:r}){let o=this.headerMarshaller.format(e),n=o.byteLength+r.byteLength+16,i=new Uint8Array(n),s=new DataView(i.buffer,i.byteOffset,i.byteLength),a=new $d;return s.setUint32(0,n,!1),s.setUint32(4,o.byteLength,!1),a.update(i.subarray(0,8)),s.setUint32(8,a.digestSync(),!1),i.set(o,12),i.set(r,o.byteLength+12),a.update(i.subarray(8,n-4)),s.setUint32(n-4,a.digestSync(),!1),i}decode(e){let{headers:r,body:o}=Yee(e);return{headers:this.headerMarshaller.parse(r),body:o}}formatHeaders(e){return this.headerMarshaller.format(e)}}});var gm,UF=_(()=>{gm=class{options;constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let e of this.options.inputStream)yield this.options.decoder.decode(e)}}});var ym,LF=_(()=>{ym=class{options;constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let e of this.options.messageStream)yield this.options.encoder.encode(e);this.options.includeEndFrame&&(yield new Uint8Array(0))}}});var vm,jF=_(()=>{vm=class{options;constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let e of this.options.messageStream){let r=await this.options.deserializer(e);r!==void 0&&(yield r)}}}});var wm,FF=_(()=>{wm=class{options;constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let e of this.options.inputStream)yield this.options.serializer(e)}}});function lI(t){let e=0,r=0,o=null,n=null,i=a=>{if(typeof a!="number")throw new Error("Attempted to allocate an event message where size was not a number: "+a);e=a,r=4,o=new Uint8Array(a),new DataView(o.buffer).setUint32(0,a,!1)},s=async function*(){let a=t[Symbol.asyncIterator]();for(;;){let{value:c,done:u}=await a.next();if(u){if(e)if(e===r)yield o;else throw new Error("Truncated event message received.");else return;return}let l=c.length,d=0;for(;d<l;){if(!o){let f=l-d;n||(n=new Uint8Array(4));let h=Math.min(4-r,f);if(n.set(c.slice(d,d+h),r),r+=h,d+=h,r<4)break;i(new DataView(n.buffer).getUint32(0,!1)),n=null}let p=Math.min(e-r,l-d);o.set(c.slice(d,d+p),r),r+=p,d+=p,e&&e===r&&(yield o,o=null,e=0,r=0)}}};return{[Symbol.asyncIterator]:s}}var qF=_(()=>{});function ete(t,e){let r=Cv(e.deserializer,e.toUtf8);return{[Symbol.asyncIterator]:async function*(){for await(let o of t){let n=e.eventStreamCodec.decode(o),i=await r(n);i!==void 0&&(yield i)}}}}function Cv(t,e){return async function(r){let{value:o}=r.headers[":message-type"];if(o==="error"){let n=new Error(r.headers[":error-message"].value||"UnknownError");throw n.name=r.headers[":error-code"].value,n}else if(o==="exception"){let n=r.headers[":exception-type"].value,i={[n]:r},s=await t(i);if(s.$unknown){let a=new Error(e(r.body));throw a.name=n,a}throw s[n]}else if(o==="event"){let n={[r.headers[":event-type"].value]:r},i=await t(n);return i.$unknown?void 0:i}else throw Error(`Unrecognizable event type: ${r.headers[":event-type"].value}`)}}var VF=_(()=>{});var Id,tte,GF=_(()=>{MF();UF();LF();jF();FF();qF();VF();Id=class{eventStreamCodec;utfEncoder;constructor({utf8Encoder:e,utf8Decoder:r}){this.eventStreamCodec=new hm(e,r),this.utfEncoder=e}deserialize(e,r){let o=lI(e);return new vm({messageStream:new gm({inputStream:o,decoder:this.eventStreamCodec}),deserializer:Cv(r,this.utfEncoder)})}serialize(e,r){return new ym({messageStream:new wm({inputStream:e,serializer:r}),encoder:this.eventStreamCodec,includeEndFrame:!0})}},tte=t=>new Id(t)});import{Readable as tUe}from"node:stream";async function*rUe(t){let e=!1,r=!1,o=new Array;for(t.on("error",n=>{if(e||(e=!0),n)throw n}),t.on("data",n=>{o.push(n)}),t.on("end",()=>{e=!0});!r;){let n=await new Promise(i=>setTimeout(()=>i(o.shift()),0));n&&(yield n),r=e&&o.length===0}}var Ov,rte,nte=_(()=>{GF();Ov=class{universalMarshaller;constructor({utf8Encoder:e,utf8Decoder:r}){this.universalMarshaller=new Id({utf8Decoder:r,utf8Encoder:e})}deserialize(e,r){let o=typeof e[Symbol.asyncIterator]=="function"?e:rUe(e);return this.universalMarshaller.deserialize(o,r)}serialize(e,r){return tUe.from(this.universalMarshaller.serialize(e,r))}},rte=t=>new Ov(t)});var ote,ite,ste=_(()=>{ote=t=>({[Symbol.asyncIterator]:async function*(){let e=t.getReader();try{for(;;){let{done:r,value:o}=await e.read();if(r)return;yield o}}finally{e.releaseLock()}}}),ite=t=>{let e=t[Symbol.asyncIterator]();return new ReadableStream({async pull(r){let{done:o,value:n}=await e.next();if(o)return r.close();r.enqueue(n)}})}});var ate,cte=_(()=>{ate=t=>Object.assign(t,{eventStreamMarshaller:t.eventStreamSerdeProvider(t)})});var dI,ute=_(()=>{Pe();rt();xe();dI=class{marshaller;serializer;deserializer;serdeContext;defaultContentType;compositeErrorRegistry;constructor({marshaller:e,serializer:r,deserializer:o,serdeContext:n,defaultContentType:i,compositeErrorRegistry:s}){this.marshaller=e,this.serializer=r,this.deserializer=o,this.serdeContext=n,this.defaultContentType=i,this.compositeErrorRegistry=s}async serializeEventStream({eventStream:e,requestSchema:r,initialRequest:o,initialMessageType:n}){let i=this.marshaller,s=r.getEventStreamMember(),a=r.getMemberSchema(s),c=this.serializer,u=this.defaultContentType,l=Symbol("initialRequestMarker"),d={async*[Symbol.asyncIterator](){if(o){let p={":event-type":{type:"string",value:n??"initial-request"},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:u}};c.write(r,o);let f=c.flush();yield{[l]:!0,headers:p,body:f}}for await(let p of e)yield p}};return i.serialize(d,p=>{if(p[l])return{headers:p.headers,body:p.body};let f="";for(let x in p)if(Se(p,x)&&x!=="__type"){f=x;break}let{additionalHeaders:h,body:y,eventType:w,explicitPayloadContentType:b}=this.writeEventBody(f,a,p);return{headers:{":event-type":{type:"string",value:w},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:b??u},...h},body:y}})}async deserializeEventStream({response:e,responseSchema:r,initialResponseContainer:o,initialMessageType:n}){let i=this.marshaller,s=r.getEventStreamMember(),c=r.getMemberSchema(s).getMemberSchemas(),u=Symbol("initialResponseMarker"),l=i.deserialize(e.body,async f=>{let h="";for(let w in f)if(Se(f,w)&&w!=="__type"){h=w;break}let y=f[h].body;if(h===(n??"initial-response")){let w=await this.deserializer.read(r,y);return delete w[s],{[u]:!0,...w}}else if(h in c){let w=c[h];if(w.isStructSchema()){let b={},S=!1;for(let[x,R]of w.structIterator()){let{eventHeader:T,eventPayload:M}=R.getMergedTraits();if(S=S||!!(T||M),M)R.isBlobSchema()?b[x]=y:R.isStringSchema()?b[x]=(this.serdeContext?.utf8Encoder??ur)(y):R.isStructSchema()&&(b[x]=await this.deserializer.read(R,y));else if(T){let Z=f[h].headers[x]?.value;Z!=null&&(R.isNumericSchema()?Z&&typeof Z=="object"&&"bytes"in Z?b[x]=BigInt(Z.toString()):b[x]=Number(Z):b[x]=Z)}}return{[h]:await this.readEventMember(w,y,S,b)}}return{[h]:await this.deserializer.read(w,y)}}else return{$unknown:f}}),d=l[Symbol.asyncIterator](),p=await d.next();if(p.done)return l;if(p.value?.[u]){if(!r)throw new Error("@smithy::core/protocols - initial-response event encountered in event stream but no response schema given.");for(let f in p.value)Se(p.value,f)&&(o[f]=p.value[f])}return{async*[Symbol.asyncIterator](){for(p?.value?.[u]||(yield p.value);;){let{done:f,value:h}=await d.next();if(f)break;yield h}}}}async readEventMember(e,r,o,n){let i,s=e.getSchema();if(Array.isArray(s)&&s[0]===-3){let c=s[1],u=Zt.for(c);this.compositeErrorRegistry?.copyFrom(u),i=(this.compositeErrorRegistry??u)?.getErrorCtor(s)}let a=o?n:r.byteLength===0?{}:await this.deserializer.read(e,r);if(i){let c=a.message??a.Message??"Unknown",u={},l=e.getMergedTraits().error;return l&&(u.$fault=l),Object.assign(new i({}),u,{message:c},a)}return a}writeEventBody(e,r,o){let n=this.serializer,i=e,s=null,a,c=r.getSchema()[4].includes(e),u={};if(c){let p=r.getMemberSchema(e);if(p.isStructSchema()){for(let[f,h]of p.structIterator()){let{eventHeader:y,eventPayload:w}=h.getMergedTraits();if(w)s=f;else if(y){let b=o[e][f],S="binary";h.isNumericSchema()?(-2)**31<=b&&b<=2**31-1?S="integer":S="long":h.isTimestampSchema()?S="timestamp":h.isStringSchema()?S="string":h.isBooleanSchema()&&(S="boolean"),b!=null&&(u[f]={type:S,value:b},delete o[e][f])}}if(s!==null){let f=p.getMemberSchema(s);f.isBlobSchema()?a="application/octet-stream":f.isStringSchema()&&(a="text/plain"),n.write(f,o[e][s])}else n.write(p,o[e])}else if(p.isUnitSchema())n.write(p,{});else throw new Error("@smithy/core/event-streams - non-struct member not supported in event stream union.")}else{let[p,f]=o[e];i=p,n.write(15,f)}let l=n.flush()??new Uint8Array;return{body:typeof l=="string"?(this.serdeContext?.utf8Decoder??Tr)(l):l,eventType:i,explicitPayloadContentType:a,additionalHeaders:u}}}});var lte={};Ht(lte,{EventStreamCodec:()=>hm,EventStreamMarshaller:()=>Ov,EventStreamSerde:()=>dI,HeaderMarshaller:()=>mm,Int64:()=>Au,MessageDecoderStream:()=>gm,MessageEncoderStream:()=>ym,SmithyMessageDecoderStream:()=>vm,SmithyMessageEncoderStream:()=>wm,UniversalEventStreamMarshaller:()=>Id,eventStreamSerdeProvider:()=>rte,getChunkedStream:()=>lI,getMessageUnmarshaller:()=>Cv,getUnmarshalledStream:()=>ete,iterableToReadableStream:()=>ite,readableStreamToIterable:()=>ote,resolveEventStreamSerdeConfig:()=>ate,universalEventStreamSerdeProvider:()=>tte});var dte=_(()=>{MF();zF();NF();UF();LF();jF();FF();nte();ste();GF();qF();VF();cte();ute()});var ku,pI=_(()=>{Pe();rt();Pe();lm();ku=class extends Fr{options;compositeErrorRegistry;constructor(e){super(),this.options=e,this.compositeErrorRegistry=new Zt(e.defaultNamespace);for(let r of e.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(r)}getRequestType(){return We}getResponseType(){return Lr}setSerdeContext(e){this.serdeContext=e,this.serializer.setSerdeContext(e),this.deserializer.setSerdeContext(e),this.getPayloadCodec()&&this.getPayloadCodec().setSerdeContext(e)}updateServiceEndpoint(e,r){if("url"in r){e.protocol=r.url.protocol,e.hostname=r.url.hostname,e.port=r.url.port?Number(r.url.port):void 0,e.path=r.url.pathname,e.fragment=r.url.hash||void 0,e.username=r.url.username||void 0,e.password=r.url.password||void 0,e.query||(e.query={});for(let[o,n]of r.url.searchParams.entries())e.query[o]=n;if(r.headers)for(let o in r.headers)Se(r.headers,o)&&(e.headers[o]=r.headers[o].join(", "));return e}else{if(e.protocol=r.protocol,e.hostname=r.hostname,e.port=r.port?Number(r.port):void 0,e.path=r.path,e.query={...r.query},r.headers)for(let o in r.headers)Se(r.headers,o)&&(e.headers[o]=r.headers[o]);return e}}setHostPrefix(e,r,o){if(this.serdeContext?.disableHostPrefix)return;let n=B.of(r.input),i=Ki(r.traits??{});if(i.endpoint){let s=i.endpoint?.[0];if(typeof s=="string"){for(let[a,c]of n.structIterator()){if(!c.getMergedTraits().hostLabel)continue;let u=o[a];if(typeof u!="string")throw new Error(`@smithy/core/schema - ${a} in input must be a string as hostLabel.`);s=s.replace(`{${a}}`,u)}if(e.hostname=s+e.hostname,!sv(e.hostname))throw new Error(`[${e.hostname}] is not a valid hostname.`)}}}deserializeMetadata(e){return{httpStatusCode:e.statusCode,requestId:e.headers["x-amzn-requestid"]??e.headers["x-amzn-request-id"]??e.headers["x-amz-request-id"],extendedRequestId:e.headers["x-amz-id-2"],cfId:e.headers["x-amz-cf-id"]}}resolveError(e,r,o){let n=[-3,"","Error",0,[],[],0],i;for(let s of o)for(let a of r)try{a==="*"?i=s.getSchema(e):i=s.getSchema(a+"#"+e);let c=s.getErrorCtor(i);if(c)return[i,c,"modeled"];{let u=s.getBaseException();if(u){let l=s.getErrorCtor(u);if(l)return[i,l,"synthetic"]}}}catch{}for(let s of o){let a=s.getBaseException();if(a){let c=s.getErrorCtor(a);if(c)return[a,c,"synthetic"]}}return[n,Error,"native"]}async serializeEventStream({eventStream:e,requestSchema:r,initialRequest:o}){return(await this.loadEventStreamCapability()).serializeEventStream({eventStream:e,requestSchema:r,initialRequest:o})}async deserializeEventStream({response:e,responseSchema:r,initialResponseContainer:o}){return(await this.loadEventStreamCapability()).deserializeEventStream({response:e,responseSchema:r,initialResponseContainer:o})}async loadEventStreamCapability(){let{EventStreamSerde:e,eventStreamSerdeProvider:r}=await Promise.resolve().then(()=>(dte(),lte)),o=this.resolveEventStreamMarshaller(r);return new e({marshaller:o,serializer:this.serializer,deserializer:this.deserializer,serdeContext:this.serdeContext,defaultContentType:this.getDefaultContentType(),compositeErrorRegistry:this.compositeErrorRegistry})}getDefaultContentType(){throw new Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`)}async deserializeHttpMessage(e,r,o,n,i){return[]}getEventStreamMarshaller(){let e=this.serdeContext;if(!e.eventStreamMarshaller)throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");return e.eventStreamMarshaller}resolveEventStreamMarshaller(e){let r=this.serdeContext;return r.eventStreamMarshaller?r.eventStreamMarshaller:e(this.serdeContext)}}});var Tu,pte=_(()=>{Pe();rt();xe();Pe();pI();oI();iI();Tu=class extends ku{async serializeRequest(e,r,o){let n=r&&typeof r=="object"?r:{},i=this.serializer,s={},a={},c=await o.endpoint(),u=B.of(e?.input),l=[],d=[],p=!1,f,h=new We({protocol:"",hostname:"",port:void 0,path:"",fragment:void 0,query:s,headers:a,body:void 0});if(c){this.updateServiceEndpoint(h,c),this.setHostPrefix(h,e,n);let y=Ki(e.traits);if(y.http){h.method=y.http[0];let[w,b]=y.http[1].split("?");h.path=="/"?h.path=w:h.path+=w;let S=new URLSearchParams(b??"");for(let[x,R]of S)s[x]=R}}for(let[y,w]of u.structIterator()){let b=w.getMergedTraits()??{},S=n[y];if(S==null&&!w.isIdempotencyToken()){if(b.httpLabel&&(h.path.includes(`{${y}+}`)||h.path.includes(`{${y}}`)))throw new Error(`No value provided for input HTTP label: ${y}.`);continue}if(b.httpPayload)w.isStreaming()?w.isStructSchema()?n[y]&&(f=await this.serializeEventStream({eventStream:n[y],requestSchema:u})):f=S:(i.write(w,S),f=i.flush());else if(b.httpLabel){i.write(w,S);let x=i.flush();h.path.includes(`{${y}+}`)?h.path=h.path.replace(`{${y}+}`,x.split("/").map(Ji).join("/")):h.path.includes(`{${y}}`)&&(h.path=h.path.replace(`{${y}}`,Ji(x)))}else if(b.httpHeader)i.write(w,S),a[b.httpHeader.toLowerCase()]=String(i.flush());else if(typeof b.httpPrefixHeaders=="string")for(let x in S){if(!Se(S,x))continue;let R=S[x],T=b.httpPrefixHeaders+x;i.write([w.getValueSchema(),{httpHeader:T}],R),a[T.toLowerCase()]=i.flush()}else b.httpQuery||b.httpQueryParams?this.serializeQuery(w,S,s):(p=!0,l.push(y),d.push(w))}if(p&&n){let[y,w]=(u.getName(!0)??"#Unknown").split("#"),b=u.getSchema()[6],S=[3,y,w,u.getMergedTraits(),l,d,void 0];b?S[6]=b:S.pop(),i.write(S,n),f=i.flush()}return h.headers=a,h.query=s,h.body=f,h}serializeQuery(e,r,o){let n=this.serializer,i=e.getMergedTraits();if(i.httpQueryParams){for(let s in r)if(Se(r,s)&&!(s in o)){let a=r[s],c=e.getValueSchema();Object.assign(c.getMergedTraits(),{...i,httpQuery:s,httpQueryParams:void 0}),this.serializeQuery(c,a,o)}return}if(e.isListSchema()){let s=!!e.getMergedTraits().sparse,a=[];for(let c of r){n.write([e.getValueSchema(),i],c);let u=n.flush();(s||u!==void 0)&&a.push(u)}o[i.httpQuery]=a}else n.write([e,i],r),o[i.httpQuery]=n.flush()}async deserializeResponse(e,r,o){let n=this.deserializer,i=B.of(e.output),s={};if(o.statusCode>=300){let c=await sn(o.body,r);throw c.byteLength>0&&Object.assign(s,await n.read(15,c)),await this.handleError(e,r,o,s,this.deserializeMetadata(o)),new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw.")}for(let c in o.headers){if(!Se(o.headers,c))continue;let u=o.headers[c];delete o.headers[c],o.headers[c.toLowerCase()]=u}let a=await this.deserializeHttpMessage(i,r,o,s);if(a.length){let c=await sn(o.body,r);if(c.byteLength>0){let u=await n.read(i,c);for(let l of a)u[l]!=null&&(s[l]=u[l])}}else a.discardResponseBody&&await sn(o.body,r);return s.$metadata=this.deserializeMetadata(o),s}async deserializeHttpMessage(e,r,o,n,i){let s;n instanceof Set?s=i:s=n;let a=!0,c=this.deserializer,u=B.of(e),l=[];for(let[d,p]of u.structIterator()){let f=p.getMemberTraits();if(f.httpPayload){if(a=!1,p.isStreaming())p.isStructSchema()?s[d]=await this.deserializeEventStream({response:o,responseSchema:u}):s[d]=nI(o.body);else if(o.body){let y=await sn(o.body,r);y.byteLength>0&&(s[d]=await c.read(p,y))}}else if(f.httpHeader){let h=String(f.httpHeader).toLowerCase(),y=o.headers[h];if(y!=null)if(p.isListSchema()){let w=p.getValueSchema();w.getMergedTraits().httpHeader=h;let b;w.isTimestampSchema()&&w.getSchema()===4?b=gR(y,",",2):b=em(y);let S=[];for(let x of b)S.push(await c.read(w,x.trim()));s[d]=S}else s[d]=await c.read(p,y)}else if(f.httpPrefixHeaders!==void 0){s[d]={};for(let h in o.headers)if(Se(o.headers,h)&&h.startsWith(f.httpPrefixHeaders)){let y=o.headers[h],w=p.getValueSchema();w.getMergedTraits().httpHeader=h,s[d][h.slice(f.httpPrefixHeaders.length)]=await c.read(w,y)}}else f.httpResponseCode?s[d]=o.statusCode:l.push(d)}return l.discardResponseBody=a,l}}});var na,fte=_(()=>{Pe();rt();Pe();pI();oI();na=class extends ku{async serializeRequest(e,r,o){let n=this.serializer,i={},s={},a=await o.endpoint(),c=B.of(e?.input),u=c.getSchema(),l,d=r&&typeof r=="object"?r:{},p=new We({protocol:"",hostname:"",port:void 0,path:"/",fragment:void 0,query:i,headers:s,body:void 0});if(a&&(this.updateServiceEndpoint(p,a),this.setHostPrefix(p,e,d)),d){let f=c.getEventStreamMember();if(f){if(d[f]){let h={};for(let[y]of c.structIterator())y!==f&&d[y]!=null&&(h[y]=d[y]);l=await this.serializeEventStream({eventStream:d[f],requestSchema:c,initialRequest:h})}}else n.write(u,d),l=n.flush()}return p.headers=Object.assign(p.headers,s),p.query=i,p.body=l,p.method="POST",p}async deserializeResponse(e,r,o){let n=this.deserializer,i=B.of(e.output),s={};if(o.statusCode>=300){let c=await sn(o.body,r);throw c.byteLength>0&&Object.assign(s,await n.read(15,c)),await this.handleError(e,r,o,s,this.deserializeMetadata(o)),new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw.")}for(let c in o.headers){if(!Se(o.headers,c))continue;let u=o.headers[c];delete o.headers[c],o.headers[c.toLowerCase()]=u}let a=i.getEventStreamMember();if(a)s[a]=await this.deserializeEventStream({response:o,responseSchema:i,initialResponseContainer:s});else{let c=await sn(o.body,r);c.byteLength>0&&Object.assign(s,await n.read(i,c))}return s.$metadata=this.deserializeMetadata(o),s}}});var fI,HF=_(()=>{iI();fI=(t,e,r,o,n,i)=>{if(e!=null&&e[r]!==void 0){let s=o();if(s==null||s.length<=0)throw new Error("Empty value provided for input HTTP label: "+r+".");t=t.replace(n,i?s.split("/").map(a=>Ji(a)).join("/"):Ji(s))}else throw new Error("No value provided for input HTTP label: "+r+".");return t}});function mI(t,e){return new Dv(t,e)}var Dv,mte=_(()=>{Pe();HF();Dv=class{input;context;query={};method="";headers={};path="";body=null;hostname="";resolvePathStack=[];constructor(e,r){this.input=e,this.context=r}async build(){let{hostname:e,protocol:r="https",port:o,path:n}=await this.context.endpoint();this.path=n;for(let i of this.resolvePathStack)i(this.path);return new We({protocol:r,hostname:this.hostname||e,port:o,method:this.method,path:this.path,query:this.query,body:this.body,headers:this.headers})}hn(e){return this.hostname=e,this}bp(e){return this.resolvePathStack.push(r=>{this.path=`${r?.endsWith("/")?r.slice(0,-1):r||""}`+e}),this}p(e,r,o,n){return this.resolvePathStack.push(i=>{this.path=fI(i,this.input,e,r,o,n)}),this}h(e){return this.headers=e,this}q(e){return this.query=e,this}b(e){return this.body=e,this}m(e){return this.method=e,this}}});function qr(t,e){if(e.timestampFormat.useTrait&&t.isTimestampSchema()&&(t.getSchema()===5||t.getSchema()===6||t.getSchema()===7))return t.getSchema();let{httpLabel:r,httpPrefixHeaders:o,httpHeader:n,httpQuery:i}=t.getMergedTraits();return(e.httpBindings?typeof o=="string"||n?6:i||r?5:void 0:void 0)??e.timestampFormat.default}var hI=_(()=>{});var Cu,KF=_(()=>{rt();xe();lm();hI();Cu=class extends Fr{settings;constructor(e){super(),this.settings=e}read(e,r){let o=B.of(e);if(o.isListSchema())return em(r).map(n=>this.read(o.getValueSchema(),n));if(o.isBlobSchema())return(this.serdeContext?.base64Decoder??pr)(r);if(o.isTimestampSchema())switch(qr(o,this.settings)){case 5:return mR(r);case 6:return hR(r);case 7:return Eu(r);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",r),new Date(r)}if(o.isStringSchema()){let n=o.getMergedTraits().mediaType,i=r;if(n)return o.getMergedTraits().httpHeader&&(i=this.base64ToUtf8(i)),(n==="application/json"||n.endsWith("+json"))&&(i=Er.from(i)),i}return o.isNumericSchema()?Number(r):o.isBigIntegerSchema()?BigInt(r):o.isBigDecimalSchema()?new nt(r,"bigDecimal"):o.isBooleanSchema()?String(r).toLowerCase()==="true":r}base64ToUtf8(e){return(this.serdeContext?.utf8Encoder??ur)((this.serdeContext?.base64Decoder??pr)(e))}}});var Ou,hte=_(()=>{rt();xe();lm();KF();Ou=class extends Fr{codecDeserializer;stringDeserializer;constructor(e,r){super(),this.codecDeserializer=e,this.stringDeserializer=new Cu(r)}setSerdeContext(e){this.stringDeserializer.setSerdeContext(e),this.codecDeserializer.setSerdeContext(e),this.serdeContext=e}read(e,r){let o=B.of(e),n=o.getMergedTraits(),i=this.serdeContext?.utf8Encoder??ur;if(n.httpHeader||n.httpResponseCode)return this.stringDeserializer.read(o,i(r));if(n.httpPayload){if(o.isBlobSchema()){let s=this.serdeContext?.utf8Decoder??Tr;return typeof r=="string"?s(r):r}else if(o.isStringSchema())return"byteLength"in r?i(r):r}return this.codecDeserializer.read(o,r)}}});var _m,BF=_(()=>{rt();xe();lm();hI();_m=class extends Fr{settings;stringBuffer="";constructor(e){super(),this.settings=e}write(e,r){let o=B.of(e);switch(typeof r){case"object":if(r===null){this.stringBuffer="null";return}if(o.isTimestampSchema()){if(!(r instanceof Date))throw new Error(`@smithy/core/protocols - received non-Date value ${r} when schema expected Date in ${o.getName(!0)}`);switch(qr(o,this.settings)){case 5:this.stringBuffer=r.toISOString().replace(".000Z","Z");break;case 6:this.stringBuffer=Oo(r);break;case 7:this.stringBuffer=String(r.getTime()/1e3);break;default:console.warn("Missing timestamp format, using epoch seconds",r),this.stringBuffer=String(r.getTime()/1e3)}return}if(o.isBlobSchema()&&"byteLength"in r){this.stringBuffer=(this.serdeContext?.base64Encoder??Wt)(r);return}if(o.isListSchema()&&Array.isArray(r)){let s="";for(let a of r){this.write([o.getValueSchema(),o.getMergedTraits()],a);let c=this.flush(),u=o.getValueSchema().isTimestampSchema()?c:fR(c);s!==""&&(s+=", "),s+=u}this.stringBuffer=s;return}this.stringBuffer=JSON.stringify(r,null,2);break;case"string":let n=o.getMergedTraits().mediaType,i=r;if(n&&((n==="application/json"||n.endsWith("+json"))&&(i=Er.from(i)),o.getMergedTraits().httpHeader)){this.stringBuffer=(this.serdeContext?.base64Encoder??Wt)(i.toString());return}this.stringBuffer=r;break;default:o.isIdempotencyToken()?this.stringBuffer=Lo():this.stringBuffer=String(r)}}flush(){let e=this.stringBuffer;return this.stringBuffer="",e}}});var Du,gte=_(()=>{rt();BF();Du=class{codecSerializer;stringSerializer;buffer;constructor(e,r,o=new _m(r)){this.codecSerializer=e,this.stringSerializer=o}setSerdeContext(e){this.codecSerializer.setSerdeContext(e),this.stringSerializer.setSerdeContext(e)}write(e,r){let o=B.of(e),n=o.getMergedTraits();if(n.httpHeader||n.httpLabel||n.httpQuery){this.stringSerializer.write(o,r),this.buffer=this.stringSerializer.flush();return}return this.codecSerializer.write(o,r)}flush(){if(this.buffer!==void 0){let e=this.buffer;return this.buffer=void 0,e}return this.codecSerializer.flush()}}});var yte,gI,vte=_(()=>{yte=Vt(js()),gI=class{name;kind;values;constructor({name:e,kind:r=yte.FieldPosition.HEADER,values:o=[]}){this.name=e,this.kind=r,this.values=o}add(e){this.values.push(e)}set(e){this.values=e}remove(e){this.values=this.values.filter(r=>r!==e)}toString(){return this.values.map(e=>e.includes(",")||e.includes(" ")?`"${e}"`:e).join(", ")}get(){return this.values}}});var yI,wte=_(()=>{yI=class{entries={};encoding;constructor({fields:e=[],encoding:r="utf-8"}){e.forEach(this.setField.bind(this)),this.encoding=r}setField(e){this.entries[e.name.toLowerCase()]=e}getField(e){return this.entries[e.toLowerCase()]}removeField(e){delete this.entries[e.toLowerCase()]}getByType(e){return Object.values(this.entries).filter(r=>r.kind===e)}}});var oa,ia,_te=_(()=>{oa=t=>(t.logger&&t.logger.constructor?.name!=="NoOpLogger"&&t.requestHandler?.updateHttpClientConfig?.(Symbol.for("logger"),t.logger),{setHttpHandler(e){t.requestHandler=e},httpHandler(){return t.requestHandler},updateHttpClientConfig(e,r){t.requestHandler?.updateHttpClientConfig(e,r)},httpHandlerConfigs(){return t.requestHandler.httpHandlerConfigs()}}),ia=t=>({requestHandler:t.httpHandler()})});function ZF(t){return e=>async r=>{let o=r.request;if(We.isInstance(o)){let{body:n,headers:i}=o;if(n&&Object.keys(i).map(s=>s.toLowerCase()).indexOf(bte)===-1)try{let s=t(n);s!=null&&(o.headers={...o.headers,[bte]:String(s)})}catch{}}return e({...r,request:o})}}var bte,WF,sa,Ste=_(()=>{Pe();bte="content-length";WF={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},sa=t=>({applyToStack:e=>{e.add(ZF(t.bodyLengthChecker),WF)}})});var Nu,nUe,vI=_(()=>{Nu=t=>encodeURIComponent(t).replace(/[!'()*]/g,nUe),nUe=t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`});var xte,Ete=_(()=>{vI();xte=t=>t.split("/").map(Nu).join("/")});function $te(t){let e=[];for(let r of Object.keys(t).sort()){let o=t[r];if(r=Nu(r),Array.isArray(o))for(let n=0,i=o.length;n<i;n++)e.push(`${r}=${Nu(o[n])}`);else{let n=r;(o||typeof o=="string")&&(n+=`=${Nu(o)}`),e.push(n)}}return e.join("&")}var Rte=_(()=>{vI()});var zu={};Ht(zu,{Field:()=>gI,Fields:()=>yI,FromStringShapeDeserializer:()=>Cu,HttpBindingProtocol:()=>Tu,HttpInterceptingShapeDeserializer:()=>Ou,HttpInterceptingShapeSerializer:()=>Du,HttpProtocol:()=>ku,HttpRequest:()=>We,HttpResponse:()=>Lr,RequestBuilder:()=>Dv,RpcProtocol:()=>na,SerdeContext:()=>Fr,ToStringShapeSerializer:()=>_m,buildQueryString:()=>$te,collectBody:()=>sn,contentLengthMiddleware:()=>ZF,contentLengthMiddlewareOptions:()=>WF,determineTimestampFormat:()=>qr,escapeUri:()=>Nu,escapeUriPath:()=>xte,extendedEncodeURIComponent:()=>Ji,getContentLengthPlugin:()=>sa,getHttpHandlerExtensionConfiguration:()=>oa,isValidHostname:()=>sv,parseQueryString:()=>av,parseUrl:()=>nn,requestBuilder:()=>mI,resolveHttpHandlerRuntimeConfig:()=>ia,resolvedPath:()=>fI});var ge=_(()=>{oI();iI();pte();pI();fte();mte();HF();KF();hte();gte();BF();hI();lm();vte();wte();Pe();Pe();Pe();_te();Ste();vI();Ete();Rte();Pe();Pe()});var Ite,Ate,Pte,kte,Tte,Cte,Ote=_(()=>{Ite=["AccessDeniedException","AuthFailure","InvalidSignatureException","RequestExpired","RequestInTheFuture","RequestTimeTooSkewed","SignatureDoesNotMatch"],Ate=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],Pte=["TimeoutError","RequestTimeout","RequestTimeoutException"],kte=[500,502,503,504],Tte=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],Cte=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN"]});function YF(t){return t.code==="ERR_HTTP2_STREAM_ERROR"&&t.message.includes("NGHTTP2_REFUSED_STREAM")}var Nv,wI,JF,XF,aa,Mu,_I,bm=_(()=>{Ote();Nv=t=>t?.$retryable!==void 0,wI=t=>Ite.includes(t.name),JF=t=>t.$metadata?.clockSkewCorrected,XF=t=>{let e=new Set(["Failed to fetch","NetworkError when attempting to fetch resource","The Internet connection appears to be offline","Load failed","Network request failed"]);return t&&t instanceof TypeError?e.has(t.message):!1},aa=t=>t.$metadata?.httpStatusCode===429||Ate.includes(t.name)||t.$retryable?.throttling==!0,Mu=(t,e=0)=>t?.name!=="AbortError"&&(Nv(t)||JF(t)||t.name==="InvalidSignatureException"&&t.message?.includes("Signature expired")||Pte.includes(t.name)||Tte.includes(t?.code||"")||Cte.includes(t?.code||"")||kte.includes(t.$metadata?.httpStatusCode||0)||XF(t)||YF(t)||t.cause!==void 0&&e<=10&&Mu(t.cause,e+1)),_I=t=>{if(t.$metadata?.httpStatusCode!==void 0){let e=t.$metadata.httpStatusCode;return 500<=e&&e<=599&&!Mu(t)}return!1}});var bI,zv,SI,Sm,QF,e2,xI,Uu,Lu,Mv=_(()=>{bI=100,zv=2e4,SI=500,Sm=500,QF=5,e2=10,xI=1,Uu="amz-sdk-invocation-id",Lu="amz-sdk-request"});function t2(t,e){if(Lr.isInstance(t))for(let r in t.headers){if(!Se(t.headers,r))continue;let o=r.toLowerCase();if(o==="retry-after"){let n=t.headers[r],i=NaN;if(n.endsWith("GMT"))try{i=(xu(n).getTime()-Date.now())/1e3}catch(s){e?.trace?.("Failed to parse retry-after header"),e?.trace?.(s)}else n.match(/ GMT, ((\d+)|(\d+\.\d+))$/)?i=Number(n.match(/ GMT, ([\d.]+)$/)?.[1]):n.match(/^((\d+)|(\d+\.\d+))$/)?i=Number(n):Date.parse(n)>=Date.now()&&(i=(Date.parse(n)-Date.now())/1e3);return isNaN(i)?void 0:new Date(Date.now()+i*1e3)}else if(o==="x-amz-retry-after"){let n=t.headers[r],i=Number(n);if(isNaN(i)){e?.trace?.(`Failed to parse x-amz-retry-after=${n}`);return}return new Date(Date.now()+i)}}}function Dte(t,e){return t2(t,e)}var r2=_(()=>{Pe();ge();xe()});var EI,n2=_(()=>{EI=t=>t instanceof Error?t:t instanceof Object?Object.assign(new Error,t):typeof t=="string"?new Error(t):new Error(`AWS SDK error wrapper for ${t}`)});function o2(t){return e=>(r,o)=>async n=>{let i=await e.retryStrategy(),s=await e.maxAttempts();if(iUe(i)){i=i;let a=await i.acquireInitialRetryToken((o.partition_id??"")+(o.__retryLongPoll?":longpoll":"")),c=new Error,u=0,l=0,{request:d}=n,p=We.isInstance(d);for(p&&(d.headers[Uu]=um());;)try{p&&(d.headers[Lu]=`attempt=${u+1}; max=${s}`);let{response:f,output:h}=await r(n);return i.recordSuccess(a),h.$metadata.attempts=u+1,h.$metadata.totalRetryDelay=l,{response:f,output:h}}catch(f){let h=sUe(f,e.logger);if(c=EI(f),p&&t(d))throw(o.logger instanceof mo?console:o.logger)?.warn("An error was encountered in a non-retryable streaming request."),c;try{a=await i.refreshRetryTokenForRetry(a,h)}catch{throw c.$metadata||(c.$metadata={}),c.$metadata.attempts=u+1,c.$metadata.totalRetryDelay=l,c}u=a.getRetryCount();let y=a.getRetryDelay();l+=(a?.$retryLog?.acquisitionDelay??0)+y,y>0&&await oUe(y)}}else return i=i,i?.mode&&(o.userAgent=[...o.userAgent||[],["cfg/retry-mode",i.mode]]),i.retry(r,n)}}function Nte(t){let e=o2(t);return r=>({applyToStack:o=>{o.add(e(r),i2)}})}var oUe,iUe,sUe,aUe,i2,s2=_(()=>{ve();ge();xe();bm();Mv();r2();n2();oUe=t=>new Promise(e=>setTimeout(e,t)),iUe=t=>typeof t.acquireInitialRetryToken<"u"&&typeof t.refreshRetryTokenForRetry<"u"&&typeof t.recordSuccess<"u",sUe=(t,e)=>{let r={error:t,errorType:aUe(t)},o=t2(t.$response,e);return o&&(r.retryAfterHint=o),r},aUe=t=>aa(t)?"THROTTLING":Mu(t)?"TRANSIENT":_I(t)?"SERVER_ERROR":"CLIENT_ERROR",i2={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0}});var ju,$I=_(()=>{bm();ju=class t{static setTimeoutFn=(e,r)=>setTimeout(e,r);beta;minCapacity;minFillRate;scaleConstant;smooth;enabled=!1;availableTokens=0;lastMaxRate=0;measuredTxRate=0;requestCount=0;fillRate;lastThrottleTime;lastTimestamp=0;lastTxRateBucket;maxCapacity;timeWindow=0;constructor(e){this.beta=e?.beta??.7,this.minCapacity=e?.minCapacity??1,this.minFillRate=e?.minFillRate??.5,this.scaleConstant=e?.scaleConstant??.4,this.smooth=e?.smooth??.8,this.lastThrottleTime=this.getCurrentTimeInSeconds(),this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds()),this.fillRate=this.minFillRate,this.maxCapacity=this.minCapacity}async getSendToken(){return this.acquireTokenBucket(1)}updateClientSendingRate(e){let r;this.updateMeasuredRate();let o=e;if(o?.errorType==="THROTTLING"||aa(o?.error??e)){let s=this.enabled?Math.min(this.measuredTxRate,this.fillRate):this.measuredTxRate;this.lastMaxRate=s,this.calculateTimeWindow(),this.lastThrottleTime=this.getCurrentTimeInSeconds(),r=this.cubicThrottle(s),this.enableTokenBucket()}else this.calculateTimeWindow(),r=this.cubicSuccess(this.getCurrentTimeInSeconds());let i=Math.min(r,2*this.measuredTxRate);this.updateTokenBucketRate(i)}getCurrentTimeInSeconds(){return Date.now()/1e3}async acquireTokenBucket(e){if(this.enabled){for(this.refillTokenBucket();e>this.availableTokens;){let r=(e-this.availableTokens)/this.fillRate*1e3;await new Promise(o=>t.setTimeoutFn(o,r)),this.refillTokenBucket()}this.availableTokens=this.availableTokens-e}}refillTokenBucket(){let e=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=e;return}let r=(e-this.lastTimestamp)*this.fillRate;this.availableTokens=Math.min(this.maxCapacity,this.availableTokens+r),this.lastTimestamp=e}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,1/3))}cubicThrottle(e){return this.getPrecise(e*this.beta)}cubicSuccess(e){return this.getPrecise(this.scaleConstant*Math.pow(e-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(e){this.refillTokenBucket(),this.fillRate=Math.max(e,this.minFillRate),this.maxCapacity=Math.max(e,this.minCapacity),this.availableTokens=Math.min(this.availableTokens,this.maxCapacity)}updateMeasuredRate(){let e=this.getCurrentTimeInSeconds(),r=Math.floor(e*2)/2;if(this.requestCount++,r>this.lastTxRateBucket){let o=this.requestCount/(r-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(o*this.smooth+this.measuredTxRate*(1-this.smooth)),this.requestCount=0,this.lastTxRateBucket=r}}getPrecise(e){return parseFloat(e.toFixed(8))}}});var vr,xm=_(()=>{vr=class t{static v2026=typeof process<"u"&&process.env?.SMITHY_NEW_RETRIES_2026==="true";static delay(){return t.v2026?50:100}static throttlingDelay(){return t.v2026?1e3:500}static cost(){return t.v2026?14:5}static throttlingCost(){return t.v2026?5:10}static modifiedCostType(){return t.v2026?"THROTTLING":"TRANSIENT"}}});var RI,zte=_(()=>{xm();RI=class{x=vr.delay();computeNextBackoffDelay(e){let n=Math.random()*Math.min(this.x*2**e,2e4);return Math.floor(n)}setDelayBase(e){this.x=e}}});var Uv,Mte=_(()=>{Uv=class{delay;count;cost;longPoll;$retryLog={acquisitionDelay:0};constructor(e,r,o,n){this.delay=e,this.count=r,this.cost=o,this.longPoll=n}getRetryCount(){return this.count}getRetryDelay(){return Math.min(2e4,this.delay)}getRetryCost(){return this.cost}isLongPoll(){return this.longPoll}}});var Vr,Yi,li,Ad=_(()=>{(function(t){t.STANDARD="standard",t.ADAPTIVE="adaptive"})(Vr||(Vr={}));Yi=3,li=Vr.STANDARD});var II,Qi,Lv=_(()=>{zte();Mte();Ad();xm();II={incompatible:1,attempts:2,capacity:3},Qi=class{mode=Vr.STANDARD;retryBackoffStrategy;capacity=500;maxAttemptsProvider;baseDelay;constructor(e){typeof e=="number"?this.maxAttemptsProvider=async()=>e:typeof e=="function"?this.maxAttemptsProvider=e:e&&typeof e=="object"&&(this.maxAttemptsProvider=async()=>e.maxAttempts,this.baseDelay=e.baseDelay,this.retryBackoffStrategy=e.backoff),this.maxAttemptsProvider??=async()=>Yi,this.baseDelay??=vr.delay(),this.retryBackoffStrategy??=new RI}async acquireInitialRetryToken(e){return new Uv(vr.delay(),0,void 0,vr.v2026&&e.includes(":longpoll"))}async refreshRetryTokenForRetry(e,r){let o=await this.getMaxAttempts(),n=this.retryCode(e,r,o),i=n===0,s=e.isLongPoll?.();if(i||s){let a=r.errorType;this.retryBackoffStrategy.setDelayBase(a==="THROTTLING"?vr.throttlingDelay():this.baseDelay);let c=this.retryBackoffStrategy.computeNextBackoffDelay(e.getRetryCount()),u=c;if(r.retryAfterHint instanceof Date&&(u=Math.max(c,Math.min(r.retryAfterHint.getTime()-Date.now(),c+5e3))),i){let l=this.getCapacityCost(a);this.capacity-=l;let d=new Uv(0,e.getRetryCount()+1,l,e.isLongPoll?.()??!1);return await new Promise(p=>setTimeout(p,u)),d.$retryLog.acquisitionDelay=u,d}else{let l=vr.v2026&&n===II.capacity&&s?u:0;l>0&&await new Promise(d=>setTimeout(d,l))}}throw new Error("No retry token available")}recordSuccess(e){this.capacity=Math.min(500,this.capacity+(e.getRetryCost()??1))}getCapacity(){return this.capacity}async maxAttempts(){return this.maxAttemptsProvider()}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch{return console.warn(`Max attempts provider could not resolve. Using default of ${Yi}`),Yi}}retryCode(e,r,o){let n=e.getRetryCount()+1,i=this.isRetryableError(r.errorType)?0:II.incompatible,s=n<o?0:II.attempts,a=this.capacity>=this.getCapacityCost(r.errorType)?0:II.capacity;return i||s||a}getCapacityCost(e){return e===vr.modifiedCostType()?vr.throttlingCost():vr.cost()}isRetryableError(e){return e==="THROTTLING"||e==="TRANSIENT"}}});var Em,a2=_(()=>{$I();Lv();Ad();Em=class{mode=Vr.ADAPTIVE;rateLimiter;standardRetryStrategy;constructor(e,r){let{rateLimiter:o}=r??{};this.rateLimiter=o??new ju,this.standardRetryStrategy=r?new Qi({maxAttempts:typeof e=="number"?e:3,...r}):new Qi(e)}async acquireInitialRetryToken(e){let r=await this.standardRetryStrategy.acquireInitialRetryToken(e);return await this.rateLimiter.getSendToken(),r}async refreshRetryTokenForRetry(e,r){this.rateLimiter.updateClientSendingRate(r);let o=await this.standardRetryStrategy.refreshRetryTokenForRetry(e,r);return await this.rateLimiter.getSendToken(),o}recordSuccess(e){this.rateLimiter.updateClientSendingRate({}),this.standardRetryStrategy.recordSuccess(e)}async maxAttemptsProvider(){return this.standardRetryStrategy.maxAttempts()}}});var AI,Ute=_(()=>{Lv();xm();AI=class extends Qi{computeNextBackoffDelay;constructor(e,r=vr.delay()){super(typeof e=="function"?e:async()=>e),typeof r=="number"?this.computeNextBackoffDelay=()=>r:this.computeNextBackoffDelay=r,this.retryBackoffStrategy.computeNextBackoffDelay=o=>{let n=o+1;return this.computeNextBackoffDelay(n)}}}});var Lte,jte=_(()=>{Lte=(t,e)=>{let r=t,o=e?.noRetryIncrement??1,n=e?.retryCost??5,i=e?.timeoutRetryCost??10,s=t,a=d=>d.name==="TimeoutError"?i:n,c=d=>a(d)<=s;return Object.freeze({hasRetryTokens:c,retrieveRetryTokens:d=>{if(!c(d))throw new Error("No retry token available");let p=a(d);return s-=p,p},releaseRetryTokens:d=>{s+=d??o,s=Math.min(s,r)}})}});var PI,c2=_(()=>{PI=(t,e)=>Math.floor(Math.min(2e4,Math.random()*2**e*t))});var kI,u2=_(()=>{bm();kI=t=>t?Nv(t)||wI(t)||aa(t)||Mu(t):!1});var $m,cUe,l2=_(()=>{ge();xe();bm();Ad();Mv();n2();jte();c2();u2();$m=class{maxAttemptsProvider;retryDecider;delayDecider;retryQuota;mode=Vr.STANDARD;constructor(e,r){this.maxAttemptsProvider=e,this.retryDecider=r?.retryDecider??kI,this.delayDecider=r?.delayDecider??PI,this.retryQuota=r?.retryQuota??Lte(500)}shouldRetry(e,r,o){return r<o&&this.retryDecider(e)&&this.retryQuota.hasRetryTokens(e)}async getMaxAttempts(){let e;try{e=await this.maxAttemptsProvider()}catch{e=Yi}return e}async retry(e,r,o){let n,i=0,s=0,a=await this.getMaxAttempts(),{request:c}=r;for(We.isInstance(c)&&(c.headers[Uu]=um());;)try{We.isInstance(c)&&(c.headers[Lu]=`attempt=${i+1}; max=${a}`),o?.beforeRequest&&await o.beforeRequest();let{response:u,output:l}=await e(r);return o?.afterRequest&&o.afterRequest(u),this.retryQuota.releaseRetryTokens(n),l.$metadata.attempts=i+1,l.$metadata.totalRetryDelay=s,{response:u,output:l}}catch(u){let l=EI(u);if(i++,this.shouldRetry(l,i,a)){n=this.retryQuota.retrieveRetryTokens(l);let d=this.delayDecider(aa(l)?500:100,i),p=cUe(l.$response),f=Math.max(p||0,d);s+=f,await new Promise(h=>setTimeout(h,f));continue}throw l.$metadata||(l.$metadata={}),l.$metadata.attempts=i,l.$metadata.totalRetryDelay=s,l}}},cUe=t=>{if(!Lr.isInstance(t))return;let e=Object.keys(t.headers).find(i=>i.toLowerCase()==="retry-after");if(!e)return;let r=t.headers[e],o=Number(r);if(!Number.isNaN(o))return Math.min(o*1e3,2e4);let n=new Date(r);return Math.min(n.getTime()-Date.now(),2e4)}});var TI,Fte=_(()=>{$I();Ad();l2();TI=class extends $m{rateLimiter;constructor(e,r){let{rateLimiter:o,...n}=r??{};super(e,n),this.rateLimiter=o??new ju,this.mode=Vr.ADAPTIVE}async retry(e,r){return super.retry(e,r,{beforeRequest:async()=>this.rateLimiter.getSendToken(),afterRequest:o=>{this.rateLimiter.updateClientSendingRate(o)}})}}});var CI,OI,ca,ua,d2,p2,la,qte=_(()=>{ve();a2();Lv();Ad();xm();CI="AWS_MAX_ATTEMPTS",OI="max_attempts",ca={environmentVariableSelector:t=>{let e=t[CI];if(!e)return;let r=parseInt(e);if(Number.isNaN(r))throw new Error(`Environment variable ${CI} mast be a number, got "${e}"`);return r},configFileSelector:t=>{let e=t[OI];if(!e)return;let r=parseInt(e);if(Number.isNaN(r))throw new Error(`Shared config file entry ${OI} mast be a number, got "${e}"`);return r},default:Yi},ua=(t,e)=>{let{retryStrategy:r,retryMode:o}=t,{defaultMaxAttempts:n=Yi,defaultBaseDelay:i=vr.delay()}=e??{},s=jt(t.maxAttempts??n),a=r?Promise.resolve(r):void 0,c=async()=>{let u=await s();return await jt(o)()===Vr.ADAPTIVE?new Em(s,{maxAttempts:u,baseDelay:i}):new Qi({maxAttempts:u,baseDelay:i})};return Object.assign(t,{maxAttempts:s,retryStrategy:()=>a??=c()})},d2="AWS_RETRY_MODE",p2="retry_mode",la={environmentVariableSelector:t=>t[d2],configFileSelector:t=>t[p2],default:li}});var f2,m2,Vte,Gte=_(()=>{ge();Mv();f2=()=>t=>async e=>{let{request:r}=e;return We.isInstance(r)&&(delete r.headers[Uu],delete r.headers[Lu]),t(e)},m2={name:"omitRetryHeadersMiddleware",tags:["RETRY","HEADERS","OMIT_RETRY_HEADERS"],relation:"before",toMiddleware:"awsAuthMiddleware",override:!0},Vte=t=>({applyToStack:e=>{e.addRelativeTo(f2(),m2)}})});var h2={};Ht(h2,{AdaptiveRetryStrategy:()=>Em,CONFIG_MAX_ATTEMPTS:()=>OI,CONFIG_RETRY_MODE:()=>p2,ConfiguredRetryStrategy:()=>AI,DEFAULT_MAX_ATTEMPTS:()=>Yi,DEFAULT_RETRY_DELAY_BASE:()=>bI,DEFAULT_RETRY_MODE:()=>li,DefaultRateLimiter:()=>ju,DeprecatedAdaptiveRetryStrategy:()=>TI,DeprecatedStandardRetryStrategy:()=>$m,ENV_MAX_ATTEMPTS:()=>CI,ENV_RETRY_MODE:()=>d2,INITIAL_RETRY_TOKENS:()=>Sm,INVOCATION_ID_HEADER:()=>Uu,MAXIMUM_RETRY_DELAY:()=>zv,NODE_MAX_ATTEMPT_CONFIG_OPTIONS:()=>ca,NODE_RETRY_MODE_CONFIG_OPTIONS:()=>la,NO_RETRY_INCREMENT:()=>xI,REQUEST_HEADER:()=>Lu,RETRY_COST:()=>QF,RETRY_MODES:()=>Vr,Retry:()=>vr,StandardRetryStrategy:()=>Qi,THROTTLING_RETRY_DELAY_BASE:()=>SI,TIMEOUT_RETRY_COST:()=>e2,defaultDelayDecider:()=>PI,defaultRetryDecider:()=>kI,getOmitRetryHeadersPlugin:()=>Vte,getRetryAfterHint:()=>Dte,getRetryPlugin:()=>yc,isBrowserNetworkError:()=>XF,isClockSkewCorrectedError:()=>JF,isClockSkewError:()=>wI,isNodeJsHttp2TransientError:()=>YF,isRetryableByTrait:()=>Nv,isServerError:()=>_I,isThrottlingError:()=>aa,isTransientError:()=>Mu,omitRetryHeadersMiddleware:()=>f2,omitRetryHeadersMiddlewareOptions:()=>m2,resolveRetryConfig:()=>ua,retryMiddleware:()=>uUe,retryMiddlewareOptions:()=>i2});var uUe,yc,jo=_(()=>{NJ();s2();bm();a2();Ute();$I();Lv();Ad();Mv();xm();Fte();l2();c2();u2();qte();Gte();s2();r2();uUe=o2(Sj),yc=Nte(Sj)});function di(t,e,r){t.__aws_sdk_context?t.__aws_sdk_context.features||(t.__aws_sdk_context.features={}):t.__aws_sdk_context={features:{}},t.__aws_sdk_context.features[e]=r}var g2=_(()=>{jo();vr.v2026||=typeof process=="object"&&process.env?.AWS_NEW_RETRIES_2026==="true"});function Hte(t,e,r){return t.$source||(t.$source={}),t.$source[e]=r,t}var Kte=_(()=>{});function Rm(t){return t}var y2,v2,da,Bte=_(()=>{ge();y2=t=>e=>async r=>{if(!We.isInstance(r.request))return e(r);let{request:o}=r,{handlerProtocol:n=""}=t.requestHandler.metadata||{};if(n.indexOf("h2")>=0&&!o.headers[":authority"])delete o.headers.host,o.headers[":authority"]=o.hostname+(o.port?":"+o.port:"");else if(!o.headers.host){let i=o.hostname;o.port!=null&&(i+=`:${o.port}`),o.headers.host=i}return e(r)},v2={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},da=t=>({applyToStack:e=>{e.add(y2(t),v2)}})});var w2,_2,pa,Zte=_(()=>{w2=()=>(t,e)=>async r=>{try{let o=await t(r),{clientName:n,commandName:i,logger:s,dynamoDbDocumentClientOptions:a={}}=e,{overrideInputFilterSensitiveLog:c,overrideOutputFilterSensitiveLog:u}=a,l=c??e.inputFilterSensitiveLog,d=u??e.outputFilterSensitiveLog,{$metadata:p,...f}=o.output;return s?.info?.({clientName:n,commandName:i,input:l(r.input),output:d(f),metadata:p}),o}catch(o){let{clientName:n,commandName:i,logger:s,dynamoDbDocumentClientOptions:a={}}=e,{overrideInputFilterSensitiveLog:c}=a,u=c??e.inputFilterSensitiveLog;throw s?.error?.({clientName:n,commandName:i,input:u(r.input),error:o,metadata:o.$metadata}),o}},_2={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},pa=t=>({applyToStack:e=>{e.add(w2(),_2)}})});var DI,b2=_(()=>{DI={step:"build",tags:["RECURSION_DETECTION","TRACE_CONTEXT_PROPAGATION"],name:"recursionDetectionMiddleware",override:!0,priority:"low"}});var Fu,S2,NI,x2,E2,jv,Wte=_(()=>{Fu={REQUEST_ID:Symbol.for("_AWS_LAMBDA_REQUEST_ID"),X_RAY_TRACE_ID:Symbol.for("_AWS_LAMBDA_X_RAY_TRACE_ID"),TENANT_ID:Symbol.for("_AWS_LAMBDA_TENANT_ID"),TRACEPARENT:Symbol.for("_AWS_LAMBDA_TRACEPARENT"),TRACESTATE:Symbol.for("_AWS_LAMBDA_TRACESTATE"),BAGGAGE:Symbol.for("_AWS_LAMBDA_BAGGAGE")},S2=["true","1"].includes(process.env?.AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA??"");S2||(globalThis.awslambda=globalThis.awslambda||{});NI=class{static PROTECTED_KEYS=Fu;isProtectedKey(e){return Object.values(Fu).includes(e)}getRequestId(){return this.get(Fu.REQUEST_ID)??"-"}getXRayTraceId(){return this.get(Fu.X_RAY_TRACE_ID)}getTenantId(){return this.get(Fu.TENANT_ID)}getTraceparent(){return this.get(Fu.TRACEPARENT)}getTracestate(){return this.get(Fu.TRACESTATE)}getBaggage(){return this.get(Fu.BAGGAGE)}},x2=class extends NI{currentContext;getContext(){return this.currentContext}hasContext(){return this.currentContext!==void 0}get(e){return this.currentContext?.[e]}set(e,r){if(this.isProtectedKey(e))throw new Error(`Cannot modify protected Lambda context field: ${String(e)}`);this.currentContext=this.currentContext||{},this.currentContext[e]=r}run(e,r){return this.currentContext=e,r()}},E2=class t extends NI{als;static async create(){let e=new t,r=await import("node:async_hooks");return e.als=new r.AsyncLocalStorage,e}getContext(){return this.als.getStore()}hasContext(){return this.als.getStore()!==void 0}get(e){return this.als.getStore()?.[e]}set(e,r){if(this.isProtectedKey(e))throw new Error(`Cannot modify protected Lambda context field: ${String(e)}`);let o=this.als.getStore();if(!o)throw new Error("No context available");o[e]=r}run(e,r){return this.als.run(e,r)}};(function(t){let e=null;async function r(o){return e||(e=(async()=>{let i=o===!0||"AWS_LAMBDA_MAX_CONCURRENCY"in process.env?await E2.create():new x2;return!S2&&globalThis.awslambda?.InvokeStore?globalThis.awslambda.InvokeStore:(!S2&&globalThis.awslambda&&(globalThis.awslambda.InvokeStore=i),i)})()),e}t.getInstanceAsync=r,t._testing=process.env.AWS_LAMBDA_BENCHMARK_MODE==="1"?{reset:()=>{e=null,globalThis.awslambda?.InvokeStore&&delete globalThis.awslambda.InvokeStore,globalThis.awslambda={InvokeStore:void 0}}}:void 0})(jv||(jv={}))});function pUe(t){for(let e of Object.keys(t)){let r=e.toLowerCase();e!==r&&(r===R2||r===Jte||r===Xte)&&(t[r]=t[e],delete t[e])}}var lUe,dUe,$2,R2,Jte,Xte,zI,I2=_(()=>{Wte();ge();lUe="AWS_LAMBDA_FUNCTION_NAME",dUe="_X_AMZN_TRACE_ID",$2="X-Amzn-Trace-Id",R2="traceparent",Jte="tracestate",Xte="baggage",zI=()=>t=>async e=>{let{request:r}=e;if(!We.isInstance(r))return t(e);let o;{let n=Object.keys(r.headers??{}).find(i=>i.toLowerCase()===$2.toLowerCase())??$2;if(!r.headers.hasOwnProperty(n)){let i=process.env[lUe],s=process.env[dUe];o??=await jv.getInstanceAsync();let c=o?.getXRayTraceId()??s,u=l=>typeof l=="string"&&l.length>0;u(i)&&u(c)&&(r.headers[$2]=c)}}if(pUe(r.headers),!r.headers[R2]){let i=(o??=await jv.getInstanceAsync())?.getTraceparent?.();if(i){r.headers[R2]=i;let s=o?.getTracestate?.();s&&(r.headers[Jte]=s);let a=o?.getBaggage?.();a&&(r.headers[Xte]=a)}}return t(e)}});var fa,Yte=_(()=>{b2();I2();fa=t=>({applyToStack:e=>{e.add(zI(),DI)}})});var Qte,ere=_(()=>{Qte=(t,e)=>{if(!e||e.length===0)return t;let r=[];for(let o of e)for(let n of t)n.schemeId.split("#")[1]===o&&r.push(n);for(let o of t)r.find(({schemeId:n})=>n===o.schemeId)||r.push(o);return r}});function fUe(t){let e=new Map;for(let r of t)e.set(r.schemeId,r);return e}var Pd,MI=_(()=>{Pe();ere();Pd=(t,e)=>(r,o)=>async n=>{let i=t.httpAuthSchemeProvider(await e.httpAuthSchemeParametersProvider(t,o,n.input)),s=t.authSchemePreference?await t.authSchemePreference():[],a=Qte(i,s),c=fUe(t.httpAuthSchemes),u=Bt(o),l=[];for(let d of a){let p=c.get(d.schemeId);if(!p){l.push(`HttpAuthScheme \`${d.schemeId}\` was not enabled for this service.`);continue}let f=p.identityProvider(await e.identityProviderConfigProvider(t));if(!f){l.push(`HttpAuthScheme \`${d.schemeId}\` did not have an IdentityProvider configured.`);continue}let{identityProperties:h={},signingProperties:y={}}=d.propertiesExtractor?.(t,o)||{};d.identityProperties=Object.assign(d.identityProperties||{},h),d.signingProperties=Object.assign(d.signingProperties||{},y),u.selectedHttpAuthScheme={httpAuthOption:d,identity:await f(d.identityProperties),signer:p.signer};break}if(!u.selectedHttpAuthScheme)throw new Error(l.join(`
25
+ If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body`);return n.stream()};return Object.assign(t,{transformToByteArray:r,transformToString:async n=>{let i=await r();if(n==="base64")return eI(i);if(n==="hex")return ai(i);if(n===void 0||n==="utf8"||n==="utf-8")return vee(i);if(typeof TextDecoder=="function")return new TextDecoder(n).decode(i);throw new Error("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(e)throw new Error(bee);if(e=!0,See(t))return o(t);if(Cr(t))return t;throw new Error(`Cannot transform payload to web stream, got ${t}`)}})},See=t=>typeof Blob=="function"&&t instanceof Blob});import{Writable as EMe}from"node:stream";var rI,SF,xF=_(()=>{_v();bF();Wi();rI=t=>Ru(t)?wF(t):Cr(t)?_F(t):new Promise((e,r)=>{let o=new SF,n=t;n.pipe(o),n.on("error",i=>{o.end(),r(i)}),o.on("error",r),o.on("finish",function(){let i=Ws(this.bufferedBytes);e(i)})}),SF=class extends EMe{bufferedBytes=[];_write(e,r,o){this.bufferedBytes.push(e),o()}}});import{Readable as EF}from"node:stream";var $ee,nI,Ree=_(()=>{bu();Eee();xF();$ee="The stream has already been transformed.",nI=t=>{if(!(t instanceof EF))try{return xee(t)}catch{let n=t?.__proto__?.constructor?.name||t;throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${n}`)}let e=!1,r=async()=>{if(e)throw new Error($ee);return e=!0,await rI(t)};return Object.assign(t,{transformToByteArray:r,transformToString:async o=>{let n=await r();return o===void 0||Buffer.isEncoding(o)?Zi(n.buffer,n.byteOffset,n.byteLength).toString(o):new TextDecoder(o).decode(n)},transformToWebStream:()=>{if(e)throw new Error($ee);if(t.readableFlowing!==null)throw new Error("The stream has been consumed by other callbacks.");if(typeof EF.toWeb!="function")throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available.");return e=!0,EF.toWeb(t)}})}});async function Iee(t){return typeof t.stream=="function"&&(t=t.stream()),t.tee()}var Aee=_(()=>{});import{PassThrough as Pee}from"node:stream";async function kee(t){if(Cr(t)||Ru(t))return Iee(t);let e=new Pee,r=new Pee;return t.pipe(e),t.pipe(r),[e,r]}var Tee=_(()=>{Aee();Wi()});var Ed={};Ht(Ed,{ChecksumStream:()=>cm,Hash:()=>YR,LazyJsonString:()=>Er,NumericValue:()=>nt,Uint8ArrayBlobAdapter:()=>xd,_parseEpochTimestamp:()=>Eu,_parseRfc3339DateTimeWithOffset:()=>mR,_parseRfc7231DateTime:()=>hR,calculateBodyLength:()=>Zs,concatBytes:()=>Ws,copyDocumentWithTransform:()=>iX,createBufferedReadable:()=>cee,createChecksumStream:()=>oee,dateToUtcString:()=>Oo,deserializerMiddleware:()=>wR,deserializerMiddlewareOption:()=>lF,expectBoolean:()=>cX,expectByte:()=>aR,expectFloat32:()=>yv,expectInt:()=>uX,expectInt32:()=>iR,expectLong:()=>Zf,expectNonNull:()=>lX,expectNumber:()=>Bf,expectObject:()=>r4,expectShort:()=>sR,expectString:()=>dX,expectUnion:()=>uR,fromArrayBuffer:()=>Zi,fromBase64:()=>fr,fromHex:()=>vR,fromString:()=>_u,fromUtf8:()=>Tr,generateIdempotencyToken:()=>Lo,getAwsChunkedEncodingStream:()=>pee,getSerdePlugin:()=>HQ,handleFloat:()=>fX,hasOwn:()=>Se,headStream:()=>gee,isArrayBuffer:()=>rR,isBlob:()=>Ru,isReadableStream:()=>Cr,limitedParseDouble:()=>dR,limitedParseFloat:()=>mX,limitedParseFloat32:()=>hX,logger:()=>Wf,nv:()=>yR,parseBoolean:()=>aX,parseEpochTimestamp:()=>Qf,parseRfc3339DateTime:()=>wX,parseRfc3339DateTimeWithOffset:()=>Yf,parseRfc7231DateTime:()=>xu,quoteHeader:()=>fR,sdkStreamMixin:()=>nI,serializerMiddleware:()=>XR,serializerMiddlewareOption:()=>dF,splitEvery:()=>gR,splitHeader:()=>em,splitStream:()=>kee,streamCollector:()=>rI,strictParseByte:()=>pR,strictParseDouble:()=>vv,strictParseFloat:()=>pX,strictParseFloat32:()=>lR,strictParseInt:()=>yX,strictParseInt32:()=>vX,strictParseLong:()=>n4,strictParseShort:()=>Su,toBase64:()=>Wt,toHex:()=>ai,toUint8Array:()=>Jn,toUtf8:()=>ur,v4:()=>um});import{getRandomValues as $Me}from"node:crypto";var xd,RMe,um,Lo,xe=_(()=>{Q7();e4();tX();nR();rX();oX();sX();_X();bX();o4();SX();$X();RX();IX();PX();d4();TX();p4();_v();bu();Qj();m4();KQ();uF();ZQ();pF();iee();uee();fee();yee();Ree();Tee();Wi();xF();Pe();xd=class extends eX(ur,Tr,Wt,fr){},RMe=$Me,um=nX(RMe),Lo=um});var sn,oI=_(()=>{xe();sn=async(t=new Uint8Array,e)=>{if(t instanceof Uint8Array)return xd.mutate(t);if(!t)return xd.mutate(new Uint8Array);let r=e.streamCollector(t);return xd.mutate(await r)}});function Ji(t){return encodeURIComponent(t).replace(/[!'()*]/g,function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})}var iI=_(()=>{});var Fr,lm=_(()=>{Fr=class{serdeContext;setSerdeContext(e){this.serdeContext=e}}});async function sI(t,e,r=1024*1024){let o=t.size,n=0;for(;n<o;){let i=t.slice(n,Math.min(o,n+r));e(new Uint8Array(await i.arrayBuffer())),n+=i.size}}var $F=_(()=>{});var Cee,Oee=_(()=>{$F();Cee=async function(e,r){let o=new e;return await sI(r,n=>{o.update(n)}),o.digest()}});import{Writable as IMe}from"node:stream";var dm,RF=_(()=>{xe();dm=class extends IMe{hash;constructor(e,r){super(r),this.hash=e}_write(e,r,o){try{this.hash.update(Jn(e))}catch(n){return o(n)}o()}}});import{createReadStream as AMe}from"node:fs";var Dee,PMe,Nee=_(()=>{RF();Dee=(t,e)=>new Promise((r,o)=>{if(!PMe(e)){o(new Error("Unable to calculate hash for non-file streams."));return}let n=AMe(e.path,{start:e.start,end:e.end}),i=new t,s=new dm(i);n.pipe(s),n.on("error",a=>{s.end(),o(a)}),s.on("error",o),s.on("finish",function(){i.digest().then(r).catch(o)})}),PMe=t=>typeof t.path=="string"});var zee,Mee=_(()=>{RF();zee=(t,e)=>{if(e.readableFlowing!==null)throw new Error("Unable to calculate hash for flowing readable stream");let r=new t,o=new dm(r);return e.pipe(o),new Promise((n,i)=>{e.on("error",s=>{o.end(),i(s)}),o.on("error",i),o.on("finish",()=>{r.digest().then(n).catch(i)})})}});function IF(t,e){let r=t[0],o=t[1],n=t[2],i=t[3];for(let s=0;s<64;++s){let a,c;s<16?(a=o&n|~o&i,c=s):s<32?(a=i&o|n&~i,c=(5*s+1)%16):s<48?(a=o^n^i,c=(3*s+5)%16):(a=n^(o|~i),c=7*s%16);let u=e.getUint32(c*4,!0),l=i;i=n,n=o;let d=kMe[(s>>4)*4+(s&3)],p=(r+a&Iu)+(u+TMe[s]&Iu)&Iu;o=o+((p<<d|p>>>32-d)>>>0)&Iu,r=l}t[0]=t[0]+r&Iu,t[1]=t[1]+o&Iu,t[2]=t[2]+n&Iu,t[3]=t[3]+i&Iu}var pm,Uee,Iu,kMe,TMe,AF=_(()=>{xe();pm=class{digestLength=16;state=Uint32Array.from(Uee);writeBuffer=new DataView(new ArrayBuffer(64));bufferLength=0;bytesHashed=0;update(e){let r=Jn(e),o=0,n=r.byteLength;for(this.bytesHashed+=n;n>0;)this.writeBuffer.setUint8(this.bufferLength++,r[o++]),--n,this.bufferLength===64&&(IF(this.state,this.writeBuffer),this.bufferLength=0)}async digest(){let e=Uint32Array.from(this.state),r=new DataView(this.writeBuffer.buffer.slice(0)),o=this.bufferLength,n=this.bytesHashed*8;if(r.setUint8(o++,128),this.bufferLength%64>=56){for(let a=o;a<64;++a)r.setUint8(a,0);IF(e,r),o=0}for(let a=o;a<56;++a)r.setUint8(a,0);r.setUint32(56,n>>>0,!0),r.setUint32(60,Math.floor(n/2**32),!0),IF(e,r);let i=new Uint8Array(16),s=new DataView(i.buffer);for(let a=0;a<4;++a)s.setUint32(a*4,e[a],!0);return i}reset(){this.state.set(Uee),this.writeBuffer=new DataView(new ArrayBuffer(64)),this.bufferLength=0,this.bytesHashed=0}},Uee=[1732584193,4023233417,2562383102,271733878],Iu=4294967295,kMe=Uint8Array.of(7,12,17,22,5,9,14,20,4,11,16,23,6,10,15,21),TMe=Array.from({length:64},(t,e)=>Math.abs(Math.sin(e+1))*2**32>>>0)});import{createHash as PF}from"node:crypto";function OMe(){return class{digestLength=16;hash=PF("md5");update(e){this.hash.update(Jn(e))}async digest(){let e=this.hash.copy().digest();return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}reset(){this.hash=PF("md5")}}}var CMe,kF,Lee=_(()=>{xe();AF();CMe=(()=>{try{return PF("md5"),!0}catch{return!1}})(),kF=CMe?OMe():pm});var jee,TF,fm,CF=_(()=>{jee=new Uint32Array(256);for(let t=0;t<256;++t){let e=t;for(let r=0;r<8;++r)e=e&1?3988292384^e>>>1:e>>>1;jee[t]=e>>>0}TF=4294967295,fm=class{digestLength=4;checksum=TF;update(e){for(let r=0;r<e.length;++r)this.checksum=this.checksum>>>8^jee[(this.checksum^e[r])&255]}digestSync(){return(this.checksum^TF)>>>0}async digest(){let e=this.digestSync(),r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,e,!1),r}reset(){this.checksum=TF}}});import*as OF from"node:zlib";function DMe(t){return class{digestLength=4;value=0;update(r){this.value=t(r,this.value)}digestSync(){return this.value>>>0}async digest(){let r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,this.digestSync(),!1),r}reset(){this.value=0}}}var Fee,$d,qee=_(()=>{CF();Fee=typeof OF.crc32=="function"?OF.crc32:void 0,$d=Fee?DMe(Fee):fm});var an,Vee,NMe,hc,Gee,zMe,aI=_(()=>{xe();an=64,Vee=32,NMe=2**53-1,hc=class t{digestLength=Vee;state=Int32Array.from(Gee);w;buffer=new Uint8Array(64);bufferLength=0;bytesHashed=0;finished=!1;inner;outer;constructor(e){if(e){let r=t.normalizeKey(e);this.inner=new t,this.outer=new t;let{inner:o,outer:n}=this,i=new Uint8Array(an*2);for(let s=0;s<an;++s)i[s]=54^r[s],i[s+an]=92^r[s];o.update(i.subarray(0,an)),n.update(i.subarray(an))}}update(e){if(this.finished)throw new Error("Attempted to update an already finished HMAC.");if(this.inner){this.inner.update(e);return}let r=Jn(e),o=0,{byteLength:n}=r;if(this.bytesHashed+=n,this.bytesHashed*8>NMe)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;n>0;)this.buffer[this.bufferLength++]=r[o++],n--,this.bufferLength===an&&(this.hashBuffer(),this.bufferLength=0)}async digest(){let{inner:e,outer:r}=this;if(e&&r){if(this.finished)throw new Error("Attempted to digest an already finished HMAC.");this.finished=!0;let o=e.digestSync();return r.update(o),r.digestSync()}return this.digestSync()}reset(){this.state=Int32Array.from(Gee),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0}digestSync(){let e=this.state.slice(),r=this.buffer.slice(),o=this.bufferLength,n=this.bytesHashed*8,i=new DataView(r.buffer,r.byteOffset,r.byteLength);if(i.setUint8(o++,128),(o-1)%an>=an-8){for(let a=o;a<an;++a)i.setUint8(a,0);this.hashBufferWith(e,r),o=0}for(let a=o;a<an-8;++a)i.setUint8(a,0);i.setUint32(an-8,Math.floor(n/4294967296),!1),i.setUint32(an-4,n,!1),this.hashBufferWith(e,r);let s=new Uint8Array(Vee);for(let a=0;a<8;++a)s[a*4]=e[a]>>>24&255,s[a*4+1]=e[a]>>>16&255,s[a*4+2]=e[a]>>>8&255,s[a*4+3]=e[a]>>>0&255;return s}static normalizeKey(e){let r=Jn(e);if(r.byteLength>an){let o=new t;o.update(r);let n=o.digestSync(),i=new Uint8Array(an);return i.set(n),i}if(r.byteLength<an){let o=new Uint8Array(an);return o.set(r),o}return r}hashBuffer(){this.hashBufferWith(this.state,this.buffer)}hashBufferWith(e,r){let o=this.w??=new Int32Array(64),n=e[0],i=e[1],s=e[2],a=e[3],c=e[4],u=e[5],l=e[6],d=e[7];for(let p=0;p<an;++p){if(p<16)o[p]=(r[p*4]&255)<<24|(r[p*4+1]&255)<<16|(r[p*4+2]&255)<<8|r[p*4+3]&255;else{let y=o[p-2],w=(y>>>17|y<<15)^(y>>>19|y<<13)^y>>>10;y=o[p-15];let b=(y>>>7|y<<25)^(y>>>18|y<<14)^y>>>3;o[p]=(w+o[p-7]|0)+(b+o[p-16]|0)}let f=(((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))+(c&u^~c&l)|0)+(d+(zMe[p]+o[p]|0)|0)|0,h=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&i^n&s^i&s)|0;d=l,l=u,u=c,c=a+f|0,a=s,s=i,i=n,n=f+h|0}e[0]+=n,e[1]+=i,e[2]+=s,e[3]+=a,e[4]+=c,e[5]+=u,e[6]+=l,e[7]+=d}},Gee=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),zMe=new Int32Array([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])});import{createHash as Hee,createHmac as MMe}from"node:crypto";function LMe(){return class{digestLength=32;secret;hash;isHmac;finished=!1;constructor(e){this.secret=e,this.isHmac=!!e,this.hash=this.createHash()}update(e){if(this.finished)throw new Error("Attempted to update an already finished hash.");this.hash.update(e)}async digest(){let e;return this.isHmac?(this.finished=!0,e=this.hash.digest()):e=this.hash.copy().digest(),new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}reset(){this.hash=this.createHash(),this.finished=!1}createHash(){return this.secret?MMe("sha256",jMe(this.secret)):Hee("sha256")}}}function jMe(t){return typeof t=="string"?t:ArrayBuffer.isView(t)?Buffer.from(t.buffer,t.byteOffset,t.byteLength):Buffer.from(t)}var UMe,Xi,Kee=_(()=>{aI();UMe=(()=>{try{return Hee("sha256"),!0}catch{return!1}})(),Xi=UMe?LMe():hc});var FMe,qMe,VMe,cI,GMe,uI,Bee=_(()=>{xe();aI();({digest:FMe,sign:qMe,importKey:VMe}=globalThis?.crypto?.subtle??{}),cI=typeof FMe=="function"&&typeof qMe=="function"&&typeof VMe=="function"?globalThis.crypto.subtle:void 0,GMe=8*1024*1024,uI=class{digestLength=32;secret;pending=[];pendingBytes=0;fallback;finished=!1;constructor(e){e&&(this.secret=Jn(e))}update(e){if(this.finished)throw new Error("Attempted to update an already finished HMAC.");if(this.fallback){this.fallback.update(e);return}this.pending.push(e.slice()),this.pendingBytes+=e.byteLength,this.pendingBytes>=GMe&&this.switchToFallback()}async digest(){if(this.fallback)return this.fallback.digest();if(this.secret&&this.finished)throw new Error("Attempted to digest an already finished HMAC.");let e=Ws(this.pending);if(cI){if(this.secret){this.finished=!0;let n=await cI.importKey("raw",this.secret,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=await cI.sign("HMAC",n,e);return new Uint8Array(i)}let o=await cI.digest("SHA-256",e);return new Uint8Array(o)}let r=new hc(this.secret);return r.update(e),r.digest()}reset(){this.pending=[],this.pendingBytes=0,this.fallback=void 0,this.finished=!1}switchToFallback(){let e=new hc(this.secret);for(let r of this.pending)e.update(r);this.fallback=e,this.pending=[],this.pendingBytes=0}}});var DF={};Ht(DF,{Crc32:()=>$d,Crc32Js:()=>fm,Crc32Node:()=>$d,Md5:()=>kF,Md5Js:()=>pm,Md5Node:()=>kF,Sha256:()=>Xi,Sha256Js:()=>hc,Sha256Node:()=>Xi,Sha256WebCrypto:()=>uI,blobHasher:()=>Cee,blobReader:()=>sI,fileStreamHasher:()=>Dee,readableStreamHasher:()=>zee});var gc=_(()=>{Oee();Nee();Mee();AF();Lee();CF();qee();aI();Kee();Bee();$F()});function Zee(t){for(let e=0;e<8;e++)t[e]^=255;for(let e=7;e>-1&&(t[e]++,t[e]===0);e--);}var Au,NF=_(()=>{xe();Au=class t{bytes;constructor(e){if(this.bytes=e,e.byteLength!==8)throw new Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(e){if(e>9223372036854776e3||e<-9223372036854776e3)throw new Error(`${e} is too large (or, if negative, too small) to represent as an Int64`);let r=new Uint8Array(8);for(let o=7,n=Math.abs(Math.round(e));o>-1&&n>0;o--,n/=256)r[o]=n;return e<0&&Zee(r),new t(r)}valueOf(){let e=this.bytes.slice(0),r=e[0]&128;return r&&Zee(e),parseInt(ai(e),16)*(r?-1:1)}toString(){return String(this.valueOf())}}});var mm,Wee,Jee,HMe,KMe,BMe,ZMe,WMe,JMe,XMe,YMe,QMe,zF=_(()=>{Pe();xe();NF();mm=class{toUtf8;fromUtf8;constructor(e,r){this.toUtf8=e,this.fromUtf8=r}format(e){let r=[];for(let i in e){if(!Se(e,i))continue;let s=this.fromUtf8(i);r.push(Uint8Array.from([s.byteLength]),s,this.formatHeaderValue(e[i]))}let o=new Uint8Array(r.reduce((i,s)=>i+s.byteLength,0)),n=0;for(let i of r)o.set(i,n),n+=i.byteLength;return o}formatHeaderValue(e){switch(e.type){case"boolean":return Uint8Array.from([e.value?0:1]);case"byte":return Uint8Array.from([2,e.value]);case"short":let r=new DataView(new ArrayBuffer(3));return r.setUint8(0,3),r.setInt16(1,e.value,!1),new Uint8Array(r.buffer);case"integer":let o=new DataView(new ArrayBuffer(5));return o.setUint8(0,4),o.setInt32(1,e.value,!1),new Uint8Array(o.buffer);case"long":let n=new Uint8Array(9);return n[0]=5,n.set(e.value.bytes,1),n;case"binary":let i=new DataView(new ArrayBuffer(3+e.value.byteLength));i.setUint8(0,6),i.setUint16(1,e.value.byteLength,!1);let s=new Uint8Array(i.buffer);return s.set(e.value,3),s;case"string":let a=this.fromUtf8(e.value),c=new DataView(new ArrayBuffer(3+a.byteLength));c.setUint8(0,7),c.setUint16(1,a.byteLength,!1);let u=new Uint8Array(c.buffer);return u.set(a,3),u;case"timestamp":let l=new Uint8Array(9);return l[0]=8,l.set(Au.fromNumber(e.value.valueOf()).bytes,1),l;case"uuid":if(!QMe.test(e.value))throw new Error(`Invalid UUID received: ${e.value}`);let d=new Uint8Array(17);return d[0]=9,d.set(vR(e.value.replace(/-/g,"")),1),d}}parse(e){let r={},o=0;for(;o<e.byteLength;){let n=e.getUint8(o++),i=this.toUtf8(new Uint8Array(e.buffer,e.byteOffset+o,n));switch(o+=n,e.getUint8(o++)){case 0:r[i]={type:Jee,value:!0};break;case 1:r[i]={type:Jee,value:!1};break;case 2:r[i]={type:HMe,value:e.getInt8(o++)};break;case 3:r[i]={type:KMe,value:e.getInt16(o,!1)},o+=2;break;case 4:r[i]={type:BMe,value:e.getInt32(o,!1)},o+=4;break;case 5:r[i]={type:ZMe,value:new Au(new Uint8Array(e.buffer,e.byteOffset+o,8))},o+=8;break;case 6:let s=e.getUint16(o,!1);o+=2,r[i]={type:WMe,value:new Uint8Array(e.buffer,e.byteOffset+o,s)},o+=s;break;case 7:let a=e.getUint16(o,!1);o+=2,r[i]={type:JMe,value:this.toUtf8(new Uint8Array(e.buffer,e.byteOffset+o,a))},o+=a;break;case 8:r[i]={type:XMe,value:new Date(new Au(new Uint8Array(e.buffer,e.byteOffset+o,8)).valueOf())},o+=8;break;case 9:let c=new Uint8Array(e.buffer,e.byteOffset+o,16);o+=16,r[i]={type:YMe,value:`${ai(c.subarray(0,4))}-${ai(c.subarray(4,6))}-${ai(c.subarray(6,8))}-${ai(c.subarray(8,10))}-${ai(c.subarray(10))}`};break;default:throw new Error("Unrecognized header type tag")}}return r}};(function(t){t[t.boolTrue=0]="boolTrue",t[t.boolFalse=1]="boolFalse",t[t.byte=2]="byte",t[t.short=3]="short",t[t.integer=4]="integer",t[t.long=5]="long",t[t.byteArray=6]="byteArray",t[t.string=7]="string",t[t.timestamp=8]="timestamp",t[t.uuid=9]="uuid"})(Wee||(Wee={}));Jee="boolean",HMe="byte",KMe="short",BMe="integer",ZMe="long",WMe="binary",JMe="string",XMe="timestamp",YMe="uuid",QMe=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/});function Yee({byteLength:t,byteOffset:e,buffer:r}){if(t<eUe)throw new Error("Provided message too short to accommodate event stream message overhead");let o=new DataView(r,e,t),n=o.getUint32(0,!1);if(t!==n)throw new Error("Reported message length does not match received message length");let i=o.getUint32(Xee,!1),s=o.getUint32(Pu,!1),a=o.getUint32(t-Rd,!1),c=new $d;if(c.update(new Uint8Array(r,e,Pu)),s!==c.digestSync())throw new Error(`The prelude checksum specified in the message (${s}) does not match the calculated CRC32 checksum (${c.digestSync()})`);if(c.update(new Uint8Array(r,e+Pu,t-(Pu+Rd))),a!==c.digestSync())throw new Error(`The message checksum (${c.digestSync()}) did not match the expected value of ${a}`);return{headers:new DataView(r,e+Pu+Rd,i),body:new Uint8Array(r,e+Pu+Rd+i,n-i-(Pu+Rd+Rd))}}var Xee,Pu,Rd,eUe,Qee=_(()=>{gc();Xee=4,Pu=Xee*2,Rd=4,eUe=Pu+Rd*2});var hm,MF=_(()=>{gc();zF();Qee();hm=class{headerMarshaller;messageBuffer;isEndOfStream;constructor(e,r){this.headerMarshaller=new mm(e,r),this.messageBuffer=[],this.isEndOfStream=!1}feed(e){this.messageBuffer.push(this.decode(e))}endOfStream(){this.isEndOfStream=!0}getMessage(){let e=this.messageBuffer.pop(),r=this.isEndOfStream;return{getMessage(){return e},isEndOfStream(){return r}}}getAvailableMessages(){let e=this.messageBuffer;this.messageBuffer=[];let r=this.isEndOfStream;return{getMessages(){return e},isEndOfStream(){return r}}}encode({headers:e,body:r}){let o=this.headerMarshaller.format(e),n=o.byteLength+r.byteLength+16,i=new Uint8Array(n),s=new DataView(i.buffer,i.byteOffset,i.byteLength),a=new $d;return s.setUint32(0,n,!1),s.setUint32(4,o.byteLength,!1),a.update(i.subarray(0,8)),s.setUint32(8,a.digestSync(),!1),i.set(o,12),i.set(r,o.byteLength+12),a.update(i.subarray(8,n-4)),s.setUint32(n-4,a.digestSync(),!1),i}decode(e){let{headers:r,body:o}=Yee(e);return{headers:this.headerMarshaller.parse(r),body:o}}formatHeaders(e){return this.headerMarshaller.format(e)}}});var gm,UF=_(()=>{gm=class{options;constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let e of this.options.inputStream)yield this.options.decoder.decode(e)}}});var ym,LF=_(()=>{ym=class{options;constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let e of this.options.messageStream)yield this.options.encoder.encode(e);this.options.includeEndFrame&&(yield new Uint8Array(0))}}});var vm,jF=_(()=>{vm=class{options;constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let e of this.options.messageStream){let r=await this.options.deserializer(e);r!==void 0&&(yield r)}}}});var wm,FF=_(()=>{wm=class{options;constructor(e){this.options=e}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let e of this.options.inputStream)yield this.options.serializer(e)}}});function lI(t){let e=0,r=0,o=null,n=null,i=a=>{if(typeof a!="number")throw new Error("Attempted to allocate an event message where size was not a number: "+a);e=a,r=4,o=new Uint8Array(a),new DataView(o.buffer).setUint32(0,a,!1)},s=async function*(){let a=t[Symbol.asyncIterator]();for(;;){let{value:c,done:u}=await a.next();if(u){if(e)if(e===r)yield o;else throw new Error("Truncated event message received.");else return;return}let l=c.length,d=0;for(;d<l;){if(!o){let f=l-d;n||(n=new Uint8Array(4));let h=Math.min(4-r,f);if(n.set(c.slice(d,d+h),r),r+=h,d+=h,r<4)break;i(new DataView(n.buffer).getUint32(0,!1)),n=null}let p=Math.min(e-r,l-d);o.set(c.slice(d,d+p),r),r+=p,d+=p,e&&e===r&&(yield o,o=null,e=0,r=0)}}};return{[Symbol.asyncIterator]:s}}var qF=_(()=>{});function ete(t,e){let r=Cv(e.deserializer,e.toUtf8);return{[Symbol.asyncIterator]:async function*(){for await(let o of t){let n=e.eventStreamCodec.decode(o),i=await r(n);i!==void 0&&(yield i)}}}}function Cv(t,e){return async function(r){let{value:o}=r.headers[":message-type"];if(o==="error"){let n=new Error(r.headers[":error-message"].value||"UnknownError");throw n.name=r.headers[":error-code"].value,n}else if(o==="exception"){let n=r.headers[":exception-type"].value,i={[n]:r},s=await t(i);if(s.$unknown){let a=new Error(e(r.body));throw a.name=n,a}throw s[n]}else if(o==="event"){let n={[r.headers[":event-type"].value]:r},i=await t(n);return i.$unknown?void 0:i}else throw Error(`Unrecognizable event type: ${r.headers[":event-type"].value}`)}}var VF=_(()=>{});var Id,tte,GF=_(()=>{MF();UF();LF();jF();FF();qF();VF();Id=class{eventStreamCodec;utfEncoder;constructor({utf8Encoder:e,utf8Decoder:r}){this.eventStreamCodec=new hm(e,r),this.utfEncoder=e}deserialize(e,r){let o=lI(e);return new vm({messageStream:new gm({inputStream:o,decoder:this.eventStreamCodec}),deserializer:Cv(r,this.utfEncoder)})}serialize(e,r){return new ym({messageStream:new wm({inputStream:e,serializer:r}),encoder:this.eventStreamCodec,includeEndFrame:!0})}},tte=t=>new Id(t)});import{Readable as tUe}from"node:stream";async function*rUe(t){let e=!1,r=!1,o=new Array;for(t.on("error",n=>{if(e||(e=!0),n)throw n}),t.on("data",n=>{o.push(n)}),t.on("end",()=>{e=!0});!r;){let n=await new Promise(i=>setTimeout(()=>i(o.shift()),0));n&&(yield n),r=e&&o.length===0}}var Ov,rte,nte=_(()=>{GF();Ov=class{universalMarshaller;constructor({utf8Encoder:e,utf8Decoder:r}){this.universalMarshaller=new Id({utf8Decoder:r,utf8Encoder:e})}deserialize(e,r){let o=typeof e[Symbol.asyncIterator]=="function"?e:rUe(e);return this.universalMarshaller.deserialize(o,r)}serialize(e,r){return tUe.from(this.universalMarshaller.serialize(e,r))}},rte=t=>new Ov(t)});var ote,ite,ste=_(()=>{ote=t=>({[Symbol.asyncIterator]:async function*(){let e=t.getReader();try{for(;;){let{done:r,value:o}=await e.read();if(r)return;yield o}}finally{e.releaseLock()}}}),ite=t=>{let e=t[Symbol.asyncIterator]();return new ReadableStream({async pull(r){let{done:o,value:n}=await e.next();if(o)return r.close();r.enqueue(n)}})}});var ate,cte=_(()=>{ate=t=>Object.assign(t,{eventStreamMarshaller:t.eventStreamSerdeProvider(t)})});var dI,ute=_(()=>{Pe();rt();xe();dI=class{marshaller;serializer;deserializer;serdeContext;defaultContentType;compositeErrorRegistry;constructor({marshaller:e,serializer:r,deserializer:o,serdeContext:n,defaultContentType:i,compositeErrorRegistry:s}){this.marshaller=e,this.serializer=r,this.deserializer=o,this.serdeContext=n,this.defaultContentType=i,this.compositeErrorRegistry=s}async serializeEventStream({eventStream:e,requestSchema:r,initialRequest:o,initialMessageType:n}){let i=this.marshaller,s=r.getEventStreamMember(),a=r.getMemberSchema(s),c=this.serializer,u=this.defaultContentType,l=Symbol("initialRequestMarker"),d={async*[Symbol.asyncIterator](){if(o){let p={":event-type":{type:"string",value:n??"initial-request"},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:u}};c.write(r,o);let f=c.flush();yield{[l]:!0,headers:p,body:f}}for await(let p of e)yield p}};return i.serialize(d,p=>{if(p[l])return{headers:p.headers,body:p.body};let f="";for(let x in p)if(Se(p,x)&&x!=="__type"){f=x;break}let{additionalHeaders:h,body:y,eventType:w,explicitPayloadContentType:b}=this.writeEventBody(f,a,p);return{headers:{":event-type":{type:"string",value:w},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:b??u},...h},body:y}})}async deserializeEventStream({response:e,responseSchema:r,initialResponseContainer:o,initialMessageType:n}){let i=this.marshaller,s=r.getEventStreamMember(),c=r.getMemberSchema(s).getMemberSchemas(),u=Symbol("initialResponseMarker"),l=i.deserialize(e.body,async f=>{let h="";for(let w in f)if(Se(f,w)&&w!=="__type"){h=w;break}let y=f[h].body;if(h===(n??"initial-response")){let w=await this.deserializer.read(r,y);return delete w[s],{[u]:!0,...w}}else if(h in c){let w=c[h];if(w.isStructSchema()){let b={},S=!1;for(let[x,R]of w.structIterator()){let{eventHeader:T,eventPayload:M}=R.getMergedTraits();if(S=S||!!(T||M),M)R.isBlobSchema()?b[x]=y:R.isStringSchema()?b[x]=(this.serdeContext?.utf8Encoder??ur)(y):R.isStructSchema()&&(b[x]=await this.deserializer.read(R,y));else if(T){let Z=f[h].headers[x]?.value;Z!=null&&(R.isNumericSchema()?Z&&typeof Z=="object"&&"bytes"in Z?b[x]=BigInt(Z.toString()):b[x]=Number(Z):b[x]=Z)}}return{[h]:await this.readEventMember(w,y,S,b)}}return{[h]:await this.deserializer.read(w,y)}}else return{$unknown:f}}),d=l[Symbol.asyncIterator](),p=await d.next();if(p.done)return l;if(p.value?.[u]){if(!r)throw new Error("@smithy::core/protocols - initial-response event encountered in event stream but no response schema given.");for(let f in p.value)Se(p.value,f)&&(o[f]=p.value[f])}return{async*[Symbol.asyncIterator](){for(p?.value?.[u]||(yield p.value);;){let{done:f,value:h}=await d.next();if(f)break;yield h}}}}async readEventMember(e,r,o,n){let i,s=e.getSchema();if(Array.isArray(s)&&s[0]===-3){let c=s[1],u=Zt.for(c);this.compositeErrorRegistry?.copyFrom(u),i=(this.compositeErrorRegistry??u)?.getErrorCtor(s)}let a=o?n:r.byteLength===0?{}:await this.deserializer.read(e,r);if(i){let c=a.message??a.Message??"Unknown",u={},l=e.getMergedTraits().error;return l&&(u.$fault=l),Object.assign(new i({}),u,{message:c},a)}return a}writeEventBody(e,r,o){let n=this.serializer,i=e,s=null,a,c=r.getSchema()[4].includes(e),u={};if(c){let p=r.getMemberSchema(e);if(p.isStructSchema()){for(let[f,h]of p.structIterator()){let{eventHeader:y,eventPayload:w}=h.getMergedTraits();if(w)s=f;else if(y){let b=o[e][f],S="binary";h.isNumericSchema()?(-2)**31<=b&&b<=2**31-1?S="integer":S="long":h.isTimestampSchema()?S="timestamp":h.isStringSchema()?S="string":h.isBooleanSchema()&&(S="boolean"),b!=null&&(u[f]={type:S,value:b},delete o[e][f])}}if(s!==null){let f=p.getMemberSchema(s);f.isBlobSchema()?a="application/octet-stream":f.isStringSchema()&&(a="text/plain"),n.write(f,o[e][s])}else n.write(p,o[e])}else if(p.isUnitSchema())n.write(p,{});else throw new Error("@smithy/core/event-streams - non-struct member not supported in event stream union.")}else{let[p,f]=o[e];i=p,n.write(15,f)}let l=n.flush()??new Uint8Array;return{body:typeof l=="string"?(this.serdeContext?.utf8Decoder??Tr)(l):l,eventType:i,explicitPayloadContentType:a,additionalHeaders:u}}}});var lte={};Ht(lte,{EventStreamCodec:()=>hm,EventStreamMarshaller:()=>Ov,EventStreamSerde:()=>dI,HeaderMarshaller:()=>mm,Int64:()=>Au,MessageDecoderStream:()=>gm,MessageEncoderStream:()=>ym,SmithyMessageDecoderStream:()=>vm,SmithyMessageEncoderStream:()=>wm,UniversalEventStreamMarshaller:()=>Id,eventStreamSerdeProvider:()=>rte,getChunkedStream:()=>lI,getMessageUnmarshaller:()=>Cv,getUnmarshalledStream:()=>ete,iterableToReadableStream:()=>ite,readableStreamToIterable:()=>ote,resolveEventStreamSerdeConfig:()=>ate,universalEventStreamSerdeProvider:()=>tte});var dte=_(()=>{MF();zF();NF();UF();LF();jF();FF();nte();ste();GF();qF();VF();cte();ute()});var ku,pI=_(()=>{Pe();rt();Pe();lm();ku=class extends Fr{options;compositeErrorRegistry;constructor(e){super(),this.options=e,this.compositeErrorRegistry=new Zt(e.defaultNamespace);for(let r of e.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(r)}getRequestType(){return We}getResponseType(){return Lr}setSerdeContext(e){this.serdeContext=e,this.serializer.setSerdeContext(e),this.deserializer.setSerdeContext(e),this.getPayloadCodec()&&this.getPayloadCodec().setSerdeContext(e)}updateServiceEndpoint(e,r){if("url"in r){e.protocol=r.url.protocol,e.hostname=r.url.hostname,e.port=r.url.port?Number(r.url.port):void 0,e.path=r.url.pathname,e.fragment=r.url.hash||void 0,e.username=r.url.username||void 0,e.password=r.url.password||void 0,e.query||(e.query={});for(let[o,n]of r.url.searchParams.entries())e.query[o]=n;if(r.headers)for(let o in r.headers)Se(r.headers,o)&&(e.headers[o]=r.headers[o].join(", "));return e}else{if(e.protocol=r.protocol,e.hostname=r.hostname,e.port=r.port?Number(r.port):void 0,e.path=r.path,e.query={...r.query},r.headers)for(let o in r.headers)Se(r.headers,o)&&(e.headers[o]=r.headers[o]);return e}}setHostPrefix(e,r,o){if(this.serdeContext?.disableHostPrefix)return;let n=B.of(r.input),i=Ki(r.traits??{});if(i.endpoint){let s=i.endpoint?.[0];if(typeof s=="string"){for(let[a,c]of n.structIterator()){if(!c.getMergedTraits().hostLabel)continue;let u=o[a];if(typeof u!="string")throw new Error(`@smithy/core/schema - ${a} in input must be a string as hostLabel.`);s=s.replace(`{${a}}`,u)}if(e.hostname=s+e.hostname,!sv(e.hostname))throw new Error(`[${e.hostname}] is not a valid hostname.`)}}}deserializeMetadata(e){return{httpStatusCode:e.statusCode,requestId:e.headers["x-amzn-requestid"]??e.headers["x-amzn-request-id"]??e.headers["x-amz-request-id"],extendedRequestId:e.headers["x-amz-id-2"],cfId:e.headers["x-amz-cf-id"]}}resolveError(e,r,o){let n=[-3,"","Error",0,[],[],0],i;for(let s of o)for(let a of r)try{a==="*"?i=s.getSchema(e):i=s.getSchema(a+"#"+e);let c=s.getErrorCtor(i);if(c)return[i,c,"modeled"];{let u=s.getBaseException();if(u){let l=s.getErrorCtor(u);if(l)return[i,l,"synthetic"]}}}catch{}for(let s of o){let a=s.getBaseException();if(a){let c=s.getErrorCtor(a);if(c)return[a,c,"synthetic"]}}return[n,Error,"native"]}async serializeEventStream({eventStream:e,requestSchema:r,initialRequest:o}){return(await this.loadEventStreamCapability()).serializeEventStream({eventStream:e,requestSchema:r,initialRequest:o})}async deserializeEventStream({response:e,responseSchema:r,initialResponseContainer:o}){return(await this.loadEventStreamCapability()).deserializeEventStream({response:e,responseSchema:r,initialResponseContainer:o})}async loadEventStreamCapability(){let{EventStreamSerde:e,eventStreamSerdeProvider:r}=await Promise.resolve().then(()=>(dte(),lte)),o=this.resolveEventStreamMarshaller(r);return new e({marshaller:o,serializer:this.serializer,deserializer:this.deserializer,serdeContext:this.serdeContext,defaultContentType:this.getDefaultContentType(),compositeErrorRegistry:this.compositeErrorRegistry})}getDefaultContentType(){throw new Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`)}async deserializeHttpMessage(e,r,o,n,i){return[]}getEventStreamMarshaller(){let e=this.serdeContext;if(!e.eventStreamMarshaller)throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");return e.eventStreamMarshaller}resolveEventStreamMarshaller(e){let r=this.serdeContext;return r.eventStreamMarshaller?r.eventStreamMarshaller:e(this.serdeContext)}}});var Tu,pte=_(()=>{Pe();rt();xe();Pe();pI();oI();iI();Tu=class extends ku{async serializeRequest(e,r,o){let n=r&&typeof r=="object"?r:{},i=this.serializer,s={},a={},c=await o.endpoint(),u=B.of(e?.input),l=[],d=[],p=!1,f,h=new We({protocol:"",hostname:"",port:void 0,path:"",fragment:void 0,query:s,headers:a,body:void 0});if(c){this.updateServiceEndpoint(h,c),this.setHostPrefix(h,e,n);let y=Ki(e.traits);if(y.http){h.method=y.http[0];let[w,b]=y.http[1].split("?");h.path=="/"?h.path=w:h.path+=w;let S=new URLSearchParams(b??"");for(let[x,R]of S)s[x]=R}}for(let[y,w]of u.structIterator()){let b=w.getMergedTraits()??{},S=n[y];if(S==null&&!w.isIdempotencyToken()){if(b.httpLabel&&(h.path.includes(`{${y}+}`)||h.path.includes(`{${y}}`)))throw new Error(`No value provided for input HTTP label: ${y}.`);continue}if(b.httpPayload)w.isStreaming()?w.isStructSchema()?n[y]&&(f=await this.serializeEventStream({eventStream:n[y],requestSchema:u})):f=S:(i.write(w,S),f=i.flush());else if(b.httpLabel){i.write(w,S);let x=i.flush();h.path.includes(`{${y}+}`)?h.path=h.path.replace(`{${y}+}`,x.split("/").map(Ji).join("/")):h.path.includes(`{${y}}`)&&(h.path=h.path.replace(`{${y}}`,Ji(x)))}else if(b.httpHeader)i.write(w,S),a[b.httpHeader.toLowerCase()]=String(i.flush());else if(typeof b.httpPrefixHeaders=="string")for(let x in S){if(!Se(S,x))continue;let R=S[x],T=b.httpPrefixHeaders+x;i.write([w.getValueSchema(),{httpHeader:T}],R),a[T.toLowerCase()]=i.flush()}else b.httpQuery||b.httpQueryParams?this.serializeQuery(w,S,s):(p=!0,l.push(y),d.push(w))}if(p&&n){let[y,w]=(u.getName(!0)??"#Unknown").split("#"),b=u.getSchema()[6],S=[3,y,w,u.getMergedTraits(),l,d,void 0];b?S[6]=b:S.pop(),i.write(S,n),f=i.flush()}return h.headers=a,h.query=s,h.body=f,h}serializeQuery(e,r,o){let n=this.serializer,i=e.getMergedTraits();if(i.httpQueryParams){for(let s in r)if(Se(r,s)&&!(s in o)){let a=r[s],c=e.getValueSchema();Object.assign(c.getMergedTraits(),{...i,httpQuery:s,httpQueryParams:void 0}),this.serializeQuery(c,a,o)}return}if(e.isListSchema()){let s=!!e.getMergedTraits().sparse,a=[];for(let c of r){n.write([e.getValueSchema(),i],c);let u=n.flush();(s||u!==void 0)&&a.push(u)}o[i.httpQuery]=a}else n.write([e,i],r),o[i.httpQuery]=n.flush()}async deserializeResponse(e,r,o){let n=this.deserializer,i=B.of(e.output),s={};if(o.statusCode>=300){let c=await sn(o.body,r);throw c.byteLength>0&&Object.assign(s,await n.read(15,c)),await this.handleError(e,r,o,s,this.deserializeMetadata(o)),new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw.")}for(let c in o.headers){if(!Se(o.headers,c))continue;let u=o.headers[c];delete o.headers[c],o.headers[c.toLowerCase()]=u}let a=await this.deserializeHttpMessage(i,r,o,s);if(a.length){let c=await sn(o.body,r);if(c.byteLength>0){let u=await n.read(i,c);for(let l of a)u[l]!=null&&(s[l]=u[l])}}else a.discardResponseBody&&await sn(o.body,r);return s.$metadata=this.deserializeMetadata(o),s}async deserializeHttpMessage(e,r,o,n,i){let s;n instanceof Set?s=i:s=n;let a=!0,c=this.deserializer,u=B.of(e),l=[];for(let[d,p]of u.structIterator()){let f=p.getMemberTraits();if(f.httpPayload){if(a=!1,p.isStreaming())p.isStructSchema()?s[d]=await this.deserializeEventStream({response:o,responseSchema:u}):s[d]=nI(o.body);else if(o.body){let y=await sn(o.body,r);y.byteLength>0&&(s[d]=await c.read(p,y))}}else if(f.httpHeader){let h=String(f.httpHeader).toLowerCase(),y=o.headers[h];if(y!=null)if(p.isListSchema()){let w=p.getValueSchema();w.getMergedTraits().httpHeader=h;let b;w.isTimestampSchema()&&w.getSchema()===4?b=gR(y,",",2):b=em(y);let S=[];for(let x of b)S.push(await c.read(w,x.trim()));s[d]=S}else s[d]=await c.read(p,y)}else if(f.httpPrefixHeaders!==void 0){s[d]={};for(let h in o.headers)if(Se(o.headers,h)&&h.startsWith(f.httpPrefixHeaders)){let y=o.headers[h],w=p.getValueSchema();w.getMergedTraits().httpHeader=h,s[d][h.slice(f.httpPrefixHeaders.length)]=await c.read(w,y)}}else f.httpResponseCode?s[d]=o.statusCode:l.push(d)}return l.discardResponseBody=a,l}}});var na,fte=_(()=>{Pe();rt();Pe();pI();oI();na=class extends ku{async serializeRequest(e,r,o){let n=this.serializer,i={},s={},a=await o.endpoint(),c=B.of(e?.input),u=c.getSchema(),l,d=r&&typeof r=="object"?r:{},p=new We({protocol:"",hostname:"",port:void 0,path:"/",fragment:void 0,query:i,headers:s,body:void 0});if(a&&(this.updateServiceEndpoint(p,a),this.setHostPrefix(p,e,d)),d){let f=c.getEventStreamMember();if(f){if(d[f]){let h={};for(let[y]of c.structIterator())y!==f&&d[y]!=null&&(h[y]=d[y]);l=await this.serializeEventStream({eventStream:d[f],requestSchema:c,initialRequest:h})}}else n.write(u,d),l=n.flush()}return p.headers=Object.assign(p.headers,s),p.query=i,p.body=l,p.method="POST",p}async deserializeResponse(e,r,o){let n=this.deserializer,i=B.of(e.output),s={};if(o.statusCode>=300){let c=await sn(o.body,r);throw c.byteLength>0&&Object.assign(s,await n.read(15,c)),await this.handleError(e,r,o,s,this.deserializeMetadata(o)),new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw.")}for(let c in o.headers){if(!Se(o.headers,c))continue;let u=o.headers[c];delete o.headers[c],o.headers[c.toLowerCase()]=u}let a=i.getEventStreamMember();if(a)s[a]=await this.deserializeEventStream({response:o,responseSchema:i,initialResponseContainer:s});else{let c=await sn(o.body,r);c.byteLength>0&&Object.assign(s,await n.read(i,c))}return s.$metadata=this.deserializeMetadata(o),s}}});var fI,HF=_(()=>{iI();fI=(t,e,r,o,n,i)=>{if(e!=null&&e[r]!==void 0){let s=o();if(s==null||s.length<=0)throw new Error("Empty value provided for input HTTP label: "+r+".");t=t.replace(n,i?s.split("/").map(a=>Ji(a)).join("/"):Ji(s))}else throw new Error("No value provided for input HTTP label: "+r+".");return t}});function mI(t,e){return new Dv(t,e)}var Dv,mte=_(()=>{Pe();HF();Dv=class{input;context;query={};method="";headers={};path="";body=null;hostname="";resolvePathStack=[];constructor(e,r){this.input=e,this.context=r}async build(){let{hostname:e,protocol:r="https",port:o,path:n}=await this.context.endpoint();this.path=n;for(let i of this.resolvePathStack)i(this.path);return new We({protocol:r,hostname:this.hostname||e,port:o,method:this.method,path:this.path,query:this.query,body:this.body,headers:this.headers})}hn(e){return this.hostname=e,this}bp(e){return this.resolvePathStack.push(r=>{this.path=`${r?.endsWith("/")?r.slice(0,-1):r||""}`+e}),this}p(e,r,o,n){return this.resolvePathStack.push(i=>{this.path=fI(i,this.input,e,r,o,n)}),this}h(e){return this.headers=e,this}q(e){return this.query=e,this}b(e){return this.body=e,this}m(e){return this.method=e,this}}});function qr(t,e){if(e.timestampFormat.useTrait&&t.isTimestampSchema()&&(t.getSchema()===5||t.getSchema()===6||t.getSchema()===7))return t.getSchema();let{httpLabel:r,httpPrefixHeaders:o,httpHeader:n,httpQuery:i}=t.getMergedTraits();return(e.httpBindings?typeof o=="string"||n?6:i||r?5:void 0:void 0)??e.timestampFormat.default}var hI=_(()=>{});var Cu,KF=_(()=>{rt();xe();lm();hI();Cu=class extends Fr{settings;constructor(e){super(),this.settings=e}read(e,r){let o=B.of(e);if(o.isListSchema())return em(r).map(n=>this.read(o.getValueSchema(),n));if(o.isBlobSchema())return(this.serdeContext?.base64Decoder??fr)(r);if(o.isTimestampSchema())switch(qr(o,this.settings)){case 5:return mR(r);case 6:return hR(r);case 7:return Eu(r);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",r),new Date(r)}if(o.isStringSchema()){let n=o.getMergedTraits().mediaType,i=r;if(n)return o.getMergedTraits().httpHeader&&(i=this.base64ToUtf8(i)),(n==="application/json"||n.endsWith("+json"))&&(i=Er.from(i)),i}return o.isNumericSchema()?Number(r):o.isBigIntegerSchema()?BigInt(r):o.isBigDecimalSchema()?new nt(r,"bigDecimal"):o.isBooleanSchema()?String(r).toLowerCase()==="true":r}base64ToUtf8(e){return(this.serdeContext?.utf8Encoder??ur)((this.serdeContext?.base64Decoder??fr)(e))}}});var Ou,hte=_(()=>{rt();xe();lm();KF();Ou=class extends Fr{codecDeserializer;stringDeserializer;constructor(e,r){super(),this.codecDeserializer=e,this.stringDeserializer=new Cu(r)}setSerdeContext(e){this.stringDeserializer.setSerdeContext(e),this.codecDeserializer.setSerdeContext(e),this.serdeContext=e}read(e,r){let o=B.of(e),n=o.getMergedTraits(),i=this.serdeContext?.utf8Encoder??ur;if(n.httpHeader||n.httpResponseCode)return this.stringDeserializer.read(o,i(r));if(n.httpPayload){if(o.isBlobSchema()){let s=this.serdeContext?.utf8Decoder??Tr;return typeof r=="string"?s(r):r}else if(o.isStringSchema())return"byteLength"in r?i(r):r}return this.codecDeserializer.read(o,r)}}});var _m,BF=_(()=>{rt();xe();lm();hI();_m=class extends Fr{settings;stringBuffer="";constructor(e){super(),this.settings=e}write(e,r){let o=B.of(e);switch(typeof r){case"object":if(r===null){this.stringBuffer="null";return}if(o.isTimestampSchema()){if(!(r instanceof Date))throw new Error(`@smithy/core/protocols - received non-Date value ${r} when schema expected Date in ${o.getName(!0)}`);switch(qr(o,this.settings)){case 5:this.stringBuffer=r.toISOString().replace(".000Z","Z");break;case 6:this.stringBuffer=Oo(r);break;case 7:this.stringBuffer=String(r.getTime()/1e3);break;default:console.warn("Missing timestamp format, using epoch seconds",r),this.stringBuffer=String(r.getTime()/1e3)}return}if(o.isBlobSchema()&&"byteLength"in r){this.stringBuffer=(this.serdeContext?.base64Encoder??Wt)(r);return}if(o.isListSchema()&&Array.isArray(r)){let s="";for(let a of r){this.write([o.getValueSchema(),o.getMergedTraits()],a);let c=this.flush(),u=o.getValueSchema().isTimestampSchema()?c:fR(c);s!==""&&(s+=", "),s+=u}this.stringBuffer=s;return}this.stringBuffer=JSON.stringify(r,null,2);break;case"string":let n=o.getMergedTraits().mediaType,i=r;if(n&&((n==="application/json"||n.endsWith("+json"))&&(i=Er.from(i)),o.getMergedTraits().httpHeader)){this.stringBuffer=(this.serdeContext?.base64Encoder??Wt)(i.toString());return}this.stringBuffer=r;break;default:o.isIdempotencyToken()?this.stringBuffer=Lo():this.stringBuffer=String(r)}}flush(){let e=this.stringBuffer;return this.stringBuffer="",e}}});var Du,gte=_(()=>{rt();BF();Du=class{codecSerializer;stringSerializer;buffer;constructor(e,r,o=new _m(r)){this.codecSerializer=e,this.stringSerializer=o}setSerdeContext(e){this.codecSerializer.setSerdeContext(e),this.stringSerializer.setSerdeContext(e)}write(e,r){let o=B.of(e),n=o.getMergedTraits();if(n.httpHeader||n.httpLabel||n.httpQuery){this.stringSerializer.write(o,r),this.buffer=this.stringSerializer.flush();return}return this.codecSerializer.write(o,r)}flush(){if(this.buffer!==void 0){let e=this.buffer;return this.buffer=void 0,e}return this.codecSerializer.flush()}}});var yte,gI,vte=_(()=>{yte=Vt(js()),gI=class{name;kind;values;constructor({name:e,kind:r=yte.FieldPosition.HEADER,values:o=[]}){this.name=e,this.kind=r,this.values=o}add(e){this.values.push(e)}set(e){this.values=e}remove(e){this.values=this.values.filter(r=>r!==e)}toString(){return this.values.map(e=>e.includes(",")||e.includes(" ")?`"${e}"`:e).join(", ")}get(){return this.values}}});var yI,wte=_(()=>{yI=class{entries={};encoding;constructor({fields:e=[],encoding:r="utf-8"}){e.forEach(this.setField.bind(this)),this.encoding=r}setField(e){this.entries[e.name.toLowerCase()]=e}getField(e){return this.entries[e.toLowerCase()]}removeField(e){delete this.entries[e.toLowerCase()]}getByType(e){return Object.values(this.entries).filter(r=>r.kind===e)}}});var oa,ia,_te=_(()=>{oa=t=>(t.logger&&t.logger.constructor?.name!=="NoOpLogger"&&t.requestHandler?.updateHttpClientConfig?.(Symbol.for("logger"),t.logger),{setHttpHandler(e){t.requestHandler=e},httpHandler(){return t.requestHandler},updateHttpClientConfig(e,r){t.requestHandler?.updateHttpClientConfig(e,r)},httpHandlerConfigs(){return t.requestHandler.httpHandlerConfigs()}}),ia=t=>({requestHandler:t.httpHandler()})});function ZF(t){return e=>async r=>{let o=r.request;if(We.isInstance(o)){let{body:n,headers:i}=o;if(n&&Object.keys(i).map(s=>s.toLowerCase()).indexOf(bte)===-1)try{let s=t(n);s!=null&&(o.headers={...o.headers,[bte]:String(s)})}catch{}}return e({...r,request:o})}}var bte,WF,sa,Ste=_(()=>{Pe();bte="content-length";WF={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},sa=t=>({applyToStack:e=>{e.add(ZF(t.bodyLengthChecker),WF)}})});var Nu,nUe,vI=_(()=>{Nu=t=>encodeURIComponent(t).replace(/[!'()*]/g,nUe),nUe=t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`});var xte,Ete=_(()=>{vI();xte=t=>t.split("/").map(Nu).join("/")});function $te(t){let e=[];for(let r of Object.keys(t).sort()){let o=t[r];if(r=Nu(r),Array.isArray(o))for(let n=0,i=o.length;n<i;n++)e.push(`${r}=${Nu(o[n])}`);else{let n=r;(o||typeof o=="string")&&(n+=`=${Nu(o)}`),e.push(n)}}return e.join("&")}var Rte=_(()=>{vI()});var zu={};Ht(zu,{Field:()=>gI,Fields:()=>yI,FromStringShapeDeserializer:()=>Cu,HttpBindingProtocol:()=>Tu,HttpInterceptingShapeDeserializer:()=>Ou,HttpInterceptingShapeSerializer:()=>Du,HttpProtocol:()=>ku,HttpRequest:()=>We,HttpResponse:()=>Lr,RequestBuilder:()=>Dv,RpcProtocol:()=>na,SerdeContext:()=>Fr,ToStringShapeSerializer:()=>_m,buildQueryString:()=>$te,collectBody:()=>sn,contentLengthMiddleware:()=>ZF,contentLengthMiddlewareOptions:()=>WF,determineTimestampFormat:()=>qr,escapeUri:()=>Nu,escapeUriPath:()=>xte,extendedEncodeURIComponent:()=>Ji,getContentLengthPlugin:()=>sa,getHttpHandlerExtensionConfiguration:()=>oa,isValidHostname:()=>sv,parseQueryString:()=>av,parseUrl:()=>nn,requestBuilder:()=>mI,resolveHttpHandlerRuntimeConfig:()=>ia,resolvedPath:()=>fI});var ge=_(()=>{oI();iI();pte();pI();fte();mte();HF();KF();hte();gte();BF();hI();lm();vte();wte();Pe();Pe();Pe();_te();Ste();vI();Ete();Rte();Pe();Pe()});var Ite,Ate,Pte,kte,Tte,Cte,Ote=_(()=>{Ite=["AccessDeniedException","AuthFailure","InvalidSignatureException","RequestExpired","RequestInTheFuture","RequestTimeTooSkewed","SignatureDoesNotMatch"],Ate=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],Pte=["TimeoutError","RequestTimeout","RequestTimeoutException"],kte=[500,502,503,504],Tte=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],Cte=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN"]});function YF(t){return t.code==="ERR_HTTP2_STREAM_ERROR"&&t.message.includes("NGHTTP2_REFUSED_STREAM")}var Nv,wI,JF,XF,aa,Mu,_I,bm=_(()=>{Ote();Nv=t=>t?.$retryable!==void 0,wI=t=>Ite.includes(t.name),JF=t=>t.$metadata?.clockSkewCorrected,XF=t=>{let e=new Set(["Failed to fetch","NetworkError when attempting to fetch resource","The Internet connection appears to be offline","Load failed","Network request failed"]);return t&&t instanceof TypeError?e.has(t.message):!1},aa=t=>t.$metadata?.httpStatusCode===429||Ate.includes(t.name)||t.$retryable?.throttling==!0,Mu=(t,e=0)=>t?.name!=="AbortError"&&(Nv(t)||JF(t)||t.name==="InvalidSignatureException"&&t.message?.includes("Signature expired")||Pte.includes(t.name)||Tte.includes(t?.code||"")||Cte.includes(t?.code||"")||kte.includes(t.$metadata?.httpStatusCode||0)||XF(t)||YF(t)||t.cause!==void 0&&e<=10&&Mu(t.cause,e+1)),_I=t=>{if(t.$metadata?.httpStatusCode!==void 0){let e=t.$metadata.httpStatusCode;return 500<=e&&e<=599&&!Mu(t)}return!1}});var bI,zv,SI,Sm,QF,e2,xI,Uu,Lu,Mv=_(()=>{bI=100,zv=2e4,SI=500,Sm=500,QF=5,e2=10,xI=1,Uu="amz-sdk-invocation-id",Lu="amz-sdk-request"});function t2(t,e){if(Lr.isInstance(t))for(let r in t.headers){if(!Se(t.headers,r))continue;let o=r.toLowerCase();if(o==="retry-after"){let n=t.headers[r],i=NaN;if(n.endsWith("GMT"))try{i=(xu(n).getTime()-Date.now())/1e3}catch(s){e?.trace?.("Failed to parse retry-after header"),e?.trace?.(s)}else n.match(/ GMT, ((\d+)|(\d+\.\d+))$/)?i=Number(n.match(/ GMT, ([\d.]+)$/)?.[1]):n.match(/^((\d+)|(\d+\.\d+))$/)?i=Number(n):Date.parse(n)>=Date.now()&&(i=(Date.parse(n)-Date.now())/1e3);return isNaN(i)?void 0:new Date(Date.now()+i*1e3)}else if(o==="x-amz-retry-after"){let n=t.headers[r],i=Number(n);if(isNaN(i)){e?.trace?.(`Failed to parse x-amz-retry-after=${n}`);return}return new Date(Date.now()+i)}}}function Dte(t,e){return t2(t,e)}var r2=_(()=>{Pe();ge();xe()});var EI,n2=_(()=>{EI=t=>t instanceof Error?t:t instanceof Object?Object.assign(new Error,t):typeof t=="string"?new Error(t):new Error(`AWS SDK error wrapper for ${t}`)});function o2(t){return e=>(r,o)=>async n=>{let i=await e.retryStrategy(),s=await e.maxAttempts();if(iUe(i)){i=i;let a=await i.acquireInitialRetryToken((o.partition_id??"")+(o.__retryLongPoll?":longpoll":"")),c=new Error,u=0,l=0,{request:d}=n,p=We.isInstance(d);for(p&&(d.headers[Uu]=um());;)try{p&&(d.headers[Lu]=`attempt=${u+1}; max=${s}`);let{response:f,output:h}=await r(n);return i.recordSuccess(a),h.$metadata.attempts=u+1,h.$metadata.totalRetryDelay=l,{response:f,output:h}}catch(f){let h=sUe(f,e.logger);if(c=EI(f),p&&t(d))throw(o.logger instanceof mo?console:o.logger)?.warn("An error was encountered in a non-retryable streaming request."),c;try{a=await i.refreshRetryTokenForRetry(a,h)}catch{throw c.$metadata||(c.$metadata={}),c.$metadata.attempts=u+1,c.$metadata.totalRetryDelay=l,c}u=a.getRetryCount();let y=a.getRetryDelay();l+=(a?.$retryLog?.acquisitionDelay??0)+y,y>0&&await oUe(y)}}else return i=i,i?.mode&&(o.userAgent=[...o.userAgent||[],["cfg/retry-mode",i.mode]]),i.retry(r,n)}}function Nte(t){let e=o2(t);return r=>({applyToStack:o=>{o.add(e(r),i2)}})}var oUe,iUe,sUe,aUe,i2,s2=_(()=>{ve();ge();xe();bm();Mv();r2();n2();oUe=t=>new Promise(e=>setTimeout(e,t)),iUe=t=>typeof t.acquireInitialRetryToken<"u"&&typeof t.refreshRetryTokenForRetry<"u"&&typeof t.recordSuccess<"u",sUe=(t,e)=>{let r={error:t,errorType:aUe(t)},o=t2(t.$response,e);return o&&(r.retryAfterHint=o),r},aUe=t=>aa(t)?"THROTTLING":Mu(t)?"TRANSIENT":_I(t)?"SERVER_ERROR":"CLIENT_ERROR",i2={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0}});var ju,$I=_(()=>{bm();ju=class t{static setTimeoutFn=(e,r)=>setTimeout(e,r);beta;minCapacity;minFillRate;scaleConstant;smooth;enabled=!1;availableTokens=0;lastMaxRate=0;measuredTxRate=0;requestCount=0;fillRate;lastThrottleTime;lastTimestamp=0;lastTxRateBucket;maxCapacity;timeWindow=0;constructor(e){this.beta=e?.beta??.7,this.minCapacity=e?.minCapacity??1,this.minFillRate=e?.minFillRate??.5,this.scaleConstant=e?.scaleConstant??.4,this.smooth=e?.smooth??.8,this.lastThrottleTime=this.getCurrentTimeInSeconds(),this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds()),this.fillRate=this.minFillRate,this.maxCapacity=this.minCapacity}async getSendToken(){return this.acquireTokenBucket(1)}updateClientSendingRate(e){let r;this.updateMeasuredRate();let o=e;if(o?.errorType==="THROTTLING"||aa(o?.error??e)){let s=this.enabled?Math.min(this.measuredTxRate,this.fillRate):this.measuredTxRate;this.lastMaxRate=s,this.calculateTimeWindow(),this.lastThrottleTime=this.getCurrentTimeInSeconds(),r=this.cubicThrottle(s),this.enableTokenBucket()}else this.calculateTimeWindow(),r=this.cubicSuccess(this.getCurrentTimeInSeconds());let i=Math.min(r,2*this.measuredTxRate);this.updateTokenBucketRate(i)}getCurrentTimeInSeconds(){return Date.now()/1e3}async acquireTokenBucket(e){if(this.enabled){for(this.refillTokenBucket();e>this.availableTokens;){let r=(e-this.availableTokens)/this.fillRate*1e3;await new Promise(o=>t.setTimeoutFn(o,r)),this.refillTokenBucket()}this.availableTokens=this.availableTokens-e}}refillTokenBucket(){let e=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=e;return}let r=(e-this.lastTimestamp)*this.fillRate;this.availableTokens=Math.min(this.maxCapacity,this.availableTokens+r),this.lastTimestamp=e}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,1/3))}cubicThrottle(e){return this.getPrecise(e*this.beta)}cubicSuccess(e){return this.getPrecise(this.scaleConstant*Math.pow(e-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(e){this.refillTokenBucket(),this.fillRate=Math.max(e,this.minFillRate),this.maxCapacity=Math.max(e,this.minCapacity),this.availableTokens=Math.min(this.availableTokens,this.maxCapacity)}updateMeasuredRate(){let e=this.getCurrentTimeInSeconds(),r=Math.floor(e*2)/2;if(this.requestCount++,r>this.lastTxRateBucket){let o=this.requestCount/(r-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(o*this.smooth+this.measuredTxRate*(1-this.smooth)),this.requestCount=0,this.lastTxRateBucket=r}}getPrecise(e){return parseFloat(e.toFixed(8))}}});var wr,xm=_(()=>{wr=class t{static v2026=typeof process<"u"&&process.env?.SMITHY_NEW_RETRIES_2026==="true";static delay(){return t.v2026?50:100}static throttlingDelay(){return t.v2026?1e3:500}static cost(){return t.v2026?14:5}static throttlingCost(){return t.v2026?5:10}static modifiedCostType(){return t.v2026?"THROTTLING":"TRANSIENT"}}});var RI,zte=_(()=>{xm();RI=class{x=wr.delay();computeNextBackoffDelay(e){let n=Math.random()*Math.min(this.x*2**e,2e4);return Math.floor(n)}setDelayBase(e){this.x=e}}});var Uv,Mte=_(()=>{Uv=class{delay;count;cost;longPoll;$retryLog={acquisitionDelay:0};constructor(e,r,o,n){this.delay=e,this.count=r,this.cost=o,this.longPoll=n}getRetryCount(){return this.count}getRetryDelay(){return Math.min(2e4,this.delay)}getRetryCost(){return this.cost}isLongPoll(){return this.longPoll}}});var Vr,Yi,li,Ad=_(()=>{(function(t){t.STANDARD="standard",t.ADAPTIVE="adaptive"})(Vr||(Vr={}));Yi=3,li=Vr.STANDARD});var II,Qi,Lv=_(()=>{zte();Mte();Ad();xm();II={incompatible:1,attempts:2,capacity:3},Qi=class{mode=Vr.STANDARD;retryBackoffStrategy;capacity=500;maxAttemptsProvider;baseDelay;constructor(e){typeof e=="number"?this.maxAttemptsProvider=async()=>e:typeof e=="function"?this.maxAttemptsProvider=e:e&&typeof e=="object"&&(this.maxAttemptsProvider=async()=>e.maxAttempts,this.baseDelay=e.baseDelay,this.retryBackoffStrategy=e.backoff),this.maxAttemptsProvider??=async()=>Yi,this.baseDelay??=wr.delay(),this.retryBackoffStrategy??=new RI}async acquireInitialRetryToken(e){return new Uv(wr.delay(),0,void 0,wr.v2026&&e.includes(":longpoll"))}async refreshRetryTokenForRetry(e,r){let o=await this.getMaxAttempts(),n=this.retryCode(e,r,o),i=n===0,s=e.isLongPoll?.();if(i||s){let a=r.errorType;this.retryBackoffStrategy.setDelayBase(a==="THROTTLING"?wr.throttlingDelay():this.baseDelay);let c=this.retryBackoffStrategy.computeNextBackoffDelay(e.getRetryCount()),u=c;if(r.retryAfterHint instanceof Date&&(u=Math.max(c,Math.min(r.retryAfterHint.getTime()-Date.now(),c+5e3))),i){let l=this.getCapacityCost(a);this.capacity-=l;let d=new Uv(0,e.getRetryCount()+1,l,e.isLongPoll?.()??!1);return await new Promise(p=>setTimeout(p,u)),d.$retryLog.acquisitionDelay=u,d}else{let l=wr.v2026&&n===II.capacity&&s?u:0;l>0&&await new Promise(d=>setTimeout(d,l))}}throw new Error("No retry token available")}recordSuccess(e){this.capacity=Math.min(500,this.capacity+(e.getRetryCost()??1))}getCapacity(){return this.capacity}async maxAttempts(){return this.maxAttemptsProvider()}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch{return console.warn(`Max attempts provider could not resolve. Using default of ${Yi}`),Yi}}retryCode(e,r,o){let n=e.getRetryCount()+1,i=this.isRetryableError(r.errorType)?0:II.incompatible,s=n<o?0:II.attempts,a=this.capacity>=this.getCapacityCost(r.errorType)?0:II.capacity;return i||s||a}getCapacityCost(e){return e===wr.modifiedCostType()?wr.throttlingCost():wr.cost()}isRetryableError(e){return e==="THROTTLING"||e==="TRANSIENT"}}});var Em,a2=_(()=>{$I();Lv();Ad();Em=class{mode=Vr.ADAPTIVE;rateLimiter;standardRetryStrategy;constructor(e,r){let{rateLimiter:o}=r??{};this.rateLimiter=o??new ju,this.standardRetryStrategy=r?new Qi({maxAttempts:typeof e=="number"?e:3,...r}):new Qi(e)}async acquireInitialRetryToken(e){let r=await this.standardRetryStrategy.acquireInitialRetryToken(e);return await this.rateLimiter.getSendToken(),r}async refreshRetryTokenForRetry(e,r){this.rateLimiter.updateClientSendingRate(r);let o=await this.standardRetryStrategy.refreshRetryTokenForRetry(e,r);return await this.rateLimiter.getSendToken(),o}recordSuccess(e){this.rateLimiter.updateClientSendingRate({}),this.standardRetryStrategy.recordSuccess(e)}async maxAttemptsProvider(){return this.standardRetryStrategy.maxAttempts()}}});var AI,Ute=_(()=>{Lv();xm();AI=class extends Qi{computeNextBackoffDelay;constructor(e,r=wr.delay()){super(typeof e=="function"?e:async()=>e),typeof r=="number"?this.computeNextBackoffDelay=()=>r:this.computeNextBackoffDelay=r,this.retryBackoffStrategy.computeNextBackoffDelay=o=>{let n=o+1;return this.computeNextBackoffDelay(n)}}}});var Lte,jte=_(()=>{Lte=(t,e)=>{let r=t,o=e?.noRetryIncrement??1,n=e?.retryCost??5,i=e?.timeoutRetryCost??10,s=t,a=d=>d.name==="TimeoutError"?i:n,c=d=>a(d)<=s;return Object.freeze({hasRetryTokens:c,retrieveRetryTokens:d=>{if(!c(d))throw new Error("No retry token available");let p=a(d);return s-=p,p},releaseRetryTokens:d=>{s+=d??o,s=Math.min(s,r)}})}});var PI,c2=_(()=>{PI=(t,e)=>Math.floor(Math.min(2e4,Math.random()*2**e*t))});var kI,u2=_(()=>{bm();kI=t=>t?Nv(t)||wI(t)||aa(t)||Mu(t):!1});var $m,cUe,l2=_(()=>{ge();xe();bm();Ad();Mv();n2();jte();c2();u2();$m=class{maxAttemptsProvider;retryDecider;delayDecider;retryQuota;mode=Vr.STANDARD;constructor(e,r){this.maxAttemptsProvider=e,this.retryDecider=r?.retryDecider??kI,this.delayDecider=r?.delayDecider??PI,this.retryQuota=r?.retryQuota??Lte(500)}shouldRetry(e,r,o){return r<o&&this.retryDecider(e)&&this.retryQuota.hasRetryTokens(e)}async getMaxAttempts(){let e;try{e=await this.maxAttemptsProvider()}catch{e=Yi}return e}async retry(e,r,o){let n,i=0,s=0,a=await this.getMaxAttempts(),{request:c}=r;for(We.isInstance(c)&&(c.headers[Uu]=um());;)try{We.isInstance(c)&&(c.headers[Lu]=`attempt=${i+1}; max=${a}`),o?.beforeRequest&&await o.beforeRequest();let{response:u,output:l}=await e(r);return o?.afterRequest&&o.afterRequest(u),this.retryQuota.releaseRetryTokens(n),l.$metadata.attempts=i+1,l.$metadata.totalRetryDelay=s,{response:u,output:l}}catch(u){let l=EI(u);if(i++,this.shouldRetry(l,i,a)){n=this.retryQuota.retrieveRetryTokens(l);let d=this.delayDecider(aa(l)?500:100,i),p=cUe(l.$response),f=Math.max(p||0,d);s+=f,await new Promise(h=>setTimeout(h,f));continue}throw l.$metadata||(l.$metadata={}),l.$metadata.attempts=i,l.$metadata.totalRetryDelay=s,l}}},cUe=t=>{if(!Lr.isInstance(t))return;let e=Object.keys(t.headers).find(i=>i.toLowerCase()==="retry-after");if(!e)return;let r=t.headers[e],o=Number(r);if(!Number.isNaN(o))return Math.min(o*1e3,2e4);let n=new Date(r);return Math.min(n.getTime()-Date.now(),2e4)}});var TI,Fte=_(()=>{$I();Ad();l2();TI=class extends $m{rateLimiter;constructor(e,r){let{rateLimiter:o,...n}=r??{};super(e,n),this.rateLimiter=o??new ju,this.mode=Vr.ADAPTIVE}async retry(e,r){return super.retry(e,r,{beforeRequest:async()=>this.rateLimiter.getSendToken(),afterRequest:o=>{this.rateLimiter.updateClientSendingRate(o)}})}}});var CI,OI,ca,ua,d2,p2,la,qte=_(()=>{ve();a2();Lv();Ad();xm();CI="AWS_MAX_ATTEMPTS",OI="max_attempts",ca={environmentVariableSelector:t=>{let e=t[CI];if(!e)return;let r=parseInt(e);if(Number.isNaN(r))throw new Error(`Environment variable ${CI} mast be a number, got "${e}"`);return r},configFileSelector:t=>{let e=t[OI];if(!e)return;let r=parseInt(e);if(Number.isNaN(r))throw new Error(`Shared config file entry ${OI} mast be a number, got "${e}"`);return r},default:Yi},ua=(t,e)=>{let{retryStrategy:r,retryMode:o}=t,{defaultMaxAttempts:n=Yi,defaultBaseDelay:i=wr.delay()}=e??{},s=jt(t.maxAttempts??n),a=r?Promise.resolve(r):void 0,c=async()=>{let u=await s();return await jt(o)()===Vr.ADAPTIVE?new Em(s,{maxAttempts:u,baseDelay:i}):new Qi({maxAttempts:u,baseDelay:i})};return Object.assign(t,{maxAttempts:s,retryStrategy:()=>a??=c()})},d2="AWS_RETRY_MODE",p2="retry_mode",la={environmentVariableSelector:t=>t[d2],configFileSelector:t=>t[p2],default:li}});var f2,m2,Vte,Gte=_(()=>{ge();Mv();f2=()=>t=>async e=>{let{request:r}=e;return We.isInstance(r)&&(delete r.headers[Uu],delete r.headers[Lu]),t(e)},m2={name:"omitRetryHeadersMiddleware",tags:["RETRY","HEADERS","OMIT_RETRY_HEADERS"],relation:"before",toMiddleware:"awsAuthMiddleware",override:!0},Vte=t=>({applyToStack:e=>{e.addRelativeTo(f2(),m2)}})});var h2={};Ht(h2,{AdaptiveRetryStrategy:()=>Em,CONFIG_MAX_ATTEMPTS:()=>OI,CONFIG_RETRY_MODE:()=>p2,ConfiguredRetryStrategy:()=>AI,DEFAULT_MAX_ATTEMPTS:()=>Yi,DEFAULT_RETRY_DELAY_BASE:()=>bI,DEFAULT_RETRY_MODE:()=>li,DefaultRateLimiter:()=>ju,DeprecatedAdaptiveRetryStrategy:()=>TI,DeprecatedStandardRetryStrategy:()=>$m,ENV_MAX_ATTEMPTS:()=>CI,ENV_RETRY_MODE:()=>d2,INITIAL_RETRY_TOKENS:()=>Sm,INVOCATION_ID_HEADER:()=>Uu,MAXIMUM_RETRY_DELAY:()=>zv,NODE_MAX_ATTEMPT_CONFIG_OPTIONS:()=>ca,NODE_RETRY_MODE_CONFIG_OPTIONS:()=>la,NO_RETRY_INCREMENT:()=>xI,REQUEST_HEADER:()=>Lu,RETRY_COST:()=>QF,RETRY_MODES:()=>Vr,Retry:()=>wr,StandardRetryStrategy:()=>Qi,THROTTLING_RETRY_DELAY_BASE:()=>SI,TIMEOUT_RETRY_COST:()=>e2,defaultDelayDecider:()=>PI,defaultRetryDecider:()=>kI,getOmitRetryHeadersPlugin:()=>Vte,getRetryAfterHint:()=>Dte,getRetryPlugin:()=>yc,isBrowserNetworkError:()=>XF,isClockSkewCorrectedError:()=>JF,isClockSkewError:()=>wI,isNodeJsHttp2TransientError:()=>YF,isRetryableByTrait:()=>Nv,isServerError:()=>_I,isThrottlingError:()=>aa,isTransientError:()=>Mu,omitRetryHeadersMiddleware:()=>f2,omitRetryHeadersMiddlewareOptions:()=>m2,resolveRetryConfig:()=>ua,retryMiddleware:()=>uUe,retryMiddlewareOptions:()=>i2});var uUe,yc,jo=_(()=>{NJ();s2();bm();a2();Ute();$I();Lv();Ad();Mv();xm();Fte();l2();c2();u2();qte();Gte();s2();r2();uUe=o2(Sj),yc=Nte(Sj)});function di(t,e,r){t.__aws_sdk_context?t.__aws_sdk_context.features||(t.__aws_sdk_context.features={}):t.__aws_sdk_context={features:{}},t.__aws_sdk_context.features[e]=r}var g2=_(()=>{jo();wr.v2026||=typeof process=="object"&&process.env?.AWS_NEW_RETRIES_2026==="true"});function Hte(t,e,r){return t.$source||(t.$source={}),t.$source[e]=r,t}var Kte=_(()=>{});function Rm(t){return t}var y2,v2,da,Bte=_(()=>{ge();y2=t=>e=>async r=>{if(!We.isInstance(r.request))return e(r);let{request:o}=r,{handlerProtocol:n=""}=t.requestHandler.metadata||{};if(n.indexOf("h2")>=0&&!o.headers[":authority"])delete o.headers.host,o.headers[":authority"]=o.hostname+(o.port?":"+o.port:"");else if(!o.headers.host){let i=o.hostname;o.port!=null&&(i+=`:${o.port}`),o.headers.host=i}return e(r)},v2={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},da=t=>({applyToStack:e=>{e.add(y2(t),v2)}})});var w2,_2,pa,Zte=_(()=>{w2=()=>(t,e)=>async r=>{try{let o=await t(r),{clientName:n,commandName:i,logger:s,dynamoDbDocumentClientOptions:a={}}=e,{overrideInputFilterSensitiveLog:c,overrideOutputFilterSensitiveLog:u}=a,l=c??e.inputFilterSensitiveLog,d=u??e.outputFilterSensitiveLog,{$metadata:p,...f}=o.output;return s?.info?.({clientName:n,commandName:i,input:l(r.input),output:d(f),metadata:p}),o}catch(o){let{clientName:n,commandName:i,logger:s,dynamoDbDocumentClientOptions:a={}}=e,{overrideInputFilterSensitiveLog:c}=a,u=c??e.inputFilterSensitiveLog;throw s?.error?.({clientName:n,commandName:i,input:u(r.input),error:o,metadata:o.$metadata}),o}},_2={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},pa=t=>({applyToStack:e=>{e.add(w2(),_2)}})});var DI,b2=_(()=>{DI={step:"build",tags:["RECURSION_DETECTION","TRACE_CONTEXT_PROPAGATION"],name:"recursionDetectionMiddleware",override:!0,priority:"low"}});var Fu,S2,NI,x2,E2,jv,Wte=_(()=>{Fu={REQUEST_ID:Symbol.for("_AWS_LAMBDA_REQUEST_ID"),X_RAY_TRACE_ID:Symbol.for("_AWS_LAMBDA_X_RAY_TRACE_ID"),TENANT_ID:Symbol.for("_AWS_LAMBDA_TENANT_ID"),TRACEPARENT:Symbol.for("_AWS_LAMBDA_TRACEPARENT"),TRACESTATE:Symbol.for("_AWS_LAMBDA_TRACESTATE"),BAGGAGE:Symbol.for("_AWS_LAMBDA_BAGGAGE")},S2=["true","1"].includes(process.env?.AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA??"");S2||(globalThis.awslambda=globalThis.awslambda||{});NI=class{static PROTECTED_KEYS=Fu;isProtectedKey(e){return Object.values(Fu).includes(e)}getRequestId(){return this.get(Fu.REQUEST_ID)??"-"}getXRayTraceId(){return this.get(Fu.X_RAY_TRACE_ID)}getTenantId(){return this.get(Fu.TENANT_ID)}getTraceparent(){return this.get(Fu.TRACEPARENT)}getTracestate(){return this.get(Fu.TRACESTATE)}getBaggage(){return this.get(Fu.BAGGAGE)}},x2=class extends NI{currentContext;getContext(){return this.currentContext}hasContext(){return this.currentContext!==void 0}get(e){return this.currentContext?.[e]}set(e,r){if(this.isProtectedKey(e))throw new Error(`Cannot modify protected Lambda context field: ${String(e)}`);this.currentContext=this.currentContext||{},this.currentContext[e]=r}run(e,r){return this.currentContext=e,r()}},E2=class t extends NI{als;static async create(){let e=new t,r=await import("node:async_hooks");return e.als=new r.AsyncLocalStorage,e}getContext(){return this.als.getStore()}hasContext(){return this.als.getStore()!==void 0}get(e){return this.als.getStore()?.[e]}set(e,r){if(this.isProtectedKey(e))throw new Error(`Cannot modify protected Lambda context field: ${String(e)}`);let o=this.als.getStore();if(!o)throw new Error("No context available");o[e]=r}run(e,r){return this.als.run(e,r)}};(function(t){let e=null;async function r(o){return e||(e=(async()=>{let i=o===!0||"AWS_LAMBDA_MAX_CONCURRENCY"in process.env?await E2.create():new x2;return!S2&&globalThis.awslambda?.InvokeStore?globalThis.awslambda.InvokeStore:(!S2&&globalThis.awslambda&&(globalThis.awslambda.InvokeStore=i),i)})()),e}t.getInstanceAsync=r,t._testing=process.env.AWS_LAMBDA_BENCHMARK_MODE==="1"?{reset:()=>{e=null,globalThis.awslambda?.InvokeStore&&delete globalThis.awslambda.InvokeStore,globalThis.awslambda={InvokeStore:void 0}}}:void 0})(jv||(jv={}))});function pUe(t){for(let e of Object.keys(t)){let r=e.toLowerCase();e!==r&&(r===R2||r===Jte||r===Xte)&&(t[r]=t[e],delete t[e])}}var lUe,dUe,$2,R2,Jte,Xte,zI,I2=_(()=>{Wte();ge();lUe="AWS_LAMBDA_FUNCTION_NAME",dUe="_X_AMZN_TRACE_ID",$2="X-Amzn-Trace-Id",R2="traceparent",Jte="tracestate",Xte="baggage",zI=()=>t=>async e=>{let{request:r}=e;if(!We.isInstance(r))return t(e);let o;{let n=Object.keys(r.headers??{}).find(i=>i.toLowerCase()===$2.toLowerCase())??$2;if(!r.headers.hasOwnProperty(n)){let i=process.env[lUe],s=process.env[dUe];o??=await jv.getInstanceAsync();let c=o?.getXRayTraceId()??s,u=l=>typeof l=="string"&&l.length>0;u(i)&&u(c)&&(r.headers[$2]=c)}}if(pUe(r.headers),!r.headers[R2]){let i=(o??=await jv.getInstanceAsync())?.getTraceparent?.();if(i){r.headers[R2]=i;let s=o?.getTracestate?.();s&&(r.headers[Jte]=s);let a=o?.getBaggage?.();a&&(r.headers[Xte]=a)}}return t(e)}});var fa,Yte=_(()=>{b2();I2();fa=t=>({applyToStack:e=>{e.add(zI(),DI)}})});var Qte,ere=_(()=>{Qte=(t,e)=>{if(!e||e.length===0)return t;let r=[];for(let o of e)for(let n of t)n.schemeId.split("#")[1]===o&&r.push(n);for(let o of t)r.find(({schemeId:n})=>n===o.schemeId)||r.push(o);return r}});function fUe(t){let e=new Map;for(let r of t)e.set(r.schemeId,r);return e}var Pd,MI=_(()=>{Pe();ere();Pd=(t,e)=>(r,o)=>async n=>{let i=t.httpAuthSchemeProvider(await e.httpAuthSchemeParametersProvider(t,o,n.input)),s=t.authSchemePreference?await t.authSchemePreference():[],a=Qte(i,s),c=fUe(t.httpAuthSchemes),u=Bt(o),l=[];for(let d of a){let p=c.get(d.schemeId);if(!p){l.push(`HttpAuthScheme \`${d.schemeId}\` was not enabled for this service.`);continue}let f=p.identityProvider(await e.identityProviderConfigProvider(t));if(!f){l.push(`HttpAuthScheme \`${d.schemeId}\` did not have an IdentityProvider configured.`);continue}let{identityProperties:h={},signingProperties:y={}}=d.propertiesExtractor?.(t,o)||{};d.identityProperties=Object.assign(d.identityProperties||{},h),d.signingProperties=Object.assign(d.signingProperties||{},y),u.selectedHttpAuthScheme={httpAuthOption:d,identity:await f(d.identityProperties),signer:p.signer};break}if(!u.selectedHttpAuthScheme)throw new Error(l.join(`
26
26
  `));return r(n)}});var UI,es,tre=_(()=>{MI();UI={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},es=(t,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:r})=>({applyToStack:o=>{o.addRelativeTo(Pd(t,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:r}),UI)}})});var LI,A2,rre=_(()=>{MI();LI={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"serializerMiddleware"},A2=(t,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:r})=>({applyToStack:o=>{o.addRelativeTo(Pd(t,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:r}),LI)}})});var nre=_(()=>{MI();tre();rre()});var mUe,hUe,Fv,P2=_(()=>{ge();Pe();mUe=t=>e=>{throw e},hUe=(t,e)=>{},Fv=t=>(e,r)=>async o=>{if(!We.isInstance(o.request))return e(o);let i=Bt(r).selectedHttpAuthScheme;if(!i)throw new Error("No HttpAuthScheme was selected: unable to sign request");let{httpAuthOption:{signingProperties:s={}},identity:a,signer:c}=i,u=await e({...o,request:await c.sign(o.request,a,s)}).catch((c.errorHandler||mUe)(s));return(c.successHandler||hUe)(u.response,s),u}});var jI,ts,ore=_(()=>{P2();jI={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},ts=t=>({applyToStack:e=>{e.addRelativeTo(Fv(t),jI)}})});var ire=_(()=>{P2();ore()});var pi,sre=_(()=>{pi=t=>{if(typeof t=="function")return t;let e=Promise.resolve(t);return()=>e}});function are(t,e,r,o,n){return async function*(s,a,...c){let u=a,l=s.startingToken??u[r],d=!0,p;for(;d;){if(u[r]=l,n&&(u[n]=u[n]??s.pageSize),s.client instanceof t)p=await gUe(e,s.client,a,s.withCommand,...c);else throw new Error(`Invalid client, expected instance of ${t.name}`);yield p;let f=l;l=yUe(p,o),d=!!(l&&(!s.stopOnSameToken||l!==f))}return void 0}}var gUe,yUe,cre=_(()=>{gUe=async(t,e,r,o=i=>i,...n)=>{let i=new t(r);return i=o(i)??i,await e.send(i,...n)};yUe=(t,e)=>{let r=t,o=e.split(".");for(let n of o){if(!r||typeof r!="object")return;r=r[n]}return r}});function ure(t,e,r){t.__smithy_context?t.__smithy_context.features||(t.__smithy_context.features={}):t.__smithy_context={features:{}},t.__smithy_context.features[e]=r}var lre=_(()=>{});var Fo,dre=_(()=>{Pe();Fo=class{authSchemes=new Map;constructor(e){for(let r in e){if(!Se(e,r))continue;let o=e[r];o!==void 0&&this.authSchemes.set(r,o)}}getIdentityProvider(e){return this.authSchemes.get(e)}}});var k2,Im,pre=_(()=>{ge();k2=Vt(js()),Im=class{async sign(e,r,o){if(!o)throw new Error("request could not be signed with `apiKey` since the `name` and `in` signer properties are missing");if(!o.name)throw new Error("request could not be signed with `apiKey` since the `name` signer property is missing");if(!o.in)throw new Error("request could not be signed with `apiKey` since the `in` signer property is missing");if(!r.apiKey)throw new Error("request could not be signed with `apiKey` since the `apiKey` is not defined");let n=We.clone(e);if(o.in===k2.HttpApiKeyAuthLocation.QUERY)n.query[o.name]=r.apiKey;else if(o.in===k2.HttpApiKeyAuthLocation.HEADER)n.headers[o.name]=o.scheme?`${o.scheme} ${r.apiKey}`:r.apiKey;else throw new Error("request can only be signed with `apiKey` locations `query` or `header`, but found: `"+o.in+"`");return n}}});var Am,fre=_(()=>{ge();Am=class{async sign(e,r,o){let n=We.clone(e);if(!r.token)throw new Error("request could not be signed with `token` since the `token` is not defined");return n.headers.Authorization=`Bearer ${r.token}`,n}}});var An,mre=_(()=>{An=class{async sign(e,r,o){return e}}});var hre=_(()=>{pre();fre();mre()});var FI,T2,qv,Pm,Vv,gre=_(()=>{FI=t=>function(r){return Pm(r)&&r.expiration.getTime()-Date.now()<t},T2=3e5,qv=FI(3e5),Pm=t=>t.expiration!==void 0,Vv=(t,e,r)=>{if(t===void 0)return;let o=typeof t!="function"?async()=>Promise.resolve(t):t,n,i,s,a=!1,c=async u=>{i||(i=o(u));try{n=await i,s=!0,a=!1}finally{i=void 0}return n};return e===void 0?async u=>((!s||u?.forceRefresh)&&(n=await c(u)),n):async u=>((!s||u?.forceRefresh)&&(n=await c(u)),a?n:r(n)?(e(n)&&await c(u),n):(a=!0,n))}});var yre=_(()=>{dre();hre();gre()});var C2={};Ht(C2,{DefaultIdentityProviderConfig:()=>Fo,EXPIRATION_MS:()=>T2,HttpApiKeyAuthSigner:()=>Im,HttpBearerAuthSigner:()=>Am,NoAuthSigner:()=>An,createIsIdentityExpiredFunction:()=>FI,createPaginator:()=>are,doesIdentityRequireRefresh:()=>Pm,getHttpAuthSchemeEndpointRuleSetPlugin:()=>es,getHttpAuthSchemePlugin:()=>A2,getHttpSigningPlugin:()=>ts,getSmithyContext:()=>Bt,httpAuthSchemeEndpointRuleSetMiddlewareOptions:()=>UI,httpAuthSchemeMiddleware:()=>Pd,httpAuthSchemeMiddlewareOptions:()=>LI,httpSigningMiddleware:()=>Fv,httpSigningMiddlewareOptions:()=>jI,isIdentityExpired:()=>qv,memoizeIdentityProvider:()=>Vv,normalizeProvider:()=>pi,requestBuilder:()=>mI,setFeature:()=>ure});var Yn=_(()=>{Pe();nre();ire();sre();cre();ge();lre();yre()});function vUe(t){return t===void 0?!0:typeof t=="string"&&t.length<=50}function ma(t){let e=pi(t.userAgentAppId??Gv),{customUserAgent:r}=t;return Object.assign(t,{customUserAgent:typeof r=="string"?[[r]]:r,userAgentAppId:async()=>{let o=await e();if(!vUe(o)){let n=t.logger?.constructor?.name==="NoOpLogger"||!t.logger?console:t.logger;typeof o!="string"?n?.warn("userAgentAppId must be a string or undefined."):o.length>50&&n?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.")}return o}})}var Gv,O2=_(()=>{Yn();Gv=void 0});var D2,vre=_(()=>{D2={partitions:[{id:"aws",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-east-1",name:"aws",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$",regions:{"af-south-1":{description:"Africa (Cape Town)"},"ap-east-1":{description:"Asia Pacific (Hong Kong)"},"ap-east-2":{description:"Asia Pacific (Taipei)"},"ap-northeast-1":{description:"Asia Pacific (Tokyo)"},"ap-northeast-2":{description:"Asia Pacific (Seoul)"},"ap-northeast-3":{description:"Asia Pacific (Osaka)"},"ap-south-1":{description:"Asia Pacific (Mumbai)"},"ap-south-2":{description:"Asia Pacific (Hyderabad)"},"ap-southeast-1":{description:"Asia Pacific (Singapore)"},"ap-southeast-2":{description:"Asia Pacific (Sydney)"},"ap-southeast-3":{description:"Asia Pacific (Jakarta)"},"ap-southeast-4":{description:"Asia Pacific (Melbourne)"},"ap-southeast-5":{description:"Asia Pacific (Malaysia)"},"ap-southeast-6":{description:"Asia Pacific (New Zealand)"},"ap-southeast-7":{description:"Asia Pacific (Thailand)"},"aws-global":{description:"aws global region"},"ca-central-1":{description:"Canada (Central)"},"ca-west-1":{description:"Canada West (Calgary)"},"eu-central-1":{description:"Europe (Frankfurt)"},"eu-central-2":{description:"Europe (Zurich)"},"eu-north-1":{description:"Europe (Stockholm)"},"eu-south-1":{description:"Europe (Milan)"},"eu-south-2":{description:"Europe (Spain)"},"eu-west-1":{description:"Europe (Ireland)"},"eu-west-2":{description:"Europe (London)"},"eu-west-3":{description:"Europe (Paris)"},"il-central-1":{description:"Israel (Tel Aviv)"},"me-central-1":{description:"Middle East (UAE)"},"me-south-1":{description:"Middle East (Bahrain)"},"mx-central-1":{description:"Mexico (Central)"},"sa-east-1":{description:"South America (Sao Paulo)"},"us-east-1":{description:"US East (N. Virginia)"},"us-east-2":{description:"US East (Ohio)"},"us-west-1":{description:"US West (N. California)"},"us-west-2":{description:"US West (Oregon)"}}},{id:"aws-cn",outputs:{dnsSuffix:"amazonaws.com.cn",dualStackDnsSuffix:"api.amazonwebservices.com.cn",implicitGlobalRegion:"cn-northwest-1",name:"aws-cn",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^cn\\-\\w+\\-\\d+$",regions:{"aws-cn-global":{description:"aws-cn global region"},"cn-north-1":{description:"China (Beijing)"},"cn-northwest-1":{description:"China (Ningxia)"}}},{id:"aws-eusc",outputs:{dnsSuffix:"amazonaws.eu",dualStackDnsSuffix:"api.amazonwebservices.eu",implicitGlobalRegion:"eusc-de-east-1",name:"aws-eusc",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eusc\\-(de)\\-\\w+\\-\\d+$",regions:{"eusc-de-east-1":{description:"AWS European Sovereign Cloud (Germany)"}}},{id:"aws-iso",outputs:{dnsSuffix:"c2s.ic.gov",dualStackDnsSuffix:"api.aws.ic.gov",implicitGlobalRegion:"us-iso-east-1",name:"aws-iso",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-iso\\-\\w+\\-\\d+$",regions:{"aws-iso-global":{description:"aws-iso global region"},"us-iso-east-1":{description:"US ISO East"},"us-iso-west-1":{description:"US ISO WEST"}}},{id:"aws-iso-b",outputs:{dnsSuffix:"sc2s.sgov.gov",dualStackDnsSuffix:"api.aws.scloud",implicitGlobalRegion:"us-isob-east-1",name:"aws-iso-b",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isob\\-\\w+\\-\\d+$",regions:{"aws-iso-b-global":{description:"aws-iso-b global region"},"us-isob-east-1":{description:"US ISOB East (Ohio)"},"us-isob-west-1":{description:"US ISOB West"}}},{id:"aws-iso-e",outputs:{dnsSuffix:"cloud.adc-e.uk",dualStackDnsSuffix:"api.cloud-aws.adc-e.uk",implicitGlobalRegion:"eu-isoe-west-1",name:"aws-iso-e",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eu\\-isoe\\-\\w+\\-\\d+$",regions:{"aws-iso-e-global":{description:"aws-iso-e global region"},"eu-isoe-west-1":{description:"EU ISOE West"}}},{id:"aws-iso-f",outputs:{dnsSuffix:"csp.hci.ic.gov",dualStackDnsSuffix:"api.aws.hci.ic.gov",implicitGlobalRegion:"us-isof-south-1",name:"aws-iso-f",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isof\\-\\w+\\-\\d+$",regions:{"aws-iso-f-global":{description:"aws-iso-f global region"},"us-isof-east-1":{description:"US ISOF EAST"},"us-isof-south-1":{description:"US ISOF SOUTH"}}},{id:"aws-us-gov",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-gov-west-1",name:"aws-us-gov",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-gov\\-\\w+\\-\\d+$",regions:{"aws-us-gov-global":{description:"aws-us-gov global region"},"us-gov-east-1":{description:"AWS GovCloud (US-East)"},"us-gov-west-1":{description:"AWS GovCloud (US-West)"}}}],version:"1.1"}});var wre,_re,qI,N2,bre,VI,GI=_(()=>{vre();wre=D2,_re="",qI=t=>{let{partitions:e}=wre;for(let o of e){let{regions:n,outputs:i}=o;for(let[s,a]of Object.entries(n))if(s===t)return{...i,...a}}for(let o of e){let{regionRegex:n,outputs:i}=o;if(new RegExp(n).test(t))return{...i}}let r=e.find(o=>o.id==="aws");if(!r)throw new Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");return{...r.outputs}},N2=(t,e="")=>{wre=t,_re=e},bre=()=>{N2(D2,"")},VI=()=>_re});async function Sre(t,e,r){if(r.request?.headers?.["smithy-protocol"]==="rpc-v2-cbor"&&di(t,"PROTOCOL_RPC_V2_CBOR","M"),typeof e.retryStrategy=="function"){let i=await e.retryStrategy();if(typeof i.mode=="string")switch(i.mode){case Vr.ADAPTIVE:di(t,"RETRY_MODE_ADAPTIVE","F");break;case Vr.STANDARD:di(t,"RETRY_MODE_STANDARD","E");break}}if(typeof e.accountIdEndpointMode=="function"){let i=t.endpointV2;switch(String(i?.url?.hostname).match(wUe)&&di(t,"ACCOUNT_ID_ENDPOINT","O"),await e.accountIdEndpointMode?.()){case"disabled":di(t,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":di(t,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":di(t,"ACCOUNT_ID_MODE_REQUIRED","R");break}}let n=t.__smithy_context?.selectedHttpAuthScheme?.identity;if(n?.$source){let i=n;i.accountId&&di(t,"RESOLVED_ACCOUNT_ID","T");for(let[s,a]of Object.entries(i.$source??{}))di(t,s,a)}}var wUe,xre=_(()=>{jo();g2();wUe=/\d{12}\.ddb/});var z2,HI,Ere,$re,Rre=_(()=>{z2="user-agent",HI="x-amz-user-agent",Ere=/[^!$%&'*+\-.^_`|~\w]/g,$re=/[^!$%&'*+\-.^_`|~\w#]/g});function Ire(t){let e="";for(let r in t){let o=t[r];if(e.length+o.length+1<=1024){e.length?e+=","+o:e+=o;continue}break}return e}var Are=_(()=>{});var U2,KI,L2,ha,Tre=_(()=>{ge();GI();xre();Rre();Are();U2=t=>(e,r)=>async o=>{let{request:n}=o;if(!We.isInstance(n))return e(o);let{headers:i}=n,s=r?.userAgent?.map(KI)||[],a=(await t.defaultUserAgentProvider()).map(KI);await Sre(r,t,o);let c=r;a.push(`m/${Ire(Object.assign({},r.__smithy_context?.features,c.__aws_sdk_context?.features))}`);let u=t?.customUserAgent?.map(KI)||[],l=await t.userAgentAppId();l&&a.push(KI(["app",`${l}`]));let d=VI(),p=(d?[d]:[]).concat([...a,...s,...u]).join(" "),f=[...a.filter(h=>h.startsWith("aws-sdk-")),...u].join(" ");return t.runtime!=="browser"?(f&&(i[HI]=i[HI]?`${i[z2]} ${f}`:f),i[z2]=p):i[HI]=p,e({...o,request:n})},KI=t=>{let e=t[0].split("/").map(s=>s.replace(Ere,"-")).join("/"),r=t[1]?.replace($re,"-"),o=e.indexOf("/"),n=e.substring(0,o),i=e.substring(o+1);return n==="api"&&(i=i.toLowerCase()),[n,i,r].filter(s=>s&&s.length>0).reduce((s,a,c)=>{switch(c){case 0:return a;case 1:return`${s}/${a}`;default:return`${s}#${a}`}},"")},L2={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},ha=t=>({applyToStack:e=>{e.add(U2(t),L2)}})});import{versions as j2}from"node:process";var Cre,Ore=_(()=>{Cre=()=>{let t=["deno","bun","llrt"];for(let e of t)if(j2[e])return[`md/${e}`,j2[e]];return["md/nodejs",j2.node]}});var Hv,F2=_(()=>{Hv={isCrtAvailable:!1}});var Dre,Nre=_(()=>{F2();Dre=()=>Hv.isCrtAvailable?["md/crt-avail"]:null});import{platform as _Ue,release as bUe}from"node:os";import{env as zre}from"node:process";var rs,Mre,Ure=_(()=>{Ore();Nre();F2();rs=({serviceId:t,clientVersion:e})=>{let r=Cre();return async o=>{let n=[["aws-sdk-js",e],["ua","2.1"],[`os/${_Ue()}`,bUe()],["lang/js"],r],i=Dre();i&&n.push(i),t&&n.push([`api/${t}`,e]),zre.AWS_EXECUTION_ENV&&n.push([`exec-env/${zre.AWS_EXECUTION_ENV}`]);let s=await o?.userAgentAppId?.();return s?[...n,[`app/${s}`]]:[...n]}},Mre=rs});var q2,V2,SUe,ga,Lre=_(()=>{O2();q2="AWS_SDK_UA_APP_ID",V2="sdk_ua_app_id",SUe="sdk-ua-app-id",ga={environmentVariableSelector:t=>t[q2],configFileSelector:t=>t[V2]??t[SUe],default:Gv}});var jre=U((Kv,G2)=>{(function(t,e){typeof Kv=="object"&&typeof G2=="object"?G2.exports=e():typeof define=="function"&&define.amd?define([],e):typeof Kv=="object"?Kv.bowser=e():t.bowser=e()})(Kv,(function(){return(function(t){var e={};function r(o){if(e[o])return e[o].exports;var n=e[o]={i:o,l:!1,exports:{}};return t[o].call(n.exports,n,n.exports,r),n.l=!0,n.exports}return r.m=t,r.c=e,r.d=function(o,n,i){r.o(o,n)||Object.defineProperty(o,n,{enumerable:!0,get:i})},r.r=function(o){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(o,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(o,"__esModule",{value:!0})},r.t=function(o,n){if(1&n&&(o=r(o)),8&n||4&n&&typeof o=="object"&&o&&o.__esModule)return o;var i=Object.create(null);if(r.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:o}),2&n&&typeof o!="string")for(var s in o)r.d(i,s,function(a){return o[a]}.bind(null,s));return i},r.n=function(o){var n=o&&o.__esModule?function(){return o.default}:function(){return o};return r.d(n,"a",n),n},r.o=function(o,n){return Object.prototype.hasOwnProperty.call(o,n)},r.p="",r(r.s=90)})({17:function(t,e,r){"use strict";e.__esModule=!0,e.default=void 0;var o=r(18),n=(function(){function i(){}return i.getFirstMatch=function(s,a){var c=a.match(s);return c&&c.length>0&&c[1]||""},i.getSecondMatch=function(s,a){var c=a.match(s);return c&&c.length>1&&c[2]||""},i.matchAndReturnConst=function(s,a,c){if(s.test(a))return c},i.getWindowsVersionName=function(s){switch(s){case"NT":return"NT";case"XP":return"XP";case"NT 5.0":return"2000";case"NT 5.1":return"XP";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}},i.getMacOSVersionName=function(s){var a=s.split(".").splice(0,2).map((function(l){return parseInt(l,10)||0}));a.push(0);var c=a[0],u=a[1];if(c===10)switch(u){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}switch(c){case 11:return"Big Sur";case 12:return"Monterey";case 13:return"Ventura";case 14:return"Sonoma";case 15:return"Sequoia";default:return}},i.getAndroidVersionName=function(s){var a=s.split(".").splice(0,2).map((function(c){return parseInt(c,10)||0}));if(a.push(0),!(a[0]===1&&a[1]<5))return a[0]===1&&a[1]<6?"Cupcake":a[0]===1&&a[1]>=6?"Donut":a[0]===2&&a[1]<2?"Eclair":a[0]===2&&a[1]===2?"Froyo":a[0]===2&&a[1]>2?"Gingerbread":a[0]===3?"Honeycomb":a[0]===4&&a[1]<1?"Ice Cream Sandwich":a[0]===4&&a[1]<4?"Jelly Bean":a[0]===4&&a[1]>=4?"KitKat":a[0]===5?"Lollipop":a[0]===6?"Marshmallow":a[0]===7?"Nougat":a[0]===8?"Oreo":a[0]===9?"Pie":void 0},i.getVersionPrecision=function(s){return s.split(".").length},i.compareVersions=function(s,a,c){c===void 0&&(c=!1);var u=i.getVersionPrecision(s),l=i.getVersionPrecision(a),d=Math.max(u,l),p=0,f=i.map([s,a],(function(h){var y=d-i.getVersionPrecision(h),w=h+new Array(y+1).join(".0");return i.map(w.split("."),(function(b){return new Array(20-b.length).join("0")+b})).reverse()}));for(c&&(p=d-Math.min(u,l)),d-=1;d>=p;){if(f[0][d]>f[1][d])return 1;if(f[0][d]===f[1][d]){if(d===p)return 0;d-=1}else if(f[0][d]<f[1][d])return-1}},i.map=function(s,a){var c,u=[];if(Array.prototype.map)return Array.prototype.map.call(s,a);for(c=0;c<s.length;c+=1)u.push(a(s[c]));return u},i.find=function(s,a){var c,u;if(Array.prototype.find)return Array.prototype.find.call(s,a);for(c=0,u=s.length;c<u;c+=1){var l=s[c];if(a(l,c))return l}},i.assign=function(s){for(var a,c,u=s,l=arguments.length,d=new Array(l>1?l-1:0),p=1;p<l;p++)d[p-1]=arguments[p];if(Object.assign)return Object.assign.apply(Object,[s].concat(d));var f=function(){var h=d[a];typeof h=="object"&&h!==null&&Object.keys(h).forEach((function(y){u[y]=h[y]}))};for(a=0,c=d.length;a<c;a+=1)f();return s},i.getBrowserAlias=function(s){return o.BROWSER_ALIASES_MAP[s]},i.getBrowserTypeByAlias=function(s){return o.BROWSER_MAP[s]||""},i})();e.default=n,t.exports=e.default},18:function(t,e,r){"use strict";e.__esModule=!0,e.ENGINE_MAP=e.OS_MAP=e.PLATFORMS_MAP=e.BROWSER_MAP=e.BROWSER_ALIASES_MAP=void 0,e.BROWSER_ALIASES_MAP={AmazonBot:"amazonbot","Amazon Silk":"amazon_silk","Android Browser":"android",BaiduSpider:"baiduspider",Bada:"bada",BingCrawler:"bingcrawler",Brave:"brave",BlackBerry:"blackberry","ChatGPT-User":"chatgpt_user",Chrome:"chrome",ClaudeBot:"claudebot",Chromium:"chromium",Diffbot:"diffbot",DuckDuckBot:"duckduckbot",DuckDuckGo:"duckduckgo",Electron:"electron",Epiphany:"epiphany",FacebookExternalHit:"facebookexternalhit",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot",GPTBot:"gptbot","Internet Explorer":"ie",InternetArchiveCrawler:"internetarchivecrawler","K-Meleon":"k_meleon",LibreWolf:"librewolf",Linespider:"linespider",Maxthon:"maxthon","Meta-ExternalAds":"meta_externalads","Meta-ExternalAgent":"meta_externalagent","Meta-ExternalFetcher":"meta_externalfetcher","Meta-WebIndexer":"meta_webindexer","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver","OAI-SearchBot":"oai_searchbot",Omgilibot:"omgilibot",Opera:"opera","Opera Coast":"opera_coast","Pale Moon":"pale_moon",PerplexityBot:"perplexitybot","Perplexity-User":"perplexity_user",PhantomJS:"phantomjs",PingdomBot:"pingdombot",Puffin:"puffin",QQ:"qq",QQLite:"qqlite",QupZilla:"qupzilla",Roku:"roku",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SlackBot:"slackbot",SeaMonkey:"seamonkey",Sleipnir:"sleipnir","Sogou Browser":"sogou",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat",YahooSlurp:"yahooslurp","Yandex Browser":"yandex",YandexBot:"yandexbot",YouBot:"youbot"},e.BROWSER_MAP={amazonbot:"AmazonBot",amazon_silk:"Amazon Silk",android:"Android Browser",baiduspider:"BaiduSpider",bada:"Bada",bingcrawler:"BingCrawler",blackberry:"BlackBerry",brave:"Brave",chatgpt_user:"ChatGPT-User",chrome:"Chrome",claudebot:"ClaudeBot",chromium:"Chromium",diffbot:"Diffbot",duckduckbot:"DuckDuckBot",duckduckgo:"DuckDuckGo",edge:"Microsoft Edge",electron:"Electron",epiphany:"Epiphany",facebookexternalhit:"FacebookExternalHit",firefox:"Firefox",focus:"Focus",generic:"Generic",google_search:"Google Search",googlebot:"Googlebot",gptbot:"GPTBot",ie:"Internet Explorer",internetarchivecrawler:"InternetArchiveCrawler",k_meleon:"K-Meleon",librewolf:"LibreWolf",linespider:"Linespider",maxthon:"Maxthon",meta_externalads:"Meta-ExternalAds",meta_externalagent:"Meta-ExternalAgent",meta_externalfetcher:"Meta-ExternalFetcher",meta_webindexer:"Meta-WebIndexer",mz:"MZ Browser",naver:"NAVER Whale Browser",oai_searchbot:"OAI-SearchBot",omgilibot:"Omgilibot",opera:"Opera",opera_coast:"Opera Coast",pale_moon:"Pale Moon",perplexitybot:"PerplexityBot",perplexity_user:"Perplexity-User",phantomjs:"PhantomJS",pingdombot:"PingdomBot",puffin:"Puffin",qq:"QQ Browser",qqlite:"QQ Browser Lite",qupzilla:"QupZilla",roku:"Roku",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",slackbot:"SlackBot",sleipnir:"Sleipnir",sogou:"Sogou Browser",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yahooslurp:"YahooSlurp",yandex:"Yandex Browser",yandexbot:"YandexBot",youbot:"YouBot"},e.PLATFORMS_MAP={bot:"bot",desktop:"desktop",mobile:"mobile",tablet:"tablet",tv:"tv"},e.OS_MAP={Android:"Android",Bada:"Bada",BlackBerry:"BlackBerry",ChromeOS:"Chrome OS",HarmonyOS:"HarmonyOS",iOS:"iOS",Linux:"Linux",MacOS:"macOS",PlayStation4:"PlayStation 4",Roku:"Roku",Tizen:"Tizen",WebOS:"WebOS",Windows:"Windows",WindowsPhone:"Windows Phone"},e.ENGINE_MAP={Blink:"Blink",EdgeHTML:"EdgeHTML",Gecko:"Gecko",Presto:"Presto",Trident:"Trident",WebKit:"WebKit"}},90:function(t,e,r){"use strict";e.__esModule=!0,e.default=void 0;var o,n=(o=r(91))&&o.__esModule?o:{default:o},i=r(18);function s(c,u){for(var l=0;l<u.length;l++){var d=u[l];d.enumerable=d.enumerable||!1,d.configurable=!0,"value"in d&&(d.writable=!0),Object.defineProperty(c,d.key,d)}}var a=(function(){function c(){}var u,l,d;return c.getParser=function(p,f,h){if(f===void 0&&(f=!1),h===void 0&&(h=null),typeof p!="string")throw new Error("UserAgent should be a string");return new n.default(p,f,h)},c.parse=function(p,f){return f===void 0&&(f=null),new n.default(p,f).getResult()},u=c,d=[{key:"BROWSER_MAP",get:function(){return i.BROWSER_MAP}},{key:"ENGINE_MAP",get:function(){return i.ENGINE_MAP}},{key:"OS_MAP",get:function(){return i.OS_MAP}},{key:"PLATFORMS_MAP",get:function(){return i.PLATFORMS_MAP}}],(l=null)&&s(u.prototype,l),d&&s(u,d),c})();e.default=a,t.exports=e.default},91:function(t,e,r){"use strict";e.__esModule=!0,e.default=void 0;var o=c(r(92)),n=c(r(93)),i=c(r(94)),s=c(r(95)),a=c(r(17));function c(l){return l&&l.__esModule?l:{default:l}}var u=(function(){function l(p,f,h){if(f===void 0&&(f=!1),h===void 0&&(h=null),p==null||p==="")throw new Error("UserAgent parameter can't be empty");this._ua=p;var y=!1;typeof f=="boolean"?(y=f,this._hints=h):this._hints=f!=null&&typeof f=="object"?f:null,this.parsedResult={},y!==!0&&this.parse()}var d=l.prototype;return d.getHints=function(){return this._hints},d.hasBrand=function(p){if(!this._hints||!Array.isArray(this._hints.brands))return!1;var f=p.toLowerCase();return this._hints.brands.some((function(h){return h.brand&&h.brand.toLowerCase()===f}))},d.getBrandVersion=function(p){if(this._hints&&Array.isArray(this._hints.brands)){var f=p.toLowerCase(),h=this._hints.brands.find((function(y){return y.brand&&y.brand.toLowerCase()===f}));return h?h.version:void 0}},d.getUA=function(){return this._ua},d.test=function(p){return p.test(this._ua)},d.parseBrowser=function(){var p=this;this.parsedResult.browser={};var f=a.default.find(o.default,(function(h){if(typeof h.test=="function")return h.test(p);if(Array.isArray(h.test))return h.test.some((function(y){return p.test(y)}));throw new Error("Browser's test function is not valid")}));return f&&(this.parsedResult.browser=f.describe(this.getUA(),this)),this.parsedResult.browser},d.getBrowser=function(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()},d.getBrowserName=function(p){return p?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""},d.getBrowserVersion=function(){return this.getBrowser().version},d.getOS=function(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()},d.parseOS=function(){var p=this;this.parsedResult.os={};var f=a.default.find(n.default,(function(h){if(typeof h.test=="function")return h.test(p);if(Array.isArray(h.test))return h.test.some((function(y){return p.test(y)}));throw new Error("Browser's test function is not valid")}));return f&&(this.parsedResult.os=f.describe(this.getUA())),this.parsedResult.os},d.getOSName=function(p){var f=this.getOS().name;return p?String(f).toLowerCase()||"":f||""},d.getOSVersion=function(){return this.getOS().version},d.getPlatform=function(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()},d.getPlatformType=function(p){p===void 0&&(p=!1);var f=this.getPlatform().type;return p?String(f).toLowerCase()||"":f||""},d.parsePlatform=function(){var p=this;this.parsedResult.platform={};var f=a.default.find(i.default,(function(h){if(typeof h.test=="function")return h.test(p);if(Array.isArray(h.test))return h.test.some((function(y){return p.test(y)}));throw new Error("Browser's test function is not valid")}));return f&&(this.parsedResult.platform=f.describe(this.getUA())),this.parsedResult.platform},d.getEngine=function(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()},d.getEngineName=function(p){return p?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""},d.parseEngine=function(){var p=this;this.parsedResult.engine={};var f=a.default.find(s.default,(function(h){if(typeof h.test=="function")return h.test(p);if(Array.isArray(h.test))return h.test.some((function(y){return p.test(y)}));throw new Error("Browser's test function is not valid")}));return f&&(this.parsedResult.engine=f.describe(this.getUA())),this.parsedResult.engine},d.parse=function(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this},d.getResult=function(){return a.default.assign({},this.parsedResult)},d.satisfies=function(p){var f=this,h={},y=0,w={},b=0;if(Object.keys(p).forEach((function(Ae){var Te=p[Ae];typeof Te=="string"?(w[Ae]=Te,b+=1):typeof Te=="object"&&(h[Ae]=Te,y+=1)})),y>0){var S=Object.keys(h),x=a.default.find(S,(function(Ae){return f.isOS(Ae)}));if(x){var R=this.satisfies(h[x]);if(R!==void 0)return R}var T=a.default.find(S,(function(Ae){return f.isPlatform(Ae)}));if(T){var M=this.satisfies(h[T]);if(M!==void 0)return M}}if(b>0){var Z=Object.keys(w),te=a.default.find(Z,(function(Ae){return f.isBrowser(Ae,!0)}));if(te!==void 0)return this.compareVersion(w[te])}},d.isBrowser=function(p,f){f===void 0&&(f=!1);var h=this.getBrowserName().toLowerCase(),y=p.toLowerCase(),w=a.default.getBrowserTypeByAlias(y);return f&&w&&(y=w.toLowerCase()),y===h},d.compareVersion=function(p){var f=[0],h=p,y=!1,w=this.getBrowserVersion();if(typeof w=="string")return p[0]===">"||p[0]==="<"?(h=p.substr(1),p[1]==="="?(y=!0,h=p.substr(2)):f=[],p[0]===">"?f.push(1):f.push(-1)):p[0]==="="?h=p.substr(1):p[0]==="~"&&(y=!0,h=p.substr(1)),f.indexOf(a.default.compareVersions(w,h,y))>-1},d.isOS=function(p){return this.getOSName(!0)===String(p).toLowerCase()},d.isPlatform=function(p){return this.getPlatformType(!0)===String(p).toLowerCase()},d.isEngine=function(p){return this.getEngineName(!0)===String(p).toLowerCase()},d.is=function(p,f){return f===void 0&&(f=!1),this.isBrowser(p,f)||this.isOS(p)||this.isPlatform(p)},d.some=function(p){var f=this;return p===void 0&&(p=[]),p.some((function(h){return f.is(h)}))},l})();e.default=u,t.exports=e.default},92:function(t,e,r){"use strict";e.__esModule=!0,e.default=void 0;var o,n=(o=r(17))&&o.__esModule?o:{default:o},i=/version\/(\d+(\.?_?\d+)+)/i,s=[{test:[/gptbot/i],describe:function(a){var c={name:"GPTBot"},u=n.default.getFirstMatch(/gptbot\/(\d+(\.\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/chatgpt-user/i],describe:function(a){var c={name:"ChatGPT-User"},u=n.default.getFirstMatch(/chatgpt-user\/(\d+(\.\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/oai-searchbot/i],describe:function(a){var c={name:"OAI-SearchBot"},u=n.default.getFirstMatch(/oai-searchbot\/(\d+(\.\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(a){var c={name:"ClaudeBot"},u=n.default.getFirstMatch(/(?:claudebot|claude-web|claude-user|claude-searchbot)\/(\d+(\.\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(a){var c={name:"Omgilibot"},u=n.default.getFirstMatch(/(?:omgilibot|webzio-extended)\/(\d+(\.\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/diffbot/i],describe:function(a){var c={name:"Diffbot"},u=n.default.getFirstMatch(/diffbot\/(\d+(\.\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/perplexitybot/i],describe:function(a){var c={name:"PerplexityBot"},u=n.default.getFirstMatch(/perplexitybot\/(\d+(\.\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/perplexity-user/i],describe:function(a){var c={name:"Perplexity-User"},u=n.default.getFirstMatch(/perplexity-user\/(\d+(\.\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/youbot/i],describe:function(a){var c={name:"YouBot"},u=n.default.getFirstMatch(/youbot\/(\d+(\.\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/meta-webindexer/i],describe:function(a){var c={name:"Meta-WebIndexer"},u=n.default.getFirstMatch(/meta-webindexer\/(\d+(\.\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/meta-externalads/i],describe:function(a){var c={name:"Meta-ExternalAds"},u=n.default.getFirstMatch(/meta-externalads\/(\d+(\.\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/meta-externalagent/i],describe:function(a){var c={name:"Meta-ExternalAgent"},u=n.default.getFirstMatch(/meta-externalagent\/(\d+(\.\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/meta-externalfetcher/i],describe:function(a){var c={name:"Meta-ExternalFetcher"},u=n.default.getFirstMatch(/meta-externalfetcher\/(\d+(\.\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/googlebot/i],describe:function(a){var c={name:"Googlebot"},u=n.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/linespider/i],describe:function(a){var c={name:"Linespider"},u=n.default.getFirstMatch(/(?:linespider)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/amazonbot/i],describe:function(a){var c={name:"AmazonBot"},u=n.default.getFirstMatch(/amazonbot\/(\d+(\.\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/bingbot/i],describe:function(a){var c={name:"BingCrawler"},u=n.default.getFirstMatch(/bingbot\/(\d+(\.\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/baiduspider/i],describe:function(a){var c={name:"BaiduSpider"},u=n.default.getFirstMatch(/baiduspider\/(\d+(\.\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/duckduckbot/i],describe:function(a){var c={name:"DuckDuckBot"},u=n.default.getFirstMatch(/duckduckbot\/(\d+(\.\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/ia_archiver/i],describe:function(a){var c={name:"InternetArchiveCrawler"},u=n.default.getFirstMatch(/ia_archiver\/(\d+(\.\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{name:"FacebookExternalHit"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(a){var c={name:"SlackBot"},u=n.default.getFirstMatch(/(?:slackbot|slack-imgproxy)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/yahoo!?[\s/]*slurp/i],describe:function(){return{name:"YahooSlurp"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe:function(){return{name:"YandexBot"}}},{test:[/pingdom/i],describe:function(){return{name:"PingdomBot"}}},{test:[/opera/i],describe:function(a){var c={name:"Opera"},u=n.default.getFirstMatch(i,a)||n.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/opr\/|opios/i],describe:function(a){var c={name:"Opera"},u=n.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/SamsungBrowser/i],describe:function(a){var c={name:"Samsung Internet for Android"},u=n.default.getFirstMatch(i,a)||n.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/Whale/i],describe:function(a){var c={name:"NAVER Whale Browser"},u=n.default.getFirstMatch(i,a)||n.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/PaleMoon/i],describe:function(a){var c={name:"Pale Moon"},u=n.default.getFirstMatch(i,a)||n.default.getFirstMatch(/(?:PaleMoon)[\s/](\d+(?:\.\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/MZBrowser/i],describe:function(a){var c={name:"MZ Browser"},u=n.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/focus/i],describe:function(a){var c={name:"Focus"},u=n.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/swing/i],describe:function(a){var c={name:"Swing"},u=n.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/coast/i],describe:function(a){var c={name:"Opera Coast"},u=n.default.getFirstMatch(i,a)||n.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(a){var c={name:"Opera Touch"},u=n.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/yabrowser/i],describe:function(a){var c={name:"Yandex Browser"},u=n.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/ucbrowser/i],describe:function(a){var c={name:"UC Browser"},u=n.default.getFirstMatch(i,a)||n.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/Maxthon|mxios/i],describe:function(a){var c={name:"Maxthon"},u=n.default.getFirstMatch(i,a)||n.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/epiphany/i],describe:function(a){var c={name:"Epiphany"},u=n.default.getFirstMatch(i,a)||n.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/puffin/i],describe:function(a){var c={name:"Puffin"},u=n.default.getFirstMatch(i,a)||n.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/sleipnir/i],describe:function(a){var c={name:"Sleipnir"},u=n.default.getFirstMatch(i,a)||n.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/k-meleon/i],describe:function(a){var c={name:"K-Meleon"},u=n.default.getFirstMatch(i,a)||n.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/micromessenger/i],describe:function(a){var c={name:"WeChat"},u=n.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/qqbrowser/i],describe:function(a){var c={name:/qqbrowserlite/i.test(a)?"QQ Browser Lite":"QQ Browser"},u=n.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/msie|trident/i],describe:function(a){var c={name:"Internet Explorer"},u=n.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/\sedg\//i],describe:function(a){var c={name:"Microsoft Edge"},u=n.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/edg([ea]|ios)/i],describe:function(a){var c={name:"Microsoft Edge"},u=n.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/vivaldi/i],describe:function(a){var c={name:"Vivaldi"},u=n.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/seamonkey/i],describe:function(a){var c={name:"SeaMonkey"},u=n.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/sailfish/i],describe:function(a){var c={name:"Sailfish"},u=n.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,a);return u&&(c.version=u),c}},{test:[/silk/i],describe:function(a){var c={name:"Amazon Silk"},u=n.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/phantom/i],describe:function(a){var c={name:"PhantomJS"},u=n.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/slimerjs/i],describe:function(a){var c={name:"SlimerJS"},u=n.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(a){var c={name:"BlackBerry"},u=n.default.getFirstMatch(i,a)||n.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/(web|hpw)[o0]s/i],describe:function(a){var c={name:"WebOS Browser"},u=n.default.getFirstMatch(i,a)||n.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/bada/i],describe:function(a){var c={name:"Bada"},u=n.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/tizen/i],describe:function(a){var c={name:"Tizen"},u=n.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/qupzilla/i],describe:function(a){var c={name:"QupZilla"},u=n.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/librewolf/i],describe:function(a){var c={name:"LibreWolf"},u=n.default.getFirstMatch(/(?:librewolf)[\s/](\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/firefox|iceweasel|fxios/i],describe:function(a){var c={name:"Firefox"},u=n.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/electron/i],describe:function(a){var c={name:"Electron"},u=n.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/sogoumobilebrowser/i,/metasr/i,/se 2\.[x]/i],describe:function(a){var c={name:"Sogou Browser"},u=n.default.getFirstMatch(/(?:sogoumobilebrowser)[\s/](\d+(\.?_?\d+)+)/i,a),l=n.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,a),d=n.default.getFirstMatch(/se ([\d.]+)x/i,a),p=u||l||d;return p&&(c.version=p),c}},{test:[/MiuiBrowser/i],describe:function(a){var c={name:"Miui"},u=n.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:function(a){return!!a.hasBrand("DuckDuckGo")||a.test(/\sDdg\/[\d.]+$/i)},describe:function(a,c){var u={name:"DuckDuckGo"};if(c){var l=c.getBrandVersion("DuckDuckGo");if(l)return u.version=l,u}var d=n.default.getFirstMatch(/\sDdg\/([\d.]+)$/i,a);return d&&(u.version=d),u}},{test:function(a){return a.hasBrand("Brave")},describe:function(a,c){var u={name:"Brave"};if(c){var l=c.getBrandVersion("Brave");if(l)return u.version=l,u}return u}},{test:[/chromium/i],describe:function(a){var c={name:"Chromium"},u=n.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,a)||n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/chrome|crios|crmo/i],describe:function(a){var c={name:"Chrome"},u=n.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/GSA/i],describe:function(a){var c={name:"Google Search"},u=n.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:function(a){var c=!a.test(/like android/i),u=a.test(/android/i);return c&&u},describe:function(a){var c={name:"Android Browser"},u=n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/playstation 4/i],describe:function(a){var c={name:"PlayStation 4"},u=n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/safari|applewebkit/i],describe:function(a){var c={name:"Safari"},u=n.default.getFirstMatch(i,a);return u&&(c.version=u),c}},{test:[/.*/i],describe:function(a){var c=a.search("\\(")!==-1?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:n.default.getFirstMatch(c,a),version:n.default.getSecondMatch(c,a)}}}];e.default=s,t.exports=e.default},93:function(t,e,r){"use strict";e.__esModule=!0,e.default=void 0;var o,n=(o=r(17))&&o.__esModule?o:{default:o},i=r(18),s=[{test:[/Roku\/DVP/],describe:function(a){var c=n.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,a);return{name:i.OS_MAP.Roku,version:c}}},{test:[/windows phone/i],describe:function(a){var c=n.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,a);return{name:i.OS_MAP.WindowsPhone,version:c}}},{test:[/windows /i],describe:function(a){var c=n.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,a),u=n.default.getWindowsVersionName(c);return{name:i.OS_MAP.Windows,version:c,versionName:u}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(a){var c={name:i.OS_MAP.iOS},u=n.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,a);return u&&(c.version=u),c}},{test:[/macintosh/i],describe:function(a){var c=n.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,a).replace(/[_\s]/g,"."),u=n.default.getMacOSVersionName(c),l={name:i.OS_MAP.MacOS,version:c};return u&&(l.versionName=u),l}},{test:[/(ipod|iphone|ipad)/i],describe:function(a){var c=n.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,a).replace(/[_\s]/g,".");return{name:i.OS_MAP.iOS,version:c}}},{test:[/OpenHarmony/i],describe:function(a){var c=n.default.getFirstMatch(/OpenHarmony\s+(\d+(\.\d+)*)/i,a);return{name:i.OS_MAP.HarmonyOS,version:c}}},{test:function(a){var c=!a.test(/like android/i),u=a.test(/android/i);return c&&u},describe:function(a){var c=n.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,a),u=n.default.getAndroidVersionName(c),l={name:i.OS_MAP.Android,version:c};return u&&(l.versionName=u),l}},{test:[/(web|hpw)[o0]s/i],describe:function(a){var c=n.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,a),u={name:i.OS_MAP.WebOS};return c&&c.length&&(u.version=c),u}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(a){var c=n.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,a)||n.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,a)||n.default.getFirstMatch(/\bbb(\d+)/i,a);return{name:i.OS_MAP.BlackBerry,version:c}}},{test:[/bada/i],describe:function(a){var c=n.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,a);return{name:i.OS_MAP.Bada,version:c}}},{test:[/tizen/i],describe:function(a){var c=n.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,a);return{name:i.OS_MAP.Tizen,version:c}}},{test:[/linux/i],describe:function(){return{name:i.OS_MAP.Linux}}},{test:[/CrOS/],describe:function(){return{name:i.OS_MAP.ChromeOS}}},{test:[/PlayStation 4/],describe:function(a){var c=n.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,a);return{name:i.OS_MAP.PlayStation4,version:c}}}];e.default=s,t.exports=e.default},94:function(t,e,r){"use strict";e.__esModule=!0,e.default=void 0;var o,n=(o=r(17))&&o.__esModule?o:{default:o},i=r(18),s=[{test:[/googlebot/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Google"}}},{test:[/linespider/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Line"}}},{test:[/amazonbot/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Amazon"}}},{test:[/gptbot/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/chatgpt-user/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/oai-searchbot/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/baiduspider/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Baidu"}}},{test:[/bingbot/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Bing"}}},{test:[/duckduckbot/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"DuckDuckGo"}}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Anthropic"}}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Webz.io"}}},{test:[/diffbot/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Diffbot"}}},{test:[/perplexitybot/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Perplexity AI"}}},{test:[/perplexity-user/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Perplexity AI"}}},{test:[/youbot/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"You.com"}}},{test:[/ia_archiver/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Internet Archive"}}},{test:[/meta-webindexer/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalads/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalagent/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalfetcher/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Slack"}}},{test:[/yahoo/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Yahoo"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Yandex"}}},{test:[/pingdom/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Pingdom"}}},{test:[/huawei/i],describe:function(a){var c=n.default.getFirstMatch(/(can-l01)/i,a)&&"Nova",u={type:i.PLATFORMS_MAP.mobile,vendor:"Huawei"};return c&&(u.model=c),u}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return{type:i.PLATFORMS_MAP.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe:function(){return{type:i.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(){return{type:i.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe:function(){return{type:i.PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe:function(){return{type:i.PLATFORMS_MAP.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe:function(){return{type:i.PLATFORMS_MAP.tablet}}},{test:function(a){var c=a.test(/ipod|iphone/i),u=a.test(/like (ipod|iphone)/i);return c&&!u},describe:function(a){var c=n.default.getFirstMatch(/(ipod|iphone)/i,a);return{type:i.PLATFORMS_MAP.mobile,vendor:"Apple",model:c}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:i.PLATFORMS_MAP.mobile,vendor:"Nexus"}}},{test:[/Nokia/i],describe:function(a){var c=n.default.getFirstMatch(/Nokia\s+([0-9]+(\.[0-9]+)?)/i,a),u={type:i.PLATFORMS_MAP.mobile,vendor:"Nokia"};return c&&(u.model=c),u}},{test:[/[^-]mobi/i],describe:function(){return{type:i.PLATFORMS_MAP.mobile}}},{test:function(a){return a.getBrowserName(!0)==="blackberry"},describe:function(){return{type:i.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(a){return a.getBrowserName(!0)==="bada"},describe:function(){return{type:i.PLATFORMS_MAP.mobile}}},{test:function(a){return a.getBrowserName()==="windows phone"},describe:function(){return{type:i.PLATFORMS_MAP.mobile,vendor:"Microsoft"}}},{test:function(a){var c=Number(String(a.getOSVersion()).split(".")[0]);return a.getOSName(!0)==="android"&&c>=3},describe:function(){return{type:i.PLATFORMS_MAP.tablet}}},{test:function(a){return a.getOSName(!0)==="android"},describe:function(){return{type:i.PLATFORMS_MAP.mobile}}},{test:[/smart-?tv|smarttv/i],describe:function(){return{type:i.PLATFORMS_MAP.tv}}},{test:[/netcast/i],describe:function(){return{type:i.PLATFORMS_MAP.tv}}},{test:function(a){return a.getOSName(!0)==="macos"},describe:function(){return{type:i.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(a){return a.getOSName(!0)==="windows"},describe:function(){return{type:i.PLATFORMS_MAP.desktop}}},{test:function(a){return a.getOSName(!0)==="linux"},describe:function(){return{type:i.PLATFORMS_MAP.desktop}}},{test:function(a){return a.getOSName(!0)==="playstation 4"},describe:function(){return{type:i.PLATFORMS_MAP.tv}}},{test:function(a){return a.getOSName(!0)==="roku"},describe:function(){return{type:i.PLATFORMS_MAP.tv}}}];e.default=s,t.exports=e.default},95:function(t,e,r){"use strict";e.__esModule=!0,e.default=void 0;var o,n=(o=r(17))&&o.__esModule?o:{default:o},i=r(18),s=[{test:function(a){return a.getBrowserName(!0)==="microsoft edge"},describe:function(a){if(/\sedg\//i.test(a))return{name:i.ENGINE_MAP.Blink};var c=n.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,a);return{name:i.ENGINE_MAP.EdgeHTML,version:c}}},{test:[/trident/i],describe:function(a){var c={name:i.ENGINE_MAP.Trident},u=n.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:function(a){return a.test(/presto/i)},describe:function(a){var c={name:i.ENGINE_MAP.Presto},u=n.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:function(a){var c=a.test(/gecko/i),u=a.test(/like gecko/i);return c&&!u},describe:function(a){var c={name:i.ENGINE_MAP.Gecko},u=n.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:i.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(a){var c={name:i.ENGINE_MAP.WebKit},u=n.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,a);return u&&(c.version=u),c}}];e.default=s,t.exports=e.default}})}))});var Fre,qre=_(()=>{Fre=({serviceId:t,clientVersion:e})=>async r=>{let o=await Promise.resolve().then(()=>Vt(jre())),n=o.parse??o.default.parse??(()=>""),i=typeof window<"u"&&window?.navigator?.userAgent?n(window.navigator.userAgent):void 0,s=[["aws-sdk-js",e],["ua","2.1"],[`os/${i?.os?.name||"other"}`,i?.os?.version],["lang/js"],["md/browser",`${i?.browser?.name??"unknown"}_${i?.browser?.version??"unknown"}`]];t&&s.push([`api/${t}`,e]);let a=await r?.userAgentAppId?.();return a&&s.push([`app/${a}`]),s}});var Vre,Gre=_(()=>{Vre={os(t){if(/iPhone|iPad|iPod/.test(t))return"iOS";if(/Macintosh|Mac OS X/.test(t))return"macOS";if(/Windows NT/.test(t))return"Windows";if(/Android/.test(t))return"Android";if(/Linux/.test(t))return"Linux"},browser(t){if(/EdgiOS|EdgA|Edg\//.test(t))return"Microsoft Edge";if(/Firefox\//.test(t))return"Firefox";if(/Chrome\//.test(t))return"Chrome";if(/Safari\//.test(t))return"Safari"}}});var H2=_(()=>{Jt()});var Bv,K2=_(()=>{Jt();H2();Bv=(t,e=!1)=>{if(e){for(let r of t.split("."))if(!Bv(r))return!1;return!0}return!(!Hi(t)||t.length<3||t.length>63||t!==t.toLowerCase()||lc(t))}});var BI,B2=_(()=>{BI=t=>{let e=t.split(":");if(e.length<6)return null;let[r,o,n,i,s,...a]=e;if(r!=="arn"||o===""||n===""||a.join(":")==="")return null;let c=a.map(u=>u.split("/")).flat();return{partition:o,service:n,region:i,accountId:s,resourceId:c}}});var ns,Hre=_(()=>{Jt();K2();B2();GI();ns={isVirtualHostableS3Bucket:Bv,parseArn:BI,partition:qI};ho.aws=ns});var Kre=_(()=>{Jt()});var Bre,Z2,Zre=_(()=>{ge();Bre=t=>{if(typeof t.endpointProvider!="function")throw new Error("@aws-sdk/util-endpoint - endpointProvider and endpoint missing in config for this client.");let{endpoint:e}=t;return e===void 0&&(t.endpoint=async()=>Z2(t.endpointProvider({Region:typeof t.region=="function"?await t.region():t.region,UseDualStack:typeof t.useDualstackEndpoint=="function"?await t.useDualstackEndpoint():t.useDualstackEndpoint,UseFIPS:typeof t.useFipsEndpoint=="function"?await t.useFipsEndpoint():t.useFipsEndpoint,Endpoint:void 0},{logger:t.logger}))),t},Z2=t=>nn(t.url)});var Wre=_(()=>{Jt()});var Jre=_(()=>{Dt();Dt()});function ZI(t={}){return Ie({...on,async default(){return W2.silence||console.warn("@aws-sdk - WARN - default STS region of us-east-1 used. See @aws-sdk/credential-providers README and set a region explicitly."),"us-east-1"}},{...Xn,...t})}var W2,Xre=_(()=>{Dt();W2={silence:!1}});var ya,va,Yre=_(()=>{ya=t=>({setRegion(e){t.region=e},region(){return t.region}}),va=t=>({region:t.region()})});var os={};Ht(os,{DEFAULT_UA_APP_ID:()=>Gv,EndpointError:()=>pt,NODE_APP_ID_CONFIG_OPTIONS:()=>ga,NODE_REGION_CONFIG_FILE_OPTIONS:()=>Xn,NODE_REGION_CONFIG_OPTIONS:()=>on,REGION_ENV_NAME:()=>om,REGION_INI_NAME:()=>im,UA_APP_ID_ENV_NAME:()=>q2,UA_APP_ID_INI_NAME:()=>V2,awsEndpointFunctions:()=>ns,createDefaultUserAgentProvider:()=>rs,createUserAgentStringParsingProvider:()=>Fre,crtAvailability:()=>Hv,defaultUserAgent:()=>Mre,emitWarningIfUnsupportedVersion:()=>Ls,fallback:()=>Vre,getAwsRegionExtensionConfiguration:()=>ya,getHostHeaderPlugin:()=>da,getLoggerPlugin:()=>pa,getLongPollPlugin:()=>CJ,getRecursionDetectionPlugin:()=>fa,getUserAgentMiddlewareOptions:()=>L2,getUserAgentPlugin:()=>ha,getUserAgentPrefix:()=>VI,hostHeaderMiddleware:()=>y2,hostHeaderMiddlewareOptions:()=>v2,isIpAddress:()=>lc,isVirtualHostableS3Bucket:()=>Bv,loggerMiddleware:()=>w2,loggerMiddlewareOptions:()=>_2,parseArn:()=>BI,partition:()=>qI,recursionDetectionMiddleware:()=>zI,recursionDetectionMiddlewareOptions:()=>DI,resolveAwsRegionExtensionConfiguration:()=>va,resolveDefaultAwsRegionalEndpointsConfig:()=>Bre,resolveEndpoint:()=>Tv,resolveHostHeaderConfig:()=>Rm,resolveRegionConfig:()=>No,resolveUserAgentConfig:()=>ma,setCredentialFeature:()=>gu,setFeature:()=>di,setPartitionInfo:()=>N2,setTokenFeature:()=>Hte,state:()=>ov,stsRegionDefaultResolver:()=>ZI,stsRegionWarning:()=>W2,toEndpointV1:()=>Z2,useDefaultPartitionInfo:()=>bre,userAgentMiddleware:()=>U2});var Nt=_(()=>{TJ();OJ();DJ();g2();Kte();Bte();Zte();b2();Yte();I2();O2();Tre();Ure();Lre();Gre();qre();Hre();Kre();Zre();H2();K2();B2();GI();Wre();Jre();Xre();Yre()});var WI,JI,Qre=_(()=>{ge();WI=t=>Lr.isInstance(t)?t.headers?.date??t.headers?.Date:void 0,JI=t=>Lr.isInstance(t)?t.headers?.age??t.headers?.Age:void 0});var Zv,ene=_(()=>{Zv=t=>new Date(Date.now()+t)});var XI,tne=_(()=>{XI=(t,e,r,o)=>{if(o!==void 0)return e;let n=Date.parse(t),i=Date.now();return r!==void 0&&i-r>9e5?e:r!==void 0?n-(r+i)/2:n-i}});var J2=_(()=>{Qre();ene();tne()});var Wv,km,Gr,X2,Y2=_(()=>{ge();J2();Wv=(t,e)=>{if(!e)throw new Error(`Property \`${t}\` is not resolved for AWS SDK SigV4Auth`);return e},km=async t=>{let e=Wv("context",t.context),r=Wv("config",t.config),o=e.endpointV2?.properties?.authSchemes?.[0],i=await Wv("signer",r.signer)(o),s=t?.signingRegion,a=t?.signingRegionSet,c=t?.signingName;return{config:r,signer:i,signingRegion:s,signingRegionSet:a,signingName:c}},Gr=class{async sign(e,r,o){if(!We.isInstance(e))throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");let n=await km(o),{config:i,signer:s}=n,{signingRegion:a,signingName:c}=n,u=o.context;if(u?.authSchemes?.length??!1){let[p,f]=u.authSchemes;p?.name==="sigv4a"&&f?.name==="sigv4"&&(a=f?.signingRegion??a,c=f?.signingName??c)}let l=await i.disableClockSkewCorrection?.()===!0;return o._disableClockSkewCorrection=l,l||(o._preRequestSystemClockOffset=i.systemClockOffset,o._requestSentAt=Date.now()),await s.sign(e,{signingDate:l?new Date:Zv(i.systemClockOffset),signingRegion:a,signingService:c})}errorHandler(e){return r=>{let o=r;if(!e._disableClockSkewCorrection){let n=o.ServerTime??WI(o.$response);if(n){let i=Wv("config",e.config),s=e._preRequestSystemClockOffset,a=e._requestSentAt,c=JI(o.$response),u=XI(n,i.systemClockOffset,a,c);i.systemClockOffset=u,Math.abs(u)>=24e4&&(u!==s||s!==void 0&&s!==u)&&o.$metadata&&(o.$metadata.clockSkewCorrected=!0)}}throw r}}successHandler(e,r){if(r._disableClockSkewCorrection)return;let o=WI(e);if(o){let n=Wv("config",r.config),i=r._requestSentAt,s=JI(e);n.systemClockOffset=XI(o,n.systemClockOffset,i,s)}}},X2=Gr});var vc,rne=_(()=>{ge();J2();Y2();vc=class extends Gr{async sign(e,r,o){if(!We.isInstance(e))throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");let{config:n,signer:i,signingRegion:s,signingRegionSet:a,signingName:c}=await km(o),l=(await n.sigv4aSigningRegionSet?.()??a??[s]).join(","),d=await n.disableClockSkewCorrection?.()===!0;return o._disableClockSkewCorrection=d,d||(o._preRequestSystemClockOffset=n.systemClockOffset,o._requestSentAt=Date.now()),await i.sign(e,{signingDate:d?new Date:Zv(n.systemClockOffset),signingRegion:l,signingService:c})}}});var Q2,nne=_(()=>{Q2=t=>typeof t=="string"&&t.length>0?t.split(",").map(e=>e.trim()):[]});var YI,e6=_(()=>{YI=t=>`AWS_BEARER_TOKEN_${t.replace(/[\s-]/g,"_").toUpperCase()}`});var one,ine,is,sne=_(()=>{nne();e6();one="AWS_AUTH_SCHEME_PREFERENCE",ine="auth_scheme_preference",is={environmentVariableSelector:(t,e)=>{if(e?.signingName&&YI(e.signingName)in t)return["httpBearerAuth"];if(one in t)return Q2(t[one])},configFileSelector:t=>{if(ine in t)return Q2(t[ine])},default:[]}});var Jv,Xv,ane=_(()=>{Yn();Dt();Jv=t=>(t.sigv4aSigningRegionSet=pi(t.sigv4aSigningRegionSet),t),Xv={environmentVariableSelector(t){if(t.AWS_SIGV4A_SIGNING_REGION_SET)return t.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map(e=>e.trim());throw new Do("AWS_SIGV4A_SIGNING_REGION_SET not set in env.",{tryNextLink:!0})},configFileSelector(t){if(t.sigv4a_signing_region_set)return(t.sigv4a_signing_region_set??"").split(",").map(e=>e.trim());throw new Do("sigv4a_signing_region_set not set in profile.",{tryNextLink:!0})},default:void 0}});var p6=U(Le=>{var{hasOwn:Cm,fromUtf8:cne,fromHex:xUe,toHex:kd,toUint8Array:Yv,isArrayBuffer:EUe}=(xe(),re(Ed)),{normalizeProvider:une}=(ve(),re(Kf)),{escapeUri:QI,HttpRequest:fne}=(ge(),re(zu)),t6=class{format(e){let r=[];for(let i in e){if(!Cm(e,i))continue;let s=cne(i);r.push(Uint8Array.from([s.byteLength]),s,this.formatHeaderValue(e[i]))}let o=new Uint8Array(r.reduce((i,s)=>i+s.byteLength,0)),n=0;for(let i of r)o.set(i,n),n+=i.byteLength;return o}formatHeaderValue(e){switch(e.type){case"boolean":return Uint8Array.from([e.value?0:1]);case"byte":return Uint8Array.from([2,e.value]);case"short":let r=new DataView(new ArrayBuffer(3));return r.setUint8(0,3),r.setInt16(1,e.value,!1),new Uint8Array(r.buffer);case"integer":let o=new DataView(new ArrayBuffer(5));return o.setUint8(0,4),o.setInt32(1,e.value,!1),new Uint8Array(o.buffer);case"long":let n=new Uint8Array(9);return n[0]=5,n.set(e.value.bytes,1),n;case"binary":let i=new DataView(new ArrayBuffer(3+e.value.byteLength));i.setUint8(0,6),i.setUint16(1,e.value.byteLength,!1);let s=new Uint8Array(i.buffer);return s.set(e.value,3),s;case"string":let a=cne(e.value),c=new DataView(new ArrayBuffer(3+a.byteLength));c.setUint8(0,7),c.setUint16(1,a.byteLength,!1);let u=new Uint8Array(c.buffer);return u.set(a,3),u;case"timestamp":let l=new Uint8Array(9);return l[0]=8,l.set(r6.fromNumber(e.value.valueOf()).bytes,1),l;case"uuid":if(!$Ue.test(e.value))throw new Error(`Invalid UUID received: ${e.value}`);let d=new Uint8Array(17);return d[0]=9,d.set(xUe(e.value.replace(/-/g,"")),1),d}}},lne;(function(t){t[t.boolTrue=0]="boolTrue",t[t.boolFalse=1]="boolFalse",t[t.byte=2]="byte",t[t.short=3]="short",t[t.integer=4]="integer",t[t.long=5]="long",t[t.byteArray=6]="byteArray",t[t.string=7]="string",t[t.timestamp=8]="timestamp",t[t.uuid=9]="uuid"})(lne||(lne={}));var $Ue=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,r6=class t{bytes;constructor(e){if(this.bytes=e,e.byteLength!==8)throw new Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(e){if(e>9223372036854776e3||e<-9223372036854776e3)throw new Error(`${e} is too large (or, if negative, too small) to represent as an Int64`);let r=new Uint8Array(8);for(let o=7,n=Math.abs(Math.round(e));o>-1&&n>0;o--,n/=256)r[o]=n;return e<0&&dne(r),new t(r)}valueOf(){let e=this.bytes.slice(0),r=e[0]&128;return r&&dne(e),parseInt(kd(e),16)*(r?-1:1)}toString(){return String(this.valueOf())}};function dne(t){for(let e=0;e<8;e++)t[e]^=255;for(let e=7;e>-1&&(t[e]++,t[e]===0);e--);}var mne="X-Amz-Algorithm",hne="X-Amz-Credential",s6="X-Amz-Date",gne="X-Amz-SignedHeaders",yne="X-Amz-Expires",a6="X-Amz-Signature",c6="X-Amz-Security-Token",RUe="X-Amz-Region-Set",u6="authorization",l6=s6.toLowerCase(),vne="date",wne=[u6,l6,vne],_ne=a6.toLowerCase(),oA="x-amz-content-sha256",bne=c6.toLowerCase(),IUe="host",Sne={authorization:!0,"cache-control":!0,connection:!0,expect:!0,from:!0,"keep-alive":!0,"max-forwards":!0,pragma:!0,referer:!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0,"user-agent":!0,"x-amzn-trace-id":!0},xne=/^proxy-/,Ene=/^sec-/,AUe=[/^proxy-/i,/^sec-/i],eA="AWS4-HMAC-SHA256",PUe="AWS4-ECDSA-P256-SHA256",$ne="AWS4-HMAC-SHA256-PAYLOAD",Rne="UNSIGNED-PAYLOAD",Ine=50,d6="aws4_request",Ane=3600*24*7,Pne=({query:t={}})=>{let e=[],r={};for(let o in t){if(!Cm(t,o)||o.toLowerCase()===_ne)continue;let n=QI(o);e.push(n);let i=t[o];typeof i=="string"?r[n]=`${n}=${QI(i)}`:Array.isArray(i)&&(r[n]=i.slice(0).reduce((s,a)=>s.concat([`${n}=${QI(a)}`]),[]).sort().join("&"))}return e.sort().map(o=>r[o]).filter(o=>o).join("&")},kUe=t=>TUe(t).toISOString().replace(/\.\d{3}Z$/,"Z"),TUe=t=>typeof t=="number"?new Date(t*1e3):typeof t=="string"?Number(t)?new Date(Number(t)*1e3):new Date(t):t,iA=class{service;regionProvider;credentialProvider;sha256;uriEscapePath;applyChecksum;constructor({applyChecksum:e,credentials:r,region:o,service:n,sha256:i,uriEscapePath:s=!0}){this.service=n,this.sha256=i,this.uriEscapePath=s,this.applyChecksum=typeof e=="boolean"?e:!0,this.regionProvider=une(o),this.credentialProvider=une(r)}createCanonicalRequest(e,r,o){let n=Object.keys(r).sort();return`${e.method}
27
27
  ${this.getCanonicalPath(e)}
28
28
  ${Pne(e)}
@@ -42,14 +42,14 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
42
42
  - ECS container host 169.254.170.2
43
43
  - EKS container host 169.254.170.23 or [fd00:ec2::23]`,{logger:e})}};function zLe(t){return new PLe({protocol:t.protocol,hostname:t.hostname,port:Number(t.port),path:t.pathname,query:Array.from(t.searchParams.entries()).reduce((e,[r,o])=>(e[r]=o,e),{}),fragment:t.hash})}async function MLe(t,e){let o=await kLe(t.body).transformToString();if(t.statusCode===200){let n=JSON.parse(o);if(typeof n.AccessKeyId!="string"||typeof n.SecretAccessKey!="string"||typeof n.Token!="string"||typeof n.Expiration!="string")throw new Td("HTTP credential provider response not of the required format, an object matching: { AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }",{logger:e});return{accessKeyId:n.AccessKeyId,secretAccessKey:n.SecretAccessKey,sessionToken:n.Token,expiration:TLe(n.Expiration)}}if(t.statusCode>=400&&t.statusCode<500){let n={};try{n=JSON.parse(o)}catch{}throw Object.assign(new Td(`Server responded with status: ${t.statusCode}`,{logger:e}),{Code:n.Code,Message:n.Message})}throw new Td(`Server responded with status: ${t.statusCode}`,{logger:e})}var ULe=(t,e,r)=>async()=>{for(let o=0;o<e;++o)try{return await t()}catch{await new Promise(i=>setTimeout(i,r))}return await t()},LLe="AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",jLe="http://169.254.170.2",FLe="AWS_CONTAINER_CREDENTIALS_FULL_URI",qLe="AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE",VLe="AWS_CONTAINER_AUTHORIZATION_TOKEN",GLe=(t={})=>{t.logger?.debug("@aws-sdk/credential-provider-http - fromHttp");let e,r=t.awsContainerCredentialsRelativeUri??process.env[LLe],o=t.awsContainerCredentialsFullUri??process.env[FLe],n=t.awsContainerAuthorizationToken??process.env[VLe],i=t.awsContainerAuthorizationTokenFile??process.env[qLe],s=t.logger?.constructor?.name==="NoOpLogger"||!t.logger?.warn?console.warn:t.logger.warn.bind(t.logger);if(r&&o&&(s("@aws-sdk/credential-provider-http: you have set both awsContainerCredentialsRelativeUri and awsContainerCredentialsFullUri."),s("awsContainerCredentialsRelativeUri will take precedence.")),n&&i&&(s("@aws-sdk/credential-provider-http: you have set both awsContainerAuthorizationToken and awsContainerAuthorizationTokenFile."),s("awsContainerAuthorizationTokenFile will take precedence.")),r)e=`${jLe}${r}`;else if(o)e=o;else throw new Td(`No HTTP credential provider host provided.
44
44
  Set AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.`,{logger:t.logger});let a=new URL(e);NLe(a,t.logger);let c=ILe.create({connectionTimeout:t.timeout??1e3}),u=t.timeout??1e3,l=ULe(async()=>{let d=zLe(a);i?d.headers.Authorization=foe((await ALe.readFile(i)).toString()):n&&(d.headers.Authorization=foe(n));try{let p=await c.handle(d,{requestTimeout:u});return MLe(p.response).then(f=>RLe(f,"CREDENTIALS_HTTP","z"))}catch(p){throw new Td(String(p),{logger:t.logger})}},t.maxRetries??3,t.timeout??1e3);return async()=>{try{return await l()}finally{c.destroy?.()}}},foe=t=>{if(t.includes(`\r
45
- `))throw new Td("Authorization token contains invalid \\r\\n sequence.");return t};moe.fromHttp=GLe});function HLe(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sso-oauth",region:t.region},propertiesExtractor:(e,r)=>({signingProperties:{config:e,context:r}})}}function KLe(t){return{schemeId:"smithy.api#noAuth"}}var hoe,goe,yoe,C6=_(()=>{Pn();ve();hoe=async(t,e,r)=>({operation:Bt(e).operation,region:await jt(t.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});goe=t=>{let e=[];return t.operation==="CreateToken"?e.push(KLe(t)):e.push(HLe(t)),e},yoe=t=>{let e=wa(t);return Object.assign(e,{authSchemePreference:jt(t.authSchemePreference??[])})}});var voe,woe,O6=_(()=>{voe=t=>Object.assign(t,{useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,defaultSigningName:"sso-oauth"}),woe={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}});var Hu,iw=_(()=>{Hu={name:"@aws-sdk/nested-clients",version:"3.997.46",description:"Nested clients for AWS SDK packages.",homepage:"https://github.com/aws/aws-sdk-js-v3/tree/main/packages/nested-clients",license:"Apache-2.0",author:{name:"AWS SDK for JavaScript Team",url:"https://aws.amazon.com/sdk-for-javascript/"},repository:{type:"git",url:"https://github.com/aws/aws-sdk-js-v3.git",directory:"packages/nested-clients"},files:["./cognito-identity.d.ts","./cognito-identity.js","./signin.d.ts","./signin.js","./sso-oidc.d.ts","./sso-oidc.js","./sso.d.ts","./sso.js","./sts.d.ts","./sts.js","dist-*/**"],sideEffects:!1,main:"./dist-cjs/index.js",module:"./dist-es/index.js",browser:{"./dist-es/submodules/cognito-identity/runtimeConfig":"./dist-es/submodules/cognito-identity/runtimeConfig.browser","./dist-es/submodules/signin/runtimeConfig":"./dist-es/submodules/signin/runtimeConfig.browser","./dist-es/submodules/sso-oidc/runtimeConfig":"./dist-es/submodules/sso-oidc/runtimeConfig.browser","./dist-es/submodules/sso/runtimeConfig":"./dist-es/submodules/sso/runtimeConfig.browser","./dist-es/submodules/sts/runtimeConfig":"./dist-es/submodules/sts/runtimeConfig.browser"},types:"./dist-types/index.d.ts",typesVersions:{"<4.5":{"dist-types/*":["dist-types/ts3.4/*"],"*":["dist-types/ts3.4/submodules/*/index.d.ts"]}},"react-native":{},exports:{"./package.json":"./package.json","./sso-oidc":{types:"./dist-types/submodules/sso-oidc/index.d.ts",module:"./dist-es/submodules/sso-oidc/index.js",node:"./dist-cjs/submodules/sso-oidc/index.js",import:"./dist-es/submodules/sso-oidc/index.js",require:"./dist-cjs/submodules/sso-oidc/index.js"},"./sts":{types:"./dist-types/submodules/sts/index.d.ts",module:"./dist-es/submodules/sts/index.js",node:"./dist-cjs/submodules/sts/index.js",import:"./dist-es/submodules/sts/index.js",require:"./dist-cjs/submodules/sts/index.js"},"./signin":{types:"./dist-types/submodules/signin/index.d.ts",module:"./dist-es/submodules/signin/index.js",node:"./dist-cjs/submodules/signin/index.js",import:"./dist-es/submodules/signin/index.js",require:"./dist-cjs/submodules/signin/index.js"},"./cognito-identity":{types:"./dist-types/submodules/cognito-identity/index.d.ts",module:"./dist-es/submodules/cognito-identity/index.js",node:"./dist-cjs/submodules/cognito-identity/index.js",import:"./dist-es/submodules/cognito-identity/index.js",require:"./dist-cjs/submodules/cognito-identity/index.js"},"./sso":{types:"./dist-types/submodules/sso/index.d.ts",module:"./dist-es/submodules/sso/index.js",node:"./dist-cjs/submodules/sso/index.js",import:"./dist-es/submodules/sso/index.js",require:"./dist-cjs/submodules/sso/index.js"}},scripts:{build:"concurrently 'yarn:build:types' 'yarn:build:es' && yarn build:cjs","build:cjs":"node ../../scripts/compilation/inline","build:es":"premove dist-es && tsc -p tsconfig.es.json","build:include:deps":'yarn g:turbo run build -F="$npm_package_name"',"build:types":"premove dist-types && tsc -p tsconfig.types.json","build:types:downlevel":"downlevel-dts dist-types dist-types/ts3.4",clean:"premove dist-cjs dist-es dist-types",lint:"node ../../scripts/validation/submodules-linter.js",prebuild:"yarn lint",test:"yarn g:vitest run","test:watch":"yarn g:vitest watch"},dependencies:{"@aws-sdk/core":"^3.978.1","@aws-sdk/signature-v4-multi-region":"^3.996.47","@aws-sdk/types":"^3.974.6","@smithy/core":"^3.35.0","@smithy/fetch-http-handler":"^5.8.0","@smithy/node-http-handler":"^4.12.1","@smithy/types":"^4.19.0",tslib:"^2.6.2"},devDependencies:{concurrently:"7.0.0","downlevel-dts":"0.10.1",premove:"4.0.0",typescript:"~7.0.2"},engines:{node:">=20.0.0"}}});var D6,_oe=_(()=>{D6=Symbol("@smithy/core/cbor::tagSymbol")});var sw,N6=_(()=>{sw=(t,e)=>{let r=o=>{let n=o;return typeof n=="number"&&(n=n.toString()),n.indexOf(",")>=0&&(n=n.split(",")[0]),n.indexOf(":")>=0&&(n=n.split(":")[0]),n};if(e.__type!==void 0)return r(e.__type)}});function _A(t){let e=t.getSchema(),r=e[boe];if(r)return r;let o=[],n=[];for(let[a,c]of t.structIterator())o.push(a),n.push(c);let i=new Array(o.length);for(let a=0;a<o.length;++a)i[a]=ZLe(o[a]);let s={memberNames:o,memberSchemas:n,encodedKeys:i};return e[boe]=s,s}function ZLe(t){let e;bA?e=Buffer.from(t,"utf-8"):e=new TextEncoder().encode(t);let r=e.length,o;r<24?o=1:r<256?o=2:o=3;let n=new Uint8Array(o+r);return o===1?n[0]=96|r:o===2?(n[0]=120,n[1]=r):(n[0]=121,n[1]=r>>8,n[2]=r&255),n.set(e,o),n}function Roe(t){return bA?Buffer.allocUnsafe(t):new Uint8Array(t)}function Mm(t,e,r,o){if(e==null){if(e===void 0&&t.isIdempotencyToken()){_a(Lo());return}zt(1),Oe[Ee++]=246;return}if(t.isUnitSchema()){zt(1),Hr(5,0);return}if(typeof e=="object"){if(t.isBlobSchema()&&e instanceof Uint8Array){hA(e);return}if(t.isTimestampSchema()&&e instanceof Date){L6(e);return}if(t.isStructSchema()){JLe(t,e,o);return}if(Array.isArray(e)&&(t.isListSchema()||t.isDocumentSchema())){Eoe(t,e,t.isDocumentSchema(),o);return}if(t.isMapSchema()){M6(t,e,!1,o);return}if(e instanceof Date){L6(e);return}if(e instanceof Uint8Array){hA(e);return}if(e instanceof nt){Poe(e);return}if(e[D6]){let i=e;Aoe(i.tag,i.value);return}if(t.isDocumentSchema()){Array.isArray(e)?Eoe(t,e,!0,o):M6(t,e,!0,o);return}if(t.isBigDecimalSchema()){Um(e);return}M6(t,e,!0,o);return}if(typeof e=="string"){if(t.isBlobSchema()){let i=(o?.base64Decoder??pr)(e);hA(i);return}_a(e);return}if(typeof e=="number"){zt(9),Number.isInteger(e)&&e>=-9007199254740992&&e<=9007199254740991?SA(e):K6(e);return}if(typeof e=="boolean"){zt(1),Oe[Ee++]=224|(e?21:20);return}if(typeof e=="bigint"){vA(e);return}_a(String(e))}function JLe(t,e,r){if(t.isUnionSchema()){let d=!1;for(let[p,f]of t.structIterator()){let h=e[p];if(h!=null){zt(9),Hr(5,1),_a(p),Mm(f,h,t,r),d=!0;break}}if(!d){let{$unknown:p}=e;Array.isArray(p)?(zt(9),Hr(5,1),_a(p[0]),Um(p[1])):(zt(9),Hr(5,0))}return}let o=_A(t),{memberNames:n,memberSchemas:i,encodedKeys:s}=o,a=n.length,c;a<24?c=1:a<256?c=2:c=3,zt(c);let u=Ee;Ee+=c;let l=0;for(let d=0;d<a;++d){let p=e[n[d]];if(p==null&&!i[d].isIdempotencyToken())continue;let f=s[d];zt(f.length),Oe.set(f,Ee),Ee+=f.length,Mm(i[d],p,t,r),++l}if(typeof e.__type=="string")for(let d in e)Se(e,d)&&(n.includes(d)||(_a(d),Um(e[d]),++l));c===1?Oe[u]=160|l:c===2?(Oe[u]=184,Oe[u+1]=l):(Oe[u]=185,Oe[u+1]=l>>8,Oe[u+2]=l&255)}function Eoe(t,e,r,o){let n=!!t.getMergedTraits().sparse,i=t.getValueSchema();if(r||n){let s=[];for(let a=0;a<e.length;++a){let c=e[a];r?c!==void 0&&s.push(c):(c!=null||n)&&s.push(c)}zt(9),Hr(4,s.length);for(let a=0;a<s.length;++a)Mm(i,s[a],void 0,o)}else{let s=0;for(let a=0;a<e.length;++a)e[a]!=null&&++s;zt(9),Hr(4,s);for(let a=0;a<e.length;++a)e[a]!=null&&Mm(i,e[a],void 0,o)}}function M6(t,e,r,o){let n=!!t.getMergedTraits().sparse,i=t.getValueSchema(),s=[];for(let a in e){if(!Se(e,a))continue;let c=e[a];(r?c!==void 0:c!=null||n)&&s.push(a)}zt(9),Hr(5,s.length);for(let a=0;a<s.length;++a){let c=s[a];_a(c),Mm(i,e[c],void 0,o)}}function Um(t){if(t==null){zt(1),Oe[Ee++]=246;return}if(typeof t=="string"){_a(t);return}if(typeof t=="number"){zt(9),Number.isInteger(t)&&t>=-9007199254740992&&t<=9007199254740991?SA(t):K6(t);return}if(typeof t=="boolean"){zt(1),Oe[Ee++]=224|(t?21:20);return}if(typeof t=="bigint"){vA(t);return}if(t instanceof Uint8Array){hA(t);return}if(t instanceof Date){L6(t);return}if(t instanceof nt){Poe(t);return}if(t[D6]){let e=t;Aoe(e.tag,e.value);return}if(Array.isArray(t)){zt(9),Hr(4,t.length);for(let e=0;e<t.length;++e)Um(t[e]);return}if(typeof t=="object"){let e=Object.keys(t);zt(9),Hr(5,e.length);for(let r=0;r<e.length;++r)_a(e[r]),Um(t[e[r]]);return}_a(String(t))}function zt(t){if(Ee+t>Oe.length){let e=Oe.length*2;for(;e<Ee+t;)e*=2;let r=Roe(e);r.set(Oe.subarray(0,Ee)),Oe=r,Od=new DataView(r.buffer,r.byteOffset,r.byteLength)}}function Hr(t,e){if(e<24)Oe[Ee++]=t<<5|e;else if(e<256)Oe[Ee++]=t<<5|24,Oe[Ee++]=e;else if(e<65536)Oe[Ee++]=t<<5|25,Oe[Ee++]=e>>8,Oe[Ee++]=e&255;else if(e<4294967296)Oe[Ee++]=t<<5|26,Od.setUint32(Ee,e),Ee+=4;else{Oe[Ee++]=t<<5|27;let r=e/4294967296|0,o=e-r*4294967296|0;Od.setUint32(Ee,r),Od.setUint32(Ee+4,o),Ee+=8}}function Ioe(t,e){let r=Number(e);if(r<4294967296){Hr(t,r);return}Oe[Ee++]=t<<5|27,Od.setBigUint64(Ee,e),Ee+=8}function _a(t){let e=t.length;if(e<=23){let r=Dm.get(t);if(r){zt(r.bytes.length),Oe.set(r.bytes,Ee),Ee+=r.bytes.length,r.epoch=z6;return}let o=Ee;$oe(t,e);let n=Ee,i=Uint8Array.prototype.slice.call(Oe,o,n);if(Dm.size>=Soe){if(xoe)return;let s=0;for(let[a,c]of Dm){if(s>=1024)break;c.epoch!==z6&&(Dm.delete(a),++s)}if(s===0){xoe=!0;return}}Dm.size<Soe&&Dm.set(t,{epoch:z6,bytes:i});return}$oe(t,e)}function $oe(t,e){if(bA){let r=e*3;zt(r+9);let o=Buffer.byteLength(t);Hr(3,o),Ee+=Oe.write(t,Ee)}else{let r=e*3;zt(r+9);let o=Ee,i=WLe.encodeInto(t,Oe.subarray(o+9)).written,s;i<24?s=1:i<256?s=2:i<65536?s=3:i<4294967296?s=5:s=9,s<9&&Oe.copyWithin(o+s,o+9,o+9+i),Ee=o,Hr(3,i),Ee+=i}}function K6(t){zt(9),Oe[Ee++]=251,Od.setFloat64(Ee,t),Ee+=8}function SA(t){zt(9);let e=t>=0,r=e?0:1,o=e?t:-t-1;Hr(r,o)}function vA(t){let e=t>=0,r=e?0:1,o=e?t:-t-BigInt(1);if(o<BigInt("18446744073709551616"))zt(9),Ioe(r,o);else{let n=o.toString(2),i=Math.ceil(n.length/8),s=new Uint8Array(i),a=o;for(let c=i-1;c>=0;--c)s[c]=Number(a&BigInt(255)),a>>=BigInt(8);zt(i+16),Oe[Ee++]=e?194:195,Hr(2,i),Oe.set(s,Ee),Ee+=i}}function hA(t){zt(t.length+9),Hr(2,t.length),Oe.set(t,Ee),Ee+=t.length}function Aoe(t,e){zt(9),typeof t=="bigint"?Ioe(6,t):Hr(6,t),Um(e)}function Poe(t){let e=t.string,r=BigInt(0),o=e.search(/[eE]/);o!==-1&&(r=BigInt(e.slice(o+1)),e=e.slice(0,o));let n=e.indexOf("."),i=n===-1?0:e.length-n-1,s=r-BigInt(i),a=BigInt(e.replace(".",""));zt(9),Oe[Ee++]=196,Hr(4,2),zt(9),s>=-0x20000000000000n&&s<=0x1fffffffffffffn?SA(Number(s)):vA(s),vA(a)}function L6(t){zt(18),Hr(6,1);let e=t.getTime()/1e3;Number.isInteger(e)?SA(e):K6(e)}var yA,boe,bA,WLe,U6,Oe,Od,Ee,Soe,Dm,z6,xoe,B6=_(()=>{Pe();ge();rt();xe();_oe();yA=class extends Fr{write(e,r){Ee=0;let o=B.of(e);Mm(o,r,void 0,this.serdeContext)}flush(){let e=Oe.subarray(0,Ee);return Ee=0,Oe=Roe(U6),Od=new DataView(Oe.buffer,Oe.byteOffset,Oe.byteLength),e}},boe=Symbol.for("@smithy/cbor-struct-cache");bA=typeof Buffer<"u",WLe=new TextEncoder,U6=2048,Oe=bA?Buffer.allocUnsafe(U6):new Uint8Array(U6),Od=new DataView(Oe.buffer,Oe.byteOffset,Oe.byteLength),Ee=0,Soe=2048,Dm=new Map,z6=0,xoe=!1});function qo(t){if(ne>=Kr)throw new Error("unexpected end of CBOR payload.");let e=(fr[ne]&224)>>5;if((fr[ne]&31)===31&&e>=2&&e<=5)return tje(t,e);switch(e){case 0:return sje();case 1:return aje();case 2:return IA();case 3:return Lm();case 4:return XLe(t);case 5:return YLe(t);case 6:return eje(t);case 7:return uje();default:throw new Error(`unexpected CBOR major type ${e}.`)}}function XLe(t){let e=RA(),r=t.isListSchema()?t.getValueSchema():t,o=Array(e);for(let n=0;n<e;++n)o[n]=qo(r);return o}function YLe(t){let e=RA();if(t.isStructSchema())return QLe(t,e,ne);let r=t.isMapSchema()?t.getValueSchema():t,o={};for(let n=0;n<e;++n){let i=Lm();o[i]=qo(r)}return o}function QLe(t,e,r){let o=t.isUnionSchema(),n=_A(t),{memberSchemas:i,encodedKeys:s,memberNames:a}=n,c=s.length,u={},l,d,p=0,f=!1,h=0;for(let y=0;y<e;++y){let w=Ooe(s,c,h);if(w>=0){h=w+1,h>=c&&(h=0);let b=qo(i[w]);b!=null&&(u[a[w]]=b)}else{let b=Lm(),S=qo(B.of(15));b==="__type"&&typeof S=="string"?f=!0:(l=b,d=S,++p)}}if(o){let y=!0;for(let w in u)if(Se(u,w)){y=!1;break}y&&p===1&&(u.$unknown=[l,d])}else if(f){ne=r;let y=B.of(15);for(let w=0;w<e;++w){let b=Lm(),S=qo(y);b in u||(u[b]=S)}}return u}function eje(t){let e=$A(),r=typeof e=="bigint"?Number(e):e;if(r===1){let i=B.of(15),s=qo(i);return Eu(s)}if(r===2||r===3){let i=IA(),s=BigInt(0);for(let a=0;a<i.length;++a)s=s<<BigInt(8)|BigInt(i[a]);return r===3?-s-BigInt(1):s}if(r===4){let i=B.of(15),s=qo(i),[a,c]=s,u=c<0?-1:1,l=BigInt(u)*BigInt(c),d=String(l),p=c<0?"-":"",f;if(typeof a=="number"&&Math.abs(a)<=2**28){let y=a,w="0".repeat(Math.abs(y)+1)+d;f=y===0?w:w.slice(0,w.length+y)+"."+w.slice(y),f=f.replace(/^0+/g,""),f===""&&(f="0"),f[0]==="."&&(f="0"+f),f=p+f}else{let y=BigInt(a);if(d.length===1)f=p+d+"e"+String(y);else{let w=y+BigInt(d.length-1);f=p+d[0]+"."+d.slice(1)+"e"+String(w)}}return yR(f)}let o=B.of(15),n=qo(o);return{tag:Doe(e),value:n}}function tje(t,e){switch(e){case 3:return rje();case 2:return nje();case 4:return oje(t);case 5:return ije(t);default:throw new Error(`unexpected indefinite length for major ${e}.`)}}function rje(){ne+=1;let t=[],e=0;for(;ne<Kr;){if(fr[ne]===255){ne+=1;let o=new Uint8Array(e),n=0;for(let i=0;i<t.length;++i)o.set(t[i],n),n+=t[i].length;return Coe?Buffer.from(o.buffer,o.byteOffset,o.byteLength).toString("utf-8"):W6.decode(o)}let r=IA();t.push(r),e+=r.length}throw new Error("expected break marker.")}function nje(){ne+=1;let t=[],e=0;for(;ne<Kr;){if(fr[ne]===255){ne+=1;let o=new Uint8Array(e),n=0;for(let i=0;i<t.length;++i)o.set(t[i],n),n+=t[i].length;return o}let r=IA();t.push(r),e+=r.length}throw new Error("expected break marker.")}function oje(t){ne+=1;let e=t.isListSchema()?t.getValueSchema():t,r=[];for(;ne<Kr;){if(fr[ne]===255)return ne+=1,r;r.push(qo(e))}throw new Error("expected break marker.")}function ije(t){if(ne+=1,t.isStructSchema()){let o=_A(t),{memberSchemas:n,encodedKeys:i,memberNames:s}=o,a=i.length,c=t.isUnionSchema(),u={},l,d,p=0,f=0;for(;ne<Kr;){if(fr[ne]===255){if(ne+=1,c){let y=!0;for(let w in u)if(Se(u,w)){y=!1;break}y&&p===1&&(u.$unknown=[l,d])}return u}let h=Ooe(i,a,f);if(h>=0){f=h+1,f>=a&&(f=0);let y=qo(n[h]);y!=null&&(u[s[h]]=y)}else{let y=Lm(),w=qo(B.of(15));y!=="__type"&&(l=y,d=w,++p)}}throw new Error("expected break marker.")}let e=t.isMapSchema()?t.getValueSchema():t,r={};for(;ne<Kr;){if(fr[ne]===255)return ne+=1,r;let o=Lm();r[o]=qo(e)}throw new Error("expected break marker.")}function Ooe(t,e,r){let o=t[r];if(ne+o.length<=Kr&&Toe(ne,o))return ne+=o.length,r;for(let n=0;n<e;++n){if(n===r)continue;let i=t[n];if(ne+i.length<=Kr&&Toe(ne,i))return ne+=i.length,n}return-1}function Toe(t,e){let r=e.length;if(fr[t]!==e[0])return!1;for(let o=1;o<r;++o)if(fr[t+o]!==e[o])return!1;return!0}function $A(){let t=fr[ne]&31;if(t<24)return ne+=1,t;switch(t){case 24:return Kr-ne<2&&wc(1),ne+=2,fr[ne-1];case 25:return Kr-ne<3&&wc(2),ne+=3,Ku.getUint16(ne-2);case 26:return Kr-ne<5&&wc(4),ne+=5,Ku.getUint32(ne-4);case 27:{Kr-ne<9&&wc(8),ne+=9;let e=Ku.getUint32(ne-8);return e<2097152?e*4294967296+Ku.getUint32(ne-4):Ku.getBigUint64(ne-8)}default:throw new Error(`unexpected minor value ${t}.`)}}function RA(){let t=$A();return typeof t=="bigint"?Number(t):t}function sje(){let t=$A();return Doe(t)}function aje(){let t=$A();return typeof t=="bigint"?BigInt(-1)-t:-1-t}function IA(){let t=RA();Kr-ne<t&&wc(t);let e=ne;return ne+=t,fr.subarray(e,e+t)}function Lm(){let t=RA();Kr-ne<t&&wc(t);let e=ne;return ne+=t,t<24?cje(e,t):J6?fr.toString("utf-8",e,e+t):W6.decode(fr.subarray(e,e+t))}function cje(t,e){let r=e;for(let s=0;s<e;++s)r=r*31+fr[t+s]|0;let o=r>>>0&X6-1,n=koe[o];if(n!==void 0&&n.length===e){let s=!0;for(let a=0;a<e;++a)if(n.charCodeAt(a)!==fr[t+a]){s=!1;break}if(s)return Z6[o]=uw,n}let i=J6?fr.toString("utf-8",t,t+e):W6.decode(fr.subarray(t,t+e));return Z6[o]!==uw&&(koe[o]=i,Z6[o]=uw),i}function uje(){let t=ne,e=fr[t]&31;switch(e){case 21:return ne=t+1,!0;case 20:return ne=t+1,!1;case 22:return ne=t+1,null;case 23:return ne=t+1,null;case 25:return Kr-t<3&&wc(2),ne=t+3,lje(fr[t+1],fr[t+2]);case 26:return Kr-t<5&&wc(4),ne=t+5,Ku.getFloat32(t+1);case 27:return Kr-t<9&&wc(8),ne=t+9,Ku.getFloat64(t+1);default:throw new Error(`unexpected minor value ${e} for major 7.`)}}function lje(t,e){let r=t>>7,o=(t&124)>>2,n=(t&3)<<8|e,i=r===0?1:-1;return o===0?n===0?0:i*(Math.pow(2,-14)*(n/1024)):o===31?n===0?i*(1/0):NaN:i*(Math.pow(2,o-15)*(1+n/1024))}function Doe(t){if(typeof t=="number")return t;let e=Number(t);return Number.MIN_SAFE_INTEGER<=e&&e<=Number.MAX_SAFE_INTEGER?e:t}function wc(t){throw new Error(`CBOR: length ${t} greater than remaining buffer length.`)}function xA(t,e){if(t.isTimestampSchema()){if(typeof e=="number")return Eu(e);if(typeof e=="object"&&e!==null&&e.tag===1&&"value"in e)return Eu(e.value)}if(t.isBlobSchema()||typeof e>"u"||typeof e=="boolean"||typeof e=="number"||typeof e=="string"||typeof e=="bigint"||typeof e=="symbol"||typeof e!="object"||e===null||"byteLength"in e||e instanceof Date||e instanceof nt||t.isDocumentSchema())return e;if(t.isListSchema()){let o=t.getValueSchema(),n=[];for(let i of e)n.push(xA(o,i));return n}let r={};if(t.isMapSchema()){let o=t.getValueSchema();for(let n in e)Se(e,n)&&(r[n]=xA(o,e[n]))}else if(t.isStructSchema()){let o=t.isUnionSchema(),n;if(o){n=new Set;for(let i in e)Se(e,i)&&i!=="__type"&&n.add(i)}for(let[i,s]of t.structIterator())o&&n.delete(i),e[i]!=null&&(r[i]=xA(s,e[i]));if(o&&n?.size===1){let i=!0;for(let s in r)if(Se(r,s)){i=!1;break}if(i){let s=n.values().next().value;r.$unknown=[s,e[s]]}}else if(typeof e.__type=="string")for(let i in e)Se(e,i)&&(i in r||(r[i]=e[i]))}return r}var EA,Coe,W6,fr,J6,Ku,ne,Kr,X6,koe,Z6,uw,Noe=_(()=>{Pe();ge();rt();xe();B6();EA=class extends Fr{read(e,r){return fr=r,J6=Coe&&r instanceof Buffer,Ku=new DataView(r.buffer,r.byteOffset,r.byteLength),ne=0,Kr=r.length,uw=uw+1&65535,qo(B.of(e))}readValue(e,r){return xA(B.of(e),r)}},Coe=typeof Buffer<"u",W6=new TextDecoder,fr=new Uint8Array(0),J6=!1,Ku=new DataView(new ArrayBuffer(0)),ne=0,Kr=0,X6=2048,koe=new Array(X6),Z6=new Uint16Array(X6),uw=0});var AA,zoe=_(()=>{ge();B6();Noe();AA=class extends Fr{createSerializer(){let e=new yA;return e.setSerdeContext(this.serdeContext),e}createDeserializer(){let e=new EA;return e.setSerdeContext(this.serdeContext),e}}});var lw,Moe=_(()=>{ge();rt();Pe();zoe();N6();lw=class extends na{codec=new AA;serializer=this.codec.createSerializer();deserializer=this.codec.createDeserializer();constructor({defaultNamespace:e,errorTypeRegistries:r}){super({defaultNamespace:e,errorTypeRegistries:r})}getShapeId(){return"smithy.protocols#rpcv2Cbor"}getPayloadCodec(){return this.codec}async serializeRequest(e,r,o){let n=await super.serializeRequest(e,r,o);Object.assign(n.headers,{"content-type":this.getDefaultContentType(),"smithy-protocol":"rpc-v2-cbor",accept:this.getDefaultContentType()}),ii(e.input)==="unit"?(delete n.body,delete n.headers["content-type"]):(n.body||(this.serializer.write(15,{}),n.body=this.serializer.flush()),n.body instanceof Uint8Array&&(n.headers["content-length"]=String(n.body.byteLength)));let{service:i,operation:s}=Bt(o),a=`/service/${i}/operation/${s}`;return n.path.endsWith("/")?n.path+=a.slice(1):n.path+=a,n}async deserializeResponse(e,r,o){return super.deserializeResponse(e,r,o)}async handleError(e,r,o,n,i){let s=sw(o,n)??"Unknown",a=["*"],{defaultNamespace:c}=this.options;a.unshift(c);let[u,l]=s.includes("#")?s.split("#"):[void 0,s];u&&a.unshift(u);let d={$metadata:i,$fault:o.statusCode<500?"client":"server"},p=[this.compositeErrorRegistry];u&&p.push(Zt.for(u)),p.push(Zt.for(c));let[f,h,y]=this.resolveError(l,a,p);if(y==="native"||y==="synthetic"){n.Message&&(n.message=n.Message);let R=y==="synthetic"?new h({name:l}):new Error(l);throw Object.assign(R,d,n)}let w=B.of(f),b=n.message??n.Message??"Unknown",S=new h({}),x={};for(let[R,T]of w.structIterator())x[R]=this.deserializer.readValue(T,n[R]);throw Object.assign(S,d,{$fault:w.getMergedTraits().error,message:b},x)}getDefaultContentType(){return"application/cbor"}}});var Uoe=_(()=>{N6();Moe()});var mi,jm=_(()=>{ve();rt();mi=class{queryCompat;errorRegistry;constructor(e=!1){this.queryCompat=e}resolveRestContentType(e,r){let o=r.getMemberSchemas(),n=Object.values(o).find(i=>!!i.getMergedTraits().httpPayload);if(n){let i=n.getMergedTraits().mediaType;return i||(n.isStringSchema()?"text/plain":n.isBlobSchema()?"application/octet-stream":e)}else if(!r.isUnitSchema()&&Object.values(o).find(s=>{let{httpQuery:a,httpQueryParams:c,httpHeader:u,httpLabel:l,httpPrefixHeaders:d}=s.getMergedTraits();return!a&&!c&&!u&&!l&&d===void 0}))return e}async getErrorSchemaOrThrowBaseException(e,r,o,n,i,s){let a=e;e.includes("#")&&([,a]=e.split("#"));let c={$metadata:i,$fault:o.statusCode<500?"client":"server"};if(!this.errorRegistry)throw new Error("@aws-sdk/core/protocols - error handler not initialized.");try{return{errorSchema:s?.(this.errorRegistry,a)??this.errorRegistry.getSchema(e),errorMetadata:c}}catch{n.message=n.message??n.Message??"UnknownError";let l=this.errorRegistry,d=l.getBaseException();if(d){let h=l.getErrorCtor(d)??Error;throw this.decorateServiceException(Object.assign(new h({name:a}),c),n)}let p=n,f=p?.message??p?.Message??p?.Error?.Message??p?.Error?.message;throw this.decorateServiceException(Object.assign(new Error(f),{name:a},c),n)}}compose(e,r,o){let n=o;r.includes("#")&&([n]=r.split("#"));let i=Zt.for(n),s=Zt.for("smithy.ts.sdk.synthetic."+o);e.copyFrom(i),e.copyFrom(s),this.errorRegistry=e}decorateServiceException(e,r={}){if(this.queryCompat){let o=e.Message??r.Message,n=yd(e,r);o&&(n.message=o);let i=n.Error??{};i.Type=n.Error?.Type,i.Code=n.Error?.Code,i.Message=n.Error?.message??n.Error?.Message??o,n.Error=i;let s=n.$metadata.requestId;return s&&(n.RequestId=s),n}return yd(e,r)}setQueryCompatError(e,r){let o=r.headers?.["x-amzn-query-error"];if(e!==void 0&&o!=null){let[n,i]=o.split(";"),s=Object.keys(e),a={Code:n,Type:i};e.Code=n,e.Type=i;for(let c=0;c<s.length;c++){let u=s[c];a[u==="message"?"Message":u]=e[u]}delete a.__type,e.Error=a}}queryCompatOutput(e,r){e.Error&&(r.Error=e.Error),e.Type&&(r.Type=e.Type),e.Code&&(r.Code=e.Code)}findQueryCompatibleError(e,r){try{return e.getSchema(r)}catch{return e.find(n=>B.of(n).getMergedTraits().awsQueryError?.[0]===r)}}}});var PA,Loe=_(()=>{Uoe();rt();jm();PA=class extends lw{awsQueryCompatible;mixin;constructor({defaultNamespace:e,errorTypeRegistries:r,awsQueryCompatible:o}){super({defaultNamespace:e,errorTypeRegistries:r}),this.awsQueryCompatible=!!o,this.mixin=new mi(this.awsQueryCompatible)}async serializeRequest(e,r,o){let n=await super.serializeRequest(e,r,o);return this.awsQueryCompatible&&(n.headers["x-amzn-query-mode"]="true"),n}async handleError(e,r,o,n,i){this.awsQueryCompatible&&this.mixin.setQueryCompatError(n,o);let s=(()=>{let h=o.headers["x-amzn-query-error"];return h&&this.awsQueryCompatible?h.split(";")[0]:sw(o,n)??"Unknown"})();this.mixin.compose(this.compositeErrorRegistry,s,this.options.defaultNamespace);let{errorSchema:a,errorMetadata:c}=await this.mixin.getErrorSchemaOrThrowBaseException(s,this.options.defaultNamespace,o,n,i,this.awsQueryCompatible?this.mixin.findQueryCompatibleError:void 0),u=B.of(a),l=n.message??n.Message??"UnknownError",d=this.compositeErrorRegistry.getErrorCtor(a)??Error,p=new d({}),f={};for(let[h,y]of u.structIterator())n[h]!=null&&(f[h]=this.deserializer.readValue(y,n[h]));throw this.awsQueryCompatible&&this.mixin.queryCompatOutput(n,f),this.mixin.decorateServiceException(Object.assign(p,c,{$fault:u.getMergedTraits().error,message:l},f),n)}}});var mr,as=_(()=>{mr=class{serdeContext;setSerdeContext(e){this.serdeContext=e}}});var Bu,kA=_(()=>{Bu=class{from;to;keys;constructor(e,r){this.from=e,this.to=r;let o=Object.keys(this.from),n=new Set(o);n.delete("__type"),this.keys=n}mark(e){this.keys.delete(e)}hasUnknown(){return this.keys.size===1&&Object.keys(this.to).length===0}writeUnknown(){if(this.hasUnknown()){let e=this.keys.values().next().value,r=this.from[e];this.to.$unknown=[e,r]}}}});function TA(){if(dw===void 0)try{if(typeof Buffer!="function")dw=!1;else{let t=JSON.parse(Buffer.from([123,125]));dw=t!==null&&typeof t=="object"}}catch{dw=!1}return dw}var dw,Y6=_(()=>{});function Fm(t,e,r){if(r?.source){let o=r.source;if(typeof e=="number")return e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER?pje(o,e)?e:new nt(o,"bigDecimal"):dje(o)?new nt(o,"bigDecimal"):/[eE]/.test(o)?fje(o):BigInt(o)}return e}function dje(t){let e=t.indexOf(".");if(e===-1)return!1;let r=t.search(/[eE]/);if(r===-1)return!0;let o=r-e-1;return parseInt(t.slice(r+1),10)<o}function pje(t,e){if(t===String(e)||Object.is(e,-0))return!0;if(/[eE]/.test(t))return Q6(t)===Q6(String(e));let r=t.replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,""),o=String(e);return r===o?!0:/[eE]/.test(o)?r===Q6(o):!1}function Q6(t){let e=t.startsWith("-"),r=e?t.slice(1):t,o=r.search(/[eE]/),n;if(o===-1)n=r;else{let i=parseInt(r.slice(o+1),10),s=r.slice(0,o),a=s.indexOf("."),c,u;a===-1?(c=s,u=s.length):(c=s.slice(0,a)+s.slice(a+1),u=a),c=c.replace(/0+$/,"")||"0";let l=u+i;c==="0"?n="0":l<=0?n="0."+"0".repeat(-l)+c:l>=c.length?n=c+"0".repeat(l-c.length):n=c.slice(0,l)+"."+c.slice(l)}return n.includes(".")&&(n=n.replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")),(e?"-":"")+n}function fje(t){let e=t.search(/[eE]/),r=parseInt(t.slice(e+1),10),o=t.startsWith("-"),n=t.slice(o?1:0,e),i=n.indexOf("."),s,a;if(i===-1)s=n,a=r;else{s=n.slice(0,i)+n.slice(i+1);let u=n.length-i-1;a=r-u}s=s.replace(/0+$/,"")||"0";let c=BigInt(s)*10n**BigInt(a+(n.replace(".","").length-s.length));return o?-c:c}var CA=_(()=>{xe()});function qm(t){let e=B.of(t),r=e.getSchema();if(Array.isArray(r)&&e.isStructSchema()){if(eq in r)return r[eq];let o=OA(e,new Set);return r[eq]=o,o}return OA(e,new Set)}function OA(t,e){let r=t.getSchema();if(e.has(r))return!1;if(e.add(r),t.isBigIntegerSchema()||t.isBigDecimalSchema())return!0;if(t.isStructSchema()){for(let[,o]of t.structIterator())if(OA(o,e))return!0}else if(t.isListSchema()||t.isMapSchema()){if(OA(t.getValueSchema(),e))return!0}else if(t.isDocumentSchema())return!0;return!1}var eq,DA=_(()=>{rt();eq=Symbol.for("@aws-sdk/reviver")});var NA,tq=_(()=>{ge();xe();NA=(t,e)=>sn(t,e).then(r=>(e?.utf8Encoder??ur)(r))});async function Dd(t,e,r){let o;if(TA()&&typeof t?.[Symbol.asyncIterator]=="function"){let i=await sn(t,e);typeof Buffer=="function"&&(Buffer.isBuffer(i)?o=i:o=Buffer.from(i.buffer,i.byteOffset,i.byteLength))}if(o||(o=await NA(t,e)),o.length===0)return{};let n=r&&qm(r)?Fm:void 0;try{return JSON.parse(o,n)}catch(i){throw i?.name==="SyntaxError"&&Object.defineProperty(i,"$responseBodyText",{value:typeof o=="string"?o:o.toString("utf8")}),i}}var Foe,joe,rq,zA,MA,qoe,Vm=_(()=>{ge();tq();Y6();CA();DA();Foe=async(t,e)=>{let r=await Dd(t,e);return r.message=r.message??r.Message,r},joe=(t,e)=>Object.keys(t).find(r=>r.toLowerCase()===e.toLowerCase()),rq=t=>{let e=t;return typeof e=="number"&&(e=e.toString()),e.indexOf(",")>=0&&(e=e.split(",")[0]),e.indexOf(":")>=0&&(e=e.split(":")[0]),e.indexOf("#")>=0&&(e=e.split("#")[1]),e},zA=(t,e)=>qoe(t,e,["header","code","type"]),MA=(t,e,r=!1)=>qoe(t,e,r?["code","header","type"]:["type","code","header"]),qoe=({headers:t},e,r)=>{for(;r.length>0;)switch(r.shift()){case"header":let n=joe(t??{},"x-amzn-errortype");if(n!==void 0)return rq(t[n]);break;case"code":let i=joe(e??{},"code");if(i&&e[i]!==void 0)return rq(e[i]);break;case"type":if(e?.__type!==void 0)return rq(e.__type);break}}});function hi(t){Object.defineProperty(t,"__proto__",{value:void 0,writable:!0,enumerable:!0,configurable:!0})}var pw=_(()=>{});var Gm,nq=_(()=>{ge();rt();xe();as();kA();Y6();CA();DA();Vm();pw();Gm=class extends mr{settings;constructor(e){super(),this.settings=e}async read(e,r){let o=qm(e)?Fm:void 0,n;if(typeof r=="string"){if(r.length===0)return{};n=JSON.parse(r,o)}else if(r instanceof Uint8Array&&TA()){if(r.byteLength===0)return{};let i=Buffer.isBuffer(r)?r:Buffer.from(r.buffer,r.byteOffset,r.byteLength);n=JSON.parse(i,o)}else n=await Dd(r,this.serdeContext,e);return this._read(e,n)}readObject(e,r){return this._read(e,r)}_read(e,r){let o=r!==null&&typeof r=="object",n=B.of(e);if(o){if(n.isStructSchema())return this._readStruct(n,r);if(Array.isArray(r)&&n.isListSchema()){let s=n.getValueSchema();if(this.needsTransform(s))for(let a=0;a<r.length;++a)r[a]=this._read(s,r[a]);return r}if(n.isMapSchema()){let s=n.getValueSchema(),a=r;if(this.needsTransform(s))for(let c in a)c==="__proto__"&&hi(a),a[c]=this._read(s,a[c]);return a}}if(n.isBlobSchema()&&typeof r=="string")return pr(r);let i=n.getMergedTraits().mediaType;if(n.isStringSchema()&&typeof r=="string"&&i)return i==="application/json"||i.endsWith("+json")?Er.from(r):r;if(n.isTimestampSchema()&&r!=null)switch(qr(n,this.settings)){case 5:return Yf(r);case 6:return xu(r);case 7:return Qf(r);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",r),new Date(r)}if(n.isBigIntegerSchema()&&(typeof r=="number"||typeof r=="string"))return BigInt(r);if(n.isBigDecimalSchema()&&r!=null){if(r instanceof nt)return r;let s=r;return s.type==="bigDecimal"&&"string"in s?new nt(s.string,s.type):new nt(String(r),"bigDecimal")}if(n.isNumericSchema()&&typeof r=="string"){switch(r){case"Infinity":return 1/0;case"-Infinity":return-1/0;case"NaN":return NaN}return r}if(n.isDocumentSchema()&&o)if(Array.isArray(r))for(let s=0;s<r.length;++s){let a=r[s];a instanceof nt||(r[s]=this._read(n,a))}else{let s=r;for(let a in s){a==="__proto__"&&hi(s);let c=s[a];c instanceof nt||(s[a]=this._read(n,c))}}return r}_readStruct(e,r){let o=e.isUnionSchema(),n={},i,s=typeof r.__type=="string",{jsonName:a}=this.settings;a&&s&&(i={});let c;o&&(c=new Bu(r,n));for(let[u,l]of e.structIterator()){let d=u;a&&(d=l.getMergedTraits().jsonName??d,s&&(i[d]=u)),o&&c.mark(d),r[d]!=null&&(n[u]=this._read(l,r[d]))}if(o)c.writeUnknown();else if(s)for(let u in r){let l=r[u],d=a?i[u]??u:u;d in n||(n[d]=l)}return n}needsTransform(e){return!!(e.isBlobSchema()||e.isTimestampSchema()||e.isBigIntegerSchema()||e.isBigDecimalSchema()||e.isDocumentSchema()||e.isStructSchema()||e.isListSchema()||e.isMapSchema()||e.isStringSchema()&&e.getMergedTraits().mediaType)}}});var UA,Voe,Goe=_(()=>{xe();UA=class t extends Uint8Array{string=null;static allocUnsafe(e){if(typeof Buffer=="function"){let r=Buffer.allocUnsafe(e);return new t(r.buffer,r.byteOffset,r.byteLength)}return new t(e)}toString(){return this.s()}valueOf(){return this.s()}includes(e,r){return typeof e=="string"?this.s().includes(e,r):Uint8Array.prototype.includes.call(this,e,r)}indexOf(e,r){return typeof e=="string"?this.s().indexOf(e,r):Uint8Array.prototype.indexOf.call(this,e,r)}lastIndexOf(e,r){if(typeof e=="string")return this.s().lastIndexOf(e,r);let o=Uint8Array.prototype.lastIndexOf;return r!==void 0?o.call(this,e,r):o.call(this,e)}startsWith(e,r){return this.s().startsWith(e,r)}endsWith(e,r){return this.s().endsWith(e,r)}match(e){return this.s().match(e)}replace(e,r){return this.s().replace(e,r)}search(e){return this.s().search(e)}split(e,r){return this.s().split(e,r)}substring(e,r){return this.s().substring(e,r)}trim(){return this.s().trim()}trimStart(){return this.s().trimStart()}trimEnd(){return this.s().trimEnd()}charAt(e){return this.s().charAt(e)}charCodeAt(e){return this.s().charCodeAt(e)}padStart(e,r){return this.s().padStart(e,r)}padEnd(e,r){return this.s().padEnd(e,r)}repeat(e){return this.s().repeat(e)}toUpperCase(){return this.s().toUpperCase()}toLowerCase(){return this.s().toLowerCase()}s(){if(this.string==null){let e=Date.now();e>Voe+6e4&&(console.warn("@aws-sdk/core/protocols - WARN - JsonCodec2: you have called a string method on a Uint8Array request body. It has been automatically converted to string. In a future version this will throw an error."),Voe=e),this.string=ur(this)}return this.string}},Voe=0});function oq(t){return UA.allocUnsafe(t)}var LA,Hoe,Koe,mje,hje,Hm,jA,FA,Boe,gje,yje,vje,ba,Zoe,Km,iq=_(()=>{ge();rt();xe();as();Goe();LA=new TextEncoder,Hoe=123,Koe=125,mje=91,hje=93,Hm=34,jA=58,FA=44,Boe=92,gje=new Uint8Array([116,114,117,101]),yje=new Uint8Array([102,97,108,115,101]),vje=new Uint8Array([110,117,108,108]),ba=new Array(128).fill(null);ba[8]="b";ba[9]="t";ba[10]="n";ba[12]="f";ba[13]="r";ba[34]='"';ba[92]="\\";for(let t=0;t<32;t++)ba[t]===null&&(ba[t]="u00"+t.toString(16).padStart(2,"0"));Zoe=2048;Km=class t extends mr{settings;json;i=0;rootSchema;rawValue;passthrough=!1;constructor(e){super(),this.settings=e,this.json=oq(Zoe)}write(e,r){this.i=0,this.rawValue=r,this.rootSchema=B.of(e),this.passthrough=this.rootSchema.isBlobSchema()||this.rootSchema.isStringSchema(),this.passthrough||this.writeValue(this.rootSchema,r,void 0)}writeDiscriminatedDocument(e,r){this.i=0,this.rootSchema=B.of(e);let o=this.rootSchema;if(o.isStructSchema()&&r!=null&&typeof r=="object"){this.writeValue(o,r,void 0);let n=`"__type":"${o.getName(!0)??"Unknown"}",`,i=n.length;this.ensure(i),this.json.copyWithin(1+i,1,this.i),LA.encodeInto(n,this.json.subarray(1)),this.i+=i}else this.writeValue(o,r,void 0)}flush(){this.rootSchema=void 0;let e=this.i;this.i=0;let r=this.rawValue;if(this.rawValue=void 0,e===0)return r;let o=this.json.subarray(0,e);return this.json=oq(Zoe),o}ensure(e){let{i:r,json:o}=this;if(r+e>o.length){let n=o.length*2;for(;n<r+e;)n*=2;let i=oq(n);i.set(this.json),this.json=i}}writeAscii(e){let r=e.length;this.ensure(r);let{i:o,json:n}=this;for(let i=0;i<r;++i)n[o]=e.charCodeAt(i),o+=1;this.i=o}writeAsciiQuoted(e){let r=e.length;this.ensure(r+4);let{json:o,i:n}=this;o[n++]=Hm;for(let i=0;i<r;++i)o[n++]=e.charCodeAt(i);o[n++]=Hm,this.i=n}writeJsonString(e){this.ensure(e.length*3+2),this.json[this.i++]=Hm;let r=e.length;for(let o=0;o<r;++o){let n=e.charCodeAt(o);if(n>34&&n<92)this.json[this.i++]=n;else if(n<128){let i=ba[n];if(i!==null){this.ensure(i.length+1),this.json[this.i++]=Boe;for(let s=0;s<i.length;s++)this.json[this.i++]=i.charCodeAt(s)}else this.json[this.i++]=n}else if(n>=55296&&n<=56319){let i=o+1<r?e.charCodeAt(o+1):0;if(i>=56320&&i<=57343){this.ensure(4);let{written:s}=LA.encodeInto(e.substring(o,o+2),this.json.subarray(this.i));this.i+=s,++o}else this.ensure(6),this.writeUnicodeEscape(n)}else if(n>=56320&&n<=57343)this.ensure(6),this.writeUnicodeEscape(n);else{let{i,json:s}=this;n<2048?(s[i++]=192|n>>6,s[i++]=128|n&63):(s[i++]=224|n>>12,s[i++]=128|n>>6&63,s[i++]=128|n&63),this.i=i}}this.json[this.i++]=Hm}writeUnicodeEscape(e){let{json:r,i:o}=this;r[o++]=Boe,r[o++]=117;let n=e.toString(16).padStart(4,"0");for(let i=0;i<4;++i)r[o++]=n.charCodeAt(i);this.i=o}static B64=(()=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r=new Uint8Array(64);for(let o=0;o<64;++o)r[o]=e.charCodeAt(o);return r})();writeBase64(e){let r=Math.ceil(e.length/3)*4;this.ensure(r+2);let o=this.json,n=t.B64,i=this.i;o[i++]=Hm;let s=e.length,a=s%3,c=s-a;for(let u=0;u<c;u+=3){let l=e[u],d=e[u+1],p=e[u+2];o[i++]=n[l>>2],o[i++]=n[(l&3)<<4|d>>4],o[i++]=n[(d&15)<<2|p>>6],o[i++]=n[p&63]}if(a===2){let u=e[c],l=e[c+1];o[i++]=n[u>>2],o[i++]=n[(u&3)<<4|l>>4],o[i++]=n[(l&15)<<2],o[i++]=61}else if(a===1){let u=e[c];o[i++]=n[u>>2],o[i++]=n[(u&3)<<4],o[i++]=61,o[i++]=61}o[i++]=Hm,this.i=i}writeValue(e,r,o){if(r==null){if(o?.isStructSchema()){if(r===void 0&&B.of(e).isIdempotencyToken()){this.writeAsciiQuoted(Lo());return}return}this.ensure(4),this.json.set(vje,this.i),this.i+=4;return}let n=B.of(e),i=typeof r=="object";if(n.isStringSchema()){let s=n.getMergedTraits().mediaType;if(s&&(s==="application/json"||s.endsWith("+json"))){this.writeJsonString(Er.from(r).toString());return}}if(i){if(n.isStructSchema()){this.writeStruct(n,r);return}if(Array.isArray(r)&&(n.isListSchema()||n.isDocumentSchema())){this.writeList(n,r,n.isDocumentSchema());return}if(n.isMapSchema()){this.writeMap(n,r,!1);return}if(r instanceof Uint8Array&&(n.isBlobSchema()||n.isDocumentSchema())){this.writeBase64(r);return}if(r instanceof Date&&(n.isTimestampSchema()||n.isDocumentSchema())){this.writeTimestamp(n,r);return}if(r instanceof nt){this.writeAscii(r.string);return}if(n.isDocumentSchema()){Array.isArray(r)?this.writeList(n,r,!0):this.writeMap(n,r,!0);return}let s=JSON.stringify(r);this.writeAscii(s);return}if(typeof r=="string"){if(n.isBlobSchema()){let s=(this.serdeContext?.base64Encoder??Wt)(r);this.writeAsciiQuoted(s);return}this.writeJsonString(r);return}if(typeof r=="number"){if(Math.abs(r)===1/0||Number.isNaN(r)){this.writeAsciiQuoted(String(r));return}let s=String(r);this.writeAscii(s);return}if(typeof r=="boolean"){this.ensure(5);let{i:s,json:a}=this;r?(a.set(gje,s),s+=4):(a.set(yje,s),s+=5),this.i=s;return}if(typeof r=="bigint"){this.writeAscii(r.toString());return}this.writeAscii(String(r))}writeStruct(e,r){this.ensure(2),this.json[this.i++]=Hoe;let o=!1,n=typeof r.__type=="string",i;n&&(i=new Set);for(let[s,a]of e.structIterator()){let c=r[s];if(c==null&&!a.isIdempotencyToken())continue;o&&(this.ensure(1),this.json[this.i++]=FA),o=!0;let u=this.settings.jsonName?a.getMergedTraits().jsonName??s:s;i&&(i.add(s),i.add(u)),this.writeAsciiQuoted(u),this.json[this.i++]=jA,this.writeValue(a,c,e)}if(!o&&e.isUnionSchema()){let{$unknown:s}=r;if(Array.isArray(s)){let[a,c]=s;this.writeAsciiQuoted(a),this.ensure(1),this.json[this.i++]=jA,this.writeValue(15,c,e)}}else if(n)for(let s in r){if(i.has(s))continue;i.add(s);let a=r[s];o&&(this.ensure(1),this.json[this.i++]=FA),o=!0,this.writeAsciiQuoted(s),this.ensure(1),this.json[this.i++]=jA,this.writeValue(15,a,void 0)}this.ensure(1),this.json[this.i++]=Koe}writeList(e,r,o){let n=!!e.getMergedTraits().sparse,i=e.getValueSchema();if(!o&&(i.isStringSchema()||i.isNumericSchema()||i.isBooleanSchema())){let a=!1;for(let u=0;u<r.length;++u){let l=r[u];if(Number.isNaN(l)||l===1/0||l===-1/0||l==null&&!n){a=!0;break}}let c;if(!a)c=JSON.stringify(r);else{let u=[];for(let l=0;l<r.length;++l){let d=r[l];d==null&&!n||(Number.isNaN(d)||d===1/0||d===-1/0?u.push(String(d)):u.push(d))}c=JSON.stringify(u)}this.ensure(c.length*3),this.i+=LA.encodeInto(c,this.json.subarray(this.i)).written;return}this.ensure(2),this.json[this.i++]=mje;let s=!1;for(let a=0;a<r.length;++a){let c=r[a];(o?c===void 0:c==null&&!n)||(s&&(this.ensure(1),this.json[this.i++]=FA),this.writeValue(i,c,void 0),s=!0)}this.ensure(1),this.json[this.i++]=hje}writeMap(e,r,o){let n=!!e.getMergedTraits().sparse,i=e.getValueSchema();if(!o&&(i.isStringSchema()||i.isNumericSchema()||i.isBooleanSchema())){let a;for(let u in r){let l=r[u];Number.isNaN(l)||l===1/0||l===-1/0?((a??={})[u]=l,r[u]=String(l)):l===null&&!n&&((a??={})[u]=null,r[u]=void 0)}let c=JSON.stringify(r);a&&Object.assign(r,a),this.ensure(c.length*3),this.i+=LA.encodeInto(c,this.json.subarray(this.i)).written;return}this.ensure(2),this.json[this.i++]=Hoe;let s=!0;for(let a in r){let c=r[a];(o?c===void 0:c==null&&!n)||(s||(this.ensure(1),this.json[this.i++]=FA),s=!1,this.writeJsonString(a),this.ensure(1),this.json[this.i++]=jA,this.writeValue(i,c,void 0))}this.ensure(1),this.json[this.i++]=Koe}writeTimestamp(e,r){switch(qr(e,this.settings)){case 5:{let n=r.toISOString().replace(".000Z","Z");this.writeAsciiQuoted(n);return}case 6:{this.writeAsciiQuoted(Oo(r));return}case 7:{let n=String(r.getTime()/1e3);this.writeAscii(n);return}default:{let n=String(r.getTime()/1e3);this.writeAscii(n);return}}}}});var Zu,qA=_(()=>{as();nq();iq();Zu=class extends mr{settings;constructor(e){super(),this.settings=e}createSerializer(){let e=new Km(this.settings);return e.setSerdeContext(this.serdeContext),e}createDeserializer(){let e=new Gm(this.settings);return e.setSerdeContext(this.serdeContext),e}}});var Wu,VA=_(()=>{ge();rt();jm();qA();Vm();Wu=class extends na{serializer;deserializer;serviceTarget;codec;mixin;awsQueryCompatible;constructor({defaultNamespace:e,errorTypeRegistries:r,serviceTarget:o,awsQueryCompatible:n,jsonCodec:i}){super({defaultNamespace:e,errorTypeRegistries:r}),this.serviceTarget=o,this.codec=i??new Zu({timestampFormat:{useTrait:!0,default:7},jsonName:!1}),this.serializer=this.codec.createSerializer(),this.deserializer=this.codec.createDeserializer(),this.awsQueryCompatible=!!n,this.mixin=new mi(this.awsQueryCompatible)}async serializeRequest(e,r,o){let n=await super.serializeRequest(e,r,o);return n.path.endsWith("/")||(n.path+="/"),n.headers["content-type"]=`application/x-amz-json-${this.getJsonRpcVersion()}`,n.headers["x-amz-target"]=`${this.serviceTarget}.${e.name}`,this.awsQueryCompatible&&(n.headers["x-amzn-query-mode"]="true"),(ii(e.input)==="unit"||!n.body)&&(n.body="{}"),n}getPayloadCodec(){return this.codec}async handleError(e,r,o,n,i){let{awsQueryCompatible:s}=this;s&&this.mixin.setQueryCompatError(n,o);let a=MA(o,n,s)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,a,this.options.defaultNamespace);let{errorSchema:c,errorMetadata:u}=await this.mixin.getErrorSchemaOrThrowBaseException(a,this.options.defaultNamespace,o,n,i,s?this.mixin.findQueryCompatibleError:void 0),l=B.of(c),d=n.message??n.Message??"UnknownError",p=this.compositeErrorRegistry.getErrorCtor(c)??Error,f=new p({}),h={},y=this.codec.createDeserializer();for(let[w,b]of l.structIterator())n[w]!=null&&(h[w]=y.readObject(b,n[w]));throw s&&this.mixin.queryCompatOutput(n,h),this.mixin.decorateServiceException(Object.assign(f,u,{$fault:l.getMergedTraits().error,message:d},h),n)}}});var GA,Woe=_(()=>{VA();GA=class extends Wu{constructor({defaultNamespace:e,errorTypeRegistries:r,serviceTarget:o,awsQueryCompatible:n,jsonCodec:i}){super({defaultNamespace:e,errorTypeRegistries:r,serviceTarget:o,awsQueryCompatible:n,jsonCodec:i})}getShapeId(){return"aws.protocols#awsJson1_0"}getJsonRpcVersion(){return"1.0"}getDefaultContentType(){return"application/x-amz-json-1.0"}}});var HA,Joe=_(()=>{VA();HA=class extends Wu{constructor({defaultNamespace:e,errorTypeRegistries:r,serviceTarget:o,awsQueryCompatible:n,jsonCodec:i}){super({defaultNamespace:e,errorTypeRegistries:r,serviceTarget:o,awsQueryCompatible:n,jsonCodec:i})}getShapeId(){return"aws.protocols#awsJson1_1"}getJsonRpcVersion(){return"1.1"}getDefaultContentType(){return"application/x-amz-json-1.1"}}});var Sa,Xoe=_(()=>{ge();rt();jm();qA();Vm();Sa=class extends Tu{serializer;deserializer;codec;mixin=new mi;constructor({defaultNamespace:e,errorTypeRegistries:r,jsonCodec:o}){super({defaultNamespace:e,errorTypeRegistries:r});let n={timestampFormat:{useTrait:!0,default:7},httpBindings:!0,jsonName:!0};this.codec=o??new Zu(n),this.serializer=new Du(this.codec.createSerializer(),n),this.deserializer=new Ou(this.codec.createDeserializer(),n)}getShapeId(){return"aws.protocols#restJson1"}getPayloadCodec(){return this.codec}setSerdeContext(e){this.codec.setSerdeContext(e),super.setSerdeContext(e)}async serializeRequest(e,r,o){let n=await super.serializeRequest(e,r,o),i=B.of(e.input);if(!n.headers["content-type"]){let s=this.mixin.resolveRestContentType(this.getDefaultContentType(),i);s&&(n.headers["content-type"]=s)}return n.body==null&&n.headers["content-type"]===this.getDefaultContentType()&&(n.body="{}"),n}async deserializeResponse(e,r,o){let n=await super.deserializeResponse(e,r,o),i=B.of(e.output);for(let[s,a]of i.structIterator())a.getMemberTraits().httpPayload&&!(s in n)&&(n[s]=null);return n}async handleError(e,r,o,n,i){let s=zA(o,n)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,s,this.options.defaultNamespace);let{errorSchema:a,errorMetadata:c}=await this.mixin.getErrorSchemaOrThrowBaseException(s,this.options.defaultNamespace,o,n,i),u=B.of(a),l=n.message??n.Message??"UnknownError",d=this.compositeErrorRegistry.getErrorCtor(a)??Error,p=new d({});await this.deserializeHttpMessage(a,r,o,n);let f={},h=this.codec.createDeserializer();for(let[y,w]of u.structIterator()){let b=w.getMergedTraits().jsonName??y;f[y]=h.readObject(w,n[b])}throw this.mixin.decorateServiceException(Object.assign(p,c,{$fault:u.getMergedTraits().error,message:l},f),n)}getDefaultContentType(){return"application/json"}}});var Bm,sq=_(()=>{ge();rt();xe();xe();as();kA();CA();DA();Vm();pw();Bm=class extends mr{settings;constructor(e){super(),this.settings=e}async read(e,r){let o=qm(e)?Fm:void 0;return this._read(e,typeof r=="string"?JSON.parse(r,o):await Dd(r,this.serdeContext,e))}readObject(e,r){return this._read(e,r)}_read(e,r){let o=r!==null&&typeof r=="object",n=B.of(e);if(o){if(n.isStructSchema()){let s=r,a=n.isUnionSchema(),c={},u,{jsonName:l}=this.settings;l&&(u={});let d;a&&(d=new Bu(s,c));for(let[p,f]of n.structIterator()){let h=p;l&&(h=f.getMergedTraits().jsonName??h,u[h]=p),a&&d.mark(h),s[h]!=null&&(c[p]=this._read(f,s[h]))}if(a)d.writeUnknown();else if(typeof s.__type=="string")for(let p in s){let f=s[p],h=l?u[p]??p:p;h in c||(c[h]=f)}return c}if(Array.isArray(r)&&n.isListSchema()){let s=n.getValueSchema(),a=[];for(let c of r)a.push(this._read(s,c));return a}if(n.isMapSchema()){let s=n.getValueSchema(),a={};for(let c in r)c==="__proto__"&&hi(a),a[c]=this._read(s,r[c]);return a}}if(n.isBlobSchema()&&typeof r=="string")return pr(r);let i=n.getMergedTraits().mediaType;if(n.isStringSchema()&&typeof r=="string"&&i)return i==="application/json"||i.endsWith("+json")?Er.from(r):r;if(n.isTimestampSchema()&&r!=null)switch(qr(n,this.settings)){case 5:return Yf(r);case 6:return xu(r);case 7:return Qf(r);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",r),new Date(r)}if(n.isBigIntegerSchema()&&(typeof r=="number"||typeof r=="string"))return BigInt(r);if(n.isBigDecimalSchema()&&r!=null){if(r instanceof nt)return r;let s=r;return s.type==="bigDecimal"&&"string"in s?new nt(s.string,s.type):new nt(String(r),"bigDecimal")}if(n.isNumericSchema()&&typeof r=="string"){switch(r){case"Infinity":return 1/0;case"-Infinity":return-1/0;case"NaN":return NaN}return r}if(n.isDocumentSchema())if(o){let s=Array.isArray(r)?[]:{};for(let a in r){a==="__proto__"&&hi(s);let c=r[a];c instanceof nt?s[a]=c:s[a]=this._read(n,c)}return s}else return structuredClone(r);return r}}});var Yoe,KA,Qoe=_(()=>{xe();Yoe="\u039D",KA=class{values=new Map;counter=0;stage=0;createReplacer(){if(this.stage===1)throw new Error("@aws-sdk/core/protocols - JsonReplacer already created.");if(this.stage===2)throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");return this.stage=1,(e,r)=>{if(r instanceof nt){let o=`${Yoe+"nv"+this.counter++}_`+r.string;return this.values.set(`"${o}"`,r.string),o}if(typeof r=="bigint"){let o=r.toString(),n=`${Yoe+"b"+this.counter++}_`+o;return this.values.set(`"${n}"`,o),n}return r}}replaceInJson(e){if(this.stage===0)throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet.");if(this.stage===2)throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");if(this.stage=2,this.counter===0)return e;for(let[r,o]of this.values)e=e.replace(r,o);return e}}});var Zm,aq=_(()=>{ge();rt();xe();as();Qoe();pw();Zm=class extends mr{settings;buffer;useReplacer=!1;rootSchema;constructor(e){super(),this.settings=e}write(e,r){this.rootSchema=B.of(e),this.buffer=this._write(this.rootSchema,r)}flush(){let{rootSchema:e,useReplacer:r}=this;if(this.rootSchema=void 0,this.useReplacer=!1,e?.isStructSchema()||e?.isDocumentSchema()){if(!r)return JSON.stringify(this.buffer);let o=new KA;return o.replaceInJson(JSON.stringify(this.buffer,o.createReplacer(),0))}return this.buffer}writeDiscriminatedDocument(e,r){this.write(e,r),typeof this.buffer=="object"&&(this.buffer.__type=B.of(e).getName(!0))}_write(e,r,o){let n=r!==null&&typeof r=="object",i=B.of(e);if(n){if(i.isStructSchema()){let s=r,a={},{jsonName:c}=this.settings,u;c&&(u={});let l=0;for(let[d,p]of i.structIterator()){let f=this._write(p,s[d],i);if(f!==void 0){let h=d;c&&(h=p.getMergedTraits().jsonName??d,u[d]=h),a[h]=f,l++}}if(i.isUnionSchema()&&l===0){let{$unknown:d}=s;if(Array.isArray(d)){let[p,f]=d;p==="__proto__"&&hi(a),a[p]=this._write(15,f)}}else if(typeof s.__type=="string")for(let d in s){let p=s[d],f=c?u[d]??d:d;f in a||(a[f]=this._write(15,p))}return a}if(Array.isArray(r)&&i.isListSchema()){let s=i.getValueSchema(),a=[],c=!!i.getMergedTraits().sparse;for(let u of r)(c||u!=null)&&a.push(this._write(s,u));return a}if(i.isMapSchema()){let s=i.getValueSchema(),a={},c=!!i.getMergedTraits().sparse;for(let u in r){let l=r[u];(c||l!=null)&&(u==="__proto__"&&hi(a),a[u]=this._write(s,l))}return a}if(r instanceof Uint8Array&&i.isBlobSchema())return i===this.rootSchema?r:(this.serdeContext?.base64Encoder??Wt)(r);if(r instanceof Date&&(i.isTimestampSchema()||i.isDocumentSchema()))switch(qr(i,this.settings)){case 5:return r.toISOString().replace(".000Z","Z");case 6:return Oo(r);case 7:return r.getTime()/1e3;default:return console.warn("Missing timestamp format, using epoch seconds",r),r.getTime()/1e3}r instanceof nt&&(this.useReplacer=!0)}if(!(r===null&&o?.isStructSchema())){if(i.isStringSchema()){if(typeof r>"u"&&i.isIdempotencyToken())return Lo();let s=i.getMergedTraits().mediaType;return r!=null&&s&&(s==="application/json"||s.endsWith("+json"))?Er.from(r):r}if(typeof r=="number")return Math.abs(r)===1/0||isNaN(r)?String(r):r;if(typeof r=="string"&&i.isBlobSchema())return i===this.rootSchema?r:(this.serdeContext?.base64Encoder??Wt)(r);if(typeof r=="bigint"&&(this.useReplacer=!0),i.isDocumentSchema())if(n){if(r instanceof Uint8Array)return(this.serdeContext?.base64Encoder??Wt)(r);let s=Array.isArray(r)?[]:{};for(let a in r){let c=r[a];a==="__proto__"&&hi(s),c instanceof nt?(this.useReplacer=!0,s[a]=c):s[a]=this._write(i,c)}return s}else return structuredClone(r);return r}}}});var BA,eie=_(()=>{as();sq();aq();BA=class extends mr{settings;constructor(e){super(),this.settings=e}createSerializer(){let e=new Zm(this.settings);return e.setSerdeContext(this.serdeContext),e}createDeserializer(){let e=new Bm(this.settings);return e.setSerdeContext(this.serdeContext),e}}});var JA=U(WA=>{var wje=/[&<>"]/g,_je={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"};function bje(t){return t.replace(wje,e=>_je[e])}var Sje=/[&"'<>\r\n\u0085\u2028]/g,xje={"&":"&amp;",'"':"&quot;","'":"&apos;","<":"&lt;",">":"&gt;","\r":"&#x0D;","\n":"&#x0A;","\x85":"&#x85;","\u2028":"&#x2028;"};function Eje(t){return t.replace(Sje,e=>xje[e])}var ZA=class{value;constructor(e){this.value=e}toString(){return Eje(""+this.value)}},uq=class t{name;children;attributes={};static of(e,r,o){let n=new t(e);return r!==void 0&&n.addChildNode(new ZA(r)),o!==void 0&&n.withName(o),n}constructor(e,r=[]){this.name=e,this.children=r}withName(e){return this.name=e,this}addAttribute(e,r){return this.attributes[e]=r,this}addChildNode(e){return this.children.push(e),this}removeAttribute(e){return delete this.attributes[e],this}n(e){return this.name=e,this}c(e){return this.children.push(e),this}a(e,r){return r!=null&&(this.attributes[e]=r),this}cc(e,r,o=r){if(e[r]!=null){let n=t.of(r,e[r]).withName(o);this.c(n)}}l(e,r,o,n){e[r]!=null&&n().map(s=>{s.withName(o),this.c(s)})}lc(e,r,o,n){if(e[r]!=null){let i=n(),s=new t(o);i.map(a=>{s.c(a)}),this.c(s)}}toString(){let e=!!this.children.length,r=`<${this.name}`,o=this.attributes;for(let n of Object.keys(o)){let i=o[n];i!=null&&(r+=` ${n}="${bje(""+i)}"`)}return r+=e?`>${this.children.map(n=>n.toString()).join("")}</${this.name}>`:"/>"}};function cq(t){Object.defineProperty(t,"__proto__",{value:void 0,writable:!0,enumerable:!0,configurable:!0})}function $je(t){return new lq(t).parse()}var lq=class t{x;i=0;z;constructor(e){this.x=e,this.x=e.replace(/\r\n?/g,`
45
+ `))throw new Td("Authorization token contains invalid \\r\\n sequence.");return t};moe.fromHttp=GLe});function HLe(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sso-oauth",region:t.region},propertiesExtractor:(e,r)=>({signingProperties:{config:e,context:r}})}}function KLe(t){return{schemeId:"smithy.api#noAuth"}}var hoe,goe,yoe,C6=_(()=>{Pn();ve();hoe=async(t,e,r)=>({operation:Bt(e).operation,region:await jt(t.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});goe=t=>{let e=[];return t.operation==="CreateToken"?e.push(KLe(t)):e.push(HLe(t)),e},yoe=t=>{let e=wa(t);return Object.assign(e,{authSchemePreference:jt(t.authSchemePreference??[])})}});var voe,woe,O6=_(()=>{voe=t=>Object.assign(t,{useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,defaultSigningName:"sso-oauth"}),woe={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}});var Hu,iw=_(()=>{Hu={name:"@aws-sdk/nested-clients",version:"3.997.46",description:"Nested clients for AWS SDK packages.",homepage:"https://github.com/aws/aws-sdk-js-v3/tree/main/packages/nested-clients",license:"Apache-2.0",author:{name:"AWS SDK for JavaScript Team",url:"https://aws.amazon.com/sdk-for-javascript/"},repository:{type:"git",url:"https://github.com/aws/aws-sdk-js-v3.git",directory:"packages/nested-clients"},files:["./cognito-identity.d.ts","./cognito-identity.js","./signin.d.ts","./signin.js","./sso-oidc.d.ts","./sso-oidc.js","./sso.d.ts","./sso.js","./sts.d.ts","./sts.js","dist-*/**"],sideEffects:!1,main:"./dist-cjs/index.js",module:"./dist-es/index.js",browser:{"./dist-es/submodules/cognito-identity/runtimeConfig":"./dist-es/submodules/cognito-identity/runtimeConfig.browser","./dist-es/submodules/signin/runtimeConfig":"./dist-es/submodules/signin/runtimeConfig.browser","./dist-es/submodules/sso-oidc/runtimeConfig":"./dist-es/submodules/sso-oidc/runtimeConfig.browser","./dist-es/submodules/sso/runtimeConfig":"./dist-es/submodules/sso/runtimeConfig.browser","./dist-es/submodules/sts/runtimeConfig":"./dist-es/submodules/sts/runtimeConfig.browser"},types:"./dist-types/index.d.ts",typesVersions:{"<4.5":{"dist-types/*":["dist-types/ts3.4/*"],"*":["dist-types/ts3.4/submodules/*/index.d.ts"]}},"react-native":{},exports:{"./package.json":"./package.json","./sso-oidc":{types:"./dist-types/submodules/sso-oidc/index.d.ts",module:"./dist-es/submodules/sso-oidc/index.js",node:"./dist-cjs/submodules/sso-oidc/index.js",import:"./dist-es/submodules/sso-oidc/index.js",require:"./dist-cjs/submodules/sso-oidc/index.js"},"./sts":{types:"./dist-types/submodules/sts/index.d.ts",module:"./dist-es/submodules/sts/index.js",node:"./dist-cjs/submodules/sts/index.js",import:"./dist-es/submodules/sts/index.js",require:"./dist-cjs/submodules/sts/index.js"},"./signin":{types:"./dist-types/submodules/signin/index.d.ts",module:"./dist-es/submodules/signin/index.js",node:"./dist-cjs/submodules/signin/index.js",import:"./dist-es/submodules/signin/index.js",require:"./dist-cjs/submodules/signin/index.js"},"./cognito-identity":{types:"./dist-types/submodules/cognito-identity/index.d.ts",module:"./dist-es/submodules/cognito-identity/index.js",node:"./dist-cjs/submodules/cognito-identity/index.js",import:"./dist-es/submodules/cognito-identity/index.js",require:"./dist-cjs/submodules/cognito-identity/index.js"},"./sso":{types:"./dist-types/submodules/sso/index.d.ts",module:"./dist-es/submodules/sso/index.js",node:"./dist-cjs/submodules/sso/index.js",import:"./dist-es/submodules/sso/index.js",require:"./dist-cjs/submodules/sso/index.js"}},scripts:{build:"concurrently 'yarn:build:types' 'yarn:build:es' && yarn build:cjs","build:cjs":"node ../../scripts/compilation/inline","build:es":"premove dist-es && tsc -p tsconfig.es.json","build:include:deps":'yarn g:turbo run build -F="$npm_package_name"',"build:types":"premove dist-types && tsc -p tsconfig.types.json","build:types:downlevel":"downlevel-dts dist-types dist-types/ts3.4",clean:"premove dist-cjs dist-es dist-types",lint:"node ../../scripts/validation/submodules-linter.js",prebuild:"yarn lint",test:"yarn g:vitest run","test:watch":"yarn g:vitest watch"},dependencies:{"@aws-sdk/core":"^3.978.1","@aws-sdk/signature-v4-multi-region":"^3.996.47","@aws-sdk/types":"^3.974.6","@smithy/core":"^3.35.0","@smithy/fetch-http-handler":"^5.8.0","@smithy/node-http-handler":"^4.12.1","@smithy/types":"^4.19.0",tslib:"^2.6.2"},devDependencies:{concurrently:"7.0.0","downlevel-dts":"0.10.1",premove:"4.0.0",typescript:"~7.0.2"},engines:{node:">=20.0.0"}}});var D6,_oe=_(()=>{D6=Symbol("@smithy/core/cbor::tagSymbol")});var sw,N6=_(()=>{sw=(t,e)=>{let r=o=>{let n=o;return typeof n=="number"&&(n=n.toString()),n.indexOf(",")>=0&&(n=n.split(",")[0]),n.indexOf(":")>=0&&(n=n.split(":")[0]),n};if(e.__type!==void 0)return r(e.__type)}});function _A(t){let e=t.getSchema(),r=e[boe];if(r)return r;let o=[],n=[];for(let[a,c]of t.structIterator())o.push(a),n.push(c);let i=new Array(o.length);for(let a=0;a<o.length;++a)i[a]=ZLe(o[a]);let s={memberNames:o,memberSchemas:n,encodedKeys:i};return e[boe]=s,s}function ZLe(t){let e;bA?e=Buffer.from(t,"utf-8"):e=new TextEncoder().encode(t);let r=e.length,o;r<24?o=1:r<256?o=2:o=3;let n=new Uint8Array(o+r);return o===1?n[0]=96|r:o===2?(n[0]=120,n[1]=r):(n[0]=121,n[1]=r>>8,n[2]=r&255),n.set(e,o),n}function Roe(t){return bA?Buffer.allocUnsafe(t):new Uint8Array(t)}function Mm(t,e,r,o){if(e==null){if(e===void 0&&t.isIdempotencyToken()){_a(Lo());return}zt(1),Oe[Ee++]=246;return}if(t.isUnitSchema()){zt(1),Hr(5,0);return}if(typeof e=="object"){if(t.isBlobSchema()&&e instanceof Uint8Array){hA(e);return}if(t.isTimestampSchema()&&e instanceof Date){L6(e);return}if(t.isStructSchema()){JLe(t,e,o);return}if(Array.isArray(e)&&(t.isListSchema()||t.isDocumentSchema())){Eoe(t,e,t.isDocumentSchema(),o);return}if(t.isMapSchema()){M6(t,e,!1,o);return}if(e instanceof Date){L6(e);return}if(e instanceof Uint8Array){hA(e);return}if(e instanceof nt){Poe(e);return}if(e[D6]){let i=e;Aoe(i.tag,i.value);return}if(t.isDocumentSchema()){Array.isArray(e)?Eoe(t,e,!0,o):M6(t,e,!0,o);return}if(t.isBigDecimalSchema()){Um(e);return}M6(t,e,!0,o);return}if(typeof e=="string"){if(t.isBlobSchema()){let i=(o?.base64Decoder??fr)(e);hA(i);return}_a(e);return}if(typeof e=="number"){zt(9),Number.isInteger(e)&&e>=-9007199254740992&&e<=9007199254740991?SA(e):K6(e);return}if(typeof e=="boolean"){zt(1),Oe[Ee++]=224|(e?21:20);return}if(typeof e=="bigint"){vA(e);return}_a(String(e))}function JLe(t,e,r){if(t.isUnionSchema()){let d=!1;for(let[p,f]of t.structIterator()){let h=e[p];if(h!=null){zt(9),Hr(5,1),_a(p),Mm(f,h,t,r),d=!0;break}}if(!d){let{$unknown:p}=e;Array.isArray(p)?(zt(9),Hr(5,1),_a(p[0]),Um(p[1])):(zt(9),Hr(5,0))}return}let o=_A(t),{memberNames:n,memberSchemas:i,encodedKeys:s}=o,a=n.length,c;a<24?c=1:a<256?c=2:c=3,zt(c);let u=Ee;Ee+=c;let l=0;for(let d=0;d<a;++d){let p=e[n[d]];if(p==null&&!i[d].isIdempotencyToken())continue;let f=s[d];zt(f.length),Oe.set(f,Ee),Ee+=f.length,Mm(i[d],p,t,r),++l}if(typeof e.__type=="string")for(let d in e)Se(e,d)&&(n.includes(d)||(_a(d),Um(e[d]),++l));c===1?Oe[u]=160|l:c===2?(Oe[u]=184,Oe[u+1]=l):(Oe[u]=185,Oe[u+1]=l>>8,Oe[u+2]=l&255)}function Eoe(t,e,r,o){let n=!!t.getMergedTraits().sparse,i=t.getValueSchema();if(r||n){let s=[];for(let a=0;a<e.length;++a){let c=e[a];r?c!==void 0&&s.push(c):(c!=null||n)&&s.push(c)}zt(9),Hr(4,s.length);for(let a=0;a<s.length;++a)Mm(i,s[a],void 0,o)}else{let s=0;for(let a=0;a<e.length;++a)e[a]!=null&&++s;zt(9),Hr(4,s);for(let a=0;a<e.length;++a)e[a]!=null&&Mm(i,e[a],void 0,o)}}function M6(t,e,r,o){let n=!!t.getMergedTraits().sparse,i=t.getValueSchema(),s=[];for(let a in e){if(!Se(e,a))continue;let c=e[a];(r?c!==void 0:c!=null||n)&&s.push(a)}zt(9),Hr(5,s.length);for(let a=0;a<s.length;++a){let c=s[a];_a(c),Mm(i,e[c],void 0,o)}}function Um(t){if(t==null){zt(1),Oe[Ee++]=246;return}if(typeof t=="string"){_a(t);return}if(typeof t=="number"){zt(9),Number.isInteger(t)&&t>=-9007199254740992&&t<=9007199254740991?SA(t):K6(t);return}if(typeof t=="boolean"){zt(1),Oe[Ee++]=224|(t?21:20);return}if(typeof t=="bigint"){vA(t);return}if(t instanceof Uint8Array){hA(t);return}if(t instanceof Date){L6(t);return}if(t instanceof nt){Poe(t);return}if(t[D6]){let e=t;Aoe(e.tag,e.value);return}if(Array.isArray(t)){zt(9),Hr(4,t.length);for(let e=0;e<t.length;++e)Um(t[e]);return}if(typeof t=="object"){let e=Object.keys(t);zt(9),Hr(5,e.length);for(let r=0;r<e.length;++r)_a(e[r]),Um(t[e[r]]);return}_a(String(t))}function zt(t){if(Ee+t>Oe.length){let e=Oe.length*2;for(;e<Ee+t;)e*=2;let r=Roe(e);r.set(Oe.subarray(0,Ee)),Oe=r,Od=new DataView(r.buffer,r.byteOffset,r.byteLength)}}function Hr(t,e){if(e<24)Oe[Ee++]=t<<5|e;else if(e<256)Oe[Ee++]=t<<5|24,Oe[Ee++]=e;else if(e<65536)Oe[Ee++]=t<<5|25,Oe[Ee++]=e>>8,Oe[Ee++]=e&255;else if(e<4294967296)Oe[Ee++]=t<<5|26,Od.setUint32(Ee,e),Ee+=4;else{Oe[Ee++]=t<<5|27;let r=e/4294967296|0,o=e-r*4294967296|0;Od.setUint32(Ee,r),Od.setUint32(Ee+4,o),Ee+=8}}function Ioe(t,e){let r=Number(e);if(r<4294967296){Hr(t,r);return}Oe[Ee++]=t<<5|27,Od.setBigUint64(Ee,e),Ee+=8}function _a(t){let e=t.length;if(e<=23){let r=Dm.get(t);if(r){zt(r.bytes.length),Oe.set(r.bytes,Ee),Ee+=r.bytes.length,r.epoch=z6;return}let o=Ee;$oe(t,e);let n=Ee,i=Uint8Array.prototype.slice.call(Oe,o,n);if(Dm.size>=Soe){if(xoe)return;let s=0;for(let[a,c]of Dm){if(s>=1024)break;c.epoch!==z6&&(Dm.delete(a),++s)}if(s===0){xoe=!0;return}}Dm.size<Soe&&Dm.set(t,{epoch:z6,bytes:i});return}$oe(t,e)}function $oe(t,e){if(bA){let r=e*3;zt(r+9);let o=Buffer.byteLength(t);Hr(3,o),Ee+=Oe.write(t,Ee)}else{let r=e*3;zt(r+9);let o=Ee,i=WLe.encodeInto(t,Oe.subarray(o+9)).written,s;i<24?s=1:i<256?s=2:i<65536?s=3:i<4294967296?s=5:s=9,s<9&&Oe.copyWithin(o+s,o+9,o+9+i),Ee=o,Hr(3,i),Ee+=i}}function K6(t){zt(9),Oe[Ee++]=251,Od.setFloat64(Ee,t),Ee+=8}function SA(t){zt(9);let e=t>=0,r=e?0:1,o=e?t:-t-1;Hr(r,o)}function vA(t){let e=t>=0,r=e?0:1,o=e?t:-t-BigInt(1);if(o<BigInt("18446744073709551616"))zt(9),Ioe(r,o);else{let n=o.toString(2),i=Math.ceil(n.length/8),s=new Uint8Array(i),a=o;for(let c=i-1;c>=0;--c)s[c]=Number(a&BigInt(255)),a>>=BigInt(8);zt(i+16),Oe[Ee++]=e?194:195,Hr(2,i),Oe.set(s,Ee),Ee+=i}}function hA(t){zt(t.length+9),Hr(2,t.length),Oe.set(t,Ee),Ee+=t.length}function Aoe(t,e){zt(9),typeof t=="bigint"?Ioe(6,t):Hr(6,t),Um(e)}function Poe(t){let e=t.string,r=BigInt(0),o=e.search(/[eE]/);o!==-1&&(r=BigInt(e.slice(o+1)),e=e.slice(0,o));let n=e.indexOf("."),i=n===-1?0:e.length-n-1,s=r-BigInt(i),a=BigInt(e.replace(".",""));zt(9),Oe[Ee++]=196,Hr(4,2),zt(9),s>=-0x20000000000000n&&s<=0x1fffffffffffffn?SA(Number(s)):vA(s),vA(a)}function L6(t){zt(18),Hr(6,1);let e=t.getTime()/1e3;Number.isInteger(e)?SA(e):K6(e)}var yA,boe,bA,WLe,U6,Oe,Od,Ee,Soe,Dm,z6,xoe,B6=_(()=>{Pe();ge();rt();xe();_oe();yA=class extends Fr{write(e,r){Ee=0;let o=B.of(e);Mm(o,r,void 0,this.serdeContext)}flush(){let e=Oe.subarray(0,Ee);return Ee=0,Oe=Roe(U6),Od=new DataView(Oe.buffer,Oe.byteOffset,Oe.byteLength),e}},boe=Symbol.for("@smithy/cbor-struct-cache");bA=typeof Buffer<"u",WLe=new TextEncoder,U6=2048,Oe=bA?Buffer.allocUnsafe(U6):new Uint8Array(U6),Od=new DataView(Oe.buffer,Oe.byteOffset,Oe.byteLength),Ee=0,Soe=2048,Dm=new Map,z6=0,xoe=!1});function qo(t){if(ne>=Kr)throw new Error("unexpected end of CBOR payload.");let e=(mr[ne]&224)>>5;if((mr[ne]&31)===31&&e>=2&&e<=5)return tje(t,e);switch(e){case 0:return sje();case 1:return aje();case 2:return IA();case 3:return Lm();case 4:return XLe(t);case 5:return YLe(t);case 6:return eje(t);case 7:return uje();default:throw new Error(`unexpected CBOR major type ${e}.`)}}function XLe(t){let e=RA(),r=t.isListSchema()?t.getValueSchema():t,o=Array(e);for(let n=0;n<e;++n)o[n]=qo(r);return o}function YLe(t){let e=RA();if(t.isStructSchema())return QLe(t,e,ne);let r=t.isMapSchema()?t.getValueSchema():t,o={};for(let n=0;n<e;++n){let i=Lm();o[i]=qo(r)}return o}function QLe(t,e,r){let o=t.isUnionSchema(),n=_A(t),{memberSchemas:i,encodedKeys:s,memberNames:a}=n,c=s.length,u={},l,d,p=0,f=!1,h=0;for(let y=0;y<e;++y){let w=Ooe(s,c,h);if(w>=0){h=w+1,h>=c&&(h=0);let b=qo(i[w]);b!=null&&(u[a[w]]=b)}else{let b=Lm(),S=qo(B.of(15));b==="__type"&&typeof S=="string"?f=!0:(l=b,d=S,++p)}}if(o){let y=!0;for(let w in u)if(Se(u,w)){y=!1;break}y&&p===1&&(u.$unknown=[l,d])}else if(f){ne=r;let y=B.of(15);for(let w=0;w<e;++w){let b=Lm(),S=qo(y);b in u||(u[b]=S)}}return u}function eje(t){let e=$A(),r=typeof e=="bigint"?Number(e):e;if(r===1){let i=B.of(15),s=qo(i);return Eu(s)}if(r===2||r===3){let i=IA(),s=BigInt(0);for(let a=0;a<i.length;++a)s=s<<BigInt(8)|BigInt(i[a]);return r===3?-s-BigInt(1):s}if(r===4){let i=B.of(15),s=qo(i),[a,c]=s,u=c<0?-1:1,l=BigInt(u)*BigInt(c),d=String(l),p=c<0?"-":"",f;if(typeof a=="number"&&Math.abs(a)<=2**28){let y=a,w="0".repeat(Math.abs(y)+1)+d;f=y===0?w:w.slice(0,w.length+y)+"."+w.slice(y),f=f.replace(/^0+/g,""),f===""&&(f="0"),f[0]==="."&&(f="0"+f),f=p+f}else{let y=BigInt(a);if(d.length===1)f=p+d+"e"+String(y);else{let w=y+BigInt(d.length-1);f=p+d[0]+"."+d.slice(1)+"e"+String(w)}}return yR(f)}let o=B.of(15),n=qo(o);return{tag:Doe(e),value:n}}function tje(t,e){switch(e){case 3:return rje();case 2:return nje();case 4:return oje(t);case 5:return ije(t);default:throw new Error(`unexpected indefinite length for major ${e}.`)}}function rje(){ne+=1;let t=[],e=0;for(;ne<Kr;){if(mr[ne]===255){ne+=1;let o=new Uint8Array(e),n=0;for(let i=0;i<t.length;++i)o.set(t[i],n),n+=t[i].length;return Coe?Buffer.from(o.buffer,o.byteOffset,o.byteLength).toString("utf-8"):W6.decode(o)}let r=IA();t.push(r),e+=r.length}throw new Error("expected break marker.")}function nje(){ne+=1;let t=[],e=0;for(;ne<Kr;){if(mr[ne]===255){ne+=1;let o=new Uint8Array(e),n=0;for(let i=0;i<t.length;++i)o.set(t[i],n),n+=t[i].length;return o}let r=IA();t.push(r),e+=r.length}throw new Error("expected break marker.")}function oje(t){ne+=1;let e=t.isListSchema()?t.getValueSchema():t,r=[];for(;ne<Kr;){if(mr[ne]===255)return ne+=1,r;r.push(qo(e))}throw new Error("expected break marker.")}function ije(t){if(ne+=1,t.isStructSchema()){let o=_A(t),{memberSchemas:n,encodedKeys:i,memberNames:s}=o,a=i.length,c=t.isUnionSchema(),u={},l,d,p=0,f=0;for(;ne<Kr;){if(mr[ne]===255){if(ne+=1,c){let y=!0;for(let w in u)if(Se(u,w)){y=!1;break}y&&p===1&&(u.$unknown=[l,d])}return u}let h=Ooe(i,a,f);if(h>=0){f=h+1,f>=a&&(f=0);let y=qo(n[h]);y!=null&&(u[s[h]]=y)}else{let y=Lm(),w=qo(B.of(15));y!=="__type"&&(l=y,d=w,++p)}}throw new Error("expected break marker.")}let e=t.isMapSchema()?t.getValueSchema():t,r={};for(;ne<Kr;){if(mr[ne]===255)return ne+=1,r;let o=Lm();r[o]=qo(e)}throw new Error("expected break marker.")}function Ooe(t,e,r){let o=t[r];if(ne+o.length<=Kr&&Toe(ne,o))return ne+=o.length,r;for(let n=0;n<e;++n){if(n===r)continue;let i=t[n];if(ne+i.length<=Kr&&Toe(ne,i))return ne+=i.length,n}return-1}function Toe(t,e){let r=e.length;if(mr[t]!==e[0])return!1;for(let o=1;o<r;++o)if(mr[t+o]!==e[o])return!1;return!0}function $A(){let t=mr[ne]&31;if(t<24)return ne+=1,t;switch(t){case 24:return Kr-ne<2&&wc(1),ne+=2,mr[ne-1];case 25:return Kr-ne<3&&wc(2),ne+=3,Ku.getUint16(ne-2);case 26:return Kr-ne<5&&wc(4),ne+=5,Ku.getUint32(ne-4);case 27:{Kr-ne<9&&wc(8),ne+=9;let e=Ku.getUint32(ne-8);return e<2097152?e*4294967296+Ku.getUint32(ne-4):Ku.getBigUint64(ne-8)}default:throw new Error(`unexpected minor value ${t}.`)}}function RA(){let t=$A();return typeof t=="bigint"?Number(t):t}function sje(){let t=$A();return Doe(t)}function aje(){let t=$A();return typeof t=="bigint"?BigInt(-1)-t:-1-t}function IA(){let t=RA();Kr-ne<t&&wc(t);let e=ne;return ne+=t,mr.subarray(e,e+t)}function Lm(){let t=RA();Kr-ne<t&&wc(t);let e=ne;return ne+=t,t<24?cje(e,t):J6?mr.toString("utf-8",e,e+t):W6.decode(mr.subarray(e,e+t))}function cje(t,e){let r=e;for(let s=0;s<e;++s)r=r*31+mr[t+s]|0;let o=r>>>0&X6-1,n=koe[o];if(n!==void 0&&n.length===e){let s=!0;for(let a=0;a<e;++a)if(n.charCodeAt(a)!==mr[t+a]){s=!1;break}if(s)return Z6[o]=uw,n}let i=J6?mr.toString("utf-8",t,t+e):W6.decode(mr.subarray(t,t+e));return Z6[o]!==uw&&(koe[o]=i,Z6[o]=uw),i}function uje(){let t=ne,e=mr[t]&31;switch(e){case 21:return ne=t+1,!0;case 20:return ne=t+1,!1;case 22:return ne=t+1,null;case 23:return ne=t+1,null;case 25:return Kr-t<3&&wc(2),ne=t+3,lje(mr[t+1],mr[t+2]);case 26:return Kr-t<5&&wc(4),ne=t+5,Ku.getFloat32(t+1);case 27:return Kr-t<9&&wc(8),ne=t+9,Ku.getFloat64(t+1);default:throw new Error(`unexpected minor value ${e} for major 7.`)}}function lje(t,e){let r=t>>7,o=(t&124)>>2,n=(t&3)<<8|e,i=r===0?1:-1;return o===0?n===0?0:i*(Math.pow(2,-14)*(n/1024)):o===31?n===0?i*(1/0):NaN:i*(Math.pow(2,o-15)*(1+n/1024))}function Doe(t){if(typeof t=="number")return t;let e=Number(t);return Number.MIN_SAFE_INTEGER<=e&&e<=Number.MAX_SAFE_INTEGER?e:t}function wc(t){throw new Error(`CBOR: length ${t} greater than remaining buffer length.`)}function xA(t,e){if(t.isTimestampSchema()){if(typeof e=="number")return Eu(e);if(typeof e=="object"&&e!==null&&e.tag===1&&"value"in e)return Eu(e.value)}if(t.isBlobSchema()||typeof e>"u"||typeof e=="boolean"||typeof e=="number"||typeof e=="string"||typeof e=="bigint"||typeof e=="symbol"||typeof e!="object"||e===null||"byteLength"in e||e instanceof Date||e instanceof nt||t.isDocumentSchema())return e;if(t.isListSchema()){let o=t.getValueSchema(),n=[];for(let i of e)n.push(xA(o,i));return n}let r={};if(t.isMapSchema()){let o=t.getValueSchema();for(let n in e)Se(e,n)&&(r[n]=xA(o,e[n]))}else if(t.isStructSchema()){let o=t.isUnionSchema(),n;if(o){n=new Set;for(let i in e)Se(e,i)&&i!=="__type"&&n.add(i)}for(let[i,s]of t.structIterator())o&&n.delete(i),e[i]!=null&&(r[i]=xA(s,e[i]));if(o&&n?.size===1){let i=!0;for(let s in r)if(Se(r,s)){i=!1;break}if(i){let s=n.values().next().value;r.$unknown=[s,e[s]]}}else if(typeof e.__type=="string")for(let i in e)Se(e,i)&&(i in r||(r[i]=e[i]))}return r}var EA,Coe,W6,mr,J6,Ku,ne,Kr,X6,koe,Z6,uw,Noe=_(()=>{Pe();ge();rt();xe();B6();EA=class extends Fr{read(e,r){return mr=r,J6=Coe&&r instanceof Buffer,Ku=new DataView(r.buffer,r.byteOffset,r.byteLength),ne=0,Kr=r.length,uw=uw+1&65535,qo(B.of(e))}readValue(e,r){return xA(B.of(e),r)}},Coe=typeof Buffer<"u",W6=new TextDecoder,mr=new Uint8Array(0),J6=!1,Ku=new DataView(new ArrayBuffer(0)),ne=0,Kr=0,X6=2048,koe=new Array(X6),Z6=new Uint16Array(X6),uw=0});var AA,zoe=_(()=>{ge();B6();Noe();AA=class extends Fr{createSerializer(){let e=new yA;return e.setSerdeContext(this.serdeContext),e}createDeserializer(){let e=new EA;return e.setSerdeContext(this.serdeContext),e}}});var lw,Moe=_(()=>{ge();rt();Pe();zoe();N6();lw=class extends na{codec=new AA;serializer=this.codec.createSerializer();deserializer=this.codec.createDeserializer();constructor({defaultNamespace:e,errorTypeRegistries:r}){super({defaultNamespace:e,errorTypeRegistries:r})}getShapeId(){return"smithy.protocols#rpcv2Cbor"}getPayloadCodec(){return this.codec}async serializeRequest(e,r,o){let n=await super.serializeRequest(e,r,o);Object.assign(n.headers,{"content-type":this.getDefaultContentType(),"smithy-protocol":"rpc-v2-cbor",accept:this.getDefaultContentType()}),ii(e.input)==="unit"?(delete n.body,delete n.headers["content-type"]):(n.body||(this.serializer.write(15,{}),n.body=this.serializer.flush()),n.body instanceof Uint8Array&&(n.headers["content-length"]=String(n.body.byteLength)));let{service:i,operation:s}=Bt(o),a=`/service/${i}/operation/${s}`;return n.path.endsWith("/")?n.path+=a.slice(1):n.path+=a,n}async deserializeResponse(e,r,o){return super.deserializeResponse(e,r,o)}async handleError(e,r,o,n,i){let s=sw(o,n)??"Unknown",a=["*"],{defaultNamespace:c}=this.options;a.unshift(c);let[u,l]=s.includes("#")?s.split("#"):[void 0,s];u&&a.unshift(u);let d={$metadata:i,$fault:o.statusCode<500?"client":"server"},p=[this.compositeErrorRegistry];u&&p.push(Zt.for(u)),p.push(Zt.for(c));let[f,h,y]=this.resolveError(l,a,p);if(y==="native"||y==="synthetic"){n.Message&&(n.message=n.Message);let R=y==="synthetic"?new h({name:l}):new Error(l);throw Object.assign(R,d,n)}let w=B.of(f),b=n.message??n.Message??"Unknown",S=new h({}),x={};for(let[R,T]of w.structIterator())x[R]=this.deserializer.readValue(T,n[R]);throw Object.assign(S,d,{$fault:w.getMergedTraits().error,message:b},x)}getDefaultContentType(){return"application/cbor"}}});var Uoe=_(()=>{N6();Moe()});var mi,jm=_(()=>{ve();rt();mi=class{queryCompat;errorRegistry;constructor(e=!1){this.queryCompat=e}resolveRestContentType(e,r){let o=r.getMemberSchemas(),n=Object.values(o).find(i=>!!i.getMergedTraits().httpPayload);if(n){let i=n.getMergedTraits().mediaType;return i||(n.isStringSchema()?"text/plain":n.isBlobSchema()?"application/octet-stream":e)}else if(!r.isUnitSchema()&&Object.values(o).find(s=>{let{httpQuery:a,httpQueryParams:c,httpHeader:u,httpLabel:l,httpPrefixHeaders:d}=s.getMergedTraits();return!a&&!c&&!u&&!l&&d===void 0}))return e}async getErrorSchemaOrThrowBaseException(e,r,o,n,i,s){let a=e;e.includes("#")&&([,a]=e.split("#"));let c={$metadata:i,$fault:o.statusCode<500?"client":"server"};if(!this.errorRegistry)throw new Error("@aws-sdk/core/protocols - error handler not initialized.");try{return{errorSchema:s?.(this.errorRegistry,a)??this.errorRegistry.getSchema(e),errorMetadata:c}}catch{n.message=n.message??n.Message??"UnknownError";let l=this.errorRegistry,d=l.getBaseException();if(d){let h=l.getErrorCtor(d)??Error;throw this.decorateServiceException(Object.assign(new h({name:a}),c),n)}let p=n,f=p?.message??p?.Message??p?.Error?.Message??p?.Error?.message;throw this.decorateServiceException(Object.assign(new Error(f),{name:a},c),n)}}compose(e,r,o){let n=o;r.includes("#")&&([n]=r.split("#"));let i=Zt.for(n),s=Zt.for("smithy.ts.sdk.synthetic."+o);e.copyFrom(i),e.copyFrom(s),this.errorRegistry=e}decorateServiceException(e,r={}){if(this.queryCompat){let o=e.Message??r.Message,n=yd(e,r);o&&(n.message=o);let i=n.Error??{};i.Type=n.Error?.Type,i.Code=n.Error?.Code,i.Message=n.Error?.message??n.Error?.Message??o,n.Error=i;let s=n.$metadata.requestId;return s&&(n.RequestId=s),n}return yd(e,r)}setQueryCompatError(e,r){let o=r.headers?.["x-amzn-query-error"];if(e!==void 0&&o!=null){let[n,i]=o.split(";"),s=Object.keys(e),a={Code:n,Type:i};e.Code=n,e.Type=i;for(let c=0;c<s.length;c++){let u=s[c];a[u==="message"?"Message":u]=e[u]}delete a.__type,e.Error=a}}queryCompatOutput(e,r){e.Error&&(r.Error=e.Error),e.Type&&(r.Type=e.Type),e.Code&&(r.Code=e.Code)}findQueryCompatibleError(e,r){try{return e.getSchema(r)}catch{return e.find(n=>B.of(n).getMergedTraits().awsQueryError?.[0]===r)}}}});var PA,Loe=_(()=>{Uoe();rt();jm();PA=class extends lw{awsQueryCompatible;mixin;constructor({defaultNamespace:e,errorTypeRegistries:r,awsQueryCompatible:o}){super({defaultNamespace:e,errorTypeRegistries:r}),this.awsQueryCompatible=!!o,this.mixin=new mi(this.awsQueryCompatible)}async serializeRequest(e,r,o){let n=await super.serializeRequest(e,r,o);return this.awsQueryCompatible&&(n.headers["x-amzn-query-mode"]="true"),n}async handleError(e,r,o,n,i){this.awsQueryCompatible&&this.mixin.setQueryCompatError(n,o);let s=(()=>{let h=o.headers["x-amzn-query-error"];return h&&this.awsQueryCompatible?h.split(";")[0]:sw(o,n)??"Unknown"})();this.mixin.compose(this.compositeErrorRegistry,s,this.options.defaultNamespace);let{errorSchema:a,errorMetadata:c}=await this.mixin.getErrorSchemaOrThrowBaseException(s,this.options.defaultNamespace,o,n,i,this.awsQueryCompatible?this.mixin.findQueryCompatibleError:void 0),u=B.of(a),l=n.message??n.Message??"UnknownError",d=this.compositeErrorRegistry.getErrorCtor(a)??Error,p=new d({}),f={};for(let[h,y]of u.structIterator())n[h]!=null&&(f[h]=this.deserializer.readValue(y,n[h]));throw this.awsQueryCompatible&&this.mixin.queryCompatOutput(n,f),this.mixin.decorateServiceException(Object.assign(p,c,{$fault:u.getMergedTraits().error,message:l},f),n)}}});var hr,as=_(()=>{hr=class{serdeContext;setSerdeContext(e){this.serdeContext=e}}});var Bu,kA=_(()=>{Bu=class{from;to;keys;constructor(e,r){this.from=e,this.to=r;let o=Object.keys(this.from),n=new Set(o);n.delete("__type"),this.keys=n}mark(e){this.keys.delete(e)}hasUnknown(){return this.keys.size===1&&Object.keys(this.to).length===0}writeUnknown(){if(this.hasUnknown()){let e=this.keys.values().next().value,r=this.from[e];this.to.$unknown=[e,r]}}}});function TA(){if(dw===void 0)try{if(typeof Buffer!="function")dw=!1;else{let t=JSON.parse(Buffer.from([123,125]));dw=t!==null&&typeof t=="object"}}catch{dw=!1}return dw}var dw,Y6=_(()=>{});function Fm(t,e,r){if(r?.source){let o=r.source;if(typeof e=="number")return e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER?pje(o,e)?e:new nt(o,"bigDecimal"):dje(o)?new nt(o,"bigDecimal"):/[eE]/.test(o)?fje(o):BigInt(o)}return e}function dje(t){let e=t.indexOf(".");if(e===-1)return!1;let r=t.search(/[eE]/);if(r===-1)return!0;let o=r-e-1;return parseInt(t.slice(r+1),10)<o}function pje(t,e){if(t===String(e)||Object.is(e,-0))return!0;if(/[eE]/.test(t))return Q6(t)===Q6(String(e));let r=t.replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,""),o=String(e);return r===o?!0:/[eE]/.test(o)?r===Q6(o):!1}function Q6(t){let e=t.startsWith("-"),r=e?t.slice(1):t,o=r.search(/[eE]/),n;if(o===-1)n=r;else{let i=parseInt(r.slice(o+1),10),s=r.slice(0,o),a=s.indexOf("."),c,u;a===-1?(c=s,u=s.length):(c=s.slice(0,a)+s.slice(a+1),u=a),c=c.replace(/0+$/,"")||"0";let l=u+i;c==="0"?n="0":l<=0?n="0."+"0".repeat(-l)+c:l>=c.length?n=c+"0".repeat(l-c.length):n=c.slice(0,l)+"."+c.slice(l)}return n.includes(".")&&(n=n.replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"")),(e?"-":"")+n}function fje(t){let e=t.search(/[eE]/),r=parseInt(t.slice(e+1),10),o=t.startsWith("-"),n=t.slice(o?1:0,e),i=n.indexOf("."),s,a;if(i===-1)s=n,a=r;else{s=n.slice(0,i)+n.slice(i+1);let u=n.length-i-1;a=r-u}s=s.replace(/0+$/,"")||"0";let c=BigInt(s)*10n**BigInt(a+(n.replace(".","").length-s.length));return o?-c:c}var CA=_(()=>{xe()});function qm(t){let e=B.of(t),r=e.getSchema();if(Array.isArray(r)&&e.isStructSchema()){if(eq in r)return r[eq];let o=OA(e,new Set);return r[eq]=o,o}return OA(e,new Set)}function OA(t,e){let r=t.getSchema();if(e.has(r))return!1;if(e.add(r),t.isBigIntegerSchema()||t.isBigDecimalSchema())return!0;if(t.isStructSchema()){for(let[,o]of t.structIterator())if(OA(o,e))return!0}else if(t.isListSchema()||t.isMapSchema()){if(OA(t.getValueSchema(),e))return!0}else if(t.isDocumentSchema())return!0;return!1}var eq,DA=_(()=>{rt();eq=Symbol.for("@aws-sdk/reviver")});var NA,tq=_(()=>{ge();xe();NA=(t,e)=>sn(t,e).then(r=>(e?.utf8Encoder??ur)(r))});async function Dd(t,e,r){let o;if(TA()&&typeof t?.[Symbol.asyncIterator]=="function"){let i=await sn(t,e);typeof Buffer=="function"&&(Buffer.isBuffer(i)?o=i:o=Buffer.from(i.buffer,i.byteOffset,i.byteLength))}if(o||(o=await NA(t,e)),o.length===0)return{};let n=r&&qm(r)?Fm:void 0;try{return JSON.parse(o,n)}catch(i){throw i?.name==="SyntaxError"&&Object.defineProperty(i,"$responseBodyText",{value:typeof o=="string"?o:o.toString("utf8")}),i}}var Foe,joe,rq,zA,MA,qoe,Vm=_(()=>{ge();tq();Y6();CA();DA();Foe=async(t,e)=>{let r=await Dd(t,e);return r.message=r.message??r.Message,r},joe=(t,e)=>Object.keys(t).find(r=>r.toLowerCase()===e.toLowerCase()),rq=t=>{let e=t;return typeof e=="number"&&(e=e.toString()),e.indexOf(",")>=0&&(e=e.split(",")[0]),e.indexOf(":")>=0&&(e=e.split(":")[0]),e.indexOf("#")>=0&&(e=e.split("#")[1]),e},zA=(t,e)=>qoe(t,e,["header","code","type"]),MA=(t,e,r=!1)=>qoe(t,e,r?["code","header","type"]:["type","code","header"]),qoe=({headers:t},e,r)=>{for(;r.length>0;)switch(r.shift()){case"header":let n=joe(t??{},"x-amzn-errortype");if(n!==void 0)return rq(t[n]);break;case"code":let i=joe(e??{},"code");if(i&&e[i]!==void 0)return rq(e[i]);break;case"type":if(e?.__type!==void 0)return rq(e.__type);break}}});function hi(t){Object.defineProperty(t,"__proto__",{value:void 0,writable:!0,enumerable:!0,configurable:!0})}var pw=_(()=>{});var Gm,nq=_(()=>{ge();rt();xe();as();kA();Y6();CA();DA();Vm();pw();Gm=class extends hr{settings;constructor(e){super(),this.settings=e}async read(e,r){let o=qm(e)?Fm:void 0,n;if(typeof r=="string"){if(r.length===0)return{};n=JSON.parse(r,o)}else if(r instanceof Uint8Array&&TA()){if(r.byteLength===0)return{};let i=Buffer.isBuffer(r)?r:Buffer.from(r.buffer,r.byteOffset,r.byteLength);n=JSON.parse(i,o)}else n=await Dd(r,this.serdeContext,e);return this._read(e,n)}readObject(e,r){return this._read(e,r)}_read(e,r){let o=r!==null&&typeof r=="object",n=B.of(e);if(o){if(n.isStructSchema())return this._readStruct(n,r);if(Array.isArray(r)&&n.isListSchema()){let s=n.getValueSchema();if(this.needsTransform(s))for(let a=0;a<r.length;++a)r[a]=this._read(s,r[a]);return r}if(n.isMapSchema()){let s=n.getValueSchema(),a=r;if(this.needsTransform(s))for(let c in a)c==="__proto__"&&hi(a),a[c]=this._read(s,a[c]);return a}}if(n.isBlobSchema()&&typeof r=="string")return fr(r);let i=n.getMergedTraits().mediaType;if(n.isStringSchema()&&typeof r=="string"&&i)return i==="application/json"||i.endsWith("+json")?Er.from(r):r;if(n.isTimestampSchema()&&r!=null)switch(qr(n,this.settings)){case 5:return Yf(r);case 6:return xu(r);case 7:return Qf(r);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",r),new Date(r)}if(n.isBigIntegerSchema()&&(typeof r=="number"||typeof r=="string"))return BigInt(r);if(n.isBigDecimalSchema()&&r!=null){if(r instanceof nt)return r;let s=r;return s.type==="bigDecimal"&&"string"in s?new nt(s.string,s.type):new nt(String(r),"bigDecimal")}if(n.isNumericSchema()&&typeof r=="string"){switch(r){case"Infinity":return 1/0;case"-Infinity":return-1/0;case"NaN":return NaN}return r}if(n.isDocumentSchema()&&o)if(Array.isArray(r))for(let s=0;s<r.length;++s){let a=r[s];a instanceof nt||(r[s]=this._read(n,a))}else{let s=r;for(let a in s){a==="__proto__"&&hi(s);let c=s[a];c instanceof nt||(s[a]=this._read(n,c))}}return r}_readStruct(e,r){let o=e.isUnionSchema(),n={},i,s=typeof r.__type=="string",{jsonName:a}=this.settings;a&&s&&(i={});let c;o&&(c=new Bu(r,n));for(let[u,l]of e.structIterator()){let d=u;a&&(d=l.getMergedTraits().jsonName??d,s&&(i[d]=u)),o&&c.mark(d),r[d]!=null&&(n[u]=this._read(l,r[d]))}if(o)c.writeUnknown();else if(s)for(let u in r){let l=r[u],d=a?i[u]??u:u;d in n||(n[d]=l)}return n}needsTransform(e){return!!(e.isBlobSchema()||e.isTimestampSchema()||e.isBigIntegerSchema()||e.isBigDecimalSchema()||e.isDocumentSchema()||e.isStructSchema()||e.isListSchema()||e.isMapSchema()||e.isStringSchema()&&e.getMergedTraits().mediaType)}}});var UA,Voe,Goe=_(()=>{xe();UA=class t extends Uint8Array{string=null;static allocUnsafe(e){if(typeof Buffer=="function"){let r=Buffer.allocUnsafe(e);return new t(r.buffer,r.byteOffset,r.byteLength)}return new t(e)}toString(){return this.s()}valueOf(){return this.s()}includes(e,r){return typeof e=="string"?this.s().includes(e,r):Uint8Array.prototype.includes.call(this,e,r)}indexOf(e,r){return typeof e=="string"?this.s().indexOf(e,r):Uint8Array.prototype.indexOf.call(this,e,r)}lastIndexOf(e,r){if(typeof e=="string")return this.s().lastIndexOf(e,r);let o=Uint8Array.prototype.lastIndexOf;return r!==void 0?o.call(this,e,r):o.call(this,e)}startsWith(e,r){return this.s().startsWith(e,r)}endsWith(e,r){return this.s().endsWith(e,r)}match(e){return this.s().match(e)}replace(e,r){return this.s().replace(e,r)}search(e){return this.s().search(e)}split(e,r){return this.s().split(e,r)}substring(e,r){return this.s().substring(e,r)}trim(){return this.s().trim()}trimStart(){return this.s().trimStart()}trimEnd(){return this.s().trimEnd()}charAt(e){return this.s().charAt(e)}charCodeAt(e){return this.s().charCodeAt(e)}padStart(e,r){return this.s().padStart(e,r)}padEnd(e,r){return this.s().padEnd(e,r)}repeat(e){return this.s().repeat(e)}toUpperCase(){return this.s().toUpperCase()}toLowerCase(){return this.s().toLowerCase()}s(){if(this.string==null){let e=Date.now();e>Voe+6e4&&(console.warn("@aws-sdk/core/protocols - WARN - JsonCodec2: you have called a string method on a Uint8Array request body. It has been automatically converted to string. In a future version this will throw an error."),Voe=e),this.string=ur(this)}return this.string}},Voe=0});function oq(t){return UA.allocUnsafe(t)}var LA,Hoe,Koe,mje,hje,Hm,jA,FA,Boe,gje,yje,vje,ba,Zoe,Km,iq=_(()=>{ge();rt();xe();as();Goe();LA=new TextEncoder,Hoe=123,Koe=125,mje=91,hje=93,Hm=34,jA=58,FA=44,Boe=92,gje=new Uint8Array([116,114,117,101]),yje=new Uint8Array([102,97,108,115,101]),vje=new Uint8Array([110,117,108,108]),ba=new Array(128).fill(null);ba[8]="b";ba[9]="t";ba[10]="n";ba[12]="f";ba[13]="r";ba[34]='"';ba[92]="\\";for(let t=0;t<32;t++)ba[t]===null&&(ba[t]="u00"+t.toString(16).padStart(2,"0"));Zoe=2048;Km=class t extends hr{settings;json;i=0;rootSchema;rawValue;passthrough=!1;constructor(e){super(),this.settings=e,this.json=oq(Zoe)}write(e,r){this.i=0,this.rawValue=r,this.rootSchema=B.of(e),this.passthrough=this.rootSchema.isBlobSchema()||this.rootSchema.isStringSchema(),this.passthrough||this.writeValue(this.rootSchema,r,void 0)}writeDiscriminatedDocument(e,r){this.i=0,this.rootSchema=B.of(e);let o=this.rootSchema;if(o.isStructSchema()&&r!=null&&typeof r=="object"){this.writeValue(o,r,void 0);let n=`"__type":"${o.getName(!0)??"Unknown"}",`,i=n.length;this.ensure(i),this.json.copyWithin(1+i,1,this.i),LA.encodeInto(n,this.json.subarray(1)),this.i+=i}else this.writeValue(o,r,void 0)}flush(){this.rootSchema=void 0;let e=this.i;this.i=0;let r=this.rawValue;if(this.rawValue=void 0,e===0)return r;let o=this.json.subarray(0,e);return this.json=oq(Zoe),o}ensure(e){let{i:r,json:o}=this;if(r+e>o.length){let n=o.length*2;for(;n<r+e;)n*=2;let i=oq(n);i.set(this.json),this.json=i}}writeAscii(e){let r=e.length;this.ensure(r);let{i:o,json:n}=this;for(let i=0;i<r;++i)n[o]=e.charCodeAt(i),o+=1;this.i=o}writeAsciiQuoted(e){let r=e.length;this.ensure(r+4);let{json:o,i:n}=this;o[n++]=Hm;for(let i=0;i<r;++i)o[n++]=e.charCodeAt(i);o[n++]=Hm,this.i=n}writeJsonString(e){this.ensure(e.length*3+2),this.json[this.i++]=Hm;let r=e.length;for(let o=0;o<r;++o){let n=e.charCodeAt(o);if(n>34&&n<92)this.json[this.i++]=n;else if(n<128){let i=ba[n];if(i!==null){this.ensure(i.length+1),this.json[this.i++]=Boe;for(let s=0;s<i.length;s++)this.json[this.i++]=i.charCodeAt(s)}else this.json[this.i++]=n}else if(n>=55296&&n<=56319){let i=o+1<r?e.charCodeAt(o+1):0;if(i>=56320&&i<=57343){this.ensure(4);let{written:s}=LA.encodeInto(e.substring(o,o+2),this.json.subarray(this.i));this.i+=s,++o}else this.ensure(6),this.writeUnicodeEscape(n)}else if(n>=56320&&n<=57343)this.ensure(6),this.writeUnicodeEscape(n);else{let{i,json:s}=this;n<2048?(s[i++]=192|n>>6,s[i++]=128|n&63):(s[i++]=224|n>>12,s[i++]=128|n>>6&63,s[i++]=128|n&63),this.i=i}}this.json[this.i++]=Hm}writeUnicodeEscape(e){let{json:r,i:o}=this;r[o++]=Boe,r[o++]=117;let n=e.toString(16).padStart(4,"0");for(let i=0;i<4;++i)r[o++]=n.charCodeAt(i);this.i=o}static B64=(()=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r=new Uint8Array(64);for(let o=0;o<64;++o)r[o]=e.charCodeAt(o);return r})();writeBase64(e){let r=Math.ceil(e.length/3)*4;this.ensure(r+2);let o=this.json,n=t.B64,i=this.i;o[i++]=Hm;let s=e.length,a=s%3,c=s-a;for(let u=0;u<c;u+=3){let l=e[u],d=e[u+1],p=e[u+2];o[i++]=n[l>>2],o[i++]=n[(l&3)<<4|d>>4],o[i++]=n[(d&15)<<2|p>>6],o[i++]=n[p&63]}if(a===2){let u=e[c],l=e[c+1];o[i++]=n[u>>2],o[i++]=n[(u&3)<<4|l>>4],o[i++]=n[(l&15)<<2],o[i++]=61}else if(a===1){let u=e[c];o[i++]=n[u>>2],o[i++]=n[(u&3)<<4],o[i++]=61,o[i++]=61}o[i++]=Hm,this.i=i}writeValue(e,r,o){if(r==null){if(o?.isStructSchema()){if(r===void 0&&B.of(e).isIdempotencyToken()){this.writeAsciiQuoted(Lo());return}return}this.ensure(4),this.json.set(vje,this.i),this.i+=4;return}let n=B.of(e),i=typeof r=="object";if(n.isStringSchema()){let s=n.getMergedTraits().mediaType;if(s&&(s==="application/json"||s.endsWith("+json"))){this.writeJsonString(Er.from(r).toString());return}}if(i){if(n.isStructSchema()){this.writeStruct(n,r);return}if(Array.isArray(r)&&(n.isListSchema()||n.isDocumentSchema())){this.writeList(n,r,n.isDocumentSchema());return}if(n.isMapSchema()){this.writeMap(n,r,!1);return}if(r instanceof Uint8Array&&(n.isBlobSchema()||n.isDocumentSchema())){this.writeBase64(r);return}if(r instanceof Date&&(n.isTimestampSchema()||n.isDocumentSchema())){this.writeTimestamp(n,r);return}if(r instanceof nt){this.writeAscii(r.string);return}if(n.isDocumentSchema()){Array.isArray(r)?this.writeList(n,r,!0):this.writeMap(n,r,!0);return}let s=JSON.stringify(r);this.writeAscii(s);return}if(typeof r=="string"){if(n.isBlobSchema()){let s=(this.serdeContext?.base64Encoder??Wt)(r);this.writeAsciiQuoted(s);return}this.writeJsonString(r);return}if(typeof r=="number"){if(Math.abs(r)===1/0||Number.isNaN(r)){this.writeAsciiQuoted(String(r));return}let s=String(r);this.writeAscii(s);return}if(typeof r=="boolean"){this.ensure(5);let{i:s,json:a}=this;r?(a.set(gje,s),s+=4):(a.set(yje,s),s+=5),this.i=s;return}if(typeof r=="bigint"){this.writeAscii(r.toString());return}this.writeAscii(String(r))}writeStruct(e,r){this.ensure(2),this.json[this.i++]=Hoe;let o=!1,n=typeof r.__type=="string",i;n&&(i=new Set);for(let[s,a]of e.structIterator()){let c=r[s];if(c==null&&!a.isIdempotencyToken())continue;o&&(this.ensure(1),this.json[this.i++]=FA),o=!0;let u=this.settings.jsonName?a.getMergedTraits().jsonName??s:s;i&&(i.add(s),i.add(u)),this.writeAsciiQuoted(u),this.json[this.i++]=jA,this.writeValue(a,c,e)}if(!o&&e.isUnionSchema()){let{$unknown:s}=r;if(Array.isArray(s)){let[a,c]=s;this.writeAsciiQuoted(a),this.ensure(1),this.json[this.i++]=jA,this.writeValue(15,c,e)}}else if(n)for(let s in r){if(i.has(s))continue;i.add(s);let a=r[s];o&&(this.ensure(1),this.json[this.i++]=FA),o=!0,this.writeAsciiQuoted(s),this.ensure(1),this.json[this.i++]=jA,this.writeValue(15,a,void 0)}this.ensure(1),this.json[this.i++]=Koe}writeList(e,r,o){let n=!!e.getMergedTraits().sparse,i=e.getValueSchema();if(!o&&(i.isStringSchema()||i.isNumericSchema()||i.isBooleanSchema())){let a=!1;for(let u=0;u<r.length;++u){let l=r[u];if(Number.isNaN(l)||l===1/0||l===-1/0||l==null&&!n){a=!0;break}}let c;if(!a)c=JSON.stringify(r);else{let u=[];for(let l=0;l<r.length;++l){let d=r[l];d==null&&!n||(Number.isNaN(d)||d===1/0||d===-1/0?u.push(String(d)):u.push(d))}c=JSON.stringify(u)}this.ensure(c.length*3),this.i+=LA.encodeInto(c,this.json.subarray(this.i)).written;return}this.ensure(2),this.json[this.i++]=mje;let s=!1;for(let a=0;a<r.length;++a){let c=r[a];(o?c===void 0:c==null&&!n)||(s&&(this.ensure(1),this.json[this.i++]=FA),this.writeValue(i,c,void 0),s=!0)}this.ensure(1),this.json[this.i++]=hje}writeMap(e,r,o){let n=!!e.getMergedTraits().sparse,i=e.getValueSchema();if(!o&&(i.isStringSchema()||i.isNumericSchema()||i.isBooleanSchema())){let a;for(let u in r){let l=r[u];Number.isNaN(l)||l===1/0||l===-1/0?((a??={})[u]=l,r[u]=String(l)):l===null&&!n&&((a??={})[u]=null,r[u]=void 0)}let c=JSON.stringify(r);a&&Object.assign(r,a),this.ensure(c.length*3),this.i+=LA.encodeInto(c,this.json.subarray(this.i)).written;return}this.ensure(2),this.json[this.i++]=Hoe;let s=!0;for(let a in r){let c=r[a];(o?c===void 0:c==null&&!n)||(s||(this.ensure(1),this.json[this.i++]=FA),s=!1,this.writeJsonString(a),this.ensure(1),this.json[this.i++]=jA,this.writeValue(i,c,void 0))}this.ensure(1),this.json[this.i++]=Koe}writeTimestamp(e,r){switch(qr(e,this.settings)){case 5:{let n=r.toISOString().replace(".000Z","Z");this.writeAsciiQuoted(n);return}case 6:{this.writeAsciiQuoted(Oo(r));return}case 7:{let n=String(r.getTime()/1e3);this.writeAscii(n);return}default:{let n=String(r.getTime()/1e3);this.writeAscii(n);return}}}}});var Zu,qA=_(()=>{as();nq();iq();Zu=class extends hr{settings;constructor(e){super(),this.settings=e}createSerializer(){let e=new Km(this.settings);return e.setSerdeContext(this.serdeContext),e}createDeserializer(){let e=new Gm(this.settings);return e.setSerdeContext(this.serdeContext),e}}});var Wu,VA=_(()=>{ge();rt();jm();qA();Vm();Wu=class extends na{serializer;deserializer;serviceTarget;codec;mixin;awsQueryCompatible;constructor({defaultNamespace:e,errorTypeRegistries:r,serviceTarget:o,awsQueryCompatible:n,jsonCodec:i}){super({defaultNamespace:e,errorTypeRegistries:r}),this.serviceTarget=o,this.codec=i??new Zu({timestampFormat:{useTrait:!0,default:7},jsonName:!1}),this.serializer=this.codec.createSerializer(),this.deserializer=this.codec.createDeserializer(),this.awsQueryCompatible=!!n,this.mixin=new mi(this.awsQueryCompatible)}async serializeRequest(e,r,o){let n=await super.serializeRequest(e,r,o);return n.path.endsWith("/")||(n.path+="/"),n.headers["content-type"]=`application/x-amz-json-${this.getJsonRpcVersion()}`,n.headers["x-amz-target"]=`${this.serviceTarget}.${e.name}`,this.awsQueryCompatible&&(n.headers["x-amzn-query-mode"]="true"),(ii(e.input)==="unit"||!n.body)&&(n.body="{}"),n}getPayloadCodec(){return this.codec}async handleError(e,r,o,n,i){let{awsQueryCompatible:s}=this;s&&this.mixin.setQueryCompatError(n,o);let a=MA(o,n,s)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,a,this.options.defaultNamespace);let{errorSchema:c,errorMetadata:u}=await this.mixin.getErrorSchemaOrThrowBaseException(a,this.options.defaultNamespace,o,n,i,s?this.mixin.findQueryCompatibleError:void 0),l=B.of(c),d=n.message??n.Message??"UnknownError",p=this.compositeErrorRegistry.getErrorCtor(c)??Error,f=new p({}),h={},y=this.codec.createDeserializer();for(let[w,b]of l.structIterator())n[w]!=null&&(h[w]=y.readObject(b,n[w]));throw s&&this.mixin.queryCompatOutput(n,h),this.mixin.decorateServiceException(Object.assign(f,u,{$fault:l.getMergedTraits().error,message:d},h),n)}}});var GA,Woe=_(()=>{VA();GA=class extends Wu{constructor({defaultNamespace:e,errorTypeRegistries:r,serviceTarget:o,awsQueryCompatible:n,jsonCodec:i}){super({defaultNamespace:e,errorTypeRegistries:r,serviceTarget:o,awsQueryCompatible:n,jsonCodec:i})}getShapeId(){return"aws.protocols#awsJson1_0"}getJsonRpcVersion(){return"1.0"}getDefaultContentType(){return"application/x-amz-json-1.0"}}});var HA,Joe=_(()=>{VA();HA=class extends Wu{constructor({defaultNamespace:e,errorTypeRegistries:r,serviceTarget:o,awsQueryCompatible:n,jsonCodec:i}){super({defaultNamespace:e,errorTypeRegistries:r,serviceTarget:o,awsQueryCompatible:n,jsonCodec:i})}getShapeId(){return"aws.protocols#awsJson1_1"}getJsonRpcVersion(){return"1.1"}getDefaultContentType(){return"application/x-amz-json-1.1"}}});var Sa,Xoe=_(()=>{ge();rt();jm();qA();Vm();Sa=class extends Tu{serializer;deserializer;codec;mixin=new mi;constructor({defaultNamespace:e,errorTypeRegistries:r,jsonCodec:o}){super({defaultNamespace:e,errorTypeRegistries:r});let n={timestampFormat:{useTrait:!0,default:7},httpBindings:!0,jsonName:!0};this.codec=o??new Zu(n),this.serializer=new Du(this.codec.createSerializer(),n),this.deserializer=new Ou(this.codec.createDeserializer(),n)}getShapeId(){return"aws.protocols#restJson1"}getPayloadCodec(){return this.codec}setSerdeContext(e){this.codec.setSerdeContext(e),super.setSerdeContext(e)}async serializeRequest(e,r,o){let n=await super.serializeRequest(e,r,o),i=B.of(e.input);if(!n.headers["content-type"]){let s=this.mixin.resolveRestContentType(this.getDefaultContentType(),i);s&&(n.headers["content-type"]=s)}return n.body==null&&n.headers["content-type"]===this.getDefaultContentType()&&(n.body="{}"),n}async deserializeResponse(e,r,o){let n=await super.deserializeResponse(e,r,o),i=B.of(e.output);for(let[s,a]of i.structIterator())a.getMemberTraits().httpPayload&&!(s in n)&&(n[s]=null);return n}async handleError(e,r,o,n,i){let s=zA(o,n)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,s,this.options.defaultNamespace);let{errorSchema:a,errorMetadata:c}=await this.mixin.getErrorSchemaOrThrowBaseException(s,this.options.defaultNamespace,o,n,i),u=B.of(a),l=n.message??n.Message??"UnknownError",d=this.compositeErrorRegistry.getErrorCtor(a)??Error,p=new d({});await this.deserializeHttpMessage(a,r,o,n);let f={},h=this.codec.createDeserializer();for(let[y,w]of u.structIterator()){let b=w.getMergedTraits().jsonName??y;f[y]=h.readObject(w,n[b])}throw this.mixin.decorateServiceException(Object.assign(p,c,{$fault:u.getMergedTraits().error,message:l},f),n)}getDefaultContentType(){return"application/json"}}});var Bm,sq=_(()=>{ge();rt();xe();xe();as();kA();CA();DA();Vm();pw();Bm=class extends hr{settings;constructor(e){super(),this.settings=e}async read(e,r){let o=qm(e)?Fm:void 0;return this._read(e,typeof r=="string"?JSON.parse(r,o):await Dd(r,this.serdeContext,e))}readObject(e,r){return this._read(e,r)}_read(e,r){let o=r!==null&&typeof r=="object",n=B.of(e);if(o){if(n.isStructSchema()){let s=r,a=n.isUnionSchema(),c={},u,{jsonName:l}=this.settings;l&&(u={});let d;a&&(d=new Bu(s,c));for(let[p,f]of n.structIterator()){let h=p;l&&(h=f.getMergedTraits().jsonName??h,u[h]=p),a&&d.mark(h),s[h]!=null&&(c[p]=this._read(f,s[h]))}if(a)d.writeUnknown();else if(typeof s.__type=="string")for(let p in s){let f=s[p],h=l?u[p]??p:p;h in c||(c[h]=f)}return c}if(Array.isArray(r)&&n.isListSchema()){let s=n.getValueSchema(),a=[];for(let c of r)a.push(this._read(s,c));return a}if(n.isMapSchema()){let s=n.getValueSchema(),a={};for(let c in r)c==="__proto__"&&hi(a),a[c]=this._read(s,r[c]);return a}}if(n.isBlobSchema()&&typeof r=="string")return fr(r);let i=n.getMergedTraits().mediaType;if(n.isStringSchema()&&typeof r=="string"&&i)return i==="application/json"||i.endsWith("+json")?Er.from(r):r;if(n.isTimestampSchema()&&r!=null)switch(qr(n,this.settings)){case 5:return Yf(r);case 6:return xu(r);case 7:return Qf(r);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",r),new Date(r)}if(n.isBigIntegerSchema()&&(typeof r=="number"||typeof r=="string"))return BigInt(r);if(n.isBigDecimalSchema()&&r!=null){if(r instanceof nt)return r;let s=r;return s.type==="bigDecimal"&&"string"in s?new nt(s.string,s.type):new nt(String(r),"bigDecimal")}if(n.isNumericSchema()&&typeof r=="string"){switch(r){case"Infinity":return 1/0;case"-Infinity":return-1/0;case"NaN":return NaN}return r}if(n.isDocumentSchema())if(o){let s=Array.isArray(r)?[]:{};for(let a in r){a==="__proto__"&&hi(s);let c=r[a];c instanceof nt?s[a]=c:s[a]=this._read(n,c)}return s}else return structuredClone(r);return r}}});var Yoe,KA,Qoe=_(()=>{xe();Yoe="\u039D",KA=class{values=new Map;counter=0;stage=0;createReplacer(){if(this.stage===1)throw new Error("@aws-sdk/core/protocols - JsonReplacer already created.");if(this.stage===2)throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");return this.stage=1,(e,r)=>{if(r instanceof nt){let o=`${Yoe+"nv"+this.counter++}_`+r.string;return this.values.set(`"${o}"`,r.string),o}if(typeof r=="bigint"){let o=r.toString(),n=`${Yoe+"b"+this.counter++}_`+o;return this.values.set(`"${n}"`,o),n}return r}}replaceInJson(e){if(this.stage===0)throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet.");if(this.stage===2)throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");if(this.stage=2,this.counter===0)return e;for(let[r,o]of this.values)e=e.replace(r,o);return e}}});var Zm,aq=_(()=>{ge();rt();xe();as();Qoe();pw();Zm=class extends hr{settings;buffer;useReplacer=!1;rootSchema;constructor(e){super(),this.settings=e}write(e,r){this.rootSchema=B.of(e),this.buffer=this._write(this.rootSchema,r)}flush(){let{rootSchema:e,useReplacer:r}=this;if(this.rootSchema=void 0,this.useReplacer=!1,e?.isStructSchema()||e?.isDocumentSchema()){if(!r)return JSON.stringify(this.buffer);let o=new KA;return o.replaceInJson(JSON.stringify(this.buffer,o.createReplacer(),0))}return this.buffer}writeDiscriminatedDocument(e,r){this.write(e,r),typeof this.buffer=="object"&&(this.buffer.__type=B.of(e).getName(!0))}_write(e,r,o){let n=r!==null&&typeof r=="object",i=B.of(e);if(n){if(i.isStructSchema()){let s=r,a={},{jsonName:c}=this.settings,u;c&&(u={});let l=0;for(let[d,p]of i.structIterator()){let f=this._write(p,s[d],i);if(f!==void 0){let h=d;c&&(h=p.getMergedTraits().jsonName??d,u[d]=h),a[h]=f,l++}}if(i.isUnionSchema()&&l===0){let{$unknown:d}=s;if(Array.isArray(d)){let[p,f]=d;p==="__proto__"&&hi(a),a[p]=this._write(15,f)}}else if(typeof s.__type=="string")for(let d in s){let p=s[d],f=c?u[d]??d:d;f in a||(a[f]=this._write(15,p))}return a}if(Array.isArray(r)&&i.isListSchema()){let s=i.getValueSchema(),a=[],c=!!i.getMergedTraits().sparse;for(let u of r)(c||u!=null)&&a.push(this._write(s,u));return a}if(i.isMapSchema()){let s=i.getValueSchema(),a={},c=!!i.getMergedTraits().sparse;for(let u in r){let l=r[u];(c||l!=null)&&(u==="__proto__"&&hi(a),a[u]=this._write(s,l))}return a}if(r instanceof Uint8Array&&i.isBlobSchema())return i===this.rootSchema?r:(this.serdeContext?.base64Encoder??Wt)(r);if(r instanceof Date&&(i.isTimestampSchema()||i.isDocumentSchema()))switch(qr(i,this.settings)){case 5:return r.toISOString().replace(".000Z","Z");case 6:return Oo(r);case 7:return r.getTime()/1e3;default:return console.warn("Missing timestamp format, using epoch seconds",r),r.getTime()/1e3}r instanceof nt&&(this.useReplacer=!0)}if(!(r===null&&o?.isStructSchema())){if(i.isStringSchema()){if(typeof r>"u"&&i.isIdempotencyToken())return Lo();let s=i.getMergedTraits().mediaType;return r!=null&&s&&(s==="application/json"||s.endsWith("+json"))?Er.from(r):r}if(typeof r=="number")return Math.abs(r)===1/0||isNaN(r)?String(r):r;if(typeof r=="string"&&i.isBlobSchema())return i===this.rootSchema?r:(this.serdeContext?.base64Encoder??Wt)(r);if(typeof r=="bigint"&&(this.useReplacer=!0),i.isDocumentSchema())if(n){if(r instanceof Uint8Array)return(this.serdeContext?.base64Encoder??Wt)(r);let s=Array.isArray(r)?[]:{};for(let a in r){let c=r[a];a==="__proto__"&&hi(s),c instanceof nt?(this.useReplacer=!0,s[a]=c):s[a]=this._write(i,c)}return s}else return structuredClone(r);return r}}}});var BA,eie=_(()=>{as();sq();aq();BA=class extends hr{settings;constructor(e){super(),this.settings=e}createSerializer(){let e=new Zm(this.settings);return e.setSerdeContext(this.serdeContext),e}createDeserializer(){let e=new Bm(this.settings);return e.setSerdeContext(this.serdeContext),e}}});var JA=U(WA=>{var wje=/[&<>"]/g,_je={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"};function bje(t){return t.replace(wje,e=>_je[e])}var Sje=/[&"'<>\r\n\u0085\u2028]/g,xje={"&":"&amp;",'"':"&quot;","'":"&apos;","<":"&lt;",">":"&gt;","\r":"&#x0D;","\n":"&#x0A;","\x85":"&#x85;","\u2028":"&#x2028;"};function Eje(t){return t.replace(Sje,e=>xje[e])}var ZA=class{value;constructor(e){this.value=e}toString(){return Eje(""+this.value)}},uq=class t{name;children;attributes={};static of(e,r,o){let n=new t(e);return r!==void 0&&n.addChildNode(new ZA(r)),o!==void 0&&n.withName(o),n}constructor(e,r=[]){this.name=e,this.children=r}withName(e){return this.name=e,this}addAttribute(e,r){return this.attributes[e]=r,this}addChildNode(e){return this.children.push(e),this}removeAttribute(e){return delete this.attributes[e],this}n(e){return this.name=e,this}c(e){return this.children.push(e),this}a(e,r){return r!=null&&(this.attributes[e]=r),this}cc(e,r,o=r){if(e[r]!=null){let n=t.of(r,e[r]).withName(o);this.c(n)}}l(e,r,o,n){e[r]!=null&&n().map(s=>{s.withName(o),this.c(s)})}lc(e,r,o,n){if(e[r]!=null){let i=n(),s=new t(o);i.map(a=>{s.c(a)}),this.c(s)}}toString(){let e=!!this.children.length,r=`<${this.name}`,o=this.attributes;for(let n of Object.keys(o)){let i=o[n];i!=null&&(r+=` ${n}="${bje(""+i)}"`)}return r+=e?`>${this.children.map(n=>n.toString()).join("")}</${this.name}>`:"/>"}};function cq(t){Object.defineProperty(t,"__proto__",{value:void 0,writable:!0,enumerable:!0,configurable:!0})}function $je(t){return new lq(t).parse()}var lq=class t{x;i=0;z;constructor(e){this.x=e,this.x=e.replace(/\r\n?/g,`
46
46
  `),this.z=this.x.length}parse(){let e=this,{z:r}=e;for(;e.i<r&&(e.trim(),!(e.i>=r));)if(e.isNext("<?"))e.readTo("?>"),e.trim();else if(e.isNext("<!--"))e.readTo("-->"),e.trim();else if(e.isNext("<!DOCTYPE",!1))e.skipDoctype(),e.trim();else if(e.x[e.i]==="<"){let o=e.parseTag();return{[o.tag]:o.value}}else throw new Error("@aws-sdk XML parse error: unexpected content.");throw new Error("@aws-sdk XML parse error: no root element.")}isNext(e,r=!0){let o=this;return r?o.x.startsWith(e,o.i):o.x.toLowerCase().startsWith(e.toLowerCase(),o.i)}readTo(e){let r=this,o=r.x.indexOf(e,r.i);if(o===-1)throw new Error(`@aws-sdk XML parse error: expected "${e}" not found.`);let n=r.x.slice(r.i,o);return r.i=o+e.length,n}trim(){let e=this;for(;e.i<e.z&&` \r
47
47
  `.includes(e.x[e.i]);)++e.i}readAttrValue(){let e=this,r=e.x[e.i];++e.i;let o="";for(;e.i<e.z&&e.x[e.i]!==r;)o+=e.x[e.i++];return++e.i,e.decodeEntities(o)}parseTag(){let e=this;++e.i;let r="";for(;e.i<e.z&&!` \r
48
48
  >/`.includes(e.x[e.i]);)r+=e.x[e.i++];let o=!1,n={};for(;e.i<e.z&&(e.trim(),!">/".includes(e.x[e.i]));){let l="";for(;e.i<e.z&&!`= \r
49
49
  >/?`.includes(e.x[e.i]);)l+=e.x[e.i++];if(e.trim(),e.x[e.i]!=="=")break;++e.i,e.trim(),l==="__proto__"&&cq(n),n[l]=e.readAttrValue(),o=!0}if(e.i>=e.z)throw new Error("@aws-sdk XML parse error: unexpected end of input.");if(e.x[e.i]==="/"){if(++e.i,e.i>=e.z||e.x[e.i]!==">")throw new Error("@aws-sdk XML parse error: expected > at the end of self-closing tag.");return++e.i,{tag:r,value:o?n:""}}if(e.x[e.i]!==">")throw new Error("@aws-sdk XML parse error: expected > at the end of opening tag.");++e.i;let i=[],s=[],a=!1;for(;e.i<e.z&&!e.isNext("</");)if(e.x[e.i]==="<")e.isNext("<!--")?e.readTo("-->"):e.isNext("<![CDATA[")?(e.i+=9,i.push(e.readTo("]]>"))):e.isNext("<?")?e.readTo("?>"):(a=!0,s.push(e.parseTag()));else{let l="";for(;e.i<e.z&&e.x[e.i]!=="<";)l+=e.x[e.i++];i.push(e.decodeEntities(l))}if(!e.isNext("</"))throw new Error(`@aws-sdk XML parse error: missing closing tag </${r}>.`);e.i+=2;let c=e.readTo(">").trim();if(c!==r)throw new Error(`@aws-sdk XML parse error: mismatched tags <${r}> and </${c}>.`);if(!o&&i.length===0&&!a)return{tag:r,value:""};if(!o&&!a){let l=i.length===1?i[0]:i.join("");return l.trim()===""&&l.includes(`
50
50
  `)?{tag:r,value:""}:{tag:r,value:l}}let u={};for(let l of i)l.trim()===""&&l.includes(`
51
- `)||(u["#text"]="#text"in u?u["#text"]+l:l);for(let l of s)l.tag==="__proto__"&&cq(u),l.tag in u?Array.isArray(u[l.tag])?u[l.tag].push(l.value):u[l.tag]=[u[l.tag],l.value]:u[l.tag]=l.value;for(let[l,d]of Object.entries(n))l==="__proto__"&&cq(u),u[l]=d;return{tag:r,value:u}}static ENTITIES={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};skipDoctype(){let e=this;e.i+=9;let r=0;for(;e.i<e.z;){let o=e.x[e.i];if(o==="[")++r;else if(o==="]")--r;else if(o===">"&&r===0){++e.i;return}++e.i}throw new Error("@aws-sdk XML parse error: unclosed DOCTYPE.")}decodeEntities(e){return e.replace(/&(?:#x([0-9a-fA-F]{1,6})|#(\d{1,7})|([a-zA-Z][a-zA-Z0-9]{0,30}));/g,(r,o,n,i)=>o?String.fromCharCode(parseInt(o,16)):n?String.fromCharCode(parseInt(n,10)):t.ENTITIES[i]??"")}};WA.XmlNode=uq;WA.XmlText=ZA;WA.parseXML=$je});var tie,Ju,XA=_(()=>{tie=Vt(JA());ve();ge();rt();xe();as();kA();pw();Ju=class extends mr{settings;stringDeserializer;constructor(e){super(),this.settings=e,this.stringDeserializer=new Cu(e)}setSerdeContext(e){this.serdeContext=e,this.stringDeserializer.setSerdeContext(e)}read(e,r,o){let n=B.of(e),i=n.getMemberSchemas();if(n.isStructSchema()&&n.isMemberSchema()&&!!Object.values(i).find(u=>!!u.getMemberTraits().eventPayload)){let u={},l=Object.keys(i)[0];return i[l].isBlobSchema()?u[l]=r:u[l]=this.read(i[l],r),u}let a=(this.serdeContext?.utf8Encoder??ur)(r),c=this.parseXml(a);return this.readSchema(e,o?c[o]:c)}readSchema(e,r){let o=B.of(e);if(o.isUnitSchema())return;let n=o.getMergedTraits();if(o.isListSchema()&&!Array.isArray(r))return this.readSchema(o,[r]);if(r==null)return r;if(typeof r=="object"){let i=!!n.xmlFlattened;if(o.isListSchema()){let a=o.getValueSchema(),c=[],u=a.getMergedTraits().xmlName??"member",l=i?r:(r[0]??r)[u];if(l==null)return c;let d=Array.isArray(l)?l:[l];for(let p of d)c.push(this.readSchema(a,p));return c}let s={};if(o.isMapSchema()){let a=o.getKeySchema(),c=o.getValueSchema(),u;i?u=Array.isArray(r)?r:[r]:u=Array.isArray(r.entry)?r.entry:[r.entry];let l=a.getMergedTraits().xmlName??"key",d=c.getMergedTraits().xmlName??"value";for(let p of u){let f=p[l],h=p[d];f==="__proto__"&&hi(s),s[f]=this.readSchema(c,h)}return s}if(o.isStructSchema()){let a=o.isUnionSchema(),c;a&&(c=new Bu(r,s));for(let[u,l]of o.structIterator()){let d=l.getMergedTraits(),p=d.httpPayload?d.xmlName??l.getName():l.getMemberTraits().xmlName??u;a&&c.mark(p),r[p]!=null&&(s[u]=this.readSchema(l,r[p]))}return a&&c.writeUnknown(),s}if(o.isDocumentSchema())return r;throw new Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${o.getName(!0)}`)}return o.isListSchema()?[]:o.isMapSchema()||o.isStructSchema()?{}:this.stringDeserializer.read(o,r)}parseXml(e){if(e.length){let r;try{r=(0,tie.parseXML)(e)}catch(s){throw s&&typeof s=="object"&&Object.defineProperty(s,"$responseBodyText",{value:e}),s}let o="#text",n=Object.keys(r)[0],i=r[n];return i[o]&&(i[n]=i[o],delete i[o]),wd(i)}return{}}}});var Wm,dq=_(()=>{ge();rt();xe();xe();as();Wm=class extends mr{settings;buffer;constructor(e){super(),this.settings=e}write(e,r,o=""){this.buffer===void 0&&(this.buffer="");let n=B.of(e);if(o&&!o.endsWith(".")&&(o+="."),n.isBlobSchema())(typeof r=="string"||r instanceof Uint8Array)&&(this.writeKey(o),this.writeValue((this.serdeContext?.base64Encoder??Wt)(r)));else if(n.isBooleanSchema()||n.isNumericSchema()||n.isStringSchema())r!=null?(this.writeKey(o),this.writeValue(String(r))):n.isIdempotencyToken()&&(this.writeKey(o),this.writeValue(Lo()));else if(n.isBigIntegerSchema())r!=null&&(this.writeKey(o),this.writeValue(String(r)));else if(n.isBigDecimalSchema())r!=null&&(this.writeKey(o),this.writeValue(r instanceof nt?r.string:String(r)));else if(n.isTimestampSchema()){if(r instanceof Date)switch(this.writeKey(o),qr(n,this.settings)){case 5:this.writeValue(r.toISOString().replace(".000Z","Z"));break;case 6:this.writeValue(Oo(r));break;case 7:this.writeValue(String(r.getTime()/1e3));break}}else if(n.isDocumentSchema())Array.isArray(r)?this.write(79,r,o):r instanceof Date?this.write(4,r,o):r instanceof Uint8Array?this.write(21,r,o):r&&typeof r=="object"?this.write(143,r,o):(this.writeKey(o),this.writeValue(String(r)));else if(n.isListSchema()){if(Array.isArray(r))if(r.length===0)this.settings.serializeEmptyLists&&(this.writeKey(o),this.writeValue(""));else{let i=n.getValueSchema(),s=this.settings.flattenLists||n.getMergedTraits().xmlFlattened,a=1;for(let c of r){if(c==null)continue;let u=i.getMergedTraits(),l=this.getKey("member",u.xmlName,u.ec2QueryName),d=s?`${o}${a}`:`${o}${l}.${a}`;this.write(i,c,d),++a}}}else if(n.isMapSchema()){if(r&&typeof r=="object"){let i=n.getKeySchema(),s=n.getValueSchema(),a=n.getMergedTraits().xmlFlattened,c=1;for(let u in r){let l=r[u];if(l==null)continue;let d=i.getMergedTraits(),p=this.getKey("key",d.xmlName,d.ec2QueryName),f=a?`${o}${c}.${p}`:`${o}entry.${c}.${p}`,h=s.getMergedTraits(),y=this.getKey("value",h.xmlName,h.ec2QueryName),w=a?`${o}${c}.${y}`:`${o}entry.${c}.${y}`;this.write(i,u,f),this.write(s,l,w),++c}}}else if(n.isStructSchema()){if(r&&typeof r=="object"){let i=!1;for(let[s,a]of n.structIterator()){if(r[s]==null&&!a.isIdempotencyToken())continue;let c=a.getMergedTraits(),u=this.getKey(s,c.xmlName,c.ec2QueryName,"struct"),l=`${o}${u}`;this.write(a,r[s],l),i=!0}if(!i&&n.isUnionSchema()){let{$unknown:s}=r;if(Array.isArray(s)){let[a,c]=s,u=`${o}${a}`;this.write(15,c,u)}}}}else if(!n.isUnitSchema())throw new Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${n.getName(!0)}`)}flush(){if(this.buffer===void 0)throw new Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer.");let e=this.buffer;return delete this.buffer,e}getKey(e,r,o,n){let{ec2:i,capitalizeKeys:s}=this.settings;if(i&&o)return o;let a=r??e;return s&&n==="struct"?a[0].toUpperCase()+a.slice(1):a}writeKey(e){e.endsWith(".")&&(e=e.slice(0,e.length-1)),this.buffer+=`&${Ji(e)}=`}writeValue(e){this.buffer+=Ji(e)}}});var Xu,pq=_(()=>{ge();rt();jm();XA();dq();Xu=class extends na{options;serializer;deserializer;mixin=new mi;constructor(e){super({defaultNamespace:e.defaultNamespace,errorTypeRegistries:e.errorTypeRegistries}),this.options=e;let r={timestampFormat:{useTrait:!0,default:5},httpBindings:!1,xmlNamespace:e.xmlNamespace,serviceNamespace:e.defaultNamespace,serializeEmptyLists:!0};this.serializer=new Wm(r),this.deserializer=new Ju(r)}getShapeId(){return"aws.protocols#awsQuery"}setSerdeContext(e){this.serializer.setSerdeContext(e),this.deserializer.setSerdeContext(e)}getPayloadCodec(){throw new Error("AWSQuery protocol has no payload codec.")}async serializeRequest(e,r,o){let n=await super.serializeRequest(e,r,o);n.path.endsWith("/")||(n.path+="/"),n.headers["content-type"]="application/x-www-form-urlencoded",(ii(e.input)==="unit"||!n.body)&&(n.body="");let i=e.name.split("#")[1]??e.name;return n.body=`Action=${i}&Version=${this.options.version}`+n.body,n.body.endsWith("&")&&(n.body=n.body.slice(-1)),n}async deserializeResponse(e,r,o){let n=this.deserializer,i=B.of(e.output),s={};if(o.statusCode>=300){let l=await sn(o.body,r);l.byteLength>0&&Object.assign(s,await n.read(15,l)),await this.handleError(e,r,o,s,this.deserializeMetadata(o))}for(let l in o.headers){let d=o.headers[l];delete o.headers[l],o.headers[l.toLowerCase()]=d}let a=e.name.split("#")[1]??e.name,c=i.isStructSchema()&&this.useNestedResult()?a+"Result":void 0,u=await sn(o.body,r);return u.byteLength>0&&Object.assign(s,await n.read(i,u,c)),s.$metadata=this.deserializeMetadata(o),s}useNestedResult(){return!0}async handleError(e,r,o,n,i){let s=this.loadQueryErrorCode(o,n)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,s,this.options.defaultNamespace);let a=this.loadQueryError(n)??{},c=this.loadQueryErrorMessage(n);a.message=c,a.Error={Type:a.Type,Code:a.Code,Message:c};let{errorSchema:u,errorMetadata:l}=await this.mixin.getErrorSchemaOrThrowBaseException(s,this.options.defaultNamespace,o,a,i,this.mixin.findQueryCompatibleError),d=B.of(u),p=this.compositeErrorRegistry.getErrorCtor(u)??Error,f=new p({}),h={Type:a.Error.Type,Code:a.Error.Code,Error:a.Error};for(let[y,w]of d.structIterator()){let b=w.getMergedTraits().xmlName??y,S=a[b]??n[b];h[y]=this.deserializer.readSchema(w,S)}throw this.mixin.decorateServiceException(Object.assign(f,l,{$fault:d.getMergedTraits().error,message:c},h),n)}loadQueryErrorCode(e,r){let o=(r.Errors?.[0]?.Error??r.Errors?.Error??r.Error)?.Code;if(o!==void 0)return o;if(e.statusCode==404)return"NotFound"}loadQueryError(e){return e.Errors?.[0]?.Error??e.Errors?.Error??e.Error}loadQueryErrorMessage(e){let r=this.loadQueryError(e);return r?.message??r?.Message??e.message??e.Message??"Unknown"}getDefaultContentType(){return"application/x-www-form-urlencoded"}}});var YA,rie=_(()=>{pq();YA=class extends Xu{options;constructor(e){super(e),this.options=e;let r={capitalizeKeys:!0,flattenLists:!0,serializeEmptyLists:!1,ec2:!0};Object.assign(this.serializer.settings,r)}getShapeId(){return"aws.protocols#ec2Query"}useNestedResult(){return!1}}});var nie,fq,oie,QA,mq=_(()=>{nie=Vt(JA());ve();tq();fq=(t,e)=>NA(t,e).then(r=>{if(r.length){let o;try{o=(0,nie.parseXML)(r)}catch(a){throw a&&typeof a=="object"&&Object.defineProperty(a,"$responseBodyText",{value:r}),a}let n="#text",i=Object.keys(o)[0],s=o[i];return s[n]&&(s[i]=s[n],delete s[n]),wd(s)}return{}}),oie=async(t,e)=>{let r=await fq(t,e);return r.Error&&(r.Error.message=r.Error.message??r.Error.Message),r},QA=(t,e)=>{if(e?.Error?.Code!==void 0)return e.Error.Code;if(e?.Code!==void 0)return e.Code;if(t.statusCode==404)return"NotFound"}});var Qn,Jm,hq=_(()=>{Qn=Vt(JA());ge();rt();xe();xe();as();Jm=class extends mr{settings;stringBuffer;byteBuffer;buffer;constructor(e){super(),this.settings=e}write(e,r){let o=B.of(e);if(o.isStringSchema()&&typeof r=="string")this.stringBuffer=r;else if(o.isBlobSchema())this.byteBuffer="byteLength"in r?r:(this.serdeContext?.base64Decoder??pr)(r);else{this.buffer=this.writeStruct(o,r,void 0);let n=o.getMergedTraits();n.httpPayload&&!n.xmlName&&this.buffer.withName(o.getName())}}flush(){if(this.byteBuffer!==void 0){let r=this.byteBuffer;return delete this.byteBuffer,r}if(this.stringBuffer!==void 0){let r=this.stringBuffer;return delete this.stringBuffer,r}let e=this.buffer;return this.settings.xmlNamespace&&(e?.attributes?.xmlns||e.addAttribute("xmlns",this.settings.xmlNamespace)),delete this.buffer,e.toString()}writeStruct(e,r,o){let n=e.getMergedTraits(),i=e.isMemberSchema()&&!n.httpPayload?e.getMemberTraits().xmlName??e.getMemberName():n.xmlName??e.getName();if(!i||!e.isStructSchema())throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${e.getName(!0)}.`);let s=Qn.XmlNode.of(i),[a,c]=this.getXmlnsAttribute(e,o);for(let[l,d]of e.structIterator()){let p=r[l];if(p!=null||d.isIdempotencyToken()){if(d.getMergedTraits().xmlAttribute){s.addAttribute(d.getMergedTraits().xmlName??l,this.writeSimple(d,p));continue}if(d.isListSchema())this.writeList(d,p,s,c);else if(d.isMapSchema())this.writeMap(d,p,s,c);else if(d.isStructSchema())s.addChildNode(this.writeStruct(d,p,c));else{let f=Qn.XmlNode.of(d.getMergedTraits().xmlName??d.getMemberName());this.writeSimpleInto(d,p,f,c),s.addChildNode(f)}}}let{$unknown:u}=r;if(u&&e.isUnionSchema()&&Array.isArray(u)&&Object.keys(r).length===1){let[l,d]=u,p=Qn.XmlNode.of(l);if(typeof d!="string")if(r instanceof Qn.XmlNode||r instanceof Qn.XmlText)s.addChildNode(r);else throw new Error("@aws-sdk - $unknown union member in XML requires value of type string, @aws-sdk/xml-builder::XmlNode or XmlText.");this.writeSimpleInto(0,d,p,c),s.addChildNode(p)}return c&&s.addAttribute(a,c),s}writeList(e,r,o,n){if(!e.isMemberSchema())throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${e.getName(!0)}`);let i=e.getMergedTraits(),s=e.getValueSchema(),a=s.getMergedTraits(),c=!!a.sparse,u=!!i.xmlFlattened,[l,d]=this.getXmlnsAttribute(e,n),p=(f,h)=>{if(s.isListSchema())this.writeList(s,Array.isArray(h)?h:[h],f,d);else if(s.isMapSchema())this.writeMap(s,h,f,d);else if(s.isStructSchema()){let y=this.writeStruct(s,h,d);f.addChildNode(y.withName(u?i.xmlName??e.getMemberName():a.xmlName??"member"))}else{let y=Qn.XmlNode.of(u?i.xmlName??e.getMemberName():a.xmlName??"member");this.writeSimpleInto(s,h,y,d),f.addChildNode(y)}};if(u)for(let f of r)(c||f!=null)&&p(o,f);else{let f=Qn.XmlNode.of(i.xmlName??e.getMemberName());d&&f.addAttribute(l,d);for(let h of r)(c||h!=null)&&p(f,h);o.addChildNode(f)}}writeMap(e,r,o,n,i=!1){if(!e.isMemberSchema())throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${e.getName(!0)}`);let s=e.getMergedTraits(),a=e.getKeySchema(),u=a.getMergedTraits().xmlName??"key",l=e.getValueSchema(),d=l.getMergedTraits(),p=d.xmlName??"value",f=!!d.sparse,h=!!s.xmlFlattened,[y,w]=this.getXmlnsAttribute(e,n),b=(S,x,R)=>{let T=Qn.XmlNode.of(u,x),[M,Z]=this.getXmlnsAttribute(a,w);Z&&T.addAttribute(M,Z),S.addChildNode(T);let te=Qn.XmlNode.of(p);l.isListSchema()?this.writeList(l,R,te,w):l.isMapSchema()?this.writeMap(l,R,te,w,!0):l.isStructSchema()?te=this.writeStruct(l,R,w):this.writeSimpleInto(l,R,te,w),S.addChildNode(te)};if(h)for(let S in r){let x=r[S];if(f||x!=null){let R=Qn.XmlNode.of(s.xmlName??e.getMemberName());b(R,S,x),o.addChildNode(R)}}else{let S;i||(S=Qn.XmlNode.of(s.xmlName??e.getMemberName()),w&&S.addAttribute(y,w),o.addChildNode(S));for(let x in r){let R=r[x];if(f||R!=null){let T=Qn.XmlNode.of("entry");b(T,x,R),(i?o:S).addChildNode(T)}}}}writeSimple(e,r){if(r===null)throw new Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value.");let o=B.of(e),n=null;if(r&&typeof r=="object")if(o.isBlobSchema())n=(this.serdeContext?.base64Encoder??Wt)(r);else if(o.isTimestampSchema()&&r instanceof Date)switch(qr(o,this.settings)){case 5:n=r.toISOString().replace(".000Z","Z");break;case 6:n=Oo(r);break;case 7:n=String(r.getTime()/1e3);break;default:console.warn("Missing timestamp format, using http date",r),n=Oo(r);break}else{if(o.isBigDecimalSchema()&&r)return r instanceof nt?r.string:String(r);throw o.isMapSchema()||o.isListSchema()?new Error("@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead."):new Error(`@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${o.getName(!0)}`)}if((o.isBooleanSchema()||o.isNumericSchema()||o.isBigIntegerSchema()||o.isBigDecimalSchema())&&(n=String(r)),o.isStringSchema()&&(r===void 0&&o.isIdempotencyToken()?n=Lo():n=String(r)),n===null)throw new Error(`Unhandled schema-value pair ${o.getName(!0)}=${r}`);return n}writeSimpleInto(e,r,o,n){let i=this.writeSimple(e,r),s=B.of(e),a=new Qn.XmlText(i),[c,u]=this.getXmlnsAttribute(s,n);u&&o.addAttribute(c,u),o.addChildNode(a)}getXmlnsAttribute(e,r){let o=e.getMergedTraits(),[n,i]=o.xmlNamespace??[];return i&&i!==r?[n?`xmlns:${n}`:"xmlns",i]:[void 0,void 0]}}});var Xm,gq=_(()=>{as();XA();hq();Xm=class extends mr{settings;constructor(e){super(),this.settings=e}createSerializer(){let e=new Jm(this.settings);return e.setSerdeContext(this.serdeContext),e}createDeserializer(){let e=new Ju(this.settings);return e.setSerdeContext(this.serdeContext),e}}});var eP,iie=_(()=>{ge();rt();jm();mq();gq();eP=class extends Tu{codec;serializer;deserializer;mixin=new mi;constructor(e){super(e);let r={timestampFormat:{useTrait:!0,default:5},httpBindings:!0,xmlNamespace:e.xmlNamespace,serviceNamespace:e.defaultNamespace};this.codec=new Xm(r),this.serializer=new Du(this.codec.createSerializer(),r),this.deserializer=new Ou(this.codec.createDeserializer(),r)}getPayloadCodec(){return this.codec}getShapeId(){return"aws.protocols#restXml"}async serializeRequest(e,r,o){let n=await super.serializeRequest(e,r,o),i=B.of(e.input);if(!n.headers["content-type"]){let s=this.mixin.resolveRestContentType(this.getDefaultContentType(),i);s&&(n.headers["content-type"]=s)}return typeof n.body=="string"&&n.headers["content-type"]===this.getDefaultContentType()&&!n.body.startsWith("<?xml ")&&!this.hasUnstructuredPayloadBinding(i)&&(n.body='<?xml version="1.0" encoding="UTF-8"?>'+n.body),n}async deserializeResponse(e,r,o){return super.deserializeResponse(e,r,o)}async handleError(e,r,o,n,i){let s=QA(o,n)??"Unknown";if(this.mixin.compose(this.compositeErrorRegistry,s,this.options.defaultNamespace),n.Error&&typeof n.Error=="object")for(let y of Object.keys(n.Error))n[y]=n.Error[y],y.toLowerCase()==="message"&&(n.message=n.Error[y]);n.RequestId&&!i.requestId&&(i.requestId=n.RequestId);let{errorSchema:a,errorMetadata:c}=await this.mixin.getErrorSchemaOrThrowBaseException(s,this.options.defaultNamespace,o,n,i),u=B.of(a),l=n.Error?.message??n.Error?.Message??n.message??n.Message??"UnknownError",d=this.compositeErrorRegistry.getErrorCtor(a)??Error,p=new d({});await this.deserializeHttpMessage(a,r,o,n);let f={},h=this.codec.createDeserializer();for(let[y,w]of u.structIterator()){let b=w.getMergedTraits().xmlName??y,S=n.Error?.[b]??n[b];f[y]=h.readSchema(w,S)}throw this.mixin.decorateServiceException(Object.assign(p,c,{$fault:u.getMergedTraits().error,message:l},f),n)}getDefaultContentType(){return"application/xml"}hasUnstructuredPayloadBinding(e){for(let[,r]of e.structIterator())if(r.getMergedTraits().httpPayload)return!(r.isStructSchema()||r.isMapSchema()||r.isListSchema());return!1}}});var sie,aie=_(()=>{xe();sie=t=>{if(t!=null)return typeof t=="object"&&"__type"in t&&delete t.__type,uR(t)}});var cie,uie,lie,die=_(()=>{cie=t=>{if(t==null)return t;if(typeof t=="number"||typeof t=="bigint"){let e=new Error(`Received number ${t} where a string was expected.`);return e.name="Warning",console.warn(e),String(t)}if(typeof t=="boolean"){let e=new Error(`Received boolean ${t} where a string was expected.`);return e.name="Warning",console.warn(e),String(t)}return t},uie=t=>{if(t==null)return t;if(typeof t=="string"){let e=t.toLowerCase();if(t!==""&&e!=="false"&&e!=="true"){let r=new Error(`Received string "${t}" where a boolean was expected.`);r.name="Warning",console.warn(r)}return t!==""&&e!=="false"}return t},lie=t=>{if(t==null)return t;if(typeof t=="string"){let e=Number(t);if(e.toString()!==t){let r=new Error(`Received string "${t}" where a number was expected.`);return r.name="Warning",console.warn(r),t}return e}return t}});var yq={};Ht(yq,{AwsEc2QueryProtocol:()=>YA,AwsJson1_0Protocol:()=>GA,AwsJson1_1Protocol:()=>HA,AwsJsonRpcProtocol:()=>Wu,AwsQueryProtocol:()=>Xu,AwsRestJsonProtocol:()=>Sa,AwsRestXmlProtocol:()=>eP,AwsSmithyRpcV2CborProtocol:()=>PA,JsonCodec:()=>BA,JsonCodec2:()=>Zu,JsonShapeDeserializer:()=>Bm,JsonShapeDeserializer2:()=>Gm,JsonShapeSerializer:()=>Zm,JsonShapeSerializer2:()=>Km,QueryShapeSerializer:()=>Wm,XmlCodec:()=>Xm,XmlShapeDeserializer:()=>Ju,XmlShapeSerializer:()=>Jm,_toBool:()=>uie,_toNum:()=>lie,_toStr:()=>cie,awsExpectUnion:()=>sie,loadJsonRpcErrorCode:()=>MA,loadRestJsonErrorCode:()=>zA,loadRestXmlErrorCode:()=>QA,parseJsonBody:()=>Dd,parseJsonErrorBody:()=>Foe,parseXmlBody:()=>fq,parseXmlErrorBody:()=>oie});var Nd=_(()=>{Loe();Woe();Joe();VA();Xoe();eie();sq();aq();qA();nq();iq();Vm();rie();pq();dq();iie();gq();XA();hq();mq();aie();die()});var fw,zd,tP,pie,gie,rP,vq,fie,wq,Ym,mie,hie,Rje,go,Ije,yie,vie=_(()=>{Jt();fw="ref",zd=-1,tP=!0,pie="isSet",gie="PartitionResult",rP="booleanEquals",vq="getAttr",fie={[fw]:"Endpoint"},wq={[fw]:gie},Ym={},mie=[{[fw]:"Region"}],hie={conditions:[[pie,[fie]],[pie,mie],["aws.partition",mie,gie],[rP,[{[fw]:"UseFIPS"},tP]],[rP,[{[fw]:"UseDualStack"},tP]],[rP,[{fn:vq,argv:[wq,"supportsDualStack"]},tP]],[rP,[{fn:vq,argv:[wq,"supportsFIPS"]},tP]],["stringEquals",[{fn:vq,argv:[wq,"name"]},"aws-us-gov"]]],results:[[zd],[zd,"Invalid Configuration: FIPS and custom endpoint are not supported"],[zd,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[fie,Ym],["https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",Ym],[zd,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://oidc.{Region}.amazonaws.com",Ym],["https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}",Ym],[zd,"FIPS is enabled but this partition does not support FIPS"],["https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}",Ym],[zd,"DualStack is enabled but this partition does not support DualStack"],["https://oidc.{Region}.{PartitionResult#dnsSuffix}",Ym],[zd,"Invalid Configuration: Missing Region"]]},Rje=2,go=1e8,Ije=new Int32Array([-1,1,-1,0,13,3,1,4,go+12,2,5,go+12,3,8,6,4,7,go+11,5,go+9,go+10,4,11,9,6,10,go+8,7,go+6,go+7,5,12,go+5,6,go+4,go+5,3,go+1,14,4,go+2,go+3]),yie=ci.from(Ije,Rje,hie.conditions,hie.results)});var Aje,wie,_ie=_(()=>{Nt();Jt();vie();Aje=new ui({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),wie=(t,e={})=>Aje.get(t,()=>ra(yie,{endpointParams:t,logger:e.logger}));ho.aws=ns});var Br,nP=_(()=>{ve();Br=class t extends si{constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}}});var mw,hw,gw,yw,vw,ww,_w,bw,Sw,xw,Ew,_q=_(()=>{nP();mw=class t extends Br{name="AccessDeniedException";$fault="client";error;reason;error_description;constructor(e){super({name:"AccessDeniedException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error,this.reason=e.reason,this.error_description=e.error_description}},hw=class t extends Br{name="AuthorizationPendingException";$fault="client";error;error_description;constructor(e){super({name:"AuthorizationPendingException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error,this.error_description=e.error_description}},gw=class t extends Br{name="ExpiredTokenException";$fault="client";error;error_description;constructor(e){super({name:"ExpiredTokenException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error,this.error_description=e.error_description}},yw=class t extends Br{name="InternalServerException";$fault="server";error;error_description;constructor(e){super({name:"InternalServerException",$fault:"server",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error,this.error_description=e.error_description}},vw=class t extends Br{name="InvalidClientException";$fault="client";error;error_description;constructor(e){super({name:"InvalidClientException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error,this.error_description=e.error_description}},ww=class t extends Br{name="InvalidGrantException";$fault="client";error;error_description;constructor(e){super({name:"InvalidGrantException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error,this.error_description=e.error_description}},_w=class t extends Br{name="InvalidRequestException";$fault="client";error;reason;error_description;constructor(e){super({name:"InvalidRequestException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error,this.reason=e.reason,this.error_description=e.error_description}},bw=class t extends Br{name="InvalidScopeException";$fault="client";error;error_description;constructor(e){super({name:"InvalidScopeException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error,this.error_description=e.error_description}},Sw=class t extends Br{name="SlowDownException";$fault="client";error;error_description;constructor(e){super({name:"SlowDownException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error,this.error_description=e.error_description}},xw=class t extends Br{name="UnauthorizedClientException";$fault="client";error;error_description;constructor(e){super({name:"UnauthorizedClientException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error,this.error_description=e.error_description}},Ew=class t extends Br{name="UnsupportedGrantTypeException";$fault="client";error;error_description;constructor(e){super({name:"UnsupportedGrantTypeException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error,this.error_description=e.error_description}}});var Pje,kje,Tje,Cje,Oje,Dje,Nje,zje,Mje,Uje,Lje,jje,Fje,qje,Vje,Gje,Hje,Kje,Bje,Zje,xa,Wje,Jje,Xje,Yje,Qje,hr,e4e,cs,t4e,r4e,us,n4e,bie,Sie,o4e,xie,i4e,s4e,a4e,Rr,Eie,$ie,gi,Rie,Iie,Aie,Pie,kie,Tie,Cie,Oie,Die,Nie,zie,bq,c4e,u4e,l4e,d4e,Mie,Uie,Lie,Sq,oP=_(()=>{rt();_q();nP();Pje="AccessDeniedException",kje="AuthorizationPendingException",Tje="AccessToken",Cje="ClientSecret",Oje="CreateToken",Dje="CreateTokenRequest",Nje="CreateTokenResponse",zje="CodeVerifier",Mje="ExpiredTokenException",Uje="InvalidClientException",Lje="InvalidGrantException",jje="InvalidRequestException",Fje="InternalServerException",qje="InvalidScopeException",Vje="IdToken",Gje="RefreshToken",Hje="SlowDownException",Kje="UnauthorizedClientException",Bje="UnsupportedGrantTypeException",Zje="accessToken",xa="client",Wje="clientId",Jje="clientSecret",Xje="codeVerifier",Yje="code",Qje="deviceCode",hr="error",e4e="expiresIn",cs="error_description",t4e="grantType",r4e="http",us="httpError",n4e="idToken",bie="reason",Sie="refreshToken",o4e="redirectUri",xie="smithy.ts.sdk.synthetic.com.amazonaws.ssooidc",i4e="scope",s4e="server",a4e="tokenType",Rr="com.amazonaws.ssooidc",Eie=new Zt(xie),$ie=[-3,xie,"SSOOIDCServiceException",0,[],[]];Eie.registerError($ie,Br);gi=new Zt(Rr),Rie=[-3,Rr,Pje,{[hr]:xa,[us]:400},[hr,bie,cs],[0,0,0]];gi.registerError(Rie,mw);Iie=[-3,Rr,kje,{[hr]:xa,[us]:400},[hr,cs],[0,0]];gi.registerError(Iie,hw);Aie=[-3,Rr,Mje,{[hr]:xa,[us]:400},[hr,cs],[0,0]];gi.registerError(Aie,gw);Pie=[-3,Rr,Fje,{[hr]:s4e,[us]:500},[hr,cs],[0,0]];gi.registerError(Pie,yw);kie=[-3,Rr,Uje,{[hr]:xa,[us]:401},[hr,cs],[0,0]];gi.registerError(kie,vw);Tie=[-3,Rr,Lje,{[hr]:xa,[us]:400},[hr,cs],[0,0]];gi.registerError(Tie,ww);Cie=[-3,Rr,jje,{[hr]:xa,[us]:400},[hr,bie,cs],[0,0,0]];gi.registerError(Cie,_w);Oie=[-3,Rr,qje,{[hr]:xa,[us]:400},[hr,cs],[0,0]];gi.registerError(Oie,bw);Die=[-3,Rr,Hje,{[hr]:xa,[us]:400},[hr,cs],[0,0]];gi.registerError(Die,Sw);Nie=[-3,Rr,Kje,{[hr]:xa,[us]:400},[hr,cs],[0,0]];gi.registerError(Nie,xw);zie=[-3,Rr,Bje,{[hr]:xa,[us]:400},[hr,cs],[0,0]];gi.registerError(zie,Ew);bq=[Eie,gi],c4e=[0,Rr,Tje,8,0],u4e=[0,Rr,Cje,8,0],l4e=[0,Rr,zje,8,0],d4e=[0,Rr,Vje,8,0],Mie=[0,Rr,Gje,8,0],Uie=[3,Rr,Dje,0,[Wje,Jje,t4e,Qje,Yje,Sie,i4e,o4e,Xje],[0,[()=>u4e,0],0,0,0,[()=>Mie,0],64,0,[()=>l4e,0]],3],Lie=[3,Rr,Nje,0,[Zje,a4e,e4e,Sie,n4e],[[()=>c4e,0],0,1,[()=>Mie,0],[()=>d4e,0]]],Sq=[9,Rr,Oje,{[r4e]:["POST","/token",200]},()=>Uie,()=>Lie]});var jie,Fie=_(()=>{Pn();Nd();Yn();gc();ve();ge();xe();C6();_ie();oP();jie=t=>({apiVersion:"2019-06-10",base64Decoder:t?.base64Decoder??pr,base64Encoder:t?.base64Encoder??Wt,disableHostPrefix:t?.disableHostPrefix??!1,endpointProvider:t?.endpointProvider??wie,extensions:t?.extensions??[],httpAuthSchemeProvider:t?.httpAuthSchemeProvider??goe,httpAuthSchemes:t?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4"),signer:new Gr},{schemeId:"smithy.api#noAuth",identityProvider:e=>e.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new An}],logger:t?.logger??new mo,protocol:t?.protocol??Sa,protocolSettings:t?.protocolSettings??{defaultNamespace:"com.amazonaws.ssooidc",errorTypeRegistries:bq,version:"2019-06-10",serviceTarget:"AWSSSOOIDCService"},serviceId:t?.serviceId??"SSO OIDC",sha256:t?.sha256??Xi,urlParser:t?.urlParser??nn,utf8Decoder:t?.utf8Decoder??Tr,utf8Encoder:t?.utf8Encoder??ur})});var iP,qie,Vie=_(()=>{iw();Nt();Pn();ve();Dt();jo();xe();iP=Vt(Gu());Fie();qie=t=>{Gs(process.version);let e=ea(t),r=()=>e().then(Vs),o=jie(t);Ls(process.version);let n={profile:t?.profile,logger:o.logger};return{...o,...t,runtime:"node",defaultsMode:e,authSchemePreference:t?.authSchemePreference??Ie(is,n),bodyLengthChecker:t?.bodyLengthChecker??Zs,defaultUserAgentProvider:t?.defaultUserAgentProvider??rs({serviceId:o.serviceId,clientVersion:Hu.version}),maxAttempts:t?.maxAttempts??Ie(ca,t),region:t?.region??Ie(on,{...Xn,...n}),requestHandler:iP.NodeHttpHandler.create(t?.requestHandler??r),retryMode:t?.retryMode??Ie({...la,default:async()=>(await r()).retryMode||li},t),streamCollector:t?.streamCollector??iP.streamCollector,useDualstackEndpoint:t?.useDualstackEndpoint??Ie(Ys,n),useFipsEndpoint:t?.useFipsEndpoint??Ie(Qs,n),userAgentAppId:t?.userAgentAppId??Ie(ga,n)}}});var Gie,Hie,Kie=_(()=>{Gie=t=>{let e=t.httpAuthSchemes,r=t.httpAuthSchemeProvider,o=t.credentials;return{setHttpAuthScheme(n){let i=e.findIndex(s=>s.schemeId===n.schemeId);i===-1?e.push(n):e.splice(i,1,n)},httpAuthSchemes(){return e},setHttpAuthSchemeProvider(n){r=n},httpAuthSchemeProvider(){return r},setCredentials(n){o=n},credentials(){return o}}},Hie=t=>({httpAuthSchemes:t.httpAuthSchemes(),httpAuthSchemeProvider:t.httpAuthSchemeProvider(),credentials:t.credentials()})});var Bie,Zie=_(()=>{Nt();ve();ge();Kie();Bie=(t,e)=>{let r=Object.assign(ya(t),Bi(t),oa(t),Gie(t));return e.forEach(o=>o.configure(r)),Object.assign(t,va(r),Hs(r),ia(r),Hie(r))}});var $w,xq=_(()=>{Nt();Yn();ve();Dt();Jt();ge();jo();rt();C6();O6();Vie();Zie();$w=class extends Rn{config;constructor(...[e]){let r=qie(e||{});super(r),this.initConfig=r;let o=voe(r),n=ma(o),i=ua(n),s=No(i),a=s,c=pc(a),u=yoe(c),l=Bie(u,e?.extensions||[]);this.config=l,this.middlewareStack.use(Fs(this.config)),this.middlewareStack.use(ha(this.config)),this.middlewareStack.use(yc(this.config)),this.middlewareStack.use(sa(this.config)),this.middlewareStack.use(da(this.config)),this.middlewareStack.use(pa(this.config)),this.middlewareStack.use(fa(this.config)),this.middlewareStack.use(es(this.config,{httpAuthSchemeParametersProvider:hoe,identityProviderConfigProvider:async d=>new Fo({"aws.auth#sigv4":d.credentials})})),this.middlewareStack.use(ts(this.config))}destroy(){super.destroy()}}});var Wie,Jie,Xie,Yie=_(()=>{ve();Jt();O6();Wie=Ks(woe,"AWSSSOOIDCService","SSOOIDCClient",fc),Jie={},Xie=(t,e,r,o)=>[]});var Rw,Eq=_(()=>{Yie();oP();Rw=class extends Wie(Jie,Xie,"CreateToken",Sq){}});var p4e,sP,Qie=_(()=>{ve();Eq();xq();p4e={CreateTokenCommand:Rw},sP=class extends $w{};qs(p4e,sP)});var ese=_(()=>{Eq()});var f4e,m4e,tse=_(()=>{f4e={KMS_ACCESS_DENIED:"KMS_AccessDeniedException"},m4e={KMS_DISABLED_KEY:"KMS_DisabledException",KMS_INVALID_KEY_USAGE:"KMS_InvalidKeyUsageException",KMS_INVALID_STATE:"KMS_InvalidStateException",KMS_KEY_NOT_FOUND:"KMS_NotFoundException"}});var rse=_(()=>{});var $q={};Ht($q,{$Command:()=>Wn,AccessDeniedException:()=>mw,AccessDeniedException$:()=>Rie,AccessDeniedExceptionReason:()=>f4e,AuthorizationPendingException:()=>hw,AuthorizationPendingException$:()=>Iie,CreateToken$:()=>Sq,CreateTokenCommand:()=>Rw,CreateTokenRequest$:()=>Uie,CreateTokenResponse$:()=>Lie,ExpiredTokenException:()=>gw,ExpiredTokenException$:()=>Aie,InternalServerException:()=>yw,InternalServerException$:()=>Pie,InvalidClientException:()=>vw,InvalidClientException$:()=>kie,InvalidGrantException:()=>ww,InvalidGrantException$:()=>Tie,InvalidRequestException:()=>_w,InvalidRequestException$:()=>Cie,InvalidRequestExceptionReason:()=>m4e,InvalidScopeException:()=>bw,InvalidScopeException$:()=>Oie,SSOOIDC:()=>sP,SSOOIDCClient:()=>$w,SSOOIDCServiceException:()=>Br,SSOOIDCServiceException$:()=>$ie,SlowDownException:()=>Sw,SlowDownException$:()=>Die,UnauthorizedClientException:()=>xw,UnauthorizedClientException$:()=>Nie,UnsupportedGrantTypeException:()=>Ew,UnsupportedGrantTypeException$:()=>zie,__Client:()=>Rn,errorTypeRegistries:()=>bq});var Rq=_(()=>{xq();Qie();ese();ve();oP();tse();_q();rse();nP()});var sse=U(Iw=>{var{setTokenFeature:h4e}=(Nt(),re(os)),{getBearerTokenEnvKey:g4e}=(Pn(),re(sA)),{TokenProviderError:ls,getSSOTokenFilepath:y4e,parseKnownFiles:v4e,getProfileName:w4e,loadSsoSessionData:_4e,getSSOTokenFromFile:b4e,memoize:S4e,chain:x4e}=(Dt(),re(zo)),{promises:E4e}=io("node:fs"),$4e=({logger:t,signingName:e}={})=>async()=>{if(t?.debug?.("@aws-sdk/token-providers - fromEnvSigningName"),!e)throw new ls("Please pass 'signingName' to compute environment variable key",{logger:t});let r=g4e(e);if(!(r in process.env))throw new ls(`Token not present in '${r}' environment variable`,{logger:t});let o={token:process.env[r]};return h4e(o,"BEARER_SERVICE_ENV_VARS","3"),o},R4e=300*1e3,Iq="To refresh this SSO session run 'aws sso login' with the corresponding profile.",I4e=async(t,e={},r)=>{let{SSOOIDCClient:o}=(Rq(),re($q)),n=s=>e.clientConfig?.[s]??e.parentClientConfig?.[s]??r?.[s];return new o(Object.assign({},e.clientConfig??{},{region:t??e.clientConfig?.region,logger:n("logger"),userAgentAppId:n("userAgentAppId")}))},A4e=async(t,e,r={},o)=>{let{CreateTokenCommand:n}=(Rq(),re($q));return(await I4e(e,r,o)).send(new n({clientId:t.clientId,clientSecret:t.clientSecret,refreshToken:t.refreshToken,grantType:"refresh_token"}))},nse=t=>{if(t.expiration&&t.expiration.getTime()<Date.now())throw new ls(`Token is expired. ${Iq}`,!1)},Md=(t,e,r=!1)=>{if(typeof e>"u")throw new ls(`Value not present for '${t}' in SSO Token${r?". Cannot refresh":""}. ${Iq}`,!1)},{writeFile:P4e}=E4e,k4e=(t,e)=>{let r=y4e(t),o=JSON.stringify(e,null,2);return P4e(r,o)},ose=new Map,ise=(t={})=>async({callerClientConfig:e}={})=>{t.logger?.debug("@aws-sdk/token-providers - fromSso");let r=await v4e(t),o=w4e({profile:t.profile??e?.profile}),n=r[o];if(n){if(!n.sso_session)throw new ls(`Profile '${o}' is missing required property 'sso_session'.`)}else throw new ls(`Profile '${o}' could not be found in shared credentials file.`,!1);let i=n.sso_session,a=(await _4e(t))[i];if(!a)throw new ls(`Sso session '${i}' could not be found in shared credentials file.`,!1);for(let h of["sso_start_url","sso_region"])if(!a[h])throw new ls(`Sso session '${i}' is missing required property '${h}'.`,!1);a.sso_start_url;let c=a.sso_region,u;try{u=await b4e(i)}catch{throw new ls(`The SSO session token associated with profile=${o} was not found or is invalid. ${Iq}`,!1)}Md("accessToken",u.accessToken),Md("expiresAt",u.expiresAt);let{accessToken:l,expiresAt:d}=u,p={token:l,expiration:new Date(d)};if(p.expiration.getTime()-Date.now()>R4e)return p;let f=ose.get(i)??0;if(Date.now()-f<30*1e3)return nse(p),p;Md("clientId",u.clientId,!0),Md("clientSecret",u.clientSecret,!0),Md("refreshToken",u.refreshToken,!0);try{ose.set(i,Date.now());let h=await A4e(u,c,t,e);Md("accessToken",h.accessToken),Md("expiresIn",h.expiresIn);let y=new Date(Date.now()+h.expiresIn*1e3);try{await k4e(i,{...u,accessToken:h.accessToken,expiresAt:y.toISOString(),refreshToken:h.refreshToken})}catch{}return{token:h.accessToken,expiration:y}}catch{return nse(p),p}},T4e=({token:t,logger:e})=>async()=>{if(e?.debug("@aws-sdk/token-providers - fromStatic"),!t||!t.token)throw new ls("Please pass a valid token to fromStatic",!1);return t},C4e=(t={})=>S4e(x4e(ise(t),async()=>{throw new ls("Could not load token from any providers",!1)}),e=>e.expiration!==void 0&&e.expiration.getTime()-Date.now()<3e5,e=>e.expiration!==void 0);Iw.fromEnvSigningName=$4e;Iw.fromSso=ise;Iw.fromStatic=T4e;Iw.nodeProvider=C4e});function O4e(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"awsssoportal",region:t.region},propertiesExtractor:(e,r)=>({signingProperties:{config:e,context:r}})}}function D4e(t){return{schemeId:"smithy.api#noAuth"}}var ase,cse,use,Aq=_(()=>{Pn();ve();ase=async(t,e,r)=>({operation:Bt(e).operation,region:await jt(t.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});cse=t=>{let e=[];return t.operation==="GetRoleCredentials"?e.push(D4e(t)):e.push(O4e(t)),e},use=t=>{let e=wa(t);return Object.assign(e,{authSchemePreference:jt(t.authSchemePreference??[])})}});var lse,dse,Pq=_(()=>{lse=t=>Object.assign(t,{useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,defaultSigningName:"awsssoportal"}),dse={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}});var Aw,Ud,aP,pse,gse,cP,kq,fse,Tq,Qm,mse,hse,N4e,yo,z4e,yse,vse=_(()=>{Jt();Aw="ref",Ud=-1,aP=!0,pse="isSet",gse="PartitionResult",cP="booleanEquals",kq="getAttr",fse={[Aw]:"Endpoint"},Tq={[Aw]:gse},Qm={},mse=[{[Aw]:"Region"}],hse={conditions:[[pse,[fse]],[pse,mse],["aws.partition",mse,gse],[cP,[{[Aw]:"UseFIPS"},aP]],[cP,[{[Aw]:"UseDualStack"},aP]],[cP,[{fn:kq,argv:[Tq,"supportsDualStack"]},aP]],[cP,[{fn:kq,argv:[Tq,"supportsFIPS"]},aP]],["stringEquals",[{fn:kq,argv:[Tq,"name"]},"aws-us-gov"]]],results:[[Ud],[Ud,"Invalid Configuration: FIPS and custom endpoint are not supported"],[Ud,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[fse,Qm],["https://portal.sso-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",Qm],[Ud,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://portal.sso.{Region}.amazonaws.com",Qm],["https://portal.sso-fips.{Region}.{PartitionResult#dnsSuffix}",Qm],[Ud,"FIPS is enabled but this partition does not support FIPS"],["https://portal.sso.{Region}.{PartitionResult#dualStackDnsSuffix}",Qm],[Ud,"DualStack is enabled but this partition does not support DualStack"],["https://portal.sso.{Region}.{PartitionResult#dnsSuffix}",Qm],[Ud,"Invalid Configuration: Missing Region"]]},N4e=2,yo=1e8,z4e=new Int32Array([-1,1,-1,0,13,3,1,4,yo+12,2,5,yo+12,3,8,6,4,7,yo+11,5,yo+9,yo+10,4,11,9,6,10,yo+8,7,yo+6,yo+7,5,12,yo+5,6,yo+4,yo+5,3,yo+1,14,4,yo+2,yo+3]),yse=ci.from(z4e,N4e,hse.conditions,hse.results)});var M4e,wse,_se=_(()=>{Nt();Jt();vse();M4e=new ui({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),wse=(t,e={})=>M4e.get(t,()=>ra(yse,{endpointParams:t,logger:e.logger}));ho.aws=ns});var ds,uP=_(()=>{ve();ds=class t extends si{constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}}});var Pw,kw,Tw,Cw,Cq=_(()=>{uP();Pw=class t extends ds{name="InvalidRequestException";$fault="client";constructor(e){super({name:"InvalidRequestException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype)}},kw=class t extends ds{name="ResourceNotFoundException";$fault="client";constructor(e){super({name:"ResourceNotFoundException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype)}},Tw=class t extends ds{name="TooManyRequestsException";$fault="client";constructor(e){super({name:"TooManyRequestsException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype)}},Cw=class t extends ds{name="UnauthorizedException";$fault="client";constructor(e){super({name:"UnauthorizedException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype)}}});var U4e,L4e,j4e,F4e,q4e,V4e,G4e,H4e,K4e,B4e,Z4e,W4e,J4e,X4e,Y4e,lP,dP,Q4e,eFe,pP,tFe,bse,fP,rFe,nFe,oFe,Sse,iFe,sFe,aFe,yi,xse,Ese,Ow,$se,Rse,Ise,Ase,Oq,cFe,uFe,lFe,Pse,kse,Tse,Dq,mP=_(()=>{rt();Cq();uP();U4e="AccessTokenType",L4e="GetRoleCredentials",j4e="GetRoleCredentialsRequest",F4e="GetRoleCredentialsResponse",q4e="InvalidRequestException",V4e="RoleCredentials",G4e="ResourceNotFoundException",H4e="SecretAccessKeyType",K4e="SessionTokenType",B4e="TooManyRequestsException",Z4e="UnauthorizedException",W4e="accountId",J4e="accessKeyId",X4e="accessToken",Y4e="account_id",lP="client",dP="error",Q4e="expiration",eFe="http",pP="httpError",tFe="httpHeader",bse="httpQuery",fP="message",rFe="roleCredentials",nFe="roleName",oFe="role_name",Sse="smithy.ts.sdk.synthetic.com.amazonaws.sso",iFe="secretAccessKey",sFe="sessionToken",aFe="x-amz-sso_bearer_token",yi="com.amazonaws.sso",xse=new Zt(Sse),Ese=[-3,Sse,"SSOServiceException",0,[],[]];xse.registerError(Ese,ds);Ow=new Zt(yi),$se=[-3,yi,q4e,{[dP]:lP,[pP]:400},[fP],[0]];Ow.registerError($se,Pw);Rse=[-3,yi,G4e,{[dP]:lP,[pP]:404},[fP],[0]];Ow.registerError(Rse,kw);Ise=[-3,yi,B4e,{[dP]:lP,[pP]:429},[fP],[0]];Ow.registerError(Ise,Tw);Ase=[-3,yi,Z4e,{[dP]:lP,[pP]:401},[fP],[0]];Ow.registerError(Ase,Cw);Oq=[xse,Ow],cFe=[0,yi,U4e,8,0],uFe=[0,yi,H4e,8,0],lFe=[0,yi,K4e,8,0],Pse=[3,yi,j4e,0,[nFe,W4e,X4e],[[0,{[bse]:oFe}],[0,{[bse]:Y4e}],[()=>cFe,{[tFe]:aFe}]],3],kse=[3,yi,F4e,0,[rFe],[[()=>Tse,0]]],Tse=[3,yi,V4e,0,[J4e,iFe,sFe,Q4e],[0,[()=>uFe,0],[()=>lFe,0],1]],Dq=[9,yi,L4e,{[eFe]:["GET","/federation/credentials",200]},()=>Pse,()=>kse]});var Cse,Ose=_(()=>{Pn();Nd();Yn();gc();ve();ge();xe();Aq();_se();mP();Cse=t=>({apiVersion:"2019-06-10",base64Decoder:t?.base64Decoder??pr,base64Encoder:t?.base64Encoder??Wt,disableHostPrefix:t?.disableHostPrefix??!1,endpointProvider:t?.endpointProvider??wse,extensions:t?.extensions??[],httpAuthSchemeProvider:t?.httpAuthSchemeProvider??cse,httpAuthSchemes:t?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4"),signer:new Gr},{schemeId:"smithy.api#noAuth",identityProvider:e=>e.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new An}],logger:t?.logger??new mo,protocol:t?.protocol??Sa,protocolSettings:t?.protocolSettings??{defaultNamespace:"com.amazonaws.sso",errorTypeRegistries:Oq,version:"2019-06-10",serviceTarget:"SWBPortalService"},serviceId:t?.serviceId??"SSO",sha256:t?.sha256??Xi,urlParser:t?.urlParser??nn,utf8Decoder:t?.utf8Decoder??Tr,utf8Encoder:t?.utf8Encoder??ur})});var hP,Dse,Nse=_(()=>{iw();Nt();Pn();ve();Dt();jo();xe();hP=Vt(Gu());Ose();Dse=t=>{Gs(process.version);let e=ea(t),r=()=>e().then(Vs),o=Cse(t);Ls(process.version);let n={profile:t?.profile,logger:o.logger};return{...o,...t,runtime:"node",defaultsMode:e,authSchemePreference:t?.authSchemePreference??Ie(is,n),bodyLengthChecker:t?.bodyLengthChecker??Zs,defaultUserAgentProvider:t?.defaultUserAgentProvider??rs({serviceId:o.serviceId,clientVersion:Hu.version}),maxAttempts:t?.maxAttempts??Ie(ca,t),region:t?.region??Ie(on,{...Xn,...n}),requestHandler:hP.NodeHttpHandler.create(t?.requestHandler??r),retryMode:t?.retryMode??Ie({...la,default:async()=>(await r()).retryMode||li},t),streamCollector:t?.streamCollector??hP.streamCollector,useDualstackEndpoint:t?.useDualstackEndpoint??Ie(Ys,n),useFipsEndpoint:t?.useFipsEndpoint??Ie(Qs,n),userAgentAppId:t?.userAgentAppId??Ie(ga,n)}}});var zse,Mse,Use=_(()=>{zse=t=>{let e=t.httpAuthSchemes,r=t.httpAuthSchemeProvider,o=t.credentials;return{setHttpAuthScheme(n){let i=e.findIndex(s=>s.schemeId===n.schemeId);i===-1?e.push(n):e.splice(i,1,n)},httpAuthSchemes(){return e},setHttpAuthSchemeProvider(n){r=n},httpAuthSchemeProvider(){return r},setCredentials(n){o=n},credentials(){return o}}},Mse=t=>({httpAuthSchemes:t.httpAuthSchemes(),httpAuthSchemeProvider:t.httpAuthSchemeProvider(),credentials:t.credentials()})});var Lse,jse=_(()=>{Nt();ve();ge();Use();Lse=(t,e)=>{let r=Object.assign(ya(t),Bi(t),oa(t),zse(t));return e.forEach(o=>o.configure(r)),Object.assign(t,va(r),Hs(r),ia(r),Mse(r))}});var Dw,Nq=_(()=>{Nt();Yn();ve();Dt();Jt();ge();jo();rt();Aq();Pq();Nse();jse();Dw=class extends Rn{config;constructor(...[e]){let r=Dse(e||{});super(r),this.initConfig=r;let o=lse(r),n=ma(o),i=ua(n),s=No(i),a=s,c=pc(a),u=use(c),l=Lse(u,e?.extensions||[]);this.config=l,this.middlewareStack.use(Fs(this.config)),this.middlewareStack.use(ha(this.config)),this.middlewareStack.use(yc(this.config)),this.middlewareStack.use(sa(this.config)),this.middlewareStack.use(da(this.config)),this.middlewareStack.use(pa(this.config)),this.middlewareStack.use(fa(this.config)),this.middlewareStack.use(es(this.config,{httpAuthSchemeParametersProvider:ase,identityProviderConfigProvider:async d=>new Fo({"aws.auth#sigv4":d.credentials})})),this.middlewareStack.use(ts(this.config))}destroy(){super.destroy()}}});var Fse,qse,Vse,Gse=_(()=>{ve();Jt();Pq();Fse=Ks(dse,"SWBPortalService","SSOClient",fc),qse={},Vse=(t,e,r,o)=>[]});var Nw,zq=_(()=>{Gse();mP();Nw=class extends Fse(qse,Vse,"GetRoleCredentials",Dq){}});var dFe,gP,Hse=_(()=>{ve();zq();Nq();dFe={GetRoleCredentialsCommand:Nw},gP=class extends Dw{};qs(dFe,gP)});var Kse=_(()=>{zq()});var Bse=_(()=>{});var Zse={};Ht(Zse,{$Command:()=>Wn,GetRoleCredentials$:()=>Dq,GetRoleCredentialsCommand:()=>Nw,GetRoleCredentialsRequest$:()=>Pse,GetRoleCredentialsResponse$:()=>kse,InvalidRequestException:()=>Pw,InvalidRequestException$:()=>$se,ResourceNotFoundException:()=>kw,ResourceNotFoundException$:()=>Rse,RoleCredentials$:()=>Tse,SSO:()=>gP,SSOClient:()=>Dw,SSOServiceException:()=>ds,SSOServiceException$:()=>Ese,TooManyRequestsException:()=>Tw,TooManyRequestsException$:()=>Ise,UnauthorizedException:()=>Cw,UnauthorizedException$:()=>Ase,__Client:()=>Rn,errorTypeRegistries:()=>Oq});var Wse=_(()=>{Nq();Hse();Kse();ve();mP();Cq();Bse();uP()});var Jse=U(Mq=>{var{GetRoleCredentialsCommand:pFe,SSOClient:fFe}=(Wse(),re(Zse));Mq.GetRoleCredentialsCommand=pFe;Mq.SSOClient=fFe});var Uq=U(yP=>{var{CredentialsProviderError:ps,getSSOTokenFromFile:mFe,getProfileName:hFe,parseKnownFiles:gFe,loadSsoSessionData:yFe}=(Dt(),re(zo)),{setCredentialFeature:Xse}=(Nt(),re(os)),{fromSso:vFe}=sse(),Qse=t=>t&&(typeof t.sso_start_url=="string"||typeof t.sso_account_id=="string"||typeof t.sso_session=="string"||typeof t.sso_region=="string"||typeof t.sso_role_name=="string"),zw=!1,Yse=async({ssoStartUrl:t,ssoSession:e,ssoAccountId:r,ssoRegion:o,ssoRoleName:n,ssoClient:i,clientConfig:s,parentClientConfig:a,callerClientConfig:c,profile:u,filepath:l,configFilepath:d,ignoreCache:p,logger:f})=>{let h,y="To refresh this SSO session run aws sso login with the corresponding profile.";if(e)try{let me=await vFe({profile:u,filepath:l,configFilepath:d,ignoreCache:p,clientConfig:s,parentClientConfig:a,logger:f})({callerClientConfig:c});h={accessToken:me.token,expiresAt:new Date(me.expiration).toISOString()}}catch(me){throw new ps(me.message,{tryNextLink:zw,logger:f})}else try{h=await mFe(t)}catch{throw new ps(`The SSO session associated with this profile is invalid. ${y}`,{tryNextLink:zw,logger:f})}if(new Date(h.expiresAt).getTime()-Date.now()<=0)throw new ps(`The SSO session associated with this profile has expired. ${y}`,{tryNextLink:zw,logger:f});let{accessToken:w}=h,{SSOClient:b,GetRoleCredentialsCommand:S}=Jse(),x=i||new b(Object.assign({},s??{},{logger:s?.logger??c?.logger??a?.logger,region:s?.region??o,userAgentAppId:s?.userAgentAppId??c?.userAgentAppId??a?.userAgentAppId})),R;try{R=await x.send(new S({accountId:r,roleName:n,accessToken:w}))}catch(me){throw new ps(me,{tryNextLink:zw,logger:f})}let{roleCredentials:{accessKeyId:T,secretAccessKey:M,sessionToken:Z,expiration:te,credentialScope:Ae,accountId:Te}={}}=R;if(!T||!M||!Z||!te)throw new ps("SSO returns an invalid temporary credential.",{tryNextLink:zw,logger:f});let bt={accessKeyId:T,secretAccessKey:M,sessionToken:Z,expiration:new Date(te),...Ae&&{credentialScope:Ae},...Te&&{accountId:Te}};return e?Xse(bt,"CREDENTIALS_SSO","s"):Xse(bt,"CREDENTIALS_SSO_LEGACY","u"),bt},eae=(t,e)=>{let{sso_start_url:r,sso_account_id:o,sso_region:n,sso_role_name:i}=t;if(!r||!o||!n||!i)throw new ps(`Profile is configured with invalid SSO credentials. Required parameters "sso_account_id", "sso_region", "sso_role_name", "sso_start_url". Got ${Object.keys(t).join(", ")}
52
- Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`,{tryNextLink:!1,logger:e});return t},wFe=(t={})=>async({callerClientConfig:e}={})=>{t.logger?.debug("@aws-sdk/credential-provider-sso - fromSSO");let{ssoStartUrl:r,ssoAccountId:o,ssoRegion:n,ssoRoleName:i,ssoSession:s}=t,{ssoClient:a}=t,c=hFe({profile:t.profile??e?.profile});if(!r&&!o&&!n&&!i&&!s){let l=(await gFe(t))[c];if(!l)throw new ps(`Profile ${c} was not found.`,{logger:t.logger});if(!Qse(l))throw new ps(`Profile ${c} is not configured with SSO credentials.`,{logger:t.logger});if(l?.sso_session){let b=(await yFe(t))[l.sso_session],S=` configurations in profile ${c} and sso-session ${l.sso_session}`;if(n&&n!==b.sso_region)throw new ps("Conflicting SSO region"+S,{tryNextLink:!1,logger:t.logger});if(r&&r!==b.sso_start_url)throw new ps("Conflicting SSO start_url"+S,{tryNextLink:!1,logger:t.logger});l.sso_region=b.sso_region,l.sso_start_url=b.sso_start_url}let{sso_start_url:d,sso_account_id:p,sso_region:f,sso_role_name:h,sso_session:y}=eae(l,t.logger);return Yse({ssoStartUrl:d,ssoSession:y,ssoAccountId:p,ssoRegion:f,ssoRoleName:h,ssoClient:a,clientConfig:t.clientConfig,parentClientConfig:t.parentClientConfig,callerClientConfig:t.callerClientConfig,profile:c,filepath:t.filepath,configFilepath:t.configFilepath,ignoreCache:t.ignoreCache,logger:t.logger})}else{if(!r||!o||!n||!i)throw new ps('Incomplete configuration. The fromSSO() argument hash must include "ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"',{tryNextLink:!1,logger:t.logger});return Yse({ssoStartUrl:r,ssoSession:s,ssoAccountId:o,ssoRegion:n,ssoRoleName:i,ssoClient:a,clientConfig:t.clientConfig,parentClientConfig:t.parentClientConfig,callerClientConfig:t.callerClientConfig,profile:c,filepath:t.filepath,configFilepath:t.configFilepath,ignoreCache:t.ignoreCache,logger:t.logger})}};yP.fromSSO=wFe;yP.isSsoProfile=Qse;yP.validateSsoProfile=eae});var th,Ld,Mw,tae,uae,Uw,un,Lq,rae,nae,oae,iae,sae,ln,jq,eh,aae,cae,_Fe,Et,bFe,lae,dae=_(()=>{Jt();th="ref",Ld=-1,Mw=!0,tae="isSet",uae="PartitionResult",Uw="booleanEquals",un="stringEquals",Lq="getAttr",rae="us-east-1",nae="sigv4",oae="sts",iae="https://sts.{Region}.{PartitionResult#dnsSuffix}",sae={[th]:"Endpoint"},ln={[th]:"Region"},jq={[th]:uae},eh={},aae=[ln],cae={conditions:[[tae,[sae]],[tae,aae],["aws.partition",aae,uae],[Uw,[{[th]:"UseFIPS"},Mw]],[Uw,[{[th]:"UseDualStack"},Mw]],[un,[ln,"aws-global"]],[Uw,[{[th]:"UseGlobalEndpoint"},Mw]],[un,[ln,"eu-central-1"]],[Uw,[{fn:Lq,argv:[jq,"supportsDualStack"]},Mw]],[Uw,[{fn:Lq,argv:[jq,"supportsFIPS"]},Mw]],[un,[ln,"ap-south-1"]],[un,[ln,"eu-north-1"]],[un,[ln,"eu-west-1"]],[un,[ln,"eu-west-2"]],[un,[ln,"eu-west-3"]],[un,[ln,"sa-east-1"]],[un,[ln,rae]],[un,[ln,"us-east-2"]],[un,[ln,"us-west-2"]],[un,[ln,"us-west-1"]],[un,[ln,"ca-central-1"]],[un,[ln,"ap-southeast-1"]],[un,[ln,"ap-northeast-1"]],[un,[ln,"ap-southeast-2"]],[un,[{fn:Lq,argv:[jq,"name"]},"aws-us-gov"]]],results:[[Ld],["https://sts.amazonaws.com",{authSchemes:[{name:nae,signingName:oae,signingRegion:rae}]}],[iae,{authSchemes:[{name:nae,signingName:oae,signingRegion:"{Region}"}]}],[Ld,"Invalid Configuration: FIPS and custom endpoint are not supported"],[Ld,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[sae,eh],["https://sts-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",eh],[Ld,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://sts.{Region}.amazonaws.com",eh],["https://sts-fips.{Region}.{PartitionResult#dnsSuffix}",eh],[Ld,"FIPS is enabled but this partition does not support FIPS"],["https://sts.{Region}.{PartitionResult#dualStackDnsSuffix}",eh],[Ld,"DualStack is enabled but this partition does not support DualStack"],[iae,eh],[Ld,"Invalid Configuration: Missing Region"]]},_Fe=2,Et=1e8,bFe=new Int32Array([-1,1,-1,0,30,3,1,4,Et+14,2,5,Et+14,3,25,6,4,24,7,5,Et+1,8,6,9,Et+13,7,Et+1,10,10,Et+1,11,11,Et+1,12,12,Et+1,13,13,Et+1,14,14,Et+1,15,15,Et+1,16,16,Et+1,17,17,Et+1,18,18,Et+1,19,19,Et+1,20,20,Et+1,21,21,Et+1,22,22,Et+1,23,23,Et+1,Et+2,8,Et+11,Et+12,4,28,26,9,27,Et+10,24,Et+8,Et+9,8,29,Et+7,9,Et+6,Et+7,3,Et+3,31,4,Et+4,Et+5]),lae=ci.from(bFe,_Fe,cae.conditions,cae.results)});var SFe,vP,Fq=_(()=>{Nt();Jt();dae();SFe=new ui({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS","UseGlobalEndpoint"]}),vP=(t,e={})=>SFe.get(t,()=>ra(lae,{endpointParams:t,logger:e.logger}));ho.aws=ns});function mae(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sts",region:t.region},propertiesExtractor:(e,r)=>({signingProperties:{config:e,context:r}})}}function qq(t){return{schemeId:"aws.auth#sigv4a",signingProperties:{name:"sts",region:t.region},propertiesExtractor:(e,r)=>({signingProperties:{config:e,context:r}})}}function hae(t){return{schemeId:"smithy.api#noAuth"}}var pae,xFe,EFe,fae,$Fe,RFe,gae,yae,Vq=_(()=>{Pn();pae=Vt(uA());ve();Jt();Fq();xFe=t=>async(e,r,o)=>{if(!o)throw new Error("Could not find `input` for `defaultEndpointRuleSetHttpAuthSchemeParametersProvider`");let n=await t(e,r,o),i=Bt(r)?.commandInstance?.constructor?.getEndpointParameterInstructions;if(!i)throw new Error(`getEndpointParameterInstructions() is not defined on '${r.commandName}'`);let s=await Iv(o,{getEndpointParameterInstructions:i},e);return Object.assign(n,s)},EFe=async(t,e,r)=>({operation:Bt(e).operation,region:await jt(t.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()}),fae=xFe(EFe);$Fe=(t,e,r)=>n=>{let s=t(n).properties?.authSchemes;if(!s)return e(n);let a=[];for(let c of s){let{name:u,properties:l={},...d}=c,p=u.toLowerCase();u!==p&&console.warn(`HttpAuthScheme has been normalized with lowercasing: '${u}' to '${p}'`);let f;if(p==="sigv4a"){f="aws.auth#sigv4a";let w=s.find(b=>{let S=b.name.toLowerCase();return S!=="sigv4a"&&S.startsWith("sigv4")});if(pae.SignatureV4MultiRegion.sigv4aDependency()==="none"&&w)continue}else if(p.startsWith("sigv4"))f="aws.auth#sigv4";else throw new Error(`Unknown HttpAuthScheme found in '@smithy.rules#endpointRuleSet': '${p}'`);let h=r[f];if(!h)throw new Error(`Could not find HttpAuthOption create function for '${f}'`);let y=h(n);y.schemeId=f,y.signingProperties={...y.signingProperties||{},...d,...l},a.push(y)}return a},RFe=t=>{let e=[];return t.operation==="AssumeRoleWithWebIdentity"?(e.push(hae(t)),e.push(qq(t))):(e.push(mae(t)),e.push(qq(t))),e},gae=$Fe(vP,RFe,{"aws.auth#sigv4":mae,"aws.auth#sigv4a":qq,"smithy.api#noAuth":hae}),yae=t=>{let e=wa(t),r=Jv(e);return Object.assign(r,{authSchemePreference:jt(t.authSchemePreference??[])})}});var vae,wae,Gq=_(()=>{vae=t=>Object.assign(t,{useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,useGlobalEndpoint:t.useGlobalEndpoint??!1,defaultSigningName:"sts"}),wae={UseGlobalEndpoint:{type:"builtInParams",name:"useGlobalEndpoint"},UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}});var vo,wP=_(()=>{ve();vo=class t extends si{constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}}});var Lw,jw,Fw,qw,Vw,Gw,Hw,Hq=_(()=>{wP();Lw=class t extends vo{name="ExpiredTokenException";$fault="client";constructor(e){super({name:"ExpiredTokenException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype)}},jw=class t extends vo{name="MalformedPolicyDocumentException";$fault="client";constructor(e){super({name:"MalformedPolicyDocumentException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype)}},Fw=class t extends vo{name="PackedPolicyTooLargeException";$fault="client";constructor(e){super({name:"PackedPolicyTooLargeException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype)}},qw=class t extends vo{name="RegionDisabledException";$fault="client";constructor(e){super({name:"RegionDisabledException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype)}},Vw=class t extends vo{name="IDPRejectedClaimException";$fault="client";constructor(e){super({name:"IDPRejectedClaimException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype)}},Gw=class t extends vo{name="InvalidIdentityTokenException";$fault="client";constructor(e){super({name:"InvalidIdentityTokenException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype)}},Hw=class t extends vo{name="IDPCommunicationErrorException";$fault="client";$retryable={};constructor(e){super({name:"IDPCommunicationErrorException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype)}}});var IFe,AFe,PFe,kFe,TFe,CFe,Kq,OFe,DFe,NFe,zFe,Bq,MFe,_ae,UFe,LFe,jFe,FFe,qFe,VFe,GFe,HFe,bae,Sae,xae,KFe,BFe,ZFe,WFe,JFe,XFe,Eae,YFe,QFe,$ae,e2e,Rae,t2e,r2e,Zq,n2e,o2e,Iae,Aae,i2e,s2e,a2e,c2e,u2e,l2e,d2e,p2e,jd,Fd,f2e,qd,Vd,Gd,m2e,Pae,h2e,sr,kae,Tae,Yu,Cae,Oae,Dae,Nae,zae,Mae,Uae,Wq,g2e,y2e,Jq,Lae,jae,Fae,qae,Xq,Vae,Gae,Hae,Kae,v2e,w2e,Yq,Qq,Kw=_(()=>{rt();Hq();wP();IFe="Arn",AFe="AccessKeyId",PFe="AssumeRole",kFe="AssumedRoleId",TFe="AssumeRoleRequest",CFe="AssumeRoleResponse",Kq="AssumedRoleUser",OFe="AssumeRoleWithWebIdentity",DFe="AssumeRoleWithWebIdentityRequest",NFe="AssumeRoleWithWebIdentityResponse",zFe="Audience",Bq="Credentials",MFe="ContextAssertion",_ae="DurationSeconds",UFe="Expiration",LFe="ExternalId",jFe="ExpiredTokenException",FFe="IDPCommunicationErrorException",qFe="IDPRejectedClaimException",VFe="InvalidIdentityTokenException",GFe="Key",HFe="MalformedPolicyDocumentException",bae="MinimumSessionTokenSize",Sae="Policy",xae="PolicyArns",KFe="ProviderArn",BFe="ProvidedContexts",ZFe="ProvidedContextsListType",WFe="ProvidedContext",JFe="PolicyDescriptorType",XFe="ProviderId",Eae="PackedPolicySize",YFe="PackedPolicyTooLargeException",QFe="Provider",$ae="RoleArn",e2e="RegionDisabledException",Rae="RoleSessionName",t2e="SecretAccessKey",r2e="SubjectFromWebIdentityToken",Zq="SourceIdentity",n2e="SerialNumber",o2e="SessionToken",Iae="SessionTokenSize",Aae="SessionTokenUtilization",i2e="Tags",s2e="TokenCode",a2e="TransitiveTagKeys",c2e="Tag",u2e="Value",l2e="WebIdentityToken",d2e="arn",p2e="accessKeySecretType",jd="awsQueryError",Fd="client",f2e="clientTokenType",qd="error",Vd="httpError",Gd="message",m2e="policyDescriptorListType",Pae="smithy.ts.sdk.synthetic.com.amazonaws.sts",h2e="tagListType",sr="com.amazonaws.sts",kae=new Zt(Pae),Tae=[-3,Pae,"STSServiceException",0,[],[]];kae.registerError(Tae,vo);Yu=new Zt(sr),Cae=[-3,sr,jFe,{[jd]:["ExpiredTokenException",400],[qd]:Fd,[Vd]:400},[Gd],[0]];Yu.registerError(Cae,Lw);Oae=[-3,sr,FFe,{[jd]:["IDPCommunicationError",400],[qd]:Fd,[Vd]:400},[Gd],[0]];Yu.registerError(Oae,Hw);Dae=[-3,sr,qFe,{[jd]:["IDPRejectedClaim",403],[qd]:Fd,[Vd]:403},[Gd],[0]];Yu.registerError(Dae,Vw);Nae=[-3,sr,VFe,{[jd]:["InvalidIdentityToken",400],[qd]:Fd,[Vd]:400},[Gd],[0]];Yu.registerError(Nae,Gw);zae=[-3,sr,HFe,{[jd]:["MalformedPolicyDocument",400],[qd]:Fd,[Vd]:400},[Gd],[0]];Yu.registerError(zae,jw);Mae=[-3,sr,YFe,{[jd]:["PackedPolicyTooLarge",400],[qd]:Fd,[Vd]:400},[Gd],[0]];Yu.registerError(Mae,Fw);Uae=[-3,sr,e2e,{[jd]:["RegionDisabledException",403],[qd]:Fd,[Vd]:403},[Gd],[0]];Yu.registerError(Uae,qw);Wq=[kae,Yu],g2e=[0,sr,p2e,8,0],y2e=[0,sr,f2e,8,0],Jq=[3,sr,Kq,0,[kFe,IFe],[0,0],2],Lae=[3,sr,TFe,0,[$ae,Rae,xae,Sae,_ae,i2e,a2e,LFe,n2e,s2e,Zq,BFe,bae],[0,0,()=>Kae,0,1,()=>w2e,64,0,0,0,0,()=>v2e,1],2],jae=[3,sr,CFe,0,[Bq,Kq,Eae,Zq,Aae,Iae],[[()=>Xq,0],()=>Jq,1,0,1,1]],Fae=[3,sr,DFe,0,[$ae,Rae,l2e,XFe,xae,Sae,_ae,bae],[0,0,[()=>y2e,0],0,()=>Kae,0,1,1],3],qae=[3,sr,NFe,0,[Bq,r2e,Kq,Eae,QFe,zFe,Zq,Aae,Iae],[[()=>Xq,0],0,()=>Jq,1,0,0,0,1,1]],Xq=[3,sr,Bq,0,[AFe,t2e,o2e,UFe],[0,[()=>g2e,0],0,4],4],Vae=[3,sr,JFe,0,[d2e],[0]],Gae=[3,sr,WFe,0,[KFe,MFe],[0,0]],Hae=[3,sr,c2e,0,[GFe,u2e],[0,0],2],Kae=[1,sr,m2e,0,()=>Vae],v2e=[1,sr,ZFe,0,()=>Gae],w2e=[1,sr,h2e,0,()=>Hae],Yq=[9,sr,PFe,0,()=>Lae,()=>jae],Qq=[9,sr,OFe,0,()=>Fae,()=>qae]});var Bae,Zae,Wae=_(()=>{Pn();Nd();Bae=Vt(uA());Yn();gc();ve();ge();xe();Vq();Fq();Kw();Zae=t=>({apiVersion:"2011-06-15",base64Decoder:t?.base64Decoder??pr,base64Encoder:t?.base64Encoder??Wt,disableHostPrefix:t?.disableHostPrefix??!1,endpointProvider:t?.endpointProvider??vP,extensions:t?.extensions??[],httpAuthSchemeProvider:t?.httpAuthSchemeProvider??gae,httpAuthSchemes:t?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4"),signer:new Gr},{schemeId:"aws.auth#sigv4a",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4a"),signer:new vc},{schemeId:"smithy.api#noAuth",identityProvider:e=>e.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new An}],logger:t?.logger??new mo,protocol:t?.protocol??Xu,protocolSettings:t?.protocolSettings??{defaultNamespace:"com.amazonaws.sts",errorTypeRegistries:Wq,xmlNamespace:"https://sts.amazonaws.com/doc/2011-06-15/",version:"2011-06-15",serviceTarget:"AWSSecurityTokenServiceV20110615"},serviceId:t?.serviceId??"STS",sha256:t?.sha256??Xi,signerConstructor:t?.signerConstructor??Bae.SignatureV4MultiRegion,urlParser:t?.urlParser??nn,utf8Decoder:t?.utf8Decoder??Tr,utf8Encoder:t?.utf8Encoder??ur})});var _P,Jae,Xae=_(()=>{iw();Nt();Pn();Yn();ve();Dt();jo();xe();_P=Vt(Gu());Wae();Jae=t=>{Gs(process.version);let e=ea(t),r=()=>e().then(Vs),o=Zae(t);Ls(process.version);let n={profile:t?.profile,logger:o.logger};return{...o,...t,runtime:"node",defaultsMode:e,authSchemePreference:t?.authSchemePreference??Ie(is,n),bodyLengthChecker:t?.bodyLengthChecker??Zs,defaultUserAgentProvider:t?.defaultUserAgentProvider??rs({serviceId:o.serviceId,clientVersion:Hu.version}),httpAuthSchemes:t?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:i=>i.getIdentityProvider("aws.auth#sigv4")||(async s=>await t.credentialDefaultProvider(s?.__config||{})()),signer:new Gr},{schemeId:"aws.auth#sigv4a",identityProvider:i=>i.getIdentityProvider("aws.auth#sigv4a"),signer:new vc},{schemeId:"smithy.api#noAuth",identityProvider:i=>i.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new An}],maxAttempts:t?.maxAttempts??Ie(ca,t),region:t?.region??Ie(on,{...Xn,...n}),requestHandler:_P.NodeHttpHandler.create(t?.requestHandler??r),retryMode:t?.retryMode??Ie({...la,default:async()=>(await r()).retryMode||li},t),sigv4aSigningRegionSet:t?.sigv4aSigningRegionSet??Ie(Xv,n),streamCollector:t?.streamCollector??_P.streamCollector,useDualstackEndpoint:t?.useDualstackEndpoint??Ie(Ys,n),useFipsEndpoint:t?.useFipsEndpoint??Ie(Qs,n),userAgentAppId:t?.userAgentAppId??Ie(ga,n)}}});var Yae,Qae,ece=_(()=>{Yae=t=>{let e=t.httpAuthSchemes,r=t.httpAuthSchemeProvider,o=t.credentials;return{setHttpAuthScheme(n){let i=e.findIndex(s=>s.schemeId===n.schemeId);i===-1?e.push(n):e.splice(i,1,n)},httpAuthSchemes(){return e},setHttpAuthSchemeProvider(n){r=n},httpAuthSchemeProvider(){return r},setCredentials(n){o=n},credentials(){return o}}},Qae=t=>({httpAuthSchemes:t.httpAuthSchemes(),httpAuthSchemeProvider:t.httpAuthSchemeProvider(),credentials:t.credentials()})});var tce,rce=_(()=>{Nt();ve();ge();ece();tce=(t,e)=>{let r=Object.assign(ya(t),Bi(t),oa(t),Yae(t));return e.forEach(o=>o.configure(r)),Object.assign(t,va(r),Hs(r),ia(r),Qae(r))}});var Qu,bP=_(()=>{Nt();Yn();ve();Dt();Jt();ge();jo();rt();Vq();Gq();Xae();rce();Qu=class extends Rn{config;constructor(...[e]){let r=Jae(e||{});super(r),this.initConfig=r;let o=vae(r),n=ma(o),i=ua(n),s=No(i),a=s,c=pc(a),u=yae(c),l=tce(u,e?.extensions||[]);this.config=l,this.middlewareStack.use(Fs(this.config)),this.middlewareStack.use(ha(this.config)),this.middlewareStack.use(yc(this.config)),this.middlewareStack.use(sa(this.config)),this.middlewareStack.use(da(this.config)),this.middlewareStack.use(pa(this.config)),this.middlewareStack.use(fa(this.config)),this.middlewareStack.use(es(this.config,{httpAuthSchemeParametersProvider:fae,identityProviderConfigProvider:async d=>new Fo({"aws.auth#sigv4":d.credentials,"aws.auth#sigv4a":d.credentials})})),this.middlewareStack.use(ts(this.config))}destroy(){super.destroy()}}});var SP,xP,EP,eV=_(()=>{ve();Jt();Gq();SP=Ks(wae,"AWSSecurityTokenServiceV20110615","STSClient",fc),xP={},EP=(t,e,r,o)=>[]});var Hd,$P=_(()=>{eV();Kw();Hd=class extends SP(xP,EP,"AssumeRole",Yq){}});var Kd,RP=_(()=>{eV();Kw();Kd=class extends SP(xP,EP,"AssumeRoleWithWebIdentity",Qq){}});var _2e,IP,nce=_(()=>{ve();$P();RP();bP();_2e={AssumeRoleCommand:Hd,AssumeRoleWithWebIdentityCommand:Kd},IP=class extends Qu{};qs(_2e,IP)});var oce=_(()=>{$P();RP()});var ice=_(()=>{});var sce,ace,cce,uce,lce,dce=_(()=>{Nt();$P();RP();sce=t=>{if(typeof t?.Arn=="string"){let e=t.Arn.split(":");if(e.length>4&&e[4]!=="")return e[4]}},ace=async(t,e,r,o={})=>{let n=typeof t=="function"?await t():t,i=typeof e=="function"?await e():e,s="",a=n??i??(s=await ZI(o)());return r?.debug?.("@aws-sdk/client-sts::resolveRegion","accepting first of:",`${n} (credential provider clientConfig)`,`${i} (contextual client)`,`${s} (STS default: AWS_REGION, profile region, or us-east-1)`),a},cce=(t,e)=>{let r,o;return async(n,i)=>{if(o=n,!r){let{logger:l=t?.parentClientConfig?.logger,profile:d=t?.parentClientConfig?.profile,region:p,requestHandler:f=t?.parentClientConfig?.requestHandler,credentialProviderLogger:h,userAgentAppId:y=t?.parentClientConfig?.userAgentAppId}=t,w=await ace(p,t?.parentClientConfig?.region,h,{logger:l,profile:d}),b=!lce(f);r=new e({...t,userAgentAppId:y,profile:d,credentialDefaultProvider:()=>async()=>o,region:w,requestHandler:b?f:void 0,logger:l})}let{Credentials:s,AssumedRoleUser:a}=await r.send(new Hd(i));if(!s||!s.AccessKeyId||!s.SecretAccessKey)throw new Error(`Invalid response from STS.assumeRole call with role ${i.RoleArn}`);let c=sce(a),u={accessKeyId:s.AccessKeyId,secretAccessKey:s.SecretAccessKey,sessionToken:s.SessionToken,expiration:s.Expiration,...s.CredentialScope&&{credentialScope:s.CredentialScope},...c&&{accountId:c}};return gu(u,"CREDENTIALS_STS_ASSUME_ROLE","i"),u}},uce=(t,e)=>{let r;return async o=>{if(!r){let{logger:c=t?.parentClientConfig?.logger,profile:u=t?.parentClientConfig?.profile,region:l,requestHandler:d=t?.parentClientConfig?.requestHandler,credentialProviderLogger:p,userAgentAppId:f=t?.parentClientConfig?.userAgentAppId}=t,h=await ace(l,t?.parentClientConfig?.region,p,{logger:c,profile:u}),y=!lce(d);r=new e({...t,userAgentAppId:f,profile:u,region:h,requestHandler:y?d:void 0,logger:c})}let{Credentials:n,AssumedRoleUser:i}=await r.send(new Kd(o));if(!n||!n.AccessKeyId||!n.SecretAccessKey)throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${o.RoleArn}`);let s=sce(i),a={accessKeyId:n.AccessKeyId,secretAccessKey:n.SecretAccessKey,sessionToken:n.SessionToken,expiration:n.Expiration,...n.CredentialScope&&{credentialScope:n.CredentialScope},...s&&{accountId:s}};return s&&gu(a,"RESOLVED_ACCOUNT_ID","T"),gu(a,"CREDENTIALS_STS_ASSUME_ROLE_WEB_ID","k"),a}},lce=t=>t?.metadata?.handlerProtocol==="h2"});var pce,fce,mce,b2e,hce=_(()=>{dce();bP();pce=(t,e)=>e?class extends t{constructor(o){super(o);for(let n of e)this.middlewareStack.use(n)}}:t,fce=(t={},e)=>cce(t,pce(Qu,e)),mce=(t={},e)=>uce(t,pce(Qu,e)),b2e=t=>e=>t({roleAssumer:fce(e),roleAssumerWithWebIdentity:mce(e),...e})});var tV={};Ht(tV,{$Command:()=>Wn,AssumeRole$:()=>Yq,AssumeRoleCommand:()=>Hd,AssumeRoleRequest$:()=>Lae,AssumeRoleResponse$:()=>jae,AssumeRoleWithWebIdentity$:()=>Qq,AssumeRoleWithWebIdentityCommand:()=>Kd,AssumeRoleWithWebIdentityRequest$:()=>Fae,AssumeRoleWithWebIdentityResponse$:()=>qae,AssumedRoleUser$:()=>Jq,Credentials$:()=>Xq,ExpiredTokenException:()=>Lw,ExpiredTokenException$:()=>Cae,IDPCommunicationErrorException:()=>Hw,IDPCommunicationErrorException$:()=>Oae,IDPRejectedClaimException:()=>Vw,IDPRejectedClaimException$:()=>Dae,InvalidIdentityTokenException:()=>Gw,InvalidIdentityTokenException$:()=>Nae,MalformedPolicyDocumentException:()=>jw,MalformedPolicyDocumentException$:()=>zae,PackedPolicyTooLargeException:()=>Fw,PackedPolicyTooLargeException$:()=>Mae,PolicyDescriptorType$:()=>Vae,ProvidedContext$:()=>Gae,RegionDisabledException:()=>qw,RegionDisabledException$:()=>Uae,STS:()=>IP,STSClient:()=>Qu,STSServiceException:()=>vo,STSServiceException$:()=>Tae,Tag$:()=>Hae,__Client:()=>Rn,decorateDefaultCredentialProvider:()=>b2e,errorTypeRegistries:()=>Wq,getDefaultRoleAssumer:()=>fce,getDefaultRoleAssumerWithWebIdentity:()=>mce});var rV=_(()=>{bP();nce();oce();ve();Kw();Hq();ice();hce();wP()});function S2e(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"signin",region:t.region},propertiesExtractor:(e,r)=>({signingProperties:{config:e,context:r}})}}function x2e(t){return{schemeId:"smithy.api#noAuth"}}var gce,yce,vce,nV=_(()=>{Pn();ve();gce=async(t,e,r)=>({operation:Bt(e).operation,region:await jt(t.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});yce=t=>{let e=[];return t.operation==="CreateOAuth2Token"?e.push(x2e(t)):e.push(S2e(t)),e},vce=t=>{let e=wa(t);return Object.assign(e,{authSchemePreference:jt(t.authSchemePreference??[])})}});var wce,_ce,oV=_(()=>{wce=t=>Object.assign(t,{useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,defaultSigningName:"signin"}),_ce={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}});var rl,el,bce,rh,Sce,nh,xce,sV,_c,iV,Ece,$ce,tl,Pce,Rce,AP,kn,Ice,Ace,E2e,ct,$2e,kce,Tce=_(()=>{Jt();rl="ref",el=-1,bce=!1,rh=!0,Sce="isSet",nh="booleanEquals",xce="coalesce",sV="PartitionResult",_c="stringEquals",iV="getAttr",Ece="https://signin.{Region}.{PartitionResult#dualStackDnsSuffix}",$ce={[rl]:"Endpoint"},tl={fn:iV,argv:[{[rl]:sV},"name"]},Pce={[rl]:"Region"},Rce={[rl]:sV},AP={authSchemes:[{name:"sigv4",signingName:"signin",signingRegion:"{Region}"}]},kn={},Ice=[Pce],Ace={conditions:[[Sce,Ice],[nh,[{fn:xce,argv:[{[rl]:"IsControlPlane"},bce]},rh]],[Sce,[$ce]],["aws.partition",Ice,sV],[nh,[{[rl]:"UseFIPS"},rh]],[_c,[tl,"aws"]],[nh,[{fn:xce,argv:[{[rl]:"IsOAuthEndpoint"},bce]},rh]],[nh,[{[rl]:"UseDualStack"},rh]],[_c,[tl,"aws-cn"]],[_c,[Pce,"us-gov-west-1"]],[_c,[tl,"aws-us-gov"]],[nh,[{fn:iV,argv:[Rce,"supportsFIPS"]},rh]],[_c,[tl,"aws-iso"]],[_c,[tl,"aws-iso-b"]],[_c,[tl,"aws-iso-f"]],[_c,[tl,"aws-iso-e"]],[_c,[tl,"aws-eusc"]],[nh,[{fn:iV,argv:[Rce,"supportsDualStack"]},rh]]],results:[[el],["https://signin.{Region}.api.aws",AP],["https://signin.{Region}.api.amazonwebservices.com.cn",AP],[Ece,AP],[el,"FIPS endpoints are not supported for OAuth operations. Disable FIPS or use a non-OAuth operation."],["https://{Region}.oauth.signin.aws",AP],["https://{Region}.signin.aws.amazon.com",kn],["https://{Region}.signin.amazonaws.cn",kn],["https://{Region}.signin.amazonaws-us-gov.com",kn],["https://{Region}.signin.c2shome.ic.gov",kn],["https://{Region}.signin.sc2shome.sgov.gov",kn],["https://{Region}.signin.csphome.hci.ic.gov",kn],["https://{Region}.signin.csphome.adc-e.uk",kn],["https://{Region}.signin.amazonaws-eusc.eu",kn],["https://signin-fips.amazonaws-us-gov.com",kn],["https://{Region}.signin-fips.amazonaws-us-gov.com",kn],["https://{Region}.signin.{PartitionResult#dnsSuffix}",kn],[el,"Invalid Configuration: FIPS and custom endpoint are not supported"],[el,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[$ce,kn],["https://signin-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",kn],[el,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://signin-fips.{Region}.{PartitionResult#dnsSuffix}",kn],[el,"FIPS is enabled but this partition does not support FIPS"],[Ece,kn],[el,"DualStack is enabled but this partition does not support DualStack"],["https://signin.{Region}.{PartitionResult#dnsSuffix}",kn],[el,"Invalid Configuration: Missing Region"]]},E2e=2,ct=1e8,$2e=new Int32Array([-1,1,-1,0,6,3,2,36,4,4,5,ct+27,6,ct+4,ct+27,1,29,7,2,36,8,3,9,31,4,22,10,5,19,11,7,21,12,8,ct+7,13,10,ct+8,14,12,ct+9,15,13,ct+10,16,14,ct+11,17,15,ct+12,18,16,ct+13,ct+16,6,ct+5,20,7,21,ct+6,17,ct+24,ct+25,6,ct+4,23,7,27,24,9,ct+14,25,10,ct+15,26,11,ct+22,ct+23,11,28,ct+21,17,ct+20,ct+21,2,35,30,3,39,31,4,32,ct+27,6,ct+4,33,7,ct+27,34,9,ct+14,ct+27,3,39,36,4,38,37,7,ct+18,ct+19,6,ct+4,ct+17,5,ct+1,40,8,ct+2,ct+3]),kce=ci.from($2e,E2e,Ace.conditions,Ace.results)});var R2e,Cce,Oce=_(()=>{Nt();Jt();Tce();R2e=new ui({size:50,params:["Endpoint","IsControlPlane","IsOAuthEndpoint","Region","UseDualStack","UseFIPS"]}),Cce=(t,e={})=>R2e.get(t,()=>ra(kce,{endpointParams:t,logger:e.logger}));ho.aws=ns});var fs,PP=_(()=>{ve();fs=class t extends si{constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}}});var Bw,Zw,Ww,Jw,aV=_(()=>{PP();Bw=class t extends fs{name="AccessDeniedException";$fault="client";error;constructor(e){super({name:"AccessDeniedException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error}},Zw=class t extends fs{name="InternalServerException";$fault="server";error;constructor(e){super({name:"InternalServerException",$fault:"server",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error}},Ww=class t extends fs{name="TooManyRequestsError";$fault="client";error;constructor(e){super({name:"TooManyRequestsError",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error}},Jw=class t extends fs{name="ValidationException";$fault="client";error;constructor(e){super({name:"ValidationException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error}}});var I2e,A2e,P2e,k2e,T2e,C2e,O2e,D2e,N2e,z2e,M2e,U2e,L2e,j2e,F2e,Dce,cV,q2e,pV,Nce,zce,V2e,nl,uV,G2e,lV,H2e,Fce,fV,Mce,dn,TP,K2e,kP,Uce,qce,Lce,jce,B2e,Z2e,W2e,dV,J2e,Tn,Vce,Gce,Xw,Hce,Kce,Bce,Zce,mV,X2e,Wce,Jce,Xce,Yce,Qce,eue,tue,rue,hV,gV,Yw=_(()=>{rt();aV();PP();I2e="AccessDeniedException",A2e="AccessToken",P2e="CreateOAuth2Token",k2e="CreateOAuth2TokenRequest",T2e="CreateOAuth2TokenRequestBody",C2e="CreateOAuth2TokenResponseBody",O2e="CreateOAuth2TokenResponse",D2e="CreateOAuth2TokenWithIAM",N2e="CreateOAuth2TokenWithIAMRequest",z2e="CreateOAuth2TokenWithIAMResponse",M2e="InternalServerException",U2e="OAuthAccessToken",L2e="RefreshToken",j2e="TooManyRequestsError",F2e="ValidationException",Dce="accessKeyId",cV="accessToken",q2e="access_token",pV="client",Nce="clientId",zce="codeVerifier",V2e="code",nl="error",uV="expiresIn",G2e="expires_in",lV="grantType",H2e="grant_type",Fce="http",fV="httpError",Mce="idToken",dn="jsonName",TP="message",K2e="resource",kP="refreshToken",Uce="redirectUri",qce="smithy.ts.sdk.synthetic.com.amazonaws.signin",Lce="secretAccessKey",jce="sessionToken",B2e="server",Z2e="tokenInput",W2e="tokenOutput",dV="tokenType",J2e="token_type",Tn="com.amazonaws.signin",Vce=new Zt(qce),Gce=[-3,qce,"SigninServiceException",0,[],[]];Vce.registerError(Gce,fs);Xw=new Zt(Tn),Hce=[-3,Tn,I2e,{[nl]:pV},[nl,TP],[0,0],2];Xw.registerError(Hce,Bw);Kce=[-3,Tn,M2e,{[nl]:B2e,[fV]:500},[nl,TP],[0,0],2];Xw.registerError(Kce,Zw);Bce=[-3,Tn,j2e,{[nl]:pV,[fV]:429},[nl,TP],[0,0],2];Xw.registerError(Bce,Ww);Zce=[-3,Tn,F2e,{[nl]:pV,[fV]:400},[nl,TP],[0,0],2];Xw.registerError(Zce,Jw);mV=[Vce,Xw],X2e=[0,Tn,U2e,8,0],Wce=[0,Tn,L2e,8,0],Jce=[3,Tn,A2e,8,[Dce,Lce,jce],[[0,{[dn]:Dce}],[0,{[dn]:Lce}],[0,{[dn]:jce}]],3],Xce=[3,Tn,k2e,0,[Z2e],[[()=>Yce,16]],1],Yce=[3,Tn,T2e,0,[Nce,lV,V2e,Uce,zce,kP],[[0,{[dn]:Nce}],[0,{[dn]:lV}],0,[0,{[dn]:Uce}],[0,{[dn]:zce}],[()=>Wce,{[dn]:kP}]],2],Qce=[3,Tn,O2e,0,[W2e],[[()=>eue,16]],1],eue=[3,Tn,C2e,0,[cV,dV,uV,kP,Mce],[[()=>Jce,{[dn]:cV}],[0,{[dn]:dV}],[1,{[dn]:uV}],[()=>Wce,{[dn]:kP}],[0,{[dn]:Mce}]],4],tue=[3,Tn,N2e,0,[lV,K2e],[[0,{[dn]:H2e}],0],2],rue=[3,Tn,z2e,0,[cV,dV,uV],[[()=>X2e,{[dn]:q2e}],[0,{[dn]:J2e}],[1,{[dn]:G2e}]],3],hV=[9,Tn,P2e,{[Fce]:["POST","/v1/token",200]},()=>Xce,()=>Qce],gV=[9,Tn,D2e,{[Fce]:["POST","/v1/token?x-amz-client-auth-method=iam",200]},()=>tue,()=>rue]});var nue,oue=_(()=>{Pn();Nd();Yn();gc();ve();ge();xe();nV();Oce();Yw();nue=t=>({apiVersion:"2023-01-01",base64Decoder:t?.base64Decoder??pr,base64Encoder:t?.base64Encoder??Wt,disableHostPrefix:t?.disableHostPrefix??!1,endpointProvider:t?.endpointProvider??Cce,extensions:t?.extensions??[],httpAuthSchemeProvider:t?.httpAuthSchemeProvider??yce,httpAuthSchemes:t?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4"),signer:new Gr},{schemeId:"smithy.api#noAuth",identityProvider:e=>e.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new An}],logger:t?.logger??new mo,protocol:t?.protocol??Sa,protocolSettings:t?.protocolSettings??{defaultNamespace:"com.amazonaws.signin",errorTypeRegistries:mV,version:"2023-01-01",serviceTarget:"Signin"},serviceId:t?.serviceId??"Signin",sha256:t?.sha256??Xi,urlParser:t?.urlParser??nn,utf8Decoder:t?.utf8Decoder??Tr,utf8Encoder:t?.utf8Encoder??ur})});var CP,iue,sue=_(()=>{iw();Nt();Pn();ve();Dt();jo();xe();CP=Vt(Gu());oue();iue=t=>{Gs(process.version);let e=ea(t),r=()=>e().then(Vs),o=nue(t);Ls(process.version);let n={profile:t?.profile,logger:o.logger};return{...o,...t,runtime:"node",defaultsMode:e,authSchemePreference:t?.authSchemePreference??Ie(is,n),bodyLengthChecker:t?.bodyLengthChecker??Zs,defaultUserAgentProvider:t?.defaultUserAgentProvider??rs({serviceId:o.serviceId,clientVersion:Hu.version}),maxAttempts:t?.maxAttempts??Ie(ca,t),region:t?.region??Ie(on,{...Xn,...n}),requestHandler:CP.NodeHttpHandler.create(t?.requestHandler??r),retryMode:t?.retryMode??Ie({...la,default:async()=>(await r()).retryMode||li},t),streamCollector:t?.streamCollector??CP.streamCollector,useDualstackEndpoint:t?.useDualstackEndpoint??Ie(Ys,n),useFipsEndpoint:t?.useFipsEndpoint??Ie(Qs,n),userAgentAppId:t?.userAgentAppId??Ie(ga,n)}}});var aue,cue,uue=_(()=>{aue=t=>{let e=t.httpAuthSchemes,r=t.httpAuthSchemeProvider,o=t.credentials;return{setHttpAuthScheme(n){let i=e.findIndex(s=>s.schemeId===n.schemeId);i===-1?e.push(n):e.splice(i,1,n)},httpAuthSchemes(){return e},setHttpAuthSchemeProvider(n){r=n},httpAuthSchemeProvider(){return r},setCredentials(n){o=n},credentials(){return o}}},cue=t=>({httpAuthSchemes:t.httpAuthSchemes(),httpAuthSchemeProvider:t.httpAuthSchemeProvider(),credentials:t.credentials()})});var lue,due=_(()=>{Nt();ve();ge();uue();lue=(t,e)=>{let r=Object.assign(ya(t),Bi(t),oa(t),aue(t));return e.forEach(o=>o.configure(r)),Object.assign(t,va(r),Hs(r),ia(r),cue(r))}});var Qw,yV=_(()=>{Nt();Yn();ve();Dt();Jt();ge();jo();rt();nV();oV();sue();due();Qw=class extends Rn{config;constructor(...[e]){let r=iue(e||{});super(r),this.initConfig=r;let o=wce(r),n=ma(o),i=ua(n),s=No(i),a=s,c=pc(a),u=vce(c),l=lue(u,e?.extensions||[]);this.config=l,this.middlewareStack.use(Fs(this.config)),this.middlewareStack.use(ha(this.config)),this.middlewareStack.use(yc(this.config)),this.middlewareStack.use(sa(this.config)),this.middlewareStack.use(da(this.config)),this.middlewareStack.use(pa(this.config)),this.middlewareStack.use(fa(this.config)),this.middlewareStack.use(es(this.config,{httpAuthSchemeParametersProvider:gce,identityProviderConfigProvider:async d=>new Fo({"aws.auth#sigv4":d.credentials})})),this.middlewareStack.use(ts(this.config))}destroy(){super.destroy()}}});var OP,pue,fue,DP,vV=_(()=>{ve();Jt();oV();OP=Ks(_ce,"Signin","SigninClient",fc),pue={IsControlPlane:{type:"staticContextParams",value:!1}},fue={IsOAuthEndpoint:{type:"staticContextParams",value:!0}},DP=(t,e,r,o)=>[]});var e_,wV=_(()=>{vV();Yw();e_=class extends OP(pue,DP,"CreateOAuth2Token",hV){}});var t_,_V=_(()=>{vV();Yw();t_=class extends OP(fue,DP,"CreateOAuth2TokenWithIAM",gV){}});var Y2e,NP,mue=_(()=>{ve();wV();_V();yV();Y2e={CreateOAuth2TokenCommand:e_,CreateOAuth2TokenWithIAMCommand:t_},NP=class extends Qw{};qs(Y2e,NP)});var hue=_(()=>{wV();_V()});var Q2e,gue=_(()=>{Q2e={AUTHCODE_EXPIRED:"AUTHCODE_EXPIRED",CONFLICT:"CONFLICT",INSUFFICIENT_PERMISSIONS:"INSUFFICIENT_PERMISSIONS",INVALID_REQUEST:"INVALID_REQUEST",RESOURCE_NOT_FOUND:"RESOURCE_NOT_FOUND",SERVER_ERROR:"server_error",SERVICE_QUOTA_EXCEEDED:"SERVICE_QUOTA_EXCEEDED",TOKEN_EXPIRED:"TOKEN_EXPIRED",USER_CREDENTIALS_CHANGED:"USER_CREDENTIALS_CHANGED"}});var yue=_(()=>{});var vue={};Ht(vue,{$Command:()=>Wn,AccessDeniedException:()=>Bw,AccessDeniedException$:()=>Hce,AccessToken$:()=>Jce,CreateOAuth2Token$:()=>hV,CreateOAuth2TokenCommand:()=>e_,CreateOAuth2TokenRequest$:()=>Xce,CreateOAuth2TokenRequestBody$:()=>Yce,CreateOAuth2TokenResponse$:()=>Qce,CreateOAuth2TokenResponseBody$:()=>eue,CreateOAuth2TokenWithIAM$:()=>gV,CreateOAuth2TokenWithIAMCommand:()=>t_,CreateOAuth2TokenWithIAMRequest$:()=>tue,CreateOAuth2TokenWithIAMResponse$:()=>rue,InternalServerException:()=>Zw,InternalServerException$:()=>Kce,OAuth2ErrorCode:()=>Q2e,Signin:()=>NP,SigninClient:()=>Qw,SigninServiceException:()=>fs,SigninServiceException$:()=>Gce,TooManyRequestsError:()=>Ww,TooManyRequestsError$:()=>Bce,ValidationException:()=>Jw,ValidationException$:()=>Zce,__Client:()=>Rn,errorTypeRegistries:()=>mV});var wue=_(()=>{yV();mue();hue();ve();Yw();gue();aV();yue();PP()});var Sue=U(bue=>{var{setCredentialFeature:e6e}=(Nt(),re(os)),{CredentialsProviderError:ol,parseKnownFiles:t6e,getProfileName:r6e}=(Dt(),re(zo)),{HttpRequest:n6e}=(ge(),re(zu)),{createHash:o6e,createPrivateKey:i6e,createPublicKey:s6e,sign:a6e}=io("node:crypto"),{promises:bV}=io("node:fs"),{homedir:c6e}=io("node:os"),{dirname:u6e,join:_ue}=io("node:path"),SV=class t{profileData;init;callerClientConfig;static REFRESH_THRESHOLD=300*1e3;constructor(e,r,o){this.profileData=e,this.init=r,this.callerClientConfig=o}async loadCredentials(){let e=await this.loadToken();if(!e)throw new ol(`Failed to load a token for session ${this.loginSession}, please re-authenticate using aws login`,{tryNextLink:!1,logger:this.logger});let r=e.accessToken,o=Date.now();return new Date(r.expiresAt).getTime()-o<=t.REFRESH_THRESHOLD?this.refresh(e):this.toCredentials(e.accessToken)}get logger(){return this.init?.logger}get loginSession(){return this.profileData.login_session}toCredentials(e){return{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey,sessionToken:e.sessionToken,accountId:e.accountId,expiration:new Date(e.expiresAt)}}async refresh(e){let r=await this.loadToken().catch(()=>e),o=Date.now(),n=new Date(r.accessToken.expiresAt).getTime(),i=new Date(e.accessToken.expiresAt).getTime(),s=n<=o&&i>o?e:r;if(new Date(s.accessToken.expiresAt).getTime()-Date.now()>t.REFRESH_THRESHOLD)return this.toCredentials(s.accessToken);let{SigninClient:c,CreateOAuth2TokenCommand:u}=(wue(),re(vue)),{logger:l,userAgentAppId:d}=this.callerClientConfig??{},f=(b=>b?.metadata?.handlerProtocol==="h2")(this.callerClientConfig?.requestHandler)?void 0:this.callerClientConfig?.requestHandler,h=this.profileData.region??await this.callerClientConfig?.region?.()??process.env.AWS_REGION,y=new c({credentials:{accessKeyId:"",secretAccessKey:""},region:h,requestHandler:f,logger:l,userAgentAppId:d,...this.init?.clientConfig});this.createDPoPInterceptor(y.middlewareStack);let w={tokenInput:{clientId:s.clientId,refreshToken:s.refreshToken,grantType:"refresh_token"}};try{let b=await y.send(new u(w)),{accessKeyId:S,secretAccessKey:x,sessionToken:R}=b.tokenOutput?.accessToken??{},{refreshToken:T,expiresIn:M}=b.tokenOutput??{};if(!S||!x||!R||!T)throw new ol("Token refresh response missing required fields",{logger:this.logger,tryNextLink:!1});let Z=(M??900)*1e3,te=new Date(Date.now()+Z),Ae={...s,accessToken:{...s.accessToken,accessKeyId:S,secretAccessKey:x,sessionToken:R,expiresAt:te.toISOString()},refreshToken:T};return await this.saveToken(Ae),this.toCredentials(Ae.accessToken)}catch(b){if(b.name==="AccessDeniedException"){let x=b.error,R;switch(x){case"TOKEN_EXPIRED":R="Your session has expired. Please reauthenticate.";break;case"USER_CREDENTIALS_CHANGED":R="Unable to refresh credentials because of a change in your password. Please reauthenticate with your new password.";break;case"INSUFFICIENT_PERMISSIONS":R="Unable to refresh credentials due to insufficient permissions. You may be missing permission for the 'CreateOAuth2Token' action.";break;default:R=`Failed to refresh token: ${String(b)}. Please re-authenticate using \`aws login\``}throw new ol(R,{logger:this.logger,tryNextLink:!1})}if(new Date(s.accessToken.expiresAt).getTime()>Date.now())return this.logger?.warn?.(`Failed to refresh token: ${String(b)}. Using existing token until expiry.`),this.toCredentials(s.accessToken);throw new ol(`Failed to refresh token: ${String(b)}. Please re-authenticate using aws login`,{logger:this.logger})}}async loadToken(){let e=this.getTokenFilePath();try{let r=await bV.readFile(e,"utf8"),o=JSON.parse(r),n=["accessToken","clientId","refreshToken","dpopKey"].filter(i=>!o[i]);if(o.accessToken?.accountId||n.push("accountId"),n.length>0)throw new ol(`Token validation failed, missing fields: ${n.join(", ")}`,{logger:this.logger,tryNextLink:!1});return o}catch(r){throw new ol(`Failed to load token from ${e}: ${String(r)}`,{logger:this.logger,tryNextLink:!1})}}async saveToken(e){let r=this.getTokenFilePath(),o=u6e(r);try{await bV.mkdir(o,{recursive:!0})}catch{}await bV.writeFile(r,JSON.stringify(e,null,2),"utf8")}getTokenFilePath(){let e=process.env.AWS_LOGIN_CACHE_DIRECTORY??_ue(c6e(),".aws","login","cache"),r=Buffer.from(this.loginSession,"utf8"),o=o6e("sha256").update(r).digest("hex");return _ue(e,`${o}.json`)}derToRawSignature(e){let r=2;if(e[r]!==2)throw new Error("Invalid DER signature");r++;let o=e[r++],n=e.subarray(r,r+o);if(r+=o,e[r]!==2)throw new Error("Invalid DER signature");r++;let i=e[r++],s=e.subarray(r,r+i);n=n[0]===0?n.subarray(1):n,s=s[0]===0?s.subarray(1):s;let a=Buffer.concat([Buffer.alloc(32-n.length),n]),c=Buffer.concat([Buffer.alloc(32-s.length),s]);return Buffer.concat([a,c])}createDPoPInterceptor(e){e.add(r=>async o=>{if(n6e.isInstance(o.request)){let n=o.request,i=`${n.protocol}//${n.hostname}${n.port?`:${n.port}`:""}${n.path}`,s=await this.generateDpop(n.method,i);n.headers={...n.headers,DPoP:s}}return r(o)},{step:"finalizeRequest",name:"dpopInterceptor",override:!0})}async generateDpop(e="POST",r){let o=await this.loadToken();try{let n=i6e({key:o.dpopKey,format:"pem",type:"sec1"}),s=s6e(n).export({format:"der",type:"spki"}),a=-1;for(let S=0;S<s.length;S++)if(s[S]===4){a=S;break}let c=s.slice(a+1,a+33),u=s.slice(a+33,a+65),l={alg:"ES256",typ:"dpop+jwt",jwk:{kty:"EC",crv:"P-256",x:c.toString("base64url"),y:u.toString("base64url")}},d={jti:crypto.randomUUID(),htm:e,htu:r,iat:Math.floor(Date.now()/1e3)},p=Buffer.from(JSON.stringify(l)).toString("base64url"),f=Buffer.from(JSON.stringify(d)).toString("base64url"),h=`${p}.${f}`,y=a6e("sha256",Buffer.from(h),n),b=this.derToRawSignature(y).toString("base64url");return`${h}.${b}`}catch(n){throw new ol(`Failed to generate Dpop proof: ${n instanceof Error?n.message:String(n)}`,{logger:this.logger,tryNextLink:!1})}}},l6e=t=>async({callerClientConfig:e}={})=>{t?.logger?.debug?.("@aws-sdk/credential-providers - fromLoginCredentials");let r=await t6e(t||{}),o=r6e({profile:t?.profile??e?.profile}),n=r[o];if(!n?.login_session)throw new ol(`Profile ${o} does not contain login_session.`,{tryNextLink:!0,logger:t?.logger});let s=await new SV(n,t,e).loadCredentials();return e6e(s,"CREDENTIALS_LOGIN","AD")};bue.fromLoginCredentials=l6e});var EV=U(xue=>{var{externalDataInterceptor:d6e,CredentialsProviderError:xV,parseKnownFiles:p6e,getProfileName:f6e}=(Dt(),re(zo)),{exec:m6e}=io("node:child_process"),{promisify:h6e}=io("node:util"),{setCredentialFeature:g6e}=(Nt(),re(os)),y6e=(t,e,r)=>{if(e.Version!==1)throw Error(`Profile ${t} credential_process did not return Version 1.`);if(e.AccessKeyId===void 0||e.SecretAccessKey===void 0)throw Error(`Profile ${t} credential_process returned invalid credentials.`);if(e.Expiration){let i=new Date;if(new Date(e.Expiration)<i)throw Error(`Profile ${t} credential_process returned expired credentials.`)}let o=e.AccountId;!o&&r?.[t]?.aws_account_id&&(o=r[t].aws_account_id);let n={accessKeyId:e.AccessKeyId,secretAccessKey:e.SecretAccessKey,...e.SessionToken&&{sessionToken:e.SessionToken},...e.Expiration&&{expiration:new Date(e.Expiration)},...e.CredentialScope&&{credentialScope:e.CredentialScope},...o&&{accountId:o}};return g6e(n,"CREDENTIALS_PROCESS","w"),n},v6e=async(t,e,r)=>{let o=e[t];if(e[t]){let n=o.credential_process;if(n!==void 0){let i=h6e(d6e?.getTokenRecord?.().exec??m6e);try{let{stdout:s}=await i(n),a;try{a=JSON.parse(s.trim())}catch{throw Error(`Profile ${t} credential_process returned invalid JSON.`)}return y6e(t,a,e)}catch(s){throw new xV(s.message,{logger:r})}}else throw new xV(`Profile ${t} did not contain credential_process.`,{logger:r})}else throw new xV(`Profile ${t} could not be found in shared credentials file.`,{logger:r})},w6e=(t={})=>async({callerClientConfig:e}={})=>{t.logger?.debug("@aws-sdk/credential-provider-process - fromProcess");let r=await p6e(t);return v6e(f6e({profile:t.profile??e?.profile}),r,t.logger)};xue.fromProcess=w6e});var RV=U($V=>{var{setCredentialFeature:_6e}=(Nt(),re(os)),{CredentialsProviderError:b6e,externalDataInterceptor:S6e}=(Dt(),re(zo)),{readFileSync:x6e}=io("node:fs"),$ue=t=>async e=>{t.logger?.debug("@aws-sdk/credential-provider-web-identity - fromWebToken");let{roleArn:r,roleSessionName:o,webIdentityToken:n,providerId:i,policyArns:s,policy:a,durationSeconds:c}=t,{roleAssumerWithWebIdentity:u}=t;if(!u){let{getDefaultRoleAssumerWithWebIdentity:l}=(rV(),re(tV));u=l({...t.clientConfig,credentialProviderLogger:t.logger,parentClientConfig:{...e?.callerClientConfig,...t.parentClientConfig}},t.clientPlugins)}return u({RoleArn:r,RoleSessionName:o??`aws-sdk-js-session-${Date.now()}`,WebIdentityToken:n,ProviderId:i,PolicyArns:s,Policy:a,DurationSeconds:c})},Eue="AWS_WEB_IDENTITY_TOKEN_FILE",E6e="AWS_ROLE_ARN",$6e="AWS_ROLE_SESSION_NAME",R6e=(t={})=>async e=>{t.logger?.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile");let r=t?.webIdentityTokenFile??process.env[Eue],o=t?.roleArn??process.env[E6e],n=t?.roleSessionName??process.env[$6e];if(!r||!o)throw new b6e("Web identity configuration not specified",{logger:t.logger});let i=await $ue({...t,webIdentityToken:S6e?.getTokenRecord?.()[r]??x6e(r,{encoding:"ascii"}),roleArn:o,roleSessionName:n})(e);return r===process.env[Eue]&&_6e(i,"CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN","h"),i};$V.fromTokenFile=R6e;$V.fromWebToken=$ue});var Cue=U(Tue=>{var{CredentialsProviderError:zP,chain:I6e,getProfileName:Pue,parseKnownFiles:A6e}=(Dt(),re(zo)),{setCredentialFeature:bc}=(Nt(),re(os)),P6e=(t,e,r)=>{let o={EcsContainer:async n=>{let{fromHttp:i}=T6(),{fromContainerMetadata:s}=dA();return r?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer"),async()=>I6e(i(n??{}),s(n))().then(IV)},Ec2InstanceMetadata:async n=>{r?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata");let{fromInstanceMetadata:i}=dA();return async()=>i(n)().then(IV)},Environment:async n=>{r?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment");let{fromEnv:i}=v6();return async()=>i(n)().then(IV)}};if(t in o)return o[t];throw new zP(`Unsupported credential source in profile ${e}. Got ${t}, expected EcsContainer or Ec2InstanceMetadata or Environment.`,{logger:r})},IV=t=>bc(t,"CREDENTIALS_PROFILE_NAMED_PROVIDER","p"),k6e=(t,{profile:e="default",logger:r}={})=>!!t&&typeof t=="object"&&typeof t.role_arn=="string"&&["undefined","string"].indexOf(typeof t.role_session_name)>-1&&["undefined","string"].indexOf(typeof t.external_id)>-1&&["undefined","string"].indexOf(typeof t.mfa_serial)>-1&&(T6e(t,{profile:e,logger:r})||C6e(t,{profile:e,logger:r})),T6e=(t,{profile:e,logger:r})=>{let o=typeof t.source_profile=="string"&&typeof t.credential_source>"u";return o&&r?.debug?.(` ${e} isAssumeRoleWithSourceProfile source_profile=${t.source_profile}`),o},C6e=(t,{profile:e,logger:r})=>{let o=typeof t.credential_source=="string"&&typeof t.source_profile>"u";return o&&r?.debug?.(` ${e} isCredentialSourceProfile credential_source=${t.credential_source}`),o},O6e=async(t,e,r,o,n={},i)=>{r.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)");let s=e[t],{source_profile:a,region:c}=s;if(!r.roleAssumer){let{getDefaultRoleAssumer:l}=(rV(),re(tV));r.roleAssumer=l({...r.clientConfig,credentialProviderLogger:r.logger,parentClientConfig:{...o,...r?.parentClientConfig,region:c??r?.parentClientConfig?.region??o?.region}},r.clientPlugins)}if(a&&a in n)throw new zP(`Detected a cycle attempting to resolve credentials for profile ${Pue(r)}. Profiles visited: `+Object.keys(n).join(", "),{logger:r.logger});r.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${a?`source_profile=[${a}]`:`profile=[${t}]`}`);let u=a?i(a,e,r,o,{...n,[a]:!0},Rue(e[a]??{})):(await P6e(s.credential_source,t,r.logger)(r))();if(Rue(s))return u.then(l=>bc(l,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"));{let l={RoleArn:s.role_arn,RoleSessionName:s.role_session_name||`aws-sdk-js-${Date.now()}`,ExternalId:s.external_id,DurationSeconds:parseInt(s.duration_seconds||"3600",10)},{mfa_serial:d}=s;if(d){if(!r.mfaCodeProvider)throw new zP(`Profile ${t} requires multi-factor authentication, but no MFA code callback was provided.`,{logger:r.logger,tryNextLink:!1});l.SerialNumber=d,l.TokenCode=await r.mfaCodeProvider(d)}let p=await u;return r.roleAssumer(p,l).then(f=>bc(f,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"))}},Rue=t=>!t.role_arn&&!!t.credential_source,D6e=t=>!!(t&&t.login_session),N6e=async(t,e,r)=>{let{fromLoginCredentials:o}=Sue(),n=await o({...e,profile:t})({callerClientConfig:r});return bc(n,"CREDENTIALS_PROFILE_LOGIN","AC")},z6e=t=>!!t&&typeof t=="object"&&typeof t.credential_process=="string",M6e=async(t,e)=>{let{fromProcess:r}=EV(),o=await r({...t,profile:e})();return bc(o,"CREDENTIALS_PROFILE_PROCESS","v")},U6e=async(t,e,r={},o)=>{let{fromSSO:n}=Uq();return n({profile:t,logger:r.logger,parentClientConfig:r.parentClientConfig,clientConfig:r.clientConfig})({callerClientConfig:o}).then(i=>e.sso_session?bc(i,"CREDENTIALS_PROFILE_SSO","r"):bc(i,"CREDENTIALS_PROFILE_SSO_LEGACY","t"))},L6e=t=>t&&(typeof t.sso_start_url=="string"||typeof t.sso_account_id=="string"||typeof t.sso_session=="string"||typeof t.sso_region=="string"||typeof t.sso_role_name=="string"),Iue=t=>!!t&&typeof t=="object"&&typeof t.aws_access_key_id=="string"&&typeof t.aws_secret_access_key=="string"&&["undefined","string"].indexOf(typeof t.aws_session_token)>-1&&["undefined","string"].indexOf(typeof t.aws_account_id)>-1,Aue=async(t,e)=>{e?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials");let r={accessKeyId:t.aws_access_key_id,secretAccessKey:t.aws_secret_access_key,sessionToken:t.aws_session_token,...t.aws_credential_scope&&{credentialScope:t.aws_credential_scope},...t.aws_account_id&&{accountId:t.aws_account_id}};return bc(r,"CREDENTIALS_PROFILE","n")},j6e=t=>!!t&&typeof t=="object"&&typeof t.web_identity_token_file=="string"&&typeof t.role_arn=="string"&&["undefined","string"].indexOf(typeof t.role_session_name)>-1,F6e=async(t,e,r)=>{let{fromTokenFile:o}=RV(),n=await o({webIdentityTokenFile:t.web_identity_token_file,roleArn:t.role_arn,roleSessionName:t.role_session_name,roleAssumerWithWebIdentity:e.roleAssumerWithWebIdentity,logger:e.logger,parentClientConfig:e.parentClientConfig})({callerClientConfig:r});return bc(n,"CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN","q")},kue=async(t,e,r,o,n={},i=!1)=>{let s=e[t];if(Object.keys(n).length>0&&Iue(s))return Aue(s,r);if(i||k6e(s,{profile:t,logger:r.logger}))return O6e(t,e,r,o,n,kue);if(Iue(s))return Aue(s,r);if(j6e(s))return F6e(s,r,o);if(z6e(s))return M6e(r,t);if(L6e(s))return await U6e(t,s,r,o);if(D6e(s))return N6e(t,r,o);throw new zP(`Could not resolve credentials using profile: [${t}] in configuration/credentials file(s).`,{logger:r.logger})},q6e=(t={})=>async({callerClientConfig:e}={})=>{t.logger?.debug("@aws-sdk/credential-provider-ini - fromIni");let r=await A6e(t);return kue(Pue({profile:t.profile??e?.profile}),r,t,e)};Tue.fromIni=q6e});var AV=U(UP=>{var{ENV_KEY:V6e,ENV_SECRET:G6e,fromEnv:H6e}=v6(),{chain:K6e,CredentialsProviderError:MP,ENV_PROFILE:B6e}=(Dt(),re(zo)),Oue="AWS_EC2_METADATA_DISABLED",Z6e=async t=>{let{ENV_CMDS_FULL_URI:e,ENV_CMDS_RELATIVE_URI:r,fromContainerMetadata:o,fromInstanceMetadata:n}=dA();if(process.env[r]||process.env[e]){t.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromHttp/fromContainerMetadata");let{fromHttp:i}=T6();return K6e(i(t),o(t))}return process.env[Oue]&&process.env[Oue]!=="false"?async()=>{throw new MP("EC2 Instance Metadata Service access disabled",{logger:t.logger})}:(t.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata"),n(t))};function W6e(t,e){let r=J6e(t),o,n,i,s,a=async c=>{if(c?.forceRefresh)return s||(s=r(c).then(u=>{i=u}).finally(()=>{s=void 0})),await s,i;if(i?.expiration&&i?.expiration?.getTime()<Date.now()&&(i=void 0),o)await o;else if(!i||e?.(i))if(i)n||(n=r(c).then(u=>{i=u}).catch(()=>{}).finally(()=>{n=void 0}));else return o=r(c).then(u=>{i=u}).finally(()=>{o=void 0}),a(c);return i};return a}var J6e=t=>async e=>{let r;for(let o of t)try{return await o(e)}catch(n){if(r=n,n?.tryNextLink)continue;throw n}throw r},Due=!1,X6e=(t={})=>W6e([async()=>{if(t.profile??process.env[B6e])throw process.env[V6e]&&process.env[G6e]&&(Due||((t.logger?.warn&&t.logger?.constructor?.name!=="NoOpLogger"?t.logger.warn.bind(t.logger):console.warn)(`@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING:
51
+ `)||(u["#text"]="#text"in u?u["#text"]+l:l);for(let l of s)l.tag==="__proto__"&&cq(u),l.tag in u?Array.isArray(u[l.tag])?u[l.tag].push(l.value):u[l.tag]=[u[l.tag],l.value]:u[l.tag]=l.value;for(let[l,d]of Object.entries(n))l==="__proto__"&&cq(u),u[l]=d;return{tag:r,value:u}}static ENTITIES={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};skipDoctype(){let e=this;e.i+=9;let r=0;for(;e.i<e.z;){let o=e.x[e.i];if(o==="[")++r;else if(o==="]")--r;else if(o===">"&&r===0){++e.i;return}++e.i}throw new Error("@aws-sdk XML parse error: unclosed DOCTYPE.")}decodeEntities(e){return e.replace(/&(?:#x([0-9a-fA-F]{1,6})|#(\d{1,7})|([a-zA-Z][a-zA-Z0-9]{0,30}));/g,(r,o,n,i)=>o?String.fromCharCode(parseInt(o,16)):n?String.fromCharCode(parseInt(n,10)):t.ENTITIES[i]??"")}};WA.XmlNode=uq;WA.XmlText=ZA;WA.parseXML=$je});var tie,Ju,XA=_(()=>{tie=Vt(JA());ve();ge();rt();xe();as();kA();pw();Ju=class extends hr{settings;stringDeserializer;constructor(e){super(),this.settings=e,this.stringDeserializer=new Cu(e)}setSerdeContext(e){this.serdeContext=e,this.stringDeserializer.setSerdeContext(e)}read(e,r,o){let n=B.of(e),i=n.getMemberSchemas();if(n.isStructSchema()&&n.isMemberSchema()&&!!Object.values(i).find(u=>!!u.getMemberTraits().eventPayload)){let u={},l=Object.keys(i)[0];return i[l].isBlobSchema()?u[l]=r:u[l]=this.read(i[l],r),u}let a=(this.serdeContext?.utf8Encoder??ur)(r),c=this.parseXml(a);return this.readSchema(e,o?c[o]:c)}readSchema(e,r){let o=B.of(e);if(o.isUnitSchema())return;let n=o.getMergedTraits();if(o.isListSchema()&&!Array.isArray(r))return this.readSchema(o,[r]);if(r==null)return r;if(typeof r=="object"){let i=!!n.xmlFlattened;if(o.isListSchema()){let a=o.getValueSchema(),c=[],u=a.getMergedTraits().xmlName??"member",l=i?r:(r[0]??r)[u];if(l==null)return c;let d=Array.isArray(l)?l:[l];for(let p of d)c.push(this.readSchema(a,p));return c}let s={};if(o.isMapSchema()){let a=o.getKeySchema(),c=o.getValueSchema(),u;i?u=Array.isArray(r)?r:[r]:u=Array.isArray(r.entry)?r.entry:[r.entry];let l=a.getMergedTraits().xmlName??"key",d=c.getMergedTraits().xmlName??"value";for(let p of u){let f=p[l],h=p[d];f==="__proto__"&&hi(s),s[f]=this.readSchema(c,h)}return s}if(o.isStructSchema()){let a=o.isUnionSchema(),c;a&&(c=new Bu(r,s));for(let[u,l]of o.structIterator()){let d=l.getMergedTraits(),p=d.httpPayload?d.xmlName??l.getName():l.getMemberTraits().xmlName??u;a&&c.mark(p),r[p]!=null&&(s[u]=this.readSchema(l,r[p]))}return a&&c.writeUnknown(),s}if(o.isDocumentSchema())return r;throw new Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${o.getName(!0)}`)}return o.isListSchema()?[]:o.isMapSchema()||o.isStructSchema()?{}:this.stringDeserializer.read(o,r)}parseXml(e){if(e.length){let r;try{r=(0,tie.parseXML)(e)}catch(s){throw s&&typeof s=="object"&&Object.defineProperty(s,"$responseBodyText",{value:e}),s}let o="#text",n=Object.keys(r)[0],i=r[n];return i[o]&&(i[n]=i[o],delete i[o]),wd(i)}return{}}}});var Wm,dq=_(()=>{ge();rt();xe();xe();as();Wm=class extends hr{settings;buffer;constructor(e){super(),this.settings=e}write(e,r,o=""){this.buffer===void 0&&(this.buffer="");let n=B.of(e);if(o&&!o.endsWith(".")&&(o+="."),n.isBlobSchema())(typeof r=="string"||r instanceof Uint8Array)&&(this.writeKey(o),this.writeValue((this.serdeContext?.base64Encoder??Wt)(r)));else if(n.isBooleanSchema()||n.isNumericSchema()||n.isStringSchema())r!=null?(this.writeKey(o),this.writeValue(String(r))):n.isIdempotencyToken()&&(this.writeKey(o),this.writeValue(Lo()));else if(n.isBigIntegerSchema())r!=null&&(this.writeKey(o),this.writeValue(String(r)));else if(n.isBigDecimalSchema())r!=null&&(this.writeKey(o),this.writeValue(r instanceof nt?r.string:String(r)));else if(n.isTimestampSchema()){if(r instanceof Date)switch(this.writeKey(o),qr(n,this.settings)){case 5:this.writeValue(r.toISOString().replace(".000Z","Z"));break;case 6:this.writeValue(Oo(r));break;case 7:this.writeValue(String(r.getTime()/1e3));break}}else if(n.isDocumentSchema())Array.isArray(r)?this.write(79,r,o):r instanceof Date?this.write(4,r,o):r instanceof Uint8Array?this.write(21,r,o):r&&typeof r=="object"?this.write(143,r,o):(this.writeKey(o),this.writeValue(String(r)));else if(n.isListSchema()){if(Array.isArray(r))if(r.length===0)this.settings.serializeEmptyLists&&(this.writeKey(o),this.writeValue(""));else{let i=n.getValueSchema(),s=this.settings.flattenLists||n.getMergedTraits().xmlFlattened,a=1;for(let c of r){if(c==null)continue;let u=i.getMergedTraits(),l=this.getKey("member",u.xmlName,u.ec2QueryName),d=s?`${o}${a}`:`${o}${l}.${a}`;this.write(i,c,d),++a}}}else if(n.isMapSchema()){if(r&&typeof r=="object"){let i=n.getKeySchema(),s=n.getValueSchema(),a=n.getMergedTraits().xmlFlattened,c=1;for(let u in r){let l=r[u];if(l==null)continue;let d=i.getMergedTraits(),p=this.getKey("key",d.xmlName,d.ec2QueryName),f=a?`${o}${c}.${p}`:`${o}entry.${c}.${p}`,h=s.getMergedTraits(),y=this.getKey("value",h.xmlName,h.ec2QueryName),w=a?`${o}${c}.${y}`:`${o}entry.${c}.${y}`;this.write(i,u,f),this.write(s,l,w),++c}}}else if(n.isStructSchema()){if(r&&typeof r=="object"){let i=!1;for(let[s,a]of n.structIterator()){if(r[s]==null&&!a.isIdempotencyToken())continue;let c=a.getMergedTraits(),u=this.getKey(s,c.xmlName,c.ec2QueryName,"struct"),l=`${o}${u}`;this.write(a,r[s],l),i=!0}if(!i&&n.isUnionSchema()){let{$unknown:s}=r;if(Array.isArray(s)){let[a,c]=s,u=`${o}${a}`;this.write(15,c,u)}}}}else if(!n.isUnitSchema())throw new Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${n.getName(!0)}`)}flush(){if(this.buffer===void 0)throw new Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer.");let e=this.buffer;return delete this.buffer,e}getKey(e,r,o,n){let{ec2:i,capitalizeKeys:s}=this.settings;if(i&&o)return o;let a=r??e;return s&&n==="struct"?a[0].toUpperCase()+a.slice(1):a}writeKey(e){e.endsWith(".")&&(e=e.slice(0,e.length-1)),this.buffer+=`&${Ji(e)}=`}writeValue(e){this.buffer+=Ji(e)}}});var Xu,pq=_(()=>{ge();rt();jm();XA();dq();Xu=class extends na{options;serializer;deserializer;mixin=new mi;constructor(e){super({defaultNamespace:e.defaultNamespace,errorTypeRegistries:e.errorTypeRegistries}),this.options=e;let r={timestampFormat:{useTrait:!0,default:5},httpBindings:!1,xmlNamespace:e.xmlNamespace,serviceNamespace:e.defaultNamespace,serializeEmptyLists:!0};this.serializer=new Wm(r),this.deserializer=new Ju(r)}getShapeId(){return"aws.protocols#awsQuery"}setSerdeContext(e){this.serializer.setSerdeContext(e),this.deserializer.setSerdeContext(e)}getPayloadCodec(){throw new Error("AWSQuery protocol has no payload codec.")}async serializeRequest(e,r,o){let n=await super.serializeRequest(e,r,o);n.path.endsWith("/")||(n.path+="/"),n.headers["content-type"]="application/x-www-form-urlencoded",(ii(e.input)==="unit"||!n.body)&&(n.body="");let i=e.name.split("#")[1]??e.name;return n.body=`Action=${i}&Version=${this.options.version}`+n.body,n.body.endsWith("&")&&(n.body=n.body.slice(-1)),n}async deserializeResponse(e,r,o){let n=this.deserializer,i=B.of(e.output),s={};if(o.statusCode>=300){let l=await sn(o.body,r);l.byteLength>0&&Object.assign(s,await n.read(15,l)),await this.handleError(e,r,o,s,this.deserializeMetadata(o))}for(let l in o.headers){let d=o.headers[l];delete o.headers[l],o.headers[l.toLowerCase()]=d}let a=e.name.split("#")[1]??e.name,c=i.isStructSchema()&&this.useNestedResult()?a+"Result":void 0,u=await sn(o.body,r);return u.byteLength>0&&Object.assign(s,await n.read(i,u,c)),s.$metadata=this.deserializeMetadata(o),s}useNestedResult(){return!0}async handleError(e,r,o,n,i){let s=this.loadQueryErrorCode(o,n)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,s,this.options.defaultNamespace);let a=this.loadQueryError(n)??{},c=this.loadQueryErrorMessage(n);a.message=c,a.Error={Type:a.Type,Code:a.Code,Message:c};let{errorSchema:u,errorMetadata:l}=await this.mixin.getErrorSchemaOrThrowBaseException(s,this.options.defaultNamespace,o,a,i,this.mixin.findQueryCompatibleError),d=B.of(u),p=this.compositeErrorRegistry.getErrorCtor(u)??Error,f=new p({}),h={Type:a.Error.Type,Code:a.Error.Code,Error:a.Error};for(let[y,w]of d.structIterator()){let b=w.getMergedTraits().xmlName??y,S=a[b]??n[b];h[y]=this.deserializer.readSchema(w,S)}throw this.mixin.decorateServiceException(Object.assign(f,l,{$fault:d.getMergedTraits().error,message:c},h),n)}loadQueryErrorCode(e,r){let o=(r.Errors?.[0]?.Error??r.Errors?.Error??r.Error)?.Code;if(o!==void 0)return o;if(e.statusCode==404)return"NotFound"}loadQueryError(e){return e.Errors?.[0]?.Error??e.Errors?.Error??e.Error}loadQueryErrorMessage(e){let r=this.loadQueryError(e);return r?.message??r?.Message??e.message??e.Message??"Unknown"}getDefaultContentType(){return"application/x-www-form-urlencoded"}}});var YA,rie=_(()=>{pq();YA=class extends Xu{options;constructor(e){super(e),this.options=e;let r={capitalizeKeys:!0,flattenLists:!0,serializeEmptyLists:!1,ec2:!0};Object.assign(this.serializer.settings,r)}getShapeId(){return"aws.protocols#ec2Query"}useNestedResult(){return!1}}});var nie,fq,oie,QA,mq=_(()=>{nie=Vt(JA());ve();tq();fq=(t,e)=>NA(t,e).then(r=>{if(r.length){let o;try{o=(0,nie.parseXML)(r)}catch(a){throw a&&typeof a=="object"&&Object.defineProperty(a,"$responseBodyText",{value:r}),a}let n="#text",i=Object.keys(o)[0],s=o[i];return s[n]&&(s[i]=s[n],delete s[n]),wd(s)}return{}}),oie=async(t,e)=>{let r=await fq(t,e);return r.Error&&(r.Error.message=r.Error.message??r.Error.Message),r},QA=(t,e)=>{if(e?.Error?.Code!==void 0)return e.Error.Code;if(e?.Code!==void 0)return e.Code;if(t.statusCode==404)return"NotFound"}});var Qn,Jm,hq=_(()=>{Qn=Vt(JA());ge();rt();xe();xe();as();Jm=class extends hr{settings;stringBuffer;byteBuffer;buffer;constructor(e){super(),this.settings=e}write(e,r){let o=B.of(e);if(o.isStringSchema()&&typeof r=="string")this.stringBuffer=r;else if(o.isBlobSchema())this.byteBuffer="byteLength"in r?r:(this.serdeContext?.base64Decoder??fr)(r);else{this.buffer=this.writeStruct(o,r,void 0);let n=o.getMergedTraits();n.httpPayload&&!n.xmlName&&this.buffer.withName(o.getName())}}flush(){if(this.byteBuffer!==void 0){let r=this.byteBuffer;return delete this.byteBuffer,r}if(this.stringBuffer!==void 0){let r=this.stringBuffer;return delete this.stringBuffer,r}let e=this.buffer;return this.settings.xmlNamespace&&(e?.attributes?.xmlns||e.addAttribute("xmlns",this.settings.xmlNamespace)),delete this.buffer,e.toString()}writeStruct(e,r,o){let n=e.getMergedTraits(),i=e.isMemberSchema()&&!n.httpPayload?e.getMemberTraits().xmlName??e.getMemberName():n.xmlName??e.getName();if(!i||!e.isStructSchema())throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${e.getName(!0)}.`);let s=Qn.XmlNode.of(i),[a,c]=this.getXmlnsAttribute(e,o);for(let[l,d]of e.structIterator()){let p=r[l];if(p!=null||d.isIdempotencyToken()){if(d.getMergedTraits().xmlAttribute){s.addAttribute(d.getMergedTraits().xmlName??l,this.writeSimple(d,p));continue}if(d.isListSchema())this.writeList(d,p,s,c);else if(d.isMapSchema())this.writeMap(d,p,s,c);else if(d.isStructSchema())s.addChildNode(this.writeStruct(d,p,c));else{let f=Qn.XmlNode.of(d.getMergedTraits().xmlName??d.getMemberName());this.writeSimpleInto(d,p,f,c),s.addChildNode(f)}}}let{$unknown:u}=r;if(u&&e.isUnionSchema()&&Array.isArray(u)&&Object.keys(r).length===1){let[l,d]=u,p=Qn.XmlNode.of(l);if(typeof d!="string")if(r instanceof Qn.XmlNode||r instanceof Qn.XmlText)s.addChildNode(r);else throw new Error("@aws-sdk - $unknown union member in XML requires value of type string, @aws-sdk/xml-builder::XmlNode or XmlText.");this.writeSimpleInto(0,d,p,c),s.addChildNode(p)}return c&&s.addAttribute(a,c),s}writeList(e,r,o,n){if(!e.isMemberSchema())throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${e.getName(!0)}`);let i=e.getMergedTraits(),s=e.getValueSchema(),a=s.getMergedTraits(),c=!!a.sparse,u=!!i.xmlFlattened,[l,d]=this.getXmlnsAttribute(e,n),p=(f,h)=>{if(s.isListSchema())this.writeList(s,Array.isArray(h)?h:[h],f,d);else if(s.isMapSchema())this.writeMap(s,h,f,d);else if(s.isStructSchema()){let y=this.writeStruct(s,h,d);f.addChildNode(y.withName(u?i.xmlName??e.getMemberName():a.xmlName??"member"))}else{let y=Qn.XmlNode.of(u?i.xmlName??e.getMemberName():a.xmlName??"member");this.writeSimpleInto(s,h,y,d),f.addChildNode(y)}};if(u)for(let f of r)(c||f!=null)&&p(o,f);else{let f=Qn.XmlNode.of(i.xmlName??e.getMemberName());d&&f.addAttribute(l,d);for(let h of r)(c||h!=null)&&p(f,h);o.addChildNode(f)}}writeMap(e,r,o,n,i=!1){if(!e.isMemberSchema())throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${e.getName(!0)}`);let s=e.getMergedTraits(),a=e.getKeySchema(),u=a.getMergedTraits().xmlName??"key",l=e.getValueSchema(),d=l.getMergedTraits(),p=d.xmlName??"value",f=!!d.sparse,h=!!s.xmlFlattened,[y,w]=this.getXmlnsAttribute(e,n),b=(S,x,R)=>{let T=Qn.XmlNode.of(u,x),[M,Z]=this.getXmlnsAttribute(a,w);Z&&T.addAttribute(M,Z),S.addChildNode(T);let te=Qn.XmlNode.of(p);l.isListSchema()?this.writeList(l,R,te,w):l.isMapSchema()?this.writeMap(l,R,te,w,!0):l.isStructSchema()?te=this.writeStruct(l,R,w):this.writeSimpleInto(l,R,te,w),S.addChildNode(te)};if(h)for(let S in r){let x=r[S];if(f||x!=null){let R=Qn.XmlNode.of(s.xmlName??e.getMemberName());b(R,S,x),o.addChildNode(R)}}else{let S;i||(S=Qn.XmlNode.of(s.xmlName??e.getMemberName()),w&&S.addAttribute(y,w),o.addChildNode(S));for(let x in r){let R=r[x];if(f||R!=null){let T=Qn.XmlNode.of("entry");b(T,x,R),(i?o:S).addChildNode(T)}}}}writeSimple(e,r){if(r===null)throw new Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value.");let o=B.of(e),n=null;if(r&&typeof r=="object")if(o.isBlobSchema())n=(this.serdeContext?.base64Encoder??Wt)(r);else if(o.isTimestampSchema()&&r instanceof Date)switch(qr(o,this.settings)){case 5:n=r.toISOString().replace(".000Z","Z");break;case 6:n=Oo(r);break;case 7:n=String(r.getTime()/1e3);break;default:console.warn("Missing timestamp format, using http date",r),n=Oo(r);break}else{if(o.isBigDecimalSchema()&&r)return r instanceof nt?r.string:String(r);throw o.isMapSchema()||o.isListSchema()?new Error("@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead."):new Error(`@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${o.getName(!0)}`)}if((o.isBooleanSchema()||o.isNumericSchema()||o.isBigIntegerSchema()||o.isBigDecimalSchema())&&(n=String(r)),o.isStringSchema()&&(r===void 0&&o.isIdempotencyToken()?n=Lo():n=String(r)),n===null)throw new Error(`Unhandled schema-value pair ${o.getName(!0)}=${r}`);return n}writeSimpleInto(e,r,o,n){let i=this.writeSimple(e,r),s=B.of(e),a=new Qn.XmlText(i),[c,u]=this.getXmlnsAttribute(s,n);u&&o.addAttribute(c,u),o.addChildNode(a)}getXmlnsAttribute(e,r){let o=e.getMergedTraits(),[n,i]=o.xmlNamespace??[];return i&&i!==r?[n?`xmlns:${n}`:"xmlns",i]:[void 0,void 0]}}});var Xm,gq=_(()=>{as();XA();hq();Xm=class extends hr{settings;constructor(e){super(),this.settings=e}createSerializer(){let e=new Jm(this.settings);return e.setSerdeContext(this.serdeContext),e}createDeserializer(){let e=new Ju(this.settings);return e.setSerdeContext(this.serdeContext),e}}});var eP,iie=_(()=>{ge();rt();jm();mq();gq();eP=class extends Tu{codec;serializer;deserializer;mixin=new mi;constructor(e){super(e);let r={timestampFormat:{useTrait:!0,default:5},httpBindings:!0,xmlNamespace:e.xmlNamespace,serviceNamespace:e.defaultNamespace};this.codec=new Xm(r),this.serializer=new Du(this.codec.createSerializer(),r),this.deserializer=new Ou(this.codec.createDeserializer(),r)}getPayloadCodec(){return this.codec}getShapeId(){return"aws.protocols#restXml"}async serializeRequest(e,r,o){let n=await super.serializeRequest(e,r,o),i=B.of(e.input);if(!n.headers["content-type"]){let s=this.mixin.resolveRestContentType(this.getDefaultContentType(),i);s&&(n.headers["content-type"]=s)}return typeof n.body=="string"&&n.headers["content-type"]===this.getDefaultContentType()&&!n.body.startsWith("<?xml ")&&!this.hasUnstructuredPayloadBinding(i)&&(n.body='<?xml version="1.0" encoding="UTF-8"?>'+n.body),n}async deserializeResponse(e,r,o){return super.deserializeResponse(e,r,o)}async handleError(e,r,o,n,i){let s=QA(o,n)??"Unknown";if(this.mixin.compose(this.compositeErrorRegistry,s,this.options.defaultNamespace),n.Error&&typeof n.Error=="object")for(let y of Object.keys(n.Error))n[y]=n.Error[y],y.toLowerCase()==="message"&&(n.message=n.Error[y]);n.RequestId&&!i.requestId&&(i.requestId=n.RequestId);let{errorSchema:a,errorMetadata:c}=await this.mixin.getErrorSchemaOrThrowBaseException(s,this.options.defaultNamespace,o,n,i),u=B.of(a),l=n.Error?.message??n.Error?.Message??n.message??n.Message??"UnknownError",d=this.compositeErrorRegistry.getErrorCtor(a)??Error,p=new d({});await this.deserializeHttpMessage(a,r,o,n);let f={},h=this.codec.createDeserializer();for(let[y,w]of u.structIterator()){let b=w.getMergedTraits().xmlName??y,S=n.Error?.[b]??n[b];f[y]=h.readSchema(w,S)}throw this.mixin.decorateServiceException(Object.assign(p,c,{$fault:u.getMergedTraits().error,message:l},f),n)}getDefaultContentType(){return"application/xml"}hasUnstructuredPayloadBinding(e){for(let[,r]of e.structIterator())if(r.getMergedTraits().httpPayload)return!(r.isStructSchema()||r.isMapSchema()||r.isListSchema());return!1}}});var sie,aie=_(()=>{xe();sie=t=>{if(t!=null)return typeof t=="object"&&"__type"in t&&delete t.__type,uR(t)}});var cie,uie,lie,die=_(()=>{cie=t=>{if(t==null)return t;if(typeof t=="number"||typeof t=="bigint"){let e=new Error(`Received number ${t} where a string was expected.`);return e.name="Warning",console.warn(e),String(t)}if(typeof t=="boolean"){let e=new Error(`Received boolean ${t} where a string was expected.`);return e.name="Warning",console.warn(e),String(t)}return t},uie=t=>{if(t==null)return t;if(typeof t=="string"){let e=t.toLowerCase();if(t!==""&&e!=="false"&&e!=="true"){let r=new Error(`Received string "${t}" where a boolean was expected.`);r.name="Warning",console.warn(r)}return t!==""&&e!=="false"}return t},lie=t=>{if(t==null)return t;if(typeof t=="string"){let e=Number(t);if(e.toString()!==t){let r=new Error(`Received string "${t}" where a number was expected.`);return r.name="Warning",console.warn(r),t}return e}return t}});var yq={};Ht(yq,{AwsEc2QueryProtocol:()=>YA,AwsJson1_0Protocol:()=>GA,AwsJson1_1Protocol:()=>HA,AwsJsonRpcProtocol:()=>Wu,AwsQueryProtocol:()=>Xu,AwsRestJsonProtocol:()=>Sa,AwsRestXmlProtocol:()=>eP,AwsSmithyRpcV2CborProtocol:()=>PA,JsonCodec:()=>BA,JsonCodec2:()=>Zu,JsonShapeDeserializer:()=>Bm,JsonShapeDeserializer2:()=>Gm,JsonShapeSerializer:()=>Zm,JsonShapeSerializer2:()=>Km,QueryShapeSerializer:()=>Wm,XmlCodec:()=>Xm,XmlShapeDeserializer:()=>Ju,XmlShapeSerializer:()=>Jm,_toBool:()=>uie,_toNum:()=>lie,_toStr:()=>cie,awsExpectUnion:()=>sie,loadJsonRpcErrorCode:()=>MA,loadRestJsonErrorCode:()=>zA,loadRestXmlErrorCode:()=>QA,parseJsonBody:()=>Dd,parseJsonErrorBody:()=>Foe,parseXmlBody:()=>fq,parseXmlErrorBody:()=>oie});var Nd=_(()=>{Loe();Woe();Joe();VA();Xoe();eie();sq();aq();qA();nq();iq();Vm();rie();pq();dq();iie();gq();XA();hq();mq();aie();die()});var fw,zd,tP,pie,gie,rP,vq,fie,wq,Ym,mie,hie,Rje,go,Ije,yie,vie=_(()=>{Jt();fw="ref",zd=-1,tP=!0,pie="isSet",gie="PartitionResult",rP="booleanEquals",vq="getAttr",fie={[fw]:"Endpoint"},wq={[fw]:gie},Ym={},mie=[{[fw]:"Region"}],hie={conditions:[[pie,[fie]],[pie,mie],["aws.partition",mie,gie],[rP,[{[fw]:"UseFIPS"},tP]],[rP,[{[fw]:"UseDualStack"},tP]],[rP,[{fn:vq,argv:[wq,"supportsDualStack"]},tP]],[rP,[{fn:vq,argv:[wq,"supportsFIPS"]},tP]],["stringEquals",[{fn:vq,argv:[wq,"name"]},"aws-us-gov"]]],results:[[zd],[zd,"Invalid Configuration: FIPS and custom endpoint are not supported"],[zd,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[fie,Ym],["https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",Ym],[zd,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://oidc.{Region}.amazonaws.com",Ym],["https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}",Ym],[zd,"FIPS is enabled but this partition does not support FIPS"],["https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}",Ym],[zd,"DualStack is enabled but this partition does not support DualStack"],["https://oidc.{Region}.{PartitionResult#dnsSuffix}",Ym],[zd,"Invalid Configuration: Missing Region"]]},Rje=2,go=1e8,Ije=new Int32Array([-1,1,-1,0,13,3,1,4,go+12,2,5,go+12,3,8,6,4,7,go+11,5,go+9,go+10,4,11,9,6,10,go+8,7,go+6,go+7,5,12,go+5,6,go+4,go+5,3,go+1,14,4,go+2,go+3]),yie=ci.from(Ije,Rje,hie.conditions,hie.results)});var Aje,wie,_ie=_(()=>{Nt();Jt();vie();Aje=new ui({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),wie=(t,e={})=>Aje.get(t,()=>ra(yie,{endpointParams:t,logger:e.logger}));ho.aws=ns});var Br,nP=_(()=>{ve();Br=class t extends si{constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}}});var mw,hw,gw,yw,vw,ww,_w,bw,Sw,xw,Ew,_q=_(()=>{nP();mw=class t extends Br{name="AccessDeniedException";$fault="client";error;reason;error_description;constructor(e){super({name:"AccessDeniedException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error,this.reason=e.reason,this.error_description=e.error_description}},hw=class t extends Br{name="AuthorizationPendingException";$fault="client";error;error_description;constructor(e){super({name:"AuthorizationPendingException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error,this.error_description=e.error_description}},gw=class t extends Br{name="ExpiredTokenException";$fault="client";error;error_description;constructor(e){super({name:"ExpiredTokenException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error,this.error_description=e.error_description}},yw=class t extends Br{name="InternalServerException";$fault="server";error;error_description;constructor(e){super({name:"InternalServerException",$fault:"server",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error,this.error_description=e.error_description}},vw=class t extends Br{name="InvalidClientException";$fault="client";error;error_description;constructor(e){super({name:"InvalidClientException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error,this.error_description=e.error_description}},ww=class t extends Br{name="InvalidGrantException";$fault="client";error;error_description;constructor(e){super({name:"InvalidGrantException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error,this.error_description=e.error_description}},_w=class t extends Br{name="InvalidRequestException";$fault="client";error;reason;error_description;constructor(e){super({name:"InvalidRequestException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error,this.reason=e.reason,this.error_description=e.error_description}},bw=class t extends Br{name="InvalidScopeException";$fault="client";error;error_description;constructor(e){super({name:"InvalidScopeException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error,this.error_description=e.error_description}},Sw=class t extends Br{name="SlowDownException";$fault="client";error;error_description;constructor(e){super({name:"SlowDownException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error,this.error_description=e.error_description}},xw=class t extends Br{name="UnauthorizedClientException";$fault="client";error;error_description;constructor(e){super({name:"UnauthorizedClientException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error,this.error_description=e.error_description}},Ew=class t extends Br{name="UnsupportedGrantTypeException";$fault="client";error;error_description;constructor(e){super({name:"UnsupportedGrantTypeException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error,this.error_description=e.error_description}}});var Pje,kje,Tje,Cje,Oje,Dje,Nje,zje,Mje,Uje,Lje,jje,Fje,qje,Vje,Gje,Hje,Kje,Bje,Zje,xa,Wje,Jje,Xje,Yje,Qje,gr,e4e,cs,t4e,r4e,us,n4e,bie,Sie,o4e,xie,i4e,s4e,a4e,Rr,Eie,$ie,gi,Rie,Iie,Aie,Pie,kie,Tie,Cie,Oie,Die,Nie,zie,bq,c4e,u4e,l4e,d4e,Mie,Uie,Lie,Sq,oP=_(()=>{rt();_q();nP();Pje="AccessDeniedException",kje="AuthorizationPendingException",Tje="AccessToken",Cje="ClientSecret",Oje="CreateToken",Dje="CreateTokenRequest",Nje="CreateTokenResponse",zje="CodeVerifier",Mje="ExpiredTokenException",Uje="InvalidClientException",Lje="InvalidGrantException",jje="InvalidRequestException",Fje="InternalServerException",qje="InvalidScopeException",Vje="IdToken",Gje="RefreshToken",Hje="SlowDownException",Kje="UnauthorizedClientException",Bje="UnsupportedGrantTypeException",Zje="accessToken",xa="client",Wje="clientId",Jje="clientSecret",Xje="codeVerifier",Yje="code",Qje="deviceCode",gr="error",e4e="expiresIn",cs="error_description",t4e="grantType",r4e="http",us="httpError",n4e="idToken",bie="reason",Sie="refreshToken",o4e="redirectUri",xie="smithy.ts.sdk.synthetic.com.amazonaws.ssooidc",i4e="scope",s4e="server",a4e="tokenType",Rr="com.amazonaws.ssooidc",Eie=new Zt(xie),$ie=[-3,xie,"SSOOIDCServiceException",0,[],[]];Eie.registerError($ie,Br);gi=new Zt(Rr),Rie=[-3,Rr,Pje,{[gr]:xa,[us]:400},[gr,bie,cs],[0,0,0]];gi.registerError(Rie,mw);Iie=[-3,Rr,kje,{[gr]:xa,[us]:400},[gr,cs],[0,0]];gi.registerError(Iie,hw);Aie=[-3,Rr,Mje,{[gr]:xa,[us]:400},[gr,cs],[0,0]];gi.registerError(Aie,gw);Pie=[-3,Rr,Fje,{[gr]:s4e,[us]:500},[gr,cs],[0,0]];gi.registerError(Pie,yw);kie=[-3,Rr,Uje,{[gr]:xa,[us]:401},[gr,cs],[0,0]];gi.registerError(kie,vw);Tie=[-3,Rr,Lje,{[gr]:xa,[us]:400},[gr,cs],[0,0]];gi.registerError(Tie,ww);Cie=[-3,Rr,jje,{[gr]:xa,[us]:400},[gr,bie,cs],[0,0,0]];gi.registerError(Cie,_w);Oie=[-3,Rr,qje,{[gr]:xa,[us]:400},[gr,cs],[0,0]];gi.registerError(Oie,bw);Die=[-3,Rr,Hje,{[gr]:xa,[us]:400},[gr,cs],[0,0]];gi.registerError(Die,Sw);Nie=[-3,Rr,Kje,{[gr]:xa,[us]:400},[gr,cs],[0,0]];gi.registerError(Nie,xw);zie=[-3,Rr,Bje,{[gr]:xa,[us]:400},[gr,cs],[0,0]];gi.registerError(zie,Ew);bq=[Eie,gi],c4e=[0,Rr,Tje,8,0],u4e=[0,Rr,Cje,8,0],l4e=[0,Rr,zje,8,0],d4e=[0,Rr,Vje,8,0],Mie=[0,Rr,Gje,8,0],Uie=[3,Rr,Dje,0,[Wje,Jje,t4e,Qje,Yje,Sie,i4e,o4e,Xje],[0,[()=>u4e,0],0,0,0,[()=>Mie,0],64,0,[()=>l4e,0]],3],Lie=[3,Rr,Nje,0,[Zje,a4e,e4e,Sie,n4e],[[()=>c4e,0],0,1,[()=>Mie,0],[()=>d4e,0]]],Sq=[9,Rr,Oje,{[r4e]:["POST","/token",200]},()=>Uie,()=>Lie]});var jie,Fie=_(()=>{Pn();Nd();Yn();gc();ve();ge();xe();C6();_ie();oP();jie=t=>({apiVersion:"2019-06-10",base64Decoder:t?.base64Decoder??fr,base64Encoder:t?.base64Encoder??Wt,disableHostPrefix:t?.disableHostPrefix??!1,endpointProvider:t?.endpointProvider??wie,extensions:t?.extensions??[],httpAuthSchemeProvider:t?.httpAuthSchemeProvider??goe,httpAuthSchemes:t?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4"),signer:new Gr},{schemeId:"smithy.api#noAuth",identityProvider:e=>e.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new An}],logger:t?.logger??new mo,protocol:t?.protocol??Sa,protocolSettings:t?.protocolSettings??{defaultNamespace:"com.amazonaws.ssooidc",errorTypeRegistries:bq,version:"2019-06-10",serviceTarget:"AWSSSOOIDCService"},serviceId:t?.serviceId??"SSO OIDC",sha256:t?.sha256??Xi,urlParser:t?.urlParser??nn,utf8Decoder:t?.utf8Decoder??Tr,utf8Encoder:t?.utf8Encoder??ur})});var iP,qie,Vie=_(()=>{iw();Nt();Pn();ve();Dt();jo();xe();iP=Vt(Gu());Fie();qie=t=>{Gs(process.version);let e=ea(t),r=()=>e().then(Vs),o=jie(t);Ls(process.version);let n={profile:t?.profile,logger:o.logger};return{...o,...t,runtime:"node",defaultsMode:e,authSchemePreference:t?.authSchemePreference??Ie(is,n),bodyLengthChecker:t?.bodyLengthChecker??Zs,defaultUserAgentProvider:t?.defaultUserAgentProvider??rs({serviceId:o.serviceId,clientVersion:Hu.version}),maxAttempts:t?.maxAttempts??Ie(ca,t),region:t?.region??Ie(on,{...Xn,...n}),requestHandler:iP.NodeHttpHandler.create(t?.requestHandler??r),retryMode:t?.retryMode??Ie({...la,default:async()=>(await r()).retryMode||li},t),streamCollector:t?.streamCollector??iP.streamCollector,useDualstackEndpoint:t?.useDualstackEndpoint??Ie(Ys,n),useFipsEndpoint:t?.useFipsEndpoint??Ie(Qs,n),userAgentAppId:t?.userAgentAppId??Ie(ga,n)}}});var Gie,Hie,Kie=_(()=>{Gie=t=>{let e=t.httpAuthSchemes,r=t.httpAuthSchemeProvider,o=t.credentials;return{setHttpAuthScheme(n){let i=e.findIndex(s=>s.schemeId===n.schemeId);i===-1?e.push(n):e.splice(i,1,n)},httpAuthSchemes(){return e},setHttpAuthSchemeProvider(n){r=n},httpAuthSchemeProvider(){return r},setCredentials(n){o=n},credentials(){return o}}},Hie=t=>({httpAuthSchemes:t.httpAuthSchemes(),httpAuthSchemeProvider:t.httpAuthSchemeProvider(),credentials:t.credentials()})});var Bie,Zie=_(()=>{Nt();ve();ge();Kie();Bie=(t,e)=>{let r=Object.assign(ya(t),Bi(t),oa(t),Gie(t));return e.forEach(o=>o.configure(r)),Object.assign(t,va(r),Hs(r),ia(r),Hie(r))}});var $w,xq=_(()=>{Nt();Yn();ve();Dt();Jt();ge();jo();rt();C6();O6();Vie();Zie();$w=class extends Rn{config;constructor(...[e]){let r=qie(e||{});super(r),this.initConfig=r;let o=voe(r),n=ma(o),i=ua(n),s=No(i),a=s,c=pc(a),u=yoe(c),l=Bie(u,e?.extensions||[]);this.config=l,this.middlewareStack.use(Fs(this.config)),this.middlewareStack.use(ha(this.config)),this.middlewareStack.use(yc(this.config)),this.middlewareStack.use(sa(this.config)),this.middlewareStack.use(da(this.config)),this.middlewareStack.use(pa(this.config)),this.middlewareStack.use(fa(this.config)),this.middlewareStack.use(es(this.config,{httpAuthSchemeParametersProvider:hoe,identityProviderConfigProvider:async d=>new Fo({"aws.auth#sigv4":d.credentials})})),this.middlewareStack.use(ts(this.config))}destroy(){super.destroy()}}});var Wie,Jie,Xie,Yie=_(()=>{ve();Jt();O6();Wie=Ks(woe,"AWSSSOOIDCService","SSOOIDCClient",fc),Jie={},Xie=(t,e,r,o)=>[]});var Rw,Eq=_(()=>{Yie();oP();Rw=class extends Wie(Jie,Xie,"CreateToken",Sq){}});var p4e,sP,Qie=_(()=>{ve();Eq();xq();p4e={CreateTokenCommand:Rw},sP=class extends $w{};qs(p4e,sP)});var ese=_(()=>{Eq()});var f4e,m4e,tse=_(()=>{f4e={KMS_ACCESS_DENIED:"KMS_AccessDeniedException"},m4e={KMS_DISABLED_KEY:"KMS_DisabledException",KMS_INVALID_KEY_USAGE:"KMS_InvalidKeyUsageException",KMS_INVALID_STATE:"KMS_InvalidStateException",KMS_KEY_NOT_FOUND:"KMS_NotFoundException"}});var rse=_(()=>{});var $q={};Ht($q,{$Command:()=>Wn,AccessDeniedException:()=>mw,AccessDeniedException$:()=>Rie,AccessDeniedExceptionReason:()=>f4e,AuthorizationPendingException:()=>hw,AuthorizationPendingException$:()=>Iie,CreateToken$:()=>Sq,CreateTokenCommand:()=>Rw,CreateTokenRequest$:()=>Uie,CreateTokenResponse$:()=>Lie,ExpiredTokenException:()=>gw,ExpiredTokenException$:()=>Aie,InternalServerException:()=>yw,InternalServerException$:()=>Pie,InvalidClientException:()=>vw,InvalidClientException$:()=>kie,InvalidGrantException:()=>ww,InvalidGrantException$:()=>Tie,InvalidRequestException:()=>_w,InvalidRequestException$:()=>Cie,InvalidRequestExceptionReason:()=>m4e,InvalidScopeException:()=>bw,InvalidScopeException$:()=>Oie,SSOOIDC:()=>sP,SSOOIDCClient:()=>$w,SSOOIDCServiceException:()=>Br,SSOOIDCServiceException$:()=>$ie,SlowDownException:()=>Sw,SlowDownException$:()=>Die,UnauthorizedClientException:()=>xw,UnauthorizedClientException$:()=>Nie,UnsupportedGrantTypeException:()=>Ew,UnsupportedGrantTypeException$:()=>zie,__Client:()=>Rn,errorTypeRegistries:()=>bq});var Rq=_(()=>{xq();Qie();ese();ve();oP();tse();_q();rse();nP()});var sse=U(Iw=>{var{setTokenFeature:h4e}=(Nt(),re(os)),{getBearerTokenEnvKey:g4e}=(Pn(),re(sA)),{TokenProviderError:ls,getSSOTokenFilepath:y4e,parseKnownFiles:v4e,getProfileName:w4e,loadSsoSessionData:_4e,getSSOTokenFromFile:b4e,memoize:S4e,chain:x4e}=(Dt(),re(zo)),{promises:E4e}=io("node:fs"),$4e=({logger:t,signingName:e}={})=>async()=>{if(t?.debug?.("@aws-sdk/token-providers - fromEnvSigningName"),!e)throw new ls("Please pass 'signingName' to compute environment variable key",{logger:t});let r=g4e(e);if(!(r in process.env))throw new ls(`Token not present in '${r}' environment variable`,{logger:t});let o={token:process.env[r]};return h4e(o,"BEARER_SERVICE_ENV_VARS","3"),o},R4e=300*1e3,Iq="To refresh this SSO session run 'aws sso login' with the corresponding profile.",I4e=async(t,e={},r)=>{let{SSOOIDCClient:o}=(Rq(),re($q)),n=s=>e.clientConfig?.[s]??e.parentClientConfig?.[s]??r?.[s];return new o(Object.assign({},e.clientConfig??{},{region:t??e.clientConfig?.region,logger:n("logger"),userAgentAppId:n("userAgentAppId")}))},A4e=async(t,e,r={},o)=>{let{CreateTokenCommand:n}=(Rq(),re($q));return(await I4e(e,r,o)).send(new n({clientId:t.clientId,clientSecret:t.clientSecret,refreshToken:t.refreshToken,grantType:"refresh_token"}))},nse=t=>{if(t.expiration&&t.expiration.getTime()<Date.now())throw new ls(`Token is expired. ${Iq}`,!1)},Md=(t,e,r=!1)=>{if(typeof e>"u")throw new ls(`Value not present for '${t}' in SSO Token${r?". Cannot refresh":""}. ${Iq}`,!1)},{writeFile:P4e}=E4e,k4e=(t,e)=>{let r=y4e(t),o=JSON.stringify(e,null,2);return P4e(r,o)},ose=new Map,ise=(t={})=>async({callerClientConfig:e}={})=>{t.logger?.debug("@aws-sdk/token-providers - fromSso");let r=await v4e(t),o=w4e({profile:t.profile??e?.profile}),n=r[o];if(n){if(!n.sso_session)throw new ls(`Profile '${o}' is missing required property 'sso_session'.`)}else throw new ls(`Profile '${o}' could not be found in shared credentials file.`,!1);let i=n.sso_session,a=(await _4e(t))[i];if(!a)throw new ls(`Sso session '${i}' could not be found in shared credentials file.`,!1);for(let h of["sso_start_url","sso_region"])if(!a[h])throw new ls(`Sso session '${i}' is missing required property '${h}'.`,!1);a.sso_start_url;let c=a.sso_region,u;try{u=await b4e(i)}catch{throw new ls(`The SSO session token associated with profile=${o} was not found or is invalid. ${Iq}`,!1)}Md("accessToken",u.accessToken),Md("expiresAt",u.expiresAt);let{accessToken:l,expiresAt:d}=u,p={token:l,expiration:new Date(d)};if(p.expiration.getTime()-Date.now()>R4e)return p;let f=ose.get(i)??0;if(Date.now()-f<30*1e3)return nse(p),p;Md("clientId",u.clientId,!0),Md("clientSecret",u.clientSecret,!0),Md("refreshToken",u.refreshToken,!0);try{ose.set(i,Date.now());let h=await A4e(u,c,t,e);Md("accessToken",h.accessToken),Md("expiresIn",h.expiresIn);let y=new Date(Date.now()+h.expiresIn*1e3);try{await k4e(i,{...u,accessToken:h.accessToken,expiresAt:y.toISOString(),refreshToken:h.refreshToken})}catch{}return{token:h.accessToken,expiration:y}}catch{return nse(p),p}},T4e=({token:t,logger:e})=>async()=>{if(e?.debug("@aws-sdk/token-providers - fromStatic"),!t||!t.token)throw new ls("Please pass a valid token to fromStatic",!1);return t},C4e=(t={})=>S4e(x4e(ise(t),async()=>{throw new ls("Could not load token from any providers",!1)}),e=>e.expiration!==void 0&&e.expiration.getTime()-Date.now()<3e5,e=>e.expiration!==void 0);Iw.fromEnvSigningName=$4e;Iw.fromSso=ise;Iw.fromStatic=T4e;Iw.nodeProvider=C4e});function O4e(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"awsssoportal",region:t.region},propertiesExtractor:(e,r)=>({signingProperties:{config:e,context:r}})}}function D4e(t){return{schemeId:"smithy.api#noAuth"}}var ase,cse,use,Aq=_(()=>{Pn();ve();ase=async(t,e,r)=>({operation:Bt(e).operation,region:await jt(t.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});cse=t=>{let e=[];return t.operation==="GetRoleCredentials"?e.push(D4e(t)):e.push(O4e(t)),e},use=t=>{let e=wa(t);return Object.assign(e,{authSchemePreference:jt(t.authSchemePreference??[])})}});var lse,dse,Pq=_(()=>{lse=t=>Object.assign(t,{useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,defaultSigningName:"awsssoportal"}),dse={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}});var Aw,Ud,aP,pse,gse,cP,kq,fse,Tq,Qm,mse,hse,N4e,yo,z4e,yse,vse=_(()=>{Jt();Aw="ref",Ud=-1,aP=!0,pse="isSet",gse="PartitionResult",cP="booleanEquals",kq="getAttr",fse={[Aw]:"Endpoint"},Tq={[Aw]:gse},Qm={},mse=[{[Aw]:"Region"}],hse={conditions:[[pse,[fse]],[pse,mse],["aws.partition",mse,gse],[cP,[{[Aw]:"UseFIPS"},aP]],[cP,[{[Aw]:"UseDualStack"},aP]],[cP,[{fn:kq,argv:[Tq,"supportsDualStack"]},aP]],[cP,[{fn:kq,argv:[Tq,"supportsFIPS"]},aP]],["stringEquals",[{fn:kq,argv:[Tq,"name"]},"aws-us-gov"]]],results:[[Ud],[Ud,"Invalid Configuration: FIPS and custom endpoint are not supported"],[Ud,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[fse,Qm],["https://portal.sso-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",Qm],[Ud,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://portal.sso.{Region}.amazonaws.com",Qm],["https://portal.sso-fips.{Region}.{PartitionResult#dnsSuffix}",Qm],[Ud,"FIPS is enabled but this partition does not support FIPS"],["https://portal.sso.{Region}.{PartitionResult#dualStackDnsSuffix}",Qm],[Ud,"DualStack is enabled but this partition does not support DualStack"],["https://portal.sso.{Region}.{PartitionResult#dnsSuffix}",Qm],[Ud,"Invalid Configuration: Missing Region"]]},N4e=2,yo=1e8,z4e=new Int32Array([-1,1,-1,0,13,3,1,4,yo+12,2,5,yo+12,3,8,6,4,7,yo+11,5,yo+9,yo+10,4,11,9,6,10,yo+8,7,yo+6,yo+7,5,12,yo+5,6,yo+4,yo+5,3,yo+1,14,4,yo+2,yo+3]),yse=ci.from(z4e,N4e,hse.conditions,hse.results)});var M4e,wse,_se=_(()=>{Nt();Jt();vse();M4e=new ui({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),wse=(t,e={})=>M4e.get(t,()=>ra(yse,{endpointParams:t,logger:e.logger}));ho.aws=ns});var ds,uP=_(()=>{ve();ds=class t extends si{constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}}});var Pw,kw,Tw,Cw,Cq=_(()=>{uP();Pw=class t extends ds{name="InvalidRequestException";$fault="client";constructor(e){super({name:"InvalidRequestException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype)}},kw=class t extends ds{name="ResourceNotFoundException";$fault="client";constructor(e){super({name:"ResourceNotFoundException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype)}},Tw=class t extends ds{name="TooManyRequestsException";$fault="client";constructor(e){super({name:"TooManyRequestsException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype)}},Cw=class t extends ds{name="UnauthorizedException";$fault="client";constructor(e){super({name:"UnauthorizedException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype)}}});var U4e,L4e,j4e,F4e,q4e,V4e,G4e,H4e,K4e,B4e,Z4e,W4e,J4e,X4e,Y4e,lP,dP,Q4e,eFe,pP,tFe,bse,fP,rFe,nFe,oFe,Sse,iFe,sFe,aFe,yi,xse,Ese,Ow,$se,Rse,Ise,Ase,Oq,cFe,uFe,lFe,Pse,kse,Tse,Dq,mP=_(()=>{rt();Cq();uP();U4e="AccessTokenType",L4e="GetRoleCredentials",j4e="GetRoleCredentialsRequest",F4e="GetRoleCredentialsResponse",q4e="InvalidRequestException",V4e="RoleCredentials",G4e="ResourceNotFoundException",H4e="SecretAccessKeyType",K4e="SessionTokenType",B4e="TooManyRequestsException",Z4e="UnauthorizedException",W4e="accountId",J4e="accessKeyId",X4e="accessToken",Y4e="account_id",lP="client",dP="error",Q4e="expiration",eFe="http",pP="httpError",tFe="httpHeader",bse="httpQuery",fP="message",rFe="roleCredentials",nFe="roleName",oFe="role_name",Sse="smithy.ts.sdk.synthetic.com.amazonaws.sso",iFe="secretAccessKey",sFe="sessionToken",aFe="x-amz-sso_bearer_token",yi="com.amazonaws.sso",xse=new Zt(Sse),Ese=[-3,Sse,"SSOServiceException",0,[],[]];xse.registerError(Ese,ds);Ow=new Zt(yi),$se=[-3,yi,q4e,{[dP]:lP,[pP]:400},[fP],[0]];Ow.registerError($se,Pw);Rse=[-3,yi,G4e,{[dP]:lP,[pP]:404},[fP],[0]];Ow.registerError(Rse,kw);Ise=[-3,yi,B4e,{[dP]:lP,[pP]:429},[fP],[0]];Ow.registerError(Ise,Tw);Ase=[-3,yi,Z4e,{[dP]:lP,[pP]:401},[fP],[0]];Ow.registerError(Ase,Cw);Oq=[xse,Ow],cFe=[0,yi,U4e,8,0],uFe=[0,yi,H4e,8,0],lFe=[0,yi,K4e,8,0],Pse=[3,yi,j4e,0,[nFe,W4e,X4e],[[0,{[bse]:oFe}],[0,{[bse]:Y4e}],[()=>cFe,{[tFe]:aFe}]],3],kse=[3,yi,F4e,0,[rFe],[[()=>Tse,0]]],Tse=[3,yi,V4e,0,[J4e,iFe,sFe,Q4e],[0,[()=>uFe,0],[()=>lFe,0],1]],Dq=[9,yi,L4e,{[eFe]:["GET","/federation/credentials",200]},()=>Pse,()=>kse]});var Cse,Ose=_(()=>{Pn();Nd();Yn();gc();ve();ge();xe();Aq();_se();mP();Cse=t=>({apiVersion:"2019-06-10",base64Decoder:t?.base64Decoder??fr,base64Encoder:t?.base64Encoder??Wt,disableHostPrefix:t?.disableHostPrefix??!1,endpointProvider:t?.endpointProvider??wse,extensions:t?.extensions??[],httpAuthSchemeProvider:t?.httpAuthSchemeProvider??cse,httpAuthSchemes:t?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4"),signer:new Gr},{schemeId:"smithy.api#noAuth",identityProvider:e=>e.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new An}],logger:t?.logger??new mo,protocol:t?.protocol??Sa,protocolSettings:t?.protocolSettings??{defaultNamespace:"com.amazonaws.sso",errorTypeRegistries:Oq,version:"2019-06-10",serviceTarget:"SWBPortalService"},serviceId:t?.serviceId??"SSO",sha256:t?.sha256??Xi,urlParser:t?.urlParser??nn,utf8Decoder:t?.utf8Decoder??Tr,utf8Encoder:t?.utf8Encoder??ur})});var hP,Dse,Nse=_(()=>{iw();Nt();Pn();ve();Dt();jo();xe();hP=Vt(Gu());Ose();Dse=t=>{Gs(process.version);let e=ea(t),r=()=>e().then(Vs),o=Cse(t);Ls(process.version);let n={profile:t?.profile,logger:o.logger};return{...o,...t,runtime:"node",defaultsMode:e,authSchemePreference:t?.authSchemePreference??Ie(is,n),bodyLengthChecker:t?.bodyLengthChecker??Zs,defaultUserAgentProvider:t?.defaultUserAgentProvider??rs({serviceId:o.serviceId,clientVersion:Hu.version}),maxAttempts:t?.maxAttempts??Ie(ca,t),region:t?.region??Ie(on,{...Xn,...n}),requestHandler:hP.NodeHttpHandler.create(t?.requestHandler??r),retryMode:t?.retryMode??Ie({...la,default:async()=>(await r()).retryMode||li},t),streamCollector:t?.streamCollector??hP.streamCollector,useDualstackEndpoint:t?.useDualstackEndpoint??Ie(Ys,n),useFipsEndpoint:t?.useFipsEndpoint??Ie(Qs,n),userAgentAppId:t?.userAgentAppId??Ie(ga,n)}}});var zse,Mse,Use=_(()=>{zse=t=>{let e=t.httpAuthSchemes,r=t.httpAuthSchemeProvider,o=t.credentials;return{setHttpAuthScheme(n){let i=e.findIndex(s=>s.schemeId===n.schemeId);i===-1?e.push(n):e.splice(i,1,n)},httpAuthSchemes(){return e},setHttpAuthSchemeProvider(n){r=n},httpAuthSchemeProvider(){return r},setCredentials(n){o=n},credentials(){return o}}},Mse=t=>({httpAuthSchemes:t.httpAuthSchemes(),httpAuthSchemeProvider:t.httpAuthSchemeProvider(),credentials:t.credentials()})});var Lse,jse=_(()=>{Nt();ve();ge();Use();Lse=(t,e)=>{let r=Object.assign(ya(t),Bi(t),oa(t),zse(t));return e.forEach(o=>o.configure(r)),Object.assign(t,va(r),Hs(r),ia(r),Mse(r))}});var Dw,Nq=_(()=>{Nt();Yn();ve();Dt();Jt();ge();jo();rt();Aq();Pq();Nse();jse();Dw=class extends Rn{config;constructor(...[e]){let r=Dse(e||{});super(r),this.initConfig=r;let o=lse(r),n=ma(o),i=ua(n),s=No(i),a=s,c=pc(a),u=use(c),l=Lse(u,e?.extensions||[]);this.config=l,this.middlewareStack.use(Fs(this.config)),this.middlewareStack.use(ha(this.config)),this.middlewareStack.use(yc(this.config)),this.middlewareStack.use(sa(this.config)),this.middlewareStack.use(da(this.config)),this.middlewareStack.use(pa(this.config)),this.middlewareStack.use(fa(this.config)),this.middlewareStack.use(es(this.config,{httpAuthSchemeParametersProvider:ase,identityProviderConfigProvider:async d=>new Fo({"aws.auth#sigv4":d.credentials})})),this.middlewareStack.use(ts(this.config))}destroy(){super.destroy()}}});var Fse,qse,Vse,Gse=_(()=>{ve();Jt();Pq();Fse=Ks(dse,"SWBPortalService","SSOClient",fc),qse={},Vse=(t,e,r,o)=>[]});var Nw,zq=_(()=>{Gse();mP();Nw=class extends Fse(qse,Vse,"GetRoleCredentials",Dq){}});var dFe,gP,Hse=_(()=>{ve();zq();Nq();dFe={GetRoleCredentialsCommand:Nw},gP=class extends Dw{};qs(dFe,gP)});var Kse=_(()=>{zq()});var Bse=_(()=>{});var Zse={};Ht(Zse,{$Command:()=>Wn,GetRoleCredentials$:()=>Dq,GetRoleCredentialsCommand:()=>Nw,GetRoleCredentialsRequest$:()=>Pse,GetRoleCredentialsResponse$:()=>kse,InvalidRequestException:()=>Pw,InvalidRequestException$:()=>$se,ResourceNotFoundException:()=>kw,ResourceNotFoundException$:()=>Rse,RoleCredentials$:()=>Tse,SSO:()=>gP,SSOClient:()=>Dw,SSOServiceException:()=>ds,SSOServiceException$:()=>Ese,TooManyRequestsException:()=>Tw,TooManyRequestsException$:()=>Ise,UnauthorizedException:()=>Cw,UnauthorizedException$:()=>Ase,__Client:()=>Rn,errorTypeRegistries:()=>Oq});var Wse=_(()=>{Nq();Hse();Kse();ve();mP();Cq();Bse();uP()});var Jse=U(Mq=>{var{GetRoleCredentialsCommand:pFe,SSOClient:fFe}=(Wse(),re(Zse));Mq.GetRoleCredentialsCommand=pFe;Mq.SSOClient=fFe});var Uq=U(yP=>{var{CredentialsProviderError:ps,getSSOTokenFromFile:mFe,getProfileName:hFe,parseKnownFiles:gFe,loadSsoSessionData:yFe}=(Dt(),re(zo)),{setCredentialFeature:Xse}=(Nt(),re(os)),{fromSso:vFe}=sse(),Qse=t=>t&&(typeof t.sso_start_url=="string"||typeof t.sso_account_id=="string"||typeof t.sso_session=="string"||typeof t.sso_region=="string"||typeof t.sso_role_name=="string"),zw=!1,Yse=async({ssoStartUrl:t,ssoSession:e,ssoAccountId:r,ssoRegion:o,ssoRoleName:n,ssoClient:i,clientConfig:s,parentClientConfig:a,callerClientConfig:c,profile:u,filepath:l,configFilepath:d,ignoreCache:p,logger:f})=>{let h,y="To refresh this SSO session run aws sso login with the corresponding profile.";if(e)try{let me=await vFe({profile:u,filepath:l,configFilepath:d,ignoreCache:p,clientConfig:s,parentClientConfig:a,logger:f})({callerClientConfig:c});h={accessToken:me.token,expiresAt:new Date(me.expiration).toISOString()}}catch(me){throw new ps(me.message,{tryNextLink:zw,logger:f})}else try{h=await mFe(t)}catch{throw new ps(`The SSO session associated with this profile is invalid. ${y}`,{tryNextLink:zw,logger:f})}if(new Date(h.expiresAt).getTime()-Date.now()<=0)throw new ps(`The SSO session associated with this profile has expired. ${y}`,{tryNextLink:zw,logger:f});let{accessToken:w}=h,{SSOClient:b,GetRoleCredentialsCommand:S}=Jse(),x=i||new b(Object.assign({},s??{},{logger:s?.logger??c?.logger??a?.logger,region:s?.region??o,userAgentAppId:s?.userAgentAppId??c?.userAgentAppId??a?.userAgentAppId})),R;try{R=await x.send(new S({accountId:r,roleName:n,accessToken:w}))}catch(me){throw new ps(me,{tryNextLink:zw,logger:f})}let{roleCredentials:{accessKeyId:T,secretAccessKey:M,sessionToken:Z,expiration:te,credentialScope:Ae,accountId:Te}={}}=R;if(!T||!M||!Z||!te)throw new ps("SSO returns an invalid temporary credential.",{tryNextLink:zw,logger:f});let bt={accessKeyId:T,secretAccessKey:M,sessionToken:Z,expiration:new Date(te),...Ae&&{credentialScope:Ae},...Te&&{accountId:Te}};return e?Xse(bt,"CREDENTIALS_SSO","s"):Xse(bt,"CREDENTIALS_SSO_LEGACY","u"),bt},eae=(t,e)=>{let{sso_start_url:r,sso_account_id:o,sso_region:n,sso_role_name:i}=t;if(!r||!o||!n||!i)throw new ps(`Profile is configured with invalid SSO credentials. Required parameters "sso_account_id", "sso_region", "sso_role_name", "sso_start_url". Got ${Object.keys(t).join(", ")}
52
+ Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`,{tryNextLink:!1,logger:e});return t},wFe=(t={})=>async({callerClientConfig:e}={})=>{t.logger?.debug("@aws-sdk/credential-provider-sso - fromSSO");let{ssoStartUrl:r,ssoAccountId:o,ssoRegion:n,ssoRoleName:i,ssoSession:s}=t,{ssoClient:a}=t,c=hFe({profile:t.profile??e?.profile});if(!r&&!o&&!n&&!i&&!s){let l=(await gFe(t))[c];if(!l)throw new ps(`Profile ${c} was not found.`,{logger:t.logger});if(!Qse(l))throw new ps(`Profile ${c} is not configured with SSO credentials.`,{logger:t.logger});if(l?.sso_session){let b=(await yFe(t))[l.sso_session],S=` configurations in profile ${c} and sso-session ${l.sso_session}`;if(n&&n!==b.sso_region)throw new ps("Conflicting SSO region"+S,{tryNextLink:!1,logger:t.logger});if(r&&r!==b.sso_start_url)throw new ps("Conflicting SSO start_url"+S,{tryNextLink:!1,logger:t.logger});l.sso_region=b.sso_region,l.sso_start_url=b.sso_start_url}let{sso_start_url:d,sso_account_id:p,sso_region:f,sso_role_name:h,sso_session:y}=eae(l,t.logger);return Yse({ssoStartUrl:d,ssoSession:y,ssoAccountId:p,ssoRegion:f,ssoRoleName:h,ssoClient:a,clientConfig:t.clientConfig,parentClientConfig:t.parentClientConfig,callerClientConfig:t.callerClientConfig,profile:c,filepath:t.filepath,configFilepath:t.configFilepath,ignoreCache:t.ignoreCache,logger:t.logger})}else{if(!r||!o||!n||!i)throw new ps('Incomplete configuration. The fromSSO() argument hash must include "ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"',{tryNextLink:!1,logger:t.logger});return Yse({ssoStartUrl:r,ssoSession:s,ssoAccountId:o,ssoRegion:n,ssoRoleName:i,ssoClient:a,clientConfig:t.clientConfig,parentClientConfig:t.parentClientConfig,callerClientConfig:t.callerClientConfig,profile:c,filepath:t.filepath,configFilepath:t.configFilepath,ignoreCache:t.ignoreCache,logger:t.logger})}};yP.fromSSO=wFe;yP.isSsoProfile=Qse;yP.validateSsoProfile=eae});var th,Ld,Mw,tae,uae,Uw,un,Lq,rae,nae,oae,iae,sae,ln,jq,eh,aae,cae,_Fe,Et,bFe,lae,dae=_(()=>{Jt();th="ref",Ld=-1,Mw=!0,tae="isSet",uae="PartitionResult",Uw="booleanEquals",un="stringEquals",Lq="getAttr",rae="us-east-1",nae="sigv4",oae="sts",iae="https://sts.{Region}.{PartitionResult#dnsSuffix}",sae={[th]:"Endpoint"},ln={[th]:"Region"},jq={[th]:uae},eh={},aae=[ln],cae={conditions:[[tae,[sae]],[tae,aae],["aws.partition",aae,uae],[Uw,[{[th]:"UseFIPS"},Mw]],[Uw,[{[th]:"UseDualStack"},Mw]],[un,[ln,"aws-global"]],[Uw,[{[th]:"UseGlobalEndpoint"},Mw]],[un,[ln,"eu-central-1"]],[Uw,[{fn:Lq,argv:[jq,"supportsDualStack"]},Mw]],[Uw,[{fn:Lq,argv:[jq,"supportsFIPS"]},Mw]],[un,[ln,"ap-south-1"]],[un,[ln,"eu-north-1"]],[un,[ln,"eu-west-1"]],[un,[ln,"eu-west-2"]],[un,[ln,"eu-west-3"]],[un,[ln,"sa-east-1"]],[un,[ln,rae]],[un,[ln,"us-east-2"]],[un,[ln,"us-west-2"]],[un,[ln,"us-west-1"]],[un,[ln,"ca-central-1"]],[un,[ln,"ap-southeast-1"]],[un,[ln,"ap-northeast-1"]],[un,[ln,"ap-southeast-2"]],[un,[{fn:Lq,argv:[jq,"name"]},"aws-us-gov"]]],results:[[Ld],["https://sts.amazonaws.com",{authSchemes:[{name:nae,signingName:oae,signingRegion:rae}]}],[iae,{authSchemes:[{name:nae,signingName:oae,signingRegion:"{Region}"}]}],[Ld,"Invalid Configuration: FIPS and custom endpoint are not supported"],[Ld,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[sae,eh],["https://sts-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",eh],[Ld,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://sts.{Region}.amazonaws.com",eh],["https://sts-fips.{Region}.{PartitionResult#dnsSuffix}",eh],[Ld,"FIPS is enabled but this partition does not support FIPS"],["https://sts.{Region}.{PartitionResult#dualStackDnsSuffix}",eh],[Ld,"DualStack is enabled but this partition does not support DualStack"],[iae,eh],[Ld,"Invalid Configuration: Missing Region"]]},_Fe=2,Et=1e8,bFe=new Int32Array([-1,1,-1,0,30,3,1,4,Et+14,2,5,Et+14,3,25,6,4,24,7,5,Et+1,8,6,9,Et+13,7,Et+1,10,10,Et+1,11,11,Et+1,12,12,Et+1,13,13,Et+1,14,14,Et+1,15,15,Et+1,16,16,Et+1,17,17,Et+1,18,18,Et+1,19,19,Et+1,20,20,Et+1,21,21,Et+1,22,22,Et+1,23,23,Et+1,Et+2,8,Et+11,Et+12,4,28,26,9,27,Et+10,24,Et+8,Et+9,8,29,Et+7,9,Et+6,Et+7,3,Et+3,31,4,Et+4,Et+5]),lae=ci.from(bFe,_Fe,cae.conditions,cae.results)});var SFe,vP,Fq=_(()=>{Nt();Jt();dae();SFe=new ui({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS","UseGlobalEndpoint"]}),vP=(t,e={})=>SFe.get(t,()=>ra(lae,{endpointParams:t,logger:e.logger}));ho.aws=ns});function mae(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sts",region:t.region},propertiesExtractor:(e,r)=>({signingProperties:{config:e,context:r}})}}function qq(t){return{schemeId:"aws.auth#sigv4a",signingProperties:{name:"sts",region:t.region},propertiesExtractor:(e,r)=>({signingProperties:{config:e,context:r}})}}function hae(t){return{schemeId:"smithy.api#noAuth"}}var pae,xFe,EFe,fae,$Fe,RFe,gae,yae,Vq=_(()=>{Pn();pae=Vt(uA());ve();Jt();Fq();xFe=t=>async(e,r,o)=>{if(!o)throw new Error("Could not find `input` for `defaultEndpointRuleSetHttpAuthSchemeParametersProvider`");let n=await t(e,r,o),i=Bt(r)?.commandInstance?.constructor?.getEndpointParameterInstructions;if(!i)throw new Error(`getEndpointParameterInstructions() is not defined on '${r.commandName}'`);let s=await Iv(o,{getEndpointParameterInstructions:i},e);return Object.assign(n,s)},EFe=async(t,e,r)=>({operation:Bt(e).operation,region:await jt(t.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()}),fae=xFe(EFe);$Fe=(t,e,r)=>n=>{let s=t(n).properties?.authSchemes;if(!s)return e(n);let a=[];for(let c of s){let{name:u,properties:l={},...d}=c,p=u.toLowerCase();u!==p&&console.warn(`HttpAuthScheme has been normalized with lowercasing: '${u}' to '${p}'`);let f;if(p==="sigv4a"){f="aws.auth#sigv4a";let w=s.find(b=>{let S=b.name.toLowerCase();return S!=="sigv4a"&&S.startsWith("sigv4")});if(pae.SignatureV4MultiRegion.sigv4aDependency()==="none"&&w)continue}else if(p.startsWith("sigv4"))f="aws.auth#sigv4";else throw new Error(`Unknown HttpAuthScheme found in '@smithy.rules#endpointRuleSet': '${p}'`);let h=r[f];if(!h)throw new Error(`Could not find HttpAuthOption create function for '${f}'`);let y=h(n);y.schemeId=f,y.signingProperties={...y.signingProperties||{},...d,...l},a.push(y)}return a},RFe=t=>{let e=[];return t.operation==="AssumeRoleWithWebIdentity"?(e.push(hae(t)),e.push(qq(t))):(e.push(mae(t)),e.push(qq(t))),e},gae=$Fe(vP,RFe,{"aws.auth#sigv4":mae,"aws.auth#sigv4a":qq,"smithy.api#noAuth":hae}),yae=t=>{let e=wa(t),r=Jv(e);return Object.assign(r,{authSchemePreference:jt(t.authSchemePreference??[])})}});var vae,wae,Gq=_(()=>{vae=t=>Object.assign(t,{useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,useGlobalEndpoint:t.useGlobalEndpoint??!1,defaultSigningName:"sts"}),wae={UseGlobalEndpoint:{type:"builtInParams",name:"useGlobalEndpoint"},UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}});var vo,wP=_(()=>{ve();vo=class t extends si{constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}}});var Lw,jw,Fw,qw,Vw,Gw,Hw,Hq=_(()=>{wP();Lw=class t extends vo{name="ExpiredTokenException";$fault="client";constructor(e){super({name:"ExpiredTokenException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype)}},jw=class t extends vo{name="MalformedPolicyDocumentException";$fault="client";constructor(e){super({name:"MalformedPolicyDocumentException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype)}},Fw=class t extends vo{name="PackedPolicyTooLargeException";$fault="client";constructor(e){super({name:"PackedPolicyTooLargeException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype)}},qw=class t extends vo{name="RegionDisabledException";$fault="client";constructor(e){super({name:"RegionDisabledException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype)}},Vw=class t extends vo{name="IDPRejectedClaimException";$fault="client";constructor(e){super({name:"IDPRejectedClaimException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype)}},Gw=class t extends vo{name="InvalidIdentityTokenException";$fault="client";constructor(e){super({name:"InvalidIdentityTokenException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype)}},Hw=class t extends vo{name="IDPCommunicationErrorException";$fault="client";$retryable={};constructor(e){super({name:"IDPCommunicationErrorException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype)}}});var IFe,AFe,PFe,kFe,TFe,CFe,Kq,OFe,DFe,NFe,zFe,Bq,MFe,_ae,UFe,LFe,jFe,FFe,qFe,VFe,GFe,HFe,bae,Sae,xae,KFe,BFe,ZFe,WFe,JFe,XFe,Eae,YFe,QFe,$ae,e2e,Rae,t2e,r2e,Zq,n2e,o2e,Iae,Aae,i2e,s2e,a2e,c2e,u2e,l2e,d2e,p2e,jd,Fd,f2e,qd,Vd,Gd,m2e,Pae,h2e,sr,kae,Tae,Yu,Cae,Oae,Dae,Nae,zae,Mae,Uae,Wq,g2e,y2e,Jq,Lae,jae,Fae,qae,Xq,Vae,Gae,Hae,Kae,v2e,w2e,Yq,Qq,Kw=_(()=>{rt();Hq();wP();IFe="Arn",AFe="AccessKeyId",PFe="AssumeRole",kFe="AssumedRoleId",TFe="AssumeRoleRequest",CFe="AssumeRoleResponse",Kq="AssumedRoleUser",OFe="AssumeRoleWithWebIdentity",DFe="AssumeRoleWithWebIdentityRequest",NFe="AssumeRoleWithWebIdentityResponse",zFe="Audience",Bq="Credentials",MFe="ContextAssertion",_ae="DurationSeconds",UFe="Expiration",LFe="ExternalId",jFe="ExpiredTokenException",FFe="IDPCommunicationErrorException",qFe="IDPRejectedClaimException",VFe="InvalidIdentityTokenException",GFe="Key",HFe="MalformedPolicyDocumentException",bae="MinimumSessionTokenSize",Sae="Policy",xae="PolicyArns",KFe="ProviderArn",BFe="ProvidedContexts",ZFe="ProvidedContextsListType",WFe="ProvidedContext",JFe="PolicyDescriptorType",XFe="ProviderId",Eae="PackedPolicySize",YFe="PackedPolicyTooLargeException",QFe="Provider",$ae="RoleArn",e2e="RegionDisabledException",Rae="RoleSessionName",t2e="SecretAccessKey",r2e="SubjectFromWebIdentityToken",Zq="SourceIdentity",n2e="SerialNumber",o2e="SessionToken",Iae="SessionTokenSize",Aae="SessionTokenUtilization",i2e="Tags",s2e="TokenCode",a2e="TransitiveTagKeys",c2e="Tag",u2e="Value",l2e="WebIdentityToken",d2e="arn",p2e="accessKeySecretType",jd="awsQueryError",Fd="client",f2e="clientTokenType",qd="error",Vd="httpError",Gd="message",m2e="policyDescriptorListType",Pae="smithy.ts.sdk.synthetic.com.amazonaws.sts",h2e="tagListType",sr="com.amazonaws.sts",kae=new Zt(Pae),Tae=[-3,Pae,"STSServiceException",0,[],[]];kae.registerError(Tae,vo);Yu=new Zt(sr),Cae=[-3,sr,jFe,{[jd]:["ExpiredTokenException",400],[qd]:Fd,[Vd]:400},[Gd],[0]];Yu.registerError(Cae,Lw);Oae=[-3,sr,FFe,{[jd]:["IDPCommunicationError",400],[qd]:Fd,[Vd]:400},[Gd],[0]];Yu.registerError(Oae,Hw);Dae=[-3,sr,qFe,{[jd]:["IDPRejectedClaim",403],[qd]:Fd,[Vd]:403},[Gd],[0]];Yu.registerError(Dae,Vw);Nae=[-3,sr,VFe,{[jd]:["InvalidIdentityToken",400],[qd]:Fd,[Vd]:400},[Gd],[0]];Yu.registerError(Nae,Gw);zae=[-3,sr,HFe,{[jd]:["MalformedPolicyDocument",400],[qd]:Fd,[Vd]:400},[Gd],[0]];Yu.registerError(zae,jw);Mae=[-3,sr,YFe,{[jd]:["PackedPolicyTooLarge",400],[qd]:Fd,[Vd]:400},[Gd],[0]];Yu.registerError(Mae,Fw);Uae=[-3,sr,e2e,{[jd]:["RegionDisabledException",403],[qd]:Fd,[Vd]:403},[Gd],[0]];Yu.registerError(Uae,qw);Wq=[kae,Yu],g2e=[0,sr,p2e,8,0],y2e=[0,sr,f2e,8,0],Jq=[3,sr,Kq,0,[kFe,IFe],[0,0],2],Lae=[3,sr,TFe,0,[$ae,Rae,xae,Sae,_ae,i2e,a2e,LFe,n2e,s2e,Zq,BFe,bae],[0,0,()=>Kae,0,1,()=>w2e,64,0,0,0,0,()=>v2e,1],2],jae=[3,sr,CFe,0,[Bq,Kq,Eae,Zq,Aae,Iae],[[()=>Xq,0],()=>Jq,1,0,1,1]],Fae=[3,sr,DFe,0,[$ae,Rae,l2e,XFe,xae,Sae,_ae,bae],[0,0,[()=>y2e,0],0,()=>Kae,0,1,1],3],qae=[3,sr,NFe,0,[Bq,r2e,Kq,Eae,QFe,zFe,Zq,Aae,Iae],[[()=>Xq,0],0,()=>Jq,1,0,0,0,1,1]],Xq=[3,sr,Bq,0,[AFe,t2e,o2e,UFe],[0,[()=>g2e,0],0,4],4],Vae=[3,sr,JFe,0,[d2e],[0]],Gae=[3,sr,WFe,0,[KFe,MFe],[0,0]],Hae=[3,sr,c2e,0,[GFe,u2e],[0,0],2],Kae=[1,sr,m2e,0,()=>Vae],v2e=[1,sr,ZFe,0,()=>Gae],w2e=[1,sr,h2e,0,()=>Hae],Yq=[9,sr,PFe,0,()=>Lae,()=>jae],Qq=[9,sr,OFe,0,()=>Fae,()=>qae]});var Bae,Zae,Wae=_(()=>{Pn();Nd();Bae=Vt(uA());Yn();gc();ve();ge();xe();Vq();Fq();Kw();Zae=t=>({apiVersion:"2011-06-15",base64Decoder:t?.base64Decoder??fr,base64Encoder:t?.base64Encoder??Wt,disableHostPrefix:t?.disableHostPrefix??!1,endpointProvider:t?.endpointProvider??vP,extensions:t?.extensions??[],httpAuthSchemeProvider:t?.httpAuthSchemeProvider??gae,httpAuthSchemes:t?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4"),signer:new Gr},{schemeId:"aws.auth#sigv4a",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4a"),signer:new vc},{schemeId:"smithy.api#noAuth",identityProvider:e=>e.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new An}],logger:t?.logger??new mo,protocol:t?.protocol??Xu,protocolSettings:t?.protocolSettings??{defaultNamespace:"com.amazonaws.sts",errorTypeRegistries:Wq,xmlNamespace:"https://sts.amazonaws.com/doc/2011-06-15/",version:"2011-06-15",serviceTarget:"AWSSecurityTokenServiceV20110615"},serviceId:t?.serviceId??"STS",sha256:t?.sha256??Xi,signerConstructor:t?.signerConstructor??Bae.SignatureV4MultiRegion,urlParser:t?.urlParser??nn,utf8Decoder:t?.utf8Decoder??Tr,utf8Encoder:t?.utf8Encoder??ur})});var _P,Jae,Xae=_(()=>{iw();Nt();Pn();Yn();ve();Dt();jo();xe();_P=Vt(Gu());Wae();Jae=t=>{Gs(process.version);let e=ea(t),r=()=>e().then(Vs),o=Zae(t);Ls(process.version);let n={profile:t?.profile,logger:o.logger};return{...o,...t,runtime:"node",defaultsMode:e,authSchemePreference:t?.authSchemePreference??Ie(is,n),bodyLengthChecker:t?.bodyLengthChecker??Zs,defaultUserAgentProvider:t?.defaultUserAgentProvider??rs({serviceId:o.serviceId,clientVersion:Hu.version}),httpAuthSchemes:t?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:i=>i.getIdentityProvider("aws.auth#sigv4")||(async s=>await t.credentialDefaultProvider(s?.__config||{})()),signer:new Gr},{schemeId:"aws.auth#sigv4a",identityProvider:i=>i.getIdentityProvider("aws.auth#sigv4a"),signer:new vc},{schemeId:"smithy.api#noAuth",identityProvider:i=>i.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new An}],maxAttempts:t?.maxAttempts??Ie(ca,t),region:t?.region??Ie(on,{...Xn,...n}),requestHandler:_P.NodeHttpHandler.create(t?.requestHandler??r),retryMode:t?.retryMode??Ie({...la,default:async()=>(await r()).retryMode||li},t),sigv4aSigningRegionSet:t?.sigv4aSigningRegionSet??Ie(Xv,n),streamCollector:t?.streamCollector??_P.streamCollector,useDualstackEndpoint:t?.useDualstackEndpoint??Ie(Ys,n),useFipsEndpoint:t?.useFipsEndpoint??Ie(Qs,n),userAgentAppId:t?.userAgentAppId??Ie(ga,n)}}});var Yae,Qae,ece=_(()=>{Yae=t=>{let e=t.httpAuthSchemes,r=t.httpAuthSchemeProvider,o=t.credentials;return{setHttpAuthScheme(n){let i=e.findIndex(s=>s.schemeId===n.schemeId);i===-1?e.push(n):e.splice(i,1,n)},httpAuthSchemes(){return e},setHttpAuthSchemeProvider(n){r=n},httpAuthSchemeProvider(){return r},setCredentials(n){o=n},credentials(){return o}}},Qae=t=>({httpAuthSchemes:t.httpAuthSchemes(),httpAuthSchemeProvider:t.httpAuthSchemeProvider(),credentials:t.credentials()})});var tce,rce=_(()=>{Nt();ve();ge();ece();tce=(t,e)=>{let r=Object.assign(ya(t),Bi(t),oa(t),Yae(t));return e.forEach(o=>o.configure(r)),Object.assign(t,va(r),Hs(r),ia(r),Qae(r))}});var Qu,bP=_(()=>{Nt();Yn();ve();Dt();Jt();ge();jo();rt();Vq();Gq();Xae();rce();Qu=class extends Rn{config;constructor(...[e]){let r=Jae(e||{});super(r),this.initConfig=r;let o=vae(r),n=ma(o),i=ua(n),s=No(i),a=s,c=pc(a),u=yae(c),l=tce(u,e?.extensions||[]);this.config=l,this.middlewareStack.use(Fs(this.config)),this.middlewareStack.use(ha(this.config)),this.middlewareStack.use(yc(this.config)),this.middlewareStack.use(sa(this.config)),this.middlewareStack.use(da(this.config)),this.middlewareStack.use(pa(this.config)),this.middlewareStack.use(fa(this.config)),this.middlewareStack.use(es(this.config,{httpAuthSchemeParametersProvider:fae,identityProviderConfigProvider:async d=>new Fo({"aws.auth#sigv4":d.credentials,"aws.auth#sigv4a":d.credentials})})),this.middlewareStack.use(ts(this.config))}destroy(){super.destroy()}}});var SP,xP,EP,eV=_(()=>{ve();Jt();Gq();SP=Ks(wae,"AWSSecurityTokenServiceV20110615","STSClient",fc),xP={},EP=(t,e,r,o)=>[]});var Hd,$P=_(()=>{eV();Kw();Hd=class extends SP(xP,EP,"AssumeRole",Yq){}});var Kd,RP=_(()=>{eV();Kw();Kd=class extends SP(xP,EP,"AssumeRoleWithWebIdentity",Qq){}});var _2e,IP,nce=_(()=>{ve();$P();RP();bP();_2e={AssumeRoleCommand:Hd,AssumeRoleWithWebIdentityCommand:Kd},IP=class extends Qu{};qs(_2e,IP)});var oce=_(()=>{$P();RP()});var ice=_(()=>{});var sce,ace,cce,uce,lce,dce=_(()=>{Nt();$P();RP();sce=t=>{if(typeof t?.Arn=="string"){let e=t.Arn.split(":");if(e.length>4&&e[4]!=="")return e[4]}},ace=async(t,e,r,o={})=>{let n=typeof t=="function"?await t():t,i=typeof e=="function"?await e():e,s="",a=n??i??(s=await ZI(o)());return r?.debug?.("@aws-sdk/client-sts::resolveRegion","accepting first of:",`${n} (credential provider clientConfig)`,`${i} (contextual client)`,`${s} (STS default: AWS_REGION, profile region, or us-east-1)`),a},cce=(t,e)=>{let r,o;return async(n,i)=>{if(o=n,!r){let{logger:l=t?.parentClientConfig?.logger,profile:d=t?.parentClientConfig?.profile,region:p,requestHandler:f=t?.parentClientConfig?.requestHandler,credentialProviderLogger:h,userAgentAppId:y=t?.parentClientConfig?.userAgentAppId}=t,w=await ace(p,t?.parentClientConfig?.region,h,{logger:l,profile:d}),b=!lce(f);r=new e({...t,userAgentAppId:y,profile:d,credentialDefaultProvider:()=>async()=>o,region:w,requestHandler:b?f:void 0,logger:l})}let{Credentials:s,AssumedRoleUser:a}=await r.send(new Hd(i));if(!s||!s.AccessKeyId||!s.SecretAccessKey)throw new Error(`Invalid response from STS.assumeRole call with role ${i.RoleArn}`);let c=sce(a),u={accessKeyId:s.AccessKeyId,secretAccessKey:s.SecretAccessKey,sessionToken:s.SessionToken,expiration:s.Expiration,...s.CredentialScope&&{credentialScope:s.CredentialScope},...c&&{accountId:c}};return gu(u,"CREDENTIALS_STS_ASSUME_ROLE","i"),u}},uce=(t,e)=>{let r;return async o=>{if(!r){let{logger:c=t?.parentClientConfig?.logger,profile:u=t?.parentClientConfig?.profile,region:l,requestHandler:d=t?.parentClientConfig?.requestHandler,credentialProviderLogger:p,userAgentAppId:f=t?.parentClientConfig?.userAgentAppId}=t,h=await ace(l,t?.parentClientConfig?.region,p,{logger:c,profile:u}),y=!lce(d);r=new e({...t,userAgentAppId:f,profile:u,region:h,requestHandler:y?d:void 0,logger:c})}let{Credentials:n,AssumedRoleUser:i}=await r.send(new Kd(o));if(!n||!n.AccessKeyId||!n.SecretAccessKey)throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${o.RoleArn}`);let s=sce(i),a={accessKeyId:n.AccessKeyId,secretAccessKey:n.SecretAccessKey,sessionToken:n.SessionToken,expiration:n.Expiration,...n.CredentialScope&&{credentialScope:n.CredentialScope},...s&&{accountId:s}};return s&&gu(a,"RESOLVED_ACCOUNT_ID","T"),gu(a,"CREDENTIALS_STS_ASSUME_ROLE_WEB_ID","k"),a}},lce=t=>t?.metadata?.handlerProtocol==="h2"});var pce,fce,mce,b2e,hce=_(()=>{dce();bP();pce=(t,e)=>e?class extends t{constructor(o){super(o);for(let n of e)this.middlewareStack.use(n)}}:t,fce=(t={},e)=>cce(t,pce(Qu,e)),mce=(t={},e)=>uce(t,pce(Qu,e)),b2e=t=>e=>t({roleAssumer:fce(e),roleAssumerWithWebIdentity:mce(e),...e})});var tV={};Ht(tV,{$Command:()=>Wn,AssumeRole$:()=>Yq,AssumeRoleCommand:()=>Hd,AssumeRoleRequest$:()=>Lae,AssumeRoleResponse$:()=>jae,AssumeRoleWithWebIdentity$:()=>Qq,AssumeRoleWithWebIdentityCommand:()=>Kd,AssumeRoleWithWebIdentityRequest$:()=>Fae,AssumeRoleWithWebIdentityResponse$:()=>qae,AssumedRoleUser$:()=>Jq,Credentials$:()=>Xq,ExpiredTokenException:()=>Lw,ExpiredTokenException$:()=>Cae,IDPCommunicationErrorException:()=>Hw,IDPCommunicationErrorException$:()=>Oae,IDPRejectedClaimException:()=>Vw,IDPRejectedClaimException$:()=>Dae,InvalidIdentityTokenException:()=>Gw,InvalidIdentityTokenException$:()=>Nae,MalformedPolicyDocumentException:()=>jw,MalformedPolicyDocumentException$:()=>zae,PackedPolicyTooLargeException:()=>Fw,PackedPolicyTooLargeException$:()=>Mae,PolicyDescriptorType$:()=>Vae,ProvidedContext$:()=>Gae,RegionDisabledException:()=>qw,RegionDisabledException$:()=>Uae,STS:()=>IP,STSClient:()=>Qu,STSServiceException:()=>vo,STSServiceException$:()=>Tae,Tag$:()=>Hae,__Client:()=>Rn,decorateDefaultCredentialProvider:()=>b2e,errorTypeRegistries:()=>Wq,getDefaultRoleAssumer:()=>fce,getDefaultRoleAssumerWithWebIdentity:()=>mce});var rV=_(()=>{bP();nce();oce();ve();Kw();Hq();ice();hce();wP()});function S2e(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"signin",region:t.region},propertiesExtractor:(e,r)=>({signingProperties:{config:e,context:r}})}}function x2e(t){return{schemeId:"smithy.api#noAuth"}}var gce,yce,vce,nV=_(()=>{Pn();ve();gce=async(t,e,r)=>({operation:Bt(e).operation,region:await jt(t.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});yce=t=>{let e=[];return t.operation==="CreateOAuth2Token"?e.push(x2e(t)):e.push(S2e(t)),e},vce=t=>{let e=wa(t);return Object.assign(e,{authSchemePreference:jt(t.authSchemePreference??[])})}});var wce,_ce,oV=_(()=>{wce=t=>Object.assign(t,{useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,defaultSigningName:"signin"}),_ce={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}});var rl,el,bce,rh,Sce,nh,xce,sV,_c,iV,Ece,$ce,tl,Pce,Rce,AP,kn,Ice,Ace,E2e,ct,$2e,kce,Tce=_(()=>{Jt();rl="ref",el=-1,bce=!1,rh=!0,Sce="isSet",nh="booleanEquals",xce="coalesce",sV="PartitionResult",_c="stringEquals",iV="getAttr",Ece="https://signin.{Region}.{PartitionResult#dualStackDnsSuffix}",$ce={[rl]:"Endpoint"},tl={fn:iV,argv:[{[rl]:sV},"name"]},Pce={[rl]:"Region"},Rce={[rl]:sV},AP={authSchemes:[{name:"sigv4",signingName:"signin",signingRegion:"{Region}"}]},kn={},Ice=[Pce],Ace={conditions:[[Sce,Ice],[nh,[{fn:xce,argv:[{[rl]:"IsControlPlane"},bce]},rh]],[Sce,[$ce]],["aws.partition",Ice,sV],[nh,[{[rl]:"UseFIPS"},rh]],[_c,[tl,"aws"]],[nh,[{fn:xce,argv:[{[rl]:"IsOAuthEndpoint"},bce]},rh]],[nh,[{[rl]:"UseDualStack"},rh]],[_c,[tl,"aws-cn"]],[_c,[Pce,"us-gov-west-1"]],[_c,[tl,"aws-us-gov"]],[nh,[{fn:iV,argv:[Rce,"supportsFIPS"]},rh]],[_c,[tl,"aws-iso"]],[_c,[tl,"aws-iso-b"]],[_c,[tl,"aws-iso-f"]],[_c,[tl,"aws-iso-e"]],[_c,[tl,"aws-eusc"]],[nh,[{fn:iV,argv:[Rce,"supportsDualStack"]},rh]]],results:[[el],["https://signin.{Region}.api.aws",AP],["https://signin.{Region}.api.amazonwebservices.com.cn",AP],[Ece,AP],[el,"FIPS endpoints are not supported for OAuth operations. Disable FIPS or use a non-OAuth operation."],["https://{Region}.oauth.signin.aws",AP],["https://{Region}.signin.aws.amazon.com",kn],["https://{Region}.signin.amazonaws.cn",kn],["https://{Region}.signin.amazonaws-us-gov.com",kn],["https://{Region}.signin.c2shome.ic.gov",kn],["https://{Region}.signin.sc2shome.sgov.gov",kn],["https://{Region}.signin.csphome.hci.ic.gov",kn],["https://{Region}.signin.csphome.adc-e.uk",kn],["https://{Region}.signin.amazonaws-eusc.eu",kn],["https://signin-fips.amazonaws-us-gov.com",kn],["https://{Region}.signin-fips.amazonaws-us-gov.com",kn],["https://{Region}.signin.{PartitionResult#dnsSuffix}",kn],[el,"Invalid Configuration: FIPS and custom endpoint are not supported"],[el,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[$ce,kn],["https://signin-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",kn],[el,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://signin-fips.{Region}.{PartitionResult#dnsSuffix}",kn],[el,"FIPS is enabled but this partition does not support FIPS"],[Ece,kn],[el,"DualStack is enabled but this partition does not support DualStack"],["https://signin.{Region}.{PartitionResult#dnsSuffix}",kn],[el,"Invalid Configuration: Missing Region"]]},E2e=2,ct=1e8,$2e=new Int32Array([-1,1,-1,0,6,3,2,36,4,4,5,ct+27,6,ct+4,ct+27,1,29,7,2,36,8,3,9,31,4,22,10,5,19,11,7,21,12,8,ct+7,13,10,ct+8,14,12,ct+9,15,13,ct+10,16,14,ct+11,17,15,ct+12,18,16,ct+13,ct+16,6,ct+5,20,7,21,ct+6,17,ct+24,ct+25,6,ct+4,23,7,27,24,9,ct+14,25,10,ct+15,26,11,ct+22,ct+23,11,28,ct+21,17,ct+20,ct+21,2,35,30,3,39,31,4,32,ct+27,6,ct+4,33,7,ct+27,34,9,ct+14,ct+27,3,39,36,4,38,37,7,ct+18,ct+19,6,ct+4,ct+17,5,ct+1,40,8,ct+2,ct+3]),kce=ci.from($2e,E2e,Ace.conditions,Ace.results)});var R2e,Cce,Oce=_(()=>{Nt();Jt();Tce();R2e=new ui({size:50,params:["Endpoint","IsControlPlane","IsOAuthEndpoint","Region","UseDualStack","UseFIPS"]}),Cce=(t,e={})=>R2e.get(t,()=>ra(kce,{endpointParams:t,logger:e.logger}));ho.aws=ns});var fs,PP=_(()=>{ve();fs=class t extends si{constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}}});var Bw,Zw,Ww,Jw,aV=_(()=>{PP();Bw=class t extends fs{name="AccessDeniedException";$fault="client";error;constructor(e){super({name:"AccessDeniedException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error}},Zw=class t extends fs{name="InternalServerException";$fault="server";error;constructor(e){super({name:"InternalServerException",$fault:"server",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error}},Ww=class t extends fs{name="TooManyRequestsError";$fault="client";error;constructor(e){super({name:"TooManyRequestsError",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error}},Jw=class t extends fs{name="ValidationException";$fault="client";error;constructor(e){super({name:"ValidationException",$fault:"client",...e}),Object.setPrototypeOf(this,t.prototype),this.error=e.error}}});var I2e,A2e,P2e,k2e,T2e,C2e,O2e,D2e,N2e,z2e,M2e,U2e,L2e,j2e,F2e,Dce,cV,q2e,pV,Nce,zce,V2e,nl,uV,G2e,lV,H2e,Fce,fV,Mce,dn,TP,K2e,kP,Uce,qce,Lce,jce,B2e,Z2e,W2e,dV,J2e,Tn,Vce,Gce,Xw,Hce,Kce,Bce,Zce,mV,X2e,Wce,Jce,Xce,Yce,Qce,eue,tue,rue,hV,gV,Yw=_(()=>{rt();aV();PP();I2e="AccessDeniedException",A2e="AccessToken",P2e="CreateOAuth2Token",k2e="CreateOAuth2TokenRequest",T2e="CreateOAuth2TokenRequestBody",C2e="CreateOAuth2TokenResponseBody",O2e="CreateOAuth2TokenResponse",D2e="CreateOAuth2TokenWithIAM",N2e="CreateOAuth2TokenWithIAMRequest",z2e="CreateOAuth2TokenWithIAMResponse",M2e="InternalServerException",U2e="OAuthAccessToken",L2e="RefreshToken",j2e="TooManyRequestsError",F2e="ValidationException",Dce="accessKeyId",cV="accessToken",q2e="access_token",pV="client",Nce="clientId",zce="codeVerifier",V2e="code",nl="error",uV="expiresIn",G2e="expires_in",lV="grantType",H2e="grant_type",Fce="http",fV="httpError",Mce="idToken",dn="jsonName",TP="message",K2e="resource",kP="refreshToken",Uce="redirectUri",qce="smithy.ts.sdk.synthetic.com.amazonaws.signin",Lce="secretAccessKey",jce="sessionToken",B2e="server",Z2e="tokenInput",W2e="tokenOutput",dV="tokenType",J2e="token_type",Tn="com.amazonaws.signin",Vce=new Zt(qce),Gce=[-3,qce,"SigninServiceException",0,[],[]];Vce.registerError(Gce,fs);Xw=new Zt(Tn),Hce=[-3,Tn,I2e,{[nl]:pV},[nl,TP],[0,0],2];Xw.registerError(Hce,Bw);Kce=[-3,Tn,M2e,{[nl]:B2e,[fV]:500},[nl,TP],[0,0],2];Xw.registerError(Kce,Zw);Bce=[-3,Tn,j2e,{[nl]:pV,[fV]:429},[nl,TP],[0,0],2];Xw.registerError(Bce,Ww);Zce=[-3,Tn,F2e,{[nl]:pV,[fV]:400},[nl,TP],[0,0],2];Xw.registerError(Zce,Jw);mV=[Vce,Xw],X2e=[0,Tn,U2e,8,0],Wce=[0,Tn,L2e,8,0],Jce=[3,Tn,A2e,8,[Dce,Lce,jce],[[0,{[dn]:Dce}],[0,{[dn]:Lce}],[0,{[dn]:jce}]],3],Xce=[3,Tn,k2e,0,[Z2e],[[()=>Yce,16]],1],Yce=[3,Tn,T2e,0,[Nce,lV,V2e,Uce,zce,kP],[[0,{[dn]:Nce}],[0,{[dn]:lV}],0,[0,{[dn]:Uce}],[0,{[dn]:zce}],[()=>Wce,{[dn]:kP}]],2],Qce=[3,Tn,O2e,0,[W2e],[[()=>eue,16]],1],eue=[3,Tn,C2e,0,[cV,dV,uV,kP,Mce],[[()=>Jce,{[dn]:cV}],[0,{[dn]:dV}],[1,{[dn]:uV}],[()=>Wce,{[dn]:kP}],[0,{[dn]:Mce}]],4],tue=[3,Tn,N2e,0,[lV,K2e],[[0,{[dn]:H2e}],0],2],rue=[3,Tn,z2e,0,[cV,dV,uV],[[()=>X2e,{[dn]:q2e}],[0,{[dn]:J2e}],[1,{[dn]:G2e}]],3],hV=[9,Tn,P2e,{[Fce]:["POST","/v1/token",200]},()=>Xce,()=>Qce],gV=[9,Tn,D2e,{[Fce]:["POST","/v1/token?x-amz-client-auth-method=iam",200]},()=>tue,()=>rue]});var nue,oue=_(()=>{Pn();Nd();Yn();gc();ve();ge();xe();nV();Oce();Yw();nue=t=>({apiVersion:"2023-01-01",base64Decoder:t?.base64Decoder??fr,base64Encoder:t?.base64Encoder??Wt,disableHostPrefix:t?.disableHostPrefix??!1,endpointProvider:t?.endpointProvider??Cce,extensions:t?.extensions??[],httpAuthSchemeProvider:t?.httpAuthSchemeProvider??yce,httpAuthSchemes:t?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4"),signer:new Gr},{schemeId:"smithy.api#noAuth",identityProvider:e=>e.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new An}],logger:t?.logger??new mo,protocol:t?.protocol??Sa,protocolSettings:t?.protocolSettings??{defaultNamespace:"com.amazonaws.signin",errorTypeRegistries:mV,version:"2023-01-01",serviceTarget:"Signin"},serviceId:t?.serviceId??"Signin",sha256:t?.sha256??Xi,urlParser:t?.urlParser??nn,utf8Decoder:t?.utf8Decoder??Tr,utf8Encoder:t?.utf8Encoder??ur})});var CP,iue,sue=_(()=>{iw();Nt();Pn();ve();Dt();jo();xe();CP=Vt(Gu());oue();iue=t=>{Gs(process.version);let e=ea(t),r=()=>e().then(Vs),o=nue(t);Ls(process.version);let n={profile:t?.profile,logger:o.logger};return{...o,...t,runtime:"node",defaultsMode:e,authSchemePreference:t?.authSchemePreference??Ie(is,n),bodyLengthChecker:t?.bodyLengthChecker??Zs,defaultUserAgentProvider:t?.defaultUserAgentProvider??rs({serviceId:o.serviceId,clientVersion:Hu.version}),maxAttempts:t?.maxAttempts??Ie(ca,t),region:t?.region??Ie(on,{...Xn,...n}),requestHandler:CP.NodeHttpHandler.create(t?.requestHandler??r),retryMode:t?.retryMode??Ie({...la,default:async()=>(await r()).retryMode||li},t),streamCollector:t?.streamCollector??CP.streamCollector,useDualstackEndpoint:t?.useDualstackEndpoint??Ie(Ys,n),useFipsEndpoint:t?.useFipsEndpoint??Ie(Qs,n),userAgentAppId:t?.userAgentAppId??Ie(ga,n)}}});var aue,cue,uue=_(()=>{aue=t=>{let e=t.httpAuthSchemes,r=t.httpAuthSchemeProvider,o=t.credentials;return{setHttpAuthScheme(n){let i=e.findIndex(s=>s.schemeId===n.schemeId);i===-1?e.push(n):e.splice(i,1,n)},httpAuthSchemes(){return e},setHttpAuthSchemeProvider(n){r=n},httpAuthSchemeProvider(){return r},setCredentials(n){o=n},credentials(){return o}}},cue=t=>({httpAuthSchemes:t.httpAuthSchemes(),httpAuthSchemeProvider:t.httpAuthSchemeProvider(),credentials:t.credentials()})});var lue,due=_(()=>{Nt();ve();ge();uue();lue=(t,e)=>{let r=Object.assign(ya(t),Bi(t),oa(t),aue(t));return e.forEach(o=>o.configure(r)),Object.assign(t,va(r),Hs(r),ia(r),cue(r))}});var Qw,yV=_(()=>{Nt();Yn();ve();Dt();Jt();ge();jo();rt();nV();oV();sue();due();Qw=class extends Rn{config;constructor(...[e]){let r=iue(e||{});super(r),this.initConfig=r;let o=wce(r),n=ma(o),i=ua(n),s=No(i),a=s,c=pc(a),u=vce(c),l=lue(u,e?.extensions||[]);this.config=l,this.middlewareStack.use(Fs(this.config)),this.middlewareStack.use(ha(this.config)),this.middlewareStack.use(yc(this.config)),this.middlewareStack.use(sa(this.config)),this.middlewareStack.use(da(this.config)),this.middlewareStack.use(pa(this.config)),this.middlewareStack.use(fa(this.config)),this.middlewareStack.use(es(this.config,{httpAuthSchemeParametersProvider:gce,identityProviderConfigProvider:async d=>new Fo({"aws.auth#sigv4":d.credentials})})),this.middlewareStack.use(ts(this.config))}destroy(){super.destroy()}}});var OP,pue,fue,DP,vV=_(()=>{ve();Jt();oV();OP=Ks(_ce,"Signin","SigninClient",fc),pue={IsControlPlane:{type:"staticContextParams",value:!1}},fue={IsOAuthEndpoint:{type:"staticContextParams",value:!0}},DP=(t,e,r,o)=>[]});var e_,wV=_(()=>{vV();Yw();e_=class extends OP(pue,DP,"CreateOAuth2Token",hV){}});var t_,_V=_(()=>{vV();Yw();t_=class extends OP(fue,DP,"CreateOAuth2TokenWithIAM",gV){}});var Y2e,NP,mue=_(()=>{ve();wV();_V();yV();Y2e={CreateOAuth2TokenCommand:e_,CreateOAuth2TokenWithIAMCommand:t_},NP=class extends Qw{};qs(Y2e,NP)});var hue=_(()=>{wV();_V()});var Q2e,gue=_(()=>{Q2e={AUTHCODE_EXPIRED:"AUTHCODE_EXPIRED",CONFLICT:"CONFLICT",INSUFFICIENT_PERMISSIONS:"INSUFFICIENT_PERMISSIONS",INVALID_REQUEST:"INVALID_REQUEST",RESOURCE_NOT_FOUND:"RESOURCE_NOT_FOUND",SERVER_ERROR:"server_error",SERVICE_QUOTA_EXCEEDED:"SERVICE_QUOTA_EXCEEDED",TOKEN_EXPIRED:"TOKEN_EXPIRED",USER_CREDENTIALS_CHANGED:"USER_CREDENTIALS_CHANGED"}});var yue=_(()=>{});var vue={};Ht(vue,{$Command:()=>Wn,AccessDeniedException:()=>Bw,AccessDeniedException$:()=>Hce,AccessToken$:()=>Jce,CreateOAuth2Token$:()=>hV,CreateOAuth2TokenCommand:()=>e_,CreateOAuth2TokenRequest$:()=>Xce,CreateOAuth2TokenRequestBody$:()=>Yce,CreateOAuth2TokenResponse$:()=>Qce,CreateOAuth2TokenResponseBody$:()=>eue,CreateOAuth2TokenWithIAM$:()=>gV,CreateOAuth2TokenWithIAMCommand:()=>t_,CreateOAuth2TokenWithIAMRequest$:()=>tue,CreateOAuth2TokenWithIAMResponse$:()=>rue,InternalServerException:()=>Zw,InternalServerException$:()=>Kce,OAuth2ErrorCode:()=>Q2e,Signin:()=>NP,SigninClient:()=>Qw,SigninServiceException:()=>fs,SigninServiceException$:()=>Gce,TooManyRequestsError:()=>Ww,TooManyRequestsError$:()=>Bce,ValidationException:()=>Jw,ValidationException$:()=>Zce,__Client:()=>Rn,errorTypeRegistries:()=>mV});var wue=_(()=>{yV();mue();hue();ve();Yw();gue();aV();yue();PP()});var Sue=U(bue=>{var{setCredentialFeature:e6e}=(Nt(),re(os)),{CredentialsProviderError:ol,parseKnownFiles:t6e,getProfileName:r6e}=(Dt(),re(zo)),{HttpRequest:n6e}=(ge(),re(zu)),{createHash:o6e,createPrivateKey:i6e,createPublicKey:s6e,sign:a6e}=io("node:crypto"),{promises:bV}=io("node:fs"),{homedir:c6e}=io("node:os"),{dirname:u6e,join:_ue}=io("node:path"),SV=class t{profileData;init;callerClientConfig;static REFRESH_THRESHOLD=300*1e3;constructor(e,r,o){this.profileData=e,this.init=r,this.callerClientConfig=o}async loadCredentials(){let e=await this.loadToken();if(!e)throw new ol(`Failed to load a token for session ${this.loginSession}, please re-authenticate using aws login`,{tryNextLink:!1,logger:this.logger});let r=e.accessToken,o=Date.now();return new Date(r.expiresAt).getTime()-o<=t.REFRESH_THRESHOLD?this.refresh(e):this.toCredentials(e.accessToken)}get logger(){return this.init?.logger}get loginSession(){return this.profileData.login_session}toCredentials(e){return{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey,sessionToken:e.sessionToken,accountId:e.accountId,expiration:new Date(e.expiresAt)}}async refresh(e){let r=await this.loadToken().catch(()=>e),o=Date.now(),n=new Date(r.accessToken.expiresAt).getTime(),i=new Date(e.accessToken.expiresAt).getTime(),s=n<=o&&i>o?e:r;if(new Date(s.accessToken.expiresAt).getTime()-Date.now()>t.REFRESH_THRESHOLD)return this.toCredentials(s.accessToken);let{SigninClient:c,CreateOAuth2TokenCommand:u}=(wue(),re(vue)),{logger:l,userAgentAppId:d}=this.callerClientConfig??{},f=(b=>b?.metadata?.handlerProtocol==="h2")(this.callerClientConfig?.requestHandler)?void 0:this.callerClientConfig?.requestHandler,h=this.profileData.region??await this.callerClientConfig?.region?.()??process.env.AWS_REGION,y=new c({credentials:{accessKeyId:"",secretAccessKey:""},region:h,requestHandler:f,logger:l,userAgentAppId:d,...this.init?.clientConfig});this.createDPoPInterceptor(y.middlewareStack);let w={tokenInput:{clientId:s.clientId,refreshToken:s.refreshToken,grantType:"refresh_token"}};try{let b=await y.send(new u(w)),{accessKeyId:S,secretAccessKey:x,sessionToken:R}=b.tokenOutput?.accessToken??{},{refreshToken:T,expiresIn:M}=b.tokenOutput??{};if(!S||!x||!R||!T)throw new ol("Token refresh response missing required fields",{logger:this.logger,tryNextLink:!1});let Z=(M??900)*1e3,te=new Date(Date.now()+Z),Ae={...s,accessToken:{...s.accessToken,accessKeyId:S,secretAccessKey:x,sessionToken:R,expiresAt:te.toISOString()},refreshToken:T};return await this.saveToken(Ae),this.toCredentials(Ae.accessToken)}catch(b){if(b.name==="AccessDeniedException"){let x=b.error,R;switch(x){case"TOKEN_EXPIRED":R="Your session has expired. Please reauthenticate.";break;case"USER_CREDENTIALS_CHANGED":R="Unable to refresh credentials because of a change in your password. Please reauthenticate with your new password.";break;case"INSUFFICIENT_PERMISSIONS":R="Unable to refresh credentials due to insufficient permissions. You may be missing permission for the 'CreateOAuth2Token' action.";break;default:R=`Failed to refresh token: ${String(b)}. Please re-authenticate using \`aws login\``}throw new ol(R,{logger:this.logger,tryNextLink:!1})}if(new Date(s.accessToken.expiresAt).getTime()>Date.now())return this.logger?.warn?.(`Failed to refresh token: ${String(b)}. Using existing token until expiry.`),this.toCredentials(s.accessToken);throw new ol(`Failed to refresh token: ${String(b)}. Please re-authenticate using aws login`,{logger:this.logger})}}async loadToken(){let e=this.getTokenFilePath();try{let r=await bV.readFile(e,"utf8"),o=JSON.parse(r),n=["accessToken","clientId","refreshToken","dpopKey"].filter(i=>!o[i]);if(o.accessToken?.accountId||n.push("accountId"),n.length>0)throw new ol(`Token validation failed, missing fields: ${n.join(", ")}`,{logger:this.logger,tryNextLink:!1});return o}catch(r){throw new ol(`Failed to load token from ${e}: ${String(r)}`,{logger:this.logger,tryNextLink:!1})}}async saveToken(e){let r=this.getTokenFilePath(),o=u6e(r);try{await bV.mkdir(o,{recursive:!0})}catch{}await bV.writeFile(r,JSON.stringify(e,null,2),"utf8")}getTokenFilePath(){let e=process.env.AWS_LOGIN_CACHE_DIRECTORY??_ue(c6e(),".aws","login","cache"),r=Buffer.from(this.loginSession,"utf8"),o=o6e("sha256").update(r).digest("hex");return _ue(e,`${o}.json`)}derToRawSignature(e){let r=2;if(e[r]!==2)throw new Error("Invalid DER signature");r++;let o=e[r++],n=e.subarray(r,r+o);if(r+=o,e[r]!==2)throw new Error("Invalid DER signature");r++;let i=e[r++],s=e.subarray(r,r+i);n=n[0]===0?n.subarray(1):n,s=s[0]===0?s.subarray(1):s;let a=Buffer.concat([Buffer.alloc(32-n.length),n]),c=Buffer.concat([Buffer.alloc(32-s.length),s]);return Buffer.concat([a,c])}createDPoPInterceptor(e){e.add(r=>async o=>{if(n6e.isInstance(o.request)){let n=o.request,i=`${n.protocol}//${n.hostname}${n.port?`:${n.port}`:""}${n.path}`,s=await this.generateDpop(n.method,i);n.headers={...n.headers,DPoP:s}}return r(o)},{step:"finalizeRequest",name:"dpopInterceptor",override:!0})}async generateDpop(e="POST",r){let o=await this.loadToken();try{let n=i6e({key:o.dpopKey,format:"pem",type:"sec1"}),s=s6e(n).export({format:"der",type:"spki"}),a=-1;for(let S=0;S<s.length;S++)if(s[S]===4){a=S;break}let c=s.slice(a+1,a+33),u=s.slice(a+33,a+65),l={alg:"ES256",typ:"dpop+jwt",jwk:{kty:"EC",crv:"P-256",x:c.toString("base64url"),y:u.toString("base64url")}},d={jti:crypto.randomUUID(),htm:e,htu:r,iat:Math.floor(Date.now()/1e3)},p=Buffer.from(JSON.stringify(l)).toString("base64url"),f=Buffer.from(JSON.stringify(d)).toString("base64url"),h=`${p}.${f}`,y=a6e("sha256",Buffer.from(h),n),b=this.derToRawSignature(y).toString("base64url");return`${h}.${b}`}catch(n){throw new ol(`Failed to generate Dpop proof: ${n instanceof Error?n.message:String(n)}`,{logger:this.logger,tryNextLink:!1})}}},l6e=t=>async({callerClientConfig:e}={})=>{t?.logger?.debug?.("@aws-sdk/credential-providers - fromLoginCredentials");let r=await t6e(t||{}),o=r6e({profile:t?.profile??e?.profile}),n=r[o];if(!n?.login_session)throw new ol(`Profile ${o} does not contain login_session.`,{tryNextLink:!0,logger:t?.logger});let s=await new SV(n,t,e).loadCredentials();return e6e(s,"CREDENTIALS_LOGIN","AD")};bue.fromLoginCredentials=l6e});var EV=U(xue=>{var{externalDataInterceptor:d6e,CredentialsProviderError:xV,parseKnownFiles:p6e,getProfileName:f6e}=(Dt(),re(zo)),{exec:m6e}=io("node:child_process"),{promisify:h6e}=io("node:util"),{setCredentialFeature:g6e}=(Nt(),re(os)),y6e=(t,e,r)=>{if(e.Version!==1)throw Error(`Profile ${t} credential_process did not return Version 1.`);if(e.AccessKeyId===void 0||e.SecretAccessKey===void 0)throw Error(`Profile ${t} credential_process returned invalid credentials.`);if(e.Expiration){let i=new Date;if(new Date(e.Expiration)<i)throw Error(`Profile ${t} credential_process returned expired credentials.`)}let o=e.AccountId;!o&&r?.[t]?.aws_account_id&&(o=r[t].aws_account_id);let n={accessKeyId:e.AccessKeyId,secretAccessKey:e.SecretAccessKey,...e.SessionToken&&{sessionToken:e.SessionToken},...e.Expiration&&{expiration:new Date(e.Expiration)},...e.CredentialScope&&{credentialScope:e.CredentialScope},...o&&{accountId:o}};return g6e(n,"CREDENTIALS_PROCESS","w"),n},v6e=async(t,e,r)=>{let o=e[t];if(e[t]){let n=o.credential_process;if(n!==void 0){let i=h6e(d6e?.getTokenRecord?.().exec??m6e);try{let{stdout:s}=await i(n),a;try{a=JSON.parse(s.trim())}catch{throw Error(`Profile ${t} credential_process returned invalid JSON.`)}return y6e(t,a,e)}catch(s){throw new xV(s.message,{logger:r})}}else throw new xV(`Profile ${t} did not contain credential_process.`,{logger:r})}else throw new xV(`Profile ${t} could not be found in shared credentials file.`,{logger:r})},w6e=(t={})=>async({callerClientConfig:e}={})=>{t.logger?.debug("@aws-sdk/credential-provider-process - fromProcess");let r=await p6e(t);return v6e(f6e({profile:t.profile??e?.profile}),r,t.logger)};xue.fromProcess=w6e});var RV=U($V=>{var{setCredentialFeature:_6e}=(Nt(),re(os)),{CredentialsProviderError:b6e,externalDataInterceptor:S6e}=(Dt(),re(zo)),{readFileSync:x6e}=io("node:fs"),$ue=t=>async e=>{t.logger?.debug("@aws-sdk/credential-provider-web-identity - fromWebToken");let{roleArn:r,roleSessionName:o,webIdentityToken:n,providerId:i,policyArns:s,policy:a,durationSeconds:c}=t,{roleAssumerWithWebIdentity:u}=t;if(!u){let{getDefaultRoleAssumerWithWebIdentity:l}=(rV(),re(tV));u=l({...t.clientConfig,credentialProviderLogger:t.logger,parentClientConfig:{...e?.callerClientConfig,...t.parentClientConfig}},t.clientPlugins)}return u({RoleArn:r,RoleSessionName:o??`aws-sdk-js-session-${Date.now()}`,WebIdentityToken:n,ProviderId:i,PolicyArns:s,Policy:a,DurationSeconds:c})},Eue="AWS_WEB_IDENTITY_TOKEN_FILE",E6e="AWS_ROLE_ARN",$6e="AWS_ROLE_SESSION_NAME",R6e=(t={})=>async e=>{t.logger?.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile");let r=t?.webIdentityTokenFile??process.env[Eue],o=t?.roleArn??process.env[E6e],n=t?.roleSessionName??process.env[$6e];if(!r||!o)throw new b6e("Web identity configuration not specified",{logger:t.logger});let i=await $ue({...t,webIdentityToken:S6e?.getTokenRecord?.()[r]??x6e(r,{encoding:"ascii"}),roleArn:o,roleSessionName:n})(e);return r===process.env[Eue]&&_6e(i,"CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN","h"),i};$V.fromTokenFile=R6e;$V.fromWebToken=$ue});var Cue=U(Tue=>{var{CredentialsProviderError:zP,chain:I6e,getProfileName:Pue,parseKnownFiles:A6e}=(Dt(),re(zo)),{setCredentialFeature:bc}=(Nt(),re(os)),P6e=(t,e,r)=>{let o={EcsContainer:async n=>{let{fromHttp:i}=T6(),{fromContainerMetadata:s}=dA();return r?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer"),async()=>I6e(i(n??{}),s(n))().then(IV)},Ec2InstanceMetadata:async n=>{r?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata");let{fromInstanceMetadata:i}=dA();return async()=>i(n)().then(IV)},Environment:async n=>{r?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment");let{fromEnv:i}=v6();return async()=>i(n)().then(IV)}};if(t in o)return o[t];throw new zP(`Unsupported credential source in profile ${e}. Got ${t}, expected EcsContainer or Ec2InstanceMetadata or Environment.`,{logger:r})},IV=t=>bc(t,"CREDENTIALS_PROFILE_NAMED_PROVIDER","p"),k6e=(t,{profile:e="default",logger:r}={})=>!!t&&typeof t=="object"&&typeof t.role_arn=="string"&&["undefined","string"].indexOf(typeof t.role_session_name)>-1&&["undefined","string"].indexOf(typeof t.external_id)>-1&&["undefined","string"].indexOf(typeof t.mfa_serial)>-1&&(T6e(t,{profile:e,logger:r})||C6e(t,{profile:e,logger:r})),T6e=(t,{profile:e,logger:r})=>{let o=typeof t.source_profile=="string"&&typeof t.credential_source>"u";return o&&r?.debug?.(` ${e} isAssumeRoleWithSourceProfile source_profile=${t.source_profile}`),o},C6e=(t,{profile:e,logger:r})=>{let o=typeof t.credential_source=="string"&&typeof t.source_profile>"u";return o&&r?.debug?.(` ${e} isCredentialSourceProfile credential_source=${t.credential_source}`),o},O6e=async(t,e,r,o,n={},i)=>{r.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)");let s=e[t],{source_profile:a,region:c}=s;if(!r.roleAssumer){let{getDefaultRoleAssumer:l}=(rV(),re(tV));r.roleAssumer=l({...r.clientConfig,credentialProviderLogger:r.logger,parentClientConfig:{...o,...r?.parentClientConfig,region:c??r?.parentClientConfig?.region??o?.region}},r.clientPlugins)}if(a&&a in n)throw new zP(`Detected a cycle attempting to resolve credentials for profile ${Pue(r)}. Profiles visited: `+Object.keys(n).join(", "),{logger:r.logger});r.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${a?`source_profile=[${a}]`:`profile=[${t}]`}`);let u=a?i(a,e,r,o,{...n,[a]:!0},Rue(e[a]??{})):(await P6e(s.credential_source,t,r.logger)(r))();if(Rue(s))return u.then(l=>bc(l,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"));{let l={RoleArn:s.role_arn,RoleSessionName:s.role_session_name||`aws-sdk-js-${Date.now()}`,ExternalId:s.external_id,DurationSeconds:parseInt(s.duration_seconds||"3600",10)},{mfa_serial:d}=s;if(d){if(!r.mfaCodeProvider)throw new zP(`Profile ${t} requires multi-factor authentication, but no MFA code callback was provided.`,{logger:r.logger,tryNextLink:!1});l.SerialNumber=d,l.TokenCode=await r.mfaCodeProvider(d)}let p=await u;return r.roleAssumer(p,l).then(f=>bc(f,"CREDENTIALS_PROFILE_SOURCE_PROFILE","o"))}},Rue=t=>!t.role_arn&&!!t.credential_source,D6e=t=>!!(t&&t.login_session),N6e=async(t,e,r)=>{let{fromLoginCredentials:o}=Sue(),n=await o({...e,profile:t})({callerClientConfig:r});return bc(n,"CREDENTIALS_PROFILE_LOGIN","AC")},z6e=t=>!!t&&typeof t=="object"&&typeof t.credential_process=="string",M6e=async(t,e)=>{let{fromProcess:r}=EV(),o=await r({...t,profile:e})();return bc(o,"CREDENTIALS_PROFILE_PROCESS","v")},U6e=async(t,e,r={},o)=>{let{fromSSO:n}=Uq();return n({profile:t,logger:r.logger,parentClientConfig:r.parentClientConfig,clientConfig:r.clientConfig})({callerClientConfig:o}).then(i=>e.sso_session?bc(i,"CREDENTIALS_PROFILE_SSO","r"):bc(i,"CREDENTIALS_PROFILE_SSO_LEGACY","t"))},L6e=t=>t&&(typeof t.sso_start_url=="string"||typeof t.sso_account_id=="string"||typeof t.sso_session=="string"||typeof t.sso_region=="string"||typeof t.sso_role_name=="string"),Iue=t=>!!t&&typeof t=="object"&&typeof t.aws_access_key_id=="string"&&typeof t.aws_secret_access_key=="string"&&["undefined","string"].indexOf(typeof t.aws_session_token)>-1&&["undefined","string"].indexOf(typeof t.aws_account_id)>-1,Aue=async(t,e)=>{e?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials");let r={accessKeyId:t.aws_access_key_id,secretAccessKey:t.aws_secret_access_key,sessionToken:t.aws_session_token,...t.aws_credential_scope&&{credentialScope:t.aws_credential_scope},...t.aws_account_id&&{accountId:t.aws_account_id}};return bc(r,"CREDENTIALS_PROFILE","n")},j6e=t=>!!t&&typeof t=="object"&&typeof t.web_identity_token_file=="string"&&typeof t.role_arn=="string"&&["undefined","string"].indexOf(typeof t.role_session_name)>-1,F6e=async(t,e,r)=>{let{fromTokenFile:o}=RV(),n=await o({webIdentityTokenFile:t.web_identity_token_file,roleArn:t.role_arn,roleSessionName:t.role_session_name,roleAssumerWithWebIdentity:e.roleAssumerWithWebIdentity,logger:e.logger,parentClientConfig:e.parentClientConfig})({callerClientConfig:r});return bc(n,"CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN","q")},kue=async(t,e,r,o,n={},i=!1)=>{let s=e[t];if(Object.keys(n).length>0&&Iue(s))return Aue(s,r);if(i||k6e(s,{profile:t,logger:r.logger}))return O6e(t,e,r,o,n,kue);if(Iue(s))return Aue(s,r);if(j6e(s))return F6e(s,r,o);if(z6e(s))return M6e(r,t);if(L6e(s))return await U6e(t,s,r,o);if(D6e(s))return N6e(t,r,o);throw new zP(`Could not resolve credentials using profile: [${t}] in configuration/credentials file(s).`,{logger:r.logger})},q6e=(t={})=>async({callerClientConfig:e}={})=>{t.logger?.debug("@aws-sdk/credential-provider-ini - fromIni");let r=await A6e(t);return kue(Pue({profile:t.profile??e?.profile}),r,t,e)};Tue.fromIni=q6e});var AV=U(UP=>{var{ENV_KEY:V6e,ENV_SECRET:G6e,fromEnv:H6e}=v6(),{chain:K6e,CredentialsProviderError:MP,ENV_PROFILE:B6e}=(Dt(),re(zo)),Oue="AWS_EC2_METADATA_DISABLED",Z6e=async t=>{let{ENV_CMDS_FULL_URI:e,ENV_CMDS_RELATIVE_URI:r,fromContainerMetadata:o,fromInstanceMetadata:n}=dA();if(process.env[r]||process.env[e]){t.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromHttp/fromContainerMetadata");let{fromHttp:i}=T6();return K6e(i(t),o(t))}return process.env[Oue]&&process.env[Oue]!=="false"?async()=>{throw new MP("EC2 Instance Metadata Service access disabled",{logger:t.logger})}:(t.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata"),n(t))};function W6e(t,e){let r=J6e(t),o,n,i,s,a=async c=>{if(c?.forceRefresh)return s||(s=r(c).then(u=>{i=u}).finally(()=>{s=void 0})),await s,i;if(i?.expiration&&i?.expiration?.getTime()<Date.now()&&(i=void 0),o)await o;else if(!i||e?.(i))if(i)n||(n=r(c).then(u=>{i=u}).catch(()=>{}).finally(()=>{n=void 0}));else return o=r(c).then(u=>{i=u}).finally(()=>{o=void 0}),a(c);return i};return a}var J6e=t=>async e=>{let r;for(let o of t)try{return await o(e)}catch(n){if(r=n,n?.tryNextLink)continue;throw n}throw r},Due=!1,X6e=(t={})=>W6e([async()=>{if(t.profile??process.env[B6e])throw process.env[V6e]&&process.env[G6e]&&(Due||((t.logger?.warn&&t.logger?.constructor?.name!=="NoOpLogger"?t.logger.warn.bind(t.logger):console.warn)(`@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING:
53
53
  Multiple credential sources detected:
54
54
  Both AWS_PROFILE and the pair AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY static credentials are set.
55
55
  This SDK will proceed with the AWS_PROFILE value.
@@ -64,7 +64,7 @@ Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.ht
64
64
  || ${s} === "boolean" || ${n} === null`).assign(a,(0,Ue._)`[${n}]`)}}}function Nat({gen:t,parentData:e,parentDataProperty:r},o){t.if((0,Ue._)`${e} !== undefined`,()=>t.assign((0,Ue._)`${e}[${r}]`,o))}function cH(t,e,r,o=Bh.Correct){let n=o===Bh.Correct?Ue.operators.EQ:Ue.operators.NEQ,i;switch(t){case"null":return(0,Ue._)`${e} ${n} null`;case"array":i=(0,Ue._)`Array.isArray(${e})`;break;case"object":i=(0,Ue._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":i=s((0,Ue._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":i=s();break;default:return(0,Ue._)`typeof ${e} ${n} ${t}`}return o===Bh.Correct?i:(0,Ue.not)(i);function s(a=Ue.nil){return(0,Ue.and)((0,Ue._)`typeof ${e} == "number"`,a,r?(0,Ue._)`isFinite(${e})`:Ue.nil)}}Un.checkDataType=cH;function uH(t,e,r,o){if(t.length===1)return cH(t[0],e,r,o);let n,i=(0,N$e.toHash)(t);if(i.array&&i.object){let s=(0,Ue._)`typeof ${e} != "object"`;n=i.null?s:(0,Ue._)`!${e} || ${s}`,delete i.null,delete i.array,delete i.object}else n=Ue.nil;i.number&&delete i.integer;for(let s in i)n=(0,Ue.and)(n,cH(s,e,r,o));return n}Un.checkDataTypes=uH;var zat={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,Ue._)`{type: ${t}}`:(0,Ue._)`{type: ${e}}`};function lH(t){let e=Mat(t);(0,kat.reportError)(e,zat)}Un.reportTypeError=lH;function Mat(t){let{gen:e,data:r,schema:o}=t,n=(0,N$e.schemaRefOrVal)(t,o,"type");return{gen:e,keyword:"type",data:r,schema:o.type,schemaCode:n,schemaValue:n,parentSchema:o,params:{},it:t}}});var L$e=U(CN=>{"use strict";Object.defineProperty(CN,"__esModule",{value:!0});CN.assignDefaults=void 0;var Zh=je(),Uat=mt();function Lat(t,e){let{properties:r,items:o}=t.schema;if(e==="object"&&r)for(let n in r)U$e(t,n,r[n].default);else e==="array"&&Array.isArray(o)&&o.forEach((n,i)=>U$e(t,i,n.default))}CN.assignDefaults=Lat;function U$e(t,e,r){let{gen:o,compositeRule:n,data:i,opts:s}=t;if(r===void 0)return;let a=(0,Zh._)`${i}${(0,Zh.getProperty)(e)}`;if(n){(0,Uat.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Zh._)`${a} === undefined`;s.useDefaults==="empty"&&(c=(0,Zh._)`${c} || ${a} === null || ${a} === ""`),o.if(c,(0,Zh._)`${a} = ${(0,Zh.stringify)(r)}`)}});var Ti=U(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.validateUnion=Ft.validateArray=Ft.usePattern=Ft.callValidateCode=Ft.schemaProperties=Ft.allSchemaProperties=Ft.noPropertyInData=Ft.propertyInData=Ft.isOwnProperty=Ft.hasPropFunc=Ft.reportMissingProp=Ft.checkMissingProp=Ft.checkReportMissingProp=void 0;var Qt=je(),dH=mt(),Il=zc(),jat=mt();function Fat(t,e){let{gen:r,data:o,it:n}=t;r.if(fH(r,o,e,n.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Qt._)`${e}`},!0),t.error()})}Ft.checkReportMissingProp=Fat;function qat({gen:t,data:e,it:{opts:r}},o,n){return(0,Qt.or)(...o.map(i=>(0,Qt.and)(fH(t,e,i,r.ownProperties),(0,Qt._)`${n} = ${i}`)))}Ft.checkMissingProp=qat;function Vat(t,e){t.setParams({missingProperty:e},!0),t.error()}Ft.reportMissingProp=Vat;function j$e(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Qt._)`Object.prototype.hasOwnProperty`})}Ft.hasPropFunc=j$e;function pH(t,e,r){return(0,Qt._)`${j$e(t)}.call(${e}, ${r})`}Ft.isOwnProperty=pH;function Gat(t,e,r,o){let n=(0,Qt._)`${e}${(0,Qt.getProperty)(r)} !== undefined`;return o?(0,Qt._)`${n} && ${pH(t,e,r)}`:n}Ft.propertyInData=Gat;function fH(t,e,r,o){let n=(0,Qt._)`${e}${(0,Qt.getProperty)(r)} === undefined`;return o?(0,Qt.or)(n,(0,Qt.not)(pH(t,e,r))):n}Ft.noPropertyInData=fH;function F$e(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Ft.allSchemaProperties=F$e;function Hat(t,e){return F$e(e).filter(r=>!(0,dH.alwaysValidSchema)(t,e[r]))}Ft.schemaProperties=Hat;function Kat({schemaCode:t,data:e,it:{gen:r,topSchemaRef:o,schemaPath:n,errorPath:i},it:s},a,c,u){let l=u?(0,Qt._)`${t}, ${e}, ${o}${n}`:e,d=[[Il.default.instancePath,(0,Qt.strConcat)(Il.default.instancePath,i)],[Il.default.parentData,s.parentData],[Il.default.parentDataProperty,s.parentDataProperty],[Il.default.rootData,Il.default.rootData]];s.opts.dynamicRef&&d.push([Il.default.dynamicAnchors,Il.default.dynamicAnchors]);let p=(0,Qt._)`${l}, ${r.object(...d)}`;return c!==Qt.nil?(0,Qt._)`${a}.call(${c}, ${p})`:(0,Qt._)`${a}(${p})`}Ft.callValidateCode=Kat;var Bat=(0,Qt._)`new RegExp`;function Zat({gen:t,it:{opts:e}},r){let o=e.unicodeRegExp?"u":"",{regExp:n}=e.code,i=n(r,o);return t.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,Qt._)`${n.code==="new RegExp"?Bat:(0,jat.useFunc)(t,n)}(${r}, ${o})`})}Ft.usePattern=Zat;function Wat(t){let{gen:e,data:r,keyword:o,it:n}=t,i=e.name("valid");if(n.allErrors){let a=e.let("valid",!0);return s(()=>e.assign(a,!1)),a}return e.var(i,!0),s(()=>e.break()),i;function s(a){let c=e.const("len",(0,Qt._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:o,dataProp:u,dataPropType:dH.Type.Num},i),e.if((0,Qt.not)(i),a)})}}Ft.validateArray=Wat;function Jat(t){let{gen:e,schema:r,keyword:o,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,dH.alwaysValidSchema)(n,c))&&!n.opts.unevaluated)return;let s=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:o,schemaProp:u,compositeRule:!0},a);e.assign(s,(0,Qt._)`${s} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,Qt.not)(s))})),t.result(s,()=>t.reset(),()=>t.error(!0))}Ft.validateUnion=Jat});var G$e=U(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.validateKeywordUsage=Ca.validSchemaType=Ca.funcKeywordCode=Ca.macroKeywordCode=void 0;var oo=je(),up=zc(),Xat=Ti(),Yat=Lb();function Qat(t,e){let{gen:r,keyword:o,schema:n,parentSchema:i,it:s}=t,a=e.macro.call(s.self,n,i,s),c=V$e(r,o,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:oo.nil,errSchemaPath:`${s.errSchemaPath}/${o}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Ca.macroKeywordCode=Qat;function ect(t,e){var r;let{gen:o,keyword:n,schema:i,parentSchema:s,$data:a,it:c}=t;rct(c,e);let u=!a&&e.compile?e.compile.call(c.self,i,s,c):e.validate,l=V$e(o,n,u),d=o.let("valid");t.block$data(d,p),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function p(){if(e.errors===!1)y(),e.modifying&&q$e(t),w(()=>t.error());else{let b=e.async?f():h();e.modifying&&q$e(t),w(()=>tct(t,b))}}function f(){let b=o.let("ruleErrs",null);return o.try(()=>y((0,oo._)`await `),S=>o.assign(d,!1).if((0,oo._)`${S} instanceof ${c.ValidationError}`,()=>o.assign(b,(0,oo._)`${S}.errors`),()=>o.throw(S))),b}function h(){let b=(0,oo._)`${l}.errors`;return o.assign(b,null),y(oo.nil),b}function y(b=e.async?(0,oo._)`await `:oo.nil){let S=c.opts.passContext?up.default.this:up.default.self,x=!("compile"in e&&!a||e.schema===!1);o.assign(d,(0,oo._)`${b}${(0,Xat.callValidateCode)(t,l,S,x)}`,e.modifying)}function w(b){var S;o.if((0,oo.not)((S=e.valid)!==null&&S!==void 0?S:d),b)}}Ca.funcKeywordCode=ect;function q$e(t){let{gen:e,data:r,it:o}=t;e.if(o.parentData,()=>e.assign(r,(0,oo._)`${o.parentData}[${o.parentDataProperty}]`))}function tct(t,e){let{gen:r}=t;r.if((0,oo._)`Array.isArray(${e})`,()=>{r.assign(up.default.vErrors,(0,oo._)`${up.default.vErrors} === null ? ${e} : ${up.default.vErrors}.concat(${e})`).assign(up.default.errors,(0,oo._)`${up.default.vErrors}.length`),(0,Yat.extendErrors)(t)},()=>t.error())}function rct({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function V$e(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,oo.stringify)(r)})}function nct(t,e,r=!1){return!e.length||e.some(o=>o==="array"?Array.isArray(t):o==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==o||r&&typeof t>"u")}Ca.validSchemaType=nct;function oct({schema:t,opts:e,self:r,errSchemaPath:o},n,i){if(Array.isArray(n.keyword)?!n.keyword.includes(i):n.keyword!==i)throw new Error("ajv implementation error");let s=n.dependencies;if(s?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${i}: ${s.join(",")}`);if(n.validateSchema&&!n.validateSchema(t[i])){let c=`keyword "${i}" value is invalid at path "${o}": `+r.errorsText(n.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Ca.validateKeywordUsage=oct});var K$e=U(Al=>{"use strict";Object.defineProperty(Al,"__esModule",{value:!0});Al.extendSubschemaMode=Al.extendSubschemaData=Al.getSubschema=void 0;var Oa=je(),H$e=mt();function ict(t,{keyword:e,schemaProp:r,schema:o,schemaPath:n,errSchemaPath:i,topSchemaRef:s}){if(e!==void 0&&o!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Oa._)`${t.schemaPath}${(0,Oa.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Oa._)`${t.schemaPath}${(0,Oa.getProperty)(e)}${(0,Oa.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,H$e.escapeFragment)(r)}`}}if(o!==void 0){if(n===void 0||i===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:o,schemaPath:n,topSchemaRef:s,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}Al.getSubschema=ict;function sct(t,e,{dataProp:r,dataPropType:o,data:n,dataTypes:i,propertyName:s}){if(n!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,p=a.let("data",(0,Oa._)`${e.data}${(0,Oa.getProperty)(r)}`,!0);c(p),t.errorPath=(0,Oa.str)`${u}${(0,H$e.getErrorPath)(r,o,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Oa._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(n!==void 0){let u=n instanceof Oa.Name?n:a.let("data",n,!0);c(u),s!==void 0&&(t.propertyName=s)}i&&(t.dataTypes=i);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}Al.extendSubschemaData=sct;function act(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:o,createErrors:n,allErrors:i}){o!==void 0&&(t.compositeRule=o),n!==void 0&&(t.createErrors=n),i!==void 0&&(t.allErrors=i),t.jtdDiscriminator=e,t.jtdMetadata=r}Al.extendSubschemaMode=act});var mH=U((gXt,B$e)=>{"use strict";B$e.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var o,n,i;if(Array.isArray(e)){if(o=e.length,o!=r.length)return!1;for(n=o;n--!==0;)if(!t(e[n],r[n]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(i=Object.keys(e),o=i.length,o!==Object.keys(r).length)return!1;for(n=o;n--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[n]))return!1;for(n=o;n--!==0;){var s=i[n];if(!t(e[s],r[s]))return!1}return!0}return e!==e&&r!==r}});var W$e=U((yXt,Z$e)=>{"use strict";var Pl=Z$e.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var o=typeof r=="function"?r:r.pre||function(){},n=r.post||function(){};ON(e,o,n,t,"",t)};Pl.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Pl.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Pl.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Pl.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function ON(t,e,r,o,n,i,s,a,c,u){if(o&&typeof o=="object"&&!Array.isArray(o)){e(o,n,i,s,a,c,u);for(var l in o){var d=o[l];if(Array.isArray(d)){if(l in Pl.arrayKeywords)for(var p=0;p<d.length;p++)ON(t,e,r,d[p],n+"/"+l+"/"+p,i,n,l,o,p)}else if(l in Pl.propsKeywords){if(d&&typeof d=="object")for(var f in d)ON(t,e,r,d[f],n+"/"+l+"/"+cct(f),i,n,l,o,f)}else(l in Pl.keywords||t.allKeys&&!(l in Pl.skipKeywords))&&ON(t,e,r,d,n+"/"+l,i,n,l,o)}r(o,n,i,s,a,c,u)}}function cct(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Fb=U(bo=>{"use strict";Object.defineProperty(bo,"__esModule",{value:!0});bo.getSchemaRefs=bo.resolveUrl=bo.normalizeId=bo._getFullPath=bo.getFullPath=bo.inlineRef=void 0;var uct=mt(),lct=mH(),dct=W$e(),pct=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function fct(t,e=!0){return typeof t=="boolean"?!0:e===!0?!hH(t):e?J$e(t)<=e:!1}bo.inlineRef=fct;var mct=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function hH(t){for(let e in t){if(mct.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(hH)||typeof r=="object"&&hH(r))return!0}return!1}function J$e(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!pct.has(r)&&(typeof t[r]=="object"&&(0,uct.eachItem)(t[r],o=>e+=J$e(o)),e===1/0))return 1/0}return e}function X$e(t,e="",r){r!==!1&&(e=Wh(e));let o=t.parse(e);return Y$e(t,o)}bo.getFullPath=X$e;function Y$e(t,e){return t.serialize(e).split("#")[0]+"#"}bo._getFullPath=Y$e;var hct=/#\/?$/;function Wh(t){return t?t.replace(hct,""):""}bo.normalizeId=Wh;function gct(t,e,r){return r=Wh(r),t.resolve(e,r)}bo.resolveUrl=gct;var yct=/^[a-z_][-a-z0-9._]*$/i;function vct(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:o}=this.opts,n=Wh(t[r]||e),i={"":n},s=X$e(o,n,!1),a={},c=new Set;return dct(t,{allKeys:!0},(d,p,f,h)=>{if(h===void 0)return;let y=s+p,w=i[h];typeof d[r]=="string"&&(w=b.call(this,d[r])),S.call(this,d.$anchor),S.call(this,d.$dynamicAnchor),i[p]=w;function b(x){let R=this.opts.uriResolver.resolve;if(x=Wh(w?R(w,x):x),c.has(x))throw l(x);c.add(x);let T=this.refs[x];return typeof T=="string"&&(T=this.refs[T]),typeof T=="object"?u(d,T.schema,x):x!==Wh(y)&&(x[0]==="#"?(u(d,a[x],x),a[x]=d):this.refs[x]=y),x}function S(x){if(typeof x=="string"){if(!yct.test(x))throw new Error(`invalid anchor "${x}"`);b.call(this,`#${x}`)}}}),a;function u(d,p,f){if(p!==void 0&&!lct(d,p))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}bo.getSchemaRefs=vct});var Gb=U(kl=>{"use strict";Object.defineProperty(kl,"__esModule",{value:!0});kl.getData=kl.KeywordCxt=kl.validateFunctionCode=void 0;var nRe=C$e(),Q$e=jb(),yH=aH(),DN=jb(),wct=L$e(),Vb=G$e(),gH=K$e(),de=je(),Re=zc(),_ct=Fb(),Mc=mt(),qb=Lb();function bct(t){if(sRe(t)&&(aRe(t),iRe(t))){Ect(t);return}oRe(t,()=>(0,nRe.topBoolOrEmptySchema)(t))}kl.validateFunctionCode=bct;function oRe({gen:t,validateName:e,schema:r,schemaEnv:o,opts:n},i){n.code.es5?t.func(e,(0,de._)`${Re.default.data}, ${Re.default.valCxt}`,o.$async,()=>{t.code((0,de._)`"use strict"; ${eRe(r,n)}`),xct(t,n),t.code(i)}):t.func(e,(0,de._)`${Re.default.data}, ${Sct(n)}`,o.$async,()=>t.code(eRe(r,n)).code(i))}function Sct(t){return(0,de._)`{${Re.default.instancePath}="", ${Re.default.parentData}, ${Re.default.parentDataProperty}, ${Re.default.rootData}=${Re.default.data}${t.dynamicRef?(0,de._)`, ${Re.default.dynamicAnchors}={}`:de.nil}}={}`}function xct(t,e){t.if(Re.default.valCxt,()=>{t.var(Re.default.instancePath,(0,de._)`${Re.default.valCxt}.${Re.default.instancePath}`),t.var(Re.default.parentData,(0,de._)`${Re.default.valCxt}.${Re.default.parentData}`),t.var(Re.default.parentDataProperty,(0,de._)`${Re.default.valCxt}.${Re.default.parentDataProperty}`),t.var(Re.default.rootData,(0,de._)`${Re.default.valCxt}.${Re.default.rootData}`),e.dynamicRef&&t.var(Re.default.dynamicAnchors,(0,de._)`${Re.default.valCxt}.${Re.default.dynamicAnchors}`)},()=>{t.var(Re.default.instancePath,(0,de._)`""`),t.var(Re.default.parentData,(0,de._)`undefined`),t.var(Re.default.parentDataProperty,(0,de._)`undefined`),t.var(Re.default.rootData,Re.default.data),e.dynamicRef&&t.var(Re.default.dynamicAnchors,(0,de._)`{}`)})}function Ect(t){let{schema:e,opts:r,gen:o}=t;oRe(t,()=>{r.$comment&&e.$comment&&uRe(t),Pct(t),o.let(Re.default.vErrors,null),o.let(Re.default.errors,0),r.unevaluated&&$ct(t),cRe(t),Cct(t)})}function $ct(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,de._)`${r}.evaluated`),e.if((0,de._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,de._)`${t.evaluated}.props`,(0,de._)`undefined`)),e.if((0,de._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,de._)`${t.evaluated}.items`,(0,de._)`undefined`))}function eRe(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,de._)`/*# sourceURL=${r} */`:de.nil}function Rct(t,e){if(sRe(t)&&(aRe(t),iRe(t))){Ict(t,e);return}(0,nRe.boolOrEmptySchema)(t,e)}function iRe({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function sRe(t){return typeof t.schema!="boolean"}function Ict(t,e){let{schema:r,gen:o,opts:n}=t;n.$comment&&r.$comment&&uRe(t),kct(t),Tct(t);let i=o.const("_errs",Re.default.errors);cRe(t,i),o.var(e,(0,de._)`${i} === ${Re.default.errors}`)}function aRe(t){(0,Mc.checkUnknownRules)(t),Act(t)}function cRe(t,e){if(t.opts.jtd)return tRe(t,[],!1,e);let r=(0,Q$e.getSchemaTypes)(t.schema),o=(0,Q$e.coerceAndCheckDataType)(t,r);tRe(t,r,!o,e)}function Act(t){let{schema:e,errSchemaPath:r,opts:o,self:n}=t;e.$ref&&o.ignoreKeywordsWithRef&&(0,Mc.schemaHasRulesButRef)(e,n.RULES)&&n.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function Pct(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Mc.checkStrictMode)(t,"default is ignored in the schema root")}function kct(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,_ct.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Tct(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function uRe({gen:t,schemaEnv:e,schema:r,errSchemaPath:o,opts:n}){let i=r.$comment;if(n.$comment===!0)t.code((0,de._)`${Re.default.self}.logger.log(${i})`);else if(typeof n.$comment=="function"){let s=(0,de.str)`${o}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,de._)`${Re.default.self}.opts.$comment(${i}, ${s}, ${a}.schema)`)}}function Cct(t){let{gen:e,schemaEnv:r,validateName:o,ValidationError:n,opts:i}=t;r.$async?e.if((0,de._)`${Re.default.errors} === 0`,()=>e.return(Re.default.data),()=>e.throw((0,de._)`new ${n}(${Re.default.vErrors})`)):(e.assign((0,de._)`${o}.errors`,Re.default.vErrors),i.unevaluated&&Oct(t),e.return((0,de._)`${Re.default.errors} === 0`))}function Oct({gen:t,evaluated:e,props:r,items:o}){r instanceof de.Name&&t.assign((0,de._)`${e}.props`,r),o instanceof de.Name&&t.assign((0,de._)`${e}.items`,o)}function tRe(t,e,r,o){let{gen:n,schema:i,data:s,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(i.$ref&&(c.ignoreKeywordsWithRef||!(0,Mc.schemaHasRulesButRef)(i,l))){n.block(()=>dRe(t,"$ref",l.all.$ref.definition));return}c.jtd||Dct(t,e),n.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,yH.shouldUseGroup)(i,p)&&(p.type?(n.if((0,DN.checkDataType)(p.type,s,c.strictNumbers)),rRe(t,p),e.length===1&&e[0]===p.type&&r&&(n.else(),(0,DN.reportTypeError)(t)),n.endIf()):rRe(t,p),a||n.if((0,de._)`${Re.default.errors} === ${o||0}`))}}function rRe(t,e){let{gen:r,schema:o,opts:{useDefaults:n}}=t;n&&(0,wct.assignDefaults)(t,e.type),r.block(()=>{for(let i of e.rules)(0,yH.shouldUseRule)(o,i)&&dRe(t,i.keyword,i.definition,e.type)})}function Dct(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Nct(t,e),t.opts.allowUnionTypes||zct(t,e),Mct(t,t.dataTypes))}function Nct(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{lRe(t.dataTypes,r)||vH(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),Lct(t,e)}}function zct(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&vH(t,"use allowUnionTypes to allow union type keyword")}function Mct(t,e){let r=t.self.RULES.all;for(let o in r){let n=r[o];if(typeof n=="object"&&(0,yH.shouldUseRule)(t.schema,n)){let{type:i}=n.definition;i.length&&!i.some(s=>Uct(e,s))&&vH(t,`missing type "${i.join(",")}" for keyword "${o}"`)}}}function Uct(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function lRe(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function Lct(t,e){let r=[];for(let o of t.dataTypes)lRe(e,o)?r.push(o):e.includes("integer")&&o==="number"&&r.push("integer");t.dataTypes=r}function vH(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Mc.checkStrictMode)(t,e,t.opts.strictTypes)}var NN=class{constructor(e,r,o){if((0,Vb.validateKeywordUsage)(e,r,o),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=o,this.data=e.data,this.schema=e.schema[o],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Mc.schemaRefOrVal)(e,this.schema,o,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",pRe(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Vb.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${o} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",Re.default.errors))}result(e,r,o){this.failResult((0,de.not)(e),r,o)}failResult(e,r,o){this.gen.if(e),o?o():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,de.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,de._)`${r} !== undefined && (${(0,de.or)(this.invalid$data(),e)})`)}error(e,r,o){if(r){this.setParams(r),this._error(e,o),this.setParams({});return}this._error(e,o)}_error(e,r){(e?qb.reportExtraError:qb.reportError)(this,this.def.error,r)}$dataError(){(0,qb.reportError)(this,this.def.$dataError||qb.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,qb.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,o=de.nil){this.gen.block(()=>{this.check$data(e,o),r()})}check$data(e=de.nil,r=de.nil){if(!this.$data)return;let{gen:o,schemaCode:n,schemaType:i,def:s}=this;o.if((0,de.or)((0,de._)`${n} === undefined`,r)),e!==de.nil&&o.assign(e,!0),(i.length||s.validateSchema)&&(o.elseIf(this.invalid$data()),this.$dataError(),e!==de.nil&&o.assign(e,!1)),o.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:o,def:n,it:i}=this;return(0,de.or)(s(),a());function s(){if(o.length){if(!(r instanceof de.Name))throw new Error("ajv implementation error");let c=Array.isArray(o)?o:[o];return(0,de._)`${(0,DN.checkDataTypes)(c,r,i.opts.strictNumbers,DN.DataType.Wrong)}`}return de.nil}function a(){if(n.validateSchema){let c=e.scopeValue("validate$data",{ref:n.validateSchema});return(0,de._)`!${c}(${r})`}return de.nil}}subschema(e,r){let o=(0,gH.getSubschema)(this.it,e);(0,gH.extendSubschemaData)(o,this.it,e),(0,gH.extendSubschemaMode)(o,e);let n={...this.it,...o,items:void 0,props:void 0};return Rct(n,r),n}mergeEvaluated(e,r){let{it:o,gen:n}=this;o.opts.unevaluated&&(o.props!==!0&&e.props!==void 0&&(o.props=Mc.mergeEvaluated.props(n,e.props,o.props,r)),o.items!==!0&&e.items!==void 0&&(o.items=Mc.mergeEvaluated.items(n,e.items,o.items,r)))}mergeValidEvaluated(e,r){let{it:o,gen:n}=this;if(o.opts.unevaluated&&(o.props!==!0||o.items!==!0))return n.if(r,()=>this.mergeEvaluated(e,de.Name)),!0}};kl.KeywordCxt=NN;function dRe(t,e,r,o){let n=new NN(t,r,e);"code"in r?r.code(n,o):n.$data&&r.validate?(0,Vb.funcKeywordCode)(n,r):"macro"in r?(0,Vb.macroKeywordCode)(n,r):(r.compile||r.validate)&&(0,Vb.funcKeywordCode)(n,r)}var jct=/^\/(?:[^~]|~0|~1)*$/,Fct=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function pRe(t,{dataLevel:e,dataNames:r,dataPathArr:o}){let n,i;if(t==="")return Re.default.rootData;if(t[0]==="/"){if(!jct.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);n=t,i=Re.default.rootData}else{let u=Fct.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(n=u[2],n==="#"){if(l>=e)throw new Error(c("property/index",l));return o[e-l]}if(l>e)throw new Error(c("data",l));if(i=r[e-l],!n)return i}let s=i,a=n.split("/");for(let u of a)u&&(i=(0,de._)`${i}${(0,de.getProperty)((0,Mc.unescapeJsonPointer)(u))}`,s=(0,de._)`${s} && ${i}`);return s;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}kl.getData=pRe});var zN=U(_H=>{"use strict";Object.defineProperty(_H,"__esModule",{value:!0});var wH=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};_H.default=wH});var Hb=U(xH=>{"use strict";Object.defineProperty(xH,"__esModule",{value:!0});var bH=Fb(),SH=class extends Error{constructor(e,r,o,n){super(n||`can't resolve reference ${o} from id ${r}`),this.missingRef=(0,bH.resolveUrl)(e,r,o),this.missingSchema=(0,bH.normalizeId)((0,bH.getFullPath)(e,this.missingRef))}};xH.default=SH});var UN=U(Ci=>{"use strict";Object.defineProperty(Ci,"__esModule",{value:!0});Ci.resolveSchema=Ci.getCompilingSchema=Ci.resolveRef=Ci.compileSchema=Ci.SchemaEnv=void 0;var $s=je(),qct=zN(),lp=zc(),Rs=Fb(),fRe=mt(),Vct=Gb(),Jh=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let o;typeof e.schema=="object"&&(o=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,Rs.normalizeId)(o?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=o?.$async,this.refs={}}};Ci.SchemaEnv=Jh;function $H(t){let e=mRe.call(this,t);if(e)return e;let r=(0,Rs.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:o,lines:n}=this.opts.code,{ownProperties:i}=this.opts,s=new $s.CodeGen(this.scope,{es5:o,lines:n,ownProperties:i}),a;t.$async&&(a=s.scopeValue("Error",{ref:qct.default,code:(0,$s._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");t.validateName=c;let u={gen:s,allErrors:this.opts.allErrors,data:lp.default.data,parentData:lp.default.parentData,parentDataProperty:lp.default.parentDataProperty,dataNames:[lp.default.data],dataPathArr:[$s.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,$s.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:$s.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,$s._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,Vct.validateFunctionCode)(u),s.optimize(this.opts.code.optimize);let d=s.toString();l=`${s.scopeRefs(lp.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let f=new Function(`${lp.default.self}`,`${lp.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:d,scopeValues:s._values}),this.opts.unevaluated){let{props:h,items:y}=u;f.evaluated={props:h instanceof $s.Name?void 0:h,items:y instanceof $s.Name?void 0:y,dynamicProps:h instanceof $s.Name,dynamicItems:y instanceof $s.Name},f.source&&(f.source.evaluated=(0,$s.stringify)(f.evaluated))}return t.validate=f,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}Ci.compileSchema=$H;function Gct(t,e,r){var o;r=(0,Rs.resolveUrl)(this.opts.uriResolver,e,r);let n=t.refs[r];if(n)return n;let i=Bct.call(this,t,r);if(i===void 0){let s=(o=t.localRefs)===null||o===void 0?void 0:o[r],{schemaId:a}=this.opts;s&&(i=new Jh({schema:s,schemaId:a,root:t,baseId:e}))}if(i!==void 0)return t.refs[r]=Hct.call(this,i)}Ci.resolveRef=Gct;function Hct(t){return(0,Rs.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:$H.call(this,t)}function mRe(t){for(let e of this._compilations)if(Kct(e,t))return e}Ci.getCompilingSchema=mRe;function Kct(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Bct(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||MN.call(this,t,e)}function MN(t,e){let r=this.opts.uriResolver.parse(e),o=(0,Rs._getFullPath)(this.opts.uriResolver,r),n=(0,Rs.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&o===n)return EH.call(this,r,t);let i=(0,Rs.normalizeId)(o),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let a=MN.call(this,t,s);return typeof a?.schema!="object"?void 0:EH.call(this,r,a)}if(typeof s?.schema=="object"){if(s.validate||$H.call(this,s),i===(0,Rs.normalizeId)(e)){let{schema:a}=s,{schemaId:c}=this.opts,u=a[c];return u&&(n=(0,Rs.resolveUrl)(this.opts.uriResolver,n,u)),new Jh({schema:a,schemaId:c,root:t,baseId:n})}return EH.call(this,r,s)}}Ci.resolveSchema=MN;var Zct=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function EH(t,{baseId:e,schema:r,root:o}){var n;if(((n=t.fragment)===null||n===void 0?void 0:n[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,fRe.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!Zct.has(a)&&u&&(e=(0,Rs.resolveUrl)(this.opts.uriResolver,e,u))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,fRe.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Rs.resolveUrl)(this.opts.uriResolver,e,r.$ref);i=MN.call(this,o,a)}let{schemaId:s}=this.opts;if(i=i||new Jh({schema:r,schemaId:s,root:o,baseId:e}),i.schema!==i.root.schema)return i}});var hRe=U((xXt,Wct)=>{Wct.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var TH=U((EXt,SRe)=>{"use strict";var Jct=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),IH=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),Xct=RegExp.prototype.test.bind(/^\d*$/u),dp=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),AH=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),yRe=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),PH=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),Yct=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),So=new Array(256);{let t="0123456789ABCDEF";for(let e=0;e<256;e++)So[e]="%"+t[e>>4]+t[e&15]}function Ln(t){return t<2048?So[192|t>>6]+So[128|t&63]:t<65536?So[224|t>>12]+So[128|t>>6&63]+So[128|t&63]:So[240|t>>18]+So[128|t>>12&63]+So[128|t>>6&63]+So[128|t&63]}function Qct(t){let e="",r=0,o=0;for(o=0;o<t.length;o++)if(r=t[o].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[o];break}for(o+=1;o<t.length;o++){if(r=t[o].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[o]}return e}var eut=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),tut=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),rut=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),nut=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function out(t){if(t.length===0)return!1;for(let e=0;e<t.length;e++)if(!rut(t[e])){if(t[e]==="%"&&e+2<t.length&&dp(t.slice(e+1,e+3))){e+=2;continue}return!1}return!0}function gRe(t){let e=-1,r=0,o=-1,n=0;for(let a=0;a<t.length;a++)t[a]==="0"?(o===-1&&(o=a),n++,n>r&&(r=n,e=o)):(o=-1,n=0);if(r<2)return t.join(":");let i=t.slice(0,e).join(":"),s=t.slice(e+r).join(":");return i+"::"+s}function iut(t){let e=t.indexOf("::");if(e!==-1&&t.indexOf("::",e+1)!==-1)return;let r=e===-1?t.split(":"):t.slice(0,e).split(":"),o=e===-1?[]:t.slice(e+2).split(":");e!==-1&&(r.length===1&&r[0]===""&&(r.length=0),o.length===1&&o[0]===""&&(o.length=0));let n=r.concat(o),i=0;for(let a=0;a<n.length;a++){let c=n[a];if(c==="")return;if(c.indexOf(".")!==-1){if(a!==n.length-1||e!==-1&&o.length===0||!IH(c))return;i+=2;continue}if(!eut(c))return;n[a]=parseInt(c,16).toString(16),i++}if(e===-1)return i!==8?void 0:gRe(n);if(i>=8)return;let s=n.slice(0,r.length);for(let a=i;a<8;a++)s.push("0");for(let a=r.length;a<n.length;a++)s.push(n[a]);return gRe(s)}function RH(t){let e=t[0]==="["&&t[t.length-1]==="]";if((t[0]==="["||t[t.length-1]==="]")&&!e)return{host:t,isIPV6:!1,error:!0};let o=e?t.slice(1,-1):t;if(e&&tut(o))return o=o.toLowerCase(),{host:`[${o}]`,escapedHost:o,isIPV6:!1,isIPVFuture:!0};if(sut(o,":")<2)return{host:t,isIPV6:!1,error:e};let n="",i=o.indexOf("%");if(i!==-1){let a=o.slice(i,i+3).toLowerCase()==="%25"?3:1;if(n=o.slice(i+a),!out(n))return{host:t,isIPV6:!1,error:!0};o=o.slice(0,i)}let s=iut(o);return s===void 0?{host:t,isIPV6:!1,error:!0}:{host:s+(n?"%"+n:""),escapedHost:s+(n?"%25"+n:""),isIPV6:!0}}function sut(t,e){let r=0;for(let o=0;o<t.length;o++)t[o]===e&&r++;return r}function aut(t){let e=t,r=[],o=-1,n=0;for(;n=e.length;){if(n===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(n===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(n===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((o=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,o)),e=e.slice(o)}return r.join("")}var cut={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},uut=/[@/?#:]/g,lut=/[@/?#]/g;function vRe(t,e){let r=e?lut:uut;return r.lastIndex=0,t.replace(r,o=>cut[o])}function wRe(t,e=!1){if(t.indexOf("%")===-1)return t;let r="";for(let o=0;o<t.length;o++){if(t[o]==="%"&&o+2<t.length){let n=t.slice(o+1,o+3);if(dp(n)){let i=n.toUpperCase(),s=String.fromCharCode(parseInt(i,16));e&&AH(s)?r+=s:r+="%"+i,o+=2;continue}}r+=t[o]}return r}function dut(t){let e="";for(let r=0;r<t.length;r++){let o=t[r];if(o==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(dp(n)){let i=n.toUpperCase(),s=String.fromCharCode(parseInt(i,16));s!=="."&&AH(s)?e+=s:e+="%"+i,r+=2;continue}}if(yRe(o))e+=o;else{let n=t.charCodeAt(r);if(n<128)e+=bRe(n)?o:So[n];else if(n<55296||n>57343)e+=Ln(n);else if(n<=56319&&r+1<t.length){let i=t.charCodeAt(r+1);i>=56320&&i<=57343?(e+=Ln(65536+(n-55296<<10)+(i-56320)),r++):e+=Ln(65533)}else e+=Ln(65533)}}return e}function put(t,e=!1){let r="",o=e&&t[0]!=="/";for(let n=0;n<t.length;n++){let i=t[n];if(i==="%"&&n+2<t.length){let s=t.slice(n+1,n+3);if(dp(s)){r+="%"+s.toUpperCase(),n+=2;continue}}if(i==="/"&&(o=!1),yRe(i)&&(i!==":"||!o))r+=i;else{let s=t.charCodeAt(n);if(s<128)r+=So[s];else if(s<55296||s>57343)r+=Ln(s);else if(s<=56319&&n+1<t.length){let a=t.charCodeAt(n+1);a>=56320&&a<=57343?(r+=Ln(65536+(s-55296<<10)+(a-56320)),n++):r+=Ln(65533)}else r+=Ln(65533)}}return r}function kH(t,e){let r="";for(let o=0;o<t.length;o++){let n=t[o];if(n==="%"&&o+2<t.length){let i=t.slice(o+1,o+3);if(dp(i)){r+="%"+i.toUpperCase(),o+=2;continue}}if(e(n))r+=n;else{let i=t.charCodeAt(o);if(i<128)r+=So[i];else if(i<55296||i>57343)r+=Ln(i);else if(i<=56319&&o+1<t.length){let s=t.charCodeAt(o+1);s>=56320&&s<=57343?(r+=Ln(65536+(i-55296<<10)+(s-56320)),o++):r+=Ln(65533)}else r+=Ln(65533)}}return r}function _Re(t){return kH(t,Yct)}function fut(t){return kH(t,PH)}function mut(t){return kH(t,PH)}function bRe(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||t===42||t===43||t===45||t===46||t===47||t===64||t===95}function hut(t){let e="";for(let r=0;r<t.length;r++){let o=t[r];if(o==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(dp(n)){let i=n.toUpperCase(),s=String.fromCharCode(parseInt(i,16));AH(s)?e+=s:e+="%"+i,r+=2;continue}}if(PH(o))e+=o;else{let n=t.charCodeAt(r);if(n<128)e+=bRe(n)?o:So[n];else if(n<55296||n>57343)e+=Ln(n);else if(n<=56319&&r+1<t.length){let i=t.charCodeAt(r+1);i>=56320&&i<=57343?(e+=Ln(65536+(n-55296<<10)+(i-56320)),r++):e+=Ln(65533)}else e+=Ln(65533)}}return e}function gut(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let o=t.slice(r+1,r+3);if(dp(o)){e+="%"+o.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function yut(t){let e=[];if(t.userinfo!==void 0&&(e.push(_Re(t.userinfo)),e.push("@")),t.host!==void 0){let r=t.host;if(!IH(r)){let o=RH(r);o.isIPV6!==!0&&o.isIPVFuture!==!0&&(r=wRe(r,!0),o=RH(r)),o.isIPV6===!0||o.isIPVFuture===!0?r=`[${o.escapedHost}]`:r=vRe(r,!1)}e.push(r)}if(typeof t.port=="number"||typeof t.port=="string"){let r=String(t.port);if(!Xct(r))throw new TypeError("URI port is malformed.");e.push(":"),e.push(r)}return e.length?e.join(""):void 0}SRe.exports={nonSimpleDomain:nut,recomposeAuthority:yut,reescapeHostDelimiters:vRe,normalizePercentEncoding:wRe,normalizePathEncoding:dut,serializePathEncoding:put,normalizeQueryFragmentEncoding:hut,encodeUserinfo:_Re,encodeQuery:fut,encodeFragment:mut,escapePreservingEscapes:gut,removeDotSegments:aut,isIPv4:IH,isUUID:Jct,normalizeIPv6:RH,stringArrayToHexStripped:Qct}});var IRe=U(($Xt,RRe)=>{"use strict";var{isUUID:vut}=TH(),wut=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,_ut=["http","https","ws","wss","urn","urn:uuid"];function but(t){return _ut.indexOf(t)!==-1}function CH(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function xRe(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function ERe(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function Sut(t){return t.secure=CH(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function xut(t){if((t.port===(CH(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let e=t.resourceName.indexOf("?"),r=e===-1?t.resourceName:t.resourceName.slice(0,e);t.path=r&&r!=="/"?r:void 0,t.query=e===-1?void 0:t.resourceName.slice(e+1),t.resourceName=void 0}return t.fragment=void 0,t}function Eut(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(wut);if(r&&r[0]===t.path){let o=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let n=`${o}:${e.nid||t.nid}`,i=OH(n);t.path=void 0,i&&(t=i.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function $ut(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",o=t.nid.toLowerCase(),n=`${r}:${e.nid||o}`,i=OH(n);i&&(t=i.serialize(t,e));let s=t,a=t.nss;return s.path=`${o||e.nid}:${a}`,e.skipEscape=!0,s}function Rut(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!vut(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function Iut(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var $Re={scheme:"http",domainHost:!0,parse:xRe,serialize:ERe},Aut={scheme:"https",domainHost:$Re.domainHost,parse:xRe,serialize:ERe},LN={scheme:"ws",domainHost:!0,parse:Sut,serialize:xut},Put={scheme:"wss",domainHost:LN.domainHost,parse:LN.parse,serialize:LN.serialize},kut={scheme:"urn",parse:Eut,serialize:$ut,skipNormalize:!0},Tut={scheme:"urn:uuid",parse:Rut,serialize:Iut,skipNormalize:!0},jN={http:$Re,https:Aut,ws:LN,wss:Put,urn:kut,"urn:uuid":Tut};Object.setPrototypeOf(jN,null);function OH(t){return t&&(jN[t]||jN[t.toLowerCase()])||void 0}RRe.exports={wsIsSecure:CH,SCHEMES:jN,isValidSchemeName:but,getSchemeHandler:OH}});var jRe=U((RXt,VN)=>{"use strict";var{normalizeIPv6:CRe,removeDotSegments:Bb,recomposeAuthority:Cut,normalizePercentEncoding:DH,normalizePathEncoding:Out,serializePathEncoding:ARe,normalizeQueryFragmentEncoding:PRe,encodeQuery:Dut,encodeFragment:Nut,reescapeHostDelimiters:zut,isIPv4:ORe,nonSimpleDomain:Mut}=TH(),{SCHEMES:DRe,getSchemeHandler:NH}=IRe(),NRe=/^[A-Za-z][A-Za-z0-9+.-]*$/u,zRe="URI scheme is malformed.";function kRe(t){let e=unescape(String(t));if(!NRe.test(e))throw new TypeError(zRe);return e}function Uut(t,e){return typeof t=="string"?t=Kut(t,e):typeof t=="object"&&(t=qN(pp(t,e),e)),t}function Lut(t,e,r){let o=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:n,malformedAuthorityOrPort:i,malformedPercentEncoding:s,malformedSchemeSpecific:a,malformedHost:c,malformedScheme:u}=FN(t,o),{parsed:l,malformedAuthorityOrPort:d,malformedPercentEncoding:p,malformedSchemeSpecific:f,malformedHost:h,malformedScheme:y}=FN(e,o);if(i||d||s||p||a||f||c||h||u||y)throw new Error(n.error||l.error||"URI is malformed.");let w=MRe(n,l,o,!0),b=NH(r&&r.scheme||w.scheme),S=w.host,x=S!==void 0&&S!==""&&(ORe(S)||CRe(S).isIPV6);URe(w,r||{},b,x);let R=S&&S.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(S);if(w.error&&!R)throw new Error(w.error);return o.skipEscape=!0,pp(w,o)}function MRe(t,e,r,o){let n={};return o||(t=qN(pp(t,r),r),e=qN(pp(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(n.scheme=e.scheme,n.userinfo=e.userinfo,n.host=e.host,n.port=e.port,n.path=Bb(e.path||""),n.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(n.userinfo=e.userinfo,n.host=e.host,n.port=e.port,n.path=Bb(e.path||""),n.query=e.query):(e.path?(e.path[0]==="/"?n.path=Bb(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?n.path="/"+e.path:t.path?n.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:n.path=e.path,n.path=Bb(n.path)),n.query=e.query):(n.path=t.path,e.query!==void 0?n.query=e.query:n.query=t.query),n.userinfo=t.userinfo,n.host=t.host,n.port=t.port),n.scheme=t.scheme),n.fragment=e.fragment,n}function jut(t,e,r){let o=TRe(t,r),n=TRe(e,r);return o!==void 0&&n!==void 0&&o===n}function pp(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},o=Object.assign({},e),n=[];r.scheme&&(r.scheme=kRe(r.scheme));let i=NH(o.scheme||r.scheme);i&&i.serialize&&i.serialize(r,o);let s=r.userinfo!==void 0||r.host!==void 0||r.port!==void 0,a=!o.skipEscape&&r.scheme===void 0&&!s;r.path!==void 0&&(o.skipEscape?r.path=DH(r.path):r.path=ARe(r.path,a)),o.reference!=="suffix"&&r.scheme&&(r.scheme=kRe(r.scheme),n.push(r.scheme,":"));let c=Cut(r);if(c!==void 0&&(o.reference!=="suffix"&&n.push("//"),n.push(c),r.path&&r.path[0]!=="/"&&n.push("/")),r.path!==void 0){let u=r.path;!o.absolutePath&&(!i||!i.absolutePath)&&(u=Bb(u)),a&&(u=ARe(u,!0)),c===void 0&&u[0]==="/"&&u[1]==="/"&&(u="/%2F"+u.slice(2)),n.push(u)}return r.query!==void 0&&n.push("?",Dut(r.query)),r.fragment!==void 0&&n.push("#",Nut(r.fragment)),n.join("")}var Fut=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,qut=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,Vut=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function Gut(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function Kb(t){if(t===void 0)return!1;let e=t.indexOf("%");for(;e!==-1;){if(e+2>=t.length||!/^[\da-f]{2}$/iu.test(t.slice(e+1,e+3)))return!0;e=t.indexOf("%",e+3)}return!1}function zH(t){return t[0]==="["&&t[t.length-1]==="]"}function Hut(t){let e=t[4];return Kb(t[3])||e!==void 0&&!zH(e)&&Kb(e)||Kb(t[6])||Kb(t[7])||Kb(t[8])}function URe(t,e,r,o){if(!e.unicodeSupport&&(!r||!r.unicodeSupport)&&t.host&&!zH(t.host)&&(e.domainHost||r&&r.domainHost)&&o===!1&&Mut(t.host))try{t.host=new URL("http://"+t.host).hostname}catch(n){return t.error=t.error||"Host's domain name can not be converted to ASCII: "+n,!0}return!1}function FN(t,e){let r=Object.assign({},e),o={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},n=!1,i=!1,s=!1,a=!1,c=!1,u=!1,l=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let d=t.match(qut);d!==null&&d[1].indexOf("\\")!==-1&&(o.error="URI authority must not contain a literal backslash.",n=!0);let p=t.match(Vut);if(p!==null){let h=p[1],y=h.replace(/[\t\n\r]/g,"");y.length>=2&&(y.slice(0,2)!=="//"?(o.error=o.error||"URI authority must not contain a literal backslash.",n=!0):h.length!==y.length&&(o.error=o.error||"URI authority introducer must not contain whitespace.",n=!0))}let f=t.match(Fut);if(f){if(o.scheme=f[1],o.userinfo=f[3],o.host=f[4],o.port=parseInt(f[5],10),o.path=f[6]||"",o.query=f[7],o.fragment=f[8],o.scheme!==void 0){let w=unescape(o.scheme);NRe.test(w)?o.scheme=w.toLowerCase():(o.error=o.error||zRe,u=!0)}i=Hut(f),i&&(o.error=o.error||"URI contains malformed percent-encoding."),isNaN(o.port)&&(o.port=f[5]);let h=Gut(o,f);if(h!==void 0&&(o.error=o.error||h,n=!0),o.host)if(ORe(o.host)===!1){let b=zH(o.host),S=o.host.indexOf("[")!==-1||o.host.indexOf("]")!==-1,x=CRe(o.host);l=x.isIPV6||x.isIPVFuture===!0,c=S&&(!b||x.error===!0),o.host=l?x.host:x.host.toLowerCase(),c&&(o.error=o.error||"URI host is malformed.",n=!0)}else l=!0;o.scheme===void 0&&o.userinfo===void 0&&o.host===void 0&&o.port===void 0&&o.query===void 0&&!o.path?o.reference="same-document":o.scheme===void 0?o.reference="relative":o.fragment===void 0?o.reference="absolute":o.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==o.reference&&(o.error=o.error||"URI is not a "+r.reference+" reference.");let y=NH(r.scheme||o.scheme);if(c||(a=URe(o,r,y,l)),t.indexOf("%")!==-1&&o.host!==void 0&&!c){let w=l?o.host:DH(o.host,!0);l||(w=DH(w.toLowerCase())),o.host=zut(w,l)}(!y||y&&!y.skipNormalize)&&(o.path&&(o.path=Out(o.path)),o.query&&(o.query=PRe(o.query)),o.fragment&&(o.fragment=PRe(o.fragment))),y&&y.parse&&(y.parse(o,r),y===DRe.urn&&o.nid===void 0&&(s=!0))}else o.error=o.error||"URI can not be parsed.";return{parsed:o,malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:s,malformedHost:a,malformedScheme:u}}function qN(t,e){return FN(t,e).parsed}function Kut(t,e){return LRe(t,e).normalized}function LRe(t,e){let{parsed:r,malformedAuthorityOrPort:o,malformedPercentEncoding:n,malformedSchemeSpecific:i,malformedHost:s,malformedScheme:a}=FN(t,e);return{normalized:o||n||i||s||a?t:pp(r,e),malformedAuthorityOrPort:o,malformedPercentEncoding:n,malformedSchemeSpecific:i,malformedHost:s,malformedScheme:a}}function TRe(t,e){if(typeof t!="string"&&typeof t!="object")return;let r;try{r=typeof t=="string"?t:pp(t,e)}catch{return}let{normalized:o,malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:s,malformedHost:a,malformedScheme:c}=LRe(r,e);return n||i||s||a||c?void 0:o}var MH={SCHEMES:DRe,normalize:Uut,resolve:Lut,resolveComponent:MRe,equal:jut,serialize:pp,parse:qN};VN.exports=MH;VN.exports.default=MH;VN.exports.fastUri=MH});var qRe=U(UH=>{"use strict";Object.defineProperty(UH,"__esModule",{value:!0});var FRe=jRe();FRe.code='require("ajv/dist/runtime/uri").default';UH.default=FRe});var JRe=U(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.CodeGen=yn.Name=yn.nil=yn.stringify=yn.str=yn._=yn.KeywordCxt=void 0;var But=Gb();Object.defineProperty(yn,"KeywordCxt",{enumerable:!0,get:function(){return But.KeywordCxt}});var Xh=je();Object.defineProperty(yn,"_",{enumerable:!0,get:function(){return Xh._}});Object.defineProperty(yn,"str",{enumerable:!0,get:function(){return Xh.str}});Object.defineProperty(yn,"stringify",{enumerable:!0,get:function(){return Xh.stringify}});Object.defineProperty(yn,"nil",{enumerable:!0,get:function(){return Xh.nil}});Object.defineProperty(yn,"Name",{enumerable:!0,get:function(){return Xh.Name}});Object.defineProperty(yn,"CodeGen",{enumerable:!0,get:function(){return Xh.CodeGen}});var Zut=zN(),BRe=Hb(),Wut=sH(),Zb=UN(),Jut=je(),Wb=Fb(),GN=jb(),jH=mt(),VRe=hRe(),Xut=qRe(),ZRe=(t,e)=>new RegExp(t,e);ZRe.code="new RegExp";var Yut=["removeAdditional","useDefaults","coerceTypes"],Qut=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),elt={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},tlt={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},GRe=200;function rlt(t){var e,r,o,n,i,s,a,c,u,l,d,p,f,h,y,w,b,S,x,R,T,M,Z,te,Ae;let Te=t.strict,bt=(e=t.code)===null||e===void 0?void 0:e.optimize,me=bt===!0||bt===void 0?1:bt||0,Fe=(o=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&o!==void 0?o:ZRe,se=(n=t.uriResolver)!==null&&n!==void 0?n:Xut.default;return{strictSchema:(s=(i=t.strictSchema)!==null&&i!==void 0?i:Te)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Te)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:Te)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:Te)!==null&&p!==void 0?p:"log",strictRequired:(h=(f=t.strictRequired)!==null&&f!==void 0?f:Te)!==null&&h!==void 0?h:!1,code:t.code?{...t.code,optimize:me,regExp:Fe}:{optimize:me,regExp:Fe},loopRequired:(y=t.loopRequired)!==null&&y!==void 0?y:GRe,loopEnum:(w=t.loopEnum)!==null&&w!==void 0?w:GRe,meta:(b=t.meta)!==null&&b!==void 0?b:!0,messages:(S=t.messages)!==null&&S!==void 0?S:!0,inlineRefs:(x=t.inlineRefs)!==null&&x!==void 0?x:!0,schemaId:(R=t.schemaId)!==null&&R!==void 0?R:"$id",addUsedSchema:(T=t.addUsedSchema)!==null&&T!==void 0?T:!0,validateSchema:(M=t.validateSchema)!==null&&M!==void 0?M:!0,validateFormats:(Z=t.validateFormats)!==null&&Z!==void 0?Z:!0,unicodeRegExp:(te=t.unicodeRegExp)!==null&&te!==void 0?te:!0,int32range:(Ae=t.int32range)!==null&&Ae!==void 0?Ae:!0,uriResolver:se}}var Jb=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...rlt(e)};let{es5:r,lines:o}=this.opts.code;this.scope=new Jut.ValueScope({scope:{},prefixes:Qut,es5:r,lines:o}),this.logger=clt(e.logger);let n=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Wut.getRules)(),HRe.call(this,elt,e,"NOT SUPPORTED"),HRe.call(this,tlt,e,"DEPRECATED","warn"),this._metaOpts=slt.call(this),e.formats&&olt.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&ilt.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),nlt.call(this),e.validateFormats=n}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:o}=this.opts,n=VRe;o==="id"&&(n={...VRe},n.id=n.$id,delete n.$id),r&&e&&this.addMetaSchema(n,n[o],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let o;if(typeof e=="string"){if(o=this.getSchema(e),!o)throw new Error(`no schema with key or ref "${e}"`)}else o=this.compile(e);let n=o(r);return"$async"in o||(this.errors=o.errors),n}compile(e,r){let o=this._addSchema(e,r);return o.validate||this._compileSchemaEnv(o)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:o}=this.opts;return n.call(this,e,r);async function n(l,d){await i.call(this,l.$schema);let p=this._addSchema(l,d);return p.validate||s.call(this,p)}async function i(l){l&&!this.getSchema(l)&&await n.call(this,{$ref:l},!0)}async function s(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof BRe.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),s.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await i.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=o(l))}finally{delete this._loading[l]}}}addSchema(e,r,o,n=this.opts.validateSchema){if(Array.isArray(e)){for(let s of e)this.addSchema(s,void 0,o,n);return this}let i;if(typeof e=="object"){let{schemaId:s}=this.opts;if(i=e[s],i!==void 0&&typeof i!="string")throw new Error(`schema ${s} must be string`)}return r=(0,Wb.normalizeId)(r||i),this._checkUnique(r),this.schemas[r]=this._addSchema(e,o,r,n,!0),this}addMetaSchema(e,r,o=this.opts.validateSchema){return this.addSchema(e,r,!0,o),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let o;if(o=e.$schema,o!==void 0&&typeof o!="string")throw new Error("$schema must be a string");if(o=o||this.opts.defaultMeta||this.defaultMeta(),!o)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let n=this.validate(o,e);if(!n&&r){let i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return n}getSchema(e){let r;for(;typeof(r=KRe.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:o}=this.opts,n=new Zb.SchemaEnv({schema:{},schemaId:o});if(r=Zb.resolveSchema.call(this,n,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=KRe.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let o=e[this.opts.schemaId];return o&&(o=(0,Wb.normalizeId)(o),delete this.schemas[o],delete this.refs[o]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let o;if(typeof e=="string")o=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=o);else if(typeof e=="object"&&r===void 0){if(r=e,o=r.keyword,Array.isArray(o)&&!o.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(llt.call(this,o,r),!r)return(0,jH.eachItem)(o,i=>LH.call(this,i)),this;plt.call(this,r);let n={...r,type:(0,GN.getJSONTypes)(r.type),schemaType:(0,GN.getJSONTypes)(r.schemaType)};return(0,jH.eachItem)(o,n.type.length===0?i=>LH.call(this,i,n):i=>n.type.forEach(s=>LH.call(this,i,n,s))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let o of r.rules){let n=o.rules.findIndex(i=>i.keyword===e);n>=0&&o.rules.splice(n,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:o="data"}={}){return!e||e.length===0?"No errors":e.map(n=>`${o}${n.instancePath} ${n.message}`).reduce((n,i)=>n+r+i)}$dataMetaSchema(e,r){let o=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let n of r){let i=n.split("/").slice(1),s=e;for(let a of i)s=s[a];for(let a in o){let c=o[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=s[a];u&&l&&(s[a]=WRe(l))}}return e}_removeAllSchemas(e,r){for(let o in e){let n=e[o];(!r||r.test(o))&&(typeof n=="string"?delete e[o]:n&&!n.meta&&(this._cache.delete(n.schema),delete e[o]))}}_addSchema(e,r,o,n=this.opts.validateSchema,i=this.opts.addUsedSchema){let s,{schemaId:a}=this.opts;if(typeof e=="object")s=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;o=(0,Wb.normalizeId)(s||o);let u=Wb.getSchemaRefs.call(this,e,o);return c=new Zb.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:o,localRefs:u}),this._cache.set(c.schema,c),i&&!o.startsWith("#")&&(o&&this._checkUnique(o),this.refs[o]=c),n&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Zb.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{Zb.compileSchema.call(this,e)}finally{this.opts=r}}};Jb.ValidationError=Zut.default;Jb.MissingRefError=BRe.default;yn.default=Jb;function HRe(t,e,r,o="error"){for(let n in t){let i=n;i in e&&this.logger[o](`${r}: option ${n}. ${t[i]}`)}}function KRe(t){return t=(0,Wb.normalizeId)(t),this.schemas[t]||this.refs[t]}function nlt(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function olt(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function ilt(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function slt(){let t={...this.opts};for(let e of Yut)delete t[e];return t}var alt={log(){},warn(){},error(){}};function clt(t){if(t===!1)return alt;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var ult=/^[a-z_$][a-z0-9_$:-]*$/i;function llt(t,e){let{RULES:r}=this;if((0,jH.eachItem)(t,o=>{if(r.keywords[o])throw new Error(`Keyword ${o} is already defined`);if(!ult.test(o))throw new Error(`Keyword ${o} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function LH(t,e,r){var o;let n=e?.post;if(r&&n)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,s=n?i.post:i.rules.find(({type:c})=>c===r);if(s||(s={type:r,rules:[]},i.rules.push(s)),i.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,GN.getJSONTypes)(e.type),schemaType:(0,GN.getJSONTypes)(e.schemaType)}};e.before?dlt.call(this,s,a,e.before):s.rules.push(a),i.all[t]=a,(o=e.implements)===null||o===void 0||o.forEach(c=>this.addKeyword(c))}function dlt(t,e,r){let o=t.rules.findIndex(n=>n.keyword===r);o>=0?t.rules.splice(o,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function plt(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=WRe(e)),t.validateSchema=this.compile(e,!0))}var flt={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function WRe(t){return{anyOf:[t,flt]}}});var XRe=U(FH=>{"use strict";Object.defineProperty(FH,"__esModule",{value:!0});var mlt={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};FH.default=mlt});var tIe=U(fp=>{"use strict";Object.defineProperty(fp,"__esModule",{value:!0});fp.callRef=fp.getValidate=void 0;var hlt=Hb(),YRe=Ti(),xo=je(),Yh=zc(),QRe=UN(),HN=mt(),glt={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:o}=t,{baseId:n,schemaEnv:i,validateName:s,opts:a,self:c}=o,{root:u}=i;if((r==="#"||r==="#/")&&n===u.baseId)return d();let l=QRe.resolveRef.call(c,u,n,r);if(l===void 0)throw new hlt.default(o.opts.uriResolver,n,r);if(l instanceof QRe.SchemaEnv)return p(l);return f(l);function d(){if(i===u)return KN(t,s,i,i.$async);let h=e.scopeValue("root",{ref:u});return KN(t,(0,xo._)`${h}.validate`,u,u.$async)}function p(h){let y=eIe(t,h);KN(t,y,h,h.$async)}function f(h){let y=e.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,xo.stringify)(h)}:{ref:h}),w=e.name("valid"),b=t.subschema({schema:h,dataTypes:[],schemaPath:xo.nil,topSchemaRef:y,errSchemaPath:r},w);t.mergeEvaluated(b),t.ok(w)}}};function eIe(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,xo._)`${r.scopeValue("wrapper",{ref:e})}.validate`}fp.getValidate=eIe;function KN(t,e,r,o){let{gen:n,it:i}=t,{allErrors:s,schemaEnv:a,opts:c}=i,u=c.passContext?Yh.default.this:xo.nil;o?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=n.let("valid");n.try(()=>{n.code((0,xo._)`await ${(0,YRe.callValidateCode)(t,e,u)}`),f(e),s||n.assign(h,!0)},y=>{n.if((0,xo._)`!(${y} instanceof ${i.ValidationError})`,()=>n.throw(y)),p(y),s||n.assign(h,!1)}),t.ok(h)}function d(){t.result((0,YRe.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(h){let y=(0,xo._)`${h}.errors`;n.assign(Yh.default.vErrors,(0,xo._)`${Yh.default.vErrors} === null ? ${y} : ${Yh.default.vErrors}.concat(${y})`),n.assign(Yh.default.errors,(0,xo._)`${Yh.default.vErrors}.length`)}function f(h){var y;if(!i.opts.unevaluated)return;let w=(y=r?.validate)===null||y===void 0?void 0:y.evaluated;if(i.props!==!0)if(w&&!w.dynamicProps)w.props!==void 0&&(i.props=HN.mergeEvaluated.props(n,w.props,i.props));else{let b=n.var("props",(0,xo._)`${h}.evaluated.props`);i.props=HN.mergeEvaluated.props(n,b,i.props,xo.Name)}if(i.items!==!0)if(w&&!w.dynamicItems)w.items!==void 0&&(i.items=HN.mergeEvaluated.items(n,w.items,i.items));else{let b=n.var("items",(0,xo._)`${h}.evaluated.items`);i.items=HN.mergeEvaluated.items(n,b,i.items,xo.Name)}}}fp.callRef=KN;fp.default=glt});var rIe=U(qH=>{"use strict";Object.defineProperty(qH,"__esModule",{value:!0});var ylt=XRe(),vlt=tIe(),wlt=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",ylt.default,vlt.default];qH.default=wlt});var nIe=U(VH=>{"use strict";Object.defineProperty(VH,"__esModule",{value:!0});var BN=je(),Tl=BN.operators,ZN={maximum:{okStr:"<=",ok:Tl.LTE,fail:Tl.GT},minimum:{okStr:">=",ok:Tl.GTE,fail:Tl.LT},exclusiveMaximum:{okStr:"<",ok:Tl.LT,fail:Tl.GTE},exclusiveMinimum:{okStr:">",ok:Tl.GT,fail:Tl.LTE}},_lt={message:({keyword:t,schemaCode:e})=>(0,BN.str)`must be ${ZN[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,BN._)`{comparison: ${ZN[t].okStr}, limit: ${e}}`},blt={keyword:Object.keys(ZN),type:"number",schemaType:"number",$data:!0,error:_lt,code(t){let{keyword:e,data:r,schemaCode:o}=t;t.fail$data((0,BN._)`${r} ${ZN[e].fail} ${o} || isNaN(${r})`)}};VH.default=blt});var oIe=U(GH=>{"use strict";Object.defineProperty(GH,"__esModule",{value:!0});var Xb=je(),Slt={message:({schemaCode:t})=>(0,Xb.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Xb._)`{multipleOf: ${t}}`},xlt={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Slt,code(t){let{gen:e,data:r,schemaCode:o,it:n}=t,i=n.opts.multipleOfPrecision,s=e.let("res"),a=i?(0,Xb._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,Xb._)`${s} !== parseInt(${s})`;t.fail$data((0,Xb._)`(${o} === 0 || (${s} = ${r}/${o}, ${a}))`)}};GH.default=xlt});var sIe=U(HH=>{"use strict";Object.defineProperty(HH,"__esModule",{value:!0});function iIe(t){let e=t.length,r=0,o=0,n;for(;o<e;)r++,n=t.charCodeAt(o++),n>=55296&&n<=56319&&o<e&&(n=t.charCodeAt(o),(n&64512)===56320&&o++);return r}HH.default=iIe;iIe.code='require("ajv/dist/runtime/ucs2length").default'});var aIe=U(KH=>{"use strict";Object.defineProperty(KH,"__esModule",{value:!0});var mp=je(),Elt=mt(),$lt=sIe(),Rlt={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,mp.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,mp._)`{limit: ${t}}`},Ilt={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Rlt,code(t){let{keyword:e,data:r,schemaCode:o,it:n}=t,i=e==="maxLength"?mp.operators.GT:mp.operators.LT,s=n.opts.unicode===!1?(0,mp._)`${r}.length`:(0,mp._)`${(0,Elt.useFunc)(t.gen,$lt.default)}(${r})`;t.fail$data((0,mp._)`${s} ${i} ${o}`)}};KH.default=Ilt});var cIe=U(BH=>{"use strict";Object.defineProperty(BH,"__esModule",{value:!0});var Alt=Ti(),Plt=mt(),Qh=je(),klt={message:({schemaCode:t})=>(0,Qh.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Qh._)`{pattern: ${t}}`},Tlt={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:klt,code(t){let{gen:e,data:r,$data:o,schema:n,schemaCode:i,it:s}=t,a=s.opts.unicodeRegExp?"u":"";if(o){let{regExp:c}=s.opts.code,u=c.code==="new RegExp"?(0,Qh._)`new RegExp`:(0,Plt.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,Qh._)`${u}(${i}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,Qh._)`!${l}`)}else{let c=(0,Alt.usePattern)(t,n);t.fail$data((0,Qh._)`!${c}.test(${r})`)}}};BH.default=Tlt});var uIe=U(ZH=>{"use strict";Object.defineProperty(ZH,"__esModule",{value:!0});var Yb=je(),Clt={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Yb.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Yb._)`{limit: ${t}}`},Olt={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Clt,code(t){let{keyword:e,data:r,schemaCode:o}=t,n=e==="maxProperties"?Yb.operators.GT:Yb.operators.LT;t.fail$data((0,Yb._)`Object.keys(${r}).length ${n} ${o}`)}};ZH.default=Olt});var lIe=U(WH=>{"use strict";Object.defineProperty(WH,"__esModule",{value:!0});var Qb=Ti(),eS=je(),Dlt=mt(),Nlt={message:({params:{missingProperty:t}})=>(0,eS.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,eS._)`{missingProperty: ${t}}`},zlt={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Nlt,code(t){let{gen:e,schema:r,schemaCode:o,data:n,$data:i,it:s}=t,{opts:a}=s;if(!i&&r.length===0)return;let c=r.length>=a.loopRequired;if(s.allErrors?u():l(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:h}=t.it;for(let y of r)if(f?.[y]===void 0&&!h.has(y)){let w=s.schemaEnv.baseId+s.errSchemaPath,b=`required property "${y}" is not defined at "${w}" (strictRequired)`;(0,Dlt.checkStrictMode)(s,b,s.opts.strictRequired)}}function u(){if(c||i)t.block$data(eS.nil,d);else for(let f of r)(0,Qb.checkReportMissingProp)(t,f)}function l(){let f=e.let("missing");if(c||i){let h=e.let("valid",!0);t.block$data(h,()=>p(f,h)),t.ok(h)}else e.if((0,Qb.checkMissingProp)(t,r,f)),(0,Qb.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",o,f=>{t.setParams({missingProperty:f}),e.if((0,Qb.noPropertyInData)(e,n,f,a.ownProperties),()=>t.error())})}function p(f,h){t.setParams({missingProperty:f}),e.forOf(f,o,()=>{e.assign(h,(0,Qb.propertyInData)(e,n,f,a.ownProperties)),e.if((0,eS.not)(h),()=>{t.error(),e.break()})},eS.nil)}}};WH.default=zlt});var dIe=U(JH=>{"use strict";Object.defineProperty(JH,"__esModule",{value:!0});var tS=je(),Mlt={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,tS.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,tS._)`{limit: ${t}}`},Ult={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Mlt,code(t){let{keyword:e,data:r,schemaCode:o}=t,n=e==="maxItems"?tS.operators.GT:tS.operators.LT;t.fail$data((0,tS._)`${r}.length ${n} ${o}`)}};JH.default=Ult});var WN=U(XH=>{"use strict";Object.defineProperty(XH,"__esModule",{value:!0});var pIe=mH();pIe.code='require("ajv/dist/runtime/equal").default';XH.default=pIe});var fIe=U(QH=>{"use strict";Object.defineProperty(QH,"__esModule",{value:!0});var YH=jb(),vn=je(),Llt=mt(),jlt=WN(),Flt={message:({params:{i:t,j:e}})=>(0,vn.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,vn._)`{i: ${t}, j: ${e}}`},qlt={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Flt,code(t){let{gen:e,data:r,$data:o,schema:n,parentSchema:i,schemaCode:s,it:a}=t;if(!o&&!n)return;let c=e.let("valid"),u=i.items?(0,YH.getSchemaTypes)(i.items):[];t.block$data(c,l,(0,vn._)`${s} === false`),t.ok(c);function l(){let h=e.let("i",(0,vn._)`${r}.length`),y=e.let("j");t.setParams({i:h,j:y}),e.assign(c,!0),e.if((0,vn._)`${h} > 1`,()=>(d()?p:f)(h,y))}function d(){return u.length>0&&!u.some(h=>h==="object"||h==="array")}function p(h,y){let w=e.name("item"),b=(0,YH.checkDataTypes)(u,w,a.opts.strictNumbers,YH.DataType.Wrong),S=e.const("indices",(0,vn._)`{}`);e.for((0,vn._)`;${h}--;`,()=>{e.let(w,(0,vn._)`${r}[${h}]`),e.if(b,(0,vn._)`continue`),u.length>1&&e.if((0,vn._)`typeof ${w} == "string"`,(0,vn._)`${w} += "_"`),e.if((0,vn._)`typeof ${S}[${w}] == "number"`,()=>{e.assign(y,(0,vn._)`${S}[${w}]`),t.error(),e.assign(c,!1).break()}).code((0,vn._)`${S}[${w}] = ${h}`)})}function f(h,y){let w=(0,Llt.useFunc)(e,jlt.default),b=e.name("outer");e.label(b).for((0,vn._)`;${h}--;`,()=>e.for((0,vn._)`${y} = ${h}; ${y}--;`,()=>e.if((0,vn._)`${w}(${r}[${h}], ${r}[${y}])`,()=>{t.error(),e.assign(c,!1).break(b)})))}}};QH.default=qlt});var mIe=U(tK=>{"use strict";Object.defineProperty(tK,"__esModule",{value:!0});var eK=je(),Vlt=mt(),Glt=WN(),Hlt={message:"must be equal to constant",params:({schemaCode:t})=>(0,eK._)`{allowedValue: ${t}}`},Klt={keyword:"const",$data:!0,error:Hlt,code(t){let{gen:e,data:r,$data:o,schemaCode:n,schema:i}=t;o||i&&typeof i=="object"?t.fail$data((0,eK._)`!${(0,Vlt.useFunc)(e,Glt.default)}(${r}, ${n})`):t.fail((0,eK._)`${i} !== ${r}`)}};tK.default=Klt});var hIe=U(rK=>{"use strict";Object.defineProperty(rK,"__esModule",{value:!0});var rS=je(),Blt=mt(),Zlt=WN(),Wlt={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,rS._)`{allowedValues: ${t}}`},Jlt={keyword:"enum",schemaType:"array",$data:!0,error:Wlt,code(t){let{gen:e,data:r,$data:o,schema:n,schemaCode:i,it:s}=t;if(!o&&n.length===0)throw new Error("enum must have non-empty array");let a=n.length>=s.opts.loopEnum,c,u=()=>c??(c=(0,Blt.useFunc)(e,Zlt.default)),l;if(a||o)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(n))throw new Error("ajv implementation error");let f=e.const("vSchema",i);l=(0,rS.or)(...n.map((h,y)=>p(f,y)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",i,f=>e.if((0,rS._)`${u()}(${r}, ${f})`,()=>e.assign(l,!0).break()))}function p(f,h){let y=n[h];return typeof y=="object"&&y!==null?(0,rS._)`${u()}(${r}, ${f}[${h}])`:(0,rS._)`${r} === ${y}`}}};rK.default=Jlt});var gIe=U(nK=>{"use strict";Object.defineProperty(nK,"__esModule",{value:!0});var Xlt=nIe(),Ylt=oIe(),Qlt=aIe(),edt=cIe(),tdt=uIe(),rdt=lIe(),ndt=dIe(),odt=fIe(),idt=mIe(),sdt=hIe(),adt=[Xlt.default,Ylt.default,Qlt.default,edt.default,tdt.default,rdt.default,ndt.default,odt.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},idt.default,sdt.default];nK.default=adt});var iK=U(nS=>{"use strict";Object.defineProperty(nS,"__esModule",{value:!0});nS.validateAdditionalItems=void 0;var hp=je(),oK=mt(),cdt={message:({params:{len:t}})=>(0,hp.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,hp._)`{limit: ${t}}`},udt={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:cdt,code(t){let{parentSchema:e,it:r}=t,{items:o}=e;if(!Array.isArray(o)){(0,oK.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}yIe(t,o)}};function yIe(t,e){let{gen:r,schema:o,data:n,keyword:i,it:s}=t;s.items=!0;let a=r.const("len",(0,hp._)`${n}.length`);if(o===!1)t.setParams({len:e.length}),t.pass((0,hp._)`${a} <= ${e.length}`);else if(typeof o=="object"&&!(0,oK.alwaysValidSchema)(s,o)){let u=r.var("valid",(0,hp._)`${a} <= ${e.length}`);r.if((0,hp.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:i,dataProp:l,dataPropType:oK.Type.Num},u),s.allErrors||r.if((0,hp.not)(u),()=>r.break())})}}nS.validateAdditionalItems=yIe;nS.default=udt});var sK=U(oS=>{"use strict";Object.defineProperty(oS,"__esModule",{value:!0});oS.validateTuple=void 0;var vIe=je(),JN=mt(),ldt=Ti(),ddt={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return wIe(t,"additionalItems",e);r.items=!0,!(0,JN.alwaysValidSchema)(r,e)&&t.ok((0,ldt.validateArray)(t))}};function wIe(t,e,r=t.schema){let{gen:o,parentSchema:n,data:i,keyword:s,it:a}=t;l(n),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=JN.mergeEvaluated.items(o,r.length,a.items));let c=o.name("valid"),u=o.const("len",(0,vIe._)`${i}.length`);r.forEach((d,p)=>{(0,JN.alwaysValidSchema)(a,d)||(o.if((0,vIe._)`${u} > ${p}`,()=>t.subschema({keyword:s,schemaProp:p,dataProp:p},c)),t.ok(c))});function l(d){let{opts:p,errSchemaPath:f}=a,h=r.length,y=h===d.minItems&&(h===d.maxItems||d[e]===!1);if(p.strictTuples&&!y){let w=`"${s}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,JN.checkStrictMode)(a,w,p.strictTuples)}}}oS.validateTuple=wIe;oS.default=ddt});var _Ie=U(aK=>{"use strict";Object.defineProperty(aK,"__esModule",{value:!0});var pdt=sK(),fdt={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,pdt.validateTuple)(t,"items")};aK.default=fdt});var SIe=U(cK=>{"use strict";Object.defineProperty(cK,"__esModule",{value:!0});var bIe=je(),mdt=mt(),hdt=Ti(),gdt=iK(),ydt={message:({params:{len:t}})=>(0,bIe.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,bIe._)`{limit: ${t}}`},vdt={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:ydt,code(t){let{schema:e,parentSchema:r,it:o}=t,{prefixItems:n}=r;o.items=!0,!(0,mdt.alwaysValidSchema)(o,e)&&(n?(0,gdt.validateAdditionalItems)(t,n):t.ok((0,hdt.validateArray)(t)))}};cK.default=vdt});var xIe=U(uK=>{"use strict";Object.defineProperty(uK,"__esModule",{value:!0});var Oi=je(),XN=mt(),wdt={message:({params:{min:t,max:e}})=>e===void 0?(0,Oi.str)`must contain at least ${t} valid item(s)`:(0,Oi.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Oi._)`{minContains: ${t}}`:(0,Oi._)`{minContains: ${t}, maxContains: ${e}}`},_dt={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:wdt,code(t){let{gen:e,schema:r,parentSchema:o,data:n,it:i}=t,s,a,{minContains:c,maxContains:u}=o;i.opts.next?(s=c===void 0?1:c,a=u):s=1;let l=e.const("len",(0,Oi._)`${n}.length`);if(t.setParams({min:s,max:a}),a===void 0&&s===0){(0,XN.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,XN.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,XN.alwaysValidSchema)(i,r)){let y=(0,Oi._)`${l} >= ${s}`;a!==void 0&&(y=(0,Oi._)`${y} && ${l} <= ${a}`),t.pass(y);return}i.items=!0;let d=e.name("valid");a===void 0&&s===1?f(d,()=>e.if(d,()=>e.break())):s===0?(e.let(d,!0),a!==void 0&&e.if((0,Oi._)`${n}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let y=e.name("_valid"),w=e.let("count",0);f(y,()=>e.if(y,()=>h(w)))}function f(y,w){e.forRange("i",0,l,b=>{t.subschema({keyword:"contains",dataProp:b,dataPropType:XN.Type.Num,compositeRule:!0},y),w()})}function h(y){e.code((0,Oi._)`${y}++`),a===void 0?e.if((0,Oi._)`${y} >= ${s}`,()=>e.assign(d,!0).break()):(e.if((0,Oi._)`${y} > ${a}`,()=>e.assign(d,!1).break()),s===1?e.assign(d,!0):e.if((0,Oi._)`${y} >= ${s}`,()=>e.assign(d,!0)))}}};uK.default=_dt});var RIe=U(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});Da.validateSchemaDeps=Da.validatePropertyDeps=Da.error=void 0;var lK=je(),bdt=mt(),iS=Ti();Da.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let o=e===1?"property":"properties";return(0,lK.str)`must have ${o} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:o}})=>(0,lK._)`{property: ${t},
65
65
  missingProperty: ${o},
66
66
  depsCount: ${e},
67
- deps: ${r}}`};var Sdt={keyword:"dependencies",type:"object",schemaType:"object",error:Da.error,code(t){let[e,r]=xdt(t);EIe(t,e),$Ie(t,r)}};function xdt({schema:t}){let e={},r={};for(let o in t){if(o==="__proto__")continue;let n=Array.isArray(t[o])?e:r;n[o]=t[o]}return[e,r]}function EIe(t,e=t.schema){let{gen:r,data:o,it:n}=t;if(Object.keys(e).length===0)return;let i=r.let("missing");for(let s in e){let a=e[s];if(a.length===0)continue;let c=(0,iS.propertyInData)(r,o,s,n.opts.ownProperties);t.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),n.allErrors?r.if(c,()=>{for(let u of a)(0,iS.checkReportMissingProp)(t,u)}):(r.if((0,lK._)`${c} && (${(0,iS.checkMissingProp)(t,a,i)})`),(0,iS.reportMissingProp)(t,i),r.else())}}Da.validatePropertyDeps=EIe;function $Ie(t,e=t.schema){let{gen:r,data:o,keyword:n,it:i}=t,s=r.name("valid");for(let a in e)(0,bdt.alwaysValidSchema)(i,e[a])||(r.if((0,iS.propertyInData)(r,o,a,i.opts.ownProperties),()=>{let c=t.subschema({keyword:n,schemaProp:a},s);t.mergeValidEvaluated(c,s)},()=>r.var(s,!0)),t.ok(s))}Da.validateSchemaDeps=$Ie;Da.default=Sdt});var AIe=U(dK=>{"use strict";Object.defineProperty(dK,"__esModule",{value:!0});var IIe=je(),Edt=mt(),$dt={message:"property name must be valid",params:({params:t})=>(0,IIe._)`{propertyName: ${t.propertyName}}`},Rdt={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:$dt,code(t){let{gen:e,schema:r,data:o,it:n}=t;if((0,Edt.alwaysValidSchema)(n,r))return;let i=e.name("valid");e.forIn("key",o,s=>{t.setParams({propertyName:s}),t.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},i),e.if((0,IIe.not)(i),()=>{t.error(!0),n.allErrors||e.break()})}),t.ok(i)}};dK.default=Rdt});var fK=U(pK=>{"use strict";Object.defineProperty(pK,"__esModule",{value:!0});var YN=Ti(),Is=je(),Idt=zc(),QN=mt(),Adt={message:"must NOT have additional properties",params:({params:t})=>(0,Is._)`{additionalProperty: ${t.additionalProperty}}`},Pdt={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Adt,code(t){let{gen:e,schema:r,parentSchema:o,data:n,errsCount:i,it:s}=t;if(!i)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=s;if(s.props=!0,c.removeAdditional!=="all"&&(0,QN.alwaysValidSchema)(s,r))return;let u=(0,YN.allSchemaProperties)(o.properties),l=(0,YN.allSchemaProperties)(o.patternProperties);d(),t.ok((0,Is._)`${i} === ${Idt.default.errors}`);function d(){e.forIn("key",n,w=>{!u.length&&!l.length?h(w):e.if(p(w),()=>h(w))})}function p(w){let b;if(u.length>8){let S=(0,QN.schemaRefOrVal)(s,o.properties,"properties");b=(0,YN.isOwnProperty)(e,S,w)}else u.length?b=(0,Is.or)(...u.map(S=>(0,Is._)`${w} === ${S}`)):b=Is.nil;return l.length&&(b=(0,Is.or)(b,...l.map(S=>(0,Is._)`${(0,YN.usePattern)(t,S)}.test(${w})`))),(0,Is.not)(b)}function f(w){e.code((0,Is._)`delete ${n}[${w}]`)}function h(w){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(w);return}if(r===!1){t.setParams({additionalProperty:w}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,QN.alwaysValidSchema)(s,r)){let b=e.name("valid");c.removeAdditional==="failing"?(y(w,b,!1),e.if((0,Is.not)(b),()=>{t.reset(),f(w)})):(y(w,b),a||e.if((0,Is.not)(b),()=>e.break()))}}function y(w,b,S){let x={keyword:"additionalProperties",dataProp:w,dataPropType:QN.Type.Str};S===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(x,b)}}};pK.default=Pdt});var TIe=U(hK=>{"use strict";Object.defineProperty(hK,"__esModule",{value:!0});var kdt=Gb(),PIe=Ti(),mK=mt(),kIe=fK(),Tdt={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:o,data:n,it:i}=t;i.opts.removeAdditional==="all"&&o.additionalProperties===void 0&&kIe.default.code(new kdt.KeywordCxt(i,kIe.default,"additionalProperties"));let s=(0,PIe.allSchemaProperties)(r);for(let d of s)i.definedProperties.add(d);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=mK.mergeEvaluated.props(e,(0,mK.toHash)(s),i.props));let a=s.filter(d=>!(0,mK.alwaysValidSchema)(i,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,PIe.propertyInData)(e,n,d,i.opts.ownProperties)),l(d),i.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return i.opts.useDefaults&&!i.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};hK.default=Tdt});var NIe=U(gK=>{"use strict";Object.defineProperty(gK,"__esModule",{value:!0});var CIe=Ti(),e1=je(),OIe=mt(),DIe=mt(),Cdt={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:o,parentSchema:n,it:i}=t,{opts:s}=i,a=(0,CIe.allSchemaProperties)(r),c=a.filter(y=>(0,OIe.alwaysValidSchema)(i,r[y]));if(a.length===0||c.length===a.length&&(!i.opts.unevaluated||i.props===!0))return;let u=s.strictSchema&&!s.allowMatchingProperties&&n.properties,l=e.name("valid");i.props!==!0&&!(i.props instanceof e1.Name)&&(i.props=(0,DIe.evaluatedPropsToName)(e,i.props));let{props:d}=i;p();function p(){for(let y of a)u&&f(y),i.allErrors?h(y):(e.var(l,!0),h(y),e.if(l))}function f(y){for(let w in u)new RegExp(y).test(w)&&(0,OIe.checkStrictMode)(i,`property ${w} matches pattern ${y} (use allowMatchingProperties)`)}function h(y){e.forIn("key",o,w=>{e.if((0,e1._)`${(0,CIe.usePattern)(t,y)}.test(${w})`,()=>{let b=c.includes(y);b||t.subschema({keyword:"patternProperties",schemaProp:y,dataProp:w,dataPropType:DIe.Type.Str},l),i.opts.unevaluated&&d!==!0?e.assign((0,e1._)`${d}[${w}]`,!0):!b&&!i.allErrors&&e.if((0,e1.not)(l),()=>e.break())})})}}};gK.default=Cdt});var zIe=U(yK=>{"use strict";Object.defineProperty(yK,"__esModule",{value:!0});var Odt=mt(),Ddt={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:o}=t;if((0,Odt.alwaysValidSchema)(o,r)){t.fail();return}let n=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},n),t.failResult(n,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};yK.default=Ddt});var MIe=U(vK=>{"use strict";Object.defineProperty(vK,"__esModule",{value:!0});var Ndt=Ti(),zdt={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Ndt.validateUnion,error:{message:"must match a schema in anyOf"}};vK.default=zdt});var UIe=U(wK=>{"use strict";Object.defineProperty(wK,"__esModule",{value:!0});var t1=je(),Mdt=mt(),Udt={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,t1._)`{passingSchemas: ${t.passing}}`},Ldt={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Udt,code(t){let{gen:e,schema:r,parentSchema:o,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(n.opts.discriminator&&o.discriminator)return;let i=r,s=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(s,()=>t.reset(),()=>t.error(!0));function u(){i.forEach((l,d)=>{let p;(0,Mdt.alwaysValidSchema)(n,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,t1._)`${c} && ${s}`).assign(s,!1).assign(a,(0,t1._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(s,!0),e.assign(a,d),p&&t.mergeEvaluated(p,t1.Name)})})}}};wK.default=Ldt});var LIe=U(_K=>{"use strict";Object.defineProperty(_K,"__esModule",{value:!0});var jdt=mt(),Fdt={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let n=e.name("valid");r.forEach((i,s)=>{if((0,jdt.alwaysValidSchema)(o,i))return;let a=t.subschema({keyword:"allOf",schemaProp:s},n);t.ok(n),t.mergeEvaluated(a)})}};_K.default=Fdt});var qIe=U(bK=>{"use strict";Object.defineProperty(bK,"__esModule",{value:!0});var r1=je(),FIe=mt(),qdt={message:({params:t})=>(0,r1.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,r1._)`{failingKeyword: ${t.ifClause}}`},Vdt={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:qdt,code(t){let{gen:e,parentSchema:r,it:o}=t;r.then===void 0&&r.else===void 0&&(0,FIe.checkStrictMode)(o,'"if" without "then" and "else" is ignored');let n=jIe(o,"then"),i=jIe(o,"else");if(!n&&!i)return;let s=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),n&&i){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else n?e.if(a,u("then")):e.if((0,r1.not)(a),u("else"));t.pass(s,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let p=t.subschema({keyword:l},a);e.assign(s,a),t.mergeValidEvaluated(p,s),d?e.assign(d,(0,r1._)`${l}`):t.setParams({ifClause:l})}}}};function jIe(t,e){let r=t.schema[e];return r!==void 0&&!(0,FIe.alwaysValidSchema)(t,r)}bK.default=Vdt});var VIe=U(SK=>{"use strict";Object.defineProperty(SK,"__esModule",{value:!0});var Gdt=mt(),Hdt={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,Gdt.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};SK.default=Hdt});var GIe=U(xK=>{"use strict";Object.defineProperty(xK,"__esModule",{value:!0});var Kdt=iK(),Bdt=_Ie(),Zdt=sK(),Wdt=SIe(),Jdt=xIe(),Xdt=RIe(),Ydt=AIe(),Qdt=fK(),ept=TIe(),tpt=NIe(),rpt=zIe(),npt=MIe(),opt=UIe(),ipt=LIe(),spt=qIe(),apt=VIe();function cpt(t=!1){let e=[rpt.default,npt.default,opt.default,ipt.default,spt.default,apt.default,Ydt.default,Qdt.default,Xdt.default,ept.default,tpt.default];return t?e.push(Bdt.default,Wdt.default):e.push(Kdt.default,Zdt.default),e.push(Jdt.default),e}xK.default=cpt});var HIe=U(EK=>{"use strict";Object.defineProperty(EK,"__esModule",{value:!0});var wr=je(),upt={message:({schemaCode:t})=>(0,wr.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,wr._)`{format: ${t}}`},lpt={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:upt,code(t,e){let{gen:r,data:o,$data:n,schema:i,schemaCode:s,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;n?p():f();function p(){let h=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),y=r.const("fDef",(0,wr._)`${h}[${s}]`),w=r.let("fType"),b=r.let("format");r.if((0,wr._)`typeof ${y} == "object" && !(${y} instanceof RegExp)`,()=>r.assign(w,(0,wr._)`${y}.type || "string"`).assign(b,(0,wr._)`${y}.validate`),()=>r.assign(w,(0,wr._)`"string"`).assign(b,y)),t.fail$data((0,wr.or)(S(),x()));function S(){return c.strictSchema===!1?wr.nil:(0,wr._)`${s} && !${b}`}function x(){let R=l.$async?(0,wr._)`(${y}.async ? await ${b}(${o}) : ${b}(${o}))`:(0,wr._)`${b}(${o})`,T=(0,wr._)`(typeof ${b} == "function" ? ${R} : ${b}.test(${o}))`;return(0,wr._)`${b} && ${b} !== true && ${w} === ${e} && !${T}`}}function f(){let h=d.formats[i];if(!h){S();return}if(h===!0)return;let[y,w,b]=x(h);y===e&&t.pass(R());function S(){if(c.strictSchema===!1){d.logger.warn(T());return}throw new Error(T());function T(){return`unknown format "${i}" ignored in schema at path "${u}"`}}function x(T){let M=T instanceof RegExp?(0,wr.regexpCode)(T):c.code.formats?(0,wr._)`${c.code.formats}${(0,wr.getProperty)(i)}`:void 0,Z=r.scopeValue("formats",{key:i,ref:T,code:M});return typeof T=="object"&&!(T instanceof RegExp)?[T.type||"string",T.validate,(0,wr._)`${Z}.validate`]:["string",T,Z]}function R(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!l.$async)throw new Error("async format in sync schema");return(0,wr._)`await ${b}(${o})`}return typeof w=="function"?(0,wr._)`${b}(${o})`:(0,wr._)`${b}.test(${o})`}}}};EK.default=lpt});var KIe=U($K=>{"use strict";Object.defineProperty($K,"__esModule",{value:!0});var dpt=HIe(),ppt=[dpt.default];$K.default=ppt});var BIe=U(eg=>{"use strict";Object.defineProperty(eg,"__esModule",{value:!0});eg.contentVocabulary=eg.metadataVocabulary=void 0;eg.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];eg.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var WIe=U(RK=>{"use strict";Object.defineProperty(RK,"__esModule",{value:!0});var fpt=rIe(),mpt=gIe(),hpt=GIe(),gpt=KIe(),ZIe=BIe(),ypt=[fpt.default,mpt.default,(0,hpt.default)(),gpt.default,ZIe.metadataVocabulary,ZIe.contentVocabulary];RK.default=ypt});var XIe=U(n1=>{"use strict";Object.defineProperty(n1,"__esModule",{value:!0});n1.DiscrError=void 0;var JIe;(function(t){t.Tag="tag",t.Mapping="mapping"})(JIe||(n1.DiscrError=JIe={}))});var QIe=U(AK=>{"use strict";Object.defineProperty(AK,"__esModule",{value:!0});var tg=je(),IK=XIe(),YIe=UN(),vpt=Hb(),wpt=mt(),_pt={message:({params:{discrError:t,tagName:e}})=>t===IK.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,tg._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},bpt={keyword:"discriminator",type:"object",schemaType:"object",error:_pt,code(t){let{gen:e,data:r,schema:o,parentSchema:n,it:i}=t,{oneOf:s}=n;if(!i.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=o.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(o.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,tg._)`${r}${(0,tg.getProperty)(a)}`);e.if((0,tg._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:IK.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let f=p();e.if(!1);for(let h in f)e.elseIf((0,tg._)`${u} === ${h}`),e.assign(c,d(f[h]));e.else(),t.error(!1,{discrError:IK.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(f){let h=e.name("valid"),y=t.subschema({keyword:"oneOf",schemaProp:f},h);return t.mergeEvaluated(y,tg.Name),h}function p(){var f;let h={},y=b(n),w=!0;for(let R=0;R<s.length;R++){let T=s[R];if(T?.$ref&&!(0,wpt.schemaHasRulesButRef)(T,i.self.RULES)){let Z=T.$ref;if(T=YIe.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,Z),T instanceof YIe.SchemaEnv&&(T=T.schema),T===void 0)throw new vpt.default(i.opts.uriResolver,i.baseId,Z)}let M=(f=T?.properties)===null||f===void 0?void 0:f[a];if(typeof M!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);w=w&&(y||b(T)),S(M,R)}if(!w)throw new Error(`discriminator: "${a}" must be required`);return h;function b({required:R}){return Array.isArray(R)&&R.includes(a)}function S(R,T){if(R.const)x(R.const,T);else if(R.enum)for(let M of R.enum)x(M,T);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function x(R,T){if(typeof R!="string"||R in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[R]=T}}}};AK.default=bpt});var eAe=U((mYt,Spt)=>{Spt.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var kK=U((er,PK)=>{"use strict";Object.defineProperty(er,"__esModule",{value:!0});er.MissingRefError=er.ValidationError=er.CodeGen=er.Name=er.nil=er.stringify=er.str=er._=er.KeywordCxt=er.Ajv=void 0;var xpt=JRe(),Ept=WIe(),$pt=QIe(),tAe=eAe(),Rpt=["/properties"],o1="http://json-schema.org/draft-07/schema",rg=class extends xpt.default{_addVocabularies(){super._addVocabularies(),Ept.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword($pt.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(tAe,Rpt):tAe;this.addMetaSchema(e,o1,!1),this.refs["http://json-schema.org/schema"]=o1}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(o1)?o1:void 0)}};er.Ajv=rg;PK.exports=er=rg;PK.exports.Ajv=rg;Object.defineProperty(er,"__esModule",{value:!0});er.default=rg;var Ipt=Gb();Object.defineProperty(er,"KeywordCxt",{enumerable:!0,get:function(){return Ipt.KeywordCxt}});var ng=je();Object.defineProperty(er,"_",{enumerable:!0,get:function(){return ng._}});Object.defineProperty(er,"str",{enumerable:!0,get:function(){return ng.str}});Object.defineProperty(er,"stringify",{enumerable:!0,get:function(){return ng.stringify}});Object.defineProperty(er,"nil",{enumerable:!0,get:function(){return ng.nil}});Object.defineProperty(er,"Name",{enumerable:!0,get:function(){return ng.Name}});Object.defineProperty(er,"CodeGen",{enumerable:!0,get:function(){return ng.CodeGen}});var Apt=zN();Object.defineProperty(er,"ValidationError",{enumerable:!0,get:function(){return Apt.default}});var Ppt=Hb();Object.defineProperty(er,"MissingRefError",{enumerable:!0,get:function(){return Ppt.default}})});var uAe=U(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.formatNames=za.fastFormats=za.fullFormats=void 0;function Na(t,e){return{validate:t,compare:e}}za.fullFormats={date:Na(iAe,DK),time:Na(CK(!0),NK),"date-time":Na(rAe(!0),aAe),"iso-time":Na(CK(),sAe),"iso-date-time":Na(rAe(),cAe),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Npt,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:qpt,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:zpt,int32:{type:"number",validate:Lpt},int64:{type:"number",validate:jpt},float:{type:"number",validate:oAe},double:{type:"number",validate:oAe},password:!0,binary:!0};za.fastFormats={...za.fullFormats,date:Na(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,DK),time:Na(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,NK),"date-time":Na(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,aAe),"iso-time":Na(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,sAe),"iso-date-time":Na(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,cAe),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};za.formatNames=Object.keys(za.fullFormats);function kpt(t){return t%4===0&&(t%100!==0||t%400===0)}var Tpt=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Cpt=[0,31,28,31,30,31,30,31,31,30,31,30,31];function iAe(t){let e=Tpt.exec(t);if(!e)return!1;let r=+e[1],o=+e[2],n=+e[3];return o>=1&&o<=12&&n>=1&&n<=(o===2&&kpt(r)?29:Cpt[o])}function DK(t,e){if(t&&e)return t>e?1:t<e?-1:0}var TK=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function CK(t){return function(r){let o=TK.exec(r);if(!o)return!1;let n=+o[1],i=+o[2],s=+o[3],a=o[4],c=o[5]==="-"?-1:1,u=+(o[6]||0),l=+(o[7]||0);if(u>23||l>59||t&&!a)return!1;if(n<=23&&i<=59&&s<60)return!0;let d=i-l*c,p=n-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&s<61}}function NK(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),o=new Date("2020-01-01T"+e).valueOf();if(r&&o)return r-o}function sAe(t,e){if(!(t&&e))return;let r=TK.exec(t),o=TK.exec(e);if(r&&o)return t=r[1]+r[2]+r[3],e=o[1]+o[2]+o[3],t>e?1:t<e?-1:0}var OK=/t|\s/i;function rAe(t){let e=CK(t);return function(o){let n=o.split(OK);return n.length===2&&iAe(n[0])&&e(n[1])}}function aAe(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),o=new Date(e).valueOf();if(r&&o)return r-o}function cAe(t,e){if(!(t&&e))return;let[r,o]=t.split(OK),[n,i]=e.split(OK),s=DK(r,n);if(s!==void 0)return s||NK(o,i)}var Opt=/\/|:/,Dpt=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Npt(t){return Opt.test(t)&&Dpt.test(t)}var nAe=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function zpt(t){return nAe.lastIndex=0,nAe.test(t)}var Mpt=-(2**31),Upt=2**31-1;function Lpt(t){return Number.isInteger(t)&&t<=Upt&&t>=Mpt}function jpt(t){return Number.isInteger(t)}function oAe(){return!0}var Fpt=/[^\\]\\Z/;function qpt(t){if(Fpt.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var lAe=U(og=>{"use strict";Object.defineProperty(og,"__esModule",{value:!0});og.formatLimitDefinition=void 0;var Vpt=kK(),As=je(),Cl=As.operators,i1={formatMaximum:{okStr:"<=",ok:Cl.LTE,fail:Cl.GT},formatMinimum:{okStr:">=",ok:Cl.GTE,fail:Cl.LT},formatExclusiveMaximum:{okStr:"<",ok:Cl.LT,fail:Cl.GTE},formatExclusiveMinimum:{okStr:">",ok:Cl.GT,fail:Cl.LTE}},Gpt={message:({keyword:t,schemaCode:e})=>(0,As.str)`should be ${i1[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,As._)`{comparison: ${i1[t].okStr}, limit: ${e}}`};og.formatLimitDefinition={keyword:Object.keys(i1),type:"string",schemaType:"string",$data:!0,error:Gpt,code(t){let{gen:e,data:r,schemaCode:o,keyword:n,it:i}=t,{opts:s,self:a}=i;if(!s.validateFormats)return;let c=new Vpt.KeywordCxt(i,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:s.code.formats}),f=e.const("fmt",(0,As._)`${p}[${c.schemaCode}]`);t.fail$data((0,As.or)((0,As._)`typeof ${f} != "object"`,(0,As._)`${f} instanceof RegExp`,(0,As._)`typeof ${f}.compare != "function"`,d(f)))}function l(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${n}": format "${p}" does not define "compare" function`);let h=e.scopeValue("formats",{key:p,ref:f,code:s.code.formats?(0,As._)`${s.code.formats}${(0,As.getProperty)(p)}`:void 0});t.fail$data(d(h))}function d(p){return(0,As._)`${p}.compare(${r}, ${o}) ${i1[n].fail} 0`}},dependencies:["format"]};var Hpt=t=>(t.addKeyword(og.formatLimitDefinition),t);og.default=Hpt});var mAe=U((sS,fAe)=>{"use strict";Object.defineProperty(sS,"__esModule",{value:!0});var ig=uAe(),Kpt=lAe(),zK=je(),dAe=new zK.Name("fullFormats"),Bpt=new zK.Name("fastFormats"),MK=(t,e={keywords:!0})=>{if(Array.isArray(e))return pAe(t,e,ig.fullFormats,dAe),t;let[r,o]=e.mode==="fast"?[ig.fastFormats,Bpt]:[ig.fullFormats,dAe],n=e.formats||ig.formatNames;return pAe(t,n,r,o),e.keywords&&(0,Kpt.default)(t),t};MK.get=(t,e="full")=>{let o=(e==="fast"?ig.fastFormats:ig.fullFormats)[t];if(!o)throw new Error(`Unknown format "${t}"`);return o};function pAe(t,e,r,o){var n,i;(n=(i=t.opts.code).formats)!==null&&n!==void 0||(i.formats=(0,zK._)`require("ajv-formats/dist/formats").${o}`);for(let s of e)t.addFormat(s,r[s])}fAe.exports=sS=MK;Object.defineProperty(sS,"__esModule",{value:!0});sS.default=MK});import{parseArgs as aft}from"node:util";import{hostname as f1}from"node:os";import{open as cft,readFile as qK,rename as uft,rm as lft}from"node:fs/promises";import{dirname as dft,join as pft,resolve as UAe}from"node:path";import{randomUUID as fft}from"node:crypto";import{Readable as LAe}from"node:stream";import{pipeline as jAe}from"node:stream/promises";import{setTimeout as VK}from"node:timers/promises";var m={};Ht(m,{$brand:()=>P1,$input:()=>Xz,$output:()=>Jz,INVALID:()=>qn,NEVER:()=>A1,TimePrecision:()=>oM,ZodAny:()=>gU,ZodArray:()=>_U,ZodBase64:()=>pE,ZodBase64URL:()=>fE,ZodBigInt:()=>pf,ZodBigIntFormat:()=>gE,ZodBoolean:()=>df,ZodCIDRv4:()=>lE,ZodCIDRv6:()=>dE,ZodCUID:()=>nE,ZodCUID2:()=>oE,ZodCatch:()=>LU,ZodCodec:()=>hy,ZodCompileAsyncError:()=>Di,ZodCompileUnsupportedError:()=>Be,ZodCreditCard:()=>dU,ZodCustom:()=>gy,ZodCustomStringFormat:()=>Jl,ZodDate:()=>ly,ZodDefault:()=>OU,ZodDiscriminatedUnion:()=>SU,ZodE164:()=>mE,ZodEmail:()=>Q0,ZodEmoji:()=>tE,ZodEnum:()=>cf,ZodError:()=>HCe,ZodExactOptional:()=>wE,ZodFile:()=>PU,ZodFirstPartyTypeKind:()=>QU,ZodFunction:()=>WU,ZodGUID:()=>eE,ZodIBAN:()=>pU,ZodIPv4:()=>cE,ZodIPv6:()=>uE,ZodISODate:()=>Zc,ZodISODateTime:()=>Bc,ZodISODuration:()=>Jc,ZodISOTime:()=>Wc,ZodInstanceOf:()=>YU,ZodIntersection:()=>xU,ZodIssueCode:()=>ZCe,ZodJWT:()=>hE,ZodKSUID:()=>aE,ZodLazy:()=>KU,ZodLiteral:()=>AU,ZodMAC:()=>lU,ZodMap:()=>RU,ZodNaN:()=>FU,ZodNanoID:()=>rE,ZodNever:()=>vU,ZodNonOptional:()=>_E,ZodNull:()=>hU,ZodNullable:()=>CU,ZodNumber:()=>lf,ZodNumberFormat:()=>Xl,ZodObject:()=>dy,ZodOptional:()=>Yl,ZodPipe:()=>my,ZodPrefault:()=>NU,ZodPreprocess:()=>qU,ZodPromise:()=>ZU,ZodReadonly:()=>VU,ZodRealError:()=>lo,ZodRecord:()=>af,ZodSet:()=>IU,ZodString:()=>uf,ZodStringFormat:()=>Tt,ZodSuccess:()=>UU,ZodSymbol:()=>fU,ZodTemplateLiteral:()=>HU,ZodTransform:()=>kU,ZodTuple:()=>EU,ZodType:()=>Ce,ZodULID:()=>iE,ZodURL:()=>cy,ZodUUID:()=>Os,ZodUndefined:()=>mU,ZodUnion:()=>py,ZodUnknown:()=>yU,ZodVoid:()=>wU,ZodXID:()=>sE,ZodXor:()=>bU,_ZodString:()=>Y0,_default:()=>DU,_function:()=>DW,any:()=>hW,array:()=>qe,base64:()=>WZ,base64url:()=>JZ,bigint:()=>lW,boolean:()=>gr,catch:()=>jU,check:()=>NW,cidrv4:()=>BZ,cidrv6:()=>ZZ,clone:()=>gt,codec:()=>kW,coerce:()=>tL,compile:()=>tM,config:()=>lr,core:()=>zi,creditCard:()=>YZ,cuid:()=>LZ,cuid2:()=>jZ,currencyCode:()=>oW,custom:()=>bE,date:()=>yW,decode:()=>nU,decodeAsync:()=>iU,deepPartial:()=>BW,describe:()=>zW,discriminatedUnion:()=>fy,e164:()=>XZ,email:()=>PZ,emoji:()=>MZ,encode:()=>rU,encodeAsync:()=>oU,endsWith:()=>Wp,enum:()=>Yr,exactOptional:()=>TU,file:()=>RW,flattenError:()=>mg,float32:()=>sW,float64:()=>aW,formatError:()=>hg,fromJSONSchema:()=>HW,function:()=>DW,getDiscriminatedOption:()=>Kz,getErrorMap:()=>JCe,globalRegistry:()=>Jr,gt:()=>Ts,gte:()=>Ro,guid:()=>kZ,hash:()=>iW,hex:()=>nW,hostname:()=>rW,httpUrl:()=>zZ,iban:()=>QZ,includes:()=>Bp,input:()=>WW,instanceof:()=>UW,int:()=>J0,int32:()=>cW,int64:()=>dW,intersection:()=>ff,invertCodec:()=>TW,ipv4:()=>GZ,ipv6:()=>KZ,iso:()=>Ql,json:()=>jW,jwt:()=>eW,keyof:()=>vW,ksuid:()=>VZ,lazy:()=>BU,length:()=>Bl,literal:()=>ae,locales:()=>Fp,looseObject:()=>Xr,looseRecord:()=>SW,lowercase:()=>Hp,lt:()=>ks,lte:()=>$o,mac:()=>HZ,map:()=>xW,maxLength:()=>Kl,maxSize:()=>qc,memoizer:()=>Cg,meta:()=>MW,mime:()=>Xp,minLength:()=>qa,minSize:()=>Cs,multipleOf:()=>Fc,nan:()=>PW,nanoid:()=>UZ,nativeEnum:()=>$W,negative:()=>O0,never:()=>yE,nonnegative:()=>N0,nonoptional:()=>MU,nonpositive:()=>D0,normalize:()=>Yp,null:()=>uy,nullable:()=>ay,nullish:()=>IW,number:()=>yt,object:()=>X,optional:()=>kt,output:()=>JW,overwrite:()=>Ni,parse:()=>YM,parseAsync:()=>QM,partialRecord:()=>bW,pipe:()=>X0,positive:()=>C0,prefault:()=>zU,preprocess:()=>yy,prettifyError:()=>D1,promise:()=>OW,properties:()=>Jp,property:()=>z0,readonly:()=>GU,record:()=>Ct,refine:()=>JU,regex:()=>Gp,regexes:()=>Eo,registry:()=>i0,safeDecode:()=>aU,safeDecodeAsync:()=>uU,safeEncode:()=>sU,safeEncodeAsync:()=>cU,safeParse:()=>eU,safeParseAsync:()=>tU,set:()=>EW,setErrorMap:()=>WCe,size:()=>Hl,slugify:()=>rf,startsWith:()=>Zp,strictObject:()=>wW,string:()=>O,stringFormat:()=>tW,stringbool:()=>LW,success:()=>AW,superRefine:()=>XU,symbol:()=>fW,templateLiteral:()=>CW,toJSONSchema:()=>Zl,toLowerCase:()=>ef,toUpperCase:()=>tf,toZod:()=>sg,transform:()=>vE,treeifyError:()=>O1,trim:()=>Qp,tuple:()=>$U,uint32:()=>uW,uint64:()=>pW,ulid:()=>FZ,undefined:()=>mW,union:()=>It,unknown:()=>Ut,uppercase:()=>Kp,url:()=>NZ,util:()=>D,uuid:()=>TZ,uuidv4:()=>CZ,uuidv6:()=>OZ,uuidv7:()=>DZ,validate:()=>Tp,validateAsync:()=>Cp,void:()=>gW,withParser:()=>s0,xid:()=>qZ,xor:()=>_W});var zi={};Ht(zi,{$ZodAny:()=>wx,$ZodArray:()=>Ex,$ZodAsyncError:()=>co,$ZodBase64:()=>nx,$ZodBase64URL:()=>ix,$ZodBigInt:()=>Rg,$ZodBigIntFormat:()=>hx,$ZodBoolean:()=>Np,$ZodCIDRv4:()=>QS,$ZodCIDRv6:()=>tx,$ZodCUID:()=>HS,$ZodCUID2:()=>KS,$ZodCatch:()=>qx,$ZodCheck:()=>Pt,$ZodCheckBigIntFormat:()=>_z,$ZodCheckEndsWith:()=>Cz,$ZodCheckGreaterThan:()=>kS,$ZodCheckIncludes:()=>kz,$ZodCheckLengthEquals:()=>Rz,$ZodCheckLessThan:()=>PS,$ZodCheckLowerCase:()=>Az,$ZodCheckMaxLength:()=>Ez,$ZodCheckMaxSize:()=>bz,$ZodCheckMimeType:()=>Nz,$ZodCheckMinLength:()=>$z,$ZodCheckMinSize:()=>Sz,$ZodCheckMultipleOf:()=>vz,$ZodCheckNumberFormat:()=>wz,$ZodCheckOverwrite:()=>zz,$ZodCheckProperties:()=>Dz,$ZodCheckProperty:()=>Oz,$ZodCheckRegex:()=>Iz,$ZodCheckSizeEquals:()=>xz,$ZodCheckStartsWith:()=>Tz,$ZodCheckStringFormat:()=>Op,$ZodCheckUpperCase:()=>Pz,$ZodCodec:()=>Mp,$ZodCreditCard:()=>cx,$ZodCustom:()=>Zx,$ZodCustomStringFormat:()=>fx,$ZodCyclicError:()=>Yx,$ZodDate:()=>xx,$ZodDefault:()=>Ux,$ZodDiscriminatedUnion:()=>Ix,$ZodE164:()=>sx,$ZodEmail:()=>US,$ZodEmoji:()=>VS,$ZodEncodeError:()=>Lc,$ZodEnum:()=>Cx,$ZodError:()=>C1,$ZodExactOptional:()=>zx,$ZodFile:()=>Dx,$ZodFunction:()=>Kx,$ZodGUID:()=>zS,$ZodIBAN:()=>lx,$ZodIPv4:()=>JS,$ZodIPv6:()=>XS,$ZodISODate:()=>qz,$ZodISODateTime:()=>Fz,$ZodISODuration:()=>Gz,$ZodISOTime:()=>Vz,$ZodIntersection:()=>Ax,$ZodJWT:()=>px,$ZodKSUID:()=>WS,$ZodLazy:()=>Up,$ZodLiteral:()=>Ox,$ZodMAC:()=>YS,$ZodMap:()=>kx,$ZodNaN:()=>Vx,$ZodNanoID:()=>GS,$ZodNever:()=>bx,$ZodNonOptional:()=>jx,$ZodNull:()=>vx,$ZodNullable:()=>Mx,$ZodNumber:()=>$g,$ZodNumberFormat:()=>mx,$ZodObject:()=>$x,$ZodObjectJIT:()=>Hz,$ZodOptional:()=>Ag,$ZodPipe:()=>Pg,$ZodPrefault:()=>Lx,$ZodPreprocess:()=>Bz,$ZodPromise:()=>Bx,$ZodReadonly:()=>Gx,$ZodRealError:()=>uo,$ZodRecord:()=>Px,$ZodRegistry:()=>o0,$ZodSet:()=>Tx,$ZodString:()=>jc,$ZodStringFormat:()=>St,$ZodSuccess:()=>Fx,$ZodSymbol:()=>gx,$ZodTemplateLiteral:()=>Hx,$ZodTransform:()=>Nx,$ZodTuple:()=>Ig,$ZodType:()=>be,$ZodULID:()=>BS,$ZodURL:()=>qS,$ZodUUID:()=>MS,$ZodUndefined:()=>yx,$ZodUnion:()=>zp,$ZodUnknown:()=>_x,$ZodVoid:()=>Sx,$ZodXID:()=>ZS,$ZodXor:()=>Rx,$brand:()=>P1,$constructor:()=>$,$input:()=>Xz,$output:()=>Jz,Doc:()=>jl,INVALID:()=>qn,JSONSchema:()=>RZ,JSONSchemaGenerator:()=>B0,NEVER:()=>A1,TimePrecision:()=>oM,URL_BAD_FORMAT:()=>Lz,URL_UNPARSEABLE:()=>_g,ZodCompileAsyncError:()=>Di,ZodCompileUnsupportedError:()=>Be,_any:()=>R0,_array:()=>uM,_base64:()=>Xg,_base64url:()=>Yg,_bigint:()=>_0,_boolean:()=>w0,_catch:()=>OCe,_check:()=>lZ,_cidrv4:()=>Wg,_cidrv6:()=>Jg,_coercedBigint:()=>aM,_coercedBoolean:()=>sM,_coercedDate:()=>cM,_coercedNumber:()=>iM,_coercedString:()=>nM,_creditCard:()=>d0,_cuid:()=>qg,_cuid2:()=>Vg,_custom:()=>U0,_date:()=>k0,_decode:()=>vS,_decodeAsync:()=>_S,_default:()=>kCe,_discriminatedUnion:()=>vCe,_e164:()=>Qg,_email:()=>Dg,_emoji:()=>jg,_encode:()=>yS,_encodeAsync:()=>wS,_endsWith:()=>Wp,_enum:()=>ECe,_file:()=>M0,_float32:()=>h0,_float64:()=>g0,_gt:()=>Ts,_gte:()=>Ro,_guid:()=>Ng,_iban:()=>p0,_includes:()=>Bp,_int:()=>m0,_int32:()=>y0,_int64:()=>b0,_intersection:()=>wCe,_ipv4:()=>Bg,_ipv6:()=>Zg,_isoDate:()=>ry,_isoDateTime:()=>ty,_isoDuration:()=>oy,_isoTime:()=>ny,_jwt:()=>ey,_ksuid:()=>Kg,_lazy:()=>MCe,_length:()=>Bl,_literal:()=>RCe,_lowercase:()=>Hp,_lt:()=>ks,_lte:()=>$o,_mac:()=>l0,_map:()=>SCe,_max:()=>$o,_maxLength:()=>Kl,_maxSize:()=>qc,_mime:()=>Xp,_min:()=>Ro,_minLength:()=>qa,_minSize:()=>Cs,_multipleOf:()=>Fc,_nan:()=>T0,_nanoid:()=>Fg,_nativeEnum:()=>$Ce,_negative:()=>O0,_never:()=>A0,_nonnegative:()=>N0,_nonoptional:()=>TCe,_nonpositive:()=>D0,_normalize:()=>Yp,_null:()=>$0,_nullable:()=>PCe,_number:()=>f0,_optional:()=>ACe,_overwrite:()=>Ni,_parse:()=>$p,_parseAsync:()=>Rp,_pipe:()=>DCe,_positive:()=>C0,_promise:()=>UCe,_properties:()=>Jp,_property:()=>z0,_readonly:()=>NCe,_record:()=>bCe,_refine:()=>L0,_regex:()=>Gp,_safeDecode:()=>SS,_safeDecodeAsync:()=>ES,_safeEncode:()=>bS,_safeEncodeAsync:()=>xS,_safeParse:()=>Ip,_safeParseAsync:()=>Pp,_set:()=>xCe,_size:()=>Hl,_slugify:()=>rf,_startsWith:()=>Zp,_string:()=>u0,_stringFormat:()=>Vc,_stringbool:()=>V0,_success:()=>CCe,_superRefine:()=>j0,_symbol:()=>x0,_templateLiteral:()=>zCe,_toLowerCase:()=>ef,_toUpperCase:()=>tf,_transform:()=>ICe,_trim:()=>Qp,_tuple:()=>_Ce,_uint32:()=>v0,_uint64:()=>S0,_ulid:()=>Gg,_undefined:()=>E0,_union:()=>gCe,_unknown:()=>I0,_uppercase:()=>Kp,_url:()=>Vp,_uuid:()=>zg,_uuidv4:()=>Mg,_uuidv6:()=>Ug,_uuidv7:()=>Lg,_void:()=>P0,_xid:()=>Hg,_xor:()=>yCe,base64Charset:()=>rx,base64urlCharset:()=>Eg,canParseURL:()=>jz,clone:()=>gt,compile:()=>tM,compileFn:()=>a0,config:()=>lr,createStandardJSONSchemaMethod:()=>nf,createToJSONSchemaMethod:()=>dM,decode:()=>dB,decodeAsync:()=>fB,describe:()=>F0,encode:()=>lB,encodeAsync:()=>pB,extractDefs:()=>Hc,finalize:()=>Kc,flattenError:()=>mg,formatError:()=>hg,getDiscriminatedOption:()=>Kz,globalConfig:()=>zr,globalRegistry:()=>Jr,handleUnrepresentable:()=>Pr,initializeContext:()=>Gc,isBackEdge:()=>e0,isRecursiveSchema:()=>Qx,isValidBase64:()=>xg,isValidBase64URL:()=>ox,isValidCIDRv6:()=>ex,isValidCreditCard:()=>ax,isValidIBAN:()=>ux,isValidIPv6:()=>Sg,isValidJWT:()=>dx,locales:()=>Fp,memoizer:()=>Cg,mergeValues:()=>Dp,meta:()=>q0,parse:()=>Ml,parseAsync:()=>Ul,parseURLObject:()=>MB,prettifyError:()=>D1,process:()=>Rt,processSchema:()=>Rt,regexes:()=>Eo,registry:()=>i0,safeDecode:()=>hB,safeDecodeAsync:()=>yB,safeEncode:()=>mB,safeEncodeAsync:()=>gB,safeParse:()=>Ap,safeParseAsync:()=>kp,standardProps:()=>NS,stripTabAndNewline:()=>bg,toDotPath:()=>cB,toJSONSchema:()=>Zl,toZod:()=>sg,treeifyError:()=>O1,urlHostnameOk:()=>jS,urlProtocolOk:()=>FS,util:()=>D,validate:()=>Tp,validateAsync:()=>Cp,validateURL:()=>LS,version:()=>Mz,withParser:()=>s0});var D={};Ht(D,{BIGINT_FORMAT_RANGES:()=>lg,CONSTANT_CATCH:()=>hS,Class:()=>y1,NUMBER_FORMAT_RANGES:()=>ug,aborted:()=>Fn,allowsEval:()=>_1,assert:()=>YAe,assertEqual:()=>ZAe,assertIs:()=>JAe,assertNever:()=>XAe,assertNotEqual:()=>WAe,assignProp:()=>Wr,attachSchema:()=>mS,base64ToUint8Array:()=>rB,base64urlToUint8Array:()=>lPe,cached:()=>bp,captureStackTrace:()=>pS,cleanEnum:()=>uPe,cleanRegex:()=>ja,clone:()=>gt,cloneDef:()=>tPe,codePointLength:()=>zl,constantCatch:()=>R1,createTransparentProxy:()=>aPe,defineLazy:()=>v1,defineLazyInternal:()=>Me,derived:()=>mPe,esc:()=>jn,escapeRegex:()=>Xo,explicitlyAborted:()=>x1,extend:()=>JK,finalizeIssue:()=>ao,floatSafeRemainder:()=>ag,getElementAtPath:()=>rPe,getEnumValues:()=>wp,getLengthableOrigin:()=>pg,getParsedType:()=>sPe,getSizableOrigin:()=>dg,hexToUint8Array:()=>pPe,hide:()=>fg,installLazyProp:()=>$1,isObject:()=>Nl,isPlainObject:()=>Jo,issue:()=>Ep,joinValues:()=>I,jsonStringifyReplacer:()=>_p,members:()=>E1,merge:()=>QK,mergeDefs:()=>Wo,normalizeParams:()=>j,nullish:()=>dS,numKeys:()=>iPe,objectClone:()=>QAe,omit:()=>WK,optionalKeys:()=>S1,own:()=>Ps,parsedType:()=>z,partial:()=>eB,pick:()=>ZK,prefixIssues:()=>so,primitiveTypes:()=>b1,promiseAllObject:()=>nPe,propertyKeyTypes:()=>cg,randomString:()=>oPe,rawShape:()=>Sp,required:()=>tB,safeExtend:()=>YK,shallowClone:()=>xp,slugify:()=>w1,stringifyPrimitive:()=>N,toZod:()=>sg,uint8ArrayToBase64:()=>nB,uint8ArrayToBase64url:()=>dPe,uint8ArrayToHex:()=>fPe,unwrapMessage:()=>vp});function ZAe(t){return t}function WAe(t){return t}function sg(){return t=>t}function JAe(t){}function XAe(t){throw new Error("Unexpected value in exhaustive check")}function YAe(t){}function wp(t){let e=Object.values(t).filter(o=>typeof o=="number");return Object.entries(t).filter(([o,n])=>e.indexOf(+o)===-1).map(([o,n])=>n)}function I(t,e="|"){return t.map(r=>N(r)).join(e)}function _p(t,e){return typeof e=="bigint"?e.toString():e}var g1=class{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;return e!==void 0&&(this._value=e(),this._getter=void 0),this._value}};function bp(t){return new g1(t)}function dS(t){return t==null}function ja(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function ag(t,e){let r=t/e,o=Math.round(r),n=4*Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-o)<n?0:r-o}var HK=Symbol("evaluating");function v1(t,e,r){let o;Object.defineProperty(t,e,{get(){if(o!==HK)return o===void 0&&(o=HK,o=r()),o},set(n){Object.defineProperty(t,e,{value:n})},configurable:!0})}function QAe(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function Wr(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Sp(t){let e=Object.getOwnPropertyDescriptor(t,"shape");return e?.get?e.get.raw:e?.value}function La(t){return Sp(t._zod.def)??t._zod.def.shape}function KK(t,e,r){Object.defineProperty(t,e,{get(){let o=r();return Wr(this,e,o),o},enumerable:!0,configurable:!0})}function BK(t,e,r){e in t?Wr(t,e,r):t[e]=r}function Dl(t,e,r,o){let n=La(e);for(let i of r){let s=Object.getOwnPropertyDescriptor(n,i);s.enumerable&&(s.get?KK(t,i,()=>{let a=e._zod.def.shape[i];return o?o(a,i):a}):BK(t,i,o?o(s.value,i):s.value))}}function ePe(t,e){for(let r of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,r);o.enumerable&&(o.get?KK(t,r,()=>e[r]):BK(t,r,o.value))}}function Wo(...t){let e={};for(let r of t){let o=Object.getOwnPropertyDescriptors(r);Object.assign(e,o)}return Object.defineProperties({},e)}function tPe(t){return Wo(t._zod.def)}function rPe(t,e){return e?e.reduce((r,o)=>r?.[o],t):t}function nPe(t){let e=Object.keys(t),r=e.map(o=>t[o]);return Promise.all(r).then(o=>{let n={};for(let i=0;i<e.length;i++)n[e[i]]=o[i];return n})}function oPe(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let o=0;o<t;o++)r+=e[Math.floor(Math.random()*e.length)];return r}function jn(t){return JSON.stringify(t)}function w1(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var pS="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function Nl(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var _1=bp(()=>{if(zr.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Jo(t){if(Nl(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(Nl(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function xp(t){return Jo(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function iPe(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var sPe=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},cg=new Set(["string","number","symbol"]),b1=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Xo(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function gt(t,e,r){let o=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(o._zod.parent=t),o}function j(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function aPe(t){let e;return new Proxy({},{get(r,o,n){return e??(e=t()),Reflect.get(e,o,n)},set(r,o,n,i){return e??(e=t()),Reflect.set(e,o,n,i)},has(r,o){return e??(e=t()),Reflect.has(e,o)},deleteProperty(r,o){return e??(e=t()),Reflect.deleteProperty(e,o)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,o){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,o)},defineProperty(r,o,n){return e??(e=t()),Reflect.defineProperty(e,o,n)}})}function N(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function S1(t){return Object.keys(t).filter(e=>t[e]._zod.optin!==void 0&&t[e]._zod.optout==="optional")}var ug={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},lg={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function ZK(t,e){let r=t._zod.def,o=r.checks;if(o&&o.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let i={};return Dl(i,t,fS(t,e)),gt(t,Wo(r,{shape:i,checks:[]}))}function fS(t,e){let r=La(t),o=[];for(let n of Reflect.ownKeys(e)){if(!Object.getOwnPropertyDescriptor(r,n)?.enumerable)throw new Error(`Unrecognized key: "${String(n)}"`);e[n]&&o.push(n)}return o}function WK(t,e){let r=t._zod.def,o=r.checks;if(o&&o.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let i=new Set(fS(t,e)),s={};return Dl(s,t,Reflect.ownKeys(La(t)).filter(a=>!i.has(a))),gt(t,Wo(r,{shape:s,checks:[]}))}function JK(t,e){if(!Jo(e))throw new Error("Invalid input to extend: expected a plain object");let r=t._zod.def.checks;if(r&&r.length>0){let n=La(t);for(let i of Reflect.ownKeys(e))if(Object.getOwnPropertyDescriptor(n,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return gt(t,Wo(t._zod.def,{shape:XK(t,e)}))}function XK(t,e){let r={};return Dl(r,t,Reflect.ownKeys(La(t))),ePe(r,e),r}function YK(t,e){if(!Jo(e))throw new Error("Invalid input to safeExtend: expected a plain object");return gt(t,Wo(t._zod.def,{shape:XK(t,e)}))}function QK(t,e){if(!e?._zod?.def)throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(t._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r={};Dl(r,t,Reflect.ownKeys(La(t))),Dl(r,e,Reflect.ownKeys(La(e)));let o=Wo(t._zod.def,{shape:r,get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return gt(t,o)}function eB(t,e,r,o="partial"){let i=e._zod.def.checks;if(i&&i.length>0)throw new Error(`.${o}() cannot be used on object schemas containing refinements`);let a=r?new Set(fS(e,r)):void 0,c={};return Dl(c,e,Reflect.ownKeys(La(e)),t&&((u,l)=>a&&!a.has(l)?u:new t({type:"optional",innerType:u}))),gt(e,Wo(e._zod.def,{shape:c,checks:[]}))}function tB(t,e,r){let o=r?new Set(fS(e,r)):void 0,n={};return Dl(n,e,Reflect.ownKeys(La(e)),(i,s)=>o&&!o.has(s)?i:new t({type:"nonoptional",innerType:i})),gt(e,Wo(e._zod.def,{shape:n}))}function Fn(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function x1(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue===!1)return!0;return!1}function so(t,e){return e.map(r=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(t),r})}function vp(t){return typeof t=="string"?t:t?.message}function mS(t,e,r){var o;for(let n=e;n<t.length;n++)(o=t[n]).schema??(o.schema=r)}function ao(t,e,r){var o;let n=t.inst?._zod?.traits;n?.has("$ZodType")&&(n.has("$ZodCheck")?(o=t).schema??(o.schema=t.inst):t.schema=t.inst);let i=t.schema!==t.inst?t.schema?._zod.def?.error:void 0,s=t.message?t.message:vp(t.inst?._zod.def?.error?.(t))??vp(i?.(t))??vp(e?.error?.(t))??vp(r.customError?.(t))??vp(r.localeError?.(t))??"Invalid input",a={};for(let c of Object.keys(t))c==="inst"||c==="schema"||c==="continue"||c==="input"||c==="__proto__"||(a[c]=t[c]);return a.path??(a.path=[]),a.message=s,e?.reportInput&&(a.input=t.input),a}function dg(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}var cPe=/[\uD800-\uDBFF]/;function zl(t){let e=t.length;if(!cPe.test(t))return e;let r=e;for(let o=0;o<e-1;o++)(t.charCodeAt(o)&64512)===55296&&(t.charCodeAt(o+1)&64512)===56320&&(r--,o++);return r}function pg(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function z(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let r=t;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return e}function Ep(...t){let[e,r,o]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:o}:{...e}}function uPe(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function rB(t){let e=atob(t),r=new Uint8Array(e.length);for(let o=0;o<e.length;o++)r[o]=e.charCodeAt(o);return r}function nB(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}function lPe(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-e.length%4)%4);return rB(e+r)}function dPe(t){return nB(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function pPe(t){let e=t.replace(/^0x/,"");if(e.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(e.length/2);for(let o=0;o<e.length;o+=2)r[o/2]=Number.parseInt(e.slice(o,o+2),16);return r}function fPe(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var y1=class{constructor(...e){}};function E1(t,e){for(let r in e){let o=Object.getOwnPropertyDescriptor(e,r);o.get?Object.defineProperty(t,r,{...o,enumerable:!1}):hPe(t,r,o.value)}}function Ps(t,e,r,o=!0){return Object.defineProperty(t,e,{configurable:!0,writable:!0,enumerable:o,value:r}),r}function fg(t,e,r){return Ps(t,e,r,!1)}function mPe(t,e){for(let r in t){let o=t[r];Object.defineProperty(e,r,{configurable:!0,enumerable:!0,get(){return Ps(this,r,o(this))},set(n){Ps(this,r,n)}})}return e}function hPe(t,e,r){Object.defineProperty(t,e,{configurable:!0,get(){return this==null?r:Ps(this,e,r.bind(this))},set(o){Ps(this,e,o)}})}function gPe(t,e){let r=Object.getPrototypeOf(t);return e in r?void 0:r}var h1,Uc=!1,yPe={configurable:!0,get(){Uc=!0}};function Me(t,e,r){let o=Object.getPrototypeOf(t._zod);if(e in o&&h1!==t._zod){h1=void 0;return}h1=t._zod,Object.defineProperty(o,e,{configurable:!0,get(){Object.defineProperty(this,e,yPe);let n=Uc;Uc=!1;try{let i=r(this);return Uc?delete this[e]:Object.defineProperty(this,e,{configurable:!0,writable:!0,value:i}),Uc=Uc||n,i}catch(i){throw delete this[e],Uc=Uc||n,i}},set(n){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:n})}})}function $1(t,e,r,o){let n=gPe(t,e);n&&Object.defineProperty(n,e,{configurable:!0,get(){let i={configurable:!0,writable:!0,enumerable:o,value:void 0};return Object.defineProperty(this,e,i),i.value=r(this),Object.defineProperty(this,e,i),i.value},set(i){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:o,value:i})}})}var hS="~constantCatch";function R1(t){let e=()=>t;return e[hS]=!0,e}var oB,A1=Object.freeze({status:"aborted"}),I1={value:void 0,enumerable:!1},iB="captureStackTrace"in Error?Error:null;function vPe(t){let e=iB;if(e){let r=e.stackTraceLimit;if(typeof r=="number"){try{e.stackTraceLimit=0}catch{return iB=null,new t}try{return new t}finally{e.stackTraceLimit=r}}}return new t}function $(t,e,r,o){let n={};function i(p){this.def=p,this.constr=d,this.traits=new Set}i.prototype=n;let s=r,a=s&&new WeakSet;function c(p,f){if(p._zod){if(p._zod.traits.has(t))return}else{I1.value=new i(f);try{Object.defineProperty(p,"_zod",I1)}finally{I1.value=void 0}}if(p._zod.traits.add(t),e(p,f),a){let y=Object.getPrototypeOf(p),w=p._zod.constr.prototype,b=y;for(;b&&b!==w;)b=Object.getPrototypeOf(b);let S=b??y;a.has(S)||(a.add(S),E1(S,s))}let h=d.prototype;for(let y in h)Object.prototype.hasOwnProperty.call(h,y)&&(y in p||(p[y]=h[y].bind(p)))}let u=o?.Parent??Object;class l extends u{}Object.defineProperty(l,"name",{value:t});function d(p){let f=o?.Parent?vPe(l):this;c(f,p);let h=f._zod.deferred;if(h){for(let w of h)w();f._zod.deferred=void 0}let y=globalThis.__zod_globalConfig?.postProcessor;return y&&y(f),f}return Object.defineProperty(d,"init",{value:c}),Object.defineProperty(d,Symbol.hasInstance,{value:p=>o?.Parent&&p instanceof o.Parent?!0:p?._zod?.traits?.has(t)}),Object.defineProperty(d,"name",{value:t}),d}var P1=Symbol("zod_brand"),co=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Lc=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(oB=globalThis).__zod_globalConfig??(oB.__zod_globalConfig={});var zr=globalThis.__zod_globalConfig;function lr(t){return t&&Object.assign(zr,t),zr}function wPe(){let t=this._zod;return t.message??(t.message=JSON.stringify(t.def,_p,2)),t.message}function _Pe(t){this._zod.message=t}var bPe={get:wPe,set:_Pe,enumerable:!0,configurable:!0},T1={value:void 0,enumerable:!1},sB=new WeakSet([Object.prototype,Error.prototype]),aB=(t,e)=>{t.name="$ZodError",T1.value=e,Object.defineProperty(t,"issues",T1),T1.value=void 0,Object.defineProperty(t,"message",bPe);let r=Object.getPrototypeOf(t);sB.has(r)||(sB.add(r),Object.defineProperty(r,"toString",{configurable:!0,enumerable:!1,get(){let o=()=>this.message;return Object.defineProperty(this,"toString",{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,"toString",{value:o,configurable:!0,writable:!0})}}))},C1=$("$ZodError",aB),uo=$("$ZodError",aB,void 0,{Parent:Error});function SPe(t,e,r){return Object.prototype.hasOwnProperty.call(t,e)||(e==="__proto__"?Object.defineProperty(t,e,{value:r(),writable:!0,enumerable:!0,configurable:!0}):t[e]=r()),t[e]}function mg(t,e=r=>r.message){let r={},o=[];for(let n of t.issues)n.path.length>0?SPe(r,n.path[0],()=>[]).push(e(n)):o.push(e(n));return{formErrors:o,fieldErrors:r}}function hg(t,e=r=>r.message){let r={_errors:[]},o=(n,i=[])=>{for(let s of n.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>o({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")o({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")o({issues:s.issues},[...i,...s.path]);else{let a=[...i,...s.path];if(a.length===0)r._errors.push(e(s));else{let c=r,u=0;for(;u<a.length;){let l=a[u],d=u===a.length-1;if(l==="_errors"){d&&c._errors.push(e(s)),u++;continue}Object.prototype.hasOwnProperty.call(c,l)||Object.defineProperty(c,l,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let p=c[l];d&&p._errors.push(e(s)),c=p,u++}}}};return o(t),r}function O1(t,e=r=>r.message){let r={errors:[]},o=(n,i=[])=>{var s;for(let a of n.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(c=>o({issues:c},[...i,...a.path]));else if(a.code==="invalid_key")o({issues:a.issues},[...i,...a.path]);else if(a.code==="invalid_element")o({issues:a.issues},[...i,...a.path]);else{let c=[...i,...a.path];if(c.length===0){r.errors.push(e(a));continue}let u=r,l=0;for(;l<c.length;){let d=c[l],p=l===c.length-1;typeof d=="string"?(u.properties??(u.properties={}),Object.prototype.hasOwnProperty.call(u.properties,d)||Object.defineProperty(u.properties,d,{value:{errors:[]},enumerable:!0,writable:!0,configurable:!0}),u=u.properties[d]):(u.items??(u.items=[]),(s=u.items)[d]??(s[d]={errors:[]}),u=u.items[d]),p&&u.errors.push(e(a)),l++}}};return o(t),r}function cB(t){let e=[],r=t.map(o=>typeof o=="object"?o.key:o);for(let o of r)typeof o=="number"?e.push(`[${o}]`):typeof o=="symbol"?e.push(`[${JSON.stringify(String(o))}]`):/[^\w$]/.test(o)?e.push(`[${JSON.stringify(o)}]`):(e.length&&e.push("."),e.push(o));return e.join("")}function D1(t){let e=[],r=[...t.issues].sort((o,n)=>(o.path??[]).length-(n.path??[]).length);for(let o of r)e.push(`\u2716 ${o.message}`),o.path?.length&&e.push(` \u2192 at ${cB(o.path)}`);return e.join(`
67
+ deps: ${r}}`};var Sdt={keyword:"dependencies",type:"object",schemaType:"object",error:Da.error,code(t){let[e,r]=xdt(t);EIe(t,e),$Ie(t,r)}};function xdt({schema:t}){let e={},r={};for(let o in t){if(o==="__proto__")continue;let n=Array.isArray(t[o])?e:r;n[o]=t[o]}return[e,r]}function EIe(t,e=t.schema){let{gen:r,data:o,it:n}=t;if(Object.keys(e).length===0)return;let i=r.let("missing");for(let s in e){let a=e[s];if(a.length===0)continue;let c=(0,iS.propertyInData)(r,o,s,n.opts.ownProperties);t.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),n.allErrors?r.if(c,()=>{for(let u of a)(0,iS.checkReportMissingProp)(t,u)}):(r.if((0,lK._)`${c} && (${(0,iS.checkMissingProp)(t,a,i)})`),(0,iS.reportMissingProp)(t,i),r.else())}}Da.validatePropertyDeps=EIe;function $Ie(t,e=t.schema){let{gen:r,data:o,keyword:n,it:i}=t,s=r.name("valid");for(let a in e)(0,bdt.alwaysValidSchema)(i,e[a])||(r.if((0,iS.propertyInData)(r,o,a,i.opts.ownProperties),()=>{let c=t.subschema({keyword:n,schemaProp:a},s);t.mergeValidEvaluated(c,s)},()=>r.var(s,!0)),t.ok(s))}Da.validateSchemaDeps=$Ie;Da.default=Sdt});var AIe=U(dK=>{"use strict";Object.defineProperty(dK,"__esModule",{value:!0});var IIe=je(),Edt=mt(),$dt={message:"property name must be valid",params:({params:t})=>(0,IIe._)`{propertyName: ${t.propertyName}}`},Rdt={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:$dt,code(t){let{gen:e,schema:r,data:o,it:n}=t;if((0,Edt.alwaysValidSchema)(n,r))return;let i=e.name("valid");e.forIn("key",o,s=>{t.setParams({propertyName:s}),t.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},i),e.if((0,IIe.not)(i),()=>{t.error(!0),n.allErrors||e.break()})}),t.ok(i)}};dK.default=Rdt});var fK=U(pK=>{"use strict";Object.defineProperty(pK,"__esModule",{value:!0});var YN=Ti(),Is=je(),Idt=zc(),QN=mt(),Adt={message:"must NOT have additional properties",params:({params:t})=>(0,Is._)`{additionalProperty: ${t.additionalProperty}}`},Pdt={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Adt,code(t){let{gen:e,schema:r,parentSchema:o,data:n,errsCount:i,it:s}=t;if(!i)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=s;if(s.props=!0,c.removeAdditional!=="all"&&(0,QN.alwaysValidSchema)(s,r))return;let u=(0,YN.allSchemaProperties)(o.properties),l=(0,YN.allSchemaProperties)(o.patternProperties);d(),t.ok((0,Is._)`${i} === ${Idt.default.errors}`);function d(){e.forIn("key",n,w=>{!u.length&&!l.length?h(w):e.if(p(w),()=>h(w))})}function p(w){let b;if(u.length>8){let S=(0,QN.schemaRefOrVal)(s,o.properties,"properties");b=(0,YN.isOwnProperty)(e,S,w)}else u.length?b=(0,Is.or)(...u.map(S=>(0,Is._)`${w} === ${S}`)):b=Is.nil;return l.length&&(b=(0,Is.or)(b,...l.map(S=>(0,Is._)`${(0,YN.usePattern)(t,S)}.test(${w})`))),(0,Is.not)(b)}function f(w){e.code((0,Is._)`delete ${n}[${w}]`)}function h(w){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(w);return}if(r===!1){t.setParams({additionalProperty:w}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,QN.alwaysValidSchema)(s,r)){let b=e.name("valid");c.removeAdditional==="failing"?(y(w,b,!1),e.if((0,Is.not)(b),()=>{t.reset(),f(w)})):(y(w,b),a||e.if((0,Is.not)(b),()=>e.break()))}}function y(w,b,S){let x={keyword:"additionalProperties",dataProp:w,dataPropType:QN.Type.Str};S===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(x,b)}}};pK.default=Pdt});var TIe=U(hK=>{"use strict";Object.defineProperty(hK,"__esModule",{value:!0});var kdt=Gb(),PIe=Ti(),mK=mt(),kIe=fK(),Tdt={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:o,data:n,it:i}=t;i.opts.removeAdditional==="all"&&o.additionalProperties===void 0&&kIe.default.code(new kdt.KeywordCxt(i,kIe.default,"additionalProperties"));let s=(0,PIe.allSchemaProperties)(r);for(let d of s)i.definedProperties.add(d);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=mK.mergeEvaluated.props(e,(0,mK.toHash)(s),i.props));let a=s.filter(d=>!(0,mK.alwaysValidSchema)(i,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,PIe.propertyInData)(e,n,d,i.opts.ownProperties)),l(d),i.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return i.opts.useDefaults&&!i.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};hK.default=Tdt});var NIe=U(gK=>{"use strict";Object.defineProperty(gK,"__esModule",{value:!0});var CIe=Ti(),e1=je(),OIe=mt(),DIe=mt(),Cdt={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:o,parentSchema:n,it:i}=t,{opts:s}=i,a=(0,CIe.allSchemaProperties)(r),c=a.filter(y=>(0,OIe.alwaysValidSchema)(i,r[y]));if(a.length===0||c.length===a.length&&(!i.opts.unevaluated||i.props===!0))return;let u=s.strictSchema&&!s.allowMatchingProperties&&n.properties,l=e.name("valid");i.props!==!0&&!(i.props instanceof e1.Name)&&(i.props=(0,DIe.evaluatedPropsToName)(e,i.props));let{props:d}=i;p();function p(){for(let y of a)u&&f(y),i.allErrors?h(y):(e.var(l,!0),h(y),e.if(l))}function f(y){for(let w in u)new RegExp(y).test(w)&&(0,OIe.checkStrictMode)(i,`property ${w} matches pattern ${y} (use allowMatchingProperties)`)}function h(y){e.forIn("key",o,w=>{e.if((0,e1._)`${(0,CIe.usePattern)(t,y)}.test(${w})`,()=>{let b=c.includes(y);b||t.subschema({keyword:"patternProperties",schemaProp:y,dataProp:w,dataPropType:DIe.Type.Str},l),i.opts.unevaluated&&d!==!0?e.assign((0,e1._)`${d}[${w}]`,!0):!b&&!i.allErrors&&e.if((0,e1.not)(l),()=>e.break())})})}}};gK.default=Cdt});var zIe=U(yK=>{"use strict";Object.defineProperty(yK,"__esModule",{value:!0});var Odt=mt(),Ddt={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:o}=t;if((0,Odt.alwaysValidSchema)(o,r)){t.fail();return}let n=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},n),t.failResult(n,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};yK.default=Ddt});var MIe=U(vK=>{"use strict";Object.defineProperty(vK,"__esModule",{value:!0});var Ndt=Ti(),zdt={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Ndt.validateUnion,error:{message:"must match a schema in anyOf"}};vK.default=zdt});var UIe=U(wK=>{"use strict";Object.defineProperty(wK,"__esModule",{value:!0});var t1=je(),Mdt=mt(),Udt={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,t1._)`{passingSchemas: ${t.passing}}`},Ldt={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Udt,code(t){let{gen:e,schema:r,parentSchema:o,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(n.opts.discriminator&&o.discriminator)return;let i=r,s=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(s,()=>t.reset(),()=>t.error(!0));function u(){i.forEach((l,d)=>{let p;(0,Mdt.alwaysValidSchema)(n,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,t1._)`${c} && ${s}`).assign(s,!1).assign(a,(0,t1._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(s,!0),e.assign(a,d),p&&t.mergeEvaluated(p,t1.Name)})})}}};wK.default=Ldt});var LIe=U(_K=>{"use strict";Object.defineProperty(_K,"__esModule",{value:!0});var jdt=mt(),Fdt={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let n=e.name("valid");r.forEach((i,s)=>{if((0,jdt.alwaysValidSchema)(o,i))return;let a=t.subschema({keyword:"allOf",schemaProp:s},n);t.ok(n),t.mergeEvaluated(a)})}};_K.default=Fdt});var qIe=U(bK=>{"use strict";Object.defineProperty(bK,"__esModule",{value:!0});var r1=je(),FIe=mt(),qdt={message:({params:t})=>(0,r1.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,r1._)`{failingKeyword: ${t.ifClause}}`},Vdt={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:qdt,code(t){let{gen:e,parentSchema:r,it:o}=t;r.then===void 0&&r.else===void 0&&(0,FIe.checkStrictMode)(o,'"if" without "then" and "else" is ignored');let n=jIe(o,"then"),i=jIe(o,"else");if(!n&&!i)return;let s=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),n&&i){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else n?e.if(a,u("then")):e.if((0,r1.not)(a),u("else"));t.pass(s,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let p=t.subschema({keyword:l},a);e.assign(s,a),t.mergeValidEvaluated(p,s),d?e.assign(d,(0,r1._)`${l}`):t.setParams({ifClause:l})}}}};function jIe(t,e){let r=t.schema[e];return r!==void 0&&!(0,FIe.alwaysValidSchema)(t,r)}bK.default=Vdt});var VIe=U(SK=>{"use strict";Object.defineProperty(SK,"__esModule",{value:!0});var Gdt=mt(),Hdt={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,Gdt.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};SK.default=Hdt});var GIe=U(xK=>{"use strict";Object.defineProperty(xK,"__esModule",{value:!0});var Kdt=iK(),Bdt=_Ie(),Zdt=sK(),Wdt=SIe(),Jdt=xIe(),Xdt=RIe(),Ydt=AIe(),Qdt=fK(),ept=TIe(),tpt=NIe(),rpt=zIe(),npt=MIe(),opt=UIe(),ipt=LIe(),spt=qIe(),apt=VIe();function cpt(t=!1){let e=[rpt.default,npt.default,opt.default,ipt.default,spt.default,apt.default,Ydt.default,Qdt.default,Xdt.default,ept.default,tpt.default];return t?e.push(Bdt.default,Wdt.default):e.push(Kdt.default,Zdt.default),e.push(Jdt.default),e}xK.default=cpt});var HIe=U(EK=>{"use strict";Object.defineProperty(EK,"__esModule",{value:!0});var _r=je(),upt={message:({schemaCode:t})=>(0,_r.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,_r._)`{format: ${t}}`},lpt={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:upt,code(t,e){let{gen:r,data:o,$data:n,schema:i,schemaCode:s,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;n?p():f();function p(){let h=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),y=r.const("fDef",(0,_r._)`${h}[${s}]`),w=r.let("fType"),b=r.let("format");r.if((0,_r._)`typeof ${y} == "object" && !(${y} instanceof RegExp)`,()=>r.assign(w,(0,_r._)`${y}.type || "string"`).assign(b,(0,_r._)`${y}.validate`),()=>r.assign(w,(0,_r._)`"string"`).assign(b,y)),t.fail$data((0,_r.or)(S(),x()));function S(){return c.strictSchema===!1?_r.nil:(0,_r._)`${s} && !${b}`}function x(){let R=l.$async?(0,_r._)`(${y}.async ? await ${b}(${o}) : ${b}(${o}))`:(0,_r._)`${b}(${o})`,T=(0,_r._)`(typeof ${b} == "function" ? ${R} : ${b}.test(${o}))`;return(0,_r._)`${b} && ${b} !== true && ${w} === ${e} && !${T}`}}function f(){let h=d.formats[i];if(!h){S();return}if(h===!0)return;let[y,w,b]=x(h);y===e&&t.pass(R());function S(){if(c.strictSchema===!1){d.logger.warn(T());return}throw new Error(T());function T(){return`unknown format "${i}" ignored in schema at path "${u}"`}}function x(T){let M=T instanceof RegExp?(0,_r.regexpCode)(T):c.code.formats?(0,_r._)`${c.code.formats}${(0,_r.getProperty)(i)}`:void 0,Z=r.scopeValue("formats",{key:i,ref:T,code:M});return typeof T=="object"&&!(T instanceof RegExp)?[T.type||"string",T.validate,(0,_r._)`${Z}.validate`]:["string",T,Z]}function R(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!l.$async)throw new Error("async format in sync schema");return(0,_r._)`await ${b}(${o})`}return typeof w=="function"?(0,_r._)`${b}(${o})`:(0,_r._)`${b}.test(${o})`}}}};EK.default=lpt});var KIe=U($K=>{"use strict";Object.defineProperty($K,"__esModule",{value:!0});var dpt=HIe(),ppt=[dpt.default];$K.default=ppt});var BIe=U(eg=>{"use strict";Object.defineProperty(eg,"__esModule",{value:!0});eg.contentVocabulary=eg.metadataVocabulary=void 0;eg.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];eg.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var WIe=U(RK=>{"use strict";Object.defineProperty(RK,"__esModule",{value:!0});var fpt=rIe(),mpt=gIe(),hpt=GIe(),gpt=KIe(),ZIe=BIe(),ypt=[fpt.default,mpt.default,(0,hpt.default)(),gpt.default,ZIe.metadataVocabulary,ZIe.contentVocabulary];RK.default=ypt});var XIe=U(n1=>{"use strict";Object.defineProperty(n1,"__esModule",{value:!0});n1.DiscrError=void 0;var JIe;(function(t){t.Tag="tag",t.Mapping="mapping"})(JIe||(n1.DiscrError=JIe={}))});var QIe=U(AK=>{"use strict";Object.defineProperty(AK,"__esModule",{value:!0});var tg=je(),IK=XIe(),YIe=UN(),vpt=Hb(),wpt=mt(),_pt={message:({params:{discrError:t,tagName:e}})=>t===IK.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,tg._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},bpt={keyword:"discriminator",type:"object",schemaType:"object",error:_pt,code(t){let{gen:e,data:r,schema:o,parentSchema:n,it:i}=t,{oneOf:s}=n;if(!i.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=o.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(o.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,tg._)`${r}${(0,tg.getProperty)(a)}`);e.if((0,tg._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:IK.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let f=p();e.if(!1);for(let h in f)e.elseIf((0,tg._)`${u} === ${h}`),e.assign(c,d(f[h]));e.else(),t.error(!1,{discrError:IK.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(f){let h=e.name("valid"),y=t.subschema({keyword:"oneOf",schemaProp:f},h);return t.mergeEvaluated(y,tg.Name),h}function p(){var f;let h={},y=b(n),w=!0;for(let R=0;R<s.length;R++){let T=s[R];if(T?.$ref&&!(0,wpt.schemaHasRulesButRef)(T,i.self.RULES)){let Z=T.$ref;if(T=YIe.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,Z),T instanceof YIe.SchemaEnv&&(T=T.schema),T===void 0)throw new vpt.default(i.opts.uriResolver,i.baseId,Z)}let M=(f=T?.properties)===null||f===void 0?void 0:f[a];if(typeof M!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);w=w&&(y||b(T)),S(M,R)}if(!w)throw new Error(`discriminator: "${a}" must be required`);return h;function b({required:R}){return Array.isArray(R)&&R.includes(a)}function S(R,T){if(R.const)x(R.const,T);else if(R.enum)for(let M of R.enum)x(M,T);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function x(R,T){if(typeof R!="string"||R in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[R]=T}}}};AK.default=bpt});var eAe=U((mYt,Spt)=>{Spt.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var kK=U((er,PK)=>{"use strict";Object.defineProperty(er,"__esModule",{value:!0});er.MissingRefError=er.ValidationError=er.CodeGen=er.Name=er.nil=er.stringify=er.str=er._=er.KeywordCxt=er.Ajv=void 0;var xpt=JRe(),Ept=WIe(),$pt=QIe(),tAe=eAe(),Rpt=["/properties"],o1="http://json-schema.org/draft-07/schema",rg=class extends xpt.default{_addVocabularies(){super._addVocabularies(),Ept.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword($pt.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(tAe,Rpt):tAe;this.addMetaSchema(e,o1,!1),this.refs["http://json-schema.org/schema"]=o1}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(o1)?o1:void 0)}};er.Ajv=rg;PK.exports=er=rg;PK.exports.Ajv=rg;Object.defineProperty(er,"__esModule",{value:!0});er.default=rg;var Ipt=Gb();Object.defineProperty(er,"KeywordCxt",{enumerable:!0,get:function(){return Ipt.KeywordCxt}});var ng=je();Object.defineProperty(er,"_",{enumerable:!0,get:function(){return ng._}});Object.defineProperty(er,"str",{enumerable:!0,get:function(){return ng.str}});Object.defineProperty(er,"stringify",{enumerable:!0,get:function(){return ng.stringify}});Object.defineProperty(er,"nil",{enumerable:!0,get:function(){return ng.nil}});Object.defineProperty(er,"Name",{enumerable:!0,get:function(){return ng.Name}});Object.defineProperty(er,"CodeGen",{enumerable:!0,get:function(){return ng.CodeGen}});var Apt=zN();Object.defineProperty(er,"ValidationError",{enumerable:!0,get:function(){return Apt.default}});var Ppt=Hb();Object.defineProperty(er,"MissingRefError",{enumerable:!0,get:function(){return Ppt.default}})});var uAe=U(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.formatNames=za.fastFormats=za.fullFormats=void 0;function Na(t,e){return{validate:t,compare:e}}za.fullFormats={date:Na(iAe,DK),time:Na(CK(!0),NK),"date-time":Na(rAe(!0),aAe),"iso-time":Na(CK(),sAe),"iso-date-time":Na(rAe(),cAe),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Npt,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:qpt,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:zpt,int32:{type:"number",validate:Lpt},int64:{type:"number",validate:jpt},float:{type:"number",validate:oAe},double:{type:"number",validate:oAe},password:!0,binary:!0};za.fastFormats={...za.fullFormats,date:Na(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,DK),time:Na(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,NK),"date-time":Na(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,aAe),"iso-time":Na(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,sAe),"iso-date-time":Na(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,cAe),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};za.formatNames=Object.keys(za.fullFormats);function kpt(t){return t%4===0&&(t%100!==0||t%400===0)}var Tpt=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Cpt=[0,31,28,31,30,31,30,31,31,30,31,30,31];function iAe(t){let e=Tpt.exec(t);if(!e)return!1;let r=+e[1],o=+e[2],n=+e[3];return o>=1&&o<=12&&n>=1&&n<=(o===2&&kpt(r)?29:Cpt[o])}function DK(t,e){if(t&&e)return t>e?1:t<e?-1:0}var TK=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function CK(t){return function(r){let o=TK.exec(r);if(!o)return!1;let n=+o[1],i=+o[2],s=+o[3],a=o[4],c=o[5]==="-"?-1:1,u=+(o[6]||0),l=+(o[7]||0);if(u>23||l>59||t&&!a)return!1;if(n<=23&&i<=59&&s<60)return!0;let d=i-l*c,p=n-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&s<61}}function NK(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),o=new Date("2020-01-01T"+e).valueOf();if(r&&o)return r-o}function sAe(t,e){if(!(t&&e))return;let r=TK.exec(t),o=TK.exec(e);if(r&&o)return t=r[1]+r[2]+r[3],e=o[1]+o[2]+o[3],t>e?1:t<e?-1:0}var OK=/t|\s/i;function rAe(t){let e=CK(t);return function(o){let n=o.split(OK);return n.length===2&&iAe(n[0])&&e(n[1])}}function aAe(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),o=new Date(e).valueOf();if(r&&o)return r-o}function cAe(t,e){if(!(t&&e))return;let[r,o]=t.split(OK),[n,i]=e.split(OK),s=DK(r,n);if(s!==void 0)return s||NK(o,i)}var Opt=/\/|:/,Dpt=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Npt(t){return Opt.test(t)&&Dpt.test(t)}var nAe=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function zpt(t){return nAe.lastIndex=0,nAe.test(t)}var Mpt=-(2**31),Upt=2**31-1;function Lpt(t){return Number.isInteger(t)&&t<=Upt&&t>=Mpt}function jpt(t){return Number.isInteger(t)}function oAe(){return!0}var Fpt=/[^\\]\\Z/;function qpt(t){if(Fpt.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var lAe=U(og=>{"use strict";Object.defineProperty(og,"__esModule",{value:!0});og.formatLimitDefinition=void 0;var Vpt=kK(),As=je(),Cl=As.operators,i1={formatMaximum:{okStr:"<=",ok:Cl.LTE,fail:Cl.GT},formatMinimum:{okStr:">=",ok:Cl.GTE,fail:Cl.LT},formatExclusiveMaximum:{okStr:"<",ok:Cl.LT,fail:Cl.GTE},formatExclusiveMinimum:{okStr:">",ok:Cl.GT,fail:Cl.LTE}},Gpt={message:({keyword:t,schemaCode:e})=>(0,As.str)`should be ${i1[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,As._)`{comparison: ${i1[t].okStr}, limit: ${e}}`};og.formatLimitDefinition={keyword:Object.keys(i1),type:"string",schemaType:"string",$data:!0,error:Gpt,code(t){let{gen:e,data:r,schemaCode:o,keyword:n,it:i}=t,{opts:s,self:a}=i;if(!s.validateFormats)return;let c=new Vpt.KeywordCxt(i,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:s.code.formats}),f=e.const("fmt",(0,As._)`${p}[${c.schemaCode}]`);t.fail$data((0,As.or)((0,As._)`typeof ${f} != "object"`,(0,As._)`${f} instanceof RegExp`,(0,As._)`typeof ${f}.compare != "function"`,d(f)))}function l(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${n}": format "${p}" does not define "compare" function`);let h=e.scopeValue("formats",{key:p,ref:f,code:s.code.formats?(0,As._)`${s.code.formats}${(0,As.getProperty)(p)}`:void 0});t.fail$data(d(h))}function d(p){return(0,As._)`${p}.compare(${r}, ${o}) ${i1[n].fail} 0`}},dependencies:["format"]};var Hpt=t=>(t.addKeyword(og.formatLimitDefinition),t);og.default=Hpt});var mAe=U((sS,fAe)=>{"use strict";Object.defineProperty(sS,"__esModule",{value:!0});var ig=uAe(),Kpt=lAe(),zK=je(),dAe=new zK.Name("fullFormats"),Bpt=new zK.Name("fastFormats"),MK=(t,e={keywords:!0})=>{if(Array.isArray(e))return pAe(t,e,ig.fullFormats,dAe),t;let[r,o]=e.mode==="fast"?[ig.fastFormats,Bpt]:[ig.fullFormats,dAe],n=e.formats||ig.formatNames;return pAe(t,n,r,o),e.keywords&&(0,Kpt.default)(t),t};MK.get=(t,e="full")=>{let o=(e==="fast"?ig.fastFormats:ig.fullFormats)[t];if(!o)throw new Error(`Unknown format "${t}"`);return o};function pAe(t,e,r,o){var n,i;(n=(i=t.opts.code).formats)!==null&&n!==void 0||(i.formats=(0,zK._)`require("ajv-formats/dist/formats").${o}`);for(let s of e)t.addFormat(s,r[s])}fAe.exports=sS=MK;Object.defineProperty(sS,"__esModule",{value:!0});sS.default=MK});import{parseArgs as aft}from"node:util";import{hostname as f1}from"node:os";import{open as cft,readFile as qK,rename as uft,rm as lft}from"node:fs/promises";import{dirname as dft,join as pft,resolve as UAe}from"node:path";import{randomUUID as fft}from"node:crypto";import{Readable as LAe}from"node:stream";import{pipeline as jAe}from"node:stream/promises";import{setTimeout as VK}from"node:timers/promises";var m={};Ht(m,{$brand:()=>P1,$input:()=>Xz,$output:()=>Jz,INVALID:()=>qn,NEVER:()=>A1,TimePrecision:()=>oM,ZodAny:()=>gU,ZodArray:()=>_U,ZodBase64:()=>pE,ZodBase64URL:()=>fE,ZodBigInt:()=>pf,ZodBigIntFormat:()=>gE,ZodBoolean:()=>df,ZodCIDRv4:()=>lE,ZodCIDRv6:()=>dE,ZodCUID:()=>nE,ZodCUID2:()=>oE,ZodCatch:()=>LU,ZodCodec:()=>hy,ZodCompileAsyncError:()=>Di,ZodCompileUnsupportedError:()=>Be,ZodCreditCard:()=>dU,ZodCustom:()=>gy,ZodCustomStringFormat:()=>Jl,ZodDate:()=>ly,ZodDefault:()=>OU,ZodDiscriminatedUnion:()=>SU,ZodE164:()=>mE,ZodEmail:()=>Q0,ZodEmoji:()=>tE,ZodEnum:()=>cf,ZodError:()=>HCe,ZodExactOptional:()=>wE,ZodFile:()=>PU,ZodFirstPartyTypeKind:()=>QU,ZodFunction:()=>WU,ZodGUID:()=>eE,ZodIBAN:()=>pU,ZodIPv4:()=>cE,ZodIPv6:()=>uE,ZodISODate:()=>Zc,ZodISODateTime:()=>Bc,ZodISODuration:()=>Jc,ZodISOTime:()=>Wc,ZodInstanceOf:()=>YU,ZodIntersection:()=>xU,ZodIssueCode:()=>ZCe,ZodJWT:()=>hE,ZodKSUID:()=>aE,ZodLazy:()=>KU,ZodLiteral:()=>AU,ZodMAC:()=>lU,ZodMap:()=>RU,ZodNaN:()=>FU,ZodNanoID:()=>rE,ZodNever:()=>vU,ZodNonOptional:()=>_E,ZodNull:()=>hU,ZodNullable:()=>CU,ZodNumber:()=>lf,ZodNumberFormat:()=>Xl,ZodObject:()=>dy,ZodOptional:()=>Yl,ZodPipe:()=>my,ZodPrefault:()=>NU,ZodPreprocess:()=>qU,ZodPromise:()=>ZU,ZodReadonly:()=>VU,ZodRealError:()=>lo,ZodRecord:()=>af,ZodSet:()=>IU,ZodString:()=>uf,ZodStringFormat:()=>Tt,ZodSuccess:()=>UU,ZodSymbol:()=>fU,ZodTemplateLiteral:()=>HU,ZodTransform:()=>kU,ZodTuple:()=>EU,ZodType:()=>Ce,ZodULID:()=>iE,ZodURL:()=>cy,ZodUUID:()=>Os,ZodUndefined:()=>mU,ZodUnion:()=>py,ZodUnknown:()=>yU,ZodVoid:()=>wU,ZodXID:()=>sE,ZodXor:()=>bU,_ZodString:()=>Y0,_default:()=>DU,_function:()=>DW,any:()=>hW,array:()=>qe,base64:()=>WZ,base64url:()=>JZ,bigint:()=>lW,boolean:()=>yr,catch:()=>jU,check:()=>NW,cidrv4:()=>BZ,cidrv6:()=>ZZ,clone:()=>gt,codec:()=>kW,coerce:()=>tL,compile:()=>tM,config:()=>lr,core:()=>zi,creditCard:()=>YZ,cuid:()=>LZ,cuid2:()=>jZ,currencyCode:()=>oW,custom:()=>bE,date:()=>yW,decode:()=>nU,decodeAsync:()=>iU,deepPartial:()=>BW,describe:()=>zW,discriminatedUnion:()=>fy,e164:()=>XZ,email:()=>PZ,emoji:()=>MZ,encode:()=>rU,encodeAsync:()=>oU,endsWith:()=>Wp,enum:()=>Yr,exactOptional:()=>TU,file:()=>RW,flattenError:()=>mg,float32:()=>sW,float64:()=>aW,formatError:()=>hg,fromJSONSchema:()=>HW,function:()=>DW,getDiscriminatedOption:()=>Kz,getErrorMap:()=>JCe,globalRegistry:()=>Jr,gt:()=>Ts,gte:()=>Ro,guid:()=>kZ,hash:()=>iW,hex:()=>nW,hostname:()=>rW,httpUrl:()=>zZ,iban:()=>QZ,includes:()=>Bp,input:()=>WW,instanceof:()=>UW,int:()=>J0,int32:()=>cW,int64:()=>dW,intersection:()=>ff,invertCodec:()=>TW,ipv4:()=>GZ,ipv6:()=>KZ,iso:()=>Ql,json:()=>jW,jwt:()=>eW,keyof:()=>vW,ksuid:()=>VZ,lazy:()=>BU,length:()=>Bl,literal:()=>ae,locales:()=>Fp,looseObject:()=>Xr,looseRecord:()=>SW,lowercase:()=>Hp,lt:()=>ks,lte:()=>$o,mac:()=>HZ,map:()=>xW,maxLength:()=>Kl,maxSize:()=>qc,memoizer:()=>Cg,meta:()=>MW,mime:()=>Xp,minLength:()=>qa,minSize:()=>Cs,multipleOf:()=>Fc,nan:()=>PW,nanoid:()=>UZ,nativeEnum:()=>$W,negative:()=>O0,never:()=>yE,nonnegative:()=>N0,nonoptional:()=>MU,nonpositive:()=>D0,normalize:()=>Yp,null:()=>uy,nullable:()=>ay,nullish:()=>IW,number:()=>yt,object:()=>X,optional:()=>kt,output:()=>JW,overwrite:()=>Ni,parse:()=>YM,parseAsync:()=>QM,partialRecord:()=>bW,pipe:()=>X0,positive:()=>C0,prefault:()=>zU,preprocess:()=>yy,prettifyError:()=>D1,promise:()=>OW,properties:()=>Jp,property:()=>z0,readonly:()=>GU,record:()=>Ct,refine:()=>JU,regex:()=>Gp,regexes:()=>Eo,registry:()=>i0,safeDecode:()=>aU,safeDecodeAsync:()=>uU,safeEncode:()=>sU,safeEncodeAsync:()=>cU,safeParse:()=>eU,safeParseAsync:()=>tU,set:()=>EW,setErrorMap:()=>WCe,size:()=>Hl,slugify:()=>rf,startsWith:()=>Zp,strictObject:()=>wW,string:()=>O,stringFormat:()=>tW,stringbool:()=>LW,success:()=>AW,superRefine:()=>XU,symbol:()=>fW,templateLiteral:()=>CW,toJSONSchema:()=>Zl,toLowerCase:()=>ef,toUpperCase:()=>tf,toZod:()=>sg,transform:()=>vE,treeifyError:()=>O1,trim:()=>Qp,tuple:()=>$U,uint32:()=>uW,uint64:()=>pW,ulid:()=>FZ,undefined:()=>mW,union:()=>It,unknown:()=>Ut,uppercase:()=>Kp,url:()=>NZ,util:()=>D,uuid:()=>TZ,uuidv4:()=>CZ,uuidv6:()=>OZ,uuidv7:()=>DZ,validate:()=>Tp,validateAsync:()=>Cp,void:()=>gW,withParser:()=>s0,xid:()=>qZ,xor:()=>_W});var zi={};Ht(zi,{$ZodAny:()=>wx,$ZodArray:()=>Ex,$ZodAsyncError:()=>co,$ZodBase64:()=>nx,$ZodBase64URL:()=>ix,$ZodBigInt:()=>Rg,$ZodBigIntFormat:()=>hx,$ZodBoolean:()=>Np,$ZodCIDRv4:()=>QS,$ZodCIDRv6:()=>tx,$ZodCUID:()=>HS,$ZodCUID2:()=>KS,$ZodCatch:()=>qx,$ZodCheck:()=>Pt,$ZodCheckBigIntFormat:()=>_z,$ZodCheckEndsWith:()=>Cz,$ZodCheckGreaterThan:()=>kS,$ZodCheckIncludes:()=>kz,$ZodCheckLengthEquals:()=>Rz,$ZodCheckLessThan:()=>PS,$ZodCheckLowerCase:()=>Az,$ZodCheckMaxLength:()=>Ez,$ZodCheckMaxSize:()=>bz,$ZodCheckMimeType:()=>Nz,$ZodCheckMinLength:()=>$z,$ZodCheckMinSize:()=>Sz,$ZodCheckMultipleOf:()=>vz,$ZodCheckNumberFormat:()=>wz,$ZodCheckOverwrite:()=>zz,$ZodCheckProperties:()=>Dz,$ZodCheckProperty:()=>Oz,$ZodCheckRegex:()=>Iz,$ZodCheckSizeEquals:()=>xz,$ZodCheckStartsWith:()=>Tz,$ZodCheckStringFormat:()=>Op,$ZodCheckUpperCase:()=>Pz,$ZodCodec:()=>Mp,$ZodCreditCard:()=>cx,$ZodCustom:()=>Zx,$ZodCustomStringFormat:()=>fx,$ZodCyclicError:()=>Yx,$ZodDate:()=>xx,$ZodDefault:()=>Ux,$ZodDiscriminatedUnion:()=>Ix,$ZodE164:()=>sx,$ZodEmail:()=>US,$ZodEmoji:()=>VS,$ZodEncodeError:()=>Lc,$ZodEnum:()=>Cx,$ZodError:()=>C1,$ZodExactOptional:()=>zx,$ZodFile:()=>Dx,$ZodFunction:()=>Kx,$ZodGUID:()=>zS,$ZodIBAN:()=>lx,$ZodIPv4:()=>JS,$ZodIPv6:()=>XS,$ZodISODate:()=>qz,$ZodISODateTime:()=>Fz,$ZodISODuration:()=>Gz,$ZodISOTime:()=>Vz,$ZodIntersection:()=>Ax,$ZodJWT:()=>px,$ZodKSUID:()=>WS,$ZodLazy:()=>Up,$ZodLiteral:()=>Ox,$ZodMAC:()=>YS,$ZodMap:()=>kx,$ZodNaN:()=>Vx,$ZodNanoID:()=>GS,$ZodNever:()=>bx,$ZodNonOptional:()=>jx,$ZodNull:()=>vx,$ZodNullable:()=>Mx,$ZodNumber:()=>$g,$ZodNumberFormat:()=>mx,$ZodObject:()=>$x,$ZodObjectJIT:()=>Hz,$ZodOptional:()=>Ag,$ZodPipe:()=>Pg,$ZodPrefault:()=>Lx,$ZodPreprocess:()=>Bz,$ZodPromise:()=>Bx,$ZodReadonly:()=>Gx,$ZodRealError:()=>uo,$ZodRecord:()=>Px,$ZodRegistry:()=>o0,$ZodSet:()=>Tx,$ZodString:()=>jc,$ZodStringFormat:()=>St,$ZodSuccess:()=>Fx,$ZodSymbol:()=>gx,$ZodTemplateLiteral:()=>Hx,$ZodTransform:()=>Nx,$ZodTuple:()=>Ig,$ZodType:()=>be,$ZodULID:()=>BS,$ZodURL:()=>qS,$ZodUUID:()=>MS,$ZodUndefined:()=>yx,$ZodUnion:()=>zp,$ZodUnknown:()=>_x,$ZodVoid:()=>Sx,$ZodXID:()=>ZS,$ZodXor:()=>Rx,$brand:()=>P1,$constructor:()=>$,$input:()=>Xz,$output:()=>Jz,Doc:()=>jl,INVALID:()=>qn,JSONSchema:()=>RZ,JSONSchemaGenerator:()=>B0,NEVER:()=>A1,TimePrecision:()=>oM,URL_BAD_FORMAT:()=>Lz,URL_UNPARSEABLE:()=>_g,ZodCompileAsyncError:()=>Di,ZodCompileUnsupportedError:()=>Be,_any:()=>R0,_array:()=>uM,_base64:()=>Xg,_base64url:()=>Yg,_bigint:()=>_0,_boolean:()=>w0,_catch:()=>OCe,_check:()=>lZ,_cidrv4:()=>Wg,_cidrv6:()=>Jg,_coercedBigint:()=>aM,_coercedBoolean:()=>sM,_coercedDate:()=>cM,_coercedNumber:()=>iM,_coercedString:()=>nM,_creditCard:()=>d0,_cuid:()=>qg,_cuid2:()=>Vg,_custom:()=>U0,_date:()=>k0,_decode:()=>vS,_decodeAsync:()=>_S,_default:()=>kCe,_discriminatedUnion:()=>vCe,_e164:()=>Qg,_email:()=>Dg,_emoji:()=>jg,_encode:()=>yS,_encodeAsync:()=>wS,_endsWith:()=>Wp,_enum:()=>ECe,_file:()=>M0,_float32:()=>h0,_float64:()=>g0,_gt:()=>Ts,_gte:()=>Ro,_guid:()=>Ng,_iban:()=>p0,_includes:()=>Bp,_int:()=>m0,_int32:()=>y0,_int64:()=>b0,_intersection:()=>wCe,_ipv4:()=>Bg,_ipv6:()=>Zg,_isoDate:()=>ry,_isoDateTime:()=>ty,_isoDuration:()=>oy,_isoTime:()=>ny,_jwt:()=>ey,_ksuid:()=>Kg,_lazy:()=>MCe,_length:()=>Bl,_literal:()=>RCe,_lowercase:()=>Hp,_lt:()=>ks,_lte:()=>$o,_mac:()=>l0,_map:()=>SCe,_max:()=>$o,_maxLength:()=>Kl,_maxSize:()=>qc,_mime:()=>Xp,_min:()=>Ro,_minLength:()=>qa,_minSize:()=>Cs,_multipleOf:()=>Fc,_nan:()=>T0,_nanoid:()=>Fg,_nativeEnum:()=>$Ce,_negative:()=>O0,_never:()=>A0,_nonnegative:()=>N0,_nonoptional:()=>TCe,_nonpositive:()=>D0,_normalize:()=>Yp,_null:()=>$0,_nullable:()=>PCe,_number:()=>f0,_optional:()=>ACe,_overwrite:()=>Ni,_parse:()=>$p,_parseAsync:()=>Rp,_pipe:()=>DCe,_positive:()=>C0,_promise:()=>UCe,_properties:()=>Jp,_property:()=>z0,_readonly:()=>NCe,_record:()=>bCe,_refine:()=>L0,_regex:()=>Gp,_safeDecode:()=>SS,_safeDecodeAsync:()=>ES,_safeEncode:()=>bS,_safeEncodeAsync:()=>xS,_safeParse:()=>Ip,_safeParseAsync:()=>Pp,_set:()=>xCe,_size:()=>Hl,_slugify:()=>rf,_startsWith:()=>Zp,_string:()=>u0,_stringFormat:()=>Vc,_stringbool:()=>V0,_success:()=>CCe,_superRefine:()=>j0,_symbol:()=>x0,_templateLiteral:()=>zCe,_toLowerCase:()=>ef,_toUpperCase:()=>tf,_transform:()=>ICe,_trim:()=>Qp,_tuple:()=>_Ce,_uint32:()=>v0,_uint64:()=>S0,_ulid:()=>Gg,_undefined:()=>E0,_union:()=>gCe,_unknown:()=>I0,_uppercase:()=>Kp,_url:()=>Vp,_uuid:()=>zg,_uuidv4:()=>Mg,_uuidv6:()=>Ug,_uuidv7:()=>Lg,_void:()=>P0,_xid:()=>Hg,_xor:()=>yCe,base64Charset:()=>rx,base64urlCharset:()=>Eg,canParseURL:()=>jz,clone:()=>gt,compile:()=>tM,compileFn:()=>a0,config:()=>lr,createStandardJSONSchemaMethod:()=>nf,createToJSONSchemaMethod:()=>dM,decode:()=>dB,decodeAsync:()=>fB,describe:()=>F0,encode:()=>lB,encodeAsync:()=>pB,extractDefs:()=>Hc,finalize:()=>Kc,flattenError:()=>mg,formatError:()=>hg,getDiscriminatedOption:()=>Kz,globalConfig:()=>zr,globalRegistry:()=>Jr,handleUnrepresentable:()=>Pr,initializeContext:()=>Gc,isBackEdge:()=>e0,isRecursiveSchema:()=>Qx,isValidBase64:()=>xg,isValidBase64URL:()=>ox,isValidCIDRv6:()=>ex,isValidCreditCard:()=>ax,isValidIBAN:()=>ux,isValidIPv6:()=>Sg,isValidJWT:()=>dx,locales:()=>Fp,memoizer:()=>Cg,mergeValues:()=>Dp,meta:()=>q0,parse:()=>Ml,parseAsync:()=>Ul,parseURLObject:()=>MB,prettifyError:()=>D1,process:()=>Rt,processSchema:()=>Rt,regexes:()=>Eo,registry:()=>i0,safeDecode:()=>hB,safeDecodeAsync:()=>yB,safeEncode:()=>mB,safeEncodeAsync:()=>gB,safeParse:()=>Ap,safeParseAsync:()=>kp,standardProps:()=>NS,stripTabAndNewline:()=>bg,toDotPath:()=>cB,toJSONSchema:()=>Zl,toZod:()=>sg,treeifyError:()=>O1,urlHostnameOk:()=>jS,urlProtocolOk:()=>FS,util:()=>D,validate:()=>Tp,validateAsync:()=>Cp,validateURL:()=>LS,version:()=>Mz,withParser:()=>s0});var D={};Ht(D,{BIGINT_FORMAT_RANGES:()=>lg,CONSTANT_CATCH:()=>hS,Class:()=>y1,NUMBER_FORMAT_RANGES:()=>ug,aborted:()=>Fn,allowsEval:()=>_1,assert:()=>YAe,assertEqual:()=>ZAe,assertIs:()=>JAe,assertNever:()=>XAe,assertNotEqual:()=>WAe,assignProp:()=>Wr,attachSchema:()=>mS,base64ToUint8Array:()=>rB,base64urlToUint8Array:()=>lPe,cached:()=>bp,captureStackTrace:()=>pS,cleanEnum:()=>uPe,cleanRegex:()=>ja,clone:()=>gt,cloneDef:()=>tPe,codePointLength:()=>zl,constantCatch:()=>R1,createTransparentProxy:()=>aPe,defineLazy:()=>v1,defineLazyInternal:()=>Me,derived:()=>mPe,esc:()=>jn,escapeRegex:()=>Xo,explicitlyAborted:()=>x1,extend:()=>JK,finalizeIssue:()=>ao,floatSafeRemainder:()=>ag,getElementAtPath:()=>rPe,getEnumValues:()=>wp,getLengthableOrigin:()=>pg,getParsedType:()=>sPe,getSizableOrigin:()=>dg,hexToUint8Array:()=>pPe,hide:()=>fg,installLazyProp:()=>$1,isObject:()=>Nl,isPlainObject:()=>Jo,issue:()=>Ep,joinValues:()=>I,jsonStringifyReplacer:()=>_p,members:()=>E1,merge:()=>QK,mergeDefs:()=>Wo,normalizeParams:()=>j,nullish:()=>dS,numKeys:()=>iPe,objectClone:()=>QAe,omit:()=>WK,optionalKeys:()=>S1,own:()=>Ps,parsedType:()=>z,partial:()=>eB,pick:()=>ZK,prefixIssues:()=>so,primitiveTypes:()=>b1,promiseAllObject:()=>nPe,propertyKeyTypes:()=>cg,randomString:()=>oPe,rawShape:()=>Sp,required:()=>tB,safeExtend:()=>YK,shallowClone:()=>xp,slugify:()=>w1,stringifyPrimitive:()=>N,toZod:()=>sg,uint8ArrayToBase64:()=>nB,uint8ArrayToBase64url:()=>dPe,uint8ArrayToHex:()=>fPe,unwrapMessage:()=>vp});function ZAe(t){return t}function WAe(t){return t}function sg(){return t=>t}function JAe(t){}function XAe(t){throw new Error("Unexpected value in exhaustive check")}function YAe(t){}function wp(t){let e=Object.values(t).filter(o=>typeof o=="number");return Object.entries(t).filter(([o,n])=>e.indexOf(+o)===-1).map(([o,n])=>n)}function I(t,e="|"){return t.map(r=>N(r)).join(e)}function _p(t,e){return typeof e=="bigint"?e.toString():e}var g1=class{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;return e!==void 0&&(this._value=e(),this._getter=void 0),this._value}};function bp(t){return new g1(t)}function dS(t){return t==null}function ja(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function ag(t,e){let r=t/e,o=Math.round(r),n=4*Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-o)<n?0:r-o}var HK=Symbol("evaluating");function v1(t,e,r){let o;Object.defineProperty(t,e,{get(){if(o!==HK)return o===void 0&&(o=HK,o=r()),o},set(n){Object.defineProperty(t,e,{value:n})},configurable:!0})}function QAe(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function Wr(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Sp(t){let e=Object.getOwnPropertyDescriptor(t,"shape");return e?.get?e.get.raw:e?.value}function La(t){return Sp(t._zod.def)??t._zod.def.shape}function KK(t,e,r){Object.defineProperty(t,e,{get(){let o=r();return Wr(this,e,o),o},enumerable:!0,configurable:!0})}function BK(t,e,r){e in t?Wr(t,e,r):t[e]=r}function Dl(t,e,r,o){let n=La(e);for(let i of r){let s=Object.getOwnPropertyDescriptor(n,i);s.enumerable&&(s.get?KK(t,i,()=>{let a=e._zod.def.shape[i];return o?o(a,i):a}):BK(t,i,o?o(s.value,i):s.value))}}function ePe(t,e){for(let r of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,r);o.enumerable&&(o.get?KK(t,r,()=>e[r]):BK(t,r,o.value))}}function Wo(...t){let e={};for(let r of t){let o=Object.getOwnPropertyDescriptors(r);Object.assign(e,o)}return Object.defineProperties({},e)}function tPe(t){return Wo(t._zod.def)}function rPe(t,e){return e?e.reduce((r,o)=>r?.[o],t):t}function nPe(t){let e=Object.keys(t),r=e.map(o=>t[o]);return Promise.all(r).then(o=>{let n={};for(let i=0;i<e.length;i++)n[e[i]]=o[i];return n})}function oPe(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let o=0;o<t;o++)r+=e[Math.floor(Math.random()*e.length)];return r}function jn(t){return JSON.stringify(t)}function w1(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var pS="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function Nl(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var _1=bp(()=>{if(zr.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Jo(t){if(Nl(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(Nl(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function xp(t){return Jo(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function iPe(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var sPe=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},cg=new Set(["string","number","symbol"]),b1=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Xo(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function gt(t,e,r){let o=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(o._zod.parent=t),o}function j(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function aPe(t){let e;return new Proxy({},{get(r,o,n){return e??(e=t()),Reflect.get(e,o,n)},set(r,o,n,i){return e??(e=t()),Reflect.set(e,o,n,i)},has(r,o){return e??(e=t()),Reflect.has(e,o)},deleteProperty(r,o){return e??(e=t()),Reflect.deleteProperty(e,o)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,o){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,o)},defineProperty(r,o,n){return e??(e=t()),Reflect.defineProperty(e,o,n)}})}function N(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function S1(t){return Object.keys(t).filter(e=>t[e]._zod.optin!==void 0&&t[e]._zod.optout==="optional")}var ug={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},lg={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function ZK(t,e){let r=t._zod.def,o=r.checks;if(o&&o.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let i={};return Dl(i,t,fS(t,e)),gt(t,Wo(r,{shape:i,checks:[]}))}function fS(t,e){let r=La(t),o=[];for(let n of Reflect.ownKeys(e)){if(!Object.getOwnPropertyDescriptor(r,n)?.enumerable)throw new Error(`Unrecognized key: "${String(n)}"`);e[n]&&o.push(n)}return o}function WK(t,e){let r=t._zod.def,o=r.checks;if(o&&o.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let i=new Set(fS(t,e)),s={};return Dl(s,t,Reflect.ownKeys(La(t)).filter(a=>!i.has(a))),gt(t,Wo(r,{shape:s,checks:[]}))}function JK(t,e){if(!Jo(e))throw new Error("Invalid input to extend: expected a plain object");let r=t._zod.def.checks;if(r&&r.length>0){let n=La(t);for(let i of Reflect.ownKeys(e))if(Object.getOwnPropertyDescriptor(n,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return gt(t,Wo(t._zod.def,{shape:XK(t,e)}))}function XK(t,e){let r={};return Dl(r,t,Reflect.ownKeys(La(t))),ePe(r,e),r}function YK(t,e){if(!Jo(e))throw new Error("Invalid input to safeExtend: expected a plain object");return gt(t,Wo(t._zod.def,{shape:XK(t,e)}))}function QK(t,e){if(!e?._zod?.def)throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(t._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r={};Dl(r,t,Reflect.ownKeys(La(t))),Dl(r,e,Reflect.ownKeys(La(e)));let o=Wo(t._zod.def,{shape:r,get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return gt(t,o)}function eB(t,e,r,o="partial"){let i=e._zod.def.checks;if(i&&i.length>0)throw new Error(`.${o}() cannot be used on object schemas containing refinements`);let a=r?new Set(fS(e,r)):void 0,c={};return Dl(c,e,Reflect.ownKeys(La(e)),t&&((u,l)=>a&&!a.has(l)?u:new t({type:"optional",innerType:u}))),gt(e,Wo(e._zod.def,{shape:c,checks:[]}))}function tB(t,e,r){let o=r?new Set(fS(e,r)):void 0,n={};return Dl(n,e,Reflect.ownKeys(La(e)),(i,s)=>o&&!o.has(s)?i:new t({type:"nonoptional",innerType:i})),gt(e,Wo(e._zod.def,{shape:n}))}function Fn(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function x1(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue===!1)return!0;return!1}function so(t,e){return e.map(r=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(t),r})}function vp(t){return typeof t=="string"?t:t?.message}function mS(t,e,r){var o;for(let n=e;n<t.length;n++)(o=t[n]).schema??(o.schema=r)}function ao(t,e,r){var o;let n=t.inst?._zod?.traits;n?.has("$ZodType")&&(n.has("$ZodCheck")?(o=t).schema??(o.schema=t.inst):t.schema=t.inst);let i=t.schema!==t.inst?t.schema?._zod.def?.error:void 0,s=t.message?t.message:vp(t.inst?._zod.def?.error?.(t))??vp(i?.(t))??vp(e?.error?.(t))??vp(r.customError?.(t))??vp(r.localeError?.(t))??"Invalid input",a={};for(let c of Object.keys(t))c==="inst"||c==="schema"||c==="continue"||c==="input"||c==="__proto__"||(a[c]=t[c]);return a.path??(a.path=[]),a.message=s,e?.reportInput&&(a.input=t.input),a}function dg(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}var cPe=/[\uD800-\uDBFF]/;function zl(t){let e=t.length;if(!cPe.test(t))return e;let r=e;for(let o=0;o<e-1;o++)(t.charCodeAt(o)&64512)===55296&&(t.charCodeAt(o+1)&64512)===56320&&(r--,o++);return r}function pg(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function z(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let r=t;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return e}function Ep(...t){let[e,r,o]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:o}:{...e}}function uPe(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function rB(t){let e=atob(t),r=new Uint8Array(e.length);for(let o=0;o<e.length;o++)r[o]=e.charCodeAt(o);return r}function nB(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}function lPe(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-e.length%4)%4);return rB(e+r)}function dPe(t){return nB(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function pPe(t){let e=t.replace(/^0x/,"");if(e.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(e.length/2);for(let o=0;o<e.length;o+=2)r[o/2]=Number.parseInt(e.slice(o,o+2),16);return r}function fPe(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var y1=class{constructor(...e){}};function E1(t,e){for(let r in e){let o=Object.getOwnPropertyDescriptor(e,r);o.get?Object.defineProperty(t,r,{...o,enumerable:!1}):hPe(t,r,o.value)}}function Ps(t,e,r,o=!0){return Object.defineProperty(t,e,{configurable:!0,writable:!0,enumerable:o,value:r}),r}function fg(t,e,r){return Ps(t,e,r,!1)}function mPe(t,e){for(let r in t){let o=t[r];Object.defineProperty(e,r,{configurable:!0,enumerable:!0,get(){return Ps(this,r,o(this))},set(n){Ps(this,r,n)}})}return e}function hPe(t,e,r){Object.defineProperty(t,e,{configurable:!0,get(){return this==null?r:Ps(this,e,r.bind(this))},set(o){Ps(this,e,o)}})}function gPe(t,e){let r=Object.getPrototypeOf(t);return e in r?void 0:r}var h1,Uc=!1,yPe={configurable:!0,get(){Uc=!0}};function Me(t,e,r){let o=Object.getPrototypeOf(t._zod);if(e in o&&h1!==t._zod){h1=void 0;return}h1=t._zod,Object.defineProperty(o,e,{configurable:!0,get(){Object.defineProperty(this,e,yPe);let n=Uc;Uc=!1;try{let i=r(this);return Uc?delete this[e]:Object.defineProperty(this,e,{configurable:!0,writable:!0,value:i}),Uc=Uc||n,i}catch(i){throw delete this[e],Uc=Uc||n,i}},set(n){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:n})}})}function $1(t,e,r,o){let n=gPe(t,e);n&&Object.defineProperty(n,e,{configurable:!0,get(){let i={configurable:!0,writable:!0,enumerable:o,value:void 0};return Object.defineProperty(this,e,i),i.value=r(this),Object.defineProperty(this,e,i),i.value},set(i){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:o,value:i})}})}var hS="~constantCatch";function R1(t){let e=()=>t;return e[hS]=!0,e}var oB,A1=Object.freeze({status:"aborted"}),I1={value:void 0,enumerable:!1},iB="captureStackTrace"in Error?Error:null;function vPe(t){let e=iB;if(e){let r=e.stackTraceLimit;if(typeof r=="number"){try{e.stackTraceLimit=0}catch{return iB=null,new t}try{return new t}finally{e.stackTraceLimit=r}}}return new t}function $(t,e,r,o){let n={};function i(p){this.def=p,this.constr=d,this.traits=new Set}i.prototype=n;let s=r,a=s&&new WeakSet;function c(p,f){if(p._zod){if(p._zod.traits.has(t))return}else{I1.value=new i(f);try{Object.defineProperty(p,"_zod",I1)}finally{I1.value=void 0}}if(p._zod.traits.add(t),e(p,f),a){let y=Object.getPrototypeOf(p),w=p._zod.constr.prototype,b=y;for(;b&&b!==w;)b=Object.getPrototypeOf(b);let S=b??y;a.has(S)||(a.add(S),E1(S,s))}let h=d.prototype;for(let y in h)Object.prototype.hasOwnProperty.call(h,y)&&(y in p||(p[y]=h[y].bind(p)))}let u=o?.Parent??Object;class l extends u{}Object.defineProperty(l,"name",{value:t});function d(p){let f=o?.Parent?vPe(l):this;c(f,p);let h=f._zod.deferred;if(h){for(let w of h)w();f._zod.deferred=void 0}let y=globalThis.__zod_globalConfig?.postProcessor;return y&&y(f),f}return Object.defineProperty(d,"init",{value:c}),Object.defineProperty(d,Symbol.hasInstance,{value:p=>o?.Parent&&p instanceof o.Parent?!0:p?._zod?.traits?.has(t)}),Object.defineProperty(d,"name",{value:t}),d}var P1=Symbol("zod_brand"),co=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Lc=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(oB=globalThis).__zod_globalConfig??(oB.__zod_globalConfig={});var zr=globalThis.__zod_globalConfig;function lr(t){return t&&Object.assign(zr,t),zr}function wPe(){let t=this._zod;return t.message??(t.message=JSON.stringify(t.def,_p,2)),t.message}function _Pe(t){this._zod.message=t}var bPe={get:wPe,set:_Pe,enumerable:!0,configurable:!0},T1={value:void 0,enumerable:!1},sB=new WeakSet([Object.prototype,Error.prototype]),aB=(t,e)=>{t.name="$ZodError",T1.value=e,Object.defineProperty(t,"issues",T1),T1.value=void 0,Object.defineProperty(t,"message",bPe);let r=Object.getPrototypeOf(t);sB.has(r)||(sB.add(r),Object.defineProperty(r,"toString",{configurable:!0,enumerable:!1,get(){let o=()=>this.message;return Object.defineProperty(this,"toString",{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,"toString",{value:o,configurable:!0,writable:!0})}}))},C1=$("$ZodError",aB),uo=$("$ZodError",aB,void 0,{Parent:Error});function SPe(t,e,r){return Object.prototype.hasOwnProperty.call(t,e)||(e==="__proto__"?Object.defineProperty(t,e,{value:r(),writable:!0,enumerable:!0,configurable:!0}):t[e]=r()),t[e]}function mg(t,e=r=>r.message){let r={},o=[];for(let n of t.issues)n.path.length>0?SPe(r,n.path[0],()=>[]).push(e(n)):o.push(e(n));return{formErrors:o,fieldErrors:r}}function hg(t,e=r=>r.message){let r={_errors:[]},o=(n,i=[])=>{for(let s of n.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>o({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")o({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")o({issues:s.issues},[...i,...s.path]);else{let a=[...i,...s.path];if(a.length===0)r._errors.push(e(s));else{let c=r,u=0;for(;u<a.length;){let l=a[u],d=u===a.length-1;if(l==="_errors"){d&&c._errors.push(e(s)),u++;continue}Object.prototype.hasOwnProperty.call(c,l)||Object.defineProperty(c,l,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let p=c[l];d&&p._errors.push(e(s)),c=p,u++}}}};return o(t),r}function O1(t,e=r=>r.message){let r={errors:[]},o=(n,i=[])=>{var s;for(let a of n.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(c=>o({issues:c},[...i,...a.path]));else if(a.code==="invalid_key")o({issues:a.issues},[...i,...a.path]);else if(a.code==="invalid_element")o({issues:a.issues},[...i,...a.path]);else{let c=[...i,...a.path];if(c.length===0){r.errors.push(e(a));continue}let u=r,l=0;for(;l<c.length;){let d=c[l],p=l===c.length-1;typeof d=="string"?(u.properties??(u.properties={}),Object.prototype.hasOwnProperty.call(u.properties,d)||Object.defineProperty(u.properties,d,{value:{errors:[]},enumerable:!0,writable:!0,configurable:!0}),u=u.properties[d]):(u.items??(u.items=[]),(s=u.items)[d]??(s[d]={errors:[]}),u=u.items[d]),p&&u.errors.push(e(a)),l++}}};return o(t),r}function cB(t){let e=[],r=t.map(o=>typeof o=="object"?o.key:o);for(let o of r)typeof o=="number"?e.push(`[${o}]`):typeof o=="symbol"?e.push(`[${JSON.stringify(String(o))}]`):/[^\w$]/.test(o)?e.push(`[${JSON.stringify(o)}]`):(e.length&&e.push("."),e.push(o));return e.join("")}function D1(t){let e=[],r=[...t.issues].sort((o,n)=>(o.path??[]).length-(n.path??[]).length);for(let o of r)e.push(`\u2716 ${o.message}`),o.path?.length&&e.push(` \u2192 at ${cB(o.path)}`);return e.join(`
68
68
  `)}function gS(t,e){return{callee:e?.callee??t,Err:e?.Err}}var $p=t=>{let e=(r,o,n,i)=>{let s=n?{...n,async:!1}:{async:!1},a=r._zod.run({value:o,issues:[]},s);if(a instanceof Promise)throw new co;if(a.issues.length){let c=new(i?.Err??t)(a.issues.map(u=>ao(u,s,lr())));throw pS(c,i?.callee??e),c}return a.value};return e},Ml=$p(uo),Rp=t=>{let e=async(r,o,n,i)=>{let s=n?{...n,async:!0}:{async:!0},a=r._zod.run({value:o,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){let c=new(i?.Err??t)(a.issues.map(u=>ao(u,s,lr())));throw pS(c,i?.callee??e),c}return a.value};return e},Ul=Rp(uo),Ip=t=>(e,r,o)=>{let n=o?{...o,async:!1}:{async:!1},i=e._zod.run({value:r,issues:[]},n);if(i instanceof Promise)throw new co;return i.issues.length?uB(t,i.issues,n):{success:!0,data:i.value}},Ap=Ip(uo);function uB(t,e,r){let o;return{success:!1,get error(){return o||(o=new t(e.map(n=>ao(n,r,lr()))),e=void 0,r=void 0),o},set error(n){o=n,e=void 0,r=void 0}}}var Pp=t=>async(e,r,o)=>{let n=o?{...o,async:!0}:{async:!0},i=e._zod.run({value:r,issues:[]},n);return i instanceof Promise&&(i=await i),i.issues.length?uB(t,i.issues,n):{success:!0,data:i.value}},kp=Pp(uo),EPe=Symbol.for("zod.compile.invalid"),$Pe=Symbol.for("zod.compile.fallback"),Tp=((t,e,r)=>{let o=t._zod.bag.validator;if(o!==void 0){if(o(e)!==EPe)return!0;if(o.definite===!0&&r===void 0)return!1}return RPe(t,e,r)});function RPe(t,e,r){let o=r?{...r,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},n=t._zod.bag.fallbackRun,i;if(n?(o[$Pe]=!0,i=n({value:e,issues:[]},o)):i=t._zod.run({value:e,issues:[]},o),i instanceof Promise)throw new co;return i.issues.length===0}var Cp=async(t,e,r)=>{let o=r?{...r,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},n=t._zod.run({value:e,issues:[]},o);return n instanceof Promise&&(n=await n),n.issues.length===0},yS=t=>{let e=$p(t),r=(o,n,i,s)=>{let a=i?{...i,direction:"backward"}:{direction:"backward"};return e(o,n,a,gS(r,s))};return r},lB=yS(uo),vS=t=>{let e=$p(t),r=(o,n,i,s)=>e(o,n,i,gS(r,s));return r},dB=vS(uo),wS=t=>{let e=Rp(t),r=async(o,n,i,s)=>{let a=i?{...i,direction:"backward"}:{direction:"backward"};return await e(o,n,a,gS(r,s))};return r},pB=wS(uo),_S=t=>{let e=Rp(t),r=async(o,n,i,s)=>await e(o,n,i,gS(r,s));return r},fB=_S(uo),bS=t=>(e,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Ip(t)(e,r,n)},mB=bS(uo),SS=t=>(e,r,o)=>Ip(t)(e,r,o),hB=SS(uo),xS=t=>async(e,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Pp(t)(e,r,n)},gB=xS(uo),ES=t=>async(e,r,o)=>Pp(t)(e,r,o),yB=ES(uo);var Eo={};Ht(Eo,{anyString:()=>az,base64:()=>Y1,base64url:()=>Q1,bigint:()=>uz,boolean:()=>lz,browserEmail:()=>DPe,cidrv4:()=>J1,cidrv6:()=>X1,creditCard:()=>$S,cuid:()=>z1,cuid2:()=>M1,currencyCode:()=>nz,date:()=>oz,datetime:()=>sz,domain:()=>tz,duration:()=>V1,e164:()=>rz,email:()=>H1,emoji:()=>K1,extendedDuration:()=>IPe,guid:()=>G1,hex:()=>hz,hostname:()=>ez,html5Email:()=>TPe,httpProtocol:()=>gg,iban:()=>RS,idnEmail:()=>OPe,integer:()=>yg,ipv4:()=>B1,ipv6:()=>Z1,ksuid:()=>j1,lowercase:()=>fz,mac:()=>W1,md5_base64:()=>UPe,md5_base64url:()=>LPe,md5_hex:()=>MPe,nanoid:()=>F1,nanoidOfLength:()=>q1,null:()=>dz,number:()=>Fa,rfc5322Email:()=>CPe,sha1_base64:()=>FPe,sha1_base64url:()=>qPe,sha1_hex:()=>jPe,sha256_base64:()=>GPe,sha256_base64url:()=>HPe,sha256_hex:()=>VPe,sha384_base64:()=>BPe,sha384_base64url:()=>ZPe,sha384_hex:()=>KPe,sha512_base64:()=>JPe,sha512_base64url:()=>XPe,sha512_hex:()=>WPe,string:()=>cz,time:()=>iz,ulid:()=>U1,undefined:()=>pz,unicodeEmail:()=>vB,uppercase:()=>mz,uuid:()=>Ll,uuid4:()=>APe,uuid6:()=>PPe,uuid7:()=>kPe,xid:()=>L1});var z1=/^[cC][0-9a-z]{6,}$/,M1=/^[0-9a-z]+$/,U1=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,L1=/^[0-9a-vA-V]{20}$/,j1=/^[A-Za-z0-9]{27}$/,F1=/^[a-zA-Z0-9_-]{21}$/;function q1(t){return new RegExp(`^[a-zA-Z0-9_-]{${t}}$`)}var V1=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,IPe=/^[-+]?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)?)??$/,G1=/^([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})$/,Ll=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([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)$/,APe=Ll(4),PPe=Ll(6),kPe=Ll(7),H1=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,TPe=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,CPe=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,vB=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,OPe=vB,DPe=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,NPe="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function K1(){return new RegExp(NPe,"u")}var B1=/^(?:(?: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])$/,Z1=/^(([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}|:))$/,W1=t=>{let e=Xo(t??":");return new RegExp(`^(?:[0-9A-F]{2}${e}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${e}){5}[0-9a-f]{2}$`)},J1=/^((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])$/,X1=/^(([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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Y1=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Q1=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,ez=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,tz=/^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/,gg=/^https?$/,rz=/^\+[1-9]\d{6,14}$/,$S=/^\d(?:[ -]?\d){11,18}$/,nz=/^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/,RS=/^[A-Z]{2}(?!00|01|99)\d{2}[A-Z0-9]{11,30}$/,wB="(?:(?:\\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])))";function zPe(t){return new RegExp(`^${t}$`)}var oz=zPe(wB);function N1(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:t.seconds?`${e}:[0-5]\\d(?:\\.\\d+)?`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function iz(t){return new RegExp(`^${N1(t)}$`)}function sz(t){let e=["Z"];t.offset&&e.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let r=`${N1({precision:t.precision,seconds:!0})}(?:${e.join("|")})`,o=t.local?`${r}|${N1({precision:t.precision})}`:r;return new RegExp(`^${wB}T(?:${o})$`)}var az=/^[\s\S]{0,}$/,cz=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},uz=/^-?\d+n?$/,yg=/^-?\d+$/,Fa=/^-?\d+(?:\.\d+)?$/,lz=/^(?:true|false)$/i,dz=/^null$/i;var pz=/^undefined$/i;var fz=/^[^A-Z]*$/,mz=/^[^a-z]*$/,hz=/^[0-9a-fA-F]*$/;function vg(t,e){return new RegExp(`^[A-Za-z0-9+/]{${t}}${e}$`)}function wg(t){return new RegExp(`^[A-Za-z0-9_-]{${t}}$`)}var MPe=/^[0-9a-fA-F]{32}$/,UPe=vg(22,"=="),LPe=wg(22),jPe=/^[0-9a-fA-F]{40}$/,FPe=vg(27,"="),qPe=wg(27),VPe=/^[0-9a-fA-F]{64}$/,GPe=vg(43,"="),HPe=wg(43),KPe=/^[0-9a-fA-F]{96}$/,BPe=vg(64,""),ZPe=wg(64),WPe=/^[0-9a-fA-F]{128}$/,JPe=vg(86,"=="),XPe=wg(86);var Pt=$("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),gz=t=>{let e=t.value;return!dS(e)&&e.size!==void 0},yz=t=>{let e=t.value;return!dS(e)&&e.length!==void 0},IS={number:"number",bigint:"bigint",object:"date"},PS=$("$ZodCheckLessThan",(t,e)=>{Pt.init(t,e);let r=IS[typeof e.value];t._zod.check=o=>{(e.inclusive?o.value<=e.value:o.value<e.value)||o.issues.push({origin:IS[typeof o.value]??r,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:o.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),kS=$("$ZodCheckGreaterThan",(t,e)=>{Pt.init(t,e);let r=IS[typeof e.value];t._zod.check=o=>{(e.inclusive?o.value>=e.value:o.value>e.value)||o.issues.push({origin:IS[typeof o.value]??r,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:o.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),vz=$("$ZodCheckMultipleOf",(t,e)=>{Pt.init(t,e),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?e.value!==BigInt(0)&&r.value%e.value===BigInt(0):ag(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),wz=$("$ZodCheckNumberFormat",(t,e)=>{Pt.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),o=r?"int":"number",[n,i]=ug[e.format];t._zod.check=s=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:o,format:e.format,code:"invalid_type",continue:!1,input:a,inst:t});return}if(!Number.isSafeInteger(a)){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:t,origin:o,inclusive:!0,continue:!e.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:o,inclusive:!0,continue:!e.abort});return}}a<n&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:n,inclusive:!0,inst:t,continue:!e.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:t,continue:!e.abort})}}),_z=$("$ZodCheckBigIntFormat",(t,e)=>{Pt.init(t,e);let[r,o]=lg[e.format];t._zod.check=n=>{let i=n.value;i<r&&n.issues.push({origin:"bigint",input:i,code:"too_small",minimum:r,inclusive:!0,inst:t,continue:!e.abort}),i>o&&n.issues.push({origin:"bigint",input:i,code:"too_big",maximum:o,inclusive:!0,inst:t,continue:!e.abort})}}),bz=$("$ZodCheckMaxSize",(t,e)=>{var r;Pt.init(t,e),(r=t._zod.def).when??(r.when=gz),t._zod.check=o=>{let n=o.value;n.size<=e.maximum||o.issues.push({origin:dg(n),code:"too_big",maximum:e.maximum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),Sz=$("$ZodCheckMinSize",(t,e)=>{var r;Pt.init(t,e),(r=t._zod.def).when??(r.when=gz),t._zod.check=o=>{let n=o.value;n.size>=e.minimum||o.issues.push({origin:dg(n),code:"too_small",minimum:e.minimum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),xz=$("$ZodCheckSizeEquals",(t,e)=>{var r;Pt.init(t,e),(r=t._zod.def).when??(r.when=gz),t._zod.check=o=>{let n=o.value,i=n.size;if(i===e.size)return;let s=i>e.size;o.issues.push({origin:dg(n),...s?{code:"too_big",maximum:e.size}:{code:"too_small",minimum:e.size},inclusive:!0,exact:!0,input:o.value,inst:t,continue:!e.abort})}}),Ez=$("$ZodCheckMaxLength",(t,e)=>{var r;Pt.init(t,e),(r=t._zod.def).when??(r.when=yz),t._zod.check=o=>{let n=o.value,i=n.length;if((typeof n=="string"&&i>e.maximum?zl(n):i)<=e.maximum)return;let a=pg(n);o.issues.push({origin:a,code:"too_big",maximum:e.maximum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),$z=$("$ZodCheckMinLength",(t,e)=>{var r;Pt.init(t,e),(r=t._zod.def).when??(r.when=yz),t._zod.check=o=>{let n=o.value,i=n.length;if((typeof n=="string"&&i>=e.minimum&&i<e.minimum*2?zl(n):i)>=e.minimum)return;let a=pg(n);o.issues.push({origin:a,code:"too_small",minimum:e.minimum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),Rz=$("$ZodCheckLengthEquals",(t,e)=>{var r;Pt.init(t,e),(r=t._zod.def).when??(r.when=yz),t._zod.check=o=>{let n=o.value,i=n.length,s=typeof n=="string"&&i>=e.length&&i<=e.length*2?zl(n):i;if(s===e.length)return;let a=pg(n),c=s>e.length;o.issues.push({origin:a,...c?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:o.value,inst:t,continue:!e.abort})}}),Op=$("$ZodCheckStringFormat",(t,e)=>{var r,o;Pt.init(t,e),e.pattern?(r=t._zod).check??(r.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:e.format,input:n.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(o=t._zod).check??(o.check=()=>{})}),Iz=$("$ZodCheckRegex",(t,e)=>{Op.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Az=$("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=fz),Op.init(t,e)}),Pz=$("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=mz),Op.init(t,e)}),kz=$("$ZodCheckIncludes",(t,e)=>{Pt.init(t,e);let r=Xo(e.includes),o=new RegExp(typeof e.position=="number"?`^.{${e.position},}${r}`:r);e.pattern=o,t._zod.check=n=>{n.value.includes(e.includes,e.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:n.value,inst:t,continue:!e.abort})}}),Tz=$("$ZodCheckStartsWith",(t,e)=>{Pt.init(t,e);let r=new RegExp(`^${Xo(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.check=o=>{o.value.startsWith(e.prefix)||o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:o.value,inst:t,continue:!e.abort})}}),Cz=$("$ZodCheckEndsWith",(t,e)=>{Pt.init(t,e);let r=new RegExp(`.*${Xo(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.check=o=>{o.value.endsWith(e.suffix)||o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:o.value,inst:t,continue:!e.abort})}});function AS(t,e,r){t.issues.length&&e.issues.push(...so(r,t.issues))}var Oz=$("$ZodCheckProperty",(t,e)=>{Pt.init(t,e),t._zod.check=r=>{let o=e.schema._zod.run({value:r.value[e.property],issues:[]},{});if(o instanceof Promise)return o.then(n=>AS(n,r,e.property));AS(o,r,e.property)}}),Dz=$("$ZodCheckProperties",(t,e)=>{Pt.init(t,e),fg(t,Symbol.iterator,function*(){yield t});let r;t._zod.check=o=>{if(o.value==null){o.issues.push({expected:"object",code:"invalid_type",input:o.value,inst:t});return}r??(r=Reflect.ownKeys(e.shape).map(s=>[s,e.shape[s]]));let n=o.value,i;for(let[s,a]of r){let c=a._zod.run({value:n[s],issues:[]},{});c instanceof Promise?(i??(i=[]),i.push(c.then(u=>AS(u,o,s)))):AS(c,o,s)}if(i)return Promise.all(i).then(()=>{})}}),Nz=$("$ZodCheckMimeType",(t,e)=>{Pt.init(t,e);let r=new Set(e.mime);t._zod.check=o=>{r.has(o.value.type)||o.issues.push({code:"invalid_value",values:e.mime,input:o.value.type,inst:t,continue:!e.abort})}}),zz=$("$ZodCheckOverwrite",(t,e)=>{Pt.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var jl=class{constructor(e=[],r={}){this.content=[],this.indent=0,this.args=e,this.closed=r}indented(e){this.indent+=1;try{e(this)}finally{this.indent-=1}}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let o=e.split(`
69
69
  `).filter(s=>s),n=Math.min(...o.map(s=>s.length-s.trimStart().length)),i=o.map(s=>s.slice(n)).map(s=>" ".repeat(this.indent*2)+s);for(let s of i)this.content.push(s)}compile(){let e=Function,r=this?.content??[""];return new e(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
70
70
  ${r.join(`
@@ -125,28 +125,28 @@ ${c}`:c:"",l=Function,d=`return (input) => {
125
125
  ${c}
126
126
  }`,p;try{p=new l(...s,d)(...a)}catch(f){throw new Be(`this schema (generated code failed to evaluate: ${f.message})`)}return e?.debug&&(p.code=u),p.definite=o.definite,p}function ye(t,e){for(let[o,n]of t.constants)if(n===e)return o;let r=`c${t.constantCounter++}`;return t.constants.set(r,e),r}function Vl(t,e){return t.definite=!1,ye(t,e)}function pe(t){return`v${t.varCounter++}`}function wTe(t,e){let r=t._zod.run({value:e,issues:[]},{});if(r&&typeof r.then=="function")return qn;let o=r;return o.issues.length===0?o.value:qn}function _n(t,e,r,o,n=!0){let i=t.content.length,s=e.constants.size,a=e.constantCounter,c=e.varCounter;try{return nr(t,e,r,o,n)}catch(u){if(!(u instanceof Be)||!u.islandable)throw u;if(t.content.length=i,e.constants.size>s){let l=Array.from(e.constants.keys()).slice(s);for(let d of l)e.constants.delete(d)}return e.constantCounter=a,e.varCounter=c,_Te(t,e,r,o)}}function _Te(t,e,r,o){e.definite=!1;let n=ye(e,r),i=ye(e,wTe),s=pe(e);return t.write(`const ${s} = ${i}(${n}, ${o});`),t.write(`if (${s} === INVALID) return INVALID;`),s}var bTe=new Set(["max_size","min_size","size_equals","max_length","min_length","length_equals"]);function STe(t,e,r,o){let n=r._zod.def.checks;if(!n||n.length===0)return o;let i=o;for(let s of n){let a=s._zod.def;if(a.when&&!bTe.has(a.check))throw new Be('check with a custom "when" condition');switch(a.check){case"greater_than":xTe(t,e,a,i);break;case"less_than":ETe(t,e,a,i);break;case"multiple_of":$Te(t,e,a,i);break;case"number_format":cZ(t,a,i);break;case"min_length":{let c=Fl(a.minimum,"min_length"),u=Yz(t,e,i,`${i}.length >= ${c} && ${i}.length < ${a.minimum*2}`);t.write(`if (${u} < ${c}) return INVALID;`);break}case"max_length":{let c=Fl(a.maximum,"max_length"),u=Yz(t,e,i,`${i}.length > ${c}`);t.write(`if (${u} > ${c}) return INVALID;`);break}case"length_equals":{let c=Fl(a.length,"length_equals"),u=Yz(t,e,i,`${i}.length >= ${c} && ${i}.length <= ${a.length*2}`);t.write(`if (${u} !== ${c}) return INVALID;`);break}case"min_size":t.write(`if (${i}.size < ${Fl(a.minimum,"min_size")}) return INVALID;`);break;case"max_size":t.write(`if (${i}.size > ${Fl(a.maximum,"max_size")}) return INVALID;`);break;case"size_equals":t.write(`if (${i}.size !== ${Fl(a.size,"size_equals")}) return INVALID;`);break;case"string_format":i=uZ(t,e,a,i);break;case"custom":i=TTe(t,e,s,i);break;case"bigint_format":RTe(t,a,i);break;case"mime_type":ITe(t,e,a,i);break;case"property":PTe(t,e,a,i);break;case"properties":ATe(t,e,a,i);break;case"overwrite":{let c=pe(e);kTe(t,e,s,i,c),i=c;break}default:throw new Be(`check type ${a.check}`)}}return i}function Yz(t,e,r,o){let n=ye(e,zl),i=pe(e);return t.write(`const ${i} = typeof ${r} === "string" && ${o} ? ${n}(${r}) : ${r}.length;`),i}function Fl(t,e){if(typeof t!="number"||!Number.isFinite(t))throw new Be(`${e} bound of type ${typeof t}`);return`${t}`}function aZ(t,e){if(typeof e=="bigint")return`${e}n`;if(typeof e=="number"){if(Number.isNaN(e))throw new Be("comparison check with NaN bound");return`${e}`}if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new Be("comparison check with Invalid Date bound");return ye(t,e)}throw new Be(`comparison check bound of type ${typeof e}`)}function xTe(t,e,r,o){let n=r.inclusive?"<":"<=";t.write(`if (${o} ${n} ${aZ(e,r.value)}) return INVALID;`)}function ETe(t,e,r,o){let n=r.inclusive?">":">=";t.write(`if (${o} ${n} ${aZ(e,r.value)}) return INVALID;`)}function $Te(t,e,r,o){if(typeof r.value=="bigint"){if(r.value===BigInt(0))throw new Be("multiple_of check with a zero divisor");t.write(`if (${o} % ${r.value}n !== 0n) return INVALID;`)}else{let n=ye(e,ag);t.write(`if (${n}(${o}, ${Fl(r.value,"multiple_of")}) !== 0) return INVALID;`)}}function cZ(t,e,r){let o=e.format;switch(o){case"safeint":t.write(`if (!Number.isSafeInteger(${r})) return INVALID;`);break;case"int32":t.write(`if (!Number.isInteger(${r}) || ${r} < -2147483648 || ${r} > 2147483647) return INVALID;`);break;case"uint32":t.write(`if (!Number.isInteger(${r}) || ${r} < 0 || ${r} > 4294967295) return INVALID;`);break;case"float32":t.write(`if (!Number.isFinite(${r}) || ${r} < -3.4028234663852886e38 || ${r} > 3.4028234663852886e38) return INVALID;`);break;case"float64":t.write(`if (!Number.isFinite(${r})) return INVALID;`);break;default:throw new Be(`number format ${o}`)}}function RTe(t,e,r){let o=e.format;if(o)switch(o){case"int64":t.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":t.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break;default:throw new Be(`bigint format ${o}`)}}function ITe(t,e,r,o){let n=r.mime;if(n&&n.length>0){let i=ye(e,new Set(n));t.write(`if (!${i}.has(${o}.type)) return INVALID;`)}}function ATe(t,e,r,o){if(r.when)throw new Be('check with a custom "when" condition');t.write(`if (${o} == null) return INVALID;`);let n=r.shape;for(let i of Reflect.ownKeys(n)){let s=typeof i=="symbol"?ye(e,i):jn(i),a=pe(e);t.write(`const ${a} = ${o}[${s}];`),_n(t,e,n[i],a,!1)}}function PTe(t,e,r,o){let n=`${o}[${JSON.stringify(r.property)}]`;nr(t,e,r.schema,n)}function kTe(t,e,r,o,n){let i=r._zod.def.tx;if(!i)throw new Be("overwrite check without a transform function");if(Gl(i))throw new Di("z.compile: async overwrite transforms are not supported");let s=ye(e,i);t.write(`const ${n} = ${s}(${o});`)}function Qz(){throw new co}function rM(t){this.issues.push(t)}function TTe(t,e,r,o){let n=r._zod.def;if(n.fn){if(Gl(n.fn))throw new Di("z.compile: async .refine() predicates are not supported");let i=Vl(e,n.fn),s=ye(e,Qz),a=pe(e);return t.write(`const ${a} = ${i}(${o});`),t.write(`if (${a} instanceof Promise) ${s}();`),t.write(`if (!${a}) return INVALID;`),o}if(r._zod.check){if(Gl(r._zod.check))throw new Di("z.compile: async .superRefine() / check functions are not supported");let i=r._zod.check,a=Vl(e,u=>{let l={value:u,issues:[],addIssue:rM};return i(l)instanceof Promise&&Qz(),l.issues.length===0?l.value:qn}),c=pe(e);return t.write(`const ${c} = ${a}(${o});`),t.write(`if (${c} === INVALID) return INVALID;`),c}throw new Be("custom check without a predicate or check function")}var CTe=new Set(["cidrv4","cuid","cuid2","date","datetime","duration","e164","email","emoji","ends_with","guid","includes","ipv4","ksuid","lowercase","mac","nanoid","regex","starts_with","time","ulid","uppercase","uuid","xid"]);function uZ(t,e,r,o,n=!0){let i=r.format;if(i==="base64"){let u=ye(e,xg);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="base64url"){let u=ye(e,ox);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="jwt"){let u=ye(e,dx),l=ye(e,r.alg??null);return t.write(`if (!${u}(${o}, ${l})) return INVALID;`),o}if(i==="ipv6"){let u=ye(e,Sg);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="cidrv6"){let u=ye(e,ex);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="credit_card"){let u=ye(e,ax);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(i==="iban"){let u=ye(e,ux);return t.write(`if (!${u}(${o})) return INVALID;`),o}let s=r;if(i==="url"||i==="httpurl"||s.normalize||s.hostname!==void 0||s.protocol!==void 0){let u=ye(e,LS),l=ye(e,r),d=pe(e),p=pe(e);if(t.write(`const ${d} = ${o}.trim();`),t.write(`const ${p} = ${u}(${d}, ${l});`),t.write(`if (typeof ${p} === "number") return INVALID;`),s.hostname!==void 0){let y=ye(e,jS);t.write(`if (!${y}(${p}, ${l}.hostname)) return INVALID;`)}if(s.protocol!==void 0){let y=ye(e,FS);t.write(`if (!${y}(${p}, ${l}.protocol)) return INVALID;`)}if(!n)return null;let f=pe(e),h=s.normalize?`${p}.href`:`${ye(e,bg)}(${d})`;return t.write(`const ${f} = ${h};`),f}let a=r.fn;if(a){if(Gl(a))throw new Be(`async string format ${i}`);let u=ye(e,a);return t.write(`if (!${u}(${o})) return INVALID;`),o}if(CTe.has(i)&&r.pattern){let u=ye(e,r.pattern);return t.write(`${u}.lastIndex = 0;`),t.write(`if (!${u}.test(${o})) return INVALID;`),o}let c=r.format;switch(c){case"regex":throw new Be("regex format without a pattern");case"lowercase":t.write(`if (${o} !== ${o}.toLowerCase()) return INVALID;`);break;case"uppercase":t.write(`if (${o} !== ${o}.toUpperCase()) return INVALID;`);break;case"includes":t.write(`if (!${o}.includes(${jn(r.includes)})) return INVALID;`);break;case"starts_with":{let u=r.prefix;t.write(`if (${o}.slice(0, ${u.length}) !== ${jn(u)}) return INVALID;`);break}case"ends_with":{let u=r.suffix;t.write(`if (${o}.slice(-${u.length}) !== ${jn(u)}) return INVALID;`);break}default:throw new Be(`string format ${c}`)}return o}function nr(t,e,r,o,n=!0){let i=r._zod.def,s=i.type;if(i.coerce)throw new Be(`coercion (z.coerce.${s}())`);let a=n||!!i.checks?.length,c;switch(s){case"string":c=OTe(t,e,r,o,a);break;case"number":c=DTe(t,r,o);break;case"boolean":c=NTe(t,o);break;case"bigint":c=zTe(t,r,o);break;case"symbol":c=MTe(t,o);break;case"undefined":c=UTe(t,o);break;case"null":c=LTe(t,o);break;case"any":case"unknown":c=o;break;case"never":t.write("return INVALID;"),c=o;break;case"void":c=jTe(t,o);break;case"nan":c=FTe(t,o);break;case"date":c=qTe(t,o);break;case"object":c=VTe(t,e,r,o,a);break;case"optional":c=GTe(t,e,r,o,a);break;case"nullable":c=BTe(t,e,r,o,a);break;case"array":c=ZTe(t,e,r,o,a);break;case"literal":c=WTe(t,e,r,o);break;case"enum":c=JTe(t,e,r,o);break;case"readonly":{let u=oZ(t,e,r,o),l=pe(e);t.write(`const ${l} = Object.freeze(${u});`),c=l;break}case"success":oZ(t,e,r,o),c="true";break;case"default":case"prefault":c=XTe(t,e,r,o);break;case"nonoptional":c=YTe(t,e,r,o);break;case"tuple":c=QTe(t,e,r,o);break;case"union":c=eCe(t,e,r,o);break;case"intersection":c=nCe(t,e,r,o);break;case"record":c=oCe(t,e,r,o);break;case"map":c=sCe(t,e,r,o);break;case"set":c=aCe(t,e,r,o);break;case"file":c=cCe(t,o);break;case"template_literal":c=uCe(t,e,r,o);break;case"lazy":c=lCe(t,e,r,o);break;case"pipe":c=dCe(t,e,r,o);break;case"custom":c=pCe(t,e,r,o);break;case"transform":c=hCe(t,e,r,o);break;case"catch":c=mCe(t,e,r,o);break;default:throw new Be(`schema type ${s}`)}return c===null?null:STe(t,e,r,c)}function OTe(t,e,r,o,n=!0){t.write(`if (typeof ${o} !== "string") return INVALID;`);let i=r._zod.def;return i.format===void 0?o:uZ(t,e,i,o,n)}function DTe(t,e,r){t.write(`if (typeof ${r} !== "number" || !Number.isFinite(${r})) return INVALID;`);let o=e._zod.def;return o.check==="number_format"&&o.format&&cZ(t,{format:o.format},r),r}function NTe(t,e){return t.write(`if (typeof ${e} !== "boolean") return INVALID;`),e}function zTe(t,e,r){t.write(`if (typeof ${r} !== "bigint") return INVALID;`);let o=e._zod.def;if(o.format)switch(o.format){case"int64":t.write(`if (${r} < -9223372036854775808n || ${r} > 9223372036854775807n) return INVALID;`);break;case"uint64":t.write(`if (${r} < 0n || ${r} > 18446744073709551615n) return INVALID;`);break}return r}function MTe(t,e){return t.write(`if (typeof ${e} !== "symbol") return INVALID;`),e}function UTe(t,e){return t.write(`if (${e} !== undefined) return INVALID;`),e}function LTe(t,e){return t.write(`if (${e} !== null) return INVALID;`),e}function jTe(t,e){return t.write(`if (${e} !== undefined) return INVALID;`),e}function FTe(t,e){return t.write(`if (typeof ${e} !== "number" || !Number.isNaN(${e})) return INVALID;`),e}function qTe(t,e){return t.write(`if (!(${e} instanceof Date) || Number.isNaN(${e}.getTime())) return INVALID;`),e}function VTe(t,e,r,o,n=!0){let i=r._zod.def;t.write(`if (typeof ${o} !== "object" || ${o} === null || Array.isArray(${o})) return INVALID;`);let s=i.shape,a=Object.keys(s),c=Object.getOwnPropertySymbols(s),u=c.length?[...a,...c]:a,l=S=>typeof S=="symbol"?ye(e,S):jn(S),d=S=>typeof S=="symbol"?`[${l(S)}]`:jn(S),p=s;if(a.includes("__proto__"))throw new Be('object shape key "__proto__"');let f=new Map;for(let S of u){let x=p[S],R=l(S),T=pe(e);if(t.write(`const ${T} = ${o}[${R}];`),x._zod.optin!==void 0){let M=pe(e);t.write(`let ${M} = (() => {`),t.indented(Z=>{let te=_n(Z,e,x,T);Z.write(`return ${te};`)}),t.write("})();"),x._zod.optout==="optional"?(t.write(`if (${M} === INVALID) {`),t.indented(Z=>{Z.write(`if (${R} in ${o}) return INVALID;`),Z.write(`${M} = undefined;`)}),t.write("}")):t.write(`if (${M} === INVALID) return INVALID;`),f.set(S,M)}else{KTe(x)&&t.write(`if (!(${R} in ${o})) return INVALID;`);let M=_n(t,e,x,T,n);M!==null&&f.set(S,M)}}let h=i.catchall,y="none";if(h){let S=h._zod.def.type;if(S==="never"){let x=a.map(R=>`k !== ${jn(R)}`).join(" && ")||"true";t.write(`for (const k in ${o}) {`),t.indented(R=>{R.write(`if (${x}) return INVALID;`)}),t.write("}")}else(S==="unknown"||S==="any")&&!h._zod.def.checks?.length?y="passthrough":y="schema"}let w=pe(e),b=u.some(S=>nZ(p[S])||eM(p[S]));if(!n){if(y==="schema"){let S=a.length>0?ye(e,new Set(a)):null;t.write(`for (const k in ${o}) {`),t.indented(x=>{x.write('if (k === "__proto__") continue;'),S&&x.write(`if (${S}.has(k)) continue;`);let R=pe(e);x.write(`const ${R} = ${o}[k];`),_n(x,e,h,R,!1)}),t.write("}")}return null}if(b){t.write(`const ${w} = {};`);for(let S of u){let x=l(S),R=f.get(S);eM(p[S])?t.write(`if (${x} in ${o}) ${w}[${x}] = ${R};`):nZ(p[S])?t.write(`if (${R} !== undefined || ${x} in ${o}) ${w}[${x}] = ${R};`):t.write(`${w}[${x}] = ${R};`)}}else{let S=u.map(x=>`${d(x)}: ${f.get(x)}`).join(", ");t.write(`const ${w} = { ${S} };`)}if(y!=="none"){let S=a.length>0?ye(e,new Set(a)):null;t.write(`for (const k in ${o}) {`),t.indented(x=>{if(x.write('if (k === "__proto__") continue;'),S&&x.write(`if (${S}.has(k)) continue;`),y==="passthrough")x.write(`${w}[k] = ${o}[k];`);else{let R=pe(e);x.write(`const ${R} = ${o}[k];`);let T=_n(x,e,h,R);x.write(`${w}[k] = ${T};`)}}),t.write("}")}return w}function GTe(t,e,r,o,n=!0){let i=r._zod.def;if(HTe(r))return nr(t,e,i.innerType,o,n);if(i.innerType._zod.optin==="defaulted"){let a=pe(e),c=pe(e);return t.write(`let ${a};`),t.write(`if (${o} === undefined) {`),t.indented(u=>{u.write(`const ${c} = (() => {`),u.indented(l=>{let d=nr(l,e,i.innerType,o);l.write(`return ${d};`)}),u.write("})();"),u.write(`if (${c} !== INVALID) ${a} = ${c};`)}),t.write("} else {"),t.indented(u=>{let l=nr(u,e,i.innerType,o);u.write(`${a} = ${l};`)}),t.write("}"),a}let s=n?pe(e):null;return s&&t.write(`let ${s};`),t.write(`if (${o} !== undefined) {`),t.indented(a=>{let c=nr(a,e,i.innerType,o,n);s&&c!==null&&a.write(`${s} = ${c};`)}),t.write("}"),s}function HTe(t){return t._zod.traits?.has("$ZodExactOptional")===!0}function KTe(t){return t._zod.optin===void 0&&ql(t)}function ql(t){if(t._zod.def.coerce)return!0;let e=t._zod.def;switch(e.type){case"any":case"unknown":case"undefined":case"void":case"default":case"prefault":case"transform":case"custom":case"lazy":return!0;case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"never":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":return!1;case"nonoptional":return e.innerType?ql(e.innerType):!1;case"literal":return!!e.values?.includes(void 0);case"enum":return!!t._zod.values?.has(void 0);case"optional":case"nullable":case"readonly":case"success":return e.innerType?ql(e.innerType):!0;case"catch":return!0;case"union":return e.options?e.options.some(ql):!0;case"intersection":return!e.left||!e.right?!0:ql(e.left)&&ql(e.right);case"pipe":return e.in?ql(e.in):!0;default:return!0}}function eM(t){return t._zod.optin==="optional"&&t._zod.optout==="optional"}function nZ(t){return(t._zod.optin!=="defaulted"||t._zod.optout==="optional")&&qp(t)}function qp(t){let e=t._zod.def;switch(e.type){case"string":case"number":case"boolean":case"bigint":case"symbol":case"null":case"nan":case"date":case"object":case"array":case"tuple":case"record":case"map":case"set":case"file":case"template_literal":case"never":case"success":return!1;case"literal":return!!e.values?.includes(void 0);case"enum":return!!t._zod.values?.has(void 0);case"optional":return!0;case"nullable":case"readonly":case"nonoptional":return e.innerType?qp(e.innerType):!0;case"union":return e.options?e.options.some(qp):!0;case"intersection":return!e.left||!e.right||qp(e.left)||qp(e.right);case"pipe":return e.out?qp(e.out):!0;default:return!0}}function BTe(t,e,r,o,n=!0){let i=r._zod.def,s=n?pe(e):null;return s&&t.write(`let ${s} = null;`),t.write(`if (${o} !== null) {`),t.indented(a=>{let c=nr(a,e,i.innerType,o,n);s&&c!==null&&a.write(`${s} = ${c};`)}),t.write("}"),s}function ZTe(t,e,r,o,n=!0){let i=r._zod.def;t.write(`if (!Array.isArray(${o})) return INVALID;`);let s=n?pe(e):null,a=pe(e),c=pe(e);return s&&t.write(`const ${s} = new Array(${o}.length);`),t.write(`for (let ${a} = 0; ${a} < ${o}.length; ${a}++) {`),t.indented(u=>{u.write(`const ${c} = ${o}[${a}];`);let l=_n(u,e,i.element,c,n);s&&l!==null&&u.write(`${s}[${a}] = ${l};`)}),t.write("}"),s}function WTe(t,e,r,o){let i=r._zod.def.values;if(i.length!==1){let a=ye(e,new Set(i));return t.write(`if (!${a}.has(${o})) return INVALID;`),o}let s=i[0];if(typeof s=="number"&&Number.isNaN(s)){let a=ye(e,new Set(i));return t.write(`if (!${a}.has(${o})) return INVALID;`),o}if(typeof s=="string")t.write(`if (${o} !== ${jn(s)}) return INVALID;`);else if(typeof s=="number"||typeof s=="boolean")t.write(`if (${o} !== ${s}) return INVALID;`);else if(s===null)t.write(`if (${o} !== null) return INVALID;`);else if(s===void 0)t.write(`if (${o} !== undefined) return INVALID;`);else if(typeof s=="bigint")t.write(`if (${o} !== ${s}n) return INVALID;`);else throw new Be(`literal type ${typeof s}`);return o}function JTe(t,e,r,o){let n=r._zod.values;if(!n)throw new Be("enum schema without enumerated values");let i=ye(e,n);return t.write(`if (!${i}.has(${o})) return INVALID;`),o}function oZ(t,e,r,o){let n=r._zod.def;return nr(t,e,n.innerType,o)}function XTe(t,e,r,o){let n=r._zod.def,s=Object.getOwnPropertyDescriptor(r._zod.def,"defaultValue")?()=>r._zod.def.defaultValue:void 0;if(r._zod.def.type==="prefault"){if(!s)return nr(t,e,n.innerType,o);let c=ye(e,s),u=pe(e);return t.write(`let ${u} = ${o};`),t.write(`if (${o} === undefined) ${u} = ${c}();`),nr(t,e,n.innerType,u)}let a=pe(e);if(s){let c=ye(e,s),u=ye(e,xp);t.write(`let ${a};`),t.write(`if (${o} === undefined) {`),t.indented(l=>{l.write(`${a} = ${u}(${c}());`)}),t.write("} else {"),t.indented(l=>{let d=nr(l,e,n.innerType,o);l.write(`${a} = ${d} === undefined ? ${u}(${c}()) : ${d};`)}),t.write("}")}else t.write(`let ${a};`),t.write(`if (${o} !== undefined) {`),t.indented(c=>{let u=nr(c,e,n.innerType,o);c.write(`${a} = ${u};`)}),t.write("}");return a}function YTe(t,e,r,o){let n=r._zod.def,i=nr(t,e,n.innerType,o),s=pe(e);return t.write(`const ${s} = ${i};`),t.write(`if (${s} === undefined) return INVALID;`),s}function QTe(t,e,r,o){let n=r._zod.def,i=n.items,s=n.rest;t.write(`if (!Array.isArray(${o})) return INVALID;`);let a=iZ(i,"optin"),c=iZ(i,"optout");s?t.write(`if (${o}.length < ${a}) return INVALID;`):t.write(`if (${o}.length < ${a} || ${o}.length > ${i.length}) return INVALID;`);let u=pe(e);t.write(`const ${u} = [];`);for(let l=0;l<i.length;l++){let d=i[l];if(l>=c)t.write(`if (${u}.length === ${l}) {`),t.indented(p=>{p.write(`if (${l} < ${o}.length) {`),p.indented(f=>{let h=pe(e);f.write(`const ${h} = ${o}[${l}];`);let y=_n(f,e,d,h);f.write(`${u}[${l}] = ${y};`)}),p.write("} else {"),p.indented(f=>{if(eM(d)){f.write(`${u}.length = ${l};`);return}let h=pe(e),y=pe(e);f.write(`const ${h} = undefined;`),f.write(`const ${y} = (() => {`),f.indented(w=>{let b=_n(w,e,d,h);w.write(`return ${b};`)}),f.write("})();"),f.write(`if (${y} === INVALID || ${y} === undefined) ${u}.length = ${l};`),f.write(`else ${u}[${l}] = ${y};`)}),p.write("}")}),t.write("}");else{let p=pe(e);t.write(`const ${p} = ${o}[${l}];`);let f=_n(t,e,d,p);t.write(`${u}[${l}] = ${f};`)}}if(s){let l=pe(e),d=pe(e);t.write(`for (let ${l} = ${i.length}; ${l} < ${o}.length; ${l}++) {`),t.indented(p=>{p.write(`const ${d} = ${o}[${l}];`);let f=_n(p,e,s,d);p.write(`${u}[${l}] = ${f};`)}),t.write("}")}return u}function iZ(t,e){for(let r=t.length-1;r>=0;r--)if(!(e==="optin"?t[r]._zod.optin!==void 0:t[r]._zod.optout==="optional"))return r+1;return 0}function eCe(t,e,r,o){let n=r._zod.def,i=n.options;if(n.discriminator)return tCe(t,e,n,o);if(n.inclusive===!1)throw new Be("exclusive unions (z.xor)");if(i.length===0)return t.write("return INVALID;"),o;if(i.length===1)return nr(t,e,i[0],o);if(i.every(c=>c._zod.def.type==="literal"&&!c._zod.def.checks?.length)){let c=new Set(i.flatMap(l=>l._zod.def.values)),u=ye(e,c);return t.write(`if (!${u}.has(${o})) return INVALID;`),o}let a=pe(e);t.write(`let ${a};`);for(let c=0;c<i.length;c++){let u=i[c];c===0?t.write(`${a} = (() => {`):t.write(`if (${a} === INVALID) ${a} = (() => {`),t.indented(l=>{let d=nr(l,e,u,o);l.write(`return ${d};`)}),t.write("})();")}return t.write(`if (${a} === INVALID) return INVALID;`),a}function tCe(t,e,r,o){if(r.unionFallback)throw new Be("discriminated union with unionFallback");if(r.options.length===0)return t.write("return INVALID;"),o;let n=pe(e),i=pe(e);t.write(`const ${n} = ${o}?.[${jn(r.discriminator)}];`),t.write(`let ${i};`);let s=!0,a=new Set;for(let c of r.options){let u=c._zod.propValues?.[r.discriminator];if(!u||u.size===0)throw new Be("discriminated union option without static discriminator values");for(let p of u){if(a.has(p))throw new Be(`duplicate discriminator value ${String(p)}`);a.add(p)}let l=Array.from(u,p=>rCe(e,n,p)),d=s?"if":"else if";t.write(`${d} (${l.join(" || ")}) {`),t.indented(p=>{let f=nr(p,e,c,o);p.write(`${i} = ${f};`)}),t.write("}"),s=!1}return t.write("else { return INVALID; }"),i}function rCe(t,e,r){if(typeof r=="string")return`${e} === ${jn(r)}`;if(typeof r=="number")return Number.isNaN(r)?`Number.isNaN(${e})`:`${e} === ${r}`;if(typeof r=="boolean")return`${e} === ${r}`;if(r===null)return`${e} === null`;if(r===void 0)return`${e} === undefined`;if(typeof r=="bigint")return`${e} === ${r}n`;if(typeof r=="symbol"){let o=ye(t,r);return`${e} === ${o}`}throw new Be(`literal discriminator value ${String(r)}`)}function nCe(t,e,r,o){let n=r._zod.def;e.definite=!1;let i=_n(t,e,n.left,o),s=_n(t,e,n.right,o),a=ye(e,Dp),c=pe(e);return t.write(`const ${c} = ${a}(${i}, ${s});`),t.write(`if (!${c}.valid) return INVALID;`),`${c}.data`}function oCe(t,e,r,o){let n=r._zod.def,i=ye(e,Jo);t.write(`if (!${i}(${o})) return INVALID;`);let s=pe(e),a=pe(e),c=pe(e);t.write(`const ${s} = {};`);let u=n,l=u.partial?void 0:n.keyType._zod.values;if(l){let f=[];for(let y of l){if(!(typeof y=="string"||typeof y=="number"||typeof y=="symbol"))throw new Be(`record key value ${String(y)}`);let w=typeof y=="number"?y.toString():y;if(w==="__proto__")throw new Be('record key "__proto__"');f.push(w);let b=ye(e,y),S=nr(t,e,n.keyType,b),x=pe(e);t.write(`const ${x} = ${o}[${iCe(e,w)}];`);let R=_n(t,e,n.valueType,x);t.write(`${s}[${S}] = ${R};`)}let h=ye(e,new Set(f));return t.write(`for (const ${a} in ${o}) {`),t.indented(y=>{y.write(`if (${h}.has(${a})) continue;`),u.mode==="loose"?y.write(`if (${a} !== "__proto__") ${s}[${a}] = ${o}[${a}];`):y.write("return INVALID;")}),t.write("}"),s}let d=n.keyType._zod.def;if(!(d.type==="string"&&d.format===void 0&&!d.coerce&&(d.checks?.length??0)===0)){let f=n.mode==="loose",h=a0(n.keyType);h.definite===!1&&(e.definite=!1);let y=ye(e,h),w=ye(e,Fa),b=pe(e);return sZ(t,e,o,a,S=>{S.write(`let ${b} = ${y}(${a});`),S.write(`if (${b} === INVALID && typeof ${a} === "string" && ${w}.test(${a})) ${b} = ${y}(Number(${a}));`),f?S.write(`if (${b} === INVALID) { ${s}[${a}] = ${o}[${a}]; continue; }`):S.write(`if (${b} === INVALID) return INVALID;`),S.write(`if (${b} === "__proto__") continue;`);let x=pe(e);S.write(`const ${x} = ${o}[${a}];`);let R=_n(S,e,n.valueType,x);S.write(`${s}[${b}] = ${R};`)}),s}return sZ(t,e,o,a,f=>{f.write(`const ${c} = ${o}[${a}];`);let h=_n(f,e,n.valueType,c);f.write(`${s}[${a}] = ${h};`)},"return INVALID;"),s}function sZ(t,e,r,o,n,i){let s=ye(e,Object.prototype.propertyIsEnumerable),a=pe(e),c=pe(e),u=pe(e);t.write(`const ${a} = Object.getOwnPropertySymbols(${r});`),t.write(`const ${c} = Object.getOwnPropertyNames(${r});`),t.write(`for (let ${u} = 0; ${u} < ${c}.length; ${u}++) {`),t.indented(l=>{l.write(`const ${o} = ${c}[${u}];`),l.write(`if (${o} === "__proto__" || !${s}.call(${r}, ${o})) continue;`),n(l)}),t.write("}"),t.write(`for (let ${u} = 0; ${u} < ${a}.length; ${u}++) {`),t.indented(l=>{l.write(`const ${o} = ${a}[${u}];`),l.write(`if (!${s}.call(${r}, ${o})) continue;`),i?l.write(i):n(l)}),t.write("}")}function iCe(t,e){return typeof e=="string"?jn(e):ye(t,e)}function sCe(t,e,r,o){let n=r._zod.def;t.write(`if (!(${o} instanceof Map)) return INVALID;`);let i=pe(e),s=pe(e),a=pe(e);return t.write(`const ${i} = new Map();`),t.write(`for (const [${s}, ${a}] of ${o}) {`),t.indented(c=>{let u=nr(c,e,n.keyType,s),l=nr(c,e,n.valueType,a);c.write(`${i}.set(${u}, ${l});`)}),t.write("}"),i}function aCe(t,e,r,o){let n=r._zod.def;t.write(`if (!(${o} instanceof Set)) return INVALID;`);let i=pe(e),s=pe(e);return t.write(`const ${i} = new Set();`),t.write(`for (const ${s} of ${o}) {`),t.indented(a=>{let c=nr(a,e,n.valueType,s);a.write(`${i}.add(${c});`)}),t.write("}"),i}function cCe(t,e){return t.write(`if (!(${e} instanceof File)) return INVALID;`),e}function uCe(t,e,r,o){t.write(`if (typeof ${o} !== "string") return INVALID;`);let n=r._zod.pattern;if(n){let i=ye(e,n);t.write(`${i}.lastIndex = 0;`),t.write(`if (!${i}.test(${o})) return INVALID;`)}return o}function lCe(t,e,r,o){let n=r._zod.def,i=Vl(e,n.getter),s=ye(e,{parser:null});t.write(`if (!${s}.parser) {`),t.indented(c=>{c.write(`const inner = ${i}();`),c.write(`${s}.parser = function(input) {`),c.indented(u=>{u.write("const result = inner._zod.run({ value: input, issues: [] }, {});"),u.write("return result.issues.length === 0 ? result.value : INVALID;")}),c.write("};")}),t.write("}");let a=pe(e);return t.write(`const ${a} = ${s}.parser(${o});`),t.write(`if (${a} === INVALID) return INVALID;`),a}function dCe(t,e,r,o){let n=r._zod.def,i=nr(t,e,n.in,o);if(n.transform){if(Gl(n.transform))throw new Di("z.compile: async transforms in pipes are not supported");let s=n.transform,c=Vl(e,l=>{let d={value:l,issues:[],addIssue:rM},p=s(l,d);return p instanceof Promise?qn:d.issues.length===0?p:qn}),u=pe(e);return t.write(`const ${u} = ${c}(${i});`),t.write(`if (${u} === INVALID) return INVALID;`),nr(t,e,n.out,u)}else return nr(t,e,n.out,i)}function Gl(t){return typeof t=="function"&&(t.constructor.name==="AsyncFunction"||t[Symbol.toStringTag]==="AsyncFunction")}function pCe(t,e,r,o){let n=r._zod.def;if(n.fn){if(Gl(n.fn))throw new Di("z.compile: async custom predicates are not supported");let i=Vl(e,n.fn),s=ye(e,Qz),a=pe(e);t.write(`const ${a} = ${i}(${o});`),t.write(`if (${a} instanceof Promise) ${s}();`),t.write(`if (!${a}) return INVALID;`)}else throw new Be("custom schema without a predicate function");return o}function fCe(t,e,r){let o=t._zod.run({value:r,issues:[]},{});if(o&&typeof o.then=="function")return qn;let n=o;return n.issues.length===0?n.value:e()}function mCe(t,e,r,o){let n=r._zod.def;if(!n.catchValue[hS])throw new Be("catch with a callback (only a constant catch value compiles)",!1);let i=pe(e);t.write(`let ${i} = (() => {`),t.indented(u=>{let l=_n(u,e,n.innerType,o);u.write(`return ${l};`)}),t.write("})();");let s=ye(e,n.innerType),a=Vl(e,n.catchValue),c=ye(e,fCe);return t.write(`if (${i} === INVALID) {`),t.indented(u=>{u.write(`${i} = ${c}(${s}, ${a}, ${o});`),u.write(`if (${i} === INVALID) return INVALID;`)}),t.write("}"),i}function hCe(t,e,r,o){let n=r._zod.def;if(n.transform){if(Gl(n.transform))throw new Di("z.compile: async transforms are not supported");let i=n.transform,a=Vl(e,u=>{let l={value:u,issues:[],addIssue:rM},d=i(u,l);return d instanceof Promise?qn:l.issues.length===0?d:qn}),c=pe(e);return t.write(`const ${c} = ${a}(${o});`),t.write(`if (${c} === INVALID) return INVALID;`),c}return o}function c0(t){return t.checks&&(t.checks=[...t.checks]),t}function u0(t,e){return new t(c0({type:"string",...j(e)}))}function nM(t,e){return new t(c0({type:"string",coerce:!0,...j(e)}))}function Dg(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...j(e)})}function Ng(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...j(e)})}function zg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...j(e)})}function Mg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...j(e)})}function Ug(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...j(e)})}function Lg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...j(e)})}function Vp(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...j(e)})}function jg(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...j(e)})}function Fg(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...j(e)})}function qg(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...j(e)})}function Vg(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...j(e)})}function Gg(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...j(e)})}function Hg(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...j(e)})}function Kg(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...j(e)})}function Bg(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...j(e)})}function Zg(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...j(e)})}function l0(t,e){return new t({type:"string",format:"mac",check:"string_format",abort:!1,...j(e)})}function Wg(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...j(e)})}function Jg(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...j(e)})}function Xg(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...j(e)})}function Yg(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...j(e)})}function Qg(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...j(e)})}function d0(t,e){return new t({type:"string",format:"credit_card",check:"string_format",abort:!1,...j(e)})}function p0(t,e){return new t({type:"string",format:"iban",check:"string_format",abort:!1,...j(e)})}function ey(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...j(e)})}var oM={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function ty(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...j(e)})}function ry(t,e){return new t({type:"string",format:"date",check:"string_format",...j(e)})}function ny(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...j(e)})}function oy(t,e){return new t({type:"string",format:"duration",check:"string_format",...j(e)})}function f0(t,e){return new t(c0({type:"number",checks:[],...j(e)}))}function iM(t,e){return new t(c0({type:"number",coerce:!0,checks:[],...j(e)}))}function m0(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...j(e)})}function h0(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float32",...j(e)})}function g0(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float64",...j(e)})}function y0(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"int32",...j(e)})}function v0(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"uint32",...j(e)})}function w0(t,e){return new t({type:"boolean",...j(e)})}function sM(t,e){return new t({type:"boolean",coerce:!0,...j(e)})}function _0(t,e){return new t({type:"bigint",...j(e)})}function aM(t,e){return new t({type:"bigint",coerce:!0,...j(e)})}function b0(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...j(e)})}function S0(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...j(e)})}function x0(t,e){return new t({type:"symbol",...j(e)})}function E0(t,e){return new t({type:"undefined",...j(e)})}function $0(t,e){return new t({type:"null",...j(e)})}function R0(t){return new t({type:"any"})}function I0(t){return new t({type:"unknown"})}function A0(t,e){return new t({type:"never",...j(e)})}function P0(t,e){return new t({type:"void",...j(e)})}function k0(t,e){return new t({type:"date",...j(e)})}function cM(t,e){return new t({type:"date",coerce:!0,...j(e)})}function T0(t,e){return new t({type:"nan",...j(e)})}function ks(t,e){return new PS({check:"less_than",...j(e),value:t,inclusive:!1})}function $o(t,e){return new PS({check:"less_than",...j(e),value:t,inclusive:!0})}function Ts(t,e){return new kS({check:"greater_than",...j(e),value:t,inclusive:!1})}function Ro(t,e){return new kS({check:"greater_than",...j(e),value:t,inclusive:!0})}function C0(t){return Ts(0,t)}function O0(t){return ks(0,t)}function D0(t){return $o(0,t)}function N0(t){return Ro(0,t)}function Fc(t,e){return new vz({check:"multiple_of",...j(e),value:t})}function qc(t,e){return new bz({check:"max_size",...j(e),maximum:t})}function Cs(t,e){return new Sz({check:"min_size",...j(e),minimum:t})}function Hl(t,e){return new xz({check:"size_equals",...j(e),size:t})}function Kl(t,e){return new Ez({check:"max_length",...j(e),maximum:t})}function qa(t,e){return new $z({check:"min_length",...j(e),minimum:t})}function Bl(t,e){return new Rz({check:"length_equals",...j(e),length:t})}function Gp(t,e){return new Iz({check:"string_format",format:"regex",...j(e),pattern:t})}function Hp(t){return new Az({check:"string_format",format:"lowercase",...j(t)})}function Kp(t){return new Pz({check:"string_format",format:"uppercase",...j(t)})}function Bp(t,e){return new kz({check:"string_format",format:"includes",...j(e),includes:t})}function Zp(t,e){return new Tz({check:"string_format",format:"starts_with",...j(e),prefix:t})}function Wp(t,e){return new Cz({check:"string_format",format:"ends_with",...j(e),suffix:t})}function z0(t,e,r){return new Oz({check:"property",property:t,schema:e,...j(r)})}function Jp(t,e){return new Dz({check:"properties",shape:t,...j(e)})}function Xp(t,e){return new Nz({check:"mime_type",mime:t,...j(e)})}function Ni(t){return new zz({check:"overwrite",tx:t})}function Yp(t){return Ni(e=>e.normalize(t))}function Qp(){return Ni(t=>t.trim())}function ef(){return Ni(t=>t.toLowerCase())}function tf(){return Ni(t=>t.toUpperCase())}function rf(){return Ni(t=>w1(t))}function uM(t,e,r){return new t({type:"array",element:e,...j(r)})}function gCe(t,e,r){return new t({type:"union",options:e,...j(r)})}function yCe(t,e,r){return new t({type:"union",options:e,inclusive:!1,...j(r)})}function vCe(t,e,r,o){return new t({type:"union",options:r,discriminator:e,...j(o)})}function wCe(t,e,r){return new t({type:"intersection",left:e,right:r})}function _Ce(t,e,r,o){let n=r instanceof be,i=n?o:r,s=n?r:null;return new t({type:"tuple",items:e,rest:s,...j(i)})}function bCe(t,e,r,o){return new t({type:"record",keyType:e,valueType:r,...j(o)})}function SCe(t,e,r,o){return new t({type:"map",keyType:e,valueType:r,...j(o)})}function xCe(t,e,r){return new t({type:"set",valueType:e,...j(r)})}function ECe(t,e,r){let o=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new t({type:"enum",entries:o,...j(r)})}function $Ce(t,e,r){return new t({type:"enum",entries:e,...j(r)})}function RCe(t,e,r){return new t({type:"literal",values:Array.isArray(e)?e:[e],...j(r)})}function M0(t,e){return new t({type:"file",...j(e)})}function ICe(t,e){return new t({type:"transform",transform:e})}function ACe(t,e){return new t({type:"optional",innerType:e})}function PCe(t,e){return new t({type:"nullable",innerType:e})}function kCe(t,e,r){return new t({type:"default",innerType:e,get defaultValue(){return typeof r=="function"?r():xp(r)}})}function TCe(t,e,r){return new t({type:"nonoptional",innerType:e,...j(r)})}function CCe(t,e){return new t({type:"success",innerType:e})}function OCe(t,e,r){return new t({type:"catch",innerType:e,catchValue:typeof r=="function"?r:R1(r)})}function DCe(t,e,r){return new t({type:"pipe",in:e,out:r})}function NCe(t,e){return new t({type:"readonly",innerType:e})}function zCe(t,e,r){return new t({type:"template_literal",parts:e,...j(r)})}function MCe(t,e){return new t({type:"lazy",getter:e})}function UCe(t,e){return new t({type:"promise",innerType:e})}function U0(t,e,r){let o=j(r);return o.abort??(o.abort=!0),new t({type:"custom",check:"custom",fn:e,...o})}function L0(t,e,r){return new t({type:"custom",check:"custom",fn:e,...j(r)})}function j0(t,e){let r=lZ(o=>(o.addIssue=n=>{if(typeof n=="string")o.issues.push(Ep(n,o.value,r._zod.def));else{let i=n;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),"input"in i||(i.input=o.value),i.inst??(i.inst=r),i.continue??(i.continue=!r._zod.def.abort),o.issues.push(Ep(i))}},t(o.value,o)),e);return r}function lZ(t,e){let r=new Pt({check:"custom",...j(e)});return r._zod.check=t,r}function F0(t){let e=new Pt({check:"describe"});return e._zod.onattach=[r=>{let o=Jr.get(r)??{};Jr.add(r,{...o,description:t})}],e._zod.check=()=>{},e}function q0(t){let e=new Pt({check:"meta"});return e._zod.onattach=[r=>{let o=Jr.get(r)??{};Jr.add(r,{...o,...t})}],e._zod.check=()=>{},e}function V0(t,e){let r=j(e),o=r.truthy??["true","1","yes","on","y","enabled"],n=r.falsy??["false","0","no","off","n","disabled"];r.case!=="sensitive"&&(o=o.map(f=>typeof f=="string"?f.toLowerCase():f),n=n.map(f=>typeof f=="string"?f.toLowerCase():f));let i=new Set(o),s=new Set(n),a=t.Codec??Mp,c=t.Boolean??Np,u=t.String??jc,l=new u({type:"string",error:r.error}),d=new c({type:"boolean",error:r.error}),p=new a({type:"pipe",in:l,out:d,transform:((f,h)=>{let y=f;return r.case!=="sensitive"&&(y=y.toLowerCase()),i.has(y)?!0:s.has(y)?!1:(h.issues.push({code:"invalid_value",expected:"stringbool",values:[...i,...s],input:h.value,inst:p,continue:!1}),{})}),reverseTransform:((f,h)=>f===!0?o[0]||"true":n[0]||"false"),error:r.error});return p._zod.bag.truthy=o,p._zod.bag.falsy=n,p._zod.bag.case=r.case??"insensitive",p}function Vc(t,e,r,o={}){let n=j(o),i={check:"string_format",type:"string",format:e,fn:typeof r=="function"?r:a=>r.test(a),...n};return r instanceof RegExp&&(i.pattern=r),new t(i)}function iy(t,...e){for(let r of e)for(let o of Reflect.ownKeys(r))Object.prototype.propertyIsEnumerable.call(r,o)&&Wr(t,o,r[o]);return t}function Gc(t){let e=t?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??Jr,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:t?.cycles??"ref",reused:t?.reused??"inline",intersections:[],deferred:[],external:t?.external??void 0}}function Pr(t,e,r,o,n){let i=typeof e.unrepresentable=="function"?e.unrepresentable({zodSchema:t,path:o.path,message:n}):e.unrepresentable;if(i==="any")return!1;if(i===void 0||i==="throw")throw new Error(n);return Object.assign(r,i),!0}function Rt(t,e,r={path:[],schemaPath:[]}){var o;let n=t._zod.def,i=e.seen.get(t);if(i)return i.count++,r.schemaPath.includes(t)&&(i.cycle=r.path),i.schema;let s={schema:{},count:1,cycle:void 0,path:r.path};e.seen.set(t,s),e.sharedDefsExtractedFor=void 0,e.sharedEmitDoneFor=void 0;let a=t._zod.toJSONSchema?.();if(a)s.schema=a;else{let l={...r,schemaPath:[...r.schemaPath,t],path:r.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,s.schema,l);else{let p=s.schema,f=e.processors[n.type];if(!f)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);f(t,e,p,l)}let d=t._zod.parent;d&&(s.ref||(s.ref=d),Rt(d,e,l),e.seen.get(d).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&iy(s.schema,c),e.io==="input"&&Vn(t)&&(delete s.schema.examples,delete s.schema.default),e.io==="input"&&"_prefault"in s.schema&&((o=s.schema).default??(o.default=s.schema._prefault)),delete s.schema._prefault,e.seen.get(t).schema}function dZ(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function Hc(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");if(t.external&&t.sharedDefsExtractedFor===t.external)return;let o=new Map;for(let s of t.seen.entries()){let a=t.metadataRegistry.get(s[0])?.id;if(a){let c=o.get(a);if(c&&c!==s[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(a,s[0])}}let n=s=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let d=t.external.registry.get(s[0])?.id,p=t.external.uri??(h=>h);if(d)return{ref:p(d)};let f=s[1].defId??s[1].schema.id??`schema${t.counter++}`;return s[1].defId=f,{defId:f,ref:`${p("__shared")}#/${a}/${dZ(f)}`}}let c="#",u=`${c}/${a}/`;if(s[1]===r&&!s[1].schema.id)return{ref:c};let l=s[1].schema.id??`__schema${t.counter++}`;return{defId:l,ref:u+dZ(l)}},i=s=>{if(s[1].schema.$ref)return;let a=s[1],{ref:c,defId:u}=n(s);a.def={...a.schema},u&&(a.defId=u);let l=a.schema;for(let d in l)delete l[d];l.$ref=c};if(t.cycles==="throw")for(let s of t.seen.entries()){let a=s[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
127
127
 
128
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of t.seen.entries()){let a=s[1];if(e===s[0]){i(s);continue}if(t.external){let u=t.external.registry.get(s[0])?.id;if(e!==s[0]&&u){i(s);continue}}if(t.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}a.count>1&&t.reused==="ref"&&i(s)}t.external&&(t.sharedDefsExtractedFor=t.external)}function mZ(t){let e=t.anyOf;if(!Array.isArray(e)||e.length===0||t.type!==void 0)return;let r=[];for(let o of e){if(!o||typeof o!="object")return;mZ(o);let n=Object.keys(o);if(n.length!==1||n[0]!=="type")return;let i=o.type;for(let s of Array.isArray(i)?i:[i]){if(typeof s!="string")return;r.includes(s)||r.push(s)}}delete t.anyOf,t.type=r.length===1?r[0]:r}var hZ=new Set(["type","properties","required","additionalProperties"]),pZ=["oneOf","anyOf"];function fZ(t){let e=t.additionalProperties;return e===void 0||e===!1||typeof e!="object"||e===null?null:Object.keys(e).length?e:null}function lM(t){let e=[];for(let i of t){if(typeof i!="object"||i.type!=="object")return null;for(let s in i)if(!hZ.has(s))return null;e.push(i)}let r={},o=new Set;for(let i of e){for(let s in i.properties){if(Object.prototype.hasOwnProperty.call(r,s))continue;let a=[];for(let u of e){let l=u.properties?.[s]??fZ(u);l!=null&&(a.some(d=>JSON.stringify(d)===JSON.stringify(l))||a.push(l))}let c=a.length===1?a[0]:lM(a)??{allOf:a};Wr(r,s,c)}for(let s of i.required??[])o.add(s)}let n={type:"object",properties:r};if(o.size&&(n.required=[...o]),e.every(i=>i.additionalProperties===!1))n.additionalProperties=!1;else{let i=[];for(let s of e){let a=fZ(s);a&&!i.some(c=>JSON.stringify(c)===JSON.stringify(a))&&i.push(a)}i.length===1?n.additionalProperties=i[0]:i.length>1&&(n.additionalProperties={allOf:i})}return n}function LCe(t){let e=t.allOf;if(!Array.isArray(e)||e.length<2)return;for(let n of hZ)if(n in t)return;let r=e.filter(n=>pZ.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=lM(e);else{let n=r[0],i=pZ.find(c=>Array.isArray(n[c]));if(Object.keys(n).length!==1)return;let s=e.filter(c=>c!==n),a=n[i].map(c=>lM([...s,c]));if(a.some(c=>!c))return;o={[i]:a}}o&&(delete t.allOf,iy(t,o))}function Kc(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},d=c.ref;if(c.ref=null,d){o(d);let f=t.seen.get(d),h=f.schema;if(h.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(h)):iy(u,h),iy(u,l),a._zod.parent===d)for(let w in u)w==="$ref"||w==="allOf"||w in l||delete u[w];if(h.$ref&&f.def)for(let w in u)w==="$ref"||w==="allOf"||w in f.def&&JSON.stringify(u[w])===JSON.stringify(f.def[w])&&delete u[w]}let p=a._zod.parent;if(p&&p!==d){o(p);let f=t.seen.get(p);if(f?.schema.$ref&&(u.$ref=f.schema.$ref,f.def))for(let h in u)h==="$ref"||h==="allOf"||h in f.def&&JSON.stringify(u[h])===JSON.stringify(f.def[h])&&delete u[h]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};if(!t.external||t.sharedEmitDoneFor!==t.external){for(let a of[...t.seen.entries()].reverse())o(a[0]);if(t.target!=="openapi-3.0")for(let a of t.seen.entries())mZ(a[1].def??a[1].schema);for(let a of t.deferred)a();if(t.intersections.length){let a=new Map;for(let c of t.seen.values())for(let u of[c.schema,c.def]){let l=u?.allOf;if(!Array.isArray(l))continue;let d=a.get(l);d?d.push(u):a.set(l,[u])}for(let c of t.intersections)for(let u of a.get(c)??[])LCe(u)}}let n={};if(t.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");n.$id=t.external.uri(a)}iy(n,r.defId?r.schema:r.def??r.schema);let i=t.metadataRegistry.get(e)?.id;i!==void 0&&n.id===i&&delete n.id;let s=t.external?.defs??{};if(!t.external||t.sharedEmitDoneFor!==t.external)for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,Wr(s,c.defId,c.def))}t.external&&(t.sharedEmitDoneFor=t.external),t.external||Object.keys(s).length>0&&(t.target==="draft-2020-12"?n.$defs=s:n.definitions=s);try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:nf(e,"input",t.processors),output:nf(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Vn(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return Vn(o.element,r);if(o.type==="set")return Vn(o.valueType,r);if(o.type==="lazy")return Vn(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault"||o.type==="catch")return Vn(o.innerType,r);if(o.type==="intersection")return Vn(o.left,r)||Vn(o.right,r);if(o.type==="record"||o.type==="map")return Vn(o.keyType,r)||Vn(o.valueType,r);if(o.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Vn(o.in,r)||Vn(o.out,r);if(o.type==="object"){for(let n in o.shape)if(Vn(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(Vn(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(Vn(n,r))return!0;return!!(o.rest&&Vn(o.rest,r))}return!1}var dM=(t,e={})=>r=>{let o=Gc({...r,processors:e});return Rt(t,o),Hc(o,t),Kc(o,t)},nf=(t,e,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},s=Gc({...n??{},target:i,io:e,processors:r});return Rt(t,s),Hc(s,t),Kc(s,t)};var of=(t,e,r)=>{(t[e]===void 0||r>t[e])&&(t[e]=r)},sf=(t,e,r)=>{(t[e]===void 0||r<t[e])&&(t[e]=r)},gZ=(t,e)=>{of(t,"minimum",e),sf(t,"maximum",e)},_Z=(t,e)=>{t.multipleOf??(t.multipleOf=[]),t.multipleOf.includes(e)||t.multipleOf.push(e)},bZ=(t,e)=>{t.patterns??(t.patterns=new Set),t.patterns.add(e)},SZ=(t,e)=>{t.mime=t.mime?t.mime.filter(r=>e.includes(r)):[...e]},xZ=(t,e)=>{t.format=e,e.includes("int")&&(t.isInt=!0)},yZ=(t,e)=>of(t,"minimum",e.minimum),vZ=(t,e)=>sf(t,"maximum",e.maximum),wZ=t=>(e,r)=>{xZ(e,r.format);let[o,n]=t[r.format];of(e,"minimum",o),sf(e,"maximum",n)},jCe={greater_than:(t,e)=>of(t,e.inclusive?"minimum":"exclusiveMinimum",e.value),less_than:(t,e)=>sf(t,e.inclusive?"maximum":"exclusiveMaximum",e.value),multiple_of:(t,e)=>_Z(t,e.value),number_format:wZ(ug),bigint_format:wZ(lg),min_length:yZ,max_length:vZ,length_equals:(t,e)=>gZ(t,e.length),min_size:yZ,max_size:vZ,size_equals:(t,e)=>gZ(t,e.size),string_format:(t,e)=>{xZ(t,e.format),e.pattern&&bZ(t,e.pattern),(e.format==="base64"||e.format==="base64url")&&(t.contentEncoding=e.format),(e.local||e.precision===-1)&&(t.laxFormat=!0)},mime_type:(t,e)=>SZ(t,e.mime)};function kr(t){let e={},r=t._zod.def,o=t._zod.traits.has("$ZodCheck")?[t,...r.checks??[]]:r.checks??[];for(let i of o)jCe[i._zod.def.check]?.(e,i._zod.def);let n=t._zod.bag;n.minimum!==void 0&&of(e,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&of(e,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&sf(e,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&sf(e,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&_Z(e,n.multipleOf),n.format!==void 0&&(e.format??(e.format=n.format),n.format.includes("int")&&(e.isInt=!0)),n.mime&&SZ(e,n.mime);for(let i of n.patterns??[])bZ(e,i);return e}var FCe={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},qCe=new Map([[rx,Y1],[Eg,Q1]]),EZ=t=>qCe.get(t)??t,mM=(t,e,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:u,laxFormat:l}=kr(t);if(typeof i=="number"&&(n.minLength=i),typeof s=="number"&&(n.maxLength=s),a&&(n.format=FCe[a]??a,n.format===""&&delete n.format,(a==="time"||l)&&delete n.format),u&&(n.contentEncoding=u),c&&c.size>0){let d=[...c].map(EZ);d.length===1?n.pattern=d[0].source:d.length>1&&(n.allOf=[...d.map(p=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},hM=(t,e,r,o)=>{let n=r,{minimum:i,maximum:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:l}=kr(t);n.type=l?"integer":"number";let d=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),p=typeof c=="number"&&c<=(s??Number.POSITIVE_INFINITY),f=e.target==="draft-04"||e.target==="openapi-3.0";if(d?f?(n.minimum=u,n.exclusiveMinimum=!0):n.exclusiveMinimum=u:typeof i=="number"&&(n.minimum=i),p?f?(n.maximum=c,n.exclusiveMaximum=!0):n.exclusiveMaximum=c:typeof s=="number"&&(n.maximum=s),a){let h=new Set;for(let b of a)Number.isFinite(b)&&b!==0?h.add(Math.abs(b)):Pr(t,e,n,o,`A multipleOf divisor of ${b} cannot be represented in JSON Schema`);let[y,...w]=h;y!==void 0&&(n.multipleOf=y),w.length&&(n.allOf=[...n.allOf??[],...w.map(b=>({multipleOf:b}))])}},gM=(t,e,r,o)=>{r.type="boolean"},yM=(t,e,r,o)=>{Pr(t,e,r,o,"BigInt cannot be represented in JSON Schema")},vM=(t,e,r,o)=>{Pr(t,e,r,o,"Symbols cannot be represented in JSON Schema")},wM=(t,e,r,o)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},_M=(t,e,r,o)=>{Pr(t,e,r,o,"Undefined cannot be represented in JSON Schema")},bM=(t,e,r,o)=>{Pr(t,e,r,o,"Void cannot be represented in JSON Schema")},SM=(t,e,r,o)=>{r.not={}},xM=(t,e,r,o)=>{},EM=(t,e,r,o)=>{},$M=(t,e,r,o)=>{Pr(t,e,r,o,"Date cannot be represented in JSON Schema")},RM=(t,e,r,o)=>{let n=t._zod.def,i=wp(n.entries);if(i.length===0){r.not={};return}i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),r.enum=i},IM=(t,e,r,o)=>{let n=t._zod.def;if(n.values.length===0){r.not={};return}let i=[];for(let s of n.values)if(s===void 0){if(Pr(t,e,r,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s=="bigint"){if(Pr(t,e,r,o,"BigInt literals cannot be represented in JSON Schema"))return;i.push(Number(s))}else i.push(s);if(i.length!==0)if(i.length===1){let s=i[0];r.type=s===null?"null":typeof s,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[s]:r.const=s}else i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),i.every(s=>typeof s=="boolean")&&(r.type="boolean"),i.every(s=>s===null)&&(r.type="null"),r.enum=i},AM=(t,e,r,o)=>{Pr(t,e,r,o,"NaN cannot be represented in JSON Schema")},PM=(t,e,r,o)=>{let n=r,i=t._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=i.source},kM=(t,e,r,o)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:i,maximum:s,mime:a}=kr(t);i!==void 0&&(n.minLength=i),s!==void 0&&(n.maxLength=s),a&&(a.length===0?n.not={}:a.length===1?n.contentMediaType=a[0]:n.anyOf=a.map(c=>({contentMediaType:c})))},TM=(t,e,r,o)=>{r.type="boolean"},CM=(t,e,r,o)=>{Pr(t,e,r,o,"Custom types cannot be represented in JSON Schema")},OM=(t,e,r,o)=>{Pr(t,e,r,o,"Function types cannot be represented in JSON Schema")},DM=(t,e,r,o)=>{Pr(t,e,r,o,"Transforms cannot be represented in JSON Schema")},NM=(t,e,r,o)=>{Pr(t,e,r,o,"Map cannot be represented in JSON Schema")},zM=(t,e,r,o)=>{Pr(t,e,r,o,"Set cannot be represented in JSON Schema")},MM=(t,e,r,o)=>{let n=r,i=t._zod.def,{minimum:s,maximum:a}=kr(t);typeof s=="number"&&(n.minItems=s),typeof a=="number"&&(n.maxItems=a),n.type="array",n.items=Rt(i.element,e,{...o,path:[...o.path,"items"]})};function sy(t){let e=t._zod.def;return e.type==="pipe"&&e.in._zod.traits.has("$ZodTransform")?sy(e.out):e.type==="catch"?sy(e.innerType):t._zod.optin}var UM=(t,e,r,o)=>{let n=r,i=t._zod.def,s=i.shape;if(Object.getOwnPropertySymbols(s).length&&Pr(t,e,n,o,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let u in s)Wr(n.properties,u,Rt(s[u],e,{...o,path:[...o.path,"properties",u]}));let c=[];for(let u of Object.keys(s)){let l=i.shape[u];(e.io==="input"?sy(l)===void 0:l._zod.optout===void 0)&&c.push(u)}c.length>0&&(n.required=c),i.catchall?._zod.def.type==="never"?n.additionalProperties=!1:i.catchall?i.catchall&&(n.additionalProperties=Rt(i.catchall,e,{...o,path:[...o.path,"additionalProperties"]})):e.io==="output"&&(n.additionalProperties=!1)},H0=(t,e,r,o)=>{let n=t._zod.def,i=n.inclusive===!1,s=n.options.map((a,c)=>Rt(a,e,{...o,path:[...o.path,i?"oneOf":"anyOf",c]}));i?r.oneOf=s:r.anyOf=s},LM=(t,e,r,o)=>{let n=t._zod.def,i=Rt(n.left,e,{...o,path:[...o.path,"allOf",0]}),s=Rt(n.right,e,{...o,path:[...o.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=c,e.intersections.push(c)},jM=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="array";let s=e.target==="draft-2020-12"?"prefixItems":"items",a=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((y,w)=>Rt(y,e,{...o,path:[...o.path,s,w]})),u=i.rest?Rt(i.rest,e,{...o,path:[...o.path,a,...e.target==="openapi-3.0"?[i.items.length]:[]]}):null,l=i.items.length;for(;l>0;){let y=i.items[l-1];if(!(e.io==="input"?sy(y)!==void 0:y._zod.optout==="optional"))break;l--}let d=i.items.length,p=!i.rest;e.target==="draft-2020-12"?(n.prefixItems=c,p?n.items=!1:u&&(n.items=u),l>0&&(n.minItems=l),p&&(n.maxItems=d)):e.target==="openapi-3.0"?(n.items={anyOf:c},u&&n.items.anyOf.push(u),l>0&&(n.minItems=l),p&&(n.maxItems=d)):(n.items=c,p?n.additionalItems=!1:u&&(n.additionalItems=u),l>0&&(n.minItems=l),p&&(n.maxItems=d));let{minimum:f,maximum:h}=kr(t);typeof f=="number"&&(n.minItems=f),typeof h=="number"&&(n.maxItems=h)};function pM(t,e,r){if(e.$ref){if(r.has(e))return e;r.add(e);let h=t.get(e)?.def;if(!h)return e;let y=pM(t,h,r);return y===h?e:y}for(let h of["anyOf","oneOf"]){let y=e[h];if(!Array.isArray(y))continue;let w=y.map(b=>pM(t,b,r));w.some((b,S)=>b!==y[S])&&(e={...e,[h]:w})}let o=Array.isArray(e.type)?e.type:[e.type],n=!o.includes("string")&&o.some(h=>h==="number"||h==="integer"),i=e.enum??(e.const!==void 0?[e.const]:void 0);if(!n&&!i?.some(h=>typeof h=="number"))return e;let{minimum:s,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:l,format:d,id:p,...f}=e;return f.enum?f.enum=f.enum.map(h=>typeof h=="number"?String(h):h):typeof f.const=="number"&&(f.const=String(f.const)),n&&(f.type="string",i||(f.pattern=(o.includes("number")?Fa:yg).source)),f}var fM=new WeakMap;function VCe(t){let e=new Map;for(let o of t.seen.values())o.def&&!e.has(o.schema)&&e.set(o.schema,o);let r=new Map;for(let o of fM.get(t)??[]){let n=t.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let s=pM(e,i,new Set);s!==i&&r.set(i,s)}if(r.size)for(let o of t.seen.values())for(let n of[o.schema,o.def]){let i=n&&r.get(n.propertyNames);i&&(n.propertyNames=i)}}var FM=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="object";let s=i.keyType,a=kr(s).patterns;if(i.mode==="loose"&&a&&a.size>0){let l=Rt(i.valueType,e,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let d of a)Wr(n.patternProperties,EZ(d).source,l)}else{if(e.target==="draft-07"||e.target==="draft-2020-12"){n.propertyNames=Rt(i.keyType,e,{...o,path:[...o.path,"propertyNames"]});let l=fM.get(e);l||(l=[],fM.set(e,l),e.deferred.push(()=>VCe(e))),l.push(t)}n.additionalProperties=Rt(i.valueType,e,{...o,path:[...o.path,"additionalProperties"]})}let c=s._zod.values,u=e.io==="input"&&sy(i.valueType)!==void 0;if(c&&!i.partial&&!u){let l=[...c].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(n.required=l.map(String))}},qM=(t,e,r,o)=>{let n=t._zod.def,i=Rt(n.innerType,e,o),s=e.seen.get(t);e.target==="openapi-3.0"?(s.ref=n.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},VM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},GM=Symbol();function $Z(t,e,r,o,n){let i=!1,s=JSON.stringify(t,(a,c)=>typeof c!="bigint"?c:(i=!0,null));return i?(Pr(e,r,o,n,"BigInt defaults cannot be represented in JSON Schema"),GM):JSON.parse(s)}var HM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s=$Z(n.defaultValue,t,e,r,o);s!==GM&&(r.default=s)},KM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);if(i.ref=n.innerType,e.io!=="input")return;let s=$Z(n.defaultValue,t,e,r,o);s!==GM&&(r._prefault=s)},BM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{Pr(t,e,r,o,"Dynamic catch values are not supported in JSON Schema");return}r.default=s},ZM=(t,e,r,o)=>{let n=t._zod.def,i=n.in._zod.traits.has("$ZodTransform"),s=e.io==="input"?i?n.out:n.in:n.out;Rt(s,e,o);let a=e.seen.get(t);a.ref=s},WM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType,r.readOnly=!0},JM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},K0=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},XM=(t,e,r,o)=>{let n=t._zod.innerType;Rt(n,e,o);let i=e.seen.get(t);i.ref=n},G0={string:mM,number:hM,boolean:gM,bigint:yM,symbol:vM,null:wM,undefined:_M,void:bM,never:SM,any:xM,unknown:EM,date:$M,enum:RM,literal:IM,nan:AM,template_literal:PM,file:kM,success:TM,custom:CM,function:OM,transform:DM,map:NM,set:zM,array:MM,object:UM,union:H0,intersection:LM,tuple:jM,record:FM,nullable:qM,nonoptional:VM,default:HM,prefault:KM,catch:BM,pipe:ZM,readonly:WM,promise:JM,optional:K0,lazy:XM};function Zl(t,e){if("_idmap"in t){let o=t,n=Gc({...e,processors:G0}),i={};for(let c of o._idmap.entries()){let[u,l]=c;Rt(l,n)}let s={},a={registry:o,uri:e?.uri,defs:i};n.external=a;for(let c of o._idmap.entries()){let[u,l]=c;Hc(n,l),Wr(s,u,Kc(n,l))}if(Object.keys(i).length>0){let c=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[c]:i}}return{schemas:s}}let r=Gc({...e,processors:G0});return Rt(t,r),Hc(r,t),Kc(r,t)}var B0=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(e){this.ctx.counter=e}get seen(){return this.ctx.seen}constructor(e){let r=e?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=Gc({processors:G0,target:r,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,r={path:[],schemaPath:[]}){return Rt(e,this.ctx,r)}emit(e,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,Hc(this.ctx,e);let o=Kc(this.ctx,e),{"~standard":n,...i}=o;return i}};var RZ={};var mf={};Ht(mf,{ZodAny:()=>gU,ZodArray:()=>_U,ZodBase64:()=>pE,ZodBase64URL:()=>fE,ZodBigInt:()=>pf,ZodBigIntFormat:()=>gE,ZodBoolean:()=>df,ZodCIDRv4:()=>lE,ZodCIDRv6:()=>dE,ZodCUID:()=>nE,ZodCUID2:()=>oE,ZodCatch:()=>LU,ZodCodec:()=>hy,ZodCreditCard:()=>dU,ZodCustom:()=>gy,ZodCustomStringFormat:()=>Jl,ZodDate:()=>ly,ZodDefault:()=>OU,ZodDiscriminatedUnion:()=>SU,ZodE164:()=>mE,ZodEmail:()=>Q0,ZodEmoji:()=>tE,ZodEnum:()=>cf,ZodExactOptional:()=>wE,ZodFile:()=>PU,ZodFunction:()=>WU,ZodGUID:()=>eE,ZodIBAN:()=>pU,ZodIPv4:()=>cE,ZodIPv6:()=>uE,ZodISODate:()=>Zc,ZodISODateTime:()=>Bc,ZodISODuration:()=>Jc,ZodISOTime:()=>Wc,ZodInstanceOf:()=>YU,ZodIntersection:()=>xU,ZodJWT:()=>hE,ZodKSUID:()=>aE,ZodLazy:()=>KU,ZodLiteral:()=>AU,ZodMAC:()=>lU,ZodMap:()=>RU,ZodNaN:()=>FU,ZodNanoID:()=>rE,ZodNever:()=>vU,ZodNonOptional:()=>_E,ZodNull:()=>hU,ZodNullable:()=>CU,ZodNumber:()=>lf,ZodNumberFormat:()=>Xl,ZodObject:()=>dy,ZodOptional:()=>Yl,ZodPipe:()=>my,ZodPrefault:()=>NU,ZodPreprocess:()=>qU,ZodPromise:()=>ZU,ZodReadonly:()=>VU,ZodRecord:()=>af,ZodSet:()=>IU,ZodString:()=>uf,ZodStringFormat:()=>Tt,ZodSuccess:()=>UU,ZodSymbol:()=>fU,ZodTemplateLiteral:()=>HU,ZodTransform:()=>kU,ZodTuple:()=>EU,ZodType:()=>Ce,ZodULID:()=>iE,ZodURL:()=>cy,ZodUUID:()=>Os,ZodUndefined:()=>mU,ZodUnion:()=>py,ZodUnknown:()=>yU,ZodVoid:()=>wU,ZodXID:()=>sE,ZodXor:()=>bU,_ZodString:()=>Y0,_default:()=>DU,_function:()=>DW,any:()=>hW,array:()=>qe,base64:()=>WZ,base64url:()=>JZ,bigint:()=>lW,boolean:()=>gr,catch:()=>jU,check:()=>NW,cidrv4:()=>BZ,cidrv6:()=>ZZ,codec:()=>kW,creditCard:()=>YZ,cuid:()=>LZ,cuid2:()=>jZ,currencyCode:()=>oW,custom:()=>bE,date:()=>yW,describe:()=>zW,discriminatedUnion:()=>fy,e164:()=>XZ,email:()=>PZ,emoji:()=>MZ,enum:()=>Yr,exactOptional:()=>TU,file:()=>RW,float32:()=>sW,float64:()=>aW,function:()=>DW,guid:()=>kZ,hash:()=>iW,hex:()=>nW,hostname:()=>rW,httpUrl:()=>zZ,iban:()=>QZ,instanceof:()=>UW,int:()=>J0,int32:()=>cW,int64:()=>dW,intersection:()=>ff,invertCodec:()=>TW,ipv4:()=>GZ,ipv6:()=>KZ,json:()=>jW,jwt:()=>eW,keyof:()=>vW,ksuid:()=>VZ,lazy:()=>BU,literal:()=>ae,looseObject:()=>Xr,looseRecord:()=>SW,mac:()=>HZ,map:()=>xW,meta:()=>MW,nan:()=>PW,nanoid:()=>UZ,nativeEnum:()=>$W,never:()=>yE,nonoptional:()=>MU,null:()=>uy,nullable:()=>ay,nullish:()=>IW,number:()=>yt,object:()=>X,optional:()=>kt,partialRecord:()=>bW,pipe:()=>X0,prefault:()=>zU,preprocess:()=>yy,promise:()=>OW,readonly:()=>GU,record:()=>Ct,refine:()=>JU,set:()=>EW,strictObject:()=>wW,string:()=>O,stringFormat:()=>tW,stringbool:()=>LW,success:()=>AW,superRefine:()=>XU,symbol:()=>fW,templateLiteral:()=>CW,transform:()=>vE,tuple:()=>$U,uint32:()=>uW,uint64:()=>pW,ulid:()=>FZ,undefined:()=>mW,union:()=>It,unknown:()=>Ut,url:()=>NZ,uuid:()=>TZ,uuidv4:()=>CZ,uuidv6:()=>OZ,uuidv7:()=>DZ,void:()=>gW,xid:()=>qZ,xor:()=>_W});var Z0={};Ht(Z0,{endsWith:()=>Wp,gt:()=>Ts,gte:()=>Ro,includes:()=>Bp,length:()=>Bl,lowercase:()=>Hp,lt:()=>ks,lte:()=>$o,maxLength:()=>Kl,maxSize:()=>qc,mime:()=>Xp,minLength:()=>qa,minSize:()=>Cs,multipleOf:()=>Fc,negative:()=>O0,nonnegative:()=>N0,nonpositive:()=>D0,normalize:()=>Yp,overwrite:()=>Ni,positive:()=>C0,properties:()=>Jp,property:()=>z0,regex:()=>Gp,size:()=>Hl,slugify:()=>rf,startsWith:()=>Zp,toLowerCase:()=>ef,toUpperCase:()=>tf,trim:()=>Qp,uppercase:()=>Kp});var IZ=new WeakSet([Object.prototype,Error.prototype]);function W0(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!1,get(){let o=r(this);return Object.defineProperty(this,e,{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,e,{value:o,configurable:!0,writable:!0})}})}var AZ=(t,e)=>{C1.init(t,e),t.name="ZodError";let r=Object.getPrototypeOf(t);IZ.has(r)||(IZ.add(r),W0(r,"format",o=>n=>hg(o,n)),W0(r,"flatten",o=>n=>mg(o,n)),W0(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,_p,2)}),W0(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,_p,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},HCe=$("ZodError",AZ),lo=$("ZodError",AZ,void 0,{Parent:Error});var YM=$p(lo),QM=Rp(lo),eU=Ip(lo),tU=Pp(lo),rU=yS(lo),nU=vS(lo),oU=wS(lo),iU=_S(lo),sU=bS(lo),aU=SS(lo),cU=xS(lo),uU=ES(lo);function BCe(){zr.localeError||lr(t0())}function Wl(){zr.memoizer||lr({memoizer:Cg()})}var Ce=$("ZodType",(t,e)=>(BCe(),be.init(t,e),t.def=e,t.type=e.type,t),{check(...t){let e=this.def;return this.clone(D.mergeDefs(e,{checks:[...e.checks??[],...t.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...t){return this.check(...t)},clone(t,e){return gt(this,t,e)},brand(){return this},register(t,e){return t.add(this,e),this},refine(t,e){return this.check(JU(t,e))},superRefine(t,e){return this.check(XU(t,e))},overwrite(t){return this.check(Ni(t))},optional(){return kt(this)},exactOptional(){return TU(this)},nullable(){return ay(this)},nullish(){return kt(ay(this))},nonoptional(t){return MU(this,t)},array(){return qe(this)},or(t){return It([this,t])},and(t){return ff(this,t)},transform(t){return X0(this,vE(t))},default(t){return DU(this,t)},prefault(t){return zU(this,t)},catch(t){return jU(this,t)},pipe(t){return X0(this,t)},readonly(){return GU(this)},describe(t){let e=this.clone();return Jr.add(e,{description:t}),e},meta(...t){if(t.length===0)return Jr.get(this);let e=this.clone();return Jr.add(e,t[0]),e},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(t,...e){return e.length===0?t(this):t(this,...e)},get"~standard"(){return D.hide(this,"~standard",{...NS(this),jsonSchema:{input:nf(this,"input"),output:nf(this,"output")}})},set"~standard"(t){D.own(this,"~standard",t)},parse:function t(e,r){return YM(this,e,r,{callee:t})},parseAsync:async function t(e,r){return await QM(this,e,r,{callee:t})},safeParse(t,e){return eU(this,t,e)},async safeParseAsync(t,e){return tU(this,t,e)},get spa(){return this?.safeParseAsync},set spa(t){D.own(this,"spa",t)},validate(t,e){return Tp(this,t,e)},validateAsync(t,e){return Cp(this,t,e)},encode:function t(e,r){return rU(this,e,r,{callee:t})},decode:function t(e,r){return nU(this,e,r,{callee:t})},encodeAsync:async function t(e,r){return await oU(this,e,r,{callee:t})},decodeAsync:async function t(e,r){return await iU(this,e,r,{callee:t})},safeEncode(t,e){return sU(this,t,e)},safeDecode(t,e){return aU(this,t,e)},async safeEncodeAsync(t,e){return cU(this,t,e)},async safeDecodeAsync(t,e){return uU(this,t,e)},toJSONSchema(t){return dM(this,{})(t)},get description(){return Jr.get(this)?.description},get _def(){return this._zod.def}}),Y0=$("_ZodString",(t,e)=>{jc.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>mM(t,r,o,n)},D.derived({format:t=>kr(t).format??null,minLength:t=>kr(t).minimum??null,maxLength:t=>kr(t).maximum??null},{regex(...t){return this.check(Gp(...t))},includes(...t){return this.check(Bp(...t))},startsWith(...t){return this.check(Zp(...t))},endsWith(...t){return this.check(Wp(...t))},min(...t){return this.check(qa(...t))},max(...t){return this.check(Kl(...t))},length(...t){return this.check(Bl(...t))},nonempty(...t){return this.check(qa(1,...t))},lowercase(t){return this.check(Hp(t))},uppercase(t){return this.check(Kp(t))},trim(){return this.check(Qp())},normalize(...t){return this.check(Yp(...t))},toLowerCase(){return this.check(ef())},toUpperCase(){return this.check(tf())},slugify(){return this.check(rf())}})),uf=$("ZodString",(t,e)=>{jc.init(t,e),Y0.init(t,e)},{email(t){return this.check(Dg(Q0,t))},url(t){return this.check(Vp(cy,t))},jwt(t){return this.check(ey(hE,t))},emoji(t){return this.check(jg(tE,t))},guid(t){return this.check(Ng(eE,t))},uuid(t){return this.check(zg(Os,t))},uuidv4(t){return this.check(Mg(Os,t))},uuidv6(t){return this.check(Ug(Os,t))},uuidv7(t){return this.check(Lg(Os,t))},nanoid(t){return this.check(Fg(rE,t))},cuid(t){return this.check(qg(nE,t))},cuid2(t){return this.check(Vg(oE,t))},ulid(t){return this.check(Gg(iE,t))},base64(t){return this.check(Xg(pE,t))},base64url(t){return this.check(Yg(fE,t))},xid(t){return this.check(Hg(sE,t))},ksuid(t){return this.check(Kg(aE,t))},ipv4(t){return this.check(Bg(cE,t))},ipv6(t){return this.check(Zg(uE,t))},cidrv4(t){return this.check(Wg(lE,t))},cidrv6(t){return this.check(Jg(dE,t))},e164(t){return this.check(Qg(mE,t))},datetime(t){return this.check(ty(Bc,t))},date(t){return this.check(ry(Zc,t))},time(t){return this.check(ny(Wc,t))},duration(t){return this.check(oy(Jc,t))}});function O(t){return u0(uf,t)}var Tt=$("ZodStringFormat",(t,e)=>{St.init(t,e),Y0.init(t,e)}),Bc=$("ZodISODateTime",(t,e)=>{Fz.init(t,e),Tt.init(t,e)}),Zc=$("ZodISODate",(t,e)=>{qz.init(t,e),Tt.init(t,e)}),Wc=$("ZodISOTime",(t,e)=>{Vz.init(t,e),Tt.init(t,e)}),Jc=$("ZodISODuration",(t,e)=>{Gz.init(t,e),Tt.init(t,e)}),Q0=$("ZodEmail",(t,e)=>{US.init(t,e),Tt.init(t,e)});function PZ(t){return Dg(Q0,t)}var eE=$("ZodGUID",(t,e)=>{zS.init(t,e),Tt.init(t,e)});function kZ(t){return Ng(eE,t)}var Os=$("ZodUUID",(t,e)=>{MS.init(t,e),Tt.init(t,e)});function TZ(t){return zg(Os,t)}function CZ(t){return Mg(Os,t)}function OZ(t){return Ug(Os,t)}function DZ(t){return Lg(Os,t)}var cy=$("ZodURL",(t,e)=>{qS.init(t,e),Tt.init(t,e)});function NZ(t){return Vp(cy,t)}function zZ(t){return Vp(cy,{protocol:gg,hostname:tz,...D.normalizeParams(t)})}var tE=$("ZodEmoji",(t,e)=>{VS.init(t,e),Tt.init(t,e)});function MZ(t){return jg(tE,t)}var rE=$("ZodNanoID",(t,e)=>{GS.init(t,e),Tt.init(t,e)});function UZ(t){return Fg(rE,t)}var nE=$("ZodCUID",(t,e)=>{HS.init(t,e),Tt.init(t,e)});function LZ(t){return qg(nE,t)}var oE=$("ZodCUID2",(t,e)=>{KS.init(t,e),Tt.init(t,e)});function jZ(t){return Vg(oE,t)}var iE=$("ZodULID",(t,e)=>{BS.init(t,e),Tt.init(t,e)});function FZ(t){return Gg(iE,t)}var sE=$("ZodXID",(t,e)=>{ZS.init(t,e),Tt.init(t,e)});function qZ(t){return Hg(sE,t)}var aE=$("ZodKSUID",(t,e)=>{WS.init(t,e),Tt.init(t,e)});function VZ(t){return Kg(aE,t)}var cE=$("ZodIPv4",(t,e)=>{JS.init(t,e),Tt.init(t,e)});function GZ(t){return Bg(cE,t)}var lU=$("ZodMAC",(t,e)=>{YS.init(t,e),Tt.init(t,e)});function HZ(t){return l0(lU,t)}var uE=$("ZodIPv6",(t,e)=>{XS.init(t,e),Tt.init(t,e)});function KZ(t){return Zg(uE,t)}var lE=$("ZodCIDRv4",(t,e)=>{QS.init(t,e),Tt.init(t,e)});function BZ(t){return Wg(lE,t)}var dE=$("ZodCIDRv6",(t,e)=>{tx.init(t,e),Tt.init(t,e)});function ZZ(t){return Jg(dE,t)}var pE=$("ZodBase64",(t,e)=>{nx.init(t,e),Tt.init(t,e)});function WZ(t){return Xg(pE,t)}var fE=$("ZodBase64URL",(t,e)=>{ix.init(t,e),Tt.init(t,e)});function JZ(t){return Yg(fE,t)}var mE=$("ZodE164",(t,e)=>{sx.init(t,e),Tt.init(t,e)});function XZ(t){return Qg(mE,t)}var dU=$("ZodCreditCard",(t,e)=>{cx.init(t,e),Tt.init(t,e)});function YZ(t){return d0(dU,t)}var pU=$("ZodIBAN",(t,e)=>{lx.init(t,e),Tt.init(t,e)});function QZ(t){return p0(pU,t)}var hE=$("ZodJWT",(t,e)=>{px.init(t,e),Tt.init(t,e)});function eW(t){return ey(hE,t)}var Jl=$("ZodCustomStringFormat",(t,e)=>{fx.init(t,e),Tt.init(t,e)});function tW(t,e,r={}){return Vc(Jl,t,e,r)}function rW(t){return Vc(Jl,"hostname",ez,t)}function nW(t){return Vc(Jl,"hex",hz,t)}function oW(t){return Vc(Jl,"currency_code",nz,t)}function iW(t,e){let r=e?.enc??"hex",o=`${t}_${r}`,n=Eo[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return Vc(Jl,o,n,e)}var lf=$("ZodNumber",(t,e)=>{$g.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>hM(t,r,o,n),t.isFinite=!0},D.derived({minValue:t=>{let{minimum:e,exclusiveMinimum:r}=kr(t);return Math.max(e??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:t=>{let{maximum:e,exclusiveMaximum:r}=kr(t);return Math.min(e??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:t=>{let{isInt:e,multipleOf:r}=kr(t);return!!e||!!r?.some(Number.isSafeInteger)},format:t=>kr(t).format??null},{gt(t,e){return this.check(Ts(t,e))},gte(t,e){return this.check(Ro(t,e))},min(t,e){return this.check(Ro(t,e))},lt(t,e){return this.check(ks(t,e))},lte(t,e){return this.check($o(t,e))},max(t,e){return this.check($o(t,e))},int(t){return this.check(J0(t))},safe(t){return this.check(J0(t))},positive(t){return this.check(Ts(0,t))},nonnegative(t){return this.check(Ro(0,t))},negative(t){return this.check(ks(0,t))},nonpositive(t){return this.check($o(0,t))},multipleOf(t,e){return this.check(Fc(t,e))},step(t,e){return this.check(Fc(t,e))},finite(){return this}}));function yt(t){return f0(lf,t)}var Xl=$("ZodNumberFormat",(t,e)=>{mx.init(t,e),lf.init(t,e)});function J0(t){return m0(Xl,t)}function sW(t){return h0(Xl,t)}function aW(t){return g0(Xl,t)}function cW(t){return y0(Xl,t)}function uW(t){return v0(Xl,t)}var df=$("ZodBoolean",(t,e)=>{Np.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>gM(t,r,o,n)});function gr(t){return w0(df,t)}var pf=$("ZodBigInt",(t,e)=>{Rg.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>yM(t,r,o,n)},D.derived({minValue:t=>kr(t).minimum??null,maxValue:t=>kr(t).maximum??null,format:t=>kr(t).format??null},{gte(t,e){return this.check(Ro(t,e))},min(t,e){return this.check(Ro(t,e))},gt(t,e){return this.check(Ts(t,e))},lt(t,e){return this.check(ks(t,e))},lte(t,e){return this.check($o(t,e))},max(t,e){return this.check($o(t,e))},positive(t){return this.check(Ts(BigInt(0),t))},negative(t){return this.check(ks(BigInt(0),t))},nonpositive(t){return this.check($o(BigInt(0),t))},nonnegative(t){return this.check(Ro(BigInt(0),t))},multipleOf(t,e){return this.check(Fc(t,e))}}));function lW(t){return _0(pf,t)}var gE=$("ZodBigIntFormat",(t,e)=>{hx.init(t,e),pf.init(t,e)});function dW(t){return b0(gE,t)}function pW(t){return S0(gE,t)}var fU=$("ZodSymbol",(t,e)=>{gx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>vM(t,r,o,n)});function fW(t){return x0(fU,t)}var mU=$("ZodUndefined",(t,e)=>{yx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>_M(t,r,o,n)});function mW(t){return E0(mU,t)}var hU=$("ZodNull",(t,e)=>{vx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>wM(t,r,o,n)});function uy(t){return $0(hU,t)}var gU=$("ZodAny",(t,e)=>{wx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>xM(t,r,o,n)});function hW(){return R0(gU)}var yU=$("ZodUnknown",(t,e)=>{_x.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>EM(t,r,o,n)});function Ut(){return I0(yU)}var vU=$("ZodNever",(t,e)=>{bx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>SM(t,r,o,n)});function yE(t){return A0(vU,t)}var wU=$("ZodVoid",(t,e)=>{Sx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>bM(t,r,o,n)});function gW(t){return P0(wU,t)}var ly=$("ZodDate",(t,e)=>{xx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>$M(t,r,o,n),t.min=(r,o)=>t.check(Ro(r,o)),t.max=(r,o)=>t.check($o(r,o))},D.derived({minDate:t=>{let{minimum:e}=kr(t);return e?new Date(e):null},maxDate:t=>{let{maximum:e}=kr(t);return e?new Date(e):null}},{}));function yW(t){return k0(ly,t)}var _U=$("ZodArray",(t,e)=>{Wl(),Ex.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>MM(t,r,o,n),t.element=e.element},{min(t,e){return this.check(qa(t,e))},nonempty(t){return this.check(qa(1,t))},max(t,e){return this.check(Kl(t,e))},length(t,e){return this.check(Bl(t,e))},unwrap(){return this.element}});function qe(t,e){return uM(_U,t,e)}function vW(t){let e=t._zod.def.shape;return Yr(Object.keys(e))}var dy=$("ZodObject",(t,e)=>{Wl(),Hz.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>UM(t,r,o,n),D.installLazyProp(t,"shape",r=>r._zod.def.shape,!1)},{keyof(){return Yr(Object.keys(this._zod.def.shape))},catchall(t){return this.clone(D.mergeDefs(this._zod.def,{catchall:t}))},passthrough(){return this.clone(D.mergeDefs(this._zod.def,{catchall:Ut()}))},loose(){return this.clone(D.mergeDefs(this._zod.def,{catchall:Ut()}))},strict(){return this.clone(D.mergeDefs(this._zod.def,{catchall:yE()}))},strip(){return this.clone(D.mergeDefs(this._zod.def,{catchall:void 0}))},extend(t){return D.extend(this,t)},safeExtend(t){return D.safeExtend(this,t)},merge(t){return D.merge(this,t)},pick(t){return D.pick(this,t)},omit(t){return D.omit(this,t)},partial(...t){return D.partial(Yl,this,t[0])},exactPartial(...t){return D.partial(wE,this,t[0],"exactPartial")},required(...t){return D.required(_E,this,t[0])}});function X(t,e){let r={type:"object",shape:t??{},...D.normalizeParams(e)};return new dy(r)}function wW(t,e){return new dy({type:"object",shape:t,catchall:yE(),...D.normalizeParams(e)})}function Xr(t,e){return new dy({type:"object",shape:t,catchall:Ut(),...D.normalizeParams(e)})}var py=$("ZodUnion",(t,e)=>{zp.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>H0(t,r,o,n),t.options=e.options});function It(t,e){return new py({type:"union",options:t,...D.normalizeParams(e)})}var bU=$("ZodXor",(t,e)=>{py.init(t,e),Rx.init(t,e),t._zod.processJSONSchema=(r,o,n)=>H0(t,r,o,n),t.options=e.options});function _W(t,e){return new bU({type:"union",options:t,inclusive:!1,...D.normalizeParams(e)})}var SU=$("ZodDiscriminatedUnion",(t,e)=>{py.init(t,e),Ix.init(t,e)});function fy(t,e,r){return new SU({type:"union",options:e,discriminator:t,...D.normalizeParams(r)})}var xU=$("ZodIntersection",(t,e)=>{Ax.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>LM(t,r,o,n)});function ff(t,e){return new xU({type:"intersection",left:t,right:e})}var EU=$("ZodTuple",(t,e)=>{Wl(),Ig.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>jM(t,r,o,n)},{rest(t){return this.clone({...this._zod.def,rest:t})},partial(){let t=this._zod.def;if(t.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...t,items:t.items.map(e=>new Yl({type:"optional",innerType:e}))})}});function $U(t,e,r){let o=e instanceof be,n=o?r:e,i=o?e:null;return new EU({type:"tuple",items:t,rest:i,...D.normalizeParams(n)})}var af=$("ZodRecord",(t,e)=>{Wl(),Px.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>FM(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType});function Ct(t,e,r){return!e||!e._zod?new af({type:"record",keyType:O(),valueType:t,...D.normalizeParams(e)}):new af({type:"record",keyType:t,valueType:e,...D.normalizeParams(r)})}function bW(t,e,r){return new af({type:"record",keyType:t,valueType:e,...D.normalizeParams(r),partial:!0})}function SW(t,e,r){return new af({type:"record",keyType:t,valueType:e,mode:"loose",...D.normalizeParams(r)})}var RU=$("ZodMap",(t,e)=>{Wl(),kx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>NM(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(Cs(...r)),t.nonempty=r=>t.check(Cs(1,r)),t.max=(...r)=>t.check(qc(...r)),t.size=(...r)=>t.check(Hl(...r))});function xW(t,e,r){return new RU({type:"map",keyType:t,valueType:e,...D.normalizeParams(r)})}var IU=$("ZodSet",(t,e)=>{Wl(),Tx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>zM(t,r,o,n),t.min=(...r)=>t.check(Cs(...r)),t.nonempty=r=>t.check(Cs(1,r)),t.max=(...r)=>t.check(qc(...r)),t.size=(...r)=>t.check(Hl(...r))});function EW(t,e){return new IU({type:"set",valueType:t,...D.normalizeParams(e)})}var cf=$("ZodEnum",(t,e)=>{Cx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(o,n,i)=>RM(t,o,n,i),t.enum=e.entries,t.options=[...t._zod.values];let r=new Set(Object.keys(e.entries));t.extract=(o,n)=>{let i={};for(let s of o)if(r.has(s))i[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new cf({...e,checks:[],...D.normalizeParams(n),entries:i})},t.exclude=(o,n)=>{let i={...e.entries};for(let s of o)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new cf({...e,checks:[],...D.normalizeParams(n),entries:i})}});function Yr(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new cf({type:"enum",entries:r,...D.normalizeParams(e)})}function $W(t,e){return new cf({type:"enum",entries:t,...D.normalizeParams(e)})}var AU=$("ZodLiteral",(t,e)=>{Ox.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>IM(t,r,o,n),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function ae(t,e){return new AU({type:"literal",values:Array.isArray(t)?t:[t],...D.normalizeParams(e)})}var PU=$("ZodFile",(t,e)=>{Dx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>kM(t,r,o,n),t.min=(r,o)=>t.check(Cs(r,o)),t.max=(r,o)=>t.check(qc(r,o)),t.mime=(r,o)=>t.check(Xp(Array.isArray(r)?r:[r],o))});function RW(t){return M0(PU,t)}var kU=$("ZodTransform",(t,e)=>{Wl(),Nx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>DM(t,r,o,n),t._zod.parse=(r,o)=>{if(o.direction==="backward")throw new Lc(t.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(D.issue(i,r.value,e));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),"input"in s||(s.input=r.value),s.inst??(s.inst=t),r.issues.push(D.issue(s))}};let n=e.transform(r.value,r);return n instanceof Promise?n.then(i=>(r.value=i,r)):(r.value=n,r)}});function vE(t){return new kU({type:"transform",transform:t})}var Yl=$("ZodOptional",(t,e)=>{Ag.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>K0(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function kt(t){return new Yl({type:"optional",innerType:t})}var wE=$("ZodExactOptional",(t,e)=>{zx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>K0(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function TU(t){return new wE({type:"optional",innerType:t})}var CU=$("ZodNullable",(t,e)=>{Mx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>qM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function ay(t){return new CU({type:"nullable",innerType:t})}function IW(t){return kt(ay(t))}var OU=$("ZodDefault",(t,e)=>{Ux.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>HM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function DU(t,e){return new OU({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():D.shallowClone(e)}})}var NU=$("ZodPrefault",(t,e)=>{Lx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>KM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function zU(t,e){return new NU({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():D.shallowClone(e)}})}var _E=$("ZodNonOptional",(t,e)=>{jx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>VM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function MU(t,e){return new _E({type:"nonoptional",innerType:t,...D.normalizeParams(e)})}var UU=$("ZodSuccess",(t,e)=>{Fx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>TM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function AW(t){return new UU({type:"success",innerType:t})}var LU=$("ZodCatch",(t,e)=>{qx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>BM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function jU(t,e){return new LU({type:"catch",innerType:t,catchValue:typeof e=="function"?e:D.constantCatch(e)})}var FU=$("ZodNaN",(t,e)=>{Vx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>AM(t,r,o,n)});function PW(t){return T0(FU,t)}var my=$("ZodPipe",(t,e)=>{Pg.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>ZM(t,r,o,n),t.in=e.in,t.out=e.out});function X0(t,e){return new my({type:"pipe",in:t,out:e})}var hy=$("ZodCodec",(t,e)=>{my.init(t,e),Mp.init(t,e)});function kW(t,e,r){return new hy({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}function TW(t){let e=t._zod.def;return new hy({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}var qU=$("ZodPreprocess",(t,e)=>{my.init(t,e),Bz.init(t,e)}),VU=$("ZodReadonly",(t,e)=>{Gx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>WM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function GU(t){return new VU({type:"readonly",innerType:t})}var HU=$("ZodTemplateLiteral",(t,e)=>{Hx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>PM(t,r,o,n)});function CW(t,e){return new HU({type:"template_literal",parts:t,...D.normalizeParams(e)})}var KU=$("ZodLazy",(t,e)=>{Up.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>XM(t,r,o,n),t.unwrap=()=>t._zod.def.getter()});function BU(t){return new KU({type:"lazy",getter:t})}var ZU=$("ZodPromise",(t,e)=>{Bx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>JM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function OW(t){return new ZU({type:"promise",innerType:t})}var WU=$("ZodFunction",(t,e)=>{Kx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>OM(t,r,o,n)});function DW(t){return new WU({type:"function",input:Array.isArray(t?.input)?$U(t?.input):t?.input??qe(Ut()),output:t?.output??Ut()})}var gy=$("ZodCustom",(t,e)=>{Zx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>CM(t,r,o,n)});function NW(t){let e=new Pt({check:"custom"});return e._zod.check=t,e}function bE(t,e){return U0(gy,t??(()=>!0),e)}function JU(t,e={}){return L0(gy,t,e)}function XU(t,e){return j0(t,e)}var zW=F0,MW=q0,YU=$("ZodInstanceOf",(t,e)=>{gy.init(t,e)},{properties(t,e){return this.check(Jp(t,e))}});function UW(t,e={}){let r=new YU({type:"custom",check:"custom",fn:o=>o instanceof t,abort:!0,...D.normalizeParams(e)});return r._zod.bag.Class=t,r._zod.check=o=>{o.value instanceof t||o.issues.push({code:"invalid_type",expected:t.name,input:o.value,inst:r,path:[...r._zod.def.path??[]]})},r}var LW=(...t)=>V0({Codec:hy,Boolean:df,String:uf},...t);function jW(t){let e=BU(()=>It([O(t),yt(),gr(),uy(),qe(e),Ct(O(),e)]));return e}function yy(t,e){return new qU({type:"pipe",in:vE(t),out:e})}var ZCe={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"};function WCe(t){lr({customError:t})}function JCe(){return lr().customError}var QU;QU||(QU={});var Ql={};Ht(Ql,{ZodISODate:()=>Zc,ZodISODateTime:()=>Bc,ZodISODuration:()=>Jc,ZodISOTime:()=>Wc,date:()=>YCe,datetime:()=>XCe,duration:()=>eOe,time:()=>QCe});function XCe(t){return ty(Bc,t)}function YCe(t){return ry(Zc,t)}function QCe(t){return ny(Wc,t)}function eOe(t){return oy(Jc,t)}var J={...mf,...Z0,iso:Ql},tOe=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function rOe(t,e){let r=t.$schema;return r==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":r==="http://json-schema.org/draft-07/schema#"?"draft-7":r==="http://json-schema.org/draft-04/schema#"?"draft-4":e??"draft-2020-12"}function FW(t,e){return t.map((r,o)=>o<e?r:r.optional())}function nOe(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function oOe(t,e){if(!t.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let r=t.slice(1).split("/").filter(Boolean);if(r.length===0)return e.rootSchema;let o=e.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===o){let n=r[1]===void 0?void 0:nOe(r[1]);if(!n||!e.defs[n])throw new Error(`Reference not found: ${t}`);return e.defs[n]}throw new Error(`Reference not found: ${t}`)}function iOe(t,e){return J.transform(o=>o).check(o=>{let n=o.value;if(typeof n!="object"||n===null||Array.isArray(n))return;let i=Object.getOwnPropertyNames(n);if(e.minProperties!==void 0&&i.length<e.minProperties&&o.issues.push({origin:"object",code:"too_small",minimum:e.minProperties,inclusive:!0,message:`Too small: expected object to have >=${e.minProperties} properties`,input:n,inst:t,continue:!0}),e.maxProperties!==void 0&&i.length>e.maxProperties&&o.issues.push({origin:"object",code:"too_big",maximum:e.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${e.maxProperties} properties`,input:n,inst:t,continue:!0}),e.keySchema)for(let s of i){let a=e.keySchema.safeParse(s);a.success||o.issues.push({code:"invalid_key",origin:"record",issues:a.error.issues,input:s,path:[s],continue:!0})}}).pipe(t)}function eL(t,e){if(t===null)return"z";let r=typeof t;if(r!=="object"){if(r==="number"&&Number.isNaN(t))return null;let o=String(t);return`${r[0]}${o.length}:${o}`}if(e.has(t))return null;e.add(t);try{if(Array.isArray(t)){let i=[];for(let s of t){let a=eL(s,e);if(a===null)return null;i.push(a)}return`a${i.length}:[${i.join(",")}]`}let o=Object.keys(t).sort(),n=[];for(let i of o){let s=eL(t[i],e);if(s===null)return null;n.push(`${i.length}:${i}=${s}`)}return`o${n.length}:{${n.join(",")}}`}finally{e.delete(t)}}var sOe=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),aOe=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function vy(t){return typeof t!="object"||t===null?!1:Array.isArray(t)?t.some(vy):typeof t.$ref=="string"?!0:Object.entries(t).some(([e,r])=>sOe.has(e)?vy(r):!aOe.has(e)||typeof r!="object"||r===null?!1:Object.values(r).some(vy))}function qW(t){return t===1?"element":"elements"}function cOe(t,e){return J.transform(o=>o).check(o=>{let n=o.value;if(Array.isArray(n)){if(e.uniqueItems===!0){let i=new Map;for(let s=0;s<n.length;s++){let a=eL(n[s],new Set);if(a===null)continue;let c=i.get(a);if(c===void 0){i.set(a,s);continue}o.issues.push({code:"custom",message:`Array items must be unique: element at index ${s} duplicates the one at index ${c}`,input:n,path:[s],continue:!0})}}if(e.containsSchema){let i=e.minContains??1,s=e.maxContains!==void 0?e.maxContains+1:Number.POSITIVE_INFINITY,a=0;for(let c of n)if(e.containsSchema.safeParse(c).success&&++a>=s)break;a<i&&o.issues.push({code:"custom",message:`Array must contain at least ${i} matching ${qW(i)}; found ${a}`,input:n,continue:!0}),e.maxContains!==void 0&&a>e.maxContains&&o.issues.push({code:"custom",message:`Array must contain at most ${e.maxContains} matching ${qW(e.maxContains)}`,input:n,continue:!0})}}}).pipe(t)}function VW(t,e){if(t!==!1)return t===void 0||t===!0?J.any():Gn(t,e)}var uOe=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function GW(t,e){if(t.not!==void 0){if(typeof t.not=="object"&&Object.keys(t.not).length===0)return J.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(t.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(t.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(t.if!==void 0||t.then!==void 0||t.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(t.dependentSchemas!==void 0||t.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(t.$ref){let n=t.$ref;if(e.refs.has(n))return e.refs.get(n);if(e.processing.has(n))return J.lazy(()=>{if(!e.refs.has(n))throw new Error(`Circular reference not resolved: ${n}`);return e.refs.get(n)});e.processing.add(n);let i=oOe(n,e),s=Gn(i,e);return e.refs.set(n,s),e.processing.delete(n),s}if(t.enum!==void 0){let n=t.enum;if(e.version==="openapi-3.0"&&t.nullable===!0&&n.length===1&&n[0]===null)return J.null();if(n.length===0)return J.never();if(n.length===1)return J.literal(n[0]);if(n.every(s=>typeof s=="string"))return J.enum(n);let i=n.map(s=>J.literal(s));return i.length<2?i[0]:J.union([i[0],i[1],...i.slice(2)])}if(t.const!==void 0)return J.literal(t.const);let r=t.type;if(Array.isArray(r)){let n=r.map(i=>{let s={...t,type:i};return GW(s,e)});return n.length===0?J.never():n.length===1?n[0]:J.union(n)}if(!r)return J.any();let o;switch(r){case"string":{let n=J.string();if(t.format){let i=t.format;i==="email"?n=n.check(J.email()):i==="uri"||i==="uri-reference"?n=n.check(J.url()):i==="uuid"||i==="guid"?n=n.check(J.uuid()):i==="date-time"?n=n.check(J.iso.datetime({offset:!0})):i==="date"?n=n.check(J.iso.date()):i==="time"?n=n.check(J.regex(uOe)):i==="duration"?n=n.check(J.iso.duration()):i==="hostname"?n=n.check(J.hostname()):i==="ipv4"?n=n.check(J.ipv4()):i==="ipv6"?n=n.check(J.ipv6()):i==="mac"?n=n.check(J.mac()):i==="cidr"?n=n.check(J.cidrv4()):i==="cidr-v6"?n=n.check(J.cidrv6()):i==="base64"?n=n.check(J.base64()):i==="base64url"?n=n.check(J.base64url()):i==="e164"?n=n.check(J.e164()):i==="credit_card"?n=n.check(J.creditCard()):i==="iban"?n=n.check(J.iban()):i==="jwt"?n=n.check(J.jwt()):i==="emoji"?n=n.check(J.emoji()):i==="nanoid"?n=n.check(J.nanoid()):i==="cuid"?n=n.check(J.cuid()):i==="cuid2"?n=n.check(J.cuid2()):i==="ulid"?n=n.check(J.ulid()):i==="xid"?n=n.check(J.xid()):i==="ksuid"&&(n=n.check(J.ksuid()))}typeof t.minLength=="number"&&(n=n.min(t.minLength)),typeof t.maxLength=="number"&&(n=n.max(t.maxLength)),t.pattern&&(n=n.regex(new RegExp(t.pattern))),o=n;break}case"number":case"integer":{let n=r==="integer"?J.number().int():J.number();typeof t.minimum=="number"&&t.exclusiveMinimum!==!0&&(n=n.min(t.minimum)),typeof t.maximum=="number"&&t.exclusiveMaximum!==!0&&(n=n.max(t.maximum)),typeof t.exclusiveMinimum=="number"?n=n.gt(t.exclusiveMinimum):t.exclusiveMinimum===!0&&typeof t.minimum=="number"&&(n=n.gt(t.minimum)),typeof t.exclusiveMaximum=="number"?n=n.lt(t.exclusiveMaximum):t.exclusiveMaximum===!0&&typeof t.maximum=="number"&&(n=n.lt(t.maximum)),typeof t.multipleOf=="number"&&(n=n.multipleOf(t.multipleOf)),o=n;break}case"boolean":{o=J.boolean();break}case"null":{o=J.null();break}case"object":{let n={},i=t.properties||{},s=new Set(t.required||[]),a=typeof t.additionalProperties=="object"?Gn(t.additionalProperties,e):void 0;for(let[d,p]of Object.entries(i)){let f=Gn(p,e);Wr(n,d,s.has(d)?f:f.optional())}if(t.patternProperties){let d=t.patternProperties,p=Object.keys(d),f=[];for(let y of p){let w=Gn(d[y],e),b=J.string().regex(new RegExp(y));f.push(J.looseRecord(b,w))}let h=[];if(Object.keys(n).length>0&&h.push(J.object(n).passthrough()),h.push(...f),h.length===0)o=J.object({}).passthrough();else if(h.length===1)o=h[0];else{let y=J.intersection(h[0],h[1]);for(let w=2;w<h.length;w++)y=J.intersection(y,h[w]);o=y}if(t.additionalProperties===!1){let y=Object.keys(n),w=p.map(S=>new RegExp(S)),b=o;o=o.check(S=>{if(!Jo(S.value))return;let x=[];for(let R of Object.keys(S.value))y.includes(R)||w.some(T=>T.test(R))||x.push(R);x.length&&S.issues.push({code:"unrecognized_keys",keys:x,input:S.value,inst:b})})}}else{let d=J.object(n);t.additionalProperties===!1?o=d.strict():a?o=d.catchall(a):o=d.passthrough()}let c=t.propertyNames!==void 0&&t.propertyNames!==!0,u=typeof t.minProperties=="number"?t.minProperties:void 0,l=typeof t.maxProperties=="number"?t.maxProperties:void 0;if(c||u!==void 0||l!==void 0){let d;if(c){let p=typeof t.propertyNames=="object"&&t.propertyNames.type===void 0?{type:"string",...t.propertyNames}:t.propertyNames;d=Gn(p,e)}o=iOe(o,{keySchema:d,minProperties:u,maxProperties:l})}break}case"array":{let n=t.prefixItems,i=t.items;if(n&&Array.isArray(n)){let s=typeof t.minItems=="number"?t.minItems:0,a=n.map(d=>Gn(d,e)),c=FW(a,s),u=Array.isArray(i)?void 0:VW(i,e),l=J.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(J.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(J.maxLength(t.maxItems)))}else if(Array.isArray(i)){let s=typeof t.minItems=="number"?t.minItems:0,a=i.map(d=>Gn(d,e)),c=FW(a,s),u=VW(t.additionalItems,e),l=J.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(J.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(J.maxLength(t.maxItems)))}else if(i!==void 0){let s=Gn(i,e),a=J.array(s);typeof t.minItems=="number"&&(a=a.min(t.minItems)),typeof t.maxItems=="number"&&(a=a.max(t.maxItems)),o=a}else o=J.array(J.any());(t.uniqueItems===!0||t.contains!==void 0)&&(o=cOe(o,{uniqueItems:t.uniqueItems===!0,containsSchema:t.contains!==void 0?Gn(t.contains,e):void 0,minContains:typeof t.minContains=="number"?t.minContains:void 0,maxContains:typeof t.maxContains=="number"?t.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${r}`)}return o}function Gn(t,e){if(typeof t=="boolean")return t?J.any():J.never();let r=GW(t,e),o=t.type||t.enum!==void 0||t.const!==void 0;if(t.anyOf&&Array.isArray(t.anyOf)){let a=t.anyOf.map(u=>Gn(u,e)),c=J.union(a);r=o?J.intersection(r,c):c}if(t.oneOf&&Array.isArray(t.oneOf)){let a=t.oneOf.map(u=>Gn(u,e)),c=J.xor(a);r=o?J.intersection(r,c):c}if(t.allOf&&Array.isArray(t.allOf))if(t.allOf.length===0)r=o?r:J.any();else{let a=o?r:Gn(t.allOf[0],e),c=o?0:1;for(let u=c;u<t.allOf.length;u++)a=J.intersection(a,Gn(t.allOf[u],e));r=a}t.nullable===!0&&e.version==="openapi-3.0"&&(r=J.nullable(r)),t.readOnly===!0&&(r=J.readonly(r)),t.default!==void 0&&(r=r.default(t.default));let n={},i=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of i)a in t&&(n[a]=t[a]);let s=["contentEncoding","contentMediaType","contentSchema"];for(let a of s)a in t&&(n[a]=t[a]);if(t.type==="object"&&t.$ref===void 0){t.propertyNames!==void 0&&!vy(t.propertyNames)&&(n.propertyNames=t.propertyNames);for(let a of["minProperties","maxProperties"])t[a]!==void 0&&(n[a]=t[a])}if(t.type==="array"&&t.$ref===void 0){t.contains!==void 0&&!vy(t.contains)&&(n.contains=t.contains);for(let a of["uniqueItems","minContains","maxContains"])t[a]!==void 0&&(n[a]=t[a])}for(let a of Object.keys(t))tOe.has(a)||Wr(n,a,t[a]);return Object.keys(n).length>0&&e.registry.add(r,n),t.description&&(r=r.describe(t.description)),r}function HW(t,e){if(typeof t=="boolean")return t?J.any():J.never();let r;try{r=JSON.parse(JSON.stringify(t))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let o=rOe(r,e?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:e?.registry??Jr};return Gn(r,i)}var KW=Symbol("z.visit/resolving");function wy(t,e){let r=typeof e=="function"?e:(s,a)=>{let c=e[s._zod.def.type];return c?c(s,a):s},o=new Map;function n(s){let a=o.get(s);if(a===KW)return new Up({type:"lazy",getter:()=>o.get(s)});if(a!==void 0)return a;o.set(s,KW);let c=i(s),u=r(c,c!==s);return o.set(s,u),u}function i(s){let a=s._zod.def,c=a.type;switch(c){case"object":{let u=a.shape,l=Object.keys(u),d=!1,p={};for(let h of l){let y=n(u[h]);y!==u[h]&&(d=!0),p[h]=y}let f=a.catchall;return a.catchall&&(f=n(a.catchall),f!==a.catchall&&(d=!0)),d?gt(s,{...a,shape:p,catchall:f}):s}case"array":{let u=n(a.element);return u===a.element?s:gt(s,{...a,element:u})}case"tuple":{let u=a.items,l=!1,d=[];for(let f of u){let h=n(f);h!==f&&(l=!0),d.push(h)}let p=a.rest;return a.rest&&(p=n(a.rest),p!==a.rest&&(l=!0)),l?gt(s,{...a,items:d,rest:p}):s}case"record":case"map":{let u=n(a.keyType),l=n(a.valueType);return u===a.keyType&&l===a.valueType?s:gt(s,{...a,keyType:u,valueType:l})}case"set":{let u=n(a.valueType);return u===a.valueType?s:gt(s,{...a,valueType:u})}case"union":{let u=a.options,l=!1,d=[];for(let p of u){let f=n(p);f!==p&&(l=!0),d.push(f)}return l?gt(s,{...a,options:d}):s}case"intersection":{let u=n(a.left),l=n(a.right);return u===a.left&&l===a.right?s:gt(s,{...a,left:u,right:l})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let u=n(a.innerType);return u===a.innerType?s:gt(s,{...a,innerType:u})}case"pipe":{let u=n(a.in),l=n(a.out);return u===a.in&&l===a.out?s:gt(s,{...a,in:u,out:l})}case"function":{let u=n(a.input),l=n(a.output);return u===a.input&&l===a.output?s:gt(s,{...a,input:u,output:l})}case"lazy":{let u=a.getter,{_cachedInner:l,...d}=a;return gt(s,{...d,getter:()=>n(u())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return s;default:return s}}return n(t)}function BW(t){return wy(t,{object:e=>e.partial(),union:e=>{let r=e._zod.def;return r.discriminator===void 0?e:It(r.options)}})}function lOe(t,e){if(!e?.length)return t;let r=t._zod.def;return gt(t,Wo(r,{checks:[...r.checks??[],...e]}),{parent:!0})}function ZW(t){return lOe(t.out,t.checks)}function dOe(t){return t.in._zod.traits.has("$ZodTransform")?ZW(t):t.in}function WW(t){return wy(t,{pipe:e=>dOe(e._zod.def),default:(e,r)=>r?kt(e._zod.def.innerType):e,catch:(e,r)=>r?e._zod.def.innerType:e})}function JW(t){return wy(t,{pipe:e=>ZW(e._zod.def),prefault:(e,r)=>r?e._zod.def.innerType:e})}var tL={};Ht(tL,{bigint:()=>hOe,boolean:()=>mOe,date:()=>gOe,number:()=>fOe,string:()=>pOe});function pOe(t){return nM(uf,t)}function fOe(t){return iM(lf,t)}function mOe(t){return sM(df,t)}function hOe(t){return aM(pf,t)}function gOe(t){return cM(ly,t)}var _y={name:"@tomato414941/foundation",version:"14.1.0",description:"Manage Foundation resources and run commands in execution environments.",type:"module",engines:{node:">=24"},bin:{foundation:"dist/cli.mjs"},files:["dist/cli.mjs"],repository:{type:"git",url:"git+https://github.com/tomato414941/foundation.git",directory:"cli"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},license:"MIT"};typeof window<"u"&&m.config({jitless:!0});function vOe(t){let e=/^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521))[ \t]+([A-Za-z0-9+/]+={0,2})(?:[ \t]+[^\r\n\0]*)?$/.exec(t.trim());if(!e)return null;try{let r=Uint8Array.from(atob(e[2]),a=>a.charCodeAt(0)),o=new DataView(r.buffer),n=0,i=()=>{if(n+4>r.length)throw new Error("Invalid SSH key.");let a=o.getUint32(n);if(n+=4,n+a>r.length)throw new Error("Invalid SSH key.");let c=r.subarray(n,n+a);return n+=a,c},s=a=>new TextDecoder().decode(a);if(s(i())!==e[1])return null;if(e[1]==="ssh-ed25519"){if(i().length!==32)return null}else if(e[1]==="ssh-rsa"){let a=i(),c=i();if(!a.length||c.length<256||c.length>1025)return null}else{let a=s(i()),c=i(),u={nistp256:65,nistp384:97,nistp521:133};if(e[1]!=="ecdsa-sha2-"+a||c[0]!==4||c.length!==u[a])return null}return n===r.length?r:null}catch{return null}}var by=m.string().trim().max(8192).refine(t=>vOe(t)!==null,"Use an OpenSSH public key from a .pub file."),Sy=m.object({authorizedKeys:m.array(by).max(32)}).strict(),dyt=Sy.extend({revision:m.number().int().positive().optional()}),rL=Sy.extend({host:m.string().min(1).max(253).nullable(),port:m.number().int().min(1).max(65535),username:m.literal("root"),workingDirectory:m.literal("/workspace"),hostKey:by.nullable(),fingerprint:m.string().nullable(),revision:m.number().int().positive(),appliedRevision:m.number().int().nonnegative(),activeSessions:m.number().int().min(0).max(1024)}).strict(),pyt=rL.extend({state:m.enum(["starting","configuring","ready","disabled","stopped"])}),fyt=m.object({hostKey:by,appliedRevision:m.number().int().nonnegative(),activeSessions:m.number().int().min(0).max(1024)}).strict(),wOe=Sy.extend({port:m.number().int().min(1).max(65535),revision:m.number().int().positive()}).strict(),SE=m.object({configuration:wOe.nullable()}).strict();var hf=new TextEncoder,gf=new TextDecoder,XW=new TextDecoder("utf-8",{fatal:!0}),xE=2**32;function Hn(...t){let e=t.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(e),o=0;for(let n of t)r.set(n,o),o+=n.length;return r}function nL(t,e,r){if(e<0||e>=xE)throw new RangeError(`value must be >= 0 and <= ${xE-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function oL(t){let e=Math.floor(t/xE),r=t%xE,o=new Uint8Array(8);return nL(o,e,0),nL(o,r,4),o}function EE(t){let e=new Uint8Array(4);return nL(e,t),e}var _Oe=/[^\x00-\x7f]/;function Qr(t){if(typeof t=="string"&&t.length>=128){if(_Oe.test(t))throw new TypeError("non-ASCII string encountered in encode()");return hf.encode(t)}let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++){let o=t.charCodeAt(r);if(o>127)throw new TypeError("non-ASCII string encountered in encode()");e[r]=o}return e}function YW(t,e=!1){if(Uint8Array.prototype.toBase64)return t.toBase64({alphabet:e?"base64url":"base64",omitPadding:e});let r=32768,o=[];for(let i=0;i<t.length;i+=r)o.push(String.fromCharCode.apply(null,t.subarray(i,i+r)));let n=btoa(o.join(""));return e?n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"):n}function QW(t,e=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(t,{alphabet:e?"base64url":"base64"});if(e){if(t.includes("+")||t.includes("/"))throw new TypeError("Invalid base64url");t=t.replace(/-/g,"+").replace(/_/g,"/")}let r=atob(t),o=new Uint8Array(r.length);for(let n=0;n<r.length;n++)o[n]=r.charCodeAt(n);return o}async function $E(t,e){let r=`SHA-${t.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,e))}var Va=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,r){super(e,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};var ed=class extends Va{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},Ot=class extends Va{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},Xc=class extends Va{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",r){super(e,r)}},H=class extends Va{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},Yt=class extends Va{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"};var xy=class extends Va{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"};var RE=class extends Va{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}};var bOe="The input to be decoded is not correctly encoded.";function td(t){try{return QW(typeof t=="string"?t:gf.decode(t),!0)}catch(e){throw new TypeError(bOe,{cause:e})}}function or(t){return YW(typeof t=="string"?hf.encode(t):t,!0)}function Io(t,e){if(!(t instanceof Uint8Array))throw new TypeError(`${e} must be an instance of Uint8Array`)}function _r(t){if(typeof t!="object"||t===null||Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||Object.getPrototypeOf(e)===null}function Yc(...t){let e=new Set;for(let r of t)if(r)for(let o of Object.keys(r)){if(e.has(o))return!1;e.add(o)}return!0}function Yo(t,e){if(t!==void 0)throw new TypeError(`${e} can only be called once`)}function po(t,e,r){try{return td(t)}catch{throw new r(`Failed to base64url decode the ${e}`)}}function IE(t,e,r){try{return Qr(t)}catch{throw new r(`The ${e} is not a valid base64url string`)}}function yf(t,e,r){let o;try{o=JSON.parse(XW.decode(td(t)))}catch{throw new e(r)}if(!_r(o))throw new e(r);return o}var AE={__proto__:null,b64:!0},PE={__proto__:null};function Ey(t,e){if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${t}" option must be an array of strings`);return e===void 0?void 0:new Set(e)}function kE(t,e){let{crit:r}=e??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new t('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function Qc(t,e,r,o,n){if(n.crit!==void 0&&o?.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return[];if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(s=>typeof s!="string"||s.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i=r===void 0?e:{__proto__:null,...r,...e};for(let s of o.crit){if(!(s in i))throw new Ot(`Extension Header Parameter "${s}" is not recognized`);if(!Object.hasOwn(n,s)||n[s]===void 0)throw new t(`Extension Header Parameter "${s}" is missing`);if(i[s]&&(!Object.hasOwn(o,s)||o[s]===void 0))throw new t(`Extension Header Parameter "${s}" MUST be integrity protected`)}return o.crit}function TE(t,e){if(e.includes("b64")){let r=t.b64;if(typeof r!="boolean")throw new Yt('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}function rd(t,e){let r,o;try{r=JSON.stringify(e),o=JSON.parse(r)}catch(n){throw new t("JOSE Header is not valid JSON",{cause:n})}if(!_r(o))throw new t("JOSE Header is not a JSON object");return[o,r]}var SOe=t=>t[Symbol.toStringTag],xOe=(t,e,r)=>{let{alg:o}=t;if(e.use!==void 0){let n=r==="sign"||r==="verify"?"sig":"enc";if(e.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(e.alg!==void 0&&e.alg!==o)throw new TypeError(`Invalid key for this operation, its "alg" must be "${o}" when present`);if(Array.isArray(e.key_ops)){let n=r==="encrypt"||r==="decrypt"?t.ops?.[r==="encrypt"?0:1]:r;if(n&&!e.key_ops.includes(n))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}};async function Mi(t,e,r){let{alg:o,secret:n}=t,i=r==="decrypt"||r==="sign";if(n&&e instanceof Uint8Array)return e;let s,a;if(_r(e)){if(s=lL(e),typeof s.kty!="string")throw e5(o,e,n);if(!(n?s.kty==="oct"&&typeof s.k=="string":s.kty!=="oct"&&(i?s.kty==="AKP"&&typeof s.priv=="string"||typeof s.d=="string":s.d===void 0&&s.priv===void 0)))throw new TypeError(n?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${i?"private":"public"} JWK`);if(xOe(t,s,r),s.kty==="oct")return td(s.k);if(!Object.isFrozen(e)){let{key_ops:l}=e;Array.isArray(l)&&Object.freeze(l),Object.freeze(e)}}else{if(!aL(e))throw e5(o,e,n);let l=n?"secret":i?"private":"public";if(e.type!==l&&(n||["secret","public","private"].includes(e.type)))throw new TypeError(`${SOe(e)} instances must be of type "${l}" for the ${o} algorithm`);if(eu(e))return e;if(a=e,a.type==="secret")return a.export()}iL||=new WeakMap;let c=e,u=iL.get(c);if(u?.[o])return u[o];if(u||iL.set(c,u={}),a&&typeof a.toCryptoKey=="function"){let l=a.type==="public",d=EOe[a.asymmetricKeyDetails?.namedCurve],p=t.resolve?.({crv:d,asymmetricKeyType:a.asymmetricKeyType})??t.subtle;return u[o]=a.toCryptoKey(p,l,t.usages[l?0:1])}return s??=a.export({format:"jwk"}),s.alg=o,u[o]=await wf(t,s)}var iL,EOe={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function OE(t){if(!eu(t))throw new Error("CryptoKey instance expected")}var eu=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},sL=t=>t?.[Symbol.toStringTag]==="KeyObject",aL=t=>eu(t)||sL(t);function t5(t,e,...r){if(r.length>2){let o=r.pop();t+=`one of type ${r.join(", ")}, or ${o}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}var Ga=(t,...e)=>t5("Key must be ",t,...e);function e5(t,e,r){let o=["CryptoKey","KeyObject","JSON Web Key"];return r&&o.push("Uint8Array"),new TypeError(t5(`Key for the ${t} algorithm must be `,e,...o))}var CE=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`);function cL(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function vf(t,e){let{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}function uL(t,e,r){let o=t.algorithm;if(o.name!==e.name)throw CE(e.name);if(e.hash&&o.hash?.name!==e.hash)throw CE(e.hash,"algorithm.hash");if(e.namedCurve&&o.namedCurve!==e.namedCurve)throw CE(e.namedCurve,"algorithm.namedCurve");if(e.length!==void 0&&o.length!==e.length)throw CE(e.length,"algorithm.length");cL(t,r)}function DE(t){return{__proto__:null,...t}}function lL(t){let e=DE(t);if(e.ext!==void 0&&typeof e.ext!="boolean")throw new TypeError('"ext" (Extractable) Parameter must be a boolean');if(e.key_ops!==void 0){let r=e.key_ops,o=Array.isArray(r)?[...r]:void 0;if(!o||o.some(n=>typeof n!="string")||new Set(o).size!==o.length)throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');e.key_ops=o}return e}function NE(t){if(t!==void 0&&typeof t!="boolean")throw new TypeError('"extractable" option must be a boolean');return t}async function wf(t,e,r){if(!t.kty.includes(e.kty))throw new Ot('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let o=t.resolve?.({kty:e.kty,crv:e.crv})??t.subtle,n=!!(e.d||e.priv),i={...e,ext:r??e.ext};return i.kty!=="AKP"&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,o,i.ext??!n,e.key_ops??t.usages[n?1:0])}async function Ui(t,e,r,o=!1){return t instanceof Uint8Array&&(t=await crypto.subtle.importKey("raw",t,e,o,[r])),uL(t,e,r),t}var nd=t=>crypto.getRandomValues(new Uint8Array(t.cekBits>>3));function zE(t,e){let r=t.byteLength<<3;if(r!==e)throw new H(`Invalid Content Encryption Key length. Expected ${e} bits, got ${r} bits`)}var $Oe=t=>crypto.getRandomValues(new Uint8Array(t.ivBits>>3));function r5(t,e){if(e.length<<3!==t.ivBits)throw new H("Invalid Initialization Vector length")}async function n5(t,e,r){if(!(e instanceof Uint8Array))throw new TypeError(Ga(e,"Uint8Array"));let o=t.cekBits>>1,n=await crypto.subtle.importKey("raw",e.subarray(o>>3),"AES-CBC",!1,[r]),i=await crypto.subtle.importKey("raw",e.subarray(0,o>>3),{hash:`SHA-${o<<1}`,name:"HMAC"},!1,["sign"]);return[n,i,o]}async function o5(t,e,r){return new Uint8Array((await crypto.subtle.sign("HMAC",t,e)).slice(0,r>>3))}async function ROe(t,e,r,o,n){let[i,s,a]=await n5(t,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:o,name:"AES-CBC"},i,e)),u=Hn(n,o,c,oL(n.length*8)),l=await o5(s,u,a);return{ciphertext:c,tag:l,iv:o}}async function IOe(t,e){let r={name:"HMAC",hash:"SHA-256"},o=await crypto.subtle.generateKey(r,!1,["sign","verify"]),n=await crypto.subtle.sign(r,o,t);return crypto.subtle.verify(r,o,n,e)}async function AOe(t,e,r,o,n,i){let[s,a,c]=await n5(t,e,"decrypt"),u=Hn(i,o,r,oL(i.length*8)),l=await o5(a,u,c);try{if(await IOe(n,l))return new Uint8Array(await crypto.subtle.decrypt({iv:o,name:"AES-CBC"},s,r))}catch{}throw new Xc}async function ME(t,e,r,o,n){if(!eu(r)&&!(r instanceof Uint8Array))throw new TypeError(Ga(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(o?r5(t,o):o=$Oe(t),r instanceof Uint8Array&&zE(r,t.cekBits),t.cbc)return ROe(t,e,r,o,n);let i=await Ui(r,t.subtle,"encrypt"),s=new Uint8Array(await crypto.subtle.encrypt({additionalData:n,iv:o,name:"AES-GCM",tagLength:128},i,e));return{ciphertext:s.subarray(0,-16),tag:s.subarray(-16),iv:o}}async function UE(t,e,r,o,n,i){if(!eu(e)&&!(e instanceof Uint8Array))throw new TypeError(Ga(e,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!o)throw new H("JWE Initialization Vector missing");if(!n)throw new H("JWE Authentication Tag missing");if(!t.cbc&&n.length!==16)throw new H("Invalid Authentication Tag length");if(r5(t,o),e instanceof Uint8Array&&zE(e,t.cekBits),t.cbc)return AOe(t,e,r,o,n,i);let s=await Ui(e,t.subtle,"decrypt");try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:i,iv:o,name:"AES-GCM",tagLength:128},s,Hn(r,n)))}catch{throw new Xc}}function $y(t){let e={__proto__:null};for(let r in t)e[r]={...t[r],alg:r};return e}var POe=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],kOe=[[],["deriveBits"]],FE=[[],[]];function LE(t){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${t}`},usages:POe,ops:["wrapKey","unwrapKey"]}}function jE(t){return{kty:["EC","OKP"],mode:t,subtle:{name:"ECDH"},resolve:({kty:e,crv:r,asymmetricKeyType:o})=>{if(r==="X25519"||o==="x25519")return{name:"X25519"};if(e==="OKP")throw new Ot('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:r}},usages:kOe,ops:[void 0,"deriveBits"]}}function _f(t,e=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:e?"AES-GCM":"AES-KW",length:t},usages:FE,ops:e?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function dL(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:FE,ops:["deriveBits","deriveBits"]}}var Ha=$y({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:FE,ops:["encrypt","decrypt"]},"RSA-OAEP":LE(1),"RSA-OAEP-256":LE(256),"RSA-OAEP-384":LE(384),"RSA-OAEP-512":LE(512),"ECDH-ES":jE("direct-key-agreement"),"ECDH-ES+A128KW":jE("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":jE("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":jE("key-agreement-with-key-wrapping"),A128KW:_f(128),A192KW:_f(192),A256KW:_f(256),A128GCMKW:_f(128,!0),A192GCMKW:_f(192,!0),A256GCMKW:_f(256,!0),"PBES2-HS256+A128KW":dL(),"PBES2-HS384+A192KW":dL(),"PBES2-HS512+A256KW":dL()}),TOe=["encrypt","decrypt"];function bf(t,e=!1){return{kty:["oct"],secret:!0,subtle:{name:e?"AES-CBC":"AES-GCM",length:t},usages:FE,ops:TOe,cekBits:t,ivBits:e?128:96,cbc:e}}var COe=$y({A128GCM:bf(128),A192GCM:bf(192),A256GCM:bf(256),"A128CBC-HS256":bf(256,!0),"A192CBC-HS384":bf(384,!0),"A256CBC-HS512":bf(512,!0)});function i5(t,e){throw new Ot(`Invalid or unsupported "${t}" (JWE ${e}) header value`)}function Li(t){return(typeof t=="string"?Ha[t]:void 0)??i5("alg","Algorithm")}function ji(t){return t.mode==="key-wrapping"||t.mode==="key-encryption"||t.mode==="key-agreement-with-key-wrapping"}function od(t){return(typeof t=="string"?COe[t]:void 0)??i5("enc","Encryption Algorithm")}function s5(t,e){if(t.algorithm.name!=="ECDH"&&t.algorithm.name!=="X25519")throw new TypeError("CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519");cL(t,e)}async function OOe(t,e,r){let o=await Ui(e,Li(t).subtle,"wrapKey",!0),n=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",n,o,"AES-KW"))}async function DOe(t,e,r){let o=await Ui(e,Li(t).subtle,"unwrapKey",!0),n=await crypto.subtle.unwrapKey("raw",r,o,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",n))}function c5(t,e,r){uL(e,Li(t).subtle,r),vf(t,e)}async function u5(t,e,r,o){if(!(t instanceof Uint8Array)||t.length<8)throw new H("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new H("PBES2 Count Input must be a positive integer");let n=Hn(Qr(e),Uint8Array.of(0),t),i=parseInt(e.slice(13,16),10),s={hash:`SHA-${e.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:n},a=await Ui(o,Li(e).subtle,"deriveBits");return new Uint8Array(await crypto.subtle.deriveBits(s,a,i))}function pL(t){return Hn(EE(t.length),t)}async function NOe(t,e,r){let o=e>>3,n=32,i=Math.ceil(o/n),s=new Uint8Array(i*n);for(let a=1;a<=i;a++){let c=await $E("sha256",Hn(EE(a),t,r));s.set(c,(a-1)*n)}return s.slice(0,o)}async function l5(t,e,r,o,n=new Uint8Array,i=new Uint8Array){s5(t),s5(e,"deriveBits");let s=Hn(pL(Qr(r)),pL(n),pL(i),EE(o)),a=new Uint8Array(await crypto.subtle.deriveBits({name:t.algorithm.name,public:t},e,t.algorithm.name==="X25519"?256:Math.ceil(parseInt(t.algorithm.namedCurve.slice(-3),10)/8)<<3));return NOe(a,o,s)}function d5(t){OE(t);let e=t.algorithm.namedCurve;if(e!=="P-256"&&e!=="P-384"&&e!=="P-521"&&t.algorithm.name!=="X25519")throw new Ot("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function qE(t,e){let r=t[e];if(r!==void 0){if(typeof r!="string")throw new H(`JOSE Header "${e}" (Agreement Party${e==="apu"?"U":"V"}Info) invalid`);return po(r,e,H)}}function p5(t,e){if(!(t===void 0||e===void 0||t.byteLength!==e.byteLength)){for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return;throw new H('JOSE Header "apu" and "apv" values must be distinct')}}function zOe(t){if(t===void 0)throw new H("JWE Encrypted Key missing")}function a5(t){if(t!==void 0)throw new H("Encountered unexpected JWE Encrypted Key")}function MOe(t){if(t!==void 0&&t!==1/0&&(!Number.isSafeInteger(t)||t<1))throw new TypeError("maxPBES2Count must be a positive safe integer or Infinity")}async function f5(t,e,r,o,n,i){let{alg:s}=t,a=t.mode;if(a==="direct-encryption")return a5(o),r;let c=a==="direct-key-agreement";switch(c?a5(o):zOe(o),t.subtle.name){case"ECDH":{let{epk:u}=n;if(!_r(u)||["d","k","p","q","dp","dq","qi","oth","priv"].some(h=>Object.hasOwn(u,h)))throw new H('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');d5(r);let l=await wf(t,u),d=qE(n,"apu"),p=qE(n,"apv");p5(d,p);let f=await l5(l,r,c?e.alg:s,c?e.cekBits:parseInt(s.slice(-5,-2),10),d,p);if(c)return f;r=f;break}case"RSA-OAEP":return OE(r),c5(s,r,"decrypt"),new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP",r,o));case"PBKDF2":{if(typeof n.p2c!="number")throw new H('JOSE Header "p2c" (PBES2 Count) missing or invalid');MOe(i);let u=i??1e4;if(n.p2c>u)throw new H('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new H('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let l=po(n.p2s,"p2s",H);r=await u5(l,s,n.p2c,r);break}case"AES-GCM":{if(typeof n.iv!="string")throw new H('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new H('JOSE Header "tag" (Authentication Tag) missing or invalid');let u=po(n.iv,"iv",H),l=po(n.tag,"tag",H);if(u.byteLength!==12)throw new H("Invalid Initialization Vector length");if(l.byteLength!==16)throw new H("Invalid Authentication Tag length");return UE(od(s.slice(0,-2)),r,o,u,l,new Uint8Array)}}return DOe(s.slice(-6),r,o)}async function VE(t,e,r,o,n,i={}){let{alg:s,mode:a}=t,c=ji(t);if(n!==void 0&&!c)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${s}`);let u=await Mi(a==="direct-encryption"?e:t,r,"encrypt");if(a==="direct-encryption")return[u,void 0,void 0];let l=c?n??nd(e):void 0;l&&zE(l,e.cekBits);let d,p;switch(t.subtle.name){case"ECDH":{d5(u);let{apu:f,apv:h}=i;f!==void 0&&Io(f,'"apu"'),h!==void 0&&Io(h,'"apv"');let y=f??qE(o,"apu"),w=h??qE(o,"apv");p5(y,w);let b;i.epk!==void 0?b=await Mi(t,i.epk,"decrypt"):b=(await crypto.subtle.generateKey(u.algorithm,!0,["deriveBits"])).privateKey;let S=crypto.subtle,x=b;if(!x.extractable){if(typeof S.getPublicKey!="function")throw new TypeError('CryptoKey for "epk" must be extractable');x=await S.getPublicKey(b,[])}let{x:R,y:T,crv:M,kty:Z}=await S.exportKey("jwk",x),te=a==="direct-key-agreement",Ae=await l5(u,b,te?e.alg:s,te?e.cekBits:parseInt(s.slice(-5,-2),10),y,w),Te={x:R,crv:M,kty:Z};if(Z==="EC"&&(Te.y=T),p={epk:Te},f!==void 0&&(p.apu=or(f)),h!==void 0&&(p.apv=or(h)),te)return[Ae,void 0,p];u=Ae;break}case"RSA-OAEP":{OE(u),c5(s,u,"encrypt"),d=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",u,l));break}case"PBKDF2":{let{p2c:f=2048,p2s:h=crypto.getRandomValues(new Uint8Array(16))}=i;u=await u5(h,s,f,u),p={p2c:f,p2s:or(h)};break}case"AES-GCM":{let f=i.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):i.iv;if(!(f instanceof Uint8Array))throw new TypeError('"iv" must be an instance of Uint8Array');let h=await ME(od(s.slice(0,-2)),l,u,f,new Uint8Array);d=h.ciphertext,p={iv:or(h.iv),tag:or(h.tag)}}}if(d??=await OOe(s.slice(-6),u,l),!(d instanceof Uint8Array)||!d.byteLength)throw new TypeError("JWE key management algorithm did not produce an Encrypted Key");return[l,d,p]}function GE(t,e){if(t.zip!==void 0&&t.zip!=="DEF")throw new Ot('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(t.zip!==void 0&&!e?.zip)throw new H('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function m5(t){if(typeof globalThis[t]>"u")throw new Ot(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${t} API.`)}async function h5(t,e,r=1/0){let o=t.writable.getWriter();o.write(e).catch(()=>{}),o.close().catch(()=>{});let n=[],i=0,s=t.readable.getReader();for(;;){let{value:a,done:c}=await s.read();if(c)break;if(n.push(a),i+=a.byteLength,r!==1/0&&i>r)throw new H("Decompressed plaintext exceeded the configured limit")}return Hn(...n)}async function g5(t){return m5("CompressionStream"),h5(new CompressionStream("deflate-raw"),t)}async function y5(t,e){return m5("DecompressionStream"),h5(new DecompressionStream("deflate-raw"),t,e)}function v5(t){let{aad:e,ciphertext:r,iv:o,protected:n,tag:i,unprotected:s}=t;if(o!==void 0&&(typeof o!="string"||!o))throw new H("JWE Initialization Vector incorrect type");if(typeof r!="string")throw new H("JWE Ciphertext missing or incorrect type");if(i!==void 0&&(typeof i!="string"||!i))throw new H("JWE Authentication Tag incorrect type");if(n!==void 0&&typeof n!="string")throw new H("JWE Protected Header incorrect type");if(e!==void 0&&(typeof e!="string"||!e))throw new H("JWE AAD incorrect type");if(s!==void 0&&!_r(s))throw new H("JWE Shared Unprotected Header incorrect type");return{aad:e,ciphertext:r,iv:o,protected:n,tag:i,unprotected:s===void 0?void 0:{...s}}}function w5(t){let e,r;try{let{header:o}=t;if(_r(o)){r=o.alg;let i=Object.keys(o);i.includes("alg")||(r=void 0),e=Object.fromEntries(i.map(s=>[s,s==="alg"?r:o[s]]))}else e=o;let{encrypted_key:n}=t;return[{encrypted_key:n,header:e},r]}catch(o){return[void 0,r,o]}}function _5(t){let{encrypted_key:e,header:r}=t;if(e!==void 0&&typeof e!="string")throw new H("JWE Encrypted Key incorrect type");if(r!==void 0&&!_r(r))throw new H("JWE Per-Recipient Unprotected Header incorrect type");if(t.protected===void 0&&r===void 0&&t.unprotected===void 0)throw new H("JOSE Header missing")}function fL(t){let{protected:e,ciphertext:r,iv:o,tag:n,aad:i}=t,s;return e!==void 0&&(s=yf(e,H,"JWE Protected Header is invalid")),[s,po(r,"ciphertext",H),o!==void 0?po(o,"iv",H):void 0,n!==void 0?po(n,"tag",H):void 0,IE((e??"")+(i!==void 0?`.${i}`:""),"aad",H)]}function HE(t){return[t&&Ey("keyManagementAlgorithms",t.keyManagementAlgorithms),t&&Ey("contentEncryptionAlgorithms",t.contentEncryptionAlgorithms),t?.crit,t?.maxPBES2Count,t?.maxDecompressedLength]}async function mL(t,e,r,o=fL(t)){let[n,i,s,a,c]=o,{header:u,unprotected:l,aad:d}=t,p;if(u!==void 0||l!==void 0){if(!Yc(n,u,l))throw new H("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");p={...n,...u,...l}}else p=n??{};let[f,h,y,w,b]=e,{encrypted_key:S}=t;Qc(H,PE,y,n,p),GE(p,n);let{alg:x,enc:R}=p;if(typeof x!="string"||!x)throw new H("missing JWE Algorithm (alg) in JWE Header");let T=Ha[x];if(S===""&&(!T||!ji(T)))throw new H("JWE Encrypted Key incorrect type");let M=T?.mode==="integrated-encryption";if(!M&&(typeof R!="string"||!R))throw new H("missing JWE Encryption Algorithm (enc) in JWE Header");if(f&&!f.has(x)||!f&&x.startsWith("PBES2"))throw new ed('"alg" (Algorithm) Header Parameter value not allowed');let Z;if(M){if(R!==void 0)throw new H('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(s?.byteLength)throw new H("JWE Initialization Vector must be empty for integrated encryption");if(a?.byteLength)throw new H("JWE Authentication Tag must be empty for integrated encryption")}else{if(h&&!h.has(R))throw new ed('"enc" (Encryption Algorithm) Header Parameter value not allowed');Z=od(R)}let te;if(S!==void 0)try{te=po(S,"encrypted_key",H)}catch(Fe){if(!T||!ji(T))throw Fe;te=new Uint8Array}let Ae=!1;typeof r=="function"&&(r=await r(n,t),Ae=!0);let Te=T??Li(x);ji(Te)&&te===void 0&&(te=new Uint8Array);let bt=await Mi(Te.mode==="direct-encryption"?Z:Te,r,"decrypt"),me;if(Te.mode==="integrated-encryption")me=await Te.decrypt(bt,te,i,c,n,p);else{let Fe=Z,se;try{se=await f5(Te,Fe,bt,te,p,w),ji(Te)&&se instanceof Uint8Array&&se.byteLength<<3!==Fe.cekBits&&(se=nd(Fe))}catch(rr){if(rr instanceof TypeError||rr instanceof H||rr instanceof Ot)throw rr;se=nd(Fe)}me=await UE(Fe,se,i,s,a,c)}if(p.zip==="DEF"){let Fe=b??25e4;if(Fe===0)throw new Ot('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(Fe!==1/0&&(!Number.isSafeInteger(Fe)||Fe<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");me=await y5(me,Fe).catch(se=>{throw se instanceof H?se:new H("Failed to decompress plaintext",{cause:se})})}return{plaintext:me,...n&&{protectedHeader:n},...d!==void 0&&{additionalAuthenticatedData:po(d,"aad",H)},...l&&{sharedUnprotectedHeader:l},...u&&{unprotectedHeader:u},...Ae&&{key:bt}}}async function b5(t,e,r){if(t instanceof Uint8Array&&(t=gf.decode(t)),typeof t!="string")throw new H("Compact JWE must be a string or Uint8Array");let{0:o,1:n,2:i,3:s,4:a,length:c}=t.split(".");if(c!==5)throw new H("Invalid Compact JWE");return mL({ciphertext:s,iv:i||void 0,protected:o,tag:a||void 0,encrypted_key:n||void 0},e,r)}async function Ry(t,e,r){return b5(t,HE(r),e)}async function hL(t,e,r){if(!_r(t))throw new H("General JWE must be an object");let o=t.recipients;if(!Array.isArray(o))throw new H("JWE Recipients missing or incorrect type");let n=Array.from(o);if(!n.every(_r))throw new H("JWE Recipients missing or incorrect type");if(!n.length)throw new H("JWE Recipients has no members");let i,s,a;try{i=HE(r),s=v5(t),a=fL(s)}catch{throw new Xc}let c=n.map(u=>w5(u));if(n.length>1)for(let[,u]of c){let l=a[0]?.alg??u??s.unprotected?.alg,d=typeof l=="string"?Ha[l]:void 0;if(d&&!ji(d))throw new H(`"${l}" alg may only have a single recipient`)}for(let[u]of c)if(u)try{let l={...s,...u};return _5(l),await mL(l,i,e,a)}catch{}throw new Xc}function KE(t,e,r){if(!Yc(t,e,r))throw new H("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}function gL(t,e,r=!1){if(!t[1]&&!t[2]&&!t[3])throw new H("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");e!==void 0&&(t[8]=e?.crit);let[,o,n,i,s,a,c,u,l]=t;if(s!==void 0&&Io(s,"JWE Additional Authenticated Data"),a!==void 0&&Io(a,"JWE Content Encryption Key"),c!==void 0&&Io(c,"JWE Initialization Vector"),!r&&o!==void 0&&(o=rd(H,o)[0],t[1]=o),n!==void 0&&(n=rd(H,n)[0],t[2]=n),!r&&i!==void 0&&(i=rd(H,i)[0],t[3]=i),u!==void 0&&!_r(u))throw new TypeError("JWE Key Management Parameters must be an object");KE(o,n,i);let d={...o,...n,...i};kE(H,o),Qc(H,PE,l,o,d),GE(d,o);let{alg:p,enc:f}=d;if(typeof p!="string"||!p)throw new H('JWE "alg" (Algorithm) Header Parameter missing or invalid');let h=Ha[p];if(h?.mode==="integrated-encryption"){if(f!==void 0)throw new H('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(a!==void 0)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${p}`);if(c!==void 0)throw new TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${p}`);return[d,void 0,h]}if(typeof f!="string"||!f)throw new H('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[d,od(f),h]}async function yL(t,e,r){let[o,n,i]=e,[s,a,c,u,l,d,p,f,,h]=t,y=a,w=c,b=i??Li(o.alg),S,x,R;b.mode==="integrated-encryption"?R=await Mi(b,r,"encrypt"):[R,S,x]=await VE(b,n,r,o,d,f),x&&(h?w=w?{...w,...x}:x:y=y?{...y,...x}:x,KE(y,w,u));let T=y?or(JSON.stringify(y)):"",M=l?.byteLength?or(l):void 0,Z=Qr(M?`${T}.${M}`:T),te=s;o.zip==="DEF"&&(te=await g5(te).catch(Fe=>{throw new H("Failed to compress plaintext",{cause:Fe})}));let Ae,Te,bt;b.mode==="integrated-encryption"?[S,Ae]=await b.encrypt(R,te,Z,y,o,f):{ciphertext:Ae,tag:Te,iv:bt}=await ME(n,te,R,p,Z);let me={ciphertext:or(Ae)};return bt&&(me.iv=or(bt)),Te&&(me.tag=or(Te)),S?.byteLength&&(me.encrypted_key=or(S)),M&&(me.aad=M),y&&(me.protected=T),u&&(me.unprotected=u),w&&(me.header=w),me}async function S5(t,e,r){return yL(t,gL(t,r),e)}function x5(t){return[t.protected,t.encrypted_key,t.iv,t.ciphertext,t.tag].join(".")}var vL=class{#e;state;constructor(e,r,o){this.#e=e,this.state=[void 0,void 0,r,o]}setUnprotectedHeader(e){return Yo(this.state[0],"setUnprotectedHeader"),this.state[0]=e,this}setKeyManagementParameters(e){return Yo(this.state[1],"setKeyManagementParameters"),this.state[1]=e,this}addRecipient(...e){return this.#e.addRecipient(...e)}encrypt(...e){return this.#e.encrypt(...e)}done(){return this.#e}},Iy=class{#e;#t=[];#r;#n;#o;constructor(e){this.#e=e}addRecipient(e,r){let o=new vL(this,e,r?.crit);return this.#t.push(o),o}setProtectedHeader(e){return Yo(this.#r,"setProtectedHeader"),this.#r=e,this}setSharedUnprotectedHeader(e){return Yo(this.#n,"setSharedUnprotectedHeader"),this.#n=e,this}setAdditionalAuthenticatedData(e){return this.#o=e,this}async encrypt(){if(!this.#t.length)throw new H("at least one recipient must be added");Io(this.#e,"plaintext");let e=this.#t.length>1,r,o=this.#r,n=this.#n,i=[];for(let h of this.#t){let[y,w,b,S]=h.state,x=[this.#e,o,y,n,this.#o,void 0,void 0,w,S,e],R=gL(x,void 0,i.length>0);i.length||(o=x[1],n=x[3]),i.push([x,R,b]);let[{alg:T,enc:M},,Z]=R;if(e&&Z&&!ji(Z))throw new H(`"${T}" alg may only have a single recipient`);if(!r)r=M;else if(r!==M)throw new H('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients')}for(let[,h]of i)h[2]??=Li(h[0].alg);let[s,a,c]=i[0],u=e?nd(a[1]):void 0;s[5]=u;let{encrypted_key:l,header:d,...p}=await yL(s,a,c),f={...p,recipients:[{}]};l&&(f.recipients[0].encrypted_key=l),d&&(f.recipients[0].header=d);for(let h=1;h<i.length;h++){let[y,[w,b,S],x]=i[h],R=y[2],[,T,M]=await VE(S,b,x,w,u,y[7]),Z={encrypted_key:or(T)};if(R||M){let te={...R,...M};M&&KE(y[1],te,y[3]),Z.header=te}f.recipients.push(Z)}return f}};var Ay=[["verify"],["sign"]];function wL(t){let e={name:"HMAC",hash:`SHA-${t}`};return{kty:["oct"],secret:!0,subtle:e,signing:e,usages:Ay}}function Sf(t,e){let r={name:e?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${t}`};return{kty:["RSA"],subtle:r,signing:e?{...r,saltLength:e}:r,usages:Ay,minRsaBits:2048}}function _L(t,e){return{kty:["EC"],crv:t,subtle:{name:"ECDSA",namedCurve:t},signing:{name:"ECDSA",hash:`SHA-${e}`},usages:Ay}}function E5(){let t={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:t,signing:t,usages:Ay}}function bL(t){let e={name:`ML-DSA-${t}`};return{kty:["AKP"],subtle:e,signing:e,usages:Ay}}var SL=$y({HS256:wL(256),HS384:wL(384),HS512:wL(512),RS256:Sf(256),RS384:Sf(384),RS512:Sf(512),PS256:Sf(256,32),PS384:Sf(384,48),PS512:Sf(512,64),ES256:_L("P-256",256),ES384:_L("P-384",384),ES512:_L("P-521",512),EdDSA:E5(),Ed25519:E5(),"ML-DSA-44":bL(44),"ML-DSA-65":bL(65),"ML-DSA-87":bL(87)});function BE(t){let e=typeof t=="string"?SL[t]:void 0;if(!e)throw new Ot(`alg ${t} is not supported either by JOSE or your javascript runtime`);return e}function $5(t){return[t&&Ey("algorithms",t.algorithms),t?.crit]}function UOe(t){return t===void 0?{}:yf(t,Yt,"JWS Protected Header is invalid")}function LOe(t){try{return Qr(t)}catch{throw new Yt("JWS Compact Serialization payload must use only ASCII characters")}}async function jOe(t,e,r,o,n){let{protected:i,header:s,payload:a}=t,c=n??UOe(i);if(!Yc(c,s))throw new Yt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let u={...c,...s},l=TE(c,Qc(Yt,AE,e[1],c,u)),{alg:d}=u;if(typeof d!="string"||!d)throw new Yt('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(e[0]&&!e[0].has(d))throw new ed('"alg" (Algorithm) Header Parameter value not allowed');if(l){if(typeof a!="string")throw new Yt("JWS Payload must be a string")}else if(typeof a!="string"&&!(a instanceof Uint8Array))throw new Yt("JWS Payload must be a string or an Uint8Array instance");let p=l||typeof a!="string"?a:o(a),f=!1;typeof r=="function"&&(r=await r(c,t),f=!0);let h=BE(d),y=Hn(i!==void 0?Qr(i):new Uint8Array,Qr("."),typeof p=="string"?e[2]??=IE(p,"payload",Yt):p),w=po(t.signature,"signature",Yt),b=await Mi(h,r,"verify"),S=await Ui(b,h.subtle,"verify");h.minRsaBits&&vf(h.alg,S);let x=!1;try{x=await crypto.subtle.verify(h.signing,S,w,y)}catch{}if(!x)throw new RE;let R={payload:typeof p=="string"?po(p,"payload",Yt):p};return i!==void 0&&(R.protectedHeader=c),s!==void 0&&(R.unprotectedHeader=s),f?[{...R,key:b},l]:[R,l]}async function R5(t,e,r){if(t instanceof Uint8Array&&(t=gf.decode(t)),typeof t!="string")throw new Yt("Compact JWS must be a string or Uint8Array");let{0:o,1:n,2:i,length:s}=t.split(".");if(s!==3)throw new Yt("Invalid Compact JWS");return jOe({payload:n,protected:o,signature:i},e,r,LOe)}async function xL(t,e,r){let[o]=await R5(t,$5(r),e);return o}var xf=class{#e;constructor(e){Io(e,"plaintext"),this.#e=[e]}setContentEncryptionKey(e){return Yo(this.#e[5],"setContentEncryptionKey"),this.#e[5]=e,this}setInitializationVector(e){return Yo(this.#e[6],"setInitializationVector"),this.#e[6]=e,this}setProtectedHeader(e){return Yo(this.#e[1],"setProtectedHeader"),this.#e[1]=e,this}setKeyManagementParameters(e){return Yo(this.#e[7],"setKeyManagementParameters"),this.#e[7]=e,this}async encrypt(e,r){return x5(await S5([...this.#e],e,r))}};async function FOe(t,e,r){let[o,n,i,s]=t,a="";if(n!==void 0){let b=rd(Yt,n);n=b[0],a=or(b[1])}if(i!==void 0&&(i=rd(Yt,i)[0]),!n&&!i)throw new Yt("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Yc(n,i))throw new Yt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let c={...n,...i};kE(Yt,n);let u=TE(n,Qc(Yt,AE,s,n,c));u||r?.();let{alg:l}=c;if(typeof l!="string"||!l)throw new Yt('JWS "alg" (Algorithm) Header Parameter missing or invalid');let d=BE(l),p="",f=o,h;if(u){let b=t[4];b?(p=b[0]??=or(o),f=b[1]??=Qr(p)):(p=or(o),h=hf.encode(`${a}.${p}`))}h??=Hn(Qr(a),Qr("."),f);let y=await Ui(await Mi(d,e,"sign"),d.subtle,"sign");d.minRsaBits&&vf(d.alg,y);let w={signature:or(new Uint8Array(await crypto.subtle.sign(d.signing,y,h))),payload:p};return n&&(w.protected=a),i&&(w.header=i),[w,u]}async function I5(t,e,r,o,n){let[i]=await FOe([t,e,void 0,r],o,n);return`${i.protected}.${i.payload}.${i.signature}`}var Py=class{#e;#t;constructor(e){Io(e,"payload"),this.#e=e}setProtectedHeader(e){return Yo(this.#t,"setProtectedHeader"),this.#t=e,this}async sign(e,r){return I5(this.#e,this.#t,r?.crit,e,()=>{throw new TypeError("use the flattened module for creating JWS with b64: false")})}};var EL='"alg" (Algorithm)';function $L(t='JWK "alg" (Algorithm) Parameter'){throw new Ot(`Invalid or unsupported ${t} value`)}function ky(t,e){return(typeof t=="string"?SL[t]??Ha[t]:void 0)??$L(e)}async function tu(t){if(sL(t))if(t.type==="secret")t=t.export();else return t.export({format:"jwk"});if(t instanceof Uint8Array)return{kty:"oct",k:or(t)};if(!eu(t))throw new TypeError(Ga(t,"CryptoKey","KeyObject","Uint8Array"));if(!t.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let e=await crypto.subtle.exportKey("jwk",t);delete e.ext,delete e.key_ops,delete e.use,e.kty!=="AKP"&&delete e.alg;for(let r of Object.keys(e))e[r]===void 0&&delete e[r];return e}var Ka=(t,e)=>{if(typeof t!="string"||!t)throw new xy(`${e} missing or invalid`)};async function RL(t,e){let r;if(_r(t)){if(r=DE(t),typeof r.kty!="string")throw new TypeError(Ga(t,"CryptoKey","KeyObject","JSON Web Key"))}else if(aL(t))r=DE(await tu(t));else throw new TypeError(Ga(t,"CryptoKey","KeyObject","JSON Web Key"));if(e??="sha256",e!=="sha256"&&e!=="sha384"&&e!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let o;switch(r.kty){case"AKP":Ka(r.alg,'"alg" (Algorithm) Parameter'),Ka(r.pub,'"pub" (Public key) Parameter'),o={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":Ka(r.crv,'"crv" (Curve) Parameter'),Ka(r.x,'"x" (X Coordinate) Parameter'),Ka(r.y,'"y" (Y Coordinate) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":Ka(r.crv,'"crv" (Subtype of Key Pair) Parameter'),Ka(r.x,'"x" (Public Key) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":Ka(r.e,'"e" (Exponent) Parameter'),Ka(r.n,'"n" (Modulus) Parameter'),o={e:r.e,kty:r.kty,n:r.n};break;case"oct":if(typeof r.k!="string")throw new xy('"k" (Key Value) Parameter missing or invalid');o={k:r.k,kty:r.kty};break;default:throw new Ot('"kty" (Key Type) Parameter missing or unsupported')}let n=Qr(JSON.stringify(o));return or(await $E(e,n))}async function Qo(t,e,r){if(!_r(t))throw new TypeError("JWK must be an object");let o=lL(t),n=NE(r?.extractable),{alg:i}=o;if(e??=i,o.kty!=="oct"&&!e)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');switch(o.kty){case"oct":if(typeof o.k!="string")throw new TypeError('missing "k" (Key Value) Parameter value');return td(o.k);case"AKP":{if(typeof i!="string"||!i)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(e!==i)throw new TypeError("JWK alg and alg option value mismatch");return wf(ky(e),o,n)}case"RSA":case"EC":case"OKP":return wf(ky(e),o,n);default:throw new Ot('Unsupported "kty" (Key Type) Parameter value')}}function IL(t){let e;if(typeof t=="string"){let o=t.split(".");(o.length===3||o.length===5)&&([e]=o)}else if(typeof t=="object"&&t)if("protected"in t)e=t.protected;else throw new TypeError("Token does not contain a Protected Header");let r="Invalid Token or Protected Header formatting";if(typeof e!="string"||!e)throw new TypeError(r);return yf(e,TypeError,r)}function qOe(t){let e=t?.modulusLength??2048;if(typeof e!="number"||!Number.isInteger(e)||e<2048)throw new Ot("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return e}async function Ty(t,e){let r=NE(e?.extractable),o=ky(t,EL);o.secret&&$L(EL);let n;if(o.resolve){let i=e?.crv??"P-256";if(!["P-256","P-384","P-521","X25519"].includes(i))throw new Ot("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519");n=o.resolve({crv:i})}else{if(o.crv!==void 0&&e?.crv!==void 0&&e.crv!==o.crv)throw new Ot(`Invalid or unsupported crv option provided, the only supported value for ${t} is ${o.crv}`);n=o.kty[0]==="RSA"?{...o.subtle,publicExponent:Uint8Array.of(1,0,1),modulusLength:qOe(e)}:o.subtle}return crypto.subtle.generateKey(n,r??!1,[...o.usages[1],...o.usages[0]])}var T5=m.string().regex(/^[a-z]{2}(?:-gov)?-[a-z]+-\d$/),C5=m.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:iam::\d{12}:role\/.+/),A5=m.string().min(1).max(128),P5=m.string().min(1).max(16384),VOe=m.discriminatedUnion("kind",[m.object({kind:m.literal("access_key"),accessKeyId:A5,secretAccessKey:P5}).strict(),m.object({kind:m.literal("session"),accessKeyId:A5,secretAccessKey:P5,sessionToken:m.string().min(1).max(16384),expiresAt:m.number().int().positive().max(Number.MAX_SAFE_INTEGER)}).strict(),m.object({kind:m.literal("environment")}).strict()]),GOe=m.object({arn:C5,externalId:m.string().min(2).max(1224).regex(/^[\w+=,.@:\/-]+$/).optional()}).strict(),Ba=m.object({authentication:VOe,region:T5,role:GOe.optional()}).strict(),ZE=m.object({accountId:m.string().regex(/^\d{12}$/),principalId:m.string().min(1).max(256),arn:m.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:(?:iam|sts)::\d{12}:.+/)}).strict(),WE=Ba.extend({sourceIdentity:ZE.optional(),identity:ZE.optional()}).strict();function Ef(t){return t.includes(":assumed-role/")?t.slice(0,t.lastIndexOf("/")):t}function k5(t){return{...t,arn:Ef(t.arn)}}function O5(t){return{authentication:t.authentication.kind,region:t.region,role:t.role??null,...t.sourceIdentity?{sourceIdentity:k5(t.sourceIdentity)}:{},...t.identity?{identity:k5(t.identity)}:{}}}var JE=m.object({authentication:m.enum(["access_key","session","environment"]),region:T5,sourceAccountId:m.string().regex(/^\d{12}$/).optional(),sourceArn:m.string().max(2e3).optional(),roleArn:C5.optional(),expiresAt:m.number().int().positive().optional()}).strict();function D5(t){return{authentication:t.authentication.kind,region:t.region,...t.sourceIdentity?{sourceAccountId:t.sourceIdentity.accountId,sourceArn:t.sourceIdentity.arn}:{},...t.role?{roleArn:t.role.arn}:{},...t.authentication.kind==="session"?{expiresAt:t.authentication.expiresAt}:{}}}var N5=m.object({method:m.enum(["GET","POST","PUT","DELETE","PATCH"]),path:m.string().min(1).max(1e3).regex(/^\/[^\s\u0000]*$/)}).strict(),Cy=m.object({account:m.string().min(1),identities:m.array(m.string()),user:m.string().nullable(),description:m.string().nullable(),roles:m.array(m.string()).nullable(),credentialId:m.number().int().positive(),rules:m.array(N5),allowedIPs:m.array(m.string()).nullable(),expiresAt:m.number().nullable()}).strict();function z5(t){return t.map(e=>{let r=e.match(/^(GET|POST|PUT|DELETE|PATCH) (\/[^\s\u0000]*)$/);if(!r)throw new Error("Use one HTTP method and API path for each OVH permission.");return N5.parse({method:r[1],path:r[2]})})}typeof window<"u"&&m.config({jitless:!0});var E=m.uuid(),fe=m.string().trim().min(1).max(200).regex(/^[^\u0000-\u001f\u007f]+$/u),$e=m.iso.datetime(),yr=m.json(),Lt=m.record(m.string(),yr),M5=m.enum(["ja","en"]),U5=m.enum(["read","create","update","delete","share","transfer","reveal","use","execute","manage_credentials","manage_billing","export"]);var L5=m.enum(["variable","connection","service","method","app","object","environment","function","keyring"]),bn=m.object({kty:m.literal("EC"),crv:m.literal("P-256"),x:m.string().min(40).max(50),y:m.string().min(40).max(50)}).strict(),HOe=m.object({alg:m.literal("dir"),enc:m.literal("A256GCM"),sub:E}).strict(),e$=m.string().max(16384).regex(/^[A-Za-z0-9_-]+\.\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{22}$/).refine(t=>{try{return HOe.safeParse(IL(t)).success}catch{return!1}},"Use an A256GCM JWE for the wrapped encryption key.").brand(),Ao=m.object({protected:m.string().max(2048),iv:m.string().max(64),ciphertext:m.string().max(2e6),tag:m.string().max(64),aad:m.string().max(2048).optional(),recipients:m.array(m.object({encrypted_key:m.string().max(2048),header:m.object({kid:E,epk:bn.optional(),alg:m.string().optional()}).passthrough()})).min(1).max(100)}).strict(),Wwt=m.object({id:E,name:fe,publicKey:bn}),ru=m.object({id:E,name:fe,owner:m.object({id:E,name:fe}).nullable(),createdAt:$e,permissions:m.array(U5),createKinds:m.array(L5),publicKey:bn.nullable()}),j5=m.object({id:E,kind:m.enum(["passkey","email","key"]),name:m.string(),createdAt:$e,lastUsedAt:$e.nullable(),expiresAt:$e.nullable(),canOpen:m.boolean()}),F5=m.string().regex(/^[a-z][a-z_]*[a-z]$/).max(64),KOe=m.object({subjectId:E,relation:F5,objectId:E}).strict(),Jwt=KOe.extend({objectType:m.enum(["principal",...L5.options]),subjectName:fe,objectName:fe,createdAt:$e}),Xwt=m.object({error:m.object({code:m.string(),message:m.string(),details:yr.optional()})}),Ywt=m.object({ok:m.literal(!0)}),BOe=m.object({value:m.string().min(1).max(200),label:m.string().min(1).max(200),values:m.record(m.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),m.string()).default({})}).strict(),t$=m.object({name:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),label:m.string(),secret:m.boolean().optional(),inputType:m.enum(["text","password"]).optional(),required:m.boolean().optional(),placeholder:m.string().optional(),note:m.string().optional(),pattern:m.string().optional(),choices:m.array(BOe).min(1).max(100).optional(),defaultValue:m.string().max(1e3).optional(),when:m.object({field:m.string(),values:m.array(m.string()).min(1)}).strict().optional(),visibility:m.enum(["application","connection"]).optional()}).superRefine((t,e)=>{let r=t.choices??[];new Set(r.map(o=>o.value)).size!==r.length&&e.addIssue({code:"custom",path:["choices"],message:"Use a unique value for each choice."})}),AL=m.record(m.string().regex(/^[A-Z_][A-Z0-9_]*$/),m.string()),ZOe=m.record(m.string().regex(/^[A-Z_][A-Z0-9_]*$/),m.union([m.string(),m.array(m.union([m.string().max(8192),m.object({pointer:m.string().max(1e3)}).strict()])).min(1).max(32)])),PL=m.object({values:m.array(m.object({id:m.string(),name:m.string(),description:m.string().optional()})).optional(),default:m.array(m.string()).default([]),required:m.array(m.string()).optional(),separator:m.string().default(" "),docs:m.url().optional()}),id=m.string().min(1).max(4096),YE=m.union([m.string(),m.array(m.string()).min(1)]),WOe=m.object({application:m.enum(["required","implicit"]).default("required"),grantType:m.enum(["authorization_code","client_credentials"]).optional(),issuer:m.url().optional(),registrationUrl:m.url().optional(),authorizeUrl:id.optional(),tokenUrl:id,identity:m.object({url:id.optional(),from:m.enum(["token","app"]).optional(),method:m.enum(["GET","POST"]).default("GET"),id:YE.default("/id"),name:YE.default("/name"),headers:m.record(m.string(),m.string()).default({})}).optional(),revoke:m.object({url:id,style:m.enum(["rfc7009","bearer","github","delete"]).default("rfc7009"),auth:m.enum(["body","basic","none"]).optional()}).optional(),clientAuth:m.enum(["body","basic","none"]).default("body"),pkce:m.boolean().default(!0),tokenFormat:m.enum(["form","json"]).default("form"),okPointer:m.string().optional(),authorizeParams:m.record(m.string(),m.string()).default({}),tokenParams:m.record(m.string(),m.string()).default({}),defaults:m.record(m.string(),m.string()).default({}),scopes:PL.default({default:[],separator:" "}),fields:m.array(t$).default([]),outputs:AL.default({ACCESS_TOKEN:"/accessToken"}),adapter:m.string().regex(/^[a-z][a-z0-9_-]{0,99}$/).optional(),keep:m.array(m.string()).default([]),hint:m.string().optional()}).refine(t=>t.grantType==="client_credentials"||!!t.authorizeUrl,{path:["authorizeUrl"],message:"An authorization code flow requires an authorization URL."}),JOe=m.object({fields:m.array(t$).min(1),outputs:ZOe,resolver:m.literal("vultr-role").optional(),bindFields:m.boolean().optional(),constants:m.record(m.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),m.string()).optional(),identity:m.object({url:id,headers:m.record(m.string(),m.string()),id:YE,name:YE}).strict().optional(),console:m.url().optional(),instructions:m.string().optional(),hint:m.string().optional()}),kL=m.enum(["oauth","token","aws","ovh","approval"]),XOe=m.object({hint:m.string().optional()}).strict(),YOe=m.object({authorization:m.enum(["api_key","consumer_key"]),apiBaseUrl:id,fields:m.array(t$).min(1),scopes:PL.default({default:[],separator:`
129
- `}),outputs:AL,hint:m.string().optional()}).strict(),Ny={name:fe,docs:m.url().optional(),console:id.optional()},r$=m.object({...Ny,kind:m.literal("oauth"),config:WOe}).strict(),n$=m.object({...Ny,kind:m.literal("token"),config:JOe}).strict(),o$=m.object({...Ny,kind:m.literal("aws"),config:XOe}).strict(),i$=m.object({...Ny,kind:m.literal("ovh"),config:YOe}).strict(),s$=m.object({...Ny,kind:m.literal("approval"),config:m.object({adapter:m.literal("runpod-flash"),fields:m.array(t$).default([]),scopes:PL.default({default:[],separator:" "}),outputs:AL,hint:m.string().optional()}).strict()}).strict(),nu=m.discriminatedUnion("kind",[r$,n$,o$,i$,s$]),Oy={id:m.string().min(1),builtin:m.boolean(),availability:m.enum(["ready","app-required","unavailable"]),defaultName:fe,registration:m.object({kind:m.enum(["input","authorization"]),device:m.enum(["browser","cli"]),browserExchange:m.enum(["available","unavailable","unknown"]),tokenAlternatives:m.array(m.string())}).strict()},zy=m.discriminatedUnion("kind",[r$.extend(Oy),n$.extend(Oy),o$.extend(Oy),i$.extend(Oy),s$.extend(Oy)]),Dy=m.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),TL=m.object({name:fe,logo:m.string().regex(/^[a-z0-9-]+$/).optional(),api:m.url().optional(),docs:m.url().optional(),console:m.url().optional(),targets:m.array(m.object({id:Dy,name:fe,api:m.url().optional(),methods:m.array(Dy).min(1)}).strict()).max(32).optional()}).strict(),QOe=TL.extend({methods:m.record(Dy,m.string().min(1))}).strict(),q5=TL.extend({methods:m.record(Dy,m.union([m.string().min(1),nu]))}).strict(),Qwt=TL.extend({id:m.string(),builtin:m.boolean(),methods:m.record(Dy,zy)}),V5=m.object({id:E,output:m.string().min(1).max(100).optional()}).strict(),G5=t=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(t)&&!/^(FOUNDATION_|LD_|DYLD_)|^(NODE_OPTIONS|BASH_ENV|ENV|PYTHONSTARTUP|GIT_CONFIG_COUNT|GIT_CONFIG_SYSTEM)$/u.test(t),CL=m.object({name:m.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),source:V5,format:m.enum(["text","file","json"]).default("text"),pointer:m.string().optional()}).strict(),eDe=m.object({pointer:m.string().max(500),parts:m.array(m.union([m.string().max(8192),V5])).min(1).max(32)}).strict(),Za=m.object({url:m.string().max(4096),method:m.enum(["GET","HEAD","POST","PUT","PATCH","DELETE"]).default("GET"),headers:m.record(m.string(),m.string().max(8192)).default({}),body:m.string().max(1e6).optional(),json:yr.optional(),form:m.record(m.string(),m.string()).optional(),bindings:m.array(eDe).max(32).default([])}).strict(),Wa=m.object({command:m.array(m.string().max(8192)).min(1).max(100),stdin:m.string().max(1e6).optional(),timeoutSeconds:m.number().int().min(1).max(3600).default(60),inputs:m.array(CL).max(32).default([])}).strict(),H5=m.discriminatedUnion("kind",[Wa.omit({stdin:!0}).extend({kind:m.literal("command")}).strict(),m.object({kind:m.literal("http"),request:Za,responseFormat:m.enum(["text","json"]).default("json")}).strict()]),ei=m.object({description:m.string().max(2e3).default(""),environmentId:E,program:H5,inputAccess:m.object({expiresAt:$e.nullable().default(null)}).strict().default({expiresAt:null}),parameters:m.array(m.object({name:m.string().regex(/^[A-Za-z][A-Za-z0-9_]*$/),label:m.string().max(100),type:m.enum(["string","number","boolean","json"]).default("string"),required:m.boolean().default(!0),default:yr.optional()}).strict()).max(32).default([]),result:m.enum(["text","json"]).default("json")}).strict(),Ja={id:E,ownerId:E,name:fe,createdAt:$e,updatedAt:$e,version:m.number().int().positive(),permissions:m.array(U5)},tDe=m.enum(["starting","running","stopping","stopped","failed"]),rDe=m.object({state:m.enum(["pending","failed","complete"]),error:m.string().nullable()}),nDe=m.object({idleSeconds:m.number().int().min(60).max(86400).default(3600),maxSeconds:m.number().int().min(60).max(86400).default(3600)}).strict(),K5=m.object({image:m.string().min(1).max(300).optional(),size:m.enum(["small","medium","large"]).default("small"),lifetime:nDe.default({idleSeconds:3600,maxSeconds:3600}),ssh:Sy.optional()}).strict(),OL={recipients:m.array(E).default([]),executors:m.array(E).default([]),custodyRevision:m.number().int().positive().nullable().default(null)},oDe=m.object({...Ja,kind:m.literal("variable"),data:m.object({...OL,bytes:m.number().int().nonnegative()})}),iDe=m.object({...Ja,kind:m.literal("connection"),data:m.object({...OL,methodId:m.string(),fields:m.record(m.string(),m.string()).default({}),settings:m.array(m.object({name:m.string(),label:m.string(),value:m.string()})).default([]),methodName:m.string(),methodKind:kL,services:m.array(m.object({id:m.string(),name:fe})).default([]),account:m.string(),accountId:m.string().nullable().default(null),accountVerified:m.boolean().default(!1),scopes:m.array(m.string()),scopesStatus:m.enum(["unknown","requested","reported"]).default("unknown"),outputs:m.array(m.string()),state:m.enum(["ready","reconnect","review","disconnecting","uncertain"]),appId:E.nullable(),generation:E.optional(),authorizationDigest:m.string().optional(),aws:JE.optional(),ovh:Cy.optional()})}),sDe=m.object({...Ja,kind:m.literal("service"),data:QOe}),aDe=m.object({...Ja,kind:m.literal("method"),data:nu}),cDe=m.object({...Ja,kind:m.literal("app"),data:m.object({...OL,methodId:m.string(),clientId:m.string(),fields:m.record(m.string(),m.string()).default({}),generation:E.optional()})}),uDe=m.object({...Ja,kind:m.literal("object"),data:m.object({size:m.number().int().nonnegative(),contentType:m.string()})}),lDe=m.object({...Ja,kind:m.literal("environment"),data:K5.extend({executorId:E.optional(),operatorId:E.optional(),driver:m.enum(["attached","managed"]).optional(),capabilities:m.array(m.string()).optional(),isolation:m.enum(["process","container"]).optional(),manifestDigest:m.string().optional(),processes:m.object({workingDirectory:m.string()}).optional(),ssh:rL.optional(),awsPrincipal:m.string().optional(),state:tDe,connected:m.boolean(),deletion:rDe.optional(),startedAt:$e.nullable(),stoppedAt:$e.nullable(),lastActiveAt:$e,error:m.string().nullable()})}),a$=m.object({...Ja,kind:m.literal("function"),data:ei.omit({environmentId:!0,program:!0}).extend({environmentId:E.optional(),program:H5.optional()})}),dDe=m.object({...Ja,kind:m.literal("keyring"),data:m.object({revision:m.number().int().positive(),signature:m.string()})}),br=m.discriminatedUnion("kind",[oDe,iDe,sDe,aDe,cDe,uDe,lDe,a$,dDe]),e_t=m.discriminatedUnion("kind",[m.object({kind:m.literal("service"),name:fe,definition:q5}).strict(),m.object({kind:m.literal("method"),name:fe,definition:nu}).strict(),m.object({kind:m.literal("environment"),name:fe.optional(),options:K5}).strict()]),t_t=m.object({version:m.number().int().positive(),name:fe.optional(),definition:m.union([q5,nu]).optional()}).strict(),Fi=m.object({name:m.string().regex(/^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*)+$/),input:Lt}).strict(),c$=Fi.extend({inputs:m.array(m.object({pointer:m.string(),label:m.string().min(1).max(100),secret:m.boolean().default(!1),multiline:m.boolean().default(!1),site:m.url().optional()}).strict()).max(16).default([])}),QE=m.object({ja:m.string(),en:m.string()}).strict(),DL=c$.extend({title:QE,execution:m.enum(["server","keyholder"]),configure:m.array(m.string()),environment:m.object({required:m.boolean(),reason:QE.nullable()}).strict()}),B5=m.object({to:E.optional(),executionId:E.optional(),message:m.string().max(1e3).default(""),operations:m.array(c$).min(1).max(8).optional(),expiresInMinutes:m.number().int().min(1).max(1440).default(30)}).strict().superRefine((t,e)=>{!!t.executionId==!!t.operations&&e.addIssue({code:"custom",message:"Choose an execution or supply processing definitions."})}),XE=m.object({id:E,name:fe}),Z5=m.discriminatedUnion("kind",[m.object({kind:m.literal("line"),subject:XE,relation:F5,object:XE}),m.object({kind:m.literal("transfer"),item:XE,to:XE})]),u$=m.object({id:E,executionId:E,from:ru.pick({id:!0,name:!0}),to:ru.pick({id:!0,name:!0}).nullable(),message:m.string(),purpose:m.enum(["input","approval"]),state:m.enum(["pending","accepted","declined","cancelled","expired"]),createdAt:$e,expiresAt:$e,url:m.url(),code:m.string().optional(),returnUrl:m.url().nullable(),refreshUrl:m.url().nullable(),canRespond:m.boolean(),canCancel:m.boolean()}),r_t=m.object({id:E,name:fe,publicKey:bn,state:m.enum(["pending","approving","approved"]),principalId:E.nullable(),createdAt:$e,expiresAt:$e}),n_t=m.object({available:m.boolean(),required:m.boolean(),active:m.boolean(),payer:ru.pick({id:!0,name:!0}).nullable()}),o_t=m.object({storageBytes:m.number().nonnegative(),storageLimit:m.number().positive(),computeSeconds:m.number().nonnegative(),computeLimit:m.number().positive(),month:m.string()}),i_t=m.object({id:m.string(),actorId:E.nullable(),action:m.string(),targetId:E.nullable(),createdAt:$e,details:Lt}),s_t=m.object({returnUrl:m.url().optional(),refreshUrl:m.url().optional()}).strict(),Mr=t=>m.object({items:m.array(t),next:m.string().nullable().default(null)}),a_t=m.object({id:E}),c_t=m.object({owner:E}),pDe=m.object({limit:m.coerce.number().int().min(1).max(200).default(100),after:m.string().optional()}),u_t=pDe.extend({object:E.optional(),subject:E.optional()}).refine(t=>!!t.object!=!!t.subject,"Choose the object or the subject of the lines.");var fDe=m.object({email:m.boolean(),environments:m.boolean(),ssh:m.boolean(),objects:m.boolean(),payments:m.boolean()}),l$=m.object({principal:ru.nullable(),credentialId:E.nullable(),wrappedKey:e$.nullable(),requestId:E.nullable(),server:m.object({name:fe}),features:fDe,principals:m.array(ru)}),f_t=m.object({email:m.email().max(254),returnTo:m.string().max(2048).optional(),locale:M5.default("ja"),principalId:E.optional()}).strict(),m_t=m.object({intent:m.enum(["register","authenticate"]),name:fe.optional(),principalId:E.optional(),returnTo:m.string().max(2048).optional()}).strict(),h_t=m.object({challengeId:E,credential:m.json(),publicKey:bn.optional(),existingPublicKey:bn.optional(),wrappedKey:e$.optional()}).strict();var mDe=new TextEncoder,hDe=new TextDecoder,My="ECDH-ES+A256KW",NL="A256GCM",tt=t=>mDe.encode(t),Kn=t=>hDe.decode(t);function Ds(t){let e="";for(let r=0;r<t.length;r+=8192)e+=String.fromCharCode(...t.subarray(r,r+8192));return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function d$(t){return Uint8Array.from(atob(t.replaceAll("-","+").replaceAll("_","/")),e=>e.charCodeAt(0))}async function p$(){let t=await Ty(My,{crv:"P-256",extractable:!0});return{publicKey:bn.parse(await tu(t.publicKey)),privateKey:await tu(t.privateKey)}}async function Xa(t,e,r){if(!e.length||new Set(e.map(n=>n.id)).size!==e.length)throw new Error("Recipients must be distinct and nonempty.");let o=new Iy(t).setProtectedHeader({enc:NL}).setAdditionalAuthenticatedData(tt(r));for(let n of e)o.addRecipient(await Qo(n.publicKey,My)).setUnprotectedHeader({alg:My,kid:n.id});return Ao.parse(await o.encrypt())}async function Po(t,e,r,o){if(t.aad!==Ds(tt(o)))throw new Error("The encrypted content belongs to a different item.");let n=t.recipients.find(a=>a.header.kid===r);if(!n)throw new Error("This principal cannot decrypt the content.");let i=e instanceof CryptoKey?e:await Qo(e,My);return(await hL({...t,recipients:[n]},i,{keyManagementAlgorithms:[My],contentEncryptionAlgorithms:[NL]})).plaintext}async function gDe(t){let e=await crypto.subtle.importKey("raw",new Uint8Array(t),"HKDF",!1,["deriveBits"]);return new Uint8Array(await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:tt("Foundation"),info:tt("passkey encryption key")},e,256))}async function W5(t,e,r){let o=await Ry(t,await gDe(e),{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[NL]});if(o.protectedHeader.sub!==r)throw new Error("The key belongs to a different principal.");return JSON.parse(Kn(o.plaintext))}var Sr=m.string().regex(/^[A-Za-z0-9_-]{43}$/),cr=m.string().min(100).max(4e6),J5=bn.extend({d:m.string().regex(/^[A-Za-z0-9_-]{43}$/)}),Uy=m.object({encryption:J5,signing:J5}).strict(),Kt=m.object({id:E,principalId:E,generation:m.number().int().positive(),previous:Sr.nullable(),encryption:bn,signing:bn}).strict();function C(t){if(t===null||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)||typeof t=="string"&&!/[\uD800-\uDFFF]/u.test(t))return JSON.stringify(t);if(Array.isArray(t))return"["+Array.from(t,C).join(",")+"]";if(t&&typeof t=="object"&&Object.getPrototypeOf(t)===Object.prototype)return"{"+Object.keys(t).sort().map(e=>{if(/[\uD800-\uDFFF]/u.test(e))throw new Error("Use Unicode property names.");return JSON.stringify(e)+":"+C(t[e])}).join(",")+"}";throw new Error("Use finite numbers, Unicode strings, arrays, and plain JSON objects.")}async function $f(t){return RL(bn.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y}),"sha256")}async function Q(t){return Ds(new Uint8Array(await crypto.subtle.digest("SHA-256",tt(C(t)))))}async function Ya(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",tt(C(t))));return"sha256:"+Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}async function m$(){let[t,e]=await Promise.all([p$(),Ty("ES256",{crv:"P-256",extractable:!0})]),r=await tu(e.privateKey);return Uy.parse({encryption:t.privateKey,signing:r})}function f$(t){return bn.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y})}function h$(t,e){return Kt.parse({id:crypto.randomUUID(),principalId:t,generation:1,previous:null,encryption:f$(e.encryption),signing:f$(e.signing)})}async function ir(t,e,r){let o=e instanceof CryptoKey?e:await Qo(e,"ES256");return new Py(tt(C(t))).setProtectedHeader({alg:"ES256",typ:"foundation."+r+"+jws"}).sign(o)}async function Ur(t,e,r,o){if(C(await Ly(e,r,o))!==C(t))throw new Error("The signature does not authorize this content.")}async function Ly(t,e,r){let o=await xL(t,await Qo(bn.parse(e),"ES256"),{algorithms:["ES256"]});if(o.protectedHeader.typ!=="foundation."+r+"+jws"||Object.keys(o.protectedHeader).some(s=>!["alg","typ"].includes(s)))throw new Error("The signature does not authorize this content.");let n=new TextDecoder("utf-8",{fatal:!0}).decode(o.payload),i=JSON.parse(n);if(C(i)!==n)throw new Error("Sign canonical JSON content.");return i}var Ns=m.object({binding:Kt,signature:cr}).strict();async function jy(t,e){if(await zs(t),await $f(e.encryption)!==await $f(t.encryption)||await $f(e.signing)!==await $f(t.signing))throw new Error("The private keys do not match this identity.");return{binding:t,signature:await ir(t,e.signing,"key-binding")}}async function zs(t){let e=Kt.parse(t);if(e.generation===1!=(e.previous===null))throw new Error("Link each replacement key to its preceding binding.");if(await $f(e.encryption)===await $f(e.signing))throw new Error("Use separate encryption and signing keys.");await Qo(e.encryption,"ECDH-ES+A256KW"),await Qo(e.signing,"ES256")}async function g$(t){let{binding:e,signature:r}=Ns.parse(t);return await zs(e),await Ur(e,r,e.signing,"key-binding"),e}var X5=m.object({ownerId:E,name:fe,resourceId:E.optional(),version:m.number().int().positive().optional(),environmentIds:m.array(E).max(32).optional()}).strict(),Y5=X5.extend({value:m.literal("").optional()}),zL=X5.extend({methodId:m.string().min(1).max(200),clientId:m.string().max(1e3),fields:m.record(m.string(),m.string()).optional(),clientSecret:m.literal("").optional()}),Rf=m.object({ownerId:E,name:fe,definition:ei,resourceId:E.optional(),version:m.number().int().positive().optional()}).strict(),y$=m.object({ownerId:E,connectionId:E,environmentId:E}).strict(),Q5=m.object({ownerId:E,connectionId:E,version:m.number().int().positive(),users:m.array(E).max(32),expiresAt:m.iso.datetime().optional()}).strict(),e8=m.object({ownerId:E,methodId:m.string().min(1).max(200),connectionId:E.optional(),name:fe.optional(),appId:E.optional(),redirectUri:m.url().optional(),users:m.array(E).max(32).optional(),scopes:m.array(m.string().min(1).max(1e3)).max(200).optional(),methodDigest:m.string().regex(/^[A-Za-z0-9_-]{43}$/).optional(),clientId:m.string().max(1e3).optional(),fields:m.record(m.string(),m.string()).optional(),clientSecret:m.literal("").optional()}).strict(),Fy=m.object({ownerId:E,environmentId:E.optional(),operation:m.union([m.object({kind:m.literal("http"),request:Za}).strict(),Wa.extend({kind:m.literal("command")}),m.object({kind:m.enum(["http","command"]),programId:E,programDigest:m.string().regex(/^[A-Za-z0-9_-]{43}$/)}).strict()]),save:m.record(m.string(),fe).default({})}).strict().superRefine((t,e)=>{t.environmentId||e.addIssue({code:"custom",path:["environmentId"],message:"Choose an execution environment."})}),v$=m.object({name:Fi.shape.name,title:QE,execution:m.enum(["server","keyholder"]),configure:m.array(m.string()),environment:DL.shape.environment,input:Lt}).strict(),t8=m.object({id:E.optional(),operations:m.array(c$).min(1).max(8),responderId:E.optional(),message:m.string().max(1e3).default(""),expiresInMinutes:m.number().int().min(1).max(1440).default(1440)}).strict(),r8=m.object({values:m.array(Lt).max(8).default([]),configuration:m.array(Lt).max(8).default([]),code:m.string().max(20).optional()}).strict(),If=m.object({index:m.number().int().nonnegative(),invocation:Fi,approval:m.object({id:E,index:m.number().int().nonnegative()}).strict().optional(),continuation:m.object({kind:m.enum(["connection","run"]),id:E}).strict().nullable()}).strict(),Ze=m.object({id:E,actorId:E,ownerId:E,requests:m.array(E),steps:m.array(m.object({index:m.number().int().nonnegative(),name:Fi.shape.name,state:m.enum(["waiting","running","succeeded","failed","uncertain","cancelled"]),runs:m.array(m.object({kind:m.enum(["run","function"]),id:E}).strict())}).strict()),creator:ru.pick({id:!0,name:!0}),operations:m.array(DL),approval:m.object({requestId:E.nullable(),proposal:Z5.nullable()}).strict().nullable(),canContinue:m.boolean(),canCancel:m.boolean(),url:m.url(),code:m.string().optional(),error:m.object({code:m.string(),message:m.string()}).strict().nullable(),index:m.number().int().nonnegative(),state:m.enum(["waiting","running","succeeded","failed","uncertain","cancelled"]),wait:m.enum(["approval","input","execution"]).nullable(),waiting:If.nullable(),results:m.array(yr.nullable()),createdAt:m.iso.datetime(),expiresAt:m.iso.datetime()}).strict(),n8=m.object({id:E,index:m.number().int().nonnegative(),invocation:Fi,continuationId:E.optional()}).strict();var Af=m.url().refine(t=>{let e=new URL(t);return e.origin===t&&!e.username&&!e.password&&(e.protocol==="https:"||e.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(e.hostname))},"Use an HTTPS origin, or HTTP on localhost."),he={value:"03546b17-fa44-409f-b151-8da1a398b324",tokenSet:"7d4b64dd-4546-4acb-8e96-91f864bccea6",clientCredential:"714fc044-2cce-4f3f-a477-281ee64fe632",executionResult:"71eacb19-c2e3-49cb-b7d3-f3f634f5c887"},yDe=m.enum([he.value,he.tokenSet,he.clientCredential,he.executionResult]),i8=t=>t===he.executionResult?14e5:1e6,ue={http:"bdf57b0a-bce9-4a1d-ad62-0ccd73578e7a",command:"85bb00b6-ca1e-478d-94ca-a217f0c73e49",function:"b6b12c71-7a51-4f18-930c-48e6f511a963",connect:"5c0d6e68-61ef-4023-8500-05defca4edf1",refresh:"00bc45aa-7b68-4350-b73e-eda476c6236c",revoke:"832624ed-e6bb-4829-80a4-283f5333ce63"},qy=m.enum([ue.http,ue.command,ue.function,ue.connect,ue.refresh,ue.revoke]);var vDe={[he.value]:[ue.http,ue.command,ue.function],[he.tokenSet]:[ue.http,ue.command,ue.function,ue.refresh,ue.revoke],[he.clientCredential]:[ue.connect,ue.refresh,ue.revoke],[he.executionResult]:[]},ou=t=>vDe[t],s8=t=>ou(t).filter(e=>e===ue.function||e===ue.refresh),ML=t=>t===he.tokenSet,wDe=m.object({id:E,digest:Sr}).strict(),_De=m.object({actor:Kt,executor:Kt,operations:m.array(qy).min(1).max(6),functionDigests:m.array(Sr).max(100).default([]),origins:m.array(Af).max(100).default([]),callerProgram:m.boolean().default(!1),expiresAt:$e}).strict(),bDe=m.object({function:wDe,executor:Kt,operations:m.array(qy).min(1).max(6),expiresAt:$e.nullable()}).strict(),SDe=m.union([_De,bDe]);function Qa(t,e=Date.now()){return t.expiresAt===null||Date.parse(t.expiresAt)>e}function Pf(t){return t.expiresAt===null?1/0:Date.parse(t.expiresAt)}var en=m.object({format:m.literal(2),origin:Af,id:E,ownerId:E,contentType:yDe,revision:m.number().int().positive(),authorities:m.array(Kt).min(1).max(100),readers:m.array(Kt).min(1).max(100),grants:m.array(SDe).max(100),observers:m.array(E).max(100).optional(),producers:m.array(m.object({executor:Kt,runId:E,expiresAt:$e,materialRevision:m.number().int().positive().default(1)}).strict()).max(100).default([])}).strict(),o8=m.object({ownerId:E,authorities:m.array(Kt).min(1).max(100)}).strict(),a8=m.object({origin:Af,id:E,revision:m.number().int().positive(),from:o8,to:o8,policyDigest:Sr,previous:Sr.nullable(),signerId:E}).strict(),xDe=a8.extend({signature:cr}),UL=m.array(xDe).max(16),Vy=m.object({policy:en,authorityId:E,signature:cr,lineage:UL.optional()}).strict(),tn=m.object({policy:en,authorityId:E,authorization:cr,lineage:UL.optional(),materialRevision:m.number().int().positive(),updatedAt:$e,creationRunId:E.nullable(),metadata:Lt,sealed:Ao,signerId:E,signature:cr}).strict(),sd=t=>({ownerId:t.ownerId,authorities:t.authorities});async function c8(t,e=[]){let r;for(let o of e){let{signature:n,...i}=o;if(o.origin!==t.origin||o.id!==t.id||o.revision>t.revision||r&&(o.revision<=r.revision||C(r.to)!==C(o.from))||o.previous!==(r?await Q(r):null))throw new Error("Keep the signed chain of authority changes for this item.");let s=o.from.authorities.find(a=>a.id===o.signerId);if(!s)throw new Error("Only an existing authority can hand over this item.");await Ur(i,n,s.signing,"authority-handoff"),r=o}if(r&&C(r.to)!==C(sd(t)))throw new Error("Use the authorities approved by the latest handoff.")}function LL(t){let e=t.policy.authorities.find(n=>n.id===t.authorityId);if(e)return e;let r=t.lineage?.at(-1),o=r?.revision===t.policy.revision?r.from.authorities.find(n=>n.id===t.authorityId):void 0;if(!o||o.id!==r?.signerId)throw new Error("The policy must be signed by an approved authority.");return o}function w$(t,e){if(t.id!==e.policy.id||t.origin!==e.policy.origin||t.contentType!==e.policy.contentType)return!1;let r=C(sd(t));return r===C(sd(e.policy))?!0:!!e.lineage?.some(o=>o.revision>t.revision&&C(o.from)===r)}async function u8(t,e,r,o){let n=[...t?.lineage??[]];if(t&&C(sd(t.policy))!==C(sd(e))){if(await ko(t),!t.policy.authorities.some(s=>C(s)===C(r))||t.policy.id!==e.id||t.policy.origin!==e.origin||t.policy.contentType!==e.contentType||e.revision!==t.policy.revision+1)throw new Error("An existing authority must approve this handoff at the next policy revision.");let i=a8.parse({origin:e.origin,id:e.id,revision:e.revision,from:sd(t.policy),to:sd(e),policyDigest:await Q(e),previous:n.length?await Q(n.at(-1)):null,signerId:r.id});n.push({...i,signature:await ir(i,o.signing,"authority-handoff")})}return n.length?{lineage:UL.parse(n)}:{}}async function _$(t){let e=en.parse(t),r=[...e.authorities,...e.readers,...e.grants.flatMap(n=>"actor"in n?[n.actor,n.executor]:[n.executor]),...e.producers.map(n=>n.executor)],o=new Map;for(let n of r){await zs(n);let i=C(n);if(o.has(n.id)&&o.get(n.id)!==i)throw new Error("Each key binding must identify the same keys throughout a policy.");o.set(n.id,i)}for(let n of[e.readers,e.authorities])if(new Set(n.map(i=>i.id)).size!==n.length)throw new Error("Choose distinct key bindings.");for(let n of e.authorities)if(!e.readers.some(i=>i.id===n.id))throw new Error("A policy authority must be able to open its content.");for(let n of e.grants){if(new Set(n.operations).size!==n.operations.length||n.operations.some(i=>!ou(e.contentType).includes(i)))throw new Error("Grant only the operations this kind of content supports.");if("function"in n){if(n.operations.some(i=>i!==ue.function&&i!==ue.refresh))throw new Error("Function grants authorize the saved function and its credential renewal.");continue}if(n.operations.some(i=>i===ue.http||i===ue.command)&&!n.callerProgram)throw new Error("Explicitly authorize caller-supplied programs before allowing arbitrary execution.");if(n.operations.includes(ue.function)&&!n.functionDigests.length&&!n.callerProgram)throw new Error("Choose the exact functions this grant authorizes.")}return e}function b$(t){return[...new Map([...t.readers,...t.grants.map(e=>e.executor)].map(e=>[e.id,e])).values()]}async function iu(t,e){return C({purpose:"resource",policyDigest:await Q(t),materialRevision:e})}async function ad(t,e,r,o,n,i,s){if(t.byteLength>i8(e.contentType))throw new Error("The content exceeds its storage limit.");let a=await _$(e),c=await u8(s,a,o,n);if(!a.authorities.some(p=>C(p)===C(o))&&c.lineage?.at(-1)?.revision!==a.revision)throw new Error("Only a policy authority can replace its content.");let u=await Xa(t,b$(a).map(p=>({id:p.id,publicKey:p.encryption})),await iu(a,r)),l={policy:a,...c,authorityId:o.id,authorization:await ir(a,n.signing,"access-policy"),materialRevision:r,updatedAt:new Date().toISOString(),creationRunId:null,metadata:i??(a.contentType===he.value?{bytes:t.byteLength}:{}),sealed:u,signerId:o.id},d=tn.parse({...l,signature:await ir(l,n.signing,"resource")});return await ko(d),d}async function ko(t){let e=tn.parse(t),{signature:r,...o}=e;await _$(e.policy),await c8(e.policy,e.lineage);let n=LL(e),i=e.lineage?.at(-1);if(i?.revision===e.policy.revision&&i.policyDigest!==await Q(e.policy))throw new Error("The handoff approves a different access policy.");await Ur(e.policy,e.authorization,n.signing,"access-policy");let s=(e.signerId===n.id?n:void 0)??e.policy.authorities.find(u=>u.id===e.signerId)??e.policy.producers.find(u=>u.executor.id===e.signerId&&u.runId===e.creationRunId&&u.materialRevision===e.materialRevision&&(e.policy.contentType===he.executionResult||Date.parse(u.expiresAt)>Date.parse(e.updatedAt)))?.executor??(ML(e.policy.contentType)?e.policy.grants.find(u=>u.executor.id===e.signerId&&u.operations.includes(ue.refresh)&&Qa(u,Date.parse(e.updatedAt)))?.executor:void 0);if(!s||Date.parse(e.updatedAt)>Date.now()+3e4)throw new Error("The signer cannot replace this content.");await Ur(o,r,s.signing,"resource");let a=b$(e.policy).map(u=>u.id).sort(),c=e.sealed.recipients.map(u=>u.header.kid).sort();if(C(a)!==C(c)||e.sealed.aad!==Ds(tt(await iu(e.policy,e.materialRevision))))throw new Error("Encrypt content for exactly the recipients authorized by its policy.");return e}async function l8(t,e,r,o,n=t.metadata){let i=await ko(t);if(!ML(i.policy.contentType)||!(i.policy.authorities.some(p=>C(p)===C(r))||i.policy.grants.some(p=>C(p.executor)===C(r)&&p.operations.includes(ue.refresh)&&Qa(p))))throw new Error("This executor cannot renew this connection.");if(e.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let s=i.materialRevision+1,a=await Xa(e,b$(i.policy).map(p=>({id:p.id,publicKey:p.encryption})),await iu(i.policy,s)),{signature:c,...u}=i,l={...u,materialRevision:s,updatedAt:new Date().toISOString(),metadata:n,sealed:a,signerId:r.id},d={...l,signature:await ir(l,o.signing,"resource")};return await ko(d),d}async function S$(t,e,r,o){let n=await _$(t);if(!n.authorities.some(s=>C(s)===C(e)))throw new Error("Only an authority can approve this policy.");let i={policy:n,...await u8(o,n,e,r),authorityId:e.id,signature:await ir(n,r.signing,"access-policy")};return await su(i),i}async function su(t){let e=Vy.parse(t);await _$(e.policy),await c8(e.policy,e.lineage);let r=e.lineage?.at(-1);if(r?.revision===e.policy.revision&&r.policyDigest!==await Q(e.policy))throw new Error("The handoff approves a different access policy.");let o=e.policy.authorities.find(n=>n.id===e.authorityId);if(!o)throw new Error("The policy must be signed by an authority.");return await Ur(e.policy,e.signature,o.signing,"access-policy"),e}async function Gy(t,e,r,o,n,i){let s=await su(e),{policy:a}=s,c=a.producers.find(p=>p.runId===r&&C(p.executor)===C(o)&&(a.contentType===he.executionResult||Date.parse(p.expiresAt)>Date.now()));if(!c)throw new Error("Approve this execution before storing its output.");if(t.byteLength>i8(a.contentType))throw new Error("The content exceeds its storage limit.");let u=await Xa(t,b$(a).map(p=>({id:p.id,publicKey:p.encryption})),await iu(a,c.materialRevision)),l={policy:a,...s.lineage?{lineage:s.lineage}:{},authorityId:s.authorityId,authorization:s.signature,materialRevision:c.materialRevision,updatedAt:new Date().toISOString(),creationRunId:r,metadata:i,sealed:u,signerId:o.id},d={...l,signature:await ir(l,n.signing,"resource")};return await ko(d),d}async function cd(t,e,r){let o=await ko(t);if(!o.policy.readers.some(n=>C(n)===C(e)))throw new Error("This identity cannot reveal the content.");return Po(o.sealed,r,e.id,await iu(o.policy,o.materialRevision))}var EDe=m.object({id:E,policyDigest:Sr,materialRevision:m.number().int().positive(),authorizationDigest:Sr.optional()}).strict();async function jL(t,e){return e.id===t.policy.id&&e.policyDigest===await Q(t.policy)&&(e.authorizationDigest===void 0||e.authorizationDigest===t.metadata.authorizationDigest)&&(e.materialRevision===t.materialRevision||ML(t.policy.contentType)&&e.authorizationDigest!==void 0&&e.authorizationDigest===t.metadata.authorizationDigest&&t.materialRevision>=e.materialRevision)}var x$=m.object({format:m.literal(2),id:E,origin:Af,ownerId:E,approval:m.object({id:E,index:m.number().int().min(0).max(7)}).strict().optional(),operationContext:n8.optional(),actor:Kt,environmentId:E,executor:Kt,environmentDigest:Sr,operation:qy,functionDigest:Sr.nullable(),functionId:E.optional(),operationDigest:Sr,sources:m.array(EDe).max(100),resultRecipients:m.array(Kt).min(1).max(100),resultApproval:Vy.optional(),createdAt:$e,expiresAt:$e}).strict(),kf=m.object({intent:x$,signature:cr,sealed:Ao}).strict();async function ud(t,e){return C({purpose:"run-"+e,origin:t.origin,id:t.id,intentDigest:await Q(t)})}async function d8(t,e,r){if(x$.parse(t),await Q(e)!==t.operationDigest)throw new Error("The operation does not match the execution intent.");let o={intent:t,sealed:await Xa(tt(C(e)),[{id:t.executor.id,publicKey:t.executor.encryption}],await ud(t,"input"))};return kf.parse({...o,signature:await ir(o,r.signing,"run")})}async function $De(t,e=Date.now()){let r=kf.parse(t),{signature:o,...n}=r;await Ur(n,o,r.intent.actor.signing,"run");let{intent:i}=r,s=Date.parse(i.createdAt),a=Date.parse(i.expiresAt);if(s>e+3e4||a<=e||a<=s||a-s>864e5)throw new Error("Use an execution intent valid for at most 24 hours.");if(new Set(i.sources.map(c=>c.id)).size!==i.sources.length||new Set(i.resultRecipients.map(c=>c.id)).size!==i.resultRecipients.length)throw new Error("Choose distinct inputs and result recipients.");if(i.resultApproval){let c=await su(i.resultApproval),u=c.policy;if(c.authorityId!==i.actor.id||u.id!==i.id||u.origin!==i.origin||u.ownerId!==i.ownerId||u.contentType!==he.executionResult||u.revision!==1||u.grants.length||!u.authorities.some(l=>C(l)===C(i.actor))||C(u.readers)!==C(i.resultRecipients)||u.producers.length!==1||u.producers[0].runId!==i.id||C(u.producers[0].executor)!==C(i.executor)||u.producers[0].materialRevision!==1)throw new Error("Approve this execution result for its readers and selected executor.")}if(r.sealed.recipients.length!==1||r.sealed.recipients[0].header.kid!==i.executor.id||r.sealed.aad!==Ds(tt(await ud(i,"input"))))throw new Error("Encrypt this operation for its selected executor.");return r}async function p8(t,e,r){let o=await $De(t);if(C(o.intent.executor)!==C(e))throw new Error("This operation belongs to another executor.");let n=await Po(o.sealed,r.encryption,e.id,await ud(o.intent,"input")),i=new TextDecoder("utf-8",{fatal:!0}).decode(n),s=JSON.parse(i);if(C(s)!==i||await Q(s)!==o.intent.operationDigest)throw new Error("The decrypted operation does not match its signed intent.");return{intent:o.intent,operation:s}}async function ld(t,e,r={}){let o=await ko(t),n=o.policy,i=e.sources.find(c=>c.id===n.id);if(!i||e.origin!==n.origin||!await jL(o,i))throw new Error("The input changed after this execution was authorized.");if(C(e.actor)===C(e.executor)&&n.readers.some(c=>C(c)===C(e.actor)))return o;if(!n.grants.filter(c=>("actor"in c?C(c.actor)===C(e.actor):c.function.id===e.functionId&&c.function.digest===e.functionDigest)&&C(c.executor)===C(e.executor)&&c.operations.includes(e.operation)&&Qa(c,r.now)&&Pf(c)>=Date.parse(e.expiresAt)).some(c=>"function"in c?e.operation===ue.function||e.operation===ue.refresh:e.operation===ue.function&&!c.callerProgram&&(!e.functionDigest||!c.functionDigests.includes(e.functionDigest))||c.origins.length&&(!r.destination||!c.origins.includes(new URL(r.destination).origin))?!1:e.operation!==ue.command&&e.operation!==ue.http||c.callerProgram))throw new Error("This identity cannot use this input on the selected executor.");return o}async function au(t,e,r,o={}){return await ld(t,e,o),Po(t.sealed,r.encryption,e.executor.id,await iu(t.policy,t.materialRevision))}var dd=3,FL=m.string().regex(/^arn:aws[a-z-]*:iam::\d{12}:(?:role|user)\/(?:[\x21-\x7e]{1,510}\/)?[\w+=,.@-]{1,64}$/),f8=m.object({format:m.literal(3),id:E,origin:Af,ownerId:E,name:fe,executor:Kt,operatorId:E,driver:m.enum(["attached","managed"]),capabilities:m.array(qy).min(1).max(6),functionVersion:m.number().int().positive().optional(),resultVersion:m.literal(1).optional(),isolation:m.enum(["process","container"]),commandImage:m.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/).optional(),awsPrincipal:FL.optional(),revision:m.number().int().positive()}).strict(),qL=m.object({manifest:f8,signature:cr}).strict();async function VL(t,e){let r=f8.parse(t),o={manifest:r,signature:await ir(r,e.signing,"environment")};return await Cf(o),o}async function Cf(t){let e=qL.parse(t),{manifest:r}=e;if(await zs(r.executor),new Set(r.capabilities).size!==r.capabilities.length)throw new Error("Choose distinct execution capabilities.");if(r.capabilities.includes(ue.command)&&r.isolation==="container"&&!r.commandImage)throw new Error("Choose the container image used for commands.");if(r.driver==="managed"&&r.capabilities.includes(ue.command)&&r.isolation!=="container")throw new Error("Managed commands require container isolation.");return await Ur(r,e.signature,r.executor.signing,"environment"),e}async function Of(t,e){let{manifest:r}=await Cf(t);if(e.environmentId!==r.id||e.origin!==r.origin||e.environmentDigest!==await Q(r)||C(e.executor)!==C(r.executor)||!r.capabilities.includes(e.operation)||e.operation===ue.function&&r.functionVersion!==dd)throw new Error("This environment does not authorize the requested execution.")}var E$=m.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),$$=m.object({ok:m.boolean(),result:yr.nullable(),error:m.object({code:m.string().max(100),message:m.string().max(1e3)}).nullable()}).strict(),m8={id:E,intentDigest:Sr,executorId:E,state:m.enum(["succeeded","failed","cancelled","uncertain"]),finishedAt:$e},h8=m.object({...m8,sealed:Ao,signature:cr}).strict(),g8=m.object({...m8,format:m.literal(2),accessDigest:Sr,proofDigest:Sr,approval:Vy,content:tn,previousDigest:Sr.optional(),previous:h8.optional(),signature:cr}).strict(),Hy=m.union([h8,g8]),RDe=m.object({result:$$,proof:cr}).strict(),y8=t=>{let{signature:e,content:r,approval:o,previous:n,...i}=t;return i};async function GL(t,e,r,o,n,i){await su(n);let s={format:2,id:t.id,intentDigest:await Q(t),executorId:t.executor.id,state:e,finishedAt:i?.finishedAt??new Date().toISOString(),accessDigest:await Q(n),...i?{previousDigest:await Q(i)}:{}},a=await ir({...s,resultDigest:await Q(r)},o.signing,"execution-result"),c=tt(C({result:$$.parse(r),proof:a}));if(c.byteLength>14e5)throw new Tf;let u=await Gy(c,n,t.id,t.executor,o,{bytes:c.byteLength}),l={...s,proofDigest:await Q(a)},d=g8.parse({...l,approval:n,content:u,...i?{previous:i}:{},signature:await ir(l,o.signing,"receipt")});return await HL(d,t),d}var Tf=class extends Error{constructor(){super("The encoded execution result exceeds 1,400,000 bytes.")}};async function Df(t,e,r,o){let n=$$.parse(r);if(e==="succeeded"!==n.ok)throw new Error("The result must match its completion state.");if(t.resultApproval)return GL(t,e,n,o,t.resultApproval);let i=tt(C(n));if(i.byteLength>14e5)throw new Tf;let s=await Xa(i,t.resultRecipients.map(c=>({id:c.id,publicKey:c.encryption})),await ud(t,"result")),a={id:t.id,intentDigest:await Q(t),executorId:t.executor.id,state:e,finishedAt:new Date().toISOString(),sealed:s};return Hy.parse({...a,signature:await ir(a,o.signing,"receipt")})}async function HL(t,e){let r=Hy.parse(t);if("content"in r){await Ur(y8(r),r.signature,e.executor.signing,"receipt");let i=await su(r.approval),s=i.policy;if(r.id!==e.id||r.intentDigest!==await Q(e)||r.executorId!==e.executor.id||r.accessDigest!==await Q(i)||i.authorityId!==e.actor.id||!s.authorities.some(a=>C(a)===C(e.actor))||s.id!==e.id||s.origin!==e.origin||s.ownerId!==e.ownerId||s.contentType!==he.executionResult||s.grants.length||e.resultApproval&&C(e.resultApproval)!==C(i))throw new Error("The result does not belong to the requested execution.");if(!e.resultApproval||r.previous){if(!r.previous||r.previousDigest!==await Q(r.previous))throw new Error("Keep the original execution receipt when sharing a legacy result.");if(await HL(r.previous,e),r.state!==r.previous.state||r.finishedAt!==r.previous.finishedAt)throw new Error("Keep the original execution outcome when sharing its result.")}else if(r.previousDigest)throw new Error("Provide the original receipt for its signed digest.");if(await ko(r.content),!w$(s,r.content)||r.content.policy.revision<s.revision||r.content.policy.grants.length)throw new Error("An existing authority must approve sharing this result.");return r}if(e.resultApproval)throw new Error("Return the protected result approved by this execution.");let{signature:o,...n}=r;if(await Ur(n,o,e.executor.signing,"receipt"),r.id!==e.id||r.intentDigest!==await Q(e)||r.executorId!==e.executor.id||r.sealed.aad!==Ds(tt(await ud(e,"result")))||C(r.sealed.recipients.map(i=>i.header.kid).sort())!==C(e.resultRecipients.map(i=>i.id).sort()))throw new Error("The result does not belong to the requested execution.");return r}async function v8(t,e,r,o){if(await HL(t,e),"content"in t){if(!t.content.policy.readers.some(l=>l.id===r))throw new Error("This principal cannot decrypt the result.");let s=await Po(t.content.sealed,o.encryption,r,await iu(t.content.policy,t.content.materialRevision)),a=RDe.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s)));if(await Q(a.proof)!==t.proofDigest)throw new Error("The result proof does not belong to this receipt.");let{proofDigest:c,...u}=y8(t);if(await Ur({...u,resultDigest:await Q(a.result)},a.proof,e.executor.signing,"execution-result"),t.state==="succeeded"!==a.result.ok)throw new Error("The result does not match its completion state.");return a.result}let n=await Po(t.sealed,o.encryption,r,await ud(e,"result")),i=$$.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n)));if(t.state==="succeeded"!==i.ok)throw new Error("The encrypted result does not match its completion state.");return i}var IDe=m.enum(["http","command","function","connect","refresh","revoke"]),Bn=m.object({id:E,ownerId:E,actorId:E,environmentId:E,kind:IDe,state:E$,intent:x$,requestSignature:cr,receipt:Hy.nullable(),error:m.string().nullable(),createdAt:$e,startedAt:$e.nullable(),finishedAt:$e.nullable()}).strict(),R$=m.object({name:fe,approval:Vy}).strict(),w8=m.object({kind:m.literal("function"),functionId:E,definition:ei,arguments:Lt.default({}),outputs:m.record(m.string(),R$).default({})}).strict(),ec=m.discriminatedUnion("kind",[m.object({kind:m.literal("http"),request:Za,save:m.record(m.string(),R$).default({})}).strict(),m.object({kind:m.literal("command"),...Wa.shape}).strict(),m.object({kind:m.enum(["connect","refresh","revoke"]),input:yr}).strict()]);var cu=class extends Error{constructor(r,o,n){super(n);this.code=r;this.status=o}code;status},tc=class{constructor(e){this.identity=e}identity;async response(e,r={}){if(!e.startsWith("/api/")||e.includes("\\")||/[\u0000-\u001f]/.test(e))throw new Error("Use a path beginning with /api/.");let o=new URL(e,this.identity.origin);if(o.origin!==this.identity.origin)throw new Error("Use a path on the configured Foundation origin.");let n;try{n=await fetch(o,{method:r.method??"GET",headers:{authorization:"Bearer "+this.identity.token,...r.raw?{"content-type":"application/octet-stream"}:r.body!==void 0?{"content-type":"application/json"}:{}},body:r.raw?new Uint8Array(r.raw):r.body!==void 0?JSON.stringify(r.body):void 0,redirect:"error",signal:AbortSignal.any([AbortSignal.timeout(9e4),...r.signal?[r.signal]:[]])})}catch{throw new Error("Could not reach Foundation. Check the origin and your network connection.")}if(!n.ok){let i;try{i=m.object({error:m.object({code:m.string(),message:m.string()})}).parse(await n.json())}catch{throw new cu("http_error",n.status,"Foundation returned HTTP "+n.status+".")}throw new cu(i.error.code,n.status,i.error.message)}return n}async json(e,r={},o){let n=await this.response(e,r),i=n.status===204?null:await n.json();return o?o.parse(i):i}async session(){return this.json("/api/session",{},l$)}};import{chmod as ADe,lstat as PDe,mkdir as kDe,open as KL,readFile as b8,rename as TDe,rm as CDe}from"node:fs/promises";import{dirname as ODe,join as BL,resolve as DDe}from"node:path";import{homedir as NDe}from"node:os";import{randomUUID as zDe}from"node:crypto";var ZL=m.object({origin:m.url(),principalId:m.uuid(),token:m.string().min(20),keys:Uy.nullable(),binding:Kt.nullable()}).strict().refine(t=>!!t.keys==!!t.binding&&(!t.binding||t.binding.principalId===t.principalId),"Use the keys bound to this identity."),S8=m.object({current:m.uuid(),identities:m.array(ZL).min(1)}).strict().refine(t=>t.identities.some(e=>e.principalId===t.current),"The current identity is missing.");function rc(){return BL(process.env.XDG_CONFIG_HOME||BL(NDe(),".config"),"foundation","identity.json")}function uu(t=process.env.FOUNDATION_ORIGIN||"https://foundationsystems.app"){let e;try{e=new URL(t)}catch{throw new Error("Set FOUNDATION_ORIGIN to an HTTPS origin.")}if(e.username||e.password||e.pathname!=="/"||e.search||e.hash||e.protocol!=="https:"&&!(e.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(e.hostname)))throw new Error("Use an HTTPS origin, or HTTP on localhost.");return e.origin}async function I$(t){let e;try{let n=rc(),i=await PDe(n);if(!i.isFile()||i.isSymbolicLink())throw new Error("The identity must be a regular file.");process.platform!=="win32"&&i.mode&63&&await ADe(n,384);let s=S8.parse(JSON.parse(await b8(n,"utf8")));e=s.identities.find(a=>a.principalId===s.current)}catch(n){if(!(n instanceof Error&&"code"in n&&n.code==="ENOENT"))throw new Error("The saved identity could not be read. Check its contents and permissions.")}let r=uu(t||process.env.FOUNDATION_ORIGIN||e?.origin),o=process.env.FOUNDATION_TOKEN;if(o){if(t&&process.env.FOUNDATION_ORIGIN&&r!==uu(process.env.FOUNDATION_ORIGIN))throw new Error("The environment identity belongs to a different origin.");let n=process.env.FOUNDATION_PRINCIPAL_ID,i=process.env.FOUNDATION_PRIVATE_KEYS,s=process.env.FOUNDATION_KEY_BINDING;if(!n)throw new Error("FOUNDATION_TOKEN requires FOUNDATION_PRINCIPAL_ID.");try{return ZL.parse({origin:r,principalId:n,token:o,keys:i?JSON.parse(Buffer.from(i,"base64url").toString("utf8")):null,binding:s?JSON.parse(Buffer.from(s,"base64url").toString("utf8")):null})}catch{throw new Error("The Foundation environment identity is invalid.")}}if(!e)throw new Error("Run foundation login to sign in on this machine.");if(r!==uu(e.origin))throw new Error("This identity belongs to another origin. Use a separate XDG_CONFIG_HOME to initialize another server.");return{...e,origin:r}}async function Ky(t){let e=rc(),r;try{r=S8.parse(JSON.parse(await b8(e,"utf8")))}catch(i){if(!(i instanceof Error&&"code"in i&&i.code==="ENOENT"))throw new Error("The saved identity could not be read. Check its contents and permissions.")}let o=ZL.parse(t),n=(r?.identities??[]).filter(i=>!(i.origin===o.origin&&i.principalId===o.principalId));await Nf(e,JSON.stringify({current:o.principalId,identities:[...n,o]},null,2)+`
128
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of t.seen.entries()){let a=s[1];if(e===s[0]){i(s);continue}if(t.external){let u=t.external.registry.get(s[0])?.id;if(e!==s[0]&&u){i(s);continue}}if(t.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}a.count>1&&t.reused==="ref"&&i(s)}t.external&&(t.sharedDefsExtractedFor=t.external)}function mZ(t){let e=t.anyOf;if(!Array.isArray(e)||e.length===0||t.type!==void 0)return;let r=[];for(let o of e){if(!o||typeof o!="object")return;mZ(o);let n=Object.keys(o);if(n.length!==1||n[0]!=="type")return;let i=o.type;for(let s of Array.isArray(i)?i:[i]){if(typeof s!="string")return;r.includes(s)||r.push(s)}}delete t.anyOf,t.type=r.length===1?r[0]:r}var hZ=new Set(["type","properties","required","additionalProperties"]),pZ=["oneOf","anyOf"];function fZ(t){let e=t.additionalProperties;return e===void 0||e===!1||typeof e!="object"||e===null?null:Object.keys(e).length?e:null}function lM(t){let e=[];for(let i of t){if(typeof i!="object"||i.type!=="object")return null;for(let s in i)if(!hZ.has(s))return null;e.push(i)}let r={},o=new Set;for(let i of e){for(let s in i.properties){if(Object.prototype.hasOwnProperty.call(r,s))continue;let a=[];for(let u of e){let l=u.properties?.[s]??fZ(u);l!=null&&(a.some(d=>JSON.stringify(d)===JSON.stringify(l))||a.push(l))}let c=a.length===1?a[0]:lM(a)??{allOf:a};Wr(r,s,c)}for(let s of i.required??[])o.add(s)}let n={type:"object",properties:r};if(o.size&&(n.required=[...o]),e.every(i=>i.additionalProperties===!1))n.additionalProperties=!1;else{let i=[];for(let s of e){let a=fZ(s);a&&!i.some(c=>JSON.stringify(c)===JSON.stringify(a))&&i.push(a)}i.length===1?n.additionalProperties=i[0]:i.length>1&&(n.additionalProperties={allOf:i})}return n}function LCe(t){let e=t.allOf;if(!Array.isArray(e)||e.length<2)return;for(let n of hZ)if(n in t)return;let r=e.filter(n=>pZ.some(i=>Array.isArray(n[i]))),o=null;if(!r.length)o=lM(e);else{let n=r[0],i=pZ.find(c=>Array.isArray(n[c]));if(Object.keys(n).length!==1)return;let s=e.filter(c=>c!==n),a=n[i].map(c=>lM([...s,c]));if(a.some(c=>!c))return;o={[i]:a}}o&&(delete t.allOf,iy(t,o))}function Kc(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},d=c.ref;if(c.ref=null,d){o(d);let f=t.seen.get(d),h=f.schema;if(h.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(h)):iy(u,h),iy(u,l),a._zod.parent===d)for(let w in u)w==="$ref"||w==="allOf"||w in l||delete u[w];if(h.$ref&&f.def)for(let w in u)w==="$ref"||w==="allOf"||w in f.def&&JSON.stringify(u[w])===JSON.stringify(f.def[w])&&delete u[w]}let p=a._zod.parent;if(p&&p!==d){o(p);let f=t.seen.get(p);if(f?.schema.$ref&&(u.$ref=f.schema.$ref,f.def))for(let h in u)h==="$ref"||h==="allOf"||h in f.def&&JSON.stringify(u[h])===JSON.stringify(f.def[h])&&delete u[h]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};if(!t.external||t.sharedEmitDoneFor!==t.external){for(let a of[...t.seen.entries()].reverse())o(a[0]);if(t.target!=="openapi-3.0")for(let a of t.seen.entries())mZ(a[1].def??a[1].schema);for(let a of t.deferred)a();if(t.intersections.length){let a=new Map;for(let c of t.seen.values())for(let u of[c.schema,c.def]){let l=u?.allOf;if(!Array.isArray(l))continue;let d=a.get(l);d?d.push(u):a.set(l,[u])}for(let c of t.intersections)for(let u of a.get(c)??[])LCe(u)}}let n={};if(t.target==="draft-2020-12"?n.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?n.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?n.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");n.$id=t.external.uri(a)}iy(n,r.defId?r.schema:r.def??r.schema);let i=t.metadataRegistry.get(e)?.id;i!==void 0&&n.id===i&&delete n.id;let s=t.external?.defs??{};if(!t.external||t.sharedEmitDoneFor!==t.external)for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,Wr(s,c.defId,c.def))}t.external&&(t.sharedEmitDoneFor=t.external),t.external||Object.keys(s).length>0&&(t.target==="draft-2020-12"?n.$defs=s:n.definitions=s);try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:nf(e,"input",t.processors),output:nf(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Vn(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return Vn(o.element,r);if(o.type==="set")return Vn(o.valueType,r);if(o.type==="lazy")return Vn(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault"||o.type==="catch")return Vn(o.innerType,r);if(o.type==="intersection")return Vn(o.left,r)||Vn(o.right,r);if(o.type==="record"||o.type==="map")return Vn(o.keyType,r)||Vn(o.valueType,r);if(o.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Vn(o.in,r)||Vn(o.out,r);if(o.type==="object"){for(let n in o.shape)if(Vn(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(Vn(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(Vn(n,r))return!0;return!!(o.rest&&Vn(o.rest,r))}return!1}var dM=(t,e={})=>r=>{let o=Gc({...r,processors:e});return Rt(t,o),Hc(o,t),Kc(o,t)},nf=(t,e,r={})=>o=>{let{libraryOptions:n,target:i}=o??{},s=Gc({...n??{},target:i,io:e,processors:r});return Rt(t,s),Hc(s,t),Kc(s,t)};var of=(t,e,r)=>{(t[e]===void 0||r>t[e])&&(t[e]=r)},sf=(t,e,r)=>{(t[e]===void 0||r<t[e])&&(t[e]=r)},gZ=(t,e)=>{of(t,"minimum",e),sf(t,"maximum",e)},_Z=(t,e)=>{t.multipleOf??(t.multipleOf=[]),t.multipleOf.includes(e)||t.multipleOf.push(e)},bZ=(t,e)=>{t.patterns??(t.patterns=new Set),t.patterns.add(e)},SZ=(t,e)=>{t.mime=t.mime?t.mime.filter(r=>e.includes(r)):[...e]},xZ=(t,e)=>{t.format=e,e.includes("int")&&(t.isInt=!0)},yZ=(t,e)=>of(t,"minimum",e.minimum),vZ=(t,e)=>sf(t,"maximum",e.maximum),wZ=t=>(e,r)=>{xZ(e,r.format);let[o,n]=t[r.format];of(e,"minimum",o),sf(e,"maximum",n)},jCe={greater_than:(t,e)=>of(t,e.inclusive?"minimum":"exclusiveMinimum",e.value),less_than:(t,e)=>sf(t,e.inclusive?"maximum":"exclusiveMaximum",e.value),multiple_of:(t,e)=>_Z(t,e.value),number_format:wZ(ug),bigint_format:wZ(lg),min_length:yZ,max_length:vZ,length_equals:(t,e)=>gZ(t,e.length),min_size:yZ,max_size:vZ,size_equals:(t,e)=>gZ(t,e.size),string_format:(t,e)=>{xZ(t,e.format),e.pattern&&bZ(t,e.pattern),(e.format==="base64"||e.format==="base64url")&&(t.contentEncoding=e.format),(e.local||e.precision===-1)&&(t.laxFormat=!0)},mime_type:(t,e)=>SZ(t,e.mime)};function kr(t){let e={},r=t._zod.def,o=t._zod.traits.has("$ZodCheck")?[t,...r.checks??[]]:r.checks??[];for(let i of o)jCe[i._zod.def.check]?.(e,i._zod.def);let n=t._zod.bag;n.minimum!==void 0&&of(e,"minimum",n.minimum),n.exclusiveMinimum!==void 0&&of(e,"exclusiveMinimum",n.exclusiveMinimum),n.maximum!==void 0&&sf(e,"maximum",n.maximum),n.exclusiveMaximum!==void 0&&sf(e,"exclusiveMaximum",n.exclusiveMaximum),n.multipleOf!==void 0&&_Z(e,n.multipleOf),n.format!==void 0&&(e.format??(e.format=n.format),n.format.includes("int")&&(e.isInt=!0)),n.mime&&SZ(e,n.mime);for(let i of n.patterns??[])bZ(e,i);return e}var FCe={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},qCe=new Map([[rx,Y1],[Eg,Q1]]),EZ=t=>qCe.get(t)??t,mM=(t,e,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:u,laxFormat:l}=kr(t);if(typeof i=="number"&&(n.minLength=i),typeof s=="number"&&(n.maxLength=s),a&&(n.format=FCe[a]??a,n.format===""&&delete n.format,(a==="time"||l)&&delete n.format),u&&(n.contentEncoding=u),c&&c.size>0){let d=[...c].map(EZ);d.length===1?n.pattern=d[0].source:d.length>1&&(n.allOf=[...d.map(p=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},hM=(t,e,r,o)=>{let n=r,{minimum:i,maximum:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:l}=kr(t);n.type=l?"integer":"number";let d=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),p=typeof c=="number"&&c<=(s??Number.POSITIVE_INFINITY),f=e.target==="draft-04"||e.target==="openapi-3.0";if(d?f?(n.minimum=u,n.exclusiveMinimum=!0):n.exclusiveMinimum=u:typeof i=="number"&&(n.minimum=i),p?f?(n.maximum=c,n.exclusiveMaximum=!0):n.exclusiveMaximum=c:typeof s=="number"&&(n.maximum=s),a){let h=new Set;for(let b of a)Number.isFinite(b)&&b!==0?h.add(Math.abs(b)):Pr(t,e,n,o,`A multipleOf divisor of ${b} cannot be represented in JSON Schema`);let[y,...w]=h;y!==void 0&&(n.multipleOf=y),w.length&&(n.allOf=[...n.allOf??[],...w.map(b=>({multipleOf:b}))])}},gM=(t,e,r,o)=>{r.type="boolean"},yM=(t,e,r,o)=>{Pr(t,e,r,o,"BigInt cannot be represented in JSON Schema")},vM=(t,e,r,o)=>{Pr(t,e,r,o,"Symbols cannot be represented in JSON Schema")},wM=(t,e,r,o)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},_M=(t,e,r,o)=>{Pr(t,e,r,o,"Undefined cannot be represented in JSON Schema")},bM=(t,e,r,o)=>{Pr(t,e,r,o,"Void cannot be represented in JSON Schema")},SM=(t,e,r,o)=>{r.not={}},xM=(t,e,r,o)=>{},EM=(t,e,r,o)=>{},$M=(t,e,r,o)=>{Pr(t,e,r,o,"Date cannot be represented in JSON Schema")},RM=(t,e,r,o)=>{let n=t._zod.def,i=wp(n.entries);if(i.length===0){r.not={};return}i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),r.enum=i},IM=(t,e,r,o)=>{let n=t._zod.def;if(n.values.length===0){r.not={};return}let i=[];for(let s of n.values)if(s===void 0){if(Pr(t,e,r,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s=="bigint"){if(Pr(t,e,r,o,"BigInt literals cannot be represented in JSON Schema"))return;i.push(Number(s))}else i.push(s);if(i.length!==0)if(i.length===1){let s=i[0];r.type=s===null?"null":typeof s,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[s]:r.const=s}else i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),i.every(s=>typeof s=="boolean")&&(r.type="boolean"),i.every(s=>s===null)&&(r.type="null"),r.enum=i},AM=(t,e,r,o)=>{Pr(t,e,r,o,"NaN cannot be represented in JSON Schema")},PM=(t,e,r,o)=>{let n=r,i=t._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");n.type="string",n.pattern=i.source},kM=(t,e,r,o)=>{let n=r;n.type="string",n.format="binary",n.contentEncoding="binary";let{minimum:i,maximum:s,mime:a}=kr(t);i!==void 0&&(n.minLength=i),s!==void 0&&(n.maxLength=s),a&&(a.length===0?n.not={}:a.length===1?n.contentMediaType=a[0]:n.anyOf=a.map(c=>({contentMediaType:c})))},TM=(t,e,r,o)=>{r.type="boolean"},CM=(t,e,r,o)=>{Pr(t,e,r,o,"Custom types cannot be represented in JSON Schema")},OM=(t,e,r,o)=>{Pr(t,e,r,o,"Function types cannot be represented in JSON Schema")},DM=(t,e,r,o)=>{Pr(t,e,r,o,"Transforms cannot be represented in JSON Schema")},NM=(t,e,r,o)=>{Pr(t,e,r,o,"Map cannot be represented in JSON Schema")},zM=(t,e,r,o)=>{Pr(t,e,r,o,"Set cannot be represented in JSON Schema")},MM=(t,e,r,o)=>{let n=r,i=t._zod.def,{minimum:s,maximum:a}=kr(t);typeof s=="number"&&(n.minItems=s),typeof a=="number"&&(n.maxItems=a),n.type="array",n.items=Rt(i.element,e,{...o,path:[...o.path,"items"]})};function sy(t){let e=t._zod.def;return e.type==="pipe"&&e.in._zod.traits.has("$ZodTransform")?sy(e.out):e.type==="catch"?sy(e.innerType):t._zod.optin}var UM=(t,e,r,o)=>{let n=r,i=t._zod.def,s=i.shape;if(Object.getOwnPropertySymbols(s).length&&Pr(t,e,n,o,"Symbol keys cannot be represented in JSON Schema"))return;n.type="object",n.properties={};for(let u in s)Wr(n.properties,u,Rt(s[u],e,{...o,path:[...o.path,"properties",u]}));let c=[];for(let u of Object.keys(s)){let l=i.shape[u];(e.io==="input"?sy(l)===void 0:l._zod.optout===void 0)&&c.push(u)}c.length>0&&(n.required=c),i.catchall?._zod.def.type==="never"?n.additionalProperties=!1:i.catchall?i.catchall&&(n.additionalProperties=Rt(i.catchall,e,{...o,path:[...o.path,"additionalProperties"]})):e.io==="output"&&(n.additionalProperties=!1)},H0=(t,e,r,o)=>{let n=t._zod.def,i=n.inclusive===!1,s=n.options.map((a,c)=>Rt(a,e,{...o,path:[...o.path,i?"oneOf":"anyOf",c]}));i?r.oneOf=s:r.anyOf=s},LM=(t,e,r,o)=>{let n=t._zod.def,i=Rt(n.left,e,{...o,path:[...o.path,"allOf",0]}),s=Rt(n.right,e,{...o,path:[...o.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=c,e.intersections.push(c)},jM=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="array";let s=e.target==="draft-2020-12"?"prefixItems":"items",a=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((y,w)=>Rt(y,e,{...o,path:[...o.path,s,w]})),u=i.rest?Rt(i.rest,e,{...o,path:[...o.path,a,...e.target==="openapi-3.0"?[i.items.length]:[]]}):null,l=i.items.length;for(;l>0;){let y=i.items[l-1];if(!(e.io==="input"?sy(y)!==void 0:y._zod.optout==="optional"))break;l--}let d=i.items.length,p=!i.rest;e.target==="draft-2020-12"?(n.prefixItems=c,p?n.items=!1:u&&(n.items=u),l>0&&(n.minItems=l),p&&(n.maxItems=d)):e.target==="openapi-3.0"?(n.items={anyOf:c},u&&n.items.anyOf.push(u),l>0&&(n.minItems=l),p&&(n.maxItems=d)):(n.items=c,p?n.additionalItems=!1:u&&(n.additionalItems=u),l>0&&(n.minItems=l),p&&(n.maxItems=d));let{minimum:f,maximum:h}=kr(t);typeof f=="number"&&(n.minItems=f),typeof h=="number"&&(n.maxItems=h)};function pM(t,e,r){if(e.$ref){if(r.has(e))return e;r.add(e);let h=t.get(e)?.def;if(!h)return e;let y=pM(t,h,r);return y===h?e:y}for(let h of["anyOf","oneOf"]){let y=e[h];if(!Array.isArray(y))continue;let w=y.map(b=>pM(t,b,r));w.some((b,S)=>b!==y[S])&&(e={...e,[h]:w})}let o=Array.isArray(e.type)?e.type:[e.type],n=!o.includes("string")&&o.some(h=>h==="number"||h==="integer"),i=e.enum??(e.const!==void 0?[e.const]:void 0);if(!n&&!i?.some(h=>typeof h=="number"))return e;let{minimum:s,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:l,format:d,id:p,...f}=e;return f.enum?f.enum=f.enum.map(h=>typeof h=="number"?String(h):h):typeof f.const=="number"&&(f.const=String(f.const)),n&&(f.type="string",i||(f.pattern=(o.includes("number")?Fa:yg).source)),f}var fM=new WeakMap;function VCe(t){let e=new Map;for(let o of t.seen.values())o.def&&!e.has(o.schema)&&e.set(o.schema,o);let r=new Map;for(let o of fM.get(t)??[]){let n=t.seen.get(o),i=(n?.def??n?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let s=pM(e,i,new Set);s!==i&&r.set(i,s)}if(r.size)for(let o of t.seen.values())for(let n of[o.schema,o.def]){let i=n&&r.get(n.propertyNames);i&&(n.propertyNames=i)}}var FM=(t,e,r,o)=>{let n=r,i=t._zod.def;n.type="object";let s=i.keyType,a=kr(s).patterns;if(i.mode==="loose"&&a&&a.size>0){let l=Rt(i.valueType,e,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let d of a)Wr(n.patternProperties,EZ(d).source,l)}else{if(e.target==="draft-07"||e.target==="draft-2020-12"){n.propertyNames=Rt(i.keyType,e,{...o,path:[...o.path,"propertyNames"]});let l=fM.get(e);l||(l=[],fM.set(e,l),e.deferred.push(()=>VCe(e))),l.push(t)}n.additionalProperties=Rt(i.valueType,e,{...o,path:[...o.path,"additionalProperties"]})}let c=s._zod.values,u=e.io==="input"&&sy(i.valueType)!==void 0;if(c&&!i.partial&&!u){let l=[...c].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(n.required=l.map(String))}},qM=(t,e,r,o)=>{let n=t._zod.def,i=Rt(n.innerType,e,o),s=e.seen.get(t);e.target==="openapi-3.0"?(s.ref=n.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},VM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},GM=Symbol();function $Z(t,e,r,o,n){let i=!1,s=JSON.stringify(t,(a,c)=>typeof c!="bigint"?c:(i=!0,null));return i?(Pr(e,r,o,n,"BigInt defaults cannot be represented in JSON Schema"),GM):JSON.parse(s)}var HM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s=$Z(n.defaultValue,t,e,r,o);s!==GM&&(r.default=s)},KM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);if(i.ref=n.innerType,e.io!=="input")return;let s=$Z(n.defaultValue,t,e,r,o);s!==GM&&(r._prefault=s)},BM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{Pr(t,e,r,o,"Dynamic catch values are not supported in JSON Schema");return}r.default=s},ZM=(t,e,r,o)=>{let n=t._zod.def,i=n.in._zod.traits.has("$ZodTransform"),s=e.io==="input"?i?n.out:n.in:n.out;Rt(s,e,o);let a=e.seen.get(t);a.ref=s},WM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType,r.readOnly=!0},JM=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},K0=(t,e,r,o)=>{let n=t._zod.def;Rt(n.innerType,e,o);let i=e.seen.get(t);i.ref=n.innerType},XM=(t,e,r,o)=>{let n=t._zod.innerType;Rt(n,e,o);let i=e.seen.get(t);i.ref=n},G0={string:mM,number:hM,boolean:gM,bigint:yM,symbol:vM,null:wM,undefined:_M,void:bM,never:SM,any:xM,unknown:EM,date:$M,enum:RM,literal:IM,nan:AM,template_literal:PM,file:kM,success:TM,custom:CM,function:OM,transform:DM,map:NM,set:zM,array:MM,object:UM,union:H0,intersection:LM,tuple:jM,record:FM,nullable:qM,nonoptional:VM,default:HM,prefault:KM,catch:BM,pipe:ZM,readonly:WM,promise:JM,optional:K0,lazy:XM};function Zl(t,e){if("_idmap"in t){let o=t,n=Gc({...e,processors:G0}),i={};for(let c of o._idmap.entries()){let[u,l]=c;Rt(l,n)}let s={},a={registry:o,uri:e?.uri,defs:i};n.external=a;for(let c of o._idmap.entries()){let[u,l]=c;Hc(n,l),Wr(s,u,Kc(n,l))}if(Object.keys(i).length>0){let c=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[c]:i}}return{schemas:s}}let r=Gc({...e,processors:G0});return Rt(t,r),Hc(r,t),Kc(r,t)}var B0=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(e){this.ctx.counter=e}get seen(){return this.ctx.seen}constructor(e){let r=e?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=Gc({processors:G0,target:r,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,r={path:[],schemaPath:[]}){return Rt(e,this.ctx,r)}emit(e,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),this.ctx.sharedDefsExtractedFor=void 0,this.ctx.sharedEmitDoneFor=void 0,Hc(this.ctx,e);let o=Kc(this.ctx,e),{"~standard":n,...i}=o;return i}};var RZ={};var mf={};Ht(mf,{ZodAny:()=>gU,ZodArray:()=>_U,ZodBase64:()=>pE,ZodBase64URL:()=>fE,ZodBigInt:()=>pf,ZodBigIntFormat:()=>gE,ZodBoolean:()=>df,ZodCIDRv4:()=>lE,ZodCIDRv6:()=>dE,ZodCUID:()=>nE,ZodCUID2:()=>oE,ZodCatch:()=>LU,ZodCodec:()=>hy,ZodCreditCard:()=>dU,ZodCustom:()=>gy,ZodCustomStringFormat:()=>Jl,ZodDate:()=>ly,ZodDefault:()=>OU,ZodDiscriminatedUnion:()=>SU,ZodE164:()=>mE,ZodEmail:()=>Q0,ZodEmoji:()=>tE,ZodEnum:()=>cf,ZodExactOptional:()=>wE,ZodFile:()=>PU,ZodFunction:()=>WU,ZodGUID:()=>eE,ZodIBAN:()=>pU,ZodIPv4:()=>cE,ZodIPv6:()=>uE,ZodISODate:()=>Zc,ZodISODateTime:()=>Bc,ZodISODuration:()=>Jc,ZodISOTime:()=>Wc,ZodInstanceOf:()=>YU,ZodIntersection:()=>xU,ZodJWT:()=>hE,ZodKSUID:()=>aE,ZodLazy:()=>KU,ZodLiteral:()=>AU,ZodMAC:()=>lU,ZodMap:()=>RU,ZodNaN:()=>FU,ZodNanoID:()=>rE,ZodNever:()=>vU,ZodNonOptional:()=>_E,ZodNull:()=>hU,ZodNullable:()=>CU,ZodNumber:()=>lf,ZodNumberFormat:()=>Xl,ZodObject:()=>dy,ZodOptional:()=>Yl,ZodPipe:()=>my,ZodPrefault:()=>NU,ZodPreprocess:()=>qU,ZodPromise:()=>ZU,ZodReadonly:()=>VU,ZodRecord:()=>af,ZodSet:()=>IU,ZodString:()=>uf,ZodStringFormat:()=>Tt,ZodSuccess:()=>UU,ZodSymbol:()=>fU,ZodTemplateLiteral:()=>HU,ZodTransform:()=>kU,ZodTuple:()=>EU,ZodType:()=>Ce,ZodULID:()=>iE,ZodURL:()=>cy,ZodUUID:()=>Os,ZodUndefined:()=>mU,ZodUnion:()=>py,ZodUnknown:()=>yU,ZodVoid:()=>wU,ZodXID:()=>sE,ZodXor:()=>bU,_ZodString:()=>Y0,_default:()=>DU,_function:()=>DW,any:()=>hW,array:()=>qe,base64:()=>WZ,base64url:()=>JZ,bigint:()=>lW,boolean:()=>yr,catch:()=>jU,check:()=>NW,cidrv4:()=>BZ,cidrv6:()=>ZZ,codec:()=>kW,creditCard:()=>YZ,cuid:()=>LZ,cuid2:()=>jZ,currencyCode:()=>oW,custom:()=>bE,date:()=>yW,describe:()=>zW,discriminatedUnion:()=>fy,e164:()=>XZ,email:()=>PZ,emoji:()=>MZ,enum:()=>Yr,exactOptional:()=>TU,file:()=>RW,float32:()=>sW,float64:()=>aW,function:()=>DW,guid:()=>kZ,hash:()=>iW,hex:()=>nW,hostname:()=>rW,httpUrl:()=>zZ,iban:()=>QZ,instanceof:()=>UW,int:()=>J0,int32:()=>cW,int64:()=>dW,intersection:()=>ff,invertCodec:()=>TW,ipv4:()=>GZ,ipv6:()=>KZ,json:()=>jW,jwt:()=>eW,keyof:()=>vW,ksuid:()=>VZ,lazy:()=>BU,literal:()=>ae,looseObject:()=>Xr,looseRecord:()=>SW,mac:()=>HZ,map:()=>xW,meta:()=>MW,nan:()=>PW,nanoid:()=>UZ,nativeEnum:()=>$W,never:()=>yE,nonoptional:()=>MU,null:()=>uy,nullable:()=>ay,nullish:()=>IW,number:()=>yt,object:()=>X,optional:()=>kt,partialRecord:()=>bW,pipe:()=>X0,prefault:()=>zU,preprocess:()=>yy,promise:()=>OW,readonly:()=>GU,record:()=>Ct,refine:()=>JU,set:()=>EW,strictObject:()=>wW,string:()=>O,stringFormat:()=>tW,stringbool:()=>LW,success:()=>AW,superRefine:()=>XU,symbol:()=>fW,templateLiteral:()=>CW,transform:()=>vE,tuple:()=>$U,uint32:()=>uW,uint64:()=>pW,ulid:()=>FZ,undefined:()=>mW,union:()=>It,unknown:()=>Ut,url:()=>NZ,uuid:()=>TZ,uuidv4:()=>CZ,uuidv6:()=>OZ,uuidv7:()=>DZ,void:()=>gW,xid:()=>qZ,xor:()=>_W});var Z0={};Ht(Z0,{endsWith:()=>Wp,gt:()=>Ts,gte:()=>Ro,includes:()=>Bp,length:()=>Bl,lowercase:()=>Hp,lt:()=>ks,lte:()=>$o,maxLength:()=>Kl,maxSize:()=>qc,mime:()=>Xp,minLength:()=>qa,minSize:()=>Cs,multipleOf:()=>Fc,negative:()=>O0,nonnegative:()=>N0,nonpositive:()=>D0,normalize:()=>Yp,overwrite:()=>Ni,positive:()=>C0,properties:()=>Jp,property:()=>z0,regex:()=>Gp,size:()=>Hl,slugify:()=>rf,startsWith:()=>Zp,toLowerCase:()=>ef,toUpperCase:()=>tf,trim:()=>Qp,uppercase:()=>Kp});var IZ=new WeakSet([Object.prototype,Error.prototype]);function W0(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!1,get(){let o=r(this);return Object.defineProperty(this,e,{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,e,{value:o,configurable:!0,writable:!0})}})}var AZ=(t,e)=>{C1.init(t,e),t.name="ZodError";let r=Object.getPrototypeOf(t);IZ.has(r)||(IZ.add(r),W0(r,"format",o=>n=>hg(o,n)),W0(r,"flatten",o=>n=>mg(o,n)),W0(r,"addIssue",o=>n=>{o.issues.push(n),o.message=JSON.stringify(o.issues,_p,2)}),W0(r,"addIssues",o=>n=>{o.issues.push(...n),o.message=JSON.stringify(o.issues,_p,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},HCe=$("ZodError",AZ),lo=$("ZodError",AZ,void 0,{Parent:Error});var YM=$p(lo),QM=Rp(lo),eU=Ip(lo),tU=Pp(lo),rU=yS(lo),nU=vS(lo),oU=wS(lo),iU=_S(lo),sU=bS(lo),aU=SS(lo),cU=xS(lo),uU=ES(lo);function BCe(){zr.localeError||lr(t0())}function Wl(){zr.memoizer||lr({memoizer:Cg()})}var Ce=$("ZodType",(t,e)=>(BCe(),be.init(t,e),t.def=e,t.type=e.type,t),{check(...t){let e=this.def;return this.clone(D.mergeDefs(e,{checks:[...e.checks??[],...t.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...t){return this.check(...t)},clone(t,e){return gt(this,t,e)},brand(){return this},register(t,e){return t.add(this,e),this},refine(t,e){return this.check(JU(t,e))},superRefine(t,e){return this.check(XU(t,e))},overwrite(t){return this.check(Ni(t))},optional(){return kt(this)},exactOptional(){return TU(this)},nullable(){return ay(this)},nullish(){return kt(ay(this))},nonoptional(t){return MU(this,t)},array(){return qe(this)},or(t){return It([this,t])},and(t){return ff(this,t)},transform(t){return X0(this,vE(t))},default(t){return DU(this,t)},prefault(t){return zU(this,t)},catch(t){return jU(this,t)},pipe(t){return X0(this,t)},readonly(){return GU(this)},describe(t){let e=this.clone();return Jr.add(e,{description:t}),e},meta(...t){if(t.length===0)return Jr.get(this);let e=this.clone();return Jr.add(e,t[0]),e},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(t,...e){return e.length===0?t(this):t(this,...e)},get"~standard"(){return D.hide(this,"~standard",{...NS(this),jsonSchema:{input:nf(this,"input"),output:nf(this,"output")}})},set"~standard"(t){D.own(this,"~standard",t)},parse:function t(e,r){return YM(this,e,r,{callee:t})},parseAsync:async function t(e,r){return await QM(this,e,r,{callee:t})},safeParse(t,e){return eU(this,t,e)},async safeParseAsync(t,e){return tU(this,t,e)},get spa(){return this?.safeParseAsync},set spa(t){D.own(this,"spa",t)},validate(t,e){return Tp(this,t,e)},validateAsync(t,e){return Cp(this,t,e)},encode:function t(e,r){return rU(this,e,r,{callee:t})},decode:function t(e,r){return nU(this,e,r,{callee:t})},encodeAsync:async function t(e,r){return await oU(this,e,r,{callee:t})},decodeAsync:async function t(e,r){return await iU(this,e,r,{callee:t})},safeEncode(t,e){return sU(this,t,e)},safeDecode(t,e){return aU(this,t,e)},async safeEncodeAsync(t,e){return cU(this,t,e)},async safeDecodeAsync(t,e){return uU(this,t,e)},toJSONSchema(t){return dM(this,{})(t)},get description(){return Jr.get(this)?.description},get _def(){return this._zod.def}}),Y0=$("_ZodString",(t,e)=>{jc.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>mM(t,r,o,n)},D.derived({format:t=>kr(t).format??null,minLength:t=>kr(t).minimum??null,maxLength:t=>kr(t).maximum??null},{regex(...t){return this.check(Gp(...t))},includes(...t){return this.check(Bp(...t))},startsWith(...t){return this.check(Zp(...t))},endsWith(...t){return this.check(Wp(...t))},min(...t){return this.check(qa(...t))},max(...t){return this.check(Kl(...t))},length(...t){return this.check(Bl(...t))},nonempty(...t){return this.check(qa(1,...t))},lowercase(t){return this.check(Hp(t))},uppercase(t){return this.check(Kp(t))},trim(){return this.check(Qp())},normalize(...t){return this.check(Yp(...t))},toLowerCase(){return this.check(ef())},toUpperCase(){return this.check(tf())},slugify(){return this.check(rf())}})),uf=$("ZodString",(t,e)=>{jc.init(t,e),Y0.init(t,e)},{email(t){return this.check(Dg(Q0,t))},url(t){return this.check(Vp(cy,t))},jwt(t){return this.check(ey(hE,t))},emoji(t){return this.check(jg(tE,t))},guid(t){return this.check(Ng(eE,t))},uuid(t){return this.check(zg(Os,t))},uuidv4(t){return this.check(Mg(Os,t))},uuidv6(t){return this.check(Ug(Os,t))},uuidv7(t){return this.check(Lg(Os,t))},nanoid(t){return this.check(Fg(rE,t))},cuid(t){return this.check(qg(nE,t))},cuid2(t){return this.check(Vg(oE,t))},ulid(t){return this.check(Gg(iE,t))},base64(t){return this.check(Xg(pE,t))},base64url(t){return this.check(Yg(fE,t))},xid(t){return this.check(Hg(sE,t))},ksuid(t){return this.check(Kg(aE,t))},ipv4(t){return this.check(Bg(cE,t))},ipv6(t){return this.check(Zg(uE,t))},cidrv4(t){return this.check(Wg(lE,t))},cidrv6(t){return this.check(Jg(dE,t))},e164(t){return this.check(Qg(mE,t))},datetime(t){return this.check(ty(Bc,t))},date(t){return this.check(ry(Zc,t))},time(t){return this.check(ny(Wc,t))},duration(t){return this.check(oy(Jc,t))}});function O(t){return u0(uf,t)}var Tt=$("ZodStringFormat",(t,e)=>{St.init(t,e),Y0.init(t,e)}),Bc=$("ZodISODateTime",(t,e)=>{Fz.init(t,e),Tt.init(t,e)}),Zc=$("ZodISODate",(t,e)=>{qz.init(t,e),Tt.init(t,e)}),Wc=$("ZodISOTime",(t,e)=>{Vz.init(t,e),Tt.init(t,e)}),Jc=$("ZodISODuration",(t,e)=>{Gz.init(t,e),Tt.init(t,e)}),Q0=$("ZodEmail",(t,e)=>{US.init(t,e),Tt.init(t,e)});function PZ(t){return Dg(Q0,t)}var eE=$("ZodGUID",(t,e)=>{zS.init(t,e),Tt.init(t,e)});function kZ(t){return Ng(eE,t)}var Os=$("ZodUUID",(t,e)=>{MS.init(t,e),Tt.init(t,e)});function TZ(t){return zg(Os,t)}function CZ(t){return Mg(Os,t)}function OZ(t){return Ug(Os,t)}function DZ(t){return Lg(Os,t)}var cy=$("ZodURL",(t,e)=>{qS.init(t,e),Tt.init(t,e)});function NZ(t){return Vp(cy,t)}function zZ(t){return Vp(cy,{protocol:gg,hostname:tz,...D.normalizeParams(t)})}var tE=$("ZodEmoji",(t,e)=>{VS.init(t,e),Tt.init(t,e)});function MZ(t){return jg(tE,t)}var rE=$("ZodNanoID",(t,e)=>{GS.init(t,e),Tt.init(t,e)});function UZ(t){return Fg(rE,t)}var nE=$("ZodCUID",(t,e)=>{HS.init(t,e),Tt.init(t,e)});function LZ(t){return qg(nE,t)}var oE=$("ZodCUID2",(t,e)=>{KS.init(t,e),Tt.init(t,e)});function jZ(t){return Vg(oE,t)}var iE=$("ZodULID",(t,e)=>{BS.init(t,e),Tt.init(t,e)});function FZ(t){return Gg(iE,t)}var sE=$("ZodXID",(t,e)=>{ZS.init(t,e),Tt.init(t,e)});function qZ(t){return Hg(sE,t)}var aE=$("ZodKSUID",(t,e)=>{WS.init(t,e),Tt.init(t,e)});function VZ(t){return Kg(aE,t)}var cE=$("ZodIPv4",(t,e)=>{JS.init(t,e),Tt.init(t,e)});function GZ(t){return Bg(cE,t)}var lU=$("ZodMAC",(t,e)=>{YS.init(t,e),Tt.init(t,e)});function HZ(t){return l0(lU,t)}var uE=$("ZodIPv6",(t,e)=>{XS.init(t,e),Tt.init(t,e)});function KZ(t){return Zg(uE,t)}var lE=$("ZodCIDRv4",(t,e)=>{QS.init(t,e),Tt.init(t,e)});function BZ(t){return Wg(lE,t)}var dE=$("ZodCIDRv6",(t,e)=>{tx.init(t,e),Tt.init(t,e)});function ZZ(t){return Jg(dE,t)}var pE=$("ZodBase64",(t,e)=>{nx.init(t,e),Tt.init(t,e)});function WZ(t){return Xg(pE,t)}var fE=$("ZodBase64URL",(t,e)=>{ix.init(t,e),Tt.init(t,e)});function JZ(t){return Yg(fE,t)}var mE=$("ZodE164",(t,e)=>{sx.init(t,e),Tt.init(t,e)});function XZ(t){return Qg(mE,t)}var dU=$("ZodCreditCard",(t,e)=>{cx.init(t,e),Tt.init(t,e)});function YZ(t){return d0(dU,t)}var pU=$("ZodIBAN",(t,e)=>{lx.init(t,e),Tt.init(t,e)});function QZ(t){return p0(pU,t)}var hE=$("ZodJWT",(t,e)=>{px.init(t,e),Tt.init(t,e)});function eW(t){return ey(hE,t)}var Jl=$("ZodCustomStringFormat",(t,e)=>{fx.init(t,e),Tt.init(t,e)});function tW(t,e,r={}){return Vc(Jl,t,e,r)}function rW(t){return Vc(Jl,"hostname",ez,t)}function nW(t){return Vc(Jl,"hex",hz,t)}function oW(t){return Vc(Jl,"currency_code",nz,t)}function iW(t,e){let r=e?.enc??"hex",o=`${t}_${r}`,n=Eo[o];if(!n)throw new Error(`Unrecognized hash format: ${o}`);return Vc(Jl,o,n,e)}var lf=$("ZodNumber",(t,e)=>{$g.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>hM(t,r,o,n),t.isFinite=!0},D.derived({minValue:t=>{let{minimum:e,exclusiveMinimum:r}=kr(t);return Math.max(e??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:t=>{let{maximum:e,exclusiveMaximum:r}=kr(t);return Math.min(e??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:t=>{let{isInt:e,multipleOf:r}=kr(t);return!!e||!!r?.some(Number.isSafeInteger)},format:t=>kr(t).format??null},{gt(t,e){return this.check(Ts(t,e))},gte(t,e){return this.check(Ro(t,e))},min(t,e){return this.check(Ro(t,e))},lt(t,e){return this.check(ks(t,e))},lte(t,e){return this.check($o(t,e))},max(t,e){return this.check($o(t,e))},int(t){return this.check(J0(t))},safe(t){return this.check(J0(t))},positive(t){return this.check(Ts(0,t))},nonnegative(t){return this.check(Ro(0,t))},negative(t){return this.check(ks(0,t))},nonpositive(t){return this.check($o(0,t))},multipleOf(t,e){return this.check(Fc(t,e))},step(t,e){return this.check(Fc(t,e))},finite(){return this}}));function yt(t){return f0(lf,t)}var Xl=$("ZodNumberFormat",(t,e)=>{mx.init(t,e),lf.init(t,e)});function J0(t){return m0(Xl,t)}function sW(t){return h0(Xl,t)}function aW(t){return g0(Xl,t)}function cW(t){return y0(Xl,t)}function uW(t){return v0(Xl,t)}var df=$("ZodBoolean",(t,e)=>{Np.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>gM(t,r,o,n)});function yr(t){return w0(df,t)}var pf=$("ZodBigInt",(t,e)=>{Rg.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>yM(t,r,o,n)},D.derived({minValue:t=>kr(t).minimum??null,maxValue:t=>kr(t).maximum??null,format:t=>kr(t).format??null},{gte(t,e){return this.check(Ro(t,e))},min(t,e){return this.check(Ro(t,e))},gt(t,e){return this.check(Ts(t,e))},lt(t,e){return this.check(ks(t,e))},lte(t,e){return this.check($o(t,e))},max(t,e){return this.check($o(t,e))},positive(t){return this.check(Ts(BigInt(0),t))},negative(t){return this.check(ks(BigInt(0),t))},nonpositive(t){return this.check($o(BigInt(0),t))},nonnegative(t){return this.check(Ro(BigInt(0),t))},multipleOf(t,e){return this.check(Fc(t,e))}}));function lW(t){return _0(pf,t)}var gE=$("ZodBigIntFormat",(t,e)=>{hx.init(t,e),pf.init(t,e)});function dW(t){return b0(gE,t)}function pW(t){return S0(gE,t)}var fU=$("ZodSymbol",(t,e)=>{gx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>vM(t,r,o,n)});function fW(t){return x0(fU,t)}var mU=$("ZodUndefined",(t,e)=>{yx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>_M(t,r,o,n)});function mW(t){return E0(mU,t)}var hU=$("ZodNull",(t,e)=>{vx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>wM(t,r,o,n)});function uy(t){return $0(hU,t)}var gU=$("ZodAny",(t,e)=>{wx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>xM(t,r,o,n)});function hW(){return R0(gU)}var yU=$("ZodUnknown",(t,e)=>{_x.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>EM(t,r,o,n)});function Ut(){return I0(yU)}var vU=$("ZodNever",(t,e)=>{bx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>SM(t,r,o,n)});function yE(t){return A0(vU,t)}var wU=$("ZodVoid",(t,e)=>{Sx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>bM(t,r,o,n)});function gW(t){return P0(wU,t)}var ly=$("ZodDate",(t,e)=>{xx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>$M(t,r,o,n),t.min=(r,o)=>t.check(Ro(r,o)),t.max=(r,o)=>t.check($o(r,o))},D.derived({minDate:t=>{let{minimum:e}=kr(t);return e?new Date(e):null},maxDate:t=>{let{maximum:e}=kr(t);return e?new Date(e):null}},{}));function yW(t){return k0(ly,t)}var _U=$("ZodArray",(t,e)=>{Wl(),Ex.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>MM(t,r,o,n),t.element=e.element},{min(t,e){return this.check(qa(t,e))},nonempty(t){return this.check(qa(1,t))},max(t,e){return this.check(Kl(t,e))},length(t,e){return this.check(Bl(t,e))},unwrap(){return this.element}});function qe(t,e){return uM(_U,t,e)}function vW(t){let e=t._zod.def.shape;return Yr(Object.keys(e))}var dy=$("ZodObject",(t,e)=>{Wl(),Hz.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>UM(t,r,o,n),D.installLazyProp(t,"shape",r=>r._zod.def.shape,!1)},{keyof(){return Yr(Object.keys(this._zod.def.shape))},catchall(t){return this.clone(D.mergeDefs(this._zod.def,{catchall:t}))},passthrough(){return this.clone(D.mergeDefs(this._zod.def,{catchall:Ut()}))},loose(){return this.clone(D.mergeDefs(this._zod.def,{catchall:Ut()}))},strict(){return this.clone(D.mergeDefs(this._zod.def,{catchall:yE()}))},strip(){return this.clone(D.mergeDefs(this._zod.def,{catchall:void 0}))},extend(t){return D.extend(this,t)},safeExtend(t){return D.safeExtend(this,t)},merge(t){return D.merge(this,t)},pick(t){return D.pick(this,t)},omit(t){return D.omit(this,t)},partial(...t){return D.partial(Yl,this,t[0])},exactPartial(...t){return D.partial(wE,this,t[0],"exactPartial")},required(...t){return D.required(_E,this,t[0])}});function X(t,e){let r={type:"object",shape:t??{},...D.normalizeParams(e)};return new dy(r)}function wW(t,e){return new dy({type:"object",shape:t,catchall:yE(),...D.normalizeParams(e)})}function Xr(t,e){return new dy({type:"object",shape:t,catchall:Ut(),...D.normalizeParams(e)})}var py=$("ZodUnion",(t,e)=>{zp.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>H0(t,r,o,n),t.options=e.options});function It(t,e){return new py({type:"union",options:t,...D.normalizeParams(e)})}var bU=$("ZodXor",(t,e)=>{py.init(t,e),Rx.init(t,e),t._zod.processJSONSchema=(r,o,n)=>H0(t,r,o,n),t.options=e.options});function _W(t,e){return new bU({type:"union",options:t,inclusive:!1,...D.normalizeParams(e)})}var SU=$("ZodDiscriminatedUnion",(t,e)=>{py.init(t,e),Ix.init(t,e)});function fy(t,e,r){return new SU({type:"union",options:e,discriminator:t,...D.normalizeParams(r)})}var xU=$("ZodIntersection",(t,e)=>{Ax.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>LM(t,r,o,n)});function ff(t,e){return new xU({type:"intersection",left:t,right:e})}var EU=$("ZodTuple",(t,e)=>{Wl(),Ig.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>jM(t,r,o,n)},{rest(t){return this.clone({...this._zod.def,rest:t})},partial(){let t=this._zod.def;if(t.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...t,items:t.items.map(e=>new Yl({type:"optional",innerType:e}))})}});function $U(t,e,r){let o=e instanceof be,n=o?r:e,i=o?e:null;return new EU({type:"tuple",items:t,rest:i,...D.normalizeParams(n)})}var af=$("ZodRecord",(t,e)=>{Wl(),Px.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>FM(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType});function Ct(t,e,r){return!e||!e._zod?new af({type:"record",keyType:O(),valueType:t,...D.normalizeParams(e)}):new af({type:"record",keyType:t,valueType:e,...D.normalizeParams(r)})}function bW(t,e,r){return new af({type:"record",keyType:t,valueType:e,...D.normalizeParams(r),partial:!0})}function SW(t,e,r){return new af({type:"record",keyType:t,valueType:e,mode:"loose",...D.normalizeParams(r)})}var RU=$("ZodMap",(t,e)=>{Wl(),kx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>NM(t,r,o,n),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(Cs(...r)),t.nonempty=r=>t.check(Cs(1,r)),t.max=(...r)=>t.check(qc(...r)),t.size=(...r)=>t.check(Hl(...r))});function xW(t,e,r){return new RU({type:"map",keyType:t,valueType:e,...D.normalizeParams(r)})}var IU=$("ZodSet",(t,e)=>{Wl(),Tx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>zM(t,r,o,n),t.min=(...r)=>t.check(Cs(...r)),t.nonempty=r=>t.check(Cs(1,r)),t.max=(...r)=>t.check(qc(...r)),t.size=(...r)=>t.check(Hl(...r))});function EW(t,e){return new IU({type:"set",valueType:t,...D.normalizeParams(e)})}var cf=$("ZodEnum",(t,e)=>{Cx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(o,n,i)=>RM(t,o,n,i),t.enum=e.entries,t.options=[...t._zod.values];let r=new Set(Object.keys(e.entries));t.extract=(o,n)=>{let i={};for(let s of o)if(r.has(s))i[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new cf({...e,checks:[],...D.normalizeParams(n),entries:i})},t.exclude=(o,n)=>{let i={...e.entries};for(let s of o)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new cf({...e,checks:[],...D.normalizeParams(n),entries:i})}});function Yr(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(o=>[o,o])):t;return new cf({type:"enum",entries:r,...D.normalizeParams(e)})}function $W(t,e){return new cf({type:"enum",entries:t,...D.normalizeParams(e)})}var AU=$("ZodLiteral",(t,e)=>{Ox.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>IM(t,r,o,n),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function ae(t,e){return new AU({type:"literal",values:Array.isArray(t)?t:[t],...D.normalizeParams(e)})}var PU=$("ZodFile",(t,e)=>{Dx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>kM(t,r,o,n),t.min=(r,o)=>t.check(Cs(r,o)),t.max=(r,o)=>t.check(qc(r,o)),t.mime=(r,o)=>t.check(Xp(Array.isArray(r)?r:[r],o))});function RW(t){return M0(PU,t)}var kU=$("ZodTransform",(t,e)=>{Wl(),Nx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>DM(t,r,o,n),t._zod.parse=(r,o)=>{if(o.direction==="backward")throw new Lc(t.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(D.issue(i,r.value,e));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),"input"in s||(s.input=r.value),s.inst??(s.inst=t),r.issues.push(D.issue(s))}};let n=e.transform(r.value,r);return n instanceof Promise?n.then(i=>(r.value=i,r)):(r.value=n,r)}});function vE(t){return new kU({type:"transform",transform:t})}var Yl=$("ZodOptional",(t,e)=>{Ag.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>K0(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function kt(t){return new Yl({type:"optional",innerType:t})}var wE=$("ZodExactOptional",(t,e)=>{zx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>K0(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function TU(t){return new wE({type:"optional",innerType:t})}var CU=$("ZodNullable",(t,e)=>{Mx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>qM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function ay(t){return new CU({type:"nullable",innerType:t})}function IW(t){return kt(ay(t))}var OU=$("ZodDefault",(t,e)=>{Ux.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>HM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function DU(t,e){return new OU({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():D.shallowClone(e)}})}var NU=$("ZodPrefault",(t,e)=>{Lx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>KM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function zU(t,e){return new NU({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():D.shallowClone(e)}})}var _E=$("ZodNonOptional",(t,e)=>{jx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>VM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function MU(t,e){return new _E({type:"nonoptional",innerType:t,...D.normalizeParams(e)})}var UU=$("ZodSuccess",(t,e)=>{Fx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>TM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function AW(t){return new UU({type:"success",innerType:t})}var LU=$("ZodCatch",(t,e)=>{qx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>BM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function jU(t,e){return new LU({type:"catch",innerType:t,catchValue:typeof e=="function"?e:D.constantCatch(e)})}var FU=$("ZodNaN",(t,e)=>{Vx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>AM(t,r,o,n)});function PW(t){return T0(FU,t)}var my=$("ZodPipe",(t,e)=>{Pg.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>ZM(t,r,o,n),t.in=e.in,t.out=e.out});function X0(t,e){return new my({type:"pipe",in:t,out:e})}var hy=$("ZodCodec",(t,e)=>{my.init(t,e),Mp.init(t,e)});function kW(t,e,r){return new hy({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}function TW(t){let e=t._zod.def;return new hy({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}var qU=$("ZodPreprocess",(t,e)=>{my.init(t,e),Bz.init(t,e)}),VU=$("ZodReadonly",(t,e)=>{Gx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>WM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function GU(t){return new VU({type:"readonly",innerType:t})}var HU=$("ZodTemplateLiteral",(t,e)=>{Hx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>PM(t,r,o,n)});function CW(t,e){return new HU({type:"template_literal",parts:t,...D.normalizeParams(e)})}var KU=$("ZodLazy",(t,e)=>{Up.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>XM(t,r,o,n),t.unwrap=()=>t._zod.def.getter()});function BU(t){return new KU({type:"lazy",getter:t})}var ZU=$("ZodPromise",(t,e)=>{Bx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>JM(t,r,o,n),t.unwrap=()=>t._zod.def.innerType});function OW(t){return new ZU({type:"promise",innerType:t})}var WU=$("ZodFunction",(t,e)=>{Kx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>OM(t,r,o,n)});function DW(t){return new WU({type:"function",input:Array.isArray(t?.input)?$U(t?.input):t?.input??qe(Ut()),output:t?.output??Ut()})}var gy=$("ZodCustom",(t,e)=>{Zx.init(t,e),Ce.init(t,e),t._zod.processJSONSchema=(r,o,n)=>CM(t,r,o,n)});function NW(t){let e=new Pt({check:"custom"});return e._zod.check=t,e}function bE(t,e){return U0(gy,t??(()=>!0),e)}function JU(t,e={}){return L0(gy,t,e)}function XU(t,e){return j0(t,e)}var zW=F0,MW=q0,YU=$("ZodInstanceOf",(t,e)=>{gy.init(t,e)},{properties(t,e){return this.check(Jp(t,e))}});function UW(t,e={}){let r=new YU({type:"custom",check:"custom",fn:o=>o instanceof t,abort:!0,...D.normalizeParams(e)});return r._zod.bag.Class=t,r._zod.check=o=>{o.value instanceof t||o.issues.push({code:"invalid_type",expected:t.name,input:o.value,inst:r,path:[...r._zod.def.path??[]]})},r}var LW=(...t)=>V0({Codec:hy,Boolean:df,String:uf},...t);function jW(t){let e=BU(()=>It([O(t),yt(),yr(),uy(),qe(e),Ct(O(),e)]));return e}function yy(t,e){return new qU({type:"pipe",in:vE(t),out:e})}var ZCe={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"};function WCe(t){lr({customError:t})}function JCe(){return lr().customError}var QU;QU||(QU={});var Ql={};Ht(Ql,{ZodISODate:()=>Zc,ZodISODateTime:()=>Bc,ZodISODuration:()=>Jc,ZodISOTime:()=>Wc,date:()=>YCe,datetime:()=>XCe,duration:()=>eOe,time:()=>QCe});function XCe(t){return ty(Bc,t)}function YCe(t){return ry(Zc,t)}function QCe(t){return ny(Wc,t)}function eOe(t){return oy(Jc,t)}var J={...mf,...Z0,iso:Ql},tOe=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function rOe(t,e){let r=t.$schema;return r==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":r==="http://json-schema.org/draft-07/schema#"?"draft-7":r==="http://json-schema.org/draft-04/schema#"?"draft-4":e??"draft-2020-12"}function FW(t,e){return t.map((r,o)=>o<e?r:r.optional())}function nOe(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function oOe(t,e){if(!t.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let r=t.slice(1).split("/").filter(Boolean);if(r.length===0)return e.rootSchema;let o=e.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===o){let n=r[1]===void 0?void 0:nOe(r[1]);if(!n||!e.defs[n])throw new Error(`Reference not found: ${t}`);return e.defs[n]}throw new Error(`Reference not found: ${t}`)}function iOe(t,e){return J.transform(o=>o).check(o=>{let n=o.value;if(typeof n!="object"||n===null||Array.isArray(n))return;let i=Object.getOwnPropertyNames(n);if(e.minProperties!==void 0&&i.length<e.minProperties&&o.issues.push({origin:"object",code:"too_small",minimum:e.minProperties,inclusive:!0,message:`Too small: expected object to have >=${e.minProperties} properties`,input:n,inst:t,continue:!0}),e.maxProperties!==void 0&&i.length>e.maxProperties&&o.issues.push({origin:"object",code:"too_big",maximum:e.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${e.maxProperties} properties`,input:n,inst:t,continue:!0}),e.keySchema)for(let s of i){let a=e.keySchema.safeParse(s);a.success||o.issues.push({code:"invalid_key",origin:"record",issues:a.error.issues,input:s,path:[s],continue:!0})}}).pipe(t)}function eL(t,e){if(t===null)return"z";let r=typeof t;if(r!=="object"){if(r==="number"&&Number.isNaN(t))return null;let o=String(t);return`${r[0]}${o.length}:${o}`}if(e.has(t))return null;e.add(t);try{if(Array.isArray(t)){let i=[];for(let s of t){let a=eL(s,e);if(a===null)return null;i.push(a)}return`a${i.length}:[${i.join(",")}]`}let o=Object.keys(t).sort(),n=[];for(let i of o){let s=eL(t[i],e);if(s===null)return null;n.push(`${i.length}:${i}=${s}`)}return`o${n.length}:{${n.join(",")}}`}finally{e.delete(t)}}var sOe=new Set(["items","prefixItems","additionalItems","additionalProperties","contains","propertyNames","not","if","then","else","allOf","anyOf","oneOf","unevaluatedItems","unevaluatedProperties","contentSchema"]),aOe=new Set(["properties","patternProperties","dependentSchemas","dependencies","$defs","definitions"]);function vy(t){return typeof t!="object"||t===null?!1:Array.isArray(t)?t.some(vy):typeof t.$ref=="string"?!0:Object.entries(t).some(([e,r])=>sOe.has(e)?vy(r):!aOe.has(e)||typeof r!="object"||r===null?!1:Object.values(r).some(vy))}function qW(t){return t===1?"element":"elements"}function cOe(t,e){return J.transform(o=>o).check(o=>{let n=o.value;if(Array.isArray(n)){if(e.uniqueItems===!0){let i=new Map;for(let s=0;s<n.length;s++){let a=eL(n[s],new Set);if(a===null)continue;let c=i.get(a);if(c===void 0){i.set(a,s);continue}o.issues.push({code:"custom",message:`Array items must be unique: element at index ${s} duplicates the one at index ${c}`,input:n,path:[s],continue:!0})}}if(e.containsSchema){let i=e.minContains??1,s=e.maxContains!==void 0?e.maxContains+1:Number.POSITIVE_INFINITY,a=0;for(let c of n)if(e.containsSchema.safeParse(c).success&&++a>=s)break;a<i&&o.issues.push({code:"custom",message:`Array must contain at least ${i} matching ${qW(i)}; found ${a}`,input:n,continue:!0}),e.maxContains!==void 0&&a>e.maxContains&&o.issues.push({code:"custom",message:`Array must contain at most ${e.maxContains} matching ${qW(e.maxContains)}`,input:n,continue:!0})}}}).pipe(t)}function VW(t,e){if(t!==!1)return t===void 0||t===!0?J.any():Gn(t,e)}var uOe=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function GW(t,e){if(t.not!==void 0){if(typeof t.not=="object"&&Object.keys(t.not).length===0)return J.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(t.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(t.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(t.if!==void 0||t.then!==void 0||t.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(t.dependentSchemas!==void 0||t.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(t.$ref){let n=t.$ref;if(e.refs.has(n))return e.refs.get(n);if(e.processing.has(n))return J.lazy(()=>{if(!e.refs.has(n))throw new Error(`Circular reference not resolved: ${n}`);return e.refs.get(n)});e.processing.add(n);let i=oOe(n,e),s=Gn(i,e);return e.refs.set(n,s),e.processing.delete(n),s}if(t.enum!==void 0){let n=t.enum;if(e.version==="openapi-3.0"&&t.nullable===!0&&n.length===1&&n[0]===null)return J.null();if(n.length===0)return J.never();if(n.length===1)return J.literal(n[0]);if(n.every(s=>typeof s=="string"))return J.enum(n);let i=n.map(s=>J.literal(s));return i.length<2?i[0]:J.union([i[0],i[1],...i.slice(2)])}if(t.const!==void 0)return J.literal(t.const);let r=t.type;if(Array.isArray(r)){let n=r.map(i=>{let s={...t,type:i};return GW(s,e)});return n.length===0?J.never():n.length===1?n[0]:J.union(n)}if(!r)return J.any();let o;switch(r){case"string":{let n=J.string();if(t.format){let i=t.format;i==="email"?n=n.check(J.email()):i==="uri"||i==="uri-reference"?n=n.check(J.url()):i==="uuid"||i==="guid"?n=n.check(J.uuid()):i==="date-time"?n=n.check(J.iso.datetime({offset:!0})):i==="date"?n=n.check(J.iso.date()):i==="time"?n=n.check(J.regex(uOe)):i==="duration"?n=n.check(J.iso.duration()):i==="hostname"?n=n.check(J.hostname()):i==="ipv4"?n=n.check(J.ipv4()):i==="ipv6"?n=n.check(J.ipv6()):i==="mac"?n=n.check(J.mac()):i==="cidr"?n=n.check(J.cidrv4()):i==="cidr-v6"?n=n.check(J.cidrv6()):i==="base64"?n=n.check(J.base64()):i==="base64url"?n=n.check(J.base64url()):i==="e164"?n=n.check(J.e164()):i==="credit_card"?n=n.check(J.creditCard()):i==="iban"?n=n.check(J.iban()):i==="jwt"?n=n.check(J.jwt()):i==="emoji"?n=n.check(J.emoji()):i==="nanoid"?n=n.check(J.nanoid()):i==="cuid"?n=n.check(J.cuid()):i==="cuid2"?n=n.check(J.cuid2()):i==="ulid"?n=n.check(J.ulid()):i==="xid"?n=n.check(J.xid()):i==="ksuid"&&(n=n.check(J.ksuid()))}typeof t.minLength=="number"&&(n=n.min(t.minLength)),typeof t.maxLength=="number"&&(n=n.max(t.maxLength)),t.pattern&&(n=n.regex(new RegExp(t.pattern))),o=n;break}case"number":case"integer":{let n=r==="integer"?J.number().int():J.number();typeof t.minimum=="number"&&t.exclusiveMinimum!==!0&&(n=n.min(t.minimum)),typeof t.maximum=="number"&&t.exclusiveMaximum!==!0&&(n=n.max(t.maximum)),typeof t.exclusiveMinimum=="number"?n=n.gt(t.exclusiveMinimum):t.exclusiveMinimum===!0&&typeof t.minimum=="number"&&(n=n.gt(t.minimum)),typeof t.exclusiveMaximum=="number"?n=n.lt(t.exclusiveMaximum):t.exclusiveMaximum===!0&&typeof t.maximum=="number"&&(n=n.lt(t.maximum)),typeof t.multipleOf=="number"&&(n=n.multipleOf(t.multipleOf)),o=n;break}case"boolean":{o=J.boolean();break}case"null":{o=J.null();break}case"object":{let n={},i=t.properties||{},s=new Set(t.required||[]),a=typeof t.additionalProperties=="object"?Gn(t.additionalProperties,e):void 0;for(let[d,p]of Object.entries(i)){let f=Gn(p,e);Wr(n,d,s.has(d)?f:f.optional())}if(t.patternProperties){let d=t.patternProperties,p=Object.keys(d),f=[];for(let y of p){let w=Gn(d[y],e),b=J.string().regex(new RegExp(y));f.push(J.looseRecord(b,w))}let h=[];if(Object.keys(n).length>0&&h.push(J.object(n).passthrough()),h.push(...f),h.length===0)o=J.object({}).passthrough();else if(h.length===1)o=h[0];else{let y=J.intersection(h[0],h[1]);for(let w=2;w<h.length;w++)y=J.intersection(y,h[w]);o=y}if(t.additionalProperties===!1){let y=Object.keys(n),w=p.map(S=>new RegExp(S)),b=o;o=o.check(S=>{if(!Jo(S.value))return;let x=[];for(let R of Object.keys(S.value))y.includes(R)||w.some(T=>T.test(R))||x.push(R);x.length&&S.issues.push({code:"unrecognized_keys",keys:x,input:S.value,inst:b})})}}else{let d=J.object(n);t.additionalProperties===!1?o=d.strict():a?o=d.catchall(a):o=d.passthrough()}let c=t.propertyNames!==void 0&&t.propertyNames!==!0,u=typeof t.minProperties=="number"?t.minProperties:void 0,l=typeof t.maxProperties=="number"?t.maxProperties:void 0;if(c||u!==void 0||l!==void 0){let d;if(c){let p=typeof t.propertyNames=="object"&&t.propertyNames.type===void 0?{type:"string",...t.propertyNames}:t.propertyNames;d=Gn(p,e)}o=iOe(o,{keySchema:d,minProperties:u,maxProperties:l})}break}case"array":{let n=t.prefixItems,i=t.items;if(n&&Array.isArray(n)){let s=typeof t.minItems=="number"?t.minItems:0,a=n.map(d=>Gn(d,e)),c=FW(a,s),u=Array.isArray(i)?void 0:VW(i,e),l=J.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(J.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(J.maxLength(t.maxItems)))}else if(Array.isArray(i)){let s=typeof t.minItems=="number"?t.minItems:0,a=i.map(d=>Gn(d,e)),c=FW(a,s),u=VW(t.additionalItems,e),l=J.tuple(c);o=u?l.rest(u):l,typeof t.minItems=="number"&&(o=o.check(J.minLength(t.minItems))),typeof t.maxItems=="number"&&(o=o.check(J.maxLength(t.maxItems)))}else if(i!==void 0){let s=Gn(i,e),a=J.array(s);typeof t.minItems=="number"&&(a=a.min(t.minItems)),typeof t.maxItems=="number"&&(a=a.max(t.maxItems)),o=a}else o=J.array(J.any());(t.uniqueItems===!0||t.contains!==void 0)&&(o=cOe(o,{uniqueItems:t.uniqueItems===!0,containsSchema:t.contains!==void 0?Gn(t.contains,e):void 0,minContains:typeof t.minContains=="number"?t.minContains:void 0,maxContains:typeof t.maxContains=="number"?t.maxContains:void 0}));break}default:throw new Error(`Unsupported type: ${r}`)}return o}function Gn(t,e){if(typeof t=="boolean")return t?J.any():J.never();let r=GW(t,e),o=t.type||t.enum!==void 0||t.const!==void 0;if(t.anyOf&&Array.isArray(t.anyOf)){let a=t.anyOf.map(u=>Gn(u,e)),c=J.union(a);r=o?J.intersection(r,c):c}if(t.oneOf&&Array.isArray(t.oneOf)){let a=t.oneOf.map(u=>Gn(u,e)),c=J.xor(a);r=o?J.intersection(r,c):c}if(t.allOf&&Array.isArray(t.allOf))if(t.allOf.length===0)r=o?r:J.any();else{let a=o?r:Gn(t.allOf[0],e),c=o?0:1;for(let u=c;u<t.allOf.length;u++)a=J.intersection(a,Gn(t.allOf[u],e));r=a}t.nullable===!0&&e.version==="openapi-3.0"&&(r=J.nullable(r)),t.readOnly===!0&&(r=J.readonly(r)),t.default!==void 0&&(r=r.default(t.default));let n={},i=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of i)a in t&&(n[a]=t[a]);let s=["contentEncoding","contentMediaType","contentSchema"];for(let a of s)a in t&&(n[a]=t[a]);if(t.type==="object"&&t.$ref===void 0){t.propertyNames!==void 0&&!vy(t.propertyNames)&&(n.propertyNames=t.propertyNames);for(let a of["minProperties","maxProperties"])t[a]!==void 0&&(n[a]=t[a])}if(t.type==="array"&&t.$ref===void 0){t.contains!==void 0&&!vy(t.contains)&&(n.contains=t.contains);for(let a of["uniqueItems","minContains","maxContains"])t[a]!==void 0&&(n[a]=t[a])}for(let a of Object.keys(t))tOe.has(a)||Wr(n,a,t[a]);return Object.keys(n).length>0&&e.registry.add(r,n),t.description&&(r=r.describe(t.description)),r}function HW(t,e){if(typeof t=="boolean")return t?J.any():J.never();let r;try{r=JSON.parse(JSON.stringify(t))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let o=rOe(r,e?.defaultTarget),n=r.$defs||r.definitions||{},i={version:o,defs:n,refs:new Map,processing:new Set,rootSchema:r,registry:e?.registry??Jr};return Gn(r,i)}var KW=Symbol("z.visit/resolving");function wy(t,e){let r=typeof e=="function"?e:(s,a)=>{let c=e[s._zod.def.type];return c?c(s,a):s},o=new Map;function n(s){let a=o.get(s);if(a===KW)return new Up({type:"lazy",getter:()=>o.get(s)});if(a!==void 0)return a;o.set(s,KW);let c=i(s),u=r(c,c!==s);return o.set(s,u),u}function i(s){let a=s._zod.def,c=a.type;switch(c){case"object":{let u=a.shape,l=Object.keys(u),d=!1,p={};for(let h of l){let y=n(u[h]);y!==u[h]&&(d=!0),p[h]=y}let f=a.catchall;return a.catchall&&(f=n(a.catchall),f!==a.catchall&&(d=!0)),d?gt(s,{...a,shape:p,catchall:f}):s}case"array":{let u=n(a.element);return u===a.element?s:gt(s,{...a,element:u})}case"tuple":{let u=a.items,l=!1,d=[];for(let f of u){let h=n(f);h!==f&&(l=!0),d.push(h)}let p=a.rest;return a.rest&&(p=n(a.rest),p!==a.rest&&(l=!0)),l?gt(s,{...a,items:d,rest:p}):s}case"record":case"map":{let u=n(a.keyType),l=n(a.valueType);return u===a.keyType&&l===a.valueType?s:gt(s,{...a,keyType:u,valueType:l})}case"set":{let u=n(a.valueType);return u===a.valueType?s:gt(s,{...a,valueType:u})}case"union":{let u=a.options,l=!1,d=[];for(let p of u){let f=n(p);f!==p&&(l=!0),d.push(f)}return l?gt(s,{...a,options:d}):s}case"intersection":{let u=n(a.left),l=n(a.right);return u===a.left&&l===a.right?s:gt(s,{...a,left:u,right:l})}case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":{let u=n(a.innerType);return u===a.innerType?s:gt(s,{...a,innerType:u})}case"pipe":{let u=n(a.in),l=n(a.out);return u===a.in&&l===a.out?s:gt(s,{...a,in:u,out:l})}case"function":{let u=n(a.input),l=n(a.output);return u===a.input&&l===a.output?s:gt(s,{...a,input:u,output:l})}case"lazy":{let u=a.getter,{_cachedInner:l,...d}=a;return gt(s,{...d,getter:()=>n(u())})}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":return s;default:return s}}return n(t)}function BW(t){return wy(t,{object:e=>e.partial(),union:e=>{let r=e._zod.def;return r.discriminator===void 0?e:It(r.options)}})}function lOe(t,e){if(!e?.length)return t;let r=t._zod.def;return gt(t,Wo(r,{checks:[...r.checks??[],...e]}),{parent:!0})}function ZW(t){return lOe(t.out,t.checks)}function dOe(t){return t.in._zod.traits.has("$ZodTransform")?ZW(t):t.in}function WW(t){return wy(t,{pipe:e=>dOe(e._zod.def),default:(e,r)=>r?kt(e._zod.def.innerType):e,catch:(e,r)=>r?e._zod.def.innerType:e})}function JW(t){return wy(t,{pipe:e=>ZW(e._zod.def),prefault:(e,r)=>r?e._zod.def.innerType:e})}var tL={};Ht(tL,{bigint:()=>hOe,boolean:()=>mOe,date:()=>gOe,number:()=>fOe,string:()=>pOe});function pOe(t){return nM(uf,t)}function fOe(t){return iM(lf,t)}function mOe(t){return sM(df,t)}function hOe(t){return aM(pf,t)}function gOe(t){return cM(ly,t)}var _y={name:"@tomato414941/foundation",version:"15.0.0",description:"Manage Foundation resources and run commands in execution environments.",type:"module",engines:{node:">=24"},bin:{foundation:"dist/cli.mjs"},files:["dist/cli.mjs"],repository:{type:"git",url:"git+https://github.com/tomato414941/foundation.git",directory:"cli"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},license:"MIT"};typeof window<"u"&&m.config({jitless:!0});function vOe(t){let e=/^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521))[ \t]+([A-Za-z0-9+/]+={0,2})(?:[ \t]+[^\r\n\0]*)?$/.exec(t.trim());if(!e)return null;try{let r=Uint8Array.from(atob(e[2]),a=>a.charCodeAt(0)),o=new DataView(r.buffer),n=0,i=()=>{if(n+4>r.length)throw new Error("Invalid SSH key.");let a=o.getUint32(n);if(n+=4,n+a>r.length)throw new Error("Invalid SSH key.");let c=r.subarray(n,n+a);return n+=a,c},s=a=>new TextDecoder().decode(a);if(s(i())!==e[1])return null;if(e[1]==="ssh-ed25519"){if(i().length!==32)return null}else if(e[1]==="ssh-rsa"){let a=i(),c=i();if(!a.length||c.length<256||c.length>1025)return null}else{let a=s(i()),c=i(),u={nistp256:65,nistp384:97,nistp521:133};if(e[1]!=="ecdsa-sha2-"+a||c[0]!==4||c.length!==u[a])return null}return n===r.length?r:null}catch{return null}}var by=m.string().trim().max(8192).refine(t=>vOe(t)!==null,"Use an OpenSSH public key from a .pub file."),Sy=m.object({authorizedKeys:m.array(by).max(32)}).strict(),dyt=Sy.extend({revision:m.number().int().positive().optional()}),rL=Sy.extend({host:m.string().min(1).max(253).nullable(),port:m.number().int().min(1).max(65535),username:m.literal("root"),workingDirectory:m.literal("/workspace"),hostKey:by.nullable(),fingerprint:m.string().nullable(),revision:m.number().int().positive(),appliedRevision:m.number().int().nonnegative(),activeSessions:m.number().int().min(0).max(1024)}).strict(),pyt=rL.extend({state:m.enum(["starting","configuring","ready","disabled","stopped"])}),fyt=m.object({hostKey:by,appliedRevision:m.number().int().nonnegative(),activeSessions:m.number().int().min(0).max(1024)}).strict(),wOe=Sy.extend({port:m.number().int().min(1).max(65535),revision:m.number().int().positive()}).strict(),SE=m.object({configuration:wOe.nullable()}).strict();var hf=new TextEncoder,gf=new TextDecoder,XW=new TextDecoder("utf-8",{fatal:!0}),xE=2**32;function Hn(...t){let e=t.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(e),o=0;for(let n of t)r.set(n,o),o+=n.length;return r}function nL(t,e,r){if(e<0||e>=xE)throw new RangeError(`value must be >= 0 and <= ${xE-1}. Received ${e}`);t.set([e>>>24,e>>>16,e>>>8,e&255],r)}function oL(t){let e=Math.floor(t/xE),r=t%xE,o=new Uint8Array(8);return nL(o,e,0),nL(o,r,4),o}function EE(t){let e=new Uint8Array(4);return nL(e,t),e}var _Oe=/[^\x00-\x7f]/;function Qr(t){if(typeof t=="string"&&t.length>=128){if(_Oe.test(t))throw new TypeError("non-ASCII string encountered in encode()");return hf.encode(t)}let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++){let o=t.charCodeAt(r);if(o>127)throw new TypeError("non-ASCII string encountered in encode()");e[r]=o}return e}function YW(t,e=!1){if(Uint8Array.prototype.toBase64)return t.toBase64({alphabet:e?"base64url":"base64",omitPadding:e});let r=32768,o=[];for(let i=0;i<t.length;i+=r)o.push(String.fromCharCode.apply(null,t.subarray(i,i+r)));let n=btoa(o.join(""));return e?n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"):n}function QW(t,e=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(t,{alphabet:e?"base64url":"base64"});if(e){if(t.includes("+")||t.includes("/"))throw new TypeError("Invalid base64url");t=t.replace(/-/g,"+").replace(/_/g,"/")}let r=atob(t),o=new Uint8Array(r.length);for(let n=0;n<r.length;n++)o[n]=r.charCodeAt(n);return o}async function $E(t,e){let r=`SHA-${t.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,e))}var Va=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,r){super(e,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};var ed=class extends Va{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},Ot=class extends Va{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},Xc=class extends Va{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(e="decryption operation failed",r){super(e,r)}},H=class extends Va{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},Yt=class extends Va{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"};var xy=class extends Va{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"};var RE=class extends Va{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}};var bOe="The input to be decoded is not correctly encoded.";function td(t){try{return QW(typeof t=="string"?t:gf.decode(t),!0)}catch(e){throw new TypeError(bOe,{cause:e})}}function or(t){return YW(typeof t=="string"?hf.encode(t):t,!0)}function Io(t,e){if(!(t instanceof Uint8Array))throw new TypeError(`${e} must be an instance of Uint8Array`)}function br(t){if(typeof t!="object"||t===null||Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||Object.getPrototypeOf(e)===null}function Yc(...t){let e=new Set;for(let r of t)if(r)for(let o of Object.keys(r)){if(e.has(o))return!1;e.add(o)}return!0}function Yo(t,e){if(t!==void 0)throw new TypeError(`${e} can only be called once`)}function po(t,e,r){try{return td(t)}catch{throw new r(`Failed to base64url decode the ${e}`)}}function IE(t,e,r){try{return Qr(t)}catch{throw new r(`The ${e} is not a valid base64url string`)}}function yf(t,e,r){let o;try{o=JSON.parse(XW.decode(td(t)))}catch{throw new e(r)}if(!br(o))throw new e(r);return o}var AE={__proto__:null,b64:!0},PE={__proto__:null};function Ey(t,e){if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${t}" option must be an array of strings`);return e===void 0?void 0:new Set(e)}function kE(t,e){let{crit:r}=e??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new t('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function Qc(t,e,r,o,n){if(n.crit!==void 0&&o?.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return[];if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(s=>typeof s!="string"||s.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i=r===void 0?e:{__proto__:null,...r,...e};for(let s of o.crit){if(!(s in i))throw new Ot(`Extension Header Parameter "${s}" is not recognized`);if(!Object.hasOwn(n,s)||n[s]===void 0)throw new t(`Extension Header Parameter "${s}" is missing`);if(i[s]&&(!Object.hasOwn(o,s)||o[s]===void 0))throw new t(`Extension Header Parameter "${s}" MUST be integrity protected`)}return o.crit}function TE(t,e){if(e.includes("b64")){let r=t.b64;if(typeof r!="boolean")throw new Yt('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}function rd(t,e){let r,o;try{r=JSON.stringify(e),o=JSON.parse(r)}catch(n){throw new t("JOSE Header is not valid JSON",{cause:n})}if(!br(o))throw new t("JOSE Header is not a JSON object");return[o,r]}var SOe=t=>t[Symbol.toStringTag],xOe=(t,e,r)=>{let{alg:o}=t;if(e.use!==void 0){let n=r==="sign"||r==="verify"?"sig":"enc";if(e.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(e.alg!==void 0&&e.alg!==o)throw new TypeError(`Invalid key for this operation, its "alg" must be "${o}" when present`);if(Array.isArray(e.key_ops)){let n=r==="encrypt"||r==="decrypt"?t.ops?.[r==="encrypt"?0:1]:r;if(n&&!e.key_ops.includes(n))throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}};async function Mi(t,e,r){let{alg:o,secret:n}=t,i=r==="decrypt"||r==="sign";if(n&&e instanceof Uint8Array)return e;let s,a;if(br(e)){if(s=lL(e),typeof s.kty!="string")throw e5(o,e,n);if(!(n?s.kty==="oct"&&typeof s.k=="string":s.kty!=="oct"&&(i?s.kty==="AKP"&&typeof s.priv=="string"||typeof s.d=="string":s.d===void 0&&s.priv===void 0)))throw new TypeError(n?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${i?"private":"public"} JWK`);if(xOe(t,s,r),s.kty==="oct")return td(s.k);if(!Object.isFrozen(e)){let{key_ops:l}=e;Array.isArray(l)&&Object.freeze(l),Object.freeze(e)}}else{if(!aL(e))throw e5(o,e,n);let l=n?"secret":i?"private":"public";if(e.type!==l&&(n||["secret","public","private"].includes(e.type)))throw new TypeError(`${SOe(e)} instances must be of type "${l}" for the ${o} algorithm`);if(eu(e))return e;if(a=e,a.type==="secret")return a.export()}iL||=new WeakMap;let c=e,u=iL.get(c);if(u?.[o])return u[o];if(u||iL.set(c,u={}),a&&typeof a.toCryptoKey=="function"){let l=a.type==="public",d=EOe[a.asymmetricKeyDetails?.namedCurve],p=t.resolve?.({crv:d,asymmetricKeyType:a.asymmetricKeyType})??t.subtle;return u[o]=a.toCryptoKey(p,l,t.usages[l?0:1])}return s??=a.export({format:"jwk"}),s.alg=o,u[o]=await wf(t,s)}var iL,EOe={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};function OE(t){if(!eu(t))throw new Error("CryptoKey instance expected")}var eu=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},sL=t=>t?.[Symbol.toStringTag]==="KeyObject",aL=t=>eu(t)||sL(t);function t5(t,e,...r){if(r.length>2){let o=r.pop();t+=`one of type ${r.join(", ")}, or ${o}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}var Ga=(t,...e)=>t5("Key must be ",t,...e);function e5(t,e,r){let o=["CryptoKey","KeyObject","JSON Web Key"];return r&&o.push("Uint8Array"),new TypeError(t5(`Key for the ${t} algorithm must be `,e,...o))}var CE=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`);function cL(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function vf(t,e){let{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}function uL(t,e,r){let o=t.algorithm;if(o.name!==e.name)throw CE(e.name);if(e.hash&&o.hash?.name!==e.hash)throw CE(e.hash,"algorithm.hash");if(e.namedCurve&&o.namedCurve!==e.namedCurve)throw CE(e.namedCurve,"algorithm.namedCurve");if(e.length!==void 0&&o.length!==e.length)throw CE(e.length,"algorithm.length");cL(t,r)}function DE(t){return{__proto__:null,...t}}function lL(t){let e=DE(t);if(e.ext!==void 0&&typeof e.ext!="boolean")throw new TypeError('"ext" (Extractable) Parameter must be a boolean');if(e.key_ops!==void 0){let r=e.key_ops,o=Array.isArray(r)?[...r]:void 0;if(!o||o.some(n=>typeof n!="string")||new Set(o).size!==o.length)throw new TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');e.key_ops=o}return e}function NE(t){if(t!==void 0&&typeof t!="boolean")throw new TypeError('"extractable" option must be a boolean');return t}async function wf(t,e,r){if(!t.kty.includes(e.kty))throw new Ot('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let o=t.resolve?.({kty:e.kty,crv:e.crv})??t.subtle,n=!!(e.d||e.priv),i={...e,ext:r??e.ext};return i.kty!=="AKP"&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,o,i.ext??!n,e.key_ops??t.usages[n?1:0])}async function Ui(t,e,r,o=!1){return t instanceof Uint8Array&&(t=await crypto.subtle.importKey("raw",t,e,o,[r])),uL(t,e,r),t}var nd=t=>crypto.getRandomValues(new Uint8Array(t.cekBits>>3));function zE(t,e){let r=t.byteLength<<3;if(r!==e)throw new H(`Invalid Content Encryption Key length. Expected ${e} bits, got ${r} bits`)}var $Oe=t=>crypto.getRandomValues(new Uint8Array(t.ivBits>>3));function r5(t,e){if(e.length<<3!==t.ivBits)throw new H("Invalid Initialization Vector length")}async function n5(t,e,r){if(!(e instanceof Uint8Array))throw new TypeError(Ga(e,"Uint8Array"));let o=t.cekBits>>1,n=await crypto.subtle.importKey("raw",e.subarray(o>>3),"AES-CBC",!1,[r]),i=await crypto.subtle.importKey("raw",e.subarray(0,o>>3),{hash:`SHA-${o<<1}`,name:"HMAC"},!1,["sign"]);return[n,i,o]}async function o5(t,e,r){return new Uint8Array((await crypto.subtle.sign("HMAC",t,e)).slice(0,r>>3))}async function ROe(t,e,r,o,n){let[i,s,a]=await n5(t,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:o,name:"AES-CBC"},i,e)),u=Hn(n,o,c,oL(n.length*8)),l=await o5(s,u,a);return{ciphertext:c,tag:l,iv:o}}async function IOe(t,e){let r={name:"HMAC",hash:"SHA-256"},o=await crypto.subtle.generateKey(r,!1,["sign","verify"]),n=await crypto.subtle.sign(r,o,t);return crypto.subtle.verify(r,o,n,e)}async function AOe(t,e,r,o,n,i){let[s,a,c]=await n5(t,e,"decrypt"),u=Hn(i,o,r,oL(i.length*8)),l=await o5(a,u,c);try{if(await IOe(n,l))return new Uint8Array(await crypto.subtle.decrypt({iv:o,name:"AES-CBC"},s,r))}catch{}throw new Xc}async function ME(t,e,r,o,n){if(!eu(r)&&!(r instanceof Uint8Array))throw new TypeError(Ga(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(o?r5(t,o):o=$Oe(t),r instanceof Uint8Array&&zE(r,t.cekBits),t.cbc)return ROe(t,e,r,o,n);let i=await Ui(r,t.subtle,"encrypt"),s=new Uint8Array(await crypto.subtle.encrypt({additionalData:n,iv:o,name:"AES-GCM",tagLength:128},i,e));return{ciphertext:s.subarray(0,-16),tag:s.subarray(-16),iv:o}}async function UE(t,e,r,o,n,i){if(!eu(e)&&!(e instanceof Uint8Array))throw new TypeError(Ga(e,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!o)throw new H("JWE Initialization Vector missing");if(!n)throw new H("JWE Authentication Tag missing");if(!t.cbc&&n.length!==16)throw new H("Invalid Authentication Tag length");if(r5(t,o),e instanceof Uint8Array&&zE(e,t.cekBits),t.cbc)return AOe(t,e,r,o,n,i);let s=await Ui(e,t.subtle,"decrypt");try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:i,iv:o,name:"AES-GCM",tagLength:128},s,Hn(r,n)))}catch{throw new Xc}}function $y(t){let e={__proto__:null};for(let r in t)e[r]={...t[r],alg:r};return e}var POe=[["encrypt","wrapKey"],["decrypt","unwrapKey"]],kOe=[[],["deriveBits"]],FE=[[],[]];function LE(t){return{kty:["RSA"],mode:"key-encryption",subtle:{name:"RSA-OAEP",hash:`SHA-${t}`},usages:POe,ops:["wrapKey","unwrapKey"]}}function jE(t){return{kty:["EC","OKP"],mode:t,subtle:{name:"ECDH"},resolve:({kty:e,crv:r,asymmetricKeyType:o})=>{if(r==="X25519"||o==="x25519")return{name:"X25519"};if(e==="OKP")throw new Ot('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');return{name:"ECDH",namedCurve:r}},usages:kOe,ops:[void 0,"deriveBits"]}}function _f(t,e=!1){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:e?"AES-GCM":"AES-KW",length:t},usages:FE,ops:e?["encrypt","decrypt"]:["wrapKey","unwrapKey"]}}function dL(){return{kty:["oct"],mode:"key-wrapping",secret:!0,subtle:{name:"PBKDF2"},usages:FE,ops:["deriveBits","deriveBits"]}}var Ha=$y({dir:{kty:["oct"],mode:"direct-encryption",secret:!0,subtle:{name:"AES-GCM"},usages:FE,ops:["encrypt","decrypt"]},"RSA-OAEP":LE(1),"RSA-OAEP-256":LE(256),"RSA-OAEP-384":LE(384),"RSA-OAEP-512":LE(512),"ECDH-ES":jE("direct-key-agreement"),"ECDH-ES+A128KW":jE("key-agreement-with-key-wrapping"),"ECDH-ES+A192KW":jE("key-agreement-with-key-wrapping"),"ECDH-ES+A256KW":jE("key-agreement-with-key-wrapping"),A128KW:_f(128),A192KW:_f(192),A256KW:_f(256),A128GCMKW:_f(128,!0),A192GCMKW:_f(192,!0),A256GCMKW:_f(256,!0),"PBES2-HS256+A128KW":dL(),"PBES2-HS384+A192KW":dL(),"PBES2-HS512+A256KW":dL()}),TOe=["encrypt","decrypt"];function bf(t,e=!1){return{kty:["oct"],secret:!0,subtle:{name:e?"AES-CBC":"AES-GCM",length:t},usages:FE,ops:TOe,cekBits:t,ivBits:e?128:96,cbc:e}}var COe=$y({A128GCM:bf(128),A192GCM:bf(192),A256GCM:bf(256),"A128CBC-HS256":bf(256,!0),"A192CBC-HS384":bf(384,!0),"A256CBC-HS512":bf(512,!0)});function i5(t,e){throw new Ot(`Invalid or unsupported "${t}" (JWE ${e}) header value`)}function Li(t){return(typeof t=="string"?Ha[t]:void 0)??i5("alg","Algorithm")}function ji(t){return t.mode==="key-wrapping"||t.mode==="key-encryption"||t.mode==="key-agreement-with-key-wrapping"}function od(t){return(typeof t=="string"?COe[t]:void 0)??i5("enc","Encryption Algorithm")}function s5(t,e){if(t.algorithm.name!=="ECDH"&&t.algorithm.name!=="X25519")throw new TypeError("CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519");cL(t,e)}async function OOe(t,e,r){let o=await Ui(e,Li(t).subtle,"wrapKey",!0),n=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",n,o,"AES-KW"))}async function DOe(t,e,r){let o=await Ui(e,Li(t).subtle,"unwrapKey",!0),n=await crypto.subtle.unwrapKey("raw",r,o,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",n))}function c5(t,e,r){uL(e,Li(t).subtle,r),vf(t,e)}async function u5(t,e,r,o){if(!(t instanceof Uint8Array)||t.length<8)throw new H("PBES2 Salt Input must be 8 or more octets");if(!Number.isSafeInteger(r)||Math.sign(r)!==1)throw new H("PBES2 Count Input must be a positive integer");let n=Hn(Qr(e),Uint8Array.of(0),t),i=parseInt(e.slice(13,16),10),s={hash:`SHA-${e.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:n},a=await Ui(o,Li(e).subtle,"deriveBits");return new Uint8Array(await crypto.subtle.deriveBits(s,a,i))}function pL(t){return Hn(EE(t.length),t)}async function NOe(t,e,r){let o=e>>3,n=32,i=Math.ceil(o/n),s=new Uint8Array(i*n);for(let a=1;a<=i;a++){let c=await $E("sha256",Hn(EE(a),t,r));s.set(c,(a-1)*n)}return s.slice(0,o)}async function l5(t,e,r,o,n=new Uint8Array,i=new Uint8Array){s5(t),s5(e,"deriveBits");let s=Hn(pL(Qr(r)),pL(n),pL(i),EE(o)),a=new Uint8Array(await crypto.subtle.deriveBits({name:t.algorithm.name,public:t},e,t.algorithm.name==="X25519"?256:Math.ceil(parseInt(t.algorithm.namedCurve.slice(-3),10)/8)<<3));return NOe(a,o,s)}function d5(t){OE(t);let e=t.algorithm.namedCurve;if(e!=="P-256"&&e!=="P-384"&&e!=="P-521"&&t.algorithm.name!=="X25519")throw new Ot("ECDH with the provided key is not allowed or not supported by your javascript runtime")}function qE(t,e){let r=t[e];if(r!==void 0){if(typeof r!="string")throw new H(`JOSE Header "${e}" (Agreement Party${e==="apu"?"U":"V"}Info) invalid`);return po(r,e,H)}}function p5(t,e){if(!(t===void 0||e===void 0||t.byteLength!==e.byteLength)){for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return;throw new H('JOSE Header "apu" and "apv" values must be distinct')}}function zOe(t){if(t===void 0)throw new H("JWE Encrypted Key missing")}function a5(t){if(t!==void 0)throw new H("Encountered unexpected JWE Encrypted Key")}function MOe(t){if(t!==void 0&&t!==1/0&&(!Number.isSafeInteger(t)||t<1))throw new TypeError("maxPBES2Count must be a positive safe integer or Infinity")}async function f5(t,e,r,o,n,i){let{alg:s}=t,a=t.mode;if(a==="direct-encryption")return a5(o),r;let c=a==="direct-key-agreement";switch(c?a5(o):zOe(o),t.subtle.name){case"ECDH":{let{epk:u}=n;if(!br(u)||["d","k","p","q","dp","dq","qi","oth","priv"].some(h=>Object.hasOwn(u,h)))throw new H('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');d5(r);let l=await wf(t,u),d=qE(n,"apu"),p=qE(n,"apv");p5(d,p);let f=await l5(l,r,c?e.alg:s,c?e.cekBits:parseInt(s.slice(-5,-2),10),d,p);if(c)return f;r=f;break}case"RSA-OAEP":return OE(r),c5(s,r,"decrypt"),new Uint8Array(await crypto.subtle.decrypt("RSA-OAEP",r,o));case"PBKDF2":{if(typeof n.p2c!="number")throw new H('JOSE Header "p2c" (PBES2 Count) missing or invalid');MOe(i);let u=i??1e4;if(n.p2c>u)throw new H('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new H('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let l=po(n.p2s,"p2s",H);r=await u5(l,s,n.p2c,r);break}case"AES-GCM":{if(typeof n.iv!="string")throw new H('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new H('JOSE Header "tag" (Authentication Tag) missing or invalid');let u=po(n.iv,"iv",H),l=po(n.tag,"tag",H);if(u.byteLength!==12)throw new H("Invalid Initialization Vector length");if(l.byteLength!==16)throw new H("Invalid Authentication Tag length");return UE(od(s.slice(0,-2)),r,o,u,l,new Uint8Array)}}return DOe(s.slice(-6),r,o)}async function VE(t,e,r,o,n,i={}){let{alg:s,mode:a}=t,c=ji(t);if(n!==void 0&&!c)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${s}`);let u=await Mi(a==="direct-encryption"?e:t,r,"encrypt");if(a==="direct-encryption")return[u,void 0,void 0];let l=c?n??nd(e):void 0;l&&zE(l,e.cekBits);let d,p;switch(t.subtle.name){case"ECDH":{d5(u);let{apu:f,apv:h}=i;f!==void 0&&Io(f,'"apu"'),h!==void 0&&Io(h,'"apv"');let y=f??qE(o,"apu"),w=h??qE(o,"apv");p5(y,w);let b;i.epk!==void 0?b=await Mi(t,i.epk,"decrypt"):b=(await crypto.subtle.generateKey(u.algorithm,!0,["deriveBits"])).privateKey;let S=crypto.subtle,x=b;if(!x.extractable){if(typeof S.getPublicKey!="function")throw new TypeError('CryptoKey for "epk" must be extractable');x=await S.getPublicKey(b,[])}let{x:R,y:T,crv:M,kty:Z}=await S.exportKey("jwk",x),te=a==="direct-key-agreement",Ae=await l5(u,b,te?e.alg:s,te?e.cekBits:parseInt(s.slice(-5,-2),10),y,w),Te={x:R,crv:M,kty:Z};if(Z==="EC"&&(Te.y=T),p={epk:Te},f!==void 0&&(p.apu=or(f)),h!==void 0&&(p.apv=or(h)),te)return[Ae,void 0,p];u=Ae;break}case"RSA-OAEP":{OE(u),c5(s,u,"encrypt"),d=new Uint8Array(await crypto.subtle.encrypt("RSA-OAEP",u,l));break}case"PBKDF2":{let{p2c:f=2048,p2s:h=crypto.getRandomValues(new Uint8Array(16))}=i;u=await u5(h,s,f,u),p={p2c:f,p2s:or(h)};break}case"AES-GCM":{let f=i.iv===void 0?crypto.getRandomValues(new Uint8Array(12)):i.iv;if(!(f instanceof Uint8Array))throw new TypeError('"iv" must be an instance of Uint8Array');let h=await ME(od(s.slice(0,-2)),l,u,f,new Uint8Array);d=h.ciphertext,p={iv:or(h.iv),tag:or(h.tag)}}}if(d??=await OOe(s.slice(-6),u,l),!(d instanceof Uint8Array)||!d.byteLength)throw new TypeError("JWE key management algorithm did not produce an Encrypted Key");return[l,d,p]}function GE(t,e){if(t.zip!==void 0&&t.zip!=="DEF")throw new Ot('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(t.zip!==void 0&&!e?.zip)throw new H('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.')}function m5(t){if(typeof globalThis[t]>"u")throw new Ot(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${t} API.`)}async function h5(t,e,r=1/0){let o=t.writable.getWriter();o.write(e).catch(()=>{}),o.close().catch(()=>{});let n=[],i=0,s=t.readable.getReader();for(;;){let{value:a,done:c}=await s.read();if(c)break;if(n.push(a),i+=a.byteLength,r!==1/0&&i>r)throw new H("Decompressed plaintext exceeded the configured limit")}return Hn(...n)}async function g5(t){return m5("CompressionStream"),h5(new CompressionStream("deflate-raw"),t)}async function y5(t,e){return m5("DecompressionStream"),h5(new DecompressionStream("deflate-raw"),t,e)}function v5(t){let{aad:e,ciphertext:r,iv:o,protected:n,tag:i,unprotected:s}=t;if(o!==void 0&&(typeof o!="string"||!o))throw new H("JWE Initialization Vector incorrect type");if(typeof r!="string")throw new H("JWE Ciphertext missing or incorrect type");if(i!==void 0&&(typeof i!="string"||!i))throw new H("JWE Authentication Tag incorrect type");if(n!==void 0&&typeof n!="string")throw new H("JWE Protected Header incorrect type");if(e!==void 0&&(typeof e!="string"||!e))throw new H("JWE AAD incorrect type");if(s!==void 0&&!br(s))throw new H("JWE Shared Unprotected Header incorrect type");return{aad:e,ciphertext:r,iv:o,protected:n,tag:i,unprotected:s===void 0?void 0:{...s}}}function w5(t){let e,r;try{let{header:o}=t;if(br(o)){r=o.alg;let i=Object.keys(o);i.includes("alg")||(r=void 0),e=Object.fromEntries(i.map(s=>[s,s==="alg"?r:o[s]]))}else e=o;let{encrypted_key:n}=t;return[{encrypted_key:n,header:e},r]}catch(o){return[void 0,r,o]}}function _5(t){let{encrypted_key:e,header:r}=t;if(e!==void 0&&typeof e!="string")throw new H("JWE Encrypted Key incorrect type");if(r!==void 0&&!br(r))throw new H("JWE Per-Recipient Unprotected Header incorrect type");if(t.protected===void 0&&r===void 0&&t.unprotected===void 0)throw new H("JOSE Header missing")}function fL(t){let{protected:e,ciphertext:r,iv:o,tag:n,aad:i}=t,s;return e!==void 0&&(s=yf(e,H,"JWE Protected Header is invalid")),[s,po(r,"ciphertext",H),o!==void 0?po(o,"iv",H):void 0,n!==void 0?po(n,"tag",H):void 0,IE((e??"")+(i!==void 0?`.${i}`:""),"aad",H)]}function HE(t){return[t&&Ey("keyManagementAlgorithms",t.keyManagementAlgorithms),t&&Ey("contentEncryptionAlgorithms",t.contentEncryptionAlgorithms),t?.crit,t?.maxPBES2Count,t?.maxDecompressedLength]}async function mL(t,e,r,o=fL(t)){let[n,i,s,a,c]=o,{header:u,unprotected:l,aad:d}=t,p;if(u!==void 0||l!==void 0){if(!Yc(n,u,l))throw new H("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");p={...n,...u,...l}}else p=n??{};let[f,h,y,w,b]=e,{encrypted_key:S}=t;Qc(H,PE,y,n,p),GE(p,n);let{alg:x,enc:R}=p;if(typeof x!="string"||!x)throw new H("missing JWE Algorithm (alg) in JWE Header");let T=Ha[x];if(S===""&&(!T||!ji(T)))throw new H("JWE Encrypted Key incorrect type");let M=T?.mode==="integrated-encryption";if(!M&&(typeof R!="string"||!R))throw new H("missing JWE Encryption Algorithm (enc) in JWE Header");if(f&&!f.has(x)||!f&&x.startsWith("PBES2"))throw new ed('"alg" (Algorithm) Header Parameter value not allowed');let Z;if(M){if(R!==void 0)throw new H('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(s?.byteLength)throw new H("JWE Initialization Vector must be empty for integrated encryption");if(a?.byteLength)throw new H("JWE Authentication Tag must be empty for integrated encryption")}else{if(h&&!h.has(R))throw new ed('"enc" (Encryption Algorithm) Header Parameter value not allowed');Z=od(R)}let te;if(S!==void 0)try{te=po(S,"encrypted_key",H)}catch(Fe){if(!T||!ji(T))throw Fe;te=new Uint8Array}let Ae=!1;typeof r=="function"&&(r=await r(n,t),Ae=!0);let Te=T??Li(x);ji(Te)&&te===void 0&&(te=new Uint8Array);let bt=await Mi(Te.mode==="direct-encryption"?Z:Te,r,"decrypt"),me;if(Te.mode==="integrated-encryption")me=await Te.decrypt(bt,te,i,c,n,p);else{let Fe=Z,se;try{se=await f5(Te,Fe,bt,te,p,w),ji(Te)&&se instanceof Uint8Array&&se.byteLength<<3!==Fe.cekBits&&(se=nd(Fe))}catch(rr){if(rr instanceof TypeError||rr instanceof H||rr instanceof Ot)throw rr;se=nd(Fe)}me=await UE(Fe,se,i,s,a,c)}if(p.zip==="DEF"){let Fe=b??25e4;if(Fe===0)throw new Ot('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(Fe!==1/0&&(!Number.isSafeInteger(Fe)||Fe<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");me=await y5(me,Fe).catch(se=>{throw se instanceof H?se:new H("Failed to decompress plaintext",{cause:se})})}return{plaintext:me,...n&&{protectedHeader:n},...d!==void 0&&{additionalAuthenticatedData:po(d,"aad",H)},...l&&{sharedUnprotectedHeader:l},...u&&{unprotectedHeader:u},...Ae&&{key:bt}}}async function b5(t,e,r){if(t instanceof Uint8Array&&(t=gf.decode(t)),typeof t!="string")throw new H("Compact JWE must be a string or Uint8Array");let{0:o,1:n,2:i,3:s,4:a,length:c}=t.split(".");if(c!==5)throw new H("Invalid Compact JWE");return mL({ciphertext:s,iv:i||void 0,protected:o,tag:a||void 0,encrypted_key:n||void 0},e,r)}async function Ry(t,e,r){return b5(t,HE(r),e)}async function hL(t,e,r){if(!br(t))throw new H("General JWE must be an object");let o=t.recipients;if(!Array.isArray(o))throw new H("JWE Recipients missing or incorrect type");let n=Array.from(o);if(!n.every(br))throw new H("JWE Recipients missing or incorrect type");if(!n.length)throw new H("JWE Recipients has no members");let i,s,a;try{i=HE(r),s=v5(t),a=fL(s)}catch{throw new Xc}let c=n.map(u=>w5(u));if(n.length>1)for(let[,u]of c){let l=a[0]?.alg??u??s.unprotected?.alg,d=typeof l=="string"?Ha[l]:void 0;if(d&&!ji(d))throw new H(`"${l}" alg may only have a single recipient`)}for(let[u]of c)if(u)try{let l={...s,...u};return _5(l),await mL(l,i,e,a)}catch{}throw new Xc}function KE(t,e,r){if(!Yc(t,e,r))throw new H("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint")}function gL(t,e,r=!1){if(!t[1]&&!t[2]&&!t[3])throw new H("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");e!==void 0&&(t[8]=e?.crit);let[,o,n,i,s,a,c,u,l]=t;if(s!==void 0&&Io(s,"JWE Additional Authenticated Data"),a!==void 0&&Io(a,"JWE Content Encryption Key"),c!==void 0&&Io(c,"JWE Initialization Vector"),!r&&o!==void 0&&(o=rd(H,o)[0],t[1]=o),n!==void 0&&(n=rd(H,n)[0],t[2]=n),!r&&i!==void 0&&(i=rd(H,i)[0],t[3]=i),u!==void 0&&!br(u))throw new TypeError("JWE Key Management Parameters must be an object");KE(o,n,i);let d={...o,...n,...i};kE(H,o),Qc(H,PE,l,o,d),GE(d,o);let{alg:p,enc:f}=d;if(typeof p!="string"||!p)throw new H('JWE "alg" (Algorithm) Header Parameter missing or invalid');let h=Ha[p];if(h?.mode==="integrated-encryption"){if(f!==void 0)throw new H('JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption');if(a!==void 0)throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${p}`);if(c!==void 0)throw new TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${p}`);return[d,void 0,h]}if(typeof f!="string"||!f)throw new H('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');return[d,od(f),h]}async function yL(t,e,r){let[o,n,i]=e,[s,a,c,u,l,d,p,f,,h]=t,y=a,w=c,b=i??Li(o.alg),S,x,R;b.mode==="integrated-encryption"?R=await Mi(b,r,"encrypt"):[R,S,x]=await VE(b,n,r,o,d,f),x&&(h?w=w?{...w,...x}:x:y=y?{...y,...x}:x,KE(y,w,u));let T=y?or(JSON.stringify(y)):"",M=l?.byteLength?or(l):void 0,Z=Qr(M?`${T}.${M}`:T),te=s;o.zip==="DEF"&&(te=await g5(te).catch(Fe=>{throw new H("Failed to compress plaintext",{cause:Fe})}));let Ae,Te,bt;b.mode==="integrated-encryption"?[S,Ae]=await b.encrypt(R,te,Z,y,o,f):{ciphertext:Ae,tag:Te,iv:bt}=await ME(n,te,R,p,Z);let me={ciphertext:or(Ae)};return bt&&(me.iv=or(bt)),Te&&(me.tag=or(Te)),S?.byteLength&&(me.encrypted_key=or(S)),M&&(me.aad=M),y&&(me.protected=T),u&&(me.unprotected=u),w&&(me.header=w),me}async function S5(t,e,r){return yL(t,gL(t,r),e)}function x5(t){return[t.protected,t.encrypted_key,t.iv,t.ciphertext,t.tag].join(".")}var vL=class{#e;state;constructor(e,r,o){this.#e=e,this.state=[void 0,void 0,r,o]}setUnprotectedHeader(e){return Yo(this.state[0],"setUnprotectedHeader"),this.state[0]=e,this}setKeyManagementParameters(e){return Yo(this.state[1],"setKeyManagementParameters"),this.state[1]=e,this}addRecipient(...e){return this.#e.addRecipient(...e)}encrypt(...e){return this.#e.encrypt(...e)}done(){return this.#e}},Iy=class{#e;#t=[];#r;#n;#o;constructor(e){this.#e=e}addRecipient(e,r){let o=new vL(this,e,r?.crit);return this.#t.push(o),o}setProtectedHeader(e){return Yo(this.#r,"setProtectedHeader"),this.#r=e,this}setSharedUnprotectedHeader(e){return Yo(this.#n,"setSharedUnprotectedHeader"),this.#n=e,this}setAdditionalAuthenticatedData(e){return this.#o=e,this}async encrypt(){if(!this.#t.length)throw new H("at least one recipient must be added");Io(this.#e,"plaintext");let e=this.#t.length>1,r,o=this.#r,n=this.#n,i=[];for(let h of this.#t){let[y,w,b,S]=h.state,x=[this.#e,o,y,n,this.#o,void 0,void 0,w,S,e],R=gL(x,void 0,i.length>0);i.length||(o=x[1],n=x[3]),i.push([x,R,b]);let[{alg:T,enc:M},,Z]=R;if(e&&Z&&!ji(Z))throw new H(`"${T}" alg may only have a single recipient`);if(!r)r=M;else if(r!==M)throw new H('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients')}for(let[,h]of i)h[2]??=Li(h[0].alg);let[s,a,c]=i[0],u=e?nd(a[1]):void 0;s[5]=u;let{encrypted_key:l,header:d,...p}=await yL(s,a,c),f={...p,recipients:[{}]};l&&(f.recipients[0].encrypted_key=l),d&&(f.recipients[0].header=d);for(let h=1;h<i.length;h++){let[y,[w,b,S],x]=i[h],R=y[2],[,T,M]=await VE(S,b,x,w,u,y[7]),Z={encrypted_key:or(T)};if(R||M){let te={...R,...M};M&&KE(y[1],te,y[3]),Z.header=te}f.recipients.push(Z)}return f}};var Ay=[["verify"],["sign"]];function wL(t){let e={name:"HMAC",hash:`SHA-${t}`};return{kty:["oct"],secret:!0,subtle:e,signing:e,usages:Ay}}function Sf(t,e){let r={name:e?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${t}`};return{kty:["RSA"],subtle:r,signing:e?{...r,saltLength:e}:r,usages:Ay,minRsaBits:2048}}function _L(t,e){return{kty:["EC"],crv:t,subtle:{name:"ECDSA",namedCurve:t},signing:{name:"ECDSA",hash:`SHA-${e}`},usages:Ay}}function E5(){let t={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:t,signing:t,usages:Ay}}function bL(t){let e={name:`ML-DSA-${t}`};return{kty:["AKP"],subtle:e,signing:e,usages:Ay}}var SL=$y({HS256:wL(256),HS384:wL(384),HS512:wL(512),RS256:Sf(256),RS384:Sf(384),RS512:Sf(512),PS256:Sf(256,32),PS384:Sf(384,48),PS512:Sf(512,64),ES256:_L("P-256",256),ES384:_L("P-384",384),ES512:_L("P-521",512),EdDSA:E5(),Ed25519:E5(),"ML-DSA-44":bL(44),"ML-DSA-65":bL(65),"ML-DSA-87":bL(87)});function BE(t){let e=typeof t=="string"?SL[t]:void 0;if(!e)throw new Ot(`alg ${t} is not supported either by JOSE or your javascript runtime`);return e}function $5(t){return[t&&Ey("algorithms",t.algorithms),t?.crit]}function UOe(t){return t===void 0?{}:yf(t,Yt,"JWS Protected Header is invalid")}function LOe(t){try{return Qr(t)}catch{throw new Yt("JWS Compact Serialization payload must use only ASCII characters")}}async function jOe(t,e,r,o,n){let{protected:i,header:s,payload:a}=t,c=n??UOe(i);if(!Yc(c,s))throw new Yt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let u={...c,...s},l=TE(c,Qc(Yt,AE,e[1],c,u)),{alg:d}=u;if(typeof d!="string"||!d)throw new Yt('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(e[0]&&!e[0].has(d))throw new ed('"alg" (Algorithm) Header Parameter value not allowed');if(l){if(typeof a!="string")throw new Yt("JWS Payload must be a string")}else if(typeof a!="string"&&!(a instanceof Uint8Array))throw new Yt("JWS Payload must be a string or an Uint8Array instance");let p=l||typeof a!="string"?a:o(a),f=!1;typeof r=="function"&&(r=await r(c,t),f=!0);let h=BE(d),y=Hn(i!==void 0?Qr(i):new Uint8Array,Qr("."),typeof p=="string"?e[2]??=IE(p,"payload",Yt):p),w=po(t.signature,"signature",Yt),b=await Mi(h,r,"verify"),S=await Ui(b,h.subtle,"verify");h.minRsaBits&&vf(h.alg,S);let x=!1;try{x=await crypto.subtle.verify(h.signing,S,w,y)}catch{}if(!x)throw new RE;let R={payload:typeof p=="string"?po(p,"payload",Yt):p};return i!==void 0&&(R.protectedHeader=c),s!==void 0&&(R.unprotectedHeader=s),f?[{...R,key:b},l]:[R,l]}async function R5(t,e,r){if(t instanceof Uint8Array&&(t=gf.decode(t)),typeof t!="string")throw new Yt("Compact JWS must be a string or Uint8Array");let{0:o,1:n,2:i,length:s}=t.split(".");if(s!==3)throw new Yt("Invalid Compact JWS");return jOe({payload:n,protected:o,signature:i},e,r,LOe)}async function xL(t,e,r){let[o]=await R5(t,$5(r),e);return o}var xf=class{#e;constructor(e){Io(e,"plaintext"),this.#e=[e]}setContentEncryptionKey(e){return Yo(this.#e[5],"setContentEncryptionKey"),this.#e[5]=e,this}setInitializationVector(e){return Yo(this.#e[6],"setInitializationVector"),this.#e[6]=e,this}setProtectedHeader(e){return Yo(this.#e[1],"setProtectedHeader"),this.#e[1]=e,this}setKeyManagementParameters(e){return Yo(this.#e[7],"setKeyManagementParameters"),this.#e[7]=e,this}async encrypt(e,r){return x5(await S5([...this.#e],e,r))}};async function FOe(t,e,r){let[o,n,i,s]=t,a="";if(n!==void 0){let b=rd(Yt,n);n=b[0],a=or(b[1])}if(i!==void 0&&(i=rd(Yt,i)[0]),!n&&!i)throw new Yt("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Yc(n,i))throw new Yt("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let c={...n,...i};kE(Yt,n);let u=TE(n,Qc(Yt,AE,s,n,c));u||r?.();let{alg:l}=c;if(typeof l!="string"||!l)throw new Yt('JWS "alg" (Algorithm) Header Parameter missing or invalid');let d=BE(l),p="",f=o,h;if(u){let b=t[4];b?(p=b[0]??=or(o),f=b[1]??=Qr(p)):(p=or(o),h=hf.encode(`${a}.${p}`))}h??=Hn(Qr(a),Qr("."),f);let y=await Ui(await Mi(d,e,"sign"),d.subtle,"sign");d.minRsaBits&&vf(d.alg,y);let w={signature:or(new Uint8Array(await crypto.subtle.sign(d.signing,y,h))),payload:p};return n&&(w.protected=a),i&&(w.header=i),[w,u]}async function I5(t,e,r,o,n){let[i]=await FOe([t,e,void 0,r],o,n);return`${i.protected}.${i.payload}.${i.signature}`}var Py=class{#e;#t;constructor(e){Io(e,"payload"),this.#e=e}setProtectedHeader(e){return Yo(this.#t,"setProtectedHeader"),this.#t=e,this}async sign(e,r){return I5(this.#e,this.#t,r?.crit,e,()=>{throw new TypeError("use the flattened module for creating JWS with b64: false")})}};var EL='"alg" (Algorithm)';function $L(t='JWK "alg" (Algorithm) Parameter'){throw new Ot(`Invalid or unsupported ${t} value`)}function ky(t,e){return(typeof t=="string"?SL[t]??Ha[t]:void 0)??$L(e)}async function tu(t){if(sL(t))if(t.type==="secret")t=t.export();else return t.export({format:"jwk"});if(t instanceof Uint8Array)return{kty:"oct",k:or(t)};if(!eu(t))throw new TypeError(Ga(t,"CryptoKey","KeyObject","Uint8Array"));if(!t.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let e=await crypto.subtle.exportKey("jwk",t);delete e.ext,delete e.key_ops,delete e.use,e.kty!=="AKP"&&delete e.alg;for(let r of Object.keys(e))e[r]===void 0&&delete e[r];return e}var Ka=(t,e)=>{if(typeof t!="string"||!t)throw new xy(`${e} missing or invalid`)};async function RL(t,e){let r;if(br(t)){if(r=DE(t),typeof r.kty!="string")throw new TypeError(Ga(t,"CryptoKey","KeyObject","JSON Web Key"))}else if(aL(t))r=DE(await tu(t));else throw new TypeError(Ga(t,"CryptoKey","KeyObject","JSON Web Key"));if(e??="sha256",e!=="sha256"&&e!=="sha384"&&e!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let o;switch(r.kty){case"AKP":Ka(r.alg,'"alg" (Algorithm) Parameter'),Ka(r.pub,'"pub" (Public key) Parameter'),o={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":Ka(r.crv,'"crv" (Curve) Parameter'),Ka(r.x,'"x" (X Coordinate) Parameter'),Ka(r.y,'"y" (Y Coordinate) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":Ka(r.crv,'"crv" (Subtype of Key Pair) Parameter'),Ka(r.x,'"x" (Public Key) Parameter'),o={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":Ka(r.e,'"e" (Exponent) Parameter'),Ka(r.n,'"n" (Modulus) Parameter'),o={e:r.e,kty:r.kty,n:r.n};break;case"oct":if(typeof r.k!="string")throw new xy('"k" (Key Value) Parameter missing or invalid');o={k:r.k,kty:r.kty};break;default:throw new Ot('"kty" (Key Type) Parameter missing or unsupported')}let n=Qr(JSON.stringify(o));return or(await $E(e,n))}async function Qo(t,e,r){if(!br(t))throw new TypeError("JWK must be an object");let o=lL(t),n=NE(r?.extractable),{alg:i}=o;if(e??=i,o.kty!=="oct"&&!e)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');switch(o.kty){case"oct":if(typeof o.k!="string")throw new TypeError('missing "k" (Key Value) Parameter value');return td(o.k);case"AKP":{if(typeof i!="string"||!i)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(e!==i)throw new TypeError("JWK alg and alg option value mismatch");return wf(ky(e),o,n)}case"RSA":case"EC":case"OKP":return wf(ky(e),o,n);default:throw new Ot('Unsupported "kty" (Key Type) Parameter value')}}function IL(t){let e;if(typeof t=="string"){let o=t.split(".");(o.length===3||o.length===5)&&([e]=o)}else if(typeof t=="object"&&t)if("protected"in t)e=t.protected;else throw new TypeError("Token does not contain a Protected Header");let r="Invalid Token or Protected Header formatting";if(typeof e!="string"||!e)throw new TypeError(r);return yf(e,TypeError,r)}function qOe(t){let e=t?.modulusLength??2048;if(typeof e!="number"||!Number.isInteger(e)||e<2048)throw new Ot("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return e}async function Ty(t,e){let r=NE(e?.extractable),o=ky(t,EL);o.secret&&$L(EL);let n;if(o.resolve){let i=e?.crv??"P-256";if(!["P-256","P-384","P-521","X25519"].includes(i))throw new Ot("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519");n=o.resolve({crv:i})}else{if(o.crv!==void 0&&e?.crv!==void 0&&e.crv!==o.crv)throw new Ot(`Invalid or unsupported crv option provided, the only supported value for ${t} is ${o.crv}`);n=o.kty[0]==="RSA"?{...o.subtle,publicExponent:Uint8Array.of(1,0,1),modulusLength:qOe(e)}:o.subtle}return crypto.subtle.generateKey(n,r??!1,[...o.usages[1],...o.usages[0]])}var T5=m.string().regex(/^[a-z]{2}(?:-gov)?-[a-z]+-\d$/),C5=m.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:iam::\d{12}:role\/.+/),A5=m.string().min(1).max(128),P5=m.string().min(1).max(16384),VOe=m.discriminatedUnion("kind",[m.object({kind:m.literal("access_key"),accessKeyId:A5,secretAccessKey:P5}).strict(),m.object({kind:m.literal("session"),accessKeyId:A5,secretAccessKey:P5,sessionToken:m.string().min(1).max(16384),expiresAt:m.number().int().positive().max(Number.MAX_SAFE_INTEGER)}).strict(),m.object({kind:m.literal("environment")}).strict()]),GOe=m.object({arn:C5,externalId:m.string().min(2).max(1224).regex(/^[\w+=,.@:\/-]+$/).optional()}).strict(),Ba=m.object({authentication:VOe,region:T5,role:GOe.optional()}).strict(),ZE=m.object({accountId:m.string().regex(/^\d{12}$/),principalId:m.string().min(1).max(256),arn:m.string().max(2e3).regex(/^arn:aws(?:-us-gov|-cn)?:(?:iam|sts)::\d{12}:.+/)}).strict(),WE=Ba.extend({sourceIdentity:ZE.optional(),identity:ZE.optional()}).strict();function Ef(t){return t.includes(":assumed-role/")?t.slice(0,t.lastIndexOf("/")):t}function k5(t){return{...t,arn:Ef(t.arn)}}function O5(t){return{authentication:t.authentication.kind,region:t.region,role:t.role??null,...t.sourceIdentity?{sourceIdentity:k5(t.sourceIdentity)}:{},...t.identity?{identity:k5(t.identity)}:{}}}var JE=m.object({authentication:m.enum(["access_key","session","environment"]),region:T5,sourceAccountId:m.string().regex(/^\d{12}$/).optional(),sourceArn:m.string().max(2e3).optional(),roleArn:C5.optional(),expiresAt:m.number().int().positive().optional()}).strict();function D5(t){return{authentication:t.authentication.kind,region:t.region,...t.sourceIdentity?{sourceAccountId:t.sourceIdentity.accountId,sourceArn:t.sourceIdentity.arn}:{},...t.role?{roleArn:t.role.arn}:{},...t.authentication.kind==="session"?{expiresAt:t.authentication.expiresAt}:{}}}var N5=m.object({method:m.enum(["GET","POST","PUT","DELETE","PATCH"]),path:m.string().min(1).max(1e3).regex(/^\/[^\s\u0000]*$/)}).strict(),Cy=m.object({account:m.string().min(1),identities:m.array(m.string()),user:m.string().nullable(),description:m.string().nullable(),roles:m.array(m.string()).nullable(),credentialId:m.number().int().positive(),rules:m.array(N5),allowedIPs:m.array(m.string()).nullable(),expiresAt:m.number().nullable()}).strict();function z5(t){return t.map(e=>{let r=e.match(/^(GET|POST|PUT|DELETE|PATCH) (\/[^\s\u0000]*)$/);if(!r)throw new Error("Use one HTTP method and API path for each OVH permission.");return N5.parse({method:r[1],path:r[2]})})}typeof window<"u"&&m.config({jitless:!0});var E=m.uuid(),fe=m.string().trim().min(1).max(200).regex(/^[^\u0000-\u001f\u007f]+$/u),$e=m.iso.datetime(),vr=m.json(),Lt=m.record(m.string(),vr),M5=m.enum(["ja","en"]),U5=m.enum(["read","create","update","delete","share","transfer","reveal","use","execute","manage_credentials","manage_billing","export"]);var L5=m.enum(["variable","connection","service","method","app","object","environment","function","keyring"]),bn=m.object({kty:m.literal("EC"),crv:m.literal("P-256"),x:m.string().min(40).max(50),y:m.string().min(40).max(50)}).strict(),HOe=m.object({alg:m.literal("dir"),enc:m.literal("A256GCM"),sub:E}).strict(),e$=m.string().max(16384).regex(/^[A-Za-z0-9_-]+\.\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{22}$/).refine(t=>{try{return HOe.safeParse(IL(t)).success}catch{return!1}},"Use an A256GCM JWE for the wrapped encryption key.").brand(),Ao=m.object({protected:m.string().max(2048),iv:m.string().max(64),ciphertext:m.string().max(2e6),tag:m.string().max(64),aad:m.string().max(2048).optional(),recipients:m.array(m.object({encrypted_key:m.string().max(2048),header:m.object({kid:E,epk:bn.optional(),alg:m.string().optional()}).passthrough()})).min(1).max(100)}).strict(),Wwt=m.object({id:E,name:fe,publicKey:bn}),ru=m.object({id:E,name:fe,owner:m.object({id:E,name:fe}).nullable(),createdAt:$e,permissions:m.array(U5),createKinds:m.array(L5),publicKey:bn.nullable()}),j5=m.object({id:E,kind:m.enum(["passkey","email","key"]),name:m.string(),createdAt:$e,lastUsedAt:$e.nullable(),expiresAt:$e.nullable(),canOpen:m.boolean()}),F5=m.string().regex(/^[a-z][a-z_]*[a-z]$/).max(64),KOe=m.object({subjectId:E,relation:F5,objectId:E}).strict(),Jwt=KOe.extend({objectType:m.enum(["principal",...L5.options]),subjectName:fe,objectName:fe,createdAt:$e}),Xwt=m.object({error:m.object({code:m.string(),message:m.string(),details:vr.optional()})}),Ywt=m.object({ok:m.literal(!0)}),BOe=m.object({value:m.string().min(1).max(200),label:m.string().min(1).max(200),values:m.record(m.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),m.string()).default({})}).strict(),t$=m.object({name:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),label:m.string(),secret:m.boolean().optional(),inputType:m.enum(["text","password"]).optional(),required:m.boolean().optional(),placeholder:m.string().optional(),note:m.string().optional(),pattern:m.string().optional(),choices:m.array(BOe).min(1).max(100).optional(),defaultValue:m.string().max(1e3).optional(),when:m.object({field:m.string(),values:m.array(m.string()).min(1)}).strict().optional(),visibility:m.enum(["application","connection"]).optional()}).superRefine((t,e)=>{let r=t.choices??[];new Set(r.map(o=>o.value)).size!==r.length&&e.addIssue({code:"custom",path:["choices"],message:"Use a unique value for each choice."})}),AL=m.record(m.string().regex(/^[A-Z_][A-Z0-9_]*$/),m.string()),ZOe=m.record(m.string().regex(/^[A-Z_][A-Z0-9_]*$/),m.union([m.string(),m.array(m.union([m.string().max(8192),m.object({pointer:m.string().max(1e3)}).strict()])).min(1).max(32)])),PL=m.object({values:m.array(m.object({id:m.string(),name:m.string(),description:m.string().optional()})).optional(),default:m.array(m.string()).default([]),required:m.array(m.string()).optional(),separator:m.string().default(" "),docs:m.url().optional()}),id=m.string().min(1).max(4096),YE=m.union([m.string(),m.array(m.string()).min(1)]),WOe=m.object({application:m.enum(["required","implicit"]).default("required"),grantType:m.enum(["authorization_code","client_credentials"]).optional(),issuer:m.url().optional(),registrationUrl:m.url().optional(),authorizeUrl:id.optional(),tokenUrl:id,identity:m.object({url:id.optional(),from:m.enum(["token","app"]).optional(),method:m.enum(["GET","POST"]).default("GET"),id:YE.default("/id"),name:YE.default("/name"),headers:m.record(m.string(),m.string()).default({})}).optional(),revoke:m.object({url:id,style:m.enum(["rfc7009","bearer","github","delete"]).default("rfc7009"),auth:m.enum(["body","basic","none"]).optional(),tokenOnly:m.literal(!0).optional()}).optional(),clientAuth:m.enum(["body","basic","none"]).default("body"),pkce:m.boolean().default(!0),tokenFormat:m.enum(["form","json"]).default("form"),okPointer:m.string().optional(),authorizeParams:m.record(m.string(),m.string()).default({}),tokenParams:m.record(m.string(),m.string()).default({}),defaults:m.record(m.string(),m.string()).default({}),scopes:PL.default({default:[],separator:" "}),fields:m.array(t$).default([]),outputs:AL.default({ACCESS_TOKEN:"/accessToken"}),adapter:m.string().regex(/^[a-z][a-z0-9_-]{0,99}$/).optional(),keep:m.array(m.string()).default([]),hint:m.string().optional()}).refine(t=>t.grantType==="client_credentials"||!!t.authorizeUrl,{path:["authorizeUrl"],message:"An authorization code flow requires an authorization URL."}),JOe=m.object({fields:m.array(t$).min(1),outputs:ZOe,resolver:m.literal("vultr-role").optional(),bindFields:m.boolean().optional(),constants:m.record(m.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/),m.string()).optional(),identity:m.object({url:id,headers:m.record(m.string(),m.string()),id:YE,name:YE}).strict().optional(),console:m.url().optional(),instructions:m.string().optional(),hint:m.string().optional()}),kL=m.enum(["oauth","token","aws","ovh","approval"]),XOe=m.object({hint:m.string().optional()}).strict(),YOe=m.object({authorization:m.enum(["api_key","consumer_key"]),apiBaseUrl:id,fields:m.array(t$).min(1),scopes:PL.default({default:[],separator:`
129
+ `}),outputs:AL,hint:m.string().optional()}).strict(),Ny={name:fe,docs:m.url().optional(),console:id.optional()},r$=m.object({...Ny,kind:m.literal("oauth"),config:WOe}).strict(),n$=m.object({...Ny,kind:m.literal("token"),config:JOe}).strict(),o$=m.object({...Ny,kind:m.literal("aws"),config:XOe}).strict(),i$=m.object({...Ny,kind:m.literal("ovh"),config:YOe}).strict(),s$=m.object({...Ny,kind:m.literal("approval"),config:m.object({adapter:m.literal("runpod-flash"),fields:m.array(t$).default([]),scopes:PL.default({default:[],separator:" "}),outputs:AL,hint:m.string().optional()}).strict()}).strict(),nu=m.discriminatedUnion("kind",[r$,n$,o$,i$,s$]),Oy={id:m.string().min(1),builtin:m.boolean(),availability:m.enum(["ready","app-required","unavailable"]),defaultName:fe,registration:m.object({kind:m.enum(["input","authorization"]),device:m.enum(["browser","cli"]),browserExchange:m.enum(["available","unavailable","unknown"]),tokenAlternatives:m.array(m.string())}).strict()},zy=m.discriminatedUnion("kind",[r$.extend(Oy),n$.extend(Oy),o$.extend(Oy),i$.extend(Oy),s$.extend(Oy)]),Dy=m.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),TL=m.object({name:fe,logo:m.string().regex(/^[a-z0-9-]+$/).optional(),api:m.url().optional(),docs:m.url().optional(),console:m.url().optional(),targets:m.array(m.object({id:Dy,name:fe,api:m.url().optional(),methods:m.array(Dy).min(1)}).strict()).max(32).optional()}).strict(),QOe=TL.extend({methods:m.record(Dy,m.string().min(1))}).strict(),q5=TL.extend({methods:m.record(Dy,m.union([m.string().min(1),nu]))}).strict(),Qwt=TL.extend({id:m.string(),builtin:m.boolean(),methods:m.record(Dy,zy)}),V5=m.object({id:E,output:m.string().min(1).max(100).optional()}).strict(),G5=t=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(t)&&!/^(FOUNDATION_|LD_|DYLD_)|^(NODE_OPTIONS|BASH_ENV|ENV|PYTHONSTARTUP|GIT_CONFIG_COUNT|GIT_CONFIG_SYSTEM)$/u.test(t),CL=m.object({name:m.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),source:V5,format:m.enum(["text","file","json"]).default("text"),pointer:m.string().optional()}).strict(),eDe=m.object({pointer:m.string().max(500),parts:m.array(m.union([m.string().max(8192),V5])).min(1).max(32)}).strict(),Za=m.object({url:m.string().max(4096),method:m.enum(["GET","HEAD","POST","PUT","PATCH","DELETE"]).default("GET"),headers:m.record(m.string(),m.string().max(8192)).default({}),body:m.string().max(1e6).optional(),json:vr.optional(),form:m.record(m.string(),m.string()).optional(),bindings:m.array(eDe).max(32).default([])}).strict(),Wa=m.object({command:m.array(m.string().max(8192)).min(1).max(100),stdin:m.string().max(1e6).optional(),timeoutSeconds:m.number().int().min(1).max(3600).default(60),inputs:m.array(CL).max(32).default([])}).strict(),H5=m.discriminatedUnion("kind",[Wa.omit({stdin:!0}).extend({kind:m.literal("command")}).strict(),m.object({kind:m.literal("http"),request:Za,responseFormat:m.enum(["text","json"]).default("json")}).strict()]),ei=m.object({description:m.string().max(2e3).default(""),environmentId:E,program:H5,inputAccess:m.object({expiresAt:$e.nullable().default(null)}).strict().default({expiresAt:null}),parameters:m.array(m.object({name:m.string().regex(/^[A-Za-z][A-Za-z0-9_]*$/),label:m.string().max(100),type:m.enum(["string","number","boolean","json"]).default("string"),required:m.boolean().default(!0),default:vr.optional()}).strict()).max(32).default([]),result:m.enum(["text","json"]).default("json")}).strict(),Ja={id:E,ownerId:E,name:fe,createdAt:$e,updatedAt:$e,version:m.number().int().positive(),permissions:m.array(U5)},tDe=m.enum(["starting","running","stopping","stopped","failed"]),rDe=m.object({state:m.enum(["pending","failed","complete"]),error:m.string().nullable()}),nDe=m.object({idleSeconds:m.number().int().min(60).max(86400).default(3600),maxSeconds:m.number().int().min(60).max(86400).default(3600)}).strict(),K5=m.object({image:m.string().min(1).max(300).optional(),size:m.enum(["small","medium","large"]).default("small"),lifetime:nDe.default({idleSeconds:3600,maxSeconds:3600}),ssh:Sy.optional()}).strict(),OL={recipients:m.array(E).default([]),executors:m.array(E).default([]),custodyRevision:m.number().int().positive().nullable().default(null)},oDe=m.object({...Ja,kind:m.literal("variable"),data:m.object({...OL,bytes:m.number().int().nonnegative()})}),iDe=m.object({...Ja,kind:m.literal("connection"),data:m.object({...OL,methodId:m.string(),fields:m.record(m.string(),m.string()).default({}),settings:m.array(m.object({name:m.string(),label:m.string(),value:m.string()})).default([]),methodName:m.string(),methodKind:kL,services:m.array(m.object({id:m.string(),name:fe})).default([]),account:m.string(),accountId:m.string().nullable().default(null),accountVerified:m.boolean().default(!1),scopes:m.array(m.string()),scopesStatus:m.enum(["unknown","requested","reported"]).default("unknown"),outputs:m.array(m.string()),state:m.enum(["ready","reconnect","review","disconnecting","uncertain"]),revocable:m.boolean().default(!1),appId:E.nullable(),generation:E.optional(),authorizationDigest:m.string().optional(),aws:JE.optional(),ovh:Cy.optional()})}),sDe=m.object({...Ja,kind:m.literal("service"),data:QOe}),aDe=m.object({...Ja,kind:m.literal("method"),data:nu}),cDe=m.object({...Ja,kind:m.literal("app"),data:m.object({...OL,methodId:m.string(),clientId:m.string(),fields:m.record(m.string(),m.string()).default({}),generation:E.optional()})}),uDe=m.object({...Ja,kind:m.literal("object"),data:m.object({size:m.number().int().nonnegative(),contentType:m.string()})}),lDe=m.object({...Ja,kind:m.literal("environment"),data:K5.extend({executorId:E.optional(),operatorId:E.optional(),driver:m.enum(["attached","managed"]).optional(),capabilities:m.array(m.string()).optional(),isolation:m.enum(["process","container"]).optional(),manifestDigest:m.string().optional(),processes:m.object({workingDirectory:m.string()}).optional(),ssh:rL.optional(),awsPrincipal:m.string().optional(),state:tDe,connected:m.boolean(),deletion:rDe.optional(),startedAt:$e.nullable(),stoppedAt:$e.nullable(),lastActiveAt:$e,error:m.string().nullable()})}),a$=m.object({...Ja,kind:m.literal("function"),data:ei.omit({environmentId:!0,program:!0}).extend({environmentId:E.optional(),program:H5.optional()})}),dDe=m.object({...Ja,kind:m.literal("keyring"),data:m.object({revision:m.number().int().positive(),signature:m.string()})}),Sr=m.discriminatedUnion("kind",[oDe,iDe,sDe,aDe,cDe,uDe,lDe,a$,dDe]),e_t=m.discriminatedUnion("kind",[m.object({kind:m.literal("service"),name:fe,definition:q5}).strict(),m.object({kind:m.literal("method"),name:fe,definition:nu}).strict(),m.object({kind:m.literal("environment"),name:fe.optional(),options:K5}).strict()]),t_t=m.object({version:m.number().int().positive(),name:fe.optional(),definition:m.union([q5,nu]).optional()}).strict(),Fi=m.object({name:m.string().regex(/^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*)+$/),input:Lt}).strict(),c$=Fi.extend({inputs:m.array(m.object({pointer:m.string(),label:m.string().min(1).max(100),secret:m.boolean().default(!1),multiline:m.boolean().default(!1),site:m.url().optional()}).strict()).max(16).default([])}),QE=m.object({ja:m.string(),en:m.string()}).strict(),DL=c$.extend({title:QE,execution:m.enum(["server","keyholder"]),configure:m.array(m.string()),environment:m.object({required:m.boolean(),reason:QE.nullable()}).strict()}),B5=m.object({to:E.optional(),executionId:E.optional(),message:m.string().max(1e3).default(""),operations:m.array(c$).min(1).max(8).optional(),expiresInMinutes:m.number().int().min(1).max(1440).default(30)}).strict().superRefine((t,e)=>{!!t.executionId==!!t.operations&&e.addIssue({code:"custom",message:"Choose an execution or supply processing definitions."})}),XE=m.object({id:E,name:fe}),Z5=m.discriminatedUnion("kind",[m.object({kind:m.literal("line"),subject:XE,relation:F5,object:XE}),m.object({kind:m.literal("transfer"),item:XE,to:XE})]),u$=m.object({id:E,executionId:E,from:ru.pick({id:!0,name:!0}),to:ru.pick({id:!0,name:!0}).nullable(),message:m.string(),purpose:m.enum(["input","approval"]),state:m.enum(["pending","accepted","declined","cancelled","expired"]),createdAt:$e,expiresAt:$e,url:m.url(),code:m.string().optional(),returnUrl:m.url().nullable(),refreshUrl:m.url().nullable(),canRespond:m.boolean(),canCancel:m.boolean()}),r_t=m.object({id:E,name:fe,publicKey:bn,state:m.enum(["pending","approving","approved"]),principalId:E.nullable(),createdAt:$e,expiresAt:$e}),n_t=m.object({available:m.boolean(),required:m.boolean(),active:m.boolean(),payer:ru.pick({id:!0,name:!0}).nullable()}),o_t=m.object({storageBytes:m.number().nonnegative(),storageLimit:m.number().positive(),computeSeconds:m.number().nonnegative(),computeLimit:m.number().positive(),month:m.string()}),i_t=m.object({id:m.string(),actorId:E.nullable(),action:m.string(),targetId:E.nullable(),createdAt:$e,details:Lt}),s_t=m.object({returnUrl:m.url().optional(),refreshUrl:m.url().optional()}).strict(),Mr=t=>m.object({items:m.array(t),next:m.string().nullable().default(null)}),a_t=m.object({id:E}),c_t=m.object({owner:E}),pDe=m.object({limit:m.coerce.number().int().min(1).max(200).default(100),after:m.string().optional()}),u_t=pDe.extend({object:E.optional(),subject:E.optional()}).refine(t=>!!t.object!=!!t.subject,"Choose the object or the subject of the lines.");var fDe=m.object({email:m.boolean(),environments:m.boolean(),ssh:m.boolean(),objects:m.boolean(),payments:m.boolean()}),l$=m.object({principal:ru.nullable(),credentialId:E.nullable(),wrappedKey:e$.nullable(),requestId:E.nullable(),server:m.object({name:fe}),features:fDe,principals:m.array(ru)}),f_t=m.object({email:m.email().max(254),returnTo:m.string().max(2048).optional(),locale:M5.default("ja"),principalId:E.optional()}).strict(),m_t=m.object({intent:m.enum(["register","authenticate"]),name:fe.optional(),principalId:E.optional(),returnTo:m.string().max(2048).optional()}).strict(),h_t=m.object({challengeId:E,credential:m.json(),publicKey:bn.optional(),existingPublicKey:bn.optional(),wrappedKey:e$.optional()}).strict();var mDe=new TextEncoder,hDe=new TextDecoder,My="ECDH-ES+A256KW",NL="A256GCM",tt=t=>mDe.encode(t),Kn=t=>hDe.decode(t);function Ds(t){let e="";for(let r=0;r<t.length;r+=8192)e+=String.fromCharCode(...t.subarray(r,r+8192));return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function d$(t){return Uint8Array.from(atob(t.replaceAll("-","+").replaceAll("_","/")),e=>e.charCodeAt(0))}async function p$(){let t=await Ty(My,{crv:"P-256",extractable:!0});return{publicKey:bn.parse(await tu(t.publicKey)),privateKey:await tu(t.privateKey)}}async function Xa(t,e,r){if(!e.length||new Set(e.map(n=>n.id)).size!==e.length)throw new Error("Recipients must be distinct and nonempty.");let o=new Iy(t).setProtectedHeader({enc:NL}).setAdditionalAuthenticatedData(tt(r));for(let n of e)o.addRecipient(await Qo(n.publicKey,My)).setUnprotectedHeader({alg:My,kid:n.id});return Ao.parse(await o.encrypt())}async function Po(t,e,r,o){if(t.aad!==Ds(tt(o)))throw new Error("The encrypted content belongs to a different item.");let n=t.recipients.find(a=>a.header.kid===r);if(!n)throw new Error("This principal cannot decrypt the content.");let i=e instanceof CryptoKey?e:await Qo(e,My);return(await hL({...t,recipients:[n]},i,{keyManagementAlgorithms:[My],contentEncryptionAlgorithms:[NL]})).plaintext}async function gDe(t){let e=await crypto.subtle.importKey("raw",new Uint8Array(t),"HKDF",!1,["deriveBits"]);return new Uint8Array(await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:tt("Foundation"),info:tt("passkey encryption key")},e,256))}async function W5(t,e,r){let o=await Ry(t,await gDe(e),{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[NL]});if(o.protectedHeader.sub!==r)throw new Error("The key belongs to a different principal.");return JSON.parse(Kn(o.plaintext))}var xr=m.string().regex(/^[A-Za-z0-9_-]{43}$/),cr=m.string().min(100).max(4e6),J5=bn.extend({d:m.string().regex(/^[A-Za-z0-9_-]{43}$/)}),Uy=m.object({encryption:J5,signing:J5}).strict(),Kt=m.object({id:E,principalId:E,generation:m.number().int().positive(),previous:xr.nullable(),encryption:bn,signing:bn}).strict();function C(t){if(t===null||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)||typeof t=="string"&&!/[\uD800-\uDFFF]/u.test(t))return JSON.stringify(t);if(Array.isArray(t))return"["+Array.from(t,C).join(",")+"]";if(t&&typeof t=="object"&&Object.getPrototypeOf(t)===Object.prototype)return"{"+Object.keys(t).sort().map(e=>{if(/[\uD800-\uDFFF]/u.test(e))throw new Error("Use Unicode property names.");return JSON.stringify(e)+":"+C(t[e])}).join(",")+"}";throw new Error("Use finite numbers, Unicode strings, arrays, and plain JSON objects.")}async function $f(t){return RL(bn.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y}),"sha256")}async function Q(t){return Ds(new Uint8Array(await crypto.subtle.digest("SHA-256",tt(C(t)))))}async function Ya(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",tt(C(t))));return"sha256:"+Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}async function m$(){let[t,e]=await Promise.all([p$(),Ty("ES256",{crv:"P-256",extractable:!0})]),r=await tu(e.privateKey);return Uy.parse({encryption:t.privateKey,signing:r})}function f$(t){return bn.parse({kty:t.kty,crv:t.crv,x:t.x,y:t.y})}function h$(t,e){return Kt.parse({id:crypto.randomUUID(),principalId:t,generation:1,previous:null,encryption:f$(e.encryption),signing:f$(e.signing)})}async function ir(t,e,r){let o=e instanceof CryptoKey?e:await Qo(e,"ES256");return new Py(tt(C(t))).setProtectedHeader({alg:"ES256",typ:"foundation."+r+"+jws"}).sign(o)}async function Ur(t,e,r,o){if(C(await Ly(e,r,o))!==C(t))throw new Error("The signature does not authorize this content.")}async function Ly(t,e,r){let o=await xL(t,await Qo(bn.parse(e),"ES256"),{algorithms:["ES256"]});if(o.protectedHeader.typ!=="foundation."+r+"+jws"||Object.keys(o.protectedHeader).some(s=>!["alg","typ"].includes(s)))throw new Error("The signature does not authorize this content.");let n=new TextDecoder("utf-8",{fatal:!0}).decode(o.payload),i=JSON.parse(n);if(C(i)!==n)throw new Error("Sign canonical JSON content.");return i}var Ns=m.object({binding:Kt,signature:cr}).strict();async function jy(t,e){if(await zs(t),await $f(e.encryption)!==await $f(t.encryption)||await $f(e.signing)!==await $f(t.signing))throw new Error("The private keys do not match this identity.");return{binding:t,signature:await ir(t,e.signing,"key-binding")}}async function zs(t){let e=Kt.parse(t);if(e.generation===1!=(e.previous===null))throw new Error("Link each replacement key to its preceding binding.");if(await $f(e.encryption)===await $f(e.signing))throw new Error("Use separate encryption and signing keys.");await Qo(e.encryption,"ECDH-ES+A256KW"),await Qo(e.signing,"ES256")}async function g$(t){let{binding:e,signature:r}=Ns.parse(t);return await zs(e),await Ur(e,r,e.signing,"key-binding"),e}var X5=m.object({ownerId:E,name:fe,resourceId:E.optional(),version:m.number().int().positive().optional(),environmentIds:m.array(E).max(32).optional()}).strict(),Y5=X5.extend({value:m.literal("").optional()}),zL=X5.extend({methodId:m.string().min(1).max(200),clientId:m.string().max(1e3),fields:m.record(m.string(),m.string()).optional(),clientSecret:m.literal("").optional()}),Rf=m.object({ownerId:E,name:fe,definition:ei,resourceId:E.optional(),version:m.number().int().positive().optional()}).strict(),y$=m.object({ownerId:E,connectionId:E,environmentId:E}).strict(),Q5=m.object({ownerId:E,connectionId:E,version:m.number().int().positive(),users:m.array(E).max(32),expiresAt:m.iso.datetime().optional()}).strict(),e8=m.object({ownerId:E,methodId:m.string().min(1).max(200),connectionId:E.optional(),name:fe.optional(),appId:E.optional(),redirectUri:m.url().optional(),users:m.array(E).max(32).optional(),scopes:m.array(m.string().min(1).max(1e3)).max(200).optional(),methodDigest:m.string().regex(/^[A-Za-z0-9_-]{43}$/).optional(),clientId:m.string().max(1e3).optional(),fields:m.record(m.string(),m.string()).optional(),clientSecret:m.literal("").optional()}).strict(),Fy=m.object({ownerId:E,environmentId:E.optional(),operation:m.union([m.object({kind:m.literal("http"),request:Za}).strict(),Wa.extend({kind:m.literal("command")}),m.object({kind:m.enum(["http","command"]),programId:E,programDigest:m.string().regex(/^[A-Za-z0-9_-]{43}$/)}).strict()]),save:m.record(m.string(),fe).default({})}).strict().superRefine((t,e)=>{t.environmentId||e.addIssue({code:"custom",path:["environmentId"],message:"Choose an execution environment."})}),v$=m.object({name:Fi.shape.name,title:QE,execution:m.enum(["server","keyholder"]),configure:m.array(m.string()),environment:DL.shape.environment,input:Lt}).strict(),t8=m.object({id:E.optional(),operations:m.array(c$).min(1).max(8),responderId:E.optional(),message:m.string().max(1e3).default(""),expiresInMinutes:m.number().int().min(1).max(1440).default(1440)}).strict(),r8=m.object({values:m.array(Lt).max(8).default([]),configuration:m.array(Lt).max(8).default([]),code:m.string().max(20).optional()}).strict(),If=m.object({index:m.number().int().nonnegative(),invocation:Fi,approval:m.object({id:E,index:m.number().int().nonnegative()}).strict().optional(),continuation:m.object({kind:m.enum(["connection","run"]),id:E}).strict().nullable()}).strict(),Ze=m.object({id:E,actorId:E,ownerId:E,requests:m.array(E),steps:m.array(m.object({index:m.number().int().nonnegative(),name:Fi.shape.name,state:m.enum(["waiting","running","succeeded","failed","uncertain","cancelled"]),runs:m.array(m.object({kind:m.enum(["run","function"]),id:E}).strict())}).strict()),creator:ru.pick({id:!0,name:!0}),operations:m.array(DL),approval:m.object({requestId:E.nullable(),proposal:Z5.nullable()}).strict().nullable(),canContinue:m.boolean(),canCancel:m.boolean(),url:m.url(),code:m.string().optional(),error:m.object({code:m.string(),message:m.string()}).strict().nullable(),index:m.number().int().nonnegative(),state:m.enum(["waiting","running","succeeded","failed","uncertain","cancelled"]),wait:m.enum(["approval","input","execution"]).nullable(),waiting:If.nullable(),results:m.array(vr.nullable()),createdAt:m.iso.datetime(),expiresAt:m.iso.datetime()}).strict(),n8=m.object({id:E,index:m.number().int().nonnegative(),invocation:Fi,continuationId:E.optional()}).strict();var Af=m.url().refine(t=>{let e=new URL(t);return e.origin===t&&!e.username&&!e.password&&(e.protocol==="https:"||e.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(e.hostname))},"Use an HTTPS origin, or HTTP on localhost."),he={value:"03546b17-fa44-409f-b151-8da1a398b324",tokenSet:"7d4b64dd-4546-4acb-8e96-91f864bccea6",clientCredential:"714fc044-2cce-4f3f-a477-281ee64fe632",executionResult:"71eacb19-c2e3-49cb-b7d3-f3f634f5c887"},yDe=m.enum([he.value,he.tokenSet,he.clientCredential,he.executionResult]),i8=t=>t===he.executionResult?14e5:1e6,ue={http:"bdf57b0a-bce9-4a1d-ad62-0ccd73578e7a",command:"85bb00b6-ca1e-478d-94ca-a217f0c73e49",function:"b6b12c71-7a51-4f18-930c-48e6f511a963",connect:"5c0d6e68-61ef-4023-8500-05defca4edf1",refresh:"00bc45aa-7b68-4350-b73e-eda476c6236c",revoke:"832624ed-e6bb-4829-80a4-283f5333ce63"},qy=m.enum([ue.http,ue.command,ue.function,ue.connect,ue.refresh,ue.revoke]);var vDe={[he.value]:[ue.http,ue.command,ue.function],[he.tokenSet]:[ue.http,ue.command,ue.function,ue.refresh,ue.revoke],[he.clientCredential]:[ue.connect,ue.refresh,ue.revoke],[he.executionResult]:[]},ou=t=>vDe[t],s8=t=>ou(t).filter(e=>e===ue.function||e===ue.refresh),ML=t=>t===he.tokenSet,wDe=m.object({id:E,digest:xr}).strict(),_De=m.object({actor:Kt,executor:Kt,operations:m.array(qy).min(1).max(6),functionDigests:m.array(xr).max(100).default([]),origins:m.array(Af).max(100).default([]),callerProgram:m.boolean().default(!1),expiresAt:$e}).strict(),bDe=m.object({function:wDe,executor:Kt,operations:m.array(qy).min(1).max(6),expiresAt:$e.nullable()}).strict(),SDe=m.union([_De,bDe]);function Qa(t,e=Date.now()){return t.expiresAt===null||Date.parse(t.expiresAt)>e}function Pf(t){return t.expiresAt===null?1/0:Date.parse(t.expiresAt)}var en=m.object({format:m.literal(2),origin:Af,id:E,ownerId:E,contentType:yDe,revision:m.number().int().positive(),authorities:m.array(Kt).min(1).max(100),readers:m.array(Kt).min(1).max(100),grants:m.array(SDe).max(100),observers:m.array(E).max(100).optional(),producers:m.array(m.object({executor:Kt,runId:E,expiresAt:$e,materialRevision:m.number().int().positive().default(1)}).strict()).max(100).default([])}).strict(),o8=m.object({ownerId:E,authorities:m.array(Kt).min(1).max(100)}).strict(),a8=m.object({origin:Af,id:E,revision:m.number().int().positive(),from:o8,to:o8,policyDigest:xr,previous:xr.nullable(),signerId:E}).strict(),xDe=a8.extend({signature:cr}),UL=m.array(xDe).max(16),Vy=m.object({policy:en,authorityId:E,signature:cr,lineage:UL.optional()}).strict(),tn=m.object({policy:en,authorityId:E,authorization:cr,lineage:UL.optional(),materialRevision:m.number().int().positive(),updatedAt:$e,creationRunId:E.nullable(),metadata:Lt,sealed:Ao,signerId:E,signature:cr}).strict(),sd=t=>({ownerId:t.ownerId,authorities:t.authorities});async function c8(t,e=[]){let r;for(let o of e){let{signature:n,...i}=o;if(o.origin!==t.origin||o.id!==t.id||o.revision>t.revision||r&&(o.revision<=r.revision||C(r.to)!==C(o.from))||o.previous!==(r?await Q(r):null))throw new Error("Keep the signed chain of authority changes for this item.");let s=o.from.authorities.find(a=>a.id===o.signerId);if(!s)throw new Error("Only an existing authority can hand over this item.");await Ur(i,n,s.signing,"authority-handoff"),r=o}if(r&&C(r.to)!==C(sd(t)))throw new Error("Use the authorities approved by the latest handoff.")}function LL(t){let e=t.policy.authorities.find(n=>n.id===t.authorityId);if(e)return e;let r=t.lineage?.at(-1),o=r?.revision===t.policy.revision?r.from.authorities.find(n=>n.id===t.authorityId):void 0;if(!o||o.id!==r?.signerId)throw new Error("The policy must be signed by an approved authority.");return o}function w$(t,e){if(t.id!==e.policy.id||t.origin!==e.policy.origin||t.contentType!==e.policy.contentType)return!1;let r=C(sd(t));return r===C(sd(e.policy))?!0:!!e.lineage?.some(o=>o.revision>t.revision&&C(o.from)===r)}async function u8(t,e,r,o){let n=[...t?.lineage??[]];if(t&&C(sd(t.policy))!==C(sd(e))){if(await ko(t),!t.policy.authorities.some(s=>C(s)===C(r))||t.policy.id!==e.id||t.policy.origin!==e.origin||t.policy.contentType!==e.contentType||e.revision!==t.policy.revision+1)throw new Error("An existing authority must approve this handoff at the next policy revision.");let i=a8.parse({origin:e.origin,id:e.id,revision:e.revision,from:sd(t.policy),to:sd(e),policyDigest:await Q(e),previous:n.length?await Q(n.at(-1)):null,signerId:r.id});n.push({...i,signature:await ir(i,o.signing,"authority-handoff")})}return n.length?{lineage:UL.parse(n)}:{}}async function _$(t){let e=en.parse(t),r=[...e.authorities,...e.readers,...e.grants.flatMap(n=>"actor"in n?[n.actor,n.executor]:[n.executor]),...e.producers.map(n=>n.executor)],o=new Map;for(let n of r){await zs(n);let i=C(n);if(o.has(n.id)&&o.get(n.id)!==i)throw new Error("Each key binding must identify the same keys throughout a policy.");o.set(n.id,i)}for(let n of[e.readers,e.authorities])if(new Set(n.map(i=>i.id)).size!==n.length)throw new Error("Choose distinct key bindings.");for(let n of e.authorities)if(!e.readers.some(i=>i.id===n.id))throw new Error("A policy authority must be able to open its content.");for(let n of e.grants){if(new Set(n.operations).size!==n.operations.length||n.operations.some(i=>!ou(e.contentType).includes(i)))throw new Error("Grant only the operations this kind of content supports.");if("function"in n){if(n.operations.some(i=>i!==ue.function&&i!==ue.refresh))throw new Error("Function grants authorize the saved function and its credential renewal.");continue}if(n.operations.some(i=>i===ue.http||i===ue.command)&&!n.callerProgram)throw new Error("Explicitly authorize caller-supplied programs before allowing arbitrary execution.");if(n.operations.includes(ue.function)&&!n.functionDigests.length&&!n.callerProgram)throw new Error("Choose the exact functions this grant authorizes.")}return e}function b$(t){return[...new Map([...t.readers,...t.grants.map(e=>e.executor)].map(e=>[e.id,e])).values()]}async function iu(t,e){return C({purpose:"resource",policyDigest:await Q(t),materialRevision:e})}async function ad(t,e,r,o,n,i,s){if(t.byteLength>i8(e.contentType))throw new Error("The content exceeds its storage limit.");let a=await _$(e),c=await u8(s,a,o,n);if(!a.authorities.some(p=>C(p)===C(o))&&c.lineage?.at(-1)?.revision!==a.revision)throw new Error("Only a policy authority can replace its content.");let u=await Xa(t,b$(a).map(p=>({id:p.id,publicKey:p.encryption})),await iu(a,r)),l={policy:a,...c,authorityId:o.id,authorization:await ir(a,n.signing,"access-policy"),materialRevision:r,updatedAt:new Date().toISOString(),creationRunId:null,metadata:i??(a.contentType===he.value?{bytes:t.byteLength}:{}),sealed:u,signerId:o.id},d=tn.parse({...l,signature:await ir(l,n.signing,"resource")});return await ko(d),d}async function ko(t){let e=tn.parse(t),{signature:r,...o}=e;await _$(e.policy),await c8(e.policy,e.lineage);let n=LL(e),i=e.lineage?.at(-1);if(i?.revision===e.policy.revision&&i.policyDigest!==await Q(e.policy))throw new Error("The handoff approves a different access policy.");await Ur(e.policy,e.authorization,n.signing,"access-policy");let s=(e.signerId===n.id?n:void 0)??e.policy.authorities.find(u=>u.id===e.signerId)??e.policy.producers.find(u=>u.executor.id===e.signerId&&u.runId===e.creationRunId&&u.materialRevision===e.materialRevision&&(e.policy.contentType===he.executionResult||Date.parse(u.expiresAt)>Date.parse(e.updatedAt)))?.executor??(ML(e.policy.contentType)?e.policy.grants.find(u=>u.executor.id===e.signerId&&u.operations.includes(ue.refresh)&&Qa(u,Date.parse(e.updatedAt)))?.executor:void 0);if(!s||Date.parse(e.updatedAt)>Date.now()+3e4)throw new Error("The signer cannot replace this content.");await Ur(o,r,s.signing,"resource");let a=b$(e.policy).map(u=>u.id).sort(),c=e.sealed.recipients.map(u=>u.header.kid).sort();if(C(a)!==C(c)||e.sealed.aad!==Ds(tt(await iu(e.policy,e.materialRevision))))throw new Error("Encrypt content for exactly the recipients authorized by its policy.");return e}async function l8(t,e,r,o,n=t.metadata){let i=await ko(t);if(!ML(i.policy.contentType)||!(i.policy.authorities.some(p=>C(p)===C(r))||i.policy.grants.some(p=>C(p.executor)===C(r)&&p.operations.includes(ue.refresh)&&Qa(p))))throw new Error("This executor cannot renew this connection.");if(e.byteLength>1e6)throw new Error("The content exceeds 1,000,000 bytes.");let s=i.materialRevision+1,a=await Xa(e,b$(i.policy).map(p=>({id:p.id,publicKey:p.encryption})),await iu(i.policy,s)),{signature:c,...u}=i,l={...u,materialRevision:s,updatedAt:new Date().toISOString(),metadata:n,sealed:a,signerId:r.id},d={...l,signature:await ir(l,o.signing,"resource")};return await ko(d),d}async function S$(t,e,r,o){let n=await _$(t);if(!n.authorities.some(s=>C(s)===C(e)))throw new Error("Only an authority can approve this policy.");let i={policy:n,...await u8(o,n,e,r),authorityId:e.id,signature:await ir(n,r.signing,"access-policy")};return await su(i),i}async function su(t){let e=Vy.parse(t);await _$(e.policy),await c8(e.policy,e.lineage);let r=e.lineage?.at(-1);if(r?.revision===e.policy.revision&&r.policyDigest!==await Q(e.policy))throw new Error("The handoff approves a different access policy.");let o=e.policy.authorities.find(n=>n.id===e.authorityId);if(!o)throw new Error("The policy must be signed by an authority.");return await Ur(e.policy,e.signature,o.signing,"access-policy"),e}async function Gy(t,e,r,o,n,i){let s=await su(e),{policy:a}=s,c=a.producers.find(p=>p.runId===r&&C(p.executor)===C(o)&&(a.contentType===he.executionResult||Date.parse(p.expiresAt)>Date.now()));if(!c)throw new Error("Approve this execution before storing its output.");if(t.byteLength>i8(a.contentType))throw new Error("The content exceeds its storage limit.");let u=await Xa(t,b$(a).map(p=>({id:p.id,publicKey:p.encryption})),await iu(a,c.materialRevision)),l={policy:a,...s.lineage?{lineage:s.lineage}:{},authorityId:s.authorityId,authorization:s.signature,materialRevision:c.materialRevision,updatedAt:new Date().toISOString(),creationRunId:r,metadata:i,sealed:u,signerId:o.id},d={...l,signature:await ir(l,n.signing,"resource")};return await ko(d),d}async function cd(t,e,r){let o=await ko(t);if(!o.policy.readers.some(n=>C(n)===C(e)))throw new Error("This identity cannot reveal the content.");return Po(o.sealed,r,e.id,await iu(o.policy,o.materialRevision))}var EDe=m.object({id:E,policyDigest:xr,materialRevision:m.number().int().positive(),authorizationDigest:xr.optional()}).strict();async function jL(t,e){return e.id===t.policy.id&&e.policyDigest===await Q(t.policy)&&(e.authorizationDigest===void 0||e.authorizationDigest===t.metadata.authorizationDigest)&&(e.materialRevision===t.materialRevision||ML(t.policy.contentType)&&e.authorizationDigest!==void 0&&e.authorizationDigest===t.metadata.authorizationDigest&&t.materialRevision>=e.materialRevision)}var x$=m.object({format:m.literal(2),id:E,origin:Af,ownerId:E,approval:m.object({id:E,index:m.number().int().min(0).max(7)}).strict().optional(),operationContext:n8.optional(),actor:Kt,environmentId:E,executor:Kt,environmentDigest:xr,operation:qy,functionDigest:xr.nullable(),functionId:E.optional(),operationDigest:xr,sources:m.array(EDe).max(100),resultRecipients:m.array(Kt).min(1).max(100),resultApproval:Vy.optional(),createdAt:$e,expiresAt:$e}).strict(),kf=m.object({intent:x$,signature:cr,sealed:Ao}).strict();async function ud(t,e){return C({purpose:"run-"+e,origin:t.origin,id:t.id,intentDigest:await Q(t)})}async function d8(t,e,r){if(x$.parse(t),await Q(e)!==t.operationDigest)throw new Error("The operation does not match the execution intent.");let o={intent:t,sealed:await Xa(tt(C(e)),[{id:t.executor.id,publicKey:t.executor.encryption}],await ud(t,"input"))};return kf.parse({...o,signature:await ir(o,r.signing,"run")})}async function $De(t,e=Date.now()){let r=kf.parse(t),{signature:o,...n}=r;await Ur(n,o,r.intent.actor.signing,"run");let{intent:i}=r,s=Date.parse(i.createdAt),a=Date.parse(i.expiresAt);if(s>e+3e4||a<=e||a<=s||a-s>864e5)throw new Error("Use an execution intent valid for at most 24 hours.");if(new Set(i.sources.map(c=>c.id)).size!==i.sources.length||new Set(i.resultRecipients.map(c=>c.id)).size!==i.resultRecipients.length)throw new Error("Choose distinct inputs and result recipients.");if(i.resultApproval){let c=await su(i.resultApproval),u=c.policy;if(c.authorityId!==i.actor.id||u.id!==i.id||u.origin!==i.origin||u.ownerId!==i.ownerId||u.contentType!==he.executionResult||u.revision!==1||u.grants.length||!u.authorities.some(l=>C(l)===C(i.actor))||C(u.readers)!==C(i.resultRecipients)||u.producers.length!==1||u.producers[0].runId!==i.id||C(u.producers[0].executor)!==C(i.executor)||u.producers[0].materialRevision!==1)throw new Error("Approve this execution result for its readers and selected executor.")}if(r.sealed.recipients.length!==1||r.sealed.recipients[0].header.kid!==i.executor.id||r.sealed.aad!==Ds(tt(await ud(i,"input"))))throw new Error("Encrypt this operation for its selected executor.");return r}async function p8(t,e,r){let o=await $De(t);if(C(o.intent.executor)!==C(e))throw new Error("This operation belongs to another executor.");let n=await Po(o.sealed,r.encryption,e.id,await ud(o.intent,"input")),i=new TextDecoder("utf-8",{fatal:!0}).decode(n),s=JSON.parse(i);if(C(s)!==i||await Q(s)!==o.intent.operationDigest)throw new Error("The decrypted operation does not match its signed intent.");return{intent:o.intent,operation:s}}async function ld(t,e,r={}){let o=await ko(t),n=o.policy,i=e.sources.find(c=>c.id===n.id);if(!i||e.origin!==n.origin||!await jL(o,i))throw new Error("The input changed after this execution was authorized.");if(C(e.actor)===C(e.executor)&&n.readers.some(c=>C(c)===C(e.actor)))return o;if(!n.grants.filter(c=>("actor"in c?C(c.actor)===C(e.actor):c.function.id===e.functionId&&c.function.digest===e.functionDigest)&&C(c.executor)===C(e.executor)&&c.operations.includes(e.operation)&&Qa(c,r.now)&&Pf(c)>=Date.parse(e.expiresAt)).some(c=>"function"in c?e.operation===ue.function||e.operation===ue.refresh:e.operation===ue.function&&!c.callerProgram&&(!e.functionDigest||!c.functionDigests.includes(e.functionDigest))||c.origins.length&&(!r.destination||!c.origins.includes(new URL(r.destination).origin))?!1:e.operation!==ue.command&&e.operation!==ue.http||c.callerProgram))throw new Error("This identity cannot use this input on the selected executor.");return o}async function au(t,e,r,o={}){return await ld(t,e,o),Po(t.sealed,r.encryption,e.executor.id,await iu(t.policy,t.materialRevision))}var dd=3,FL=m.string().regex(/^arn:aws[a-z-]*:iam::\d{12}:(?:role|user)\/(?:[\x21-\x7e]{1,510}\/)?[\w+=,.@-]{1,64}$/),f8=m.object({format:m.literal(3),id:E,origin:Af,ownerId:E,name:fe,executor:Kt,operatorId:E,driver:m.enum(["attached","managed"]),capabilities:m.array(qy).min(1).max(6),functionVersion:m.number().int().positive().optional(),resultVersion:m.literal(1).optional(),isolation:m.enum(["process","container"]),commandImage:m.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/).optional(),awsPrincipal:FL.optional(),revision:m.number().int().positive()}).strict(),qL=m.object({manifest:f8,signature:cr}).strict();async function VL(t,e){let r=f8.parse(t),o={manifest:r,signature:await ir(r,e.signing,"environment")};return await Cf(o),o}async function Cf(t){let e=qL.parse(t),{manifest:r}=e;if(await zs(r.executor),new Set(r.capabilities).size!==r.capabilities.length)throw new Error("Choose distinct execution capabilities.");if(r.capabilities.includes(ue.command)&&r.isolation==="container"&&!r.commandImage)throw new Error("Choose the container image used for commands.");if(r.driver==="managed"&&r.capabilities.includes(ue.command)&&r.isolation!=="container")throw new Error("Managed commands require container isolation.");return await Ur(r,e.signature,r.executor.signing,"environment"),e}async function Of(t,e){let{manifest:r}=await Cf(t);if(e.environmentId!==r.id||e.origin!==r.origin||e.environmentDigest!==await Q(r)||C(e.executor)!==C(r.executor)||!r.capabilities.includes(e.operation)||e.operation===ue.function&&r.functionVersion!==dd)throw new Error("This environment does not authorize the requested execution.")}var E$=m.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),$$=m.object({ok:m.boolean(),result:vr.nullable(),error:m.object({code:m.string().max(100),message:m.string().max(1e3)}).nullable()}).strict(),m8={id:E,intentDigest:xr,executorId:E,state:m.enum(["succeeded","failed","cancelled","uncertain"]),finishedAt:$e},h8=m.object({...m8,sealed:Ao,signature:cr}).strict(),g8=m.object({...m8,format:m.literal(2),accessDigest:xr,proofDigest:xr,approval:Vy,content:tn,previousDigest:xr.optional(),previous:h8.optional(),signature:cr}).strict(),Hy=m.union([h8,g8]),RDe=m.object({result:$$,proof:cr}).strict(),y8=t=>{let{signature:e,content:r,approval:o,previous:n,...i}=t;return i};async function GL(t,e,r,o,n,i){await su(n);let s={format:2,id:t.id,intentDigest:await Q(t),executorId:t.executor.id,state:e,finishedAt:i?.finishedAt??new Date().toISOString(),accessDigest:await Q(n),...i?{previousDigest:await Q(i)}:{}},a=await ir({...s,resultDigest:await Q(r)},o.signing,"execution-result"),c=tt(C({result:$$.parse(r),proof:a}));if(c.byteLength>14e5)throw new Tf;let u=await Gy(c,n,t.id,t.executor,o,{bytes:c.byteLength}),l={...s,proofDigest:await Q(a)},d=g8.parse({...l,approval:n,content:u,...i?{previous:i}:{},signature:await ir(l,o.signing,"receipt")});return await HL(d,t),d}var Tf=class extends Error{constructor(){super("The encoded execution result exceeds 1,400,000 bytes.")}};async function Df(t,e,r,o){let n=$$.parse(r);if(e==="succeeded"!==n.ok)throw new Error("The result must match its completion state.");if(t.resultApproval)return GL(t,e,n,o,t.resultApproval);let i=tt(C(n));if(i.byteLength>14e5)throw new Tf;let s=await Xa(i,t.resultRecipients.map(c=>({id:c.id,publicKey:c.encryption})),await ud(t,"result")),a={id:t.id,intentDigest:await Q(t),executorId:t.executor.id,state:e,finishedAt:new Date().toISOString(),sealed:s};return Hy.parse({...a,signature:await ir(a,o.signing,"receipt")})}async function HL(t,e){let r=Hy.parse(t);if("content"in r){await Ur(y8(r),r.signature,e.executor.signing,"receipt");let i=await su(r.approval),s=i.policy;if(r.id!==e.id||r.intentDigest!==await Q(e)||r.executorId!==e.executor.id||r.accessDigest!==await Q(i)||i.authorityId!==e.actor.id||!s.authorities.some(a=>C(a)===C(e.actor))||s.id!==e.id||s.origin!==e.origin||s.ownerId!==e.ownerId||s.contentType!==he.executionResult||s.grants.length||e.resultApproval&&C(e.resultApproval)!==C(i))throw new Error("The result does not belong to the requested execution.");if(!e.resultApproval||r.previous){if(!r.previous||r.previousDigest!==await Q(r.previous))throw new Error("Keep the original execution receipt when sharing a legacy result.");if(await HL(r.previous,e),r.state!==r.previous.state||r.finishedAt!==r.previous.finishedAt)throw new Error("Keep the original execution outcome when sharing its result.")}else if(r.previousDigest)throw new Error("Provide the original receipt for its signed digest.");if(await ko(r.content),!w$(s,r.content)||r.content.policy.revision<s.revision||r.content.policy.grants.length)throw new Error("An existing authority must approve sharing this result.");return r}if(e.resultApproval)throw new Error("Return the protected result approved by this execution.");let{signature:o,...n}=r;if(await Ur(n,o,e.executor.signing,"receipt"),r.id!==e.id||r.intentDigest!==await Q(e)||r.executorId!==e.executor.id||r.sealed.aad!==Ds(tt(await ud(e,"result")))||C(r.sealed.recipients.map(i=>i.header.kid).sort())!==C(e.resultRecipients.map(i=>i.id).sort()))throw new Error("The result does not belong to the requested execution.");return r}async function v8(t,e,r,o){if(await HL(t,e),"content"in t){if(!t.content.policy.readers.some(l=>l.id===r))throw new Error("This principal cannot decrypt the result.");let s=await Po(t.content.sealed,o.encryption,r,await iu(t.content.policy,t.content.materialRevision)),a=RDe.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s)));if(await Q(a.proof)!==t.proofDigest)throw new Error("The result proof does not belong to this receipt.");let{proofDigest:c,...u}=y8(t);if(await Ur({...u,resultDigest:await Q(a.result)},a.proof,e.executor.signing,"execution-result"),t.state==="succeeded"!==a.result.ok)throw new Error("The result does not match its completion state.");return a.result}let n=await Po(t.sealed,o.encryption,r,await ud(e,"result")),i=$$.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n)));if(t.state==="succeeded"!==i.ok)throw new Error("The encrypted result does not match its completion state.");return i}var IDe=m.enum(["http","command","function","connect","refresh","revoke"]),Bn=m.object({id:E,ownerId:E,actorId:E,environmentId:E,kind:IDe,state:E$,intent:x$,requestSignature:cr,receipt:Hy.nullable(),error:m.string().nullable(),createdAt:$e,startedAt:$e.nullable(),finishedAt:$e.nullable()}).strict(),R$=m.object({name:fe,approval:Vy}).strict(),w8=m.object({kind:m.literal("function"),functionId:E,definition:ei,arguments:Lt.default({}),outputs:m.record(m.string(),R$).default({})}).strict(),ec=m.discriminatedUnion("kind",[m.object({kind:m.literal("http"),request:Za,save:m.record(m.string(),R$).default({})}).strict(),m.object({kind:m.literal("command"),...Wa.shape}).strict(),m.object({kind:m.enum(["connect","refresh","revoke"]),input:vr}).strict()]);var cu=class extends Error{constructor(r,o,n){super(n);this.code=r;this.status=o}code;status},tc=class{constructor(e){this.identity=e}identity;async response(e,r={}){if(!e.startsWith("/api/")||e.includes("\\")||/[\u0000-\u001f]/.test(e))throw new Error("Use a path beginning with /api/.");let o=new URL(e,this.identity.origin);if(o.origin!==this.identity.origin)throw new Error("Use a path on the configured Foundation origin.");let n;try{n=await fetch(o,{method:r.method??"GET",headers:{authorization:"Bearer "+this.identity.token,...r.raw?{"content-type":"application/octet-stream"}:r.body!==void 0?{"content-type":"application/json"}:{}},body:r.raw?new Uint8Array(r.raw):r.body!==void 0?JSON.stringify(r.body):void 0,redirect:"error",signal:AbortSignal.any([AbortSignal.timeout(9e4),...r.signal?[r.signal]:[]])})}catch{throw new Error("Could not reach Foundation. Check the origin and your network connection.")}if(!n.ok){let i;try{i=m.object({error:m.object({code:m.string(),message:m.string()})}).parse(await n.json())}catch{throw new cu("http_error",n.status,"Foundation returned HTTP "+n.status+".")}throw new cu(i.error.code,n.status,i.error.message)}return n}async json(e,r={},o){let n=await this.response(e,r),i=n.status===204?null:await n.json();return o?o.parse(i):i}async session(){return this.json("/api/session",{},l$)}};import{chmod as ADe,lstat as PDe,mkdir as kDe,open as KL,readFile as b8,rename as TDe,rm as CDe}from"node:fs/promises";import{dirname as ODe,join as BL,resolve as DDe}from"node:path";import{homedir as NDe}from"node:os";import{randomUUID as zDe}from"node:crypto";var ZL=m.object({origin:m.url(),principalId:m.uuid(),token:m.string().min(20),keys:Uy.nullable(),binding:Kt.nullable()}).strict().refine(t=>!!t.keys==!!t.binding&&(!t.binding||t.binding.principalId===t.principalId),"Use the keys bound to this identity."),S8=m.object({current:m.uuid(),identities:m.array(ZL).min(1)}).strict().refine(t=>t.identities.some(e=>e.principalId===t.current),"The current identity is missing.");function rc(){return BL(process.env.XDG_CONFIG_HOME||BL(NDe(),".config"),"foundation","identity.json")}function uu(t=process.env.FOUNDATION_ORIGIN||"https://foundationsystems.app"){let e;try{e=new URL(t)}catch{throw new Error("Set FOUNDATION_ORIGIN to an HTTPS origin.")}if(e.username||e.password||e.pathname!=="/"||e.search||e.hash||e.protocol!=="https:"&&!(e.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(e.hostname)))throw new Error("Use an HTTPS origin, or HTTP on localhost.");return e.origin}async function I$(t){let e;try{let n=rc(),i=await PDe(n);if(!i.isFile()||i.isSymbolicLink())throw new Error("The identity must be a regular file.");process.platform!=="win32"&&i.mode&63&&await ADe(n,384);let s=S8.parse(JSON.parse(await b8(n,"utf8")));e=s.identities.find(a=>a.principalId===s.current)}catch(n){if(!(n instanceof Error&&"code"in n&&n.code==="ENOENT"))throw new Error("The saved identity could not be read. Check its contents and permissions.")}let r=uu(t||process.env.FOUNDATION_ORIGIN||e?.origin),o=process.env.FOUNDATION_TOKEN;if(o){if(t&&process.env.FOUNDATION_ORIGIN&&r!==uu(process.env.FOUNDATION_ORIGIN))throw new Error("The environment identity belongs to a different origin.");let n=process.env.FOUNDATION_PRINCIPAL_ID,i=process.env.FOUNDATION_PRIVATE_KEYS,s=process.env.FOUNDATION_KEY_BINDING;if(!n)throw new Error("FOUNDATION_TOKEN requires FOUNDATION_PRINCIPAL_ID.");try{return ZL.parse({origin:r,principalId:n,token:o,keys:i?JSON.parse(Buffer.from(i,"base64url").toString("utf8")):null,binding:s?JSON.parse(Buffer.from(s,"base64url").toString("utf8")):null})}catch{throw new Error("The Foundation environment identity is invalid.")}}if(!e)throw new Error("Run foundation login to sign in on this machine.");if(r!==uu(e.origin))throw new Error("This identity belongs to another origin. Use a separate XDG_CONFIG_HOME to initialize another server.");return{...e,origin:r}}async function Ky(t){let e=rc(),r;try{r=S8.parse(JSON.parse(await b8(e,"utf8")))}catch(i){if(!(i instanceof Error&&"code"in i&&i.code==="ENOENT"))throw new Error("The saved identity could not be read. Check its contents and permissions.")}let o=ZL.parse(t),n=(r?.identities??[]).filter(i=>!(i.origin===o.origin&&i.principalId===o.principalId));await Nf(e,JSON.stringify({current:o.principalId,identities:[...n,o]},null,2)+`
130
130
  `,!!r)}async function _8(t){if(process.platform==="win32")return;let e=await KL(t,"r");try{await e.sync()}finally{await e.close()}}async function Nf(t,e,r){let o=DDe(t),n=ODe(o);if(await kDe(n,{recursive:!0,mode:448}),!r){let s=await KL(o,"wx",384);try{await s.writeFile(e),await s.sync()}finally{await s.close()}await _8(n);return}let i=BL(n,".foundation-"+zDe());try{let s=await KL(i,"wx",384);try{await s.writeFile(e),await s.sync()}finally{await s.close()}await TDe(i,o),await _8(n)}finally{await CDe(i,{force:!0})}}import{spawn as jDe}from"node:child_process";import{chmod as FDe,mkdtemp as qDe,rm as VDe,writeFile as GDe}from"node:fs/promises";import{tmpdir as HDe}from"node:os";import{join as I8}from"node:path";import{StringDecoder as KDe}from"node:string_decoder";import{spawn as x8}from"node:child_process";import{mkdir as E8,mkdtemp as MDe,rm as UDe,writeFile as $8}from"node:fs/promises";import{tmpdir as LDe}from"node:os";import{join as By}from"node:path";import{StringDecoder as R8}from"node:string_decoder";function qi(t={}){return{...Object.fromEntries(["PATH","LANG","LC_ALL","TZ","TERM","HOME","TMPDIR","SYSTEMROOT","COMSPEC","PATHEXT"].flatMap(r=>process.env[r]?[[r,process.env[r]]]:[])),...t}}var Zy=class{constructor(e){this.options=e;if(e.isolation==="container"&&!/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/.test(e.image??""))throw new Error("Choose a container image pinned to its SHA-256 digest.")}options;async execute(e,r){r.throwIfAborted();let o=await MDe(By(LDe(),"foundation-job-")),n=By(o,"files"),i="foundation-"+crypto.randomUUID(),s=this.options.isolation==="container",a=e.workspace==="temporary",c={exitCode:null,signal:null,stdout:"",stderr:"",timedOut:!1,truncated:!1},u=!1;try{await E8(n,{mode:448});let l={...e.environment};a&&s&&(l.HOME??="/tmp",l.TMPDIR??="/tmp");for(let[p,f]of Object.entries(e.files)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(p))throw new Error("Use valid file variable names.");await $8(By(n,p),Buffer.from(f,"base64"),{mode:384,flag:"wx"}),l[p]=s?"/run/foundation/"+p:By(n,p)}let d=e.command;if(s){if(Object.entries(l).some(([h,y])=>!/^[A-Za-z_][A-Za-z0-9_]*$/.test(h)||y.includes("\0")))throw new Error("Use valid environment variable names and values without null bytes.");let p=Object.entries(l).filter(([,h])=>/[\r\n]/.test(h)),f=By(o,"environment");await $8(f,Object.entries(l).filter(([,h])=>!/[\r\n]/.test(h)).map(([h,y])=>h+"="+y).join(`
131
- `),{mode:384,flag:"wx"}),!a&&this.options.workspace&&await E8(this.options.workspace,{recursive:!0,mode:448}),d=["docker","run","--rm","--name",i,"--init","--read-only","--cap-drop=ALL","--security-opt=no-new-privileges","--pids-limit=128","--memory=512m","--cpus=1","--network=bridge","--tmpfs=/tmp:rw,nosuid,nodev,size=64m","--user="+String(process.getuid?.()??65534)+":"+String(process.getgid?.()??65534),"--mount=type=bind,source="+n+",target=/run/foundation,readonly","--env-file",f,...p.flatMap(([h,y])=>["--env",h+"="+y]),...!a&&this.options.workspace?["--mount=type=bind,source="+this.options.workspace+",target=/workspace"]:[],...a?["--workdir","/tmp"]:e.workingDirectory?["--workdir",e.workingDirectory]:[],"--entrypoint="+e.command[0],"-i",this.options.image,...e.command.slice(1)]}return await new Promise(p=>{let f=x8(d[0],d.slice(1),{env:qi(s?{}:a?{...l,HOME:o,TMPDIR:o}:l),cwd:s?this.options.cwd:a?o:e.workingDirectory??this.options.cwd,detached:process.platform!=="win32",stdio:["pipe","pipe","pipe"]}),h={stdout:new R8("utf8"),stderr:new R8("utf8")},y=0,w=!1,b=(T,M)=>{let Z=Math.max(0,1e6-y);M.length>Z&&(c.truncated=!0);let te=M.subarray(0,Z);y+=te.length,c[T]+=h[T].write(te)};f.stdout.on("data",T=>b("stdout",T)),f.stderr.on("data",T=>b("stderr",T)),f.stdin.on("error",()=>{}),f.stdin.end(e.stdin??"");let S=()=>{u=!0;try{f.pid&&process.platform!=="win32"?process.kill(-f.pid,"SIGKILL"):f.kill("SIGKILL")}catch{}},x=setTimeout(()=>{c.timedOut=!0,S()},e.timeoutSeconds*1e3);x.unref();let R=()=>{w||(w=!0,clearTimeout(x),r.removeEventListener("abort",S),c.stdout+=h.stdout.end(),c.stderr+=h.stderr.end(),p())};r.addEventListener("abort",S,{once:!0}),r.aborted&&S(),f.once("error",()=>{c.exitCode=127,c.stderr="The command could not be started.",R()}),f.once("close",(T,M)=>{c.exitCode=T,c.signal=M,R()})}),c}finally{s&&u&&await new Promise(l=>{let d=x8("docker",["rm","-f",i],{env:qi(),stdio:"ignore"});d.once("close",()=>l()),d.once("error",()=>l()),setTimeout(()=>{d.kill("SIGKILL"),l()},1e4).unref()}),await UDe(o,{recursive:!0,force:!0})}}};function BDe(t){return[...new Set(t.filter(Boolean).flatMap(e=>[e,encodeURIComponent(e),JSON.stringify(e).slice(1,-1),Buffer.from(e).toString("base64"),Buffer.from(e).toString("base64url")]))].sort((e,r)=>r.length-e.length)}var A$=class{constructor(e,r){this.secrets=e;this.output=r;this.max=Math.max(1,...e.map(o=>o.length))}secrets;output;pending="";decoder=new KDe("utf8");max;write(e){this.pending+=this.decoder.write(e),this.flush(!1)}end(){this.pending+=this.decoder.end(),this.flush(!0)}flush(e){let r=e?this.pending.length:Math.max(0,this.pending.length-this.max+1),o=0,n="";for(;o<r;){let i=this.secrets.find(s=>this.pending.startsWith(s,o));i?(n+="[redacted]",o+=i.length):(n+=this.pending[o],o++)}this.pending=this.pending.slice(o),n&&this.output(n)}};async function A8(t,e){if(!e.length)throw new Error("Put the command after --.");let r=await qDe(I8(HDe(),"foundation-"));await FDe(r,448);try{let o=qi(t.environment),n=[...t.sensitive];for(let[i,s]of Object.entries(t.files)){let a=Buffer.from(s,"base64"),c=I8(r,i);await GDe(c,a,{mode:384,flag:"wx"}),o[i]=c,n.push(a.toString("utf8"),s,a.toString("base64url"))}return await new Promise((i,s)=>{let a=jDe(e[0],e.slice(1),{env:o,stdio:["inherit","pipe","pipe"],detached:process.platform!=="win32"}),c=BDe(n),u=new A$(c,h=>process.stdout.write(h)),l=new A$(c,h=>process.stderr.write(h));a.stdout.on("data",h=>u.write(h)),a.stderr.on("data",h=>l.write(h));let d=h=>{if(a.pid)try{process.platform==="win32"?a.kill(h):process.kill(-a.pid,h)}catch{}},p=()=>d("SIGINT"),f=()=>d("SIGTERM");process.on("SIGINT",p),process.on("SIGTERM",f),a.once("error",()=>s(new Error("The command could not be started. Check the executable and arguments."))),a.once("close",(h,y)=>{process.off("SIGINT",p),process.off("SIGTERM",f),u.end(),l.end(),i(h??(y==="SIGINT"?130:y==="SIGTERM"?143:1))})})}finally{await VDe(r,{recursive:!0,force:!0})}}import{dirname as AHe,join as o3}from"node:path";function xr(t){switch(t.kind){case"oauth":let e=t.config.application;return{family:"oauth",application:e,requiresApp:e==="required",browserAuthorization:t.config.grantType!=="client_credentials",fields:t.config.fields,outputs:Object.keys(t.config.outputs)};case"token":return{family:"token",application:"none",requiresApp:!1,browserAuthorization:!1,fields:t.config.fields,outputs:Object.keys(t.config.outputs)};case"approval":return{family:"approval",application:"none",requiresApp:!1,browserAuthorization:!0,fields:t.config.fields,outputs:Object.keys(t.config.outputs)};case"ovh":{let r=t.config.authorization==="consumer_key";return{family:"ovh",application:r?"required":"none",requiresApp:r,browserAuthorization:r,fields:t.config.fields,outputs:Object.keys(t.config.outputs)}}case"aws":return{family:"aws",application:"none",requiresApp:!1,browserAuthorization:!1,fields:[],outputs:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_DEFAULT_REGION","AWS_REGION"]}}}function Vi(t,e){return[...new Set([...t.required??[],...e??t.default])]}function lu(t){return xr(t).requiresApp}var ZDe=new Set(["airtable.com","dash.cloudflare.com","api.ebay.com","accounts.secure.freee.co.jp","github.com","id.heroku.com","api.hubapi.com","api.netlify.com","api.notion.com","api.render.com","login.salesforce.com","cloud.digitalocean.com","api.vultr.com","api.x.com","zoom.us"]);function P8(t){if(t.kind==="approval")return"unavailable";if(!xr(t).browserAuthorization||t.kind==="ovh"||t.kind!=="oauth")return"available";try{let e=new URL(t.config.tokenUrl).hostname;return ZDe.has(e)||e==="login.microsoftonline.com"&&t.config.clientAuth!=="none"?"unavailable":t.config.tokenUrl.includes("{")?"unknown":"available"}catch{return"unknown"}}var WDe=new Set(["format","generation","methodId","method","appId","appGeneration","account","accountId","accountName","accountVerified","scopes","scopesStatus","outputs","state","methodKind","authorizationDigest"]),k8=Lt.refine(t=>Object.keys(t).every(e=>!WDe.has(e)),"Keep method-specific facts separate from common facts."),du=m.object({accountId:m.string().max(2e3).nullable(),accountName:m.string().max(2e3),accountVerified:m.boolean(),scopes:m.array(m.string().max(1e3)).max(200),scopesStatus:m.enum(["unknown","requested","reported"]),authorization:k8,details:k8}).strict();function WL(t){if(t.method.kind!=="oauth")throw new Error("Use OAuth connection material.");let e="requestedScopes"in t?t.requestedScopes:void 0;return du.parse({accountId:t.oauth?.account??"",accountName:t.oauth?.accountName??"",accountVerified:t.oauth?.accountVerified??!1,scopes:e??t.oauth?.scopes??[],scopesStatus:e?"requested":t.oauth?.scopesStatus??"unknown",authorization:{},details:{}})}function zf(t){if(t.method.kind!=="token"&&t.method.kind!=="approval"||!t.fields)throw new Error("Use input credential material.");return"facts"in t&&t.facts?du.parse(t.facts):du.parse({accountId:null,accountName:t.method.name,accountVerified:!1,scopes:[],scopesStatus:"unknown",authorization:{},details:{}})}function JL(t){if(t.method.kind!=="ovh")throw new Error("Use OVH connection material.");let e="ovh"in t?t.ovh:void 0;if(!e){let r="requestedScopes"in t?t.requestedScopes:void 0;return du.parse({accountId:null,accountName:"",accountVerified:!1,scopes:r??[],scopesStatus:r?"requested":"unknown",authorization:{},details:{}})}return du.parse({accountId:e.user?e.account+"/"+e.user:e.account,accountName:e.account+(e.user?" / "+e.user:""),accountVerified:!0,scopes:e.rules.map(r=>r.method+" "+r.path),scopesStatus:"reported",authorization:{ovh:e},details:{ovh:e}})}function XL(t){if(t.method.kind!=="aws"||!t.aws)throw new Error("Use AWS connection material.");return du.parse({accountId:t.aws.identity?Ef(t.aws.identity.arn):null,accountName:t.aws.identity?t.aws.identity.accountId+" / "+t.aws.identity.arn.split(":").at(-1):"",accountVerified:!!t.aws.identity,scopes:[],scopesStatus:"unknown",authorization:{aws:O5(t.aws)},details:{aws:D5(t.aws)}})}var JDe={oauth:WL,token:zf,aws:XL,ovh:JL,approval:zf};function Wy(t){return JDe[t.method.kind](t)}var hJ=Vt(Y8(),1);var sc=class extends Error{template;position;hint;constructor(t,e,r,o){super(`${o} (at position ${e}): ${r}`),this.template=t,this.position=e,this.hint=r,this.name="TemplateParseError"}},bNe=class extends sc{constructor(t,e){super(t,e,"Add the missing '}' to close the expression, or remove the stray '{'.","Unclosed expression: '{' has no matching '}'"),this.name="UnclosedExpressionError"}},SNe=class extends sc{constructor(t,e){super(t,e,"Remove this stray '}' or add a matching '{' before it.","Stray '}' outside of any expression"),this.name="StrayClosingBraceError"}},xNe=class extends sc{constructor(t,e){super(t,e,"RFC 6570 expressions cannot nest. Close the outer expression with '}' before starting a new one.","Nested '{' inside an unclosed expression"),this.name="NestedOpeningBraceError"}},ENe=class extends sc{char;constructor(t,e,r){super(t,e,`Pct-encode '${r}' (e.g. '%${r.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}') or remove it. Literals may not contain CTL, SP, '"', '\\'', lone '%', '<', '>', '\\\\', '^', '\`', or '|'.`,`Invalid literal character '${r}'`),this.char=r,this.name="InvalidLiteralError"}},$Ne=class extends sc{constructor(t,e){super(t,e,"Provide at least one varname inside the braces, e.g. '{var}'.","Empty expression '{}'"),this.name="EmptyExpressionError"}},RNe=class extends sc{operator;constructor(t,e,r){super(t,e,`Operator '${r}' is reserved by RFC 6570 \xA72.2 for future extensions. Use one of '+', '#', '.', '/', ';', '?', '&' instead, or remove the operator.`,`Reserved operator '${r}'`),this.operator=r,this.name="ReservedOperatorError"}},INe=class extends sc{operator;constructor(t,e,r){super(t,e,`Replace '${r}' with one of '+', '#', '.', '/', ';', '?', '&' or remove it.`,`Unknown operator '${r}'`),this.operator=r,this.name="UnknownOperatorError"}},L$=class extends sc{varSpec;constructor(t,e,r,o,n){super(t,e,r,o),this.varSpec=n,this.name="InvalidVarSpecError"}},sj=class extends L${constructor(t,e){super(t,e,"Remove the stray comma or insert a varname before/after it.","Empty varname in variable-list",""),this.name="EmptyVarNameError"}},ANe=class extends L${offendingChar;constructor(t,e,r,o){super(t,e,`Varnames may only contain ALPHA, DIGIT, '_', '.', or pct-encoded triplets. Replace '${o}' or pct-encode it.`,`Invalid character '${o}' in varname`,r),this.offendingChar=o,this.name="InvalidVarNameError"}},PNe=class extends L${prefix;constructor(t,e,r,o){super(t,e,"Prefix modifiers must be ':N' where N is a positive integer in 1..9999 with no leading zero (e.g. ':3').",`Invalid prefix modifier ':${o}'`,r),this.prefix=o,this.name="InvalidPrefixError"}},Q8=class extends L${constructor(t,e){super(t,e,"Remove the trailing comma, or add a varspec after it.","Trailing ',' in variable-list",""),this.name="TrailingCommaError"}},kNe=class extends sc{char;constructor(t,e,r){super(t,e,"Expected ',' or '}' here. Remove the unexpected character or pct-encode it if it belongs in the varname.",`Unexpected character '${r}' in expression`),this.char=r,this.name="UnexpectedCharacterError"}},TNe=class extends Error{variableName;hint;constructor(t,e,r){super(`${r} for '${t}': ${e}`),this.variableName=t,this.hint=e,this.name="TemplateExpansionError"}},CNe=class extends TNe{prefix;valueType;constructor(t,e,r){super(t,"Remove the prefix modifier from this varspec, or provide a string value instead of a composite value.",`Prefix modifier ':${e}' is not applicable to ${r} values`),this.prefix=e,this.valueType=r,this.name="PrefixModifierNotApplicableError"}},ONe=["","+",".","/",";","?","&","#"],sJ={"":{first:"",sep:",",named:!1,ifEmpty:"",allowReserved:!1},"+":{first:"",sep:",",named:!1,ifEmpty:"",allowReserved:!0},".":{first:".",sep:".",named:!1,ifEmpty:"",allowReserved:!1},"/":{first:"/",sep:"/",named:!1,ifEmpty:"",allowReserved:!1},";":{first:";",sep:";",named:!0,ifEmpty:"",allowReserved:!1},"?":{first:"?",sep:"&",named:!0,ifEmpty:"=",allowReserved:!1},"&":{first:"&",sep:"&",named:!0,ifEmpty:"=",allowReserved:!1},"#":{first:"#",sep:",",named:!1,ifEmpty:"",allowReserved:!0}},DNe=new TextEncoder,eJ="0123456789ABCDEF",tJ=t=>mu(En(48,57),En(65,70),En(97,102))(t.charCodeAt(0)),Qy=(t,e)=>t[e]==="%"&&e+2<t.length&&tJ(t[e+1])&&tJ(t[e+2]);function aj(t,e){let r=t[e];return r==null?0:mu(aJ,cJ,fd("_"))(r)?1:Qy(t,e)?3:0}function NNe(t,e){if(Qy(t,e))return 3;let{char:r,size:o}=ev(t,e);return MNe(r)?o:0}function ev(t,e){let r=t.codePointAt(e);if(r==null)return{char:"",size:0};let o=r>65535?2:1;return{char:t.slice(e,e+o),size:o}}var dj=t=>e=>{let r="";for(let o=0;o<e.length;){if(t&&Qy(e,o)){r+=e.slice(o,o+3),o+=3;continue}let{char:n,size:i}=ev(e,o);r+=mu(uJ,s=>t&&zNe(s))(n)?n:lJ(n),o+=i}return r};function Lf(t){let e="";for(let r=0;r<t.length;){if(Qy(t,r)){e+=t.slice(r,r+3),r+=3;continue}let{char:o,size:n}=ev(t,r);e+=uJ(o)?o:lJ(o),r+=n}return e}function Xy(t,e){let r="",o=0;for(let n=0;n<t.length&&o<e;o++){if(Qy(t,n)){r+=t.slice(n,n+3),n+=3;continue}let{char:i,size:s}=ev(t,n);r+=i,n+=s}return r}var aJ=t=>mu(En(65,90),En(97,122))(t.charCodeAt(0)),cJ=t=>En(48,57)(t.charCodeAt(0)),uJ=t=>mu(aJ,cJ,e=>"-._~".includes(e))(t),zNe=t=>":/?#[]@!$&'()*+,;=".includes(t),MNe=t=>UNe(t.codePointAt(0)),UNe=t=>t!=null&&mu(fd(33),En(35,36),fd(38),En(40,59),fd(61),En(63,91),fd(93),fd(95),En(97,122),fd(126),LNe,jNe)(t);function LNe(t){if(t<65536)return mu(En(160,55295),En(63744,64975),En(65008,65519))(t);if(t>983037)return!1;let e=t%65536;return e<=65533&&(t<917504||e>=4096)}var jNe=t=>mu(En(57344,63743),En(983040,1048573),En(1048576,1114109))(t),lJ=t=>Array.from(DNe.encode(t)).map(e=>`%${eJ[e>>4]}${eJ[e&15]}`).join(""),En=(t,e)=>r=>t<=r&&r<=e,fd=t=>e=>t===e,mu=(...t)=>e=>t.some(r=>r(e));function dJ(t,e,r){return t.map(o=>o.kind==="literal"?o.text:FNe(o.vars,o.operator,e,r)).join("")}function FNe(t,e,r,o){let n=sJ[e],i=t.flatMap(s=>qNe(s,r[s.name],n,o));return i.length<1?"":`${n.first}${i.join(n.sep)}`}function qNe(t,e,r,o){if(e==null)return[];if(JNe(e)){let n=KNe(e,r.allowReserved);return n.length<1?[]:rJ(t,"list",o)?GNe(t,n,r):[]}if(WNe(e)){let n=BNe(e,r.allowReserved);return n.length<1?[]:rJ(t,"associative",o)?HNe(t,n,r):[]}return VNe(t,e,r)}function VNe(t,e,r){let o=String(e),n=t.prefix==null?o:Xy(o,t.prefix),i=dj(r.allowReserved)(n);return r.named?[Yy(Lf(t.name),i,r)]:[i]}function GNe(t,e,r){let o=Lf(t.name);if(t.explode)return r.named?e.map(i=>Yy(o,i,r)):[...e];let n=e.join(",");return r.named?[Yy(o,n,r)]:[n]}function HNe(t,e,r){if(t.explode)return e.map(([n,i])=>Yy(n,i,r));let o=e.flat(1).join(",");return r.named?[Yy(Lf(t.name),o,r)]:[o]}var Yy=(t,e,r)=>e===""?`${t}${r.ifEmpty}`:`${t}=${e}`,KNe=(t,e)=>t.filter(r=>r!=null).map(String).map(dj(e)),BNe=(t,e)=>Object.entries(t).map(([r,o])=>[r,ZNe(o)]).filter(([,r])=>r!=null).map(r=>r.map(dj(e)));function ZNe(t){if(t==null)return null;if(!Array.isArray(t))return String(t);let e=t.filter(r=>r!=null).map(String);return e.length<1?null:e.join(",")}var WNe=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),JNe=t=>Array.isArray(t);function rJ(t,e,{report:r,strict:o}){if(t.prefix==null)return!0;let n=new CNe(t.name,t.prefix,e);if(r(n),o)throw n;return!1}function XNe(t,e,r){return cj(t,e,r,0,0,{})}function cj(t,e,r,o,n,i){if(o>=t.length){if(n!==e.length)return null;let a=E1e(i);return dJ(t,a,r)===e?a:null}let s=t[o];if(s.kind==="literal")return e.startsWith(s.text,n)?cj(t,e,r,o+1,n+s.text.length,i):null;for(let a of YNe(t,e,o,n)){let c=e.slice(n,a);for(let u of e1e(s.vars,s.operator,c)){let l=pj(i,u);if(l==null)continue;let d=cj(t,e,r,o+1,a,l);if(d!=null)return d}}return null}function*YNe(t,e,r,o){let n=t.slice(r+1).find(i=>i.kind==="literal"&&i.text!=="");if(n==null||n.kind!=="literal"){yield*QNe(e.length,o);return}for(let i=e.indexOf(n.text,o);i>=0;i=e.indexOf(n.text,i+1))yield i}function*QNe(t,e){for(let r=t;r>=e;r--)yield r}function*e1e(t,e,r){if(r===""){yield*t1e(t,e);return}let o=sJ[e];if(!r.startsWith(o.first))return;let n=r.slice(o.first.length);yield*o.named?l1e(t,o,n):r1e(t,o,n)}var t1e=(t,e)=>(e===""||e==="+")&&t.length===1?[fu(t[0],"")]:[{}],r1e=(t,e,r)=>uj(t,e,fj(r,e.sep),0,0);function*uj(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of n1e(i,e,r,n))for(let a of uj(t,e,r,o+1,s.index)){let c=pj(s.bindings,a);c!=null&&(yield c)}yield*uj(t,e,r,o+1,n)}function*n1e(t,e,r,o){if(o>=r.length)return;let n=r.length-o;for(let i=1;i<=n;i++){let s=r.slice(o,o+i);for(let a of o1e(t,e,s))yield{bindings:a,index:o+i}}}function*o1e(t,e,r){let o=pJ(t,e,r.join(e.sep));if(t.prefix!=null){yield*o;return}t.explode&&r.length>0&&(yield*i1e(t,e,r)),yield*o}function*i1e(t,e,r){let o=fJ(r,e.allowReserved);if(o==null)return;let n=s1e(r,e);n!=null&&(yield fu(t,n)),yield fu(t,o)}var s1e=(t,e)=>a1e(t.join(e.sep),e);function a1e(t,e){let r=[];for(let o=0;o<t.length;){let n=t.indexOf("=",o);if(n<0)return null;let i=n+1,s=c1e(t,i,e.sep),a=ic(t.slice(o,n),e.allowReserved),c=ic(t.slice(i,s),e.allowReserved);if(a==null||c==null)return null;r.push([a,c]),o=s+e.sep.length}return r.length<1?null:Object.fromEntries(r)}function c1e(t,e,r){for(let o=e;o<t.length;o++)if(u1e(t,o,r))return o;return t.length}var u1e=(t,e,r)=>{if(!t.startsWith(r,e))return!1;let o=e+r.length;for(let n=o;n<t.length;n++){if(t[n]==="=")return n>o;if(t.startsWith(r,n))return!1}return!1};function*pJ(t,e,r){let o=ic(r,e.allowReserved);if(o==null)return;let n=fu(t,o);if(t.prefix!=null){yield n;return}let i=fj(r,",");if(i.length<2){yield n;return}let s=fJ(i,e.allowReserved);if(s==null){yield n;return}let a=i.length%2===0?w1e(i,e.allowReserved):null;a!=null&&(yield fu(t,a)),yield fu(t,s),yield n}var l1e=(t,e,r)=>lj(t,e,fj(r,e.sep).map(v1e),0,0);function*lj(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of d1e(i,e,r,n,t))for(let a of lj(t,e,r,o+1,s.index)){let c=pj(s.bindings,a);c!=null&&(yield c)}yield*lj(t,e,r,o+1,n)}function*d1e(t,e,r,o,n){if(!(o>=r.length)){if(t.explode&&t.prefix==null){yield*f1e(t,e,r,o,n);return}yield*p1e(t,e,r,o)}}function*p1e(t,e,r,o){let n=r[o];if(n.name===Lf(t.name))for(let i of pJ(t,e,n.value))yield{bindings:i,index:o+1}}function*f1e(t,e,r,o,n){yield*m1e(t,e,r,o),yield*g1e(t,e,r,o,n)}function*m1e(t,e,r,o){let n=[...h1e(Lf(t.name),e,r,o)];n.length>0&&(yield{bindings:fu(t,n),index:o+n.length})}function*h1e(t,e,r,o){for(let n=o;n<r.length&&r[n].name===t;n++){let i=ic(r[n].value,e.allowReserved);if(i==null)return;yield i}}function*g1e(t,e,r,o,n){let i=[...y1e(e,r,o,new Set(n.map(s=>Lf(s.name))))];i.length>0&&(yield{bindings:fu(t,Object.fromEntries(i)),index:o+i.length})}function*y1e(t,e,r,o){for(let n=r;n<e.length;n++){let i=e[n];if(n>r&&o.has(i.name))return;let s=ic(i.name,t.allowReserved),a=ic(i.value,t.allowReserved);if(s==null||a==null)return;yield[s,a]}}function v1e(t){let e=t.indexOf("=");return e<0?{name:t,value:""}:{name:t.slice(0,e),value:t.slice(e+1)}}function w1e(t,e){let r=[];for(let o=0;o<t.length;o+=2){let n=ic(t[o],e),i=ic(t[o+1],e);if(n==null||i==null)return null;r.push([n,i])}return Object.fromEntries(r)}function fJ(t,e){let r=[];for(let o of t){let n=ic(o,e);if(n==null)return null;r.push(n)}return r}function ic(t,e){if(e)return t;try{return decodeURIComponent(t)}catch{return null}}var fu=({name:t,prefix:e},r)=>({[t]:{value:r,prefix:e}});function pj(t,e){let r={...t};for(let[o,n]of Object.entries(e)){let i=r[o];if(i==null){r[o]=n;continue}let s=_1e(i,n);if(s==null)return null;r[o]=s}return r}var _1e=(t,e)=>U$(t)||U$(e)?b1e(t,e):S1e(t.value,e.value)?t:null;function b1e(t,e){let r=nJ(t.value),o=nJ(e.value);if(r==null||o==null)return null;let n=U$(t),i=U$(e);if(!n&&!i)return null;if(n&&!i)return Xy(o,t.prefix)===r?e:null;if(!n&&i)return Xy(r,e.prefix)===o?t:null;let s=t.prefix,a=e.prefix;return s<=a?Xy(o,s)===r?e:null:Xy(r,a)===o?t:null}var U$=t=>t.prefix!=null,nJ=t=>typeof t=="string"?t:null;function S1e(t,e){return Array.isArray(t)?Array.isArray(e)&&t.length===e.length&&t.every((r,o)=>r===e[o]):oJ(t)?oJ(e)&&x1e(Object.entries(t),Object.entries(e)):t===e}var x1e=(t,e)=>t.length===e.length&&t.every(([r,o],n)=>{let[i,s]=e[n];return r===i&&o===s}),oJ=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),E1e=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[e,r.value])),fj=(t,e)=>e===""?[t]:t.split(e),$1e=["=",",","!","@","|"];function R1e(t,e,r){let o=a=>{throw a};if(t.length<1)return o(new $Ne(e,r));let n=t[0];if(k1e(n))return o(new RNe(e,r+1,n));if(!iJ(n)&&aj(t,0)<1)return o(new INe(e,r+1,n));let i=iJ(n)?n:"",s=i===""?0:1;return{kind:"expression",operator:i,vars:I1e(t,e,r+1,s)}}function I1e(t,e,r,o){if(o>=t.length)throw new sj(e,r+o);let n=[];for(let i=o;i<t.length;){if(t[i]===",")throw i===t.length-1?new Q8(e,r+i):new sj(e,r+i);let s=i,a=A1e(t,i);if(a===s)throw new sj(e,r+i);let c=t.slice(s,a);i=a;let u=P1e(t,e,r,i,c);if(i=u.index,i<t.length&&t[i]!==",")throw u.used?new kNe(e,r+i,t[i]):new ANe(e,r+i,c,t[i]);if(n.push({name:c,explode:u.explode,...u.prefix==null?{}:{prefix:u.prefix}}),i<t.length&&(i++,i>=t.length))throw new Q8(e,r+i-1)}return n}function A1e(t,e){let r=e,o=!0;for(;r<t.length;){let n=aj(t,r);if(n>0){r+=n,o=!1;continue}if(t[r]!=="."||o||aj(t,r+1)<1)break;r++,o=!0}return r}function P1e(t,e,r,o,n){if(t[o]==="*")return{explode:!0,index:o+1,used:!0};if(t[o]!==":")return{explode:!1,index:o,used:!1};let i=o+1,s=i;for(;s<t.length&&T1e(t[s]);)s++;let a=t.slice(i,s);if(!/^[1-9][0-9]{0,3}$/.test(a))throw new PNe(e,r+o,n,a);return{explode:!1,index:s,prefix:Number(a),used:!0}}function iJ(t){return ONe.includes(t)&&t!==""}function k1e(t){return $1e.includes(t)}function T1e(t){let e=t.charCodeAt(0);return e>=48&&e<=57}function C1e(t,e){let{report:r}=e,o=[],n=i=>{let s=o.at(-1);s?.kind==="literal"?o[o.length-1]={kind:"literal",text:s.text+i}:o.push({kind:"literal",text:i})};for(let i=0;i<t.length;){let s=t[i];if(s==="{"){let l=t.indexOf("}",i+1);if(l<0){r(new bNe(t,i)),n(t.slice(i));break}let d=t.indexOf("{",i+1);if(d>=0&&d<l){r(new xNe(t,d)),n(t.slice(i,l+1)),i=l+1;continue}let p=t.slice(i+1,l);try{o.push(R1e(p,t,i))}catch(f){r(f instanceof Error?f:new Error(String(f))),n(t.slice(i,l+1))}i=l+1;continue}if(s==="}"){r(new SNe(t,i)),n(s),i++;continue}let a=NNe(t,i);if(a>0){n(t.slice(i,i+a)),i+=a;continue}let{char:c,size:u}=ev(t,i);r(new ENe(t,i,c)),n(c),i+=u}return o}var j$=class mJ{uriTemplate;options;#e;#t;constructor(e,r={}){this.uriTemplate=e,this.options=r,this.#t=M1e(r),this.#e=O1e(C1e(e,this.#t)),Object.freeze(this)}static parse(e,r={}){return new mJ(e,r)}get tokens(){return this.#e}expand=e=>dJ(this.#e,e,this.#t);match=e=>XNe(this.#e,e,this.#t);toString=()=>this.uriTemplate},O1e=t=>Object.freeze(t.map(D1e)),D1e=t=>t.kind==="literal"?Object.freeze({kind:"literal",text:t.text}):Object.freeze({kind:"expression",operator:t.operator,vars:Object.freeze(t.vars.map(N1e))}),N1e=t=>Object.freeze({name:t.name,explode:t.explode,...t.prefix==null?{}:{prefix:t.prefix}}),z1e=()=>{},M1e=({strict:t,report:e})=>(e??=z1e,t??=!0,e=t?U1e(e):e,{strict:t,report:e}),U1e=t=>e=>{throw t(e),e};var ac=class extends Error{constructor(r,o){super(o);this.code=r}code};function L1e(t,e){return!t.when||e[t.when.field]===void 0||t.when.values.includes(e[t.when.field])}function F$(t,e,r={}){let o=(i,s)=>{throw new ac(i,s)},n={...r,...e};for(let i of t)n[i.name]===void 0&&i.defaultValue!==void 0&&(n[i.name]=i.defaultValue);for(let i of t){if(!L1e(i,n)){delete n[i.name];continue}i.required!==!1&&!n[i.name]&&o("missing_field","Complete the required service fields."),n[i.name]?.includes("\0")&&o("invalid_field","Check the service fields."),i.choices&&n[i.name]&&!i.choices.some(s=>s.value===n[i.name])&&o("invalid_field","Choose an available service setting."),i.pattern&&(i.pattern.length>200||!(0,hJ.default)(i.pattern))&&o("invalid_pattern","Use a simple field validation pattern."),i.pattern&&n[i.name]&&!new RegExp(i.pattern,"u").test(n[i.name].slice(0,1e3))&&o("invalid_field","Check the service fields.")}return Object.keys(e).some(i=>!t.some(s=>s.name===i))&&o("invalid_field","Remove unrecognized service fields."),n}function Us(t,e,r={}){let o=F$(t,e,r),n={};for(let i of t){let s=i.choices?.find(a=>a.value===o[i.name]);for(let[a,c]of Object.entries(s?.values??{})){if(t.some(u=>u.name===a)||a in n&&n[a]!==c)throw new ac("invalid_field","Use distinct values for each service setting.");n[a]=c}}return{...o,...n}}function q$(t,e){for(let[r,o]of Object.entries(e)){let n=t.find(i=>i.name===r);if(!n)throw new ac("invalid_field","Use the fields declared by the connection method.");if(n.secret!==!1&&o!=="")throw new ac("encrypted_input_required","Supply private material directly with your encryption keys.")}return F$(t.map(r=>({...r,required:!1,defaultValue:void 0})),e)}function fo(t,e){return q$(t,Object.fromEntries(t.filter(r=>r.secret===!1&&e[r.name]).map(r=>[r.name,e[r.name]])))}function jf(t,e,r){q$(t,e);for(let[o,n]of Object.entries(e))if(n&&r[o]!==void 0&&r[o]!==n)throw new ac("operation_changed","Use the service settings prepared by this operation.");return{...e,...r}}function gJ(t,e=Wy(t)){return e.accountVerified?e.accountId:null}function yJ(t,e=Wy(t)){let o=(t.method.kind==="oauth"||t.method.kind==="ovh"||t.method.kind==="token"&&!!(t.method.config.identity||t.method.config.resolver||t.method.config.bindFields))&&t.method.kind!=="aws"?fo(t.method.config.fields,t.fields??{}):{};return{format:t.format,generation:t.generation,methodId:t.methodId,method:t.method,appId:t.appId,appGeneration:t.appGeneration,..."implicitApp"in t&&t.implicitApp?{implicitApp:{clientId:t.implicitApp.clientId,generation:t.implicitApp.generation,fields:t.implicitApp.fields}}:{},account:e.accountId,accountVerified:e.accountVerified,scopes:[...e.scopes].sort(),...Object.keys(o).length?{fields:o}:{},...e.authorization,...t.state?{state:t.state}:{}}}var hu=m.record(m.string().max(100),m.string().max(16384)),Zn=m.object({format:m.literal(1),methodId:m.string().min(1),generation:E,clientId:m.string().max(1e3),clientSecret:m.string().max(16384).optional(),fields:hu}).strict(),mj=m.object({accessToken:m.string().min(1).max(16384),refreshToken:m.string().min(1).max(16384).optional(),expiresAt:m.number().nullable(),refreshExpiresAt:m.number().optional(),scopes:m.array(m.string()),requestedScopes:m.array(m.string()).optional(),account:m.string(),accountName:m.string(),accountVerified:m.boolean().optional(),scopesStatus:m.enum(["unknown","requested","reported"]).optional(),extra:hu,facts:Lt}).strict(),tv={format:m.literal(2),methodId:m.string().min(1),method:nu,generation:E,appId:E.nullable(),appGeneration:E.nullable(),state:m.literal("reconnect").optional()},cc=m.never().optional(),$n=m.union([m.object({...tv,method:r$,oauth:mj.optional(),requestedScopes:m.array(m.string()).optional(),implicitApp:Zn.optional(),fields:hu.optional(),aws:cc}).strict(),m.object({...tv,method:n$,fields:hu,facts:du.optional(),oauth:cc,aws:cc}).strict(),m.object({...tv,method:s$,fields:hu,oauth:cc,aws:cc}).strict(),m.object({...tv,method:i$,fields:hu,ovh:Cy.optional(),requestedScopes:m.array(m.string()).optional(),oauth:cc,aws:cc}).strict(),m.object({...tv,method:o$,aws:WE,oauth:cc,fields:cc}).strict()]).superRefine((t,e)=>{if("implicitApp"in t&&t.implicitApp&&(t.method.kind!=="oauth"||t.method.config.application!=="implicit"||t.implicitApp.methodId!==t.methodId)&&e.addIssue({code:"custom",message:"Keep the registered client with its implicit OAuth connection."}),t.method.kind==="oauth"&&t.fields)try{q$(t.method.config.fields,t.fields)}catch{e.addIssue({code:"custom",path:["fields"],message:"Keep only declared public settings in the connection."})}lu(t.method)&&(!t.appId||!t.appGeneration)&&e.addIssue({code:"custom",message:"Bind the application required by this connection."}),!lu(t.method)&&t.appId!==null&&e.addIssue({code:"custom",message:"Use an application only when the connection requires one."}),!!t.appId!=!!t.appGeneration&&e.addIssue({code:"custom",message:"Bind the application and its generation together."}),t.method.kind==="oauth"&&t.method.config.grantType==="client_credentials"&&!("requestedScopes"in t&&t.requestedScopes)&&!t.oauth?.requestedScopes&&e.addIssue({code:"custom",message:"Keep the selected scopes for client credentials renewal."})}),rSt=m.object({methodId:m.string().min(1).max(200),clientId:m.string().max(1e3),generation:E,fields:hu.optional()}).strict(),j1e=m.object({methodId:m.string().min(1).max(200),methodKind:kL,generation:E,authorizationDigest:Sr,appId:E.nullable(),accountId:m.string().max(2e3).nullable(),accountVerified:m.boolean(),scopes:m.array(m.string().max(1e3)).max(200),scopesStatus:m.enum(["unknown","requested","reported"]),outputs:m.array(m.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/)).max(100),state:m.enum(["ready","reconnect"]),fields:hu.optional(),aws:JE.optional(),ovh:Cy.optional()}).strict();async function Ff(t,e=Wy(t)){let r=xr(t.method).outputs,o=t.method.kind!=="aws"&&t.fields?fo(t.method.config.fields,t.fields):{},n=await Q(yJ(t,e));return j1e.parse({methodId:t.methodId,methodKind:t.method.kind,generation:t.generation,authorizationDigest:n,appId:t.appId,accountId:gJ(t,e),accountVerified:e.accountVerified,scopes:e.scopes,scopesStatus:e.scopesStatus,outputs:r,state:t.state??"ready",...Object.keys(o).length?{fields:o}:{},...e.details})}var F1e=m.array(m.object({name:m.string(),label:m.string(),value:m.string()}).strict()),vJ=m.object({methodName:fe,account:m.string().max(2e3),settings:F1e.optional()}).strict();function V$(t){let e=xr(t.method).fields,r=t.method.kind!=="aws"&&t.fields?fo(e,t.fields):{},o=e.filter(n=>r[n.name]).map(n=>({name:n.name,label:n.label,value:n.choices?.find(i=>i.value===r[n.name])?.label??r[n.name]}));return{methodName:t.method.name,account:"",...o.length?{settings:o}:{}}}var hj=m.discriminatedUnion("action",[m.object({action:m.literal("refresh"),id:E}).strict(),m.object({action:m.literal("revoke"),id:E}).strict()]);var gj=Ns.extend({name:fe}),dSt=m.object({bootstrap:m.string().regex(/^[A-Za-z0-9_-]{43}$/),binding:Ns,token:m.string().regex(/^fk_[A-Za-z0-9_-]{43}$/)}).strict(),wJ=m.object({id:E,executorId:E,ownerId:E,name:fe,origin:m.url(),bootstrap:m.string().regex(/^[A-Za-z0-9_-]{43}$/),ssh:m.object({port:m.number().int().min(1).max(65535)}).strict().optional(),commandImage:m.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/)}).strict(),pSt=Ns.extend({previousSignature:cr.optional()}).strict(),_J=m.object({name:fe,content:tn,labels:vJ.optional(),version:m.number().int().positive().optional()}).strict(),rv=m.object({content:tn,version:m.number().int().positive()}).strict(),bJ=m.object({id:E,reason:m.enum(["grantExpired","recipients"]),remove:m.array(E).max(1e3).default([])}).strict(),fSt=m.record(E,m.object({version:m.number().int().positive(),content:tn}).strict()),SJ=m.object({id:E,name:fe,version:m.number().int().positive(),content:tn,policy:en}).strict(),xJ=m.object({registration:qL,stoppedAt:m.iso.datetime().nullable(),heartbeatAt:m.iso.datetime().nullable()}).strict(),EJ=m.object({lease:E,request:kf,sources:m.array(tn).max(100)}).strict().nullable(),q1e=m.object({lease:E}).strict(),mSt=q1e.extend({receipt:Hy}).strict(),nv=m.object({id:E,resource_id:E,executor_id:E,expected_revision:m.number().int().positive(),state:m.enum(["prepared","in_flight","committed","uncertain","aborted"]),fence:m.string().regex(/^\d+$/),result:tn.nullable()}),hSt=m.object({id:E,resourceId:E,expectedRevision:m.number().int().positive()}).strict(),V1e=m.object({fence:m.string().regex(/^\d+$/)}).strict(),gSt=V1e.extend({content:tn}).strict(),ySt=m.object({id:E,executionId:E,index:m.number().int().nonnegative(),stateDigest:Sr,expiresAt:$e}).strict(),yj=m.object({id:E,executionId:E,context:m.string(),sealed:Ao.nullable(),expiresAt:$e,receivedAt:$e.nullable()}).strict(),$J=(t,e)=>"oauth-callback:"+t+":"+e;var G1e=m.object({binding:Kt,verifiedAt:$e}).strict(),vj=m.object({origin:m.url(),ownerId:E,signerId:E,revision:m.number().int().positive(),keys:m.array(G1e).max(1e3)}).strict(),H1e=m.object({version:m.number().int().positive(),signature:cr}).strict(),wj=m.object({keyring:H1e.nullable()}).strict(),xSt=m.object({version:m.number().int().positive().nullable(),signature:cr}).strict();function RJ(t,e){return ir(vj.parse(t),e,"keyring")}function IJ(t){return vj.parse(JSON.parse(Kn(d$(t.split(".")[1]??""))))}async function AJ(t,e){let r=vj.parse(await Ly(t,e.signing,"keyring"));if(r.signerId!==e.id)throw new Error("Another identity signed this keyring.");return r}var oi=class extends Error{constructor(r,o){super(o);this.code=r}code},bj=class extends Error{constructor(r){super("The execution request has been saved. Check execution "+r+" before starting another operation.");this.id=r}id},_j=(t,...e)=>!!t&&typeof t=="object"&&("code"in t&&e.includes(String(t.code))||"status"in t&&e.includes(Number(t.status))),G$=class{constructor(e,r,o,n,i){this.api=e;this.origin=r;this.binding=o;this.keys=n;this.trust=i}api;origin;binding;keys;trust;verifiedKeys;async trusted(e){if(!await this.verifies(e))throw new oi("identity_untrusted","Verify and trust the encryption and signing keys for identity "+e.principalId+" before sharing.");return e}async verifies(e){if(e.principalId===this.binding.principalId)return C(this.binding)===C(e);let r=(await this.keyring()).get(e.principalId)?.binding??await this.trust.binding(e.principalId);return!!r&&C(r)===C(e)}async verifiedIdentity(e){return this.verifies((await this.inspectIdentity(e)).binding)}keyring(){return this.verifiedKeys??=this.loadKeyring().catch(e=>{throw this.verifiedKeys=void 0,e})}async loadKeyring(){let e;try{e=(await this.readKeyring()).keyring?.keys??[]}catch(i){if(_j(i,401,403))return new Map;throw i}let r=new Set(e.map(i=>i.binding.principalId)),o=new Date().toISOString(),n=(await this.trust.bindings()).filter(i=>i.principalId!==this.binding.principalId&&!r.has(i.principalId));if(n.length)try{e=(await this.changeKeyring(i=>[...i,...n.filter(s=>!i.some(a=>a.binding.principalId===s.principalId)).map(s=>({binding:s,verifiedAt:o}))])).keys}catch(i){if(i instanceof oi)throw i}return new Map(e.map(i=>[i.binding.principalId,i]))}async readKeyring(){let e="/api/principals/"+this.binding.principalId+"/keyring",{keyring:r}=await this.api.json(e,{},wj),o=await this.trust.keyring(),n=()=>new oi("keyring_conflict","The list of verified public keys does not match what this device saw before.");if(!r){if(o)throw n();return{version:null,revision:0,keyring:null}}let i=IJ(r.signature);if(i.signerId!==this.binding.id)return{version:r.version,revision:i.revision,keyring:null};let s=await AJ(r.signature,this.binding).catch(()=>{throw n()}),a=await Q(s);if(s.ownerId!==this.binding.principalId||s.origin!==this.origin||o&&(s.revision<o.revision||s.revision===o.revision&&a!==o.digest))throw n();return(!o||s.revision>o.revision)&&await this.trust.rememberKeyring({revision:s.revision,digest:a}),{version:r.version,revision:s.revision,keyring:s}}async changeKeyring(e){for(let r=1;;r++){let o=await this.readKeyring(),n={origin:this.origin,ownerId:this.binding.principalId,signerId:this.binding.id,revision:o.revision+1,keys:e(o.keyring?.keys??[])};try{await this.api.json("/api/principals/"+this.binding.principalId+"/keyring",{method:"PUT",body:{version:o.version,signature:await RJ(n,this.keys.signing)}},wj)}catch(i){if(r<3&&_j(i,"changed"))continue;throw i}return await this.trust.rememberKeyring({revision:n.revision,digest:await Q(n)}),n}}async inspectIdentity(e){let r=await this.api.json("/api/identities/"+E.parse(e)+"/binding",{},Ns);return await g$(r),{...r,fingerprint:await Ya(r.binding)}}async trustIdentity(e,r){let o=await this.inspectIdentity(e);if(o.fingerprint!==r)throw new oi("fingerprint_mismatch","The identity fingerprint does not match.");if(e===this.binding.principalId||C((await this.keyring()).get(e)?.binding??null)===C(o.binding))return o;let n=new Date().toISOString();try{let i=await this.changeKeyring(s=>[...s.filter(a=>a.binding.principalId!==e),{binding:o.binding,verifiedAt:n}]);this.verifiedKeys=Promise.resolve(new Map(i.keys.map(s=>[s.binding.principalId,s])))}catch(i){if(!_j(i,401,403))throw i;await this.trust.rememberBinding(o.binding)}return o}async environment(e,r=!0){let{registration:o,stoppedAt:n}=await this.api.json("/api/environments/"+E.parse(e)+"/registration",{},xJ);if(await Cf(o),o.manifest.origin!==this.origin||o.manifest.id!==e||n)throw new Error("Choose an active execution environment on this Foundation server.");return r&&await this.trusted(o.manifest.executor),o}async recipients(e){let{items:r}=await this.api.json("/api/principals/"+E.parse(e)+"/bound-recipients",{},Mr(gj));if(!r.length)throw new Error("Set up an encryption key for the owner before saving private content.");for(let{name:i,...s}of r)await g$(s),await this.trusted(s.binding);let o=await this.api.json("/api/principals/"+E.parse(e)+"/bound-agents",{},Mr(gj)),n=[];for(let{name:i,...s}of o.items){await g$(s);try{n.push(await this.trusted(s.binding))}catch(a){if(!(a instanceof oi&&a.code==="identity_untrusted"))throw a}}return[...r.map(i=>i.binding),...n]}async read(e){let r=await this.api.json("/api/custody/"+E.parse(e),{},rv);return await this.observe(r.content,e),r}async observe(e,r=e.policy.id){let o=await ko(e);if(o.policy.id!==r||o.policy.origin!==this.origin)throw new Error("The encrypted content belongs to another item.");let n=LL(o);await this.trusted(n);let i=await this.trust.checkpoint(o);if(i&&en.parse(i.policy),i){if(o.policy.revision<i.policy.revision||o.materialRevision<i.materialRevision||o.policy.revision===i.policy.revision&&C(o.policy)!==C(i.policy)||o.materialRevision===i.materialRevision&&await Q(o)!==i.digest)throw new oi("content_conflict","The encrypted content is older than this device has already observed.");if(o.policy.revision>i.policy.revision&&!w$(i.policy,o))throw new oi("content_conflict","An existing policy authority must approve the new recipients.")}return await this.trust.rememberContent(o),o}async reveal(e){return cd((await this.read(e)).content,this.binding,this.keys.encryption)}async sharing(e){let r=typeof e=="string"?(await this.api.json(e,{},Mr(SJ))).items:e,o={};for(let n of r){let i=await this.read(n.id);if(i.version!==n.version||C(i.content)!==C(n.content))throw new oi("content_conflict","Review the current content before changing its readers.");for(let s of n.policy.readers)await this.trusted(s);o[n.id]={version:n.version,content:await ad(await cd(i.content,this.binding,this.keys.encryption),n.policy,i.content.materialRevision+1,this.binding,this.keys,i.content.metadata,i.content)}}return o}async policy(e,r,o=[],n={}){let i=n.previous?.readers??[...new Map([...await this.recipients(e),this.binding].map(c=>[c.id,c])).values()];if(!i.some(c=>C(c)===C(this.binding)))throw new Error("Include your own identity as a reader before creating this item.");let s=n.expiresAt??new Date(Date.now()+30*864e5).toISOString(),a=n.previous?n.previous.grants.filter(c=>(!("actor"in c)||c.actor.id!==this.binding.id)&&Qa(c)):[];for(let c of o)await this.trusted(c.manifest.executor),a.push({actor:this.binding,executor:c.manifest.executor,operations:[...ou(r)],origins:[],functionDigests:[],callerProgram:r!==he.clientCredential,expiresAt:s});return en.parse({format:2,id:n.id??n.previous?.id??crypto.randomUUID(),origin:this.origin,ownerId:e,contentType:r,revision:(n.previous?.revision??0)+1,authorities:n.previous?.authorities??i,readers:i,grants:a,producers:[]})}async save(e,r,o,n={}){let i=n.previous;i&&C(o)===C({...i.content.policy,revision:o.revision})&&(o={...o,revision:i.content.policy.revision});let s=await ad(r,o,(i?.content.materialRevision??0)+1,this.binding,this.keys,n.metadata,i?.content),a={name:e,content:s,...n.labels?{labels:n.labels}:{},...i?{version:i.version}:{}},c=n.commit?await n.commit(a):await this.api.json("/api/resources/"+o.id+"/custody",{method:"PUT",body:a},br);return await this.trust.rememberContent(s),c}async pass(e,r,o,n){let i=await ad(r,o,n.content.materialRevision+1,this.binding,this.keys,n.content.metadata,n.content),s=await this.api.json("/api/resources/"+o.id+"/custody",{method:"PUT",body:{name:e,content:i,version:n.version}},m.union([br,Ze]));return"kind"in s&&await this.trust.rememberContent(i),s}async pendingProtection(){return(await this.api.json("/api/principals/"+this.binding.principalId+"/reprotection",{},Mr(bJ))).items}async reprotect(e,r="grantExpired",o=[]){let n=await this.read(e),{policy:i}=n.content,s=Date.now(),a=new Set(o),c=r==="recipients"?await this.recipients(i.ownerId):[],u=S=>!a.has(S.principalId)&&!c.some(x=>x.principalId===S.principalId&&x.id!==S.id),l=i.grants.filter(S=>Qa(S,s)&&u(S.executor)&&(!("actor"in S)||u(S.actor))),d=i.readers.filter(u),p=i.authorities.filter(u),f=c.filter(S=>!d.some(x=>x.id===S.id)),h={...i,revision:i.revision+1,grants:l,producers:[],readers:[...d,...f],authorities:[...p,...f.filter(S=>!p.some(x=>x.id===S.id))],...i.observers?{observers:i.observers.filter(S=>!a.has(S))}:{}},y=i.contentType!==he.executionResult&&i.producers.some(S=>Date.parse(S.expiresAt)>s);if(C({...h,revision:i.revision})===C(i)||y)return null;let w=await cd(n.content,this.binding,this.keys.encryption);if(i.contentType===he.executionResult){let S=await ad(w,h,n.content.materialRevision+1,this.binding,this.keys,n.content.metadata,n.content);return await this.api.json("/api/custody/"+e,{method:"PUT",body:{name:"Execution result",content:S,version:n.version}},rv),await this.trust.rememberContent(S),e}let b=await this.api.json("/api/resources/"+i.id,{},br);return this.save(b.name,w,h,{metadata:n.content.metadata,previous:n})}async reprotectPending(){let e=[],r=[];for(let o of await this.pendingProtection())try{await this.reprotect(o.id,o.reason,o.remove)&&e.push(o.id)}catch(n){r.push({id:o.id,code:n&&typeof n=="object"&&"code"in n&&typeof n.code=="string"?n.code:"failure"})}return{done:e,failed:r}}async sourceContents(e){let r=new Map;for(let o of new Set(e))r.set(o,(await this.read(o)).content);for(let o of[...r.values()])o.policy.contentType===he.tokenSet&&typeof o.metadata.appId=="string"&&!r.has(o.metadata.appId)&&r.set(o.metadata.appId,(await this.read(o.metadata.appId)).content);return[...r.values()]}async output(e,r,o,n,i){let s,a=null;do{let l=new URLSearchParams({kind:"variable",query:r,...a?{after:a}:{}}),d=await this.api.json("/api/principals/"+e+"/resources?"+l,{},Mr(br));s=d.items.find(p=>p.name===r),a=d.next}while(!s&&a);let c=s?(await this.read(s.id)).content:void 0,u=c?{...c.policy,revision:c.policy.revision+1,producers:[]}:await this.policy(e,he.value);return u.producers=[{executor:n.manifest.executor,runId:o,expiresAt:i,materialRevision:(c?.materialRevision??0)+1}],{name:r,approval:await S$(u,this.binding,this.keys,c)}}async prepare(e,r,o,n={}){let i=ec.parse(o),s=await this.environment(r);await this.trusted(s.manifest.executor);let a=n.id??crypto.randomUUID(),c=n.expiresAt??new Date(Date.now()+36e5).toISOString(),u=i,l=u.kind==="http"?u.request:null;if(i.kind==="http"){let w=n.save??{},b=Object.fromEntries(await Promise.all(Object.entries(w).map(async([S,x])=>[S,await this.output(e,x,a,s,c)])));i.save=b}let d=u.kind==="command"?u.inputs.map(w=>w.source.id):l?l.bindings.flatMap(w=>w.parts.flatMap(b=>typeof b=="string"?[]:[b.id])):[],p=await this.sourceContents([...d,...n.sourceIds??[]]);for(let w=0;w<p.length;w++){let b=p[w],S=b.policy.contentType===he.clientCredential,x=S&&i.kind!=="revoke"?ue.refresh:ue[i.kind],R=S?void 0:l?new URL(l.url).origin:void 0;if(b.policy.grants.some(me=>"actor"in me&&C(me.actor)===C(this.binding)&&C(me.executor)===C(s.manifest.executor)&&me.operations.includes(x)&&Pf(me)>=Date.parse(c)&&(!R||!me.origins.length||me.origins.includes(R))&&(S||me.callerProgram))||!b.policy.authorities.some(me=>C(me)===C(this.binding)))continue;let M=await this.read(b.policy.id),Z=await this.api.json("/api/resources/"+b.policy.id,{},br),te={actor:this.binding,executor:s.manifest.executor,operations:[...new Set([x,...b.policy.contentType===he.tokenSet?[ue.refresh]:[]])],origins:R?[R]:[],functionDigests:[],callerProgram:!S,expiresAt:c},Ae=me=>C({...me,expiresAt:null}),Te=M.content.policy.grants.filter(me=>Ae(me)===Ae(te)),bt=en.parse({...M.content.policy,revision:M.content.policy.revision+1,grants:[...M.content.policy.grants.filter(me=>Qa(me)&&Ae(me)!==Ae(te)),{...te,expiresAt:new Date(Math.max(Date.parse(c),...Te.map(me=>Pf(me)))).toISOString()}]});await this.save(Z.name,await cd(M.content,this.binding,this.keys.encryption),bt,{previous:M,metadata:M.content.metadata}),p[w]=(await this.read(b.policy.id)).content}let f=await this.policy(e,he.executionResult,[],{id:a});f.producers=[{executor:s.manifest.executor,runId:a,expiresAt:c,materialRevision:1}];let h={format:2,id:a,origin:this.origin,ownerId:e,actor:this.binding,environmentId:r,executor:s.manifest.executor,environmentDigest:await Q(s.manifest),operation:ue[i.kind],operationDigest:await Q(i),...n.approval?{approval:n.approval}:{},...n.operationContext?{operationContext:n.operationContext}:{},functionDigest:null,sources:await Promise.all(p.map(async w=>({id:w.policy.id,materialRevision:w.materialRevision,policyDigest:await Q(w.policy),...w.policy.contentType===he.tokenSet&&typeof w.metadata.authorizationDigest=="string"?{authorizationDigest:w.metadata.authorizationDigest}:{}}))),resultRecipients:f.readers,...s.manifest.resultVersion?{resultApproval:await S$(f,this.binding,this.keys)}:{},createdAt:new Date().toISOString(),expiresAt:c};await Of(s,h);let y=w=>w.policy.contentType===he.clientCredential;for(let w of p)await ld(w,y(w)&&h.operation!==ue.connect&&h.operation!==ue.revoke?{...h,operation:ue.refresh}:h,y(w)?{}:{destination:l?.url});return d8(h,i,this.keys)}async submit(e,r,o,n={}){return this.submitPrepared(await this.prepare(e,r,o,n))}async submitPrepared(e){await this.trust.rememberRun(e);try{return await this.api.json("/api/runtime/runs",{method:"POST",body:e},Bn)}catch(r){throw r&&typeof r=="object"&&"status"in r?r:new bj(e.intent.id)}}async resume(e){let r=await this.trust.run(E.parse(e));if(!r)throw new Error("Resume this execution from the device that saved its signed request.");if(C(r.intent.actor)!==C(this.binding)||r.intent.origin!==this.origin)throw new Error("Use the identity that signed this execution request.");try{let o=await this.api.json("/api/runtime/runs/"+e,{},Bn);if(C(o.intent)!==C(r.intent)||o.requestSignature!==r.signature)throw new Error("Use the saved request that started this execution.");return o}catch(o){if(!o||typeof o!="object"||!("code"in o)||o.code!=="not_found")throw o}return this.submitPrepared(r)}async result(e){if(e.intent.origin!==this.origin||e.intent.id!==e.id)throw new Error("This execution belongs to another Foundation server.");await this.trusted(e.intent.actor);let r=await Ly(e.requestSignature,e.intent.actor.signing,"run");if(C(r.intent)!==C(e.intent))throw new Error("The result belongs to a different signed request.");if(await this.trusted(e.intent.executor),!(e.receipt&&"content"in e.receipt?e.receipt.content.policy.readers:e.intent.resultRecipients).some(n=>C(n)===C(this.binding)))throw new oi("not_recipient","This identity is not a reader of the execution result.");return e.receipt&&"content"in e.receipt&&await this.observe(e.receipt.content,e.id),e.receipt?v8(e.receipt,e.intent,this.binding.id,this.keys):null}async shareLegacyResult(e){if(!e.receipt||"content"in e.receipt)return e;if(C(e.intent.actor)!==C(this.binding)||C(e.intent.executor)!==C(this.binding))throw new oi("executor_required","The original executor and requester must attest this legacy result.");let r=await this.result(e);if(!r)throw new Error("Wait for this execution to finish before sharing its result.");let o=await this.policy(e.ownerId,he.executionResult,[],{id:e.id});o.producers=[{executor:this.binding,runId:e.id,expiresAt:new Date(Date.now()+36e5).toISOString(),materialRevision:1}];let n=await GL(e.intent,e.receipt.state,r,this.keys,await S$(o,this.binding,this.keys),e.receipt);return this.api.json("/api/runtime/runs/"+e.id+"/result",{method:"PUT",body:{receipt:n}},Bn)}};import{lstat as K1e,mkdir as B1e,readFile as Z1e,readdir as W1e}from"node:fs/promises";import{join as PJ}from"node:path";var kJ=m.string().regex(/^(run|process|invocation|function|connect|refresh|checkpoint|identity|environment|flow)_[A-Za-z0-9_-]{1,100}$/),md=class{constructor(e,r,o,n){this.directory=e;this.origin=r;this.binding=o;this.privateKeys=n}directory;origin;binding;privateKeys;context(e){return C({purpose:"executor-journal",origin:this.origin,bindingId:this.binding.id,id:kJ.parse(e)})}async read(e){let r=this.context(e),o=PJ(this.directory,e+".json");try{let n=await K1e(o);if(!n.isFile()||n.isSymbolicLink()||process.platform!=="win32"&&n.mode&63)throw new Error("The execution journal must use private regular files.");let i=m.string().max(32e6).parse(JSON.parse(await Z1e(o,"utf8"))),s=await Ry(i,await Qo(this.privateKeys.encryption,"ECDH-ES+A256KW"),{keyManagementAlgorithms:["ECDH-ES+A256KW"],contentEncryptionAlgorithms:["A256GCM"]});if(s.protectedHeader.kid!==this.binding.id||s.protectedHeader.ctx!==r)throw new Error("The journal entry belongs to another operation.");let a=JSON.parse(Kn(s.plaintext));if(a.context!==r)throw new Error("The journal entry belongs to another operation.");return await Ur({context:r,value:a.value},a.signature,this.binding.signing,"journal"),a.value}catch(n){if(n instanceof Error&&"code"in n&&n.code==="ENOENT")return null;throw n}}async write(e,r){let o=this.context(e),n={context:o,value:r},i=await ir(n,this.privateKeys.signing,"journal"),s=tt(C({...n,signature:i}));if(s.byteLength>2e7)throw new Error("The execution record is too large.");let a=await new xf(s).setProtectedHeader({alg:"ECDH-ES+A256KW",enc:"A256GCM",kid:this.binding.id,ctx:o}).encrypt(await Qo(this.binding.encryption,"ECDH-ES+A256KW"));await B1e(this.directory,{recursive:!0,mode:448}),await Nf(PJ(this.directory,e+".json"),C(a),!0)}async keys(e){let r;try{r=await W1e(this.directory,{withFileTypes:!0})}catch(o){if(o instanceof Error&&"code"in o&&o.code==="ENOENT")return[];throw o}return r.filter(o=>o.isFile()&&o.name.startsWith(e)&&o.name.endsWith(".json")).map(o=>kJ.parse(o.name.slice(0,-5)))}};var H$=class{constructor(e){this.journal=e}journal;binding(e){return this.journal.read("identity_"+e)}async bindings(){return(await Promise.all((await this.journal.keys("identity_")).map(r=>this.journal.read(r)))).filter(r=>r!==null)}async rememberBinding(e){await zs(e),await this.journal.write("identity_"+e.principalId,e)}keyring(){return this.journal.read("checkpoint_keyring")}async rememberKeyring(e){await this.journal.write("checkpoint_keyring",e)}checkpoint(e){return this.journal.read("checkpoint_"+e.policy.format+"_"+e.policy.id)}async rememberContent(e){await this.journal.write("checkpoint_"+e.policy.format+"_"+e.policy.id,{policy:e.policy,materialRevision:e.materialRevision,digest:await Q(e)})}run(e){return this.journal.read("run_"+e)}async rememberRun(e){let r=await this.run(e.intent.id);if(r&&C(r)!==C(e))throw new Error("Use a new execution ID for a different request.");await this.journal.write("run_"+e.intent.id,e)}};var dt=class extends Error{constructor(r,o,n,i){super(n);this.status=r;this.code=o;this.details=i}status;code;details};function q(t,e,r,o){throw new dt(t,e,r,o)}var K$=class{api;constructor(e){this.api={async json(r,o={},n){try{return await e.json(r,o,n)}catch(i){throw i instanceof Error&&"status"in i&&typeof i.status=="number"&&"code"in i&&typeof i.code=="string"?new dt(i.status,i.code,i.message):i}}}}claim(e){return this.api.json("/api/environments/"+e+"/claim",{method:"POST",body:{}},EJ)}renew(e,r){return this.api.json("/api/runtime/runs/"+e+"/renew",{method:"POST",body:{lease:r}},m.object({active:m.boolean()}))}dispatch(e,r){return this.api.json("/api/runtime/runs/"+e+"/dispatch",{method:"POST",body:{lease:r}})}finish(e,r){return this.api.json("/api/runtime/runs/"+r.id+"/finish",{method:"POST",body:{lease:e,receipt:r}},Bn)}capture(e,r,o){return this.api.json("/api/executor/outputs",{method:"POST",body:{name:e,content:r,...o?{labels:o}:{}}},m.object({id:E}))}connections(){let e=this.api;return{prepare:(r,o,n)=>e.json("/api/connection-operations",{method:"POST",body:{id:r,resourceId:o,expectedRevision:n}},nv),dispatch:(r,o)=>e.json("/api/connection-operations/"+r+"/dispatch",{method:"POST",body:{fence:o}},nv),commit:(r,o,n)=>e.json("/api/connection-operations/"+r+"/commit",{method:"POST",body:{fence:o,content:n}},tn),uncertain:(r,o)=>e.json("/api/connection-operations/"+r+"/uncertain",{method:"POST",body:{fence:o}}),abort:(r,o)=>e.json("/api/connection-operations/"+r+"/abort",{method:"POST",body:{fence:o}},nv),state:r=>e.json("/api/connections/"+r+"/operation",{},nv.nullable())}}};import{randomUUID as SHe}from"node:crypto";var Sc=Vt(LV(),1);import{randomUUID as mGe}from"node:crypto";function mde(t){let e=ZE.safeParse({accountId:t.Account,arn:t.Arn,principalId:t.Arn?.includes(":assumed-role/")?t.UserId?.split(":")[0]:t.UserId});return(!e.success||e.data.arn.split(":")[4]!==e.data.accountId)&&q(502,"invalid_response","The AWS account could not be verified."),e.data}function hde(t,e){return t.accountId===e.accountId&&t.principalId===e.principalId&&Ef(t.arn)===Ef(e.arn)}function jV(t){t&&(!Number.isFinite(t.getTime())||t.getTime()<=Date.now())&&q(409,"reconnect_required","Reconnect with current AWS credentials.")}var fk=class{async obtain(e,r,o){let n=Ba.parse({authentication:e.authentication,region:e.region,...e.role?{role:e.role}:{}}),i=n.authentication,s=i.kind==="environment"?void 0:{accessKeyId:i.accessKeyId,secretAccessKey:i.secretAccessKey,...i.kind==="session"?{sessionToken:i.sessionToken,expiration:new Date(i.expiresAt)}:{}};jV(s?.expiration);let a=new Sc.STSClient({region:n.region,...s?{credentials:s}:{}}),c,u=AbortSignal.any([AbortSignal.timeout(2e4),...o?[o]:[]]),l=!1;try{let d=s??await a.config.credentials();jV(d.expiration),c=new Sc.STSClient({region:n.region,credentials:d});let p=r?.sourceIdentity?mde(await c.send(new Sc.GetCallerIdentityCommand({}),{abortSignal:u})):void 0;r?.sourceIdentity&&p&&!hde(p,r.sourceIdentity)&&q(409,"account_changed","Reconnect to approve the current AWS authentication source.");let f=d,h=p;if(n.role){l=!0;let b=(await c.send(new Sc.AssumeRoleCommand({RoleArn:n.role.arn,RoleSessionName:"foundation-"+mGe().slice(0,8),DurationSeconds:3600,...n.role.externalId?{ExternalId:n.role.externalId}:{}}),{abortSignal:u})).Credentials;(!b?.AccessKeyId||!b.SecretAccessKey||!b.SessionToken||!b.Expiration)&&q(502,"invalid_response","AWS did not return credentials."),f={accessKeyId:b.AccessKeyId,secretAccessKey:b.SecretAccessKey,sessionToken:b.SessionToken,expiration:b.Expiration},jV(f.expiration),r?.identity&&(c.destroy(),c=new Sc.STSClient({region:n.region,credentials:f}),h=mde(await c.send(new Sc.GetCallerIdentityCommand({}),{abortSignal:u})))}return r?.identity&&h&&!hde(h,r.identity)&&q(409,"account_changed","Reconnect to approve the current AWS account and role."),{state:WE.parse({...n,sourceIdentity:p,identity:h}),credentials:{AWS_ACCESS_KEY_ID:f.accessKeyId,AWS_SECRET_ACCESS_KEY:f.secretAccessKey,AWS_SESSION_TOKEN:f.sessionToken??"",AWS_DEFAULT_REGION:n.region,AWS_REGION:n.region}}}catch(d){if(d instanceof dt)throw d;o?.aborted&&q(409,"cancelled","The operation was cancelled."),d instanceof Error&&["ExpiredToken","ExpiredTokenException","TokenRefreshRequired"].includes(d.name)&&q(409,"reconnect_required","Reconnect with current AWS credentials."),l&&q(502,"role_denied","Check the IAM role and its trust policy for this authentication source."),q(502,"aws_authentication_failed","Check the AWS credentials available to the selected environment.")}finally{c?.destroy(),a.destroy()}}};var mk=class{constructor(e){this.aws=e}aws;facts=XL;needsRenewal(){return!1}async outputs(e,r,o){return(await this.aws.obtain(e.aws,e.aws,o)).credentials}};var FV;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(FV="oauth4webapi/v3.8.8");function bk(t,e){if(t==null)return!1;try{return t instanceof e||Object.getPrototypeOf(t)[Symbol.toStringTag]===e.prototype[Symbol.toStringTag]}catch{return!1}}var Ea="ERR_INVALID_ARG_VALUE",xc="ERR_INVALID_ARG_TYPE";function Or(t,e,r){let o=new TypeError(t,{cause:r});return Object.assign(o,{code:e}),o}var vde=Symbol(),hGe=Symbol(),gGe=Symbol(),JV=Symbol();var hk=Symbol();var yGe=new TextEncoder,vGe=new TextDecoder;function qV(t){return typeof t=="string"?yGe.encode(t):vGe.decode(t)}var VV;Uint8Array.prototype.toBase64?VV=t=>(t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t.toBase64({alphabet:"base64url",omitPadding:!0})):VV=e=>{e instanceof ArrayBuffer&&(e=new Uint8Array(e));let r=[];for(let o=0;o<e.byteLength;o+=32768)r.push(String.fromCharCode.apply(null,e.subarray(o,o+32768)));return btoa(r.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var GV;Uint8Array.fromBase64?GV=t=>{try{return Uint8Array.fromBase64(t,{alphabet:"base64url"})}catch(e){throw Or("The input to be decoded is not correctly encoded.",Ea,e)}}:GV=t=>{try{let e=atob(t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),r=new Uint8Array(e.length);for(let o=0;o<e.length;o++)r[o]=e.charCodeAt(o);return r}catch(e){throw Or("The input to be decoded is not correctly encoded.",Ea,e)}};function HV(t){return typeof t=="string"?GV(t):VV(t)}var lh=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=JGe,Error.captureStackTrace?.(this,this.constructor)}},c_=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,r?.code&&(this.code=r?.code),Error.captureStackTrace?.(this,this.constructor)}};function De(t,e,r){return new c_(t,{code:e,cause:r})}function gk(t){return!(t===null||typeof t!="object"||Array.isArray(t))}function wde(t){bk(t,Headers)&&(t=Object.fromEntries(t.entries()));let e=new Headers(t??{});if(FV&&!e.has("user-agent")&&e.set("user-agent",FV),e.has("authorization"))throw Or('"options.headers" must not include the "authorization" header name',Ea);return e}function wGe(t,e){if(e!==void 0){if(typeof e=="function"&&(e=e(t.href)),!(e instanceof AbortSignal))throw Or('"options.signal" must return or be an instance of AbortSignal',xc);return e}}function yk(t,e,r,o,n){try{if(typeof t!="number"||!Number.isFinite(t))throw Or(`${r} must be a number`,xc,n);if(t>0)return;if(e){if(t!==0)throw Or(`${r} must be a non-negative number`,Ea,n);return}throw Or(`${r} must be a positive number`,Ea,n)}catch(i){throw o?De(i.message,o,n):i}}function On(t,e,r,o){try{if(typeof t!="string")throw Or(`${e} must be a string`,xc,o);if(t.length===0)throw Or(`${e} must not be empty`,Ea,o)}catch(n){throw r?De(n.message,r,o):n}}function _de(t){bGe(t,"application/json")}function _Ge(t,...e){let r='"response" content-type must be ';if(e.length>2){let o=e.pop();r+=`${e.join(", ")}, or ${o}`}else e.length===2?r+=`${e[0]} or ${e[1]}`:r+=e[0];return De(r,YGe,t)}function bGe(t,e){if(NGe(t)!==e)throw _Ge(t,e)}async function bde(t){return On(t,"codeVerifier"),HV(await crypto.subtle.digest("SHA-256",qV(t)))}function Sde(t){let e=t?.[hGe];return typeof e=="number"&&Number.isFinite(e)?e:0}function xde(t){let e=t?.[gGe];return typeof e=="number"&&Number.isFinite(e)&&Math.sign(e)!==-1?e:30}function Ede(){return Math.floor(Date.now()/1e3)}function ph(t){if(typeof t!="object"||t===null)throw Or('"as" must be an object',xc);On(t.issuer,'"as.issuer"')}function fh(t){if(typeof t!="object"||t===null)throw Or('"client" must be an object',xc);On(t.client_id,'"client.client_id"')}function gde(t){return encodeURIComponent(t).replace(/(?:[-_.!~*'()]|%20)/g,e=>{switch(e){case"-":case"_":case".":case"!":case"~":case"*":case"'":case"(":case")":return`%${e.charCodeAt(0).toString(16).toUpperCase()}`;case"%20":return"+";default:throw new Error}})}function $de(t){return On(t,'"clientSecret"'),(e,r,o,n)=>{o.set("client_id",r.client_id),o.set("client_secret",t)}}function Rde(t){return On(t,'"clientSecret"'),(e,r,o,n)=>{let i=gde(r.client_id),s=gde(t),a=btoa(`${i}:${s}`);n.set("authorization",`Basic ${a}`)}}function Ide(){return(t,e,r,o)=>{r.set("client_id",e.client_id)}}var SGe=URL.parse?(t,e)=>URL.parse(t,e):(t,e)=>{try{return new URL(t,e)}catch{return null}};function xGe(t,e){if(e&&t.protocol!=="https:")throw De("only requests to HTTPS are allowed",eHe,t);if(t.protocol!=="https:"&&t.protocol!=="http:")throw De("only HTTP and HTTPS requests are allowed",tHe,t)}function yde(t,e,r,o){let n;if(typeof t!="string"||!(n=SGe(t)))throw De(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${e}"`:`"as.${e}"`}`,t===void 0?rHe:nHe,{attribute:r?`mtls_endpoint_aliases.${e}`:e});return xGe(n,o),n}function Ade(t,e,r,o){return r&&t.mtls_endpoint_aliases&&e in t.mtls_endpoint_aliases?yde(t.mtls_endpoint_aliases[e],e,r,o):yde(t[e],e,r,o)}var KV=class extends Error{cause;code;error;status;error_description;response;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=WGe,this.cause=r.cause,this.error=r.cause.error,this.status=r.response.status,this.error_description=r.cause.error_description,Object.defineProperty(this,"response",{enumerable:!1,value:r.response}),Error.captureStackTrace?.(this,this.constructor)}},u_=class extends Error{cause;code;error;error_description;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=XGe,this.cause=r.cause,this.error=r.cause.get("error"),this.error_description=r.cause.get("error_description")??void 0,Error.captureStackTrace?.(this,this.constructor)}},BV=class extends Error{cause;code;response;status;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=ZGe,this.cause=r.cause,this.status=r.response.status,this.response=r.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},vk="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",EGe="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",$Ge='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',RGe="("+vk+")\\s*=\\s*"+$Ge,IGe="("+vk+")\\s*=\\s*("+vk+")",AGe=new RegExp("^[,\\s]*("+vk+")"),PGe=new RegExp("^[,\\s]*"+RGe+"[,\\s]*(.*)"),kGe=new RegExp("^[,\\s]*"+IGe+"[,\\s]*(.*)"),TGe=new RegExp("^("+EGe+")(?:$|[,\\s])(.*)");function CGe(t){if(!bk(t,Response))throw Or('"response" must be an instance of Response',xc);let e=t.headers.get("www-authenticate");if(e===null)return;let r=[],o=e;for(;o;){let n=o.match(AGe),i=n?.[1].toLowerCase();if(!i)return;let s=o.substring(n[0].length);if(s&&!s.match(/^[\s,]/))return;let a=s.match(/^\s+(.*)$/),c=!!a;o=a?a[1]:void 0;let u={},l;if(c)for(;o;){let p,f;if(n=o.match(PGe)){[,p,f,o]=n,f.includes("\\")&&(f=f.replace(/\\([\s\S])/g,"$1")),u[p.toLowerCase()]=f;continue}if(n=o.match(kGe)){[,p,f,o]=n,u[p.toLowerCase()]=f;continue}if(n=o.match(TGe)){if(Object.keys(u).length)break;[,l,o]=n;break}return}else o=s||void 0;let d={scheme:i,parameters:u};l&&(d.token68=l),r.push(d)}if(r.length)return r}async function OGe(t){if(t.status>399&&t.status<500){Hde(t),_de(t);try{let e=await t.clone().json();if(gk(e)&&typeof e.error=="string"&&e.error.length)return e}catch{}}}async function Pde(t,e,r){if(t.status!==e){MGe(t);let o;throw(o=await OGe(t))?(await t.body?.cancel(),new KV("server responded with an error in the response body",{cause:o,response:t})):De(`"response" is not a conform ${r} response (unexpected HTTP status code)`,QGe,t)}}function DGe(t){if(!YV.has(t))throw Or('"options.DPoP" is not a valid DPoPHandle',Ea)}function NGe(t){return t.headers.get("content-type")?.split(";")[0]}async function kde(t,e,r,o,n,i,s){return await r(t,e,n,i),i.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(s?.[JV]||fetch)(o.href,{body:n,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:wGe(o,s?.signal)})}async function XV(t,e,r,o,n,i){let s=Ade(t,"token_endpoint",e.use_mtls_endpoint_aliases,i?.[vde]!==!0);n.set("grant_type",o);let a=wde(i?.headers);a.set("accept","application/json"),i?.DPoP!==void 0&&(DGe(i.DPoP),await i.DPoP.addProof(s,a,"POST"));let c=await kde(t,e,r,s,n,a,i);return i?.DPoP?.cacheNonce(c,s),c}async function Tde(t,e,r,o,n){ph(t),fh(e),On(o,'"refreshToken"');let i=new URLSearchParams(n?.additionalParameters);return i.set("refresh_token",o),XV(t,e,r,"refresh_token",i,n)}var Cde=new WeakMap,zGe=new WeakMap;function Ode(t){if(!t.id_token)return;let e=Cde.get(t);if(!e)throw Or('"ref" was already garbage collected or did not resolve from the proper sources',Ea);return e}async function Sk(t,e,r,o,n,i){if(ph(t),fh(e),!bk(r,Response))throw Or('"response" must be an instance of Response',xc);await Pde(r,200,"Token Endpoint"),Hde(r);let s=await cHe(r);if(On(s.access_token,'"response" body "access_token" property',Mt,{body:s}),On(s.token_type,'"response" body "token_type" property',Mt,{body:s}),s.token_type=s.token_type.toLowerCase(),s.expires_in!==void 0){let a=typeof s.expires_in!="number"?parseFloat(s.expires_in):s.expires_in;yk(a,!0,'"response" body "expires_in" property',Mt,{body:s}),s.expires_in=a}if(s.refresh_token!==void 0&&On(s.refresh_token,'"response" body "refresh_token" property',Mt,{body:s}),s.scope!==void 0&&typeof s.scope!="string")throw De('"response" body "scope" property must be a string',Mt,{body:s});if(s.id_token!==void 0){On(s.id_token,'"response" body "id_token" property',Mt,{body:s});let a=[];e.require_auth_time===!0&&a.push("auth_time"),e.default_max_age!==void 0&&(yk(e.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),o?.length&&a.push(...o);let{claims:c,jwt:u}=await VGe(t,e,s.id_token,a,n);HGe(e,c),GGe(c),zGe.set(r,u),Cde.set(s,c)}if(i?.[s.token_type]!==void 0)i[s.token_type](r,s);else if(s.token_type!=="dpop"&&s.token_type!=="bearer")throw new lh("unsupported `token_type` value",{cause:{body:s}});return s}function MGe(t){let e;if(e=CGe(t))throw new BV("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:e,response:t})}async function Dde(t,e,r,o){return Sk(t,e,r,void 0,o?.[hk],o?.recognizedTokenTypes)}function UGe(t,e){if(Array.isArray(e.claims.aud)){if(!e.claims.aud.includes(t))throw De('unexpected JWT "aud" (audience) claim value',dh,{expected:t,claims:e.claims,claim:"aud"})}else if(e.claims.aud!==t)throw De('unexpected JWT "aud" (audience) claim value',dh,{expected:t,claims:e.claims,claim:"aud"});return e}function LGe(t,e){let r=t[uHe]?.(e)??t.issuer;if(e.claims.iss!==r)throw De('unexpected JWT "iss" (issuer) claim value',dh,{expected:r,claims:e.claims,claim:"iss"});return e}var YV=new WeakSet;function jGe(t){return YV.add(t),t}var QV=Symbol();async function Nde(t,e,r,o,n,i,s){if(ph(t),fh(e),!YV.has(o))throw Or('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',Ea);On(n,'"redirectUri"');let a=Wd(o,"code");if(!a)throw De('no authorization code in "callbackParameters"',Mt);let c=new URLSearchParams(s?.additionalParameters);return c.set("redirect_uri",n),c.set("code",a),i!==QV&&(On(i,'"codeVerifier"'),c.set("code_verifier",i)),XV(t,e,r,"authorization_code",c,s)}var zde={aud:"audience",c_hash:"code hash",client_id:"client id",exp:"expiration time",iat:"issued at",iss:"issuer",jti:"jwt id",nonce:"nonce",s_hash:"state hash",sub:"subject",ath:"access token hash",htm:"http method",htu:"http uri",cnf:"confirmation",auth_time:"authentication time"};function FGe(t,e){for(let r of t)if(e.claims[r]===void 0)throw De(`JWT "${r}" (${zde[r]}) claim missing`,Mt,{claims:e.claims});return e}function qGe(t,e){if(typeof e.claims[t]!="string")throw De(`unexpected JWT "${t}" (${zde[t]}) claim type`,Mt,{claims:e.claims});return e}function VGe(t,e,r,o,n){return oHe(r,iHe.bind(void 0,e.id_token_signed_response_alg,t.id_token_signing_alg_values_supported,"RS256"),Sde(e),xde(e),n).then(FGe.bind(void 0,["aud","exp","iat","iss","sub",...o])).then(LGe.bind(void 0,t)).then(UGe.bind(void 0,e.client_id)).then(qGe.bind(void 0,"sub"))}function Mde(t,e){if(e===_k)return e;let r=e===void 0;return r&&(e=t.default_max_age),e===void 0?_k:(yk(e,!0,r?'"client.default_max_age"':'"maxAge" argument'),e)}function GGe(t){t.auth_time!==void 0&&yk(t.auth_time,!0,'ID Token "auth_time" (authentication time)',Mt,{claims:t})}function Ude(t,e,r){if(r===_k)return;let o=Ede()+Sde(t),n=xde(t);if(e.auth_time+r<o-n)throw De("too much time has elapsed since the last End-User authentication",WV,{claims:e,now:o,tolerance:n,claim:"auth_time"})}function Lde(t,e){let r=e===wk?void 0:e;if(t.nonce!==r)throw De('unexpected ID Token "nonce" claim value',dh,{expected:r,claims:t,claim:"nonce"})}function HGe(t,e){if(Array.isArray(e.aud)&&e.aud.length!==1){if(e.azp===void 0)throw De('ID Token "aud" (audience) claim includes additional untrusted audiences',dh,{claims:e,claim:"aud"});if(e.azp!==t.client_id)throw De('unexpected ID Token "azp" (authorized party) claim value',dh,{expected:t.client_id,claims:e,claim:"azp"})}}var wk=Symbol(),_k=Symbol();async function jde(t,e,r,o){return typeof o?.expectedNonce=="string"||typeof o?.maxAge=="number"||o?.requireIdToken?KGe(t,e,r,o.expectedNonce,o.maxAge,o[hk],o.recognizedTokenTypes):BGe(t,e,r,o?.maxAge,o?.[hk],o?.recognizedTokenTypes)}async function KGe(t,e,r,o,n,i,s){let a=[];switch(o){case void 0:o=wk;break;case wk:break;default:On(o,'"expectedNonce" argument'),a.push("nonce")}n=Mde(e,n),n!==_k&&a.push("auth_time");let c=await Sk(t,e,r,a,i,s);On(c.id_token,'"response" body "id_token" property',Mt,{body:c});let u=Ode(c);return Ude(e,u,n),Lde(u,o),c}async function BGe(t,e,r,o,n,i){let s=await Sk(t,e,r,void 0,n,i),a=Ode(s);return a&&(Ude(e,a,Mde(e,o)),Lde(a,wk)),s}var ZGe="OAUTH_WWW_AUTHENTICATE_CHALLENGE",WGe="OAUTH_RESPONSE_BODY_ERROR",JGe="OAUTH_UNSUPPORTED_OPERATION",XGe="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var ZV="OAUTH_PARSE_ERROR",Mt="OAUTH_INVALID_RESPONSE";var YGe="OAUTH_RESPONSE_IS_NOT_JSON",QGe="OAUTH_RESPONSE_IS_NOT_CONFORM",eHe="OAUTH_HTTP_REQUEST_FORBIDDEN",tHe="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",WV="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",dh="OAUTH_JWT_CLAIM_COMPARISON_FAILED";var rHe="OAUTH_MISSING_SERVER_METADATA",nHe="OAUTH_INVALID_SERVER_METADATA";async function Fde(t,e,r,o,n){return ph(t),fh(e),XV(t,e,r,"client_credentials",new URLSearchParams(o),n)}async function qde(t,e,r,o){return Sk(t,e,r,void 0,o?.[hk],o?.recognizedTokenTypes)}async function Vde(t,e,r,o,n){ph(t),fh(e),On(o,'"token"');let i=Ade(t,"revocation_endpoint",e.use_mtls_endpoint_aliases,n?.[vde]!==!0),s=new URLSearchParams(n?.additionalParameters);s.set("token",o);let a=wde(n?.headers);return a.delete("accept"),kde(t,e,r,i,s,a,n)}async function Gde(t){if(!bk(t,Response))throw Or('"response" must be an instance of Response',xc);await Pde(t,200,"Revocation Endpoint")}function Hde(t){if(t.bodyUsed)throw Or('"response" body has been used already',Ea)}async function oHe(t,e,r,o,n){let{0:i,1:s,length:a}=t.split(".");if(a===5)if(n!==void 0)t=await n(t),{0:i,1:s,length:a}=t.split(".");else throw new lh("JWE decryption is not configured",{cause:t});if(a!==3)throw De("Invalid JWT",Mt,t);let c;try{c=JSON.parse(qV(HV(i)))}catch(d){throw De("failed to parse JWT Header body as base64url encoded JSON",ZV,d)}if(!gk(c))throw De("JWT Header must be a top level object",Mt,t);if(e(c),c.crit!==void 0)throw new lh('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(qV(HV(s)))}catch(d){throw De("failed to parse JWT Payload body as base64url encoded JSON",ZV,d)}if(!gk(u))throw De("JWT Payload must be a top level object",Mt,t);let l=Ede()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw De('unexpected JWT "exp" (expiration time) claim type',Mt,{claims:u});if(u.exp<=l-o)throw De('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',WV,{claims:u,now:l,tolerance:o,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw De('unexpected JWT "iat" (issued at) claim type',Mt,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw De('unexpected JWT "iss" (issuer) claim type',Mt,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw De('unexpected JWT "nbf" (not before) claim type',Mt,{claims:u});if(u.nbf>l+o)throw De('unexpected JWT "nbf" (not before) claim value',WV,{claims:u,now:l,tolerance:o,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw De('unexpected JWT "aud" (audience) claim type',Mt,{claims:u});return{header:c,claims:u,jwt:t}}function iHe(t,e,r,o){if(t!==void 0){if(typeof t=="string"?o.alg!==t:!t.includes(o.alg))throw De('unexpected JWT "alg" header parameter',Mt,{header:o,expected:t,reason:"client configuration"});return}if(Array.isArray(e)){if(!e.includes(o.alg))throw De('unexpected JWT "alg" header parameter',Mt,{header:o,expected:e,reason:"authorization server metadata"});return}if(r!==void 0){if(typeof r=="string"?o.alg!==r:typeof r=="function"?!r(o.alg):!r.includes(o.alg))throw De('unexpected JWT "alg" header parameter',Mt,{header:o,expected:r,reason:"default value"});return}throw De('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:t,issuer:e,fallback:r})}function Wd(t,e){let{0:r,length:o}=t.getAll(e);if(o>1)throw De(`"${e}" parameter must be provided only once`,Mt);return r}var sHe=Symbol(),aHe=Symbol();function Kde(t,e,r,o){if(ph(t),fh(e),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw Or('"parameters" must be an instance of URLSearchParams, or URL',xc);if(Wd(r,"response"))throw De('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',Mt,{parameters:r});let n=Wd(r,"iss"),i=Wd(r,"state");if(!n&&t.authorization_response_iss_parameter_supported)throw De('response parameter "iss" (issuer) missing',Mt,{parameters:r});if(n&&n!==t.issuer)throw De('unexpected "iss" (issuer) response parameter value',Mt,{expected:t.issuer,parameters:r});switch(o){case void 0:case aHe:if(i!==void 0)throw De('unexpected "state" response parameter encountered',Mt,{expected:void 0,parameters:r});break;case sHe:break;default:if(On(o,'"expectedState" argument'),i!==o)throw De(i===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',Mt,{expected:o,parameters:r})}if(Wd(r,"error"))throw new u_("authorization response from the server is an error",{cause:r});let a=Wd(r,"id_token"),c=Wd(r,"token");if(a!==void 0||c!==void 0)throw new lh("implicit and hybrid flows are not supported");return jGe(new URLSearchParams(r))}async function cHe(t,e=_de){let r;try{r=await t.json()}catch(o){throw e(t),De('failed to parse "response" body as JSON',ZV,o)}if(!gk(r))throw De('"response" body must be a top level object',Mt,{body:r});return r}var uHe=Symbol();function l_(t){if(t==="")return[];if(!t.startsWith("/")||/~(?![01])/u.test(t))throw new Error("Invalid JSON pointer.");let e=t.slice(1).split("/").map(r=>r.replaceAll("~1","/").replaceAll("~0","~"));if(e.some(r=>["__proto__","prototype","constructor"].includes(r)))throw new Error("Invalid JSON pointer.");return e}function xi(t,e){for(let r of l_(e)){if(t===null||typeof t!="object"||!Object.hasOwn(t,r))return;t=t[r]}return t}function e3(t,e,r){let o=l_(e),n=o.pop();if(n===void 0)throw new Error("Choose a property within the object.");for(let i of o){if(t===null||typeof t!="object"||!Object.hasOwn(t,i))throw new Error("JSON pointer target does not exist.");t=t[i]}if(t===null||typeof t!="object")throw new Error("JSON pointer target does not exist.");if(Array.isArray(t)&&(!/^(0|[1-9][0-9]*)$/.test(n)||Number(n)>=t.length))throw new Error("Invalid array index.");t[n]=r}function cl(t){if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);throw new Error("The selected value is not text.")}function xk(t,e){return typeof e=="string"?cl(xi(t,e)):e.map(r=>typeof r=="string"?r:cl(xi(t,r.pointer))).join("")}function mh(t,e){let r=new Set;for(let o of e)o&&(r.add(o),r.add(encodeURIComponent(o)),r.add(JSON.stringify(o).slice(1,-1)));for(let o of[...r].sort((n,i)=>i.length-n.length))t=t.split(o).join("[redacted]");return t}var hh=Vt(Zde(),1);var dHe=hh.default.IPv6.parseCIDR("2000::/3"),pHe=new Set(["unicast","amt","as112","as112v6","orchid2","droneRemoteIdProtocolEntityTags"]);function Rk(t){if(!hh.default.isValid(t)||t.includes("%"))return!1;let e=hh.default.parse(t);return pHe.has(e.range())&&(!(e instanceof hh.default.IPv6)||e.match(dHe))}function Go(t,e){let r;try{r=new URL(t)}catch{q(400,"invalid_url","Enter an absolute HTTPS URL.")}(r.protocol!=="https:"||r.username||r.password||r.hash||r.port&&r.port!=="443"||r.origin===e)&&q(400,"invalid_url","Choose a public HTTPS destination.");let o=r.hostname.replace(/^\[|\]$/g,"");return(o==="localhost"||o.endsWith(".localhost")||o.endsWith(".local")||hh.default.isValid(o)&&!Rk(o))&&q(400,"private_destination","Choose a public HTTPS destination."),r}function ys(t){let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t.body))}catch{q(502,"invalid_response","The service returned an invalid response.")}return(!e||typeof e!="object"||Array.isArray(e))&&q(502,"invalid_response","The service returned an invalid response."),e}var $k=class{constructor(e){this.origin=e}origin;async send(e){let r=Go(e.url,this.origin),o=e.maxBytes??1048576;e.body&&(typeof e.body=="string"?new TextEncoder().encode(e.body).length:e.body.length)>o&&q(413,"body_limit","The request body is too large.");let n;try{n=await fetch(r,{method:e.method??"GET",headers:e.headers,body:typeof e.body=="string"?e.body:e.body?new Uint8Array(e.body):void 0,credentials:"omit",redirect:"error",referrerPolicy:"no-referrer",signal:AbortSignal.any([AbortSignal.timeout(2e4),...e.signal?[e.signal]:[]])})}catch{e.signal?.aborted&&q(409,"cancelled","The operation was cancelled."),q(409,"browser_exchange_unavailable","Restart authorization using the CLI on this device.")}let i=n.body?.getReader(),s=[],a=0;if(i)try{for(;;){let l=await i.read();if(l.done)break;a+=l.value.length,a>o&&q(413,"body_limit","The response body is too large."),s.push(l.value)}}finally{await i.cancel()}let c=new Uint8Array(a),u=0;for(let l of s)c.set(l,u),u+=l.length;return{status:n.status,headers:Object.fromEntries(n.headers),body:c}}};function t3(t,e){return btoa(Array.from(new TextEncoder().encode(t+":"+e),r=>String.fromCharCode(r)).join(""))}var Wde=Object.assign(Object.create(null),{dpop:()=>q(502,"invalid_response","The service returned an unsupported token.")}),fHe={redirectUri:t=>t.fields.ruName,recognizedTokenTypes:Object.assign(Object.create(null),Wde,{"user access token":()=>{}})},mHe={authorize(t,e){delete t.response_type,delete t.client_id,delete t.redirect_uri,t.callback_url=e,t.key_label="Foundation"},async exchange({spec:t,transport:e,url:r,authorization:o,verifier:n}){let i=o.parameters;return(i.getAll("state").length!==1||i.get("state")!==o.state||i.getAll("code").length!==1||!i.get("code"))&&q(400,"invalid_state","Start the connection again."),e.send({url:r(),method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({...t.tokenParams,code:i.get("code"),code_verifier:n,code_challenge_method:"S256"})})},accessTokenField:"key"},hHe={revokeRequest({app:t,url:e,current:r}){return{url:e,method:"DELETE",headers:{authorization:"Basic "+t3(t.clientId,t.clientSecret??""),"content-type":"application/json"},body:JSON.stringify({access_token:r.accessToken})}}},gHe={tokenParameters(t){let e=t.get("redirect_uri");e!==null&&(t.set("redirect_url",e),t.delete("redirect_uri"))}};function $a(t,e){let r=e?new URL(e):void 0;return{recognizedTokenTypes:Wde,...r?.hostname.endsWith(".myshopify.com")&&r.pathname==="/admin/oauth/access_token"?{normalizeToken(o){o.token_type===void 0&&(o.token_type="bearer")},...t.grantType==="client_credentials"?{clientCredentialsParameters(){return{...t.tokenParams}}}:{}}:{},...r?.hostname==="api.notion.com"&&r.pathname==="/v1/oauth/token"?{normalizeToken(o){o.refresh_token===null&&delete o.refresh_token}}:{},...t.adapter==="ebay"?fHe:t.adapter==="openrouter"?mHe:t.adapter==="vultr"?gHe:{},...t.revoke?.style==="github"?hHe:{}}}function Ec(t,e){try{return Go(new j$(t).expand(e)).href}catch{q(400,"invalid_service_url","Check the service URL and its required fields.")}}var Jde=(t,e=" ")=>typeof t=="string"?[...new Set(t.split(e).filter(Boolean))].sort():[],Ik=t=>{let e=typeof t=="number"||typeof t=="string"?Number(t):NaN;return(!Number.isSafeInteger(e)||e<=0||e>315576e3)&&q(502,"invalid_response","The service returned an invalid expiry."),e};var Jd=class{constructor(e){this.transport=e}transport;appValues(e,r){try{return{...Us(e.fields,r.fields,e.defaults),clientId:r.clientId}}catch(o){throw o instanceof ac&&q(400,o.code,o.message),o}}async authorize(e,r,o,n,i,s){(e.grantType==="client_credentials"||!e.authorizeUrl)&&q(400,"wrong_grant","This connection exchanges application credentials directly.");let a=new URL(Ec(e.authorizeUrl,this.appValues(e,r))),c={...e.authorizeParams,response_type:"code",client_id:r.clientId,redirect_uri:$a(e).redirectUri?.(r,i)??i,state:o};s.length&&(c.scope=s.join(e.scopes.separator)),e.pkce&&(c.code_challenge=await bde(n),c.code_challenge_method="S256"),$a(e).authorize?.(c,i);for(let[u,l]of Object.entries(c))a.searchParams.set(u,l);return a.href}configuration(e,r){let o={issuer:e.issuer??new URL(Ec(e.grantType==="client_credentials"?e.tokenUrl:e.authorizeUrl,this.appValues(e,r))).origin,token_endpoint:Ec(e.tokenUrl,this.appValues(e,r))};return e.issuer&&Go(e.issuer),{server:o,client:{client_id:r.clientId}}}authentication(e,r){return r==="none"?Ide():(e.clientSecret||q(409,"app_required","Add a client secret to this OAuth application."),r==="basic"?Rde(e.clientSecret):$de(e.clientSecret))}options(e){let r=e?.tokenFormat??"form";return{[JV]:async(o,{body:n,headers:i,method:s,signal:a})=>{let c=new URLSearchParams(n);e&&$a(e).tokenParameters?.(c);let u=await this.transport.send({url:o,method:s,headers:r==="json"?{...i,"content-type":"application/json"}:i,body:r==="json"?JSON.stringify(Object.fromEntries(c)):c.toString(),signal:a});return new Response([204,205,304].includes(u.status)?null:new Uint8Array(u.body),{status:u.status,headers:u.headers})}}}async json(e){return ys({status:e.status,headers:{},body:new Uint8Array(await e.arrayBuffer())})}checkResponse(e,r,o,n=!1){return(r>=400||o.error||e.okPointer&&xi(o,e.okPointer)!==!0)&&(n&&(o.error==="invalid_grant"||o.error==="invalid_token")&&q(409,"reconnect_required","Reconnect this service to renew access."),r===429&&q(503,"service_rate_limit","The service is busy. Try again later."),q(502,"authorization_failed","The service did not authorize this connection.")),o}async tokenResponse(e,r,o,n=!1){o.status===429&&q(503,"service_rate_limit","The service is busy. Try again later.");let i=this.checkResponse(e,o.status,await this.json(o),n),{server:s,client:a}=this.configuration(e,r),c=new URL(s.token_endpoint),u={...i};delete u.id_token,$a(e,c.href).normalizeToken?.(u),u.expires_in!==void 0&&(u.expires_in=Ik(u.expires_in));try{let d=await(n?Dde:e.grantType==="client_credentials"?qde:jde)(s,a,Response.json(u,{status:o.status}),{recognizedTokenTypes:$a(e,c.href).recognizedTokenTypes});return{...i,...d}}catch(l){if(l instanceof dt)throw l;q(502,"invalid_response","The service did not return a valid access token.")}}token(e,r,o,n,i=!1){let s=r[$a(e).accessTokenField??"access_token"];(typeof s!="string"||!s||s.length>16384||/[\s\u0000-\u001f]/.test(s))&&q(502,"invalid_response","The service did not return a valid access token.");let a=r.expires_in===void 0?null:Date.now()+Ik(r.expires_in)*1e3,c=r.refresh_token??n?.refreshToken;c!==void 0&&(typeof c!="string"||!c||c.length>16384)&&q(502,"invalid_response","The service returned an invalid refresh token.");let u={...n?.extra};for(let d of e.keep)typeof r[d]=="string"&&(u[d]=r[d]);let l={accessToken:s,...c?{refreshToken:String(c)}:{},expiresAt:a,scopes:r.scope!==void 0?Jde(r.scope,e.scopes.separator):i?n?.scopes??o:o,scopesStatus:r.scope!==void 0?"reported":i?n?.scopesStatus??"unknown":o.length?"requested":"unknown",account:n?.account??"",accountName:n?.accountName??"",accountVerified:n?.accountVerified??!1,extra:u,facts:{}};return r.refresh_token_expires_in!==void 0&&(l.refreshExpiresAt=Date.now()+Ik(r.refresh_token_expires_in)*1e3),n?.refreshExpiresAt&&c===n.refreshToken&&(l.refreshExpiresAt=Math.min(l.refreshExpiresAt??1/0,n.refreshExpiresAt)),l}async exchange(e,r,o,n,i,s,a,c){e.grantType==="client_credentials"&&q(400,"wrong_grant","This connection exchanges application credentials directly.");let u,l=$a(e);if(l.exchange){let p=await l.exchange({spec:e,app:r,transport:this.transport,url:()=>Ec(e.tokenUrl,this.appValues(e,r)),authorization:o,verifier:n});u=this.checkResponse(e,p.status,ys(p))}else{let{server:p,client:f}=this.configuration(e,r),h;try{let y=Kde(p,f,o.parameters,o.state);h=await Nde(p,f,this.authentication(r,e.clientAuth),y,l.redirectUri?.(r,i)??i,e.pkce?n:QV,{...this.options(e),additionalParameters:e.tokenParams})}catch(y){throw(y instanceof c_||y instanceof u_)&&q(400,"invalid_state","Start the connection again."),y}u=await this.tokenResponse(e,r,h)}let d=this.token(e,u,s,a);return await c?.(d,u),d}async clientCredentials(e,r,o,n,i){e.grantType!=="client_credentials"&&q(400,"wrong_grant","Choose a client credentials connection method.");let{server:s,client:a}=this.configuration(e,r),c=$a(e,s.token_endpoint),u={...e.tokenParams,...o.length?{scope:o.join(e.scopes.separator)}:{}},l=await Fde(s,a,this.authentication(r,e.clientAuth),c.clientCredentialsParameters?.(u)??u,this.options(e)),d=await this.tokenResponse(e,r,l),p={...this.token(e,d,o,n,!!n),requestedScopes:o};return await i?.(p,d),p}async refresh(e,r,o,n){let i=o;if(o.expiresAt!==null&&o.expiresAt<Date.now()+6e4){if(e.grantType==="client_credentials")return o.requestedScopes||q(409,"reconnect_required","Reconnect this service to select its renewal scopes."),this.clientCredentials(e,r,o.requestedScopes,o,n);(!o.refreshToken||o.refreshExpiresAt&&o.refreshExpiresAt<=Date.now())&&q(409,"reconnect_required","Reconnect this service to renew access.");let{server:s,client:a}=this.configuration(e,r),c=await Tde(s,a,this.authentication(r,e.clientAuth),o.refreshToken,{...this.options(e),additionalParameters:e.tokenParams}),u=await this.tokenResponse(e,r,c,!0);i=this.token(e,u,o.scopes,o,!0),await n?.(i,u)}return i}async revoke(e,r,o){e.revoke||q(409,"manual_revoke","Remove access in the service settings, then remove this connection.");let n=Ec(e.revoke.url,{...this.appValues(e,r),accessToken:o.accessToken,refreshToken:o.refreshToken??""});if(e.revoke.style==="rfc7009"){let{server:c,client:u}=this.configuration(e,r),l=e.revoke.auth==="none"&&e.clientAuth!=="none"?()=>{}:this.authentication(r,e.revoke.auth??e.clientAuth),d=await Vde({...c,revocation_endpoint:n},u,l,o.refreshToken??o.accessToken,this.options());try{await Gde(d)}catch{q(502,"revoke_failed","Access could not be removed at the service. Try again.")}return}let i={},s=e.revoke.auth??e.clientAuth;e.revoke.style==="bearer"?i.authorization="Bearer "+o.accessToken:s==="basic"&&(i.authorization="Basic "+t3(r.clientId,r.clientSecret??"")),(await this.transport.send($a(e).revokeRequest?.({spec:e,app:r,transport:this.transport,url:n,current:o})??{url:n,method:e.revoke.style==="bearer"?"POST":"DELETE",headers:i})).status>=300&&q(502,"revoke_failed","Access could not be removed at the service. Try again.")}outputs(e,r,o){let n={...this.appValues(e,r),...o.extra,...o,expiresAt:o.expiresAt===null?"":String(o.expiresAt)};return Object.fromEntries(Object.entries(e.outputs).map(([i,s])=>[i,cl(xi(n,s))]))}};function r3(t){if(t.method.kind!=="oauth")throw new Error("Use an OAuth connection provider.");return t.method.config}function n3(t){return t||q(409,"app_required","Choose an OAuth application."),t}function yHe(t){return{token:mj.parse(t.token),response:Lt.parse(t.response)}}var Ak=class{constructor(e){this.transport=e}transport;facts=WL;oauth(e){return new Jd({send:r=>this.transport.send({...r,...e?{signal:AbortSignal.any([e,...r.signal?[r.signal]:[]])}:{}})})}needsRenewal(e){return!e.oauth||e.oauth.expiresAt!==null&&e.oauth.expiresAt<Date.now()+6e4}async renew(e){let r=e.material,o=r3(r),n=n3(e.app),i=("requestedScopes"in r?r.requestedScopes:void 0)??r.oauth?.requestedScopes,s=(c,u)=>e.receive({token:c,response:u}),a=o.grantType==="client_credentials"?await this.oauth(e.signal).clientCredentials(o,n,i??Vi(o.scopes),r.oauth,s):await this.oauth(e.signal).refresh(o,n,r.oauth,s);return $n.parse({...e.material,oauth:a})}async recover(e,r,o){let i=yHe(o).token;return $n.parse({...e,oauth:i})}async outputs(e,r){return this.oauth().outputs(r3(e),n3(r),e.oauth)}async revoke(e,r,o){e.oauth&&await this.oauth(o).revoke(r3(e),n3(r),e.oauth)}};function vHe(t){if(t.method.kind!=="token"&&t.method.kind!=="approval")throw new Error("Use an input credential provider.");return t.method.config}var d_=class{facts=zf;needsRenewal(){return!1}async outputs(e){let r=vHe(e),o=Us(r.fields,e.fields,"constants"in r?r.constants??{}:{});return Object.fromEntries(Object.entries(r.outputs).map(([n,i])=>[n,xk(o,i)]))}};function Pk(t){if(t.method.kind!=="ovh")throw new Error("Use an OVH connection provider.");return t.method.config}var kk=class{facts=JL;values(e,r){let o=Pk(e),n=o.authorization==="consumer_key";n&&(!r?.clientId||!r.clientSecret)&&q(409,"app_required","Choose an OVHcloud API application with its key and secret.");let i=n?r.fields:e.fields;return Us(o.fields,i)}credentials(e,r){if(Pk(e).authorization==="consumer_key")return{applicationKey:r.clientId,applicationSecret:r.clientSecret,consumerKey:e.fields.consumerKey};let o=this.values(e,r);return{applicationKey:o.applicationKey,applicationSecret:o.applicationSecret,consumerKey:o.consumerKey}}needsRenewal(){return!1}async outputs(e,r){if(e.method.kind!=="ovh")throw new Error("Use OVH connection material.");let o="ovh"in e?e.ovh:void 0;o&&o.expiresAt!==null&&o.expiresAt<=Date.now()&&q(409,"reconnect_required","Reconnect OVHcloud with a current API key.");let n=Pk(e).authorization==="consumer_key"?{...this.values(e,r),...this.credentials(e,r)}:this.values(e,r);return Object.fromEntries(Object.entries(Pk(e).outputs).map(([i,s])=>[i,cl(xi(n,s))]))}};import{readFile as wHe}from"node:fs/promises";var _He=m.object({accessToken:m.string().min(1).max(16384).regex(/^\S+$/),expiresAt:m.number().int().positive()}).strict();async function bHe(t,e){if(t==="oidc"){let n=process.env.VULTR_OIDC_TOKEN_FILE,i=n?await wHe(n,"utf8"):process.env.VULTR_OIDC_TOKEN;return(!i||i.length>16384)&&q(409,"authentication_required","Provide the current OIDC token to this executor."),i.trim()}let r=await fetch("http://169.254.169.254/v1/identity/token",{redirect:"error",credentials:"omit",signal:AbortSignal.any([e,AbortSignal.timeout(3e3)])});r.ok||q(409,"authentication_required","Use a Vultr instance with an IAM role trust.");let o=(await r.text()).trim();return(!o||o.length>16384)&&q(502,"invalid_response","The instance did not return a valid identity token."),o}function Xde(t){if(t.method.kind!=="token"||t.method.config.resolver!=="vultr-role")throw new Error("Use a Vultr IAM role connection.");return t.method.config}var Tk=class{constructor(e,r=bHe){this.transport=e;this.identityToken=r}transport;identityToken;facts=zf;sessions=new Map;pending=new Map;needsRenewal(){return!1}async obtain(e,r){let o=Us(Xde(e).fields,e.fields),n=o.authentication;["api_key","oidc","instance"].includes(n)||q(400,"invalid_field","Choose a Vultr authentication source.");let i=n==="api_key"?o.token:o.credential||await this.identityToken(n,r);(!i||i.length>16384||/\s/.test(i))&&q(409,"authentication_required","Provide current credentials for the selected authentication source.");let s=Number(o.duration);(!Number.isSafeInteger(s)||s<=0||s>315576e3)&&q(400,"invalid_field","Enter a valid session duration in seconds.");let a=await this.transport.send({url:"https://api.vultr.com/v2/assumed-roles/assume",method:"POST",headers:{"content-type":"application/json",authorization:"Bearer "+i},signal:r,body:JSON.stringify({role_id:o.roleId,session_name:o.sessionName,duration:s,auth_method:n==="instance"?"jwt":n,...n==="api_key"?{user_id:o.userId}:{},...n==="oidc"?{oidc_issuer_id:o.issuerId}:{}})});a.status>=400&&q(409,"role_denied","Check the role trust, permissions and authentication source in Vultr.");let c=ys(a);(c.role_id!==void 0&&c.role_id!==o.roleId||n==="api_key"&&c.user_id!==void 0&&c.user_id!==o.userId)&&q(409,"role_changed","Reconnect to approve the returned role and authentication source.");let u=_He.parse({accessToken:c.session_token,expiresAt:typeof c.expires_at=="string"?Date.parse(c.expires_at):NaN});return u.expiresAt<=Date.now()&&q(502,"invalid_response","Vultr returned an expired role session."),u}async outputs(e,r,o){let n=Xde(e);o.throwIfAborted();let i=await Q(e),s=this.sessions.get(i);if(!s||s.expiresAt<Date.now()+6e4){let a=this.pending.get(i);a||(a=this.obtain(e,o),this.pending.set(i,a));try{s=await a,this.sessions.set(i,s)}finally{this.pending.get(i)===a&&this.pending.delete(i)}}return Object.fromEntries(Object.entries(n.outputs).map(([a,c])=>[a,xk(s,c)]))}};function Yde(t,e){let r={oauth:new Ak(t),token:new d_,aws:new mk(e),approval:new d_,ovh:new kk},o=new Tk(t);return n=>n.kind==="token"&&n.config.resolver==="vultr-role"?o:r[n.kind]}function Ra(t){return new TextDecoder("utf-8",{fatal:!0}).decode(t)}async function Ck(t,e){let r={},o={},n=[],i=new Set;for(let s of t){if(i.has(s.name)||!G5(s.name))throw new Error("Use distinct, unreserved environment variable names.");i.add(s.name);let a=await e(s.source);if(s.format==="json"&&(a=tt(cl(xi(JSON.parse(Ra(a)),s.pointer??"")))),s.format==="file")o[s.name]=Buffer.from(a).toString("base64");else{let c=Ra(a);if(c.includes("\0"))throw new Error("Use a file to pass binary content.");r[s.name]=c}n.push(Buffer.from(a).toString("utf8"),Buffer.from(a).toString("base64"),Buffer.from(a).toString("base64url"))}return{environment:r,files:o,sensitive:n}}var gh=class{constructor(e,r,o,n,i,s=new fk){this.binding=e;this.keys=r;this.broker=o;this.journal=n;this.providers=Yde(i,s)}binding;keys;broker;journal;active=new Set;providers;provider(e){return this.providers(e)}metadata(e){return Ff(e,this.provider(e.method).facts(e))}source(e,r,o){let n=o.find(i=>i.policy.id===e&&i.policy.contentType===r);return n||q(409,"input_required","Include the connection and its application in this execution."),n}async material(e,r,o){let n=$n.safeParse(JSON.parse(Ra(await au(e,r,this.keys,{destination:o}))));n.success||q(409,"reconnect_required","Reconnect this service with the current connection format.");let i=n.data;return(await this.metadata(i)).authorizationDigest!==e.metadata.authorizationDigest&&q(409,"connection_changed","Approve the current service account and permissions before using this connection."),i.state==="reconnect"&&r.operation!==ue.revoke&&q(409,"reconnect_required","Reconnect this service before using it."),i}async app(e,r,o,n){let i=this.source(e,he.clientCredential,n),s=Zn.parse(JSON.parse(Ra(await au(i,o,this.keys))));return s.methodId!==r&&q(400,"wrong_app","Choose an application for this connection method."),s}async connectionApp(e,r,o){if(xr(e.method).application==="none")return null;if(!lu(e.method))return"implicitApp"in e&&e.implicitApp?e.implicitApp:Zn.parse({format:1,methodId:e.methodId,generation:e.generation,clientId:"",fields:{}});let n=r.operation===ue.revoke?ue.revoke:ue.refresh,i=await this.app(e.appId,e.methodId,{...r,operation:n},o);return i.generation!==e.appGeneration&&q(409,"app_changed","Reconnect this service with the current application."),xr(e.method).requiresApp&&e.method.kind!=="aws"&&Object.entries(fo(e.method.config.fields,e.fields??{})).some(([s,a])=>i.fields[s]!==a)&&q(409,"app_changed","Reconnect this service with the current application settings."),i}async validate(e,r,o){let n=hj.parse(e);r.operation!==ue[n.action]&&q(400,"wrong_operation","Use the approved connection operation.");let i=await this.material(this.source(n.id,he.tokenSet,o),r);await this.connectionApp(i,r,o)}async execute(e,r,o,n){let i=hj.parse(e);this.active.has(i.id)&&q(409,"connection_busy","Another operation is updating this connection."),this.active.add(i.id);try{n.throwIfAborted();let s=this.source(i.id,he.tokenSet,o),a=await this.material(s,r);if(i.action==="refresh"){let u=await this.refresh(s,a,r,o,n);return{kind:"refreshed",id:s.policy.id,...await this.metadata(u)}}let c=this.provider(a.method);return c.revoke||q(409,"manual_revoke","Remove access in the service settings, then remove this connection."),await c.revoke(a,await this.connectionApp(a,r,o),n),{kind:"revoked",id:s.policy.id}}finally{this.active.delete(i.id)}}async outputs(e,r,o,n,i){let s=await this.material(e,r,i);return this.provider(s.method).renew&&await this.broker.state(e.policy.id)&&q(409,"connection_busy","Resolve the current token update before using this connection."),s=await this.refresh(e,s,r,o,n,i),this.provider(s.method).outputs(s,await this.connectionApp(s,r,o),n)}async refreshed(e,r){let o=await this.metadata(r);return o.authorizationDigest!==e.previous.metadata.authorizationDigest&&q(409,"connection_review","Review the changed service account or permissions before sharing the updated connection."),e.material=r,e.content=await l8(e.previous,tt(C(r)),this.binding,this.keys,o),e.phase="settled",await this.journal.write("refresh_"+e.operation.id,e),await this.broker.commit(e.operation.id,e.operation.fence,e.content),e.delivered=!0,await this.journal.write("refresh_"+e.operation.id,e),r}async refresh(e,r,o,n,i,s){let a=this.provider(r.method);if(!a.needsRenewal(r))return r;a.renew||q(409,"reconnect_required","Reconnect this service to renew access.");try{await ld(e,{...o,operation:ue.refresh},{destination:s})}catch{q(403,"refresh_required","Authorize this requester and executor to renew the connection for this destination.")}let c=await this.connectionApp(r,o,n),u=SHe(),l=await this.broker.prepare(u,e.policy.id,e.materialRevision),d={operation:l,previous:e,material:r,app:c,phase:"prepared",delivered:!1};await this.journal.write("refresh_"+u,d);try{i.throwIfAborted(),d.phase="dispatched",await this.journal.write("refresh_"+u,d),await this.broker.dispatch(u,l.fence),i.throwIfAborted();let p=await a.renew({material:r,app:c,signal:i,receive:async f=>{d.checkpoint=f,d.phase="received",await this.journal.write("refresh_"+u,d)}});return await this.refreshed(d,p)}catch(p){if(d.phase==="prepared"?await this.broker.abort(u,l.fence):await this.broker.uncertain(u,l.fence).catch(()=>{}),p instanceof dt&&["connection_review","reconnect_required","account_changed","authorization_failed","service_rate_limit"].includes(p.code))throw p;q(409,"connection_uncertain","Check the token update before using this connection again.")}}async reconcile(){let e=[];for(let r of await this.journal.keys("refresh_"))try{let o=await this.journal.read(r);if(o.delivered)continue;if(o.content){await this.broker.commit(o.operation.id,o.operation.fence,o.content),o.delivered=!0,await this.journal.write(r,o);continue}let n=await this.broker.state(o.operation.resource_id);if(!n||n.id!==o.operation.id||n.state==="prepared")n?.id===o.operation.id&&n.state==="prepared"&&await this.broker.abort(o.operation.id,o.operation.fence),o.delivered=!0,await this.journal.write(r,o);else if(o.checkpoint&&this.provider(o.material.method).recover){let i=await this.provider(o.material.method).recover(o.material,o.app,o.checkpoint);await this.refreshed(o,i)}else await this.broker.uncertain(o.operation.id,o.operation.fence),o.delivered=!0,await this.journal.write(r,o)}catch{e.push(r.slice(8))}return e}};import{lookup as xHe}from"node:dns/promises";import{request as EHe}from"node:https";import{brotliDecompressSync as $He,gunzipSync as RHe,inflateSync as IHe}from"node:zlib";var yh=class{constructor(e){this.origin=e}origin;async send(e){let r=Go(e.url,this.origin),o=r.hostname.replace(/^\[|\]$/g,""),n=e.maxBytes??1048576;e.body&&Buffer.byteLength(e.body)>n&&q(413,"body_limit","The request body is too large.");let i={"user-agent":"Foundation/1.0",accept:"application/json","accept-encoding":"identity"};for(let[s,a]of Object.entries(e.headers??{})){let c=s.toLowerCase();(["host","connection","content-length","transfer-encoding","upgrade","proxy-authorization","proxy-connection","accept-encoding","te","trailer"].includes(c)||!/^[!#$%&'*+.^_`|~0-9a-z-]+$/.test(c)||/[\r\n\u0000]/.test(a))&&q(400,"invalid_header","Choose a valid request header."),i[c]=a}try{let s=await xHe(o,{all:!0,verbatim:!0});(!s.length||s.some(u=>!Rk(u.address)))&&q(400,"private_destination","Choose a public HTTPS destination.");let a=s[0],c=AbortSignal.any([AbortSignal.timeout(2e4),...e.signal?[e.signal]:[]]);return await new Promise((u,l)=>{let d={method:e.method??"GET",headers:i,signal:c,agent:!1,lookup:(f,h,y)=>{h.all?y(null,[a]):y(null,a.address,a.family)}},p=EHe(r,d,f=>{let h=[],y=0;f.on("data",w=>{y+=w.length,y>n?f.destroy(new dt(413,"body_limit","The response body is too large.")):h.push(w)}),f.on("error",l),f.on("end",()=>{try{let w=Buffer.concat(h),b=f.headers["content-encoding"];if(b&&b!=="identity"){let x=b==="gzip"?RHe:b==="deflate"?IHe:b==="br"?$He:null;if(!x)throw new dt(502,"invalid_response","The service returned an unsupported response.");w=x(w,{maxOutputLength:n})}let S={};for(let[x,R]of Object.entries(f.headers))R!==void 0&&!["set-cookie","set-cookie2","content-encoding","transfer-encoding","connection"].includes(x)&&(S[x]=Array.isArray(R)?R.join(", "):R);u({status:f.statusCode??502,headers:S,body:new Uint8Array(w)})}catch(w){l(w)}})});p.on("error",l),p.end(e.body)})}catch(s){if(s instanceof dt)throw s;e.signal?.aborted&&q(409,"cancelled","The operation was cancelled."),q(502,"service_unavailable","The service could not be reached. Try again.")}}};function Dn(t){let{keys:e,binding:r,origin:o}=t.identity;if(!e||!r)throw new Error("Use a sign-in key with encryption and signing keys for this operation.");let n=o3(AHe(rc()),"custody",r.id),i=new md(o3(n,"client"),o,r,e),s=new G$(t,o,r,e,new H$(i)),a=new K$(t),c=new yh(o),u=new gh(r,e,a.connections(),new md(o3(n,"connections"),o,r,e),c);return{custody:s,journal:i,directory:n,keys:e,binding:r,broker:a,transport:c,connections:u}}async function Qde(t,e){let{custody:r,keys:o,binding:n,connections:i}=Dn(t),s=await r.sourceContents(e.map(u=>u.source.id)),a={format:2,id:crypto.randomUUID(),origin:t.identity.origin,ownerId:n.principalId,actor:n,executor:n,environmentId:n.id,environmentDigest:await Q(n),operation:ue.command,functionDigest:null,operationDigest:await Q(e),sources:await Promise.all(s.map(async u=>({id:u.policy.id,policyDigest:await Q(u.policy),materialRevision:u.materialRevision,...u.policy.contentType===he.tokenSet?{authorizationDigest:String(u.metadata.authorizationDigest)}:{}}))),resultRecipients:[n],createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+36e5).toISOString()},c=new Map;return Ck(e,async u=>{let l=s.find(p=>p.policy.id===u.id);if(l.policy.contentType===he.value)return au(l,a,o);c.has(u.id)||c.set(u.id,i.outputs(l,a,s,new AbortController().signal));let d=await c.get(u.id);if(!u.output||!Object.hasOwn(d,u.output))throw new Error("Choose an available connection output.");return tt(d[u.output])})}import{mkdir as wot}from"node:fs/promises";import{join as ib}from"node:path";import{setTimeout as _ot}from"node:timers/promises";function PHe(t,e){let r={};if(Object.keys(e).some(o=>!t.parameters.some(n=>n.name===o)))throw new Error("Use the parameters this function declares.");for(let o of t.parameters){let n=Object.hasOwn(e,o.name)?e[o.name]:o.default;if(n===void 0){if(o.required)throw new Error("Complete the required function parameters.");continue}if(o.type!=="json"&&typeof n!==o.type||o.type==="number"&&!Number.isFinite(n))throw new Error("Use the argument types this function declares.");if(o.required&&o.type==="string"&&n==="")throw new Error("Complete the required function parameters.");if(JSON.stringify(n).length>8192)throw new Error("The function argument is too long.");r[o.name]=n}return r}function Ok(t,e){let r=PHe(t,e);if(t.program.kind==="command"){let{kind:u,...l}=t.program;return{kind:u,...Wa.parse({...l,stdin:JSON.stringify(r)})}}if(t.result!=="json")throw new Error("HTTP functions return a JSON response containing status, headers, and body.");let o=t.program.request,n=u=>typeof u=="string"?u:JSON.stringify(u),i=(u,l=!1)=>{if(l&&typeof u=="string"){let d=/^\{\{([A-Za-z][A-Za-z0-9_]*)\}\}$/.exec(u)?.[1];if(d){if(!t.parameters.some(p=>p.name===d))throw new Error("Declare every function parameter.");return Object.hasOwn(r,d)?r[d]:null}}return typeof u=="string"?u.replace(/\{\{([A-Za-z][A-Za-z0-9_]*)\}\}/g,(d,p)=>{if(!t.parameters.some(f=>f.name===p))throw new Error("Declare every function parameter.");return Object.hasOwn(r,p)?n(r[p]):""}):Array.isArray(u)?u.map(d=>i(d,l)):u&&typeof u=="object"?Object.fromEntries(Object.entries(u).map(([d,p])=>[d,i(p,l)])):u},s=new j$(o.url).expand(Object.fromEntries(Object.entries(r).map(([u,l])=>[u,n(l)]))),a=Za.parse({...i(o),url:s,bindings:o.bindings,...o.json===void 0?{}:{json:i(o.json,!0)}}),c=new URL(o.url.replace(/\{[^}]+\}/g,"placeholder"));if(new URL(s).origin!==c.origin)throw new Error("The function must have a fixed destination host.");return{kind:"http",request:a,responseFormat:t.program.responseFormat}}function epe(t){return t.program.kind==="command"?t.program.inputs.map(e=>e.source):t.program.request.bindings.flatMap(e=>e.parts.filter(r=>typeof r!="string"))}var tpe=m.object({operation:ec,save:m.record(m.string(),fe)}).strict();function Dk(t){return t.kind==="http"?{kind:t.kind,request:t.request}:t}async function rpe(t,e){let r=t.operationContext;if(!r)return;if(r.invocation.name==="connection.revoke"){let n=y$.parse(r.invocation.input);if(e.kind!=="revoke"||C(e.input)!==C({action:"revoke",id:n.connectionId})||n.ownerId!==t.ownerId||n.environmentId!==t.environmentId)throw new Error("Revoke the reviewed connection on its selected executor.");return}if(r.invocation.name!=="run.execute")throw new Error("Use the reviewed operation.");let o=Fy.parse(r.invocation.input);if(o.ownerId!==t.ownerId||o.environmentId!==t.environmentId||o.operation.kind!==e.kind)throw new Error("Use the reviewed run and execution environment.");if("programDigest"in o.operation){if(await Q(Dk(e))!==o.operation.programDigest)throw new Error("Run the reviewed private program.")}else if(e.kind==="http"&&o.operation.kind==="http"){if(C(e.request)!==C(o.operation.request))throw new Error("Run the reviewed HTTP request and output destinations.")}else if(C(e)!==C(ec.parse(o.operation)))throw new Error("Run the reviewed command.");if(e.kind==="http"&&C(Object.fromEntries(Object.entries(e.save).map(([n,i])=>[n,i.name])))!==C(o.save))throw new Error("Use the reviewed output destinations.")}function kHe(t,e){return t.policy.contentType===he.value?e.output===void 0:t.policy.contentType===he.tokenSet&&e.output!==void 0}var Ia=class extends Error{constructor(){super("A completed result is waiting for delivery. Restart or leave this executor running to reconcile it.")}};function i3(t){return!(t instanceof dt)||["service_unavailable","connection_uncertain","lease_lost"].includes(t.code)}var Nk=class{constructor(e,r,o,n,i,s,a){this.environment=e;this.keys=r;this.broker=o;this.journal=n;this.transport=i;this.commands=s;this.extension=a}environment;keys;broker;journal;transport;commands;extension;get binding(){return this.environment.manifest.executor}async reconcile(){let e=[];for(let r of await this.journal.keys("run_"))try{let o=await this.journal.read(r);if(!o||o.delivered)continue;if(!o.receipt&&o.phase==="dispatched"){let n=o.operation?.kind==="connect"?await this.extension?.recover?.(o.operation.input,o.request.intent):null;o.receipt=n?await Df(o.request.intent,"succeeded",{ok:!0,result:n,error:null},this.keys):await Df(o.request.intent,"uncertain",{ok:!1,result:null,error:{code:"execution_interrupted",message:"Check the destination before starting another operation."}},this.keys),o.phase="settled",await this.journal.write(r,o)}o.receipt&&(await this.broker.finish(o.lease,o.receipt),o.delivered=!0,await this.journal.write(r,o))}catch{e.push(r.slice(4))}return e}async tick(e=new AbortController().signal){e.throwIfAborted();let r=await this.broker.claim(this.environment.manifest.id);if(!r)return!1;let{intent:o}=r.request,n="run_"+o.id,i=await Q(r.request),s=await this.journal.read(n);if(s&&s.digest!==i)throw new Error("A run ID was reused for a different signed request.");if(s?.receipt)return await this.broker.finish(r.lease,s.receipt),await this.journal.write(n,{...s,delivered:!0}),!0;if(s?.phase==="dispatched"){let p=await Df(o,"uncertain",{ok:!1,result:null,error:{code:"execution_interrupted",message:"Check the destination before starting another operation."}},this.keys);return await this.journal.write(n,{...s,lease:r.lease,phase:"settled",receipt:p,delivered:!1}),await this.broker.finish(r.lease,p),!0}s={digest:i,lease:r.lease,request:r.request,phase:"prepared",delivered:!1},await this.journal.write(n,s);let a=new AbortController,c=AbortSignal.any([e,a.signal]),u=setInterval(()=>{this.broker.renew(o.id,r.lease).then(p=>{p.active||a.abort()}).catch(()=>a.abort())},15e3);u.unref();let l=!1,d;try{let p=await p8(r.request,this.binding,this.keys);await Of(this.environment,p.intent);let f=ec.parse(p.operation);if(ue[f.kind]!==o.operation)throw new Error("Use the operation authorized by this intent.");await rpe(o,f),await this.validateOperation(f,o,r.sources),c.throwIfAborted(),s.operation=f,s.phase="dispatched",await this.journal.write(n,s),l=!0,await this.broker.dispatch(o.id,r.lease),c.throwIfAborted();let h=await this.executeOperation(f,o,r.sources,c);d=await Df(o,"succeeded",{ok:!0,result:h,error:null},this.keys)}catch(p){if(p instanceof Ia)throw p;p instanceof Tf&&(p=new dt(413,"result_too_large","The operation completed, but its result is too large to return. Check the destination before starting it again."));let f=l&&(c.aborted||i3(p));d=await Df(o,f?"uncertain":"failed",{ok:!1,result:null,error:p instanceof dt?{code:p.code,message:p.message}:{code:f?"execution_uncertain":"invalid_execution",message:f?"Check the destination before starting another operation.":"The executor could not authorize this operation."}},this.keys)}finally{clearInterval(u)}return s.phase="settled",s.receipt=d,await this.journal.write(n,s),await this.broker.finish(r.lease,d),s.delivered=!0,await this.journal.write(n,s),!0}request(e){let r=e.kind==="function"?Ok(e.definition,e.arguments):e;return r.kind==="http"?r.request:null}async validateOperation(e,r,o){if(new Set(o.map(c=>c.policy.id)).size!==o.length||o.length!==r.sources.length)throw new Error("Supply exactly the signed execution inputs.");for(let c of o){await ko(c);let u=r.sources.find(p=>p.id===c.policy.id);if(!u||!await jL(c,u))throw new Error("An execution input changed.");let l="checkpoint_"+c.policy.format+"_"+c.policy.id,d=await this.journal.read(l);if(d&&(c.policy.revision<d.policy||c.materialRevision<d.material))throw new Error("The execution input is older than this executor has already observed.");await this.journal.write(l,{policy:c.policy.revision,material:c.materialRevision})}if(e.kind==="function"&&(e.functionId!==r.functionId||await Q(e.definition)!==r.functionDigest||e.definition.environmentId!==r.environmentId||!this.environment.manifest.capabilities.includes(ue[e.definition.program.kind])))throw new Error("Run the exact function authorized by this intent.");if(e.kind!=="function"&&(r.functionId||r.functionDigest))throw new Error("Use function authorization only for a saved function.");let n=this.request(e);if(n){if(Go(n.url,r.origin),[n.body,n.json,n.form].filter(c=>c!==void 0).length>1)throw new Error("Choose one request body format.");for(let c of n.bindings){let u=l_(c.pointer);if(!u.length||!["headers","body","json","form"].includes(u[0])||u[0]==="body"&&u.length!==1||["headers","form"].includes(u[0])&&u.length!==2)throw new Error("Bind credentials to request headers or the body.");e3(structuredClone(n),c.pointer,"validation")}}let i=e.kind==="function"?e.outputs:e.kind==="http"?e.save:{};for(let[c,u]of Object.entries(i)){if(l_(c),!this.broker.capture)throw new Error("This executor cannot save encrypted outputs.");let l=await su(u.approval);if(C(l.policy.authorities.find(d=>d.id===l.authorityId))!==C(r.actor)||l.policy.origin!==r.origin||l.policy.contentType!==he.value||l.policy.ownerId!==r.ownerId||!l.policy.producers.some(d=>d.runId===r.id&&C(d.executor)===C(this.binding)&&Date.parse(d.expiresAt)>Date.now()))throw new Error("Approve each encrypted output for this execution.")}let s=e.kind==="function"?Ok(e.definition,e.arguments):e,a=s.kind==="command"?s.inputs.map(c=>c.source):n?n.bindings.flatMap(c=>c.parts.filter(u=>typeof u!="string")):[];for(let c of a){let u=o.find(l=>l.policy.id===c.id);if(!u||!kHe(u,c))throw new Error("Use the input named in the signed request.");await ld(u,r,{...n?{destination:n.url}:{}}),await au(u,r,this.keys,{...n?{destination:n.url}:{}})}if(e.kind==="connect"||e.kind==="refresh"||e.kind==="revoke"){if(!this.extension)throw new Error("This executor cannot manage connections.");await this.extension.validate(e.input,r,o)}}async executeOperation(e,r,o,n){if(e.kind==="connect"||e.kind==="refresh"||e.kind==="revoke")return this.extension.execute(e.input,r,o,n);let i=this.request(e),s=e.kind==="function"?Ok(e.definition,e.arguments):e,a=[],c=new Map,u=async h=>{let y=o.find(b=>b.policy.id===h.id);if(y.policy.contentType===he.value)return au(y,r,this.keys,{...i?{destination:i.url}:{}});if(!this.extension)throw new Error("This executor cannot use connections.");c.has(h.id)||c.set(h.id,this.extension.outputs(y,r,o,n,i?.url));let w=await c.get(h.id);if(!h.output||!Object.hasOwn(w,h.output))throw new Error("Choose an available connection output.");return tt(w[h.output])};if(s.kind==="command"){let h=await Ck(s.inputs,u),y=await this.commands.execute({command:s.command,timeoutSeconds:s.timeoutSeconds,...s.stdin===void 0?{}:{stdin:s.stdin},environment:h.environment,files:h.files,...e.kind==="function"?{workspace:"temporary"}:{}},n);if(e.kind==="function"){if(y.timedOut)throw new dt(408,"function_timeout","The function exceeded its time limit.");if(y.truncated)throw new dt(413,"function_output_limit","The function output exceeded its size limit.");if(y.exitCode!==0)throw new dt(422,"function_failed",mh(y.stderr,h.sensitive).slice(0,1e3)||"The function did not finish successfully.");return this.functionResult(e,r,y.stdout)}return{...y,stdout:mh(y.stdout,h.sensitive),stderr:mh(y.stderr,h.sensitive)}}let l=structuredClone(i);for(let h of l.bindings){let y="";for(let w of h.parts)if(typeof w=="string")y+=w;else{let b=Ra(await u(w));a.push(b,Buffer.from(b).toString("base64"),Buffer.from(b).toString("base64url")),y+=b}e3(l,h.pointer,y)}let d=l.body;l.json!==void 0&&(d=JSON.stringify(l.json),l.headers["content-type"]="application/json"),l.form!==void 0&&(d=new URLSearchParams(l.form).toString(),l.headers["content-type"]="application/x-www-form-urlencoded");let p=await this.transport.send({url:l.url,method:l.method,headers:l.headers,...d===void 0?{}:{body:d},signal:n});if(e.kind==="function"){if(p.status<200||p.status>=300)throw new dt(502,"service_response","The service returned HTTP "+p.status+".");let h=e.definition.program.kind==="http"?e.definition.program.responseFormat:"json",y=Ra(p.body);if(h==="json")try{y=p.body.length===0&&([204,205].includes(p.status)||l.method==="HEAD")?null:yr.parse(JSON.parse(y))}catch{throw new dt(422,"invalid_function_result","The HTTP response body must contain valid JSON.")}return this.functionResult(e,r,JSON.stringify({status:p.status,headers:p.headers,body:y}))}let f=e.kind==="http"?e.save:{};if(Object.keys(f).length){if(p.status>=400)throw new dt(502,"service_response","The service returned an unsuccessful response.");let h={};for(let[y,w]of Object.entries(f)){let b=p.body;if(y!==""){let x=xi(JSON.parse(Ra(b)),y);if(x===void 0)throw new dt(400,"invalid_pointer","The response value was not found.");b=tt(typeof x=="string"?x:JSON.stringify(x))}let S=await Gy(b,w.approval,r.id,this.binding,this.keys,{bytes:b.length});h[w.name]=(await this.broker.capture(w.name,S)).id}return{status:p.status,saved:h}}return{status:p.status,headers:Object.fromEntries(Object.entries(p.headers).map(([h,y])=>[h,mh(y,a)])),body:mh(Ra(p.body),a)}}async functionResult(e,r,o){let n;try{n=e.definition.result==="text"?o:yr.parse(JSON.parse(o))}catch{throw new dt(422,"invalid_function_result","The function must return valid JSON.")}let i={};for(let[s,a]of Object.entries(e.outputs)){let c=s===""?n:xi(n,s);if(c===void 0)throw new dt(400,"invalid_pointer","The function result value was not found.");let u=tt(typeof c=="string"?c:JSON.stringify(c)),l=await Gy(u,a.approval,r.id,this.binding,this.keys,{bytes:u.length});i[a.name]=(await this.broker.capture(a.name,l)).id}return Object.keys(i).length?{saved:i}:n}};import{spawn as THe}from"node:child_process";import{constants as s3}from"node:fs";import{open as npe,rm as CHe}from"node:fs/promises";async function ope(t){if(process.platform!=="linux"){let r=await npe(t,"wx",384).catch(()=>{throw new Error("This executor is locked. Check that its previous process has stopped before removing "+t+".")});return await r.writeFile(JSON.stringify({pid:process.pid})),async()=>{await r.close(),await CHe(t,{force:!0})}}let e=await npe(t,s3.O_CREAT|s3.O_WRONLY|s3.O_NOFOLLOW,384);try{let r=THe("flock",["--nonblock","--conflict-exit-code","73","3"],{stdio:["ignore","ignore","ignore",e.fd]});await new Promise((o,n)=>{r.once("error",()=>n(new Error("Install util-linux (flock) to run an executor on this host."))),r.once("close",i=>i===0?o():n(new Error(i===73?"This executor is already running.":"The executor lock could not be acquired.")))})}catch(r){throw await e.close(),r}return()=>e.close()}var PD=Vt(LV(),1),kD=Vt(U0e(),1);function L0e(t){return FL.safeParse(t).success?t:null}async function j0e(t=3e3){let e=new PD.STSClient({region:process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"us-east-1"}),r,o=AbortSignal.timeout(t);try{let n=await e.send(new PD.GetCallerIdentityCommand({}),{abortSignal:o});if(!n.Arn)return null;let i=L0e(n.Arn);if(i)return i;let s=/^arn:(aws[a-z-]*):sts::(\d{12}):assumed-role\/([^/]+)\/.+$/.exec(n.Arn);if(!s||n.Account!==s[2]||!n.UserId)return null;r=new kD.IAMClient({region:e.config.region,credentials:e.config.credentials});let c=(await r.send(new kD.GetRoleCommand({RoleName:s[3]}),{abortSignal:o})).Role;if(!c?.Arn||c.RoleId!==n.UserId.split(":")[0])return null;let u=L0e(c.Arn);return u?.startsWith(`arn:${s[1]}:iam::${s[2]}:role/`)&&u.split("/").at(-1)===s[3]?u:null}catch{return null}finally{e.destroy(),r?.destroy()}}var eG=m.string().refine(t=>!t.includes("\0"),"Use text without null bytes."),tG=eG.max(4096).startsWith("/"),F0e=m.object({command:m.array(eG.max(8192)).min(1).max(100).refine(t=>!!t[0],"Specify a program."),workingDirectory:tG.optional(),environment:m.record(m.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),eG.max(65536)).refine(t=>Object.keys(t).length<=128&&JSON.stringify(t).length<=1e6,"Use at most 128 environment variables and 1 MB of environment data.").default({}),stdin:m.string().max(1e6).default(""),timeoutSeconds:m.number().int().min(1).max(3600).default(60)}).strict(),a9t=F0e.extend({id:E.optional()}),q0e=m.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),V0e=m.object({exitCode:m.number().int().nullable(),signal:m.string().max(32).nullable(),stdout:m.string().max(1e6),stderr:m.string().max(1e6),timedOut:m.boolean(),truncated:m.boolean()}).strict(),c9t=m.object({state:q0e.exclude(["queued","running"]),result:V0e.nullable(),error:m.string().max(100).nullable()}).strict(),TD=F0e.extend({id:E,environmentId:E,ownerId:E,actorId:E,workingDirectory:tG,state:q0e,result:V0e.nullable(),error:m.string().nullable(),createdAt:$e,startedAt:$e.nullable(),finishedAt:$e.nullable()}).strict(),u9t=TD.pick({id:!0,environmentId:!0,ownerId:!0,actorId:!0,state:!0,createdAt:!0}).strict(),l9t=m.object({workingDirectory:tG}).strict(),G0e=m.object({lease:E,process:TD}).strict().nullable();var CD=class{constructor(e){this.api=e}api;claim(e){return this.api.json("/api/environments/"+e+"/processes/claim",{method:"POST",body:{}},G0e)}dispatch(e,r){return this.api.json("/api/processes/"+e+"/dispatch",{method:"POST",body:{lease:r}})}renew(e,r){return this.api.json("/api/processes/"+e+"/renew",{method:"POST",body:{lease:r}},m.object({active:m.boolean()}))}finish(e,r,o){return this.api.json("/api/processes/"+e+"/finish",{method:"POST",body:{lease:r,...o}},TD)}},OD=class{constructor(e,r,o,n,i=15e3){this.environmentId=e;this.broker=r;this.journal=o;this.commands=n;this.renewalMilliseconds=i}environmentId;broker;journal;commands;renewalMilliseconds;async deliver(e){await this.broker.finish(e.id,e.lease,e.completion),await this.journal.write("process_"+e.id,{...e,delivered:!0})}async reconcile(){let e=[];for(let r of await this.journal.keys("process_")){let o=await this.journal.read(r);if(!(!o||o.delivered)){o.completion??={state:"uncertain",result:null,error:"execution_interrupted"},await this.journal.write(r,o);try{await this.deliver(o)}catch{e.push(o.id)}}}return e}async tick(e=new AbortController().signal){e.throwIfAborted();let r=await this.broker.claim(this.environmentId);if(!r)return!1;let{lease:o,process:n}=r,i=await this.journal.read("process_"+n.id);if(i){let l=i.completion??{state:"uncertain",result:null,error:"execution_interrupted"};return await this.broker.finish(n.id,o,l),!0}let s={id:n.id,lease:o,delivered:!1,completion:null};await this.journal.write("process_"+n.id,s);let a=new AbortController,c=()=>a.abort();e.addEventListener("abort",c,{once:!0}),e.aborted&&c();let u;try{await this.broker.dispatch(n.id,o),u=setInterval(()=>{this.broker.renew(n.id,o).then(d=>{d.active||c()},c)},this.renewalMilliseconds),u.unref();let l=await this.commands.execute({command:n.command,workingDirectory:n.workingDirectory,stdin:n.stdin,environment:n.environment,files:{},timeoutSeconds:n.timeoutSeconds},a.signal);s.completion={state:a.signal.aborted?"cancelled":l.exitCode===0&&!l.timedOut?"succeeded":"failed",result:l,error:null}}catch{s.completion={state:a.signal.aborted?"cancelled":"failed",result:null,error:"process_failed"}}finally{clearInterval(u),e.removeEventListener("abort",c)}await this.journal.write("process_"+n.id,s);try{await this.deliver(s)}catch{throw new Ia}return!0}};var DD=m.object({format:m.literal(1),functionId:E,ownerId:E,revision:m.number().int().positive(),definition:ei,author:Kt,executor:Kt,createdAt:$e,signature:cr}).strict();async function H0e(t,e){return DD.parse({...t,signature:await ir(t,e.signing,"function-publication")})}async function K0e(t,e){let r=DD.parse(t),{signature:o,...n}=r;if(await zs(n.author),await Ur(n,o,n.author.signing,"function-publication"),e&&C(n.executor)!==C(e))throw new Error("This function is approved for another executor.");return r}var rG=m.object({functionId:E,publication:DD,contents:m.record(E,m.object({version:m.number().int().positive(),content:tn}).strict())}).strict(),sot=m.object({name:fe,definition:ei,authorization:rG}).strict(),b9t=sot.extend({version:m.number().int().positive()}),aot=m.object({id:E.optional(),ownerId:E.optional(),arguments:Lt.default({}),outputs:m.record(m.string().max(500),R$).default({})}).strict(),B0e=m.object({code:m.string().max(100),message:m.string().max(1e3)}).strict(),Z0e=m.object({id:E,functionId:E,functionVersion:m.number().int().positive(),ownerId:E,actorId:E,state:E$,result:yr.nullable(),error:B0e.nullable(),createdAt:$e,startedAt:$e.nullable(),finishedAt:$e.nullable()}).strict(),cot=m.object({id:E,functionId:E,functionVersion:m.number().int().positive(),ownerId:E,actorId:E,actor:Kt.nullable(),arguments:Lt,outputs:aot.shape.outputs,definitionDigest:m.string().regex(/^[A-Za-z0-9_-]{43}$/),createdAt:$e,expiresAt:$e}).strict(),W0e=m.object({id:E,requestDigest:m.string().regex(/^[A-Za-z0-9_-]{43}$/),state:E$.exclude(["queued","running"]),result:yr.nullable(),error:B0e.nullable(),finishedAt:$e,signature:cr}).strict(),J0e=m.object({lease:E,request:cot,publication:DD,sources:m.array(tn).max(100)}).strict().nullable();var ND=class{api;constructor(e){this.api={async json(r,o={},n){try{return await e.json(r,o,n)}catch(i){throw i instanceof Error&&"status"in i&&typeof i.status=="number"&&"code"in i&&typeof i.code=="string"?new dt(i.status,i.code,i.message):i}}}}claim(e){return this.api.json("/api/environments/"+e+"/invocations/claim",{method:"POST",body:{}},J0e)}dispatch(e,r){return this.api.json("/api/runtime/functions/"+e+"/dispatch",{method:"POST",body:{lease:r}})}renew(e,r){return this.api.json("/api/runtime/functions/"+e+"/renew",{method:"POST",body:{lease:r}},m.object({active:m.boolean(),reason:m.enum(["cancelled","authorization_changed","lease_lost"]).optional()}))}finish(e,r){return this.api.json("/api/runtime/functions/"+r.id+"/finish",{method:"POST",body:{lease:e,completion:r}},Z0e)}},zD=class{constructor(e,r,o,n=15e3){this.executor=e;this.broker=r;this.journal=o;this.renewalMilliseconds=n}executor;broker;journal;renewalMilliseconds;async complete(e,r,o,n){let i={id:e.id,requestDigest:e.digest,state:r,result:o,error:n,finishedAt:new Date().toISOString()};e.completion=W0e.parse({...i,signature:await ir(i,this.executor.keys.signing,"function-result")}),e.phase="settled",await this.journal.write("invocation_"+e.id,e)}async deliver(e){await this.broker.finish(e.lease,e.completion),e.delivered=!0,await this.journal.write("invocation_"+e.id,e)}async reconcile(){let e=[];for(let r of await this.journal.keys("invocation_"))try{let o=await this.journal.read(r);if(!o||o.delivered||o.phase==="prepared")continue;o.completion||await this.complete(o,"uncertain",null,{code:"execution_interrupted",message:"Check the result before invoking this function again."}),await this.deliver(o)}catch{e.push(r.slice(11))}return e}async tick(e=new AbortController().signal){e.throwIfAborted();let r=await this.broker.claim(this.executor.environment.manifest.id);if(!r)return!1;let{request:o,publication:n,sources:i,lease:s}=r,a=await Q(o),c="invocation_"+o.id,u=await this.journal.read(c);if(u&&u.digest!==a)throw new Error("An invocation ID was reused for different input.");if(u?.completion)return u.lease=s,await this.deliver(u),!0;if(u?.phase==="dispatched")return u.lease=s,await this.complete(u,"uncertain",null,{code:"execution_interrupted",message:"Check the result before invoking this function again."}),await this.deliver(u),!0;u={id:o.id,digest:a,lease:s,phase:"prepared",delivered:!1,completion:null},await this.journal.write(c,u);let l=new AbortController,d=AbortSignal.any([e,l.signal]),p=!1,f=!1,h=setInterval(()=>{f||(f=!0,this.broker.renew(o.id,s).then(y=>{y.active||(p||=y.reason==="cancelled",l.abort())},()=>l.abort()).finally(()=>{f=!1}))},this.renewalMilliseconds);h.unref();try{if(await K0e(n,this.executor.binding),n.functionId!==o.functionId||n.definition.environmentId!==this.executor.environment.manifest.id||await Q(n.definition)!==o.definitionDigest||Date.parse(o.expiresAt)<=Date.now()||!Qa(n.definition.inputAccess)||Pf(n.definition.inputAccess)<Date.parse(o.expiresAt))throw new Error("Run the current approved function in its configured environment.");let y="function_"+n.functionId,w=await this.journal.read(y),b=await Q(n);if(w&&(n.revision<w.revision||n.revision===w.revision&&w.digest!==b))throw new Error("The function definition is older than this executor has already observed.");await this.journal.write(y,{revision:n.revision,digest:b});let S=w8.parse({kind:"function",functionId:o.functionId,definition:n.definition,arguments:o.arguments,outputs:o.outputs}),x={format:2,id:o.id,origin:this.executor.environment.manifest.origin,ownerId:o.ownerId,actor:o.actor??this.executor.binding,executor:this.executor.binding,environmentId:n.definition.environmentId,environmentDigest:await Q(this.executor.environment.manifest),operation:ue.function,operationDigest:await Q(S),functionId:o.functionId,functionDigest:o.definitionDigest,sources:await Promise.all(i.map(async T=>({id:T.policy.id,policyDigest:await Q(T.policy),materialRevision:T.materialRevision,...T.policy.contentType===he.tokenSet&&typeof T.metadata.authorizationDigest=="string"?{authorizationDigest:T.metadata.authorizationDigest}:{}}))),resultRecipients:[this.executor.binding],createdAt:o.createdAt,expiresAt:o.expiresAt};await Of(this.executor.environment,x),await this.executor.validateOperation(S,x,i),d.throwIfAborted(),await this.broker.dispatch(o.id,s),u.phase="dispatched",await this.journal.write(c,u),d.throwIfAborted();let R=await this.executor.executeOperation(S,x,i,d);if(new TextEncoder().encode(JSON.stringify(R)).byteLength>1e6)throw new dt(413,"result_too_large","The function completed, but its result exceeded the output limit.");await this.complete(u,"succeeded",R,null)}catch(y){if(y instanceof Ia)throw y;let w=u.phase==="dispatched",b=d.aborted&&p?"cancelled":w&&(d.aborted||i3(y))?"uncertain":"failed";await this.complete(u,b,null,b==="uncertain"?{code:"execution_uncertain",message:"The outcome could not be confirmed. Check the destination before invoking this function again."}:!d.aborted&&y instanceof dt?{code:y.code,message:y.message}:{code:b==="cancelled"?"invocation_cancelled":"invalid_function",message:b==="cancelled"?"The function was cancelled.":"The executor could not authorize this function."})}finally{clearInterval(h)}try{await this.deliver(u)}catch{throw new Ia}return!0}};import{spawn as uot,execFile as lot}from"node:child_process";import{chmod as dot,lstat as X0e,mkdir as nG,readFile as Y0e,readdir as pot,realpath as Q0e,rename as fot,rm as mot,symlink as hot,writeFile as eEe}from"node:fs/promises";import{join as yl}from"node:path";import{promisify as got}from"node:util";import{createConnection as yot}from"node:net";import{setTimeout as vot}from"node:timers/promises";var oG=got(lot),ob=t=>'"'+t.replaceAll("\\","\\\\").replaceAll('"','\\"')+'"',MD=class{constructor(e,r){this.options=e;this.heartbeat=r;if(!Number.isInteger(e.port)||e.port<1||e.port>65535)throw new Error("Use a valid SSH port.");for(let o of Object.values(e))if(typeof o=="string"&&/[\r\n\0]/.test(o))throw new Error("Use SSH paths and addresses without control characters.");this.sessions=yl(e.directory,"sessions")}options;heartbeat;child=null;hostKey="";appliedRevision=0;pending=null;timer;closing=!1;sessions;async start(){if(await nG(this.options.directory,{recursive:!0,mode:448}),await nG(this.sessions,{recursive:!0,mode:448}),await nG(this.options.workspace,{recursive:!0,mode:448}),this.options.workspaceLink)try{if(await X0e(this.options.workspaceLink),await Q0e(this.options.workspaceLink)!==await Q0e(this.options.workspace))throw new Error("The SSH workspace points to another environment.")}catch(s){if(!(s instanceof Error&&"code"in s&&s.code==="ENOENT"))throw s;await hot(this.options.workspace,this.options.workspaceLink)}let e=yl(this.options.directory,"host_ed25519");try{await X0e(e)}catch(s){if(!(s instanceof Error&&"code"in s&&s.code==="ENOENT"))throw s;await oG("ssh-keygen",["-q","-t","ed25519","-N","","-C","foundation-environment","-f",e],{env:qi(),timeout:1e4})}await dot(e,384),this.hostKey=by.parse((await oG("ssh-keygen",["-y","-f",e],{env:qi(),timeout:1e4})).stdout);let r=yl(this.options.directory,"sshd_config"),o=["Port "+this.options.port,...this.options.listenAddress?["ListenAddress "+this.options.listenAddress]:[],"HostKey "+ob(e),"PidFile "+ob(yl(this.options.directory,"sshd.pid")),"AuthorizedKeysFile "+ob(yl(this.options.directory,"authorized_keys")),"AllowUsers "+(this.options.username??"root"),"PubkeyAuthentication yes","AuthenticationMethods publickey","PasswordAuthentication no","KbdInteractiveAuthentication no","PermitEmptyPasswords no","PermitRootLogin prohibit-password","UsePAM no","StrictModes yes","PrintMotd no","Subsystem sftp /usr/lib/openssh/sftp-server","ForceCommand "+(this.options.sessionCommand??"/usr/local/bin/foundation-ssh-session"),"SetEnv "+ob("FOUNDATION_SSH_SESSIONS="+this.sessions)+" "+ob("FOUNDATION_SSH_WORKSPACE="+(this.options.workspaceLink??this.options.workspace)),"ClientAliveInterval 30","ClientAliveCountMax 3","LoginGraceTime 30"].join(`
131
+ `),{mode:384,flag:"wx"}),!a&&this.options.workspace&&await E8(this.options.workspace,{recursive:!0,mode:448}),d=["docker","run","--rm","--name",i,"--init","--read-only","--cap-drop=ALL","--security-opt=no-new-privileges","--pids-limit=128","--memory=512m","--cpus=1","--network=bridge","--tmpfs=/tmp:rw,nosuid,nodev,size=64m","--user="+String(process.getuid?.()??65534)+":"+String(process.getgid?.()??65534),"--mount=type=bind,source="+n+",target=/run/foundation,readonly","--env-file",f,...p.flatMap(([h,y])=>["--env",h+"="+y]),...!a&&this.options.workspace?["--mount=type=bind,source="+this.options.workspace+",target=/workspace"]:[],...a?["--workdir","/tmp"]:e.workingDirectory?["--workdir",e.workingDirectory]:[],"--entrypoint="+e.command[0],"-i",this.options.image,...e.command.slice(1)]}return await new Promise(p=>{let f=x8(d[0],d.slice(1),{env:qi(s?{}:a?{...l,HOME:o,TMPDIR:o}:l),cwd:s?this.options.cwd:a?o:e.workingDirectory??this.options.cwd,detached:process.platform!=="win32",stdio:["pipe","pipe","pipe"]}),h={stdout:new R8("utf8"),stderr:new R8("utf8")},y=0,w=!1,b=(T,M)=>{let Z=Math.max(0,1e6-y);M.length>Z&&(c.truncated=!0);let te=M.subarray(0,Z);y+=te.length,c[T]+=h[T].write(te)};f.stdout.on("data",T=>b("stdout",T)),f.stderr.on("data",T=>b("stderr",T)),f.stdin.on("error",()=>{}),f.stdin.end(e.stdin??"");let S=()=>{u=!0;try{f.pid&&process.platform!=="win32"?process.kill(-f.pid,"SIGKILL"):f.kill("SIGKILL")}catch{}},x=setTimeout(()=>{c.timedOut=!0,S()},e.timeoutSeconds*1e3);x.unref();let R=()=>{w||(w=!0,clearTimeout(x),r.removeEventListener("abort",S),c.stdout+=h.stdout.end(),c.stderr+=h.stderr.end(),p())};r.addEventListener("abort",S,{once:!0}),r.aborted&&S(),f.once("error",()=>{c.exitCode=127,c.stderr="The command could not be started.",R()}),f.once("close",(T,M)=>{c.exitCode=T,c.signal=M,R()})}),c}finally{s&&u&&await new Promise(l=>{let d=x8("docker",["rm","-f",i],{env:qi(),stdio:"ignore"});d.once("close",()=>l()),d.once("error",()=>l()),setTimeout(()=>{d.kill("SIGKILL"),l()},1e4).unref()}),await UDe(o,{recursive:!0,force:!0})}}};function BDe(t){return[...new Set(t.filter(Boolean).flatMap(e=>[e,encodeURIComponent(e),JSON.stringify(e).slice(1,-1),Buffer.from(e).toString("base64"),Buffer.from(e).toString("base64url")]))].sort((e,r)=>r.length-e.length)}var A$=class{constructor(e,r){this.secrets=e;this.output=r;this.max=Math.max(1,...e.map(o=>o.length))}secrets;output;pending="";decoder=new KDe("utf8");max;write(e){this.pending+=this.decoder.write(e),this.flush(!1)}end(){this.pending+=this.decoder.end(),this.flush(!0)}flush(e){let r=e?this.pending.length:Math.max(0,this.pending.length-this.max+1),o=0,n="";for(;o<r;){let i=this.secrets.find(s=>this.pending.startsWith(s,o));i?(n+="[redacted]",o+=i.length):(n+=this.pending[o],o++)}this.pending=this.pending.slice(o),n&&this.output(n)}};async function A8(t,e){if(!e.length)throw new Error("Put the command after --.");let r=await qDe(I8(HDe(),"foundation-"));await FDe(r,448);try{let o=qi(t.environment),n=[...t.sensitive];for(let[i,s]of Object.entries(t.files)){let a=Buffer.from(s,"base64"),c=I8(r,i);await GDe(c,a,{mode:384,flag:"wx"}),o[i]=c,n.push(a.toString("utf8"),s,a.toString("base64url"))}return await new Promise((i,s)=>{let a=jDe(e[0],e.slice(1),{env:o,stdio:["inherit","pipe","pipe"],detached:process.platform!=="win32"}),c=BDe(n),u=new A$(c,h=>process.stdout.write(h)),l=new A$(c,h=>process.stderr.write(h));a.stdout.on("data",h=>u.write(h)),a.stderr.on("data",h=>l.write(h));let d=h=>{if(a.pid)try{process.platform==="win32"?a.kill(h):process.kill(-a.pid,h)}catch{}},p=()=>d("SIGINT"),f=()=>d("SIGTERM");process.on("SIGINT",p),process.on("SIGTERM",f),a.once("error",()=>s(new Error("The command could not be started. Check the executable and arguments."))),a.once("close",(h,y)=>{process.off("SIGINT",p),process.off("SIGTERM",f),u.end(),l.end(),i(h??(y==="SIGINT"?130:y==="SIGTERM"?143:1))})})}finally{await VDe(r,{recursive:!0,force:!0})}}import{dirname as AHe,join as o3}from"node:path";function dr(t){switch(t.kind){case"oauth":let e=t.config.application;return{family:"oauth",application:e,requiresApp:e==="required",browserAuthorization:t.config.grantType!=="client_credentials",revocable:t.config.revoke?.tokenOnly===!0,fields:t.config.fields,outputs:Object.keys(t.config.outputs)};case"token":return{family:"token",application:"none",requiresApp:!1,browserAuthorization:!1,revocable:!1,fields:t.config.fields,outputs:Object.keys(t.config.outputs)};case"approval":return{family:"approval",application:"none",requiresApp:!1,browserAuthorization:!0,revocable:!1,fields:t.config.fields,outputs:Object.keys(t.config.outputs)};case"ovh":{let r=t.config.authorization==="consumer_key";return{family:"ovh",application:r?"required":"none",requiresApp:r,browserAuthorization:r,revocable:!1,fields:t.config.fields,outputs:Object.keys(t.config.outputs)}}case"aws":return{family:"aws",application:"none",requiresApp:!1,browserAuthorization:!1,revocable:!1,fields:[],outputs:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_DEFAULT_REGION","AWS_REGION"]}}}function Vi(t,e){return[...new Set([...t.required??[],...e??t.default])]}function lu(t){return dr(t).requiresApp}var ZDe=new Set(["airtable.com","dash.cloudflare.com","api.ebay.com","accounts.secure.freee.co.jp","github.com","id.heroku.com","api.hubapi.com","api.netlify.com","api.notion.com","api.render.com","login.salesforce.com","cloud.digitalocean.com","api.vultr.com","api.x.com","zoom.us"]);function P8(t){if(t.kind==="approval")return"unavailable";if(!dr(t).browserAuthorization||t.kind==="ovh"||t.kind!=="oauth")return"available";try{let e=new URL(t.config.tokenUrl).hostname;return ZDe.has(e)||e==="login.microsoftonline.com"&&t.config.clientAuth!=="none"?"unavailable":t.config.tokenUrl.includes("{")?"unknown":"available"}catch{return"unknown"}}var WDe=new Set(["format","generation","methodId","method","appId","appGeneration","account","accountId","accountName","accountVerified","scopes","scopesStatus","outputs","state","methodKind","authorizationDigest"]),k8=Lt.refine(t=>Object.keys(t).every(e=>!WDe.has(e)),"Keep method-specific facts separate from common facts."),du=m.object({accountId:m.string().max(2e3).nullable(),accountName:m.string().max(2e3),accountVerified:m.boolean(),scopes:m.array(m.string().max(1e3)).max(200),scopesStatus:m.enum(["unknown","requested","reported"]),authorization:k8,details:k8}).strict();function WL(t){if(t.method.kind!=="oauth")throw new Error("Use OAuth connection material.");let e="requestedScopes"in t?t.requestedScopes:void 0;return du.parse({accountId:t.oauth?.account??"",accountName:t.oauth?.accountName??"",accountVerified:t.oauth?.accountVerified??!1,scopes:e??t.oauth?.scopes??[],scopesStatus:e?"requested":t.oauth?.scopesStatus??"unknown",authorization:{},details:{}})}function zf(t){if(t.method.kind!=="token"&&t.method.kind!=="approval"||!t.fields)throw new Error("Use input credential material.");return"facts"in t&&t.facts?du.parse(t.facts):du.parse({accountId:null,accountName:t.method.name,accountVerified:!1,scopes:[],scopesStatus:"unknown",authorization:{},details:{}})}function JL(t){if(t.method.kind!=="ovh")throw new Error("Use OVH connection material.");let e="ovh"in t?t.ovh:void 0;if(!e){let r="requestedScopes"in t?t.requestedScopes:void 0;return du.parse({accountId:null,accountName:"",accountVerified:!1,scopes:r??[],scopesStatus:r?"requested":"unknown",authorization:{},details:{}})}return du.parse({accountId:e.user?e.account+"/"+e.user:e.account,accountName:e.account+(e.user?" / "+e.user:""),accountVerified:!0,scopes:e.rules.map(r=>r.method+" "+r.path),scopesStatus:"reported",authorization:{ovh:e},details:{ovh:e}})}function XL(t){if(t.method.kind!=="aws"||!t.aws)throw new Error("Use AWS connection material.");return du.parse({accountId:t.aws.identity?Ef(t.aws.identity.arn):null,accountName:t.aws.identity?t.aws.identity.accountId+" / "+t.aws.identity.arn.split(":").at(-1):"",accountVerified:!!t.aws.identity,scopes:[],scopesStatus:"unknown",authorization:{aws:O5(t.aws)},details:{aws:D5(t.aws)}})}var JDe={oauth:WL,token:zf,aws:XL,ovh:JL,approval:zf};function Wy(t){return JDe[t.method.kind](t)}var hJ=Vt(Y8(),1);var sc=class extends Error{template;position;hint;constructor(t,e,r,o){super(`${o} (at position ${e}): ${r}`),this.template=t,this.position=e,this.hint=r,this.name="TemplateParseError"}},bNe=class extends sc{constructor(t,e){super(t,e,"Add the missing '}' to close the expression, or remove the stray '{'.","Unclosed expression: '{' has no matching '}'"),this.name="UnclosedExpressionError"}},SNe=class extends sc{constructor(t,e){super(t,e,"Remove this stray '}' or add a matching '{' before it.","Stray '}' outside of any expression"),this.name="StrayClosingBraceError"}},xNe=class extends sc{constructor(t,e){super(t,e,"RFC 6570 expressions cannot nest. Close the outer expression with '}' before starting a new one.","Nested '{' inside an unclosed expression"),this.name="NestedOpeningBraceError"}},ENe=class extends sc{char;constructor(t,e,r){super(t,e,`Pct-encode '${r}' (e.g. '%${r.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}') or remove it. Literals may not contain CTL, SP, '"', '\\'', lone '%', '<', '>', '\\\\', '^', '\`', or '|'.`,`Invalid literal character '${r}'`),this.char=r,this.name="InvalidLiteralError"}},$Ne=class extends sc{constructor(t,e){super(t,e,"Provide at least one varname inside the braces, e.g. '{var}'.","Empty expression '{}'"),this.name="EmptyExpressionError"}},RNe=class extends sc{operator;constructor(t,e,r){super(t,e,`Operator '${r}' is reserved by RFC 6570 \xA72.2 for future extensions. Use one of '+', '#', '.', '/', ';', '?', '&' instead, or remove the operator.`,`Reserved operator '${r}'`),this.operator=r,this.name="ReservedOperatorError"}},INe=class extends sc{operator;constructor(t,e,r){super(t,e,`Replace '${r}' with one of '+', '#', '.', '/', ';', '?', '&' or remove it.`,`Unknown operator '${r}'`),this.operator=r,this.name="UnknownOperatorError"}},L$=class extends sc{varSpec;constructor(t,e,r,o,n){super(t,e,r,o),this.varSpec=n,this.name="InvalidVarSpecError"}},sj=class extends L${constructor(t,e){super(t,e,"Remove the stray comma or insert a varname before/after it.","Empty varname in variable-list",""),this.name="EmptyVarNameError"}},ANe=class extends L${offendingChar;constructor(t,e,r,o){super(t,e,`Varnames may only contain ALPHA, DIGIT, '_', '.', or pct-encoded triplets. Replace '${o}' or pct-encode it.`,`Invalid character '${o}' in varname`,r),this.offendingChar=o,this.name="InvalidVarNameError"}},PNe=class extends L${prefix;constructor(t,e,r,o){super(t,e,"Prefix modifiers must be ':N' where N is a positive integer in 1..9999 with no leading zero (e.g. ':3').",`Invalid prefix modifier ':${o}'`,r),this.prefix=o,this.name="InvalidPrefixError"}},Q8=class extends L${constructor(t,e){super(t,e,"Remove the trailing comma, or add a varspec after it.","Trailing ',' in variable-list",""),this.name="TrailingCommaError"}},kNe=class extends sc{char;constructor(t,e,r){super(t,e,"Expected ',' or '}' here. Remove the unexpected character or pct-encode it if it belongs in the varname.",`Unexpected character '${r}' in expression`),this.char=r,this.name="UnexpectedCharacterError"}},TNe=class extends Error{variableName;hint;constructor(t,e,r){super(`${r} for '${t}': ${e}`),this.variableName=t,this.hint=e,this.name="TemplateExpansionError"}},CNe=class extends TNe{prefix;valueType;constructor(t,e,r){super(t,"Remove the prefix modifier from this varspec, or provide a string value instead of a composite value.",`Prefix modifier ':${e}' is not applicable to ${r} values`),this.prefix=e,this.valueType=r,this.name="PrefixModifierNotApplicableError"}},ONe=["","+",".","/",";","?","&","#"],sJ={"":{first:"",sep:",",named:!1,ifEmpty:"",allowReserved:!1},"+":{first:"",sep:",",named:!1,ifEmpty:"",allowReserved:!0},".":{first:".",sep:".",named:!1,ifEmpty:"",allowReserved:!1},"/":{first:"/",sep:"/",named:!1,ifEmpty:"",allowReserved:!1},";":{first:";",sep:";",named:!0,ifEmpty:"",allowReserved:!1},"?":{first:"?",sep:"&",named:!0,ifEmpty:"=",allowReserved:!1},"&":{first:"&",sep:"&",named:!0,ifEmpty:"=",allowReserved:!1},"#":{first:"#",sep:",",named:!1,ifEmpty:"",allowReserved:!0}},DNe=new TextEncoder,eJ="0123456789ABCDEF",tJ=t=>mu(En(48,57),En(65,70),En(97,102))(t.charCodeAt(0)),Qy=(t,e)=>t[e]==="%"&&e+2<t.length&&tJ(t[e+1])&&tJ(t[e+2]);function aj(t,e){let r=t[e];return r==null?0:mu(aJ,cJ,fd("_"))(r)?1:Qy(t,e)?3:0}function NNe(t,e){if(Qy(t,e))return 3;let{char:r,size:o}=ev(t,e);return MNe(r)?o:0}function ev(t,e){let r=t.codePointAt(e);if(r==null)return{char:"",size:0};let o=r>65535?2:1;return{char:t.slice(e,e+o),size:o}}var dj=t=>e=>{let r="";for(let o=0;o<e.length;){if(t&&Qy(e,o)){r+=e.slice(o,o+3),o+=3;continue}let{char:n,size:i}=ev(e,o);r+=mu(uJ,s=>t&&zNe(s))(n)?n:lJ(n),o+=i}return r};function Lf(t){let e="";for(let r=0;r<t.length;){if(Qy(t,r)){e+=t.slice(r,r+3),r+=3;continue}let{char:o,size:n}=ev(t,r);e+=uJ(o)?o:lJ(o),r+=n}return e}function Xy(t,e){let r="",o=0;for(let n=0;n<t.length&&o<e;o++){if(Qy(t,n)){r+=t.slice(n,n+3),n+=3;continue}let{char:i,size:s}=ev(t,n);r+=i,n+=s}return r}var aJ=t=>mu(En(65,90),En(97,122))(t.charCodeAt(0)),cJ=t=>En(48,57)(t.charCodeAt(0)),uJ=t=>mu(aJ,cJ,e=>"-._~".includes(e))(t),zNe=t=>":/?#[]@!$&'()*+,;=".includes(t),MNe=t=>UNe(t.codePointAt(0)),UNe=t=>t!=null&&mu(fd(33),En(35,36),fd(38),En(40,59),fd(61),En(63,91),fd(93),fd(95),En(97,122),fd(126),LNe,jNe)(t);function LNe(t){if(t<65536)return mu(En(160,55295),En(63744,64975),En(65008,65519))(t);if(t>983037)return!1;let e=t%65536;return e<=65533&&(t<917504||e>=4096)}var jNe=t=>mu(En(57344,63743),En(983040,1048573),En(1048576,1114109))(t),lJ=t=>Array.from(DNe.encode(t)).map(e=>`%${eJ[e>>4]}${eJ[e&15]}`).join(""),En=(t,e)=>r=>t<=r&&r<=e,fd=t=>e=>t===e,mu=(...t)=>e=>t.some(r=>r(e));function dJ(t,e,r){return t.map(o=>o.kind==="literal"?o.text:FNe(o.vars,o.operator,e,r)).join("")}function FNe(t,e,r,o){let n=sJ[e],i=t.flatMap(s=>qNe(s,r[s.name],n,o));return i.length<1?"":`${n.first}${i.join(n.sep)}`}function qNe(t,e,r,o){if(e==null)return[];if(JNe(e)){let n=KNe(e,r.allowReserved);return n.length<1?[]:rJ(t,"list",o)?GNe(t,n,r):[]}if(WNe(e)){let n=BNe(e,r.allowReserved);return n.length<1?[]:rJ(t,"associative",o)?HNe(t,n,r):[]}return VNe(t,e,r)}function VNe(t,e,r){let o=String(e),n=t.prefix==null?o:Xy(o,t.prefix),i=dj(r.allowReserved)(n);return r.named?[Yy(Lf(t.name),i,r)]:[i]}function GNe(t,e,r){let o=Lf(t.name);if(t.explode)return r.named?e.map(i=>Yy(o,i,r)):[...e];let n=e.join(",");return r.named?[Yy(o,n,r)]:[n]}function HNe(t,e,r){if(t.explode)return e.map(([n,i])=>Yy(n,i,r));let o=e.flat(1).join(",");return r.named?[Yy(Lf(t.name),o,r)]:[o]}var Yy=(t,e,r)=>e===""?`${t}${r.ifEmpty}`:`${t}=${e}`,KNe=(t,e)=>t.filter(r=>r!=null).map(String).map(dj(e)),BNe=(t,e)=>Object.entries(t).map(([r,o])=>[r,ZNe(o)]).filter(([,r])=>r!=null).map(r=>r.map(dj(e)));function ZNe(t){if(t==null)return null;if(!Array.isArray(t))return String(t);let e=t.filter(r=>r!=null).map(String);return e.length<1?null:e.join(",")}var WNe=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),JNe=t=>Array.isArray(t);function rJ(t,e,{report:r,strict:o}){if(t.prefix==null)return!0;let n=new CNe(t.name,t.prefix,e);if(r(n),o)throw n;return!1}function XNe(t,e,r){return cj(t,e,r,0,0,{})}function cj(t,e,r,o,n,i){if(o>=t.length){if(n!==e.length)return null;let a=E1e(i);return dJ(t,a,r)===e?a:null}let s=t[o];if(s.kind==="literal")return e.startsWith(s.text,n)?cj(t,e,r,o+1,n+s.text.length,i):null;for(let a of YNe(t,e,o,n)){let c=e.slice(n,a);for(let u of e1e(s.vars,s.operator,c)){let l=pj(i,u);if(l==null)continue;let d=cj(t,e,r,o+1,a,l);if(d!=null)return d}}return null}function*YNe(t,e,r,o){let n=t.slice(r+1).find(i=>i.kind==="literal"&&i.text!=="");if(n==null||n.kind!=="literal"){yield*QNe(e.length,o);return}for(let i=e.indexOf(n.text,o);i>=0;i=e.indexOf(n.text,i+1))yield i}function*QNe(t,e){for(let r=t;r>=e;r--)yield r}function*e1e(t,e,r){if(r===""){yield*t1e(t,e);return}let o=sJ[e];if(!r.startsWith(o.first))return;let n=r.slice(o.first.length);yield*o.named?l1e(t,o,n):r1e(t,o,n)}var t1e=(t,e)=>(e===""||e==="+")&&t.length===1?[fu(t[0],"")]:[{}],r1e=(t,e,r)=>uj(t,e,fj(r,e.sep),0,0);function*uj(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of n1e(i,e,r,n))for(let a of uj(t,e,r,o+1,s.index)){let c=pj(s.bindings,a);c!=null&&(yield c)}yield*uj(t,e,r,o+1,n)}function*n1e(t,e,r,o){if(o>=r.length)return;let n=r.length-o;for(let i=1;i<=n;i++){let s=r.slice(o,o+i);for(let a of o1e(t,e,s))yield{bindings:a,index:o+i}}}function*o1e(t,e,r){let o=pJ(t,e,r.join(e.sep));if(t.prefix!=null){yield*o;return}t.explode&&r.length>0&&(yield*i1e(t,e,r)),yield*o}function*i1e(t,e,r){let o=fJ(r,e.allowReserved);if(o==null)return;let n=s1e(r,e);n!=null&&(yield fu(t,n)),yield fu(t,o)}var s1e=(t,e)=>a1e(t.join(e.sep),e);function a1e(t,e){let r=[];for(let o=0;o<t.length;){let n=t.indexOf("=",o);if(n<0)return null;let i=n+1,s=c1e(t,i,e.sep),a=ic(t.slice(o,n),e.allowReserved),c=ic(t.slice(i,s),e.allowReserved);if(a==null||c==null)return null;r.push([a,c]),o=s+e.sep.length}return r.length<1?null:Object.fromEntries(r)}function c1e(t,e,r){for(let o=e;o<t.length;o++)if(u1e(t,o,r))return o;return t.length}var u1e=(t,e,r)=>{if(!t.startsWith(r,e))return!1;let o=e+r.length;for(let n=o;n<t.length;n++){if(t[n]==="=")return n>o;if(t.startsWith(r,n))return!1}return!1};function*pJ(t,e,r){let o=ic(r,e.allowReserved);if(o==null)return;let n=fu(t,o);if(t.prefix!=null){yield n;return}let i=fj(r,",");if(i.length<2){yield n;return}let s=fJ(i,e.allowReserved);if(s==null){yield n;return}let a=i.length%2===0?w1e(i,e.allowReserved):null;a!=null&&(yield fu(t,a)),yield fu(t,s),yield n}var l1e=(t,e,r)=>lj(t,e,fj(r,e.sep).map(v1e),0,0);function*lj(t,e,r,o,n){if(o>=t.length){n>=r.length&&(yield{});return}let i=t[o];for(let s of d1e(i,e,r,n,t))for(let a of lj(t,e,r,o+1,s.index)){let c=pj(s.bindings,a);c!=null&&(yield c)}yield*lj(t,e,r,o+1,n)}function*d1e(t,e,r,o,n){if(!(o>=r.length)){if(t.explode&&t.prefix==null){yield*f1e(t,e,r,o,n);return}yield*p1e(t,e,r,o)}}function*p1e(t,e,r,o){let n=r[o];if(n.name===Lf(t.name))for(let i of pJ(t,e,n.value))yield{bindings:i,index:o+1}}function*f1e(t,e,r,o,n){yield*m1e(t,e,r,o),yield*g1e(t,e,r,o,n)}function*m1e(t,e,r,o){let n=[...h1e(Lf(t.name),e,r,o)];n.length>0&&(yield{bindings:fu(t,n),index:o+n.length})}function*h1e(t,e,r,o){for(let n=o;n<r.length&&r[n].name===t;n++){let i=ic(r[n].value,e.allowReserved);if(i==null)return;yield i}}function*g1e(t,e,r,o,n){let i=[...y1e(e,r,o,new Set(n.map(s=>Lf(s.name))))];i.length>0&&(yield{bindings:fu(t,Object.fromEntries(i)),index:o+i.length})}function*y1e(t,e,r,o){for(let n=r;n<e.length;n++){let i=e[n];if(n>r&&o.has(i.name))return;let s=ic(i.name,t.allowReserved),a=ic(i.value,t.allowReserved);if(s==null||a==null)return;yield[s,a]}}function v1e(t){let e=t.indexOf("=");return e<0?{name:t,value:""}:{name:t.slice(0,e),value:t.slice(e+1)}}function w1e(t,e){let r=[];for(let o=0;o<t.length;o+=2){let n=ic(t[o],e),i=ic(t[o+1],e);if(n==null||i==null)return null;r.push([n,i])}return Object.fromEntries(r)}function fJ(t,e){let r=[];for(let o of t){let n=ic(o,e);if(n==null)return null;r.push(n)}return r}function ic(t,e){if(e)return t;try{return decodeURIComponent(t)}catch{return null}}var fu=({name:t,prefix:e},r)=>({[t]:{value:r,prefix:e}});function pj(t,e){let r={...t};for(let[o,n]of Object.entries(e)){let i=r[o];if(i==null){r[o]=n;continue}let s=_1e(i,n);if(s==null)return null;r[o]=s}return r}var _1e=(t,e)=>U$(t)||U$(e)?b1e(t,e):S1e(t.value,e.value)?t:null;function b1e(t,e){let r=nJ(t.value),o=nJ(e.value);if(r==null||o==null)return null;let n=U$(t),i=U$(e);if(!n&&!i)return null;if(n&&!i)return Xy(o,t.prefix)===r?e:null;if(!n&&i)return Xy(r,e.prefix)===o?t:null;let s=t.prefix,a=e.prefix;return s<=a?Xy(o,s)===r?e:null:Xy(r,a)===o?t:null}var U$=t=>t.prefix!=null,nJ=t=>typeof t=="string"?t:null;function S1e(t,e){return Array.isArray(t)?Array.isArray(e)&&t.length===e.length&&t.every((r,o)=>r===e[o]):oJ(t)?oJ(e)&&x1e(Object.entries(t),Object.entries(e)):t===e}var x1e=(t,e)=>t.length===e.length&&t.every(([r,o],n)=>{let[i,s]=e[n];return r===i&&o===s}),oJ=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),E1e=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[e,r.value])),fj=(t,e)=>e===""?[t]:t.split(e),$1e=["=",",","!","@","|"];function R1e(t,e,r){let o=a=>{throw a};if(t.length<1)return o(new $Ne(e,r));let n=t[0];if(k1e(n))return o(new RNe(e,r+1,n));if(!iJ(n)&&aj(t,0)<1)return o(new INe(e,r+1,n));let i=iJ(n)?n:"",s=i===""?0:1;return{kind:"expression",operator:i,vars:I1e(t,e,r+1,s)}}function I1e(t,e,r,o){if(o>=t.length)throw new sj(e,r+o);let n=[];for(let i=o;i<t.length;){if(t[i]===",")throw i===t.length-1?new Q8(e,r+i):new sj(e,r+i);let s=i,a=A1e(t,i);if(a===s)throw new sj(e,r+i);let c=t.slice(s,a);i=a;let u=P1e(t,e,r,i,c);if(i=u.index,i<t.length&&t[i]!==",")throw u.used?new kNe(e,r+i,t[i]):new ANe(e,r+i,c,t[i]);if(n.push({name:c,explode:u.explode,...u.prefix==null?{}:{prefix:u.prefix}}),i<t.length&&(i++,i>=t.length))throw new Q8(e,r+i-1)}return n}function A1e(t,e){let r=e,o=!0;for(;r<t.length;){let n=aj(t,r);if(n>0){r+=n,o=!1;continue}if(t[r]!=="."||o||aj(t,r+1)<1)break;r++,o=!0}return r}function P1e(t,e,r,o,n){if(t[o]==="*")return{explode:!0,index:o+1,used:!0};if(t[o]!==":")return{explode:!1,index:o,used:!1};let i=o+1,s=i;for(;s<t.length&&T1e(t[s]);)s++;let a=t.slice(i,s);if(!/^[1-9][0-9]{0,3}$/.test(a))throw new PNe(e,r+o,n,a);return{explode:!1,index:s,prefix:Number(a),used:!0}}function iJ(t){return ONe.includes(t)&&t!==""}function k1e(t){return $1e.includes(t)}function T1e(t){let e=t.charCodeAt(0);return e>=48&&e<=57}function C1e(t,e){let{report:r}=e,o=[],n=i=>{let s=o.at(-1);s?.kind==="literal"?o[o.length-1]={kind:"literal",text:s.text+i}:o.push({kind:"literal",text:i})};for(let i=0;i<t.length;){let s=t[i];if(s==="{"){let l=t.indexOf("}",i+1);if(l<0){r(new bNe(t,i)),n(t.slice(i));break}let d=t.indexOf("{",i+1);if(d>=0&&d<l){r(new xNe(t,d)),n(t.slice(i,l+1)),i=l+1;continue}let p=t.slice(i+1,l);try{o.push(R1e(p,t,i))}catch(f){r(f instanceof Error?f:new Error(String(f))),n(t.slice(i,l+1))}i=l+1;continue}if(s==="}"){r(new SNe(t,i)),n(s),i++;continue}let a=NNe(t,i);if(a>0){n(t.slice(i,i+a)),i+=a;continue}let{char:c,size:u}=ev(t,i);r(new ENe(t,i,c)),n(c),i+=u}return o}var j$=class mJ{uriTemplate;options;#e;#t;constructor(e,r={}){this.uriTemplate=e,this.options=r,this.#t=M1e(r),this.#e=O1e(C1e(e,this.#t)),Object.freeze(this)}static parse(e,r={}){return new mJ(e,r)}get tokens(){return this.#e}expand=e=>dJ(this.#e,e,this.#t);match=e=>XNe(this.#e,e,this.#t);toString=()=>this.uriTemplate},O1e=t=>Object.freeze(t.map(D1e)),D1e=t=>t.kind==="literal"?Object.freeze({kind:"literal",text:t.text}):Object.freeze({kind:"expression",operator:t.operator,vars:Object.freeze(t.vars.map(N1e))}),N1e=t=>Object.freeze({name:t.name,explode:t.explode,...t.prefix==null?{}:{prefix:t.prefix}}),z1e=()=>{},M1e=({strict:t,report:e})=>(e??=z1e,t??=!0,e=t?U1e(e):e,{strict:t,report:e}),U1e=t=>e=>{throw t(e),e};var ac=class extends Error{constructor(r,o){super(o);this.code=r}code};function L1e(t,e){return!t.when||e[t.when.field]===void 0||t.when.values.includes(e[t.when.field])}function F$(t,e,r={}){let o=(i,s)=>{throw new ac(i,s)},n={...r,...e};for(let i of t)n[i.name]===void 0&&i.defaultValue!==void 0&&(n[i.name]=i.defaultValue);for(let i of t){if(!L1e(i,n)){delete n[i.name];continue}i.required!==!1&&!n[i.name]&&o("missing_field","Complete the required service fields."),n[i.name]?.includes("\0")&&o("invalid_field","Check the service fields."),i.choices&&n[i.name]&&!i.choices.some(s=>s.value===n[i.name])&&o("invalid_field","Choose an available service setting."),i.pattern&&(i.pattern.length>200||!(0,hJ.default)(i.pattern))&&o("invalid_pattern","Use a simple field validation pattern."),i.pattern&&n[i.name]&&!new RegExp(i.pattern,"u").test(n[i.name].slice(0,1e3))&&o("invalid_field","Check the service fields.")}return Object.keys(e).some(i=>!t.some(s=>s.name===i))&&o("invalid_field","Remove unrecognized service fields."),n}function Us(t,e,r={}){let o=F$(t,e,r),n={};for(let i of t){let s=i.choices?.find(a=>a.value===o[i.name]);for(let[a,c]of Object.entries(s?.values??{})){if(t.some(u=>u.name===a)||a in n&&n[a]!==c)throw new ac("invalid_field","Use distinct values for each service setting.");n[a]=c}}return{...o,...n}}function q$(t,e){for(let[r,o]of Object.entries(e)){let n=t.find(i=>i.name===r);if(!n)throw new ac("invalid_field","Use the fields declared by the connection method.");if(n.secret!==!1&&o!=="")throw new ac("encrypted_input_required","Supply private material directly with your encryption keys.")}return F$(t.map(r=>({...r,required:!1,defaultValue:void 0})),e)}function fo(t,e){return q$(t,Object.fromEntries(t.filter(r=>r.secret===!1&&e[r.name]).map(r=>[r.name,e[r.name]])))}function jf(t,e,r){q$(t,e);for(let[o,n]of Object.entries(e))if(n&&r[o]!==void 0&&r[o]!==n)throw new ac("operation_changed","Use the service settings prepared by this operation.");return{...e,...r}}function gJ(t,e=Wy(t)){return e.accountVerified?e.accountId:null}function yJ(t,e=Wy(t)){let o=(t.method.kind==="oauth"||t.method.kind==="ovh"||t.method.kind==="token"&&!!(t.method.config.identity||t.method.config.resolver||t.method.config.bindFields))&&t.method.kind!=="aws"?fo(t.method.config.fields,t.fields??{}):{};return{format:t.format,generation:t.generation,methodId:t.methodId,method:t.method,appId:t.appId,appGeneration:t.appGeneration,..."implicitApp"in t&&t.implicitApp?{implicitApp:{clientId:t.implicitApp.clientId,generation:t.implicitApp.generation,fields:t.implicitApp.fields}}:{},account:e.accountId,accountVerified:e.accountVerified,scopes:[...e.scopes].sort(),...Object.keys(o).length?{fields:o}:{},...e.authorization,...t.state?{state:t.state}:{}}}var hu=m.record(m.string().max(100),m.string().max(16384)),Zn=m.object({format:m.literal(1),methodId:m.string().min(1),generation:E,clientId:m.string().max(1e3),clientSecret:m.string().max(16384).optional(),fields:hu}).strict(),mj=m.object({accessToken:m.string().min(1).max(16384),refreshToken:m.string().min(1).max(16384).optional(),expiresAt:m.number().nullable(),refreshExpiresAt:m.number().optional(),scopes:m.array(m.string()),requestedScopes:m.array(m.string()).optional(),account:m.string(),accountName:m.string(),accountVerified:m.boolean().optional(),scopesStatus:m.enum(["unknown","requested","reported"]).optional(),extra:hu,facts:Lt}).strict(),tv={format:m.literal(2),methodId:m.string().min(1),method:nu,generation:E,appId:E.nullable(),appGeneration:E.nullable(),state:m.literal("reconnect").optional()},cc=m.never().optional(),$n=m.union([m.object({...tv,method:r$,oauth:mj.optional(),requestedScopes:m.array(m.string()).optional(),implicitApp:Zn.optional(),fields:hu.optional(),aws:cc}).strict(),m.object({...tv,method:n$,fields:hu,facts:du.optional(),oauth:cc,aws:cc}).strict(),m.object({...tv,method:s$,fields:hu,oauth:cc,aws:cc}).strict(),m.object({...tv,method:i$,fields:hu,ovh:Cy.optional(),requestedScopes:m.array(m.string()).optional(),oauth:cc,aws:cc}).strict(),m.object({...tv,method:o$,aws:WE,oauth:cc,fields:cc}).strict()]).superRefine((t,e)=>{if("implicitApp"in t&&t.implicitApp&&(t.method.kind!=="oauth"||t.method.config.application!=="implicit"||t.implicitApp.methodId!==t.methodId)&&e.addIssue({code:"custom",message:"Keep the registered client with its implicit OAuth connection."}),t.method.kind==="oauth"&&t.fields)try{q$(t.method.config.fields,t.fields)}catch{e.addIssue({code:"custom",path:["fields"],message:"Keep only declared public settings in the connection."})}lu(t.method)&&(!t.appId||!t.appGeneration)&&e.addIssue({code:"custom",message:"Bind the application required by this connection."}),!lu(t.method)&&t.appId!==null&&e.addIssue({code:"custom",message:"Use an application only when the connection requires one."}),!!t.appId!=!!t.appGeneration&&e.addIssue({code:"custom",message:"Bind the application and its generation together."}),t.method.kind==="oauth"&&t.method.config.grantType==="client_credentials"&&!("requestedScopes"in t&&t.requestedScopes)&&!t.oauth?.requestedScopes&&e.addIssue({code:"custom",message:"Keep the selected scopes for client credentials renewal."})}),rSt=m.object({methodId:m.string().min(1).max(200),clientId:m.string().max(1e3),generation:E,fields:hu.optional()}).strict(),j1e=m.object({methodId:m.string().min(1).max(200),methodKind:kL,generation:E,authorizationDigest:xr,appId:E.nullable(),accountId:m.string().max(2e3).nullable(),accountVerified:m.boolean(),scopes:m.array(m.string().max(1e3)).max(200),scopesStatus:m.enum(["unknown","requested","reported"]),outputs:m.array(m.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/)).max(100),state:m.enum(["ready","reconnect"]),revocable:m.literal(!0).optional(),fields:hu.optional(),aws:JE.optional(),ovh:Cy.optional()}).strict();async function Ff(t,e=Wy(t)){let{outputs:r,revocable:o}=dr(t.method),n=t.method.kind!=="aws"&&t.fields?fo(t.method.config.fields,t.fields):{},i=await Q(yJ(t,e));return j1e.parse({methodId:t.methodId,methodKind:t.method.kind,generation:t.generation,authorizationDigest:i,appId:t.appId,accountId:gJ(t,e),accountVerified:e.accountVerified,scopes:e.scopes,scopesStatus:e.scopesStatus,outputs:r,state:t.state??"ready",...o?{revocable:o}:{},...Object.keys(n).length?{fields:n}:{},...e.details})}var F1e=m.array(m.object({name:m.string(),label:m.string(),value:m.string()}).strict()),vJ=m.object({methodName:fe,account:m.string().max(2e3),settings:F1e.optional()}).strict();function V$(t){let e=dr(t.method).fields,r=t.method.kind!=="aws"&&t.fields?fo(e,t.fields):{},o=e.filter(n=>r[n.name]).map(n=>({name:n.name,label:n.label,value:n.choices?.find(i=>i.value===r[n.name])?.label??r[n.name]}));return{methodName:t.method.name,account:"",...o.length?{settings:o}:{}}}var hj=m.discriminatedUnion("action",[m.object({action:m.literal("refresh"),id:E}).strict(),m.object({action:m.literal("revoke"),id:E}).strict()]);var gj=Ns.extend({name:fe}),dSt=m.object({bootstrap:m.string().regex(/^[A-Za-z0-9_-]{43}$/),binding:Ns,token:m.string().regex(/^fk_[A-Za-z0-9_-]{43}$/)}).strict(),wJ=m.object({id:E,executorId:E,ownerId:E,name:fe,origin:m.url(),bootstrap:m.string().regex(/^[A-Za-z0-9_-]{43}$/),ssh:m.object({port:m.number().int().min(1).max(65535)}).strict().optional(),commandImage:m.string().regex(/^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/)}).strict(),pSt=Ns.extend({previousSignature:cr.optional()}).strict(),_J=m.object({name:fe,content:tn,labels:vJ.optional(),version:m.number().int().positive().optional()}).strict(),rv=m.object({content:tn,version:m.number().int().positive()}).strict(),bJ=m.object({id:E,reason:m.enum(["grantExpired","recipients"]),remove:m.array(E).max(1e3).default([])}).strict(),fSt=m.record(E,m.object({version:m.number().int().positive(),content:tn}).strict()),SJ=m.object({id:E,name:fe,version:m.number().int().positive(),content:tn,policy:en}).strict(),xJ=m.object({registration:qL,stoppedAt:m.iso.datetime().nullable(),heartbeatAt:m.iso.datetime().nullable()}).strict(),EJ=m.object({lease:E,request:kf,sources:m.array(tn).max(100)}).strict().nullable(),q1e=m.object({lease:E}).strict(),mSt=q1e.extend({receipt:Hy}).strict(),nv=m.object({id:E,resource_id:E,executor_id:E,expected_revision:m.number().int().positive(),state:m.enum(["prepared","in_flight","committed","uncertain","aborted"]),fence:m.string().regex(/^\d+$/),result:tn.nullable()}),hSt=m.object({id:E,resourceId:E,expectedRevision:m.number().int().positive()}).strict(),V1e=m.object({fence:m.string().regex(/^\d+$/)}).strict(),gSt=V1e.extend({content:tn}).strict(),ySt=m.object({id:E,executionId:E,index:m.number().int().nonnegative(),stateDigest:xr,expiresAt:$e}).strict(),yj=m.object({id:E,executionId:E,context:m.string(),sealed:Ao.nullable(),expiresAt:$e,receivedAt:$e.nullable()}).strict(),$J=(t,e)=>"oauth-callback:"+t+":"+e;var G1e=m.object({binding:Kt,verifiedAt:$e}).strict(),vj=m.object({origin:m.url(),ownerId:E,signerId:E,revision:m.number().int().positive(),keys:m.array(G1e).max(1e3)}).strict(),H1e=m.object({version:m.number().int().positive(),signature:cr}).strict(),wj=m.object({keyring:H1e.nullable()}).strict(),xSt=m.object({version:m.number().int().positive().nullable(),signature:cr}).strict();function RJ(t,e){return ir(vj.parse(t),e,"keyring")}function IJ(t){return vj.parse(JSON.parse(Kn(d$(t.split(".")[1]??""))))}async function AJ(t,e){let r=vj.parse(await Ly(t,e.signing,"keyring"));if(r.signerId!==e.id)throw new Error("Another identity signed this keyring.");return r}var oi=class extends Error{constructor(r,o){super(o);this.code=r}code},bj=class extends Error{constructor(r){super("The execution request has been saved. Check execution "+r+" before starting another operation.");this.id=r}id},_j=(t,...e)=>!!t&&typeof t=="object"&&("code"in t&&e.includes(String(t.code))||"status"in t&&e.includes(Number(t.status))),G$=class{constructor(e,r,o,n,i){this.api=e;this.origin=r;this.binding=o;this.keys=n;this.trust=i}api;origin;binding;keys;trust;verifiedKeys;async trusted(e){if(!await this.verifies(e))throw new oi("identity_untrusted","Verify and trust the encryption and signing keys for identity "+e.principalId+" before sharing.");return e}async verifies(e){if(e.principalId===this.binding.principalId)return C(this.binding)===C(e);let r=(await this.keyring()).get(e.principalId)?.binding??await this.trust.binding(e.principalId);return!!r&&C(r)===C(e)}async verifiedIdentity(e){return this.verifies((await this.inspectIdentity(e)).binding)}keyring(){return this.verifiedKeys??=this.loadKeyring().catch(e=>{throw this.verifiedKeys=void 0,e})}async loadKeyring(){let e;try{e=(await this.readKeyring()).keyring?.keys??[]}catch(i){if(_j(i,401,403))return new Map;throw i}let r=new Set(e.map(i=>i.binding.principalId)),o=new Date().toISOString(),n=(await this.trust.bindings()).filter(i=>i.principalId!==this.binding.principalId&&!r.has(i.principalId));if(n.length)try{e=(await this.changeKeyring(i=>[...i,...n.filter(s=>!i.some(a=>a.binding.principalId===s.principalId)).map(s=>({binding:s,verifiedAt:o}))])).keys}catch(i){if(i instanceof oi)throw i}return new Map(e.map(i=>[i.binding.principalId,i]))}async readKeyring(){let e="/api/principals/"+this.binding.principalId+"/keyring",{keyring:r}=await this.api.json(e,{},wj),o=await this.trust.keyring(),n=()=>new oi("keyring_conflict","The list of verified public keys does not match what this device saw before.");if(!r){if(o)throw n();return{version:null,revision:0,keyring:null}}let i=IJ(r.signature);if(i.signerId!==this.binding.id)return{version:r.version,revision:i.revision,keyring:null};let s=await AJ(r.signature,this.binding).catch(()=>{throw n()}),a=await Q(s);if(s.ownerId!==this.binding.principalId||s.origin!==this.origin||o&&(s.revision<o.revision||s.revision===o.revision&&a!==o.digest))throw n();return(!o||s.revision>o.revision)&&await this.trust.rememberKeyring({revision:s.revision,digest:a}),{version:r.version,revision:s.revision,keyring:s}}async changeKeyring(e){for(let r=1;;r++){let o=await this.readKeyring(),n={origin:this.origin,ownerId:this.binding.principalId,signerId:this.binding.id,revision:o.revision+1,keys:e(o.keyring?.keys??[])};try{await this.api.json("/api/principals/"+this.binding.principalId+"/keyring",{method:"PUT",body:{version:o.version,signature:await RJ(n,this.keys.signing)}},wj)}catch(i){if(r<3&&_j(i,"changed"))continue;throw i}return await this.trust.rememberKeyring({revision:n.revision,digest:await Q(n)}),n}}async inspectIdentity(e){let r=await this.api.json("/api/identities/"+E.parse(e)+"/binding",{},Ns);return await g$(r),{...r,fingerprint:await Ya(r.binding)}}async trustIdentity(e,r){let o=await this.inspectIdentity(e);if(o.fingerprint!==r)throw new oi("fingerprint_mismatch","The identity fingerprint does not match.");if(e===this.binding.principalId||C((await this.keyring()).get(e)?.binding??null)===C(o.binding))return o;let n=new Date().toISOString();try{let i=await this.changeKeyring(s=>[...s.filter(a=>a.binding.principalId!==e),{binding:o.binding,verifiedAt:n}]);this.verifiedKeys=Promise.resolve(new Map(i.keys.map(s=>[s.binding.principalId,s])))}catch(i){if(!_j(i,401,403))throw i;await this.trust.rememberBinding(o.binding)}return o}async environment(e,r=!0){let{registration:o,stoppedAt:n}=await this.api.json("/api/environments/"+E.parse(e)+"/registration",{},xJ);if(await Cf(o),o.manifest.origin!==this.origin||o.manifest.id!==e||n)throw new Error("Choose an active execution environment on this Foundation server.");return r&&await this.trusted(o.manifest.executor),o}async recipients(e){let{items:r}=await this.api.json("/api/principals/"+E.parse(e)+"/bound-recipients",{},Mr(gj));if(!r.length)throw new Error("Set up an encryption key for the owner before saving private content.");for(let{name:i,...s}of r)await g$(s),await this.trusted(s.binding);let o=await this.api.json("/api/principals/"+E.parse(e)+"/bound-agents",{},Mr(gj)),n=[];for(let{name:i,...s}of o.items){await g$(s);try{n.push(await this.trusted(s.binding))}catch(a){if(!(a instanceof oi&&a.code==="identity_untrusted"))throw a}}return[...r.map(i=>i.binding),...n]}async read(e){let r=await this.api.json("/api/custody/"+E.parse(e),{},rv);return await this.observe(r.content,e),r}async observe(e,r=e.policy.id){let o=await ko(e);if(o.policy.id!==r||o.policy.origin!==this.origin)throw new Error("The encrypted content belongs to another item.");let n=LL(o);await this.trusted(n);let i=await this.trust.checkpoint(o);if(i&&en.parse(i.policy),i){if(o.policy.revision<i.policy.revision||o.materialRevision<i.materialRevision||o.policy.revision===i.policy.revision&&C(o.policy)!==C(i.policy)||o.materialRevision===i.materialRevision&&await Q(o)!==i.digest)throw new oi("content_conflict","The encrypted content is older than this device has already observed.");if(o.policy.revision>i.policy.revision&&!w$(i.policy,o))throw new oi("content_conflict","An existing policy authority must approve the new recipients.")}return await this.trust.rememberContent(o),o}async reveal(e){return cd((await this.read(e)).content,this.binding,this.keys.encryption)}async sharing(e){let r=typeof e=="string"?(await this.api.json(e,{},Mr(SJ))).items:e,o={};for(let n of r){let i=await this.read(n.id);if(i.version!==n.version||C(i.content)!==C(n.content))throw new oi("content_conflict","Review the current content before changing its readers.");for(let s of n.policy.readers)await this.trusted(s);o[n.id]={version:n.version,content:await ad(await cd(i.content,this.binding,this.keys.encryption),n.policy,i.content.materialRevision+1,this.binding,this.keys,i.content.metadata,i.content)}}return o}async policy(e,r,o=[],n={}){let i=n.previous?.readers??[...new Map([...await this.recipients(e),this.binding].map(c=>[c.id,c])).values()];if(!i.some(c=>C(c)===C(this.binding)))throw new Error("Include your own identity as a reader before creating this item.");let s=n.expiresAt??new Date(Date.now()+30*864e5).toISOString(),a=n.previous?n.previous.grants.filter(c=>(!("actor"in c)||c.actor.id!==this.binding.id)&&Qa(c)):[];for(let c of o)await this.trusted(c.manifest.executor),a.push({actor:this.binding,executor:c.manifest.executor,operations:[...ou(r)],origins:[],functionDigests:[],callerProgram:r!==he.clientCredential,expiresAt:s});return en.parse({format:2,id:n.id??n.previous?.id??crypto.randomUUID(),origin:this.origin,ownerId:e,contentType:r,revision:(n.previous?.revision??0)+1,authorities:n.previous?.authorities??i,readers:i,grants:a,producers:[]})}async save(e,r,o,n={}){let i=n.previous;i&&C(o)===C({...i.content.policy,revision:o.revision})&&(o={...o,revision:i.content.policy.revision});let s=await ad(r,o,(i?.content.materialRevision??0)+1,this.binding,this.keys,n.metadata,i?.content),a={name:e,content:s,...n.labels?{labels:n.labels}:{},...i?{version:i.version}:{}},c=n.commit?await n.commit(a):await this.api.json("/api/resources/"+o.id+"/custody",{method:"PUT",body:a},Sr);return await this.trust.rememberContent(s),c}async pass(e,r,o,n){let i=await ad(r,o,n.content.materialRevision+1,this.binding,this.keys,n.content.metadata,n.content),s=await this.api.json("/api/resources/"+o.id+"/custody",{method:"PUT",body:{name:e,content:i,version:n.version}},m.union([Sr,Ze]));return"kind"in s&&await this.trust.rememberContent(i),s}async pendingProtection(){return(await this.api.json("/api/principals/"+this.binding.principalId+"/reprotection",{},Mr(bJ))).items}async reprotect(e,r="grantExpired",o=[]){let n=await this.read(e),{policy:i}=n.content,s=Date.now(),a=new Set(o),c=r==="recipients"?await this.recipients(i.ownerId):[],u=S=>!a.has(S.principalId)&&!c.some(x=>x.principalId===S.principalId&&x.id!==S.id),l=i.grants.filter(S=>Qa(S,s)&&u(S.executor)&&(!("actor"in S)||u(S.actor))),d=i.readers.filter(u),p=i.authorities.filter(u),f=c.filter(S=>!d.some(x=>x.id===S.id)),h={...i,revision:i.revision+1,grants:l,producers:[],readers:[...d,...f],authorities:[...p,...f.filter(S=>!p.some(x=>x.id===S.id))],...i.observers?{observers:i.observers.filter(S=>!a.has(S))}:{}},y=i.contentType!==he.executionResult&&i.producers.some(S=>Date.parse(S.expiresAt)>s);if(C({...h,revision:i.revision})===C(i)||y)return null;let w=await cd(n.content,this.binding,this.keys.encryption);if(i.contentType===he.executionResult){let S=await ad(w,h,n.content.materialRevision+1,this.binding,this.keys,n.content.metadata,n.content);return await this.api.json("/api/custody/"+e,{method:"PUT",body:{name:"Execution result",content:S,version:n.version}},rv),await this.trust.rememberContent(S),e}let b=await this.api.json("/api/resources/"+i.id,{},Sr);return this.save(b.name,w,h,{metadata:n.content.metadata,previous:n})}async reprotectPending(){let e=[],r=[];for(let o of await this.pendingProtection())try{await this.reprotect(o.id,o.reason,o.remove)&&e.push(o.id)}catch(n){r.push({id:o.id,code:n&&typeof n=="object"&&"code"in n&&typeof n.code=="string"?n.code:"failure"})}return{done:e,failed:r}}async sourceContents(e){let r=new Map;for(let o of new Set(e))r.set(o,(await this.read(o)).content);for(let o of[...r.values()])o.policy.contentType===he.tokenSet&&typeof o.metadata.appId=="string"&&!r.has(o.metadata.appId)&&r.set(o.metadata.appId,(await this.read(o.metadata.appId)).content);return[...r.values()]}async output(e,r,o,n,i){let s,a=null;do{let l=new URLSearchParams({kind:"variable",query:r,...a?{after:a}:{}}),d=await this.api.json("/api/principals/"+e+"/resources?"+l,{},Mr(Sr));s=d.items.find(p=>p.name===r),a=d.next}while(!s&&a);let c=s?(await this.read(s.id)).content:void 0,u=c?{...c.policy,revision:c.policy.revision+1,producers:[]}:await this.policy(e,he.value);return u.producers=[{executor:n.manifest.executor,runId:o,expiresAt:i,materialRevision:(c?.materialRevision??0)+1}],{name:r,approval:await S$(u,this.binding,this.keys,c)}}async prepare(e,r,o,n={}){let i=ec.parse(o),s=await this.environment(r);await this.trusted(s.manifest.executor);let a=n.id??crypto.randomUUID(),c=n.expiresAt??new Date(Date.now()+36e5).toISOString(),u=i,l=u.kind==="http"?u.request:null;if(i.kind==="http"){let w=n.save??{},b=Object.fromEntries(await Promise.all(Object.entries(w).map(async([S,x])=>[S,await this.output(e,x,a,s,c)])));i.save=b}let d=u.kind==="command"?u.inputs.map(w=>w.source.id):l?l.bindings.flatMap(w=>w.parts.flatMap(b=>typeof b=="string"?[]:[b.id])):[],p=await this.sourceContents([...d,...n.sourceIds??[]]);for(let w=0;w<p.length;w++){let b=p[w],S=b.policy.contentType===he.clientCredential,x=S&&i.kind!=="revoke"?ue.refresh:ue[i.kind],R=S?void 0:l?new URL(l.url).origin:void 0;if(b.policy.grants.some(me=>"actor"in me&&C(me.actor)===C(this.binding)&&C(me.executor)===C(s.manifest.executor)&&me.operations.includes(x)&&Pf(me)>=Date.parse(c)&&(!R||!me.origins.length||me.origins.includes(R))&&(S||me.callerProgram))||!b.policy.authorities.some(me=>C(me)===C(this.binding)))continue;let M=await this.read(b.policy.id),Z=await this.api.json("/api/resources/"+b.policy.id,{},Sr),te={actor:this.binding,executor:s.manifest.executor,operations:[...new Set([x,...b.policy.contentType===he.tokenSet?[ue.refresh]:[]])],origins:R?[R]:[],functionDigests:[],callerProgram:!S,expiresAt:c},Ae=me=>C({...me,expiresAt:null}),Te=M.content.policy.grants.filter(me=>Ae(me)===Ae(te)),bt=en.parse({...M.content.policy,revision:M.content.policy.revision+1,grants:[...M.content.policy.grants.filter(me=>Qa(me)&&Ae(me)!==Ae(te)),{...te,expiresAt:new Date(Math.max(Date.parse(c),...Te.map(me=>Pf(me)))).toISOString()}]});await this.save(Z.name,await cd(M.content,this.binding,this.keys.encryption),bt,{previous:M,metadata:M.content.metadata}),p[w]=(await this.read(b.policy.id)).content}let f=await this.policy(e,he.executionResult,[],{id:a});f.producers=[{executor:s.manifest.executor,runId:a,expiresAt:c,materialRevision:1}];let h={format:2,id:a,origin:this.origin,ownerId:e,actor:this.binding,environmentId:r,executor:s.manifest.executor,environmentDigest:await Q(s.manifest),operation:ue[i.kind],operationDigest:await Q(i),...n.approval?{approval:n.approval}:{},...n.operationContext?{operationContext:n.operationContext}:{},functionDigest:null,sources:await Promise.all(p.map(async w=>({id:w.policy.id,materialRevision:w.materialRevision,policyDigest:await Q(w.policy),...w.policy.contentType===he.tokenSet&&typeof w.metadata.authorizationDigest=="string"?{authorizationDigest:w.metadata.authorizationDigest}:{}}))),resultRecipients:f.readers,...s.manifest.resultVersion?{resultApproval:await S$(f,this.binding,this.keys)}:{},createdAt:new Date().toISOString(),expiresAt:c};await Of(s,h);let y=w=>w.policy.contentType===he.clientCredential;for(let w of p)await ld(w,y(w)&&h.operation!==ue.connect&&h.operation!==ue.revoke?{...h,operation:ue.refresh}:h,y(w)?{}:{destination:l?.url});return d8(h,i,this.keys)}async submit(e,r,o,n={}){return this.submitPrepared(await this.prepare(e,r,o,n))}async submitPrepared(e){await this.trust.rememberRun(e);try{return await this.api.json("/api/runtime/runs",{method:"POST",body:e},Bn)}catch(r){throw r&&typeof r=="object"&&"status"in r?r:new bj(e.intent.id)}}async resume(e){let r=await this.trust.run(E.parse(e));if(!r)throw new Error("Resume this execution from the device that saved its signed request.");if(C(r.intent.actor)!==C(this.binding)||r.intent.origin!==this.origin)throw new Error("Use the identity that signed this execution request.");try{let o=await this.api.json("/api/runtime/runs/"+e,{},Bn);if(C(o.intent)!==C(r.intent)||o.requestSignature!==r.signature)throw new Error("Use the saved request that started this execution.");return o}catch(o){if(!o||typeof o!="object"||!("code"in o)||o.code!=="not_found")throw o}return this.submitPrepared(r)}async result(e){if(e.intent.origin!==this.origin||e.intent.id!==e.id)throw new Error("This execution belongs to another Foundation server.");await this.trusted(e.intent.actor);let r=await Ly(e.requestSignature,e.intent.actor.signing,"run");if(C(r.intent)!==C(e.intent))throw new Error("The result belongs to a different signed request.");if(await this.trusted(e.intent.executor),!(e.receipt&&"content"in e.receipt?e.receipt.content.policy.readers:e.intent.resultRecipients).some(n=>C(n)===C(this.binding)))throw new oi("not_recipient","This identity is not a reader of the execution result.");return e.receipt&&"content"in e.receipt&&await this.observe(e.receipt.content,e.id),e.receipt?v8(e.receipt,e.intent,this.binding.id,this.keys):null}async shareLegacyResult(e){if(!e.receipt||"content"in e.receipt)return e;if(C(e.intent.actor)!==C(this.binding)||C(e.intent.executor)!==C(this.binding))throw new oi("executor_required","The original executor and requester must attest this legacy result.");let r=await this.result(e);if(!r)throw new Error("Wait for this execution to finish before sharing its result.");let o=await this.policy(e.ownerId,he.executionResult,[],{id:e.id});o.producers=[{executor:this.binding,runId:e.id,expiresAt:new Date(Date.now()+36e5).toISOString(),materialRevision:1}];let n=await GL(e.intent,e.receipt.state,r,this.keys,await S$(o,this.binding,this.keys),e.receipt);return this.api.json("/api/runtime/runs/"+e.id+"/result",{method:"PUT",body:{receipt:n}},Bn)}};import{lstat as K1e,mkdir as B1e,readFile as Z1e,readdir as W1e}from"node:fs/promises";import{join as PJ}from"node:path";var kJ=m.string().regex(/^(run|process|invocation|function|connect|refresh|checkpoint|identity|environment|flow)_[A-Za-z0-9_-]{1,100}$/),md=class{constructor(e,r,o,n){this.directory=e;this.origin=r;this.binding=o;this.privateKeys=n}directory;origin;binding;privateKeys;context(e){return C({purpose:"executor-journal",origin:this.origin,bindingId:this.binding.id,id:kJ.parse(e)})}async read(e){let r=this.context(e),o=PJ(this.directory,e+".json");try{let n=await K1e(o);if(!n.isFile()||n.isSymbolicLink()||process.platform!=="win32"&&n.mode&63)throw new Error("The execution journal must use private regular files.");let i=m.string().max(32e6).parse(JSON.parse(await Z1e(o,"utf8"))),s=await Ry(i,await Qo(this.privateKeys.encryption,"ECDH-ES+A256KW"),{keyManagementAlgorithms:["ECDH-ES+A256KW"],contentEncryptionAlgorithms:["A256GCM"]});if(s.protectedHeader.kid!==this.binding.id||s.protectedHeader.ctx!==r)throw new Error("The journal entry belongs to another operation.");let a=JSON.parse(Kn(s.plaintext));if(a.context!==r)throw new Error("The journal entry belongs to another operation.");return await Ur({context:r,value:a.value},a.signature,this.binding.signing,"journal"),a.value}catch(n){if(n instanceof Error&&"code"in n&&n.code==="ENOENT")return null;throw n}}async write(e,r){let o=this.context(e),n={context:o,value:r},i=await ir(n,this.privateKeys.signing,"journal"),s=tt(C({...n,signature:i}));if(s.byteLength>2e7)throw new Error("The execution record is too large.");let a=await new xf(s).setProtectedHeader({alg:"ECDH-ES+A256KW",enc:"A256GCM",kid:this.binding.id,ctx:o}).encrypt(await Qo(this.binding.encryption,"ECDH-ES+A256KW"));await B1e(this.directory,{recursive:!0,mode:448}),await Nf(PJ(this.directory,e+".json"),C(a),!0)}async keys(e){let r;try{r=await W1e(this.directory,{withFileTypes:!0})}catch(o){if(o instanceof Error&&"code"in o&&o.code==="ENOENT")return[];throw o}return r.filter(o=>o.isFile()&&o.name.startsWith(e)&&o.name.endsWith(".json")).map(o=>kJ.parse(o.name.slice(0,-5)))}};var H$=class{constructor(e){this.journal=e}journal;binding(e){return this.journal.read("identity_"+e)}async bindings(){return(await Promise.all((await this.journal.keys("identity_")).map(r=>this.journal.read(r)))).filter(r=>r!==null)}async rememberBinding(e){await zs(e),await this.journal.write("identity_"+e.principalId,e)}keyring(){return this.journal.read("checkpoint_keyring")}async rememberKeyring(e){await this.journal.write("checkpoint_keyring",e)}checkpoint(e){return this.journal.read("checkpoint_"+e.policy.format+"_"+e.policy.id)}async rememberContent(e){await this.journal.write("checkpoint_"+e.policy.format+"_"+e.policy.id,{policy:e.policy,materialRevision:e.materialRevision,digest:await Q(e)})}run(e){return this.journal.read("run_"+e)}async rememberRun(e){let r=await this.run(e.intent.id);if(r&&C(r)!==C(e))throw new Error("Use a new execution ID for a different request.");await this.journal.write("run_"+e.intent.id,e)}};var dt=class extends Error{constructor(r,o,n,i){super(n);this.status=r;this.code=o;this.details=i}status;code;details};function q(t,e,r,o){throw new dt(t,e,r,o)}var K$=class{api;constructor(e){this.api={async json(r,o={},n){try{return await e.json(r,o,n)}catch(i){throw i instanceof Error&&"status"in i&&typeof i.status=="number"&&"code"in i&&typeof i.code=="string"?new dt(i.status,i.code,i.message):i}}}}claim(e){return this.api.json("/api/environments/"+e+"/claim",{method:"POST",body:{}},EJ)}renew(e,r){return this.api.json("/api/runtime/runs/"+e+"/renew",{method:"POST",body:{lease:r}},m.object({active:m.boolean()}))}dispatch(e,r){return this.api.json("/api/runtime/runs/"+e+"/dispatch",{method:"POST",body:{lease:r}})}finish(e,r){return this.api.json("/api/runtime/runs/"+r.id+"/finish",{method:"POST",body:{lease:e,receipt:r}},Bn)}capture(e,r,o){return this.api.json("/api/executor/outputs",{method:"POST",body:{name:e,content:r,...o?{labels:o}:{}}},m.object({id:E}))}connections(){let e=this.api;return{prepare:(r,o,n)=>e.json("/api/connection-operations",{method:"POST",body:{id:r,resourceId:o,expectedRevision:n}},nv),dispatch:(r,o)=>e.json("/api/connection-operations/"+r+"/dispatch",{method:"POST",body:{fence:o}},nv),commit:(r,o,n)=>e.json("/api/connection-operations/"+r+"/commit",{method:"POST",body:{fence:o,content:n}},tn),uncertain:(r,o)=>e.json("/api/connection-operations/"+r+"/uncertain",{method:"POST",body:{fence:o}}),abort:(r,o)=>e.json("/api/connection-operations/"+r+"/abort",{method:"POST",body:{fence:o}},nv),state:r=>e.json("/api/connections/"+r+"/operation",{},nv.nullable())}}};import{randomUUID as SHe}from"node:crypto";var Sc=Vt(LV(),1);import{randomUUID as mGe}from"node:crypto";function mde(t){let e=ZE.safeParse({accountId:t.Account,arn:t.Arn,principalId:t.Arn?.includes(":assumed-role/")?t.UserId?.split(":")[0]:t.UserId});return(!e.success||e.data.arn.split(":")[4]!==e.data.accountId)&&q(502,"invalid_response","The AWS account could not be verified."),e.data}function hde(t,e){return t.accountId===e.accountId&&t.principalId===e.principalId&&Ef(t.arn)===Ef(e.arn)}function jV(t){t&&(!Number.isFinite(t.getTime())||t.getTime()<=Date.now())&&q(409,"reconnect_required","Reconnect with current AWS credentials.")}var fk=class{async obtain(e,r,o){let n=Ba.parse({authentication:e.authentication,region:e.region,...e.role?{role:e.role}:{}}),i=n.authentication,s=i.kind==="environment"?void 0:{accessKeyId:i.accessKeyId,secretAccessKey:i.secretAccessKey,...i.kind==="session"?{sessionToken:i.sessionToken,expiration:new Date(i.expiresAt)}:{}};jV(s?.expiration);let a=new Sc.STSClient({region:n.region,...s?{credentials:s}:{}}),c,u=AbortSignal.any([AbortSignal.timeout(2e4),...o?[o]:[]]),l=!1;try{let d=s??await a.config.credentials();jV(d.expiration),c=new Sc.STSClient({region:n.region,credentials:d});let p=r?.sourceIdentity?mde(await c.send(new Sc.GetCallerIdentityCommand({}),{abortSignal:u})):void 0;r?.sourceIdentity&&p&&!hde(p,r.sourceIdentity)&&q(409,"account_changed","Reconnect to approve the current AWS authentication source.");let f=d,h=p;if(n.role){l=!0;let b=(await c.send(new Sc.AssumeRoleCommand({RoleArn:n.role.arn,RoleSessionName:"foundation-"+mGe().slice(0,8),DurationSeconds:3600,...n.role.externalId?{ExternalId:n.role.externalId}:{}}),{abortSignal:u})).Credentials;(!b?.AccessKeyId||!b.SecretAccessKey||!b.SessionToken||!b.Expiration)&&q(502,"invalid_response","AWS did not return credentials."),f={accessKeyId:b.AccessKeyId,secretAccessKey:b.SecretAccessKey,sessionToken:b.SessionToken,expiration:b.Expiration},jV(f.expiration),r?.identity&&(c.destroy(),c=new Sc.STSClient({region:n.region,credentials:f}),h=mde(await c.send(new Sc.GetCallerIdentityCommand({}),{abortSignal:u})))}return r?.identity&&h&&!hde(h,r.identity)&&q(409,"account_changed","Reconnect to approve the current AWS account and role."),{state:WE.parse({...n,sourceIdentity:p,identity:h}),credentials:{AWS_ACCESS_KEY_ID:f.accessKeyId,AWS_SECRET_ACCESS_KEY:f.secretAccessKey,AWS_SESSION_TOKEN:f.sessionToken??"",AWS_DEFAULT_REGION:n.region,AWS_REGION:n.region}}}catch(d){if(d instanceof dt)throw d;o?.aborted&&q(409,"cancelled","The operation was cancelled."),d instanceof Error&&["ExpiredToken","ExpiredTokenException","TokenRefreshRequired"].includes(d.name)&&q(409,"reconnect_required","Reconnect with current AWS credentials."),l&&q(502,"role_denied","Check the IAM role and its trust policy for this authentication source."),q(502,"aws_authentication_failed","Check the AWS credentials available to the selected environment.")}finally{c?.destroy(),a.destroy()}}};var mk=class{constructor(e){this.aws=e}aws;facts=XL;needsRenewal(){return!1}async outputs(e,r,o){return(await this.aws.obtain(e.aws,e.aws,o)).credentials}};var FV;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(FV="oauth4webapi/v3.8.8");function bk(t,e){if(t==null)return!1;try{return t instanceof e||Object.getPrototypeOf(t)[Symbol.toStringTag]===e.prototype[Symbol.toStringTag]}catch{return!1}}var Ea="ERR_INVALID_ARG_VALUE",xc="ERR_INVALID_ARG_TYPE";function Or(t,e,r){let o=new TypeError(t,{cause:r});return Object.assign(o,{code:e}),o}var vde=Symbol(),hGe=Symbol(),gGe=Symbol(),JV=Symbol();var hk=Symbol();var yGe=new TextEncoder,vGe=new TextDecoder;function qV(t){return typeof t=="string"?yGe.encode(t):vGe.decode(t)}var VV;Uint8Array.prototype.toBase64?VV=t=>(t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t.toBase64({alphabet:"base64url",omitPadding:!0})):VV=e=>{e instanceof ArrayBuffer&&(e=new Uint8Array(e));let r=[];for(let o=0;o<e.byteLength;o+=32768)r.push(String.fromCharCode.apply(null,e.subarray(o,o+32768)));return btoa(r.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var GV;Uint8Array.fromBase64?GV=t=>{try{return Uint8Array.fromBase64(t,{alphabet:"base64url"})}catch(e){throw Or("The input to be decoded is not correctly encoded.",Ea,e)}}:GV=t=>{try{let e=atob(t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),r=new Uint8Array(e.length);for(let o=0;o<e.length;o++)r[o]=e.charCodeAt(o);return r}catch(e){throw Or("The input to be decoded is not correctly encoded.",Ea,e)}};function HV(t){return typeof t=="string"?GV(t):VV(t)}var lh=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=JGe,Error.captureStackTrace?.(this,this.constructor)}},c_=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,r?.code&&(this.code=r?.code),Error.captureStackTrace?.(this,this.constructor)}};function De(t,e,r){return new c_(t,{code:e,cause:r})}function gk(t){return!(t===null||typeof t!="object"||Array.isArray(t))}function wde(t){bk(t,Headers)&&(t=Object.fromEntries(t.entries()));let e=new Headers(t??{});if(FV&&!e.has("user-agent")&&e.set("user-agent",FV),e.has("authorization"))throw Or('"options.headers" must not include the "authorization" header name',Ea);return e}function wGe(t,e){if(e!==void 0){if(typeof e=="function"&&(e=e(t.href)),!(e instanceof AbortSignal))throw Or('"options.signal" must return or be an instance of AbortSignal',xc);return e}}function yk(t,e,r,o,n){try{if(typeof t!="number"||!Number.isFinite(t))throw Or(`${r} must be a number`,xc,n);if(t>0)return;if(e){if(t!==0)throw Or(`${r} must be a non-negative number`,Ea,n);return}throw Or(`${r} must be a positive number`,Ea,n)}catch(i){throw o?De(i.message,o,n):i}}function On(t,e,r,o){try{if(typeof t!="string")throw Or(`${e} must be a string`,xc,o);if(t.length===0)throw Or(`${e} must not be empty`,Ea,o)}catch(n){throw r?De(n.message,r,o):n}}function _de(t){bGe(t,"application/json")}function _Ge(t,...e){let r='"response" content-type must be ';if(e.length>2){let o=e.pop();r+=`${e.join(", ")}, or ${o}`}else e.length===2?r+=`${e[0]} or ${e[1]}`:r+=e[0];return De(r,YGe,t)}function bGe(t,e){if(NGe(t)!==e)throw _Ge(t,e)}async function bde(t){return On(t,"codeVerifier"),HV(await crypto.subtle.digest("SHA-256",qV(t)))}function Sde(t){let e=t?.[hGe];return typeof e=="number"&&Number.isFinite(e)?e:0}function xde(t){let e=t?.[gGe];return typeof e=="number"&&Number.isFinite(e)&&Math.sign(e)!==-1?e:30}function Ede(){return Math.floor(Date.now()/1e3)}function ph(t){if(typeof t!="object"||t===null)throw Or('"as" must be an object',xc);On(t.issuer,'"as.issuer"')}function fh(t){if(typeof t!="object"||t===null)throw Or('"client" must be an object',xc);On(t.client_id,'"client.client_id"')}function gde(t){return encodeURIComponent(t).replace(/(?:[-_.!~*'()]|%20)/g,e=>{switch(e){case"-":case"_":case".":case"!":case"~":case"*":case"'":case"(":case")":return`%${e.charCodeAt(0).toString(16).toUpperCase()}`;case"%20":return"+";default:throw new Error}})}function $de(t){return On(t,'"clientSecret"'),(e,r,o,n)=>{o.set("client_id",r.client_id),o.set("client_secret",t)}}function Rde(t){return On(t,'"clientSecret"'),(e,r,o,n)=>{let i=gde(r.client_id),s=gde(t),a=btoa(`${i}:${s}`);n.set("authorization",`Basic ${a}`)}}function Ide(){return(t,e,r,o)=>{r.set("client_id",e.client_id)}}var SGe=URL.parse?(t,e)=>URL.parse(t,e):(t,e)=>{try{return new URL(t,e)}catch{return null}};function xGe(t,e){if(e&&t.protocol!=="https:")throw De("only requests to HTTPS are allowed",eHe,t);if(t.protocol!=="https:"&&t.protocol!=="http:")throw De("only HTTP and HTTPS requests are allowed",tHe,t)}function yde(t,e,r,o){let n;if(typeof t!="string"||!(n=SGe(t)))throw De(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${e}"`:`"as.${e}"`}`,t===void 0?rHe:nHe,{attribute:r?`mtls_endpoint_aliases.${e}`:e});return xGe(n,o),n}function Ade(t,e,r,o){return r&&t.mtls_endpoint_aliases&&e in t.mtls_endpoint_aliases?yde(t.mtls_endpoint_aliases[e],e,r,o):yde(t[e],e,r,o)}var KV=class extends Error{cause;code;error;status;error_description;response;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=WGe,this.cause=r.cause,this.error=r.cause.error,this.status=r.response.status,this.error_description=r.cause.error_description,Object.defineProperty(this,"response",{enumerable:!1,value:r.response}),Error.captureStackTrace?.(this,this.constructor)}},u_=class extends Error{cause;code;error;error_description;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=XGe,this.cause=r.cause,this.error=r.cause.get("error"),this.error_description=r.cause.get("error_description")??void 0,Error.captureStackTrace?.(this,this.constructor)}},BV=class extends Error{cause;code;response;status;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=ZGe,this.cause=r.cause,this.status=r.response.status,this.response=r.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},vk="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",EGe="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",$Ge='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',RGe="("+vk+")\\s*=\\s*"+$Ge,IGe="("+vk+")\\s*=\\s*("+vk+")",AGe=new RegExp("^[,\\s]*("+vk+")"),PGe=new RegExp("^[,\\s]*"+RGe+"[,\\s]*(.*)"),kGe=new RegExp("^[,\\s]*"+IGe+"[,\\s]*(.*)"),TGe=new RegExp("^("+EGe+")(?:$|[,\\s])(.*)");function CGe(t){if(!bk(t,Response))throw Or('"response" must be an instance of Response',xc);let e=t.headers.get("www-authenticate");if(e===null)return;let r=[],o=e;for(;o;){let n=o.match(AGe),i=n?.[1].toLowerCase();if(!i)return;let s=o.substring(n[0].length);if(s&&!s.match(/^[\s,]/))return;let a=s.match(/^\s+(.*)$/),c=!!a;o=a?a[1]:void 0;let u={},l;if(c)for(;o;){let p,f;if(n=o.match(PGe)){[,p,f,o]=n,f.includes("\\")&&(f=f.replace(/\\([\s\S])/g,"$1")),u[p.toLowerCase()]=f;continue}if(n=o.match(kGe)){[,p,f,o]=n,u[p.toLowerCase()]=f;continue}if(n=o.match(TGe)){if(Object.keys(u).length)break;[,l,o]=n;break}return}else o=s||void 0;let d={scheme:i,parameters:u};l&&(d.token68=l),r.push(d)}if(r.length)return r}async function OGe(t){if(t.status>399&&t.status<500){Hde(t),_de(t);try{let e=await t.clone().json();if(gk(e)&&typeof e.error=="string"&&e.error.length)return e}catch{}}}async function Pde(t,e,r){if(t.status!==e){MGe(t);let o;throw(o=await OGe(t))?(await t.body?.cancel(),new KV("server responded with an error in the response body",{cause:o,response:t})):De(`"response" is not a conform ${r} response (unexpected HTTP status code)`,QGe,t)}}function DGe(t){if(!YV.has(t))throw Or('"options.DPoP" is not a valid DPoPHandle',Ea)}function NGe(t){return t.headers.get("content-type")?.split(";")[0]}async function kde(t,e,r,o,n,i,s){return await r(t,e,n,i),i.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(s?.[JV]||fetch)(o.href,{body:n,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:wGe(o,s?.signal)})}async function XV(t,e,r,o,n,i){let s=Ade(t,"token_endpoint",e.use_mtls_endpoint_aliases,i?.[vde]!==!0);n.set("grant_type",o);let a=wde(i?.headers);a.set("accept","application/json"),i?.DPoP!==void 0&&(DGe(i.DPoP),await i.DPoP.addProof(s,a,"POST"));let c=await kde(t,e,r,s,n,a,i);return i?.DPoP?.cacheNonce(c,s),c}async function Tde(t,e,r,o,n){ph(t),fh(e),On(o,'"refreshToken"');let i=new URLSearchParams(n?.additionalParameters);return i.set("refresh_token",o),XV(t,e,r,"refresh_token",i,n)}var Cde=new WeakMap,zGe=new WeakMap;function Ode(t){if(!t.id_token)return;let e=Cde.get(t);if(!e)throw Or('"ref" was already garbage collected or did not resolve from the proper sources',Ea);return e}async function Sk(t,e,r,o,n,i){if(ph(t),fh(e),!bk(r,Response))throw Or('"response" must be an instance of Response',xc);await Pde(r,200,"Token Endpoint"),Hde(r);let s=await cHe(r);if(On(s.access_token,'"response" body "access_token" property',Mt,{body:s}),On(s.token_type,'"response" body "token_type" property',Mt,{body:s}),s.token_type=s.token_type.toLowerCase(),s.expires_in!==void 0){let a=typeof s.expires_in!="number"?parseFloat(s.expires_in):s.expires_in;yk(a,!0,'"response" body "expires_in" property',Mt,{body:s}),s.expires_in=a}if(s.refresh_token!==void 0&&On(s.refresh_token,'"response" body "refresh_token" property',Mt,{body:s}),s.scope!==void 0&&typeof s.scope!="string")throw De('"response" body "scope" property must be a string',Mt,{body:s});if(s.id_token!==void 0){On(s.id_token,'"response" body "id_token" property',Mt,{body:s});let a=[];e.require_auth_time===!0&&a.push("auth_time"),e.default_max_age!==void 0&&(yk(e.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),o?.length&&a.push(...o);let{claims:c,jwt:u}=await VGe(t,e,s.id_token,a,n);HGe(e,c),GGe(c),zGe.set(r,u),Cde.set(s,c)}if(i?.[s.token_type]!==void 0)i[s.token_type](r,s);else if(s.token_type!=="dpop"&&s.token_type!=="bearer")throw new lh("unsupported `token_type` value",{cause:{body:s}});return s}function MGe(t){let e;if(e=CGe(t))throw new BV("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:e,response:t})}async function Dde(t,e,r,o){return Sk(t,e,r,void 0,o?.[hk],o?.recognizedTokenTypes)}function UGe(t,e){if(Array.isArray(e.claims.aud)){if(!e.claims.aud.includes(t))throw De('unexpected JWT "aud" (audience) claim value',dh,{expected:t,claims:e.claims,claim:"aud"})}else if(e.claims.aud!==t)throw De('unexpected JWT "aud" (audience) claim value',dh,{expected:t,claims:e.claims,claim:"aud"});return e}function LGe(t,e){let r=t[uHe]?.(e)??t.issuer;if(e.claims.iss!==r)throw De('unexpected JWT "iss" (issuer) claim value',dh,{expected:r,claims:e.claims,claim:"iss"});return e}var YV=new WeakSet;function jGe(t){return YV.add(t),t}var QV=Symbol();async function Nde(t,e,r,o,n,i,s){if(ph(t),fh(e),!YV.has(o))throw Or('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',Ea);On(n,'"redirectUri"');let a=Wd(o,"code");if(!a)throw De('no authorization code in "callbackParameters"',Mt);let c=new URLSearchParams(s?.additionalParameters);return c.set("redirect_uri",n),c.set("code",a),i!==QV&&(On(i,'"codeVerifier"'),c.set("code_verifier",i)),XV(t,e,r,"authorization_code",c,s)}var zde={aud:"audience",c_hash:"code hash",client_id:"client id",exp:"expiration time",iat:"issued at",iss:"issuer",jti:"jwt id",nonce:"nonce",s_hash:"state hash",sub:"subject",ath:"access token hash",htm:"http method",htu:"http uri",cnf:"confirmation",auth_time:"authentication time"};function FGe(t,e){for(let r of t)if(e.claims[r]===void 0)throw De(`JWT "${r}" (${zde[r]}) claim missing`,Mt,{claims:e.claims});return e}function qGe(t,e){if(typeof e.claims[t]!="string")throw De(`unexpected JWT "${t}" (${zde[t]}) claim type`,Mt,{claims:e.claims});return e}function VGe(t,e,r,o,n){return oHe(r,iHe.bind(void 0,e.id_token_signed_response_alg,t.id_token_signing_alg_values_supported,"RS256"),Sde(e),xde(e),n).then(FGe.bind(void 0,["aud","exp","iat","iss","sub",...o])).then(LGe.bind(void 0,t)).then(UGe.bind(void 0,e.client_id)).then(qGe.bind(void 0,"sub"))}function Mde(t,e){if(e===_k)return e;let r=e===void 0;return r&&(e=t.default_max_age),e===void 0?_k:(yk(e,!0,r?'"client.default_max_age"':'"maxAge" argument'),e)}function GGe(t){t.auth_time!==void 0&&yk(t.auth_time,!0,'ID Token "auth_time" (authentication time)',Mt,{claims:t})}function Ude(t,e,r){if(r===_k)return;let o=Ede()+Sde(t),n=xde(t);if(e.auth_time+r<o-n)throw De("too much time has elapsed since the last End-User authentication",WV,{claims:e,now:o,tolerance:n,claim:"auth_time"})}function Lde(t,e){let r=e===wk?void 0:e;if(t.nonce!==r)throw De('unexpected ID Token "nonce" claim value',dh,{expected:r,claims:t,claim:"nonce"})}function HGe(t,e){if(Array.isArray(e.aud)&&e.aud.length!==1){if(e.azp===void 0)throw De('ID Token "aud" (audience) claim includes additional untrusted audiences',dh,{claims:e,claim:"aud"});if(e.azp!==t.client_id)throw De('unexpected ID Token "azp" (authorized party) claim value',dh,{expected:t.client_id,claims:e,claim:"azp"})}}var wk=Symbol(),_k=Symbol();async function jde(t,e,r,o){return typeof o?.expectedNonce=="string"||typeof o?.maxAge=="number"||o?.requireIdToken?KGe(t,e,r,o.expectedNonce,o.maxAge,o[hk],o.recognizedTokenTypes):BGe(t,e,r,o?.maxAge,o?.[hk],o?.recognizedTokenTypes)}async function KGe(t,e,r,o,n,i,s){let a=[];switch(o){case void 0:o=wk;break;case wk:break;default:On(o,'"expectedNonce" argument'),a.push("nonce")}n=Mde(e,n),n!==_k&&a.push("auth_time");let c=await Sk(t,e,r,a,i,s);On(c.id_token,'"response" body "id_token" property',Mt,{body:c});let u=Ode(c);return Ude(e,u,n),Lde(u,o),c}async function BGe(t,e,r,o,n,i){let s=await Sk(t,e,r,void 0,n,i),a=Ode(s);return a&&(Ude(e,a,Mde(e,o)),Lde(a,wk)),s}var ZGe="OAUTH_WWW_AUTHENTICATE_CHALLENGE",WGe="OAUTH_RESPONSE_BODY_ERROR",JGe="OAUTH_UNSUPPORTED_OPERATION",XGe="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var ZV="OAUTH_PARSE_ERROR",Mt="OAUTH_INVALID_RESPONSE";var YGe="OAUTH_RESPONSE_IS_NOT_JSON",QGe="OAUTH_RESPONSE_IS_NOT_CONFORM",eHe="OAUTH_HTTP_REQUEST_FORBIDDEN",tHe="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",WV="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",dh="OAUTH_JWT_CLAIM_COMPARISON_FAILED";var rHe="OAUTH_MISSING_SERVER_METADATA",nHe="OAUTH_INVALID_SERVER_METADATA";async function Fde(t,e,r,o,n){return ph(t),fh(e),XV(t,e,r,"client_credentials",new URLSearchParams(o),n)}async function qde(t,e,r,o){return Sk(t,e,r,void 0,o?.[hk],o?.recognizedTokenTypes)}async function Vde(t,e,r,o,n){ph(t),fh(e),On(o,'"token"');let i=Ade(t,"revocation_endpoint",e.use_mtls_endpoint_aliases,n?.[vde]!==!0),s=new URLSearchParams(n?.additionalParameters);s.set("token",o);let a=wde(n?.headers);return a.delete("accept"),kde(t,e,r,i,s,a,n)}async function Gde(t){if(!bk(t,Response))throw Or('"response" must be an instance of Response',xc);await Pde(t,200,"Revocation Endpoint")}function Hde(t){if(t.bodyUsed)throw Or('"response" body has been used already',Ea)}async function oHe(t,e,r,o,n){let{0:i,1:s,length:a}=t.split(".");if(a===5)if(n!==void 0)t=await n(t),{0:i,1:s,length:a}=t.split(".");else throw new lh("JWE decryption is not configured",{cause:t});if(a!==3)throw De("Invalid JWT",Mt,t);let c;try{c=JSON.parse(qV(HV(i)))}catch(d){throw De("failed to parse JWT Header body as base64url encoded JSON",ZV,d)}if(!gk(c))throw De("JWT Header must be a top level object",Mt,t);if(e(c),c.crit!==void 0)throw new lh('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(qV(HV(s)))}catch(d){throw De("failed to parse JWT Payload body as base64url encoded JSON",ZV,d)}if(!gk(u))throw De("JWT Payload must be a top level object",Mt,t);let l=Ede()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw De('unexpected JWT "exp" (expiration time) claim type',Mt,{claims:u});if(u.exp<=l-o)throw De('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',WV,{claims:u,now:l,tolerance:o,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw De('unexpected JWT "iat" (issued at) claim type',Mt,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw De('unexpected JWT "iss" (issuer) claim type',Mt,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw De('unexpected JWT "nbf" (not before) claim type',Mt,{claims:u});if(u.nbf>l+o)throw De('unexpected JWT "nbf" (not before) claim value',WV,{claims:u,now:l,tolerance:o,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw De('unexpected JWT "aud" (audience) claim type',Mt,{claims:u});return{header:c,claims:u,jwt:t}}function iHe(t,e,r,o){if(t!==void 0){if(typeof t=="string"?o.alg!==t:!t.includes(o.alg))throw De('unexpected JWT "alg" header parameter',Mt,{header:o,expected:t,reason:"client configuration"});return}if(Array.isArray(e)){if(!e.includes(o.alg))throw De('unexpected JWT "alg" header parameter',Mt,{header:o,expected:e,reason:"authorization server metadata"});return}if(r!==void 0){if(typeof r=="string"?o.alg!==r:typeof r=="function"?!r(o.alg):!r.includes(o.alg))throw De('unexpected JWT "alg" header parameter',Mt,{header:o,expected:r,reason:"default value"});return}throw De('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:t,issuer:e,fallback:r})}function Wd(t,e){let{0:r,length:o}=t.getAll(e);if(o>1)throw De(`"${e}" parameter must be provided only once`,Mt);return r}var sHe=Symbol(),aHe=Symbol();function Kde(t,e,r,o){if(ph(t),fh(e),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw Or('"parameters" must be an instance of URLSearchParams, or URL',xc);if(Wd(r,"response"))throw De('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',Mt,{parameters:r});let n=Wd(r,"iss"),i=Wd(r,"state");if(!n&&t.authorization_response_iss_parameter_supported)throw De('response parameter "iss" (issuer) missing',Mt,{parameters:r});if(n&&n!==t.issuer)throw De('unexpected "iss" (issuer) response parameter value',Mt,{expected:t.issuer,parameters:r});switch(o){case void 0:case aHe:if(i!==void 0)throw De('unexpected "state" response parameter encountered',Mt,{expected:void 0,parameters:r});break;case sHe:break;default:if(On(o,'"expectedState" argument'),i!==o)throw De(i===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',Mt,{expected:o,parameters:r})}if(Wd(r,"error"))throw new u_("authorization response from the server is an error",{cause:r});let a=Wd(r,"id_token"),c=Wd(r,"token");if(a!==void 0||c!==void 0)throw new lh("implicit and hybrid flows are not supported");return jGe(new URLSearchParams(r))}async function cHe(t,e=_de){let r;try{r=await t.json()}catch(o){throw e(t),De('failed to parse "response" body as JSON',ZV,o)}if(!gk(r))throw De('"response" body must be a top level object',Mt,{body:r});return r}var uHe=Symbol();function l_(t){if(t==="")return[];if(!t.startsWith("/")||/~(?![01])/u.test(t))throw new Error("Invalid JSON pointer.");let e=t.slice(1).split("/").map(r=>r.replaceAll("~1","/").replaceAll("~0","~"));if(e.some(r=>["__proto__","prototype","constructor"].includes(r)))throw new Error("Invalid JSON pointer.");return e}function xi(t,e){for(let r of l_(e)){if(t===null||typeof t!="object"||!Object.hasOwn(t,r))return;t=t[r]}return t}function e3(t,e,r){let o=l_(e),n=o.pop();if(n===void 0)throw new Error("Choose a property within the object.");for(let i of o){if(t===null||typeof t!="object"||!Object.hasOwn(t,i))throw new Error("JSON pointer target does not exist.");t=t[i]}if(t===null||typeof t!="object")throw new Error("JSON pointer target does not exist.");if(Array.isArray(t)&&(!/^(0|[1-9][0-9]*)$/.test(n)||Number(n)>=t.length))throw new Error("Invalid array index.");t[n]=r}function cl(t){if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);throw new Error("The selected value is not text.")}function xk(t,e){return typeof e=="string"?cl(xi(t,e)):e.map(r=>typeof r=="string"?r:cl(xi(t,r.pointer))).join("")}function mh(t,e){let r=new Set;for(let o of e)o&&(r.add(o),r.add(encodeURIComponent(o)),r.add(JSON.stringify(o).slice(1,-1)));for(let o of[...r].sort((n,i)=>i.length-n.length))t=t.split(o).join("[redacted]");return t}var hh=Vt(Zde(),1);var dHe=hh.default.IPv6.parseCIDR("2000::/3"),pHe=new Set(["unicast","amt","as112","as112v6","orchid2","droneRemoteIdProtocolEntityTags"]);function Rk(t){if(!hh.default.isValid(t)||t.includes("%"))return!1;let e=hh.default.parse(t);return pHe.has(e.range())&&(!(e instanceof hh.default.IPv6)||e.match(dHe))}function Go(t,e){let r;try{r=new URL(t)}catch{q(400,"invalid_url","Enter an absolute HTTPS URL.")}(r.protocol!=="https:"||r.username||r.password||r.hash||r.port&&r.port!=="443"||r.origin===e)&&q(400,"invalid_url","Choose a public HTTPS destination.");let o=r.hostname.replace(/^\[|\]$/g,"");return(o==="localhost"||o.endsWith(".localhost")||o.endsWith(".local")||hh.default.isValid(o)&&!Rk(o))&&q(400,"private_destination","Choose a public HTTPS destination."),r}function ys(t){let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t.body))}catch{q(502,"invalid_response","The service returned an invalid response.")}return(!e||typeof e!="object"||Array.isArray(e))&&q(502,"invalid_response","The service returned an invalid response."),e}var $k=class{constructor(e){this.origin=e}origin;async send(e){let r=Go(e.url,this.origin),o=e.maxBytes??1048576;e.body&&(typeof e.body=="string"?new TextEncoder().encode(e.body).length:e.body.length)>o&&q(413,"body_limit","The request body is too large.");let n;try{n=await fetch(r,{method:e.method??"GET",headers:e.headers,body:typeof e.body=="string"?e.body:e.body?new Uint8Array(e.body):void 0,credentials:"omit",redirect:"error",referrerPolicy:"no-referrer",signal:AbortSignal.any([AbortSignal.timeout(2e4),...e.signal?[e.signal]:[]])})}catch{e.signal?.aborted&&q(409,"cancelled","The operation was cancelled."),q(409,"browser_exchange_unavailable","Restart authorization using the CLI on this device.")}let i=n.body?.getReader(),s=[],a=0;if(i)try{for(;;){let l=await i.read();if(l.done)break;a+=l.value.length,a>o&&q(413,"body_limit","The response body is too large."),s.push(l.value)}}finally{await i.cancel()}let c=new Uint8Array(a),u=0;for(let l of s)c.set(l,u),u+=l.length;return{status:n.status,headers:Object.fromEntries(n.headers),body:c}}};function t3(t,e){return btoa(Array.from(new TextEncoder().encode(t+":"+e),r=>String.fromCharCode(r)).join(""))}var Wde=Object.assign(Object.create(null),{dpop:()=>q(502,"invalid_response","The service returned an unsupported token.")}),fHe={redirectUri:t=>t.fields.ruName,recognizedTokenTypes:Object.assign(Object.create(null),Wde,{"user access token":()=>{}})},mHe={authorize(t,e){delete t.response_type,delete t.client_id,delete t.redirect_uri,t.callback_url=e,t.key_label="Foundation"},async exchange({spec:t,transport:e,url:r,authorization:o,verifier:n}){let i=o.parameters;return(i.getAll("state").length!==1||i.get("state")!==o.state||i.getAll("code").length!==1||!i.get("code"))&&q(400,"invalid_state","Start the connection again."),e.send({url:r(),method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({...t.tokenParams,code:i.get("code"),code_verifier:n,code_challenge_method:"S256"})})},accessTokenField:"key"},hHe={revokeRequest({app:t,url:e,current:r}){return{url:e,method:"DELETE",headers:{authorization:"Basic "+t3(t.clientId,t.clientSecret??""),"content-type":"application/json"},body:JSON.stringify({access_token:r.accessToken})}}},gHe={tokenParameters(t){let e=t.get("redirect_uri");e!==null&&(t.set("redirect_url",e),t.delete("redirect_uri"))}};function $a(t,e){let r=e?new URL(e):void 0;return{recognizedTokenTypes:Wde,...r?.hostname.endsWith(".myshopify.com")&&r.pathname==="/admin/oauth/access_token"?{normalizeToken(o){o.token_type===void 0&&(o.token_type="bearer")},...t.grantType==="client_credentials"?{clientCredentialsParameters(){return{...t.tokenParams}}}:{}}:{},...r?.hostname==="api.notion.com"&&r.pathname==="/v1/oauth/token"?{normalizeToken(o){o.refresh_token===null&&delete o.refresh_token}}:{},...t.adapter==="ebay"?fHe:t.adapter==="openrouter"?mHe:t.adapter==="vultr"?gHe:{},...t.revoke?.style==="github"?hHe:{}}}function Ec(t,e){try{return Go(new j$(t).expand(e)).href}catch{q(400,"invalid_service_url","Check the service URL and its required fields.")}}var Jde=(t,e=" ")=>typeof t=="string"?[...new Set(t.split(e).filter(Boolean))].sort():[],Ik=t=>{let e=typeof t=="number"||typeof t=="string"?Number(t):NaN;return(!Number.isSafeInteger(e)||e<=0||e>315576e3)&&q(502,"invalid_response","The service returned an invalid expiry."),e};var Jd=class{constructor(e){this.transport=e}transport;appValues(e,r){try{return{...Us(e.fields,r.fields,e.defaults),clientId:r.clientId}}catch(o){throw o instanceof ac&&q(400,o.code,o.message),o}}async authorize(e,r,o,n,i,s){(e.grantType==="client_credentials"||!e.authorizeUrl)&&q(400,"wrong_grant","This connection exchanges application credentials directly.");let a=new URL(Ec(e.authorizeUrl,this.appValues(e,r))),c={...e.authorizeParams,response_type:"code",client_id:r.clientId,redirect_uri:$a(e).redirectUri?.(r,i)??i,state:o};s.length&&(c.scope=s.join(e.scopes.separator)),e.pkce&&(c.code_challenge=await bde(n),c.code_challenge_method="S256"),$a(e).authorize?.(c,i);for(let[u,l]of Object.entries(c))a.searchParams.set(u,l);return a.href}configuration(e,r){let o={issuer:e.issuer??new URL(Ec(e.grantType==="client_credentials"?e.tokenUrl:e.authorizeUrl,this.appValues(e,r))).origin,token_endpoint:Ec(e.tokenUrl,this.appValues(e,r))};return e.issuer&&Go(e.issuer),{server:o,client:{client_id:r.clientId}}}authentication(e,r){return r==="none"?Ide():(e.clientSecret||q(409,"app_required","Add a client secret to this OAuth application."),r==="basic"?Rde(e.clientSecret):$de(e.clientSecret))}options(e){let r=e?.tokenFormat??"form";return{[JV]:async(o,{body:n,headers:i,method:s,signal:a})=>{let c=new URLSearchParams(n);e&&$a(e).tokenParameters?.(c);let u=await this.transport.send({url:o,method:s,headers:r==="json"?{...i,"content-type":"application/json"}:i,body:r==="json"?JSON.stringify(Object.fromEntries(c)):c.toString(),signal:a});return new Response([204,205,304].includes(u.status)?null:new Uint8Array(u.body),{status:u.status,headers:u.headers})}}}async json(e){return ys({status:e.status,headers:{},body:new Uint8Array(await e.arrayBuffer())})}checkResponse(e,r,o,n=!1){return(r>=400||o.error||e.okPointer&&xi(o,e.okPointer)!==!0)&&(n&&(o.error==="invalid_grant"||o.error==="invalid_token")&&q(409,"reconnect_required","Reconnect this service to renew access."),r===429&&q(503,"service_rate_limit","The service is busy. Try again later."),q(502,"authorization_failed","The service did not authorize this connection.")),o}async tokenResponse(e,r,o,n=!1){o.status===429&&q(503,"service_rate_limit","The service is busy. Try again later.");let i=this.checkResponse(e,o.status,await this.json(o),n),{server:s,client:a}=this.configuration(e,r),c=new URL(s.token_endpoint),u={...i};delete u.id_token,$a(e,c.href).normalizeToken?.(u),u.expires_in!==void 0&&(u.expires_in=Ik(u.expires_in));try{let d=await(n?Dde:e.grantType==="client_credentials"?qde:jde)(s,a,Response.json(u,{status:o.status}),{recognizedTokenTypes:$a(e,c.href).recognizedTokenTypes});return{...i,...d}}catch(l){if(l instanceof dt)throw l;q(502,"invalid_response","The service did not return a valid access token.")}}token(e,r,o,n,i=!1){let s=r[$a(e).accessTokenField??"access_token"];(typeof s!="string"||!s||s.length>16384||/[\s\u0000-\u001f]/.test(s))&&q(502,"invalid_response","The service did not return a valid access token.");let a=r.expires_in===void 0?null:Date.now()+Ik(r.expires_in)*1e3,c=r.refresh_token??n?.refreshToken;c!==void 0&&(typeof c!="string"||!c||c.length>16384)&&q(502,"invalid_response","The service returned an invalid refresh token.");let u={...n?.extra};for(let d of e.keep)typeof r[d]=="string"&&(u[d]=r[d]);let l={accessToken:s,...c?{refreshToken:String(c)}:{},expiresAt:a,scopes:r.scope!==void 0?Jde(r.scope,e.scopes.separator):i?n?.scopes??o:o,scopesStatus:r.scope!==void 0?"reported":i?n?.scopesStatus??"unknown":o.length?"requested":"unknown",account:n?.account??"",accountName:n?.accountName??"",accountVerified:n?.accountVerified??!1,extra:u,facts:{}};return r.refresh_token_expires_in!==void 0&&(l.refreshExpiresAt=Date.now()+Ik(r.refresh_token_expires_in)*1e3),n?.refreshExpiresAt&&c===n.refreshToken&&(l.refreshExpiresAt=Math.min(l.refreshExpiresAt??1/0,n.refreshExpiresAt)),l}async exchange(e,r,o,n,i,s,a,c){e.grantType==="client_credentials"&&q(400,"wrong_grant","This connection exchanges application credentials directly.");let u,l=$a(e);if(l.exchange){let p=await l.exchange({spec:e,app:r,transport:this.transport,url:()=>Ec(e.tokenUrl,this.appValues(e,r)),authorization:o,verifier:n});u=this.checkResponse(e,p.status,ys(p))}else{let{server:p,client:f}=this.configuration(e,r),h;try{let y=Kde(p,f,o.parameters,o.state);h=await Nde(p,f,this.authentication(r,e.clientAuth),y,l.redirectUri?.(r,i)??i,e.pkce?n:QV,{...this.options(e),additionalParameters:e.tokenParams})}catch(y){throw(y instanceof c_||y instanceof u_)&&q(400,"invalid_state","Start the connection again."),y}u=await this.tokenResponse(e,r,h)}let d=this.token(e,u,s,a);return await c?.(d,u),d}async clientCredentials(e,r,o,n,i){e.grantType!=="client_credentials"&&q(400,"wrong_grant","Choose a client credentials connection method.");let{server:s,client:a}=this.configuration(e,r),c=$a(e,s.token_endpoint),u={...e.tokenParams,...o.length?{scope:o.join(e.scopes.separator)}:{}},l=await Fde(s,a,this.authentication(r,e.clientAuth),c.clientCredentialsParameters?.(u)??u,this.options(e)),d=await this.tokenResponse(e,r,l),p={...this.token(e,d,o,n,!!n),requestedScopes:o};return await i?.(p,d),p}async refresh(e,r,o,n){let i=o;if(o.expiresAt!==null&&o.expiresAt<Date.now()+6e4){if(e.grantType==="client_credentials")return o.requestedScopes||q(409,"reconnect_required","Reconnect this service to select its renewal scopes."),this.clientCredentials(e,r,o.requestedScopes,o,n);(!o.refreshToken||o.refreshExpiresAt&&o.refreshExpiresAt<=Date.now())&&q(409,"reconnect_required","Reconnect this service to renew access.");let{server:s,client:a}=this.configuration(e,r),c=await Tde(s,a,this.authentication(r,e.clientAuth),o.refreshToken,{...this.options(e),additionalParameters:e.tokenParams}),u=await this.tokenResponse(e,r,c,!0);i=this.token(e,u,o.scopes,o,!0),await n?.(i,u)}return i}async revoke(e,r,o){if(!e.revoke?.tokenOnly)throw new Error("Revoke only with an endpoint that invalidates this token alone.");let n=Ec(e.revoke.url,{...this.appValues(e,r),accessToken:o.accessToken,refreshToken:o.refreshToken??""});if(e.revoke.style==="rfc7009"){let{server:c,client:u}=this.configuration(e,r),l=e.revoke.auth==="none"&&e.clientAuth!=="none"?()=>{}:this.authentication(r,e.revoke.auth??e.clientAuth),d=await Vde({...c,revocation_endpoint:n},u,l,o.refreshToken??o.accessToken,this.options());try{await Gde(d)}catch{q(502,"revoke_failed","The service did not revoke the token.")}return}let i={},s=e.revoke.auth??e.clientAuth;e.revoke.style==="bearer"?i.authorization="Bearer "+o.accessToken:s==="basic"&&(i.authorization="Basic "+t3(r.clientId,r.clientSecret??"")),(await this.transport.send($a(e).revokeRequest?.({spec:e,app:r,transport:this.transport,url:n,current:o})??{url:n,method:e.revoke.style==="bearer"?"POST":"DELETE",headers:i})).status>=300&&q(502,"revoke_failed","The service did not revoke the token.")}outputs(e,r,o){let n={...this.appValues(e,r),...o.extra,...o,expiresAt:o.expiresAt===null?"":String(o.expiresAt)};return Object.fromEntries(Object.entries(e.outputs).map(([i,s])=>[i,cl(xi(n,s))]))}};function r3(t){if(t.method.kind!=="oauth")throw new Error("Use an OAuth connection provider.");return t.method.config}function n3(t){return t||q(409,"app_required","Choose an OAuth application."),t}function yHe(t){return{token:mj.parse(t.token),response:Lt.parse(t.response)}}var Ak=class{constructor(e){this.transport=e}transport;facts=WL;oauth(e){return new Jd({send:r=>this.transport.send({...r,...e?{signal:AbortSignal.any([e,...r.signal?[r.signal]:[]])}:{}})})}needsRenewal(e){return!e.oauth||e.oauth.expiresAt!==null&&e.oauth.expiresAt<Date.now()+6e4}async renew(e){let r=e.material,o=r3(r),n=n3(e.app),i=("requestedScopes"in r?r.requestedScopes:void 0)??r.oauth?.requestedScopes,s=(c,u)=>e.receive({token:c,response:u}),a=o.grantType==="client_credentials"?await this.oauth(e.signal).clientCredentials(o,n,i??Vi(o.scopes),r.oauth,s):await this.oauth(e.signal).refresh(o,n,r.oauth,s);return $n.parse({...e.material,oauth:a})}async recover(e,r,o){let i=yHe(o).token;return $n.parse({...e,oauth:i})}async outputs(e,r){return this.oauth().outputs(r3(e),n3(r),e.oauth)}async revoke(e,r,o){e.oauth&&await this.oauth(o).revoke(r3(e),n3(r),e.oauth)}};function vHe(t){if(t.method.kind!=="token"&&t.method.kind!=="approval")throw new Error("Use an input credential provider.");return t.method.config}var d_=class{facts=zf;needsRenewal(){return!1}async outputs(e){let r=vHe(e),o=Us(r.fields,e.fields,"constants"in r?r.constants??{}:{});return Object.fromEntries(Object.entries(r.outputs).map(([n,i])=>[n,xk(o,i)]))}};function Pk(t){if(t.method.kind!=="ovh")throw new Error("Use an OVH connection provider.");return t.method.config}var kk=class{facts=JL;values(e,r){let o=Pk(e),n=o.authorization==="consumer_key";n&&(!r?.clientId||!r.clientSecret)&&q(409,"app_required","Choose an OVHcloud API application with its key and secret.");let i=n?r.fields:e.fields;return Us(o.fields,i)}credentials(e,r){if(Pk(e).authorization==="consumer_key")return{applicationKey:r.clientId,applicationSecret:r.clientSecret,consumerKey:e.fields.consumerKey};let o=this.values(e,r);return{applicationKey:o.applicationKey,applicationSecret:o.applicationSecret,consumerKey:o.consumerKey}}needsRenewal(){return!1}async outputs(e,r){if(e.method.kind!=="ovh")throw new Error("Use OVH connection material.");let o="ovh"in e?e.ovh:void 0;o&&o.expiresAt!==null&&o.expiresAt<=Date.now()&&q(409,"reconnect_required","Reconnect OVHcloud with a current API key.");let n=Pk(e).authorization==="consumer_key"?{...this.values(e,r),...this.credentials(e,r)}:this.values(e,r);return Object.fromEntries(Object.entries(Pk(e).outputs).map(([i,s])=>[i,cl(xi(n,s))]))}};import{readFile as wHe}from"node:fs/promises";var _He=m.object({accessToken:m.string().min(1).max(16384).regex(/^\S+$/),expiresAt:m.number().int().positive()}).strict();async function bHe(t,e){if(t==="oidc"){let n=process.env.VULTR_OIDC_TOKEN_FILE,i=n?await wHe(n,"utf8"):process.env.VULTR_OIDC_TOKEN;return(!i||i.length>16384)&&q(409,"authentication_required","Provide the current OIDC token to this executor."),i.trim()}let r=await fetch("http://169.254.169.254/v1/identity/token",{redirect:"error",credentials:"omit",signal:AbortSignal.any([e,AbortSignal.timeout(3e3)])});r.ok||q(409,"authentication_required","Use a Vultr instance with an IAM role trust.");let o=(await r.text()).trim();return(!o||o.length>16384)&&q(502,"invalid_response","The instance did not return a valid identity token."),o}function Xde(t){if(t.method.kind!=="token"||t.method.config.resolver!=="vultr-role")throw new Error("Use a Vultr IAM role connection.");return t.method.config}var Tk=class{constructor(e,r=bHe){this.transport=e;this.identityToken=r}transport;identityToken;facts=zf;sessions=new Map;pending=new Map;needsRenewal(){return!1}async obtain(e,r){let o=Us(Xde(e).fields,e.fields),n=o.authentication;["api_key","oidc","instance"].includes(n)||q(400,"invalid_field","Choose a Vultr authentication source.");let i=n==="api_key"?o.token:o.credential||await this.identityToken(n,r);(!i||i.length>16384||/\s/.test(i))&&q(409,"authentication_required","Provide current credentials for the selected authentication source.");let s=Number(o.duration);(!Number.isSafeInteger(s)||s<=0||s>315576e3)&&q(400,"invalid_field","Enter a valid session duration in seconds.");let a=await this.transport.send({url:"https://api.vultr.com/v2/assumed-roles/assume",method:"POST",headers:{"content-type":"application/json",authorization:"Bearer "+i},signal:r,body:JSON.stringify({role_id:o.roleId,session_name:o.sessionName,duration:s,auth_method:n==="instance"?"jwt":n,...n==="api_key"?{user_id:o.userId}:{},...n==="oidc"?{oidc_issuer_id:o.issuerId}:{}})});a.status>=400&&q(409,"role_denied","Check the role trust, permissions and authentication source in Vultr.");let c=ys(a);(c.role_id!==void 0&&c.role_id!==o.roleId||n==="api_key"&&c.user_id!==void 0&&c.user_id!==o.userId)&&q(409,"role_changed","Reconnect to approve the returned role and authentication source.");let u=_He.parse({accessToken:c.session_token,expiresAt:typeof c.expires_at=="string"?Date.parse(c.expires_at):NaN});return u.expiresAt<=Date.now()&&q(502,"invalid_response","Vultr returned an expired role session."),u}async outputs(e,r,o){let n=Xde(e);o.throwIfAborted();let i=await Q(e),s=this.sessions.get(i);if(!s||s.expiresAt<Date.now()+6e4){let a=this.pending.get(i);a||(a=this.obtain(e,o),this.pending.set(i,a));try{s=await a,this.sessions.set(i,s)}finally{this.pending.get(i)===a&&this.pending.delete(i)}}return Object.fromEntries(Object.entries(n.outputs).map(([a,c])=>[a,xk(s,c)]))}};function Yde(t,e){let r={oauth:new Ak(t),token:new d_,aws:new mk(e),approval:new d_,ovh:new kk},o=new Tk(t);return n=>n.kind==="token"&&n.config.resolver==="vultr-role"?o:r[n.kind]}function Ra(t){return new TextDecoder("utf-8",{fatal:!0}).decode(t)}async function Ck(t,e){let r={},o={},n=[],i=new Set;for(let s of t){if(i.has(s.name)||!G5(s.name))throw new Error("Use distinct, unreserved environment variable names.");i.add(s.name);let a=await e(s.source);if(s.format==="json"&&(a=tt(cl(xi(JSON.parse(Ra(a)),s.pointer??"")))),s.format==="file")o[s.name]=Buffer.from(a).toString("base64");else{let c=Ra(a);if(c.includes("\0"))throw new Error("Use a file to pass binary content.");r[s.name]=c}n.push(Buffer.from(a).toString("utf8"),Buffer.from(a).toString("base64"),Buffer.from(a).toString("base64url"))}return{environment:r,files:o,sensitive:n}}var gh=class{constructor(e,r,o,n,i,s=new fk){this.binding=e;this.keys=r;this.broker=o;this.journal=n;this.providers=Yde(i,s)}binding;keys;broker;journal;active=new Set;providers;provider(e){return this.providers(e)}metadata(e){return Ff(e,this.provider(e.method).facts(e))}source(e,r,o){let n=o.find(i=>i.policy.id===e&&i.policy.contentType===r);return n||q(409,"input_required","Include the connection and its application in this execution."),n}async material(e,r,o){let n=$n.safeParse(JSON.parse(Ra(await au(e,r,this.keys,{destination:o}))));n.success||q(409,"reconnect_required","Reconnect this service with the current connection format.");let i=n.data;return(await this.metadata(i)).authorizationDigest!==e.metadata.authorizationDigest&&q(409,"connection_changed","Approve the current service account and permissions before using this connection."),i.state==="reconnect"&&r.operation!==ue.revoke&&q(409,"reconnect_required","Reconnect this service before using it."),i}async app(e,r,o,n){let i=this.source(e,he.clientCredential,n),s=Zn.parse(JSON.parse(Ra(await au(i,o,this.keys))));return s.methodId!==r&&q(400,"wrong_app","Choose an application for this connection method."),s}async connectionApp(e,r,o){if(dr(e.method).application==="none")return null;if(!lu(e.method))return"implicitApp"in e&&e.implicitApp?e.implicitApp:Zn.parse({format:1,methodId:e.methodId,generation:e.generation,clientId:"",fields:{}});let n=r.operation===ue.revoke?ue.revoke:ue.refresh,i=await this.app(e.appId,e.methodId,{...r,operation:n},o);return i.generation!==e.appGeneration&&q(409,"app_changed","Reconnect this service with the current application."),dr(e.method).requiresApp&&e.method.kind!=="aws"&&Object.entries(fo(e.method.config.fields,e.fields??{})).some(([s,a])=>i.fields[s]!==a)&&q(409,"app_changed","Reconnect this service with the current application settings."),i}async validate(e,r,o){let n=hj.parse(e);r.operation!==ue[n.action]&&q(400,"wrong_operation","Use the approved connection operation.");let i=await this.material(this.source(n.id,he.tokenSet,o),r);(n.action==="refresh"||dr(i.method).revocable)&&await this.connectionApp(i,r,o)}async execute(e,r,o,n){let i=hj.parse(e);this.active.has(i.id)&&q(409,"connection_busy","Another operation is updating this connection."),this.active.add(i.id);try{n.throwIfAborted();let s=this.source(i.id,he.tokenSet,o),a=await this.material(s,r);if(i.action==="refresh"){let l=await this.refresh(s,a,r,o,n);return{kind:"refreshed",id:s.policy.id,...await this.metadata(l)}}let c=this.provider(a.method),u=dr(a.method).revocable&&!!c.revoke;return u&&await c.revoke(a,await this.connectionApp(a,r,o),n),{kind:"disconnected",id:s.policy.id,revoked:u}}finally{this.active.delete(i.id)}}async outputs(e,r,o,n,i){let s=await this.material(e,r,i);return this.provider(s.method).renew&&await this.broker.state(e.policy.id)&&q(409,"connection_busy","Resolve the current token update before using this connection."),s=await this.refresh(e,s,r,o,n,i),this.provider(s.method).outputs(s,await this.connectionApp(s,r,o),n)}async refreshed(e,r){let o=await this.metadata(r);return o.authorizationDigest!==e.previous.metadata.authorizationDigest&&q(409,"connection_review","Review the changed service account or permissions before sharing the updated connection."),e.material=r,e.content=await l8(e.previous,tt(C(r)),this.binding,this.keys,o),e.phase="settled",await this.journal.write("refresh_"+e.operation.id,e),await this.broker.commit(e.operation.id,e.operation.fence,e.content),e.delivered=!0,await this.journal.write("refresh_"+e.operation.id,e),r}async refresh(e,r,o,n,i,s){let a=this.provider(r.method);if(!a.needsRenewal(r))return r;a.renew||q(409,"reconnect_required","Reconnect this service to renew access.");try{await ld(e,{...o,operation:ue.refresh},{destination:s})}catch{q(403,"refresh_required","Authorize this requester and executor to renew the connection for this destination.")}let c=await this.connectionApp(r,o,n),u=SHe(),l=await this.broker.prepare(u,e.policy.id,e.materialRevision),d={operation:l,previous:e,material:r,app:c,phase:"prepared",delivered:!1};await this.journal.write("refresh_"+u,d);try{i.throwIfAborted(),d.phase="dispatched",await this.journal.write("refresh_"+u,d),await this.broker.dispatch(u,l.fence),i.throwIfAborted();let p=await a.renew({material:r,app:c,signal:i,receive:async f=>{d.checkpoint=f,d.phase="received",await this.journal.write("refresh_"+u,d)}});return await this.refreshed(d,p)}catch(p){if(d.phase==="prepared"?await this.broker.abort(u,l.fence):await this.broker.uncertain(u,l.fence).catch(()=>{}),p instanceof dt&&["connection_review","reconnect_required","account_changed","authorization_failed","service_rate_limit"].includes(p.code))throw p;q(409,"connection_uncertain","Check the token update before using this connection again.")}}async reconcile(){let e=[];for(let r of await this.journal.keys("refresh_"))try{let o=await this.journal.read(r);if(o.delivered)continue;if(o.content){await this.broker.commit(o.operation.id,o.operation.fence,o.content),o.delivered=!0,await this.journal.write(r,o);continue}let n=await this.broker.state(o.operation.resource_id);if(!n||n.id!==o.operation.id||n.state==="prepared")n?.id===o.operation.id&&n.state==="prepared"&&await this.broker.abort(o.operation.id,o.operation.fence),o.delivered=!0,await this.journal.write(r,o);else if(o.checkpoint&&this.provider(o.material.method).recover){let i=await this.provider(o.material.method).recover(o.material,o.app,o.checkpoint);await this.refreshed(o,i)}else await this.broker.uncertain(o.operation.id,o.operation.fence),o.delivered=!0,await this.journal.write(r,o)}catch{e.push(r.slice(8))}return e}};import{lookup as xHe}from"node:dns/promises";import{request as EHe}from"node:https";import{brotliDecompressSync as $He,gunzipSync as RHe,inflateSync as IHe}from"node:zlib";var yh=class{constructor(e){this.origin=e}origin;async send(e){let r=Go(e.url,this.origin),o=r.hostname.replace(/^\[|\]$/g,""),n=e.maxBytes??1048576;e.body&&Buffer.byteLength(e.body)>n&&q(413,"body_limit","The request body is too large.");let i={"user-agent":"Foundation/1.0",accept:"application/json","accept-encoding":"identity"};for(let[s,a]of Object.entries(e.headers??{})){let c=s.toLowerCase();(["host","connection","content-length","transfer-encoding","upgrade","proxy-authorization","proxy-connection","accept-encoding","te","trailer"].includes(c)||!/^[!#$%&'*+.^_`|~0-9a-z-]+$/.test(c)||/[\r\n\u0000]/.test(a))&&q(400,"invalid_header","Choose a valid request header."),i[c]=a}try{let s=await xHe(o,{all:!0,verbatim:!0});(!s.length||s.some(u=>!Rk(u.address)))&&q(400,"private_destination","Choose a public HTTPS destination.");let a=s[0],c=AbortSignal.any([AbortSignal.timeout(2e4),...e.signal?[e.signal]:[]]);return await new Promise((u,l)=>{let d={method:e.method??"GET",headers:i,signal:c,agent:!1,lookup:(f,h,y)=>{h.all?y(null,[a]):y(null,a.address,a.family)}},p=EHe(r,d,f=>{let h=[],y=0;f.on("data",w=>{y+=w.length,y>n?f.destroy(new dt(413,"body_limit","The response body is too large.")):h.push(w)}),f.on("error",l),f.on("end",()=>{try{let w=Buffer.concat(h),b=f.headers["content-encoding"];if(b&&b!=="identity"){let x=b==="gzip"?RHe:b==="deflate"?IHe:b==="br"?$He:null;if(!x)throw new dt(502,"invalid_response","The service returned an unsupported response.");w=x(w,{maxOutputLength:n})}let S={};for(let[x,R]of Object.entries(f.headers))R!==void 0&&!["set-cookie","set-cookie2","content-encoding","transfer-encoding","connection"].includes(x)&&(S[x]=Array.isArray(R)?R.join(", "):R);u({status:f.statusCode??502,headers:S,body:new Uint8Array(w)})}catch(w){l(w)}})});p.on("error",l),p.end(e.body)})}catch(s){if(s instanceof dt)throw s;e.signal?.aborted&&q(409,"cancelled","The operation was cancelled."),q(502,"service_unavailable","The service could not be reached. Try again.")}}};function Dn(t){let{keys:e,binding:r,origin:o}=t.identity;if(!e||!r)throw new Error("Use a sign-in key with encryption and signing keys for this operation.");let n=o3(AHe(rc()),"custody",r.id),i=new md(o3(n,"client"),o,r,e),s=new G$(t,o,r,e,new H$(i)),a=new K$(t),c=new yh(o),u=new gh(r,e,a.connections(),new md(o3(n,"connections"),o,r,e),c);return{custody:s,journal:i,directory:n,keys:e,binding:r,broker:a,transport:c,connections:u}}async function Qde(t,e){let{custody:r,keys:o,binding:n,connections:i}=Dn(t),s=await r.sourceContents(e.map(u=>u.source.id)),a={format:2,id:crypto.randomUUID(),origin:t.identity.origin,ownerId:n.principalId,actor:n,executor:n,environmentId:n.id,environmentDigest:await Q(n),operation:ue.command,functionDigest:null,operationDigest:await Q(e),sources:await Promise.all(s.map(async u=>({id:u.policy.id,policyDigest:await Q(u.policy),materialRevision:u.materialRevision,...u.policy.contentType===he.tokenSet?{authorizationDigest:String(u.metadata.authorizationDigest)}:{}}))),resultRecipients:[n],createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+36e5).toISOString()},c=new Map;return Ck(e,async u=>{let l=s.find(p=>p.policy.id===u.id);if(l.policy.contentType===he.value)return au(l,a,o);c.has(u.id)||c.set(u.id,i.outputs(l,a,s,new AbortController().signal));let d=await c.get(u.id);if(!u.output||!Object.hasOwn(d,u.output))throw new Error("Choose an available connection output.");return tt(d[u.output])})}import{mkdir as wot}from"node:fs/promises";import{join as ib}from"node:path";import{setTimeout as _ot}from"node:timers/promises";function PHe(t,e){let r={};if(Object.keys(e).some(o=>!t.parameters.some(n=>n.name===o)))throw new Error("Use the parameters this function declares.");for(let o of t.parameters){let n=Object.hasOwn(e,o.name)?e[o.name]:o.default;if(n===void 0){if(o.required)throw new Error("Complete the required function parameters.");continue}if(o.type!=="json"&&typeof n!==o.type||o.type==="number"&&!Number.isFinite(n))throw new Error("Use the argument types this function declares.");if(o.required&&o.type==="string"&&n==="")throw new Error("Complete the required function parameters.");if(JSON.stringify(n).length>8192)throw new Error("The function argument is too long.");r[o.name]=n}return r}function Ok(t,e){let r=PHe(t,e);if(t.program.kind==="command"){let{kind:u,...l}=t.program;return{kind:u,...Wa.parse({...l,stdin:JSON.stringify(r)})}}if(t.result!=="json")throw new Error("HTTP functions return a JSON response containing status, headers, and body.");let o=t.program.request,n=u=>typeof u=="string"?u:JSON.stringify(u),i=(u,l=!1)=>{if(l&&typeof u=="string"){let d=/^\{\{([A-Za-z][A-Za-z0-9_]*)\}\}$/.exec(u)?.[1];if(d){if(!t.parameters.some(p=>p.name===d))throw new Error("Declare every function parameter.");return Object.hasOwn(r,d)?r[d]:null}}return typeof u=="string"?u.replace(/\{\{([A-Za-z][A-Za-z0-9_]*)\}\}/g,(d,p)=>{if(!t.parameters.some(f=>f.name===p))throw new Error("Declare every function parameter.");return Object.hasOwn(r,p)?n(r[p]):""}):Array.isArray(u)?u.map(d=>i(d,l)):u&&typeof u=="object"?Object.fromEntries(Object.entries(u).map(([d,p])=>[d,i(p,l)])):u},s=new j$(o.url).expand(Object.fromEntries(Object.entries(r).map(([u,l])=>[u,n(l)]))),a=Za.parse({...i(o),url:s,bindings:o.bindings,...o.json===void 0?{}:{json:i(o.json,!0)}}),c=new URL(o.url.replace(/\{[^}]+\}/g,"placeholder"));if(new URL(s).origin!==c.origin)throw new Error("The function must have a fixed destination host.");return{kind:"http",request:a,responseFormat:t.program.responseFormat}}function epe(t){return t.program.kind==="command"?t.program.inputs.map(e=>e.source):t.program.request.bindings.flatMap(e=>e.parts.filter(r=>typeof r!="string"))}var tpe=m.object({operation:ec,save:m.record(m.string(),fe)}).strict();function Dk(t){return t.kind==="http"?{kind:t.kind,request:t.request}:t}async function rpe(t,e){let r=t.operationContext;if(!r)return;if(r.invocation.name==="connection.revoke"){let n=y$.parse(r.invocation.input);if(e.kind!=="revoke"||C(e.input)!==C({action:"revoke",id:n.connectionId})||n.ownerId!==t.ownerId||n.environmentId!==t.environmentId)throw new Error("Revoke the reviewed connection on its selected executor.");return}if(r.invocation.name!=="run.execute")throw new Error("Use the reviewed operation.");let o=Fy.parse(r.invocation.input);if(o.ownerId!==t.ownerId||o.environmentId!==t.environmentId||o.operation.kind!==e.kind)throw new Error("Use the reviewed run and execution environment.");if("programDigest"in o.operation){if(await Q(Dk(e))!==o.operation.programDigest)throw new Error("Run the reviewed private program.")}else if(e.kind==="http"&&o.operation.kind==="http"){if(C(e.request)!==C(o.operation.request))throw new Error("Run the reviewed HTTP request and output destinations.")}else if(C(e)!==C(ec.parse(o.operation)))throw new Error("Run the reviewed command.");if(e.kind==="http"&&C(Object.fromEntries(Object.entries(e.save).map(([n,i])=>[n,i.name])))!==C(o.save))throw new Error("Use the reviewed output destinations.")}function kHe(t,e){return t.policy.contentType===he.value?e.output===void 0:t.policy.contentType===he.tokenSet&&e.output!==void 0}var Ia=class extends Error{constructor(){super("A completed result is waiting for delivery. Restart or leave this executor running to reconcile it.")}};function i3(t){return!(t instanceof dt)||["service_unavailable","connection_uncertain","lease_lost"].includes(t.code)}var Nk=class{constructor(e,r,o,n,i,s,a){this.environment=e;this.keys=r;this.broker=o;this.journal=n;this.transport=i;this.commands=s;this.extension=a}environment;keys;broker;journal;transport;commands;extension;get binding(){return this.environment.manifest.executor}async reconcile(){let e=[];for(let r of await this.journal.keys("run_"))try{let o=await this.journal.read(r);if(!o||o.delivered)continue;if(!o.receipt&&o.phase==="dispatched"){let n=o.operation?.kind==="connect"?await this.extension?.recover?.(o.operation.input,o.request.intent):null;o.receipt=n?await Df(o.request.intent,"succeeded",{ok:!0,result:n,error:null},this.keys):await Df(o.request.intent,"uncertain",{ok:!1,result:null,error:{code:"execution_interrupted",message:"Check the destination before starting another operation."}},this.keys),o.phase="settled",await this.journal.write(r,o)}o.receipt&&(await this.broker.finish(o.lease,o.receipt),o.delivered=!0,await this.journal.write(r,o))}catch{e.push(r.slice(4))}return e}async tick(e=new AbortController().signal){e.throwIfAborted();let r=await this.broker.claim(this.environment.manifest.id);if(!r)return!1;let{intent:o}=r.request,n="run_"+o.id,i=await Q(r.request),s=await this.journal.read(n);if(s&&s.digest!==i)throw new Error("A run ID was reused for a different signed request.");if(s?.receipt)return await this.broker.finish(r.lease,s.receipt),await this.journal.write(n,{...s,delivered:!0}),!0;if(s?.phase==="dispatched"){let p=await Df(o,"uncertain",{ok:!1,result:null,error:{code:"execution_interrupted",message:"Check the destination before starting another operation."}},this.keys);return await this.journal.write(n,{...s,lease:r.lease,phase:"settled",receipt:p,delivered:!1}),await this.broker.finish(r.lease,p),!0}s={digest:i,lease:r.lease,request:r.request,phase:"prepared",delivered:!1},await this.journal.write(n,s);let a=new AbortController,c=AbortSignal.any([e,a.signal]),u=setInterval(()=>{this.broker.renew(o.id,r.lease).then(p=>{p.active||a.abort()}).catch(()=>a.abort())},15e3);u.unref();let l=!1,d;try{let p=await p8(r.request,this.binding,this.keys);await Of(this.environment,p.intent);let f=ec.parse(p.operation);if(ue[f.kind]!==o.operation)throw new Error("Use the operation authorized by this intent.");await rpe(o,f),await this.validateOperation(f,o,r.sources),c.throwIfAborted(),s.operation=f,s.phase="dispatched",await this.journal.write(n,s),l=!0,await this.broker.dispatch(o.id,r.lease),c.throwIfAborted();let h=await this.executeOperation(f,o,r.sources,c);d=await Df(o,"succeeded",{ok:!0,result:h,error:null},this.keys)}catch(p){if(p instanceof Ia)throw p;p instanceof Tf&&(p=new dt(413,"result_too_large","The operation completed, but its result is too large to return. Check the destination before starting it again."));let f=l&&(c.aborted||i3(p));d=await Df(o,f?"uncertain":"failed",{ok:!1,result:null,error:p instanceof dt?{code:p.code,message:p.message}:{code:f?"execution_uncertain":"invalid_execution",message:f?"Check the destination before starting another operation.":"The executor could not authorize this operation."}},this.keys)}finally{clearInterval(u)}return s.phase="settled",s.receipt=d,await this.journal.write(n,s),await this.broker.finish(r.lease,d),s.delivered=!0,await this.journal.write(n,s),!0}request(e){let r=e.kind==="function"?Ok(e.definition,e.arguments):e;return r.kind==="http"?r.request:null}async validateOperation(e,r,o){if(new Set(o.map(c=>c.policy.id)).size!==o.length||o.length!==r.sources.length)throw new Error("Supply exactly the signed execution inputs.");for(let c of o){await ko(c);let u=r.sources.find(p=>p.id===c.policy.id);if(!u||!await jL(c,u))throw new Error("An execution input changed.");let l="checkpoint_"+c.policy.format+"_"+c.policy.id,d=await this.journal.read(l);if(d&&(c.policy.revision<d.policy||c.materialRevision<d.material))throw new Error("The execution input is older than this executor has already observed.");await this.journal.write(l,{policy:c.policy.revision,material:c.materialRevision})}if(e.kind==="function"&&(e.functionId!==r.functionId||await Q(e.definition)!==r.functionDigest||e.definition.environmentId!==r.environmentId||!this.environment.manifest.capabilities.includes(ue[e.definition.program.kind])))throw new Error("Run the exact function authorized by this intent.");if(e.kind!=="function"&&(r.functionId||r.functionDigest))throw new Error("Use function authorization only for a saved function.");let n=this.request(e);if(n){if(Go(n.url,r.origin),[n.body,n.json,n.form].filter(c=>c!==void 0).length>1)throw new Error("Choose one request body format.");for(let c of n.bindings){let u=l_(c.pointer);if(!u.length||!["headers","body","json","form"].includes(u[0])||u[0]==="body"&&u.length!==1||["headers","form"].includes(u[0])&&u.length!==2)throw new Error("Bind credentials to request headers or the body.");e3(structuredClone(n),c.pointer,"validation")}}let i=e.kind==="function"?e.outputs:e.kind==="http"?e.save:{};for(let[c,u]of Object.entries(i)){if(l_(c),!this.broker.capture)throw new Error("This executor cannot save encrypted outputs.");let l=await su(u.approval);if(C(l.policy.authorities.find(d=>d.id===l.authorityId))!==C(r.actor)||l.policy.origin!==r.origin||l.policy.contentType!==he.value||l.policy.ownerId!==r.ownerId||!l.policy.producers.some(d=>d.runId===r.id&&C(d.executor)===C(this.binding)&&Date.parse(d.expiresAt)>Date.now()))throw new Error("Approve each encrypted output for this execution.")}let s=e.kind==="function"?Ok(e.definition,e.arguments):e,a=s.kind==="command"?s.inputs.map(c=>c.source):n?n.bindings.flatMap(c=>c.parts.filter(u=>typeof u!="string")):[];for(let c of a){let u=o.find(l=>l.policy.id===c.id);if(!u||!kHe(u,c))throw new Error("Use the input named in the signed request.");await ld(u,r,{...n?{destination:n.url}:{}}),await au(u,r,this.keys,{...n?{destination:n.url}:{}})}if(e.kind==="connect"||e.kind==="refresh"||e.kind==="revoke"){if(!this.extension)throw new Error("This executor cannot manage connections.");await this.extension.validate(e.input,r,o)}}async executeOperation(e,r,o,n){if(e.kind==="connect"||e.kind==="refresh"||e.kind==="revoke")return this.extension.execute(e.input,r,o,n);let i=this.request(e),s=e.kind==="function"?Ok(e.definition,e.arguments):e,a=[],c=new Map,u=async h=>{let y=o.find(b=>b.policy.id===h.id);if(y.policy.contentType===he.value)return au(y,r,this.keys,{...i?{destination:i.url}:{}});if(!this.extension)throw new Error("This executor cannot use connections.");c.has(h.id)||c.set(h.id,this.extension.outputs(y,r,o,n,i?.url));let w=await c.get(h.id);if(!h.output||!Object.hasOwn(w,h.output))throw new Error("Choose an available connection output.");return tt(w[h.output])};if(s.kind==="command"){let h=await Ck(s.inputs,u),y=await this.commands.execute({command:s.command,timeoutSeconds:s.timeoutSeconds,...s.stdin===void 0?{}:{stdin:s.stdin},environment:h.environment,files:h.files,...e.kind==="function"?{workspace:"temporary"}:{}},n);if(e.kind==="function"){if(y.timedOut)throw new dt(408,"function_timeout","The function exceeded its time limit.");if(y.truncated)throw new dt(413,"function_output_limit","The function output exceeded its size limit.");if(y.exitCode!==0)throw new dt(422,"function_failed",mh(y.stderr,h.sensitive).slice(0,1e3)||"The function did not finish successfully.");return this.functionResult(e,r,y.stdout)}return{...y,stdout:mh(y.stdout,h.sensitive),stderr:mh(y.stderr,h.sensitive)}}let l=structuredClone(i);for(let h of l.bindings){let y="";for(let w of h.parts)if(typeof w=="string")y+=w;else{let b=Ra(await u(w));a.push(b,Buffer.from(b).toString("base64"),Buffer.from(b).toString("base64url")),y+=b}e3(l,h.pointer,y)}let d=l.body;l.json!==void 0&&(d=JSON.stringify(l.json),l.headers["content-type"]="application/json"),l.form!==void 0&&(d=new URLSearchParams(l.form).toString(),l.headers["content-type"]="application/x-www-form-urlencoded");let p=await this.transport.send({url:l.url,method:l.method,headers:l.headers,...d===void 0?{}:{body:d},signal:n});if(e.kind==="function"){if(p.status<200||p.status>=300)throw new dt(502,"service_response","The service returned HTTP "+p.status+".");let h=e.definition.program.kind==="http"?e.definition.program.responseFormat:"json",y=Ra(p.body);if(h==="json")try{y=p.body.length===0&&([204,205].includes(p.status)||l.method==="HEAD")?null:vr.parse(JSON.parse(y))}catch{throw new dt(422,"invalid_function_result","The HTTP response body must contain valid JSON.")}return this.functionResult(e,r,JSON.stringify({status:p.status,headers:p.headers,body:y}))}let f=e.kind==="http"?e.save:{};if(Object.keys(f).length){if(p.status>=400)throw new dt(502,"service_response","The service returned an unsuccessful response.");let h={};for(let[y,w]of Object.entries(f)){let b=p.body;if(y!==""){let x=xi(JSON.parse(Ra(b)),y);if(x===void 0)throw new dt(400,"invalid_pointer","The response value was not found.");b=tt(typeof x=="string"?x:JSON.stringify(x))}let S=await Gy(b,w.approval,r.id,this.binding,this.keys,{bytes:b.length});h[w.name]=(await this.broker.capture(w.name,S)).id}return{status:p.status,saved:h}}return{status:p.status,headers:Object.fromEntries(Object.entries(p.headers).map(([h,y])=>[h,mh(y,a)])),body:mh(Ra(p.body),a)}}async functionResult(e,r,o){let n;try{n=e.definition.result==="text"?o:vr.parse(JSON.parse(o))}catch{throw new dt(422,"invalid_function_result","The function must return valid JSON.")}let i={};for(let[s,a]of Object.entries(e.outputs)){let c=s===""?n:xi(n,s);if(c===void 0)throw new dt(400,"invalid_pointer","The function result value was not found.");let u=tt(typeof c=="string"?c:JSON.stringify(c)),l=await Gy(u,a.approval,r.id,this.binding,this.keys,{bytes:u.length});i[a.name]=(await this.broker.capture(a.name,l)).id}return Object.keys(i).length?{saved:i}:n}};import{spawn as THe}from"node:child_process";import{constants as s3}from"node:fs";import{open as npe,rm as CHe}from"node:fs/promises";async function ope(t){if(process.platform!=="linux"){let r=await npe(t,"wx",384).catch(()=>{throw new Error("This executor is locked. Check that its previous process has stopped before removing "+t+".")});return await r.writeFile(JSON.stringify({pid:process.pid})),async()=>{await r.close(),await CHe(t,{force:!0})}}let e=await npe(t,s3.O_CREAT|s3.O_WRONLY|s3.O_NOFOLLOW,384);try{let r=THe("flock",["--nonblock","--conflict-exit-code","73","3"],{stdio:["ignore","ignore","ignore",e.fd]});await new Promise((o,n)=>{r.once("error",()=>n(new Error("Install util-linux (flock) to run an executor on this host."))),r.once("close",i=>i===0?o():n(new Error(i===73?"This executor is already running.":"The executor lock could not be acquired.")))})}catch(r){throw await e.close(),r}return()=>e.close()}var PD=Vt(LV(),1),kD=Vt(U0e(),1);function L0e(t){return FL.safeParse(t).success?t:null}async function j0e(t=3e3){let e=new PD.STSClient({region:process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"us-east-1"}),r,o=AbortSignal.timeout(t);try{let n=await e.send(new PD.GetCallerIdentityCommand({}),{abortSignal:o});if(!n.Arn)return null;let i=L0e(n.Arn);if(i)return i;let s=/^arn:(aws[a-z-]*):sts::(\d{12}):assumed-role\/([^/]+)\/.+$/.exec(n.Arn);if(!s||n.Account!==s[2]||!n.UserId)return null;r=new kD.IAMClient({region:e.config.region,credentials:e.config.credentials});let c=(await r.send(new kD.GetRoleCommand({RoleName:s[3]}),{abortSignal:o})).Role;if(!c?.Arn||c.RoleId!==n.UserId.split(":")[0])return null;let u=L0e(c.Arn);return u?.startsWith(`arn:${s[1]}:iam::${s[2]}:role/`)&&u.split("/").at(-1)===s[3]?u:null}catch{return null}finally{e.destroy(),r?.destroy()}}var eG=m.string().refine(t=>!t.includes("\0"),"Use text without null bytes."),tG=eG.max(4096).startsWith("/"),F0e=m.object({command:m.array(eG.max(8192)).min(1).max(100).refine(t=>!!t[0],"Specify a program."),workingDirectory:tG.optional(),environment:m.record(m.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),eG.max(65536)).refine(t=>Object.keys(t).length<=128&&JSON.stringify(t).length<=1e6,"Use at most 128 environment variables and 1 MB of environment data.").default({}),stdin:m.string().max(1e6).default(""),timeoutSeconds:m.number().int().min(1).max(3600).default(60)}).strict(),a9t=F0e.extend({id:E.optional()}),q0e=m.enum(["queued","running","succeeded","failed","cancelled","uncertain"]),V0e=m.object({exitCode:m.number().int().nullable(),signal:m.string().max(32).nullable(),stdout:m.string().max(1e6),stderr:m.string().max(1e6),timedOut:m.boolean(),truncated:m.boolean()}).strict(),c9t=m.object({state:q0e.exclude(["queued","running"]),result:V0e.nullable(),error:m.string().max(100).nullable()}).strict(),TD=F0e.extend({id:E,environmentId:E,ownerId:E,actorId:E,workingDirectory:tG,state:q0e,result:V0e.nullable(),error:m.string().nullable(),createdAt:$e,startedAt:$e.nullable(),finishedAt:$e.nullable()}).strict(),u9t=TD.pick({id:!0,environmentId:!0,ownerId:!0,actorId:!0,state:!0,createdAt:!0}).strict(),l9t=m.object({workingDirectory:tG}).strict(),G0e=m.object({lease:E,process:TD}).strict().nullable();var CD=class{constructor(e){this.api=e}api;claim(e){return this.api.json("/api/environments/"+e+"/processes/claim",{method:"POST",body:{}},G0e)}dispatch(e,r){return this.api.json("/api/processes/"+e+"/dispatch",{method:"POST",body:{lease:r}})}renew(e,r){return this.api.json("/api/processes/"+e+"/renew",{method:"POST",body:{lease:r}},m.object({active:m.boolean()}))}finish(e,r,o){return this.api.json("/api/processes/"+e+"/finish",{method:"POST",body:{lease:r,...o}},TD)}},OD=class{constructor(e,r,o,n,i=15e3){this.environmentId=e;this.broker=r;this.journal=o;this.commands=n;this.renewalMilliseconds=i}environmentId;broker;journal;commands;renewalMilliseconds;async deliver(e){await this.broker.finish(e.id,e.lease,e.completion),await this.journal.write("process_"+e.id,{...e,delivered:!0})}async reconcile(){let e=[];for(let r of await this.journal.keys("process_")){let o=await this.journal.read(r);if(!(!o||o.delivered)){o.completion??={state:"uncertain",result:null,error:"execution_interrupted"},await this.journal.write(r,o);try{await this.deliver(o)}catch{e.push(o.id)}}}return e}async tick(e=new AbortController().signal){e.throwIfAborted();let r=await this.broker.claim(this.environmentId);if(!r)return!1;let{lease:o,process:n}=r,i=await this.journal.read("process_"+n.id);if(i){let l=i.completion??{state:"uncertain",result:null,error:"execution_interrupted"};return await this.broker.finish(n.id,o,l),!0}let s={id:n.id,lease:o,delivered:!1,completion:null};await this.journal.write("process_"+n.id,s);let a=new AbortController,c=()=>a.abort();e.addEventListener("abort",c,{once:!0}),e.aborted&&c();let u;try{await this.broker.dispatch(n.id,o),u=setInterval(()=>{this.broker.renew(n.id,o).then(d=>{d.active||c()},c)},this.renewalMilliseconds),u.unref();let l=await this.commands.execute({command:n.command,workingDirectory:n.workingDirectory,stdin:n.stdin,environment:n.environment,files:{},timeoutSeconds:n.timeoutSeconds},a.signal);s.completion={state:a.signal.aborted?"cancelled":l.exitCode===0&&!l.timedOut?"succeeded":"failed",result:l,error:null}}catch{s.completion={state:a.signal.aborted?"cancelled":"failed",result:null,error:"process_failed"}}finally{clearInterval(u),e.removeEventListener("abort",c)}await this.journal.write("process_"+n.id,s);try{await this.deliver(s)}catch{throw new Ia}return!0}};var DD=m.object({format:m.literal(1),functionId:E,ownerId:E,revision:m.number().int().positive(),definition:ei,author:Kt,executor:Kt,createdAt:$e,signature:cr}).strict();async function H0e(t,e){return DD.parse({...t,signature:await ir(t,e.signing,"function-publication")})}async function K0e(t,e){let r=DD.parse(t),{signature:o,...n}=r;if(await zs(n.author),await Ur(n,o,n.author.signing,"function-publication"),e&&C(n.executor)!==C(e))throw new Error("This function is approved for another executor.");return r}var rG=m.object({functionId:E,publication:DD,contents:m.record(E,m.object({version:m.number().int().positive(),content:tn}).strict())}).strict(),sot=m.object({name:fe,definition:ei,authorization:rG}).strict(),b9t=sot.extend({version:m.number().int().positive()}),aot=m.object({id:E.optional(),ownerId:E.optional(),arguments:Lt.default({}),outputs:m.record(m.string().max(500),R$).default({})}).strict(),B0e=m.object({code:m.string().max(100),message:m.string().max(1e3)}).strict(),Z0e=m.object({id:E,functionId:E,functionVersion:m.number().int().positive(),ownerId:E,actorId:E,state:E$,result:vr.nullable(),error:B0e.nullable(),createdAt:$e,startedAt:$e.nullable(),finishedAt:$e.nullable()}).strict(),cot=m.object({id:E,functionId:E,functionVersion:m.number().int().positive(),ownerId:E,actorId:E,actor:Kt.nullable(),arguments:Lt,outputs:aot.shape.outputs,definitionDigest:m.string().regex(/^[A-Za-z0-9_-]{43}$/),createdAt:$e,expiresAt:$e}).strict(),W0e=m.object({id:E,requestDigest:m.string().regex(/^[A-Za-z0-9_-]{43}$/),state:E$.exclude(["queued","running"]),result:vr.nullable(),error:B0e.nullable(),finishedAt:$e,signature:cr}).strict(),J0e=m.object({lease:E,request:cot,publication:DD,sources:m.array(tn).max(100)}).strict().nullable();var ND=class{api;constructor(e){this.api={async json(r,o={},n){try{return await e.json(r,o,n)}catch(i){throw i instanceof Error&&"status"in i&&typeof i.status=="number"&&"code"in i&&typeof i.code=="string"?new dt(i.status,i.code,i.message):i}}}}claim(e){return this.api.json("/api/environments/"+e+"/invocations/claim",{method:"POST",body:{}},J0e)}dispatch(e,r){return this.api.json("/api/runtime/functions/"+e+"/dispatch",{method:"POST",body:{lease:r}})}renew(e,r){return this.api.json("/api/runtime/functions/"+e+"/renew",{method:"POST",body:{lease:r}},m.object({active:m.boolean(),reason:m.enum(["cancelled","authorization_changed","lease_lost"]).optional()}))}finish(e,r){return this.api.json("/api/runtime/functions/"+r.id+"/finish",{method:"POST",body:{lease:e,completion:r}},Z0e)}},zD=class{constructor(e,r,o,n=15e3){this.executor=e;this.broker=r;this.journal=o;this.renewalMilliseconds=n}executor;broker;journal;renewalMilliseconds;async complete(e,r,o,n){let i={id:e.id,requestDigest:e.digest,state:r,result:o,error:n,finishedAt:new Date().toISOString()};e.completion=W0e.parse({...i,signature:await ir(i,this.executor.keys.signing,"function-result")}),e.phase="settled",await this.journal.write("invocation_"+e.id,e)}async deliver(e){await this.broker.finish(e.lease,e.completion),e.delivered=!0,await this.journal.write("invocation_"+e.id,e)}async reconcile(){let e=[];for(let r of await this.journal.keys("invocation_"))try{let o=await this.journal.read(r);if(!o||o.delivered||o.phase==="prepared")continue;o.completion||await this.complete(o,"uncertain",null,{code:"execution_interrupted",message:"Check the result before invoking this function again."}),await this.deliver(o)}catch{e.push(r.slice(11))}return e}async tick(e=new AbortController().signal){e.throwIfAborted();let r=await this.broker.claim(this.executor.environment.manifest.id);if(!r)return!1;let{request:o,publication:n,sources:i,lease:s}=r,a=await Q(o),c="invocation_"+o.id,u=await this.journal.read(c);if(u&&u.digest!==a)throw new Error("An invocation ID was reused for different input.");if(u?.completion)return u.lease=s,await this.deliver(u),!0;if(u?.phase==="dispatched")return u.lease=s,await this.complete(u,"uncertain",null,{code:"execution_interrupted",message:"Check the result before invoking this function again."}),await this.deliver(u),!0;u={id:o.id,digest:a,lease:s,phase:"prepared",delivered:!1,completion:null},await this.journal.write(c,u);let l=new AbortController,d=AbortSignal.any([e,l.signal]),p=!1,f=!1,h=setInterval(()=>{f||(f=!0,this.broker.renew(o.id,s).then(y=>{y.active||(p||=y.reason==="cancelled",l.abort())},()=>l.abort()).finally(()=>{f=!1}))},this.renewalMilliseconds);h.unref();try{if(await K0e(n,this.executor.binding),n.functionId!==o.functionId||n.definition.environmentId!==this.executor.environment.manifest.id||await Q(n.definition)!==o.definitionDigest||Date.parse(o.expiresAt)<=Date.now()||!Qa(n.definition.inputAccess)||Pf(n.definition.inputAccess)<Date.parse(o.expiresAt))throw new Error("Run the current approved function in its configured environment.");let y="function_"+n.functionId,w=await this.journal.read(y),b=await Q(n);if(w&&(n.revision<w.revision||n.revision===w.revision&&w.digest!==b))throw new Error("The function definition is older than this executor has already observed.");await this.journal.write(y,{revision:n.revision,digest:b});let S=w8.parse({kind:"function",functionId:o.functionId,definition:n.definition,arguments:o.arguments,outputs:o.outputs}),x={format:2,id:o.id,origin:this.executor.environment.manifest.origin,ownerId:o.ownerId,actor:o.actor??this.executor.binding,executor:this.executor.binding,environmentId:n.definition.environmentId,environmentDigest:await Q(this.executor.environment.manifest),operation:ue.function,operationDigest:await Q(S),functionId:o.functionId,functionDigest:o.definitionDigest,sources:await Promise.all(i.map(async T=>({id:T.policy.id,policyDigest:await Q(T.policy),materialRevision:T.materialRevision,...T.policy.contentType===he.tokenSet&&typeof T.metadata.authorizationDigest=="string"?{authorizationDigest:T.metadata.authorizationDigest}:{}}))),resultRecipients:[this.executor.binding],createdAt:o.createdAt,expiresAt:o.expiresAt};await Of(this.executor.environment,x),await this.executor.validateOperation(S,x,i),d.throwIfAborted(),await this.broker.dispatch(o.id,s),u.phase="dispatched",await this.journal.write(c,u),d.throwIfAborted();let R=await this.executor.executeOperation(S,x,i,d);if(new TextEncoder().encode(JSON.stringify(R)).byteLength>1e6)throw new dt(413,"result_too_large","The function completed, but its result exceeded the output limit.");await this.complete(u,"succeeded",R,null)}catch(y){if(y instanceof Ia)throw y;let w=u.phase==="dispatched",b=d.aborted&&p?"cancelled":w&&(d.aborted||i3(y))?"uncertain":"failed";await this.complete(u,b,null,b==="uncertain"?{code:"execution_uncertain",message:"The outcome could not be confirmed. Check the destination before invoking this function again."}:!d.aborted&&y instanceof dt?{code:y.code,message:y.message}:{code:b==="cancelled"?"invocation_cancelled":"invalid_function",message:b==="cancelled"?"The function was cancelled.":"The executor could not authorize this function."})}finally{clearInterval(h)}try{await this.deliver(u)}catch{throw new Ia}return!0}};import{spawn as uot,execFile as lot}from"node:child_process";import{chmod as dot,lstat as X0e,mkdir as nG,readFile as Y0e,readdir as pot,realpath as Q0e,rename as fot,rm as mot,symlink as hot,writeFile as eEe}from"node:fs/promises";import{join as yl}from"node:path";import{promisify as got}from"node:util";import{createConnection as yot}from"node:net";import{setTimeout as vot}from"node:timers/promises";var oG=got(lot),ob=t=>'"'+t.replaceAll("\\","\\\\").replaceAll('"','\\"')+'"',MD=class{constructor(e,r){this.options=e;this.heartbeat=r;if(!Number.isInteger(e.port)||e.port<1||e.port>65535)throw new Error("Use a valid SSH port.");for(let o of Object.values(e))if(typeof o=="string"&&/[\r\n\0]/.test(o))throw new Error("Use SSH paths and addresses without control characters.");this.sessions=yl(e.directory,"sessions")}options;heartbeat;child=null;hostKey="";appliedRevision=0;pending=null;timer;closing=!1;sessions;async start(){if(await nG(this.options.directory,{recursive:!0,mode:448}),await nG(this.sessions,{recursive:!0,mode:448}),await nG(this.options.workspace,{recursive:!0,mode:448}),this.options.workspaceLink)try{if(await X0e(this.options.workspaceLink),await Q0e(this.options.workspaceLink)!==await Q0e(this.options.workspace))throw new Error("The SSH workspace points to another environment.")}catch(s){if(!(s instanceof Error&&"code"in s&&s.code==="ENOENT"))throw s;await hot(this.options.workspace,this.options.workspaceLink)}let e=yl(this.options.directory,"host_ed25519");try{await X0e(e)}catch(s){if(!(s instanceof Error&&"code"in s&&s.code==="ENOENT"))throw s;await oG("ssh-keygen",["-q","-t","ed25519","-N","","-C","foundation-environment","-f",e],{env:qi(),timeout:1e4})}await dot(e,384),this.hostKey=by.parse((await oG("ssh-keygen",["-y","-f",e],{env:qi(),timeout:1e4})).stdout);let r=yl(this.options.directory,"sshd_config"),o=["Port "+this.options.port,...this.options.listenAddress?["ListenAddress "+this.options.listenAddress]:[],"HostKey "+ob(e),"PidFile "+ob(yl(this.options.directory,"sshd.pid")),"AuthorizedKeysFile "+ob(yl(this.options.directory,"authorized_keys")),"AllowUsers "+(this.options.username??"root"),"PubkeyAuthentication yes","AuthenticationMethods publickey","PasswordAuthentication no","KbdInteractiveAuthentication no","PermitEmptyPasswords no","PermitRootLogin prohibit-password","UsePAM no","StrictModes yes","PrintMotd no","Subsystem sftp /usr/lib/openssh/sftp-server","ForceCommand "+(this.options.sessionCommand??"/usr/local/bin/foundation-ssh-session"),"SetEnv "+ob("FOUNDATION_SSH_SESSIONS="+this.sessions)+" "+ob("FOUNDATION_SSH_WORKSPACE="+(this.options.workspaceLink??this.options.workspace)),"ClientAliveInterval 30","ClientAliveCountMax 3","LoginGraceTime 30"].join(`
132
132
  `)+`
133
133
  `;await eEe(r,o,{mode:384}),await this.sync(),await oG("/usr/sbin/sshd",["-t","-f",r],{env:qi(),timeout:1e4});let n=uot("/usr/sbin/sshd",["-D","-e","-f",r],{env:qi(),detached:!0,stdio:"ignore"});this.child=n;let i=null;n.once("error",s=>{i=s});try{for(let s=0;;s++){if(i||n.exitCode!==null||n.signalCode!==null||s>=100)throw i??new Error("The SSH server could not start.");if(await this.listening())break;await vot(50)}await this.sync(),this.timer=setInterval(()=>{!this.pending&&!this.closing&&(this.pending=this.sync().catch(()=>{process.stderr.write(JSON.stringify({event:"ssh_settings_pending"})+`
134
134
  `)}).finally(()=>{this.pending=null}))},1e4),this.timer.unref()}catch(s){throw await this.stop(),s}}ensureRunning(){if(!this.child?.pid||this.child.exitCode!==null||this.child.signalCode!==null)throw new Error("The SSH server has stopped.")}listening(){return new Promise(e=>{let r=yot({host:this.options.listenAddress==="::1"?"::1":"127.0.0.1",port:this.options.port});r.setTimeout(500),r.once("connect",()=>{r.destroy(),e(!0)}),r.once("error",()=>{r.destroy(),e(!1)}),r.once("timeout",()=>{r.destroy(),e(!1)})})}async activeSessions(){let e=0;for(let r of await pot(this.sessions)){if(!/^[1-9][0-9]*$/.test(r))continue;let o=yl(this.sessions,r);try{let[n,i]=await Promise.all([Y0e(o,"utf8"),Y0e("/proc/"+r+"/stat","utf8")]),s=a=>a.slice(a.lastIndexOf(")")+2).trim().split(/\s+/)[19];if(!s(n)||s(n)!==s(i))throw new Error("The SSH session has ended.");e++}catch{await mot(o,{force:!0})}}return Math.min(e,1024)}async sync(){let{configuration:e}=SE.parse(await this.heartbeat({hostKey:this.hostKey,appliedRevision:this.child?.pid&&this.child.exitCode===null&&this.child.signalCode===null?this.appliedRevision:0,activeSessions:await this.activeSessions()}));if(!e||e.port!==this.options.port)throw new Error("The SSH settings belong to another listener.");if(this.appliedRevision!==e.revision){let r=yl(this.options.directory,"authorized_keys."+crypto.randomUUID());await eEe(r,e.authorizedKeys.join(`
135
135
  `)+`
136
136
  `,{mode:384,flag:"wx"}),await fot(r,yl(this.options.directory,"authorized_keys")),this.appliedRevision=e.revision}}async stop(){this.closing=!0,clearInterval(this.timer),await this.pending;let e=this.child;this.child=null,!(!e?.pid||e.exitCode!==null||e.signalCode!==null)&&await new Promise(r=>{e.once("close",()=>r());try{process.kill(-e.pid,"SIGTERM")}catch{r()}let o=setTimeout(()=>{try{process.kill(-e.pid,"SIGKILL")}catch{}r()},2e3);o.unref(),e.once("close",()=>clearTimeout(o))})}};async function UD(t,e){let{directory:r,keys:o,binding:n,broker:i,transport:s}=Dn(t),a=E.parse(e.id??crypto.randomUUID()),c=ib(r,"executors",a);await wot(c,{recursive:!0,mode:448});let u=await ope(ib(c,"process.lock")),l=new AbortController,d=()=>l.abort();process.on("SIGINT",d),process.on("SIGTERM",d);let p;try{let f=new md(c,t.identity.origin,n,o),h=await f.read("environment_"+a),y=await j0e();if(h){if(await Cf(h),h.manifest.ownerId!==e.ownerId||C(h.manifest.executor)!==C(n))throw new Error("Use the owner and identity originally registered for this executor.");if(h.manifest.functionVersion!==dd||h.manifest.resultVersion!==1||(h.manifest.awsPrincipal??null)!==y){let{awsPrincipal:T,...M}=h.manifest;h=await VL({...M,functionVersion:dd,resultVersion:1,...y?{awsPrincipal:y}:{},revision:M.revision+1},o),await f.write("environment_"+a,h)}}else h=await VL({format:3,id:a,origin:t.identity.origin,ownerId:e.ownerId,name:e.name,executor:n,operatorId:n.principalId,driver:e.managed?"managed":"attached",capabilities:Object.values(ue),functionVersion:dd,resultVersion:1,isolation:e.isolation,...e.image?{commandImage:e.image}:{},...y?{awsPrincipal:y}:{},revision:1},o),await f.write("environment_"+a,h);await t.json("/api/environments/"+a+"/registration",{method:"PUT",body:h}),process.stdout.write(JSON.stringify({environmentId:a,identityId:n.principalId,fingerprint:await Ya(n),isolation:h.manifest.isolation,...h.manifest.awsPrincipal?{awsPrincipal:h.manifest.awsPrincipal}:{},...h.manifest.isolation==="process"?{notice:"Only allow trusted code on this host."}:{}})+`
137
137
  `);let w=new gh(n,o,i.connections(),f,s),b=new Nk(h,o,i,f,s,new Zy({isolation:h.manifest.isolation,image:h.manifest.commandImage}),w),S=new zD(b,new ND(t),f),x=h.manifest.isolation==="container"?"/workspace":process.cwd();await t.json("/api/environments/"+a+"/processes/registration",{method:"PUT",body:{workingDirectory:x}}),e.managed&&e.ssh&&(p=new MD({directory:ib(c,"ssh"),workspace:ib(c,"workspace"),workspaceLink:"/workspace",port:e.ssh.port},T=>t.json("/api/environments/"+a+"/ssh/heartbeat",{method:"POST",body:T},SE)),await p.start());let R=new OD(a,new CD(t),f,new Zy({isolation:h.manifest.isolation,image:h.manifest.commandImage,workspace:ib(c,"workspace")}));do{p?.ensureRunning();let T=[...await w.reconcile(),...await b.reconcile(),...await S.reconcile(),...await R.reconcile()];T.length&&process.stderr.write(JSON.stringify({event:"reconciliation_pending",ids:T})+`
138
- `);let M=!1;try{M=await b.tick(l.signal),M=await S.tick(l.signal)||M,M=await R.tick(l.signal)||M}catch(Z){if(!(Z instanceof Ia)||e.once)throw Z}if(e.once)break;M||await _ot(1e3,void 0,{signal:l.signal})}while(!l.signal.aborted)}catch(f){if(!l.signal.aborted)throw f}finally{try{await p?.stop()}finally{process.off("SIGINT",d),process.off("SIGTERM",d),await u()}}return 0}async function LD(t,e,r,o){let n=r?.policy??await t.policy(e,he.tokenSet,[]);if(!o)return n;let i=await Promise.all([...new Set(o)].map(async s=>{let{binding:a}=await t.inspectIdentity(s);return await t.trusted(a),a}));return n=en.parse({...n,revision:n.revision+(r?1:0),grants:[...n.grants.filter(s=>!("actor"in s)),...i.map(s=>({actor:s,executor:s,operations:[...ou(he.tokenSet)],origins:[],functionDigests:[],callerProgram:!0,expiresAt:new Date(Date.now()+30*864e5).toISOString()}))]}),n}function jD(t){if(xr(t.method).application==="none")return null;let e=t.app??Zn.parse({format:1,methodId:t.methodId,generation:crypto.randomUUID(),clientId:"",fields:{}});if(xr(t.method).requiresApp&&(!t.appId||e.methodId!==t.methodId))throw new Error("Choose an application for this connection method.");if(t.method.kind==="oauth"&&t.method.config.clientAuth!=="none"&&!e.clientSecret||t.method.kind==="ovh"&&(!e.clientId||!e.clientSecret))throw new Error("Enter the application client ID and secret.");return e}function tEe(t,e){let r={format:2,methodId:t.methodId,method:t.method,generation:crypto.randomUUID(),appId:t.appId,appGeneration:t.appId?t.app.generation:null};if(t.method.kind==="aws")return $n.parse({...r,aws:Ba.parse(t.aws)});if(t.method.kind==="oauth")return $n.parse({...r,requestedScopes:t.scopes,fields:fo(t.method.config.fields,t.app.fields)});let o=t.method.config.fields,n=Object.fromEntries(o.filter(s=>e?.fields?.[s.name]!==void 0).map(s=>[s.name,e.fields[s.name]])),i=Object.fromEntries(Object.entries(t.fields).filter(([s,a])=>a!==""||o.find(c=>c.name===s)?.secret===!1||n[s]===void 0));return $n.parse({...r,fields:F$(o,i,n)})}var FD=m.object({consumerKey:m.string().min(1).max(16384),validationUrl:m.url()});async function rEe(t,e,r,o,n){if(t.method.kind==="oauth"){if(t.method.config.registrationUrl&&!t.app.clientId){if(t.method.config.application!=="implicit"||t.method.config.clientAuth!=="none")throw new Error("Use dynamic registration only with an implicit public OAuth client.");let l=await e.send({url:Go(t.method.config.registrationUrl).href,method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_name:"Foundation",redirect_uris:[n],token_endpoint_auth_method:"none",grant_types:["authorization_code"],response_types:["code"]})});if(l.status>=400)throw new Error("The service could not register this connection.");let d=m.object({client_id:m.string().min(1).max(1e3),token_endpoint_auth_method:m.literal("none").optional()}).parse(ys(l));t.app.clientId=d.client_id}return{url:await new Jd(e).authorize(t.method.config,t.app,r,o,n,t.scopes)}}if(t.method.kind!=="ovh"||t.method.config.authorization!=="consumer_key")throw new Error("Choose a browser authorization method.");let i=new URL(n);i.searchParams.set("state",r);let s=Ec(t.method.config.apiBaseUrl,Us(t.method.config.fields,t.app.fields)).replace(/\/$/,"")+"/auth/credential",a=await e.send({url:s,method:"POST",headers:{"content-type":"application/json","X-Ovh-Application":t.app.clientId},body:JSON.stringify({redirection:i.href,accessRules:z5(Vi(t.method.config.scopes,t.scopes))})});if(a.status>=400)throw new Error("Check the OVHcloud application key and account region.");let c=FD.parse(ys(a)),u=Go(c.validationUrl);if(!["ovh.com","ovhcloud.com"].some(l=>u.hostname===l||u.hostname.endsWith("."+l)))throw new Error("OVHcloud returned an unexpected authorization address.");return{url:c.validationUrl,ovh:c}}async function nEe(t,e,r,o,n,i,s){let a=new URLSearchParams(r);if(a.getAll("state").length!==1||a.get("state")!==o)throw new Error("The authorization response does not match this connection.");if(a.has("error"))throw new Error("The service authorization was cancelled.");let c={format:2,methodId:t.methodId,method:t.method,generation:crypto.randomUUID(),appId:t.appId,appGeneration:t.appId?t.app.generation:null,fields:fo(xr(t.method).fields,t.app.fields),requestedScopes:t.scopes};if(t.method.kind==="ovh")return $n.parse({...c,fields:{...c.fields,consumerKey:FD.parse(s).consumerKey}});if(t.method.kind!=="oauth")throw new Error("Choose a browser authorization method.");let u=await new Jd(e).exchange(t.method.config,t.app,{parameters:a,state:o},n,i,t.scopes);return $n.parse({...c,oauth:u,...t.method.config.registrationUrl&&!t.appId?{implicitApp:t.app}:{}})}var qD=m.object({id:m.string().min(1).max(1e3),expiresAt:m.number().int().positive()}).strict();async function oEe(t,e,r={}){let o=await t.send({url:"https://api.runpod.io/graphql",method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({query:e,variables:r})});o.status>=400&&q(502,"authorization_failed","RunPod could not authorize this connection.");let n=ys(o);return n.errors&&q(502,"authorization_failed","RunPod could not authorize this connection."),m.record(m.string(),m.unknown()).parse(n.data)}async function iEe(t){let e=await oEe(t,`mutation createFlashAuthRequest {
138
+ `);let M=!1;try{M=await b.tick(l.signal),M=await S.tick(l.signal)||M,M=await R.tick(l.signal)||M}catch(Z){if(!(Z instanceof Ia)||e.once)throw Z}if(e.once)break;M||await _ot(1e3,void 0,{signal:l.signal})}while(!l.signal.aborted)}catch(f){if(!l.signal.aborted)throw f}finally{try{await p?.stop()}finally{process.off("SIGINT",d),process.off("SIGTERM",d),await u()}}return 0}async function LD(t,e,r,o){let n=r?.policy??await t.policy(e,he.tokenSet,[]);if(!o)return n;let i=await Promise.all([...new Set(o)].map(async s=>{let{binding:a}=await t.inspectIdentity(s);return await t.trusted(a),a}));return n=en.parse({...n,revision:n.revision+(r?1:0),grants:[...n.grants.filter(s=>!("actor"in s)),...i.map(s=>({actor:s,executor:s,operations:[...ou(he.tokenSet)],origins:[],functionDigests:[],callerProgram:!0,expiresAt:new Date(Date.now()+30*864e5).toISOString()}))]}),n}function jD(t){if(dr(t.method).application==="none")return null;let e=t.app??Zn.parse({format:1,methodId:t.methodId,generation:crypto.randomUUID(),clientId:"",fields:{}});if(dr(t.method).requiresApp&&(!t.appId||e.methodId!==t.methodId))throw new Error("Choose an application for this connection method.");if(t.method.kind==="oauth"&&t.method.config.clientAuth!=="none"&&!e.clientSecret||t.method.kind==="ovh"&&(!e.clientId||!e.clientSecret))throw new Error("Enter the application client ID and secret.");return e}function tEe(t,e){let r={format:2,methodId:t.methodId,method:t.method,generation:crypto.randomUUID(),appId:t.appId,appGeneration:t.appId?t.app.generation:null};if(t.method.kind==="aws")return $n.parse({...r,aws:Ba.parse(t.aws)});if(t.method.kind==="oauth")return $n.parse({...r,requestedScopes:t.scopes,fields:fo(t.method.config.fields,t.app.fields)});let o=t.method.config.fields,n=Object.fromEntries(o.filter(s=>e?.fields?.[s.name]!==void 0).map(s=>[s.name,e.fields[s.name]])),i=Object.fromEntries(Object.entries(t.fields).filter(([s,a])=>a!==""||o.find(c=>c.name===s)?.secret===!1||n[s]===void 0));return $n.parse({...r,fields:F$(o,i,n)})}var FD=m.object({consumerKey:m.string().min(1).max(16384),validationUrl:m.url()});async function rEe(t,e,r,o,n){if(t.method.kind==="oauth"){if(t.method.config.registrationUrl&&!t.app.clientId){if(t.method.config.application!=="implicit"||t.method.config.clientAuth!=="none")throw new Error("Use dynamic registration only with an implicit public OAuth client.");let l=await e.send({url:Go(t.method.config.registrationUrl).href,method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_name:"Foundation",redirect_uris:[n],token_endpoint_auth_method:"none",grant_types:["authorization_code"],response_types:["code"]})});if(l.status>=400)throw new Error("The service could not register this connection.");let d=m.object({client_id:m.string().min(1).max(1e3),token_endpoint_auth_method:m.literal("none").optional()}).parse(ys(l));t.app.clientId=d.client_id}return{url:await new Jd(e).authorize(t.method.config,t.app,r,o,n,t.scopes)}}if(t.method.kind!=="ovh"||t.method.config.authorization!=="consumer_key")throw new Error("Choose a browser authorization method.");let i=new URL(n);i.searchParams.set("state",r);let s=Ec(t.method.config.apiBaseUrl,Us(t.method.config.fields,t.app.fields)).replace(/\/$/,"")+"/auth/credential",a=await e.send({url:s,method:"POST",headers:{"content-type":"application/json","X-Ovh-Application":t.app.clientId},body:JSON.stringify({redirection:i.href,accessRules:z5(Vi(t.method.config.scopes,t.scopes))})});if(a.status>=400)throw new Error("Check the OVHcloud application key and account region.");let c=FD.parse(ys(a)),u=Go(c.validationUrl);if(!["ovh.com","ovhcloud.com"].some(l=>u.hostname===l||u.hostname.endsWith("."+l)))throw new Error("OVHcloud returned an unexpected authorization address.");return{url:c.validationUrl,ovh:c}}async function nEe(t,e,r,o,n,i,s){let a=new URLSearchParams(r);if(a.getAll("state").length!==1||a.get("state")!==o)throw new Error("The authorization response does not match this connection.");if(a.has("error"))throw new Error("The service authorization was cancelled.");let c={format:2,methodId:t.methodId,method:t.method,generation:crypto.randomUUID(),appId:t.appId,appGeneration:t.appId?t.app.generation:null,fields:fo(dr(t.method).fields,t.app.fields),requestedScopes:t.scopes};if(t.method.kind==="ovh")return $n.parse({...c,fields:{...c.fields,consumerKey:FD.parse(s).consumerKey}});if(t.method.kind!=="oauth")throw new Error("Choose a browser authorization method.");let u=await new Jd(e).exchange(t.method.config,t.app,{parameters:a,state:o},n,i,t.scopes);return $n.parse({...c,oauth:u,...t.method.config.registrationUrl&&!t.appId?{implicitApp:t.app}:{}})}var qD=m.object({id:m.string().min(1).max(1e3),expiresAt:m.number().int().positive()}).strict();async function oEe(t,e,r={}){let o=await t.send({url:"https://api.runpod.io/graphql",method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({query:e,variables:r})});o.status>=400&&q(502,"authorization_failed","RunPod could not authorize this connection.");let n=ys(o);return n.errors&&q(502,"authorization_failed","RunPod could not authorize this connection."),m.record(m.string(),m.unknown()).parse(n.data)}async function iEe(t){let e=await oEe(t,`mutation createFlashAuthRequest {
139
139
  createFlashAuthRequest { id status expiresAt }
140
140
  }`),r=m.object({id:m.string().min(1).max(1e3),expiresAt:m.iso.datetime({offset:!0})}).parse(e.createFlashAuthRequest),o=qD.parse({id:r.id,expiresAt:Date.parse(r.expiresAt)});o.expiresAt<=Date.now()&&q(409,"authorization_expired","Start the RunPod connection again.");let n=new URL("https://console.runpod.io/flash/login");return n.searchParams.set("request",r.id),{approval:o,url:n.href}}async function sEe(t,e){e.expiresAt<=Date.now()&&q(409,"authorization_expired","Start the RunPod connection again.");let r=await oEe(t,`query flashAuthRequestStatus($flashAuthRequestId: String!) {
141
141
  flashAuthRequestStatus(flashAuthRequestId: $flashAuthRequestId) { id status expiresAt apiKey }
142
- }`,{flashAuthRequestId:e.id}),o=m.object({id:m.string(),status:m.string(),apiKey:m.string().nullish()}).parse(r.flashAuthRequestStatus);return o.id!==e.id&&q(502,"invalid_response","RunPod returned another authorization request."),o.apiKey&&["APPROVED","CONSUMED"].includes(o.status)?m.string().min(1).max(16384).regex(/^\S+$/).parse(o.apiKey):(["DENIED","EXPIRED","CONSUMED"].includes(o.status)&&q(409,"authorization_failed","Start the RunPod connection again."),o.status!=="PENDING"&&q(502,"invalid_response","RunPod returned an unknown authorization state."),null)}var sb=m.object({id:E,ownerId:E,name:fe,registration:m.object({methodId:m.string().min(1),method:nu,appId:E.nullable(),app:Zn.nullable(),fields:m.record(m.string(),m.string()),scopes:m.array(m.string())}).strict(),policy:en,previousPolicyDigest:m.string().nullable(),step:m.enum(["start","cli","authorize","exchange","commit","connected","cancelled","failed"]),createdAt:m.iso.datetime(),expiresAt:m.number(),execution:m.object({id:E,index:m.number().int().nonnegative()}).strict(),url:m.url().nullable(),connectionId:E.nullable(),authorizationState:m.string(),verifier:m.string(),redirectUri:m.url(),ovh:FD.optional(),material:$n.optional(),proof:_J.optional(),approval:qD.optional(),error:m.string().optional(),exchangeStartedAt:m.number().optional(),exchangeDevice:m.enum(["browser","cli"])}).strict(),bot=sb.pick({id:!0,ownerId:!0,name:!0,execution:!0,error:!0}).strip(),VD=()=>Ds(crypto.getRandomValues(new Uint8Array(32))),GD=class{constructor(e,r,o=new $k(e.origin),n="browser"){this.custody=e;this.store=r;this.transport=o;this.device=n}custody;store;transport;device;approvalPolls=new Map;async flow(e){let r=await this.store.get(E.parse(e));if(!r)throw new Error("The saved progress for this connection is unavailable.");let o=sb.parse(r);if(o.policy.origin!==this.custody.origin||!o.policy.authorities.some(n=>C(n)===C(this.custody.binding)))throw new Error("Open this connection with its initiating identity.");return o}async start(e){let r=await this.custody.api.json("/api/executions/"+e.execution.id+"/input",{},If.extend({id:E}));if(r.index!==e.execution.index||r.invocation.name!=="connection.connect"||r.invocation.input.ownerId!==e.ownerId||r.invocation.input.methodId!==e.methodId||r.invocation.input.methodDigest!==await Q(e.method)||r.invocation.input.appId&&r.invocation.input.appId!==e.appId||r.invocation.input.name&&r.invocation.input.name!==e.name)throw new Error("Use the connection prepared by this operation.");for(let[h,y]of Object.entries(r.invocation.input.fields??{}))if(y&&e.fields?.[h]!==y)throw new Error("Use the service settings prepared by this operation.");if(!xr(e.method).browserAuthorization||e.method.kind==="token"||e.method.kind==="aws")throw new Error("Choose a browser authorization method.");let o=Vi(e.method.config.scopes,e.scopes);if(r.invocation.input.scopes&&C(o.slice().sort())!==C(Vi(e.method.config.scopes,r.invocation.input.scopes).sort()))throw new Error("Use the service permissions prepared by this operation.");let n={...!r.invocation.input.appId&&e.appId?{appId:e.appId}:{},...r.invocation.input.name?{}:{name:e.name}};Object.keys(n).length&&await this.custody.api.json("/api/executions/"+e.execution.id+"/input",{method:"PATCH",body:{index:e.execution.index,values:n}},Ze);let i=e.connectionId?await this.custody.read(e.connectionId):void 0;if(i&&(i.content.policy.contentType!==he.tokenSet||i.content.policy.ownerId!==e.ownerId))throw new Error("Choose a connection belonging to this owner.");let s=xr(e.method).requiresApp?E.parse(e.appId):null,a=s?Zn.parse(JSON.parse(Kn(await this.custody.reveal(s)))):null,c=jD({...e,app:a}),u=await LD(this.custody,e.ownerId,i?.content,e.users),l=await this.custody.api.json("/api/executions/"+e.execution.id,{},Ze),d=crypto.randomUUID(),p={id:d,ownerId:e.ownerId,name:e.name,registration:{methodId:e.methodId,method:e.method,appId:s,app:c,fields:e.fields??{},scopes:o},policy:u,previousPolicyDigest:i?await Q(i.content.policy):null,step:this.device==="browser"&&P8(e.method)==="unavailable"?"cli":"start",createdAt:new Date().toISOString(),expiresAt:Math.min(Date.now()+6e5,Date.parse(l.expiresAt)),execution:e.execution,url:null,connectionId:null,authorizationState:VD(),verifier:VD(),redirectUri:e.redirectUri??this.custody.origin+"/oauth/callback",exchangeDevice:this.device},f=new URL(p.redirectUri);if(p.redirectUri!==this.custody.origin+"/oauth/callback"&&!(this.device==="cli"&&f.protocol==="http:"&&["127.0.0.1","[::1]"].includes(f.hostname)&&!f.username&&!f.password&&!f.hash&&!f.search))throw new Error("Use the Foundation callback or a callback on this computer.");return await this.store.put(p),await this.custody.api.json("/api/executions/"+p.execution.id+"/continuation",{method:"PUT",body:{index:p.execution.index,continuation:{kind:"connection",id:d}}},Ze),this.progress(d)}view(e){return bot.parse(e)}async awaitingAuthorization(e){let r=await this.custody.api.json("/api/executions/"+e.execution.id+"/input",{},If.extend({id:E}));if(r.index!==e.execution.index||r.continuation?.id!==e.id||r.invocation.input.methodDigest!==await Q(e.registration.method))throw new Error("Continue the connection that is awaiting authorization.")}async pollApproval(e){if(e.expiresAt<=Date.now())throw new Error("Start the connection again.");await this.awaitingAuthorization(e);let r=await sEe(this.transport,qD.parse(e.approval));return r?(await this.awaitingAuthorization(e),e.material=$n.parse({format:2,methodId:e.registration.methodId,method:e.registration.method,generation:crypto.randomUUID(),appId:null,appGeneration:null,fields:{token:r}}),e.step="commit",await this.store.put(e),this.accept(e.id)):{kind:"authorize",flow:this.view(e),url:e.url}}cli(e){return{kind:"cli",flow:this.view(e),command:(e.step==="authorize"?"foundation connect wait ":"foundation execution continue ")+e.execution.id}}async authorize(e){if(e.expiresAt<=Date.now())throw new Error("Start the connection again.");if(e.registration.method.kind==="approval"){let o=await iEe(this.transport);return e.approval=o.approval,e.expiresAt=Math.min(e.expiresAt,o.approval.expiresAt),e.step="authorize",e.url=o.url,await this.store.put(e),{kind:"authorize",flow:this.view(e),url:e.url}}e.redirectUri===this.custody.origin+"/oauth/callback"&&await this.custody.api.json("/api/oauth/relays",{method:"POST",body:{id:e.id,executionId:e.execution.id,index:e.execution.index,stateDigest:await Q(e.authorizationState),expiresAt:new Date(e.expiresAt).toISOString()}},yj);let r=await rEe(e.registration,this.transport,e.authorizationState,e.verifier,e.redirectUri);return e.step="authorize",e.url=r.url,"ovh"in r&&(e.ovh=r.ovh),await this.store.put(e),{kind:"authorize",flow:this.view(e),url:e.url}}async progress(e,r=!0){let o=await this.flow(e);if(o.step==="connected")return o.proof&&await this.custody.api.json("/api/executions/"+o.execution.id+"/complete",{method:"POST",body:{index:o.execution.index,proof:o.proof}},Ze),{kind:"connected",flow:this.view(o),id:o.connectionId};if(o.step==="cancelled")return{kind:"cancelled",flow:this.view(o)};if(o.step==="failed")return{kind:"failed",flow:this.view(o),error:o.error??"authorization_failed"};if(o.step==="commit")return this.accept(e);if(o.step==="exchange"){if(Date.now()-(o.exchangeStartedAt??Date.now())<3e4)return{kind:"pending",flow:this.view(o)};o.step="cli",o.error="browser_exchange_unavailable",await this.store.put(o)}if(o.step==="cli"){if(this.device==="browser")return this.cli(o);let n=await this.custody.api.json("/api/executions/"+o.execution.id,{},Ze);o.step="start",o.exchangeDevice="cli",o.authorizationState=VD(),o.verifier=VD(),o.expiresAt=Math.min(Date.now()+6e5,Date.parse(n.expiresAt)),delete o.error,await this.store.put(o)}if(o.step==="start")return this.authorize(o);if(o.exchangeDevice==="cli"&&this.device==="browser")return this.cli(o);if(o.registration.method.kind==="approval"){let n=this.approvalPolls.get(e);n||(n=this.pollApproval(o),this.approvalPolls.set(e,n));try{return await n}finally{this.approvalPolls.get(e)===n&&this.approvalPolls.delete(e)}}if(r&&o.redirectUri===this.custody.origin+"/oauth/callback"){let n=await this.custody.api.json("/api/oauth/relays/"+e,{},yj);if(n.id!==e||n.executionId!==o.execution.id||n.context!==$J(this.custody.origin,e))throw new Error("The authorization response belongs to another connection.");if(n.sealed)return this.complete(e,Kn(await Po(n.sealed,this.custody.keys.encryption,this.custody.binding.id,n.context)))}return{kind:"authorize",flow:this.view(o),url:o.url}}async complete(e,r){let o=await this.flow(e);if(o.step!=="authorize")return this.progress(e,!1);if(o.exchangeDevice==="cli"&&this.device==="browser")return this.cli(o);if(o.expiresAt<=Date.now())throw new Error("Start the connection again.");await this.awaitingAuthorization(o);let n=new URLSearchParams(r);if(n.getAll("state").length!==1||n.get("state")!==o.authorizationState)throw new Error("The authorization response does not match this connection.");if(n.has("error"))return this.cancel(e);if(o.registration.appId){let i=Zn.parse(JSON.parse(Kn(await this.custody.reveal(o.registration.appId)))),s=o.registration.app;if(i.methodId!==s.methodId||i.generation!==s.generation||i.clientId!==s.clientId||C(i.fields)!==C(s.fields))throw new Error("Start authorization again with the current application.");o.registration.app=i}o.step="exchange",o.exchangeStartedAt=Date.now(),await this.store.put(o);try{o.material=await nEe(o.registration,this.transport,r,o.authorizationState,o.verifier,o.redirectUri,o.ovh)}catch(i){if(o.error=i&&typeof i=="object"&&"code"in i&&typeof i.code=="string"?i.code:"authorization_failed",o.step=o.error==="browser_exchange_unavailable"?"cli":"failed",await this.store.put(o),o.step==="cli"&&this.device==="browser")return this.cli(o);throw i}return o.step="commit",await this.store.put(o),this.accept(e)}async accept(e){let r=await this.flow(e);if(r.step!=="commit"||!r.material)throw new Error("Complete authorization before saving this connection.");let o=r.previousPolicyDigest?await this.custody.read(r.policy.id):void 0;if(o&&await Q(o.content.policy)!==r.previousPolicyDigest)throw new Error("The connection recipients changed. Start again to approve the current recipients.");let n=async i=>(r.proof=i,await this.store.put(r),await this.custody.api.json("/api/executions/"+r.execution.id+"/complete",{method:"POST",body:{index:r.execution.index,proof:i}},Ze),this.custody.api.json("/api/resources/"+r.policy.id,{},br));return r.proof?await n(r.proof):await this.custody.save(r.name,tt(C(r.material)),r.policy,{previous:o,metadata:await Ff(r.material),labels:V$(r.material),commit:n}),r.step="connected",r.connectionId=r.policy.id,await this.store.put(r),{kind:"connected",flow:this.view(r),id:r.connectionId}}async cancel(e){let r=await this.flow(e);return await this.custody.api.json("/api/executions/"+r.execution.id+"/cancel",{method:"POST",body:{}},Ze),r.step="cancelled",await this.store.put(r),{kind:"cancelled",flow:this.view(r)}}};var aEe=m.object({id:E,actorId:E,bindingId:E,origin:m.url(),revision:m.number().int().positive(),sealed:Ao,signature:cr}).strict(),cEe=(t,e)=>"operation-continuation:"+t+":"+e,ab=class{constructor(e){this.custody=e}custody;revisions=new Map;async get(e,r){let o=await this.custody.api.json("/api/operation-continuations/"+E.parse(e),{},aEe.nullable());if(!o)return this.revisions.set(e,0),null;let{signature:n,...i}=o;if(i.id!==e||i.origin!==this.custody.origin||i.actorId!==this.custody.binding.principalId||i.bindingId!==this.custody.binding.id)throw new Error("Use the identity that started this operation.");await Ur(i,n,this.custody.binding.signing,"operation-continuation");let s=r.parse(JSON.parse(Kn(await Po(i.sealed,this.custody.keys.encryption,this.custody.binding.id,cEe(this.custody.origin,e)))));return this.revisions.set(e,i.revision),s}async put(e,r){this.revisions.has(e)||await this.get(e,m.unknown());let o={id:e,origin:this.custody.origin,actorId:this.custody.binding.principalId,bindingId:this.custody.binding.id,revision:this.revisions.get(e)+1,sealed:await Xa(tt(C(r)),[{id:this.custody.binding.id,publicKey:this.custody.binding.encryption}],cEe(this.custody.origin,e))},n=await ir(o,this.custody.keys.signing,"operation-continuation");await this.custody.api.json("/api/operation-continuations/"+e,{method:"PUT",body:{...o,signature:n}},aEe),this.revisions.set(e,o.revision)}},HD=class{records;constructor(e){this.records=new ab(e)}async get(e){let r=await this.records.get(e,sb);if(r&&r.id!==e)throw new Error("The saved progress belongs to another operation.");return r}put(e){return this.records.put(e.id,sb.parse(e))}};var iG=class extends Error{constructor(r,o){super("The function invocation could not be confirmed. Invocation ID: "+r+". Check its result or retry with the same ID.",{cause:o});this.invocationId=r}invocationId},Pa=class{constructor(e,r){this.api=e;this.custody=r}api;custody;get(e){return this.api.json("/api/functions/"+E.parse(e),{},a$)}async prepare(e){if(!this.custody)throw new Error("Use your encryption keys to approve a function definition.");let r=this.custody,o=ei.parse(e.definition);if(o.program.kind==="http"&&o.result!=="json")throw new Error("HTTP functions return a JSON response containing status, headers, and body.");if(o.inputAccess.expiresAt!==null&&Date.parse(o.inputAccess.expiresAt)<=Date.now())throw new Error("Choose a future expiration for this function\u2019s input access.");let n=await r.environment(o.environmentId);if(n.manifest.functionVersion!==dd)throw new Error("Update this execution environment to the current Foundation CLI.");let i=e.resourceId??crypto.randomUUID(),s=await r.sourceContents(epe(o).map(p=>p.id)),a=new Set(s.map(p=>p.policy.id));if(e.resourceId){let p=await this.api.json("/api/functions/"+i+"/authorizations",{},Mr(rv));for(let f of p.items)a.has(f.content.policy.id)||(await r.observe(f.content),s.push(f.content))}let c={},u={id:i,digest:await Q(o)};for(let p of s){let f=await r.read(p.policy.id);if(!f.content.policy.authorities.some(y=>C(y)===C(r.binding)))throw new Error("An authority of each input must approve its use by this function.");let h=en.parse({...f.content.policy,revision:f.content.policy.revision+1,grants:[...f.content.policy.grants.filter(y=>!("function"in y)||y.function.id!==i),...a.has(p.policy.id)?[{function:u,executor:n.manifest.executor,operations:s8(p.policy.contentType),expiresAt:o.inputAccess.expiresAt}]:[]]});c[p.policy.id]={version:f.version,content:await ad(await cd(f.content,r.binding,r.keys.encryption),h,f.content.materialRevision+1,r.binding,r.keys,f.content.metadata,f.content)}}let l=await H0e({format:1,functionId:i,ownerId:e.ownerId,revision:e.resourceId?(e.version??0)+1:1,definition:o,author:r.binding,executor:n.manifest.executor,createdAt:new Date().toISOString()},r.keys);return rG.parse({functionId:i,publication:l,contents:c})}async remember(e){if(this.custody)for(let{content:r}of Object.values(e.contents))await this.custody.trust.rememberContent(r)}async save(e){if(!this.custody)throw new Error("Use your encryption keys to approve a function definition.");let r=Rf.parse(e),o=await this.api.json("/api/executions",{method:"POST",body:{operations:[{name:"function.save",input:Lt.parse(r)}]}},Ze),n=await this.prepare(r),i=await this.api.json("/api/executions/"+o.id+"/complete",{method:"POST",body:{index:o.index,proof:n}},Ze);return await this.remember(n),a$.parse(i.results[o.index])}async invoke(e,r={},o={}){let n=o.id??crypto.randomUUID(),i={};if(Object.keys(o.save??{}).length){if(!this.custody)throw new Error("Use your keys to approve encrypted output destinations.");let{executor:s}=await this.api.json("/api/functions/"+E.parse(e)+"/output-recipient",{},m.object({executor:Kt}));await this.custody.trusted(s);let a={manifest:{executor:s}};for(let[c,u]of Object.entries(o.save))i[c]=await this.custody.output(o.ownerId??this.custody.binding.principalId,u,n,a,new Date(Date.now()+36e5).toISOString())}try{return await this.api.json("/api/functions/"+E.parse(e)+"/executions",{method:"POST",body:{id:n,arguments:r,outputs:i,...o.ownerId?{ownerId:o.ownerId}:{}}},Ze)}catch(s){throw s instanceof Error&&"status"in s?s:new iG(n,s)}}result(e){return this.api.json("/api/executions/"+E.parse(e),{},Ze)}cancel(e){return this.api.json("/api/executions/"+E.parse(e)+"/cancel",{method:"POST",body:{}},Ze)}remove(e){return this.api.json("/api/functions/"+E.parse(e),{method:"DELETE"})}};var uEe=m.object({value:m.string().optional(),clientSecret:m.string().optional(),fields:m.record(m.string(),m.string()).optional(),scopes:m.array(m.string()).optional(),aws:Ba.optional()}).strict(),KD=class{constructor(e,r){this.custody=e;this.connections=r;this.records=new ab(e)}custody;connections;records;connectionNames=new Map;async start(e){if(e.name==="run.execute"){let r=Fy.parse(e.input);if(!("programId"in r.operation)){let o=await this.program(r.operation),n=crypto.randomUUID();await this.records.put(n,{operation:o,save:r.save}),e={...e,input:{...r,operation:{kind:r.operation.kind,programId:n,programDigest:await Q(Dk(o))}}}}}return this.custody.api.json("/api/executions",{method:"POST",body:{operations:[Fi.parse(e)]}},Ze)}async plan(e){return this.custody.api.json("/api/executions/"+E.parse(e)+"/input",{},If.extend({id:E}))}async complete(e,r,o){return this.custody.api.json("/api/executions/"+e+"/complete",{method:"POST",body:{index:r,proof:o}},Ze)}async configure(e,r){let o=await this.plan(e);return this.custody.api.json("/api/executions/"+e+"/input",{method:"PATCH",body:{index:o.index,values:r}},Ze)}async execute(e,r={}){let o=await this.start(e);return o.waiting?this.continue(o.id,r):o}async method(e){let r=(await this.custody.api.json("/api/connection-methods",{},Mr(zy))).items.find(u=>u.id===e);if(!r)throw new Error("Choose an available connection method.");this.connectionNames.set(e,r.defaultName);let{id:o,builtin:n,availability:i,registration:s,defaultName:a,...c}=r;return c}async program(e){return ec.parse(e)}async continue(e,r={}){let o=await this.custody.api.json("/api/executions/"+E.parse(e),{},Ze);if(!o.waiting)return o;let n=await this.plan(e),{name:i,input:s}=n.invocation;if(i==="app.save"||i==="connection.connect"){let a=await this.method(String(s.methodId)),c=a.kind==="aws"?[]:a.config.fields,u=fo(c,r.fields??{});if(i==="connection.connect"&&s.appId){let p=await this.custody.api.json("/api/resources/"+E.parse(s.appId),{},br);if(p.kind!=="app")throw new Error("Choose a connection application.");u={...p.data.fields,...u}}let l=s.fields,d=jf(c,l??{},u);if(Object.entries(u).some(([p,f])=>l?.[p]!==f))return await this.configure(e,{fields:d}),this.continue(e,r)}if(i==="connection.authorize"){let a=Q5.parse(s),c=await this.custody.read(a.connectionId);if(c.version!==a.version||c.content.policy.ownerId!==a.ownerId||c.content.policy.contentType!==he.tokenSet)throw new Error("Review the current connection before changing its permissions.");let u=await this.userPolicy(c.content.policy,a.users,a.expiresAt),l=await this.custody.api.json("/api/resources/"+a.connectionId,{},br);return{kind:"saved",resource:await this.custody.save(l.name,await this.custody.reveal(a.connectionId),u,{previous:c,metadata:c.content.metadata,commit:async p=>br.parse((await this.complete(e,n.index,p)).results[n.index])}),executionId:e}}if(i==="function.save"){let a=new Pa(this.custody.api,this.custody),c=await a.prepare(Rf.parse(s)),u=await this.complete(e,n.index,yr.parse(c));return await a.remember(c),{kind:"saved",resource:br.parse(u.results[n.index]),executionId:e}}if(i==="variable.save"||i==="app.save"){let a=i==="app.save"?zL.parse(s):Y5.parse(s),c=a.resourceId?await this.custody.read(a.resourceId):void 0;if(c&&c.version!==a.version)throw new Error("This item changed. Reload it before saving.");let u=await Promise.all((a.environmentIds??[]).map(y=>this.custody.environment(y))),l=i==="app.save"?he.clientCredential:he.value;if(c&&(c.content.policy.contentType!==l||c.content.policy.ownerId!==a.ownerId))throw new Error("Choose the item prepared by this operation.");let d=c&&a.environmentIds===void 0?c.content.policy:await this.custody.policy(a.ownerId,l,u,{previous:c?.content.policy}),p,f;if(i==="app.save"){let y=zL.parse(s),w=c?Zn.parse(JSON.parse(Kn(await this.custody.reveal(c.content.policy.id)))):null,b=await this.method(y.methodId),S=jf(b.kind==="aws"?[]:b.config.fields,y.fields??{},r.fields??{}),x=w&&w.methodId===y.methodId&&w.clientId===y.clientId&&C(w.fields)===C(S),R=Zn.parse({format:1,methodId:y.methodId,clientId:y.clientId,fields:S,generation:x?w.generation:crypto.randomUUID(),...r.clientSecret||w?.clientSecret?{clientSecret:r.clientSecret||w?.clientSecret}:{}});p=tt(C(R)),f={methodId:R.methodId,clientId:R.clientId,generation:R.generation,fields:fo(b.kind==="aws"?[]:b.config.fields,S)}}else{if(r.value===void 0)throw new Error("Enter the value to save.");p=typeof r.value=="string"?tt(r.value):r.value}return{kind:"saved",resource:await this.custody.save(a.name,p,d,{previous:c,metadata:f,commit:async y=>br.parse((await this.complete(e,n.index,y)).results[n.index])}),executionId:e}}if(i==="connection.connect"){if(n.continuation?.kind==="connection")return this.connections.progress(n.continuation.id);let a=e8.parse(s),c=await this.method(a.methodId);if(!a.name)return await this.configure(e,{name:this.connectionNames.get(a.methodId)??c.name}),this.continue(e,r);if(r.scopes&&!a.scopes&&(c.kind==="oauth"||c.kind==="ovh"))return await this.configure(e,{scopes:r.scopes}),this.continue(e,r);if(r.scopes&&a.scopes&&(c.kind==="oauth"||c.kind==="ovh")&&C(Vi(c.config.scopes,r.scopes).sort())!==C(Vi(c.config.scopes,a.scopes).sort()))throw new Error("Use the service permissions prepared by this operation.");let u=a.appId;if(lu(c)&&!u){if(!a.clientId)throw new Error("Enter the application client ID.");let l=Zn.parse({format:1,methodId:a.methodId,clientId:a.clientId,generation:crypto.randomUUID(),fields:jf(c.kind==="aws"?[]:c.config.fields,a.fields??{},r.fields??{}),...r.clientSecret?{clientSecret:r.clientSecret}:{}}),d=await this.custody.policy(a.ownerId,he.clientCredential,[]);u=(await this.custody.save((a.name??c.name).slice(0,185)+" application",tt(C(l)),d,{metadata:{methodId:l.methodId,clientId:l.clientId,generation:l.generation,fields:fo(c.kind==="aws"?[]:c.config.fields,l.fields)},commit:async f=>{let h=await this.custody.api.json("/api/executions/"+e+"/preparation",{method:"POST",body:{index:n.index,proof:f}},Ze);return this.custody.api.json("/api/resources/"+h.operations[n.index].input.appId,{},br)}})).id}if(!xr(c).browserAuthorization){if(await Q(c)!==a.methodDigest)throw new Error("Review the current connection method.");let l=a.connectionId?await this.custody.read(a.connectionId):void 0;if(l&&(l.content.policy.ownerId!==a.ownerId||l.content.policy.contentType!==he.tokenSet))throw new Error("Choose a connection belonging to this owner.");let d=l?$n.parse(JSON.parse(Kn(await this.custody.reveal(a.connectionId)))):void 0,p=jD({methodId:a.methodId,method:c,appId:u,app:u?Zn.parse(JSON.parse(Kn(await this.custody.reveal(u)))):null}),f=tEe({methodId:a.methodId,method:c,appId:u??null,app:p,fields:jf(xr(c).fields,a.fields??{},r.fields??{}),scopes:c.kind==="oauth"?Vi(c.config.scopes,a.scopes):[],aws:r.aws},d),h=await LD(this.custody,a.ownerId,l?.content,a.users);return{kind:"saved",resource:await this.custody.save(a.name??c.name,tt(C(f)),h,{previous:l,metadata:await Ff(f),labels:V$(f),commit:async w=>{let S=(await this.complete(e,n.index,w)).results[n.index];return this.custody.api.json("/api/resources/"+S.id,{},br)}}),executionId:e}}return this.connections.start({ownerId:a.ownerId,name:a.name??c.name,methodId:a.methodId,method:c,appId:u,connectionId:a.connectionId,fields:jf(c.kind==="aws"?[]:c.config.fields,a.fields??{},r.fields??{}),scopes:a.scopes,users:a.users,redirectUri:a.redirectUri,execution:{id:e,index:n.index}})}if(i==="run.execute"||i==="connection.revoke"){if(n.continuation?.kind==="run"){let h;try{h=await this.custody.api.json("/api/runtime/runs/"+n.continuation.id,{},Bn)}catch(y){if(!y||typeof y!="object"||!("code"in y)||y.code!=="not_found")throw y;let w=await this.records.get(n.continuation.id,kf);if(!w)throw y;h=await this.custody.submitPrepared(w)}return["queued","running"].includes(h.state)||await this.complete(e,n.index,{runId:h.id}),{kind:"run",task:h,executionId:e}}let a=i==="connection.revoke"?y$.parse(s):null,c=a?{...a,operation:{kind:"revoke",input:{action:"revoke",id:a.connectionId}},save:{}}:Fy.parse(s),u;if("programId"in c.operation){let h=await this.records.get(c.operation.programId,tpe);if(!h||await Q(Dk(h.operation))!==c.operation.programDigest)throw new Error("Use the reviewed private program.");u=h.operation}else u=c.operation.kind==="revoke"?c.operation:await this.program(c.operation);let l=crypto.randomUUID(),d=c.environmentId;if(!d)throw new Error("Choose an execution environment.");let p=await this.custody.prepare(c.ownerId,d,u,{id:l,save:c.save,approval:n.approval,...a?{sourceIds:[a.connectionId]}:{},operationContext:{id:e,index:n.index,invocation:n.invocation}});return await this.records.put(p.intent.id,p),await this.custody.api.json("/api/executions/"+e+"/continuation",{method:"PUT",body:{index:n.index,continuation:{kind:"run",id:p.intent.id}}},Ze),{kind:"run",task:await this.custody.submitPrepared(p),executionId:e}}throw new Error("Choose a supported keyholder operation.")}async userPolicy(e,r,o,n=!0){let i=o??new Date(Date.now()+2592e6).toISOString(),s=await Promise.all([...new Set(r)].map(async a=>{let{binding:c}=await this.custody.inspectIdentity(a);return await this.custody.trusted(c),c}));return en.parse({...e,revision:e.revision+(n?1:0),grants:[...e.grants.filter(a=>!("actor"in a)),...s.map(a=>({actor:a,executor:a,operations:[...ou(e.contentType)],origins:[],functionDigests:[],callerProgram:!0,expiresAt:i}))]})}};function Ri(t,e=Dn(t).custody){let r=new GD(e,new HD(e),new yh(e.origin),"cli");return new KD(e,r)}import{randomBytes as Sot}from"node:crypto";import{execFile as xot}from"node:child_process";import{promisify as Eot}from"node:util";import{lstat as $ot}from"node:fs/promises";async function lEe(){let t=process.env.FOUNDATION_EXECUTOR_BOOTSTRAP;if(!t)throw new Error("The executor enrollment is missing.");let e=wJ.parse(JSON.parse(Buffer.from(t,"base64url").toString("utf8")));e.origin=uu(e.origin),delete process.env.FOUNDATION_EXECUTOR_BOOTSTRAP;let r=!1;try{await $ot(rc()),r=!0}catch(c){if(!(c instanceof Error&&"code"in c&&c.code==="ENOENT"))throw c}if(!r){let c=await m$(),u=h$(e.executorId,c);await Ky({origin:e.origin,principalId:e.executorId,token:"fk_"+Sot(32).toString("base64url"),keys:c,binding:u})}let o=await I$(e.origin),n=new tc(o);if(o.principalId!==e.executorId||!o.keys||!o.binding)throw new Error("The saved keys belong to another executor.");if(!(await n.session().catch(async c=>{if(!(c instanceof cu)||c.status!==401)throw c;return await Rot(e,n),n.session()})).principal)throw new Error("The executor credential is no longer active.");let s=Eot(xot),a=qi();try{await s("docker",["image","inspect",e.commandImage],{env:a})}catch{await s("docker",["pull",e.commandImage],{env:a,timeout:3e5,maxBuffer:2e6})}return UD(n,{id:e.id,ownerId:e.ownerId,name:e.name,isolation:"container",image:e.commandImage,managed:!0,ssh:e.ssh})}async function Rot(t,e){let{keys:r,binding:o,token:n}=e.identity;if(!r||!o)throw new Error("Create executor keys before enrollment.");if(!(await fetch(t.origin+"/api/environments/"+t.id+"/enroll",{method:"POST",redirect:"error",signal:AbortSignal.timeout(3e4),headers:{"content-type":"application/json"},body:JSON.stringify({bootstrap:t.bootstrap,token:n,binding:await jy(o,r)})})).ok)throw new Error("The executor could not enroll. Keep its saved keys and check the environment status.")}var at;(function(t){t.assertEqual=n=>{};function e(n){}t.assertIs=e;function r(n){throw new Error}t.assertNever=r,t.arrayToEnum=n=>{let i={};for(let s of n)i[s]=s;return i},t.getValidEnumValues=n=>{let i=t.objectKeys(n).filter(a=>typeof n[n[a]]!="number"),s={};for(let a of i)s[a]=n[a];return t.objectValues(s)},t.objectValues=n=>t.objectKeys(n).map(function(i){return n[i]}),t.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{let i=[];for(let s in n)Object.prototype.hasOwnProperty.call(n,s)&&i.push(s);return i},t.find=(n,i)=>{for(let s of n)if(i(s))return s},t.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function o(n,i=" | "){return n.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}t.joinValues=o,t.jsonStringifyReplacer=(n,i)=>typeof i=="bigint"?i.toString():i})(at||(at={}));var dEe;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(dEe||(dEe={}));var Y=at.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),kc=t=>{switch(typeof t){case"undefined":return Y.undefined;case"string":return Y.string;case"number":return Number.isNaN(t)?Y.nan:Y.number;case"boolean":return Y.boolean;case"function":return Y.function;case"bigint":return Y.bigint;case"symbol":return Y.symbol;case"object":return Array.isArray(t)?Y.array:t===null?Y.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?Y.promise:typeof Map<"u"&&t instanceof Map?Y.map:typeof Set<"u"&&t instanceof Set?Y.set:typeof Date<"u"&&t instanceof Date?Y.date:Y.object;default:return Y.unknown}};var L=at.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);var Ko=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=o=>{this.issues=[...this.issues,o]},this.addIssues=(o=[])=>{this.issues=[...this.issues,...o]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(i){return i.message},o={_errors:[]},n=i=>{for(let s of i.issues)if(s.code==="invalid_union")s.unionErrors.map(n);else if(s.code==="invalid_return_type")n(s.returnTypeError);else if(s.code==="invalid_arguments")n(s.argumentsError);else if(s.path.length===0)o._errors.push(r(s));else{let a=o,c=0;for(;c<s.path.length;){let u=s.path[c],l=c===s.path.length-1;if(u==="_errors"){l&&a._errors.push(r(s)),c++;continue}Object.prototype.hasOwnProperty.call(a,u)||(u==="__proto__"?Object.defineProperty(a,u,{value:{_errors:[]},writable:!0,enumerable:!0,configurable:!0}):a[u]={_errors:[]}),a=a[u],l&&a._errors.push(r(s)),c++}}};return n(this),o}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,at.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r=Object.create(null),o=[];for(let n of this.issues)if(n.path.length>0){let i=n.path[0];r[i]=r[i]||[],r[i].push(e(n))}else o.push(e(n));return{formErrors:o,fieldErrors:r}}get formErrors(){return this.flatten()}};Ko.create=t=>new Ko(t);var Iot=(t,e)=>{let r;switch(t.code){case L.invalid_type:t.received===Y.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case L.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,at.jsonStringifyReplacer)}`;break;case L.unrecognized_keys:r=`Unrecognized key(s) in object: ${at.joinValues(t.keys,", ")}`;break;case L.invalid_union:r="Invalid input";break;case L.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${at.joinValues(t.options)}`;break;case L.invalid_enum_value:r=`Invalid enum value. Expected ${at.joinValues(t.options)}, received '${t.received}'`;break;case L.invalid_arguments:r="Invalid function arguments";break;case L.invalid_return_type:r="Invalid function return type";break;case L.invalid_date:r="Invalid date";break;case L.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:at.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case L.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case L.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case L.custom:r="Invalid input";break;case L.invalid_intersection_types:r="Intersection results could not be merged";break;case L.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case L.not_finite:r="Number must be finite";break;default:r=e.defaultError,at.assertNever(t)}return{message:r}},vl=Iot;var Aot=vl;function cb(){return Aot}var BD=t=>{let{data:e,path:r,errorMaps:o,issueData:n}=t,i=[...r,...n.path||[]],s={...n,path:i};if(n.message!==void 0)return{...n,path:i,message:n.message};let a="",c=o.filter(u=>!!u).slice().reverse();for(let u of c)a=u(s,{data:e,defaultError:a}).message;return{...n,path:i,message:a}};function W(t,e){let r=cb(),o=BD({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===vl?void 0:vl].filter(n=>!!n)});t.common.issues.push(o)}var Nn=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let o=[];for(let n of r){if(n.status==="aborted")return we;n.status==="dirty"&&e.dirty(),o.push(n.value)}return{status:e.value,value:o}}static async mergeObjectAsync(e,r){let o=[];for(let n of r){let i=await n.key,s=await n.value;o.push({key:i,value:s})}return t.mergeObjectSync(e,o)}static mergeObjectSync(e,r){let o={};for(let n of r){let{key:i,value:s}=n;if(i.status==="aborted"||s.status==="aborted")return we;i.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||n.alwaysSet)&&(o[i.value]=s.value)}return{status:e.value,value:o}}},we=Object.freeze({status:"aborted"}),Sh=t=>({status:"dirty",value:t}),to=t=>({status:"valid",value:t}),sG=t=>t.status==="aborted",aG=t=>t.status==="dirty",tp=t=>t.status==="valid",ub=t=>typeof Promise<"u"&&t instanceof Promise;var ie;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(ie||(ie={}));var Ii=class{constructor(e,r,o,n){this._cachedPath=[],this.parent=e,this.data=r,this._path=o,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},pEe=(t,e)=>{if(tp(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Ko(t.common.issues);return this._error=r,this._error}}};function ze(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:o,description:n}=t;if(e&&(r||o))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(s,a)=>{let{message:c}=t;return s.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??o??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:n}}var He=class{get description(){return this._def.description}_getType(e){return kc(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:kc(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Nn,ctx:{common:e.parent.common,data:e.data,parsedType:kc(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(ub(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let o=this.safeParse(e,r);if(o.success)return o.data;throw o.error}safeParse(e,r){let o={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kc(e)},n=this._parseSync({data:e,path:o.path,parent:o});return pEe(o,n)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kc(e)};if(!this["~standard"].async)try{let o=this._parseSync({data:e,path:[],parent:r});return tp(o)?{value:o.value}:{issues:r.common.issues}}catch(o){o?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(o=>tp(o)?{value:o.value}:{issues:r.common.issues})}async parseAsync(e,r){let o=await this.safeParseAsync(e,r);if(o.success)return o.data;throw o.error}async safeParseAsync(e,r){let o={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kc(e)},n=this._parse({data:e,path:o.path,parent:o}),i=await(ub(n)?n:Promise.resolve(n));return pEe(o,i)}refine(e,r){let o=n=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(n):r;return this._refinement((n,i)=>{let s=e(n),a=()=>i.addIssue({code:L.custom,...o(n)});return typeof Promise<"u"&&s instanceof Promise?s.then(c=>c?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(e,r){return this._refinement((o,n)=>e(o)?!0:(n.addIssue(typeof r=="function"?r(o,n):r),!1))}_refinement(e){return new bs({schema:this,typeName:F.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:r=>this["~validate"](r)}}optional(){return _s.create(this,this._def)}nullable(){return Oc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return _l.create(this)}promise(){return rp.create(this,this._def)}or(e){return Ih.create([this,e],this._def)}and(e){return Ah.create(this,e,this._def)}transform(e){return new bs({...ze(this._def),schema:this,typeName:F.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Oh({...ze(this._def),innerType:this,defaultValue:r,typeName:F.ZodDefault})}brand(){return new ZD({typeName:F.ZodBranded,type:this,...ze(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Dh({...ze(this._def),innerType:this,catchValue:r,typeName:F.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return WD.create(this,e)}readonly(){return Nh.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Pot=/^c[^\s-]{8,}$/i,kot=/^[0-9a-z]+$/,Tot=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Cot=/^[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,Oot=/^[a-z0-9_-]{21}$/i,Dot=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Not=/^[-+]?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)?)??$/,zot=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Mot="^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$",cG,Uot=/^(?:(?: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])$/,Lot=/^(?:(?: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])$/,jot=/^(([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]))$/,Fot=/^(([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])$/,qot=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Vot=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,fEe="((\\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])))",Got=new RegExp(`^${fEe}$`);function mEe(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function Hot(t){return new RegExp(`^${mEe(t)}$`)}function Kot(t){let e=`${fEe}T${mEe(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function Bot(t,e){return!!((e==="v4"||!e)&&Uot.test(t)||(e==="v6"||!e)&&jot.test(t))}function Zot(t,e){if(!Dot.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let o=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(o));return!(typeof n!="object"||n===null||"typ"in n&&n?.typ!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function Wot(t,e){return!!((e==="v4"||!e)&&Lot.test(t)||(e==="v6"||!e)&&Fot.test(t))}var Eh=class t extends He{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Y.string){let i=this._getOrReturnCtx(e);return W(i,{code:L.invalid_type,expected:Y.string,received:i.parsedType}),we}let o=new Nn,n;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(n=this._getOrReturnCtx(e,n),W(n,{code:L.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),o.dirty());else if(i.kind==="max")e.data.length>i.value&&(n=this._getOrReturnCtx(e,n),W(n,{code:L.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),o.dirty());else if(i.kind==="length"){let s=e.data.length>i.value,a=e.data.length<i.value;(s||a)&&(n=this._getOrReturnCtx(e,n),s?W(n,{code:L.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&W(n,{code:L.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),o.dirty())}else if(i.kind==="email")zot.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"email",code:L.invalid_string,message:i.message}),o.dirty());else if(i.kind==="emoji")cG||(cG=new RegExp(Mot,"u")),cG.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"emoji",code:L.invalid_string,message:i.message}),o.dirty());else if(i.kind==="uuid")Cot.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"uuid",code:L.invalid_string,message:i.message}),o.dirty());else if(i.kind==="nanoid")Oot.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"nanoid",code:L.invalid_string,message:i.message}),o.dirty());else if(i.kind==="cuid")Pot.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"cuid",code:L.invalid_string,message:i.message}),o.dirty());else if(i.kind==="cuid2")kot.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"cuid2",code:L.invalid_string,message:i.message}),o.dirty());else if(i.kind==="ulid")Tot.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"ulid",code:L.invalid_string,message:i.message}),o.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),W(n,{validation:"url",code:L.invalid_string,message:i.message}),o.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"regex",code:L.invalid_string,message:i.message}),o.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(n=this._getOrReturnCtx(e,n),W(n,{code:L.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),o.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(n=this._getOrReturnCtx(e,n),W(n,{code:L.invalid_string,validation:{startsWith:i.value},message:i.message}),o.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(n=this._getOrReturnCtx(e,n),W(n,{code:L.invalid_string,validation:{endsWith:i.value},message:i.message}),o.dirty()):i.kind==="datetime"?Kot(i).test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{code:L.invalid_string,validation:"datetime",message:i.message}),o.dirty()):i.kind==="date"?Got.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{code:L.invalid_string,validation:"date",message:i.message}),o.dirty()):i.kind==="time"?Hot(i).test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{code:L.invalid_string,validation:"time",message:i.message}),o.dirty()):i.kind==="duration"?Not.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"duration",code:L.invalid_string,message:i.message}),o.dirty()):i.kind==="ip"?Bot(e.data,i.version)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"ip",code:L.invalid_string,message:i.message}),o.dirty()):i.kind==="jwt"?Zot(e.data,i.alg)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"jwt",code:L.invalid_string,message:i.message}),o.dirty()):i.kind==="cidr"?Wot(e.data,i.version)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"cidr",code:L.invalid_string,message:i.message}),o.dirty()):i.kind==="base64"?qot.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"base64",code:L.invalid_string,message:i.message}),o.dirty()):i.kind==="base64url"?Vot.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"base64url",code:L.invalid_string,message:i.message}),o.dirty()):at.assertNever(i);return{status:o.value,value:e.data}}_regex(e,r,o){return this.refinement(n=>e.test(n),{validation:r,code:L.invalid_string,...ie.errToObj(o)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...ie.errToObj(e)})}url(e){return this._addCheck({kind:"url",...ie.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...ie.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...ie.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...ie.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...ie.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...ie.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...ie.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...ie.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...ie.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...ie.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...ie.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...ie.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...ie.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...ie.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...ie.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...ie.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...ie.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...ie.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...ie.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...ie.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...ie.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...ie.errToObj(r)})}nonempty(e){return this.min(1,ie.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...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 r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Eh.create=t=>new Eh({checks:[],typeName:F.ZodString,coerce:t?.coerce??!1,...ze(t)});function Jot(t,e){let r=(t.toString().split(".")[1]||"").length,o=(e.toString().split(".")[1]||"").length,n=r>o?r:o,i=Number.parseInt(t.toFixed(n).replace(".","")),s=Number.parseInt(e.toFixed(n).replace(".",""));return i%s/10**n}var lb=class t extends He{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==Y.number){let i=this._getOrReturnCtx(e);return W(i,{code:L.invalid_type,expected:Y.number,received:i.parsedType}),we}let o,n=new Nn;for(let i of this._def.checks)i.kind==="int"?at.isInteger(e.data)||(o=this._getOrReturnCtx(e,o),W(o,{code:L.invalid_type,expected:"integer",received:"float",message:i.message}),n.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(o=this._getOrReturnCtx(e,o),W(o,{code:L.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(o=this._getOrReturnCtx(e,o),W(o,{code:L.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="multipleOf"?Jot(e.data,i.value)!==0&&(o=this._getOrReturnCtx(e,o),W(o,{code:L.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(o=this._getOrReturnCtx(e,o),W(o,{code:L.not_finite,message:i.message}),n.dirty()):at.assertNever(i);return{status:n.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,ie.toString(r))}gt(e,r){return this.setLimit("min",e,!1,ie.toString(r))}lte(e,r){return this.setLimit("max",e,!0,ie.toString(r))}lt(e,r){return this.setLimit("max",e,!1,ie.toString(r))}setLimit(e,r,o,n){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:o,message:ie.toString(n)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:ie.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ie.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ie.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ie.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ie.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:ie.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:ie.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ie.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ie.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&at.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let o of this._def.checks){if(o.kind==="finite"||o.kind==="int"||o.kind==="multipleOf")return!0;o.kind==="min"?(r===null||o.value>r)&&(r=o.value):o.kind==="max"&&(e===null||o.value<e)&&(e=o.value)}return Number.isFinite(r)&&Number.isFinite(e)}};lb.create=t=>new lb({checks:[],typeName:F.ZodNumber,coerce:t?.coerce||!1,...ze(t)});var db=class t extends He{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)!==Y.bigint)return this._getInvalidInput(e);let o,n=new Nn;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(o=this._getOrReturnCtx(e,o),W(o,{code:L.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(o=this._getOrReturnCtx(e,o),W(o,{code:L.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(o=this._getOrReturnCtx(e,o),W(o,{code:L.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):at.assertNever(i);return{status:n.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return W(r,{code:L.invalid_type,expected:Y.bigint,received:r.parsedType}),we}gte(e,r){return this.setLimit("min",e,!0,ie.toString(r))}gt(e,r){return this.setLimit("min",e,!1,ie.toString(r))}lte(e,r){return this.setLimit("max",e,!0,ie.toString(r))}lt(e,r){return this.setLimit("max",e,!1,ie.toString(r))}setLimit(e,r,o,n){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:o,message:ie.toString(n)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ie.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ie.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ie.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ie.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:ie.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};db.create=t=>new db({checks:[],typeName:F.ZodBigInt,coerce:t?.coerce??!1,...ze(t)});var pb=class extends He{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==Y.boolean){let o=this._getOrReturnCtx(e);return W(o,{code:L.invalid_type,expected:Y.boolean,received:o.parsedType}),we}return to(e.data)}};pb.create=t=>new pb({typeName:F.ZodBoolean,coerce:t?.coerce||!1,...ze(t)});var fb=class t extends He{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Y.date){let i=this._getOrReturnCtx(e);return W(i,{code:L.invalid_type,expected:Y.date,received:i.parsedType}),we}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return W(i,{code:L.invalid_date}),we}let o=new Nn,n;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(n=this._getOrReturnCtx(e,n),W(n,{code:L.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),o.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(n=this._getOrReturnCtx(e,n),W(n,{code:L.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),o.dirty()):at.assertNever(i);return{status:o.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:ie.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:ie.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};fb.create=t=>new fb({checks:[],coerce:t?.coerce||!1,typeName:F.ZodDate,...ze(t)});var mb=class extends He{_parse(e){if(this._getType(e)!==Y.symbol){let o=this._getOrReturnCtx(e);return W(o,{code:L.invalid_type,expected:Y.symbol,received:o.parsedType}),we}return to(e.data)}};mb.create=t=>new mb({typeName:F.ZodSymbol,...ze(t)});var $h=class extends He{_parse(e){if(this._getType(e)!==Y.undefined){let o=this._getOrReturnCtx(e);return W(o,{code:L.invalid_type,expected:Y.undefined,received:o.parsedType}),we}return to(e.data)}};$h.create=t=>new $h({typeName:F.ZodUndefined,...ze(t)});var Rh=class extends He{_parse(e){if(this._getType(e)!==Y.null){let o=this._getOrReturnCtx(e);return W(o,{code:L.invalid_type,expected:Y.null,received:o.parsedType}),we}return to(e.data)}};Rh.create=t=>new Rh({typeName:F.ZodNull,...ze(t)});var hb=class extends He{constructor(){super(...arguments),this._any=!0}_parse(e){return to(e.data)}};hb.create=t=>new hb({typeName:F.ZodAny,...ze(t)});var wl=class extends He{constructor(){super(...arguments),this._unknown=!0}_parse(e){return to(e.data)}};wl.create=t=>new wl({typeName:F.ZodUnknown,...ze(t)});var ka=class extends He{_parse(e){let r=this._getOrReturnCtx(e);return W(r,{code:L.invalid_type,expected:Y.never,received:r.parsedType}),we}};ka.create=t=>new ka({typeName:F.ZodNever,...ze(t)});var gb=class extends He{_parse(e){if(this._getType(e)!==Y.undefined){let o=this._getOrReturnCtx(e);return W(o,{code:L.invalid_type,expected:Y.void,received:o.parsedType}),we}return to(e.data)}};gb.create=t=>new gb({typeName:F.ZodVoid,...ze(t)});var _l=class t extends He{_parse(e){let{ctx:r,status:o}=this._processInputParams(e),n=this._def;if(r.parsedType!==Y.array)return W(r,{code:L.invalid_type,expected:Y.array,received:r.parsedType}),we;if(n.exactLength!==null){let s=r.data.length>n.exactLength.value,a=r.data.length<n.exactLength.value;(s||a)&&(W(r,{code:s?L.too_big:L.too_small,minimum:a?n.exactLength.value:void 0,maximum:s?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),o.dirty())}if(n.minLength!==null&&r.data.length<n.minLength.value&&(W(r,{code:L.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),o.dirty()),n.maxLength!==null&&r.data.length>n.maxLength.value&&(W(r,{code:L.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),o.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>n.type._parseAsync(new Ii(r,s,r.path,a)))).then(s=>Nn.mergeArray(o,s));let i=[...r.data].map((s,a)=>n.type._parseSync(new Ii(r,s,r.path,a)));return Nn.mergeArray(o,i)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:ie.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:ie.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:ie.toString(r)}})}nonempty(e){return this.min(1,e)}};_l.create=(t,e)=>new _l({type:t,minLength:null,maxLength:null,exactLength:null,typeName:F.ZodArray,...ze(e)});function xh(t){if(t instanceof Bo){let e={};for(let r in t.shape){let o=t.shape[r];e[r]=_s.create(xh(o))}return new Bo({...t._def,shape:()=>e})}else return t instanceof _l?new _l({...t._def,type:xh(t.element)}):t instanceof _s?_s.create(xh(t.unwrap())):t instanceof Oc?Oc.create(xh(t.unwrap())):t instanceof Cc?Cc.create(t.items.map(e=>xh(e))):t}var Bo=class t extends He{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(),r=at.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==Y.object){let u=this._getOrReturnCtx(e);return W(u,{code:L.invalid_type,expected:Y.object,received:u.parsedType}),we}let{status:o,ctx:n}=this._processInputParams(e),{shape:i,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof ka&&this._def.unknownKeys==="strip"))for(let u in n.data)s.includes(u)||a.push(u);let c=[];for(let u of s){let l=i[u],d=n.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Ii(n,d,n.path,u)),alwaysSet:u in n.data})}if(this._def.catchall instanceof ka){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:n.data[l]}});else if(u==="strict")a.length>0&&(W(n,{code:L.unrecognized_keys,keys:a}),o.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=n.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Ii(n,d,n.path,l)),alwaysSet:l in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,p=await l.value;u.push({key:d,value:p,alwaysSet:l.alwaysSet})}return u}).then(u=>Nn.mergeObjectSync(o,u)):Nn.mergeObjectSync(o,c)}get shape(){return this._def.shape()}strict(e){return ie.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,o)=>{let n=this._def.errorMap?.(r,o).message??o.defaultError;return r.code==="unrecognized_keys"?{message:ie.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:F.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let o of at.objectKeys(e))e[o]&&this.shape[o]&&(r[o]=this.shape[o]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let o of at.objectKeys(this.shape))e[o]||(r[o]=this.shape[o]);return new t({...this._def,shape:()=>r})}deepPartial(){return xh(this)}partial(e){let r={};for(let o of at.objectKeys(this.shape)){let n=this.shape[o];e&&!e[o]?r[o]=n:r[o]=n.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let o of at.objectKeys(this.shape))if(e&&!e[o])r[o]=this.shape[o];else{let i=this.shape[o];for(;i instanceof _s;)i=i._def.innerType;r[o]=i}return new t({...this._def,shape:()=>r})}keyof(){return hEe(at.objectKeys(this.shape))}};Bo.create=(t,e)=>new Bo({shape:()=>t,unknownKeys:"strip",catchall:ka.create(),typeName:F.ZodObject,...ze(e)});Bo.strictCreate=(t,e)=>new Bo({shape:()=>t,unknownKeys:"strict",catchall:ka.create(),typeName:F.ZodObject,...ze(e)});Bo.lazycreate=(t,e)=>new Bo({shape:t,unknownKeys:"strip",catchall:ka.create(),typeName:F.ZodObject,...ze(e)});var Ih=class extends He{_parse(e){let{ctx:r}=this._processInputParams(e),o=this._def.options;function n(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let s=i.map(a=>new Ko(a.ctx.common.issues));return W(r,{code:L.invalid_union,unionErrors:s}),we}if(r.common.async)return Promise.all(o.map(async i=>{let s={...r,common:{...r.common,issues:[]},parent:null};return{result:await i._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(n);{let i,s=[];for(let c of o){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!i&&(i={result:l,ctx:u}),u.common.issues.length&&s.push(u.common.issues)}if(i)return r.common.issues.push(...i.ctx.common.issues),i.result;let a=s.map(c=>new Ko(c));return W(r,{code:L.invalid_union,unionErrors:a}),we}}get options(){return this._def.options}};Ih.create=(t,e)=>new Ih({options:t,typeName:F.ZodUnion,...ze(e)});var Tc=t=>t instanceof Ph?Tc(t.schema):t instanceof bs?Tc(t.innerType()):t instanceof kh?[t.value]:t instanceof Th?t.options:t instanceof Ch?at.objectValues(t.enum):t instanceof Oh?Tc(t._def.innerType):t instanceof $h?[void 0]:t instanceof Rh?[null]:t instanceof _s?[void 0,...Tc(t.unwrap())]:t instanceof Oc?[null,...Tc(t.unwrap())]:t instanceof ZD||t instanceof Nh?Tc(t.unwrap()):t instanceof Dh?Tc(t._def.innerType):[],uG=class t extends He{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==Y.object)return W(r,{code:L.invalid_type,expected:Y.object,received:r.parsedType}),we;let o=this.discriminator,n=r.data[o],i=this.optionsMap.get(n);return i?r.common.async?i._parseAsync({data:r.data,path:r.path,parent:r}):i._parseSync({data:r.data,path:r.path,parent:r}):(W(r,{code:L.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[o]}),we)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,o){let n=new Map;for(let i of r){let s=Tc(i.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of s){if(n.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);n.set(a,i)}}return new t({typeName:F.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:n,...ze(o)})}};function lG(t,e){let r=kc(t),o=kc(e);if(t===e)return{valid:!0,data:t};if(r===Y.object&&o===Y.object){let n=at.objectKeys(e),i=at.objectKeys(t).filter(a=>n.indexOf(a)!==-1),s={...t,...e};Object.prototype.hasOwnProperty.call(s,"__proto__")&&delete s.__proto__;for(let a of i){if(a==="__proto__")continue;let c=lG(t[a],e[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===Y.array&&o===Y.array){if(t.length!==e.length)return{valid:!1};let n=[];for(let i=0;i<t.length;i++){let s=t[i],a=e[i],c=lG(s,a);if(!c.valid)return{valid:!1};n.push(c.data)}return{valid:!0,data:n}}else return r===Y.date&&o===Y.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Ah=class extends He{_parse(e){let{status:r,ctx:o}=this._processInputParams(e),n=(i,s)=>{if(sG(i)||sG(s))return we;let a=lG(i.value,s.value);return a.valid?((aG(i)||aG(s))&&r.dirty(),{status:r.value,value:a.data}):(W(o,{code:L.invalid_intersection_types}),we)};return o.common.async?Promise.all([this._def.left._parseAsync({data:o.data,path:o.path,parent:o}),this._def.right._parseAsync({data:o.data,path:o.path,parent:o})]).then(([i,s])=>n(i,s)):n(this._def.left._parseSync({data:o.data,path:o.path,parent:o}),this._def.right._parseSync({data:o.data,path:o.path,parent:o}))}};Ah.create=(t,e,r)=>new Ah({left:t,right:e,typeName:F.ZodIntersection,...ze(r)});var Cc=class t extends He{_parse(e){let{status:r,ctx:o}=this._processInputParams(e);if(o.parsedType!==Y.array)return W(o,{code:L.invalid_type,expected:Y.array,received:o.parsedType}),we;if(o.data.length<this._def.items.length)return W(o,{code:L.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),we;!this._def.rest&&o.data.length>this._def.items.length&&(W(o,{code:L.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let i=[...o.data].map((s,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Ii(o,s,o.path,a)):null}).filter(s=>!!s);return o.common.async?Promise.all(i).then(s=>Nn.mergeArray(r,s)):Nn.mergeArray(r,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Cc.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Cc({items:t,typeName:F.ZodTuple,rest:null,...ze(e)})};var dG=class t extends He{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:o}=this._processInputParams(e);if(o.parsedType!==Y.object)return W(o,{code:L.invalid_type,expected:Y.object,received:o.parsedType}),we;let n=[],i=this._def.keyType,s=this._def.valueType;for(let a in o.data)n.push({key:i._parse(new Ii(o,a,o.path,a)),value:s._parse(new Ii(o,o.data[a],o.path,a)),alwaysSet:a in o.data});return o.common.async?Nn.mergeObjectAsync(r,n):Nn.mergeObjectSync(r,n)}get element(){return this._def.valueType}static create(e,r,o){return r instanceof He?new t({keyType:e,valueType:r,typeName:F.ZodRecord,...ze(o)}):new t({keyType:Eh.create(),valueType:e,typeName:F.ZodRecord,...ze(r)})}},yb=class extends He{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:o}=this._processInputParams(e);if(o.parsedType!==Y.map)return W(o,{code:L.invalid_type,expected:Y.map,received:o.parsedType}),we;let n=this._def.keyType,i=this._def.valueType,s=[...o.data.entries()].map(([a,c],u)=>({key:n._parse(new Ii(o,a,o.path,[u,"key"])),value:i._parse(new Ii(o,c,o.path,[u,"value"]))}));if(o.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of s){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return we;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of s){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return we;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};yb.create=(t,e,r)=>new yb({valueType:e,keyType:t,typeName:F.ZodMap,...ze(r)});var vb=class t extends He{_parse(e){let{status:r,ctx:o}=this._processInputParams(e);if(o.parsedType!==Y.set)return W(o,{code:L.invalid_type,expected:Y.set,received:o.parsedType}),we;let n=this._def;n.minSize!==null&&o.data.size<n.minSize.value&&(W(o,{code:L.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),r.dirty()),n.maxSize!==null&&o.data.size>n.maxSize.value&&(W(o,{code:L.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),r.dirty());let i=this._def.valueType;function s(c){let u=new Set;for(let l of c){if(l.status==="aborted")return we;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...o.data.values()].map((c,u)=>i._parse(new Ii(o,c,o.path,u)));return o.common.async?Promise.all(a).then(c=>s(c)):s(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:ie.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:ie.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};vb.create=(t,e)=>new vb({valueType:t,minSize:null,maxSize:null,typeName:F.ZodSet,...ze(e)});var pG=class t extends He{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==Y.function)return W(r,{code:L.invalid_type,expected:Y.function,received:r.parsedType}),we;function o(a,c){return BD({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,cb(),vl].filter(u=>!!u),issueData:{code:L.invalid_arguments,argumentsError:c}})}function n(a,c){return BD({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,cb(),vl].filter(u=>!!u),issueData:{code:L.invalid_return_type,returnTypeError:c}})}let i={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof rp){let a=this;return to(async function(...c){let u=new Ko([]),l=await a._def.args.parseAsync(c,i).catch(f=>{throw u.addIssue(o(c,f)),u}),d=await Reflect.apply(s,this,l);return await a._def.returns._def.type.parseAsync(d,i).catch(f=>{throw u.addIssue(n(d,f)),u})})}else{let a=this;return to(function(...c){let u=a._def.args.safeParse(c,i);if(!u.success)throw new Ko([o(c,u.error)]);let l=Reflect.apply(s,this,u.data),d=a._def.returns.safeParse(l,i);if(!d.success)throw new Ko([n(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Cc.create(e).rest(wl.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,o){return new t({args:e||Cc.create([]).rest(wl.create()),returns:r||wl.create(),typeName:F.ZodFunction,...ze(o)})}},Ph=class extends He{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Ph.create=(t,e)=>new Ph({getter:t,typeName:F.ZodLazy,...ze(e)});var kh=class extends He{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return W(r,{received:r.data,code:L.invalid_literal,expected:this._def.value}),we}return{status:"valid",value:e.data}}get value(){return this._def.value}};kh.create=(t,e)=>new kh({value:t,typeName:F.ZodLiteral,...ze(e)});function hEe(t,e){return new Th({values:t,typeName:F.ZodEnum,...ze(e)})}var Th=class t extends He{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),o=this._def.values;return W(r,{expected:at.joinValues(o),received:r.parsedType,code:L.invalid_type}),we}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),o=this._def.values;return W(r,{received:r.data,code:L.invalid_enum_value,options:o}),we}return to(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(o=>!e.includes(o)),{...this._def,...r})}};Th.create=hEe;var Ch=class extends He{_parse(e){let r=at.getValidEnumValues(this._def.values),o=this._getOrReturnCtx(e);if(o.parsedType!==Y.string&&o.parsedType!==Y.number){let n=at.objectValues(r);return W(o,{expected:at.joinValues(n),received:o.parsedType,code:L.invalid_type}),we}if(this._cache||(this._cache=new Set(at.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let n=at.objectValues(r);return W(o,{received:o.data,code:L.invalid_enum_value,options:n}),we}return to(e.data)}get enum(){return this._def.values}};Ch.create=(t,e)=>new Ch({values:t,typeName:F.ZodNativeEnum,...ze(e)});var rp=class extends He{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==Y.promise&&r.common.async===!1)return W(r,{code:L.invalid_type,expected:Y.promise,received:r.parsedType}),we;let o=r.parsedType===Y.promise?r.data:Promise.resolve(r.data);return to(o.then(n=>this._def.type.parseAsync(n,{path:r.path,errorMap:r.common.contextualErrorMap})))}};rp.create=(t,e)=>new rp({type:t,typeName:F.ZodPromise,...ze(e)});var bs=class extends He{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===F.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:o}=this._processInputParams(e),n=this._def.effect||null,i={addIssue:s=>{W(o,s),s.fatal?r.abort():r.dirty()},get path(){return o.path}};if(i.addIssue=i.addIssue.bind(i),n.type==="preprocess"){let s=n.transform(o.data,i);if(o.common.async)return Promise.resolve(s).then(async a=>{if(r.value==="aborted")return we;let c=await this._def.schema._parseAsync({data:a,path:o.path,parent:o});return c.status==="aborted"?we:c.status==="dirty"?Sh(c.value):r.value==="dirty"?Sh(c.value):c});{if(r.value==="aborted")return we;let a=this._def.schema._parseSync({data:s,path:o.path,parent:o});return a.status==="aborted"?we:a.status==="dirty"?Sh(a.value):r.value==="dirty"?Sh(a.value):a}}if(n.type==="refinement"){let s=a=>{let c=n.refinement(a,i);if(o.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(o.common.async===!1){let a=this._def.schema._parseSync({data:o.data,path:o.path,parent:o});return a.status==="aborted"?we:(a.status==="dirty"&&r.dirty(),s(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:o.data,path:o.path,parent:o}).then(a=>a.status==="aborted"?we:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.value,value:a.value}))))}if(n.type==="transform")if(o.common.async===!1){let s=this._def.schema._parseSync({data:o.data,path:o.path,parent:o});if(!tp(s))return we;let a=n.transform(s.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:o.data,path:o.path,parent:o}).then(s=>tp(s)?Promise.resolve(n.transform(s.value,i)).then(a=>({status:r.value,value:a})):we);at.assertNever(n)}};bs.create=(t,e,r)=>new bs({schema:t,typeName:F.ZodEffects,effect:e,...ze(r)});bs.createWithPreprocess=(t,e,r)=>new bs({schema:e,effect:{type:"preprocess",transform:t},typeName:F.ZodEffects,...ze(r)});var _s=class extends He{_parse(e){return this._getType(e)===Y.undefined?to(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};_s.create=(t,e)=>new _s({innerType:t,typeName:F.ZodOptional,...ze(e)});var Oc=class extends He{_parse(e){return this._getType(e)===Y.null?to(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Oc.create=(t,e)=>new Oc({innerType:t,typeName:F.ZodNullable,...ze(e)});var Oh=class extends He{_parse(e){let{ctx:r}=this._processInputParams(e),o=r.data;return r.parsedType===Y.undefined&&(o=this._def.defaultValue()),this._def.innerType._parse({data:o,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Oh.create=(t,e)=>new Oh({innerType:t,typeName:F.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ze(e)});var Dh=class extends He{_parse(e){let{ctx:r}=this._processInputParams(e),o={...r,common:{...r.common,issues:[]}},n=this._def.innerType._parse({data:o.data,path:o.path,parent:{...o}});return ub(n)?n.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ko(o.common.issues)},input:o.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new Ko(o.common.issues)},input:o.data})}}removeCatch(){return this._def.innerType}};Dh.create=(t,e)=>new Dh({innerType:t,typeName:F.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ze(e)});var wb=class extends He{_parse(e){if(this._getType(e)!==Y.nan){let o=this._getOrReturnCtx(e);return W(o,{code:L.invalid_type,expected:Y.nan,received:o.parsedType}),we}return{status:"valid",value:e.data}}};wb.create=t=>new wb({typeName:F.ZodNaN,...ze(t)});var ZD=class extends He{_parse(e){let{ctx:r}=this._processInputParams(e),o=r.data;return this._def.type._parse({data:o,path:r.path,parent:r})}unwrap(){return this._def.type}},WD=class t extends He{_parse(e){let{status:r,ctx:o}=this._processInputParams(e);if(o.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:o.data,path:o.path,parent:o});return i.status==="aborted"?we:i.status==="dirty"?(r.dirty(),Sh(i.value)):this._def.out._parseAsync({data:i.value,path:o.path,parent:o})})();{let n=this._def.in._parseSync({data:o.data,path:o.path,parent:o});return n.status==="aborted"?we:n.status==="dirty"?(r.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:o.path,parent:o})}}static create(e,r){return new t({in:e,out:r,typeName:F.ZodPipeline})}},Nh=class extends He{_parse(e){let r=this._def.innerType._parse(e),o=n=>(tp(n)&&(n.value=Object.freeze(n.value)),n);return ub(r)?r.then(n=>o(n)):o(r)}unwrap(){return this._def.innerType}};Nh.create=(t,e)=>new Nh({innerType:t,typeName:F.ZodReadonly,...ze(e)});var XWt={object:Bo.lazycreate},F;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(F||(F={}));var YWt=Eh.create,QWt=lb.create,e5t=wb.create,t5t=db.create,r5t=pb.create,n5t=fb.create,o5t=mb.create,i5t=$h.create,s5t=Rh.create,a5t=hb.create,c5t=wl.create,u5t=ka.create,l5t=gb.create,d5t=_l.create,gEe=Bo.create,p5t=Bo.strictCreate,f5t=Ih.create,m5t=uG.create,h5t=Ah.create,g5t=Cc.create,y5t=dG.create,v5t=yb.create,w5t=vb.create,_5t=pG.create,b5t=Ph.create,S5t=kh.create,x5t=Th.create,E5t=Ch.create,$5t=rp.create,R5t=bs.create,I5t=_s.create,A5t=Oc.create,P5t=bs.createWithPreprocess,k5t=WD.create;var Yot=$("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");be.init(t,e),t.def=e,t.type=e.type},{get with(){return this.check},set with(t){Ps(this,"with",t)},parse(t,e){return Ml(this,t,e,{callee:this.parse})},parseAsync(t,e){return Ul(this,t,e,{callee:this.parseAsync})},safeParse(t,e){return Ap(this,t,e)},safeParseAsync(t,e){return kp(this,t,e)},check(...t){let e=this.def;return this.clone({...e,checks:[...e.checks??[],...t.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]},{parent:!0})},clone(t,e){return gt(this,t,e)},brand(){return this},register(t,e){return t.add(this,e),this},apply(t,...e){return e.length===0?t(this):t(this,...e)}});var Qot=$("ZodMiniObject",(t,e)=>{$x.init(t,e),Yot.init(t,e),$1(t,"shape",r=>r._zod.def.shape,!1)});function fG(t,e){let r={type:"object",shape:t??{},...j(e)};return new Qot(r)}function Ta(t){return!!t._zod}function np(t){let e=Object.values(t);if(e.length===0)return fG({});let r=e.every(Ta),o=e.every(n=>!Ta(n));if(r)return fG(t);if(o)return gEe(t);throw new Error("Mixed Zod versions detected in object shape.")}function bl(t,e){return Ta(t)?Ap(t,e):t.safeParse(e)}async function JD(t,e){return Ta(t)?await kp(t,e):await t.safeParseAsync(e)}function Sl(t){if(!t)return;let e;if(Ta(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function zh(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let o=Object.values(t);if(o.length>0&&o.every(n=>typeof n=="object"&&n!==null&&(n._def!==void 0||n._zod!==void 0||typeof n.parse=="function")))return np(t)}}if(Ta(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function tit(t){return t.length===0?"object root":t.reduce((e,r,o)=>o===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function XD(t){if(t&&typeof t=="object"){if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0)return t.issues.map(e=>e.path?.length?`${e.message} at ${tit(e.path)}`:e.message).join(`
143
- `);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function yEe(t){return t.description}function vEe(t){if(Ta(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Mh(t){if(Ta(t)){let i=t._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=t._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 o=t.value;if(o!==void 0)return o}var hG="2025-11-25";var wEe=[hG,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],xl="io.modelcontextprotocol/related-task",QD="2.0",Nr=bE(t=>t!==null&&(typeof t=="object"||typeof t=="function")),_Ee=It([O(),yt().int()]),bEe=O(),G5t=Xr({ttl:yt().optional(),pollInterval:yt().optional()}),rit=X({ttl:yt().optional()}),nit=X({taskId:O()}),gG=Xr({progressToken:_Ee.optional(),[xl]:nit.optional()}),Zo=X({_meta:gG.optional()}),_b=Zo.extend({task:rit.optional()}),SEe=t=>_b.safeParse(t).success,hn=X({method:O(),params:Zo.loose().optional()}),Ai=X({_meta:gG.optional()}),Pi=X({method:O(),params:Ai.loose().optional()}),gn=Xr({_meta:gG.optional()}),eN=It([O(),yt().int()]),xEe=X({jsonrpc:ae(QD),id:eN,...hn.shape}).strict(),yG=t=>xEe.safeParse(t).success,EEe=X({jsonrpc:ae(QD),...Pi.shape}).strict(),$Ee=t=>EEe.safeParse(t).success,vG=X({jsonrpc:ae(QD),id:eN,result:gn}).strict(),bb=t=>vG.safeParse(t).success;var le;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(le||(le={}));var wG=X({jsonrpc:ae(QD),id:eN.optional(),error:X({code:yt().int(),message:O(),data:Ut().optional()})}).strict();var REe=t=>wG.safeParse(t).success;var IEe=It([xEe,EEe,vG,wG]),H5t=It([vG,wG]),tN=gn.strict(),oit=Ai.extend({requestId:eN.optional(),reason:O().optional()}),rN=Pi.extend({method:ae("notifications/cancelled"),params:oit}),iit=X({src:O(),mimeType:O().optional(),sizes:qe(O()).optional(),theme:Yr(["light","dark"]).optional()}),Sb=X({icons:qe(iit).optional()}),Uh=X({name:O(),title:O().optional()}),AEe=Uh.extend({...Uh.shape,...Sb.shape,version:O(),websiteUrl:O().optional(),description:O().optional()}),sit=ff(X({applyDefaults:gr().optional()}),Ct(O(),Ut())),ait=yy(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,ff(X({form:sit.optional(),url:Nr.optional()}),Ct(O(),Ut()).optional())),cit=Xr({list:Nr.optional(),cancel:Nr.optional(),requests:Xr({sampling:Xr({createMessage:Nr.optional()}).optional(),elicitation:Xr({create:Nr.optional()}).optional()}).optional()}),uit=Xr({list:Nr.optional(),cancel:Nr.optional(),requests:Xr({tools:Xr({call:Nr.optional()}).optional()}).optional()}),lit=X({experimental:Ct(O(),Nr).optional(),sampling:X({context:Nr.optional(),tools:Nr.optional()}).optional(),elicitation:ait.optional(),roots:X({listChanged:gr().optional()}).optional(),tasks:cit.optional(),extensions:Ct(O(),Nr).optional()}),dit=Zo.extend({protocolVersion:O(),capabilities:lit,clientInfo:AEe}),_G=hn.extend({method:ae("initialize"),params:dit});var pit=X({experimental:Ct(O(),Nr).optional(),logging:Nr.optional(),completions:Nr.optional(),prompts:X({listChanged:gr().optional()}).optional(),resources:X({subscribe:gr().optional(),listChanged:gr().optional()}).optional(),tools:X({listChanged:gr().optional()}).optional(),tasks:uit.optional(),extensions:Ct(O(),Nr).optional()}),fit=gn.extend({protocolVersion:O(),capabilities:pit,serverInfo:AEe,instructions:O().optional()}),bG=Pi.extend({method:ae("notifications/initialized"),params:Ai.optional()});var nN=hn.extend({method:ae("ping"),params:Zo.optional()}),mit=X({progress:yt(),total:kt(yt()),message:kt(O())}),hit=X({...Ai.shape,...mit.shape,progressToken:_Ee}),oN=Pi.extend({method:ae("notifications/progress"),params:hit}),git=Zo.extend({cursor:bEe.optional()}),xb=hn.extend({params:git.optional()}),Eb=gn.extend({nextCursor:bEe.optional()}),yit=Yr(["working","input_required","completed","failed","cancelled"]),$b=X({taskId:O(),status:yit,ttl:It([yt(),uy()]),createdAt:O(),lastUpdatedAt:O(),pollInterval:kt(yt()),statusMessage:kt(O())}),Lh=gn.extend({task:$b}),vit=Ai.merge($b),Rb=Pi.extend({method:ae("notifications/tasks/status"),params:vit}),iN=hn.extend({method:ae("tasks/get"),params:Zo.extend({taskId:O()})}),sN=gn.merge($b),aN=hn.extend({method:ae("tasks/result"),params:Zo.extend({taskId:O()})}),K5t=gn.loose(),cN=xb.extend({method:ae("tasks/list")}),uN=Eb.extend({tasks:qe($b)}),lN=hn.extend({method:ae("tasks/cancel"),params:Zo.extend({taskId:O()})}),PEe=gn.merge($b),kEe=X({uri:O(),mimeType:kt(O()),_meta:Ct(O(),Ut()).optional()}),TEe=kEe.extend({text:O()}),SG=O().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),CEe=kEe.extend({blob:SG}),Ib=Yr(["user","assistant"]),jh=X({audience:qe(Ib).optional(),priority:yt().min(0).max(1).optional(),lastModified:Ql.datetime({offset:!0}).optional()}),OEe=X({...Uh.shape,...Sb.shape,uri:O(),description:kt(O()),mimeType:kt(O()),size:kt(yt()),annotations:jh.optional(),_meta:kt(Xr({}))}),wit=X({...Uh.shape,...Sb.shape,uriTemplate:O(),description:kt(O()),mimeType:kt(O()),annotations:jh.optional(),_meta:kt(Xr({}))}),dN=xb.extend({method:ae("resources/list")}),_it=Eb.extend({resources:qe(OEe)}),pN=xb.extend({method:ae("resources/templates/list")}),bit=Eb.extend({resourceTemplates:qe(wit)}),xG=Zo.extend({uri:O()}),Sit=xG,fN=hn.extend({method:ae("resources/read"),params:Sit}),xit=gn.extend({contents:qe(It([TEe,CEe]))}),Eit=Pi.extend({method:ae("notifications/resources/list_changed"),params:Ai.optional()}),$it=xG,Rit=hn.extend({method:ae("resources/subscribe"),params:$it}),Iit=xG,Ait=hn.extend({method:ae("resources/unsubscribe"),params:Iit}),Pit=Ai.extend({uri:O()}),kit=Pi.extend({method:ae("notifications/resources/updated"),params:Pit}),Tit=X({name:O(),description:kt(O()),required:kt(gr())}),Cit=X({...Uh.shape,...Sb.shape,description:kt(O()),arguments:kt(qe(Tit)),_meta:kt(Xr({}))}),mN=xb.extend({method:ae("prompts/list")}),Oit=Eb.extend({prompts:qe(Cit)}),Dit=Zo.extend({name:O(),arguments:Ct(O(),O()).optional()}),hN=hn.extend({method:ae("prompts/get"),params:Dit}),EG=X({type:ae("text"),text:O(),annotations:jh.optional(),_meta:Ct(O(),Ut()).optional()}),$G=X({type:ae("image"),data:SG,mimeType:O(),annotations:jh.optional(),_meta:Ct(O(),Ut()).optional()}),RG=X({type:ae("audio"),data:SG,mimeType:O(),annotations:jh.optional(),_meta:Ct(O(),Ut()).optional()}),Nit=X({type:ae("tool_use"),name:O(),id:O(),input:Ct(O(),Ut()),_meta:Ct(O(),Ut()).optional()}),zit=X({type:ae("resource"),resource:It([TEe,CEe]),annotations:jh.optional(),_meta:Ct(O(),Ut()).optional()}),Mit=OEe.extend({type:ae("resource_link")}),IG=It([EG,$G,RG,Mit,zit]),Uit=X({role:Ib,content:IG}),Lit=gn.extend({description:O().optional(),messages:qe(Uit)}),jit=Pi.extend({method:ae("notifications/prompts/list_changed"),params:Ai.optional()}),Fit=X({title:O().optional(),readOnlyHint:gr().optional(),destructiveHint:gr().optional(),idempotentHint:gr().optional(),openWorldHint:gr().optional()}),qit=X({taskSupport:Yr(["required","optional","forbidden"]).optional()}),DEe=X({...Uh.shape,...Sb.shape,description:O().optional(),inputSchema:X({type:ae("object"),properties:Ct(O(),Nr).optional(),required:qe(O()).optional()}).catchall(Ut()),outputSchema:X({type:ae("object"),properties:Ct(O(),Nr).optional(),required:qe(O()).optional()}).catchall(Ut()).optional(),annotations:Fit.optional(),execution:qit.optional(),_meta:Ct(O(),Ut()).optional()}),gN=xb.extend({method:ae("tools/list")}),Vit=Eb.extend({tools:qe(DEe)}),yN=gn.extend({content:qe(IG).default([]),structuredContent:Ct(O(),Ut()).optional(),isError:gr().optional()}),B5t=yN.or(gn.extend({toolResult:Ut()})),Git=_b.extend({name:O(),arguments:Ct(O(),Ut()).optional()}),Fh=hn.extend({method:ae("tools/call"),params:Git}),Hit=Pi.extend({method:ae("notifications/tools/list_changed"),params:Ai.optional()}),Z5t=X({autoRefresh:gr().default(!0),debounceMs:yt().int().nonnegative().default(300)}),Ab=Yr(["debug","info","notice","warning","error","critical","alert","emergency"]),Kit=Zo.extend({level:Ab}),AG=hn.extend({method:ae("logging/setLevel"),params:Kit}),Bit=Ai.extend({level:Ab,logger:O().optional(),data:Ut()}),Zit=Pi.extend({method:ae("notifications/message"),params:Bit}),Wit=X({name:O().optional()}),Jit=X({hints:qe(Wit).optional(),costPriority:yt().min(0).max(1).optional(),speedPriority:yt().min(0).max(1).optional(),intelligencePriority:yt().min(0).max(1).optional()}),Xit=X({mode:Yr(["auto","required","none"]).optional()}),Yit=X({type:ae("tool_result"),toolUseId:O().describe("The unique identifier for the corresponding tool call."),content:qe(IG).default([]),structuredContent:X({}).loose().optional(),isError:gr().optional(),_meta:Ct(O(),Ut()).optional()}),Qit=fy("type",[EG,$G,RG]),YD=fy("type",[EG,$G,RG,Nit,Yit]),est=X({role:Ib,content:It([YD,qe(YD)]),_meta:Ct(O(),Ut()).optional()}),tst=_b.extend({messages:qe(est),modelPreferences:Jit.optional(),systemPrompt:O().optional(),includeContext:Yr(["none","thisServer","allServers"]).optional(),temperature:yt().optional(),maxTokens:yt().int(),stopSequences:qe(O()).optional(),metadata:Nr.optional(),tools:qe(DEe).optional(),toolChoice:Xit.optional()}),rst=hn.extend({method:ae("sampling/createMessage"),params:tst}),Pb=gn.extend({model:O(),stopReason:kt(Yr(["endTurn","stopSequence","maxTokens"]).or(O())),role:Ib,content:Qit}),PG=gn.extend({model:O(),stopReason:kt(Yr(["endTurn","stopSequence","maxTokens","toolUse"]).or(O())),role:Ib,content:It([YD,qe(YD)])}),nst=X({type:ae("boolean"),title:O().optional(),description:O().optional(),default:gr().optional()}),ost=X({type:ae("string"),title:O().optional(),description:O().optional(),minLength:yt().optional(),maxLength:yt().optional(),format:Yr(["email","uri","date","date-time"]).optional(),default:O().optional()}),ist=X({type:Yr(["number","integer"]),title:O().optional(),description:O().optional(),minimum:yt().optional(),maximum:yt().optional(),default:yt().optional()}),sst=X({type:ae("string"),title:O().optional(),description:O().optional(),enum:qe(O()),default:O().optional()}),ast=X({type:ae("string"),title:O().optional(),description:O().optional(),oneOf:qe(X({const:O(),title:O()})),default:O().optional()}),cst=X({type:ae("string"),title:O().optional(),description:O().optional(),enum:qe(O()),enumNames:qe(O()).optional(),default:O().optional()}),ust=It([sst,ast]),lst=X({type:ae("array"),title:O().optional(),description:O().optional(),minItems:yt().optional(),maxItems:yt().optional(),items:X({type:ae("string"),enum:qe(O())}),default:qe(O()).optional()}),dst=X({type:ae("array"),title:O().optional(),description:O().optional(),minItems:yt().optional(),maxItems:yt().optional(),items:X({anyOf:qe(X({const:O(),title:O()}))}),default:qe(O()).optional()}),pst=It([lst,dst]),fst=It([cst,ust,pst]),mst=It([fst,nst,ost,ist]),hst=_b.extend({mode:ae("form").optional(),message:O(),requestedSchema:X({type:ae("object"),properties:Ct(O(),mst),required:qe(O()).optional()})}),gst=_b.extend({mode:ae("url"),message:O(),elicitationId:O(),url:O().url()}),yst=It([hst,gst]),vst=hn.extend({method:ae("elicitation/create"),params:yst}),wst=Ai.extend({elicitationId:O()}),_st=Pi.extend({method:ae("notifications/elicitation/complete"),params:wst}),qh=gn.extend({action:Yr(["accept","decline","cancel"]),content:yy(t=>t===null?void 0:t,Ct(O(),It([O(),yt(),gr(),qe(O())])).optional())}),bst=X({type:ae("ref/resource"),uri:O()});var Sst=X({type:ae("ref/prompt"),name:O()}),xst=Zo.extend({ref:It([Sst,bst]),argument:X({name:O(),value:O()}),context:X({arguments:Ct(O(),O()).optional()}).optional()}),vN=hn.extend({method:ae("completion/complete"),params:xst});function NEe(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function zEe(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Est=gn.extend({completion:Xr({values:qe(O()).max(100),total:kt(yt().int()),hasMore:kt(gr())})}),$st=X({uri:O().startsWith("file://"),name:O().optional(),_meta:Ct(O(),Ut()).optional()}),Rst=hn.extend({method:ae("roots/list"),params:Zo.optional()}),kG=gn.extend({roots:qe($st)}),Ist=Pi.extend({method:ae("notifications/roots/list_changed"),params:Ai.optional()}),W5t=It([nN,_G,vN,AG,hN,mN,dN,pN,fN,Rit,Ait,Fh,gN,iN,aN,cN,lN]),J5t=It([rN,oN,bG,Ist,Rb]),X5t=It([tN,Pb,PG,qh,kG,sN,uN,Lh]),Y5t=It([nN,rst,vst,Rst,iN,aN,cN,lN]),Q5t=It([rN,oN,Zit,kit,Eit,Hit,jit,Rb,_st]),e8t=It([tN,fit,Est,Lit,Oit,_it,bit,xit,yN,Vit,sN,uN,Lh]),ee=class t extends Error{constructor(e,r,o){super(`MCP error ${e}: ${r}`),this.code=e,this.data=o,this.name="McpError"}static fromError(e,r,o){if(e===le.UrlElicitationRequired&&o){let n=o;if(n.elicitations)return new mG(n.elicitations,r)}return new t(e,r,o)}},mG=class extends ee{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(le.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function El(t){return t==="completed"||t==="failed"||t==="cancelled"}var UEe=Symbol("Let zodToJsonSchema decide on which parser to use");var MEe={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"},LEe=t=>typeof t=="string"?{...MEe,name:t}:{...MEe,...t};var jEe=t=>{let e=LEe(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([o,n])=>[n._def,{def:n._def,path:[...e.basePath,e.definitionPath,o],jsonSchema:void 0}]))}};function TG(t,e,r,o){o?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ut(t,e,r,o,n){t[e]=r,TG(t,e,o,n)}var wN=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function ar(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?wN(e,t.currentPath):e.join("/")}}function FEe(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==F.ZodAny&&(r.items=_e(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ut(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ut(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ut(r,"minItems",t.exactLength.value,t.exactLength.message,e),ut(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function qEe(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let o of t.checks)switch(o.kind){case"min":e.target==="jsonSchema7"?o.inclusive?ut(r,"minimum",o.value,o.message,e):ut(r,"exclusiveMinimum",o.value,o.message,e):(o.inclusive||(r.exclusiveMinimum=!0),ut(r,"minimum",o.value,o.message,e));break;case"max":e.target==="jsonSchema7"?o.inclusive?ut(r,"maximum",o.value,o.message,e):ut(r,"exclusiveMaximum",o.value,o.message,e):(o.inclusive||(r.exclusiveMaximum=!0),ut(r,"maximum",o.value,o.message,e));break;case"multipleOf":ut(r,"multipleOf",o.value,o.message,e);break}return r}function VEe(){return{type:"boolean"}}function _N(t,e){return _e(t.type._def,e)}var GEe=(t,e)=>_e(t.innerType._def,e);function CG(t,e,r){let o=r??e.dateStrategy;if(Array.isArray(o))return{anyOf:o.map((n,i)=>CG(t,e,n))};switch(o){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Ast(t,e)}}var Ast=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let o of t.checks)switch(o.kind){case"min":ut(r,"minimum",o.value,o.message,e);break;case"max":ut(r,"maximum",o.value,o.message,e);break}return r};function HEe(t,e){return{..._e(t.innerType._def,e),default:t.defaultValue()}}function KEe(t,e){return e.effectStrategy==="input"?_e(t.schema._def,e):ar(e)}function BEe(t){return{type:"string",enum:Array.from(t.values)}}var Pst=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function ZEe(t,e){let r=[_e(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),_e(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i),o=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,n=[];return r.forEach(i=>{if(Pst(i))n.push(...i.allOf),i.unevaluatedProperties===void 0&&(o=void 0);else{let s=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:a,...c}=i;s=c}else o=void 0;n.push(s)}}),n.length?{allOf:n,...o}:void 0}function WEe(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var OG,Ss={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:()=>(OG===void 0&&(OG=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),OG),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 bN(t,e){let r={type:"string"};if(t.checks)for(let o of t.checks)switch(o.kind){case"min":ut(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e);break;case"max":ut(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value,o.message,e);break;case"email":switch(e.emailStrategy){case"format:email":xs(r,"email",o.message,e);break;case"format:idn-email":xs(r,"idn-email",o.message,e);break;case"pattern:zod":ro(r,Ss.email,o.message,e);break}break;case"url":xs(r,"uri",o.message,e);break;case"uuid":xs(r,"uuid",o.message,e);break;case"regex":ro(r,o.regex,o.message,e);break;case"cuid":ro(r,Ss.cuid,o.message,e);break;case"cuid2":ro(r,Ss.cuid2,o.message,e);break;case"startsWith":ro(r,RegExp(`^${DG(o.value,e)}`),o.message,e);break;case"endsWith":ro(r,RegExp(`${DG(o.value,e)}$`),o.message,e);break;case"datetime":xs(r,"date-time",o.message,e);break;case"date":xs(r,"date",o.message,e);break;case"time":xs(r,"time",o.message,e);break;case"duration":xs(r,"duration",o.message,e);break;case"length":ut(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e),ut(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value,o.message,e);break;case"includes":{ro(r,RegExp(DG(o.value,e)),o.message,e);break}case"ip":{o.version!=="v6"&&xs(r,"ipv4",o.message,e),o.version!=="v4"&&xs(r,"ipv6",o.message,e);break}case"base64url":ro(r,Ss.base64url,o.message,e);break;case"jwt":ro(r,Ss.jwt,o.message,e);break;case"cidr":{o.version!=="v6"&&ro(r,Ss.ipv4Cidr,o.message,e),o.version!=="v4"&&ro(r,Ss.ipv6Cidr,o.message,e);break}case"emoji":ro(r,Ss.emoji(),o.message,e);break;case"ulid":{ro(r,Ss.ulid,o.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{xs(r,"binary",o.message,e);break}case"contentEncoding:base64":{ut(r,"contentEncoding","base64",o.message,e);break}case"pattern:zod":{ro(r,Ss.base64,o.message,e);break}}break}case"nanoid":ro(r,Ss.nanoid,o.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function DG(t,e){return e.patternStrategy==="escape"?Tst(t):t}var kst=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Tst(t){let e="";for(let r=0;r<t.length;r++)kst.has(t[r])||(e+="\\"),e+=t[r];return e}function xs(t,e,r,o){t.format||t.anyOf?.some(n=>n.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&o.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&o.errorMessages&&{errorMessage:{format:r}}})):ut(t,"format",e,r,o)}function ro(t,e,r,o){t.pattern||t.allOf?.some(n=>n.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&o.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:JEe(e,o),...r&&o.errorMessages&&{errorMessage:{pattern:r}}})):ut(t,"pattern",JEe(e,o),r,o)}function JEe(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},o=r.i?t.source.toLowerCase():t.source,n="",i=!1,s=!1,a=!1;for(let c=0;c<o.length;c++){if(i){n+=o[c],i=!1;continue}if(r.i){if(s){if(o[c].match(/[a-z]/)){a?(n+=o[c],n+=`${o[c-2]}-${o[c]}`.toUpperCase(),a=!1):o[c+1]==="-"&&o[c+2]?.match(/[a-z]/)?(n+=o[c],a=!0):n+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){n+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(r.m){if(o[c]==="^"){n+=`(^|(?<=[\r
142
+ }`,{flashAuthRequestId:e.id}),o=m.object({id:m.string(),status:m.string(),apiKey:m.string().nullish()}).parse(r.flashAuthRequestStatus);return o.id!==e.id&&q(502,"invalid_response","RunPod returned another authorization request."),o.apiKey&&["APPROVED","CONSUMED"].includes(o.status)?m.string().min(1).max(16384).regex(/^\S+$/).parse(o.apiKey):(["DENIED","EXPIRED","CONSUMED"].includes(o.status)&&q(409,"authorization_failed","Start the RunPod connection again."),o.status!=="PENDING"&&q(502,"invalid_response","RunPod returned an unknown authorization state."),null)}var sb=m.object({id:E,ownerId:E,name:fe,registration:m.object({methodId:m.string().min(1),method:nu,appId:E.nullable(),app:Zn.nullable(),fields:m.record(m.string(),m.string()),scopes:m.array(m.string())}).strict(),policy:en,previousPolicyDigest:m.string().nullable(),step:m.enum(["start","cli","authorize","exchange","commit","connected","cancelled","failed"]),createdAt:m.iso.datetime(),expiresAt:m.number(),execution:m.object({id:E,index:m.number().int().nonnegative()}).strict(),url:m.url().nullable(),connectionId:E.nullable(),authorizationState:m.string(),verifier:m.string(),redirectUri:m.url(),ovh:FD.optional(),material:$n.optional(),proof:_J.optional(),approval:qD.optional(),error:m.string().optional(),exchangeStartedAt:m.number().optional(),exchangeDevice:m.enum(["browser","cli"])}).strict(),bot=sb.pick({id:!0,ownerId:!0,name:!0,execution:!0,error:!0}).strip(),VD=()=>Ds(crypto.getRandomValues(new Uint8Array(32))),GD=class{constructor(e,r,o=new $k(e.origin),n="browser"){this.custody=e;this.store=r;this.transport=o;this.device=n}custody;store;transport;device;approvalPolls=new Map;async flow(e){let r=await this.store.get(E.parse(e));if(!r)throw new Error("The saved progress for this connection is unavailable.");let o=sb.parse(r);if(o.policy.origin!==this.custody.origin||!o.policy.authorities.some(n=>C(n)===C(this.custody.binding)))throw new Error("Open this connection with its initiating identity.");return o}async start(e){let r=await this.custody.api.json("/api/executions/"+e.execution.id+"/input",{},If.extend({id:E}));if(r.index!==e.execution.index||r.invocation.name!=="connection.connect"||r.invocation.input.ownerId!==e.ownerId||r.invocation.input.methodId!==e.methodId||r.invocation.input.methodDigest!==await Q(e.method)||r.invocation.input.appId&&r.invocation.input.appId!==e.appId||r.invocation.input.name&&r.invocation.input.name!==e.name)throw new Error("Use the connection prepared by this operation.");for(let[h,y]of Object.entries(r.invocation.input.fields??{}))if(y&&e.fields?.[h]!==y)throw new Error("Use the service settings prepared by this operation.");if(!dr(e.method).browserAuthorization||e.method.kind==="token"||e.method.kind==="aws")throw new Error("Choose a browser authorization method.");let o=Vi(e.method.config.scopes,e.scopes);if(r.invocation.input.scopes&&C(o.slice().sort())!==C(Vi(e.method.config.scopes,r.invocation.input.scopes).sort()))throw new Error("Use the service permissions prepared by this operation.");let n={...!r.invocation.input.appId&&e.appId?{appId:e.appId}:{},...r.invocation.input.name?{}:{name:e.name}};Object.keys(n).length&&await this.custody.api.json("/api/executions/"+e.execution.id+"/input",{method:"PATCH",body:{index:e.execution.index,values:n}},Ze);let i=e.connectionId?await this.custody.read(e.connectionId):void 0;if(i&&(i.content.policy.contentType!==he.tokenSet||i.content.policy.ownerId!==e.ownerId))throw new Error("Choose a connection belonging to this owner.");let s=dr(e.method).requiresApp?E.parse(e.appId):null,a=s?Zn.parse(JSON.parse(Kn(await this.custody.reveal(s)))):null,c=jD({...e,app:a}),u=await LD(this.custody,e.ownerId,i?.content,e.users),l=await this.custody.api.json("/api/executions/"+e.execution.id,{},Ze),d=crypto.randomUUID(),p={id:d,ownerId:e.ownerId,name:e.name,registration:{methodId:e.methodId,method:e.method,appId:s,app:c,fields:e.fields??{},scopes:o},policy:u,previousPolicyDigest:i?await Q(i.content.policy):null,step:this.device==="browser"&&P8(e.method)==="unavailable"?"cli":"start",createdAt:new Date().toISOString(),expiresAt:Math.min(Date.now()+6e5,Date.parse(l.expiresAt)),execution:e.execution,url:null,connectionId:null,authorizationState:VD(),verifier:VD(),redirectUri:e.redirectUri??this.custody.origin+"/oauth/callback",exchangeDevice:this.device},f=new URL(p.redirectUri);if(p.redirectUri!==this.custody.origin+"/oauth/callback"&&!(this.device==="cli"&&f.protocol==="http:"&&["127.0.0.1","[::1]"].includes(f.hostname)&&!f.username&&!f.password&&!f.hash&&!f.search))throw new Error("Use the Foundation callback or a callback on this computer.");return await this.store.put(p),await this.custody.api.json("/api/executions/"+p.execution.id+"/continuation",{method:"PUT",body:{index:p.execution.index,continuation:{kind:"connection",id:d}}},Ze),this.progress(d)}view(e){return bot.parse(e)}async awaitingAuthorization(e){let r=await this.custody.api.json("/api/executions/"+e.execution.id+"/input",{},If.extend({id:E}));if(r.index!==e.execution.index||r.continuation?.id!==e.id||r.invocation.input.methodDigest!==await Q(e.registration.method))throw new Error("Continue the connection that is awaiting authorization.")}async pollApproval(e){if(e.expiresAt<=Date.now())throw new Error("Start the connection again.");await this.awaitingAuthorization(e);let r=await sEe(this.transport,qD.parse(e.approval));return r?(await this.awaitingAuthorization(e),e.material=$n.parse({format:2,methodId:e.registration.methodId,method:e.registration.method,generation:crypto.randomUUID(),appId:null,appGeneration:null,fields:{token:r}}),e.step="commit",await this.store.put(e),this.accept(e.id)):{kind:"authorize",flow:this.view(e),url:e.url}}cli(e){return{kind:"cli",flow:this.view(e),command:(e.step==="authorize"?"foundation connect wait ":"foundation execution continue ")+e.execution.id}}async authorize(e){if(e.expiresAt<=Date.now())throw new Error("Start the connection again.");if(e.registration.method.kind==="approval"){let o=await iEe(this.transport);return e.approval=o.approval,e.expiresAt=Math.min(e.expiresAt,o.approval.expiresAt),e.step="authorize",e.url=o.url,await this.store.put(e),{kind:"authorize",flow:this.view(e),url:e.url}}e.redirectUri===this.custody.origin+"/oauth/callback"&&await this.custody.api.json("/api/oauth/relays",{method:"POST",body:{id:e.id,executionId:e.execution.id,index:e.execution.index,stateDigest:await Q(e.authorizationState),expiresAt:new Date(e.expiresAt).toISOString()}},yj);let r=await rEe(e.registration,this.transport,e.authorizationState,e.verifier,e.redirectUri);return e.step="authorize",e.url=r.url,"ovh"in r&&(e.ovh=r.ovh),await this.store.put(e),{kind:"authorize",flow:this.view(e),url:e.url}}async progress(e,r=!0){let o=await this.flow(e);if(o.step==="connected")return o.proof&&await this.custody.api.json("/api/executions/"+o.execution.id+"/complete",{method:"POST",body:{index:o.execution.index,proof:o.proof}},Ze),{kind:"connected",flow:this.view(o),id:o.connectionId};if(o.step==="cancelled")return{kind:"cancelled",flow:this.view(o)};if(o.step==="failed")return{kind:"failed",flow:this.view(o),error:o.error??"authorization_failed"};if(o.step==="commit")return this.accept(e);if(o.step==="exchange"){if(Date.now()-(o.exchangeStartedAt??Date.now())<3e4)return{kind:"pending",flow:this.view(o)};o.step="cli",o.error="browser_exchange_unavailable",await this.store.put(o)}if(o.step==="cli"){if(this.device==="browser")return this.cli(o);let n=await this.custody.api.json("/api/executions/"+o.execution.id,{},Ze);o.step="start",o.exchangeDevice="cli",o.authorizationState=VD(),o.verifier=VD(),o.expiresAt=Math.min(Date.now()+6e5,Date.parse(n.expiresAt)),delete o.error,await this.store.put(o)}if(o.step==="start")return this.authorize(o);if(o.exchangeDevice==="cli"&&this.device==="browser")return this.cli(o);if(o.registration.method.kind==="approval"){let n=this.approvalPolls.get(e);n||(n=this.pollApproval(o),this.approvalPolls.set(e,n));try{return await n}finally{this.approvalPolls.get(e)===n&&this.approvalPolls.delete(e)}}if(r&&o.redirectUri===this.custody.origin+"/oauth/callback"){let n=await this.custody.api.json("/api/oauth/relays/"+e,{},yj);if(n.id!==e||n.executionId!==o.execution.id||n.context!==$J(this.custody.origin,e))throw new Error("The authorization response belongs to another connection.");if(n.sealed)return this.complete(e,Kn(await Po(n.sealed,this.custody.keys.encryption,this.custody.binding.id,n.context)))}return{kind:"authorize",flow:this.view(o),url:o.url}}async complete(e,r){let o=await this.flow(e);if(o.step!=="authorize")return this.progress(e,!1);if(o.exchangeDevice==="cli"&&this.device==="browser")return this.cli(o);if(o.expiresAt<=Date.now())throw new Error("Start the connection again.");await this.awaitingAuthorization(o);let n=new URLSearchParams(r);if(n.getAll("state").length!==1||n.get("state")!==o.authorizationState)throw new Error("The authorization response does not match this connection.");if(n.has("error"))return this.cancel(e);if(o.registration.appId){let i=Zn.parse(JSON.parse(Kn(await this.custody.reveal(o.registration.appId)))),s=o.registration.app;if(i.methodId!==s.methodId||i.generation!==s.generation||i.clientId!==s.clientId||C(i.fields)!==C(s.fields))throw new Error("Start authorization again with the current application.");o.registration.app=i}o.step="exchange",o.exchangeStartedAt=Date.now(),await this.store.put(o);try{o.material=await nEe(o.registration,this.transport,r,o.authorizationState,o.verifier,o.redirectUri,o.ovh)}catch(i){if(o.error=i&&typeof i=="object"&&"code"in i&&typeof i.code=="string"?i.code:"authorization_failed",o.step=o.error==="browser_exchange_unavailable"?"cli":"failed",await this.store.put(o),o.step==="cli"&&this.device==="browser")return this.cli(o);throw i}return o.step="commit",await this.store.put(o),this.accept(e)}async accept(e){let r=await this.flow(e);if(r.step!=="commit"||!r.material)throw new Error("Complete authorization before saving this connection.");let o=r.previousPolicyDigest?await this.custody.read(r.policy.id):void 0;if(o&&await Q(o.content.policy)!==r.previousPolicyDigest)throw new Error("The connection recipients changed. Start again to approve the current recipients.");let n=async i=>(r.proof=i,await this.store.put(r),await this.custody.api.json("/api/executions/"+r.execution.id+"/complete",{method:"POST",body:{index:r.execution.index,proof:i}},Ze),this.custody.api.json("/api/resources/"+r.policy.id,{},Sr));return r.proof?await n(r.proof):await this.custody.save(r.name,tt(C(r.material)),r.policy,{previous:o,metadata:await Ff(r.material),labels:V$(r.material),commit:n}),r.step="connected",r.connectionId=r.policy.id,await this.store.put(r),{kind:"connected",flow:this.view(r),id:r.connectionId}}async cancel(e){let r=await this.flow(e);return await this.custody.api.json("/api/executions/"+r.execution.id+"/cancel",{method:"POST",body:{}},Ze),r.step="cancelled",await this.store.put(r),{kind:"cancelled",flow:this.view(r)}}};var aEe=m.object({id:E,actorId:E,bindingId:E,origin:m.url(),revision:m.number().int().positive(),sealed:Ao,signature:cr}).strict(),cEe=(t,e)=>"operation-continuation:"+t+":"+e,ab=class{constructor(e){this.custody=e}custody;revisions=new Map;async get(e,r){let o=await this.custody.api.json("/api/operation-continuations/"+E.parse(e),{},aEe.nullable());if(!o)return this.revisions.set(e,0),null;let{signature:n,...i}=o;if(i.id!==e||i.origin!==this.custody.origin||i.actorId!==this.custody.binding.principalId||i.bindingId!==this.custody.binding.id)throw new Error("Use the identity that started this operation.");await Ur(i,n,this.custody.binding.signing,"operation-continuation");let s=r.parse(JSON.parse(Kn(await Po(i.sealed,this.custody.keys.encryption,this.custody.binding.id,cEe(this.custody.origin,e)))));return this.revisions.set(e,i.revision),s}async put(e,r){this.revisions.has(e)||await this.get(e,m.unknown());let o={id:e,origin:this.custody.origin,actorId:this.custody.binding.principalId,bindingId:this.custody.binding.id,revision:this.revisions.get(e)+1,sealed:await Xa(tt(C(r)),[{id:this.custody.binding.id,publicKey:this.custody.binding.encryption}],cEe(this.custody.origin,e))},n=await ir(o,this.custody.keys.signing,"operation-continuation");await this.custody.api.json("/api/operation-continuations/"+e,{method:"PUT",body:{...o,signature:n}},aEe),this.revisions.set(e,o.revision)}},HD=class{records;constructor(e){this.records=new ab(e)}async get(e){let r=await this.records.get(e,sb);if(r&&r.id!==e)throw new Error("The saved progress belongs to another operation.");return r}put(e){return this.records.put(e.id,sb.parse(e))}};var iG=class extends Error{constructor(r,o){super("The function invocation could not be confirmed. Invocation ID: "+r+". Check its result or retry with the same ID.",{cause:o});this.invocationId=r}invocationId},Pa=class{constructor(e,r){this.api=e;this.custody=r}api;custody;get(e){return this.api.json("/api/functions/"+E.parse(e),{},a$)}async prepare(e){if(!this.custody)throw new Error("Use your encryption keys to approve a function definition.");let r=this.custody,o=ei.parse(e.definition);if(o.program.kind==="http"&&o.result!=="json")throw new Error("HTTP functions return a JSON response containing status, headers, and body.");if(o.inputAccess.expiresAt!==null&&Date.parse(o.inputAccess.expiresAt)<=Date.now())throw new Error("Choose a future expiration for this function\u2019s input access.");let n=await r.environment(o.environmentId);if(n.manifest.functionVersion!==dd)throw new Error("Update this execution environment to the current Foundation CLI.");let i=e.resourceId??crypto.randomUUID(),s=await r.sourceContents(epe(o).map(p=>p.id)),a=new Set(s.map(p=>p.policy.id));if(e.resourceId){let p=await this.api.json("/api/functions/"+i+"/authorizations",{},Mr(rv));for(let f of p.items)a.has(f.content.policy.id)||(await r.observe(f.content),s.push(f.content))}let c={},u={id:i,digest:await Q(o)};for(let p of s){let f=await r.read(p.policy.id);if(!f.content.policy.authorities.some(y=>C(y)===C(r.binding)))throw new Error("An authority of each input must approve its use by this function.");let h=en.parse({...f.content.policy,revision:f.content.policy.revision+1,grants:[...f.content.policy.grants.filter(y=>!("function"in y)||y.function.id!==i),...a.has(p.policy.id)?[{function:u,executor:n.manifest.executor,operations:s8(p.policy.contentType),expiresAt:o.inputAccess.expiresAt}]:[]]});c[p.policy.id]={version:f.version,content:await ad(await cd(f.content,r.binding,r.keys.encryption),h,f.content.materialRevision+1,r.binding,r.keys,f.content.metadata,f.content)}}let l=await H0e({format:1,functionId:i,ownerId:e.ownerId,revision:e.resourceId?(e.version??0)+1:1,definition:o,author:r.binding,executor:n.manifest.executor,createdAt:new Date().toISOString()},r.keys);return rG.parse({functionId:i,publication:l,contents:c})}async remember(e){if(this.custody)for(let{content:r}of Object.values(e.contents))await this.custody.trust.rememberContent(r)}async save(e){if(!this.custody)throw new Error("Use your encryption keys to approve a function definition.");let r=Rf.parse(e),o=await this.api.json("/api/executions",{method:"POST",body:{operations:[{name:"function.save",input:Lt.parse(r)}]}},Ze),n=await this.prepare(r),i=await this.api.json("/api/executions/"+o.id+"/complete",{method:"POST",body:{index:o.index,proof:n}},Ze);return await this.remember(n),a$.parse(i.results[o.index])}async invoke(e,r={},o={}){let n=o.id??crypto.randomUUID(),i={};if(Object.keys(o.save??{}).length){if(!this.custody)throw new Error("Use your keys to approve encrypted output destinations.");let{executor:s}=await this.api.json("/api/functions/"+E.parse(e)+"/output-recipient",{},m.object({executor:Kt}));await this.custody.trusted(s);let a={manifest:{executor:s}};for(let[c,u]of Object.entries(o.save))i[c]=await this.custody.output(o.ownerId??this.custody.binding.principalId,u,n,a,new Date(Date.now()+36e5).toISOString())}try{return await this.api.json("/api/functions/"+E.parse(e)+"/executions",{method:"POST",body:{id:n,arguments:r,outputs:i,...o.ownerId?{ownerId:o.ownerId}:{}}},Ze)}catch(s){throw s instanceof Error&&"status"in s?s:new iG(n,s)}}result(e){return this.api.json("/api/executions/"+E.parse(e),{},Ze)}cancel(e){return this.api.json("/api/executions/"+E.parse(e)+"/cancel",{method:"POST",body:{}},Ze)}remove(e){return this.api.json("/api/functions/"+E.parse(e),{method:"DELETE"})}};var uEe=m.object({value:m.string().optional(),clientSecret:m.string().optional(),fields:m.record(m.string(),m.string()).optional(),scopes:m.array(m.string()).optional(),aws:Ba.optional()}).strict(),KD=class{constructor(e,r){this.custody=e;this.connections=r;this.records=new ab(e)}custody;connections;records;connectionNames=new Map;async start(e){if(e.name==="run.execute"){let r=Fy.parse(e.input);if(!("programId"in r.operation)){let o=await this.program(r.operation),n=crypto.randomUUID();await this.records.put(n,{operation:o,save:r.save}),e={...e,input:{...r,operation:{kind:r.operation.kind,programId:n,programDigest:await Q(Dk(o))}}}}}return this.custody.api.json("/api/executions",{method:"POST",body:{operations:[Fi.parse(e)]}},Ze)}async plan(e){return this.custody.api.json("/api/executions/"+E.parse(e)+"/input",{},If.extend({id:E}))}async complete(e,r,o){return this.custody.api.json("/api/executions/"+e+"/complete",{method:"POST",body:{index:r,proof:o}},Ze)}async configure(e,r){let o=await this.plan(e);return this.custody.api.json("/api/executions/"+e+"/input",{method:"PATCH",body:{index:o.index,values:r}},Ze)}async execute(e,r={}){let o=await this.start(e);return o.waiting?this.continue(o.id,r):o}async method(e){let r=(await this.custody.api.json("/api/connection-methods",{},Mr(zy))).items.find(u=>u.id===e);if(!r)throw new Error("Choose an available connection method.");this.connectionNames.set(e,r.defaultName);let{id:o,builtin:n,availability:i,registration:s,defaultName:a,...c}=r;return c}async program(e){return ec.parse(e)}async continue(e,r={}){let o=await this.custody.api.json("/api/executions/"+E.parse(e),{},Ze);if(!o.waiting)return o;let n=await this.plan(e),{name:i,input:s}=n.invocation;if(i==="app.save"||i==="connection.connect"){let a=await this.method(String(s.methodId)),c=a.kind==="aws"?[]:a.config.fields,u=fo(c,r.fields??{});if(i==="connection.connect"&&s.appId){let p=await this.custody.api.json("/api/resources/"+E.parse(s.appId),{},Sr);if(p.kind!=="app")throw new Error("Choose a connection application.");u={...p.data.fields,...u}}let l=s.fields,d=jf(c,l??{},u);if(Object.entries(u).some(([p,f])=>l?.[p]!==f))return await this.configure(e,{fields:d}),this.continue(e,r)}if(i==="connection.authorize"){let a=Q5.parse(s),c=await this.custody.read(a.connectionId);if(c.version!==a.version||c.content.policy.ownerId!==a.ownerId||c.content.policy.contentType!==he.tokenSet)throw new Error("Review the current connection before changing its permissions.");let u=await this.userPolicy(c.content.policy,a.users,a.expiresAt),l=await this.custody.api.json("/api/resources/"+a.connectionId,{},Sr);return{kind:"saved",resource:await this.custody.save(l.name,await this.custody.reveal(a.connectionId),u,{previous:c,metadata:c.content.metadata,commit:async p=>Sr.parse((await this.complete(e,n.index,p)).results[n.index])}),executionId:e}}if(i==="function.save"){let a=new Pa(this.custody.api,this.custody),c=await a.prepare(Rf.parse(s)),u=await this.complete(e,n.index,vr.parse(c));return await a.remember(c),{kind:"saved",resource:Sr.parse(u.results[n.index]),executionId:e}}if(i==="variable.save"||i==="app.save"){let a=i==="app.save"?zL.parse(s):Y5.parse(s),c=a.resourceId?await this.custody.read(a.resourceId):void 0;if(c&&c.version!==a.version)throw new Error("This item changed. Reload it before saving.");let u=await Promise.all((a.environmentIds??[]).map(y=>this.custody.environment(y))),l=i==="app.save"?he.clientCredential:he.value;if(c&&(c.content.policy.contentType!==l||c.content.policy.ownerId!==a.ownerId))throw new Error("Choose the item prepared by this operation.");let d=c&&a.environmentIds===void 0?c.content.policy:await this.custody.policy(a.ownerId,l,u,{previous:c?.content.policy}),p,f;if(i==="app.save"){let y=zL.parse(s),w=c?Zn.parse(JSON.parse(Kn(await this.custody.reveal(c.content.policy.id)))):null,b=await this.method(y.methodId),S=jf(b.kind==="aws"?[]:b.config.fields,y.fields??{},r.fields??{}),x=w&&w.methodId===y.methodId&&w.clientId===y.clientId&&C(w.fields)===C(S),R=Zn.parse({format:1,methodId:y.methodId,clientId:y.clientId,fields:S,generation:x?w.generation:crypto.randomUUID(),...r.clientSecret||w?.clientSecret?{clientSecret:r.clientSecret||w?.clientSecret}:{}});p=tt(C(R)),f={methodId:R.methodId,clientId:R.clientId,generation:R.generation,fields:fo(b.kind==="aws"?[]:b.config.fields,S)}}else{if(r.value===void 0)throw new Error("Enter the value to save.");p=typeof r.value=="string"?tt(r.value):r.value}return{kind:"saved",resource:await this.custody.save(a.name,p,d,{previous:c,metadata:f,commit:async y=>Sr.parse((await this.complete(e,n.index,y)).results[n.index])}),executionId:e}}if(i==="connection.connect"){if(n.continuation?.kind==="connection")return this.connections.progress(n.continuation.id);let a=e8.parse(s),c=await this.method(a.methodId);if(!a.name)return await this.configure(e,{name:this.connectionNames.get(a.methodId)??c.name}),this.continue(e,r);if(r.scopes&&!a.scopes&&(c.kind==="oauth"||c.kind==="ovh"))return await this.configure(e,{scopes:r.scopes}),this.continue(e,r);if(r.scopes&&a.scopes&&(c.kind==="oauth"||c.kind==="ovh")&&C(Vi(c.config.scopes,r.scopes).sort())!==C(Vi(c.config.scopes,a.scopes).sort()))throw new Error("Use the service permissions prepared by this operation.");let u=a.appId;if(lu(c)&&!u){if(!a.clientId)throw new Error("Enter the application client ID.");let l=Zn.parse({format:1,methodId:a.methodId,clientId:a.clientId,generation:crypto.randomUUID(),fields:jf(c.kind==="aws"?[]:c.config.fields,a.fields??{},r.fields??{}),...r.clientSecret?{clientSecret:r.clientSecret}:{}}),d=await this.custody.policy(a.ownerId,he.clientCredential,[]);u=(await this.custody.save((a.name??c.name).slice(0,185)+" application",tt(C(l)),d,{metadata:{methodId:l.methodId,clientId:l.clientId,generation:l.generation,fields:fo(c.kind==="aws"?[]:c.config.fields,l.fields)},commit:async f=>{let h=await this.custody.api.json("/api/executions/"+e+"/preparation",{method:"POST",body:{index:n.index,proof:f}},Ze);return this.custody.api.json("/api/resources/"+h.operations[n.index].input.appId,{},Sr)}})).id}if(!dr(c).browserAuthorization){if(await Q(c)!==a.methodDigest)throw new Error("Review the current connection method.");let l=a.connectionId?await this.custody.read(a.connectionId):void 0;if(l&&(l.content.policy.ownerId!==a.ownerId||l.content.policy.contentType!==he.tokenSet))throw new Error("Choose a connection belonging to this owner.");let d=l?$n.parse(JSON.parse(Kn(await this.custody.reveal(a.connectionId)))):void 0,p=jD({methodId:a.methodId,method:c,appId:u,app:u?Zn.parse(JSON.parse(Kn(await this.custody.reveal(u)))):null}),f=tEe({methodId:a.methodId,method:c,appId:u??null,app:p,fields:jf(dr(c).fields,a.fields??{},r.fields??{}),scopes:c.kind==="oauth"?Vi(c.config.scopes,a.scopes):[],aws:r.aws},d),h=await LD(this.custody,a.ownerId,l?.content,a.users);return{kind:"saved",resource:await this.custody.save(a.name??c.name,tt(C(f)),h,{previous:l,metadata:await Ff(f),labels:V$(f),commit:async w=>{let S=(await this.complete(e,n.index,w)).results[n.index];return this.custody.api.json("/api/resources/"+S.id,{},Sr)}}),executionId:e}}return this.connections.start({ownerId:a.ownerId,name:a.name??c.name,methodId:a.methodId,method:c,appId:u,connectionId:a.connectionId,fields:jf(c.kind==="aws"?[]:c.config.fields,a.fields??{},r.fields??{}),scopes:a.scopes,users:a.users,redirectUri:a.redirectUri,execution:{id:e,index:n.index}})}if(i==="run.execute"||i==="connection.revoke"){if(n.continuation?.kind==="run"){let h;try{h=await this.custody.api.json("/api/runtime/runs/"+n.continuation.id,{},Bn)}catch(y){if(!y||typeof y!="object"||!("code"in y)||y.code!=="not_found")throw y;let w=await this.records.get(n.continuation.id,kf);if(!w)throw y;h=await this.custody.submitPrepared(w)}return["queued","running"].includes(h.state)||await this.complete(e,n.index,{runId:h.id}),{kind:"run",task:h,executionId:e}}let a=i==="connection.revoke"?y$.parse(s):null,c=a?{...a,operation:{kind:"revoke",input:{action:"revoke",id:a.connectionId}},save:{}}:Fy.parse(s),u;if("programId"in c.operation){let h=await this.records.get(c.operation.programId,tpe);if(!h||await Q(Dk(h.operation))!==c.operation.programDigest)throw new Error("Use the reviewed private program.");u=h.operation}else u=c.operation.kind==="revoke"?c.operation:await this.program(c.operation);let l=crypto.randomUUID(),d=c.environmentId;if(!d)throw new Error("Choose an execution environment.");let p=await this.custody.prepare(c.ownerId,d,u,{id:l,save:c.save,approval:n.approval,...a?{sourceIds:[a.connectionId]}:{},operationContext:{id:e,index:n.index,invocation:n.invocation}});return await this.records.put(p.intent.id,p),await this.custody.api.json("/api/executions/"+e+"/continuation",{method:"PUT",body:{index:n.index,continuation:{kind:"run",id:p.intent.id}}},Ze),{kind:"run",task:await this.custody.submitPrepared(p),executionId:e}}throw new Error("Choose a supported keyholder operation.")}async userPolicy(e,r,o,n=!0){let i=o??new Date(Date.now()+2592e6).toISOString(),s=await Promise.all([...new Set(r)].map(async a=>{let{binding:c}=await this.custody.inspectIdentity(a);return await this.custody.trusted(c),c}));return en.parse({...e,revision:e.revision+(n?1:0),grants:[...e.grants.filter(a=>!("actor"in a)),...s.map(a=>({actor:a,executor:a,operations:[...ou(e.contentType)],origins:[],functionDigests:[],callerProgram:!0,expiresAt:i}))]})}};function Ri(t,e=Dn(t).custody){let r=new GD(e,new HD(e),new yh(e.origin),"cli");return new KD(e,r)}import{randomBytes as Sot}from"node:crypto";import{execFile as xot}from"node:child_process";import{promisify as Eot}from"node:util";import{lstat as $ot}from"node:fs/promises";async function lEe(){let t=process.env.FOUNDATION_EXECUTOR_BOOTSTRAP;if(!t)throw new Error("The executor enrollment is missing.");let e=wJ.parse(JSON.parse(Buffer.from(t,"base64url").toString("utf8")));e.origin=uu(e.origin),delete process.env.FOUNDATION_EXECUTOR_BOOTSTRAP;let r=!1;try{await $ot(rc()),r=!0}catch(c){if(!(c instanceof Error&&"code"in c&&c.code==="ENOENT"))throw c}if(!r){let c=await m$(),u=h$(e.executorId,c);await Ky({origin:e.origin,principalId:e.executorId,token:"fk_"+Sot(32).toString("base64url"),keys:c,binding:u})}let o=await I$(e.origin),n=new tc(o);if(o.principalId!==e.executorId||!o.keys||!o.binding)throw new Error("The saved keys belong to another executor.");if(!(await n.session().catch(async c=>{if(!(c instanceof cu)||c.status!==401)throw c;return await Rot(e,n),n.session()})).principal)throw new Error("The executor credential is no longer active.");let s=Eot(xot),a=qi();try{await s("docker",["image","inspect",e.commandImage],{env:a})}catch{await s("docker",["pull",e.commandImage],{env:a,timeout:3e5,maxBuffer:2e6})}return UD(n,{id:e.id,ownerId:e.ownerId,name:e.name,isolation:"container",image:e.commandImage,managed:!0,ssh:e.ssh})}async function Rot(t,e){let{keys:r,binding:o,token:n}=e.identity;if(!r||!o)throw new Error("Create executor keys before enrollment.");if(!(await fetch(t.origin+"/api/environments/"+t.id+"/enroll",{method:"POST",redirect:"error",signal:AbortSignal.timeout(3e4),headers:{"content-type":"application/json"},body:JSON.stringify({bootstrap:t.bootstrap,token:n,binding:await jy(o,r)})})).ok)throw new Error("The executor could not enroll. Keep its saved keys and check the environment status.")}var at;(function(t){t.assertEqual=n=>{};function e(n){}t.assertIs=e;function r(n){throw new Error}t.assertNever=r,t.arrayToEnum=n=>{let i={};for(let s of n)i[s]=s;return i},t.getValidEnumValues=n=>{let i=t.objectKeys(n).filter(a=>typeof n[n[a]]!="number"),s={};for(let a of i)s[a]=n[a];return t.objectValues(s)},t.objectValues=n=>t.objectKeys(n).map(function(i){return n[i]}),t.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{let i=[];for(let s in n)Object.prototype.hasOwnProperty.call(n,s)&&i.push(s);return i},t.find=(n,i)=>{for(let s of n)if(i(s))return s},t.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function o(n,i=" | "){return n.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}t.joinValues=o,t.jsonStringifyReplacer=(n,i)=>typeof i=="bigint"?i.toString():i})(at||(at={}));var dEe;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(dEe||(dEe={}));var Y=at.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),kc=t=>{switch(typeof t){case"undefined":return Y.undefined;case"string":return Y.string;case"number":return Number.isNaN(t)?Y.nan:Y.number;case"boolean":return Y.boolean;case"function":return Y.function;case"bigint":return Y.bigint;case"symbol":return Y.symbol;case"object":return Array.isArray(t)?Y.array:t===null?Y.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?Y.promise:typeof Map<"u"&&t instanceof Map?Y.map:typeof Set<"u"&&t instanceof Set?Y.set:typeof Date<"u"&&t instanceof Date?Y.date:Y.object;default:return Y.unknown}};var L=at.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);var Ko=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=o=>{this.issues=[...this.issues,o]},this.addIssues=(o=[])=>{this.issues=[...this.issues,...o]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(i){return i.message},o={_errors:[]},n=i=>{for(let s of i.issues)if(s.code==="invalid_union")s.unionErrors.map(n);else if(s.code==="invalid_return_type")n(s.returnTypeError);else if(s.code==="invalid_arguments")n(s.argumentsError);else if(s.path.length===0)o._errors.push(r(s));else{let a=o,c=0;for(;c<s.path.length;){let u=s.path[c],l=c===s.path.length-1;if(u==="_errors"){l&&a._errors.push(r(s)),c++;continue}Object.prototype.hasOwnProperty.call(a,u)||(u==="__proto__"?Object.defineProperty(a,u,{value:{_errors:[]},writable:!0,enumerable:!0,configurable:!0}):a[u]={_errors:[]}),a=a[u],l&&a._errors.push(r(s)),c++}}};return n(this),o}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,at.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r=Object.create(null),o=[];for(let n of this.issues)if(n.path.length>0){let i=n.path[0];r[i]=r[i]||[],r[i].push(e(n))}else o.push(e(n));return{formErrors:o,fieldErrors:r}}get formErrors(){return this.flatten()}};Ko.create=t=>new Ko(t);var Iot=(t,e)=>{let r;switch(t.code){case L.invalid_type:t.received===Y.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case L.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,at.jsonStringifyReplacer)}`;break;case L.unrecognized_keys:r=`Unrecognized key(s) in object: ${at.joinValues(t.keys,", ")}`;break;case L.invalid_union:r="Invalid input";break;case L.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${at.joinValues(t.options)}`;break;case L.invalid_enum_value:r=`Invalid enum value. Expected ${at.joinValues(t.options)}, received '${t.received}'`;break;case L.invalid_arguments:r="Invalid function arguments";break;case L.invalid_return_type:r="Invalid function return type";break;case L.invalid_date:r="Invalid date";break;case L.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:at.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case L.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case L.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case L.custom:r="Invalid input";break;case L.invalid_intersection_types:r="Intersection results could not be merged";break;case L.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case L.not_finite:r="Number must be finite";break;default:r=e.defaultError,at.assertNever(t)}return{message:r}},vl=Iot;var Aot=vl;function cb(){return Aot}var BD=t=>{let{data:e,path:r,errorMaps:o,issueData:n}=t,i=[...r,...n.path||[]],s={...n,path:i};if(n.message!==void 0)return{...n,path:i,message:n.message};let a="",c=o.filter(u=>!!u).slice().reverse();for(let u of c)a=u(s,{data:e,defaultError:a}).message;return{...n,path:i,message:a}};function W(t,e){let r=cb(),o=BD({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===vl?void 0:vl].filter(n=>!!n)});t.common.issues.push(o)}var Nn=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let o=[];for(let n of r){if(n.status==="aborted")return we;n.status==="dirty"&&e.dirty(),o.push(n.value)}return{status:e.value,value:o}}static async mergeObjectAsync(e,r){let o=[];for(let n of r){let i=await n.key,s=await n.value;o.push({key:i,value:s})}return t.mergeObjectSync(e,o)}static mergeObjectSync(e,r){let o={};for(let n of r){let{key:i,value:s}=n;if(i.status==="aborted"||s.status==="aborted")return we;i.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||n.alwaysSet)&&(o[i.value]=s.value)}return{status:e.value,value:o}}},we=Object.freeze({status:"aborted"}),Sh=t=>({status:"dirty",value:t}),to=t=>({status:"valid",value:t}),sG=t=>t.status==="aborted",aG=t=>t.status==="dirty",tp=t=>t.status==="valid",ub=t=>typeof Promise<"u"&&t instanceof Promise;var ie;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(ie||(ie={}));var Ii=class{constructor(e,r,o,n){this._cachedPath=[],this.parent=e,this.data=r,this._path=o,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},pEe=(t,e)=>{if(tp(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Ko(t.common.issues);return this._error=r,this._error}}};function ze(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:o,description:n}=t;if(e&&(r||o))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(s,a)=>{let{message:c}=t;return s.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??o??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:n}}var He=class{get description(){return this._def.description}_getType(e){return kc(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:kc(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Nn,ctx:{common:e.parent.common,data:e.data,parsedType:kc(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(ub(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let o=this.safeParse(e,r);if(o.success)return o.data;throw o.error}safeParse(e,r){let o={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kc(e)},n=this._parseSync({data:e,path:o.path,parent:o});return pEe(o,n)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kc(e)};if(!this["~standard"].async)try{let o=this._parseSync({data:e,path:[],parent:r});return tp(o)?{value:o.value}:{issues:r.common.issues}}catch(o){o?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(o=>tp(o)?{value:o.value}:{issues:r.common.issues})}async parseAsync(e,r){let o=await this.safeParseAsync(e,r);if(o.success)return o.data;throw o.error}async safeParseAsync(e,r){let o={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kc(e)},n=this._parse({data:e,path:o.path,parent:o}),i=await(ub(n)?n:Promise.resolve(n));return pEe(o,i)}refine(e,r){let o=n=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(n):r;return this._refinement((n,i)=>{let s=e(n),a=()=>i.addIssue({code:L.custom,...o(n)});return typeof Promise<"u"&&s instanceof Promise?s.then(c=>c?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(e,r){return this._refinement((o,n)=>e(o)?!0:(n.addIssue(typeof r=="function"?r(o,n):r),!1))}_refinement(e){return new bs({schema:this,typeName:F.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:r=>this["~validate"](r)}}optional(){return _s.create(this,this._def)}nullable(){return Oc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return _l.create(this)}promise(){return rp.create(this,this._def)}or(e){return Ih.create([this,e],this._def)}and(e){return Ah.create(this,e,this._def)}transform(e){return new bs({...ze(this._def),schema:this,typeName:F.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Oh({...ze(this._def),innerType:this,defaultValue:r,typeName:F.ZodDefault})}brand(){return new ZD({typeName:F.ZodBranded,type:this,...ze(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Dh({...ze(this._def),innerType:this,catchValue:r,typeName:F.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return WD.create(this,e)}readonly(){return Nh.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Pot=/^c[^\s-]{8,}$/i,kot=/^[0-9a-z]+$/,Tot=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Cot=/^[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,Oot=/^[a-z0-9_-]{21}$/i,Dot=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Not=/^[-+]?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)?)??$/,zot=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Mot="^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$",cG,Uot=/^(?:(?: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])$/,Lot=/^(?:(?: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])$/,jot=/^(([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]))$/,Fot=/^(([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])$/,qot=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Vot=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,fEe="((\\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])))",Got=new RegExp(`^${fEe}$`);function mEe(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function Hot(t){return new RegExp(`^${mEe(t)}$`)}function Kot(t){let e=`${fEe}T${mEe(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function Bot(t,e){return!!((e==="v4"||!e)&&Uot.test(t)||(e==="v6"||!e)&&jot.test(t))}function Zot(t,e){if(!Dot.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let o=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(o));return!(typeof n!="object"||n===null||"typ"in n&&n?.typ!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function Wot(t,e){return!!((e==="v4"||!e)&&Lot.test(t)||(e==="v6"||!e)&&Fot.test(t))}var Eh=class t extends He{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Y.string){let i=this._getOrReturnCtx(e);return W(i,{code:L.invalid_type,expected:Y.string,received:i.parsedType}),we}let o=new Nn,n;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(n=this._getOrReturnCtx(e,n),W(n,{code:L.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),o.dirty());else if(i.kind==="max")e.data.length>i.value&&(n=this._getOrReturnCtx(e,n),W(n,{code:L.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),o.dirty());else if(i.kind==="length"){let s=e.data.length>i.value,a=e.data.length<i.value;(s||a)&&(n=this._getOrReturnCtx(e,n),s?W(n,{code:L.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&W(n,{code:L.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),o.dirty())}else if(i.kind==="email")zot.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"email",code:L.invalid_string,message:i.message}),o.dirty());else if(i.kind==="emoji")cG||(cG=new RegExp(Mot,"u")),cG.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"emoji",code:L.invalid_string,message:i.message}),o.dirty());else if(i.kind==="uuid")Cot.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"uuid",code:L.invalid_string,message:i.message}),o.dirty());else if(i.kind==="nanoid")Oot.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"nanoid",code:L.invalid_string,message:i.message}),o.dirty());else if(i.kind==="cuid")Pot.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"cuid",code:L.invalid_string,message:i.message}),o.dirty());else if(i.kind==="cuid2")kot.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"cuid2",code:L.invalid_string,message:i.message}),o.dirty());else if(i.kind==="ulid")Tot.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"ulid",code:L.invalid_string,message:i.message}),o.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),W(n,{validation:"url",code:L.invalid_string,message:i.message}),o.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"regex",code:L.invalid_string,message:i.message}),o.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(n=this._getOrReturnCtx(e,n),W(n,{code:L.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),o.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(n=this._getOrReturnCtx(e,n),W(n,{code:L.invalid_string,validation:{startsWith:i.value},message:i.message}),o.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(n=this._getOrReturnCtx(e,n),W(n,{code:L.invalid_string,validation:{endsWith:i.value},message:i.message}),o.dirty()):i.kind==="datetime"?Kot(i).test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{code:L.invalid_string,validation:"datetime",message:i.message}),o.dirty()):i.kind==="date"?Got.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{code:L.invalid_string,validation:"date",message:i.message}),o.dirty()):i.kind==="time"?Hot(i).test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{code:L.invalid_string,validation:"time",message:i.message}),o.dirty()):i.kind==="duration"?Not.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"duration",code:L.invalid_string,message:i.message}),o.dirty()):i.kind==="ip"?Bot(e.data,i.version)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"ip",code:L.invalid_string,message:i.message}),o.dirty()):i.kind==="jwt"?Zot(e.data,i.alg)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"jwt",code:L.invalid_string,message:i.message}),o.dirty()):i.kind==="cidr"?Wot(e.data,i.version)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"cidr",code:L.invalid_string,message:i.message}),o.dirty()):i.kind==="base64"?qot.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"base64",code:L.invalid_string,message:i.message}),o.dirty()):i.kind==="base64url"?Vot.test(e.data)||(n=this._getOrReturnCtx(e,n),W(n,{validation:"base64url",code:L.invalid_string,message:i.message}),o.dirty()):at.assertNever(i);return{status:o.value,value:e.data}}_regex(e,r,o){return this.refinement(n=>e.test(n),{validation:r,code:L.invalid_string,...ie.errToObj(o)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...ie.errToObj(e)})}url(e){return this._addCheck({kind:"url",...ie.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...ie.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...ie.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...ie.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...ie.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...ie.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...ie.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...ie.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...ie.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...ie.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...ie.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...ie.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...ie.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...ie.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...ie.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...ie.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...ie.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...ie.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...ie.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...ie.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...ie.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...ie.errToObj(r)})}nonempty(e){return this.min(1,ie.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...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 r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Eh.create=t=>new Eh({checks:[],typeName:F.ZodString,coerce:t?.coerce??!1,...ze(t)});function Jot(t,e){let r=(t.toString().split(".")[1]||"").length,o=(e.toString().split(".")[1]||"").length,n=r>o?r:o,i=Number.parseInt(t.toFixed(n).replace(".","")),s=Number.parseInt(e.toFixed(n).replace(".",""));return i%s/10**n}var lb=class t extends He{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==Y.number){let i=this._getOrReturnCtx(e);return W(i,{code:L.invalid_type,expected:Y.number,received:i.parsedType}),we}let o,n=new Nn;for(let i of this._def.checks)i.kind==="int"?at.isInteger(e.data)||(o=this._getOrReturnCtx(e,o),W(o,{code:L.invalid_type,expected:"integer",received:"float",message:i.message}),n.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(o=this._getOrReturnCtx(e,o),W(o,{code:L.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(o=this._getOrReturnCtx(e,o),W(o,{code:L.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="multipleOf"?Jot(e.data,i.value)!==0&&(o=this._getOrReturnCtx(e,o),W(o,{code:L.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(o=this._getOrReturnCtx(e,o),W(o,{code:L.not_finite,message:i.message}),n.dirty()):at.assertNever(i);return{status:n.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,ie.toString(r))}gt(e,r){return this.setLimit("min",e,!1,ie.toString(r))}lte(e,r){return this.setLimit("max",e,!0,ie.toString(r))}lt(e,r){return this.setLimit("max",e,!1,ie.toString(r))}setLimit(e,r,o,n){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:o,message:ie.toString(n)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:ie.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ie.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ie.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ie.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ie.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:ie.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:ie.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ie.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ie.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&at.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let o of this._def.checks){if(o.kind==="finite"||o.kind==="int"||o.kind==="multipleOf")return!0;o.kind==="min"?(r===null||o.value>r)&&(r=o.value):o.kind==="max"&&(e===null||o.value<e)&&(e=o.value)}return Number.isFinite(r)&&Number.isFinite(e)}};lb.create=t=>new lb({checks:[],typeName:F.ZodNumber,coerce:t?.coerce||!1,...ze(t)});var db=class t extends He{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)!==Y.bigint)return this._getInvalidInput(e);let o,n=new Nn;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(o=this._getOrReturnCtx(e,o),W(o,{code:L.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(o=this._getOrReturnCtx(e,o),W(o,{code:L.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(o=this._getOrReturnCtx(e,o),W(o,{code:L.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):at.assertNever(i);return{status:n.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return W(r,{code:L.invalid_type,expected:Y.bigint,received:r.parsedType}),we}gte(e,r){return this.setLimit("min",e,!0,ie.toString(r))}gt(e,r){return this.setLimit("min",e,!1,ie.toString(r))}lte(e,r){return this.setLimit("max",e,!0,ie.toString(r))}lt(e,r){return this.setLimit("max",e,!1,ie.toString(r))}setLimit(e,r,o,n){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:o,message:ie.toString(n)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ie.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ie.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ie.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ie.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:ie.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};db.create=t=>new db({checks:[],typeName:F.ZodBigInt,coerce:t?.coerce??!1,...ze(t)});var pb=class extends He{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==Y.boolean){let o=this._getOrReturnCtx(e);return W(o,{code:L.invalid_type,expected:Y.boolean,received:o.parsedType}),we}return to(e.data)}};pb.create=t=>new pb({typeName:F.ZodBoolean,coerce:t?.coerce||!1,...ze(t)});var fb=class t extends He{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Y.date){let i=this._getOrReturnCtx(e);return W(i,{code:L.invalid_type,expected:Y.date,received:i.parsedType}),we}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return W(i,{code:L.invalid_date}),we}let o=new Nn,n;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(n=this._getOrReturnCtx(e,n),W(n,{code:L.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),o.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(n=this._getOrReturnCtx(e,n),W(n,{code:L.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),o.dirty()):at.assertNever(i);return{status:o.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:ie.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:ie.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};fb.create=t=>new fb({checks:[],coerce:t?.coerce||!1,typeName:F.ZodDate,...ze(t)});var mb=class extends He{_parse(e){if(this._getType(e)!==Y.symbol){let o=this._getOrReturnCtx(e);return W(o,{code:L.invalid_type,expected:Y.symbol,received:o.parsedType}),we}return to(e.data)}};mb.create=t=>new mb({typeName:F.ZodSymbol,...ze(t)});var $h=class extends He{_parse(e){if(this._getType(e)!==Y.undefined){let o=this._getOrReturnCtx(e);return W(o,{code:L.invalid_type,expected:Y.undefined,received:o.parsedType}),we}return to(e.data)}};$h.create=t=>new $h({typeName:F.ZodUndefined,...ze(t)});var Rh=class extends He{_parse(e){if(this._getType(e)!==Y.null){let o=this._getOrReturnCtx(e);return W(o,{code:L.invalid_type,expected:Y.null,received:o.parsedType}),we}return to(e.data)}};Rh.create=t=>new Rh({typeName:F.ZodNull,...ze(t)});var hb=class extends He{constructor(){super(...arguments),this._any=!0}_parse(e){return to(e.data)}};hb.create=t=>new hb({typeName:F.ZodAny,...ze(t)});var wl=class extends He{constructor(){super(...arguments),this._unknown=!0}_parse(e){return to(e.data)}};wl.create=t=>new wl({typeName:F.ZodUnknown,...ze(t)});var ka=class extends He{_parse(e){let r=this._getOrReturnCtx(e);return W(r,{code:L.invalid_type,expected:Y.never,received:r.parsedType}),we}};ka.create=t=>new ka({typeName:F.ZodNever,...ze(t)});var gb=class extends He{_parse(e){if(this._getType(e)!==Y.undefined){let o=this._getOrReturnCtx(e);return W(o,{code:L.invalid_type,expected:Y.void,received:o.parsedType}),we}return to(e.data)}};gb.create=t=>new gb({typeName:F.ZodVoid,...ze(t)});var _l=class t extends He{_parse(e){let{ctx:r,status:o}=this._processInputParams(e),n=this._def;if(r.parsedType!==Y.array)return W(r,{code:L.invalid_type,expected:Y.array,received:r.parsedType}),we;if(n.exactLength!==null){let s=r.data.length>n.exactLength.value,a=r.data.length<n.exactLength.value;(s||a)&&(W(r,{code:s?L.too_big:L.too_small,minimum:a?n.exactLength.value:void 0,maximum:s?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),o.dirty())}if(n.minLength!==null&&r.data.length<n.minLength.value&&(W(r,{code:L.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),o.dirty()),n.maxLength!==null&&r.data.length>n.maxLength.value&&(W(r,{code:L.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),o.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>n.type._parseAsync(new Ii(r,s,r.path,a)))).then(s=>Nn.mergeArray(o,s));let i=[...r.data].map((s,a)=>n.type._parseSync(new Ii(r,s,r.path,a)));return Nn.mergeArray(o,i)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:ie.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:ie.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:ie.toString(r)}})}nonempty(e){return this.min(1,e)}};_l.create=(t,e)=>new _l({type:t,minLength:null,maxLength:null,exactLength:null,typeName:F.ZodArray,...ze(e)});function xh(t){if(t instanceof Bo){let e={};for(let r in t.shape){let o=t.shape[r];e[r]=_s.create(xh(o))}return new Bo({...t._def,shape:()=>e})}else return t instanceof _l?new _l({...t._def,type:xh(t.element)}):t instanceof _s?_s.create(xh(t.unwrap())):t instanceof Oc?Oc.create(xh(t.unwrap())):t instanceof Cc?Cc.create(t.items.map(e=>xh(e))):t}var Bo=class t extends He{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(),r=at.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==Y.object){let u=this._getOrReturnCtx(e);return W(u,{code:L.invalid_type,expected:Y.object,received:u.parsedType}),we}let{status:o,ctx:n}=this._processInputParams(e),{shape:i,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof ka&&this._def.unknownKeys==="strip"))for(let u in n.data)s.includes(u)||a.push(u);let c=[];for(let u of s){let l=i[u],d=n.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Ii(n,d,n.path,u)),alwaysSet:u in n.data})}if(this._def.catchall instanceof ka){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:n.data[l]}});else if(u==="strict")a.length>0&&(W(n,{code:L.unrecognized_keys,keys:a}),o.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=n.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Ii(n,d,n.path,l)),alwaysSet:l in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,p=await l.value;u.push({key:d,value:p,alwaysSet:l.alwaysSet})}return u}).then(u=>Nn.mergeObjectSync(o,u)):Nn.mergeObjectSync(o,c)}get shape(){return this._def.shape()}strict(e){return ie.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,o)=>{let n=this._def.errorMap?.(r,o).message??o.defaultError;return r.code==="unrecognized_keys"?{message:ie.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:F.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let o of at.objectKeys(e))e[o]&&this.shape[o]&&(r[o]=this.shape[o]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let o of at.objectKeys(this.shape))e[o]||(r[o]=this.shape[o]);return new t({...this._def,shape:()=>r})}deepPartial(){return xh(this)}partial(e){let r={};for(let o of at.objectKeys(this.shape)){let n=this.shape[o];e&&!e[o]?r[o]=n:r[o]=n.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let o of at.objectKeys(this.shape))if(e&&!e[o])r[o]=this.shape[o];else{let i=this.shape[o];for(;i instanceof _s;)i=i._def.innerType;r[o]=i}return new t({...this._def,shape:()=>r})}keyof(){return hEe(at.objectKeys(this.shape))}};Bo.create=(t,e)=>new Bo({shape:()=>t,unknownKeys:"strip",catchall:ka.create(),typeName:F.ZodObject,...ze(e)});Bo.strictCreate=(t,e)=>new Bo({shape:()=>t,unknownKeys:"strict",catchall:ka.create(),typeName:F.ZodObject,...ze(e)});Bo.lazycreate=(t,e)=>new Bo({shape:t,unknownKeys:"strip",catchall:ka.create(),typeName:F.ZodObject,...ze(e)});var Ih=class extends He{_parse(e){let{ctx:r}=this._processInputParams(e),o=this._def.options;function n(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let s=i.map(a=>new Ko(a.ctx.common.issues));return W(r,{code:L.invalid_union,unionErrors:s}),we}if(r.common.async)return Promise.all(o.map(async i=>{let s={...r,common:{...r.common,issues:[]},parent:null};return{result:await i._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(n);{let i,s=[];for(let c of o){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!i&&(i={result:l,ctx:u}),u.common.issues.length&&s.push(u.common.issues)}if(i)return r.common.issues.push(...i.ctx.common.issues),i.result;let a=s.map(c=>new Ko(c));return W(r,{code:L.invalid_union,unionErrors:a}),we}}get options(){return this._def.options}};Ih.create=(t,e)=>new Ih({options:t,typeName:F.ZodUnion,...ze(e)});var Tc=t=>t instanceof Ph?Tc(t.schema):t instanceof bs?Tc(t.innerType()):t instanceof kh?[t.value]:t instanceof Th?t.options:t instanceof Ch?at.objectValues(t.enum):t instanceof Oh?Tc(t._def.innerType):t instanceof $h?[void 0]:t instanceof Rh?[null]:t instanceof _s?[void 0,...Tc(t.unwrap())]:t instanceof Oc?[null,...Tc(t.unwrap())]:t instanceof ZD||t instanceof Nh?Tc(t.unwrap()):t instanceof Dh?Tc(t._def.innerType):[],uG=class t extends He{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==Y.object)return W(r,{code:L.invalid_type,expected:Y.object,received:r.parsedType}),we;let o=this.discriminator,n=r.data[o],i=this.optionsMap.get(n);return i?r.common.async?i._parseAsync({data:r.data,path:r.path,parent:r}):i._parseSync({data:r.data,path:r.path,parent:r}):(W(r,{code:L.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[o]}),we)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,o){let n=new Map;for(let i of r){let s=Tc(i.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of s){if(n.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);n.set(a,i)}}return new t({typeName:F.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:n,...ze(o)})}};function lG(t,e){let r=kc(t),o=kc(e);if(t===e)return{valid:!0,data:t};if(r===Y.object&&o===Y.object){let n=at.objectKeys(e),i=at.objectKeys(t).filter(a=>n.indexOf(a)!==-1),s={...t,...e};Object.prototype.hasOwnProperty.call(s,"__proto__")&&delete s.__proto__;for(let a of i){if(a==="__proto__")continue;let c=lG(t[a],e[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===Y.array&&o===Y.array){if(t.length!==e.length)return{valid:!1};let n=[];for(let i=0;i<t.length;i++){let s=t[i],a=e[i],c=lG(s,a);if(!c.valid)return{valid:!1};n.push(c.data)}return{valid:!0,data:n}}else return r===Y.date&&o===Y.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Ah=class extends He{_parse(e){let{status:r,ctx:o}=this._processInputParams(e),n=(i,s)=>{if(sG(i)||sG(s))return we;let a=lG(i.value,s.value);return a.valid?((aG(i)||aG(s))&&r.dirty(),{status:r.value,value:a.data}):(W(o,{code:L.invalid_intersection_types}),we)};return o.common.async?Promise.all([this._def.left._parseAsync({data:o.data,path:o.path,parent:o}),this._def.right._parseAsync({data:o.data,path:o.path,parent:o})]).then(([i,s])=>n(i,s)):n(this._def.left._parseSync({data:o.data,path:o.path,parent:o}),this._def.right._parseSync({data:o.data,path:o.path,parent:o}))}};Ah.create=(t,e,r)=>new Ah({left:t,right:e,typeName:F.ZodIntersection,...ze(r)});var Cc=class t extends He{_parse(e){let{status:r,ctx:o}=this._processInputParams(e);if(o.parsedType!==Y.array)return W(o,{code:L.invalid_type,expected:Y.array,received:o.parsedType}),we;if(o.data.length<this._def.items.length)return W(o,{code:L.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),we;!this._def.rest&&o.data.length>this._def.items.length&&(W(o,{code:L.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let i=[...o.data].map((s,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Ii(o,s,o.path,a)):null}).filter(s=>!!s);return o.common.async?Promise.all(i).then(s=>Nn.mergeArray(r,s)):Nn.mergeArray(r,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Cc.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Cc({items:t,typeName:F.ZodTuple,rest:null,...ze(e)})};var dG=class t extends He{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:o}=this._processInputParams(e);if(o.parsedType!==Y.object)return W(o,{code:L.invalid_type,expected:Y.object,received:o.parsedType}),we;let n=[],i=this._def.keyType,s=this._def.valueType;for(let a in o.data)n.push({key:i._parse(new Ii(o,a,o.path,a)),value:s._parse(new Ii(o,o.data[a],o.path,a)),alwaysSet:a in o.data});return o.common.async?Nn.mergeObjectAsync(r,n):Nn.mergeObjectSync(r,n)}get element(){return this._def.valueType}static create(e,r,o){return r instanceof He?new t({keyType:e,valueType:r,typeName:F.ZodRecord,...ze(o)}):new t({keyType:Eh.create(),valueType:e,typeName:F.ZodRecord,...ze(r)})}},yb=class extends He{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:o}=this._processInputParams(e);if(o.parsedType!==Y.map)return W(o,{code:L.invalid_type,expected:Y.map,received:o.parsedType}),we;let n=this._def.keyType,i=this._def.valueType,s=[...o.data.entries()].map(([a,c],u)=>({key:n._parse(new Ii(o,a,o.path,[u,"key"])),value:i._parse(new Ii(o,c,o.path,[u,"value"]))}));if(o.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of s){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return we;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of s){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return we;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};yb.create=(t,e,r)=>new yb({valueType:e,keyType:t,typeName:F.ZodMap,...ze(r)});var vb=class t extends He{_parse(e){let{status:r,ctx:o}=this._processInputParams(e);if(o.parsedType!==Y.set)return W(o,{code:L.invalid_type,expected:Y.set,received:o.parsedType}),we;let n=this._def;n.minSize!==null&&o.data.size<n.minSize.value&&(W(o,{code:L.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),r.dirty()),n.maxSize!==null&&o.data.size>n.maxSize.value&&(W(o,{code:L.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),r.dirty());let i=this._def.valueType;function s(c){let u=new Set;for(let l of c){if(l.status==="aborted")return we;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...o.data.values()].map((c,u)=>i._parse(new Ii(o,c,o.path,u)));return o.common.async?Promise.all(a).then(c=>s(c)):s(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:ie.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:ie.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};vb.create=(t,e)=>new vb({valueType:t,minSize:null,maxSize:null,typeName:F.ZodSet,...ze(e)});var pG=class t extends He{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==Y.function)return W(r,{code:L.invalid_type,expected:Y.function,received:r.parsedType}),we;function o(a,c){return BD({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,cb(),vl].filter(u=>!!u),issueData:{code:L.invalid_arguments,argumentsError:c}})}function n(a,c){return BD({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,cb(),vl].filter(u=>!!u),issueData:{code:L.invalid_return_type,returnTypeError:c}})}let i={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof rp){let a=this;return to(async function(...c){let u=new Ko([]),l=await a._def.args.parseAsync(c,i).catch(f=>{throw u.addIssue(o(c,f)),u}),d=await Reflect.apply(s,this,l);return await a._def.returns._def.type.parseAsync(d,i).catch(f=>{throw u.addIssue(n(d,f)),u})})}else{let a=this;return to(function(...c){let u=a._def.args.safeParse(c,i);if(!u.success)throw new Ko([o(c,u.error)]);let l=Reflect.apply(s,this,u.data),d=a._def.returns.safeParse(l,i);if(!d.success)throw new Ko([n(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Cc.create(e).rest(wl.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,o){return new t({args:e||Cc.create([]).rest(wl.create()),returns:r||wl.create(),typeName:F.ZodFunction,...ze(o)})}},Ph=class extends He{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Ph.create=(t,e)=>new Ph({getter:t,typeName:F.ZodLazy,...ze(e)});var kh=class extends He{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return W(r,{received:r.data,code:L.invalid_literal,expected:this._def.value}),we}return{status:"valid",value:e.data}}get value(){return this._def.value}};kh.create=(t,e)=>new kh({value:t,typeName:F.ZodLiteral,...ze(e)});function hEe(t,e){return new Th({values:t,typeName:F.ZodEnum,...ze(e)})}var Th=class t extends He{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),o=this._def.values;return W(r,{expected:at.joinValues(o),received:r.parsedType,code:L.invalid_type}),we}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),o=this._def.values;return W(r,{received:r.data,code:L.invalid_enum_value,options:o}),we}return to(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(o=>!e.includes(o)),{...this._def,...r})}};Th.create=hEe;var Ch=class extends He{_parse(e){let r=at.getValidEnumValues(this._def.values),o=this._getOrReturnCtx(e);if(o.parsedType!==Y.string&&o.parsedType!==Y.number){let n=at.objectValues(r);return W(o,{expected:at.joinValues(n),received:o.parsedType,code:L.invalid_type}),we}if(this._cache||(this._cache=new Set(at.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let n=at.objectValues(r);return W(o,{received:o.data,code:L.invalid_enum_value,options:n}),we}return to(e.data)}get enum(){return this._def.values}};Ch.create=(t,e)=>new Ch({values:t,typeName:F.ZodNativeEnum,...ze(e)});var rp=class extends He{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==Y.promise&&r.common.async===!1)return W(r,{code:L.invalid_type,expected:Y.promise,received:r.parsedType}),we;let o=r.parsedType===Y.promise?r.data:Promise.resolve(r.data);return to(o.then(n=>this._def.type.parseAsync(n,{path:r.path,errorMap:r.common.contextualErrorMap})))}};rp.create=(t,e)=>new rp({type:t,typeName:F.ZodPromise,...ze(e)});var bs=class extends He{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===F.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:o}=this._processInputParams(e),n=this._def.effect||null,i={addIssue:s=>{W(o,s),s.fatal?r.abort():r.dirty()},get path(){return o.path}};if(i.addIssue=i.addIssue.bind(i),n.type==="preprocess"){let s=n.transform(o.data,i);if(o.common.async)return Promise.resolve(s).then(async a=>{if(r.value==="aborted")return we;let c=await this._def.schema._parseAsync({data:a,path:o.path,parent:o});return c.status==="aborted"?we:c.status==="dirty"?Sh(c.value):r.value==="dirty"?Sh(c.value):c});{if(r.value==="aborted")return we;let a=this._def.schema._parseSync({data:s,path:o.path,parent:o});return a.status==="aborted"?we:a.status==="dirty"?Sh(a.value):r.value==="dirty"?Sh(a.value):a}}if(n.type==="refinement"){let s=a=>{let c=n.refinement(a,i);if(o.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(o.common.async===!1){let a=this._def.schema._parseSync({data:o.data,path:o.path,parent:o});return a.status==="aborted"?we:(a.status==="dirty"&&r.dirty(),s(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:o.data,path:o.path,parent:o}).then(a=>a.status==="aborted"?we:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.value,value:a.value}))))}if(n.type==="transform")if(o.common.async===!1){let s=this._def.schema._parseSync({data:o.data,path:o.path,parent:o});if(!tp(s))return we;let a=n.transform(s.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:o.data,path:o.path,parent:o}).then(s=>tp(s)?Promise.resolve(n.transform(s.value,i)).then(a=>({status:r.value,value:a})):we);at.assertNever(n)}};bs.create=(t,e,r)=>new bs({schema:t,typeName:F.ZodEffects,effect:e,...ze(r)});bs.createWithPreprocess=(t,e,r)=>new bs({schema:e,effect:{type:"preprocess",transform:t},typeName:F.ZodEffects,...ze(r)});var _s=class extends He{_parse(e){return this._getType(e)===Y.undefined?to(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};_s.create=(t,e)=>new _s({innerType:t,typeName:F.ZodOptional,...ze(e)});var Oc=class extends He{_parse(e){return this._getType(e)===Y.null?to(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Oc.create=(t,e)=>new Oc({innerType:t,typeName:F.ZodNullable,...ze(e)});var Oh=class extends He{_parse(e){let{ctx:r}=this._processInputParams(e),o=r.data;return r.parsedType===Y.undefined&&(o=this._def.defaultValue()),this._def.innerType._parse({data:o,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Oh.create=(t,e)=>new Oh({innerType:t,typeName:F.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ze(e)});var Dh=class extends He{_parse(e){let{ctx:r}=this._processInputParams(e),o={...r,common:{...r.common,issues:[]}},n=this._def.innerType._parse({data:o.data,path:o.path,parent:{...o}});return ub(n)?n.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ko(o.common.issues)},input:o.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new Ko(o.common.issues)},input:o.data})}}removeCatch(){return this._def.innerType}};Dh.create=(t,e)=>new Dh({innerType:t,typeName:F.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ze(e)});var wb=class extends He{_parse(e){if(this._getType(e)!==Y.nan){let o=this._getOrReturnCtx(e);return W(o,{code:L.invalid_type,expected:Y.nan,received:o.parsedType}),we}return{status:"valid",value:e.data}}};wb.create=t=>new wb({typeName:F.ZodNaN,...ze(t)});var ZD=class extends He{_parse(e){let{ctx:r}=this._processInputParams(e),o=r.data;return this._def.type._parse({data:o,path:r.path,parent:r})}unwrap(){return this._def.type}},WD=class t extends He{_parse(e){let{status:r,ctx:o}=this._processInputParams(e);if(o.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:o.data,path:o.path,parent:o});return i.status==="aborted"?we:i.status==="dirty"?(r.dirty(),Sh(i.value)):this._def.out._parseAsync({data:i.value,path:o.path,parent:o})})();{let n=this._def.in._parseSync({data:o.data,path:o.path,parent:o});return n.status==="aborted"?we:n.status==="dirty"?(r.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:o.path,parent:o})}}static create(e,r){return new t({in:e,out:r,typeName:F.ZodPipeline})}},Nh=class extends He{_parse(e){let r=this._def.innerType._parse(e),o=n=>(tp(n)&&(n.value=Object.freeze(n.value)),n);return ub(r)?r.then(n=>o(n)):o(r)}unwrap(){return this._def.innerType}};Nh.create=(t,e)=>new Nh({innerType:t,typeName:F.ZodReadonly,...ze(e)});var XWt={object:Bo.lazycreate},F;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(F||(F={}));var YWt=Eh.create,QWt=lb.create,e5t=wb.create,t5t=db.create,r5t=pb.create,n5t=fb.create,o5t=mb.create,i5t=$h.create,s5t=Rh.create,a5t=hb.create,c5t=wl.create,u5t=ka.create,l5t=gb.create,d5t=_l.create,gEe=Bo.create,p5t=Bo.strictCreate,f5t=Ih.create,m5t=uG.create,h5t=Ah.create,g5t=Cc.create,y5t=dG.create,v5t=yb.create,w5t=vb.create,_5t=pG.create,b5t=Ph.create,S5t=kh.create,x5t=Th.create,E5t=Ch.create,$5t=rp.create,R5t=bs.create,I5t=_s.create,A5t=Oc.create,P5t=bs.createWithPreprocess,k5t=WD.create;var Yot=$("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");be.init(t,e),t.def=e,t.type=e.type},{get with(){return this.check},set with(t){Ps(this,"with",t)},parse(t,e){return Ml(this,t,e,{callee:this.parse})},parseAsync(t,e){return Ul(this,t,e,{callee:this.parseAsync})},safeParse(t,e){return Ap(this,t,e)},safeParseAsync(t,e){return kp(this,t,e)},check(...t){let e=this.def;return this.clone({...e,checks:[...e.checks??[],...t.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]},{parent:!0})},clone(t,e){return gt(this,t,e)},brand(){return this},register(t,e){return t.add(this,e),this},apply(t,...e){return e.length===0?t(this):t(this,...e)}});var Qot=$("ZodMiniObject",(t,e)=>{$x.init(t,e),Yot.init(t,e),$1(t,"shape",r=>r._zod.def.shape,!1)});function fG(t,e){let r={type:"object",shape:t??{},...j(e)};return new Qot(r)}function Ta(t){return!!t._zod}function np(t){let e=Object.values(t);if(e.length===0)return fG({});let r=e.every(Ta),o=e.every(n=>!Ta(n));if(r)return fG(t);if(o)return gEe(t);throw new Error("Mixed Zod versions detected in object shape.")}function bl(t,e){return Ta(t)?Ap(t,e):t.safeParse(e)}async function JD(t,e){return Ta(t)?await kp(t,e):await t.safeParseAsync(e)}function Sl(t){if(!t)return;let e;if(Ta(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function zh(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let o=Object.values(t);if(o.length>0&&o.every(n=>typeof n=="object"&&n!==null&&(n._def!==void 0||n._zod!==void 0||typeof n.parse=="function")))return np(t)}}if(Ta(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function tit(t){return t.length===0?"object root":t.reduce((e,r,o)=>o===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function XD(t){if(t&&typeof t=="object"){if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0)return t.issues.map(e=>e.path?.length?`${e.message} at ${tit(e.path)}`:e.message).join(`
143
+ `);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function yEe(t){return t.description}function vEe(t){if(Ta(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Mh(t){if(Ta(t)){let i=t._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=t._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 o=t.value;if(o!==void 0)return o}var hG="2025-11-25";var wEe=[hG,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],xl="io.modelcontextprotocol/related-task",QD="2.0",Nr=bE(t=>t!==null&&(typeof t=="object"||typeof t=="function")),_Ee=It([O(),yt().int()]),bEe=O(),G5t=Xr({ttl:yt().optional(),pollInterval:yt().optional()}),rit=X({ttl:yt().optional()}),nit=X({taskId:O()}),gG=Xr({progressToken:_Ee.optional(),[xl]:nit.optional()}),Zo=X({_meta:gG.optional()}),_b=Zo.extend({task:rit.optional()}),SEe=t=>_b.safeParse(t).success,hn=X({method:O(),params:Zo.loose().optional()}),Ai=X({_meta:gG.optional()}),Pi=X({method:O(),params:Ai.loose().optional()}),gn=Xr({_meta:gG.optional()}),eN=It([O(),yt().int()]),xEe=X({jsonrpc:ae(QD),id:eN,...hn.shape}).strict(),yG=t=>xEe.safeParse(t).success,EEe=X({jsonrpc:ae(QD),...Pi.shape}).strict(),$Ee=t=>EEe.safeParse(t).success,vG=X({jsonrpc:ae(QD),id:eN,result:gn}).strict(),bb=t=>vG.safeParse(t).success;var le;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(le||(le={}));var wG=X({jsonrpc:ae(QD),id:eN.optional(),error:X({code:yt().int(),message:O(),data:Ut().optional()})}).strict();var REe=t=>wG.safeParse(t).success;var IEe=It([xEe,EEe,vG,wG]),H5t=It([vG,wG]),tN=gn.strict(),oit=Ai.extend({requestId:eN.optional(),reason:O().optional()}),rN=Pi.extend({method:ae("notifications/cancelled"),params:oit}),iit=X({src:O(),mimeType:O().optional(),sizes:qe(O()).optional(),theme:Yr(["light","dark"]).optional()}),Sb=X({icons:qe(iit).optional()}),Uh=X({name:O(),title:O().optional()}),AEe=Uh.extend({...Uh.shape,...Sb.shape,version:O(),websiteUrl:O().optional(),description:O().optional()}),sit=ff(X({applyDefaults:yr().optional()}),Ct(O(),Ut())),ait=yy(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,ff(X({form:sit.optional(),url:Nr.optional()}),Ct(O(),Ut()).optional())),cit=Xr({list:Nr.optional(),cancel:Nr.optional(),requests:Xr({sampling:Xr({createMessage:Nr.optional()}).optional(),elicitation:Xr({create:Nr.optional()}).optional()}).optional()}),uit=Xr({list:Nr.optional(),cancel:Nr.optional(),requests:Xr({tools:Xr({call:Nr.optional()}).optional()}).optional()}),lit=X({experimental:Ct(O(),Nr).optional(),sampling:X({context:Nr.optional(),tools:Nr.optional()}).optional(),elicitation:ait.optional(),roots:X({listChanged:yr().optional()}).optional(),tasks:cit.optional(),extensions:Ct(O(),Nr).optional()}),dit=Zo.extend({protocolVersion:O(),capabilities:lit,clientInfo:AEe}),_G=hn.extend({method:ae("initialize"),params:dit});var pit=X({experimental:Ct(O(),Nr).optional(),logging:Nr.optional(),completions:Nr.optional(),prompts:X({listChanged:yr().optional()}).optional(),resources:X({subscribe:yr().optional(),listChanged:yr().optional()}).optional(),tools:X({listChanged:yr().optional()}).optional(),tasks:uit.optional(),extensions:Ct(O(),Nr).optional()}),fit=gn.extend({protocolVersion:O(),capabilities:pit,serverInfo:AEe,instructions:O().optional()}),bG=Pi.extend({method:ae("notifications/initialized"),params:Ai.optional()});var nN=hn.extend({method:ae("ping"),params:Zo.optional()}),mit=X({progress:yt(),total:kt(yt()),message:kt(O())}),hit=X({...Ai.shape,...mit.shape,progressToken:_Ee}),oN=Pi.extend({method:ae("notifications/progress"),params:hit}),git=Zo.extend({cursor:bEe.optional()}),xb=hn.extend({params:git.optional()}),Eb=gn.extend({nextCursor:bEe.optional()}),yit=Yr(["working","input_required","completed","failed","cancelled"]),$b=X({taskId:O(),status:yit,ttl:It([yt(),uy()]),createdAt:O(),lastUpdatedAt:O(),pollInterval:kt(yt()),statusMessage:kt(O())}),Lh=gn.extend({task:$b}),vit=Ai.merge($b),Rb=Pi.extend({method:ae("notifications/tasks/status"),params:vit}),iN=hn.extend({method:ae("tasks/get"),params:Zo.extend({taskId:O()})}),sN=gn.merge($b),aN=hn.extend({method:ae("tasks/result"),params:Zo.extend({taskId:O()})}),K5t=gn.loose(),cN=xb.extend({method:ae("tasks/list")}),uN=Eb.extend({tasks:qe($b)}),lN=hn.extend({method:ae("tasks/cancel"),params:Zo.extend({taskId:O()})}),PEe=gn.merge($b),kEe=X({uri:O(),mimeType:kt(O()),_meta:Ct(O(),Ut()).optional()}),TEe=kEe.extend({text:O()}),SG=O().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),CEe=kEe.extend({blob:SG}),Ib=Yr(["user","assistant"]),jh=X({audience:qe(Ib).optional(),priority:yt().min(0).max(1).optional(),lastModified:Ql.datetime({offset:!0}).optional()}),OEe=X({...Uh.shape,...Sb.shape,uri:O(),description:kt(O()),mimeType:kt(O()),size:kt(yt()),annotations:jh.optional(),_meta:kt(Xr({}))}),wit=X({...Uh.shape,...Sb.shape,uriTemplate:O(),description:kt(O()),mimeType:kt(O()),annotations:jh.optional(),_meta:kt(Xr({}))}),dN=xb.extend({method:ae("resources/list")}),_it=Eb.extend({resources:qe(OEe)}),pN=xb.extend({method:ae("resources/templates/list")}),bit=Eb.extend({resourceTemplates:qe(wit)}),xG=Zo.extend({uri:O()}),Sit=xG,fN=hn.extend({method:ae("resources/read"),params:Sit}),xit=gn.extend({contents:qe(It([TEe,CEe]))}),Eit=Pi.extend({method:ae("notifications/resources/list_changed"),params:Ai.optional()}),$it=xG,Rit=hn.extend({method:ae("resources/subscribe"),params:$it}),Iit=xG,Ait=hn.extend({method:ae("resources/unsubscribe"),params:Iit}),Pit=Ai.extend({uri:O()}),kit=Pi.extend({method:ae("notifications/resources/updated"),params:Pit}),Tit=X({name:O(),description:kt(O()),required:kt(yr())}),Cit=X({...Uh.shape,...Sb.shape,description:kt(O()),arguments:kt(qe(Tit)),_meta:kt(Xr({}))}),mN=xb.extend({method:ae("prompts/list")}),Oit=Eb.extend({prompts:qe(Cit)}),Dit=Zo.extend({name:O(),arguments:Ct(O(),O()).optional()}),hN=hn.extend({method:ae("prompts/get"),params:Dit}),EG=X({type:ae("text"),text:O(),annotations:jh.optional(),_meta:Ct(O(),Ut()).optional()}),$G=X({type:ae("image"),data:SG,mimeType:O(),annotations:jh.optional(),_meta:Ct(O(),Ut()).optional()}),RG=X({type:ae("audio"),data:SG,mimeType:O(),annotations:jh.optional(),_meta:Ct(O(),Ut()).optional()}),Nit=X({type:ae("tool_use"),name:O(),id:O(),input:Ct(O(),Ut()),_meta:Ct(O(),Ut()).optional()}),zit=X({type:ae("resource"),resource:It([TEe,CEe]),annotations:jh.optional(),_meta:Ct(O(),Ut()).optional()}),Mit=OEe.extend({type:ae("resource_link")}),IG=It([EG,$G,RG,Mit,zit]),Uit=X({role:Ib,content:IG}),Lit=gn.extend({description:O().optional(),messages:qe(Uit)}),jit=Pi.extend({method:ae("notifications/prompts/list_changed"),params:Ai.optional()}),Fit=X({title:O().optional(),readOnlyHint:yr().optional(),destructiveHint:yr().optional(),idempotentHint:yr().optional(),openWorldHint:yr().optional()}),qit=X({taskSupport:Yr(["required","optional","forbidden"]).optional()}),DEe=X({...Uh.shape,...Sb.shape,description:O().optional(),inputSchema:X({type:ae("object"),properties:Ct(O(),Nr).optional(),required:qe(O()).optional()}).catchall(Ut()),outputSchema:X({type:ae("object"),properties:Ct(O(),Nr).optional(),required:qe(O()).optional()}).catchall(Ut()).optional(),annotations:Fit.optional(),execution:qit.optional(),_meta:Ct(O(),Ut()).optional()}),gN=xb.extend({method:ae("tools/list")}),Vit=Eb.extend({tools:qe(DEe)}),yN=gn.extend({content:qe(IG).default([]),structuredContent:Ct(O(),Ut()).optional(),isError:yr().optional()}),B5t=yN.or(gn.extend({toolResult:Ut()})),Git=_b.extend({name:O(),arguments:Ct(O(),Ut()).optional()}),Fh=hn.extend({method:ae("tools/call"),params:Git}),Hit=Pi.extend({method:ae("notifications/tools/list_changed"),params:Ai.optional()}),Z5t=X({autoRefresh:yr().default(!0),debounceMs:yt().int().nonnegative().default(300)}),Ab=Yr(["debug","info","notice","warning","error","critical","alert","emergency"]),Kit=Zo.extend({level:Ab}),AG=hn.extend({method:ae("logging/setLevel"),params:Kit}),Bit=Ai.extend({level:Ab,logger:O().optional(),data:Ut()}),Zit=Pi.extend({method:ae("notifications/message"),params:Bit}),Wit=X({name:O().optional()}),Jit=X({hints:qe(Wit).optional(),costPriority:yt().min(0).max(1).optional(),speedPriority:yt().min(0).max(1).optional(),intelligencePriority:yt().min(0).max(1).optional()}),Xit=X({mode:Yr(["auto","required","none"]).optional()}),Yit=X({type:ae("tool_result"),toolUseId:O().describe("The unique identifier for the corresponding tool call."),content:qe(IG).default([]),structuredContent:X({}).loose().optional(),isError:yr().optional(),_meta:Ct(O(),Ut()).optional()}),Qit=fy("type",[EG,$G,RG]),YD=fy("type",[EG,$G,RG,Nit,Yit]),est=X({role:Ib,content:It([YD,qe(YD)]),_meta:Ct(O(),Ut()).optional()}),tst=_b.extend({messages:qe(est),modelPreferences:Jit.optional(),systemPrompt:O().optional(),includeContext:Yr(["none","thisServer","allServers"]).optional(),temperature:yt().optional(),maxTokens:yt().int(),stopSequences:qe(O()).optional(),metadata:Nr.optional(),tools:qe(DEe).optional(),toolChoice:Xit.optional()}),rst=hn.extend({method:ae("sampling/createMessage"),params:tst}),Pb=gn.extend({model:O(),stopReason:kt(Yr(["endTurn","stopSequence","maxTokens"]).or(O())),role:Ib,content:Qit}),PG=gn.extend({model:O(),stopReason:kt(Yr(["endTurn","stopSequence","maxTokens","toolUse"]).or(O())),role:Ib,content:It([YD,qe(YD)])}),nst=X({type:ae("boolean"),title:O().optional(),description:O().optional(),default:yr().optional()}),ost=X({type:ae("string"),title:O().optional(),description:O().optional(),minLength:yt().optional(),maxLength:yt().optional(),format:Yr(["email","uri","date","date-time"]).optional(),default:O().optional()}),ist=X({type:Yr(["number","integer"]),title:O().optional(),description:O().optional(),minimum:yt().optional(),maximum:yt().optional(),default:yt().optional()}),sst=X({type:ae("string"),title:O().optional(),description:O().optional(),enum:qe(O()),default:O().optional()}),ast=X({type:ae("string"),title:O().optional(),description:O().optional(),oneOf:qe(X({const:O(),title:O()})),default:O().optional()}),cst=X({type:ae("string"),title:O().optional(),description:O().optional(),enum:qe(O()),enumNames:qe(O()).optional(),default:O().optional()}),ust=It([sst,ast]),lst=X({type:ae("array"),title:O().optional(),description:O().optional(),minItems:yt().optional(),maxItems:yt().optional(),items:X({type:ae("string"),enum:qe(O())}),default:qe(O()).optional()}),dst=X({type:ae("array"),title:O().optional(),description:O().optional(),minItems:yt().optional(),maxItems:yt().optional(),items:X({anyOf:qe(X({const:O(),title:O()}))}),default:qe(O()).optional()}),pst=It([lst,dst]),fst=It([cst,ust,pst]),mst=It([fst,nst,ost,ist]),hst=_b.extend({mode:ae("form").optional(),message:O(),requestedSchema:X({type:ae("object"),properties:Ct(O(),mst),required:qe(O()).optional()})}),gst=_b.extend({mode:ae("url"),message:O(),elicitationId:O(),url:O().url()}),yst=It([hst,gst]),vst=hn.extend({method:ae("elicitation/create"),params:yst}),wst=Ai.extend({elicitationId:O()}),_st=Pi.extend({method:ae("notifications/elicitation/complete"),params:wst}),qh=gn.extend({action:Yr(["accept","decline","cancel"]),content:yy(t=>t===null?void 0:t,Ct(O(),It([O(),yt(),yr(),qe(O())])).optional())}),bst=X({type:ae("ref/resource"),uri:O()});var Sst=X({type:ae("ref/prompt"),name:O()}),xst=Zo.extend({ref:It([Sst,bst]),argument:X({name:O(),value:O()}),context:X({arguments:Ct(O(),O()).optional()}).optional()}),vN=hn.extend({method:ae("completion/complete"),params:xst});function NEe(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function zEe(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Est=gn.extend({completion:Xr({values:qe(O()).max(100),total:kt(yt().int()),hasMore:kt(yr())})}),$st=X({uri:O().startsWith("file://"),name:O().optional(),_meta:Ct(O(),Ut()).optional()}),Rst=hn.extend({method:ae("roots/list"),params:Zo.optional()}),kG=gn.extend({roots:qe($st)}),Ist=Pi.extend({method:ae("notifications/roots/list_changed"),params:Ai.optional()}),W5t=It([nN,_G,vN,AG,hN,mN,dN,pN,fN,Rit,Ait,Fh,gN,iN,aN,cN,lN]),J5t=It([rN,oN,bG,Ist,Rb]),X5t=It([tN,Pb,PG,qh,kG,sN,uN,Lh]),Y5t=It([nN,rst,vst,Rst,iN,aN,cN,lN]),Q5t=It([rN,oN,Zit,kit,Eit,Hit,jit,Rb,_st]),e8t=It([tN,fit,Est,Lit,Oit,_it,bit,xit,yN,Vit,sN,uN,Lh]),ee=class t extends Error{constructor(e,r,o){super(`MCP error ${e}: ${r}`),this.code=e,this.data=o,this.name="McpError"}static fromError(e,r,o){if(e===le.UrlElicitationRequired&&o){let n=o;if(n.elicitations)return new mG(n.elicitations,r)}return new t(e,r,o)}},mG=class extends ee{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(le.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function El(t){return t==="completed"||t==="failed"||t==="cancelled"}var UEe=Symbol("Let zodToJsonSchema decide on which parser to use");var MEe={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"},LEe=t=>typeof t=="string"?{...MEe,name:t}:{...MEe,...t};var jEe=t=>{let e=LEe(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([o,n])=>[n._def,{def:n._def,path:[...e.basePath,e.definitionPath,o],jsonSchema:void 0}]))}};function TG(t,e,r,o){o?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ut(t,e,r,o,n){t[e]=r,TG(t,e,o,n)}var wN=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function ar(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?wN(e,t.currentPath):e.join("/")}}function FEe(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==F.ZodAny&&(r.items=_e(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ut(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ut(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ut(r,"minItems",t.exactLength.value,t.exactLength.message,e),ut(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function qEe(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let o of t.checks)switch(o.kind){case"min":e.target==="jsonSchema7"?o.inclusive?ut(r,"minimum",o.value,o.message,e):ut(r,"exclusiveMinimum",o.value,o.message,e):(o.inclusive||(r.exclusiveMinimum=!0),ut(r,"minimum",o.value,o.message,e));break;case"max":e.target==="jsonSchema7"?o.inclusive?ut(r,"maximum",o.value,o.message,e):ut(r,"exclusiveMaximum",o.value,o.message,e):(o.inclusive||(r.exclusiveMaximum=!0),ut(r,"maximum",o.value,o.message,e));break;case"multipleOf":ut(r,"multipleOf",o.value,o.message,e);break}return r}function VEe(){return{type:"boolean"}}function _N(t,e){return _e(t.type._def,e)}var GEe=(t,e)=>_e(t.innerType._def,e);function CG(t,e,r){let o=r??e.dateStrategy;if(Array.isArray(o))return{anyOf:o.map((n,i)=>CG(t,e,n))};switch(o){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Ast(t,e)}}var Ast=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let o of t.checks)switch(o.kind){case"min":ut(r,"minimum",o.value,o.message,e);break;case"max":ut(r,"maximum",o.value,o.message,e);break}return r};function HEe(t,e){return{..._e(t.innerType._def,e),default:t.defaultValue()}}function KEe(t,e){return e.effectStrategy==="input"?_e(t.schema._def,e):ar(e)}function BEe(t){return{type:"string",enum:Array.from(t.values)}}var Pst=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function ZEe(t,e){let r=[_e(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),_e(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i),o=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,n=[];return r.forEach(i=>{if(Pst(i))n.push(...i.allOf),i.unevaluatedProperties===void 0&&(o=void 0);else{let s=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:a,...c}=i;s=c}else o=void 0;n.push(s)}}),n.length?{allOf:n,...o}:void 0}function WEe(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var OG,Ss={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:()=>(OG===void 0&&(OG=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),OG),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 bN(t,e){let r={type:"string"};if(t.checks)for(let o of t.checks)switch(o.kind){case"min":ut(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e);break;case"max":ut(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value,o.message,e);break;case"email":switch(e.emailStrategy){case"format:email":xs(r,"email",o.message,e);break;case"format:idn-email":xs(r,"idn-email",o.message,e);break;case"pattern:zod":ro(r,Ss.email,o.message,e);break}break;case"url":xs(r,"uri",o.message,e);break;case"uuid":xs(r,"uuid",o.message,e);break;case"regex":ro(r,o.regex,o.message,e);break;case"cuid":ro(r,Ss.cuid,o.message,e);break;case"cuid2":ro(r,Ss.cuid2,o.message,e);break;case"startsWith":ro(r,RegExp(`^${DG(o.value,e)}`),o.message,e);break;case"endsWith":ro(r,RegExp(`${DG(o.value,e)}$`),o.message,e);break;case"datetime":xs(r,"date-time",o.message,e);break;case"date":xs(r,"date",o.message,e);break;case"time":xs(r,"time",o.message,e);break;case"duration":xs(r,"duration",o.message,e);break;case"length":ut(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,o.value):o.value,o.message,e),ut(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,o.value):o.value,o.message,e);break;case"includes":{ro(r,RegExp(DG(o.value,e)),o.message,e);break}case"ip":{o.version!=="v6"&&xs(r,"ipv4",o.message,e),o.version!=="v4"&&xs(r,"ipv6",o.message,e);break}case"base64url":ro(r,Ss.base64url,o.message,e);break;case"jwt":ro(r,Ss.jwt,o.message,e);break;case"cidr":{o.version!=="v6"&&ro(r,Ss.ipv4Cidr,o.message,e),o.version!=="v4"&&ro(r,Ss.ipv6Cidr,o.message,e);break}case"emoji":ro(r,Ss.emoji(),o.message,e);break;case"ulid":{ro(r,Ss.ulid,o.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{xs(r,"binary",o.message,e);break}case"contentEncoding:base64":{ut(r,"contentEncoding","base64",o.message,e);break}case"pattern:zod":{ro(r,Ss.base64,o.message,e);break}}break}case"nanoid":ro(r,Ss.nanoid,o.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function DG(t,e){return e.patternStrategy==="escape"?Tst(t):t}var kst=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Tst(t){let e="";for(let r=0;r<t.length;r++)kst.has(t[r])||(e+="\\"),e+=t[r];return e}function xs(t,e,r,o){t.format||t.anyOf?.some(n=>n.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&o.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&o.errorMessages&&{errorMessage:{format:r}}})):ut(t,"format",e,r,o)}function ro(t,e,r,o){t.pattern||t.allOf?.some(n=>n.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&o.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:JEe(e,o),...r&&o.errorMessages&&{errorMessage:{pattern:r}}})):ut(t,"pattern",JEe(e,o),r,o)}function JEe(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},o=r.i?t.source.toLowerCase():t.source,n="",i=!1,s=!1,a=!1;for(let c=0;c<o.length;c++){if(i){n+=o[c],i=!1;continue}if(r.i){if(s){if(o[c].match(/[a-z]/)){a?(n+=o[c],n+=`${o[c-2]}-${o[c]}`.toUpperCase(),a=!1):o[c+1]==="-"&&o[c+2]?.match(/[a-z]/)?(n+=o[c],a=!0):n+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){n+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(r.m){if(o[c]==="^"){n+=`(^|(?<=[\r
144
144
  ]))`;continue}else if(o[c]==="$"){n+=`($|(?=[\r
145
145
  ]))`;continue}}if(r.s&&o[c]==="."){n+=s?`${o[c]}\r
146
146
  `:`[${o[c]}\r
147
147
  ]`;continue}n+=o[c],o[c]==="\\"?i=!0:s&&o[c]==="]"?s=!1:!s&&o[c]==="["&&(s=!0)}try{new RegExp(n)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return n}function SN(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===F.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((o,n)=>({...o,[n]:_e(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",n]})??ar(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:_e(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===F.ZodString&&t.keyType._def.checks?.length){let{type:o,...n}=bN(t.keyType._def,e);return{...r,propertyNames:n}}else{if(t.keyType?._def.typeName===F.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===F.ZodBranded&&t.keyType._def.type._def.typeName===F.ZodString&&t.keyType._def.type._def.checks?.length){let{type:o,...n}=_N(t.keyType._def,e);return{...r,propertyNames:n}}}return r}function XEe(t,e){if(e.mapStrategy==="record")return SN(t,e);let r=_e(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||ar(e),o=_e(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||ar(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,o],minItems:2,maxItems:2}}}function YEe(t){let e=t.values,o=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),n=Array.from(new Set(o.map(i=>typeof i)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:o}}function QEe(t){return t.target==="openAi"?void 0:{not:ar({...t,currentPath:[...t.currentPath,"not"]})}}function e$e(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var kb={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function r$e(t,e){if(e.target==="openApi3")return t$e(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(o=>o._def.typeName in kb&&(!o._def.checks||!o._def.checks.length))){let o=r.reduce((n,i)=>{let s=kb[i._def.typeName];return s&&!n.includes(s)?[...n,s]:n},[]);return{type:o.length>1?o:o[0]}}else if(r.every(o=>o._def.typeName==="ZodLiteral"&&!o.description)){let o=r.reduce((n,i)=>{let s=typeof i._def.value;switch(s){case"string":case"number":case"boolean":return[...n,s];case"bigint":return[...n,"integer"];case"object":if(i._def.value===null)return[...n,"null"];default:return n}},[]);if(o.length===r.length){let n=o.filter((i,s,a)=>a.indexOf(i)===s);return{type:n.length>1?n:n[0],enum:r.reduce((i,s)=>i.includes(s._def.value)?i:[...i,s._def.value],[])}}}else if(r.every(o=>o._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((o,n)=>[...o,...n._def.values.filter(i=>!o.includes(i))],[])};return t$e(t,e)}var t$e=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((o,n)=>_e(o._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(o=>!!o&&(!e.strictUnions||typeof o=="object"&&Object.keys(o).length>0));return r.length?{anyOf:r}:void 0};function n$e(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:kb[t.innerType._def.typeName],nullable:!0}:{type:[kb[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let o=_e(t.innerType._def,{...e,currentPath:[...e.currentPath]});return o&&"$ref"in o?{allOf:[o],nullable:!0}:o&&{...o,nullable:!0}}let r=_e(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function o$e(t,e){let r={type:"number"};if(!t.checks)return r;for(let o of t.checks)switch(o.kind){case"int":r.type="integer",TG(r,"type",o.message,e);break;case"min":e.target==="jsonSchema7"?o.inclusive?ut(r,"minimum",o.value,o.message,e):ut(r,"exclusiveMinimum",o.value,o.message,e):(o.inclusive||(r.exclusiveMinimum=!0),ut(r,"minimum",o.value,o.message,e));break;case"max":e.target==="jsonSchema7"?o.inclusive?ut(r,"maximum",o.value,o.message,e):ut(r,"exclusiveMaximum",o.value,o.message,e):(o.inclusive||(r.exclusiveMaximum=!0),ut(r,"maximum",o.value,o.message,e));break;case"multipleOf":ut(r,"multipleOf",o.value,o.message,e);break}return r}function i$e(t,e){let r=e.target==="openAi",o={type:"object",properties:{}},n=[],i=t.shape();for(let a in i){let c=i[a];if(c===void 0||c._def===void 0)continue;let u=Ost(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=_e(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(o.properties[a]=l,u||n.push(a))}n.length&&(o.required=n);let s=Cst(t,e);return s!==void 0&&(o.additionalProperties=s),o}function Cst(t,e){if(t.catchall._def.typeName!=="ZodNever")return _e(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Ost(t){try{return t.isOptional()}catch{return!0}}var s$e=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return _e(t.innerType._def,e);let r=_e(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:ar(e)},r]}:ar(e)};var a$e=(t,e)=>{if(e.pipeStrategy==="input")return _e(t.in._def,e);if(e.pipeStrategy==="output")return _e(t.out._def,e);let r=_e(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),o=_e(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,o].filter(n=>n!==void 0)}};function c$e(t,e){return _e(t.type._def,e)}function u$e(t,e){let o={type:"array",uniqueItems:!0,items:_e(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ut(o,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ut(o,"maxItems",t.maxSize.value,t.maxSize.message,e),o}function l$e(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,o)=>_e(r._def,{...e,currentPath:[...e.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[]),additionalItems:_e(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,o)=>_e(r._def,{...e,currentPath:[...e.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[])}}function d$e(t){return{not:ar(t)}}function p$e(t){return ar(t)}var f$e=(t,e)=>_e(t.innerType._def,e);var m$e=(t,e,r)=>{switch(e){case F.ZodString:return bN(t,r);case F.ZodNumber:return o$e(t,r);case F.ZodObject:return i$e(t,r);case F.ZodBigInt:return qEe(t,r);case F.ZodBoolean:return VEe();case F.ZodDate:return CG(t,r);case F.ZodUndefined:return d$e(r);case F.ZodNull:return e$e(r);case F.ZodArray:return FEe(t,r);case F.ZodUnion:case F.ZodDiscriminatedUnion:return r$e(t,r);case F.ZodIntersection:return ZEe(t,r);case F.ZodTuple:return l$e(t,r);case F.ZodRecord:return SN(t,r);case F.ZodLiteral:return WEe(t,r);case F.ZodEnum:return BEe(t);case F.ZodNativeEnum:return YEe(t);case F.ZodNullable:return n$e(t,r);case F.ZodOptional:return s$e(t,r);case F.ZodMap:return XEe(t,r);case F.ZodSet:return u$e(t,r);case F.ZodLazy:return()=>t.getter()._def;case F.ZodPromise:return c$e(t,r);case F.ZodNaN:case F.ZodNever:return QEe(r);case F.ZodEffects:return KEe(t,r);case F.ZodAny:return ar(r);case F.ZodUnknown:return p$e(r);case F.ZodDefault:return HEe(t,r);case F.ZodBranded:return _N(t,r);case F.ZodReadonly:return f$e(t,r);case F.ZodCatch:return GEe(t,r);case F.ZodPipeline:return a$e(t,r);case F.ZodFunction:case F.ZodVoid:case F.ZodSymbol:return;default:return(o=>{})(e)}};function _e(t,e,r=!1){let o=e.seen.get(t);if(e.override){let a=e.override?.(t,e,o,r);if(a!==UEe)return a}if(o&&!r){let a=Dst(o,e);if(a!==void 0)return a}let n={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,n);let i=m$e(t,t.typeName,e),s=typeof i=="function"?_e(i(),e):i;if(s&&Nst(t,e,s),e.postProcess){let a=e.postProcess(s,t,e);return n.jsonSchema=s,a}return n.jsonSchema=s,s}var Dst=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:wN(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,o)=>e.currentPath[o]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),ar(e)):e.$refStrategy==="seen"?ar(e):void 0}},Nst=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var NG=(t,e)=>{let r=jEe(e),o=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:_e(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??ar(r)}),{}):void 0,n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,i=_e(t._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??ar(r),s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(i.title=s),r.flags.hasReferencedOpenAiAnyType&&(o||(o={}),o[r.openAiAnyTypeName]||(o[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=n===void 0?o?{...i,[r.definitionPath]:o}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...o,[n]:i}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),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."),a};function zst(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function zG(t,e){return Ta(t)?Zl(t,{target:zst(e?.target),io:e?.pipeStrategy??"input"}):NG(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function MG(t){let r=Sl(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let o=Mh(r);if(typeof o!="string")throw new Error("Schema method literal must be a string");return o}function UG(t,e){let r=bl(t,e);if(!r.success)throw r.error;return r.data}var Mst=6e4,xN=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(rN,r=>{this._oncancel(r)}),this.setNotificationHandler(oN,r=>{this._onprogress(r)}),this.setRequestHandler(nN,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(iN,async(r,o)=>{let n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new ee(le.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(aN,async(r,o)=>{let n=async()=>{let i=r.params.taskId;if(!await this._taskStore.getTask(i,o.sessionId))throw new ee(le.InvalidParams,`Task not found: ${i}`);if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(i,o.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,p=new ee(d.error.code,d.error.message,d.error.data);l(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:o.requestId})}}let s=await this._taskStore.getTask(i,o.sessionId);if(!s)throw new ee(le.InvalidParams,`Task not found: ${i}`);if(!El(s.status))return await this._waitForTaskUpdate(i,o.signal,o.sessionId),await n();if(El(s.status)){let a=await this._taskStore.getTaskResult(i,o.sessionId);return this._clearTaskQueue(i,o.sessionId),{...a,_meta:{...a._meta,[xl]:{taskId:i}}}}return await n()};return await n()}),this.setRequestHandler(cN,async(r,o)=>{try{let{tasks:n,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,o.sessionId);return{tasks:n,nextCursor:i,_meta:{}}}catch(n){throw new ee(le.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(lN,async(r,o)=>{try{let n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new ee(le.InvalidParams,`Task not found: ${r.params.taskId}`);if(El(n.status))throw new ee(le.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",o.sessionId),this._clearTaskQueue(r.params.taskId,o.sessionId);let i=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!i)throw new ee(le.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(n){throw n instanceof ee?n:new ee(le.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,r,o,n,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:o,resetTimeoutOnProgress:i,onTimeout:n})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let o=Date.now()-r.startTime;if(r.maxTotalTimeout&&o>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),ee.fromError(le.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:o});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new 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 r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let o=this.transport?.onerror;this._transport.onerror=i=>{o?.(i),this._onerror(i)};let n=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{n?.(i,s),bb(i)||REe(i)?this._onresponse(i):yG(i)?this._onrequest(i,s):$Ee(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();for(let o of this._requestHandlerAbortControllers.values())o.abort();this._requestHandlerAbortControllers.clear();let r=ee.fromError(le.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let o of e.values())o(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(o=>this._onerror(new Error(`Uncaught error in notification handler: ${o}`)))}_onrequest(e,r){let o=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,i=e.params?._meta?.[xl]?.taskId,s=n?.sessionId,a=this._taskStore,c=!0,u;if(i&&a&&this._taskMessageQueue&&s!==void 0&&(c=!1,u=(async()=>{if(!await a.getTask(i,s))throw new ee(le.InvalidParams,`Task not found: ${i}`);c=!0})()),o===void 0){let h={jsonrpc:"2.0",id:e.id,error:{code:le.MethodNotFound,message:"Method not found"}};if(i&&u){let y={type:"error",message:h,timestamp:Date.now()};u.then(()=>this._enqueueTaskMessage(i,y,s),()=>n?.send(h)).catch(w=>this._onerror(new Error(`Failed to send an error response: ${w}`)))}else i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:h,timestamp:Date.now()},n?.sessionId).catch(y=>this._onerror(new Error(`Failed to enqueue error response: ${y}`))):n?.send(h).catch(y=>this._onerror(new Error(`Failed to send an error response: ${y}`)));return}let l=new AbortController;this._requestHandlerAbortControllers.set(e.id,l);let d=SEe(e.params)?e.params.task:void 0,p=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,f={signal:l.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async h=>{if(l.signal.aborted)return;let y={relatedRequestId:e.id};i&&(y.relatedTask={taskId:i}),await this.notification(h,y)},sendRequest:async(h,y,w)=>{if(l.signal.aborted)throw new ee(le.ConnectionClosed,"Request was cancelled");let b={...w,relatedRequestId:e.id};i&&!b.relatedTask&&(b.relatedTask={taskId:i});let S=b.relatedTask?.taskId??i;return S&&p&&await p.updateTaskStatus(S,"input_required"),await this.request(h,y,b)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:i,taskStore:p,taskRequestedTtl:d?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};(u??Promise.resolve()).then(()=>{if(u&&l.signal.aborted)throw new ee(le.ConnectionClosed,"Request was cancelled");d&&this.assertTaskHandlerCapability(e.method)}).then(()=>o(e,f)).then(async h=>{if(l.signal.aborted)return;let y={result:h,jsonrpc:"2.0",id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:y,timestamp:Date.now()},n?.sessionId):await n?.send(y)},async h=>{if(l.signal.aborted)return;let y={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(h.code)?h.code:le.InternalError,message:h.message??"Internal error",...h.data!==void 0&&{data:h.data}}};i&&this._taskMessageQueue&&c?await this._enqueueTaskMessage(i,{type:"error",message:y,timestamp:Date.now()},n?.sessionId):await n?.send(y)}).catch(h=>this._onerror(new Error(`Failed to send response: ${h}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===l&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...o}=e.params,n=Number(r),i=this._progressHandlers.get(n);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(n),a=this._timeoutInfo.get(n);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(c){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),s(c);return}i(o)}_onresponse(e){let r=Number(e.id),o=this._requestResolvers.get(r);if(o){if(this._requestResolvers.delete(r),bb(e))o(e);else{let s=new ee(e.error.code,e.error.message,e.error.data);o(s)}return}let n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(bb(e)&&e.result&&typeof e.result=="object"){let s=e.result;if(s.task&&typeof s.task=="object"){let a=s.task;typeof a.taskId=="string"&&(i=!0,this._taskProgressTokens.set(a.taskId,r))}}if(i||this._progressHandlers.delete(r),bb(e))n(e);else{let s=ee.fromError(e.error.code,e.error.message,e.error.data);n(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,o){let{task:n}=o??{};if(!n){try{yield{type:"result",result:await this.request(e,r,o)}}catch(s){yield{type:"error",error:s instanceof ee?s:new ee(le.InternalError,String(s))}}return}let i;try{let s=await this.request(e,Lh,o);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new ee(le.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},o);if(yield{type:"taskStatus",task:a},El(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,o)}:a.status==="failed"?yield{type:"error",error:new ee(le.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new ee(le.InternalError,`Task ${i} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,o)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),o?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof ee?s:new ee(le.InternalError,String(s))}}}request(e,r,o){let{relatedRequestId:n,resumptionToken:i,onresumptiontoken:s,task:a,relatedTask:c}=o??{};return new Promise((u,l)=>{let d=S=>{l(S)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(S){d(S);return}o?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};o?.onprogress&&(this._progressHandlers.set(p,o.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[xl]:c}});let h=S=>{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(S)}},{relatedRequestId:n,resumptionToken:i,onresumptiontoken:s}).catch(R=>this._onerror(new Error(`Failed to send cancellation: ${R}`)));let x=S instanceof ee?S:new ee(le.RequestTimeout,String(S));l(x)};this._responseHandlers.set(p,S=>{if(!o?.signal?.aborted){if(S instanceof Error)return l(S);try{let x=bl(r,S.result);x.success?u(x.data):l(x.error)}catch(x){l(x)}}}),o?.signal?.addEventListener("abort",()=>{h(o?.signal?.reason)});let y=o?.timeout??Mst,w=()=>h(ee.fromError(le.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(p,y,o?.maxTotalTimeout,w,o?.resetTimeoutOnProgress??!1);let b=c?.taskId;if(b){let S=x=>{let R=this._responseHandlers.get(p);R?R(x):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,S),this._enqueueTaskMessage(b,{type:"request",message:f,timestamp:Date.now()}).catch(x=>{this._cleanupTimeout(p),l(x)})}else this._transport.send(f,{relatedRequestId:n,resumptionToken:i,onresumptiontoken:s}).catch(S=>{this._cleanupTimeout(p),l(S)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},sN,r)}async getTaskResult(e,r,o){return this.request({method:"tasks/result",params:e},r,o)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},uN,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},PEe,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let o=r?.relatedTask?.taskId;if(o){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[xl]:r.relatedTask}}};await this._enqueueTaskMessage(o,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.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 a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[xl]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let s={...e,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[xl]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(e,r){let o=MG(e);this.assertRequestHandlerCapability(o),this._requestHandlers.set(o,(n,i)=>{let s=UG(e,n);return Promise.resolve(r(s,i))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let o=MG(e);this._notificationHandlers.set(o,n=>{let i=UG(e,n);return Promise.resolve(r(i))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,o){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,o??this._transport?.sessionId,n)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let o=await this._taskMessageQueue.dequeueAll(e,r);for(let n of o)if(n.type==="request"&&yG(n.message)){let i=n.message.id,s=this._requestResolvers.get(i);s?(s(new ee(le.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r,o){let n=this._options?.defaultTaskPollInterval??1e3;try{let i=await this._taskStore?.getTask(e,o);i?.pollInterval&&(n=i.pollInterval)}catch{}return new Promise((i,s)=>{if(r.aborted){s(new ee(le.InvalidRequest,"Request cancelled"));return}let a=setTimeout(i,n);r.addEventListener("abort",()=>{clearTimeout(a),s(new ee(le.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let o=this._taskStore;if(!o)throw new Error("No task store configured");return{createTask:async n=>{if(!e)throw new Error("No request provided");return await o.createTask(n,e.id,{method:e.method,params:e.params},r)},getTask:async n=>{let i=await o.getTask(n,r);if(!i)throw new ee(le.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(n,i,s)=>{await o.storeTaskResult(n,i,s,r);let a=await o.getTask(n,r);if(a){let c=Rb.parse({method:"notifications/tasks/status",params:a});await this.notification(c),El(a.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>o.getTaskResult(n,r),updateTaskStatus:async(n,i,s)=>{let a=await o.getTask(n,r);if(!a)throw new ee(le.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(El(a.status))throw new ee(le.InvalidParams,`Cannot update task "${n}" from terminal status "${a.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await o.updateTaskStatus(n,i,s,r);let c=await o.getTask(n,r);if(c){let u=Rb.parse({method:"notifications/tasks/status",params:c});await this.notification(u),El(c.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>o.listTasks(n,r)}}};function h$e(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function g$e(t,e){let r={...t};for(let o in e){let n=o,i=e[n];if(i===void 0)continue;let s=r[n];h$e(s)&&h$e(i)?r[n]={...s,...i}:r[n]=i}return r}var hAe=Vt(kK(),1),gAe=Vt(mAe(),1);function Zpt(){let t=new hAe.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,gAe.default)(t),t}var s1=class{constructor(e){this._ajv=e??Zpt()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return o=>r(o)?{valid:!0,data:o,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var a1=class{constructor(e){this._server=e}requestStream(e,r,o){return this._server.requestStream(e,r,o)}createMessageStream(e,r){let o=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!o?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],i=Array.isArray(n.content)?n.content:[n.content],s=i.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(s){if(i.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(p=>p.type==="tool_use").map(p=>p.id)),d=new Set(i.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==d.size||![...l].every(p=>d.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Pb,r)}elicitInputStream(e,r){let o=this._server.getClientCapabilities(),n=e.mode??"form";switch(n){case"url":{if(!o?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!o?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let i=n==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:i},qh,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,o){return this._server.getTaskResult({taskId:e},r,o)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function yAe(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function vAe(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var c1=class extends xN{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ab.options.map((o,n)=>[o,n])),this.isMessageIgnored=(o,n)=>{let i=this._loggingLevels.get(n);return i?this.LOG_LEVEL_SEVERITY.get(o)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new s1,this.setRequestHandler(_G,o=>this._oninitialize(o)),this.setNotificationHandler(bG,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(AG,async(o,n)=>{let i=n.sessionId||n.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=o.params,a=Ab.safeParse(s);return a.success&&this._loggingLevels.set(i,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new a1(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=g$e(this._capabilities,e)}setRequestHandler(e,r){let n=Sl(e)?.method;if(!n)throw new Error("Schema is missing a method literal");let i=Mh(n);if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){let a=async(c,u)=>{let l=bl(Fh,c);if(!l.success){let h=l.error instanceof Error?l.error.message:String(l.error);throw new ee(le.InvalidParams,`Invalid tools/call request: ${h}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let h=bl(Lh,p);if(!h.success){let y=h.error instanceof Error?h.error.message:String(h.error);throw new ee(le.InvalidParams,`Invalid task creation result: ${y}`)}return h.data}let f=bl(yN,p);if(!f.success){let h=f.error instanceof Error?f.error.message:String(f.error);throw new ee(le.InvalidParams,`Invalid tools/call result: ${h}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new 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 new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new 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 new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new 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 new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){vAe(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&yAe(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:wEe.includes(r)?r:hG,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"},tN)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],n=Array.isArray(o.content)?o.content:[o.content],i=n.some(u=>u.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(u=>u.type==="tool_use");if(i){if(n.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(n.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},PG,r):this.request({method:"sampling/createMessage",params:e},Pb,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let n=e;return this.request({method:"elicitation/create",params:n},qh,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let n=e.mode==="form"?e:{...e,mode:"form"},i=await this.request({method:"elicitation/create",params:n},qh,r);if(i.action==="accept"&&i.content&&n.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(n.requestedSchema)(i.content);if(!a.valid)throw new ee(le.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(s){throw s instanceof ee?s:new ee(le.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return i}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},kG,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))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 _Ae=Symbol.for("mcp.completable");function UK(t){return!!t&&typeof t=="object"&&_Ae in t}function bAe(t){return t[_Ae]?.complete}var wAe;(function(t){t.Completable="McpCompletable"})(wAe||(wAe={}));var Wpt=/^[A-Za-z0-9._-]{1,128}$/;function Jpt(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!Wpt.test(t)){let r=t.split("").filter(o=>!/[A-Za-z0-9._-]/.test(o)).filter((o,n,i)=>i.indexOf(o)===n);return e.push(`Tool name contains invalid characters: ${r.map(o=>`"${o}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function Xpt(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)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 LK(t){let e=Jpt(t);return Xpt(t,e.warnings),e.isValid}var u1=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,o){let n={taskSupport:"required",...r.execution};if(n.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,n,r._meta,o)}};function Ypt(t,e){let r=0,o=[t];for(;o.length>0;){let n=o.pop();if(!(n===null||typeof n!="object"))if(Array.isArray(n))for(let i of n){if(++r>e)return r;i!==null&&typeof i=="object"&&o.push(i)}else for(let i in n){if(!Object.prototype.hasOwnProperty.call(n,i))continue;if(++r>e)return r;let s=n[i];s!==null&&typeof s=="object"&&o.push(s)}}return r}function Qpt(t){if(!(t===void 0||t===1/0)){if(typeof t!="number"||Number.isNaN(t)||t<1)throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(t)}`);return t}}var l1=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new c1(e,r),this._maxToolInputElements=Qpt(r?.maxToolInputElements)}get experimental(){return this._experimental||(this._experimental={tasks:new u1(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Ol(gN)),this.server.assertCanSetRequestHandler(Ol(Fh)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(gN,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let o={name:e,title:r.title,description:r.description,inputSchema:(()=>{let n=zh(r.inputSchema);return n?zG(n,{strictUnions:!0,pipeStrategy:"input"}):eft})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let n=zh(r.outputSchema);n&&(o.outputSchema=zG(n,{strictUnions:!0,pipeStrategy:"output"}))}return o})})),this.server.setRequestHandler(Fh,async(e,r)=>{try{let o=this._registeredTools[e.params.name];if(!o)throw new ee(le.InvalidParams,`Tool ${e.params.name} not found`);if(!o.enabled)throw new ee(le.InvalidParams,`Tool ${e.params.name} disabled`);let n=!!e.params.task,i=o.execution?.taskSupport,s="createTask"in o.handler;if((i==="required"||i==="optional")&&!s)throw new ee(le.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i==="required"&&!n)throw new ee(le.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i==="optional"&&!n&&s)return await this.handleAutomaticTaskPolling(o,e,r);let a=await this.validateToolInput(o,e.params.arguments,e.params.name),c=await this.executeToolHandler(o,a,r);return n||await this.validateToolOutput(o,c,e.params.name),c}catch(o){if(o instanceof ee&&o.code===le.UrlElicitationRequired)throw o;return this.createToolError(o instanceof Error?o.message:String(o))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,o){if(this._maxToolInputElements!==void 0&&Ypt(r,this._maxToolInputElements)>this._maxToolInputElements)throw new ee(le.InvalidParams,`Invalid arguments for tool ${o}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let i=zh(e.inputSchema)??e.inputSchema,s=await JD(i,r??{});if(!s.success){let a="error"in s?s.error:"Unknown error",c=XD(a);throw new ee(le.InvalidParams,`Input validation error: Invalid arguments for tool ${o}: ${c}`)}return s.data}async validateToolOutput(e,r,o){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new ee(le.InvalidParams,`Output validation error: Tool ${o} has an output schema but no structured content was provided`);let n=zh(e.outputSchema),i=await JD(n,r.structuredContent);if(!i.success){let s="error"in i?i.error:"Unknown error",a=XD(s);throw new ee(le.InvalidParams,`Output validation error: Invalid structured content for tool ${o}: ${a}`)}}async executeToolHandler(e,r,o){let n=e.handler;if("createTask"in n){if(!o.taskStore)throw new Error("No task store provided.");let s={...o,taskStore:o.taskStore};if(e.inputSchema){let a=n;return await Promise.resolve(a.createTask(r,s))}else{let a=n;return await Promise.resolve(a.createTask(s))}}if(e.inputSchema){let s=n;return await Promise.resolve(s(r,o))}else{let s=n;return await Promise.resolve(s(o))}}async handleAutomaticTaskPolling(e,r,o){if(!o.taskStore)throw new Error("No task store provided for task-capable tool.");let n=await this.validateToolInput(e,r.params.arguments,r.params.name),i=e.handler,s={...o,taskStore:o.taskStore},a=n?await Promise.resolve(i.createTask(n,s)):await Promise.resolve(i.createTask(s)),c=a.task.taskId,u=a.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(p=>setTimeout(p,l));let d=await o.taskStore.getTask(c);if(!d)throw new ee(le.InternalError,`Task ${c} not found during polling`);u=d}return await o.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Ol(vN)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(vN,async e=>{switch(e.params.ref.type){case"ref/prompt":return NEe(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return zEe(e),this.handleResourceCompletion(e,e.params.ref);default:throw new ee(le.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let o=this._registeredPrompts[r.name];if(!o)throw new ee(le.InvalidParams,`Prompt ${r.name} not found`);if(!o.enabled)throw new ee(le.InvalidParams,`Prompt ${r.name} disabled`);if(!o.argsSchema)return aS;let i=Sl(o.argsSchema)?.[e.params.argument.name];if(!UK(i))return aS;let s=bAe(i);if(!s)return aS;let a=await s(e.params.argument.value,e.params.context);return xAe(a)}async handleResourceCompletion(e,r){let o=Object.values(this._registeredResourceTemplates).find(s=>s.resourceTemplate.uriTemplate.toString()===r.uri);if(!o){if(this._registeredResources[r.uri])return aS;throw new ee(le.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let n=o.resourceTemplate.completeCallback(e.params.argument.name);if(!n)return aS;let i=await n(e.params.argument.value,e.params.context);return xAe(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Ol(dN)),this.server.assertCanSetRequestHandler(Ol(pN)),this.server.assertCanSetRequestHandler(Ol(fN)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(dN,async(e,r)=>{let o=Object.entries(this._registeredResources).filter(([i,s])=>s.enabled).map(([i,s])=>({uri:i,name:s.name,...s.metadata})),n=[];for(let i of Object.values(this._registeredResourceTemplates)){if(!i.resourceTemplate.listCallback)continue;let s=await i.resourceTemplate.listCallback(r);for(let a of s.resources)n.push({...i.metadata,...a})}return{resources:[...o,...n]}}),this.server.setRequestHandler(pN,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,o])=>({name:r,uriTemplate:o.resourceTemplate.uriTemplate.toString(),...o.metadata}))})),this.server.setRequestHandler(fN,async(e,r)=>{let o=new URL(e.params.uri),n=this._registeredResources[o.toString()];if(n){if(!n.enabled)throw new ee(le.InvalidParams,`Resource ${o} disabled`);return n.readCallback(o,r)}for(let i of Object.values(this._registeredResourceTemplates)){let s=i.resourceTemplate.uriTemplate.match(o.toString());if(s)return i.readCallback(o,s,r)}throw new ee(le.InvalidParams,`Resource ${o} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Ol(mN)),this.server.assertCanSetRequestHandler(Ol(hN)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(mN,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?tft(r.argsSchema):void 0}))})),this.server.setRequestHandler(hN,async(e,r)=>{let o=this._registeredPrompts[e.params.name];if(!o)throw new ee(le.InvalidParams,`Prompt ${e.params.name} not found`);if(!o.enabled)throw new ee(le.InvalidParams,`Prompt ${e.params.name} disabled`);if(o.argsSchema){let n=zh(o.argsSchema),i=await JD(n,e.params.arguments??{});if(!i.success){let c="error"in i?i.error:"Unknown error",u=XD(c);throw new ee(le.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let s=i.data,a=o.callback;return await Promise.resolve(a(s,r))}else{let n=o.callback;return await Promise.resolve(n(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...o){let n;typeof o[0]=="object"&&(n=o.shift());let i=o[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,void 0,r,n,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,void 0,r,n,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(e,r,o,n){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,o.title,r,o,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,o.title,r,o,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,r,o,n,i){let s={name:e,title:r,metadata:n,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==o&&(delete this._registeredResources[o],a.uri&&(this._registeredResources[a.uri]=s)),typeof a.name<"u"&&(s.name=a.name),typeof a.title<"u"&&(s.title=a.title),typeof a.metadata<"u"&&(s.metadata=a.metadata),typeof a.callback<"u"&&(s.readCallback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[o]=s,s}_createRegisteredResourceTemplate(e,r,o,n,i){let s={resourceTemplate:o,title:r,metadata:n,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=s)),typeof u.title<"u"&&(s.title=u.title),typeof u.template<"u"&&(s.resourceTemplate=u.template),typeof u.metadata<"u"&&(s.metadata=u.metadata),typeof u.callback<"u"&&(s.readCallback=u.callback),typeof u.enabled<"u"&&(s.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=s;let a=o.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!o.completeCallback(u))&&this.setCompletionRequestHandler(),s}_createRegisteredPrompt(e,r,o,n,i){let s={title:r,description:o,argsSchema:n===void 0?void 0:np(n),callback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=s)),typeof a.title<"u"&&(s.title=a.title),typeof a.description<"u"&&(s.description=a.description),typeof a.argsSchema<"u"&&(s.argsSchema=np(a.argsSchema)),typeof a.callback<"u"&&(s.callback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=s,n&&Object.values(n).some(c=>{let u=c instanceof Yl?c._def?.innerType:c;return UK(u)})&&this.setCompletionRequestHandler(),s}_createRegisteredTool(e,r,o,n,i,s,a,c,u){LK(e);let l={title:r,description:o,inputSchema:SAe(n),outputSchema:SAe(i),annotations:s,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&LK(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=l)),typeof d.title<"u"&&(l.title=d.title),typeof d.description<"u"&&(l.description=d.description),typeof d.paramsSchema<"u"&&(l.inputSchema=np(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=np(d.outputSchema)),typeof d.callback<"u"&&(l.handler=d.callback),typeof d.annotations<"u"&&(l.annotations=d.annotations),typeof d._meta<"u"&&(l._meta=d._meta),typeof d.enabled<"u"&&(l.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let o,n,i,s;if(typeof r[0]=="string"&&(o=r.shift()),r.length>1){let c=r[0];if(jK(c))n=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!jK(r[0])&&(s=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);s=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,o,n,i,s,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,o){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:n,description:i,inputSchema:s,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,n,i,s,a,c,{taskSupport:"forbidden"},u,o)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let o;typeof r[0]=="string"&&(o=r.shift());let n;r.length>1&&(n=r.shift());let i=r[0],s=this._createRegisteredPrompt(e,void 0,o,n,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}registerPrompt(e,r,o){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:n,description:i,argsSchema:s}=r,a=this._createRegisteredPrompt(e,n,i,s,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var eft={type:"object",properties:{}};function EAe(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function $Ae(t){return"_def"in t||"_zod"in t||EAe(t)}function jK(t){return typeof t!="object"||t===null||$Ae(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(EAe)}function SAe(t){if(t){if(jK(t))return np(t);if(!$Ae(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function tft(t){let e=Sl(t);return e?Object.entries(e).map(([r,o])=>{let n=yEe(o),i=vEe(o);return{name:r,description:n,required:!i}}):[]}function Ol(t){let r=Sl(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let o=Mh(r);if(typeof o=="string")return o;throw new Error("Schema method literal must be a string")}function xAe(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var aS={completion:{values:[],hasMore:!1}};import IAe from"node:process";var rft=10*1024*1024,d1=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??rft}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
148
148
  `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),nft(r)}clear(){this._buffer=void 0}};function nft(t){return IEe.parse(JSON.parse(t))}function RAe(t){return JSON.stringify(t)+`
149
- `}var p1=class{constructor(e=IAe.stdin,r=IAe.stdout,o){this._stdin=e,this._stdout=r,this._started=!1,this._ondata=n=>{try{this._readBuffer.append(n),this.processReadBuffer()}catch(i){this.onerror?.(i),this.close().catch(()=>{})}},this._onerror=n=>{this.onerror?.(n)},this._readBuffer=new d1({maxBufferSize:o?.maxBufferSize})}async start(){if(this._started)throw new 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(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){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(r=>{let o=RAe(e);this._stdout.write(o)?r():this._stdout.once("drain",r)})}};var Ma=m.enum(["json","markdown"]).default("json");function oft(t,e="json"){let r=JSON.parse(JSON.stringify(t)),o=JSON.stringify(r);return o.length>25e3&&(r={truncated:!0,preview:o.slice(0,24e3),characters:o.length,hint:"Use a smaller API limit or a specific schema path/component."}),{content:[{type:"text",text:e==="markdown"?"```json\n"+JSON.stringify(r,null,2)+"\n```":JSON.stringify(r)}],structuredContent:{data:r}}}async function Ua(t,e="json"){try{return oft(await t(),e)}catch(r){return{isError:!0,content:[{type:"text",text:r instanceof Error?r.message:"The operation could not be completed."}]}}}function AAe(t,e){t.registerTool("foundation_functions",{title:"Find callable functions",description:"List functions available to this identity and their declared inputs. Execute permission exposes the calling interface; reading the program requires separate permission.",inputSchema:m.object({query:m.string().max(200).optional(),limit:m.number().int().min(1).max(100).default(20),after:E.optional(),response_format:Ma}).strict(),annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},r=>Ua(()=>{let o=new URLSearchParams({limit:String(r.limit),...r.query?{query:r.query}:{},...r.after?{after:r.after}:{}});return e.request("GET","/api/functions?"+o)},r.response_format)),t.registerTool("foundation_invoke_function",{title:"Invoke a saved function",description:"Call a function using only its ID and declared arguments. Requires execute permission on the function. Connections and variables stay inside the approved executor. Returns an execution ID; use foundation_execution_result to read its state and result. Reuse the same id and arguments after a transport failure to avoid starting another invocation.",inputSchema:m.object({functionId:E,arguments:Lt.default({}),id:E.optional(),response_format:Ma}).strict(),annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},r=>Ua(async()=>{let o=r.id??crypto.randomUUID();try{return await e.request("POST","/api/functions/"+r.functionId+"/executions",{id:o,arguments:r.arguments})}catch(n){throw new Error((n instanceof Error?n.message:"The invocation request failed.")+" Check execution "+o+" or retry with the same id and arguments.")}},r.response_format)),t.registerTool("foundation_execution_result",{title:"Read an execution",description:"Read an execution state, error, and result. Does not start or retry work. Large results are returned as JSON text with offset/limit and a next offset.",inputSchema:m.object({id:E,offset:m.number().int().min(0).default(0),limit:m.number().int().min(1).max(2e4).default(2e4),response_format:Ma}).strict(),annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},r=>Ua(async()=>{let o=e.executionResult?await e.executionResult(r.id):(await e.request("GET","/api/executions/"+r.id)).body,{results:n,...i}=o,s=JSON.stringify(n),a=s.slice(r.offset,r.offset+r.limit);return{...i,offset:r.offset,text:a,next:r.offset+a.length<s.length?r.offset+a.length:null}},r.response_format)),t.registerTool("foundation_cancel_execution",{title:"Cancel a function invocation",description:"Cancel a queued invocation or ask its executor to stop an active invocation. Cancellation cannot undo effects that already happened. Inspect the final invocation state before deciding to call again.",inputSchema:m.object({id:E,response_format:Ma}).strict(),annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!0}},r=>Ua(()=>e.request("POST","/api/executions/"+r.id+"/cancel",{}),r.response_format)),t.registerTool("foundation_schema",{title:"Inspect the Foundation API",description:"Inspect API paths or a named schema component. With no filter, lists available paths and component names. Use foundation_api with page limits and cursors for resource metadata.",inputSchema:m.object({path:m.string().startsWith("/api/").optional(),component:m.string().max(200).optional(),response_format:Ma}).strict(),annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0}},r=>Ua(async()=>{let o=m.object({paths:m.record(m.string(),yr),components:m.object({schemas:m.record(m.string(),yr).default({})}).optional()}).parse(await e.schema());return r.path?o.paths[r.path]??{error:"Choose a path from foundation_schema."}:r.component?o.components?.schemas[r.component]??{error:"Choose a component from foundation_schema."}:{paths:Object.keys(o.paths),components:Object.keys(o.components?.schemas??{})}},r.response_format)),t.registerTool("foundation_api",{title:"Call the Foundation API",description:"Call Foundation resource, process, and approval APIs as this principal. Start a command with POST /api/environments/{id}/processes. Read state, exit status, and paginated stdout/stderr through GET /api/processes/{id}/output; use its next offset to read more. Inspect or cancel a process through /api/processes/{id}. Include limit/after on list paths. Use POST /api/executions with operations (name, input, optional input fields) and optional responderId to prepare work. Return its url to the principal supplying consent or private input. Protected variables and connections require client encryption in that continuation screen.",inputSchema:m.object({method:m.enum(["GET","POST","PUT","PATCH","DELETE"]),path:m.string().startsWith("/api/").max(2048),body:yr.optional(),response_format:Ma}).strict(),annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},r=>Ua(async()=>{let o=new URL(r.path,"https://foundation.invalid");if(o.origin!=="https://foundation.invalid"||!o.pathname.startsWith("/api/")||/^\/api\/mcp(?:\/|$)/u.test(o.pathname)||/[\\\u0000-\u001f]/u.test(r.path)||o.hash)throw new Error("Choose a Foundation resource API path.");return e.request(r.method,o.pathname+o.search,r.body)},r.response_format))}var ift=m.discriminatedUnion("kind",[m.object({kind:m.literal("http"),request:Za,save:m.record(m.string().max(500),fe).default({})}).strict(),Wa.extend({kind:m.literal("command")}).strict()]);function sft(t,e=()=>Dn(t).custody){let r=new l1({name:"foundation-mcp-server",version:_y.version},{instructions:"Use foundation_functions to find callable functions, foundation_invoke_function to invoke one with its declared arguments, and foundation_execution_result to read the result. Function calls require execute permission; they do not require encryption keys or access to the program, environment, connections, or variables. Use foundation_save_function with local keys to publish a definition and approve its protected inputs. Use foundation_schema to discover the common Foundation API and foundation_api to manage resources and start commands through /api/environments/{id}/processes. Inspect or cancel a process through /api/processes/{id}. For protected caller programs, foundation_run signs and encrypts a request for an explicitly selected, previously trusted executor. Reference variable and connection IDs in protected bindings or command inputs. GET /api/definitions lists user operations. Prepare operations with POST /api/executions and operations containing name, input, and optional input fields, with an optional responderId. It returns an execution ID and continuation URL; protected values are entered directly in that screen. Requests deliver executions when a handoff is needed. Use foundation_execution_result to verify and decrypt protected execution results; uncertain means inspect the destination before issuing another operation. Fingerprint trust is established separately through foundation trust or the browser, not by a model tool."});return AAe(r,{schema:()=>t.json("/api/openapi.json"),async executionResult(o){let n=await t.json("/api/executions/"+o,{},Ze);for(let i of n.steps){let s=i.runs.filter(c=>c.kind==="run").at(-1);if(!s)continue;let a=await t.json("/api/runtime/runs/"+s.id,{},Bn);a.receipt&&(n.results[i.index]=(await e().result(a))?.result??null)}return n},async request(o,n,i){let s=await t.response(n,{method:o,body:i});return{status:s.status,body:s.status===204?null:await s.json()}}}),r.registerTool("foundation_save_function",{title:"Save a reusable function",description:"Save a fixed program, its arguments and result format, and its execution environment. Command programs read arguments as JSON from stdin and write their result to stdout in temporary working storage. Approves the exact function for its protected inputs using local encryption keys. Share its execute permission to allow calls without direct input access. Reference variable or connection IDs; never supply their plaintext.",inputSchema:Rf.extend({response_format:Ma}).strict(),annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},o=>Ua(async()=>{let{response_format:n,...i}=o,s=await new Pa(t,e()).save(i);return{id:s.id,name:s.name,version:s.version}},o.response_format)),r.registerTool("foundation_run",{title:"Run on an explicitly trusted executor",description:"Sign and encrypt one HTTP request or command for an explicitly selected, trusted executor. Requires environment permission and caller-program input grants. Use foundation_invoke_function for saved functions. Use save to map HTTP result JSON pointers to encrypted variable names. Returns the execution ID and state. Retry transport failures with foundation_resume_execution and the returned ID.",inputSchema:m.object({ownerId:E.optional(),environmentId:E.optional(),operation:ift,response_format:Ma}).strict(),annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},o=>Ua(async()=>{let n=o.environmentId;if(!n)throw new Error("Choose an execution environment.");let i=o.operation.kind==="http"?{kind:"http",request:o.operation.request}:o.operation,s=await Ri(t,e()).execute({name:"run.execute",input:Lt.parse({ownerId:o.ownerId??t.identity.principalId,environmentId:n,operation:i,save:o.operation.kind==="http"?o.operation.save:{}})});if(!("kind"in s)||s.kind!=="run")return s;let{task:a}=s,c=a.intent.operationContext.id;return{id:c,state:a.state==="queued"?"running":a.state,environmentId:a.environmentId,url:t.identity.origin+"/executions/"+c}},o.response_format)),r.registerTool("foundation_resume_execution",{title:"Resubmit the same signed execution",description:"Resubmit the exact locally saved request after a submission transport failure. Uses the same ID and encrypted request, so it cannot dispatch an already dispatched operation again.",inputSchema:m.object({id:E,response_format:Ma}).strict(),annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!0}},o=>Ua(async()=>{let n=await Ri(t,e()).continue(o.id);return"kind"in n&&n.kind==="run"?t.json("/api/executions/"+n.task.intent.operationContext.id,{},Ze):n},o.response_format)),r}async function PAe(t){return await sft(t).connect(new p1),0}async function kAe(t,e){let o=(await t.json("/api/connection-methods",{},Mr(zy))).items.find(n=>n.id===e);if(!o)throw new Error("Choose an available connection method.");return o}function TAe(t){return Ri(t).connections}async function CAe(t,e){let r=await kAe(t,e.methodId);if(xr(r).application==="none")throw new Error("Choose a connection method that uses an application.");let o=Ri(t),n=e.id?await o.custody.read(E.parse(e.id)):void 0,i=await o.execute({name:"app.save",input:{ownerId:e.ownerId,name:fe.parse(e.name),methodId:e.methodId,clientId:e.clientId,...e.id?{resourceId:e.id,version:n.version}:{},...e.environments?{environmentIds:e.environments}:{}}},{clientSecret:e.clientSecret,fields:m.record(m.string(),m.string()).parse(e.fields)});if(!("kind"in i)||i.kind!=="saved")throw new Error("Finish saving the application.");return i.resource}async function OAe(t,e){let r=await kAe(t,e.methodId),o=e.connectionId?await t.json("/api/resources/"+E.parse(e.connectionId),{},br):null,n=await Ri(t).execute({name:"connection.connect",input:{ownerId:e.ownerId,methodId:e.methodId,name:fe.parse(e.name??o?.name??r.defaultName),...e.appId?{appId:e.appId}:{},...e.connectionId?{connectionId:e.connectionId}:{},...e.redirectUri?{redirectUri:e.redirectUri}:{}}},{fields:m.record(m.string(),m.string()).parse(e.fields),scopes:m.array(m.string()).optional().parse(e.scopes),...e.aws!==void 0?{aws:Ba.parse(e.aws)}:{}});if("kind"in n&&n.kind==="saved")return n;if(!("flow"in n))throw new Error("Continue the pending connection.");return n}function FK(t){return t.kind==="saved"?{kind:"connected",id:t.executionId,connectionId:t.resource.id,resource:t.resource}:{kind:t.kind,id:t.flow.execution.id,...t.kind==="pending"?{state:"running"}:{},...t.kind==="authorize"?{authorizationUrl:t.url,next:"Open the URL, then run foundation connect wait "+t.flow.execution.id}:{},...t.kind==="cli"?{next:t.command}:{},...t.kind==="connected"?{connectionId:t.id}:{},...t.kind==="failed"?{error:t.error}:{}}}var mft=`Foundation ${_y.version}
149
+ `}var p1=class{constructor(e=IAe.stdin,r=IAe.stdout,o){this._stdin=e,this._stdout=r,this._started=!1,this._ondata=n=>{try{this._readBuffer.append(n),this.processReadBuffer()}catch(i){this.onerror?.(i),this.close().catch(()=>{})}},this._onerror=n=>{this.onerror?.(n)},this._readBuffer=new d1({maxBufferSize:o?.maxBufferSize})}async start(){if(this._started)throw new 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(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){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(r=>{let o=RAe(e);this._stdout.write(o)?r():this._stdout.once("drain",r)})}};var Ma=m.enum(["json","markdown"]).default("json");function oft(t,e="json"){let r=JSON.parse(JSON.stringify(t)),o=JSON.stringify(r);return o.length>25e3&&(r={truncated:!0,preview:o.slice(0,24e3),characters:o.length,hint:"Use a smaller API limit or a specific schema path/component."}),{content:[{type:"text",text:e==="markdown"?"```json\n"+JSON.stringify(r,null,2)+"\n```":JSON.stringify(r)}],structuredContent:{data:r}}}async function Ua(t,e="json"){try{return oft(await t(),e)}catch(r){return{isError:!0,content:[{type:"text",text:r instanceof Error?r.message:"The operation could not be completed."}]}}}function AAe(t,e){t.registerTool("foundation_functions",{title:"Find callable functions",description:"List functions available to this identity and their declared inputs. Execute permission exposes the calling interface; reading the program requires separate permission.",inputSchema:m.object({query:m.string().max(200).optional(),limit:m.number().int().min(1).max(100).default(20),after:E.optional(),response_format:Ma}).strict(),annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},r=>Ua(()=>{let o=new URLSearchParams({limit:String(r.limit),...r.query?{query:r.query}:{},...r.after?{after:r.after}:{}});return e.request("GET","/api/functions?"+o)},r.response_format)),t.registerTool("foundation_invoke_function",{title:"Invoke a saved function",description:"Call a function using only its ID and declared arguments. Requires execute permission on the function. Connections and variables stay inside the approved executor. Returns an execution ID; use foundation_execution_result to read its state and result. Reuse the same id and arguments after a transport failure to avoid starting another invocation.",inputSchema:m.object({functionId:E,arguments:Lt.default({}),id:E.optional(),response_format:Ma}).strict(),annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},r=>Ua(async()=>{let o=r.id??crypto.randomUUID();try{return await e.request("POST","/api/functions/"+r.functionId+"/executions",{id:o,arguments:r.arguments})}catch(n){throw new Error((n instanceof Error?n.message:"The invocation request failed.")+" Check execution "+o+" or retry with the same id and arguments.")}},r.response_format)),t.registerTool("foundation_execution_result",{title:"Read an execution",description:"Read an execution state, error, and result. Does not start or retry work. Large results are returned as JSON text with offset/limit and a next offset.",inputSchema:m.object({id:E,offset:m.number().int().min(0).default(0),limit:m.number().int().min(1).max(2e4).default(2e4),response_format:Ma}).strict(),annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},r=>Ua(async()=>{let o=e.executionResult?await e.executionResult(r.id):(await e.request("GET","/api/executions/"+r.id)).body,{results:n,...i}=o,s=JSON.stringify(n),a=s.slice(r.offset,r.offset+r.limit);return{...i,offset:r.offset,text:a,next:r.offset+a.length<s.length?r.offset+a.length:null}},r.response_format)),t.registerTool("foundation_cancel_execution",{title:"Cancel a function invocation",description:"Cancel a queued invocation or ask its executor to stop an active invocation. Cancellation cannot undo effects that already happened. Inspect the final invocation state before deciding to call again.",inputSchema:m.object({id:E,response_format:Ma}).strict(),annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!0}},r=>Ua(()=>e.request("POST","/api/executions/"+r.id+"/cancel",{}),r.response_format)),t.registerTool("foundation_schema",{title:"Inspect the Foundation API",description:"Inspect API paths or a named schema component. With no filter, lists available paths and component names. Use foundation_api with page limits and cursors for resource metadata.",inputSchema:m.object({path:m.string().startsWith("/api/").optional(),component:m.string().max(200).optional(),response_format:Ma}).strict(),annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0}},r=>Ua(async()=>{let o=m.object({paths:m.record(m.string(),vr),components:m.object({schemas:m.record(m.string(),vr).default({})}).optional()}).parse(await e.schema());return r.path?o.paths[r.path]??{error:"Choose a path from foundation_schema."}:r.component?o.components?.schemas[r.component]??{error:"Choose a component from foundation_schema."}:{paths:Object.keys(o.paths),components:Object.keys(o.components?.schemas??{})}},r.response_format)),t.registerTool("foundation_api",{title:"Call the Foundation API",description:"Call Foundation resource, process, and approval APIs as this principal. Start a command with POST /api/environments/{id}/processes. Read state, exit status, and paginated stdout/stderr through GET /api/processes/{id}/output; use its next offset to read more. Inspect or cancel a process through /api/processes/{id}. Include limit/after on list paths. Use POST /api/executions with operations (name, input, optional input fields) and optional responderId to prepare work. Return its url to the principal supplying consent or private input. Protected variables and connections require client encryption in that continuation screen.",inputSchema:m.object({method:m.enum(["GET","POST","PUT","PATCH","DELETE"]),path:m.string().startsWith("/api/").max(2048),body:vr.optional(),response_format:Ma}).strict(),annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},r=>Ua(async()=>{let o=new URL(r.path,"https://foundation.invalid");if(o.origin!=="https://foundation.invalid"||!o.pathname.startsWith("/api/")||/^\/api\/mcp(?:\/|$)/u.test(o.pathname)||/[\\\u0000-\u001f]/u.test(r.path)||o.hash)throw new Error("Choose a Foundation resource API path.");return e.request(r.method,o.pathname+o.search,r.body)},r.response_format))}var ift=m.discriminatedUnion("kind",[m.object({kind:m.literal("http"),request:Za,save:m.record(m.string().max(500),fe).default({})}).strict(),Wa.extend({kind:m.literal("command")}).strict()]);function sft(t,e=()=>Dn(t).custody){let r=new l1({name:"foundation-mcp-server",version:_y.version},{instructions:"Use foundation_functions to find callable functions, foundation_invoke_function to invoke one with its declared arguments, and foundation_execution_result to read the result. Function calls require execute permission; they do not require encryption keys or access to the program, environment, connections, or variables. Use foundation_save_function with local keys to publish a definition and approve its protected inputs. Use foundation_schema to discover the common Foundation API and foundation_api to manage resources and start commands through /api/environments/{id}/processes. Inspect or cancel a process through /api/processes/{id}. For protected caller programs, foundation_run signs and encrypts a request for an explicitly selected, previously trusted executor. Reference variable and connection IDs in protected bindings or command inputs. GET /api/definitions lists user operations. Prepare operations with POST /api/executions and operations containing name, input, and optional input fields, with an optional responderId. It returns an execution ID and continuation URL; protected values are entered directly in that screen. Requests deliver executions when a handoff is needed. Use foundation_execution_result to verify and decrypt protected execution results; uncertain means inspect the destination before issuing another operation. Fingerprint trust is established separately through foundation trust or the browser, not by a model tool."});return AAe(r,{schema:()=>t.json("/api/openapi.json"),async executionResult(o){let n=await t.json("/api/executions/"+o,{},Ze);for(let i of n.steps){let s=i.runs.filter(c=>c.kind==="run").at(-1);if(!s)continue;let a=await t.json("/api/runtime/runs/"+s.id,{},Bn);a.receipt&&(n.results[i.index]=(await e().result(a))?.result??null)}return n},async request(o,n,i){let s=await t.response(n,{method:o,body:i});return{status:s.status,body:s.status===204?null:await s.json()}}}),r.registerTool("foundation_save_function",{title:"Save a reusable function",description:"Save a fixed program, its arguments and result format, and its execution environment. Command programs read arguments as JSON from stdin and write their result to stdout in temporary working storage. Approves the exact function for its protected inputs using local encryption keys. Share its execute permission to allow calls without direct input access. Reference variable or connection IDs; never supply their plaintext.",inputSchema:Rf.extend({response_format:Ma}).strict(),annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},o=>Ua(async()=>{let{response_format:n,...i}=o,s=await new Pa(t,e()).save(i);return{id:s.id,name:s.name,version:s.version}},o.response_format)),r.registerTool("foundation_run",{title:"Run on an explicitly trusted executor",description:"Sign and encrypt one HTTP request or command for an explicitly selected, trusted executor. Requires environment permission and caller-program input grants. Use foundation_invoke_function for saved functions. Use save to map HTTP result JSON pointers to encrypted variable names. Returns the execution ID and state. Retry transport failures with foundation_resume_execution and the returned ID.",inputSchema:m.object({ownerId:E.optional(),environmentId:E.optional(),operation:ift,response_format:Ma}).strict(),annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},o=>Ua(async()=>{let n=o.environmentId;if(!n)throw new Error("Choose an execution environment.");let i=o.operation.kind==="http"?{kind:"http",request:o.operation.request}:o.operation,s=await Ri(t,e()).execute({name:"run.execute",input:Lt.parse({ownerId:o.ownerId??t.identity.principalId,environmentId:n,operation:i,save:o.operation.kind==="http"?o.operation.save:{}})});if(!("kind"in s)||s.kind!=="run")return s;let{task:a}=s,c=a.intent.operationContext.id;return{id:c,state:a.state==="queued"?"running":a.state,environmentId:a.environmentId,url:t.identity.origin+"/executions/"+c}},o.response_format)),r.registerTool("foundation_resume_execution",{title:"Resubmit the same signed execution",description:"Resubmit the exact locally saved request after a submission transport failure. Uses the same ID and encrypted request, so it cannot dispatch an already dispatched operation again.",inputSchema:m.object({id:E,response_format:Ma}).strict(),annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!0}},o=>Ua(async()=>{let n=await Ri(t,e()).continue(o.id);return"kind"in n&&n.kind==="run"?t.json("/api/executions/"+n.task.intent.operationContext.id,{},Ze):n},o.response_format)),r}async function PAe(t){return await sft(t).connect(new p1),0}async function kAe(t,e){let o=(await t.json("/api/connection-methods",{},Mr(zy))).items.find(n=>n.id===e);if(!o)throw new Error("Choose an available connection method.");return o}function TAe(t){return Ri(t).connections}async function CAe(t,e){let r=await kAe(t,e.methodId);if(dr(r).application==="none")throw new Error("Choose a connection method that uses an application.");let o=Ri(t),n=e.id?await o.custody.read(E.parse(e.id)):void 0,i=await o.execute({name:"app.save",input:{ownerId:e.ownerId,name:fe.parse(e.name),methodId:e.methodId,clientId:e.clientId,...e.id?{resourceId:e.id,version:n.version}:{},...e.environments?{environmentIds:e.environments}:{}}},{clientSecret:e.clientSecret,fields:m.record(m.string(),m.string()).parse(e.fields)});if(!("kind"in i)||i.kind!=="saved")throw new Error("Finish saving the application.");return i.resource}async function OAe(t,e){let r=await kAe(t,e.methodId),o=e.connectionId?await t.json("/api/resources/"+E.parse(e.connectionId),{},Sr):null,n=await Ri(t).execute({name:"connection.connect",input:{ownerId:e.ownerId,methodId:e.methodId,name:fe.parse(e.name??o?.name??r.defaultName),...e.appId?{appId:e.appId}:{},...e.connectionId?{connectionId:e.connectionId}:{},...e.redirectUri?{redirectUri:e.redirectUri}:{}}},{fields:m.record(m.string(),m.string()).parse(e.fields),scopes:m.array(m.string()).optional().parse(e.scopes),...e.aws!==void 0?{aws:Ba.parse(e.aws)}:{}});if("kind"in n&&n.kind==="saved")return n;if(!("flow"in n))throw new Error("Continue the pending connection.");return n}function FK(t){return t.kind==="saved"?{kind:"connected",id:t.executionId,connectionId:t.resource.id,resource:t.resource}:{kind:t.kind,id:t.flow.execution.id,...t.kind==="pending"?{state:"running"}:{},...t.kind==="authorize"?{authorizationUrl:t.url,next:"Open the URL, then run foundation connect wait "+t.flow.execution.id}:{},...t.kind==="cli"?{next:t.command}:{},...t.kind==="connected"?{connectionId:t.id}:{},...t.kind==="failed"?{error:t.error}:{}}}var mft=`Foundation ${_y.version}
150
150
 
151
151
  Usage: foundation <command> [options]
152
152
 
@@ -233,6 +233,6 @@ The last two values are base64url-encoded JSON; omit both for metadata-only acce
233
233
  `),p.length&&process.stderr.write(p.length+` item(s) could not be sealed again yet; signing in again retries them.
234
234
  `),uS({principal:{id:s.principal.id,name:s.principal.name},origin:t,identity:rc(),fingerprint:await Ya(u)})}async function yft(t){let e=uu(t.values.origin);if(t.values.key)return zAe(e,await m1(t.values.key));let r=fe.parse(t.values.name||f1()),o=await p$(),n;try{n=await fetch(e+"/api/auth/devices",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({name:r,publicKey:o.publicKey}),redirect:"error",signal:AbortSignal.timeout(3e4)})}catch{throw new Error("Could not reach Foundation. Check --origin and your network connection.")}if(!n.ok)throw new Error("Sign-in could not start (HTTP "+n.status+").");let i=m.object({id:E,code:m.string(),poll:m.string(),url:m.url(),expiresAt:m.string()}).parse(await n.json());process.stderr.write(`Open ${i.url}
235
235
  and enter the code ${i.code.slice(0,4)}-${i.code.slice(4)} to sign in as yourself.
236
- `);let s=new Date(i.expiresAt).getTime();for(;;){if(Date.now()>=s)throw new Error("The sign-in was not approved in time. Run foundation login again.");await VK(2e3);let a=await fetch(`${e}/api/auth/devices/${i.id}?poll=${encodeURIComponent(i.poll)}`,{redirect:"error",signal:AbortSignal.timeout(3e4)}).catch(()=>null);if(!a)continue;if(a.status===404)throw new Error("The sign-in was not approved in time. Run foundation login again.");if(a.status>=500)continue;if(!a.ok)throw new Error("Sign-in failed (HTTP "+a.status+").");let c=m.object({state:m.string(),sealed:Ao.nullable()}).parse(await a.json());if(c.state!=="approved"||!c.sealed)continue;let u=new TextDecoder().decode(await Po(c.sealed,o.privateKey,i.id,"device:"+i.id));return zAe(e,u)}}async function vft(t){let e=rc(),r=uu(t.values.origin);if(t.values.key)throw new Error("Use foundation login --key to sign in with a key.");let o=fe.parse(t.values.name||f1()),n=await m$(),i;try{i=await fetch(r+"/api/auth/enroll",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({name:o,publicKey:f$(n.encryption)}),redirect:"error",signal:AbortSignal.timeout(3e4)})}catch{throw new Error("Could not reach Foundation. Check --origin and your network connection.")}if(!i.ok)throw new Error("Registration failed (HTTP "+i.status+").");let s=m.object({principal:m.object({id:E,name:fe}),credential:j5,token:m.string()}).parse(await i.json()),a=h$(s.principal.id,n),c={origin:r,principalId:s.principal.id,token:s.token,keys:n,binding:a};await Ky(c),await new tc(c).json("/api/principals/"+s.principal.id+"/binding",{method:"PUT",body:await jy(a,n)},Ns),uS({principal:s.principal,origin:r,identity:e,fingerprint:await Ya(a)})}async function cS(t,e,r){let o=Date.now()+r*1e3;for(;;){let n=await t();if(!["pending","running","queued"].includes(e(n)))return n;if(Date.now()>=o)throw new Error("The operation is still pending. Run the wait command again to continue.");await VK(1500)}}async function wft(t,e,r){let o=fe.parse(tr(e.positionals[0],"Supply the variable name."));if(!!e.values.file==!!e.values.stdin)throw new Error("Choose exactly one of --file or --stdin.");let n=e.values.file?await qK(e.values.file):await FAe(1e6);if(n.length>1e6)throw new Error("A variable must be at most 1,000,000 bytes.");let i=null,s;do{let d=new URLSearchParams({kind:"variable",query:o,limit:"200",...i?{after:i}:{}}),p=await t.json("/api/principals/"+r+"/resources?"+d,{},Mr(br));s=p.items.find(f=>f.kind==="variable"&&f.name===o),i=p.next}while(i&&!s);let a=Ri(t),c=s?await a.custody.read(s.id):void 0,u=await a.execute({name:"variable.save",input:{ownerId:r,name:o,...s?{resourceId:s.id,version:c.version}:{},...e.values.for?{environmentIds:e.values.for.map(d=>E.parse(d))}:{}}},{value:n});if(!("kind"in u)||u.kind!=="saved")throw new Error("Finish saving the variable.");let l=u.resource;await qt(l,e)}async function MAe(t,e,r){let o=await Dn(t).custody.result(e),n=await t.json("/api/executions/"+(e.intent.operationContext?.id??e.id),{},Ze);o?.ok&&(n.results[e.intent.operationContext?.index??0]=o.result),await qt(n,r)}async function _ft(t){let e=t.indexOf("--"),r=e<0?[]:t.slice(e+1),o=e<0?t:t.slice(0,e);if(o.length===0||o.includes("--help"))return process.stdout.write(mft),0;if(o.includes("--version"))return process.stdout.write(_y.version+`
236
+ `);let s=new Date(i.expiresAt).getTime();for(;;){if(Date.now()>=s)throw new Error("The sign-in was not approved in time. Run foundation login again.");await VK(2e3);let a=await fetch(`${e}/api/auth/devices/${i.id}?poll=${encodeURIComponent(i.poll)}`,{redirect:"error",signal:AbortSignal.timeout(3e4)}).catch(()=>null);if(!a)continue;if(a.status===404)throw new Error("The sign-in was not approved in time. Run foundation login again.");if(a.status>=500)continue;if(!a.ok)throw new Error("Sign-in failed (HTTP "+a.status+").");let c=m.object({state:m.string(),sealed:Ao.nullable()}).parse(await a.json());if(c.state!=="approved"||!c.sealed)continue;let u=new TextDecoder().decode(await Po(c.sealed,o.privateKey,i.id,"device:"+i.id));return zAe(e,u)}}async function vft(t){let e=rc(),r=uu(t.values.origin);if(t.values.key)throw new Error("Use foundation login --key to sign in with a key.");let o=fe.parse(t.values.name||f1()),n=await m$(),i;try{i=await fetch(r+"/api/auth/enroll",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({name:o,publicKey:f$(n.encryption)}),redirect:"error",signal:AbortSignal.timeout(3e4)})}catch{throw new Error("Could not reach Foundation. Check --origin and your network connection.")}if(!i.ok)throw new Error("Registration failed (HTTP "+i.status+").");let s=m.object({principal:m.object({id:E,name:fe}),credential:j5,token:m.string()}).parse(await i.json()),a=h$(s.principal.id,n),c={origin:r,principalId:s.principal.id,token:s.token,keys:n,binding:a};await Ky(c),await new tc(c).json("/api/principals/"+s.principal.id+"/binding",{method:"PUT",body:await jy(a,n)},Ns),uS({principal:s.principal,origin:r,identity:e,fingerprint:await Ya(a)})}async function cS(t,e,r){let o=Date.now()+r*1e3;for(;;){let n=await t();if(!["pending","running","queued"].includes(e(n)))return n;if(Date.now()>=o)throw new Error("The operation is still pending. Run the wait command again to continue.");await VK(1500)}}async function wft(t,e,r){let o=fe.parse(tr(e.positionals[0],"Supply the variable name."));if(!!e.values.file==!!e.values.stdin)throw new Error("Choose exactly one of --file or --stdin.");let n=e.values.file?await qK(e.values.file):await FAe(1e6);if(n.length>1e6)throw new Error("A variable must be at most 1,000,000 bytes.");let i=null,s;do{let d=new URLSearchParams({kind:"variable",query:o,limit:"200",...i?{after:i}:{}}),p=await t.json("/api/principals/"+r+"/resources?"+d,{},Mr(Sr));s=p.items.find(f=>f.kind==="variable"&&f.name===o),i=p.next}while(i&&!s);let a=Ri(t),c=s?await a.custody.read(s.id):void 0,u=await a.execute({name:"variable.save",input:{ownerId:r,name:o,...s?{resourceId:s.id,version:c.version}:{},...e.values.for?{environmentIds:e.values.for.map(d=>E.parse(d))}:{}}},{value:n});if(!("kind"in u)||u.kind!=="saved")throw new Error("Finish saving the variable.");let l=u.resource;await qt(l,e)}async function MAe(t,e,r){let o=await Dn(t).custody.result(e),n=await t.json("/api/executions/"+(e.intent.operationContext?.id??e.id),{},Ze);o?.ok&&(n.results[e.intent.operationContext?.index??0]=o.result),await qt(n,r)}async function _ft(t){let e=t.indexOf("--"),r=e<0?[]:t.slice(e+1),o=e<0?t:t.slice(0,e);if(o.length===0||o.includes("--help"))return process.stdout.write(mft),0;if(o.includes("--version"))return process.stdout.write(_y.version+`
237
237
  `),0;let n=o[0],i=gft(o.slice(1));if(n==="init")return await vft(i),0;if(n==="login")return await yft(i),0;if(n==="agent"&&i.positionals[0]==="managed")return lEe();let s=new tc(await I$(i.values.origin)),a=await s.session();if(!a.principal)throw new Error("The machine identity is no longer valid.");let c=E.parse(i.values.owner??a.principal.id);if(n==="mcp")return PAe(s);if(n==="status"){let{wrappedKey:u,...l}=a;return await qt({...l,...s.identity.binding?{fingerprint:await Ya(s.identity.binding),verificationUrl:await DAe(new URL("/account/trust?principal="+a.principal.id,s.identity.origin).href,s.identity)}:{}},i),0}if(n==="trust"){let{custody:u}=Dn(s),l=E.parse(tr(i.positionals[0],"Supply an identity ID."));if(i.values.fingerprint){let d=await u.trustIdentity(l,i.values.fingerprint);await qt({identityId:l,fingerprint:d.fingerprint,trusted:!0},i)}else{let d=await u.inspectIdentity(l);await qt({identityId:l,fingerprint:d.fingerprint,next:"Verify this fingerprint with the identity holder, then repeat with --fingerprint."},i)}return 0}if(n==="agent"){if(i.positionals[0]!=="start")throw new Error("Use foundation agent start.");return UD(s,{id:i.values.id?E.parse(i.values.id):void 0,ownerId:c,name:fe.parse(i.values.name??f1()),isolation:m.enum(["process","container"]).parse(i.values.isolation??"process"),image:i.values.image,managed:i.values.managed,once:i.values.once})}if(n==="app"){let u=await CAe(s,{ownerId:c,name:tr(i.positionals[0],"Supply an application name."),id:i.values.id,methodId:tr(i.values.method,"Choose --method ID."),clientId:i.values["client-id"]??"",clientSecret:i.values["client-secret"]===void 0?void 0:await m1(i.values["client-secret"]),fields:await wn(i.values.fields,{}),environments:i.values.for});return await qt(u,i),0}if(n==="definition"){if((i.positionals[0]??"list")!=="list")throw new Error("Use foundation definition list.");return await qt(await s.json("/api/definitions",{},Mr(v$)),i),0}if(n==="execution"){let u=i.positionals[0]??"list";if(u==="list")await qt(await s.json("/api/definitions",{},Mr(v$)),i);else if(u==="history")await qt(await s.json("/api/executions",{},Mr(Ze)),i);else if(u==="get")await qt(await s.json("/api/executions/"+E.parse(tr(i.positionals[1],"Supply an execution ID.")),{},Ze),i);else if(u==="start")await qt(await s.json("/api/executions",{method:"POST",body:t8.parse(await wn(i.values.body,{}))},Ze),i);else if(u==="respond")await qt(await s.json("/api/executions/"+E.parse(tr(i.positionals[1],"Supply an execution ID."))+"/respond",{method:"POST",body:r8.parse(await wn(i.values.body,{}))},Ze),i);else if(u==="cancel")await qt(await s.json("/api/executions/"+E.parse(tr(i.positionals[1],"Supply an execution ID."))+"/cancel",{method:"POST",body:{}},Ze),i);else if(u==="share-result"){let l=await s.json("/api/executions/"+E.parse(tr(i.positionals[1],"Supply an execution ID.")),{},Ze),d=Dn(s).custody,p=[];for(let f of l.steps){let h=f.runs.at(-1);if(h?.kind!=="run")continue;let y=await s.json("/api/runtime/runs/"+h.id,{},Bn),w=await d.shareLegacyResult(y);p.push({id:y.id,readers:w.receipt&&"content"in w.receipt?w.receipt.content.policy.readers.map(b=>b.principalId):[]})}await qt({id:l.id,results:p},i)}else if(u==="run"||u==="continue"){let l=uEe.parse(await wn(i.values.fields,{})),d=u==="run"?Fi.parse({name:tr(i.positionals[1],"Supply an operation name."),input:await wn(i.values.body,{})}):null;if(d){let y=(await s.json("/api/definitions",{},Mr(v$))).items.find(w=>w.name===d.name);if(!y)throw new Error("Choose an available operation.");if(y.execution==="server")return await qt(await s.json("/api/definitions/"+d.name+"/executions",{method:"POST",body:d.input}),i),0}let p=Ri(s),f=u==="continue"?await p.continue(E.parse(tr(i.positionals[1],"Supply an execution ID.")),l):await p.execute(d,l);await qt("flow"in f?FK(f):f,i)}else throw new Error("Choose execution list, start, respond, run, get, continue, share-result, or cancel.");return 0}if(n==="connect"){if(i.values.environment||i.values.for)throw new Error("Register on this device. Select an execution environment when running a program.");let u=TAe(s),l=i.positionals[0]??"start",d;if(l==="start")d=await OAe(s,{ownerId:c,methodId:tr(i.values.method,"Choose --method ID."),name:i.values.name,appId:i.values.app,connectionId:i.values.connection,fields:await wn(i.values.fields,{}),scopes:i.values.scopes===void 0?void 0:await wn(i.values.scopes,[]),aws:i.values.aws?await wn(i.values.aws):void 0,redirectUri:i.values["redirect-uri"]});else{let p=E.parse(tr(i.positionals[1],"Supply an execution ID.")),f=await s.json("/api/executions/"+p,{},Ze);if(!f.waiting?.continuation)return await qt(f,i),f.state==="succeeded"?0:1;let h=f.waiting.continuation.id;if(l==="cancel")d=await u.cancel(h);else if(l==="complete"){let y=await m1(tr(i.values.parameters,"Supply the authorization response with --parameters."));d=await u.complete(h,y.includes("://")?new URL(y).search.slice(1):y.replace(/^\?/,""))}else if(l==="status"||l==="wait")d=await u.progress(h);else throw new Error("Choose connect start, status, wait, complete, or cancel.")}if(i.values.wait||l==="wait"){let p=Date.now()+yp(i.values.timeout,600)*1e3;for(;(d.kind==="pending"||l==="wait"&&d.kind==="authorize")&&!(Date.now()>=p);)await VK(1e3),d=await u.progress(d.flow.id)}return await qt(FK(d),i),["failed","cancelled"].includes(d.kind)?1:0}if(n==="retry"){let u=E.parse(tr(i.positionals[0],"Supply a saved execution ID."));(await s.json("/api/executions/"+u,{},Ze)).state==="failed"&&await s.json("/api/executions/"+u+"/resume",{method:"POST",body:{}},Ze);let d=await Ri(s).continue(u);return"kind"in d&&d.kind==="run"?await MAe(s,d.task,i):await qt(d,i),0}if(n==="api"||n==="schema"){let u=n==="schema"?"GET":tr(i.positionals[0],"Supply an HTTP method.").toUpperCase();if(!["GET","HEAD","POST","PUT","PATCH","DELETE"].includes(u))throw new Error("Choose GET, HEAD, POST, PUT, PATCH, or DELETE.");let l=n==="schema"?"/api/openapi.json":tr(i.positionals[1],"Supply an API path beginning with /api/.");if(i.values.body&&i.values.upload)throw new Error("Choose --body or --upload.");let d=await s.response(l,{method:u,...i.values.body?{body:await wn(i.values.body)}:{},...i.values.upload?{raw:await qK(i.values.upload)}:{}});if(i.values.output)await NAe(d,i.values.output,!!i.values.force);else if(u==="HEAD"||d.status===204)uS({status:d.status});else if(d.headers.get("content-type")?.includes("json"))uS(await d.json());else{if(!d.body)throw new Error("Foundation returned an empty response.");await jAe(LAe.fromWeb(d.body),process.stdout)}return 0}if(n==="keep")return await wft(s,i,c),0;if(n==="read"){let u=E.parse(tr(i.positionals[0],"Supply the resource ID.")),l=await Dn(s).custody.reveal(u);return i.values.output?await Nf(i.values.output,l,!!i.values.force):process.stdout.write(l),0}if(n==="exec"){let u=m.array(CL).max(32).parse(await wn(i.values.inputs,[]));return A8(await Qde(s,u),r)}if(n==="function"){let u=tr(i.positionals[0],"Choose list, show, create, update, invoke, result, cancel, or delete."),l=new Pa(s);if(u==="list")return await qt(await s.json("/api/functions?limit=100"),i),0;if(u==="create"||u==="update"){let p=m.object({name:fe,definition:ei,version:m.number().int().positive().optional()}).strict().parse(await wn(i.values.body)),f=u==="update"?E.parse(tr(i.positionals[1],"Supply a function ID.")):void 0,h=f?await l.get(f):null;return await qt(await new Pa(s,Dn(s).custody).save({ownerId:h?.ownerId??c,name:p.name,definition:p.definition,...f?{resourceId:f,version:p.version??h.version}:{}}),i),0}let d=E.parse(tr(i.positionals[1],"Supply a function or execution ID."));if(u==="show")return await qt(await l.get(d),i),0;if(u==="delete")return await l.remove(d),0;if(u==="cancel")return await qt(await l.cancel(d),i),0;if(u==="invoke"||u==="result"){let p=m.record(m.string(),fe).parse(await wn(i.values.save,{})),f=Object.keys(p).length?new Pa(s,Dn(s).custody):l,h=u==="invoke"?await f.invoke(d,Lt.parse(await wn(i.values.arguments,{})),{ownerId:c,save:p,...i.values.id?{id:E.parse(i.values.id)}:{}}):await l.result(d);return i.values.wait&&(h=await cS(()=>l.result(h.id),y=>y.state,yp(i.values.timeout,3600))),await qt(h,i),["failed","cancelled","uncertain"].includes(h.state)?1:0}throw new Error("Choose list, show, create, update, invoke, result, cancel, or delete.")}if(n==="run"){if([i.values.request,!!r.length].filter(Boolean).length!==1)throw new Error("Choose --request or a command after --.");let l=E.parse(tr(i.values.environment,"Choose an explicit execution environment with --environment ID.")),d=i.values.request?{kind:"http",request:await wn(i.values.request)}:{kind:"command",command:r,timeoutSeconds:yp(i.values.timeout,60,3600),inputs:await wn(i.values.inputs,[])},p=await Ri(s).execute({name:"run.execute",input:{ownerId:c,environmentId:l,operation:Lt.parse(d),save:m.record(m.string(),fe).parse(await wn(i.values.save,{}))}});if(!("kind"in p)||p.kind!=="run")throw new Error("Continue the pending run.");let f=p.task,h=i.values.wait?await cS(()=>s.json("/api/runtime/runs/"+f.id,{},Bn),y=>y.state,yp(i.values.timeout,3600)):f;return await MAe(s,h,i),["failed","cancelled","uncertain"].includes(h.state)?1:0}if(n==="wait"){let u=E.parse(tr(i.positionals[0],"Supply a run ID.")),l=await cS(()=>s.json("/api/executions/"+u,{},Ze),d=>d.state,yp(i.values.timeout,3600));for(let d of l.steps){let p=d.runs.filter(h=>h.kind==="run").at(-1);if(!p)continue;let f=await s.json("/api/runtime/runs/"+p.id,{},Bn);f.receipt&&(l.results[d.index]=(await Dn(s).custody.result(f))?.result??null)}return await qt(l,i),l.state==="succeeded"?0:1}if(n==="request-access"||n==="request"){if(n==="request"&&i.positionals[0]==="wait"){let d=E.parse(tr(i.positionals[1],"Supply a request ID.")),p=await cS(()=>s.json("/api/requests/"+d,{},u$),f=>f.state,yp(i.values.timeout,1800));return await qt(p,i),p.state==="accepted"?0:1}let u=n==="request-access"?{to:i.values.to,message:i.values.message??f1(),operations:[{name:"relation.draw",input:{subjectId:a.principal.id,relation:"agent",objectId:"$approver"}}]}:await wn(tr(i.values.body,"Supply the request as --body JSON.")),l=await s.json("/api/requests",{method:"POST",body:B5.parse(u)},u$);if(await qt({...l,url:await DAe(l.url,s.identity)},i),i.values.wait){let d=await cS(()=>s.json("/api/requests/"+l.id,{},u$),p=>p.state,yp(i.values.timeout,1800));return await qt(d,{...i,values:{...i.values,force:!0}}),d.state==="accepted"?0:1}return 0}if(n==="export"){let u=tr(i.values.output,"Choose an export file with --output FILE.");return await NAe(await s.response("/api/principals/"+c+"/export"),u,!!i.values.force),uS({path:UAe(u)}),0}throw new Error("Unknown command: "+n+". Run foundation --help.")}try{process.exitCode=await _ft(process.argv.slice(2))}catch(t){let e=t instanceof cu?t.code+": "+t.message:t instanceof m.ZodError?"Check the command inputs against foundation schema.":t instanceof Error?t.message:"The command failed.";process.stderr.write("foundation: "+e+`
238
238
  `),process.exitCode=1}