@sunerpy/kiro-provider 0.2.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.
- package/LICENSE +21 -0
- package/README.md +217 -0
- package/dist/cli.js +162 -0
- package/package.json +49 -0
package/dist/cli.js
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// @bun
|
|
3
|
+
var ug=Object.create;var{getPrototypeOf:lg,defineProperty:Fo,getOwnPropertyNames:_g}=Object;var wg=Object.prototype.hasOwnProperty;function Ag(t){return this[t]}var Mg,dg,H=(t,n,s)=>{var r=t!=null&&typeof t==="object";if(r){var e=n?Mg??=new WeakMap:dg??=new WeakMap,i=e.get(t);if(i)return i}s=t!=null?ug(lg(t)):{};let f=n||!t||!t.__esModule?Fo(s,"default",{value:t,enumerable:!0}):s;for(let o of _g(t))if(!wg.call(f,o))Fo(f,o,{get:Ag.bind(t,o),enumerable:!0});if(r)e.set(t,f);return f};var K=(t,n)=>()=>(n||t((n={exports:{}}).exports,n),n.exports);var gg=(t)=>t;function Eg(t,n){this[t]=gg.bind(null,n)}var Rg=(t,n)=>{for(var s in n)Fo(t,s,{get:n[s],enumerable:!0,configurable:!0,set:Eg.bind(n,s)})};var j=import.meta.require;var $u=K((G9,Su)=>{var Ds=1000,Ws=Ds*60,Ys=Ws*60,ts=Ys*24,kE=ts*7,XE=ts*365.25;Su.exports=function(t,n){n=n||{};var s=typeof t;if(s==="string"&&t.length>0)return qE(t);else if(s==="number"&&isFinite(t))return n.long?aE(t):CE(t);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function qE(t){if(t=String(t),t.length>100)return;var n=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(!n)return;var s=parseFloat(n[1]),r=(n[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return s*XE;case"weeks":case"week":case"w":return s*kE;case"days":case"day":case"d":return s*ts;case"hours":case"hour":case"hrs":case"hr":case"h":return s*Ys;case"minutes":case"minute":case"mins":case"min":case"m":return s*Ws;case"seconds":case"second":case"secs":case"sec":case"s":return s*Ds;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return s;default:return}}function CE(t){var n=Math.abs(t);if(n>=ts)return Math.round(t/ts)+"d";if(n>=Ys)return Math.round(t/Ys)+"h";if(n>=Ws)return Math.round(t/Ws)+"m";if(n>=Ds)return Math.round(t/Ds)+"s";return t+"ms"}function aE(t){var n=Math.abs(t);if(n>=ts)return Ie(t,n,ts,"day");if(n>=Ys)return Ie(t,n,Ys,"hour");if(n>=Ws)return Ie(t,n,Ws,"minute");if(n>=Ds)return Ie(t,n,Ds,"second");return t+" ms"}function Ie(t,n,s,r){var e=n>=s*1.5;return Math.round(t/s)+" "+r+(e?"s":"")}});var xo=K((B9,Uu)=>{function KE(t){s.debug=s,s.default=s,s.coerce=c,s.disable=f,s.enable=e,s.enabled=o,s.humanize=$u(),s.destroy=h,Object.keys(t).forEach((u)=>{s[u]=t[u]}),s.names=[],s.skips=[],s.formatters={};function n(u){let l=0;for(let _=0;_<u.length;_++)l=(l<<5)-l+u.charCodeAt(_),l|=0;return s.colors[Math.abs(l)%s.colors.length]}s.selectColor=n;function s(u){let l,_=null,w,A;function M(...d){if(!M.enabled)return;let E=M,b=Number(new Date),L=b-(l||b);if(E.diff=L,E.prev=l,E.curr=b,l=b,d[0]=s.coerce(d[0]),typeof d[0]!=="string")d.unshift("%O");let S=0;d[0]=d[0].replace(/%([a-zA-Z%])/g,(x,X)=>{if(x==="%%")return"%";S++;let v=s.formatters[X];if(typeof v==="function"){let Q=d[S];x=v.call(E,Q),d.splice(S,1),S--}return x}),s.formatArgs.call(E,d),(E.log||s.log).apply(E,d)}if(M.namespace=u,M.useColors=s.useColors(),M.color=s.selectColor(u),M.extend=r,M.destroy=s.destroy,Object.defineProperty(M,"enabled",{enumerable:!0,configurable:!1,get:()=>{if(_!==null)return _;if(w!==s.namespaces)w=s.namespaces,A=s.enabled(u);return A},set:(d)=>{_=d}}),typeof s.init==="function")s.init(M);return M}function r(u,l){let _=s(this.namespace+(typeof l>"u"?":":l)+u);return _.log=this.log,_}function e(u){s.save(u),s.namespaces=u,s.names=[],s.skips=[];let l=(typeof u==="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let _ of l)if(_[0]==="-")s.skips.push(_.slice(1));else s.names.push(_)}function i(u,l){let _=0,w=0,A=-1,M=0;while(_<u.length)if(w<l.length&&(l[w]===u[_]||l[w]==="*"))if(l[w]==="*")A=w,M=_,w++;else _++,w++;else if(A!==-1)w=A+1,M++,_=M;else return!1;while(w<l.length&&l[w]==="*")w++;return w===l.length}function f(){let u=[...s.names,...s.skips.map((l)=>"-"+l)].join(",");return s.enable(""),u}function o(u){for(let l of s.skips)if(i(u,l))return!1;for(let l of s.names)if(i(u,l))return!0;return!1}function c(u){if(u instanceof Error)return u.stack||u.message;return u}function h(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return s.enable(s.load()),s}Uu.exports=KE});var Iu=K((Lu,Oe)=>{Lu.formatArgs=jE;Lu.save=pE;Lu.load=vE;Lu.useColors=VE;Lu.storage=ZE();Lu.destroy=(()=>{let t=!1;return()=>{if(!t)t=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}})();Lu.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function VE(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let t;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(t=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(t[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function jE(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+Oe.exports.humanize(this.diff),!this.useColors)return;let n="color: "+this.color;t.splice(1,0,n,"color: inherit");let s=0,r=0;t[0].replace(/%[a-zA-Z%]/g,(e)=>{if(e==="%%")return;if(s++,e==="%c")r=s}),t.splice(r,0,n)}Lu.log=console.debug||console.log||(()=>{});function pE(t){try{if(t)Lu.storage.setItem("debug",t);else Lu.storage.removeItem("debug")}catch(n){}}function vE(){let t;try{t=Lu.storage.getItem("debug")||Lu.storage.getItem("DEBUG")}catch(n){}if(!t&&typeof process<"u"&&"env"in process)t=process.env.DEBUG;return t}function ZE(){try{return localStorage}catch(t){}}Oe.exports=xo()(Lu);var{formatters:tR}=Oe.exports;tR.j=function(t){try{return JSON.stringify(t)}catch(n){return"[UnexpectedJSONParseError]: "+n.message}}});var Bu=K((yu,Ge)=>{var cR=j("tty"),ye=j("util");yu.init=MR;yu.log=_R;yu.formatArgs=uR;yu.save=wR;yu.load=AR;yu.useColors=hR;yu.destroy=ye.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");yu.colors=[6,2,3,4,5,1];try{let t=(()=>{throw new Error("Cannot require module "+"supports-color");})();if(t&&(t.stderr||t).level>=2)yu.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]}catch(t){}yu.inspectOpts=Object.keys(process.env).filter((t)=>{return/^debug_/i.test(t)}).reduce((t,n)=>{let s=n.substring(6).toLowerCase().replace(/_([a-z])/g,(e,i)=>{return i.toUpperCase()}),r=process.env[n];if(/^(yes|on|true|enabled)$/i.test(r))r=!0;else if(/^(no|off|false|disabled)$/i.test(r))r=!1;else if(r==="null")r=null;else r=Number(r);return t[s]=r,t},{});function hR(){return"colors"in yu.inspectOpts?Boolean(yu.inspectOpts.colors):cR.isatty(process.stderr.fd)}function uR(t){let{namespace:n,useColors:s}=this;if(s){let r=this.color,e="\x1B[3"+(r<8?r:"8;5;"+r),i=` ${e};1m${n} \x1B[0m`;t[0]=i+t[0].split(`
|
|
4
|
+
`).join(`
|
|
5
|
+
`+i),t.push(e+"m+"+Ge.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=lR()+n+" "+t[0]}function lR(){if(yu.inspectOpts.hideDate)return"";return new Date().toISOString()+" "}function _R(...t){return process.stderr.write(ye.formatWithOptions(yu.inspectOpts,...t)+`
|
|
6
|
+
`)}function wR(t){if(t)process.env.DEBUG=t;else delete process.env.DEBUG}function AR(){return process.env.DEBUG}function MR(t){t.inspectOpts={};let n=Object.keys(yu.inspectOpts);for(let s=0;s<n.length;s++)t.inspectOpts[n[s]]=yu.inspectOpts[n[s]]}Ge.exports=xo()(yu);var{formatters:Ou}=Ge.exports;Ou.o=function(t){return this.inspectOpts.colors=this.useColors,ye.inspect(t,this.inspectOpts).split(`
|
|
7
|
+
`).map((n)=>n.trim()).join(" ")};Ou.O=function(t){return this.inspectOpts.colors=this.useColors,ye.inspect(t,this.inspectOpts)}});var Jo=K((P9,Qo)=>{if(typeof process>"u"||process.type==="renderer"||!1||process.__nwjs)Qo.exports=Iu();else Qo.exports=Bu()});var es=K((zR)=>{var po;(function(t){t.HEADER="header",t.QUERY="query"})(po||(po={}));var vo;(function(t){t.HEADER="header",t.QUERY="query"})(vo||(vo={}));var Zo;(function(t){t.HTTP="http",t.HTTPS="https"})(Zo||(Zo={}));var yr;(function(t){t.MD5="md5",t.CRC32="crc32",t.CRC32C="crc32c",t.SHA1="sha1",t.SHA256="sha256"})(yr||(yr={}));var WR=(t)=>{let n=[];if(t.sha256!==void 0)n.push({algorithmId:()=>yr.SHA256,checksumConstructor:()=>t.sha256});if(t.md5!=null)n.push({algorithmId:()=>yr.MD5,checksumConstructor:()=>t.md5});return{addChecksumAlgorithm(s){n.push(s)},checksumAlgorithms(){return n}}},YR=(t)=>{let n={};return t.checksumAlgorithms().forEach((s)=>{n[s.algorithmId()]=s.checksumConstructor()}),n},xR=(t)=>{return WR(t)},QR=(t)=>{return YR(t)},tf;(function(t){t[t.HEADER=0]="HEADER",t[t.TRAILER=1]="TRAILER"})(tf||(tf={}));var JR="__smithy_context",nf;(function(t){t.PROFILE="profile",t.SSO_SESSION="sso-session",t.SERVICES="services"})(nf||(nf={}));var sf;(function(t){t.HTTP_0_9="http/0.9",t.HTTP_1_0="http/1.0",t.TDS_8_0="tds/8.0"})(sf||(sf={}));zR.AlgorithmId=yr;zR.EndpointURLScheme=Zo;zR.FieldPosition=tf;zR.HttpApiKeyAuthLocation=vo;zR.HttpAuthLocation=po;zR.IniSectionType=nf;zR.RequestHandlerProtocol=sf;zR.SMITHY_CONTEXT_KEY=JR;zR.getDefaultClientConfiguration=xR;zR.resolveDefaultRuntimeConfig=QR});var tn=K((ib)=>{var{SMITHY_CONTEXT_KEY:Ku}=es(),ZR=(t)=>t[Ku]||(t[Ku]={});class De{method;protocol;hostname;port;path;query;headers;username;password;fragment;body;constructor(t){this.method=t.method||"GET",this.hostname=t.hostname||"localhost",this.port=t.port,this.query=t.query||{},this.headers=t.headers||{},this.body=t.body,this.protocol=t.protocol?t.protocol.slice(-1)!==":"?`${t.protocol}:`:t.protocol:"https:",this.path=t.path?t.path.charAt(0)!=="/"?`/${t.path}`:t.path:"/",this.username=t.username,this.password=t.password,this.fragment=t.fragment}static clone(t){let n=new De({...t,headers:{...t.headers}});if(n.query)n.query=tb(n.query);return n}static isInstance(t){if(!t)return!1;let n=t;return"method"in n&&"protocol"in n&&"hostname"in n&&"path"in n&&typeof n.query==="object"&&typeof n.headers==="object"}clone(){return De.clone(this)}}function tb(t){return Object.keys(t).reduce((n,s)=>{let r=t[s];return{...n,[s]:Array.isArray(r)?[...r]:r}},{})}class Vu{statusCode;reason;headers;body;constructor(t){this.statusCode=t.statusCode,this.reason=t.reason,this.headers=t.headers||{},this.body=t.body}static isInstance(t){if(!t)return!1;let n=t;return typeof n.statusCode==="number"&&typeof n.headers==="object"}}var nb=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),ju=(t,n=!1)=>{if(!n)return nb.test(t);let s=t.split(".");for(let r of s)if(!ju(r))return!1;return!0};function sb(t){return/^[a-z0-9][a-z0-9.-]*[a-z0-9]$/.test(t)}var rb=(t)=>{if(typeof t==="function")return t;let n=Promise.resolve(t);return()=>n};function pu(t){let n={};if(t=t.replace(/^\?/,""),t)for(let s of t.split("&")){let[r,e=null]=s.split("=");if(r=decodeURIComponent(r),e)e=decodeURIComponent(e);if(!(r in n))n[r]=e;else if(Array.isArray(n[r]))n[r].push(e);else n[r]=[n[r],e]}return n}var We=(t)=>{if(typeof t==="string")return We(new URL(t));let{hostname:n,pathname:s,port:r,protocol:e,search:i}=t,f;if(i)f=pu(i);return{hostname:n,port:r?parseInt(r):void 0,protocol:e,path:s,query:f}},eb=(t)=>{if(typeof t==="object"){if("url"in t){let n=We(t.url);if(t.headers){n.headers={};for(let s in t.headers)n.headers[s.toLowerCase()]=t.headers[s].join(", ")}return n}return t}return We(t)};ib.HttpRequest=De;ib.HttpResponse=Vu;ib.getSmithyContext=ZR;ib.isValidHostLabel=ju;ib.isValidHostname=sb;ib.normalizeProvider=rb;ib.parseQueryString=pu;ib.parseUrl=We;ib.toEndpointV1=eb});var Pn=K((yb)=>{var{getSmithyContext:vu,HttpResponse:Mb,toEndpointV1:db}=tn(),Ye=(t)=>{if(typeof t==="function")return t();return t},of=(t,n,s,r,e)=>({name:n,namespace:t,traits:s,input:r,output:e}),gb=(t)=>(n,s)=>async(r)=>{let{response:e}=await n(r),{operationSchema:i}=vu(s),[,f,o,c,h,u]=i??[];try{let l=await t.protocol.deserializeResponse(of(f,o,c,h,u),{...t,...s},e);return{response:e,output:l}}catch(l){if(Object.defineProperty(l,"$response",{value:e,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in l)){try{l.message+=`
|
|
8
|
+
Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`}catch(w){if(!s.logger||s.logger?.constructor?.name==="NoOpLogger")console.warn("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.");else s.logger?.warn?.("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.")}if(typeof l.$responseBodyText<"u"){if(l.$response)l.$response.body=l.$responseBodyText}try{if(Mb.isInstance(e)){let{headers:w={},statusCode:A}=e,M=Object.entries(w);l.$metadata={httpStatusCode:A,requestId:rf(/^x-[\w-]+-request-?id$/,M),extendedRequestId:rf(/^x-[\w-]+-id-2$/,M),cfId:rf(/^x-[\w-]+-cf-id$/,M)}}}catch(w){}}throw l}},rf=(t,n)=>{return(n.find(([s])=>{return s.match(t)})||[void 0,void 0])[1]},Eb=(t)=>(n,s)=>async(r)=>{let{operationSchema:e}=vu(s),[,i,f,o,c,h]=e??[],u=s.endpointV2?async()=>db(s.endpointV2):t.endpoint,l=await t.protocol.serializeRequest(of(i,f,o,c,h),r.input,{...t,...s,endpoint:u});return n({...r,request:l})},Zu={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},tl={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function Rb(t){return{applyToStack:(n)=>{n.add(Eb(t),tl),n.add(gb(t),Zu),t.protocol.setSerdeContext(t)}}}class Et{name;namespace;traits;static assign(t,n){return Object.assign(t,n)}static[Symbol.hasInstance](t){let n=this.prototype.isPrototypeOf(t);if(!n&&typeof t==="object"&&t!==null)return t.symbol===this.symbol;return n}getName(){return this.namespace+"#"+this.name}}class ze extends Et{static symbol=Symbol.for("@smithy/lis");name;traits;valueSchema;symbol=ze.symbol}var bb=(t,n,s,r)=>Et.assign(new ze,{name:n,namespace:t,traits:s,valueSchema:r});class ke extends Et{static symbol=Symbol.for("@smithy/map");name;traits;keySchema;valueSchema;symbol=ke.symbol}var Tb=(t,n,s,r,e)=>Et.assign(new ke,{name:n,namespace:t,traits:s,keySchema:r,valueSchema:e});class Xe extends Et{static symbol=Symbol.for("@smithy/ope");name;traits;input;output;symbol=Xe.symbol}var Sb=(t,n,s,r,e)=>Et.assign(new Xe,{name:n,namespace:t,traits:s,input:r,output:e});class Fr extends Et{static symbol=Symbol.for("@smithy/str");name;traits;memberNames;memberList;symbol=Fr.symbol}var $b=(t,n,s,r,e)=>Et.assign(new Fr,{name:n,namespace:t,traits:s,memberNames:r,memberList:e});class qe extends Fr{static symbol=Symbol.for("@smithy/err");ctor;symbol=qe.symbol}var Ub=(t,n,s,r,e,i)=>Et.assign(new qe,{name:n,namespace:t,traits:s,memberNames:r,memberList:e,ctor:null}),xe=[];function mr(t){if(typeof t==="object")return t;if(t=t|0,xe[t])return xe[t];let n={},s=0;for(let r of["httpLabel","idempotent","idempotencyToken","sensitive","httpPayload","httpResponseCode","httpQueryParams"])if((t>>s++&1)===1)n[r]=1;return xe[t]=n}var Gr={it:Symbol.for("@smithy/nor-struct-it"),ns:Symbol.for("@smithy/ns")},Qe=[],Je={};class gn{ref;memberName;static symbol=Symbol.for("@smithy/nor");symbol=gn.symbol;name;schema;_isMemberSchema;traits;memberTraits;normalizedTraits;constructor(t,n){this.ref=t,this.memberName=n;let s=[],r=t,e=t;this._isMemberSchema=!1;while(ef(r))s.push(r[1]),r=r[0],e=Ye(r),this._isMemberSchema=!0;if(s.length>0){this.memberTraits={};for(let i=s.length-1;i>=0;--i){let f=s[i];Object.assign(this.memberTraits,mr(f))}}else this.memberTraits=0;if(e instanceof gn){let i=this.memberTraits;Object.assign(this,e),this.memberTraits=Object.assign({},i,e.getMemberTraits(),this.getMemberTraits()),this.normalizedTraits=void 0,this.memberName=n??e.memberName;return}if(this.schema=Ye(e),nl(this.schema))this.name=`${this.schema[1]}#${this.schema[2]}`,this.traits=this.schema[3];else this.name=this.memberName??String(e),this.traits=0;if(this._isMemberSchema&&!n)throw Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(!0)} missing member name.`)}static[Symbol.hasInstance](t){let n=this.prototype.isPrototypeOf(t);if(!n&&typeof t==="object"&&t!==null)return t.symbol===this.symbol;return n}static of(t){let n=typeof t==="function"||typeof t==="object"&&t!==null;if(typeof t==="number"){if(Qe[t])return Qe[t]}else if(typeof t==="string"){if(Je[t])return Je[t]}else if(n){if(t[Gr.ns])return t[Gr.ns]}let s=Ye(t);if(s instanceof gn)return s;if(ef(s)){let[e,i]=s;if(e instanceof gn)return Object.assign(e.getMergedTraits(),mr(i)),e;throw Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(t,null,2)}.`)}let r=new gn(s);if(n)return t[Gr.ns]=r;if(typeof s==="string")return Je[s]=r;if(typeof s==="number")return Qe[s]=r;return r}getSchema(){let t=this.schema;if(Array.isArray(t)&&t[0]===0)return t[4];return t}getName(t=!1){let{name:n}=this;return!t&&n&&n.includes("#")?n.split("#")[1]:n||void 0}getMemberName(){return this.memberName}isMemberSchema(){return this._isMemberSchema}isListSchema(){let t=this.getSchema();return typeof t==="number"?t>=64&&t<128:t[0]===1}isMapSchema(){let t=this.getSchema();return typeof t==="number"?t>=128&&t<=255:t[0]===2}isStructSchema(){let t=this.getSchema();if(typeof t!=="object")return!1;let n=t[0];return n===3||n===-3||n===4}isUnionSchema(){let t=this.getSchema();if(typeof t!=="object")return!1;return t[0]===4}isBlobSchema(){let t=this.getSchema();return t===21||t===42}isTimestampSchema(){let t=this.getSchema();return typeof t==="number"&&t>=4&&t<=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:t}=this.getMergedTraits();return!!t||this.getSchema()===42}isIdempotencyToken(){return!!this.getMergedTraits().idempotencyToken}getMergedTraits(){return this.normalizedTraits??(this.normalizedTraits={...this.getOwnTraits(),...this.getMemberTraits()})}getMemberTraits(){return mr(this.memberTraits)}getOwnTraits(){return mr(this.traits)}getKeySchema(){let[t,n]=[this.isDocumentSchema(),this.isMapSchema()];if(!t&&!n)throw Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(!0)}`);let s=this.getSchema(),r=t?15:s[4]??0;return Br([r,0],"key")}getValueSchema(){let t=this.getSchema(),[n,s,r]=[this.isDocumentSchema(),this.isMapSchema(),this.isListSchema()],e=typeof t==="number"?63&t:t&&typeof t==="object"&&(s||r)?t[3+t[0]]:n?15:void 0;if(e!=null)return Br([e,0],s?"value":"member");throw Error(`@smithy/core/schema - ${this.getName(!0)} has no value member.`)}getMemberSchema(t){let n=this.getSchema();if(this.isStructSchema()&&n[4].includes(t)){let s=n[4].indexOf(t),r=n[5][s];return Br(ef(r)?r:[r,0],t)}if(this.isDocumentSchema())return Br([15,0],t);throw Error(`@smithy/core/schema - ${this.getName(!0)} has no member=${t}.`)}getMemberSchemas(){let t={};try{for(let[n,s]of this.structIterator())t[n]=s}catch(n){}return t}getEventStreamMember(){if(this.isStructSchema()){for(let[t,n]of this.structIterator())if(n.isStreaming()&&n.isStructSchema())return t}return""}*structIterator(){if(this.isUnitSchema())return;if(!this.isStructSchema())throw Error("@smithy/core/schema - cannot iterate non-struct schema.");let t=this.getSchema(),n=t[4].length,s=t[Gr.it];if(s&&n===s.length){yield*s;return}s=Array(n);for(let r=0;r<n;++r){let e=t[4][r],i=Br([t[5][r],0],e);yield s[r]=[e,i]}t[Gr.it]=s}}function Br(t,n){if(t instanceof gn)return Object.assign(t,{memberName:n,_isMemberSchema:!0});return new gn(t,n)}var ef=(t)=>Array.isArray(t)&&t.length===2,nl=(t)=>Array.isArray(t)&&t.length>=5;class Pr extends Et{static symbol=Symbol.for("@smithy/sim");name;schemaRef;traits;symbol=Pr.symbol}var Lb=(t,n,s,r)=>Et.assign(new Pr,{name:n,namespace:t,traits:r,schemaRef:s}),Ib=(t,n,s,r)=>Et.assign(new Pr,{name:n,namespace:t,traits:s,schemaRef:r}),Ob={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};class dn{namespace;schemas;exceptions;static registries=new Map;constructor(t,n=new Map,s=new Map){this.namespace=t,this.schemas=n,this.exceptions=s}static for(t){if(!dn.registries.has(t))dn.registries.set(t,new dn(t));return dn.registries.get(t)}copyFrom(t){let{schemas:n,exceptions:s}=this;for(let[r,e]of t.schemas)if(!n.has(r))n.set(r,e);for(let[r,e]of t.exceptions)if(!s.has(r))s.set(r,e)}register(t,n){let s=this.normalizeShapeId(t);for(let r of[this,dn.for(s.split("#")[0])])r.schemas.set(s,n)}getSchema(t){let n=this.normalizeShapeId(t);if(!this.schemas.has(n)){if(!t.includes("#")){let s="#"+t,r=[];for(let[e,i]of this.schemas.entries())if(e.endsWith(s))r.push(i);if(r.length===1)return r[0]}throw Error(`@smithy/core/schema - schema not found for ${n}`)}return this.schemas.get(n)}registerError(t,n){let s=t,r=s[1];for(let e of[this,dn.for(r)])e.schemas.set(r+"#"+s[2],s),e.exceptions.set(s,n)}getErrorCtor(t){let n=t;if(this.exceptions.has(n))return this.exceptions.get(n);return dn.for(n[1]).exceptions.get(n)}getBaseException(){for(let t of this.exceptions.keys())if(Array.isArray(t)){let[,n,s]=t,r=n+"#"+s;if(r.startsWith("smithy.ts.sdk.synthetic.")&&r.endsWith("ServiceException"))return t}return}find(t){for(let n of this.schemas.values())if(t(n))return n;return}clear(){this.schemas.clear(),this.exceptions.clear()}normalizeShapeId(t){if(t.includes("#"))return t;return this.namespace+"#"+t}}yb.ErrorSchema=qe;yb.ListSchema=ze;yb.MapSchema=ke;yb.NormalizedSchema=gn;yb.OperationSchema=Xe;yb.SCHEMA=Ob;yb.Schema=Et;yb.SimpleSchema=Pr;yb.StructureSchema=Fr;yb.TypeRegistry=dn;yb.deref=Ye;yb.deserializerMiddlewareOption=Zu;yb.error=Ub;yb.getSchemaSerdePlugin=Rb;yb.isStaticSchema=nl;yb.list=bb;yb.map=Tb;yb.op=Sb;yb.operation=of;yb.serializerMiddlewareOption=tl;yb.sim=Lb;yb.simAdapter=Ib;yb.simpleSchemaCacheN=Qe;yb.simpleSchemaCacheS=Je;yb.struct=$b;yb.traitsCache=xe;yb.translateTraits=mr});var En=K((N4)=>{var{getSmithyContext:s4,normalizeProvider:r4}=tn();N4.getSmithyContext=s4;N4.normalizeProvider=r4;var{SMITHY_CONTEXT_KEY:e4,AlgorithmId:ae}=es();N4.AlgorithmId=ae;var{NormalizedSchema:i4}=Pn(),is=(t,n)=>{let s=[];if(t)s.push(t);if(n)for(let r of n)s.push(r);return s},Hn=(t,n)=>{return`${t||"anonymous"}${n&&n.length>0?` (a.k.a. ${n.join(",")})`:""}`},Hr=()=>{let t=[],n=[],s=!1,r=new Set,e=(l)=>l.sort((_,w)=>sl[w.step]-sl[_.step]||rl[w.priority||"normal"]-rl[_.priority||"normal"]),i=(l)=>{let _=!1,w=(A)=>{let M=is(A.name,A.aliases);if(M.includes(l)){_=!0;for(let d of M)r.delete(d);return!1}return!0};return t=t.filter(w),n=n.filter(w),_},f=(l)=>{let _=!1,w=(A)=>{if(A.middleware===l){_=!0;for(let M of is(A.name,A.aliases))r.delete(M);return!1}return!0};return t=t.filter(w),n=n.filter(w),_},o=(l)=>{return t.forEach((_)=>{l.add(_.middleware,{..._})}),n.forEach((_)=>{l.addRelativeTo(_.middleware,{..._})}),l.identifyOnResolve?.(u.identifyOnResolve()),l},c=(l)=>{let _=[];return l.before.forEach((w)=>{if(w.before.length===0&&w.after.length===0)_.push(w);else _.push(...c(w))}),_.push(l),l.after.reverse().forEach((w)=>{if(w.before.length===0&&w.after.length===0)_.push(w);else _.push(...c(w))}),_},h=(l=!1)=>{let _=[],w=[],A={};return t.forEach((d)=>{let E={...d,before:[],after:[]};for(let b of is(E.name,E.aliases))A[b]=E;_.push(E)}),n.forEach((d)=>{let E={...d,before:[],after:[]};for(let b of is(E.name,E.aliases))A[b]=E;w.push(E)}),w.forEach((d)=>{if(d.toMiddleware){let E=A[d.toMiddleware];if(E===void 0){if(l)return;throw Error(`${d.toMiddleware} is not found when adding ${Hn(d.name,d.aliases)} middleware ${d.relation} ${d.toMiddleware}`)}if(d.relation==="after")E.after.push(d);if(d.relation==="before")E.before.push(d)}}),e(_).map(c).reduce((d,E)=>{return d.push(...E),d},[])},u={add:(l,_={})=>{let{name:w,override:A,aliases:M}=_,d={step:"initialize",priority:"normal",middleware:l,..._},E=is(w,M);if(E.length>0){if(E.some((b)=>r.has(b))){if(!A)throw Error(`Duplicate middleware name '${Hn(w,M)}'`);for(let b of E){let L=t.findIndex((O)=>O.name===b||O.aliases?.some((x)=>x===b));if(L===-1)continue;let S=t[L];if(S.step!==d.step||d.priority!==S.priority)throw Error(`"${Hn(S.name,S.aliases)}" middleware with ${S.priority} priority in ${S.step} step cannot be overridden by "${Hn(w,M)}" middleware with ${d.priority} priority in ${d.step} step.`);t.splice(L,1)}}for(let b of E)r.add(b)}t.push(d)},addRelativeTo:(l,_)=>{let{name:w,override:A,aliases:M}=_,d={middleware:l,..._},E=is(w,M);if(E.length>0){if(E.some((b)=>r.has(b))){if(!A)throw Error(`Duplicate middleware name '${Hn(w,M)}'`);for(let b of E){let L=n.findIndex((O)=>O.name===b||O.aliases?.some((x)=>x===b));if(L===-1)continue;let S=n[L];if(S.toMiddleware!==d.toMiddleware||S.relation!==d.relation)throw Error(`"${Hn(S.name,S.aliases)}" middleware ${S.relation} "${S.toMiddleware}" middleware cannot be overridden by "${Hn(w,M)}" middleware ${d.relation} "${d.toMiddleware}" middleware.`);n.splice(L,1)}}for(let b of E)r.add(b)}n.push(d)},clone:()=>o(Hr()),use:(l)=>{l.applyToStack(u)},remove:(l)=>{if(typeof l==="string")return i(l);else return f(l)},removeByTag:(l)=>{let _=!1,w=(A)=>{let{tags:M,name:d,aliases:E}=A;if(M&&M.includes(l)){let b=is(d,E);for(let L of b)r.delete(L);return _=!0,!1}return!0};return t=t.filter(w),n=n.filter(w),_},concat:(l)=>{let _=o(Hr());return _.use(l),_.identifyOnResolve(s||_.identifyOnResolve()||(l.identifyOnResolve?.()??!1)),_},applyToStack:o,identify:()=>{return h(!0).map((l)=>{let _=l.step??l.relation+" "+l.toMiddleware;return Hn(l.name,l.aliases)+" - "+_})},identifyOnResolve(l){if(typeof l==="boolean")s=l;return s},resolve:(l,_)=>{for(let w of h().map((A)=>A.middleware).reverse())l=w(l,_);if(s)console.log(u.identify());return l}};return u},sl={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},rl={high:3,normal:2,low:1},o4=(t)=>()=>{throw Error(t)},f4=(t)=>()=>Promise.reject(t),Ce=()=>{let t=new WeakSet;return(n,s)=>{if(typeof s==="object"&&s!==null){if(t.has(s))return"[Circular]";t.add(s)}return s}},c4=(t)=>{return new Promise((n)=>setTimeout(n,t*1000))},ol={minDelay:2,maxDelay:120},nn;(function(t){t.ABORTED="ABORTED",t.FAILURE="FAILURE",t.SUCCESS="SUCCESS",t.RETRY="RETRY",t.TIMEOUT="TIMEOUT"})(nn||(nn={}));var h4=(t)=>{if(t.state===nn.ABORTED){let n=Error(`${JSON.stringify({...t,reason:"Request was aborted"},Ce())}`);throw n.name="AbortError",n}else if(t.state===nn.TIMEOUT){let n=Error(`${JSON.stringify({...t,reason:"Waiter has timed out"},Ce())}`);throw n.name="TimeoutError",n}else if(t.state!==nn.SUCCESS)throw Error(`${JSON.stringify(t,Ce())}`);return t},u4=async({minDelay:t,maxDelay:n,maxWaitTime:s,abortController:r,client:e,abortSignal:i},f,o)=>{let c={},[h,u]=[t*1000,n*1000],l=0,_=Date.now()+s*1000,w=Date.now()+60000,A=!1;while(!0){if(l>0){let E=w4(h,u,l,_);if(r?.signal?.aborted||i?.aborted)return c["AbortController signal aborted."]|=0,c["AbortController signal aborted."]+=1,{state:nn.ABORTED,observedResponses:c};if(Date.now()+E>_)return{state:nn.TIMEOUT,observedResponses:c};await c4(E/1000)}let{state:M,reason:d}=await o(e,f);if(d){let E=_4(d);c[E]|=0,c[E]+=1}if(M!==nn.RETRY)return{state:M,reason:d,final:d,observedResponses:c};if(l+=1,!A&&Date.now()>=w)l4(c,e),A=!0}},l4=(t={},n)=>{let s=Object.keys(t),r=0;for(let f of s){let o=t[f]|0;if(f.startsWith("403:"))r+=o}let e=n?.config?.logger,i=typeof e?.warn==="function"&&!e.constructor?.name?.includes?.("NoOpLogger")?e:console;if(r>=3||s[s.length-1]?.startsWith("403:"))i.warn("@smithy/util-waiter WARN - 403 status code encountered during waiter polling.")},_4=(t)=>{let n=t?.$response?.statusCode??t?.$metadata?.httpStatusCode;if(t?.$responseBodyText)return`${n?n+": ":""}Deserialization error for body: ${t.$responseBodyText}`;if(n){if(t?.$response||t?.message)return`${n??"Unknown"}: ${t?.message}`;return`${n}: OK`}return String(t?.message??JSON.stringify(t,Ce())??"Unknown")},w4=(t,n,s,r)=>{let e=Math.log(n/t)/Math.log(2)+1;if(s>e)return n;let i=t*2**(s-1),f=Math.min(i,n),o=A4(t,f);if(Date.now()+o>r){let c=r-Date.now();return Math.max(0,c-500)}return o},A4=(t,n)=>t+Math.random()*(n-t),M4=(t)=>{if(t.maxWaitTime<=0)throw Error("WaiterConfiguration.maxWaitTime must be greater than 0");else if(t.minDelay<=0)throw Error("WaiterConfiguration.minDelay must be greater than 0");else if(t.maxDelay<=0)throw Error("WaiterConfiguration.maxDelay must be greater than 0");else if(t.maxWaitTime<=t.minDelay)throw Error(`WaiterConfiguration.maxWaitTime [${t.maxWaitTime}] must be greater than WaiterConfiguration.minDelay [${t.minDelay}] for this waiter`);else if(t.maxDelay<t.minDelay)throw Error(`WaiterConfiguration.maxDelay [${t.maxDelay}] must be greater than WaiterConfiguration.minDelay [${t.minDelay}] for this waiter`)},el=(t)=>{let n,s=new Promise((r)=>{if(n=()=>r({state:nn.ABORTED}),typeof t.addEventListener==="function")t.addEventListener("abort",n);else t.onabort=n});return{clearListener(){if(typeof t.removeEventListener==="function")t.removeEventListener("abort",n)},aborted:s}},d4=async(t,n,s)=>{let r={...ol,...t};M4(r);let e=[u4(r,n,s)],i=[];if(t.abortSignal){let{aborted:f,clearListener:o}=el(t.abortSignal);i.push(o),e.push(f)}if(t.abortController?.signal){let{aborted:f,clearListener:o}=el(t.abortController.signal);i.push(o),e.push(f)}return Promise.race(e).then((f)=>{for(let o of i)o();return f})};class fl{config;middlewareStack=Hr();initConfig;handlers;constructor(t){this.config=t;let{protocol:n,protocolSettings:s}=t;if(s){if(typeof n==="function")t.protocol=new n(s)}}send(t,n,s){let r=typeof n!=="function"?n:void 0,e=typeof n==="function"?n:s,i=r===void 0&&this.config.cacheMiddleware===!0,f;if(i){if(!this.handlers)this.handlers=new WeakMap;let o=this.handlers;if(o.has(t.constructor))f=o.get(t.constructor);else f=t.resolveMiddleware(this.middlewareStack,this.config,r),o.set(t.constructor,f)}else delete this.handlers,f=t.resolveMiddleware(this.middlewareStack,this.config,r);if(e)f(t).then((o)=>e(null,o.output),(o)=>e(o)).catch(()=>{});else return f(t).then((o)=>o.output)}destroy(){this.config?.requestHandler?.destroy?.(),delete this.handlers}}var ff="***SensitiveInformation***";function Ke(t,n){if(n==null)return n;let s=i4.of(t);if(s.getMergedTraits().sensitive)return ff;if(s.isListSchema()){if(!!s.getValueSchema().getMergedTraits().sensitive)return ff}else if(s.isMapSchema()){if(!!s.getKeySchema().getMergedTraits().sensitive||!!s.getValueSchema().getMergedTraits().sensitive)return ff}else if(s.isStructSchema()&&typeof n==="object"){let r=n,e={};for(let[i,f]of s.structIterator())if(r[i]!=null)e[i]=Ke(f,r[i]);return e}return n}class Ve{middlewareStack=Hr();schema;static classBuilder(){return new cl}resolveMiddlewareWithContext(t,n,s,{middlewareFn:r,clientName:e,commandName:i,inputFilterSensitiveLog:f,outputFilterSensitiveLog:o,smithyContext:c,additionalContext:h,CommandCtor:u}){for(let d of r.bind(this)(u,t,n,s))this.middlewareStack.use(d);let l=t.concat(this.middlewareStack),{logger:_}=n,w={logger:_,clientName:e,commandName:i,inputFilterSensitiveLog:f,outputFilterSensitiveLog:o,[e4]:{commandInstance:this,...c},...h},{requestHandler:A}=n,M=s??{};if(c.eventStream)M={isEventStream:!0,...M};return l.resolve((d)=>A.handle(d.request,M),w)}}class cl{_init=()=>{};_ep={};_middlewareFn=()=>[];_commandName="";_clientName="";_additionalContext={};_smithyContext={};_inputFilterSensitiveLog=void 0;_outputFilterSensitiveLog=void 0;_serializer=null;_deserializer=null;_operationSchema;init(t){this._init=t}ep(t){return this._ep=t,this}m(t){return this._middlewareFn=t,this}s(t,n,s={}){return this._smithyContext={service:t,operation:n,...s},this}c(t={}){return this._additionalContext=t,this}n(t,n){return this._clientName=t,this._commandName=n,this}f(t=(s)=>s,n=(s)=>s){return this._inputFilterSensitiveLog=t,this._outputFilterSensitiveLog=n,this}ser(t){return this._serializer=t,this}de(t){return this._deserializer=t,this}sc(t){return this._operationSchema=t,this._smithyContext.operationSchema=t,this}build(){let t=this,n;return n=class extends Ve{input;static getEndpointParameterInstructions(){return t._ep}constructor(...[s]){super();this.input=s??{},t._init(this),this.schema=t._operationSchema}resolveMiddleware(s,r,e){let i=t._operationSchema,f=i?.[4]??i?.input,o=i?.[5]??i?.output;return this.resolveMiddlewareWithContext(s,r,e,{CommandCtor:n,middlewareFn:t._middlewareFn,clientName:t._clientName,commandName:t._commandName,inputFilterSensitiveLog:t._inputFilterSensitiveLog??(i?Ke.bind(null,f):(c)=>c),outputFilterSensitiveLog:t._outputFilterSensitiveLog??(i?Ke.bind(null,o):(c)=>c),smithyContext:t._smithyContext,additionalContext:t._additionalContext})}serialize=t._serializer;deserialize=t._deserializer}}}var g4="***SensitiveInformation***",E4=(t,n,s)=>{for(let[i,f]of Object.entries(t)){let o=async function(h,u,l){let _=new f(h);if(typeof u==="function")this.send(_,u);else if(typeof l==="function"){if(typeof u!=="object")throw Error(`Expected http options but got ${typeof u}`);this.send(_,u||{},l)}else return this.send(_,u)},c=(i[0].toLowerCase()+i.slice(1)).replace(/Command$/,"");n.prototype[c]=o}let{paginators:r={},waiters:e={}}=s??{};for(let[i,f]of Object.entries(r))if(n.prototype[i]===void 0)n.prototype[i]=function(o={},c,...h){return f({...c,client:this},o,...h)};for(let[i,f]of Object.entries(e))if(n.prototype[i]===void 0)n.prototype[i]=async function(o={},c,...h){let u=c;if(typeof c==="number")u={maxWaitTime:c};return f({...u,client:this},o,...h)}};class Qs extends Error{$fault;$response;$retryable;$metadata;constructor(t){super(t.message);Object.setPrototypeOf(this,Object.getPrototypeOf(this).constructor.prototype),this.name=t.name,this.$fault=t.$fault,this.$metadata=t.$metadata}static isInstance(t){if(!t)return!1;let n=t;return Qs.prototype.isPrototypeOf(n)||Boolean(n.$fault)&&Boolean(n.$metadata)&&(n.$fault==="client"||n.$fault==="server")}static[Symbol.hasInstance](t){if(!t)return!1;let n=t;if(this===Qs)return Qs.isInstance(t);if(Qs.isInstance(t)){if(n.name&&this.name)return this.prototype.isPrototypeOf(t)||n.name===this.name;return this.prototype.isPrototypeOf(t)}return!1}}var hl=(t,n={})=>{Object.entries(n).filter(([,r])=>r!==void 0).forEach(([r,e])=>{if(t[r]==null||t[r]==="")t[r]=e});let s=t.message||t.Message||"UnknownError";return t.message=s,delete t.Message,t},ul=({output:t,parsedBody:n,exceptionCtor:s,errorCode:r})=>{let e=b4(t),i=e.httpStatusCode?e.httpStatusCode+"":void 0,f=new s({name:n?.code||n?.Code||r||i||"UnknownError",$fault:"client",$metadata:e});throw hl(f,n)},R4=(t)=>{return({output:n,parsedBody:s,errorCode:r})=>{ul({output:n,parsedBody:s,exceptionCtor:t,errorCode:r})}},b4=(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"]}),T4=(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:30000};default:return{}}},il=!1,S4=(t)=>{if(t&&!il&&parseInt(t.substring(1,t.indexOf(".")))<16)il=!0},ll=Object.values(ae),_l=(t)=>{let n=[];for(let s in ae){let r=ae[s];if(t[r]===void 0)continue;n.push({algorithmId:()=>r,checksumConstructor:()=>t[r]})}for(let[s,r]of Object.entries(t.checksumAlgorithms??{}))n.push({algorithmId:()=>s,checksumConstructor:()=>r});return{addChecksumAlgorithm(s){t.checksumAlgorithms=t.checksumAlgorithms??{};let r=s.algorithmId(),e=s.checksumConstructor();if(ll.includes(r))t.checksumAlgorithms[r.toUpperCase()]=e;else t.checksumAlgorithms[r]=e;n.push(s)},checksumAlgorithms(){return n}}},wl=(t)=>{let n={};return t.checksumAlgorithms().forEach((s)=>{let r=s.algorithmId();if(ll.includes(r))n[r]=s.checksumConstructor()}),n},Al=(t)=>{return{setRetryStrategy(n){t.retryStrategy=n},retryStrategy(){return t.retryStrategy}}},Ml=(t)=>{let n={};return n.retryStrategy=t.retryStrategy(),n},dl=(t)=>{return Object.assign(_l(t),Al(t))},$4=dl,U4=(t)=>{return Object.assign(wl(t),Ml(t))},L4=(t)=>Array.isArray(t)?t:[t],gl=(t)=>{for(let s in t)if(Object.prototype.hasOwnProperty.call(t,s)&&t[s]["#text"]!==void 0)t[s]=t[s]["#text"];else if(typeof t[s]==="object"&&t[s]!==null)t[s]=gl(t[s]);return t},I4=(t)=>{return t!=null};class El{trace(){}debug(){}info(){}warn(){}error(){}}function Rl(t,n,s){let r,e,i;if(typeof n>"u"&&typeof s>"u")r={},i=t;else if(r=t,typeof n==="function")return e=n,i=s,G4(r,e,i);else i=n;for(let f of Object.keys(i)){if(!Array.isArray(i[f])){r[f]=i[f];continue}bl(r,null,i,f)}return r}var O4=(t)=>{let n={};for(let[s,r]of Object.entries(t||{}))n[s]=[,r];return n},y4=(t,n)=>{let s={};for(let r in n)bl(s,t,n,r);return s},G4=(t,n,s)=>{return Rl(t,Object.entries(s).reduce((r,[e,i])=>{if(Array.isArray(i))r[e]=i;else if(typeof i==="function")r[e]=[n,i()];else r[e]=[n,i];return r},{}))},bl=(t,n,s,r)=>{if(n!==null){let f=s[r];if(typeof f==="function")f=[,f];let[o=B4,c=m4,h=r]=f;if(typeof o==="function"&&o(n[h])||typeof o!=="function"&&!!o)t[r]=c(n[h]);return}let[e,i]=s[r];if(typeof i==="function"){let f,o=e===void 0&&(f=i())!=null,c=typeof e==="function"&&!!e(void 0)||typeof e!=="function"&&!!e;if(o)t[r]=f;else if(c)t[r]=i()}else{let f=e===void 0&&i!=null,o=typeof e==="function"&&!!e(i)||typeof e!=="function"&&!!e;if(f||o)t[r]=i}},B4=(t)=>t!=null,m4=(t)=>t,F4=(t)=>{if(t!==t)return"NaN";switch(t){case 1/0:return"Infinity";case-1/0:return"-Infinity";default:return t}},P4=(t)=>t.toISOString().replace(".000Z","Z"),cf=(t)=>{if(t==null)return{};if(Array.isArray(t))return t.filter((n)=>n!=null).map(cf);if(typeof t==="object"){let n={};for(let s of Object.keys(t)){if(t[s]==null)continue;n[s]=cf(t[s])}return n}return t};function H4(t,n,s,r){return function(i,f,o,c,h={}){let u=Object.assign({},t,i);return Ve.classBuilder().ep(u).m(function(l,_,w,A){let M=f.call(this,l,_,w,A);return M.unshift(r(w,l.getEndpointParameterInstructions())),M}).s(n,o,h).n(s,o.charAt(0).toUpperCase()+o.slice(1)+"Command").sc(c).build()}}N4.Client=fl;N4.Command=Ve;N4.NoOpLogger=El;N4.SENSITIVE_STRING=g4;N4.ServiceException=Qs;N4.WaiterState=nn;N4._json=cf;N4.checkExceptions=h4;N4.constructStack=Hr;N4.convertMap=O4;N4.createAggregatedClient=E4;N4.createWaiter=d4;N4.decorateServiceException=hl;N4.emitWarningIfUnsupportedVersion=S4;N4.getArrayIfSingleItem=L4;N4.getChecksumConfiguration=_l;N4.getDefaultClientConfiguration=$4;N4.getDefaultExtensionConfiguration=dl;N4.getRetryConfiguration=Al;N4.getValueFromTextNode=gl;N4.invalidFunction=o4;N4.invalidProvider=f4;N4.isSerializableHeaderValue=I4;N4.loadConfigsForDefaultMode=T4;N4.makeBuilder=H4;N4.map=Rl;N4.resolveChecksumRuntimeConfig=wl;N4.resolveDefaultRuntimeConfig=U4;N4.resolveRetryRuntimeConfig=Ml;N4.schemaLogFilter=Ke;N4.serializeDateTime=P4;N4.serializeFloat=F4;N4.take=y4;N4.throwDefaultError=ul;N4.waiterServiceDefaults=ol;N4.withBaseException=R4});var Rt=K((TT)=>{var{homedir:T2}=j("os"),{sep:S2,join:Nr}=j("path"),{createHash:$2}=j("crypto"),{readFile:Gl}=j("fs/promises"),{IniSectionType:je}=es(),{normalizeProvider:pe}=En(),{isValidHostLabel:U2}=tn();class Js extends Error{name="ProviderError";tryNextLink;constructor(t,n=!0){let s,r=!0;if(typeof n==="boolean")s=void 0,r=n;else if(n!=null&&typeof n==="object")s=n.logger,r=n.tryNextLink??!0;super(t);this.tryNextLink=r,Object.setPrototypeOf(this,Js.prototype),s?.debug?.(`@smithy/property-provider ${r?"->":"(!)"} ${t}`)}static from(t,n=!0){return Object.assign(new this(t.message,n),t)}}class Dr extends Js{name="CredentialsProviderError";constructor(t,n=!0){super(t,n);Object.setPrototypeOf(this,Dr.prototype)}}class wf extends Js{name="TokenProviderError";constructor(t,n=!0){super(t,n);Object.setPrototypeOf(this,wf.prototype)}}var Bl=(...t)=>async()=>{if(t.length===0)throw new Js("No providers in chain");let n;for(let s of t)try{return await s()}catch(r){if(n=r,r?.tryNextLink)continue;throw r}throw n},ml=(t)=>()=>Promise.resolve(t),Af=(t,n,s)=>{let r,e,i,f=!1,o=async()=>{if(!e)e=t();try{r=await e,i=!0,f=!1}finally{e=void 0}return r};if(n===void 0)return async(c)=>{if(!i||c?.forceRefresh)r=await o();return r};return async(c)=>{if(!i||c?.forceRefresh)r=await o();if(f)return r;if(s&&!s(r))return f=!0,r;if(n(r))return await o(),r;return r}},Rn=(t,n,s)=>{if(!(n in t))return;if(t[n]==="true")return!0;if(t[n]==="false")return!1;throw Error(`Cannot load ${s} "${n}". Expected "true" or "false", got ${t[n]}.`)},L2=(t,n,s)=>{if(!(n in t))return;let r=parseInt(t[n],10);if(Number.isNaN(r))throw TypeError(`Cannot load ${s} '${n}'. Expected number, got '${t[n]}'.`);return r},zt;(function(t){t.ENV="env",t.CONFIG="shared config entry"})(zt||(zt={}));var hf={},I2=()=>{if(process&&process.geteuid)return`${process.geteuid()}`;return"DEFAULT"},Wr=()=>{let{HOME:t,USERPROFILE:n,HOMEPATH:s,HOMEDRIVE:r=`C:${S2}`}=process.env;if(t)return t;if(n)return n;if(s)return`${r}${s}`;let e=I2();if(!hf[e])hf[e]=T2();return hf[e]},Fl="AWS_PROFILE",Pl="default",Hl=(t)=>t.profile||process.env[Fl]||Pl,Nl=(t)=>{let s=$2("sha1").update(t).digest("hex");return Nr(Wr(),".aws","sso","cache",`${s}.json`)},ve={},O2=async(t)=>{if(ve[t])return ve[t];let n=Nl(t),s=await Gl(n,"utf8");return JSON.parse(s)},os=".",y2=(t)=>Object.entries(t).filter(([n])=>{let s=n.indexOf(os);if(s===-1)return!1;return Object.values(je).includes(n.substring(0,s))}).reduce((n,[s,r])=>{let e=s.indexOf(os),i=s.substring(0,e)===je.PROFILE?s.substring(e+1):s;return n[i]=r,n},{...t.default&&{default:t.default}}),G2="AWS_CONFIG_FILE",Dl=()=>process.env[G2]||Nr(Wr(),".aws","config"),B2="AWS_SHARED_CREDENTIALS_FILE",m2=()=>process.env[B2]||Nr(Wr(),".aws","credentials"),F2=/^([\w-]+)\s(["'])?([\w-@+.%:/]+)\2$/,P2=["__proto__","profile __proto__"],lf=(t)=>{let n={},s,r;for(let e of t.split(/\r?\n/)){let i=e.split(/(^|\s)[;#]/)[0].trim();if(i[0]==="["&&i[i.length-1]==="]"){s=void 0,r=void 0;let o=i.substring(1,i.length-1),c=F2.exec(o);if(c){let[,h,,u]=c;if(Object.values(je).includes(h))s=[h,u].join(os)}else s=o;if(P2.includes(o))throw Error(`Found invalid profile name "${o}"`)}else if(s){let o=i.indexOf("=");if(![0,-1].includes(o)){let[c,h]=[i.substring(0,o).trim(),i.substring(o+1).trim()];if(h==="")r=c;else{if(r&&e.trimStart()===e)r=void 0;n[s]=n[s]||{};let u=r?[r,c].join(os):c;n[s][u]=h}}}}return n},uf={},Ze={},ti=(t,n)=>{if(Ze[t]!==void 0)return Ze[t];if(!uf[t]||n?.ignoreCache)uf[t]=Gl(t,"utf8");return uf[t]},Tl=()=>({}),Mf=async(t={})=>{let{filepath:n=m2(),configFilepath:s=Dl()}=t,r=Wr(),e="~/",i=n;if(n.startsWith("~/"))i=Nr(r,n.slice(2));let f=s;if(s.startsWith("~/"))f=Nr(r,s.slice(2));let o=await Promise.all([ti(f,{ignoreCache:t.ignoreCache}).then(lf).then(y2).catch(Tl),ti(i,{ignoreCache:t.ignoreCache}).then(lf).catch(Tl)]);return{configFile:o[0],credentialsFile:o[1]}},H2=(t)=>Object.entries(t).filter(([n])=>n.startsWith(je.SSO_SESSION+os)).reduce((n,[s,r])=>({...n,[s.substring(s.indexOf(os)+1)]:r}),{}),N2=()=>({}),D2=async(t={})=>ti(t.configFilepath??Dl()).then(lf).then(H2).catch(N2),W2=(...t)=>{let n={};for(let s of t)for(let[r,e]of Object.entries(s))if(n[r]!==void 0)Object.assign(n[r],e);else n[r]=e;return n},Y2=async(t)=>{let n=await Mf(t);return W2(n.configFile,n.credentialsFile)},x2={getFileRecord(){return Ze},interceptFile(t,n){Ze[t]=Promise.resolve(n)},getTokenRecord(){return ve},interceptToken(t,n){ve[t]=n}};function Wl(t){try{let n=new Set(Array.from(t.match(/([A-Z_]){3,}/g)??[]));return n.delete("CONFIG"),n.delete("CONFIG_PREFIX_SEPARATOR"),n.delete("ENV"),[...n].join(", ")}catch(n){return t}}var Q2=(t,n)=>async()=>{try{let s=t(process.env,n);if(s===void 0)throw Error();return s}catch(s){throw new Dr(s.message||`Not found in ENV: ${Wl(t.toString())}`,{logger:n?.logger})}},J2=(t,{preferredFile:n="config",...s}={})=>async()=>{let r=Hl(s),{configFile:e,credentialsFile:i}=await Mf(s),f=i[r]||{},o=e[r]||{},c=n==="config"?{...f,...o}:{...o,...f};try{let u=t(c,n==="config"?e:i);if(u===void 0)throw Error();return u}catch(h){throw new Dr(h.message||`Not found in config files w/ profile [${r}]: ${Wl(t.toString())}`,{logger:s.logger})}},z2=(t)=>typeof t==="function",Yl=(t)=>z2(t)?async()=>await t():ml(t),_f=({environmentVariableSelector:t,configFileSelector:n,default:s},r={})=>{let{signingName:e,logger:i}=r;return Af(Bl(Q2(t,{signingName:e,logger:i}),J2(n,r),Yl(s)))},df="AWS_USE_DUALSTACK_ENDPOINT",gf="use_dualstack_endpoint",k2=!1,X2={environmentVariableSelector:(t)=>Rn(t,df,zt.ENV),configFileSelector:(t)=>Rn(t,gf,zt.CONFIG),default:!1},q2={environmentVariableSelector:(t)=>Rn(t,df,zt.ENV),configFileSelector:(t)=>Rn(t,gf,zt.CONFIG),default:void 0},Ef="AWS_USE_FIPS_ENDPOINT",Rf="use_fips_endpoint",C2=!1,a2={environmentVariableSelector:(t)=>Rn(t,Ef,zt.ENV),configFileSelector:(t)=>Rn(t,Rf,zt.CONFIG),default:!1},K2={environmentVariableSelector:(t)=>Rn(t,Ef,zt.ENV),configFileSelector:(t)=>Rn(t,Rf,zt.CONFIG),default:void 0},V2=(t)=>{let{tls:n,endpoint:s,urlParser:r,useDualstackEndpoint:e}=t;return Object.assign(t,{tls:n??!0,endpoint:pe(typeof s==="string"?r(s):s),isCustomEndpoint:!0,useDualstackEndpoint:pe(e??!1)})},j2=async(t)=>{let{tls:n=!0}=t,s=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(s))throw Error("Invalid region in client config");let e=await t.useDualstackEndpoint(),i=await t.useFipsEndpoint(),{hostname:f}=await t.regionInfoProvider(s,{useDualstackEndpoint:e,useFipsEndpoint:i})??{};if(!f)throw Error("Cannot resolve hostname from client config");return t.urlParser(`${n?"https:":"http:"}//${f}`)},p2=(t)=>{let n=pe(t.useDualstackEndpoint??!1),{endpoint:s,useFipsEndpoint:r,urlParser:e,tls:i}=t;return Object.assign(t,{tls:i??!0,endpoint:s?pe(typeof s==="string"?e(s):s):()=>j2({...t,useDualstackEndpoint:n,useFipsEndpoint:r}),isCustomEndpoint:!!s,useDualstackEndpoint:n})},v2="AWS_EXECUTION_ENV",Sl="AWS_REGION",$l="AWS_DEFAULT_REGION",Z2="AWS_EC2_METADATA_DISABLED",tT=["in-region","cross-region","mobile","standard","legacy"],nT="/latest/meta-data/placement/region",sT="/latest/api/token",rT="x-aws-ec2-metadata-token",eT="x-aws-ec2-metadata-token-ttl-seconds",Ul=1000,iT=60000,xl=0,Ql=async()=>{if(process.env[Z2])return;if(Date.now()<xl)return;try{let t=oT(),n=(await Il({...t,path:sT,method:"PUT",headers:{[eT]:"21600"}})).toString();return(await Il({...t,path:nT,method:"GET",headers:{[rT]:n}})).toString().trim()||Ll()}catch{return Ll()}},Ll=()=>{xl=Date.now()+iT;return},oT=()=>{let t=process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT;if(t){let n=new URL(t);return{hostname:n.hostname.replace(/^\[(.+)]$/,"$1"),port:n.port?Number(n.port):void 0}}if(process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE==="IPv6")return{hostname:"fd00:ec2::254"};return{hostname:"169.254.169.254"}},Il=async(t)=>{let{request:n}=j("http");return new Promise((s,r)=>{let e=n({hostname:t.hostname,port:t.port,path:t.path,method:t.method,headers:t.headers,timeout:Ul,signal:AbortSignal.timeout(Ul)});e.on("error",(i)=>{r(i),e.destroy()}),e.on("timeout",()=>{r(Error("TimeoutError from instance metadata service")),e.destroy()}),e.on("response",(i)=>{let{statusCode:f=400}=i;if(f<200||f>=300){r(Object.assign(Error("Error response received from instance metadata service"),{statusCode:f})),e.destroy();return}let o=[];i.on("data",(c)=>o.push(c)),i.on("end",()=>{s(Buffer.concat(o)),e.destroy()})}),e.end()})},Jl="AWS_REGION",zl="region",kl={environmentVariableSelector:(t)=>t[Jl],configFileSelector:(t)=>t[zl],default:async()=>{let t=await Ql();if(t)return t;throw Error("Region is missing")}},fT={preferredFile:"credentials"},Ol=new Set,cT=(t,n=U2)=>{if(!Ol.has(t)&&!n(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 Error(`Region not accepted: region="${t}" is not a valid hostname component.`);else Ol.add(t)},Xl=(t)=>typeof t==="string"&&(t.startsWith("fips-")||t.endsWith("-fips")),hT=(t)=>Xl(t)?["fips-aws-global","aws-fips"].includes(t)?"us-east-1":t.replace(/fips-(dkr-|prod-)?|-fips/,""):t,uT=(t)=>{let{region:n,useFipsEndpoint:s}=t;if(!n)throw Error("Region is missing");return Object.assign(t,{region:async()=>{let r=typeof n==="function"?await n():n,e=hT(r);return cT(e),e},useFipsEndpoint:async()=>{let r=typeof n==="string"?n:await n();if(Xl(r))return!0;return typeof s!=="function"?Promise.resolve(!!s):s()}})},yl=(t=[],{useFipsEndpoint:n,useDualstackEndpoint:s})=>t.find(({tags:r})=>n===r.includes("fips")&&s===r.includes("dualstack"))?.hostname,lT=(t,{regionHostname:n,partitionHostname:s})=>n?n:s?s.replace("{region}",t):void 0,_T=(t,{partitionHash:n})=>Object.keys(n||{}).find((s)=>n[s].regions.includes(t))??"aws",wT=(t,{signingRegion:n,regionRegex:s,useFipsEndpoint:r})=>{if(n)return n;else if(r){let e=s.replace("\\\\","\\").replace(/^\^/g,"\\.").replace(/\$$/g,"\\."),i=t.match(e);if(i)return i[0].slice(1,-1)}},AT=(t,{useFipsEndpoint:n=!1,useDualstackEndpoint:s=!1,signingService:r,regionHash:e,partitionHash:i})=>{let f=_T(t,{partitionHash:i}),o=t in e?t:i[f]?.endpoint??t,c={useFipsEndpoint:n,useDualstackEndpoint:s},h=yl(e[o]?.variants,c),u=yl(i[f]?.variants,c),l=lT(o,{regionHostname:h,partitionHostname:u});if(l===void 0)throw Error(`Endpoint resolution failed for: ${{resolvedRegion:o,useFipsEndpoint:n,useDualstackEndpoint:s}}`);let _=wT(l,{signingRegion:e[o]?.signingRegion,regionRegex:i[f].regionRegex,useFipsEndpoint:n});return{partition:f,signingService:r,hostname:l,..._&&{signingRegion:_},...e[o]?.signingService&&{signingService:e[o].signingService}}},MT="AWS_DEFAULTS_MODE",dT="defaults_mode",gT={environmentVariableSelector:(t)=>{return t[MT]},configFileSelector:(t)=>{return t[dT]},default:"legacy"},ET=({region:t=_f(kl),defaultsMode:n=_f(gT)}={})=>Af(async()=>{let s=typeof n==="function"?await n():n;switch(s?.toLowerCase()){case"auto":return RT(t);case"in-region":case"cross-region":case"mobile":case"standard":case"legacy":return Promise.resolve(s?.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw Error(`Invalid parameter for "defaultsMode", expect ${tT.join(", ")}, got ${s}`)}}),RT=async(t)=>{if(t){let n=typeof t==="function"?await t():t,s=await bT();if(!s)return"standard";if(n===s)return"in-region";else return"cross-region"}return"standard"},bT=async()=>{if(process.env[v2]&&(process.env[Sl]||process.env[$l]))return process.env[Sl]??process.env[$l];return Ql()};TT.CONFIG_PREFIX_SEPARATOR=os;TT.CONFIG_USE_DUALSTACK_ENDPOINT=gf;TT.CONFIG_USE_FIPS_ENDPOINT=Rf;TT.CredentialsProviderError=Dr;TT.DEFAULT_PROFILE=Pl;TT.DEFAULT_USE_DUALSTACK_ENDPOINT=k2;TT.DEFAULT_USE_FIPS_ENDPOINT=C2;TT.ENV_PROFILE=Fl;TT.ENV_USE_DUALSTACK_ENDPOINT=df;TT.ENV_USE_FIPS_ENDPOINT=Ef;TT.NODE_REGION_CONFIG_FILE_OPTIONS=fT;TT.NODE_REGION_CONFIG_OPTIONS=kl;TT.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS=X2;TT.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS=a2;TT.ProviderError=Js;TT.REGION_ENV_NAME=Jl;TT.REGION_INI_NAME=zl;TT.SelectorType=zt;TT.TokenProviderError=wf;TT.booleanSelector=Rn;TT.chain=Bl;TT.externalDataInterceptor=x2;TT.fromStatic=Yl;TT.fromValue=ml;TT.getHomeDir=Wr;TT.getProfileName=Hl;TT.getRegionInfo=AT;TT.getSSOTokenFilepath=Nl;TT.getSSOTokenFromFile=O2;TT.loadConfig=_f;TT.loadSharedConfigFiles=Mf;TT.loadSsoSessionData=D2;TT.memoize=Af;TT.nodeDualstackConfigSelectors=q2;TT.nodeFipsConfigSelectors=K2;TT.numberSelector=L2;TT.parseKnownFiles=Y2;TT.readFile=ti;TT.resolveCustomEndpointsConfig=V2;TT.resolveDefaultsModeConfig=ET;TT.resolveEndpointsConfig=p2;TT.resolveRegionConfig=uT});var fs=K((K6)=>{var{CONFIG_PREFIX_SEPARATOR:ql,loadConfig:u6}=Rt(),{toEndpointV1:ni,getSmithyContext:l6,normalizeProvider:bf,isValidHostLabel:Kl}=tn();K6.isValidHostLabel=Kl;K6.middlewareEndpointToEndpointV1=ni;K6.toEndpointV1=ni;var{EndpointURLScheme:$f}=es(),Cl="AWS_ENDPOINT_URL",al="endpoint_url",_6=(t)=>({environmentVariableSelector:(n)=>{let s=t.split(" ").map((i)=>i.toUpperCase()),r=n[[Cl,...s].join("_")];if(r)return r;let e=n[Cl];if(e)return e;return},configFileSelector:(n,s)=>{if(s&&n.services){let e=s[["services",n.services].join(ql)];if(e){let i=t.split(" ").map((o)=>o.toLowerCase()),f=e[[i.join("_"),al].join(ql)];if(f)return f}}let r=n[al];if(r)return r;return},default:void 0}),si=async(t)=>u6(_6(t??""))(),w6=async(t)=>{let n=t?.Bucket||"";if(typeof t.Bucket==="string")t.Bucket=n.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"));if(E6(n)){if(t.ForcePathStyle===!0)throw Error("Path-style addressing cannot be used with ARN buckets")}else if(!g6(n)||n.indexOf(".")!==-1&&!String(t.Endpoint).startsWith("http:")||n.toLowerCase()!==n||n.length<3)t.ForcePathStyle=!0;if(t.DisableMultiRegionAccessPoints)t.disableMultiRegionAccessPoints=!0,t.DisableMRAP=!0;return t},A6=/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/,M6=/(\d+\.){3}\d+/,d6=/\.\./,g6=(t)=>A6.test(t)&&!M6.test(t)&&!d6.test(t),E6=(t)=>{let[n,s,r,,,e]=t.split(":"),i=n==="arn"&&t.split(":").length>=6,f=Boolean(i&&s&&r&&e);if(i&&!f)throw Error(`Invalid ARN: ${t} was an invalid ARN.`);return f},R6=(t,n,s,r=!1)=>{let e=async()=>{let i;if(r)i=s.clientContextParams?.[t]??s[t]??s[n];else i=s[t]??s[n];if(typeof i==="function")return i();return i};if(t==="credentialScope"||n==="CredentialScope")return async()=>{let i=typeof s.credentials==="function"?await s.credentials():s.credentials;return i?.credentialScope??i?.CredentialScope};if(t==="accountId"||n==="AccountId")return async()=>{let i=typeof s.credentials==="function"?await s.credentials():s.credentials;return i?.accountId??i?.AccountId};if(t==="endpoint"||n==="endpoint")return async()=>{if(s.isCustomEndpoint===!1)return;let i=await e();if(i&&typeof i==="object"){if("url"in i)return i.url.href;if("hostname"in i){let{protocol:f,hostname:o,port:c,path:h}=i;return`${f}//${o}${c?":"+c:""}${h}`}}return i};return e};function Vl(t){return async(n,s,r,e)=>{if(!r.isCustomEndpoint){let o;if(r.serviceConfiguredEndpoint)o=await r.serviceConfiguredEndpoint();else o=await t(r.serviceId);if(o)r.endpoint=()=>Promise.resolve(ni(o)),r.isCustomEndpoint=!0}let i=await jl(n,s,r);if(typeof r.endpointProvider!=="function")throw Error("config.endpointProvider is not set.");let f=r.endpointProvider(i,e);if(r.isCustomEndpoint&&r.endpoint){let o=await r.endpoint();if(o?.headers){f.headers??={};for(let[c,h]of Object.entries(o.headers))f.headers[c]=Array.isArray(h)?h:[h]}}return f}}var jl=async(t,n,s)=>{let r={},e=n?.getEndpointParameterInstructions?.()||{};for(let[i,f]of Object.entries(e))switch(f.type){case"staticContextParams":r[i]=f.value;break;case"contextParams":r[i]=t[f.name];break;case"clientContextParams":case"builtInParams":r[i]=await R6(f.name,i,s,f.type!=="builtInParams")();break;case"operationContextParams":r[i]=f.get(t);break;default:throw Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(f))}if(Object.keys(e).length===0)Object.assign(r,s);if(String(s.serviceId).toLowerCase()==="s3")await w6(r);return r};function b6(t,n,s){if(!t.__smithy_context)t.__smithy_context={features:{}};else if(!t.__smithy_context.features)t.__smithy_context.features={};t.__smithy_context.features[n]=s}function pl(t){let n=Vl(t);return({config:s,instructions:r})=>{return(e,i)=>async(f)=>{if(s.isCustomEndpoint)b6(i,"ENDPOINT_OVERRIDE","N");let o=await n(f.input,{getEndpointParameterInstructions(){return r}},{...s},i);i.endpointV2=o,i.authSchemes=o.properties?.authSchemes;let c=i.authSchemes?.[0];if(c){i.signing_region=c.signingRegion,i.signing_service=c.signingName;let u=l6(i)?.selectedHttpAuthScheme?.httpAuthOption;if(u)u.signingProperties=Object.assign(u.signingProperties||{},{signing_region:c.signingRegion,signingRegion:c.signingRegion,signing_service:c.signingName,signingName:c.signingName,signingRegionSet:c.signingRegionSet},c.properties)}return e({...f})}}}var T6={name:"serializerMiddleware"},vl={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:T6.name};function S6(t){let n=pl(t);return(s,r)=>({applyToStack:(e)=>{e.addRelativeTo(n({config:s,instructions:r}),vl)}})}function $6(t){return(n)=>{let s=n.tls??!0,{endpoint:r,useDualstackEndpoint:e,useFipsEndpoint:i}=n,f=r!=null?async()=>ni(await bf(r)()):void 0,c=Object.assign(n,{endpoint:f,tls:s,isCustomEndpoint:!!r,useDualstackEndpoint:bf(e??!1),useFipsEndpoint:bf(i??!1)}),h=void 0;return c.serviceConfiguredEndpoint=async()=>{if(n.serviceId&&!h)h=t(n.serviceId);return h},c}}class Uf{nodes;root;conditions;results;constructor(t,n,s,r){this.nodes=t,this.root=n,this.conditions=s,this.results=r}static from(t,n,s,r){return new Uf(t,n,s,r)}}class Zl{capacity;data=new Map;parameters=[];constructor({size:t,params:n}){if(this.capacity=t??50,n)this.parameters=n}get(t,n){let s=this.hash(t);if(s===!1)return n();if(!this.data.has(s)){if(this.data.size>this.capacity+10){let r=this.data.keys(),e=0;while(!0){let{value:i,done:f}=r.next();if(this.data.delete(i),f||++e>10)break}}this.data.set(s,n())}return this.data.get(s)}size(){return this.data.size}hash(t){let n="",{parameters:s}=this;if(s.length===0)return!1;for(let r of s){let e=String(t[r]??"");if(e.includes("|;"))return!1;n+=e+"|;"}return n}}class ut extends Error{constructor(t){super(t);this.name="EndpointError"}}var Yr="endpoints";function Nn(t){if(typeof t!=="object"||t==null)return t;if("ref"in t)return`$${Nn(t.ref)}`;if("fn"in t)return`${t.fn}(${(t.argv||[]).map(Nn).join(", ")})`;return JSON.stringify(t,null,2)}var t0={},U6=(t,n)=>t===n;function L6(...t){for(let n of t)if(n!=null)return n;return}var I6=(t)=>{let n=t.split("."),s=[];for(let r of n){let e=r.indexOf("[");if(e!==-1){if(r.indexOf("]")!==r.length-1)throw new ut(`Path: '${t}' does not end with ']'`);let i=r.slice(e+1,-1);if(Number.isNaN(parseInt(i)))throw new ut(`Invalid array index: '${i}' in path: '${t}'`);if(e!==0)s.push(r.slice(0,e));s.push(i)}else s.push(r)}return s},n0=(t,n)=>I6(n).reduce((s,r)=>{if(typeof s!=="object")throw new ut(`Index '${r}' in '${n}' not found in '${JSON.stringify(t)}'`);else if(Array.isArray(s)){let e=parseInt(r);return s[e<0?s.length+e:e]}return s[r]},t),O6=(t)=>t!=null;function y6(t,n,s){return t?n:s}var G6=(t)=>!t,B6=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}$"),s0=(t)=>B6.test(t)||t.startsWith("[")&&t.endsWith("]"),Tf={[$f.HTTP]:80,[$f.HTTPS]:443},m6=(t)=>{let n=(()=>{try{if(t instanceof URL)return t;if(typeof t==="object"&&"hostname"in t){let{hostname:_,port:w,protocol:A="",path:M="",query:d={}}=t,E=new URL(`${A}//${_}${w?`:${w}`:""}${M}`);return E.search=Object.entries(d).map(([b,L])=>`${b}=${L}`).join("&"),E}return new URL(t)}catch(_){return null}})();if(!n)return console.error(`Unable to parse ${JSON.stringify(t)} as a whatwg URL.`),null;let s=n.href,{host:r,hostname:e,pathname:i,protocol:f,search:o}=n;if(o)return null;let c=f.slice(0,-1);if(!Object.values($f).includes(c))return null;let h=s0(e),u=s.includes(`${r}:${Tf[c]}`)||typeof t==="string"&&t.includes(`${r}:${Tf[c]}`),l=`${r}${u?`:${Tf[c]}`:""}`;return{scheme:c,authority:l,path:i,normalizedPath:i.endsWith("/")?i:`${i}/`,isIp:h}};function F6(t,n,s){if(s===1)return[t];if(t==="")return[""];let r=t.split(n);if(s===0)return r;return r.slice(0,s-1).concat(r.slice(1).join(n))}var P6=(t,n)=>t===n,H6=(t,n,s,r)=>{if(t==null||n>=s||t.length<s||/[^\u0000-\u007f]/.test(t))return null;if(!r)return t.substring(n,s);return t.substring(t.length-s,t.length-n)},N6=(t)=>encodeURIComponent(t).replace(/[!*'()]/g,(n)=>`%${n.charCodeAt(0).toString(16).toUpperCase()}`),D6={booleanEquals:U6,coalesce:L6,getAttr:n0,isSet:O6,isValidHostLabel:Kl,ite:y6,not:G6,parseURL:m6,split:F6,stringEquals:P6,substring:H6,uriEncode:N6},r0=(t,n)=>{let s=[],{referenceRecord:r,endpointParams:e}=n,i=0;while(i<t.length){let f=t.indexOf("{",i);if(f===-1){s.push(t.slice(i));break}s.push(t.slice(i,f));let o=t.indexOf("}",f);if(o===-1){s.push(t.slice(f));break}if(t[f+1]==="{"&&t[o+1]==="}")s.push(t.slice(f+1,o)),i=o+2;let c=t.substring(f+1,o);if(c.includes("#")){let[h,u]=c.split("#");s.push(n0(r[h]??e[h],u))}else s.push(r[c]??e[c]);i=o+1}return s.join("")},W6=({ref:t},n)=>{return n.referenceRecord[t]??n.endpointParams[t]},xr=(t,n,s)=>{if(typeof t==="string")return r0(t,s);else if(t.fn)return i0.callFunction(t,s);else if(t.ref)return W6(t,s);throw new ut(`'${n}': ${String(t)} is not a string, function or reference.`)},e0=({fn:t,argv:n},s)=>{let r=Array(n.length);for(let f=0;f<r.length;++f){let o=n[f];if(typeof o==="boolean"||typeof o==="number")r[f]=o;else r[f]=i0.evaluateExpression(o,"arg",s)}let e=t.indexOf(".");if(e!==-1){let o=t0[t.slice(0,e)]?.[t.slice(e+1)];if(typeof o==="function")return o(...r)}let i=D6[t];if(typeof i==="function")return i(...r);throw Error(`function ${t} not loaded in endpointFunctions.`)},i0={evaluateExpression:xr,callFunction:e0},o0=(t,n)=>{let{assign:s}=t;if(s&&s in n.referenceRecord)throw new ut(`'${s}' is already defined in Reference Record.`);let r=e0(t,n);n.logger?.debug?.(`${Yr} evaluateCondition: ${Nn(t)} = ${Nn(r)}`);let e=r===""?!0:!!r;if(s!=null)return{result:e,toAssign:{name:s,value:r}};return{result:e}},f0=(t,n)=>Object.entries(t??{}).reduce((s,[r,e])=>{return s[r]=e.map((i)=>{let f=xr(i,"Header value entry",n);if(typeof f!=="string")throw new ut(`Header '${r}' value '${f}' is not a string`);return f}),s},{}),Lf=(t,n)=>Object.entries(t).reduce((s,[r,e])=>{return s[r]=h0.getEndpointProperty(e,n),s},{}),c0=(t,n)=>{if(Array.isArray(t))return t.map((s)=>c0(s,n));switch(typeof t){case"string":return r0(t,n);case"object":if(t===null)throw new ut(`Unexpected endpoint property: ${t}`);return h0.getEndpointProperties(t,n);case"boolean":return t;default:throw new ut(`Unexpected endpoint property type: ${typeof t}`)}},h0={getEndpointProperty:c0,getEndpointProperties:Lf},u0=(t,n)=>{let s=xr(t,"Endpoint URL",n);if(typeof s==="string")try{return new URL(s)}catch(r){throw console.error(`Failed to construct URL with ${s}`,r),r}throw new ut(`Endpoint URL must be a string, got ${typeof s}`)},Sf=1e8,Y6=(t,n)=>{let{nodes:s,root:r,results:e,conditions:i}=t,f=r,o={},c={referenceRecord:o,endpointParams:n.endpointParams,logger:n.logger};while(f!==1&&f!==-1&&f<Sf){let h=3*(Math.abs(f)-1),[u,l,_]=[s[h],s[h+1],s[h+2]],[w,A,M]=i[u],d=o0({fn:w,assign:M,argv:A},c);if(d.toAssign){let{name:E,value:b}=d.toAssign;o[E]=b}f=f>=0===d.result?l:_}if(f>=Sf){let h=e[f-Sf];if(h[0]===-1){let[,w]=h;throw new ut(xr(w,"Error",c))}let[u,l,_]=h;return{url:u0(u,c),properties:Lf(l,c),headers:f0(_??{},c)}}throw new ut("No matching endpoint.")},If=(t=[],n)=>{let s={},r={...n,referenceRecord:{...n.referenceRecord}},e=!1;for(let i of t){let{result:f,toAssign:o}=o0(i,r);if(!f)return{result:f};if(o)e=!0,s[o.name]=o.value,r.referenceRecord[o.name]=o.value,n.logger?.debug?.(`${Yr} assign: ${o.name} := ${Nn(o.value)}`)}if(e)return{result:!0,referenceRecord:s};return{result:!0}},x6=(t,n)=>{let{conditions:s,endpoint:r}=t,{result:e,referenceRecord:i}=If(s,n);if(!e)return;let f=i?{...n,referenceRecord:{...n.referenceRecord,...i}}:n,{url:o,properties:c,headers:h}=r;n.logger?.debug?.(`${Yr} Resolving endpoint from template: ${Nn(r)}`);let u={url:u0(o,f)};if(h!=null)u.headers=f0(h,f);if(c!=null)u.properties=Lf(c,f);return u},Q6=(t,n)=>{let{conditions:s,error:r}=t,{result:e,referenceRecord:i}=If(s,n);if(!e)return;let f=i?{...n,referenceRecord:{...n.referenceRecord,...i}}:n;throw new ut(xr(r,"Error",f))},l0=(t,n)=>{for(let s of t)if(s.type==="endpoint"){let r=x6(s,n);if(r)return r}else if(s.type==="error")Q6(s,n);else if(s.type==="tree"){let r=_0.evaluateTreeRule(s,n);if(r)return r}else throw new ut(`Unknown endpoint rule: ${s}`);throw new ut("Rules evaluation failed")},J6=(t,n)=>{let{conditions:s,rules:r}=t,{result:e,referenceRecord:i}=If(s,n);if(!e)return;let f=i?{...n,referenceRecord:{...n.referenceRecord,...i}}:n;return _0.evaluateRules(r,f)},_0={evaluateRules:l0,evaluateTreeRule:J6},z6=(t,n)=>{let{endpointParams:s,logger:r}=n,{parameters:e,rules:i}=t;n.logger?.debug?.(`${Yr} Initial EndpointParams: ${Nn(s)}`);for(let o in e){let c=e[o],h=s[o];if(h==null&&c.default!=null){s[o]=c.default;continue}if(c.required&&h==null)throw new ut(`Missing required parameter: '${o}'`)}let f=l0(i,{endpointParams:s,logger:r,referenceRecord:{}});return n.logger?.debug?.(`${Yr} Resolved endpoint: ${Nn(f)}`),f},k6=(t)=>{let{endpoint:n}=t;if(n===void 0)t.endpoint=async()=>{throw Error("@smithy/middleware-endpoint: (default endpointRuleSet) endpoint is not set - you must configure an endpoint.")};return t},X6=Vl(si),q6=$6(si),C6=pl(si),a6=S6(si);K6.BinaryDecisionDiagram=Uf;K6.EndpointCache=Zl;K6.EndpointError=ut;K6.customEndpointFunctions=t0;K6.decideEndpoint=Y6;K6.endpointMiddleware=C6;K6.endpointMiddlewareOptions=vl;K6.getEndpointFromInstructions=X6;K6.getEndpointPlugin=a6;K6.isIpAddress=s0;K6.resolveEndpoint=z6;K6.resolveEndpointConfig=q6;K6.resolveEndpointRequiredConfig=k6;K6.resolveParams=jl});var bt=K((Q5)=>{var{createHmac:_S,createHash:wS,getRandomValues:AS}=j("crypto"),{ReadStream:MS,lstatSync:dS,fstatSync:gS}=j("fs"),{HttpResponse:ES}=tn(),{toEndpointV1:RS}=fs(),{Readable:zs,Writable:b0,PassThrough:w0}=j("stream"),T0=(t)=>typeof ArrayBuffer==="function"&&t instanceof ArrayBuffer||Object.prototype.toString.call(t)==="[object ArrayBuffer]",Xs=(t,n=0,s=t.byteLength-n)=>{if(!T0(t))throw TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof t} (${t})`);return Buffer.from(t,n,s)},oi=(t,n)=>{if(typeof t!=="string")throw TypeError(`The "input" argument must be of type string. Received type ${typeof t} (${t})`);return n?Buffer.from(t,n):Buffer.from(t)},bS=/^[A-Za-z0-9+/]*={0,2}$/,S0=(t)=>{if(t.length*3%4!==0)throw TypeError("Incorrect padding on base64 string.");if(!bS.exec(t))throw TypeError("Invalid base64 string.");let n=oi(t,"base64");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)},fi=(t)=>{let n=oi(t,"utf8");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength/Uint8Array.BYTES_PER_ELEMENT)},Hf=(t)=>{let n;if(typeof t==="string")n=fi(t);else n=t;if(typeof n!=="object"||typeof n.byteOffset!=="number"||typeof n.byteLength!=="number")throw Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");return Xs(n.buffer,n.byteOffset,n.byteLength).toString("base64")};function TS(t,n,s,r){return class e extends Uint8Array{static fromString(i,f="utf-8"){if(typeof i==="string"){if(f==="base64")return e.mutate(r(i));return e.mutate(n(i))}throw Error(`Unsupported conversion from ${typeof i} to Uint8ArrayBlobAdapter.`)}static mutate(i){return Object.setPrototypeOf(i,e.prototype),i}transformToString(i="utf-8"){if(i==="base64")return s(this);return t(this)}}}var $0=(t)=>{if(typeof t==="string")return t;if(typeof t!=="object"||typeof t.byteOffset!=="number"||typeof t.byteLength!=="number")throw Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return Xs(t.buffer,t.byteOffset,t.byteLength).toString("utf8")},At=Array.from({length:256},(t,n)=>n.toString(16).padStart(2,"0"));function SS(t){if(typeof crypto<"u"&&typeof crypto.randomUUID==="function")return()=>crypto.randomUUID();return()=>{let n=new Uint8Array(16);return t(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128,At[n[0]]+At[n[1]]+At[n[2]]+At[n[3]]+"-"+At[n[4]]+At[n[5]]+"-"+At[n[6]]+At[n[7]]+"-"+At[n[8]]+At[n[9]]+"-"+At[n[10]]+At[n[11]]+At[n[12]]+At[n[13]]+At[n[14]]+At[n[15]]}}var $S=(t,n,s=(r)=>r)=>t,US=(t)=>{switch(t){case"true":return!0;case"false":return!1;default:throw Error(`Unable to parse boolean value "${t}"`)}},LS=(t)=>{if(t===null||t===void 0)return;if(typeof t==="number"){if(t===0||t===1)kr.warn(ei(`Expected boolean, got ${typeof t}: ${t}`));if(t===0)return!1;if(t===1)return!0}if(typeof t==="string"){let n=t.toLowerCase();if(n==="false"||n==="true")kr.warn(ei(`Expected boolean, got ${typeof t}: ${t}`));if(n==="false")return!1;if(n==="true")return!0}if(typeof t==="boolean")return t;throw TypeError(`Expected boolean, got ${typeof t}: ${t}`)},Jr=(t)=>{if(t===null||t===void 0)return;if(typeof t==="string"){let n=parseFloat(t);if(!Number.isNaN(n)){if(String(n)!==String(t))kr.warn(ei(`Expected number but observed string: ${t}`));return n}}if(typeof t==="number")return t;throw TypeError(`Expected number, got ${typeof t}: ${t}`)},IS=Math.ceil(340282346638528860000000000000000000000),ri=(t)=>{let n=Jr(t);if(n!==void 0&&!Number.isNaN(n)&&n!==1/0&&n!==-1/0){if(Math.abs(n)>IS)throw TypeError(`Expected 32-bit float, got ${t}`)}return n},zr=(t)=>{if(t===null||t===void 0)return;if(Number.isInteger(t)&&!Number.isNaN(t))return t;throw TypeError(`Expected integer, got ${typeof t}: ${t}`)},OS=zr,Bf=(t)=>Nf(t,32),mf=(t)=>Nf(t,16),Ff=(t)=>Nf(t,8),Nf=(t,n)=>{let s=zr(t);if(s!==void 0&&yS(s,n)!==s)throw TypeError(`Expected ${n}-bit integer, got ${t}`);return s},yS=(t,n)=>{switch(n){case 32:return Int32Array.of(t)[0];case 16:return Int16Array.of(t)[0];case 8:return Int8Array.of(t)[0]}},GS=(t,n)=>{if(t===null||t===void 0){if(n)throw TypeError(`Expected a non-null value for ${n}`);throw TypeError("Expected a non-null value")}return t},U0=(t)=>{if(t===null||t===void 0)return;if(typeof t==="object"&&!Array.isArray(t))return t;let n=Array.isArray(t)?"array":typeof t;throw TypeError(`Expected object, got ${n}: ${t}`)},BS=(t)=>{if(t===null||t===void 0)return;if(typeof t==="string")return t;if(["boolean","number","bigint"].includes(typeof t))return kr.warn(ei(`Expected string, got ${typeof t}: ${t}`)),String(t);throw TypeError(`Expected string, got ${typeof t}: ${t}`)},mS=(t)=>{if(t===null||t===void 0)return;let n=U0(t),s=[];for(let r in n)if(n[r]!=null)s.push(r);if(s.length===0)throw TypeError("Unions must have exactly one non-null member. None were found.");if(s.length>1)throw TypeError(`Unions must have exactly one non-null member. Keys ${s} were not null.`);return n},Df=(t)=>{if(typeof t=="string")return Jr(as(t));return Jr(t)},FS=Df,L0=(t)=>{if(typeof t=="string")return ri(as(t));return ri(t)},PS=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,as=(t)=>{let n=t.match(PS);if(n===null||n[0].length!==t.length)throw TypeError("Expected real number, got implicit NaN");return parseFloat(t)},Wf=(t)=>{if(typeof t=="string")return I0(t);return Jr(t)},HS=Wf,NS=Wf,DS=(t)=>{if(typeof t=="string")return I0(t);return ri(t)},I0=(t)=>{switch(t){case"NaN":return NaN;case"Infinity":return 1/0;case"-Infinity":return-1/0;default:throw Error(`Unable to parse float value: ${t}`)}},O0=(t)=>{if(typeof t==="string")return zr(as(t));return zr(t)},WS=O0,YS=(t)=>{if(typeof t==="string")return Bf(as(t));return Bf(t)},qs=(t)=>{if(typeof t==="string")return mf(as(t));return mf(t)},y0=(t)=>{if(typeof t==="string")return Ff(as(t));return Ff(t)},ei=(t)=>{return String(TypeError(t).stack||t).split(`
|
|
9
|
+
`).slice(0,5).filter((n)=>!n.includes("stackTraceWarning")).join(`
|
|
10
|
+
`)},kr={warn:console.warn},xS=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],Yf=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function QS(t){let n=t.getUTCFullYear(),s=t.getUTCMonth(),r=t.getUTCDay(),e=t.getUTCDate(),i=t.getUTCHours(),f=t.getUTCMinutes(),o=t.getUTCSeconds(),c=e<10?`0${e}`:`${e}`,h=i<10?`0${i}`:`${i}`,u=f<10?`0${f}`:`${f}`,l=o<10?`0${o}`:`${o}`;return`${xS[r]}, ${c} ${Yf[s]} ${n} ${h}:${u}:${l} GMT`}var JS=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),zS=(t)=>{if(t===null||t===void 0)return;if(typeof t!=="string")throw TypeError("RFC-3339 date-times must be expressed as strings");let n=JS.exec(t);if(!n)throw TypeError("Invalid RFC-3339 date-time value");let[s,r,e,i,f,o,c,h]=n,u=qs(Cs(r)),l=sn(e,"month",1,12),_=sn(i,"day",1,31);return Qr(u,l,_,{hours:f,minutes:o,seconds:c,fractionalMilliseconds:h})},kS=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}:\d{2})|[zZ])$/),XS=(t)=>{if(t===null||t===void 0)return;if(typeof t!=="string")throw TypeError("RFC-3339 date-times must be expressed as strings");let n=kS.exec(t);if(!n)throw TypeError("Invalid RFC-3339 date-time value");let[s,r,e,i,f,o,c,h,u]=n,l=qs(Cs(r)),_=sn(e,"month",1,12),w=sn(i,"day",1,31),A=Qr(l,_,w,{hours:f,minutes:o,seconds:c,fractionalMilliseconds:h});if(u.toUpperCase()!="Z")A.setTime(A.getTime()-r5(u));return A},qS=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$/),CS=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$/),aS=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})$/),KS=(t)=>{if(t===null||t===void 0)return;if(typeof t!=="string")throw TypeError("RFC-7231 date-times must be expressed as strings");let n=qS.exec(t);if(n){let[s,r,e,i,f,o,c,h]=n;return Qr(qs(Cs(i)),Of(e),sn(r,"day",1,31),{hours:f,minutes:o,seconds:c,fractionalMilliseconds:h})}if(n=CS.exec(t),n){let[s,r,e,i,f,o,c,h]=n;return vS(Qr(jS(i),Of(e),sn(r,"day",1,31),{hours:f,minutes:o,seconds:c,fractionalMilliseconds:h}))}if(n=aS.exec(t),n){let[s,r,e,i,f,o,c,h]=n;return Qr(qs(Cs(h)),Of(r),sn(e.trimLeft(),"day",1,31),{hours:i,minutes:f,seconds:o,fractionalMilliseconds:c})}throw TypeError("Invalid RFC-7231 date-time value")},VS=(t)=>{if(t===null||t===void 0)return;let n;if(typeof t==="number")n=t;else if(typeof t==="string")n=Df(t);else if(typeof t==="object"&&t.tag===1)n=t.value;else throw TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");if(Number.isNaN(n)||n===1/0||n===-1/0)throw TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(n*1000))},Qr=(t,n,s,r)=>{let e=n-1;return t5(t,e,s),new Date(Date.UTC(t,e,s,sn(r.hours,"hour",0,23),sn(r.minutes,"minute",0,59),sn(r.seconds,"seconds",0,60),s5(r.fractionalMilliseconds)))},jS=(t)=>{let n=new Date().getUTCFullYear(),s=Math.floor(n/100)*100+qs(Cs(t));if(s<n)return s+100;return s},pS=1576800000000,vS=(t)=>{if(t.getTime()-new Date().getTime()>pS)return new Date(Date.UTC(t.getUTCFullYear()-100,t.getUTCMonth(),t.getUTCDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds(),t.getUTCMilliseconds()));return t},Of=(t)=>{let n=Yf.indexOf(t);if(n<0)throw TypeError(`Invalid month: ${t}`);return n+1},ZS=[31,28,31,30,31,30,31,31,30,31,30,31],t5=(t,n,s)=>{let r=ZS[n];if(n===1&&n5(t))r=29;if(s>r)throw TypeError(`Invalid day for ${Yf[n]} in ${t}: ${s}`)},n5=(t)=>{return t%4===0&&(t%100!==0||t%400===0)},sn=(t,n,s,r)=>{let e=y0(Cs(t));if(e<s||e>r)throw TypeError(`${n} must be between ${s} and ${r}, inclusive`);return e},s5=(t)=>{if(t===null||t===void 0)return 0;return L0("0."+t)*1000},r5=(t)=>{let n=t[0],s=1;if(n=="+")s=1;else if(n=="-")s=-1;else throw TypeError(`Offset direction, ${n}, must be "+" or "-"`);let r=Number(t.substring(1,3)),e=Number(t.substring(4,6));return s*(r*60+e)*60*1000},Cs=(t)=>{let n=0;while(n<t.length-1&&t.charAt(n)==="0")n++;if(n===0)return t;return t.slice(n)},cs=function(n){return Object.assign(new String(n),{deserializeJSON(){return JSON.parse(String(n))},toString(){return String(n)},toJSON(){return String(n)}})};cs.from=(t)=>{if(t&&typeof t==="object"&&(t instanceof cs||("deserializeJSON"in t)))return t;else if(typeof t==="string"||Object.getPrototypeOf(t)===String.prototype)return cs(String(t));return cs(JSON.stringify(t))};cs.fromObject=cs.from;function e5(t){if(t.includes(",")||t.includes('"'))t=`"${t.replace(/"/g,"\\\"")}"`;return t}var xf="(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?",Qf="(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)",Jf="(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?",G0="(\\d?\\d)",B0="(\\d{4})",i5=new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/),o5=new RegExp(`^${xf}, ${G0} ${Qf} ${B0} ${Jf} GMT$`),f5=new RegExp(`^${xf}, ${G0}-${Qf}-(\\d\\d) ${Jf} GMT$`),c5=new RegExp(`^${xf} ${Qf} ( [1-9]|\\d\\d) ${Jf} ${B0}$`),h5=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],u5=(t)=>{if(t==null)return;let n=NaN;if(typeof t==="number")n=t;else if(typeof t==="string"){if(!/^-?\d*\.?\d+$/.test(t))throw TypeError("parseEpochTimestamp - numeric string invalid.");n=Number.parseFloat(t)}else if(typeof t==="object"&&t.tag===1)n=t.value;if(isNaN(n)||Math.abs(n)===1/0)throw TypeError("Epoch timestamps must be valid finite numbers.");return new Date(Math.round(n*1000))},l5=(t)=>{if(t==null)return;if(typeof t!=="string")throw TypeError("RFC3339 timestamps must be strings");let n=i5.exec(t);if(!n)throw TypeError(`Invalid RFC3339 timestamp format ${t}`);let[,s,r,e,i,f,o,,c,h]=n;bn(r,1,12),bn(e,1,31),bn(i,0,23),bn(f,0,59),bn(o,0,60);let u=new Date(Date.UTC(Number(s),Number(r)-1,Number(e),Number(i),Number(f),Number(o),Number(c)?Math.round(parseFloat(`0.${c}`)*1000):0));if(u.setUTCFullYear(Number(s)),h.toUpperCase()!="Z"){let[,l,_,w]=/([+-])(\d\d):(\d\d)/.exec(h)||[void 0,"+",0,0],A=l==="-"?1:-1;u.setTime(u.getTime()+A*(Number(_)*60*60*1000+Number(w)*60*1000))}return u},_5=(t)=>{if(t==null)return;if(typeof t!=="string")throw TypeError("RFC7231 timestamps must be strings.");let n,s,r,e,i,f,o,c;if(c=o5.exec(t))[,n,s,r,e,i,f,o]=c;else if(c=f5.exec(t))[,n,s,r,e,i,f,o]=c,r=(Number(r)+1900).toString();else if(c=c5.exec(t))[,s,n,e,i,f,o,r]=c;if(r&&f){let h=Date.UTC(Number(r),h5.indexOf(s),Number(n),Number(e),Number(i),Number(f),o?Math.round(parseFloat(`0.${o}`)*1000):0);bn(n,1,31),bn(e,0,23),bn(i,0,59),bn(f,0,60);let u=new Date(h);return u.setUTCFullYear(Number(r)),u}throw TypeError(`Invalid RFC7231 date-time value ${t}.`)};function bn(t,n,s){let r=Number(t);if(r<n||r>s)throw Error(`Value ${r} out of range [${n}, ${s}]`)}function w5(t,n,s){if(s<=0||!Number.isInteger(s))throw Error("Invalid number of delimiters ("+s+") for splitEvery.");let r=t.split(n);if(s===1)return r;let e=[],i="";for(let f=0;f<r.length;f++){if(i==="")i=r[f];else i+=n+r[f];if((f+1)%s===0)e.push(i),i=""}if(i!=="")e.push(i);return e}var A5=(t)=>{let n=t.length,s=[],r=!1,e=void 0,i=0;for(let f=0;f<n;++f){let o=t[f];switch(o){case'"':if(e!=="\\")r=!r;break;case",":if(!r)s.push(t.slice(i,f)),i=f+1;break}e=o}return s.push(t.slice(i)),s.map((f)=>{f=f.trim();let o=f.length;if(o<2)return f;if(f[0]==='"'&&f[o-1]==='"')f=f.slice(1,o-1);return f.replace(/\\"/g,'"')})},A0=/^-?\d*(\.\d+)?$/;class ci{string;type;constructor(t,n){if(this.string=t,this.type=n,!A0.test(t))throw Error('@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".')}toString(){return this.string}static[Symbol.hasInstance](t){if(!t||typeof t!=="object")return!1;let n=t;return ci.prototype.isPrototypeOf(t)||n.type==="bigDecimal"&&A0.test(n.string)}}function M5(t){return new ci(String(t),"bigDecimal")}var m0={},Pf={};for(let t=0;t<256;t++){let n=t.toString(16).toLowerCase();if(n.length===1)n=`0${n}`;m0[t]=n,Pf[n]=t}function d5(t){if(t.length%2!==0)throw Error("Hex encoded strings must have an even number length");let n=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2){let r=t.slice(s,s+2).toLowerCase();if(r in Pf)n[s/2]=Pf[r];else throw Error(`Cannot decode unrecognized sequence ${r} as hexadecimal`)}return n}function F0(t){let n="";for(let s=0;s<t.byteLength;s++)n+=m0[t[s]];return n}var g5=(t)=>{if(!t)return 0;if(typeof t==="string")return Buffer.byteLength(t);else if(typeof t.byteLength==="number")return t.byteLength;else if(typeof t.size==="number")return t.size;else if(typeof t.start==="number"&&typeof t.end==="number")return t.end+1-t.start;else if(t instanceof MS){if(t.path!=null)return dS(t.path).size;else if(typeof t.fd==="number")return gS(t.fd).size}throw Error(`Body Length computation failed for ${t}`)},P0=(t)=>{if(t instanceof Uint8Array)return t;if(typeof t==="string")return fi(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength/Uint8Array.BYTES_PER_ELEMENT);return new Uint8Array(t)};function hi(t,n){if(n===void 0){n=0;for(let e of t)n+=e.byteLength}let s=new Uint8Array(n),r=0;for(let e of t)s.set(e,r),r+=e.byteLength;return s}var H0=(t,n)=>(s,r)=>async(e)=>{let{response:i}=await s(e);try{let f=await n(i,t);return{response:i,output:f}}catch(f){if(Object.defineProperty(f,"$response",{value:i,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in f)){try{f.message+=`
|
|
11
|
+
Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`}catch(c){if(!r.logger||r.logger?.constructor?.name==="NoOpLogger")console.warn("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.");else r.logger?.warn?.("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.")}if(typeof f.$responseBodyText<"u"){if(f.$response)f.$response.body=f.$responseBodyText}try{if(ES.isInstance(i)){let{headers:c={}}=i,h=Object.entries(c);f.$metadata={httpStatusCode:i.statusCode,requestId:yf(/^x-[\w-]+-request-?id$/,h),extendedRequestId:yf(/^x-[\w-]+-id-2$/,h),cfId:yf(/^x-[\w-]+-cf-id$/,h)}}}catch(c){}}throw f}},yf=(t,n)=>{return(n.find(([s])=>{return s.match(t)})||[void 0,void 0])[1]},N0=(t,n)=>(s,r)=>async(e)=>{let i=t,f=r.endpointV2?async()=>RS(r.endpointV2):i.endpoint;if(!f)throw Error("No valid endpoint provider available.");let o=await n(e.input,{...t,endpoint:f});return s({...e,request:o})},D0={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},W0={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function E5(t,n,s){return{applyToStack:(r)=>{r.add(H0(t,s),D0),r.add(N0(t,n),W0)}}}class Y0{algorithmIdentifier;secret;hash;constructor(t,n){this.algorithmIdentifier=t,this.secret=n,this.reset()}update(t,n){this.hash.update(P0(M0(t,n)))}digest(){return Promise.resolve(this.hash.digest())}reset(){this.hash=this.secret?_S(this.algorithmIdentifier,M0(this.secret)):wS(this.algorithmIdentifier)}}function M0(t,n){if(Buffer.isBuffer(t))return t;if(typeof t==="string")return oi(t,n);if(ArrayBuffer.isView(t))return Xs(t.buffer,t.byteOffset,t.byteLength);return Xs(t)}var x0=class extends zs{expectedChecksum;checksumSourceLocation;checksum;source;base64Encoder;constructor({expectedChecksum:n,checksum:s,source:r,checksumSourceLocation:e,base64Encoder:i}){super();if(typeof r.pipe!=="function")throw Error(`@smithy/util-stream: unsupported source type ${r?.constructor?.name??r} in ChecksumStream.`);this.source=r,this.base64Encoder=i??Hf,this.expectedChecksum=n,this.checksum=s,this.checksumSourceLocation=e,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=(n)=>{if(this.destroyed)return;try{this.checksum.update(n)}catch(s){this.destroy(s);return}if(!this.push(n))this.source.pause()};onSourceEnd=async()=>{if(this.destroyed)return;try{let n=await this.checksum.digest(),s=this.base64Encoder(n);if(this.expectedChecksum!==s){this.destroy(Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${s}" in response header "${this.checksumSourceLocation}".`));return}}catch(n){this.destroy(n);return}this.push(null)};onSourceError=(n)=>{this.destroy(n)};onSourceClose=()=>{if(!this.destroyed&&!this.source.readableEnded)this.destroy(Error("Connection lost or stream closed before all data was received."))};_read(n){this.source.resume()}_destroy(n,s){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(),s(n)}},rn=(t)=>typeof ReadableStream==="function"&&(t?.constructor?.name===ReadableStream.name||t instanceof ReadableStream),ui=(t)=>{return typeof Blob==="function"&&(t?.constructor?.name===Blob.name||t instanceof Blob)},R5=(t)=>new TextEncoder().encode(t),Q0="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";Object.entries(Q0).reduce((t,[n,s])=>{return t[s]=Number(n),t},{});var b5=Q0.split(""),Gf=6,d0=8,T5=63;function J0(t){let n;if(typeof t==="string")n=R5(t);else n=t;let s=typeof n==="object"&&typeof n.length==="number",r=typeof n==="object"&&typeof n.byteOffset==="number"&&typeof n.byteLength==="number";if(!s&&!r)throw Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");let e="";for(let i=0;i<n.length;i+=3){let f=0,o=0;for(let h=i,u=Math.min(i+3,n.length);h<u;h++)f|=n[h]<<(u-h-1)*d0,o+=d0;let c=Math.ceil(o/Gf);f<<=c*Gf-o;for(let h=1;h<=c;h++){let u=(c-h)*Gf;e+=b5[(f&T5<<u)>>u]}e+="==".slice(0,4-c)}return e}var S5=typeof ReadableStream==="function"?ReadableStream:function(){};class z0 extends S5{}var $5=({expectedChecksum:t,checksum:n,source:s,checksumSourceLocation:r,base64Encoder:e})=>{if(!rn(s))throw Error(`@smithy/util-stream: unsupported source type ${s?.constructor?.name??s} in ChecksumStream.`);let i=e??J0;if(typeof TransformStream!=="function")throw Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream.");let f=new TransformStream({start(){},async transform(c,h){n.update(c),h.enqueue(c)},async flush(c){let h=await n.digest(),u=i(h);if(t!==u){let l=Error(`Checksum mismatch: expected "${t}" but received "${u}" in response header "${r}".`);c.error(l)}else c.terminate()}});s.pipeThrough(f);let o=f.readable;return Object.setPrototypeOf(o,z0.prototype),o};function U5(t){if(typeof ReadableStream==="function"&&rn(t.source))return $5(t);return new x0(t)}class ii{allocByteArray;byteLength=0;byteArrays=[];constructor(t){this.allocByteArray=t}push(t){this.byteArrays.push(t),this.byteLength+=t.byteLength}flush(){if(this.byteArrays.length===1){let s=this.byteArrays[0];return this.reset(),s}let t=this.allocByteArray(this.byteLength),n=0;for(let s=0;s<this.byteArrays.length;++s){let r=this.byteArrays[s];t.set(r,n),n+=r.byteLength}return this.reset(),t}reset(){this.byteArrays=[],this.byteLength=0}}function L5(t,n,s){let r=t.getReader(),e=!1,i=0,f=["",new ii((h)=>new Uint8Array(h))],o=-1,c=async(h)=>{let{value:u,done:l}=await r.read(),_=u;if(l){if(o!==-1){let w=ks(f,o);if(Dn(w)>0)h.enqueue(w)}h.close()}else{let w=X0(_,!1);if(o!==w){if(o>=0)h.enqueue(ks(f,o));o=w}if(o===-1){h.enqueue(_);return}let A=Dn(_);i+=A;let M=Dn(f[o]);if(A>=n&&M===0)h.enqueue(_);else{let d=k0(f,o,_);if(!e&&i>n*2)e=!0,s?.warn(`@smithy/util-stream - stream chunk size ${A} is below threshold of ${n}, automatically buffering.`);if(d>=n)h.enqueue(ks(f,o));else await c(h)}}};return new ReadableStream({pull:c})}function k0(t,n,s){switch(n){case 0:return t[0]+=s,Dn(t[0]);case 1:case 2:return t[n].push(s),Dn(t[n])}}function ks(t,n){switch(n){case 0:let s=t[0];return t[0]="",s;case 1:case 2:return t[n].flush()}throw Error(`@smithy/util-stream - invalid index ${n} given to flush()`)}function Dn(t){return t?.byteLength??t?.length??0}function X0(t,n=!0){if(n&&typeof Buffer<"u"&&t instanceof Buffer)return 2;if(t instanceof Uint8Array)return 1;if(typeof t==="string")return 0;return-1}function I5(t,n,s){if(rn(t))return L5(t,n,s);let r=new zs({read(){}}),e=!1,i=0,f=["",new ii((c)=>new Uint8Array(c)),new ii((c)=>Buffer.from(new Uint8Array(c)))],o=-1;return t.on("data",(c)=>{let h=X0(c,!0);if(o!==h){if(o>=0)r.push(ks(f,o));o=h}if(o===-1){r.push(c);return}let u=Dn(c);i+=u;let l=Dn(f[o]);if(u>=n&&l===0)r.push(c);else{let _=k0(f,o,c);if(!e&&i>n*2)e=!0,s?.warn(`@smithy/util-stream - stream chunk size ${u} is below threshold of ${n}, automatically buffering.`);if(_>=n)r.push(ks(f,o))}}),t.on("end",()=>{if(o!==-1){let c=ks(f,o);if(Dn(c)>0)r.push(c)}r.push(null)}),r}var O5=(t,n)=>{let{base64Encoder:s,bodyLengthChecker:r,checksumAlgorithmFn:e,checksumLocationName:i,streamHasher:f}=n,o=s!==void 0&&r!==void 0&&e!==void 0&&i!==void 0&&f!==void 0,c=o?f(e,t):void 0,h=t.getReader();return new ReadableStream({async pull(u){let{value:l,done:_}=await h.read();if(_){if(u.enqueue(`0\r
|
|
12
|
+
`),o){let w=s(await c);u.enqueue(`${i}:${w}\r
|
|
13
|
+
`),u.enqueue(`\r
|
|
14
|
+
`)}u.close()}else u.enqueue(`${(r(l)||0).toString(16)}\r
|
|
15
|
+
${l}\r
|
|
16
|
+
`)}})};function y5(t,n){let s=t,r=t;if(rn(r))return O5(r,n);let{base64Encoder:e,bodyLengthChecker:i,checksumAlgorithmFn:f,checksumLocationName:o,streamHasher:c}=n,h=e!==void 0&&f!==void 0&&o!==void 0&&c!==void 0,u=h?c(f,s):void 0,l=new zs({read:()=>{}});return s.on("data",(_)=>{let w=i(_)||0;if(w===0)return;l.push(`${w.toString(16)}\r
|
|
17
|
+
`),l.push(_),l.push(`\r
|
|
18
|
+
`)}),s.on("end",async()=>{if(l.push(`0\r
|
|
19
|
+
`),h){let _=e(await u);l.push(`${o}:${_}\r
|
|
20
|
+
`),l.push(`\r
|
|
21
|
+
`)}l.push(null)}),l}async function G5(t,n){let s=0,r=[],e=t.getReader(),i=!1;while(!i){let{done:c,value:h}=await e.read();if(h)r.push(h),s+=h?.byteLength??0;if(s>=n)break;i=c}e.releaseLock();let f=new Uint8Array(Math.min(n,s)),o=0;for(let c of r){if(c.byteLength>f.byteLength-o){f.set(c.subarray(0,f.byteLength-o),o);break}else f.set(c,o);o+=c.length}return f}var B5=(t,n)=>{if(rn(t))return G5(t,n);return new Promise((s,r)=>{let e=new m5;e.limit=n,t.pipe(e),t.on("error",(i)=>{e.end(),r(i)}),e.on("error",r),e.on("finish",function(){let i=hi(this.buffers);s(i)})})},m5=class extends b0{buffers=[];limit=1/0;bytesBuffered=0;_write(n,s,r){if(this.buffers.push(n),this.bytesBuffered+=n.byteLength??0,this.bytesBuffered>=this.limit){let e=this.bytesBuffered-this.limit,i=this.buffers[this.buffers.length-1];this.buffers[this.buffers.length-1]=i.subarray(0,i.byteLength-e),this.emit("finish")}r()}},F5=(t)=>{if(typeof t==="string")return t;if(typeof t!=="object"||typeof t.byteOffset!=="number"||typeof t.byteLength!=="number")throw Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return new TextDecoder("utf-8").decode(t)},P5=async(t)=>{if(ui(t))return q0(t);return C0(t)};async function q0(t){return t.arrayBuffer().then((n)=>new Uint8Array(n))}async function C0(t){let n=[],s=t.getReader(),r=0;while(!0){let{done:e,value:i}=await s.read();if(i)n.push(i),r+=i.length;if(e)break}return hi(n,r)}var g0="The stream has already been transformed.",H5=(t)=>{if(!E0(t)&&!rn(t)){let e=t?.__proto__?.constructor?.name||t;throw Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${e}`)}let n=!1,s=async()=>{if(n)throw Error(g0);return n=!0,await P5(t)},r=(e)=>{if(typeof e.stream!=="function")throw Error(`Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.
|
|
22
|
+
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 e.stream()};return Object.assign(t,{transformToByteArray:s,transformToString:async(e)=>{let i=await s();if(e==="base64")return J0(i);else if(e==="hex")return F0(i);else if(e===void 0||e==="utf8"||e==="utf-8")return F5(i);else if(typeof TextDecoder==="function")return new TextDecoder(e).decode(i);else throw Error("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(n)throw Error(g0);if(n=!0,E0(t))return r(t);else if(rn(t))return t;else throw Error(`Cannot transform payload to web stream, got ${t}`)}})},E0=(t)=>typeof Blob==="function"&&t instanceof Blob,a0=(t)=>{if(ui(t))return q0(t);if(rn(t))return C0(t);return new Promise((n,s)=>{let r=new K0,e=t;e.pipe(r),e.on("error",(i)=>{r.end(),s(i)}),r.on("error",s),r.on("finish",function(){let i=hi(this.bufferedBytes);n(i)})})};class K0 extends b0{bufferedBytes=[];_write(t,n,s){this.bufferedBytes.push(t),s()}}var R0="The stream has already been transformed.",N5=(t)=>{if(!(t instanceof zs))try{return H5(t)}catch(r){let e=t?.__proto__?.constructor?.name||t;throw Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${e}`)}let n=!1,s=async()=>{if(n)throw Error(R0);return n=!0,await a0(t)};return Object.assign(t,{transformToByteArray:s,transformToString:async(r)=>{let e=await s();if(r===void 0||Buffer.isEncoding(r))return Xs(e.buffer,e.byteOffset,e.byteLength).toString(r);else return new TextDecoder(r).decode(e)},transformToWebStream:()=>{if(n)throw Error(R0);if(t.readableFlowing!==null)throw Error("The stream has been consumed by other callbacks.");if(typeof zs.toWeb!=="function")throw Error("Readable.toWeb() is not supported. Please ensure a polyfill is available.");return n=!0,zs.toWeb(t)}})};async function D5(t){if(typeof t.stream==="function")t=t.stream();return t.tee()}async function W5(t){if(rn(t)||ui(t))return D5(t);let n=new w0,s=new w0;return t.pipe(n),t.pipe(s),[n,s]}class V0 extends TS($0,fi,Hf,S0){}var Y5=AS,j0=SS(Y5),x5=j0;Q5.ChecksumStream=x0;Q5.Hash=Y0;Q5.LazyJsonString=cs;Q5.NumericValue=ci;Q5.Uint8ArrayBlobAdapter=V0;Q5._parseEpochTimestamp=u5;Q5._parseRfc3339DateTimeWithOffset=l5;Q5._parseRfc7231DateTime=_5;Q5.calculateBodyLength=g5;Q5.concatBytes=hi;Q5.copyDocumentWithTransform=$S;Q5.createBufferedReadable=I5;Q5.createChecksumStream=U5;Q5.dateToUtcString=QS;Q5.deserializerMiddleware=H0;Q5.deserializerMiddlewareOption=D0;Q5.expectBoolean=LS;Q5.expectByte=Ff;Q5.expectFloat32=ri;Q5.expectInt=OS;Q5.expectInt32=Bf;Q5.expectLong=zr;Q5.expectNonNull=GS;Q5.expectNumber=Jr;Q5.expectObject=U0;Q5.expectShort=mf;Q5.expectString=BS;Q5.expectUnion=mS;Q5.fromArrayBuffer=Xs;Q5.fromBase64=S0;Q5.fromHex=d5;Q5.fromString=oi;Q5.fromUtf8=fi;Q5.generateIdempotencyToken=x5;Q5.getAwsChunkedEncodingStream=y5;Q5.getSerdePlugin=E5;Q5.handleFloat=HS;Q5.headStream=B5;Q5.isArrayBuffer=T0;Q5.isBlob=ui;Q5.isReadableStream=rn;Q5.limitedParseDouble=Wf;Q5.limitedParseFloat=NS;Q5.limitedParseFloat32=DS;Q5.logger=kr;Q5.nv=M5;Q5.parseBoolean=US;Q5.parseEpochTimestamp=VS;Q5.parseRfc3339DateTime=zS;Q5.parseRfc3339DateTimeWithOffset=XS;Q5.parseRfc7231DateTime=KS;Q5.quoteHeader=e5;Q5.sdkStreamMixin=N5;Q5.serializerMiddleware=N0;Q5.serializerMiddlewareOption=W0;Q5.splitEvery=w5;Q5.splitHeader=A5;Q5.splitStream=W5;Q5.streamCollector=a0;Q5.strictParseByte=y0;Q5.strictParseDouble=Df;Q5.strictParseFloat=FS;Q5.strictParseFloat32=L0;Q5.strictParseInt=WS;Q5.strictParseInt32=YS;Q5.strictParseLong=O0;Q5.strictParseShort=qs;Q5.toBase64=Hf;Q5.toHex=F0;Q5.toUint8Array=P0;Q5.toUtf8=$0;Q5.v4=j0});var af=K((O$)=>{var{createReadStream:i$}=j("fs"),{Writable:o$}=j("stream"),{toUint8Array:Ks,concatBytes:f$}=bt(),{createHash:Xr,createHmac:c$}=j("crypto"),p0=j("zlib");async function s_(t,n,s=1048576){let r=t.size,e=0;while(e<r){let i=t.slice(e,Math.min(r,e+s));n(new Uint8Array(await i.arrayBuffer())),e+=i.size}}var h$=async function(n,s){let r=new n;return await s_(s,(e)=>{r.update(e)}),r.digest()};class Xf extends o${hash;constructor(t,n){super(n);this.hash=t}_write(t,n,s){try{this.hash.update(Ks(t))}catch(r){return s(r)}s()}}var u$=(t,n)=>new Promise((s,r)=>{if(!l$(n)){r(Error("Unable to calculate hash for non-file streams."));return}let e=i$(n.path,{start:n.start,end:n.end}),i=new t,f=new Xf(i);e.pipe(f),e.on("error",(o)=>{f.end(),r(o)}),f.on("error",r),f.on("finish",function(){i.digest().then(s).catch(r)})}),l$=(t)=>typeof t.path==="string",_$=(t,n)=>{if(n.readableFlowing!==null)throw Error("Unable to calculate hash for flowing readable stream");let s=new t,r=new Xf(s);return n.pipe(r),new Promise((e,i)=>{n.on("error",(f)=>{r.end(),i(f)}),r.on("error",i),r.on("finish",()=>{s.digest().then(e).catch(i)})})};class qf{digestLength=16;state=Uint32Array.from(v0);writeBuffer=new DataView(new ArrayBuffer(64));bufferLength=0;bytesHashed=0;update(t){let n=Ks(t),s=0,r=n.byteLength;this.bytesHashed+=r;while(r>0)if(this.writeBuffer.setUint8(this.bufferLength++,n[s++]),--r,this.bufferLength===64)zf(this.state,this.writeBuffer),this.bufferLength=0}async digest(){let t=Uint32Array.from(this.state),n=new DataView(this.writeBuffer.buffer.slice(0)),s=this.bufferLength,r=this.bytesHashed*8;if(n.setUint8(s++,128),this.bufferLength%64>=56){for(let f=s;f<64;++f)n.setUint8(f,0);zf(t,n),s=0}for(let f=s;f<56;++f)n.setUint8(f,0);n.setUint32(56,r>>>0,!0),n.setUint32(60,Math.floor(r/4294967296),!0),zf(t,n);let e=new Uint8Array(16),i=new DataView(e.buffer);for(let f=0;f<4;++f)i.setUint32(f*4,t[f],!0);return e}reset(){this.state.set(v0),this.writeBuffer=new DataView(new ArrayBuffer(64)),this.bufferLength=0,this.bytesHashed=0}}var v0=[1732584193,4023233417,2562383102,271733878],Wn=4294967295,w$=Uint8Array.of(7,12,17,22,5,9,14,20,4,11,16,23,6,10,15,21),A$=Array.from({length:64},(t,n)=>Math.abs(Math.sin(n+1))*4294967296>>>0);function zf(t,n){let s=t[0],r=t[1],e=t[2],i=t[3];for(let f=0;f<64;++f){let o,c;if(f<16)o=r&e|~r&i,c=f;else if(f<32)o=i&r|e&~i,c=(5*f+1)%16;else if(f<48)o=r^e^i,c=(3*f+5)%16;else o=e^(r|~i),c=7*f%16;let h=n.getUint32(c*4,!0),u=i;i=e,e=r;let l=w$[(f>>4)*4+(f&3)],_=(s+o&Wn)+(h+A$[f]&Wn)&Wn;r=r+((_<<l|_>>>32-l)>>>0)&Wn,s=u}t[0]=t[0]+s&Wn,t[1]=t[1]+r&Wn,t[2]=t[2]+e&Wn,t[3]=t[3]+i&Wn}var M$=(()=>{try{return Xr("md5"),!0}catch{return!1}})(),r_=M$?d$():qf;function d$(){return class{digestLength=16;hash=Xr("md5");update(n){this.hash.update(Ks(n))}async digest(){let n=this.hash.copy().digest();return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}reset(){this.hash=Xr("md5")}}}var e_=new Uint32Array(256);for(let t=0;t<256;++t){let n=t;for(let s=0;s<8;++s)n=n&1?3988292384^n>>>1:n>>>1;e_[t]=n>>>0}var kf=4294967295;class Cf{digestLength=4;checksum=kf;update(t){for(let n=0;n<t.length;++n)this.checksum=this.checksum>>>8^e_[(this.checksum^t[n])&255]}digestSync(){return(this.checksum^kf)>>>0}async digest(){let t=this.digestSync(),n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t,!1),n}reset(){this.checksum=kf}}var Z0=typeof p0.crc32==="function"?p0.crc32:void 0,i_=Z0?g$(Z0):Cf;function g$(t){return class{digestLength=4;value=0;update(s){this.value=t(s,this.value)}digestSync(){return this.value>>>0}async digest(){let s=new Uint8Array(4);return new DataView(s.buffer).setUint32(0,this.digestSync(),!1),s}reset(){this.value=0}}}var lt=64,t_=32,E$=9007199254740991;class Tn{digestLength=t_;state=Int32Array.from(n_);w;buffer=new Uint8Array(64);bufferLength=0;bytesHashed=0;finished=!1;inner;outer;constructor(t){if(t){let n=Tn.normalizeKey(t);this.inner=new Tn,this.outer=new Tn;let{inner:s,outer:r}=this,e=new Uint8Array(lt*2);for(let i=0;i<lt;++i)e[i]=54^n[i],e[i+lt]=92^n[i];s.update(e.subarray(0,lt)),r.update(e.subarray(lt))}}update(t){if(this.finished)throw Error("Attempted to update an already finished HMAC.");if(this.inner){this.inner.update(t);return}let n=Ks(t),s=0,{byteLength:r}=n;if(this.bytesHashed+=r,this.bytesHashed*8>E$)throw Error("Cannot hash more than 2^53 - 1 bits");while(r>0)if(this.buffer[this.bufferLength++]=n[s++],r--,this.bufferLength===lt)this.hashBuffer(),this.bufferLength=0}async digest(){let{inner:t,outer:n}=this;if(t&&n){if(this.finished)throw Error("Attempted to digest an already finished HMAC.");this.finished=!0;let s=t.digestSync();return n.update(s),n.digestSync()}return this.digestSync()}reset(){this.state=Int32Array.from(n_),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0}digestSync(){let t=this.state.slice(),n=this.buffer.slice(),s=this.bufferLength,r=this.bytesHashed*8,e=new DataView(n.buffer,n.byteOffset,n.byteLength);if(e.setUint8(s++,128),(s-1)%lt>=lt-8){for(let f=s;f<lt;++f)e.setUint8(f,0);this.hashBufferWith(t,n),s=0}for(let f=s;f<lt-8;++f)e.setUint8(f,0);e.setUint32(lt-8,Math.floor(r/4294967296),!1),e.setUint32(lt-4,r,!1),this.hashBufferWith(t,n);let i=new Uint8Array(t_);for(let f=0;f<8;++f)i[f*4]=t[f]>>>24&255,i[f*4+1]=t[f]>>>16&255,i[f*4+2]=t[f]>>>8&255,i[f*4+3]=t[f]>>>0&255;return i}static normalizeKey(t){let n=Ks(t);if(n.byteLength>lt){let s=new Tn;s.update(n);let r=s.digestSync(),e=new Uint8Array(lt);return e.set(r),e}if(n.byteLength<lt){let s=new Uint8Array(lt);return s.set(n),s}return n}hashBuffer(){this.hashBufferWith(this.state,this.buffer)}hashBufferWith(t,n){let s=this.w??=new Int32Array(64),r=t[0],e=t[1],i=t[2],f=t[3],o=t[4],c=t[5],h=t[6],u=t[7];for(let l=0;l<lt;++l){if(l<16)s[l]=(n[l*4]&255)<<24|(n[l*4+1]&255)<<16|(n[l*4+2]&255)<<8|n[l*4+3]&255;else{let A=s[l-2],M=(A>>>17|A<<15)^(A>>>19|A<<13)^A>>>10;A=s[l-15];let d=(A>>>7|A<<25)^(A>>>18|A<<14)^A>>>3;s[l]=(M+s[l-7]|0)+(d+s[l-16]|0)}let _=(((o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7))+(o&c^~o&h)|0)+(u+(R$[l]+s[l]|0)|0)|0,w=((r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10))+(r&e^r&i^e&i)|0;u=h,h=c,c=o,o=f+_|0,f=i,i=e,e=r,r=_+w|0}t[0]+=r,t[1]+=e,t[2]+=i,t[3]+=f,t[4]+=o,t[5]+=c,t[6]+=h,t[7]+=u}}var n_=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),R$=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]),b$=(()=>{try{return Xr("sha256"),!0}catch{return!1}})(),o_=b$?T$():Tn;function T$(){return class{digestLength=32;secret;hash;isHmac;finished=!1;constructor(n){this.secret=n,this.isHmac=!!n,this.hash=this.createHash()}update(n){if(this.finished)throw Error("Attempted to update an already finished hash.");this.hash.update(n)}async digest(){let n;if(this.isHmac)this.finished=!0,n=this.hash.digest();else n=this.hash.copy().digest();return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}reset(){this.hash=this.createHash(),this.finished=!1}createHash(){return this.secret?c$("sha256",S$(this.secret)):Xr("sha256")}}}function S$(t){if(typeof t==="string")return t;if(ArrayBuffer.isView(t))return Buffer.from(t.buffer,t.byteOffset,t.byteLength);return Buffer.from(t)}var{digest:$$,sign:U$,importKey:L$}=globalThis?.crypto?.subtle??{},li=typeof $$==="function"&&typeof U$==="function"&&typeof L$==="function"?globalThis.crypto.subtle:void 0,I$=8388608;class f_{digestLength=32;secret;pending=[];pendingBytes=0;fallback;finished=!1;constructor(t){if(t)this.secret=Ks(t)}update(t){if(this.finished)throw Error("Attempted to update an already finished HMAC.");if(this.fallback){this.fallback.update(t);return}if(this.pending.push(t.slice()),this.pendingBytes+=t.byteLength,this.pendingBytes>=I$)this.switchToFallback()}async digest(){if(this.fallback)return this.fallback.digest();if(this.secret&&this.finished)throw Error("Attempted to digest an already finished HMAC.");let t=f$(this.pending);if(li){if(this.secret){this.finished=!0;let r=await li.importKey("raw",this.secret,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),e=await li.sign("HMAC",r,t);return new Uint8Array(e)}let s=await li.digest("SHA-256",t);return new Uint8Array(s)}let n=new Tn(this.secret);return n.update(t),n.digest()}reset(){this.pending=[],this.pendingBytes=0,this.fallback=void 0,this.finished=!1}switchToFallback(){let t=new Tn(this.secret);for(let n of this.pending)t.update(n);this.fallback=t,this.pending=[],this.pendingBytes=0}}O$.Crc32=i_;O$.Crc32Js=Cf;O$.Crc32Node=i_;O$.Md5=r_;O$.Md5Js=qf;O$.Md5Node=r_;O$.Sha256=o_;O$.Sha256Js=Tn;O$.Sha256Node=o_;O$.Sha256WebCrypto=f_;O$.blobHasher=h$;O$.blobReader=s_;O$.fileStreamHasher=u$;O$.readableStreamHasher=_$});var _i=K((uU)=>{var{Crc32:u_}=af(),{toHex:Vs,fromHex:z$,toUtf8:k$,fromUtf8:X$}=bt(),{Readable:q$}=j("stream");class js{bytes;constructor(t){if(this.bytes=t,t.byteLength!==8)throw Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(t){if(t>9223372036854776000||t<-9223372036854776000)throw Error(`${t} is too large (or, if negative, too small) to represent as an Int64`);let n=new Uint8Array(8);for(let s=7,r=Math.abs(Math.round(t));s>-1&&r>0;s--,r/=256)n[s]=r;if(t<0)c_(n);return new js(n)}valueOf(){let t=this.bytes.slice(0),n=t[0]&128;if(n)c_(t);return parseInt(Vs(t),16)*(n?-1:1)}toString(){return String(this.valueOf())}}function c_(t){for(let n=0;n<8;n++)t[n]^=255;for(let n=7;n>-1;n--)if(t[n]++,t[n]!==0)break}class Kf{toUtf8;fromUtf8;constructor(t,n){this.toUtf8=t,this.fromUtf8=n}format(t){let n=[];for(let e of Object.keys(t)){let i=this.fromUtf8(e);n.push(Uint8Array.from([i.byteLength]),i,this.formatHeaderValue(t[e]))}let s=new Uint8Array(n.reduce((e,i)=>e+i.byteLength,0)),r=0;for(let e of n)s.set(e,r),r+=e.byteLength;return s}formatHeaderValue(t){switch(t.type){case"boolean":return Uint8Array.from([t.value?tt.boolTrue:tt.boolFalse]);case"byte":return Uint8Array.from([tt.byte,t.value]);case"short":let n=new DataView(new ArrayBuffer(3));return n.setUint8(0,tt.short),n.setInt16(1,t.value,!1),new Uint8Array(n.buffer);case"integer":let s=new DataView(new ArrayBuffer(5));return s.setUint8(0,tt.integer),s.setInt32(1,t.value,!1),new Uint8Array(s.buffer);case"long":let r=new Uint8Array(9);return r[0]=tt.long,r.set(t.value.bytes,1),r;case"binary":let e=new DataView(new ArrayBuffer(3+t.value.byteLength));e.setUint8(0,tt.byteArray),e.setUint16(1,t.value.byteLength,!1);let i=new Uint8Array(e.buffer);return i.set(t.value,3),i;case"string":let f=this.fromUtf8(t.value),o=new DataView(new ArrayBuffer(3+f.byteLength));o.setUint8(0,tt.string),o.setUint16(1,f.byteLength,!1);let c=new Uint8Array(o.buffer);return c.set(f,3),c;case"timestamp":let h=new Uint8Array(9);return h[0]=tt.timestamp,h.set(js.fromNumber(t.value.valueOf()).bytes,1),h;case"uuid":if(!tU.test(t.value))throw Error(`Invalid UUID received: ${t.value}`);let u=new Uint8Array(17);return u[0]=tt.uuid,u.set(z$(t.value.replace(/-/g,"")),1),u}}parse(t){let n={},s=0;while(s<t.byteLength){let r=t.getUint8(s++),e=this.toUtf8(new Uint8Array(t.buffer,t.byteOffset+s,r));switch(s+=r,t.getUint8(s++)){case tt.boolTrue:n[e]={type:h_,value:!0};break;case tt.boolFalse:n[e]={type:h_,value:!1};break;case tt.byte:n[e]={type:C$,value:t.getInt8(s++)};break;case tt.short:n[e]={type:a$,value:t.getInt16(s,!1)},s+=2;break;case tt.integer:n[e]={type:K$,value:t.getInt32(s,!1)},s+=4;break;case tt.long:n[e]={type:V$,value:new js(new Uint8Array(t.buffer,t.byteOffset+s,8))},s+=8;break;case tt.byteArray:let i=t.getUint16(s,!1);s+=2,n[e]={type:j$,value:new Uint8Array(t.buffer,t.byteOffset+s,i)},s+=i;break;case tt.string:let f=t.getUint16(s,!1);s+=2,n[e]={type:p$,value:this.toUtf8(new Uint8Array(t.buffer,t.byteOffset+s,f))},s+=f;break;case tt.timestamp:n[e]={type:v$,value:new Date(new js(new Uint8Array(t.buffer,t.byteOffset+s,8)).valueOf())},s+=8;break;case tt.uuid:let o=new Uint8Array(t.buffer,t.byteOffset+s,16);s+=16,n[e]={type:Z$,value:`${Vs(o.subarray(0,4))}-${Vs(o.subarray(4,6))}-${Vs(o.subarray(6,8))}-${Vs(o.subarray(8,10))}-${Vs(o.subarray(10))}`};break;default:throw Error("Unrecognized header type tag")}}return n}}var tt;(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"})(tt||(tt={}));var h_="boolean",C$="byte",a$="short",K$="integer",V$="long",j$="binary",p$="string",v$="timestamp",Z$="uuid",tU=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,l_=4,Yn=l_*2,hs=4,nU=Yn+hs*2;function sU({byteLength:t,byteOffset:n,buffer:s}){if(t<nU)throw Error("Provided message too short to accommodate event stream message overhead");let r=new DataView(s,n,t),e=r.getUint32(0,!1);if(t!==e)throw Error("Reported message length does not match received message length");let i=r.getUint32(l_,!1),f=r.getUint32(Yn,!1),o=r.getUint32(t-hs,!1),c=new u_;if(c.update(new Uint8Array(s,n,Yn)),f!==c.digestSync())throw Error(`The prelude checksum specified in the message (${f}) does not match the calculated CRC32 checksum (${c.digestSync()})`);if(c.update(new Uint8Array(s,n+Yn,t-(Yn+hs))),o!==c.digestSync())throw Error(`The message checksum (${c.digestSync()}) did not match the expected value of ${o}`);return{headers:new DataView(s,n+Yn+hs,i),body:new Uint8Array(s,n+Yn+hs+i,e-i-(Yn+hs+hs))}}class Vf{headerMarshaller;messageBuffer;isEndOfStream;constructor(t,n){this.headerMarshaller=new Kf(t,n),this.messageBuffer=[],this.isEndOfStream=!1}feed(t){this.messageBuffer.push(this.decode(t))}endOfStream(){this.isEndOfStream=!0}getMessage(){let t=this.messageBuffer.pop(),n=this.isEndOfStream;return{getMessage(){return t},isEndOfStream(){return n}}}getAvailableMessages(){let t=this.messageBuffer;this.messageBuffer=[];let n=this.isEndOfStream;return{getMessages(){return t},isEndOfStream(){return n}}}encode({headers:t,body:n}){let s=this.headerMarshaller.format(t),r=s.byteLength+n.byteLength+16,e=new Uint8Array(r),i=new DataView(e.buffer,e.byteOffset,e.byteLength),f=new u_;return i.setUint32(0,r,!1),i.setUint32(4,s.byteLength,!1),f.update(e.subarray(0,8)),i.setUint32(8,f.digestSync(),!1),e.set(s,12),e.set(n,s.byteLength+12),f.update(e.subarray(8,r-4)),i.setUint32(r-4,f.digestSync(),!1),e}decode(t){let{headers:n,body:s}=sU(t);return{headers:this.headerMarshaller.parse(n),body:s}}formatHeaders(t){return this.headerMarshaller.format(t)}}class jf{options;constructor(t){this.options=t}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let t of this.options.inputStream)yield this.options.decoder.decode(t)}}class pf{options;constructor(t){this.options=t}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let t of this.options.messageStream)yield this.options.encoder.encode(t);if(this.options.includeEndFrame)yield new Uint8Array(0)}}class vf{options;constructor(t){this.options=t}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let t of this.options.messageStream){let n=await this.options.deserializer(t);if(n===void 0)continue;yield n}}}class Zf{options;constructor(t){this.options=t}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let t of this.options.inputStream)yield this.options.serializer(t)}}function __(t){let n=0,s=0,r=null,e=null,i=(o)=>{if(typeof o!=="number")throw Error("Attempted to allocate an event message where size was not a number: "+o);n=o,s=4,r=new Uint8Array(o),new DataView(r.buffer).setUint32(0,o,!1)},f=async function*(){let o=t[Symbol.asyncIterator]();while(!0){let{value:c,done:h}=await o.next();if(h){if(!n)return;else if(n===s)yield r;else throw Error("Truncated event message received.");return}let u=c.length,l=0;while(l<u){if(!r){let w=u-l;if(!e)e=new Uint8Array(4);let A=Math.min(4-s,w);if(e.set(c.slice(l,l+A),s),s+=A,l+=A,s<4)break;i(new DataView(e.buffer).getUint32(0,!1)),e=null}let _=Math.min(n-s,u-l);if(r.set(c.slice(l,l+_),s),s+=_,l+=_,n&&n===s)yield r,r=null,n=0,s=0}}};return{[Symbol.asyncIterator]:f}}function rU(t,n){let s=tc(n.deserializer,n.toUtf8);return{[Symbol.asyncIterator]:async function*(){for await(let r of t){let e=n.eventStreamCodec.decode(r),i=await s(e);if(i===void 0)continue;yield i}}}}function tc(t,n){return async function(s){let{value:r}=s.headers[":message-type"];if(r==="error"){let e=Error(s.headers[":error-message"].value||"UnknownError");throw e.name=s.headers[":error-code"].value,e}else if(r==="exception"){let e=s.headers[":exception-type"].value,i={[e]:s},f=await t(i);if(f.$unknown){let o=Error(n(s.body));throw o.name=e,o}throw f[e]}else if(r==="event"){let e={[s.headers[":event-type"].value]:s},i=await t(e);if(i.$unknown)return;return i}else throw Error(`Unrecognizable event type: ${s.headers[":event-type"].value}`)}}var nc=class{eventStreamCodec;utfEncoder;constructor({utf8Encoder:n,utf8Decoder:s}){this.eventStreamCodec=new Vf(n,s),this.utfEncoder=n}deserialize(n,s){let r=__(n);return new vf({messageStream:new jf({inputStream:r,decoder:this.eventStreamCodec}),deserializer:tc(s,this.utfEncoder)})}serialize(n,s){return new pf({messageStream:new Zf({inputStream:n,serializer:s}),encoder:this.eventStreamCodec,includeEndFrame:!0})}},eU=(t)=>new nc(t);class sc{universalMarshaller;constructor({utf8Encoder:t,utf8Decoder:n}){this.universalMarshaller=new nc({utf8Decoder:n,utf8Encoder:t})}deserialize(t,n){let s=typeof t[Symbol.asyncIterator]==="function"?t:oU(t);return this.universalMarshaller.deserialize(s,n)}serialize(t,n){return q$.from(this.universalMarshaller.serialize(t,n))}}var iU=(t)=>new sc(t);async function*oU(t){let n=!1,s=!1,r=[];t.on("error",(e)=>{if(!n)n=!0;if(e)throw e}),t.on("data",(e)=>{r.push(e)}),t.on("end",()=>{n=!0});while(!s){let e=await new Promise((i)=>setTimeout(()=>i(r.shift()),0));if(e)yield e;s=n&&r.length===0}}var fU=(t)=>({[Symbol.asyncIterator]:async function*(){let n=t.getReader();try{while(!0){let{done:s,value:r}=await n.read();if(s)return;yield r}}finally{n.releaseLock()}}}),cU=(t)=>{let n=t[Symbol.asyncIterator]();return new ReadableStream({async pull(s){let{done:r,value:e}=await n.next();if(r)return s.close();s.enqueue(e)}})},hU=(t)=>Object.assign(t,{eventStreamMarshaller:t.eventStreamSerdeProvider(t)});class w_{marshaller;serializer;deserializer;serdeContext;defaultContentType;constructor({marshaller:t,serializer:n,deserializer:s,serdeContext:r,defaultContentType:e}){this.marshaller=t,this.serializer=n,this.deserializer=s,this.serdeContext=r,this.defaultContentType=e}async serializeEventStream({eventStream:t,requestSchema:n,initialRequest:s}){let r=this.marshaller,e=n.getEventStreamMember(),i=n.getMemberSchema(e),f=this.serializer,o=this.defaultContentType,c=Symbol("initialRequestMarker"),h={async*[Symbol.asyncIterator](){if(s){let u={":event-type":{type:"string",value:"initial-request"},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:o}};f.write(n,s);let l=f.flush();yield{[c]:!0,headers:u,body:l}}for await(let u of t)yield u}};return r.serialize(h,(u)=>{if(u[c])return{headers:u.headers,body:u.body};let l="";for(let E in u)if(E!=="__type"){l=E;break}let{additionalHeaders:_,body:w,eventType:A,explicitPayloadContentType:M}=this.writeEventBody(l,i,u);return{headers:{":event-type":{type:"string",value:A},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:M??o},..._},body:w}})}async deserializeEventStream({response:t,responseSchema:n,initialResponseContainer:s}){let r=this.marshaller,e=n.getEventStreamMember(),f=n.getMemberSchema(e).getMemberSchemas(),o=Symbol("initialResponseMarker"),c=r.deserialize(t.body,async(l)=>{let _="";for(let A in l)if(A!=="__type"){_=A;break}let w=l[_].body;if(_==="initial-response"){let A=await this.deserializer.read(n,w);return delete A[e],{[o]:!0,...A}}else if(_ in f){let A=f[_];if(A.isStructSchema()){let M={},d=!1;for(let[E,b]of A.structIterator()){let{eventHeader:L,eventPayload:S}=b.getMergedTraits();if(d=d||Boolean(L||S),S){if(b.isBlobSchema())M[E]=w;else if(b.isStringSchema())M[E]=(this.serdeContext?.utf8Encoder??k$)(w);else if(b.isStructSchema())M[E]=await this.deserializer.read(b,w)}else if(L){let O=l[_].headers[E]?.value;if(O!=null)if(b.isNumericSchema())if(O&&typeof O==="object"&&"bytes"in O)M[E]=BigInt(O.toString());else M[E]=Number(O);else M[E]=O}}if(d)return{[_]:M};if(w.byteLength===0)return{[_]:{}}}return{[_]:await this.deserializer.read(A,w)}}else return{$unknown:l}}),h=c[Symbol.asyncIterator](),u=await h.next();if(u.done)return c;if(u.value?.[o]){if(!n)throw Error("@smithy::core/protocols - initial-response event encountered in event stream but no response schema given.");for(let l in u.value)s[l]=u.value[l]}return{async*[Symbol.asyncIterator](){if(!u?.value?.[o])yield u.value;while(!0){let{done:l,value:_}=await h.next();if(l)break;yield _}}}}writeEventBody(t,n,s){let r=this.serializer,e=t,i=null,f,o=(()=>{return n.getSchema()[4].includes(t)})(),c={};if(!o){let[l,_]=s[t];e=l,r.write(15,_)}else{let l=n.getMemberSchema(t);if(l.isStructSchema()){for(let[_,w]of l.structIterator()){let{eventHeader:A,eventPayload:M}=w.getMergedTraits();if(M)i=_;else if(A){let d=s[t][_],E="binary";if(w.isNumericSchema())if(-2147483648<=d&&d<=2147483647)E="integer";else E="long";else if(w.isTimestampSchema())E="timestamp";else if(w.isStringSchema())E="string";else if(w.isBooleanSchema())E="boolean";if(d!=null)c[_]={type:E,value:d},delete s[t][_]}}if(i!==null){let _=l.getMemberSchema(i);if(_.isBlobSchema())f="application/octet-stream";else if(_.isStringSchema())f="text/plain";r.write(_,s[t][i])}else r.write(l,s[t])}else if(l.isUnitSchema())r.write(l,{});else throw Error("@smithy/core/event-streams - non-struct member not supported in event stream union.")}let h=r.flush()??new Uint8Array;return{body:typeof h==="string"?(this.serdeContext?.utf8Decoder??X$)(h):h,eventType:e,explicitPayloadContentType:f,additionalHeaders:c}}}uU.EventStreamCodec=Vf;uU.EventStreamMarshaller=sc;uU.EventStreamSerde=w_;uU.HeaderMarshaller=Kf;uU.Int64=js;uU.MessageDecoderStream=jf;uU.MessageEncoderStream=pf;uU.SmithyMessageDecoderStream=vf;uU.SmithyMessageEncoderStream=Zf;uU.UniversalEventStreamMarshaller=nc;uU.eventStreamSerdeProvider=iU;uU.getChunkedStream=__;uU.getMessageUnmarshaller=tc;uU.getUnmarshalledStream=rU;uU.iterableToReadableStream=cU;uU.readableStreamToIterable=fU;uU.resolveEventStreamSerdeConfig=hU;uU.universalEventStreamSerdeProvider=eU});var Tt=K((jU)=>{var{Uint8ArrayBlobAdapter:rc,sdkStreamMixin:GU,splitEvery:BU,splitHeader:g_,fromBase64:A_,_parseEpochTimestamp:mU,_parseRfc7231DateTime:FU,_parseRfc3339DateTimeWithOffset:PU,LazyJsonString:E_,NumericValue:HU,toUtf8:R_,fromUtf8:NU,generateIdempotencyToken:DU,toBase64:M_,dateToUtcString:WU,quoteHeader:YU}=bt(),{TypeRegistry:xU,NormalizedSchema:en,translateTraits:b_}=Pn(),{HttpRequest:ps,HttpResponse:T_,isValidHostname:S_}=tn(),{parseQueryString:QU,parseUrl:JU}=tn();jU.HttpRequest=ps;jU.HttpResponse=T_;jU.isValidHostname=S_;jU.parseQueryString=QU;jU.parseUrl=JU;var{FieldPosition:zU}=es(),us=async(t=new Uint8Array,n)=>{if(t instanceof Uint8Array)return rc.mutate(t);if(!t)return rc.mutate(new Uint8Array);let s=n.streamCollector(t);return rc.mutate(await s)};function Cr(t){return encodeURIComponent(t).replace(/[!'()*]/g,function(n){return"%"+n.charCodeAt(0).toString(16).toUpperCase()})}class vs{serdeContext;setSerdeContext(t){this.serdeContext=t}}class wi extends vs{options;compositeErrorRegistry;constructor(t){super();this.options=t,this.compositeErrorRegistry=xU.for(t.defaultNamespace);for(let n of t.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(n)}getRequestType(){return ps}getResponseType(){return T_}setSerdeContext(t){if(this.serdeContext=t,this.serializer.setSerdeContext(t),this.deserializer.setSerdeContext(t),this.getPayloadCodec())this.getPayloadCodec().setSerdeContext(t)}updateServiceEndpoint(t,n){if("url"in n){if(t.protocol=n.url.protocol,t.hostname=n.url.hostname,t.port=n.url.port?Number(n.url.port):void 0,t.path=n.url.pathname,t.fragment=n.url.hash||void 0,t.username=n.url.username||void 0,t.password=n.url.password||void 0,!t.query)t.query={};for(let[s,r]of n.url.searchParams.entries())t.query[s]=r;if(n.headers)for(let s in n.headers)t.headers[s]=n.headers[s].join(", ");return t}else{if(t.protocol=n.protocol,t.hostname=n.hostname,t.port=n.port?Number(n.port):void 0,t.path=n.path,t.query={...n.query},n.headers)for(let s in n.headers)t.headers[s]=n.headers[s];return t}}setHostPrefix(t,n,s){if(this.serdeContext?.disableHostPrefix)return;let r=en.of(n.input),e=b_(n.traits??{});if(e.endpoint){let i=e.endpoint?.[0];if(typeof i==="string"){for(let[f,o]of r.structIterator()){if(!o.getMergedTraits().hostLabel)continue;let c=s[f];if(typeof c!=="string")throw Error(`@smithy/core/schema - ${f} in input must be a string as hostLabel.`);i=i.replace(`{${f}}`,c)}if(t.hostname=i+t.hostname,!S_(t.hostname))throw Error(`[${t.hostname}] is not a valid hostname.`)}}}deserializeMetadata(t){return{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"]}}async serializeEventStream({eventStream:t,requestSchema:n,initialRequest:s}){return(await this.loadEventStreamCapability()).serializeEventStream({eventStream:t,requestSchema:n,initialRequest:s})}async deserializeEventStream({response:t,responseSchema:n,initialResponseContainer:s}){return(await this.loadEventStreamCapability()).deserializeEventStream({response:t,responseSchema:n,initialResponseContainer:s})}async loadEventStreamCapability(){let{EventStreamSerde:t,eventStreamSerdeProvider:n}=_i(),s=this.resolveEventStreamMarshaller(n);return new t({marshaller:s,serializer:this.serializer,deserializer:this.deserializer,serdeContext:this.serdeContext,defaultContentType:this.getDefaultContentType()})}resolveEventStreamMarshaller(t){let n=this.serdeContext;if(n.eventStreamMarshaller)return n.eventStreamMarshaller;return t(this.serdeContext)}getDefaultContentType(){throw Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`)}async deserializeHttpMessage(t,n,s,r,e){return[]}getEventStreamMarshaller(){let t=this.serdeContext;if(!t.eventStreamMarshaller)throw Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");return t.eventStreamMarshaller}}class $_ extends wi{async serializeRequest(t,n,s){let r=n&&typeof n==="object"?n:{},e=this.serializer,i={},f={},o=await s.endpoint(),c=en.of(t?.input),h=[],u=[],l=!1,_,w=new ps({protocol:"",hostname:"",port:void 0,path:"",fragment:void 0,query:i,headers:f,body:void 0});if(o){this.updateServiceEndpoint(w,o),this.setHostPrefix(w,t,r);let A=b_(t.traits);if(A.http){w.method=A.http[0];let[M,d]=A.http[1].split("?");if(w.path=="/")w.path=M;else w.path+=M;let E=new URLSearchParams(d??"");for(let[b,L]of E)i[b]=L}}for(let[A,M]of c.structIterator()){let d=M.getMergedTraits()??{},E=r[A];if(E==null&&!M.isIdempotencyToken()){if(d.httpLabel){if(w.path.includes(`{${A}+}`)||w.path.includes(`{${A}}`))throw Error(`No value provided for input HTTP label: ${A}.`)}continue}if(d.httpPayload)if(M.isStreaming())if(M.isStructSchema()){if(r[A])_=await this.serializeEventStream({eventStream:r[A],requestSchema:c})}else _=E;else e.write(M,E),_=e.flush();else if(d.httpLabel){e.write(M,E);let b=e.flush();if(w.path.includes(`{${A}+}`))w.path=w.path.replace(`{${A}+}`,b.split("/").map(Cr).join("/"));else if(w.path.includes(`{${A}}`))w.path=w.path.replace(`{${A}}`,Cr(b))}else if(d.httpHeader)e.write(M,E),f[d.httpHeader.toLowerCase()]=String(e.flush());else if(typeof d.httpPrefixHeaders==="string")for(let b in E){let L=E[b],S=d.httpPrefixHeaders+b;e.write([M.getValueSchema(),{httpHeader:S}],L),f[S.toLowerCase()]=e.flush()}else if(d.httpQuery||d.httpQueryParams)this.serializeQuery(M,E,i);else l=!0,h.push(A),u.push(M)}if(l&&r){let[A,M]=(c.getName(!0)??"#Unknown").split("#"),d=c.getSchema()[6],E=[3,A,M,c.getMergedTraits(),h,u,void 0];if(d)E[6]=d;else E.pop();e.write(E,r),_=e.flush()}return w.headers=f,w.query=i,w.body=_,w}serializeQuery(t,n,s){let r=this.serializer,e=t.getMergedTraits();if(e.httpQueryParams){for(let i in n)if(!(i in s)){let f=n[i],o=t.getValueSchema();Object.assign(o.getMergedTraits(),{...e,httpQuery:i,httpQueryParams:void 0}),this.serializeQuery(o,f,s)}return}if(t.isListSchema()){let i=!!t.getMergedTraits().sparse,f=[];for(let o of n){r.write([t.getValueSchema(),e],o);let c=r.flush();if(i||c!==void 0)f.push(c)}s[e.httpQuery]=f}else r.write([t,e],n),s[e.httpQuery]=r.flush()}async deserializeResponse(t,n,s){let r=this.deserializer,e=en.of(t.output),i={};if(s.statusCode>=300){let o=await us(s.body,n);if(o.byteLength>0)Object.assign(i,await r.read(15,o));throw await this.handleError(t,n,s,i,this.deserializeMetadata(s)),Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw.")}for(let o in s.headers){let c=s.headers[o];delete s.headers[o],s.headers[o.toLowerCase()]=c}let f=await this.deserializeHttpMessage(e,n,s,i);if(f.length){let o=await us(s.body,n);if(o.byteLength>0){let c=await r.read(e,o);for(let h of f)if(c[h]!=null)i[h]=c[h]}}else if(f.discardResponseBody)await us(s.body,n);return i.$metadata=this.deserializeMetadata(s),i}async deserializeHttpMessage(t,n,s,r,e){let i;if(r instanceof Set)i=e;else i=r;let f=!0,o=this.deserializer,c=en.of(t),h=[];for(let[u,l]of c.structIterator()){let _=l.getMemberTraits();if(_.httpPayload){if(f=!1,l.isStreaming())if(l.isStructSchema())i[u]=await this.deserializeEventStream({response:s,responseSchema:c});else i[u]=GU(s.body);else if(s.body){let A=await us(s.body,n);if(A.byteLength>0)i[u]=await o.read(l,A)}}else if(_.httpHeader){let w=String(_.httpHeader).toLowerCase(),A=s.headers[w];if(A!=null)if(l.isListSchema()){let M=l.getValueSchema();M.getMergedTraits().httpHeader=w;let d;if(M.isTimestampSchema()&&M.getSchema()===4)d=BU(A,",",2);else d=g_(A);let E=[];for(let b of d)E.push(await o.read(M,b.trim()));i[u]=E}else i[u]=await o.read(l,A)}else if(_.httpPrefixHeaders!==void 0){i[u]={};for(let w in s.headers)if(w.startsWith(_.httpPrefixHeaders)){let A=s.headers[w],M=l.getValueSchema();M.getMergedTraits().httpHeader=w,i[u][w.slice(_.httpPrefixHeaders.length)]=await o.read(M,A)}}else if(_.httpResponseCode)i[u]=s.statusCode;else h.push(u)}return h.discardResponseBody=f,h}}class U_ extends wi{async serializeRequest(t,n,s){let r=this.serializer,e={},i={},f=await s.endpoint(),o=en.of(t?.input),c=o.getSchema(),h,u=n&&typeof n==="object"?n:{},l=new ps({protocol:"",hostname:"",port:void 0,path:"/",fragment:void 0,query:e,headers:i,body:void 0});if(f)this.updateServiceEndpoint(l,f),this.setHostPrefix(l,t,u);if(u){let _=o.getEventStreamMember();if(_){if(u[_]){let w={};for(let[A,M]of o.structIterator())if(A!==_&&u[A])r.write(M,u[A]),w[A]=r.flush();h=await this.serializeEventStream({eventStream:u[_],requestSchema:o,initialRequest:w})}}else r.write(c,u),h=r.flush()}return l.headers=Object.assign(l.headers,i),l.query=e,l.body=h,l.method="POST",l}async deserializeResponse(t,n,s){let r=this.deserializer,e=en.of(t.output),i={};if(s.statusCode>=300){let o=await us(s.body,n);if(o.byteLength>0)Object.assign(i,await r.read(15,o));throw await this.handleError(t,n,s,i,this.deserializeMetadata(s)),Error("@smithy/core/protocols - RPC Protocol error handler failed to throw.")}for(let o in s.headers){let c=s.headers[o];delete s.headers[o],s.headers[o.toLowerCase()]=c}let f=e.getEventStreamMember();if(f)i[f]=await this.deserializeEventStream({response:s,responseSchema:e,initialResponseContainer:i});else{let o=await us(s.body,n);if(o.byteLength>0)Object.assign(i,await r.read(e,o))}return i.$metadata=this.deserializeMetadata(s),i}}var L_=(t,n,s,r,e,i)=>{if(n!=null&&n[s]!==void 0){let f=r();if(f==null||f.length<=0)throw Error("Empty value provided for input HTTP label: "+s+".");t=t.replace(e,i?f.split("/").map((o)=>Cr(o)).join("/"):Cr(f))}else throw Error("No value provided for input HTTP label: "+s+".");return t};function kU(t,n){return new ec(t,n)}class ec{input;context;query={};method="";headers={};path="";body=null;hostname="";resolvePathStack=[];constructor(t,n){this.input=t,this.context=n}async build(){let{hostname:t,protocol:n="https",port:s,path:r}=await this.context.endpoint();this.path=r;for(let e of this.resolvePathStack)e(this.path);return new ps({protocol:n,hostname:this.hostname||t,port:s,method:this.method,path:this.path,query:this.query,body:this.body,headers:this.headers})}hn(t){return this.hostname=t,this}bp(t){return this.resolvePathStack.push((n)=>{this.path=`${n?.endsWith("/")?n.slice(0,-1):n||""}`+t}),this}p(t,n,s,r){return this.resolvePathStack.push((e)=>{this.path=L_(e,this.input,t,n,s,r)}),this}h(t){return this.headers=t,this}q(t){return this.query=t,this}b(t){return this.body=t,this}m(t){return this.method=t,this}}function ic(t,n){if(n.timestampFormat.useTrait){if(t.isTimestampSchema()&&(t.getSchema()===5||t.getSchema()===6||t.getSchema()===7))return t.getSchema()}let{httpLabel:s,httpPrefixHeaders:r,httpHeader:e,httpQuery:i}=t.getMergedTraits();return(n.httpBindings?typeof r==="string"||Boolean(e)?6:Boolean(i)||Boolean(s)?5:void 0:void 0)??n.timestampFormat.default}class oc extends vs{settings;constructor(t){super();this.settings=t}read(t,n){let s=en.of(t);if(s.isListSchema())return g_(n).map((r)=>this.read(s.getValueSchema(),r));if(s.isBlobSchema())return(this.serdeContext?.base64Decoder??A_)(n);if(s.isTimestampSchema())switch(ic(s,this.settings)){case 5:return PU(n);case 6:return FU(n);case 7:return mU(n);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",n),new Date(n)}if(s.isStringSchema()){let r=s.getMergedTraits().mediaType,e=n;if(r){if(s.getMergedTraits().httpHeader)e=this.base64ToUtf8(e);if(r==="application/json"||r.endsWith("+json"))e=E_.from(e);return e}}if(s.isNumericSchema())return Number(n);if(s.isBigIntegerSchema())return BigInt(n);if(s.isBigDecimalSchema())return new HU(n,"bigDecimal");if(s.isBooleanSchema())return String(n).toLowerCase()==="true";return n}base64ToUtf8(t){return(this.serdeContext?.utf8Encoder??R_)((this.serdeContext?.base64Decoder??A_)(t))}}class I_ extends vs{codecDeserializer;stringDeserializer;constructor(t,n){super();this.codecDeserializer=t,this.stringDeserializer=new oc(n)}setSerdeContext(t){this.stringDeserializer.setSerdeContext(t),this.codecDeserializer.setSerdeContext(t),this.serdeContext=t}read(t,n){let s=en.of(t),r=s.getMergedTraits(),e=this.serdeContext?.utf8Encoder??R_;if(r.httpHeader||r.httpResponseCode)return this.stringDeserializer.read(s,e(n));if(r.httpPayload){if(s.isBlobSchema()){let i=this.serdeContext?.utf8Decoder??NU;if(typeof n==="string")return i(n);return n}else if(s.isStringSchema()){if("byteLength"in n)return e(n);return n}}return this.codecDeserializer.read(s,n)}}class fc extends vs{settings;stringBuffer="";constructor(t){super();this.settings=t}write(t,n){let s=en.of(t);switch(typeof n){case"object":if(n===null){this.stringBuffer="null";return}if(s.isTimestampSchema()){if(!(n instanceof Date))throw Error(`@smithy/core/protocols - received non-Date value ${n} when schema expected Date in ${s.getName(!0)}`);switch(ic(s,this.settings)){case 5:this.stringBuffer=n.toISOString().replace(".000Z","Z");break;case 6:this.stringBuffer=WU(n);break;case 7:this.stringBuffer=String(n.getTime()/1000);break;default:console.warn("Missing timestamp format, using epoch seconds",n),this.stringBuffer=String(n.getTime()/1000)}return}if(s.isBlobSchema()&&"byteLength"in n){this.stringBuffer=(this.serdeContext?.base64Encoder??M_)(n);return}if(s.isListSchema()&&Array.isArray(n)){let i="";for(let f of n){this.write([s.getValueSchema(),s.getMergedTraits()],f);let o=this.flush(),c=s.getValueSchema().isTimestampSchema()?o:YU(o);if(i!=="")i+=", ";i+=c}this.stringBuffer=i;return}this.stringBuffer=JSON.stringify(n,null,2);break;case"string":let r=s.getMergedTraits().mediaType,e=n;if(r){if(r==="application/json"||r.endsWith("+json"))e=E_.from(e);if(s.getMergedTraits().httpHeader){this.stringBuffer=(this.serdeContext?.base64Encoder??M_)(e.toString());return}}this.stringBuffer=n;break;default:if(s.isIdempotencyToken())this.stringBuffer=DU();else this.stringBuffer=String(n)}}flush(){let t=this.stringBuffer;return this.stringBuffer="",t}}class O_{codecSerializer;stringSerializer;buffer;constructor(t,n,s=new fc(n)){this.codecSerializer=t,this.stringSerializer=s}setSerdeContext(t){this.codecSerializer.setSerdeContext(t),this.stringSerializer.setSerdeContext(t)}write(t,n){let s=en.of(t),r=s.getMergedTraits();if(r.httpHeader||r.httpLabel||r.httpQuery){this.stringSerializer.write(s,n),this.buffer=this.stringSerializer.flush();return}return this.codecSerializer.write(s,n)}flush(){if(this.buffer!==void 0){let t=this.buffer;return this.buffer=void 0,t}return this.codecSerializer.flush()}}class y_{name;kind;values;constructor({name:t,kind:n=zU.HEADER,values:s=[]}){this.name=t,this.kind=n,this.values=s}add(t){this.values.push(t)}set(t){this.values=t}remove(t){this.values=this.values.filter((n)=>n!==t)}toString(){return this.values.map((t)=>t.includes(",")||t.includes(" ")?`"${t}"`:t).join(", ")}get(){return this.values}}class G_{entries={};encoding;constructor({fields:t=[],encoding:n="utf-8"}){t.forEach(this.setField.bind(this)),this.encoding=n}setField(t){this.entries[t.name.toLowerCase()]=t}getField(t){return this.entries[t.toLowerCase()]}removeField(t){delete this.entries[t.toLowerCase()]}getByType(t){return Object.values(this.entries).filter((n)=>n.kind===t)}}var XU=(t)=>{return{setHttpHandler(n){t.httpHandler=n},httpHandler(){return t.httpHandler},updateHttpClientConfig(n,s){t.httpHandler?.updateHttpClientConfig(n,s)},httpHandlerConfigs(){return t.httpHandler.httpHandlerConfigs()}}},qU=(t)=>{return{httpHandler:t.httpHandler()}},d_="content-length";function B_(t){return(n)=>async(s)=>{let r=s.request;if(ps.isInstance(r)){let{body:e,headers:i}=r;if(e&&Object.keys(i).map((f)=>f.toLowerCase()).indexOf(d_)===-1)try{let f=t(e);r.headers={...r.headers,[d_]:String(f)}}catch(f){}}return n({...s,request:r})}}var m_={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},CU=(t)=>({applyToStack:(n)=>{n.add(B_(t.bodyLengthChecker),m_)}}),qr=(t)=>encodeURIComponent(t).replace(/[!'()*]/g,aU),aU=(t)=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`,KU=(t)=>t.split("/").map(qr).join("/");function VU(t){let n=[];for(let s of Object.keys(t).sort()){let r=t[s];if(s=qr(s),Array.isArray(r))for(let e=0,i=r.length;e<i;e++)n.push(`${s}=${qr(r[e])}`);else{let e=s;if(r||typeof r==="string")e+=`=${qr(r)}`;n.push(e)}}return n.join("&")}jU.Field=y_;jU.Fields=G_;jU.FromStringShapeDeserializer=oc;jU.HttpBindingProtocol=$_;jU.HttpInterceptingShapeDeserializer=I_;jU.HttpInterceptingShapeSerializer=O_;jU.HttpProtocol=wi;jU.RequestBuilder=ec;jU.RpcProtocol=U_;jU.SerdeContext=vs;jU.ToStringShapeSerializer=fc;jU.buildQueryString=VU;jU.collectBody=us;jU.contentLengthMiddleware=B_;jU.contentLengthMiddlewareOptions=m_;jU.determineTimestampFormat=ic;jU.escapeUri=qr;jU.escapeUriPath=KU;jU.extendedEncodeURIComponent=Cr;jU.getContentLengthPlugin=CU;jU.getHttpHandlerExtensionConfiguration=XU;jU.requestBuilder=kU;jU.resolveHttpHandlerRuntimeConfig=qU;jU.resolvedPath=L_});var pr=K((VL)=>{var{Readable:IL}=j("stream"),{NoOpLogger:OL,normalizeProvider:F_}=En(),{HttpResponse:P_,HttpRequest:Mi}=Tt(),{parseRfc7231DateTime:yL,v4:H_}=bt(),N_=(t)=>t?.body instanceof IL||typeof ReadableStream<"u"&&t?.body instanceof ReadableStream,GL=["AuthFailure","InvalidSignatureException","RequestExpired","RequestInTheFuture","RequestTimeTooSkewed","SignatureDoesNotMatch"],BL=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],mL=["TimeoutError","RequestTimeout","RequestTimeoutException"],FL=[500,502,503,504],PL=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],HL=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN"],lc=(t)=>t?.$retryable!==void 0,D_=(t)=>GL.includes(t.name),W_=(t)=>t.$metadata?.clockSkewCorrected,Y_=(t)=>{let n=new Set(["Failed to fetch","NetworkError when attempting to fetch resource","The Internet connection appears to be offline","Load failed","Network request failed"]);if(!(t&&t instanceof TypeError))return!1;return n.has(t.message)},Kr=(t)=>t.$metadata?.httpStatusCode===429||BL.includes(t.name)||t.$retryable?.throttling==!0,Vr=(t,n=0)=>lc(t)||W_(t)||t.name==="InvalidSignatureException"&&t.message?.includes("Signature expired")||mL.includes(t.name)||PL.includes(t?.code||"")||HL.includes(t?.code||"")||FL.includes(t.$metadata?.httpStatusCode||0)||Y_(t)||Q_(t)||t.cause!==void 0&&n<=10&&Vr(t.cause,n+1),x_=(t)=>{if(t.$metadata?.httpStatusCode!==void 0){let n=t.$metadata.httpStatusCode;if(500<=n&&n<=599&&!Vr(t))return!0;return!1}return!1};function Q_(t){return t.code==="ERR_HTTP2_STREAM_ERROR"&&t.message.includes("NGHTTP2_REFUSED_STREAM")}var J_=100,gi=20000,z_=500,di=500,k_=5,X_=10,_c=1,Ei="amz-sdk-invocation-id",Ri="amz-sdk-request";function q_(t,n){if(!P_.isInstance(t))return;for(let s of Object.keys(t.headers)){let r=s.toLowerCase();if(r==="retry-after"){let e=t.headers[s],i=NaN;if(e.endsWith("GMT"))try{i=(yL(e).getTime()-Date.now())/1000}catch(f){n?.trace?.("Failed to parse retry-after header"),n?.trace?.(f)}else if(e.match(/ GMT, ((\d+)|(\d+\.\d+))$/))i=Number(e.match(/ GMT, ([\d.]+)$/)?.[1]);else if(e.match(/^((\d+)|(\d+\.\d+))$/))i=Number(e);else if(Date.parse(e)>=Date.now())i=(Date.parse(e)-Date.now())/1000;if(isNaN(i))return;return new Date(Date.now()+i*1000)}else if(r==="x-amz-retry-after"){let e=t.headers[s],i=Number(e);if(isNaN(i)){n?.trace?.(`Failed to parse x-amz-retry-after=${e}`);return}return new Date(Date.now()+i)}}}function NL(t,n){return q_(t,n)}var C_=(t)=>{if(t instanceof Error)return t;if(t instanceof Object)return Object.assign(Error(),t);if(typeof t==="string")return Error(t);return Error(`AWS SDK error wrapper for ${t}`)};function a_(t){return(n)=>(s,r)=>async(e)=>{let i=await n.retryStrategy(),f=await n.maxAttempts();if(WL(i)){i=i;let o=await i.acquireInitialRetryToken((r.partition_id??"")+(r.__retryLongPoll?":longpoll":"")),c=Error(),h=0,u=0,{request:l}=e,_=Mi.isInstance(l);if(_)l.headers[Ei]=H_();while(!0)try{if(_)l.headers[Ri]=`attempt=${h+1}; max=${f}`;let{response:w,output:A}=await s(e);return i.recordSuccess(o),A.$metadata.attempts=h+1,A.$metadata.totalRetryDelay=u,{response:w,output:A}}catch(w){let A=YL(w,n.logger);if(c=C_(w),_&&t(l))throw(r.logger instanceof OL?console:r.logger)?.warn("An error was encountered in a non-retryable streaming request."),c;try{o=await i.refreshRetryTokenForRetry(o,A)}catch(d){if(!c.$metadata)c.$metadata={};throw c.$metadata.attempts=h+1,c.$metadata.totalRetryDelay=u,c}h=o.getRetryCount();let M=o.getRetryDelay();if(u+=(o?.$retryLog?.acquisitionDelay??0)+M,M>0)await DL(M)}}else{if(i=i,i?.mode)r.userAgent=[...r.userAgent||[],["cfg/retry-mode",i.mode]];return i.retry(s,e)}}}var DL=(t)=>new Promise((n)=>setTimeout(n,t)),WL=(t)=>typeof t.acquireInitialRetryToken<"u"&&typeof t.refreshRetryTokenForRetry<"u"&&typeof t.recordSuccess<"u",YL=(t,n)=>{let s={error:t,errorType:xL(t)},r=q_(t.$response,n);if(r)s.retryAfterHint=r;return s},xL=(t)=>{if(Kr(t))return"THROTTLING";if(Vr(t))return"TRANSIENT";if(x_(t))return"SERVER_ERROR";return"CLIENT_ERROR"},K_={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0};function QL(t){let n=a_(t);return(s)=>({applyToStack:(r)=>{r.add(n(s),K_)}})}class jr{static setTimeoutFn=(t,n)=>setTimeout(t,n);beta;minCapacity;minFillRate;scaleConstant;smooth;enabled=!1;availableTokens=0;lastMaxRate=0;measuredTxRate=0;requestCount=0;fillRate;lastThrottleTime;lastTimestamp=0;lastTxRateBucket;maxCapacity;timeWindow=0;constructor(t){this.beta=t?.beta??0.7,this.minCapacity=t?.minCapacity??1,this.minFillRate=t?.minFillRate??0.5,this.scaleConstant=t?.scaleConstant??0.4,this.smooth=t?.smooth??0.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(t){let n;this.updateMeasuredRate();let s=t;if(s?.errorType==="THROTTLING"||Kr(s?.error??t)){let i=!this.enabled?this.measuredTxRate:Math.min(this.measuredTxRate,this.fillRate);this.lastMaxRate=i,this.calculateTimeWindow(),this.lastThrottleTime=this.getCurrentTimeInSeconds(),n=this.cubicThrottle(i),this.enableTokenBucket()}else this.calculateTimeWindow(),n=this.cubicSuccess(this.getCurrentTimeInSeconds());let e=Math.min(n,2*this.measuredTxRate);this.updateTokenBucketRate(e)}getCurrentTimeInSeconds(){return Date.now()/1000}async acquireTokenBucket(t){if(!this.enabled)return;this.refillTokenBucket();while(t>this.availableTokens){let n=(t-this.availableTokens)/this.fillRate*1000;await new Promise((s)=>jr.setTimeoutFn(s,n)),this.refillTokenBucket()}this.availableTokens=this.availableTokens-t}refillTokenBucket(){let t=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=t;return}let n=(t-this.lastTimestamp)*this.fillRate;this.availableTokens=Math.min(this.maxCapacity,this.availableTokens+n),this.lastTimestamp=t}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,0.3333333333333333))}cubicThrottle(t){return this.getPrecise(t*this.beta)}cubicSuccess(t){return this.getPrecise(this.scaleConstant*Math.pow(t-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(t){this.refillTokenBucket(),this.fillRate=Math.max(t,this.minFillRate),this.maxCapacity=Math.max(t,this.minCapacity),this.availableTokens=Math.min(this.availableTokens,this.maxCapacity)}updateMeasuredRate(){let t=this.getCurrentTimeInSeconds(),n=Math.floor(t*2)/2;if(this.requestCount++,n>this.lastTxRateBucket){let s=this.requestCount/(n-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(s*this.smooth+this.measuredTxRate*(1-this.smooth)),this.requestCount=0,this.lastTxRateBucket=n}}getPrecise(t){return parseFloat(t.toFixed(8))}}class ct{static v2026=typeof process<"u"&&process.env?.SMITHY_NEW_RETRIES_2026==="true";static delay(){return ct.v2026?50:100}static throttlingDelay(){return ct.v2026?1000:500}static cost(){return ct.v2026?14:5}static throttlingCost(){return ct.v2026?5:10}static modifiedCostType(){return ct.v2026?"THROTTLING":"TRANSIENT"}}class V_{x=ct.delay();computeNextBackoffDelay(t){let n=Math.random(),s=2,r=n*Math.min(this.x*2**t,gi);return Math.floor(r)}setDelayBase(t){this.x=t}}class cc{delay;count;cost;longPoll;$retryLog={acquisitionDelay:0};constructor(t,n,s,r){this.delay=t,this.count=n,this.cost=s,this.longPoll=r}getRetryCount(){return this.count}getRetryDelay(){return Math.min(gi,this.delay)}getRetryCost(){return this.cost}isLongPoll(){return this.longPoll}}var Sn;(function(t){t.STANDARD="standard",t.ADAPTIVE="adaptive"})(Sn||(Sn={}));var ls=3,j_=Sn.STANDARD,Ai={incompatible:1,attempts:2,capacity:3},ar=class{mode=Sn.STANDARD;retryBackoffStrategy;capacity=di;maxAttemptsProvider;baseDelay;constructor(n){if(typeof n==="number")this.maxAttemptsProvider=async()=>n;else if(typeof n==="function")this.maxAttemptsProvider=n;else if(n&&typeof n==="object")this.maxAttemptsProvider=async()=>n.maxAttempts,this.baseDelay=n.baseDelay,this.retryBackoffStrategy=n.backoff;this.maxAttemptsProvider??=async()=>ls,this.baseDelay??=ct.delay(),this.retryBackoffStrategy??=new V_}async acquireInitialRetryToken(n){return new cc(ct.delay(),0,void 0,ct.v2026&&n.includes(":longpoll"))}async refreshRetryTokenForRetry(n,s){let r=await this.getMaxAttempts(),e=this.retryCode(n,s,r),i=e===0,f=n.isLongPoll?.();if(i||f){let o=s.errorType;this.retryBackoffStrategy.setDelayBase(o==="THROTTLING"?ct.throttlingDelay():this.baseDelay);let c=this.retryBackoffStrategy.computeNextBackoffDelay(n.getRetryCount()),h=c;if(s.retryAfterHint instanceof Date)h=Math.max(c,Math.min(s.retryAfterHint.getTime()-Date.now(),c+5000));if(!i){let u=ct.v2026&&e===Ai.capacity&&f?h:0;if(u>0)await new Promise((l)=>setTimeout(l,u))}else{let u=this.getCapacityCost(o);this.capacity-=u;let l=new cc(0,n.getRetryCount()+1,u,n.isLongPoll?.()??!1);return await new Promise((_)=>setTimeout(_,h)),l.$retryLog.acquisitionDelay=h,l}}throw Error("No retry token available")}recordSuccess(n){this.capacity=Math.min(di,this.capacity+(n.getRetryCost()??_c))}getCapacity(){return this.capacity}async maxAttempts(){return this.maxAttemptsProvider()}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch(n){return console.warn(`Max attempts provider could not resolve. Using default of ${ls}`),ls}}retryCode(n,s,r){let e=n.getRetryCount()+1,i=this.isRetryableError(s.errorType)?0:Ai.incompatible,f=e<r?0:Ai.attempts,o=this.capacity>=this.getCapacityCost(s.errorType)?0:Ai.capacity;return i||f||o}getCapacityCost(n){return n===ct.modifiedCostType()?ct.throttlingCost():ct.cost()}isRetryableError(n){return n==="THROTTLING"||n==="TRANSIENT"}},p_=class{mode=Sn.ADAPTIVE;rateLimiter;standardRetryStrategy;constructor(n,s){let{rateLimiter:r}=s??{};this.rateLimiter=r??new jr,this.standardRetryStrategy=s?new ar({maxAttempts:typeof n==="number"?n:3,...s}):new ar(n)}async acquireInitialRetryToken(n){let s=await this.standardRetryStrategy.acquireInitialRetryToken(n);return await this.rateLimiter.getSendToken(),s}async refreshRetryTokenForRetry(n,s){this.rateLimiter.updateClientSendingRate(s);let r=await this.standardRetryStrategy.refreshRetryTokenForRetry(n,s);return await this.rateLimiter.getSendToken(),r}recordSuccess(n){this.rateLimiter.updateClientSendingRate({}),this.standardRetryStrategy.recordSuccess(n)}async maxAttemptsProvider(){return this.standardRetryStrategy.maxAttempts()}};class v_ extends ar{computeNextBackoffDelay;constructor(t,n=ct.delay()){super(typeof t==="function"?t:async()=>t);if(typeof n==="number")this.computeNextBackoffDelay=()=>n;else this.computeNextBackoffDelay=n;this.retryBackoffStrategy.computeNextBackoffDelay=(s)=>{let r=s+1;return this.computeNextBackoffDelay(r)}}}var JL=(t,n)=>{let s=t,r=_c,e=k_,i=X_,f=t,o=(l)=>l.name==="TimeoutError"?i:e,c=(l)=>o(l)<=f;return Object.freeze({hasRetryTokens:c,retrieveRetryTokens:(l)=>{if(!c(l))throw Error("No retry token available");let _=o(l);return f-=_,_},releaseRetryTokens:(l)=>{f+=l??r,f=Math.min(f,s)}})},Z_=(t,n)=>Math.floor(Math.min(gi,Math.random()*2**n*t)),tw=(t)=>{if(!t)return!1;return lc(t)||D_(t)||Kr(t)||Vr(t)};class wc{maxAttemptsProvider;retryDecider;delayDecider;retryQuota;mode=Sn.STANDARD;constructor(t,n){this.maxAttemptsProvider=t,this.retryDecider=n?.retryDecider??tw,this.delayDecider=n?.delayDecider??Z_,this.retryQuota=n?.retryQuota??JL(di)}shouldRetry(t,n,s){return n<s&&this.retryDecider(t)&&this.retryQuota.hasRetryTokens(t)}async getMaxAttempts(){let t;try{t=await this.maxAttemptsProvider()}catch(n){t=ls}return t}async retry(t,n,s){let r,e=0,i=0,f=await this.getMaxAttempts(),{request:o}=n;if(Mi.isInstance(o))o.headers[Ei]=H_();while(!0)try{if(Mi.isInstance(o))o.headers[Ri]=`attempt=${e+1}; max=${f}`;if(s?.beforeRequest)await s.beforeRequest();let{response:c,output:h}=await t(n);if(s?.afterRequest)s.afterRequest(c);return this.retryQuota.releaseRetryTokens(r),h.$metadata.attempts=e+1,h.$metadata.totalRetryDelay=i,{response:c,output:h}}catch(c){let h=C_(c);if(e++,this.shouldRetry(h,e,f)){r=this.retryQuota.retrieveRetryTokens(h);let u=this.delayDecider(Kr(h)?z_:J_,e),l=zL(h.$response),_=Math.max(l||0,u);i+=_,await new Promise((w)=>setTimeout(w,_));continue}if(!h.$metadata)h.$metadata={};throw h.$metadata.attempts=e,h.$metadata.totalRetryDelay=i,h}}}var zL=(t)=>{if(!P_.isInstance(t))return;let n=Object.keys(t.headers).find((i)=>i.toLowerCase()==="retry-after");if(!n)return;let s=t.headers[n],r=Number(s);if(!Number.isNaN(r))return Math.min(r*1000,20000);let e=new Date(s);return Math.min(e.getTime()-Date.now(),20000)};class nw extends wc{rateLimiter;constructor(t,n){let{rateLimiter:s,...r}=n??{};super(t,r);this.rateLimiter=s??new jr,this.mode=Sn.ADAPTIVE}async retry(t,n){return super.retry(t,n,{beforeRequest:async()=>{return this.rateLimiter.getSendToken()},afterRequest:(s)=>{this.rateLimiter.updateClientSendingRate(s)}})}}var hc="AWS_MAX_ATTEMPTS",uc="max_attempts",kL={environmentVariableSelector:(t)=>{let n=t[hc];if(!n)return;let s=parseInt(n);if(Number.isNaN(s))throw Error(`Environment variable ${hc} mast be a number, got "${n}"`);return s},configFileSelector:(t)=>{let n=t[uc];if(!n)return;let s=parseInt(n);if(Number.isNaN(s))throw Error(`Shared config file entry ${uc} mast be a number, got "${n}"`);return s},default:ls},XL=(t,n)=>{let{retryStrategy:s,retryMode:r}=t,{defaultMaxAttempts:e=ls,defaultBaseDelay:i=ct.delay()}=n??{},f=F_(t.maxAttempts??e),o=s?Promise.resolve(s):void 0,c=async()=>{let h=await f();if(await F_(r)()===Sn.ADAPTIVE)return new p_(f,{maxAttempts:h,baseDelay:i});return new ar({maxAttempts:h,baseDelay:i})};return Object.assign(t,{maxAttempts:f,retryStrategy:()=>o??=c()})},sw="AWS_RETRY_MODE",rw="retry_mode",qL={environmentVariableSelector:(t)=>t[sw],configFileSelector:(t)=>t[rw],default:j_},ew=()=>(t)=>async(n)=>{let{request:s}=n;if(Mi.isInstance(s))delete s.headers[Ei],delete s.headers[Ri];return t(n)},iw={name:"omitRetryHeadersMiddleware",tags:["RETRY","HEADERS","OMIT_RETRY_HEADERS"],relation:"before",toMiddleware:"awsAuthMiddleware",override:!0},CL=(t)=>({applyToStack:(n)=>{n.addRelativeTo(ew(),iw)}}),aL=a_(N_),KL=QL(N_);VL.AdaptiveRetryStrategy=p_;VL.CONFIG_MAX_ATTEMPTS=uc;VL.CONFIG_RETRY_MODE=rw;VL.ConfiguredRetryStrategy=v_;VL.DEFAULT_MAX_ATTEMPTS=ls;VL.DEFAULT_RETRY_DELAY_BASE=J_;VL.DEFAULT_RETRY_MODE=j_;VL.DefaultRateLimiter=jr;VL.DeprecatedAdaptiveRetryStrategy=nw;VL.DeprecatedStandardRetryStrategy=wc;VL.ENV_MAX_ATTEMPTS=hc;VL.ENV_RETRY_MODE=sw;VL.INITIAL_RETRY_TOKENS=di;VL.INVOCATION_ID_HEADER=Ei;VL.MAXIMUM_RETRY_DELAY=gi;VL.NODE_MAX_ATTEMPT_CONFIG_OPTIONS=kL;VL.NODE_RETRY_MODE_CONFIG_OPTIONS=qL;VL.NO_RETRY_INCREMENT=_c;VL.REQUEST_HEADER=Ri;VL.RETRY_COST=k_;VL.RETRY_MODES=Sn;VL.Retry=ct;VL.StandardRetryStrategy=ar;VL.THROTTLING_RETRY_DELAY_BASE=z_;VL.TIMEOUT_RETRY_COST=X_;VL.defaultDelayDecider=Z_;VL.defaultRetryDecider=tw;VL.getOmitRetryHeadersPlugin=CL;VL.getRetryAfterHint=NL;VL.getRetryPlugin=KL;VL.isBrowserNetworkError=Y_;VL.isClockSkewCorrectedError=W_;VL.isClockSkewError=D_;VL.isNodeJsHttp2TransientError=Q_;VL.isRetryableByTrait=lc;VL.isServerError=x_;VL.isThrottlingError=Kr;VL.isTransientError=Vr;VL.omitRetryHeadersMiddleware=ew;VL.omitRetryHeadersMiddlewareOptions=iw;VL.resolveRetryConfig=XL;VL.retryMiddleware=aL;VL.retryMiddlewareOptions=K_});var fw=K((xI)=>{var xn={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")},Ac=["true","1"].includes(process.env?.AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA??"");if(!Ac)globalThis.awslambda=globalThis.awslambda||{};class bi{static PROTECTED_KEYS=xn;isProtectedKey(t){return Object.values(xn).includes(t)}getRequestId(){return this.get(xn.REQUEST_ID)??"-"}getXRayTraceId(){return this.get(xn.X_RAY_TRACE_ID)}getTenantId(){return this.get(xn.TENANT_ID)}getTraceparent(){return this.get(xn.TRACEPARENT)}getTracestate(){return this.get(xn.TRACESTATE)}getBaggage(){return this.get(xn.BAGGAGE)}}class ow extends bi{currentContext;getContext(){return this.currentContext}hasContext(){return this.currentContext!==void 0}get(t){return this.currentContext?.[t]}set(t,n){if(this.isProtectedKey(t))throw Error(`Cannot modify protected Lambda context field: ${String(t)}`);this.currentContext=this.currentContext||{},this.currentContext[t]=n}run(t,n){return this.currentContext=t,n()}}class dc extends bi{als;static async create(){let t=new dc,n=await import("async_hooks");return t.als=new n.AsyncLocalStorage,t}getContext(){return this.als.getStore()}hasContext(){return this.als.getStore()!==void 0}get(t){return this.als.getStore()?.[t]}set(t,n){if(this.isProtectedKey(t))throw Error(`Cannot modify protected Lambda context field: ${String(t)}`);let s=this.als.getStore();if(!s)throw Error("No context available");s[t]=n}run(t,n){return this.als.run(t,n)}}xI.InvokeStore=void 0;(function(t){let n=null;async function s(r){if(!n)n=(async()=>{let i=r===!0||"AWS_LAMBDA_MAX_CONCURRENCY"in process.env?await dc.create():new ow;if(!Ac&&globalThis.awslambda?.InvokeStore)return globalThis.awslambda.InvokeStore;else if(!Ac&&globalThis.awslambda)return globalThis.awslambda.InvokeStore=i,i;else return i})();return n}t.getInstanceAsync=s,t._testing=process.env.AWS_LAMBDA_BENCHMARK_MODE==="1"?{reset:()=>{if(n=null,globalThis.awslambda?.InvokeStore)delete globalThis.awslambda.InvokeStore;globalThis.awslambda={InvokeStore:void 0}}}:void 0})(xI.InvokeStore||(xI.InvokeStore={}));xI.InvokeStoreBase=bi});var Qn=K((sO)=>{var{getSmithyContext:gc}=tn();sO.getSmithyContext=gc;var{HttpRequest:Ec}=Tt(),{requestBuilder:JI}=Tt();sO.requestBuilder=JI;var{HttpApiKeyAuthLocation:cw}=es(),zI=(t,n)=>{if(!n||n.length===0)return t;let s=[];for(let r of n)for(let e of t)if(e.schemeId.split("#")[1]===r)s.push(e);for(let r of t)if(!s.find(({schemeId:e})=>e===r.schemeId))s.push(r);return s};function kI(t){let n=new Map;for(let s of t)n.set(s.schemeId,s);return n}var Rc=(t,n)=>(s,r)=>async(e)=>{let i=t.httpAuthSchemeProvider(await n.httpAuthSchemeParametersProvider(t,r,e.input)),f=t.authSchemePreference?await t.authSchemePreference():[],o=zI(i,f),c=kI(t.httpAuthSchemes),h=gc(r),u=[];for(let l of o){let _=c.get(l.schemeId);if(!_){u.push(`HttpAuthScheme \`${l.schemeId}\` was not enabled for this service.`);continue}let w=_.identityProvider(await n.identityProviderConfigProvider(t));if(!w){u.push(`HttpAuthScheme \`${l.schemeId}\` did not have an IdentityProvider configured.`);continue}let{identityProperties:A={},signingProperties:M={}}=l.propertiesExtractor?.(t,r)||{};l.identityProperties=Object.assign(l.identityProperties||{},A),l.signingProperties=Object.assign(l.signingProperties||{},M),h.selectedHttpAuthScheme={httpAuthOption:l,identity:await w(l.identityProperties),signer:_.signer};break}if(!h.selectedHttpAuthScheme)throw Error(u.join(`
|
|
23
|
+
`));return s(e)},hw={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},XI=(t,{httpAuthSchemeParametersProvider:n,identityProviderConfigProvider:s})=>({applyToStack:(r)=>{r.addRelativeTo(Rc(t,{httpAuthSchemeParametersProvider:n,identityProviderConfigProvider:s}),hw)}}),uw={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"serializerMiddleware"},qI=(t,{httpAuthSchemeParametersProvider:n,identityProviderConfigProvider:s})=>({applyToStack:(r)=>{r.addRelativeTo(Rc(t,{httpAuthSchemeParametersProvider:n,identityProviderConfigProvider:s}),uw)}}),CI=(t)=>(n)=>{throw n},aI=(t,n)=>{},lw=(t)=>(n,s)=>async(r)=>{if(!Ec.isInstance(r.request))return n(r);let i=gc(s).selectedHttpAuthScheme;if(!i)throw Error("No HttpAuthScheme was selected: unable to sign request");let{httpAuthOption:{signingProperties:f={}},identity:o,signer:c}=i,h=await n({...r,request:await c.sign(r.request,o,f)}).catch((c.errorHandler||CI)(f));return(c.successHandler||aI)(h.response,f),h},_w={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},KI=(t)=>({applyToStack:(n)=>{n.addRelativeTo(lw(),_w)}}),VI=(t)=>{if(typeof t==="function")return t;let n=Promise.resolve(t);return()=>n},jI=async(t,n,s,r=(i)=>i,...e)=>{let i=new t(s);return i=r(i)??i,await n.send(i,...e)};function pI(t,n,s,r,e){return async function*(f,o,...c){let h=o,u=f.startingToken??h[s],l=!0,_;while(l){if(h[s]=u,e)h[e]=h[e]??f.pageSize;if(f.client instanceof t)_=await jI(n,f.client,o,f.withCommand,...c);else throw Error(`Invalid client, expected instance of ${t.name}`);yield _;let w=u;u=vI(_,r),l=!!(u&&(!f.stopOnSameToken||u!==w))}return}}var vI=(t,n)=>{let s=t,r=n.split(".");for(let e of r){if(!s||typeof s!=="object")return;s=s[e]}return s};function ZI(t,n,s){if(!t.__smithy_context)t.__smithy_context={features:{}};else if(!t.__smithy_context.features)t.__smithy_context.features={};t.__smithy_context.features[n]=s}class ww{authSchemes=new Map;constructor(t){for(let n in t){let s=t[n];if(s!==void 0)this.authSchemes.set(n,s)}}getIdentityProvider(t){return this.authSchemes.get(t)}}class Aw{async sign(t,n,s){if(!s)throw Error("request could not be signed with `apiKey` since the `name` and `in` signer properties are missing");if(!s.name)throw Error("request could not be signed with `apiKey` since the `name` signer property is missing");if(!s.in)throw Error("request could not be signed with `apiKey` since the `in` signer property is missing");if(!n.apiKey)throw Error("request could not be signed with `apiKey` since the `apiKey` is not defined");let r=Ec.clone(t);if(s.in===cw.QUERY)r.query[s.name]=n.apiKey;else if(s.in===cw.HEADER)r.headers[s.name]=s.scheme?`${s.scheme} ${n.apiKey}`:n.apiKey;else throw Error("request can only be signed with `apiKey` locations `query` or `header`, but found: `"+s.in+"`");return r}}class Mw{async sign(t,n,s){let r=Ec.clone(t);if(!n.token)throw Error("request could not be signed with `token` since the `token` is not defined");return r.headers.Authorization=`Bearer ${n.token}`,r}}class dw{async sign(t,n,s){return t}}var gw=(t)=>function(s){return Rw(s)&&s.expiration.getTime()-Date.now()<t},Ew=300000,tO=gw(Ew),Rw=(t)=>t.expiration!==void 0,nO=(t,n,s)=>{if(t===void 0)return;let r=typeof t!=="function"?async()=>Promise.resolve(t):t,e,i,f,o=!1,c=async(h)=>{if(!i)i=r(h);try{e=await i,f=!0,o=!1}finally{i=void 0}return e};if(n===void 0)return async(h)=>{if(!f||h?.forceRefresh)e=await c(h);return e};return async(h)=>{if(!f||h?.forceRefresh)e=await c(h);if(o)return e;if(!s(e))return o=!0,e;if(n(e))return await c(h),e;return e}};sO.DefaultIdentityProviderConfig=ww;sO.EXPIRATION_MS=Ew;sO.HttpApiKeyAuthSigner=Aw;sO.HttpBearerAuthSigner=Mw;sO.NoAuthSigner=dw;sO.createIsIdentityExpiredFunction=gw;sO.createPaginator=pI;sO.doesIdentityRequireRefresh=Rw;sO.getHttpAuthSchemeEndpointRuleSetPlugin=XI;sO.getHttpAuthSchemePlugin=qI;sO.getHttpSigningPlugin=KI;sO.httpAuthSchemeEndpointRuleSetMiddlewareOptions=hw;sO.httpAuthSchemeMiddleware=Rc;sO.httpAuthSchemeMiddlewareOptions=uw;sO.httpSigningMiddleware=lw;sO.httpSigningMiddlewareOptions=_w;sO.isIdentityExpired=tO;sO.memoizeIdentityProvider=nO;sO.normalizeProvider=VI;sO.setFeature=ZI});var bw=K((vr,bc)=>{(function(t,n){typeof vr=="object"&&typeof bc=="object"?bc.exports=n():typeof define=="function"&&define.amd?define([],n):typeof vr=="object"?vr.bowser=n():t.bowser=n()})(vr,function(){return function(t){var n={};function s(r){if(n[r])return n[r].exports;var e=n[r]={i:r,l:!1,exports:{}};return t[r].call(e.exports,e,e.exports,s),e.l=!0,e.exports}return s.m=t,s.c=n,s.d=function(r,e,i){s.o(r,e)||Object.defineProperty(r,e,{enumerable:!0,get:i})},s.r=function(r){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(r,"__esModule",{value:!0})},s.t=function(r,e){if(1&e&&(r=s(r)),8&e)return r;if(4&e&&typeof r=="object"&&r&&r.__esModule)return r;var i=Object.create(null);if(s.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:r}),2&e&&typeof r!="string")for(var f in r)s.d(i,f,function(o){return r[o]}.bind(null,f));return i},s.n=function(r){var e=r&&r.__esModule?function(){return r.default}:function(){return r};return s.d(e,"a",e),e},s.o=function(r,e){return Object.prototype.hasOwnProperty.call(r,e)},s.p="",s(s.s=90)}({17:function(t,n,s){n.__esModule=!0,n.default=void 0;var r=s(18),e=function(){function i(){}return i.getFirstMatch=function(f,o){var c=o.match(f);return c&&c.length>0&&c[1]||""},i.getSecondMatch=function(f,o){var c=o.match(f);return c&&c.length>1&&c[2]||""},i.matchAndReturnConst=function(f,o,c){if(f.test(o))return c},i.getWindowsVersionName=function(f){switch(f){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(f){var o=f.split(".").splice(0,2).map(function(u){return parseInt(u,10)||0});o.push(0);var c=o[0],h=o[1];if(c===10)switch(h){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(f){var o=f.split(".").splice(0,2).map(function(c){return parseInt(c,10)||0});if(o.push(0),!(o[0]===1&&o[1]<5))return o[0]===1&&o[1]<6?"Cupcake":o[0]===1&&o[1]>=6?"Donut":o[0]===2&&o[1]<2?"Eclair":o[0]===2&&o[1]===2?"Froyo":o[0]===2&&o[1]>2?"Gingerbread":o[0]===3?"Honeycomb":o[0]===4&&o[1]<1?"Ice Cream Sandwich":o[0]===4&&o[1]<4?"Jelly Bean":o[0]===4&&o[1]>=4?"KitKat":o[0]===5?"Lollipop":o[0]===6?"Marshmallow":o[0]===7?"Nougat":o[0]===8?"Oreo":o[0]===9?"Pie":void 0},i.getVersionPrecision=function(f){return f.split(".").length},i.compareVersions=function(f,o,c){c===void 0&&(c=!1);var h=i.getVersionPrecision(f),u=i.getVersionPrecision(o),l=Math.max(h,u),_=0,w=i.map([f,o],function(A){var M=l-i.getVersionPrecision(A),d=A+Array(M+1).join(".0");return i.map(d.split("."),function(E){return Array(20-E.length).join("0")+E}).reverse()});for(c&&(_=l-Math.min(h,u)),l-=1;l>=_;){if(w[0][l]>w[1][l])return 1;if(w[0][l]===w[1][l]){if(l===_)return 0;l-=1}else if(w[0][l]<w[1][l])return-1}},i.map=function(f,o){var c,h=[];if(Array.prototype.map)return Array.prototype.map.call(f,o);for(c=0;c<f.length;c+=1)h.push(o(f[c]));return h},i.find=function(f,o){var c,h;if(Array.prototype.find)return Array.prototype.find.call(f,o);for(c=0,h=f.length;c<h;c+=1){var u=f[c];if(o(u,c))return u}},i.assign=function(f){for(var o,c,h=f,u=arguments.length,l=Array(u>1?u-1:0),_=1;_<u;_++)l[_-1]=arguments[_];if(Object.assign)return Object.assign.apply(Object,[f].concat(l));var w=function(){var A=l[o];typeof A=="object"&&A!==null&&Object.keys(A).forEach(function(M){h[M]=A[M]})};for(o=0,c=l.length;o<c;o+=1)w();return f},i.getBrowserAlias=function(f){return r.BROWSER_ALIASES_MAP[f]},i.getBrowserTypeByAlias=function(f){return r.BROWSER_MAP[f]||""},i}();n.default=e,t.exports=n.default},18:function(t,n,s){n.__esModule=!0,n.ENGINE_MAP=n.OS_MAP=n.PLATFORMS_MAP=n.BROWSER_MAP=n.BROWSER_ALIASES_MAP=void 0,n.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"},n.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"},n.PLATFORMS_MAP={bot:"bot",desktop:"desktop",mobile:"mobile",tablet:"tablet",tv:"tv"},n.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"},n.ENGINE_MAP={Blink:"Blink",EdgeHTML:"EdgeHTML",Gecko:"Gecko",Presto:"Presto",Trident:"Trident",WebKit:"WebKit"}},90:function(t,n,s){n.__esModule=!0,n.default=void 0;var r,e=(r=s(91))&&r.__esModule?r:{default:r},i=s(18);function f(c,h){for(var u=0;u<h.length;u++){var l=h[u];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(c,l.key,l)}}var o=function(){function c(){}var h,u,l;return c.getParser=function(_,w,A){if(w===void 0&&(w=!1),A===void 0&&(A=null),typeof _!="string")throw Error("UserAgent should be a string");return new e.default(_,w,A)},c.parse=function(_,w){return w===void 0&&(w=null),new e.default(_,w).getResult()},h=c,l=[{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}}],(u=null)&&f(h.prototype,u),l&&f(h,l),c}();n.default=o,t.exports=n.default},91:function(t,n,s){n.__esModule=!0,n.default=void 0;var r=c(s(92)),e=c(s(93)),i=c(s(94)),f=c(s(95)),o=c(s(17));function c(u){return u&&u.__esModule?u:{default:u}}var h=function(){function u(_,w,A){if(w===void 0&&(w=!1),A===void 0&&(A=null),_==null||_==="")throw Error("UserAgent parameter can't be empty");this._ua=_;var M=!1;typeof w=="boolean"?(M=w,this._hints=A):this._hints=w!=null&&typeof w=="object"?w:null,this.parsedResult={},M!==!0&&this.parse()}var l=u.prototype;return l.getHints=function(){return this._hints},l.hasBrand=function(_){if(!this._hints||!Array.isArray(this._hints.brands))return!1;var w=_.toLowerCase();return this._hints.brands.some(function(A){return A.brand&&A.brand.toLowerCase()===w})},l.getBrandVersion=function(_){if(this._hints&&Array.isArray(this._hints.brands)){var w=_.toLowerCase(),A=this._hints.brands.find(function(M){return M.brand&&M.brand.toLowerCase()===w});return A?A.version:void 0}},l.getUA=function(){return this._ua},l.test=function(_){return _.test(this._ua)},l.parseBrowser=function(){var _=this;this.parsedResult.browser={};var w=o.default.find(r.default,function(A){if(typeof A.test=="function")return A.test(_);if(Array.isArray(A.test))return A.test.some(function(M){return _.test(M)});throw Error("Browser's test function is not valid")});return w&&(this.parsedResult.browser=w.describe(this.getUA(),this)),this.parsedResult.browser},l.getBrowser=function(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()},l.getBrowserName=function(_){return _?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""},l.getBrowserVersion=function(){return this.getBrowser().version},l.getOS=function(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()},l.parseOS=function(){var _=this;this.parsedResult.os={};var w=o.default.find(e.default,function(A){if(typeof A.test=="function")return A.test(_);if(Array.isArray(A.test))return A.test.some(function(M){return _.test(M)});throw Error("Browser's test function is not valid")});return w&&(this.parsedResult.os=w.describe(this.getUA())),this.parsedResult.os},l.getOSName=function(_){var w=this.getOS().name;return _?String(w).toLowerCase()||"":w||""},l.getOSVersion=function(){return this.getOS().version},l.getPlatform=function(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()},l.getPlatformType=function(_){_===void 0&&(_=!1);var w=this.getPlatform().type;return _?String(w).toLowerCase()||"":w||""},l.parsePlatform=function(){var _=this;this.parsedResult.platform={};var w=o.default.find(i.default,function(A){if(typeof A.test=="function")return A.test(_);if(Array.isArray(A.test))return A.test.some(function(M){return _.test(M)});throw Error("Browser's test function is not valid")});return w&&(this.parsedResult.platform=w.describe(this.getUA())),this.parsedResult.platform},l.getEngine=function(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()},l.getEngineName=function(_){return _?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""},l.parseEngine=function(){var _=this;this.parsedResult.engine={};var w=o.default.find(f.default,function(A){if(typeof A.test=="function")return A.test(_);if(Array.isArray(A.test))return A.test.some(function(M){return _.test(M)});throw Error("Browser's test function is not valid")});return w&&(this.parsedResult.engine=w.describe(this.getUA())),this.parsedResult.engine},l.parse=function(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this},l.getResult=function(){return o.default.assign({},this.parsedResult)},l.satisfies=function(_){var w=this,A={},M=0,d={},E=0;if(Object.keys(_).forEach(function(Q){var rt=_[Q];typeof rt=="string"?(d[Q]=rt,E+=1):typeof rt=="object"&&(A[Q]=rt,M+=1)}),M>0){var b=Object.keys(A),L=o.default.find(b,function(Q){return w.isOS(Q)});if(L){var S=this.satisfies(A[L]);if(S!==void 0)return S}var O=o.default.find(b,function(Q){return w.isPlatform(Q)});if(O){var x=this.satisfies(A[O]);if(x!==void 0)return x}}if(E>0){var X=Object.keys(d),v=o.default.find(X,function(Q){return w.isBrowser(Q,!0)});if(v!==void 0)return this.compareVersion(d[v])}},l.isBrowser=function(_,w){w===void 0&&(w=!1);var A=this.getBrowserName().toLowerCase(),M=_.toLowerCase(),d=o.default.getBrowserTypeByAlias(M);return w&&d&&(M=d.toLowerCase()),M===A},l.compareVersion=function(_){var w=[0],A=_,M=!1,d=this.getBrowserVersion();if(typeof d=="string")return _[0]===">"||_[0]==="<"?(A=_.substr(1),_[1]==="="?(M=!0,A=_.substr(2)):w=[],_[0]===">"?w.push(1):w.push(-1)):_[0]==="="?A=_.substr(1):_[0]==="~"&&(M=!0,A=_.substr(1)),w.indexOf(o.default.compareVersions(d,A,M))>-1},l.isOS=function(_){return this.getOSName(!0)===String(_).toLowerCase()},l.isPlatform=function(_){return this.getPlatformType(!0)===String(_).toLowerCase()},l.isEngine=function(_){return this.getEngineName(!0)===String(_).toLowerCase()},l.is=function(_,w){return w===void 0&&(w=!1),this.isBrowser(_,w)||this.isOS(_)||this.isPlatform(_)},l.some=function(_){var w=this;return _===void 0&&(_=[]),_.some(function(A){return w.is(A)})},u}();n.default=h,t.exports=n.default},92:function(t,n,s){n.__esModule=!0,n.default=void 0;var r,e=(r=s(17))&&r.__esModule?r:{default:r},i=/version\/(\d+(\.?_?\d+)+)/i,f=[{test:[/gptbot/i],describe:function(o){var c={name:"GPTBot"},h=e.default.getFirstMatch(/gptbot\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/chatgpt-user/i],describe:function(o){var c={name:"ChatGPT-User"},h=e.default.getFirstMatch(/chatgpt-user\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/oai-searchbot/i],describe:function(o){var c={name:"OAI-SearchBot"},h=e.default.getFirstMatch(/oai-searchbot\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(o){var c={name:"ClaudeBot"},h=e.default.getFirstMatch(/(?:claudebot|claude-web|claude-user|claude-searchbot)\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(o){var c={name:"Omgilibot"},h=e.default.getFirstMatch(/(?:omgilibot|webzio-extended)\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/diffbot/i],describe:function(o){var c={name:"Diffbot"},h=e.default.getFirstMatch(/diffbot\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/perplexitybot/i],describe:function(o){var c={name:"PerplexityBot"},h=e.default.getFirstMatch(/perplexitybot\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/perplexity-user/i],describe:function(o){var c={name:"Perplexity-User"},h=e.default.getFirstMatch(/perplexity-user\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/youbot/i],describe:function(o){var c={name:"YouBot"},h=e.default.getFirstMatch(/youbot\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/meta-webindexer/i],describe:function(o){var c={name:"Meta-WebIndexer"},h=e.default.getFirstMatch(/meta-webindexer\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/meta-externalads/i],describe:function(o){var c={name:"Meta-ExternalAds"},h=e.default.getFirstMatch(/meta-externalads\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/meta-externalagent/i],describe:function(o){var c={name:"Meta-ExternalAgent"},h=e.default.getFirstMatch(/meta-externalagent\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/meta-externalfetcher/i],describe:function(o){var c={name:"Meta-ExternalFetcher"},h=e.default.getFirstMatch(/meta-externalfetcher\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/googlebot/i],describe:function(o){var c={name:"Googlebot"},h=e.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/linespider/i],describe:function(o){var c={name:"Linespider"},h=e.default.getFirstMatch(/(?:linespider)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/amazonbot/i],describe:function(o){var c={name:"AmazonBot"},h=e.default.getFirstMatch(/amazonbot\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/bingbot/i],describe:function(o){var c={name:"BingCrawler"},h=e.default.getFirstMatch(/bingbot\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/baiduspider/i],describe:function(o){var c={name:"BaiduSpider"},h=e.default.getFirstMatch(/baiduspider\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/duckduckbot/i],describe:function(o){var c={name:"DuckDuckBot"},h=e.default.getFirstMatch(/duckduckbot\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/ia_archiver/i],describe:function(o){var c={name:"InternetArchiveCrawler"},h=e.default.getFirstMatch(/ia_archiver\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{name:"FacebookExternalHit"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(o){var c={name:"SlackBot"},h=e.default.getFirstMatch(/(?:slackbot|slack-imgproxy)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),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(o){var c={name:"Opera"},h=e.default.getFirstMatch(i,o)||e.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/opr\/|opios/i],describe:function(o){var c={name:"Opera"},h=e.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/SamsungBrowser/i],describe:function(o){var c={name:"Samsung Internet for Android"},h=e.default.getFirstMatch(i,o)||e.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/Whale/i],describe:function(o){var c={name:"NAVER Whale Browser"},h=e.default.getFirstMatch(i,o)||e.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/PaleMoon/i],describe:function(o){var c={name:"Pale Moon"},h=e.default.getFirstMatch(i,o)||e.default.getFirstMatch(/(?:PaleMoon)[\s/](\d+(?:\.\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/MZBrowser/i],describe:function(o){var c={name:"MZ Browser"},h=e.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/focus/i],describe:function(o){var c={name:"Focus"},h=e.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/swing/i],describe:function(o){var c={name:"Swing"},h=e.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/coast/i],describe:function(o){var c={name:"Opera Coast"},h=e.default.getFirstMatch(i,o)||e.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(o){var c={name:"Opera Touch"},h=e.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/yabrowser/i],describe:function(o){var c={name:"Yandex Browser"},h=e.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/ucbrowser/i],describe:function(o){var c={name:"UC Browser"},h=e.default.getFirstMatch(i,o)||e.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/Maxthon|mxios/i],describe:function(o){var c={name:"Maxthon"},h=e.default.getFirstMatch(i,o)||e.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/epiphany/i],describe:function(o){var c={name:"Epiphany"},h=e.default.getFirstMatch(i,o)||e.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/puffin/i],describe:function(o){var c={name:"Puffin"},h=e.default.getFirstMatch(i,o)||e.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/sleipnir/i],describe:function(o){var c={name:"Sleipnir"},h=e.default.getFirstMatch(i,o)||e.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/k-meleon/i],describe:function(o){var c={name:"K-Meleon"},h=e.default.getFirstMatch(i,o)||e.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/micromessenger/i],describe:function(o){var c={name:"WeChat"},h=e.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/qqbrowser/i],describe:function(o){var c={name:/qqbrowserlite/i.test(o)?"QQ Browser Lite":"QQ Browser"},h=e.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/msie|trident/i],describe:function(o){var c={name:"Internet Explorer"},h=e.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/\sedg\//i],describe:function(o){var c={name:"Microsoft Edge"},h=e.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/edg([ea]|ios)/i],describe:function(o){var c={name:"Microsoft Edge"},h=e.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/vivaldi/i],describe:function(o){var c={name:"Vivaldi"},h=e.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/seamonkey/i],describe:function(o){var c={name:"SeaMonkey"},h=e.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/sailfish/i],describe:function(o){var c={name:"Sailfish"},h=e.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,o);return h&&(c.version=h),c}},{test:[/silk/i],describe:function(o){var c={name:"Amazon Silk"},h=e.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/phantom/i],describe:function(o){var c={name:"PhantomJS"},h=e.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/slimerjs/i],describe:function(o){var c={name:"SlimerJS"},h=e.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(o){var c={name:"BlackBerry"},h=e.default.getFirstMatch(i,o)||e.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/(web|hpw)[o0]s/i],describe:function(o){var c={name:"WebOS Browser"},h=e.default.getFirstMatch(i,o)||e.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/bada/i],describe:function(o){var c={name:"Bada"},h=e.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/tizen/i],describe:function(o){var c={name:"Tizen"},h=e.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/qupzilla/i],describe:function(o){var c={name:"QupZilla"},h=e.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/librewolf/i],describe:function(o){var c={name:"LibreWolf"},h=e.default.getFirstMatch(/(?:librewolf)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/firefox|iceweasel|fxios/i],describe:function(o){var c={name:"Firefox"},h=e.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/electron/i],describe:function(o){var c={name:"Electron"},h=e.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/sogoumobilebrowser/i,/metasr/i,/se 2\.[x]/i],describe:function(o){var c={name:"Sogou Browser"},h=e.default.getFirstMatch(/(?:sogoumobilebrowser)[\s/](\d+(\.?_?\d+)+)/i,o),u=e.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,o),l=e.default.getFirstMatch(/se ([\d.]+)x/i,o),_=h||u||l;return _&&(c.version=_),c}},{test:[/MiuiBrowser/i],describe:function(o){var c={name:"Miui"},h=e.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:function(o){return!!o.hasBrand("DuckDuckGo")||o.test(/\sDdg\/[\d.]+$/i)},describe:function(o,c){var h={name:"DuckDuckGo"};if(c){var u=c.getBrandVersion("DuckDuckGo");if(u)return h.version=u,h}var l=e.default.getFirstMatch(/\sDdg\/([\d.]+)$/i,o);return l&&(h.version=l),h}},{test:function(o){return o.hasBrand("Brave")},describe:function(o,c){var h={name:"Brave"};if(c){var u=c.getBrandVersion("Brave");if(u)return h.version=u,h}return h}},{test:[/chromium/i],describe:function(o){var c={name:"Chromium"},h=e.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/chrome|crios|crmo/i],describe:function(o){var c={name:"Chrome"},h=e.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/GSA/i],describe:function(o){var c={name:"Google Search"},h=e.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:function(o){var c=!o.test(/like android/i),h=o.test(/android/i);return c&&h},describe:function(o){var c={name:"Android Browser"},h=e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/playstation 4/i],describe:function(o){var c={name:"PlayStation 4"},h=e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/safari|applewebkit/i],describe:function(o){var c={name:"Safari"},h=e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/.*/i],describe:function(o){var c=o.search("\\(")!==-1?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:e.default.getFirstMatch(c,o),version:e.default.getSecondMatch(c,o)}}}];n.default=f,t.exports=n.default},93:function(t,n,s){n.__esModule=!0,n.default=void 0;var r,e=(r=s(17))&&r.__esModule?r:{default:r},i=s(18),f=[{test:[/Roku\/DVP/],describe:function(o){var c=e.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,o);return{name:i.OS_MAP.Roku,version:c}}},{test:[/windows phone/i],describe:function(o){var c=e.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,o);return{name:i.OS_MAP.WindowsPhone,version:c}}},{test:[/windows /i],describe:function(o){var c=e.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,o),h=e.default.getWindowsVersionName(c);return{name:i.OS_MAP.Windows,version:c,versionName:h}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(o){var c={name:i.OS_MAP.iOS},h=e.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,o);return h&&(c.version=h),c}},{test:[/macintosh/i],describe:function(o){var c=e.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,o).replace(/[_\s]/g,"."),h=e.default.getMacOSVersionName(c),u={name:i.OS_MAP.MacOS,version:c};return h&&(u.versionName=h),u}},{test:[/(ipod|iphone|ipad)/i],describe:function(o){var c=e.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,o).replace(/[_\s]/g,".");return{name:i.OS_MAP.iOS,version:c}}},{test:[/OpenHarmony/i],describe:function(o){var c=e.default.getFirstMatch(/OpenHarmony\s+(\d+(\.\d+)*)/i,o);return{name:i.OS_MAP.HarmonyOS,version:c}}},{test:function(o){var c=!o.test(/like android/i),h=o.test(/android/i);return c&&h},describe:function(o){var c=e.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,o),h=e.default.getAndroidVersionName(c),u={name:i.OS_MAP.Android,version:c};return h&&(u.versionName=h),u}},{test:[/(web|hpw)[o0]s/i],describe:function(o){var c=e.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,o),h={name:i.OS_MAP.WebOS};return c&&c.length&&(h.version=c),h}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(o){var c=e.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,o)||e.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,o)||e.default.getFirstMatch(/\bbb(\d+)/i,o);return{name:i.OS_MAP.BlackBerry,version:c}}},{test:[/bada/i],describe:function(o){var c=e.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,o);return{name:i.OS_MAP.Bada,version:c}}},{test:[/tizen/i],describe:function(o){var c=e.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,o);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(o){var c=e.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,o);return{name:i.OS_MAP.PlayStation4,version:c}}}];n.default=f,t.exports=n.default},94:function(t,n,s){n.__esModule=!0,n.default=void 0;var r,e=(r=s(17))&&r.__esModule?r:{default:r},i=s(18),f=[{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(o){var c=e.default.getFirstMatch(/(can-l01)/i,o)&&"Nova",h={type:i.PLATFORMS_MAP.mobile,vendor:"Huawei"};return c&&(h.model=c),h}},{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(o){var c=o.test(/ipod|iphone/i),h=o.test(/like (ipod|iphone)/i);return c&&!h},describe:function(o){var c=e.default.getFirstMatch(/(ipod|iphone)/i,o);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(o){var c=e.default.getFirstMatch(/Nokia\s+([0-9]+(\.[0-9]+)?)/i,o),h={type:i.PLATFORMS_MAP.mobile,vendor:"Nokia"};return c&&(h.model=c),h}},{test:[/[^-]mobi/i],describe:function(){return{type:i.PLATFORMS_MAP.mobile}}},{test:function(o){return o.getBrowserName(!0)==="blackberry"},describe:function(){return{type:i.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(o){return o.getBrowserName(!0)==="bada"},describe:function(){return{type:i.PLATFORMS_MAP.mobile}}},{test:function(o){return o.getBrowserName()==="windows phone"},describe:function(){return{type:i.PLATFORMS_MAP.mobile,vendor:"Microsoft"}}},{test:function(o){var c=Number(String(o.getOSVersion()).split(".")[0]);return o.getOSName(!0)==="android"&&c>=3},describe:function(){return{type:i.PLATFORMS_MAP.tablet}}},{test:function(o){return o.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(o){return o.getOSName(!0)==="macos"},describe:function(){return{type:i.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(o){return o.getOSName(!0)==="windows"},describe:function(){return{type:i.PLATFORMS_MAP.desktop}}},{test:function(o){return o.getOSName(!0)==="linux"},describe:function(){return{type:i.PLATFORMS_MAP.desktop}}},{test:function(o){return o.getOSName(!0)==="playstation 4"},describe:function(){return{type:i.PLATFORMS_MAP.tv}}},{test:function(o){return o.getOSName(!0)==="roku"},describe:function(){return{type:i.PLATFORMS_MAP.tv}}}];n.default=f,t.exports=n.default},95:function(t,n,s){n.__esModule=!0,n.default=void 0;var r,e=(r=s(17))&&r.__esModule?r:{default:r},i=s(18),f=[{test:function(o){return o.getBrowserName(!0)==="microsoft edge"},describe:function(o){if(/\sedg\//i.test(o))return{name:i.ENGINE_MAP.Blink};var c=e.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,o);return{name:i.ENGINE_MAP.EdgeHTML,version:c}}},{test:[/trident/i],describe:function(o){var c={name:i.ENGINE_MAP.Trident},h=e.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:function(o){return o.test(/presto/i)},describe:function(o){var c={name:i.ENGINE_MAP.Presto},h=e.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:function(o){var c=o.test(/gecko/i),h=o.test(/like gecko/i);return c&&!h},describe:function(o){var c={name:i.ENGINE_MAP.Gecko},h=e.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:i.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(o){var c={name:i.ENGINE_MAP.WebKit},h=e.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}}];n.default=f,t.exports=n.default}})})});var kt=K((Ry)=>{var{Retry:LO,RETRY_MODES:Tw}=pr(),{HttpRequest:Ic,parseUrl:IO}=Tt(),{InvokeStore:Sw}=fw(),{normalizeProvider:OO}=Qn(),{platform:yO,release:GO}=j("os"),{versions:Tc,env:$w}=j("process"),{isValidHostLabel:BO,isIpAddress:yw,customEndpointFunctions:mO}=fs(),{EndpointError:FO,resolveEndpoint:PO}=fs();Ry.EndpointError=FO;Ry.isIpAddress=yw;Ry.resolveEndpoint=PO;var{loadConfig:HO,NODE_REGION_CONFIG_OPTIONS:Gw,NODE_REGION_CONFIG_FILE_OPTIONS:Bw}=Rt(),{REGION_ENV_NAME:NO,REGION_INI_NAME:DO,resolveRegionConfig:WO}=Rt();Ry.NODE_REGION_CONFIG_FILE_OPTIONS=Bw;Ry.NODE_REGION_CONFIG_OPTIONS=Gw;Ry.REGION_ENV_NAME=NO;Ry.REGION_INI_NAME=DO;Ry.resolveRegionConfig=WO;var Si={warningEmitted:!1},YO=(t)=>{if(t&&!Si.warningEmitted){if(process.env.AWS_SDK_JS_NODE_VERSION_SUPPORT_WARNING_DISABLED==="true"){Si.warningEmitted=!0;return}let n=parseInt(t.substring(1,t.indexOf("."))),s=22;if(n<s)Si.warningEmitted=!0,process.emitWarning(`NodeVersionSupportWarning: The AWS SDK for JavaScript (v3)
|
|
24
|
+
versions published after the first week of January 2027
|
|
25
|
+
will require node >=${s}. You are running node ${t}.
|
|
26
|
+
|
|
27
|
+
To continue receiving updates to AWS services, bug fixes,
|
|
28
|
+
and security updates please upgrade to node >=${s}.
|
|
29
|
+
|
|
30
|
+
More information can be found at: https://a.co/c895JFp`)}},xO=()=>(t,n)=>async(s)=>{return n.__retryLongPoll=!0,t(s)},QO={name:"longPollMiddleware",tags:["RETRY"],step:"initialize",override:!0},JO=(t)=>({applyToStack:(n)=>{n.add(xO(),QO)}});function zO(t,n,s){if(!t.$source)t.$source={};return t.$source[n]=s,t}LO.v2026||=typeof process==="object"&&process.env?.AWS_NEW_RETRIES_2026==="true";function on(t,n,s){if(!t.__aws_sdk_context)t.__aws_sdk_context={features:{}};else if(!t.__aws_sdk_context.features)t.__aws_sdk_context.features={};t.__aws_sdk_context.features[n]=s}function kO(t,n,s){if(!t.$source)t.$source={};return t.$source[n]=s,t}function XO(t){return t}var mw=(t)=>(n)=>async(s)=>{if(!Ic.isInstance(s.request))return n(s);let{request:r}=s,{handlerProtocol:e=""}=t.requestHandler.metadata||{};if(e.indexOf("h2")>=0&&!r.headers[":authority"])delete r.headers.host,r.headers[":authority"]=r.hostname+(r.port?":"+r.port:"");else if(!r.headers.host){let i=r.hostname;if(r.port!=null)i+=`:${r.port}`;r.headers.host=i}return n(s)},Fw={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},qO=(t)=>({applyToStack:(n)=>{n.add(mw(t),Fw)}}),Pw=()=>(t,n)=>async(s)=>{try{let r=await t(s),{clientName:e,commandName:i,logger:f,dynamoDbDocumentClientOptions:o={}}=n,{overrideInputFilterSensitiveLog:c,overrideOutputFilterSensitiveLog:h}=o,u=c??n.inputFilterSensitiveLog,l=h??n.outputFilterSensitiveLog,{$metadata:_,...w}=r.output;return f?.info?.({clientName:e,commandName:i,input:u(s.input),output:l(w),metadata:_}),r}catch(r){let{clientName:e,commandName:i,logger:f,dynamoDbDocumentClientOptions:o={}}=n,{overrideInputFilterSensitiveLog:c}=o,h=c??n.inputFilterSensitiveLog;throw f?.error?.({clientName:e,commandName:i,input:h(s.input),error:r,metadata:r.$metadata}),r}},Hw={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},CO=(t)=>({applyToStack:(n)=>{n.add(Pw(),Hw)}}),Nw={step:"build",tags:["RECURSION_DETECTION","TRACE_CONTEXT_PROPAGATION"],name:"recursionDetectionMiddleware",override:!0,priority:"low"},aO="AWS_LAMBDA_FUNCTION_NAME",KO="_X_AMZN_TRACE_ID",Sc="X-Amzn-Trace-Id",Lc="traceparent",Dw="tracestate",Ww="baggage",Yw=()=>(t)=>async(n)=>{let{request:s}=n;if(!Ic.isInstance(s))return t(n);let r;{let e=Object.keys(s.headers??{}).find((i)=>i.toLowerCase()===Sc.toLowerCase())??Sc;if(!s.headers.hasOwnProperty(e)){let i=process.env[aO],f=process.env[KO];r??=await Sw.getInstanceAsync();let c=r?.getXRayTraceId()??f,h=(u)=>typeof u==="string"&&u.length>0;if(h(i)&&h(c))s.headers[Sc]=c}}if(VO(s.headers),!s.headers[Lc]){let i=(r??=await Sw.getInstanceAsync())?.getTraceparent?.();if(i){s.headers[Lc]=i;let f=r?.getTracestate?.();if(f)s.headers[Dw]=f;let o=r?.getBaggage?.();if(o)s.headers[Ww]=o}}return t(n)};function VO(t){for(let n of Object.keys(t)){let s=n.toLowerCase();if(n!==s&&(s===Lc||s===Dw||s===Ww))t[s]=t[n],delete t[n]}}var jO=(t)=>({applyToStack:(n)=>{n.add(Yw(),Nw)}}),Oc=void 0;function pO(t){if(t===void 0)return!0;return typeof t==="string"&&t.length<=50}function vO(t){let n=OO(t.userAgentAppId??Oc),{customUserAgent:s}=t;return Object.assign(t,{customUserAgent:typeof s==="string"?[[s]]:s,userAgentAppId:async()=>{let r=await n();if(!pO(r)){let e=t.logger?.constructor?.name==="NoOpLogger"||!t.logger?console:t.logger;if(typeof r!=="string")e?.warn("userAgentAppId must be a string or undefined.");else if(r.length>50)e?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.")}return r}})}var xw={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"},Qw=xw,Jw="",zw=(t)=>{let{partitions:n}=Qw;for(let r of n){let{regions:e,outputs:i}=r;for(let[f,o]of Object.entries(e))if(f===t)return{...i,...o}}for(let r of n){let{regionRegex:e,outputs:i}=r;if(new RegExp(e).test(t))return{...i}}let s=n.find((r)=>r.id==="aws");if(!s)throw Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");return{...s.outputs}},kw=(t,n="")=>{Qw=t,Jw=n},ZO=()=>{kw(xw,"")},Xw=()=>Jw,ty=/\d{12}\.ddb/;async function ny(t,n,s){if(s.request?.headers?.["smithy-protocol"]==="rpc-v2-cbor")on(t,"PROTOCOL_RPC_V2_CBOR","M");if(typeof n.retryStrategy==="function"){let i=await n.retryStrategy();if(typeof i.mode==="string")switch(i.mode){case Tw.ADAPTIVE:on(t,"RETRY_MODE_ADAPTIVE","F");break;case Tw.STANDARD:on(t,"RETRY_MODE_STANDARD","E");break}}if(typeof n.accountIdEndpointMode==="function"){let i=t.endpointV2;if(String(i?.url?.hostname).match(ty))on(t,"ACCOUNT_ID_ENDPOINT","O");switch(await n.accountIdEndpointMode?.()){case"disabled":on(t,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":on(t,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":on(t,"ACCOUNT_ID_MODE_REQUIRED","R");break}}let e=t.__smithy_context?.selectedHttpAuthScheme?.identity;if(e?.$source){let i=e;if(i.accountId)on(t,"RESOLVED_ACCOUNT_ID","T");for(let[f,o]of Object.entries(i.$source??{}))on(t,f,o)}}var Uw="user-agent",$c="x-amz-user-agent",Lw=" ",Uc="/",sy=/[^!$%&'*+\-.^_`|~\w]/g,ry=/[^!$%&'*+\-.^_`|~\w#]/g,Iw="-",ey=1024;function iy(t){let n="";for(let s in t){let r=t[s];if(n.length+r.length+1<=ey){if(n.length)n+=","+r;else n+=r;continue}break}return n}var qw=(t)=>(n,s)=>async(r)=>{let{request:e}=r;if(!Ic.isInstance(e))return n(r);let{headers:i}=e,f=s?.userAgent?.map(Ti)||[],o=(await t.defaultUserAgentProvider()).map(Ti);await ny(s,t,r);let c=s;o.push(`m/${iy(Object.assign({},s.__smithy_context?.features,c.__aws_sdk_context?.features))}`);let h=t?.customUserAgent?.map(Ti)||[],u=await t.userAgentAppId();if(u)o.push(Ti(["app",`${u}`]));let l=Xw(),_=(l?[l]:[]).concat([...o,...f,...h]).join(Lw),w=[...o.filter((A)=>A.startsWith("aws-sdk-")),...h].join(Lw);if(t.runtime!=="browser"){if(w)i[$c]=i[$c]?`${i[Uw]} ${w}`:w;i[Uw]=_}else i[$c]=_;return n({...r,request:e})},Ti=(t)=>{let n=t[0].split(Uc).map((f)=>f.replace(sy,Iw)).join(Uc),s=t[1]?.replace(ry,Iw),r=n.indexOf(Uc),e=n.substring(0,r),i=n.substring(r+1);if(e==="api")i=i.toLowerCase();return[e,i,s].filter((f)=>f&&f.length>0).reduce((f,o,c)=>{switch(c){case 0:return o;case 1:return`${f}/${o}`;default:return`${f}#${o}`}},"")},Cw={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},oy=(t)=>({applyToStack:(n)=>{n.add(qw(t),Cw)}}),fy=()=>{let t=["deno","bun","llrt"];for(let n of t)if(Tc[n])return[`md/${n}`,Tc[n]];return["md/nodejs",Tc.node]},aw={isCrtAvailable:!1},cy=()=>{if(aw.isCrtAvailable)return["md/crt-avail"];return null},Kw=({serviceId:t,clientVersion:n})=>{let s=fy();return async(r)=>{let e=[["aws-sdk-js",n],["ua","2.1"],[`os/${yO()}`,GO()],["lang/js"],s],i=cy();if(i)e.push(i);if(t)e.push([`api/${t}`,n]);if($w.AWS_EXECUTION_ENV)e.push([`exec-env/${$w.AWS_EXECUTION_ENV}`]);let f=await r?.userAgentAppId?.();return f?[...e,[`app/${f}`]]:[...e]}},hy=Kw,Vw="AWS_SDK_UA_APP_ID",jw="sdk_ua_app_id",uy="sdk-ua-app-id",ly={environmentVariableSelector:(t)=>t[Vw],configFileSelector:(t)=>t[jw]??t[uy],default:Oc},_y=({serviceId:t,clientVersion:n})=>async(s)=>{let r=bw(),e=r.parse??r.default.parse??(()=>""),i=typeof window<"u"&&window?.navigator?.userAgent?e(window.navigator.userAgent):void 0,f=[["aws-sdk-js",n],["ua","2.1"],[`os/${i?.os?.name||"other"}`,i?.os?.version],["lang/js"],["md/browser",`${i?.browser?.name??"unknown"}_${i?.browser?.version??"unknown"}`]];if(t)f.push([`api/${t}`,n]);let o=await s?.userAgentAppId?.();if(o)f.push([`app/${o}`]);return f},wy={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";return},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";return}},yc=(t,n=!1)=>{if(n){for(let s of t.split("."))if(!yc(s))return!1;return!0}if(!BO(t))return!1;if(t.length<3||t.length>63)return!1;if(t!==t.toLowerCase())return!1;if(yw(t))return!1;return!0},Ow=":",Ay="/",pw=(t)=>{let n=t.split(Ow);if(n.length<6)return null;let[s,r,e,i,f,...o]=n;if(s!=="arn"||r===""||e===""||o.join(Ow)==="")return null;let c=o.map((h)=>h.split(Ay)).flat();return{partition:r,service:e,region:i,accountId:f,resourceId:c}},vw={isVirtualHostableS3Bucket:yc,parseArn:pw,partition:zw};mO.aws=vw;var My=(t)=>{if(typeof t.endpointProvider!=="function")throw Error("@aws-sdk/util-endpoint - endpointProvider and endpoint missing in config for this client.");let{endpoint:n}=t;if(n===void 0)t.endpoint=async()=>{return Zw(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}))};return t},Zw=(t)=>IO(t.url);function dy(t={}){return HO({...Gw,async default(){if(!tA.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.");return"us-east-1"}},{...Bw,...t})}var tA={silence:!1},gy=(t)=>{return{setRegion(n){t.region=n},region(){return t.region}}},Ey=(t)=>{return{region:t.region()}};Ry.DEFAULT_UA_APP_ID=Oc;Ry.NODE_APP_ID_CONFIG_OPTIONS=ly;Ry.UA_APP_ID_ENV_NAME=Vw;Ry.UA_APP_ID_INI_NAME=jw;Ry.awsEndpointFunctions=vw;Ry.createDefaultUserAgentProvider=Kw;Ry.createUserAgentStringParsingProvider=_y;Ry.crtAvailability=aw;Ry.defaultUserAgent=hy;Ry.emitWarningIfUnsupportedVersion=YO;Ry.fallback=wy;Ry.getAwsRegionExtensionConfiguration=gy;Ry.getHostHeaderPlugin=qO;Ry.getLoggerPlugin=CO;Ry.getLongPollPlugin=JO;Ry.getRecursionDetectionPlugin=jO;Ry.getUserAgentMiddlewareOptions=Cw;Ry.getUserAgentPlugin=oy;Ry.getUserAgentPrefix=Xw;Ry.hostHeaderMiddleware=mw;Ry.hostHeaderMiddlewareOptions=Fw;Ry.isVirtualHostableS3Bucket=yc;Ry.loggerMiddleware=Pw;Ry.loggerMiddlewareOptions=Hw;Ry.parseArn=pw;Ry.partition=zw;Ry.recursionDetectionMiddleware=Yw;Ry.recursionDetectionMiddlewareOptions=Nw;Ry.resolveAwsRegionExtensionConfiguration=Ey;Ry.resolveDefaultAwsRegionalEndpointsConfig=My;Ry.resolveHostHeaderConfig=XO;Ry.resolveUserAgentConfig=vO;Ry.setCredentialFeature=zO;Ry.setFeature=on;Ry.setPartitionInfo=kw;Ry.setTokenFeature=kO;Ry.state=Si;Ry.stsRegionDefaultResolver=dy;Ry.stsRegionWarning=tA;Ry.toEndpointV1=Zw;Ry.useDefaultPartitionInfo=ZO;Ry.userAgentMiddleware=qw});var PA=K((GG)=>{var{fromUtf8:fA,fromHex:EG,toHex:_s,toUint8Array:se,isArrayBuffer:RG}=bt(),{normalizeProvider:cA}=En(),{escapeUri:$i,HttpRequest:lA}=Tt();class _A{format(t){let n=[];for(let e of Object.keys(t)){let i=fA(e);n.push(Uint8Array.from([i.byteLength]),i,this.formatHeaderValue(t[e]))}let s=new Uint8Array(n.reduce((e,i)=>e+i.byteLength,0)),r=0;for(let e of n)s.set(e,r),r+=e.byteLength;return s}formatHeaderValue(t){switch(t.type){case"boolean":return Uint8Array.from([t.value?Pt.boolTrue:Pt.boolFalse]);case"byte":return Uint8Array.from([Pt.byte,t.value]);case"short":let n=new DataView(new ArrayBuffer(3));return n.setUint8(0,Pt.short),n.setInt16(1,t.value,!1),new Uint8Array(n.buffer);case"integer":let s=new DataView(new ArrayBuffer(5));return s.setUint8(0,Pt.integer),s.setInt32(1,t.value,!1),new Uint8Array(s.buffer);case"long":let r=new Uint8Array(9);return r[0]=Pt.long,r.set(t.value.bytes,1),r;case"binary":let e=new DataView(new ArrayBuffer(3+t.value.byteLength));e.setUint8(0,Pt.byteArray),e.setUint16(1,t.value.byteLength,!1);let i=new Uint8Array(e.buffer);return i.set(t.value,3),i;case"string":let f=fA(t.value),o=new DataView(new ArrayBuffer(3+f.byteLength));o.setUint8(0,Pt.string),o.setUint16(1,f.byteLength,!1);let c=new Uint8Array(o.buffer);return c.set(f,3),c;case"timestamp":let h=new Uint8Array(9);return h[0]=Pt.timestamp,h.set(Fc.fromNumber(t.value.valueOf()).bytes,1),h;case"uuid":if(!bG.test(t.value))throw Error(`Invalid UUID received: ${t.value}`);let u=new Uint8Array(17);return u[0]=Pt.uuid,u.set(EG(t.value.replace(/-/g,"")),1),u}}}var Pt;(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"})(Pt||(Pt={}));var bG=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class Fc{bytes;constructor(t){if(this.bytes=t,t.byteLength!==8)throw Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(t){if(t>9223372036854776000||t<-9223372036854776000)throw Error(`${t} is too large (or, if negative, too small) to represent as an Int64`);let n=new Uint8Array(8);for(let s=7,r=Math.abs(Math.round(t));s>-1&&r>0;s--,r/=256)n[s]=r;if(t<0)hA(n);return new Fc(n)}valueOf(){let t=this.bytes.slice(0),n=t[0]&128;if(n)hA(t);return parseInt(_s(t),16)*(n?-1:1)}toString(){return String(this.valueOf())}}function hA(t){for(let n=0;n<8;n++)t[n]^=255;for(let n=7;n>-1;n--)if(t[n]++,t[n]!==0)break}var wA="X-Amz-Algorithm",AA="X-Amz-Credential",Pc="X-Amz-Date",MA="X-Amz-SignedHeaders",dA="X-Amz-Expires",Hc="X-Amz-Signature",Nc="X-Amz-Security-Token",TG="X-Amz-Region-Set",Dc="authorization",Wc=Pc.toLowerCase(),gA="date",EA=[Dc,Wc,gA],RA=Hc.toLowerCase(),yi="x-amz-content-sha256",bA=Nc.toLowerCase(),SG="host",TA={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},SA=/^proxy-/,$A=/^sec-/,$G=[/^proxy-/i,/^sec-/i],Ui="AWS4-HMAC-SHA256",UG="AWS4-ECDSA-P256-SHA256",UA="AWS4-HMAC-SHA256-PAYLOAD",LA="UNSIGNED-PAYLOAD",IA=50,Yc="aws4_request",OA=604800,yA=({query:t={}})=>{let n=[],s={};for(let r of Object.keys(t)){if(r.toLowerCase()===RA)continue;let e=$i(r);n.push(e);let i=t[r];if(typeof i==="string")s[e]=`${e}=${$i(i)}`;else if(Array.isArray(i))s[e]=i.slice(0).reduce((f,o)=>f.concat([`${e}=${$i(o)}`]),[]).sort().join("&")}return n.sort().map((r)=>s[r]).filter((r)=>r).join("&")},LG=(t)=>IG(t).toISOString().replace(/\.\d{3}Z$/,"Z"),IG=(t)=>{if(typeof t==="number")return new Date(t*1000);if(typeof t==="string"){if(Number(t))return new Date(Number(t)*1000);return new Date(t)}return t};class xc{service;regionProvider;credentialProvider;sha256;uriEscapePath;applyChecksum;constructor({applyChecksum:t,credentials:n,region:s,service:r,sha256:e,uriEscapePath:i=!0}){this.service=r,this.sha256=e,this.uriEscapePath=i,this.applyChecksum=typeof t==="boolean"?t:!0,this.regionProvider=cA(s),this.credentialProvider=cA(n)}createCanonicalRequest(t,n,s){let r=Object.keys(n).sort();return`${t.method}
|
|
31
|
+
${this.getCanonicalPath(t)}
|
|
32
|
+
${yA(t)}
|
|
33
|
+
${r.map((e)=>`${e}:${n[e]}`).join(`
|
|
34
|
+
`)}
|
|
35
|
+
|
|
36
|
+
${r.join(";")}
|
|
37
|
+
${s}`}async createStringToSign(t,n,s,r){let e=new this.sha256;e.update(se(s));let i=await e.digest();return`${r}
|
|
38
|
+
${t}
|
|
39
|
+
${n}
|
|
40
|
+
${_s(i)}`}getCanonicalPath({path:t}){if(this.uriEscapePath){let n=[];for(let e of t.split("/")){if(e?.length===0)continue;if(e===".")continue;if(e==="..")n.pop();else n.push(e)}let s=`${t?.startsWith("/")?"/":""}${n.join("/")}${n.length>0&&t?.endsWith("/")?"/":""}`;return $i(s).replace(/%2F/g,"/")}return t}validateResolvedCredentials(t){if(typeof t!=="object"||typeof t.accessKeyId!=="string"||typeof t.secretAccessKey!=="string")throw Error("Resolved credential object is not valid")}formatDate(t){let n=LG(t).replace(/[-:]/g,"");return{longDate:n,shortDate:n.slice(0,8)}}getCanonicalHeaderList(t){return Object.keys(t).sort().join(";")}}var nr={},Li=[],Ii=(t,n,s)=>`${t}/${n}/${s}/${Yc}`,GA=async(t,n,s,r,e)=>{let i=await uA(t,n.secretAccessKey,n.accessKeyId),f=`${s}:${r}:${e}:${_s(i)}:${n.sessionToken}`;if(f in nr)return nr[f];Li.push(f);while(Li.length>IA)delete nr[Li.shift()];let o=`AWS4${n.secretAccessKey}`;for(let c of[s,r,e,Yc])o=await uA(t,o,c);return nr[f]=o},OG=()=>{Li.length=0,Object.keys(nr).forEach((t)=>{delete nr[t]})},uA=(t,n,s)=>{let r=new t(n);return r.update(se(s)),r.digest()},Bc=({headers:t},n,s)=>{let r={};for(let e of Object.keys(t).sort()){if(t[e]==null)continue;let i=e.toLowerCase();if(i in TA||n?.has(i)||SA.test(i)||$A.test(i)){if(!s||s&&!s.has(i))continue}r[i]=t[e].trim().replace(/\s+/g," ")}return r},Oi=async({headers:t,body:n},s)=>{for(let r of Object.keys(t))if(r.toLowerCase()===yi)return t[r];if(n==null)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";else if(typeof n==="string"||ArrayBuffer.isView(n)||RG(n)){let r=new s;return r.update(se(n)),_s(await r.digest())}return LA},BA=(t,n)=>{t=t.toLowerCase();for(let s of Object.keys(n))if(t===s.toLowerCase())return!0;return!1},mA=(t,n={})=>{let{headers:s,query:r={}}=lA.clone(t);for(let e of Object.keys(s)){let i=e.toLowerCase();if(i.slice(0,6)==="x-amz-"&&!n.unhoistableHeaders?.has(i)||n.hoistableHeaders?.has(i))r[e]=s[e],delete s[e]}return{...t,headers:s,query:r}},mc=(t)=>{t=lA.clone(t);for(let n of Object.keys(t.headers))if(EA.indexOf(n.toLowerCase())>-1)delete t.headers[n];return t};class FA extends xc{headerFormatter=new _A;constructor({applyChecksum:t,credentials:n,region:s,service:r,sha256:e,uriEscapePath:i=!0}){super({applyChecksum:t,credentials:n,region:s,service:r,sha256:e,uriEscapePath:i})}async presign(t,n={}){let{signingDate:s=new Date,expiresIn:r=3600,unsignableHeaders:e,unhoistableHeaders:i,signableHeaders:f,hoistableHeaders:o,signingRegion:c,signingService:h}=n,u=await this.credentialProvider();this.validateResolvedCredentials(u);let l=c??await this.regionProvider(),{longDate:_,shortDate:w}=this.formatDate(s);if(r>OA)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");let A=Ii(w,l,h??this.service),M=mA(mc(t),{unhoistableHeaders:i,hoistableHeaders:o});if(u.sessionToken)M.query[Nc]=u.sessionToken;M.query[wA]=Ui,M.query[AA]=`${u.accessKeyId}/${A}`,M.query[Pc]=_,M.query[dA]=r.toString(10);let d=Bc(M,e,f);return M.query[MA]=this.getCanonicalHeaderList(d),M.query[Hc]=await this.getSignature(_,A,this.getSigningKey(u,l,w,h),this.createCanonicalRequest(M,d,await Oi(t,this.sha256))),M}async sign(t,n){if(typeof t==="string")return this.signString(t,n);else if(t.headers&&t.payload)return this.signEvent(t,n);else if(t.message)return this.signMessage(t,n);else return this.signRequest(t,n)}async signEvent({headers:t,payload:n},{signingDate:s=new Date,priorSignature:r,signingRegion:e,signingService:i,eventStreamCredentials:f}){let o=e??await this.regionProvider(),{shortDate:c,longDate:h}=this.formatDate(s),u=Ii(c,o,i??this.service),l=await Oi({headers:{},body:n},this.sha256),_=new this.sha256;_.update(t);let w=_s(await _.digest()),A=[UA,h,u,r,w,l].join(`
|
|
41
|
+
`);return this.signString(A,{signingDate:s,signingRegion:o,signingService:i,eventStreamCredentials:f})}async signMessage(t,{signingDate:n=new Date,signingRegion:s,signingService:r,eventStreamCredentials:e}){return this.signEvent({headers:this.headerFormatter.format(t.message.headers),payload:t.message.body},{signingDate:n,signingRegion:s,signingService:r,priorSignature:t.priorSignature,eventStreamCredentials:e}).then((f)=>{return{message:t.message,signature:f}})}async signString(t,{signingDate:n=new Date,signingRegion:s,signingService:r,eventStreamCredentials:e}={}){let i=e??await this.credentialProvider();this.validateResolvedCredentials(i);let f=s??await this.regionProvider(),{shortDate:o}=this.formatDate(n),c=new this.sha256(await this.getSigningKey(i,f,o,r));return c.update(se(t)),_s(await c.digest())}async signRequest(t,{signingDate:n=new Date,signableHeaders:s,unsignableHeaders:r,signingRegion:e,signingService:i}={}){let f=await this.credentialProvider();this.validateResolvedCredentials(f);let o=e??await this.regionProvider(),c=mc(t),{longDate:h,shortDate:u}=this.formatDate(n),l=Ii(u,o,i??this.service);if(c.headers[Wc]=h,f.sessionToken)c.headers[bA]=f.sessionToken;let _=await Oi(c,this.sha256);if(!BA(yi,c.headers)&&this.applyChecksum)c.headers[yi]=_;let w=Bc(c,r,s),A=await this.getSignature(h,l,this.getSigningKey(f,o,u,i),this.createCanonicalRequest(c,w,_));return c.headers[Dc]=`${Ui} Credential=${f.accessKeyId}/${l}, SignedHeaders=${this.getCanonicalHeaderList(w)}, Signature=${A}`,c}async getSignature(t,n,s,r){let e=await this.createStringToSign(t,n,r,Ui),i=new this.sha256(await s);return i.update(se(e)),_s(await i.digest())}getSigningKey(t,n,s,r){return GA(this.sha256,t,s,n,r||this.service)}}var yG={SignatureV4a:null};GG.ALGORITHM_IDENTIFIER=Ui;GG.ALGORITHM_IDENTIFIER_V4A=UG;GG.ALGORITHM_QUERY_PARAM=wA;GG.ALWAYS_UNSIGNABLE_HEADERS=TA;GG.AMZ_DATE_HEADER=Wc;GG.AMZ_DATE_QUERY_PARAM=Pc;GG.AUTH_HEADER=Dc;GG.CREDENTIAL_QUERY_PARAM=AA;GG.DATE_HEADER=gA;GG.EVENT_ALGORITHM_IDENTIFIER=UA;GG.EXPIRES_QUERY_PARAM=dA;GG.GENERATED_HEADERS=EA;GG.HOST_HEADER=SG;GG.KEY_TYPE_IDENTIFIER=Yc;GG.MAX_CACHE_SIZE=IA;GG.MAX_PRESIGNED_TTL=OA;GG.PROXY_HEADER_PATTERN=SA;GG.REGION_SET_PARAM=TG;GG.SEC_HEADER_PATTERN=$A;GG.SHA256_HEADER=yi;GG.SIGNATURE_HEADER=RA;GG.SIGNATURE_QUERY_PARAM=Hc;GG.SIGNED_HEADERS_QUERY_PARAM=MA;GG.SignatureV4=FA;GG.SignatureV4Base=xc;GG.TOKEN_HEADER=bA;GG.TOKEN_QUERY_PARAM=Nc;GG.UNSIGNABLE_PATTERNS=$G;GG.UNSIGNED_PAYLOAD=LA;GG.clearCredentialCache=OG;GG.createScope=Ii;GG.getCanonicalHeaders=Bc;GG.getCanonicalQuery=yA;GG.getPayloadHash=Oi;GG.getSigningKey=GA;GG.hasHeader=BA;GG.moveHeadersToQuery=mA;GG.prepareRequest=mc;GG.signatureV4aContainer=yG});var zc=K((yB)=>{var{HttpResponse:MB,HttpRequest:JA}=Tt(),{normalizeProvider:re,memoizeIdentityProvider:dB,isIdentityExpired:gB,doesIdentityRequireRefresh:EB}=Qn(),{ProviderError:HA}=Rt(),{setCredentialFeature:RB}=kt(),{SignatureV4:NA}=PA(),DA=(t)=>MB.isInstance(t)?t.headers?.date??t.headers?.Date:void 0,Qc=(t)=>new Date(Date.now()+t),bB=(t,n)=>Math.abs(Qc(n).getTime()-t)>=300000,WA=(t,n)=>{let s=Date.parse(t);if(bB(s,n))return s-Date.now();return n},ee=(t,n)=>{if(!n)throw Error(`Property \`${t}\` is not resolved for AWS SDK SigV4Auth`);return n},Jc=async(t)=>{let n=ee("context",t.context),s=ee("config",t.config),r=n.endpointV2?.properties?.authSchemes?.[0],i=await ee("signer",s.signer)(r),f=t?.signingRegion,o=t?.signingRegionSet,c=t?.signingName;return{config:s,signer:i,signingRegion:f,signingRegionSet:o,signingName:c}};class Gi{async sign(t,n,s){if(!JA.isInstance(t))throw Error("The request is not an instance of `HttpRequest` and cannot be signed");let r=await Jc(s),{config:e,signer:i}=r,{signingRegion:f,signingName:o}=r,c=s.context;if(c?.authSchemes?.length??!1){let[u,l]=c.authSchemes;if(u?.name==="sigv4a"&&l?.name==="sigv4")f=l?.signingRegion??f,o=l?.signingName??o}return s._preRequestSystemClockOffset=e.systemClockOffset,await i.sign(t,{signingDate:Qc(e.systemClockOffset),signingRegion:f,signingService:o})}errorHandler(t){return(n)=>{let s=n,r=s.ServerTime??DA(s.$response);if(r){let e=ee("config",t.config),i=t._preRequestSystemClockOffset,f=WA(r,e.systemClockOffset);if((f!==e.systemClockOffset||i!==void 0&&i!==f)&&s.$metadata)e.systemClockOffset=f,s.$metadata.clockSkewCorrected=!0}throw n}}successHandler(t,n){let s=DA(t);if(s){let r=ee("config",n.config);r.systemClockOffset=WA(s,r.systemClockOffset)}}}var TB=Gi;class zA extends Gi{async sign(t,n,s){if(!JA.isInstance(t))throw Error("The request is not an instance of `HttpRequest` and cannot be signed");let{config:r,signer:e,signingRegion:i,signingRegionSet:f,signingName:o}=await Jc(s),h=(await r.sigv4aSigningRegionSet?.()??f??[i]).join(",");return s._preRequestSystemClockOffset=r.systemClockOffset,await e.sign(t,{signingDate:Qc(r.systemClockOffset),signingRegion:h,signingService:o})}}var YA=(t)=>typeof t==="string"&&t.length>0?t.split(",").map((n)=>n.trim()):[],kA=(t)=>`AWS_BEARER_TOKEN_${t.replace(/[\s-]/g,"_").toUpperCase()}`,xA="AWS_AUTH_SCHEME_PREFERENCE",QA="auth_scheme_preference",SB={environmentVariableSelector:(t,n)=>{if(n?.signingName){if(kA(n.signingName)in t)return["httpBearerAuth"]}if(!(xA in t))return;return YA(t[xA])},configFileSelector:(t)=>{if(!(QA in t))return;return YA(t[QA])},default:[]},$B=(t)=>{return t.sigv4aSigningRegionSet=re(t.sigv4aSigningRegionSet),t},UB={environmentVariableSelector(t){if(t.AWS_SIGV4A_SIGNING_REGION_SET)return t.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((n)=>n.trim());throw new HA("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((n)=>n.trim());throw new HA("sigv4a_signing_region_set not set in profile.",{tryNextLink:!0})},default:void 0},XA=(t)=>{let n=t.credentials,s=!!t.credentials,r=void 0;Object.defineProperty(t,"credentials",{set(h){if(h&&h!==n&&h!==r)s=!0;n=h;let u=IB(t,{credentials:n,credentialDefaultProvider:t.credentialDefaultProvider}),l=OB(t,u);if(s&&!l.attributed){let _=typeof n==="object"&&n!==null;r=async(w)=>{let M=await l(w);if(_&&(!M.$source||Object.keys(M.$source).length===0))return RB(M,"CREDENTIALS_CODE","e");return M},r.memoized=l.memoized,r.configBound=l.configBound,r.attributed=!0}else r=l},get(){return r},enumerable:!0,configurable:!0}),t.credentials=n;let{signingEscapePath:e=!0,systemClockOffset:i=t.systemClockOffset||0,sha256:f}=t,o;if(t.signer)o=re(t.signer);else if(t.regionInfoProvider)o=()=>re(t.region)().then(async(h)=>[await t.regionInfoProvider(h,{useFipsEndpoint:await t.useFipsEndpoint(),useDualstackEndpoint:await t.useDualstackEndpoint()})||{},h]).then(([h,u])=>{let{signingRegion:l,signingService:_}=h;t.signingRegion=t.signingRegion||l||u,t.signingName=t.signingName||_||t.serviceId;let w={...t,credentials:t.credentials,region:t.signingRegion,service:t.signingName,sha256:f,uriEscapePath:e};return new(t.signerConstructor||NA)(w)});else o=async(h)=>{h=Object.assign({},{name:"sigv4",signingName:t.signingName||t.defaultSigningName,signingRegion:await re(t.region)(),properties:{}},h);let{signingRegion:u,signingName:l}=h;t.signingRegion=t.signingRegion||u,t.signingName=t.signingName||l||t.serviceId;let _={...t,credentials:t.credentials,region:t.signingRegion,service:t.signingName,sha256:f,uriEscapePath:e};return new(t.signerConstructor||NA)(_)};return Object.assign(t,{systemClockOffset:i,signingEscapePath:e,signer:o})},LB=XA;function IB(t,{credentials:n,credentialDefaultProvider:s}){let r;if(n)if(!n?.memoized)r=dB(n,gB,EB);else r=n;else if(s)r=re(s(Object.assign({},t,{parentClientConfig:t})));else r=async()=>{throw Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.")};return r.memoized=!0,r}function OB(t,n){if(n.configBound)return n;let s=async(r)=>n({...r,callerClientConfig:t});return s.memoized=n.memoized,s.configBound=!0,s}yB.AWSSDKSigV4Signer=TB;yB.AwsSdkSigV4ASigner=zA;yB.AwsSdkSigV4Signer=Gi;yB.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS=SB;yB.NODE_SIGV4A_CONFIG_OPTIONS=UB;yB.getBearerTokenEnvKey=kA;yB.resolveAWSSDKSigV4Config=LB;yB.resolveAwsSdkSigV4AConfig=$B;yB.resolveAwsSdkSigV4Config=XA;yB.validateSigningProperties=Jc});var Ni=K((jB)=>{var{buildQueryString:pA,HttpResponse:vA}=Tt(),Bi=j("https"),{Readable:xB}=j("stream"),kc=j("http2"),{streamCollector:QB}=bt();jB.streamCollector=QB;function Fi(t){let n=t&&typeof t==="object"&&"reason"in t?t.reason:void 0;if(n){if(n instanceof Error){let e=Error("Request aborted");return e.name="AbortError",e.cause=n,e}let r=Error(String(n));return r.name="AbortError",r}let s=Error("Request aborted");return s.name="AbortError",s}var JB=["ECONNRESET","EPIPE","ETIMEDOUT"],ZA=(t)=>{let n={};for(let s in t){let r=t[s];n[s]=Array.isArray(r)?r.join(","):r}return n},_t={setTimeout:(t,n)=>setTimeout(t,n),clearTimeout:(t)=>clearTimeout(t)},CA=1000,zB=(t,n,s=0)=>{if(!s)return-1;let r=(e)=>{let i=_t.setTimeout(()=>{t.destroy(),n(Object.assign(Error(`@smithy/node-http-handler - the request socket did not establish a connection with the server within the configured timeout of ${s} ms.`),{name:"TimeoutError"}))},s-e),f=(o)=>{if(o?.connecting)o.on("connect",()=>{_t.clearTimeout(i)});else _t.clearTimeout(i)};if(t.socket)f(t.socket);else t.on("socket",f)};if(s<2000)return r(0),0;return _t.setTimeout(r.bind(null,CA),CA)},kB=(t,n,s=0,r,e)=>{if(s)return _t.setTimeout(()=>{let i=`@smithy/node-http-handler - [${r?"ERROR":"WARN"}] a request has exceeded the configured ${s} ms requestTimeout.`;if(r){let f=Object.assign(Error(i),{name:"TimeoutError",code:"ETIMEDOUT"});t.destroy(f),n(f)}else i+=" Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.",e?.warn?.(i)},s);return-1},XB=3000,qB=(t,{keepAlive:n,keepAliveMsecs:s},r=XB)=>{if(n!==!0)return-1;let e=()=>{if(t.socket)t.socket.setKeepAlive(n,s||0);else t.on("socket",(i)=>{i.setKeepAlive(n,s||0)})};if(r===0)return e(),0;return _t.setTimeout(e,r)},aA=3000,CB=(t,n,s=0)=>{let r=(e)=>{let i=s-e,f=()=>{t.destroy(),n(Object.assign(Error(`@smithy/node-http-handler - the request socket timed out after ${s} ms of inactivity (configured by client requestHandler).`),{name:"TimeoutError"}))};if(t.socket)t.socket.setTimeout(i,f),t.on("close",()=>t.socket?.removeListener("timeout",f));else t.setTimeout(i,f)};if(0<s&&s<6000)return r(0),0;return _t.setTimeout(r.bind(null,s===0?0:aA),aA)},KA=6000;async function tM(t,n,s=KA,r=!1){let e=n.headers,i=e?e.Expect||e.expect:void 0,f=-1,o=!0;if(!r&&i==="100-continue")o=await Promise.race([new Promise((c)=>{f=Number(_t.setTimeout(()=>c(!0),Math.max(KA,s)))}),new Promise((c)=>{t.on("continue",()=>{_t.clearTimeout(f),c(!0)}),t.on("response",()=>{_t.clearTimeout(f),c(!1)}),t.on("error",()=>{_t.clearTimeout(f),c(!1)})})]);if(o)aB(t,n.body)}function aB(t,n){if(n instanceof xB){n.pipe(t);return}if(n){let s=Buffer.isBuffer(n);if(s||typeof n==="string"){if(s&&n.byteLength===0)t.end();else t.end(n);return}let e=n;if(typeof e==="object"&&e.buffer&&typeof e.byteOffset==="number"&&typeof e.byteLength==="number"){t.end(Buffer.from(e.buffer,e.byteOffset,e.byteLength));return}t.end(Buffer.from(n));return}t.end()}var KB=0,mi=void 0,VA=void 0;class Pi{config;configProvider;socketWarningTimestamp=0;externalAgent=!1;metadata={handlerProtocol:"http/1.1"};static create(t){if(typeof t?.handle==="function")return t;return new Pi(t)}static checkSocketUsage(t,n,s=console){let{sockets:r,requests:e,maxSockets:i}=t;if(typeof i!=="number"||i===1/0)return n;let f=15000;if(Date.now()-f<n)return n;if(r&&e)for(let o in r){let c=r[o]?.length??0,h=e[o]?.length??0;if(c>=i&&h>=2*i)return s?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${c} and ${h} additional requests are enqueued.
|
|
42
|
+
See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html
|
|
43
|
+
or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`),Date.now()}return n}constructor(t){this.configProvider=new Promise((n,s)=>{if(typeof t==="function")t().then((r)=>{n(this.resolveDefaultConfig(r))}).catch(s);else n(this.resolveDefaultConfig(t))})}destroy(){this.config?.httpAgent?.destroy(),this.config?.httpsAgent?.destroy()}async handle(t,{abortSignal:n,requestTimeout:s}={}){if(!this.config)this.config=await this.configProvider;let r=this.config,e=t.protocol==="https:";if(!e&&!this.config.httpAgent)this.config.httpAgent=await this.config.httpAgentProvider();return new Promise((i,f)=>{let o=void 0,c=-1,h=-1,u=-1,l=-1,_=-1,w=()=>{_t.clearTimeout(c),_t.clearTimeout(h),_t.clearTimeout(u),_t.clearTimeout(l),_t.clearTimeout(_)},A=async(U)=>{await o,w(),i(U)},M=async(U)=>{await o,w(),f(U)};if(n?.aborted){let U=Fi(n);M(U);return}let d=t.headers,E=d?(d.Expect??d.expect)==="100-continue":!1,b=e?r.httpsAgent:r.httpAgent;if(E&&!this.externalAgent)b=new(e?Bi.Agent:mi)({keepAlive:!1,maxSockets:1/0});c=_t.setTimeout(()=>{this.socketWarningTimestamp=Pi.checkSocketUsage(b,this.socketWarningTimestamp,r.logger)},r.socketAcquisitionWarningTimeout??(r.requestTimeout??2000)+(r.connectionTimeout??1000));let L=t.query?pA(t.query):"",S=void 0;if(t.username!=null||t.password!=null){let U=t.username??"",z=t.password??"";S=`${U}:${z}`}let O=t.path;if(L)O+=`?${L}`;if(t.fragment)O+=`#${t.fragment}`;let x=t.hostname??"";if(x[0]==="["&&x.endsWith("]"))x=t.hostname.slice(1,-1);else x=t.hostname;let X={headers:t.headers,host:x,method:t.method,path:O,port:t.port,agent:b,auth:S},Q=(e?Bi.request:VA)(X,(U)=>{let z=new vA({statusCode:U.statusCode||-1,reason:U.statusMessage,headers:ZA(U.headers),body:U});A({response:z})});if(Q.on("error",(U)=>{if(JB.includes(U.code))M(Object.assign(U,{name:"TimeoutError"}));else M(U)}),n){let U=()=>{Q.destroy();let z=Fi(n);M(z)};if(typeof n.addEventListener==="function"){let z=n;z.addEventListener("abort",U,{once:!0}),Q.once("close",()=>z.removeEventListener("abort",U))}else n.onabort=U}let rt=s??r.requestTimeout;h=zB(Q,M,r.connectionTimeout),u=kB(Q,M,rt,r.throwOnRequestTimeout,r.logger??console),l=CB(Q,M,r.socketTimeout);let Dt=X.agent;if(typeof Dt==="object"&&"keepAlive"in Dt)_=qB(Q,{keepAlive:Dt.keepAlive,keepAliveMsecs:Dt.keepAliveMsecs});o=tM(Q,t,rt,this.externalAgent).catch((U)=>{return w(),f(U)})})}updateHttpClientConfig(t,n){this.config=void 0,this.configProvider=this.configProvider.then((s)=>{return{...s,[t]:n}})}httpHandlerConfigs(){return this.config??{}}resolveDefaultConfig(t){let{requestTimeout:n,connectionTimeout:s,socketTimeout:r,socketAcquisitionWarningTimeout:e,httpAgent:i,httpsAgent:f,throwOnRequestTimeout:o,logger:c}=t||{},h=!0,u=50;return{connectionTimeout:s,requestTimeout:n,socketTimeout:r,socketAcquisitionWarningTimeout:e,throwOnRequestTimeout:o,httpAgentProvider:async()=>{let l=j("http"),{Agent:_,request:w}=l.default??l;if(VA=w,mi=_,i instanceof mi||typeof i?.destroy==="function")return this.externalAgent=!0,i;return new mi({keepAlive:!0,maxSockets:50,...i})},httpsAgent:(()=>{if(f instanceof Bi.Agent||typeof f?.destroy==="function")return this.externalAgent=!0,f;return new Bi.Agent({keepAlive:!0,maxSockets:50,...f})})(),logger:c}}}var VB=new Uint16Array(1);class Hi{id=VB[0]++;total=0;max=0;session;refs=0;constructor(t){t.unref(),this.session=t}retain(){if(this.session.destroyed)throw Error("@smithy/node-http-handler - cannot acquire reference to destroyed session.");this.refs+=1,this.total+=1,this.max=Math.max(this.refs,this.max),this.session.ref()}free(){if(this.session.destroyed)return;if(this.refs-=1,this.refs===0)this.session.unref();if(this.refs<0)throw Error("@smithy/node-http-handler - ClientHttp2Session refcount at zero, cannot decrement.")}deref(){return this.session}close(){if(!this.session.closed)this.session.close()}destroy(){if(this.refs=0,!this.session.destroyed)this.session.destroy()}useCount(){return this.refs}}class nM{sessions=[];maxConcurrency=0;constructor(t){this.sessions=(t??[]).map((n)=>new Hi(n))}poll(){let t=!1;for(let n of this.sessions){if(n.deref().destroyed){t=!0;continue}if(!this.maxConcurrency||n.useCount()<this.maxConcurrency)return n}if(t){for(let n of this.sessions)if(n.deref().destroyed)this.remove(n)}}offerLast(t){this.sessions.push(t)}remove(t){let n=this.sessions.indexOf(t);if(n>-1)this.sessions.splice(n,1)}[Symbol.iterator](){return this.sessions[Symbol.iterator]()}setMaxConcurrency(t){this.maxConcurrency=t}destroy(t){this.remove(t),t.destroy()}}class sM{config;connectOptions;connectionPools=new Map;constructor(t){if(this.config=t,this.config.maxConcurrency&&this.config.maxConcurrency<=0)throw RangeError("maxConcurrency must be greater than zero.")}lease(t,n){let s=this.getUrlString(t),r=this.getPool(s);if(!this.config.disableConcurrency&&!n.isEventStream){let c=r.poll();if(c)return c.retain(),c}let e=new Hi(this.connect(s)),i=e.deref();if(this.config.maxConcurrency)i.settings({maxConcurrentStreams:this.config.maxConcurrency},(c)=>{if(c)throw Error("Fail to set maxConcurrentStreams to "+this.config.maxConcurrency+"when creating new session for "+t.destination.toString())});let f=()=>{this.removeFromPoolAndClose(s,e)},o=()=>{this.removeFromPoolAndCheckedDestroy(s,e)};if(i.on("goaway",f),i.on("error",o),i.on("frameError",o),i.on("close",o),n.requestTimeout)i.setTimeout(n.requestTimeout,o);return r.offerLast(e),e.retain(),e}release(t,n){n.free()}createIsolatedSession(t,n){let s=this.getUrlString(t),r=new Hi(this.connect(s)),e=r.deref();e.settings({maxConcurrentStreams:1});let i=()=>{r.destroy()};if(e.on("error",i),e.on("frameError",i),e.on("close",i),n.requestTimeout)e.setTimeout(n.requestTimeout,i);return r.retain(),r}destroy(){for(let[t,n]of this.connectionPools){for(let s of[...n])s.destroy();this.connectionPools.delete(t)}}setMaxConcurrentStreams(t){if(t&&t<=0)throw RangeError("maxConcurrentStreams must be greater than zero.");this.config.maxConcurrency=t;for(let n of this.connectionPools.values())n.setMaxConcurrency(t)}setDisableConcurrentStreams(t){this.config.disableConcurrency=t}setNodeHttp2ConnectOptions(t){this.connectOptions=t}debug(){let t={};for(let[n,s]of this.connectionPools){let r=[];for(let e of s)r.push({id:e.id,active:e.useCount(),maxConcurrent:e.max,totalRequests:e.total});t[n]={sessions:r}}return t}removeFromPoolAndClose(t,n){this.connectionPools.get(t)?.remove(n),n.close()}removeFromPoolAndCheckedDestroy(t,n){this.connectionPools.get(t)?.remove(n),n.destroy()}getPool(t){if(!this.connectionPools.has(t)){let n=new nM;if(this.config.maxConcurrency)n.setMaxConcurrency(this.config.maxConcurrency);this.connectionPools.set(t,n)}return this.connectionPools.get(t)}getUrlString(t){return t.destination.toString()}connect(t){return this.connectOptions===void 0?kc.connect(t):kc.connect(t,this.connectOptions)}}var{constants:jA}=kc;class Xc{config;configProvider;metadata={handlerProtocol:"h2"};connectionManager=new sM({});static create(t){if(typeof t?.handle==="function")return t;return new Xc(t)}constructor(t){this.configProvider=new Promise((n,s)=>{if(typeof t==="function")t().then((r)=>{n(r||{})}).catch(s);else n(t||{})})}destroy(){this.connectionManager.destroy()}async handle(t,{abortSignal:n,requestTimeout:s,isEventStream:r}={}){if(!this.config){this.config=await this.configProvider;let{disableConcurrentStreams:c,maxConcurrentStreams:h,nodeHttp2ConnectOptions:u}=this.config;if(this.connectionManager.setDisableConcurrentStreams(c??!1),h)this.connectionManager.setMaxConcurrentStreams(h);if(u)this.connectionManager.setNodeHttp2ConnectOptions(u)}let{requestTimeout:e,disableConcurrentStreams:i}=this.config,f=i||r,o=s??e;return new Promise((c,h)=>{let u=!1,l=void 0,_=async(z)=>{await l,c(z)},w=async(z)=>{await l,h(z)};if(n?.aborted){u=!0;let z=Fi(n);w(z);return}let{hostname:A,method:M,port:d,protocol:E,query:b}=t,L="";if(t.username!=null||t.password!=null){let z=t.username??"",Gt=t.password??"";L=`${z}:${Gt}@`}let S=`${E}//${L}${A}${d?`:${d}`:""}`,O={destination:new URL(S)},x={requestTimeout:this.config?.sessionTimeout,isEventStream:r},X=f?this.connectionManager.createIsolatedSession(O,x):this.connectionManager.lease(O,x),v=X.deref(),Q=(z)=>{if(f)X.destroy();u=!0,w(z)},rt=b?pA(b):"",Dt=t.path;if(rt)Dt+=`?${rt}`;if(t.fragment)Dt+=`#${t.fragment}`;let U=v.request({...t.headers,[jA.HTTP2_HEADER_PATH]:Dt,[jA.HTTP2_HEADER_METHOD]:M});if(o)U.setTimeout(o,()=>{U.close();let z=Error(`Stream timed out because of no activity for ${o} ms`);z.name="TimeoutError",Q(z)});if(n){let z=()=>{U.close();let Gt=Fi(n);Q(Gt)};if(typeof n.addEventListener==="function"){let Gt=n;Gt.addEventListener("abort",z,{once:!0}),U.once("close",()=>Gt.removeEventListener("abort",z))}else n.onabort=z}U.on("frameError",(z,Gt,an)=>{Q(Error(`Frame type id ${z} in stream id ${an} has failed with code ${Gt}.`))}),U.on("error",Q),U.on("aborted",()=>{Q(Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${U.rstCode}.`))}),U.on("response",(z)=>{let Gt=new vA({statusCode:z[":status"]??-1,headers:ZA(z),body:U});if(u=!0,_({response:Gt}),f)v.close()}),U.on("close",()=>{if(f)X.destroy();else this.connectionManager.release(O,X);if(!u)Q(Error("Unexpected error: http2 request did not get a response"))}),l=tM(U,t,o)})}updateHttpClientConfig(t,n){this.config=void 0,this.configProvider=this.configProvider.then((s)=>{return{...s,[t]:n}})}httpHandlerConfigs(){return this.config??{}}}jB.DEFAULT_REQUEST_TIMEOUT=KB;jB.NodeHttp2Handler=Xc;jB.NodeHttpHandler=Pi});var AM=K((P3)=>{var{nv:n3,NumericValue:fM,calculateBodyLength:s3,_parseEpochTimestamp:rM,fromBase64:cM,generateIdempotencyToken:r3}=bt(),{HttpRequest:e3,collectBody:i3,SerdeContext:jc,RpcProtocol:o3}=Tt(),{NormalizedSchema:pc,deref:f3,TypeRegistry:eM}=Pn(),{getSmithyContext:c3}=tn();function ir(t){return typeof Buffer<"u"?Buffer.alloc(t):new Uint8Array(t)}var vc=Symbol("@smithy/core/cbor::tagSymbol");function Zc(t){return t[vc]=!0,t}var hM=typeof Buffer<"u",th=new TextDecoder,k=ir(0),nh=!1,Xt=new DataView(k.buffer,k.byteOffset,k.byteLength),N=0;function h3(t){k=t,nh=hM&&k instanceof Buffer,Xt=new DataView(k.buffer,k.byteOffset,k.byteLength)}function zn(t,n){if(t>=n)throw Error("unexpected end of (decode) payload.");let s=(k[t]&224)>>5,r=k[t]&31;if(r===31&&2<=s&&s<=5)return u3(t,n);switch(s){case 0:case 1:case 6:{let e,i;if(r<24)e=r,i=1;else switch(r){case 24:if(n-t<2)fn(1);e=k[t+1],i=2;break;case 25:if(n-t<3)fn(2);e=Xt.getUint16(t+1),i=3;break;case 26:if(n-t<5)fn(4);e=Xt.getUint32(t+1),i=5;break;case 27:if(n-t<9)fn(8);{let f=Xt.getUint32(t+1);if(f<2097152)e=f*4294967296+Xt.getUint32(t+5);else e=Xt.getBigUint64(t+1)}i=9;break;default:rh(r)}if(s===0)return N=i,ac(e);else if(s===1){let f;if(typeof e==="bigint")f=BigInt(-1)-e;else f=-1-e;return N=i,ac(f)}else return E3(t,n,r,e,i)}case 3:return fe(t,n);case 5:return _3(t,n);case 4:return M3(t,n);case 2:return sh(t,n);default:return R3(t,n)}}function u3(t,n){let s=(k[t]&224)>>5;if((k[t]&31)===31)switch(s){case 3:return S3(t,n);case 5:return b3(t,n);case 4:return T3(t,n);case 2:return $3(t,n)}}function l3(t,n){let s=t>>7,r=(t&124)>>2,e=(t&3)<<8|n,i=s===0?1:-1;if(r===0){if(e===0)return 0;return i*(Math.pow(2,-14)*(e/1024))}else if(r===31){if(e===0)return i*(1/0);return NaN}return i*(Math.pow(2,r-15)*(1+e/1024))}function _3(t,n){let s=ce(t,n);if(s<15)return A3(t,n,s);return w3(t,n,s)}function w3(t,n,s){let r=N;t+=r;let e=t,i=Object.create(null);for(let f=0;f<s;++f){let o=fe(t,n);if(t+=N,(k[t]&224)>>5===3)i[o]=fe(t,n);else i[o]=zn(t,n);t+=N}return N=r+(t-e),Object.setPrototypeOf(i,Object.prototype),i}function A3(t,n,s){let r=N;t+=r;let e=t,i={};for(let f=0;f<s;++f){let o=fe(t,n);t+=N,i[o]=zn(t,n),t+=N}return N=r+(t-e),i}function M3(t,n){let s=ce(t,n),r=N;t+=r;let e=t,i=Array(s);for(let f=0;f<s;++f)i[f]=zn(t,n),t+=N;return N=r+(t-e),i}function fe(t,n){let s=ce(t,n),r=N;if(t+=r,n-t<s)fn(s);if(N=r+s,s<24)return g3(t,s);if(nh)return k.toString("utf-8",t,t+s);return th.decode(k.subarray(t,t+s))}var iM=Array(2048),qc=new Uint16Array(2048),ie=0;function d3(){ie=ie+1&65535}function g3(t,n){let s=n;for(let f=0;f<n;++f)s=s*31+k[t+f]|0;let r=s>>>0&2047,e=iM[r];if(e!==void 0){if(e.length===n){let f=!0;for(let o=0;o<n;++o)if(e.charCodeAt(o)!==k[t+o]){f=!1;break}if(f)return qc[r]=ie,e}}let i=nh?k.toString("utf-8",t,t+n):th.decode(k.subarray(t,t+n));if(qc[r]!==ie)iM[r]=i,qc[r]=ie;return i}function sh(t,n){let s=ce(t,n),r=N;if(t+=r,n-t<s)fn(s);let e=k.subarray(t,t+s);return N=r+s,e}function E3(t,n,s,r,e){if(s===2||s===3){let i=ce(t+e,n),f=BigInt(0),o=t+e+N;for(let c=o;c<o+i;++c)f=f<<BigInt(8)|BigInt(k[c]);return N=e+N+i,s===3?-f-BigInt(1):f}else if(s===4){let i=zn(t+e,n),[f,o]=i,c=o<0?-1:1,h="0".repeat(Math.abs(f)+1)+String(BigInt(c)*BigInt(o)),u,l=o<0?"-":"";if(u=f===0?h:h.slice(0,h.length+f)+"."+h.slice(f),u=u.replace(/^0+/g,""),u==="")u="0";if(u[0]===".")u="0"+u;return u=l+u,N=e+N,n3(u)}else{let i=zn(t+e,n);return N=e+N,Zc({tag:ac(r),value:i})}}function R3(t,n){let s=k[t]&31;switch(s){case 21:case 20:return N=1,s===21;case 22:return N=1,null;case 23:return N=1,null;case 25:if(n-t<3)throw Error("incomplete float16 at end of buf.");return N=3,l3(k[t+1],k[t+2]);case 26:if(n-t<5)throw Error("incomplete float32 at end of buf.");return N=5,Xt.getFloat32(t+1);case 27:if(n-t<9)throw Error("incomplete float64 at end of buf.");return N=9,Xt.getFloat64(t+1);default:rh(s)}}function ce(t,n){let s=k[t]&31;if(s<24)return N=1,s;switch(s){case 24:if(n-t<2)fn(1);return N=2,k[t+1];case 25:if(n-t<3)fn(2);return N=3,Xt.getUint16(t+1);case 26:if(n-t<5)fn(4);return N=5,Xt.getUint32(t+1);case 27:if(n-t<9)fn(8);return N=9,U3(Xt.getBigUint64(t+1));default:rh(s)}}function b3(t,n){t+=1;let s=t,r={};for(;t<n;){if(k[t]===255)return N=t-s+2,r;let e=fe(t,n);t+=N,r[e]=zn(t,n),t+=N}throw Error("expected break marker.")}function T3(t,n){t+=1;let s=[];for(let r=t;t<n;){if(k[t]===255)return N=t-r+2,s;s.push(zn(t,n)),t+=N}throw Error("expected break marker.")}function S3(t,n){t+=1;let s=[];for(let r=t;t<n;){if(k[t]===255){let c=ir(s.length);if(c.set(s,0),N=t-r+2,hM)return c.toString("utf-8",0,c.length);return th.decode(c)}let e=(k[t]&224)>>5,i=k[t]&31;if(e!==3)uM(e);if(i===31)throw Error("nested indefinite string.");let f=sh(t,n);t+=N;for(let c=0;c<f.length;++c)s.push(f[c])}throw Error("expected break marker.")}function $3(t,n){t+=1;let s=[];for(let r=t;t<n;){if(k[t]===255){let c=ir(s.length);return c.set(s,0),N=t-r+2,c}let e=(k[t]&224)>>5,i=k[t]&31;if(e!==2)uM(e);if(i===31)throw Error("nested indefinite string.");let f=sh(t,n);t+=N;for(let c=0;c<f.length;++c)s.push(f[c])}throw Error("expected break marker.")}function ac(t){if(typeof t==="number")return t;let n=Number(t);if(Number.MIN_SAFE_INTEGER<=n&&n<=Number.MAX_SAFE_INTEGER)return n;return t}function U3(t){let n=Number(t);if(n<Number.MIN_SAFE_INTEGER||Number.MAX_SAFE_INTEGER<n)console.warn(Error(`@smithy/core/cbor - truncating BigInt(${t}) to ${n} with loss of precision.`));return n}function fn(t){throw Error(`length ${t} greater than remaining buf len.`)}function rh(t){throw Error(`unexpected minor value ${t}.`)}function uM(t){throw Error(`unexpected major type ${t} in indefinite string.`)}var L3=typeof Buffer<"u",rr=new Map,oe=0,Kc=!1,I3=2048,m=ir(I3),Ht=new DataView(m.buffer,m.byteOffset,m.byteLength),I=0;function O3(t){let n=[t];while(n.length){let s=n.pop();if(typeof s==="string"){let r=s.length;if(L3)if(er(r*3+9),r>23)Cc(3,Buffer.byteLength(s)),I+=m.write(s,I);else G3(s);else{let e=r*3;er(e+9);let i=I,o=new TextEncoder().encodeInto(s,m.subarray(I+9)).written,c;if(o<24)c=1;else if(o<256)c=2;else if(o<65536)c=3;else if(o<4294967296)c=5;else c=9;if(c<9)m.copyWithin(i+c,i+9,i+9+o);I=i,ws(3,o),I+=o}continue}if(m.byteLength-I<9)er(64);if(typeof s==="number"){if(Number.isInteger(s)){let r=s>=0,e=r?0:1,i=r?s:-s-1;if(i<24)m[I++]=e<<5|i;else if(i<256)m[I++]=e<<5|24,m[I++]=i;else if(i<65536)m[I++]=e<<5|25,m[I++]=i>>8,m[I++]=i&255;else if(i<4294967296)m[I++]=e<<5|26,Ht.setUint32(I,i),I+=4;else{m[I++]=e<<5|27;let f=i/4294967296|0,o=i-f*4294967296|0;Ht.setUint32(I,f),Ht.setUint32(I+4,o),I+=8}continue}m[I++]=251,Ht.setFloat64(I,s),I+=8;continue}else if(typeof s==="bigint"){let r=s>=0,e=r?0:1,i=r?s:-s-BigInt(1);if(i<BigInt("18446744073709551616")){let f=Number(i);if(f<4294967296)ws(e,f);else m[I++]=e<<5|27,Ht.setBigUint64(I,i),I+=8}else{let f=i.toString(2),o=new Uint8Array(Math.ceil(f.length/8)),c=i,h=0;while(o.byteLength-++h>=0)o[o.byteLength-h]=Number(c&BigInt(255)),c>>=BigInt(8);er(o.byteLength*2+16),m[I++]=r?194:195,Cc(2,o.byteLength),m.set(o,I),I+=o.byteLength}continue}else if(s===null){m[I++]=246;continue}else if(typeof s==="boolean"){m[I++]=224|(s?21:20);continue}else if(typeof s>"u")throw Error("@smithy/core/cbor: client may not serialize undefined value.");else if(Array.isArray(s)){ws(4,s.length),er(s.length*9+64);for(let r=s.length-1;r>=0;--r)n.push(s[r]);continue}else if(typeof s.byteLength==="number"){er(s.length*2+9),ws(2,s.length),m.set(s,I),I+=s.byteLength;continue}else if(typeof s==="object"){if(s instanceof fM){let i=s.string.indexOf("."),f=i===-1?0:i-s.string.length+1,o=BigInt(s.string.replace(".",""));m[I++]=196,ws(4,2),n.push(o),n.push(f);continue}if(s[vc])if("tag"in s&&"value"in s){n.push(s.value),Cc(6,s.tag);continue}else throw Error("tag encountered with missing fields, need 'tag' and 'value', found: "+JSON.stringify(s));let r=Object.keys(s),e=r.length;ws(5,e);for(let i=e-1;i>=0;--i)n.push(s[r[i]]),n.push(r[i]);continue}throw Error(`data type ${s?.constructor?.name??typeof s} not compatible for encoding.`)}}function y3(){oe=oe+1&65535,Kc=!1}function oM(){let t=ir(I);return t.set(m.subarray(0,I),0),I=0,t}function Vc(t){let n=m;if(m=ir(t),n)if(n.copy)n.copy(m,0,0,n.byteLength);else m.set(n,0);Ht=new DataView(m.buffer,m.byteOffset,m.byteLength)}function G3(t){let n=rr.get(t);if(n!==void 0){m.set(n.bytes,I),I+=n.bytes.length,n.epoch=oe;return}let s=I,r=Buffer.byteLength(t);ws(3,r),I+=m.write(t,I);let e=Uint8Array.prototype.slice.call(m,s,I);if(rr.size>=2048){if(Kc)return;let i=0;for(let[f,o]of rr){if(i>=1024)break;if(o.epoch!==oe)rr.delete(f),i++}if(i===0){Kc=!0;return}}if(rr.size<2048)rr.set(t,{epoch:oe,bytes:e})}function er(t){if(m.byteLength-I<t)if(I<16000000)Vc(Math.max(m.byteLength*4,m.byteLength+t));else Vc(m.byteLength+t+16000000)}function Cc(t,n){if(n<24)m[I++]=t<<5|n;else if(n<256)m[I++]=t<<5|24,m[I++]=n;else if(n<65536)m[I++]=t<<5|25,Ht.setUint16(I,n),I+=2;else if(n<4294967296)m[I++]=t<<5|26,Ht.setUint32(I,n),I+=4;else m[I++]=t<<5|27,Ht.setBigUint64(I,typeof n==="bigint"?n:BigInt(n)),I+=8}function ws(t,n){if(n<24)m[I++]=t<<5|n;else if(n<256)m[I++]=t<<5|24,m[I++]=n;else if(n<65536)m[I++]=t<<5|25,m[I++]=n>>8,m[I++]=n&255;else if(n<4294967296)m[I++]=t<<5|26,Ht.setUint32(I,n),I+=4;else{m[I++]=t<<5|27;let s=n/4294967296|0,r=n-s*4294967296|0;Ht.setUint32(I,s),Ht.setUint32(I+4,r),I+=8}}var Wi={deserialize(t){return d3(),h3(t),zn(0,t.length)},serialize(t){y3();try{return O3(t),oM()}catch(n){throw oM(),n}},resizeEncodingBuffer(t){Vc(t)}},lM=(t,n)=>{return i3(t,n).then(async(s)=>{if(s.length)try{return Wi.deserialize(s)}catch(r){throw Object.defineProperty(r,"$responseBodyText",{value:n.utf8Encoder(s)}),r}return{}})},Di=(t)=>{return Zc({tag:1,value:t.getTime()/1000})},B3=async(t,n)=>{let s=await lM(t,n);return s.message=s.message??s.Message,s},_M=(t,n)=>{let s=(e)=>{let i=e;if(typeof i==="number")i=i.toString();if(i.indexOf(",")>=0)i=i.split(",")[0];if(i.indexOf(":")>=0)i=i.split(":")[0];if(i.indexOf("#")>=0)i=i.split("#")[1];return i};if(n.__type!==void 0)return s(n.__type);let r;for(let e in n)if(e.toLowerCase()==="code"){r=e;break}if(r&&n[r]!==void 0)return s(n[r])},m3=(t)=>{if(String(t.headers["smithy-protocol"]).toLowerCase()!=="rpc-v2-cbor")throw Error("Malformed RPCv2 CBOR response, status: "+t.statusCode)},F3=async(t,n,s,r,e)=>{let i=await t.endpoint(),{hostname:f,protocol:o="https",port:c,path:h}=i,u={protocol:o,hostname:f,port:c,method:"POST",path:h.endsWith("/")?h.slice(0,-1)+s:h+s,headers:{...n}};if(r!==void 0)u.hostname=r;if(i.headers)for(let l in i.headers)u.headers[l]=i.headers[l];if(e!==void 0){u.body=e;try{u.headers["content-length"]=String(s3(e))}catch(l){}}return new e3(u)};class eh extends jc{createSerializer(){let t=new ih;return t.setSerdeContext(this.serdeContext),t}createDeserializer(){let t=new oh;return t.setSerdeContext(this.serdeContext),t}}class ih extends jc{value;write(t,n){this.value=this.serialize(t,n)}serialize(t,n){let s=pc.of(t);if(n==null){if(s.isIdempotencyToken())return r3();return n}if(s.isBlobSchema()){if(typeof n==="string")return(this.serdeContext?.base64Decoder??cM)(n);return n}if(s.isTimestampSchema()){if(typeof n==="number"||typeof n==="bigint")return Di(new Date(Number(n)/1000|0));return Di(n)}if(typeof n==="function"||typeof n==="object"){let r=n;if(s.isListSchema()&&Array.isArray(r)){let i=!!s.getMergedTraits().sparse,f=[],o=0;for(let c of r){let h=this.serialize(s.getValueSchema(),c);if(h!=null||i)f[o++]=h}return f}if(r instanceof Date)return Di(r);let e={};if(s.isMapSchema()){let i=!!s.getMergedTraits().sparse;for(let f in r){let o=this.serialize(s.getValueSchema(),r[f]);if(o!=null||i)e[f]=o}}else if(s.isStructSchema()){for(let[f,o]of s.structIterator()){let c=this.serialize(o,r[f]);if(c!=null)e[f]=c}if(s.isUnionSchema()&&Array.isArray(r.$unknown)){let[f,o]=r.$unknown;e[f]=o}else if(typeof r.__type==="string"){for(let f in r)if(!(f in e))e[f]=this.serialize(15,r[f])}}else if(s.isDocumentSchema())for(let i in r)e[i]=this.serialize(s.getValueSchema(),r[i]);else if(s.isBigDecimalSchema())return r;return e}return n}flush(){let t=Wi.serialize(this.value);return this.value=void 0,t}}class oh extends jc{read(t,n){let s=Wi.deserialize(n);return this.readValue(t,s)}readValue(t,n){let s=pc.of(t);if(s.isTimestampSchema()){if(typeof n==="number")return rM(n);if(typeof n==="object"){if(n.tag===1&&"value"in n)return rM(n.value)}}if(s.isBlobSchema()){if(typeof n==="string")return(this.serdeContext?.base64Decoder??cM)(n);return n}if(typeof n>"u"||typeof n==="boolean"||typeof n==="number"||typeof n==="string"||typeof n==="bigint"||typeof n==="symbol")return n;else if(typeof n==="object"){if(n===null)return null;if("byteLength"in n)return n;if(n instanceof Date)return n;if(s.isDocumentSchema())return n;if(s.isListSchema()){let e=[],i=s.getValueSchema();for(let f of n){let o=this.readValue(i,f);e.push(o)}return e}let r={};if(s.isMapSchema()){let e=s.getValueSchema();for(let i in n){let f=this.readValue(e,n[i]);r[i]=f}}else if(s.isStructSchema()){let e=s.isUnionSchema(),i;if(e){i=new Set;for(let f in n)if(f!=="__type")i.add(f)}for(let[f,o]of s.structIterator()){if(e)i.delete(f);if(n[f]!=null)r[f]=this.readValue(o,n[f])}if(e&&i?.size===1){let f=!0;for(let o in r){f=!1;break}if(f){let o=i.values().next().value;r.$unknown=[o,n[o]]}}else if(typeof n.__type==="string"){for(let f in n)if(!(f in r))r[f]=n[f]}}else if(n instanceof fM)return n;return r}else return n}}class wM extends o3{codec=new eh;serializer=this.codec.createSerializer();deserializer=this.codec.createDeserializer();constructor({defaultNamespace:t,errorTypeRegistries:n}){super({defaultNamespace:t,errorTypeRegistries:n})}getShapeId(){return"smithy.protocols#rpcv2Cbor"}getPayloadCodec(){return this.codec}async serializeRequest(t,n,s){let r=await super.serializeRequest(t,n,s);if(Object.assign(r.headers,{"content-type":this.getDefaultContentType(),"smithy-protocol":"rpc-v2-cbor",accept:this.getDefaultContentType()}),f3(t.input)==="unit")delete r.body,delete r.headers["content-type"];else{if(!r.body)this.serializer.write(15,{}),r.body=this.serializer.flush();try{r.headers["content-length"]=String(r.body.byteLength)}catch(o){}}let{service:e,operation:i}=c3(s),f=`/service/${e}/operation/${i}`;if(r.path.endsWith("/"))r.path+=f.slice(1);else r.path+=f;return r}async deserializeResponse(t,n,s){return super.deserializeResponse(t,n,s)}async handleError(t,n,s,r,e){let i=_M(s,r)??"Unknown",f={$metadata:e,$fault:s.statusCode<=500?"client":"server"},o=this.options.defaultNamespace;if(i.includes("#"))[o]=i.split("#");let c=this.compositeErrorRegistry,h=eM.for(o);c.copyFrom(h);let u;try{u=c.getSchema(i)}catch(d){if(r.Message)r.message=r.Message;let E=eM.for("smithy.ts.sdk.synthetic."+o);c.copyFrom(E);let b=c.getBaseException();if(b){let L=c.getErrorCtor(b);throw Object.assign(new L({name:i}),f,r)}throw Object.assign(Error(i),f,r)}let l=pc.of(u),_=c.getErrorCtor(u),w=r.message??r.Message??"Unknown",A=new _({}),M={};for(let[d,E]of l.structIterator())M[d]=this.deserializer.readValue(E,r[d]);throw Object.assign(A,f,{$fault:l.getMergedTraits().error,message:w},M)}getDefaultContentType(){return"application/cbor"}}P3.CborCodec=eh;P3.CborShapeDeserializer=oh;P3.CborShapeSerializer=ih;P3.SmithyRpcV2CborProtocol=wM;P3.buildHttpRpcRequest=F3;P3.cbor=Wi;P3.checkCborResponse=m3;P3.dateToTag=Di;P3.loadSmithyRpcV2CborErrorCode=_M;P3.parseCborBody=lM;P3.parseCborErrorBody=B3;P3.tag=Zc;P3.tagSymbol=vc});var MM=K((tm)=>{var a3=/[&<>"]/g,K3={"&":"&","<":"<",">":">",'"':"""};function V3(t){return t.replace(a3,(n)=>K3[n])}var j3=/[&"'<>\r\n\u0085\u2028]/g,p3={"&":"&",'"':""","'":"'","<":"<",">":">","\r":"
","\n":"
","\x85":"…","\u2028":"
"};function v3(t){return t.replace(j3,(n)=>p3[n])}class fh{value;constructor(t){this.value=t}toString(){return v3(""+this.value)}}class he{name;children;attributes={};static of(t,n,s){let r=new he(t);if(n!==void 0)r.addChildNode(new fh(n));if(s!==void 0)r.withName(s);return r}constructor(t,n=[]){this.name=t,this.children=n}withName(t){return this.name=t,this}addAttribute(t,n){return this.attributes[t]=n,this}addChildNode(t){return this.children.push(t),this}removeAttribute(t){return delete this.attributes[t],this}n(t){return this.name=t,this}c(t){return this.children.push(t),this}a(t,n){if(n!=null)this.attributes[t]=n;return this}cc(t,n,s=n){if(t[n]!=null){let r=he.of(n,t[n]).withName(s);this.c(r)}}l(t,n,s,r){if(t[n]!=null)r().map((i)=>{i.withName(s),this.c(i)})}lc(t,n,s,r){if(t[n]!=null){let e=r(),i=new he(s);e.map((f)=>{i.c(f)}),this.c(i)}}toString(){let t=Boolean(this.children.length),n=`<${this.name}`,s=this.attributes;for(let r of Object.keys(s)){let e=s[r];if(e!=null)n+=` ${r}="${V3(""+e)}"`}return n+=!t?"/>":`>${this.children.map((r)=>r.toString()).join("")}</${this.name}>`}}function Z3(t){return new ch(t).parse()}class ch{x;i=0;z;constructor(t){this.x=t,this.x=t.replace(/\r\n?/g,`
|
|
44
|
+
`),this.z=this.x.length}parse(){let t=this,{z:n}=t;while(t.i<n){if(t.trim(),t.i>=n)break;if(t.isNext("<?"))t.readTo("?>"),t.trim();else if(t.isNext("<!--"))t.readTo("-->"),t.trim();else if(t.isNext("<!DOCTYPE",!1))t.skipDoctype(),t.trim();else if(t.x[t.i]==="<"){let s=t.parseTag();return{[s.tag]:s.value}}else throw Error("@aws-sdk XML parse error: unexpected content.")}throw Error("@aws-sdk XML parse error: no root element.")}isNext(t,n=!0){let s=this;if(n)return s.x.startsWith(t,s.i);return s.x.toLowerCase().startsWith(t.toLowerCase(),s.i)}readTo(t){let n=this,s=n.x.indexOf(t,n.i);if(s===-1)throw Error(`@aws-sdk XML parse error: expected "${t}" not found.`);let r=n.x.slice(n.i,s);return n.i=s+t.length,r}trim(){let t=this;while(t.i<t.z&&` \r
|
|
45
|
+
`.includes(t.x[t.i]))++t.i}readAttrValue(){let t=this,n=t.x[t.i];++t.i;let s="";while(t.i<t.z&&t.x[t.i]!==n)s+=t.x[t.i++];return++t.i,t.decodeEntities(s)}parseTag(){let t=this;++t.i;let n="";while(t.i<t.z&&!` \r
|
|
46
|
+
>/`.includes(t.x[t.i]))n+=t.x[t.i++];let s=!1,r=Object.create(null);while(t.i<t.z){if(t.trim(),">/".includes(t.x[t.i]))break;let h="";while(t.i<t.z&&!`= \r
|
|
47
|
+
>/?`.includes(t.x[t.i]))h+=t.x[t.i++];if(t.trim(),t.x[t.i]!=="=")break;++t.i,t.trim(),r[h]=t.readAttrValue(),s=!0}if(t.i>=t.z)throw Error("@aws-sdk XML parse error: unexpected end of input.");if(t.x[t.i]==="/"){if(++t.i,t.i>=t.z||t.x[t.i]!==">")throw Error("@aws-sdk XML parse error: expected > at the end of self-closing tag.");return++t.i,Object.setPrototypeOf(r,Object.prototype),{tag:n,value:s?r:""}}if(t.x[t.i]!==">")throw Error("@aws-sdk XML parse error: expected > at the end of opening tag.");++t.i;let e=[],i=[],f=!1;while(t.i<t.z){if(t.isNext("</"))break;if(t.x[t.i]==="<")if(t.isNext("<!--"))t.readTo("-->");else if(t.isNext("<![CDATA["))t.i+=9,e.push(t.readTo("]]>"));else if(t.isNext("<?"))t.readTo("?>");else f=!0,i.push(t.parseTag());else{let h="";while(t.i<t.z&&t.x[t.i]!=="<")h+=t.x[t.i++];e.push(t.decodeEntities(h))}}if(!t.isNext("</"))throw Error(`@aws-sdk XML parse error: missing closing tag </${n}>.`);t.i+=2;let o=t.readTo(">").trim();if(o!==n)throw Error(`@aws-sdk XML parse error: mismatched tags <${n}> and </${o}>.`);if(!s&&e.length===0&&!f)return{tag:n,value:""};if(!s&&!f){let h=e.length===1?e[0]:e.join("");if(h.trim()===""&&h.includes(`
|
|
48
|
+
`))return{tag:n,value:""};return{tag:n,value:h}}let c=Object.create(null);for(let h of e){if(h.trim()===""&&h.includes(`
|
|
49
|
+
`))continue;c["#text"]="#text"in c?c["#text"]+h:h}for(let h of i)if(h.tag in c)if(Array.isArray(c[h.tag]))c[h.tag].push(h.value);else c[h.tag]=[c[h.tag],h.value];else c[h.tag]=h.value;for(let[h,u]of Object.entries(r))c[h]=u;return Object.setPrototypeOf(c,Object.prototype),{tag:n,value:c}}static ENTITIES={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};skipDoctype(){let t=this;t.i+=9;let n=0;while(t.i<t.z){let s=t.x[t.i];if(s==="[")++n;else if(s==="]")--n;else if(s===">"&&n===0){++t.i;return}++t.i}throw Error("@aws-sdk XML parse error: unclosed DOCTYPE.")}decodeEntities(t){return t.replace(/&(?:#x([0-9a-fA-F]{1,6})|#(\d{1,7})|([a-zA-Z][a-zA-Z0-9]{0,30}));/g,(n,s,r,e)=>{if(s)return String.fromCharCode(parseInt(s,16));if(r)return String.fromCharCode(parseInt(r,10));return ch.ENTITIES[e]??""})}}tm.XmlNode=he;tm.XmlText=fh;tm.parseXML=Z3});var bh=K((Em)=>{var{SmithyRpcV2CborProtocol:em,loadSmithyRpcV2CborErrorCode:im}=AM(),{TypeRegistry:dM,NormalizedSchema:et,deref:SM}=Pn(),{decorateServiceException:gM,getValueFromTextNode:$M}=En(),{collectBody:uh,determineTimestampFormat:Qi,RpcProtocol:UM,HttpBindingProtocol:LM,HttpInterceptingShapeSerializer:IM,HttpInterceptingShapeDeserializer:OM,FromStringShapeDeserializer:om,extendedEncodeURIComponent:EM}=Tt(),{NumericValue:cn,toUtf8:yM,fromBase64:GM,LazyJsonString:BM,parseEpochTimestamp:fm,parseRfc7231DateTime:cm,parseRfc3339DateTimeWithOffset:hm,toBase64:Yi,dateToUtcString:xi,generateIdempotencyToken:lh,expectUnion:um}=bt(),{parseXML:mM,XmlNode:qt,XmlText:RM}=MM();class or{queryCompat;errorRegistry;constructor(t=!1){this.queryCompat=t}resolveRestContentType(t,n){let s=n.getMemberSchemas(),r=Object.values(s).find((e)=>{return!!e.getMergedTraits().httpPayload});if(r){let e=r.getMergedTraits().mediaType;if(e)return e;else if(r.isStringSchema())return"text/plain";else if(r.isBlobSchema())return"application/octet-stream";else return t}else if(!n.isUnitSchema()){if(Object.values(s).find((i)=>{let{httpQuery:f,httpQueryParams:o,httpHeader:c,httpLabel:h,httpPrefixHeaders:u}=i.getMergedTraits();return!f&&!o&&!c&&!h&&u===void 0}))return t}}async getErrorSchemaOrThrowBaseException(t,n,s,r,e,i){let f=t;if(t.includes("#"))[,f]=t.split("#");let o={$metadata:e,$fault:s.statusCode<500?"client":"server"};if(!this.errorRegistry)throw Error("@aws-sdk/core/protocols - error handler not initialized.");try{return{errorSchema:i?.(this.errorRegistry,f)??this.errorRegistry.getSchema(t),errorMetadata:o}}catch(c){r.message=r.message??r.Message??"UnknownError";let h=this.errorRegistry,u=h.getBaseException();if(u){let w=h.getErrorCtor(u)??Error;throw this.decorateServiceException(Object.assign(new w({name:f}),o),r)}let l=r,_=l?.message??l?.Message??l?.Error?.Message??l?.Error?.message;throw this.decorateServiceException(Object.assign(Error(_),{name:f},o),r)}}compose(t,n,s){let r=s;if(n.includes("#"))[r]=n.split("#");let e=dM.for(r),i=dM.for("smithy.ts.sdk.synthetic."+s);t.copyFrom(e),t.copyFrom(i),this.errorRegistry=t}decorateServiceException(t,n={}){if(this.queryCompat){let s=t.Message??n.Message,r=gM(t,n);if(s)r.message=s;let e=r.Error??{};e.Type=r.Error?.Type,e.Code=r.Error?.Code,e.Message=r.Error?.message??r.Error?.Message??s,r.Error=e;let i=r.$metadata.requestId;if(i)r.RequestId=i;return r}return gM(t,n)}setQueryCompatError(t,n){let s=n.headers?.["x-amzn-query-error"];if(t!==void 0&&s!=null){let[r,e]=s.split(";"),i=Object.keys(t),f={Code:r,Type:e};t.Code=r,t.Type=e;for(let o=0;o<i.length;o++){let c=i[o];f[c==="message"?"Message":c]=t[c]}delete f.__type,t.Error=f}}queryCompatOutput(t,n){if(t.Error)n.Error=t.Error;if(t.Type)n.Type=t.Type;if(t.Code)n.Code=t.Code}findQueryCompatibleError(t,n){try{return t.getSchema(n)}catch(s){return t.find((r)=>et.of(r).getMergedTraits().awsQueryError?.[0]===n)}}}class FM extends em{awsQueryCompatible;mixin;constructor({defaultNamespace:t,errorTypeRegistries:n,awsQueryCompatible:s}){super({defaultNamespace:t,errorTypeRegistries:n});this.awsQueryCompatible=!!s,this.mixin=new or(this.awsQueryCompatible)}async serializeRequest(t,n,s){let r=await super.serializeRequest(t,n,s);if(this.awsQueryCompatible)r.headers["x-amzn-query-mode"]="true";return r}async handleError(t,n,s,r,e){if(this.awsQueryCompatible)this.mixin.setQueryCompatError(r,s);let i=(()=>{let w=s.headers["x-amzn-query-error"];if(w&&this.awsQueryCompatible)return w.split(";")[0];return im(s,r)??"Unknown"})();this.mixin.compose(this.compositeErrorRegistry,i,this.options.defaultNamespace);let{errorSchema:f,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(i,this.options.defaultNamespace,s,r,e,this.awsQueryCompatible?this.mixin.findQueryCompatibleError:void 0),c=et.of(f),h=r.message??r.Message??"UnknownError",l=new(this.compositeErrorRegistry.getErrorCtor(f)??Error)({}),_={};for(let[w,A]of c.structIterator())if(r[w]!=null)_[w]=this.deserializer.readValue(A,r[w]);if(this.awsQueryCompatible)this.mixin.queryCompatOutput(r,_);throw this.mixin.decorateServiceException(Object.assign(l,o,{$fault:c.getMergedTraits().error,message:h},_),r)}}var lm=(t)=>{if(t==null)return t;if(typeof t==="number"||typeof t==="bigint"){let n=Error(`Received number ${t} where a string was expected.`);return n.name="Warning",console.warn(n),String(t)}if(typeof t==="boolean"){let n=Error(`Received boolean ${t} where a string was expected.`);return n.name="Warning",console.warn(n),String(t)}return t},_m=(t)=>{if(t==null)return t;if(typeof t==="string"){let n=t.toLowerCase();if(t!==""&&n!=="false"&&n!=="true"){let s=Error(`Received string "${t}" where a boolean was expected.`);s.name="Warning",console.warn(s)}return t!==""&&n!=="false"}return t},wm=(t)=>{if(t==null)return t;if(typeof t==="string"){let n=Number(t);if(n.toString()!==t){let s=Error(`Received string "${t}" where a number was expected.`);return s.name="Warning",console.warn(s),t}return n}return t};class kn{serdeContext;setSerdeContext(t){this.serdeContext=t}}class _h{from;to;keys;constructor(t,n){this.from=t,this.to=n;let s=Object.keys(this.from),r=new Set(s);r.delete("__type"),this.keys=r}mark(t){this.keys.delete(t)}hasUnknown(){return this.keys.size===1&&Object.keys(this.to).length===0}writeUnknown(){if(this.hasUnknown()){let t=this.keys.values().next().value,n=this.from[t];this.to.$unknown=[t,n]}}}function Am(t,n,s){if(s?.source){let r=s.source;if(typeof n==="number"){if(n>Number.MAX_SAFE_INTEGER||n<Number.MIN_SAFE_INTEGER||r!==String(n))if(r.includes("."))return new cn(r,"bigDecimal");else return BigInt(r)}}return n}var PM=(t,n)=>uh(t,n).then((s)=>(n?.utf8Encoder??yM)(s)),wh=(t,n)=>PM(t,n).then((s)=>{if(s.length)try{return JSON.parse(s)}catch(r){if(r?.name==="SyntaxError")Object.defineProperty(r,"$responseBodyText",{value:s});throw r}return{}}),Mm=async(t,n)=>{let s=await wh(t,n);return s.message=s.message??s.Message,s},bM=(t,n)=>Object.keys(t).find((s)=>s.toLowerCase()===n.toLowerCase()),hh=(t)=>{let n=t;if(typeof n==="number")n=n.toString();if(n.indexOf(",")>=0)n=n.split(",")[0];if(n.indexOf(":")>=0)n=n.split(":")[0];if(n.indexOf("#")>=0)n=n.split("#")[1];return n},HM=(t,n)=>{return DM(t,n,["header","code","type"])},NM=(t,n,s=!1)=>{return DM(t,n,s?["code","header","type"]:["type","code","header"])},DM=({headers:t},n,s)=>{while(s.length>0)switch(s.shift()){case"header":let e=bM(t??{},"x-amzn-errortype");if(e!==void 0)return hh(t[e]);break;case"code":let i=bM(n??{},"code");if(i&&n[i]!==void 0)return hh(n[i]);break;case"type":if(n?.__type!==void 0)return hh(n.__type);break}};class Ah extends kn{settings;constructor(t){super();this.settings=t}async read(t,n){return this._read(t,typeof n==="string"?JSON.parse(n,Am):await wh(n,this.serdeContext))}readObject(t,n){return this._read(t,n)}_read(t,n){let s=n!==null&&typeof n==="object",r=et.of(t);if(s){if(r.isStructSchema()){let i=n,f=r.isUnionSchema(),o={},c=void 0,{jsonName:h}=this.settings;if(h)c={};let u;if(f)u=new _h(i,o);for(let[l,_]of r.structIterator()){let w=l;if(h)w=_.getMergedTraits().jsonName??w,c[w]=l;if(f)u.mark(w);if(i[w]!=null)o[l]=this._read(_,i[w])}if(f)u.writeUnknown();else if(typeof i.__type==="string")for(let l in i){let _=i[l],w=h?c[l]??l:l;if(!(w in o))o[w]=_}return o}if(Array.isArray(n)&&r.isListSchema()){let i=r.getValueSchema(),f=[];for(let o of n)f.push(this._read(i,o));return f}if(r.isMapSchema()){let i=r.getValueSchema(),f={};for(let o in n)f[o]=this._read(i,n[o]);return f}}if(r.isBlobSchema()&&typeof n==="string")return GM(n);let e=r.getMergedTraits().mediaType;if(r.isStringSchema()&&typeof n==="string"&&e){if(e==="application/json"||e.endsWith("+json"))return BM.from(n);return n}if(r.isTimestampSchema()&&n!=null)switch(Qi(r,this.settings)){case 5:return hm(n);case 6:return cm(n);case 7:return fm(n);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",n),new Date(n)}if(r.isBigIntegerSchema()&&(typeof n==="number"||typeof n==="string"))return BigInt(n);if(r.isBigDecimalSchema()&&n!=null){if(n instanceof cn)return n;let i=n;if(i.type==="bigDecimal"&&"string"in i)return new cn(i.string,i.type);return new cn(String(n),"bigDecimal")}if(r.isNumericSchema()&&typeof n==="string"){switch(n){case"Infinity":return 1/0;case"-Infinity":return-1/0;case"NaN":return NaN}return n}if(r.isDocumentSchema())if(s){let i=Array.isArray(n)?[]:{};for(let f in n){let o=n[f];if(o instanceof cn)i[f]=o;else i[f]=this._read(r,o)}return i}else return structuredClone(n);return n}}var TM=String.fromCharCode(925);class WM{values=new Map;counter=0;stage=0;createReplacer(){if(this.stage===1)throw Error("@aws-sdk/core/protocols - JsonReplacer already created.");if(this.stage===2)throw Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");return this.stage=1,(t,n)=>{if(n instanceof cn){let s=`${TM+"nv"+this.counter++}_`+n.string;return this.values.set(`"${s}"`,n.string),s}if(typeof n==="bigint"){let s=n.toString(),r=`${TM+"b"+this.counter++}_`+s;return this.values.set(`"${r}"`,s),r}return n}}replaceInJson(t){if(this.stage===0)throw Error("@aws-sdk/core/protocols - JsonReplacer not created yet.");if(this.stage===2)throw Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");if(this.stage=2,this.counter===0)return t;for(let[n,s]of this.values)t=t.replace(n,s);return t}}class Mh extends kn{settings;buffer;useReplacer=!1;rootSchema;constructor(t){super();this.settings=t}write(t,n){this.rootSchema=et.of(t),this.buffer=this._write(this.rootSchema,n)}flush(){let{rootSchema:t,useReplacer:n}=this;if(this.rootSchema=void 0,this.useReplacer=!1,t?.isStructSchema()||t?.isDocumentSchema()){if(!n)return JSON.stringify(this.buffer);let s=new WM;return s.replaceInJson(JSON.stringify(this.buffer,s.createReplacer(),0))}return this.buffer}writeDiscriminatedDocument(t,n){if(this.write(t,n),typeof this.buffer==="object")this.buffer.__type=et.of(t).getName(!0)}_write(t,n,s){let r=n!==null&&typeof n==="object",e=et.of(t);if(r){if(e.isStructSchema()){let i=n,f={},{jsonName:o}=this.settings,c=void 0;if(o)c={};let h=0;for(let[u,l]of e.structIterator()){let _=this._write(l,i[u],e);if(_!==void 0){let w=u;if(o)w=l.getMergedTraits().jsonName??u,c[u]=w;f[w]=_,h++}}if(e.isUnionSchema()&&h===0){let{$unknown:u}=i;if(Array.isArray(u)){let[l,_]=u;f[l]=this._write(15,_)}}else if(typeof i.__type==="string")for(let u in i){let l=i[u],_=o?c[u]??u:u;if(!(_ in f))f[_]=this._write(15,l)}return f}if(Array.isArray(n)&&e.isListSchema()){let i=e.getValueSchema(),f=[],o=!!e.getMergedTraits().sparse;for(let c of n)if(o||c!=null)f.push(this._write(i,c));return f}if(e.isMapSchema()){let i=e.getValueSchema(),f={},o=!!e.getMergedTraits().sparse;for(let c in n){let h=n[c];if(o||h!=null)f[c]=this._write(i,h)}return f}if(n instanceof Uint8Array&&(e.isBlobSchema()||e.isDocumentSchema())){if(e===this.rootSchema)return n;return(this.serdeContext?.base64Encoder??Yi)(n)}if(n instanceof Date&&(e.isTimestampSchema()||e.isDocumentSchema()))switch(Qi(e,this.settings)){case 5:return n.toISOString().replace(".000Z","Z");case 6:return xi(n);case 7:return n.getTime()/1000;default:return console.warn("Missing timestamp format, using epoch seconds",n),n.getTime()/1000}if(n instanceof cn)this.useReplacer=!0}if(n===null&&s?.isStructSchema())return;if(e.isStringSchema()){if(typeof n>"u"&&e.isIdempotencyToken())return lh();let i=e.getMergedTraits().mediaType;if(n!=null&&i){if(i==="application/json"||i.endsWith("+json"))return BM.from(n)}return n}if(typeof n==="number"&&e.isNumericSchema()){if(Math.abs(n)===1/0||isNaN(n))return String(n);return n}if(typeof n==="string"&&e.isBlobSchema()){if(e===this.rootSchema)return n;return(this.serdeContext?.base64Encoder??Yi)(n)}if(typeof n==="bigint")this.useReplacer=!0;if(e.isDocumentSchema())if(r){let i=Array.isArray(n)?[]:{};for(let f in n){let o=n[f];if(o instanceof cn)this.useReplacer=!0,i[f]=o;else i[f]=this._write(e,o)}return i}else return structuredClone(n);return n}}class Ji extends kn{settings;constructor(t){super();this.settings=t}createSerializer(){let t=new Mh(this.settings);return t.setSerdeContext(this.serdeContext),t}createDeserializer(){let t=new Ah(this.settings);return t.setSerdeContext(this.serdeContext),t}}class zi extends UM{serializer;deserializer;serviceTarget;codec;mixin;awsQueryCompatible;constructor({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:r,jsonCodec:e}){super({defaultNamespace:t,errorTypeRegistries:n});this.serviceTarget=s,this.codec=e??new Ji({timestampFormat:{useTrait:!0,default:7},jsonName:!1}),this.serializer=this.codec.createSerializer(),this.deserializer=this.codec.createDeserializer(),this.awsQueryCompatible=!!r,this.mixin=new or(this.awsQueryCompatible)}async serializeRequest(t,n,s){let r=await super.serializeRequest(t,n,s);if(!r.path.endsWith("/"))r.path+="/";if(r.headers["content-type"]=`application/x-amz-json-${this.getJsonRpcVersion()}`,r.headers["x-amz-target"]=`${this.serviceTarget}.${t.name}`,this.awsQueryCompatible)r.headers["x-amzn-query-mode"]="true";if(SM(t.input)==="unit"||!r.body)r.body="{}";return r}getPayloadCodec(){return this.codec}async handleError(t,n,s,r,e){let{awsQueryCompatible:i}=this;if(i)this.mixin.setQueryCompatError(r,s);let f=NM(s,r,i)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,f,this.options.defaultNamespace);let{errorSchema:o,errorMetadata:c}=await this.mixin.getErrorSchemaOrThrowBaseException(f,this.options.defaultNamespace,s,r,e,i?this.mixin.findQueryCompatibleError:void 0),h=et.of(o),u=r.message??r.Message??"UnknownError",_=new(this.compositeErrorRegistry.getErrorCtor(o)??Error)({}),w={},A=this.codec.createDeserializer();for(let[M,d]of h.structIterator())if(r[M]!=null)w[M]=A.readObject(d,r[M]);if(i)this.mixin.queryCompatOutput(r,w);throw this.mixin.decorateServiceException(Object.assign(_,c,{$fault:h.getMergedTraits().error,message:u},w),r)}}class YM extends zi{constructor({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:r,jsonCodec:e}){super({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:r,jsonCodec:e})}getShapeId(){return"aws.protocols#awsJson1_0"}getJsonRpcVersion(){return"1.0"}getDefaultContentType(){return"application/x-amz-json-1.0"}}class xM extends zi{constructor({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:r,jsonCodec:e}){super({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:r,jsonCodec:e})}getShapeId(){return"aws.protocols#awsJson1_1"}getJsonRpcVersion(){return"1.1"}getDefaultContentType(){return"application/x-amz-json-1.1"}}class QM extends LM{serializer;deserializer;codec;mixin=new or;constructor({defaultNamespace:t,errorTypeRegistries:n}){super({defaultNamespace:t,errorTypeRegistries:n});let s={timestampFormat:{useTrait:!0,default:7},httpBindings:!0,jsonName:!0};this.codec=new Ji(s),this.serializer=new IM(this.codec.createSerializer(),s),this.deserializer=new OM(this.codec.createDeserializer(),s)}getShapeId(){return"aws.protocols#restJson1"}getPayloadCodec(){return this.codec}setSerdeContext(t){this.codec.setSerdeContext(t),super.setSerdeContext(t)}async serializeRequest(t,n,s){let r=await super.serializeRequest(t,n,s),e=et.of(t.input);if(!r.headers["content-type"]){let i=this.mixin.resolveRestContentType(this.getDefaultContentType(),e);if(i)r.headers["content-type"]=i}if(r.body==null&&r.headers["content-type"]===this.getDefaultContentType())r.body="{}";return r}async deserializeResponse(t,n,s){let r=await super.deserializeResponse(t,n,s),e=et.of(t.output);for(let[i,f]of e.structIterator())if(f.getMemberTraits().httpPayload&&!(i in r))r[i]=null;return r}async handleError(t,n,s,r,e){let i=HM(s,r)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,i,this.options.defaultNamespace);let{errorSchema:f,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(i,this.options.defaultNamespace,s,r,e),c=et.of(f),h=r.message??r.Message??"UnknownError",l=new(this.compositeErrorRegistry.getErrorCtor(f)??Error)({});await this.deserializeHttpMessage(f,n,s,r);let _={},w=this.codec.createDeserializer();for(let[A,M]of c.structIterator()){let d=M.getMergedTraits().jsonName??A;_[A]=w.readObject(M,r[d])}throw this.mixin.decorateServiceException(Object.assign(l,o,{$fault:c.getMergedTraits().error,message:h},_),r)}getDefaultContentType(){return"application/json"}}var dm=(t)=>{if(t==null)return;if(typeof t==="object"&&"__type"in t)delete t.__type;return um(t)};class ki extends kn{settings;stringDeserializer;constructor(t){super();this.settings=t,this.stringDeserializer=new om(t)}setSerdeContext(t){this.serdeContext=t,this.stringDeserializer.setSerdeContext(t)}read(t,n,s){let r=et.of(t),e=r.getMemberSchemas();if(r.isStructSchema()&&r.isMemberSchema()&&!!Object.values(e).find((c)=>{return!!c.getMemberTraits().eventPayload})){let c={},h=Object.keys(e)[0];if(e[h].isBlobSchema())c[h]=n;else c[h]=this.read(e[h],n);return c}let f=(this.serdeContext?.utf8Encoder??yM)(n),o=this.parseXml(f);return this.readSchema(t,s?o[s]:o)}readSchema(t,n){let s=et.of(t);if(s.isUnitSchema())return;let r=s.getMergedTraits();if(s.isListSchema()&&!Array.isArray(n))return this.readSchema(s,[n]);if(n==null)return n;if(typeof n==="object"){let e=!!r.xmlFlattened;if(s.isListSchema()){let f=s.getValueSchema(),o=[],c=f.getMergedTraits().xmlName??"member",h=e?n:(n[0]??n)[c];if(h==null)return o;let u=Array.isArray(h)?h:[h];for(let l of u)o.push(this.readSchema(f,l));return o}let i={};if(s.isMapSchema()){let f=s.getKeySchema(),o=s.getValueSchema(),c;if(e)c=Array.isArray(n)?n:[n];else c=Array.isArray(n.entry)?n.entry:[n.entry];let h=f.getMergedTraits().xmlName??"key",u=o.getMergedTraits().xmlName??"value";for(let l of c){let _=l[h],w=l[u];i[_]=this.readSchema(o,w)}return i}if(s.isStructSchema()){let f=s.isUnionSchema(),o;if(f)o=new _h(n,i);for(let[c,h]of s.structIterator()){let u=h.getMergedTraits(),l=!u.httpPayload?h.getMemberTraits().xmlName??c:u.xmlName??h.getName();if(f)o.mark(l);if(n[l]!=null)i[c]=this.readSchema(h,n[l])}if(f)o.writeUnknown();return i}if(s.isDocumentSchema())return n;throw Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${s.getName(!0)}`)}if(s.isListSchema())return[];if(s.isMapSchema()||s.isStructSchema())return{};return this.stringDeserializer.read(s,n)}parseXml(t){if(t.length){let n;try{n=mM(t)}catch(i){if(i&&typeof i==="object")Object.defineProperty(i,"$responseBodyText",{value:t});throw i}let s="#text",r=Object.keys(n)[0],e=n[r];if(e[s])e[r]=e[s],delete e[s];return $M(e)}return{}}}class dh extends kn{settings;buffer;constructor(t){super();this.settings=t}write(t,n,s=""){if(this.buffer===void 0)this.buffer="";let r=et.of(t);if(s&&!s.endsWith("."))s+=".";if(r.isBlobSchema()){if(typeof n==="string"||n instanceof Uint8Array)this.writeKey(s),this.writeValue((this.serdeContext?.base64Encoder??Yi)(n))}else if(r.isBooleanSchema()||r.isNumericSchema()||r.isStringSchema()){if(n!=null)this.writeKey(s),this.writeValue(String(n));else if(r.isIdempotencyToken())this.writeKey(s),this.writeValue(lh())}else if(r.isBigIntegerSchema()){if(n!=null)this.writeKey(s),this.writeValue(String(n))}else if(r.isBigDecimalSchema()){if(n!=null)this.writeKey(s),this.writeValue(n instanceof cn?n.string:String(n))}else if(r.isTimestampSchema()){if(n instanceof Date)switch(this.writeKey(s),Qi(r,this.settings)){case 5:this.writeValue(n.toISOString().replace(".000Z","Z"));break;case 6:this.writeValue(xi(n));break;case 7:this.writeValue(String(n.getTime()/1000));break}}else if(r.isDocumentSchema())if(Array.isArray(n))this.write(79,n,s);else if(n instanceof Date)this.write(4,n,s);else if(n instanceof Uint8Array)this.write(21,n,s);else if(n&&typeof n==="object")this.write(143,n,s);else this.writeKey(s),this.writeValue(String(n));else if(r.isListSchema()){if(Array.isArray(n))if(n.length===0){if(this.settings.serializeEmptyLists)this.writeKey(s),this.writeValue("")}else{let e=r.getValueSchema(),i=this.settings.flattenLists||r.getMergedTraits().xmlFlattened,f=1;for(let o of n){if(o==null)continue;let c=e.getMergedTraits(),h=this.getKey("member",c.xmlName,c.ec2QueryName),u=i?`${s}${f}`:`${s}${h}.${f}`;this.write(e,o,u),++f}}}else if(r.isMapSchema()){if(n&&typeof n==="object"){let e=r.getKeySchema(),i=r.getValueSchema(),f=r.getMergedTraits().xmlFlattened,o=1;for(let c in n){let h=n[c];if(h==null)continue;let u=e.getMergedTraits(),l=this.getKey("key",u.xmlName,u.ec2QueryName),_=f?`${s}${o}.${l}`:`${s}entry.${o}.${l}`,w=i.getMergedTraits(),A=this.getKey("value",w.xmlName,w.ec2QueryName),M=f?`${s}${o}.${A}`:`${s}entry.${o}.${A}`;this.write(e,c,_),this.write(i,h,M),++o}}}else if(r.isStructSchema()){if(n&&typeof n==="object"){let e=!1;for(let[i,f]of r.structIterator()){if(n[i]==null&&!f.isIdempotencyToken())continue;let o=f.getMergedTraits(),c=this.getKey(i,o.xmlName,o.ec2QueryName,"struct"),h=`${s}${c}`;this.write(f,n[i],h),e=!0}if(!e&&r.isUnionSchema()){let{$unknown:i}=n;if(Array.isArray(i)){let[f,o]=i,c=`${s}${f}`;this.write(15,o,c)}}}}else if(r.isUnitSchema());else throw Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${r.getName(!0)}`)}flush(){if(this.buffer===void 0)throw Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer.");let t=this.buffer;return delete this.buffer,t}getKey(t,n,s,r){let{ec2:e,capitalizeKeys:i}=this.settings;if(e&&s)return s;let f=n??t;if(i&&r==="struct")return f[0].toUpperCase()+f.slice(1);return f}writeKey(t){if(t.endsWith("."))t=t.slice(0,t.length-1);this.buffer+=`&${EM(t)}=`}writeValue(t){this.buffer+=EM(t)}}class gh extends UM{options;serializer;deserializer;mixin=new or;constructor(t){super({defaultNamespace:t.defaultNamespace,errorTypeRegistries:t.errorTypeRegistries});this.options=t;let n={timestampFormat:{useTrait:!0,default:5},httpBindings:!1,xmlNamespace:t.xmlNamespace,serviceNamespace:t.defaultNamespace,serializeEmptyLists:!0};this.serializer=new dh(n),this.deserializer=new ki(n)}getShapeId(){return"aws.protocols#awsQuery"}setSerdeContext(t){this.serializer.setSerdeContext(t),this.deserializer.setSerdeContext(t)}getPayloadCodec(){throw Error("AWSQuery protocol has no payload codec.")}async serializeRequest(t,n,s){let r=await super.serializeRequest(t,n,s);if(!r.path.endsWith("/"))r.path+="/";if(r.headers["content-type"]="application/x-www-form-urlencoded",SM(t.input)==="unit"||!r.body)r.body="";let e=t.name.split("#")[1]??t.name;if(r.body=`Action=${e}&Version=${this.options.version}`+r.body,r.body.endsWith("&"))r.body=r.body.slice(-1);return r}async deserializeResponse(t,n,s){let r=this.deserializer,e=et.of(t.output),i={};if(s.statusCode>=300){let h=await uh(s.body,n);if(h.byteLength>0)Object.assign(i,await r.read(15,h));await this.handleError(t,n,s,i,this.deserializeMetadata(s))}for(let h in s.headers){let u=s.headers[h];delete s.headers[h],s.headers[h.toLowerCase()]=u}let f=t.name.split("#")[1]??t.name,o=e.isStructSchema()&&this.useNestedResult()?f+"Result":void 0,c=await uh(s.body,n);if(c.byteLength>0)Object.assign(i,await r.read(e,c,o));return i.$metadata=this.deserializeMetadata(s),i}useNestedResult(){return!0}async handleError(t,n,s,r,e){let i=this.loadQueryErrorCode(s,r)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,i,this.options.defaultNamespace);let f=this.loadQueryError(r)??{},o=this.loadQueryErrorMessage(r);f.message=o,f.Error={Type:f.Type,Code:f.Code,Message:o};let{errorSchema:c,errorMetadata:h}=await this.mixin.getErrorSchemaOrThrowBaseException(i,this.options.defaultNamespace,s,f,e,this.mixin.findQueryCompatibleError),u=et.of(c),_=new(this.compositeErrorRegistry.getErrorCtor(c)??Error)({}),w={Type:f.Error.Type,Code:f.Error.Code,Error:f.Error};for(let[A,M]of u.structIterator()){let d=M.getMergedTraits().xmlName??A,E=f[d]??r[d];w[A]=this.deserializer.readSchema(M,E)}throw this.mixin.decorateServiceException(Object.assign(_,h,{$fault:u.getMergedTraits().error,message:o},w),r)}loadQueryErrorCode(t,n){let s=(n.Errors?.[0]?.Error??n.Errors?.Error??n.Error)?.Code;if(s!==void 0)return s;if(t.statusCode==404)return"NotFound"}loadQueryError(t){return t.Errors?.[0]?.Error??t.Errors?.Error??t.Error}loadQueryErrorMessage(t){let n=this.loadQueryError(t);return n?.message??n?.Message??t.message??t.Message??"Unknown"}getDefaultContentType(){return"application/x-www-form-urlencoded"}}class JM extends gh{options;constructor(t){super(t);this.options=t;let n={capitalizeKeys:!0,flattenLists:!0,serializeEmptyLists:!1,ec2:!0};Object.assign(this.serializer.settings,n)}getShapeId(){return"aws.protocols#ec2Query"}useNestedResult(){return!1}}var zM=(t,n)=>PM(t,n).then((s)=>{if(s.length){let r;try{r=mM(s)}catch(o){if(o&&typeof o==="object")Object.defineProperty(o,"$responseBodyText",{value:s});throw o}let e="#text",i=Object.keys(r)[0],f=r[i];if(f[e])f[i]=f[e],delete f[e];return $M(f)}return{}}),gm=async(t,n)=>{let s=await zM(t,n);if(s.Error)s.Error.message=s.Error.message??s.Error.Message;return s},kM=(t,n)=>{if(n?.Error?.Code!==void 0)return n.Error.Code;if(n?.Code!==void 0)return n.Code;if(t.statusCode==404)return"NotFound"};class Eh extends kn{settings;stringBuffer;byteBuffer;buffer;constructor(t){super();this.settings=t}write(t,n){let s=et.of(t);if(s.isStringSchema()&&typeof n==="string")this.stringBuffer=n;else if(s.isBlobSchema())this.byteBuffer="byteLength"in n?n:(this.serdeContext?.base64Decoder??GM)(n);else{this.buffer=this.writeStruct(s,n,void 0);let r=s.getMergedTraits();if(r.httpPayload&&!r.xmlName)this.buffer.withName(s.getName())}}flush(){if(this.byteBuffer!==void 0){let n=this.byteBuffer;return delete this.byteBuffer,n}if(this.stringBuffer!==void 0){let n=this.stringBuffer;return delete this.stringBuffer,n}let t=this.buffer;if(this.settings.xmlNamespace){if(!t?.attributes?.xmlns)t.addAttribute("xmlns",this.settings.xmlNamespace)}return delete this.buffer,t.toString()}writeStruct(t,n,s){let r=t.getMergedTraits(),e=t.isMemberSchema()&&!r.httpPayload?t.getMemberTraits().xmlName??t.getMemberName():r.xmlName??t.getName();if(!e||!t.isStructSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${t.getName(!0)}.`);let i=qt.of(e),[f,o]=this.getXmlnsAttribute(t,s);for(let[h,u]of t.structIterator()){let l=n[h];if(l!=null||u.isIdempotencyToken()){if(u.getMergedTraits().xmlAttribute){i.addAttribute(u.getMergedTraits().xmlName??h,this.writeSimple(u,l));continue}if(u.isListSchema())this.writeList(u,l,i,o);else if(u.isMapSchema())this.writeMap(u,l,i,o);else if(u.isStructSchema())i.addChildNode(this.writeStruct(u,l,o));else{let _=qt.of(u.getMergedTraits().xmlName??u.getMemberName());this.writeSimpleInto(u,l,_,o),i.addChildNode(_)}}}let{$unknown:c}=n;if(c&&t.isUnionSchema()&&Array.isArray(c)&&Object.keys(n).length===1){let[h,u]=c,l=qt.of(h);if(typeof u!=="string")if(n instanceof qt||n instanceof RM)i.addChildNode(n);else throw Error("@aws-sdk - $unknown union member in XML requires value of type string, @aws-sdk/xml-builder::XmlNode or XmlText.");this.writeSimpleInto(0,u,l,o),i.addChildNode(l)}if(o)i.addAttribute(f,o);return i}writeList(t,n,s,r){if(!t.isMemberSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${t.getName(!0)}`);let e=t.getMergedTraits(),i=t.getValueSchema(),f=i.getMergedTraits(),o=!!f.sparse,c=!!e.xmlFlattened,[h,u]=this.getXmlnsAttribute(t,r),l=(_,w)=>{if(i.isListSchema())this.writeList(i,Array.isArray(w)?w:[w],_,u);else if(i.isMapSchema())this.writeMap(i,w,_,u);else if(i.isStructSchema()){let A=this.writeStruct(i,w,u);_.addChildNode(A.withName(c?e.xmlName??t.getMemberName():f.xmlName??"member"))}else{let A=qt.of(c?e.xmlName??t.getMemberName():f.xmlName??"member");this.writeSimpleInto(i,w,A,u),_.addChildNode(A)}};if(c){for(let _ of n)if(o||_!=null)l(s,_)}else{let _=qt.of(e.xmlName??t.getMemberName());if(u)_.addAttribute(h,u);for(let w of n)if(o||w!=null)l(_,w);s.addChildNode(_)}}writeMap(t,n,s,r,e=!1){if(!t.isMemberSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${t.getName(!0)}`);let i=t.getMergedTraits(),f=t.getKeySchema(),c=f.getMergedTraits().xmlName??"key",h=t.getValueSchema(),u=h.getMergedTraits(),l=u.xmlName??"value",_=!!u.sparse,w=!!i.xmlFlattened,[A,M]=this.getXmlnsAttribute(t,r),d=(E,b,L)=>{let S=qt.of(c,b),[O,x]=this.getXmlnsAttribute(f,M);if(x)S.addAttribute(O,x);E.addChildNode(S);let X=qt.of(l);if(h.isListSchema())this.writeList(h,L,X,M);else if(h.isMapSchema())this.writeMap(h,L,X,M,!0);else if(h.isStructSchema())X=this.writeStruct(h,L,M);else this.writeSimpleInto(h,L,X,M);E.addChildNode(X)};if(w)for(let E in n){let b=n[E];if(_||b!=null){let L=qt.of(i.xmlName??t.getMemberName());d(L,E,b),s.addChildNode(L)}}else{let E;if(!e){if(E=qt.of(i.xmlName??t.getMemberName()),M)E.addAttribute(A,M);s.addChildNode(E)}for(let b in n){let L=n[b];if(_||L!=null){let S=qt.of("entry");d(S,b,L),(e?s:E).addChildNode(S)}}}}writeSimple(t,n){if(n===null)throw Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value.");let s=et.of(t),r=null;if(n&&typeof n==="object")if(s.isBlobSchema())r=(this.serdeContext?.base64Encoder??Yi)(n);else if(s.isTimestampSchema()&&n instanceof Date)switch(Qi(s,this.settings)){case 5:r=n.toISOString().replace(".000Z","Z");break;case 6:r=xi(n);break;case 7:r=String(n.getTime()/1000);break;default:console.warn("Missing timestamp format, using http date",n),r=xi(n);break}else if(s.isBigDecimalSchema()&&n){if(n instanceof cn)return n.string;return String(n)}else if(s.isMapSchema()||s.isListSchema())throw Error("@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead.");else throw Error(`@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${s.getName(!0)}`);if(s.isBooleanSchema()||s.isNumericSchema()||s.isBigIntegerSchema()||s.isBigDecimalSchema())r=String(n);if(s.isStringSchema())if(n===void 0&&s.isIdempotencyToken())r=lh();else r=String(n);if(r===null)throw Error(`Unhandled schema-value pair ${s.getName(!0)}=${n}`);return r}writeSimpleInto(t,n,s,r){let e=this.writeSimple(t,n),i=et.of(t),f=new RM(e),[o,c]=this.getXmlnsAttribute(i,r);if(c)s.addAttribute(o,c);s.addChildNode(f)}getXmlnsAttribute(t,n){let s=t.getMergedTraits(),[r,e]=s.xmlNamespace??[];if(e&&e!==n)return[r?`xmlns:${r}`:"xmlns",e];return[void 0,void 0]}}class Rh extends kn{settings;constructor(t){super();this.settings=t}createSerializer(){let t=new Eh(this.settings);return t.setSerdeContext(this.serdeContext),t}createDeserializer(){let t=new ki(this.settings);return t.setSerdeContext(this.serdeContext),t}}class XM extends LM{codec;serializer;deserializer;mixin=new or;constructor(t){super(t);let n={timestampFormat:{useTrait:!0,default:5},httpBindings:!0,xmlNamespace:t.xmlNamespace,serviceNamespace:t.defaultNamespace};this.codec=new Rh(n),this.serializer=new IM(this.codec.createSerializer(),n),this.deserializer=new OM(this.codec.createDeserializer(),n)}getPayloadCodec(){return this.codec}getShapeId(){return"aws.protocols#restXml"}async serializeRequest(t,n,s){let r=await super.serializeRequest(t,n,s),e=et.of(t.input);if(!r.headers["content-type"]){let i=this.mixin.resolveRestContentType(this.getDefaultContentType(),e);if(i)r.headers["content-type"]=i}if(typeof r.body==="string"&&r.headers["content-type"]===this.getDefaultContentType()&&!r.body.startsWith("<?xml ")&&!this.hasUnstructuredPayloadBinding(e))r.body='<?xml version="1.0" encoding="UTF-8"?>'+r.body;return r}async deserializeResponse(t,n,s){return super.deserializeResponse(t,n,s)}async handleError(t,n,s,r,e){let i=kM(s,r)??"Unknown";if(this.mixin.compose(this.compositeErrorRegistry,i,this.options.defaultNamespace),r.Error&&typeof r.Error==="object"){for(let A of Object.keys(r.Error))if(r[A]=r.Error[A],A.toLowerCase()==="message")r.message=r.Error[A]}if(r.RequestId&&!e.requestId)e.requestId=r.RequestId;let{errorSchema:f,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(i,this.options.defaultNamespace,s,r,e),c=et.of(f),h=r.Error?.message??r.Error?.Message??r.message??r.Message??"UnknownError",l=new(this.compositeErrorRegistry.getErrorCtor(f)??Error)({});await this.deserializeHttpMessage(f,n,s,r);let _={},w=this.codec.createDeserializer();for(let[A,M]of c.structIterator()){let d=M.getMergedTraits().xmlName??A,E=r.Error?.[d]??r[d];_[A]=w.readSchema(M,E)}throw this.mixin.decorateServiceException(Object.assign(l,o,{$fault:c.getMergedTraits().error,message:h},_),r)}getDefaultContentType(){return"application/xml"}hasUnstructuredPayloadBinding(t){for(let[,n]of t.structIterator())if(n.getMergedTraits().httpPayload)return!(n.isStructSchema()||n.isMapSchema()||n.isListSchema());return!1}}Em.AwsEc2QueryProtocol=JM;Em.AwsJson1_0Protocol=YM;Em.AwsJson1_1Protocol=xM;Em.AwsJsonRpcProtocol=zi;Em.AwsQueryProtocol=gh;Em.AwsRestJsonProtocol=QM;Em.AwsRestXmlProtocol=XM;Em.AwsSmithyRpcV2CborProtocol=FM;Em.JsonCodec=Ji;Em.JsonShapeDeserializer=Ah;Em.JsonShapeSerializer=Mh;Em.QueryShapeSerializer=dh;Em.XmlCodec=Rh;Em.XmlShapeDeserializer=ki;Em.XmlShapeSerializer=Eh;Em._toBool=_m;Em._toNum=wm;Em._toStr=lm;Em.awsExpectUnion=dm;Em.loadJsonRpcErrorCode=NM;Em.loadRestJsonErrorCode=HM;Em.loadRestXmlErrorCode=kM;Em.parseJsonBody=wh;Em.parseJsonErrorBody=Mm;Em.parseXmlBody=zM;Em.parseXmlErrorBody=gm});var Ih=K((iH)=>{var{awsEndpointFunctions:qm,emitWarningIfUnsupportedVersion:Cm,createDefaultUserAgentProvider:am,NODE_APP_ID_CONFIG_OPTIONS:Km,getAwsRegionExtensionConfiguration:Vm,resolveAwsRegionExtensionConfiguration:jm,resolveUserAgentConfig:pm,resolveHostHeaderConfig:vm,getUserAgentPlugin:Zm,getHostHeaderPlugin:tF,getLoggerPlugin:nF,getRecursionDetectionPlugin:sF}=kt(),{NoAuthSigner:rF,getHttpAuthSchemeEndpointRuleSetPlugin:eF,DefaultIdentityProviderConfig:iF,getHttpSigningPlugin:oF}=Qn(),{normalizeProvider:VM,getSmithyContext:fF,ServiceException:cF,NoOpLogger:hF,emitWarningIfUnsupportedVersion:uF,loadConfigsForDefaultMode:lF,getDefaultExtensionConfiguration:_F,resolveDefaultRuntimeConfig:wF,Client:jM,makeBuilder:AF,createAggregatedClient:MF}=En(),{Command:dF}=En();iH.$Command=dF;iH.__Client=jM;var{resolveDefaultsModeConfig:gF,loadConfig:As,NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS:EF,NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS:RF,NODE_REGION_CONFIG_OPTIONS:bF,NODE_REGION_CONFIG_FILE_OPTIONS:TF,resolveRegionConfig:SF}=Rt(),{BinaryDecisionDiagram:$F,EndpointCache:UF,decideEndpoint:LF,customEndpointFunctions:IF,resolveEndpointConfig:OF,getEndpointPlugin:yF}=fs(),{parseUrl:GF,getHttpHandlerExtensionConfiguration:BF,resolveHttpHandlerRuntimeConfig:mF,getContentLengthPlugin:FF}=Tt(),{DEFAULT_RETRY_MODE:PF,NODE_RETRY_MODE_CONFIG_OPTIONS:HF,NODE_MAX_ATTEMPT_CONFIG_OPTIONS:NF,resolveRetryConfig:DF,getRetryPlugin:WF}=pr(),{TypeRegistry:pM,getSchemaSerdePlugin:YF}=Pn(),{resolveAwsSdkSigV4Config:xF,AwsSdkSigV4Signer:QF,NODE_AUTH_SCHEME_PREFERENCE_OPTIONS:JF}=zc(),{toUtf8:zF,fromUtf8:kF,toBase64:XF,fromBase64:qF,calculateBodyLength:CF}=bt(),{streamCollector:aF,NodeHttpHandler:KF}=Ni(),{AwsRestJsonProtocol:VF}=bh(),{Sha256:jF}=af(),pF=async(t,n,s)=>{return{operation:fF(n).operation,region:await VM(t.region)()||(()=>{throw Error("expected `region` to be configured for `aws.auth#sigv4`")})()}};function vF(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sso-oauth",region:t.region},propertiesExtractor:(n,s)=>({signingProperties:{config:n,context:s}})}}function ZF(t){return{schemeId:"smithy.api#noAuth"}}var tP=(t)=>{let n=[];switch(t.operation){case"CreateToken":{n.push(ZF());break}default:n.push(vF(t))}return n},nP=(t)=>{let n=xF(t);return Object.assign(n,{authSchemePreference:VM(t.authSchemePreference??[])})},sP=(t)=>{return Object.assign(t,{useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,defaultSigningName:"sso-oauth"})},rP={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},eP="3.997.32",iP={version:eP},ue="ref",Ms=-1,Xi=!0,qM="isSet",vM="PartitionResult",qi="booleanEquals",Th="getAttr",CM={[ue]:"Endpoint"},Sh={[ue]:vM},fr={},aM=[{[ue]:"Region"}],KM={conditions:[[qM,[CM]],[qM,aM],["aws.partition",aM,vM],[qi,[{[ue]:"UseFIPS"},Xi]],[qi,[{[ue]:"UseDualStack"},Xi]],[qi,[{fn:Th,argv:[Sh,"supportsDualStack"]},Xi]],[qi,[{fn:Th,argv:[Sh,"supportsFIPS"]},Xi]],["stringEquals",[{fn:Th,argv:[Sh,"name"]},"aws-us-gov"]]],results:[[Ms],[Ms,"Invalid Configuration: FIPS and custom endpoint are not supported"],[Ms,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[CM,fr],["https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",fr],[Ms,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://oidc.{Region}.amazonaws.com",fr],["https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}",fr],[Ms,"FIPS is enabled but this partition does not support FIPS"],["https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}",fr],[Ms,"DualStack is enabled but this partition does not support DualStack"],["https://oidc.{Region}.{PartitionResult#dnsSuffix}",fr],[Ms,"Invalid Configuration: Missing Region"]]},oP=2,St=1e8,fP=new Int32Array([-1,1,-1,0,13,3,1,4,St+12,2,5,St+12,3,8,6,4,7,St+11,5,St+9,St+10,4,11,9,6,10,St+8,7,St+6,St+7,5,12,St+5,6,St+4,St+5,3,St+1,14,4,St+2,St+3]),cP=$F.from(fP,oP,KM.conditions,KM.results),hP=new UF({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),uP=(t,n={})=>{return hP.get(t,()=>LF(cP,{endpointParams:t,logger:n.logger}))};IF.aws=qm;class dt extends cF{constructor(t){super(t);Object.setPrototypeOf(this,dt.prototype)}}class Ci extends dt{name="AccessDeniedException";$fault="client";error;reason;error_description;constructor(t){super({name:"AccessDeniedException",$fault:"client",...t});Object.setPrototypeOf(this,Ci.prototype),this.error=t.error,this.reason=t.reason,this.error_description=t.error_description}}class ai extends dt{name="AuthorizationPendingException";$fault="client";error;error_description;constructor(t){super({name:"AuthorizationPendingException",$fault:"client",...t});Object.setPrototypeOf(this,ai.prototype),this.error=t.error,this.error_description=t.error_description}}class Ki extends dt{name="ExpiredTokenException";$fault="client";error;error_description;constructor(t){super({name:"ExpiredTokenException",$fault:"client",...t});Object.setPrototypeOf(this,Ki.prototype),this.error=t.error,this.error_description=t.error_description}}class Vi extends dt{name="InternalServerException";$fault="server";error;error_description;constructor(t){super({name:"InternalServerException",$fault:"server",...t});Object.setPrototypeOf(this,Vi.prototype),this.error=t.error,this.error_description=t.error_description}}class ji extends dt{name="InvalidClientException";$fault="client";error;error_description;constructor(t){super({name:"InvalidClientException",$fault:"client",...t});Object.setPrototypeOf(this,ji.prototype),this.error=t.error,this.error_description=t.error_description}}class pi extends dt{name="InvalidGrantException";$fault="client";error;error_description;constructor(t){super({name:"InvalidGrantException",$fault:"client",...t});Object.setPrototypeOf(this,pi.prototype),this.error=t.error,this.error_description=t.error_description}}class vi extends dt{name="InvalidRequestException";$fault="client";error;reason;error_description;constructor(t){super({name:"InvalidRequestException",$fault:"client",...t});Object.setPrototypeOf(this,vi.prototype),this.error=t.error,this.reason=t.reason,this.error_description=t.error_description}}class Zi extends dt{name="InvalidScopeException";$fault="client";error;error_description;constructor(t){super({name:"InvalidScopeException",$fault:"client",...t});Object.setPrototypeOf(this,Zi.prototype),this.error=t.error,this.error_description=t.error_description}}class to extends dt{name="SlowDownException";$fault="client";error;error_description;constructor(t){super({name:"SlowDownException",$fault:"client",...t});Object.setPrototypeOf(this,to.prototype),this.error=t.error,this.error_description=t.error_description}}class no extends dt{name="UnauthorizedClientException";$fault="client";error;error_description;constructor(t){super({name:"UnauthorizedClientException",$fault:"client",...t});Object.setPrototypeOf(this,no.prototype),this.error=t.error,this.error_description=t.error_description}}class so extends dt{name="UnsupportedGrantTypeException";$fault="client";error;error_description;constructor(t){super({name:"UnsupportedGrantTypeException",$fault:"client",...t});Object.setPrototypeOf(this,so.prototype),this.error=t.error,this.error_description=t.error_description}}var lP="AccessDeniedException",_P="AuthorizationPendingException",wP="AccessToken",AP="ClientSecret",MP="CreateToken",dP="CreateTokenRequest",gP="CreateTokenResponse",EP="CodeVerifier",RP="ExpiredTokenException",bP="InvalidClientException",TP="InvalidGrantException",SP="InvalidRequestException",$P="InternalServerException",UP="InvalidScopeException",LP="IdToken",IP="RefreshToken",OP="SlowDownException",yP="UnauthorizedClientException",GP="UnsupportedGrantTypeException",BP="accessToken",hn="client",mP="clientId",FP="clientSecret",PP="codeVerifier",HP="code",NP="deviceCode",nt="error",DP="expiresIn",Ct="error_description",WP="grantType",YP="http",at="httpError",xP="idToken",ZM="reason",t1="refreshToken",QP="redirectUri",n1="smithy.ts.sdk.synthetic.com.amazonaws.ssooidc",JP="scope",zP="server",kP="tokenType",it="com.amazonaws.ssooidc",s1=pM.for(n1),r1=[-3,n1,"SSOOIDCServiceException",0,[],[]];s1.registerError(r1,dt);var Nt=pM.for(it),e1=[-3,it,lP,{[nt]:hn,[at]:400},[nt,ZM,Ct],[0,0,0]];Nt.registerError(e1,Ci);var i1=[-3,it,_P,{[nt]:hn,[at]:400},[nt,Ct],[0,0]];Nt.registerError(i1,ai);var o1=[-3,it,RP,{[nt]:hn,[at]:400},[nt,Ct],[0,0]];Nt.registerError(o1,Ki);var f1=[-3,it,$P,{[nt]:zP,[at]:500},[nt,Ct],[0,0]];Nt.registerError(f1,Vi);var c1=[-3,it,bP,{[nt]:hn,[at]:401},[nt,Ct],[0,0]];Nt.registerError(c1,ji);var h1=[-3,it,TP,{[nt]:hn,[at]:400},[nt,Ct],[0,0]];Nt.registerError(h1,pi);var u1=[-3,it,SP,{[nt]:hn,[at]:400},[nt,ZM,Ct],[0,0,0]];Nt.registerError(u1,vi);var l1=[-3,it,UP,{[nt]:hn,[at]:400},[nt,Ct],[0,0]];Nt.registerError(l1,Zi);var _1=[-3,it,OP,{[nt]:hn,[at]:400},[nt,Ct],[0,0]];Nt.registerError(_1,to);var w1=[-3,it,yP,{[nt]:hn,[at]:400},[nt,Ct],[0,0]];Nt.registerError(w1,no);var A1=[-3,it,GP,{[nt]:hn,[at]:400},[nt,Ct],[0,0]];Nt.registerError(A1,so);var M1=[s1,Nt],XP=[0,it,wP,8,0],qP=[0,it,AP,8,0],CP=[0,it,EP,8,0],aP=[0,it,LP,8,0],d1=[0,it,IP,8,0],g1=[3,it,dP,0,[mP,FP,WP,NP,HP,t1,JP,QP,PP],[0,[()=>qP,0],0,0,0,[()=>d1,0],64,0,[()=>CP,0]],3],E1=[3,it,gP,0,[BP,kP,DP,t1,xP],[[()=>XP,0],0,1,[()=>d1,0],[()=>aP,0]]],R1=[9,it,MP,{[YP]:["POST","/token",200]},()=>g1,()=>E1],KP=(t)=>{return{apiVersion:"2019-06-10",base64Decoder:t?.base64Decoder??qF,base64Encoder:t?.base64Encoder??XF,disableHostPrefix:t?.disableHostPrefix??!1,endpointProvider:t?.endpointProvider??uP,extensions:t?.extensions??[],httpAuthSchemeProvider:t?.httpAuthSchemeProvider??tP,httpAuthSchemes:t?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(n)=>n.getIdentityProvider("aws.auth#sigv4"),signer:new QF},{schemeId:"smithy.api#noAuth",identityProvider:(n)=>n.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new rF}],logger:t?.logger??new hF,protocol:t?.protocol??VF,protocolSettings:t?.protocolSettings??{defaultNamespace:"com.amazonaws.ssooidc",errorTypeRegistries:M1,version:"2019-06-10",serviceTarget:"AWSSSOOIDCService"},serviceId:t?.serviceId??"SSO OIDC",sha256:t?.sha256??jF,urlParser:t?.urlParser??GF,utf8Decoder:t?.utf8Decoder??kF,utf8Encoder:t?.utf8Encoder??zF}},VP=(t)=>{uF(process.version);let n=gF(t),s=()=>n().then(lF),r=KP(t);Cm(process.version);let e={profile:t?.profile,logger:r.logger};return{...r,...t,runtime:"node",defaultsMode:n,authSchemePreference:t?.authSchemePreference??As(JF,e),bodyLengthChecker:t?.bodyLengthChecker??CF,defaultUserAgentProvider:t?.defaultUserAgentProvider??am({serviceId:r.serviceId,clientVersion:iP.version}),maxAttempts:t?.maxAttempts??As(NF,t),region:t?.region??As(bF,{...TF,...e}),requestHandler:KF.create(t?.requestHandler??s),retryMode:t?.retryMode??As({...HF,default:async()=>(await s()).retryMode||PF},t),streamCollector:t?.streamCollector??aF,useDualstackEndpoint:t?.useDualstackEndpoint??As(RF,e),useFipsEndpoint:t?.useFipsEndpoint??As(EF,e),userAgentAppId:t?.userAgentAppId??As(Km,e)}},jP=(t)=>{let{httpAuthSchemes:n,httpAuthSchemeProvider:s,credentials:r}=t;return{setHttpAuthScheme(e){let i=n.findIndex((f)=>f.schemeId===e.schemeId);if(i===-1)n.push(e);else n.splice(i,1,e)},httpAuthSchemes(){return n},setHttpAuthSchemeProvider(e){s=e},httpAuthSchemeProvider(){return s},setCredentials(e){r=e},credentials(){return r}}},pP=(t)=>{return{httpAuthSchemes:t.httpAuthSchemes(),httpAuthSchemeProvider:t.httpAuthSchemeProvider(),credentials:t.credentials()}},vP=(t,n)=>{let s=Object.assign(Vm(t),_F(t),BF(t),jP(t));return n.forEach((r)=>r.configure(s)),Object.assign(t,jm(s),wF(s),mF(s),pP(s))};class $h extends jM{config;constructor(...[t]){let n=VP(t||{});super(n);this.initConfig=n;let s=sP(n),r=pm(s),e=DF(r),i=SF(e),f=vm(i),o=OF(f),c=nP(o),h=vP(c,t?.extensions||[]);this.config=h,this.middlewareStack.use(YF(this.config)),this.middlewareStack.use(Zm(this.config)),this.middlewareStack.use(WF(this.config)),this.middlewareStack.use(FF(this.config)),this.middlewareStack.use(tF(this.config)),this.middlewareStack.use(nF(this.config)),this.middlewareStack.use(sF(this.config)),this.middlewareStack.use(eF(this.config,{httpAuthSchemeParametersProvider:pF,identityProviderConfigProvider:async(u)=>new iF({"aws.auth#sigv4":u.credentials})})),this.middlewareStack.use(oF(this.config))}destroy(){super.destroy()}}var ZP=AF(rP,"AWSSSOOIDCService","SSOOIDCClient",yF),tH={},nH=(t,n,s,r)=>[];class Uh extends ZP(tH,nH,"CreateToken",R1){}var sH={CreateTokenCommand:Uh};class Lh extends $h{}MF(sH,Lh);var rH={KMS_ACCESS_DENIED:"KMS_AccessDeniedException"},eH={KMS_DISABLED_KEY:"KMS_DisabledException",KMS_INVALID_KEY_USAGE:"KMS_InvalidKeyUsageException",KMS_INVALID_STATE:"KMS_InvalidStateException",KMS_KEY_NOT_FOUND:"KMS_NotFoundException"};iH.AccessDeniedException=Ci;iH.AccessDeniedException$=e1;iH.AccessDeniedExceptionReason=rH;iH.AuthorizationPendingException=ai;iH.AuthorizationPendingException$=i1;iH.CreateToken$=R1;iH.CreateTokenCommand=Uh;iH.CreateTokenRequest$=g1;iH.CreateTokenResponse$=E1;iH.ExpiredTokenException=Ki;iH.ExpiredTokenException$=o1;iH.InternalServerException=Vi;iH.InternalServerException$=f1;iH.InvalidClientException=ji;iH.InvalidClientException$=c1;iH.InvalidGrantException=pi;iH.InvalidGrantException$=h1;iH.InvalidRequestException=vi;iH.InvalidRequestException$=u1;iH.InvalidRequestExceptionReason=eH;iH.InvalidScopeException=Zi;iH.InvalidScopeException$=l1;iH.SSOOIDC=Lh;iH.SSOOIDCClient=$h;iH.SSOOIDCServiceException=dt;iH.SSOOIDCServiceException$=r1;iH.SlowDownException=to;iH.SlowDownException$=_1;iH.UnauthorizedClientException=no;iH.UnauthorizedClientException$=w1;iH.UnsupportedGrantTypeException=so;iH.UnsupportedGrantTypeException$=A1;iH.errorTypeRegistries=M1});import{existsSync as FE,readFileSync as PE}from"fs";import{homedir as HE}from"os";import{join as du}from"path";var g={};Rg(g,{void:()=>rE,util:()=>J,unknown:()=>nE,union:()=>fE,undefined:()=>vg,tuple:()=>uE,transformer:()=>bE,symbol:()=>pg,string:()=>wu,strictObject:()=>oE,setErrorMap:()=>Sg,set:()=>wE,record:()=>lE,quotelessJson:()=>bg,promise:()=>RE,preprocess:()=>$E,pipeline:()=>UE,ostring:()=>LE,optional:()=>TE,onumber:()=>IE,oboolean:()=>OE,objectUtil:()=>Po,object:()=>iE,number:()=>Au,nullable:()=>SE,null:()=>Zg,never:()=>sE,nativeEnum:()=>EE,nan:()=>Kg,map:()=>_E,makeIssue:()=>Ar,literal:()=>dE,lazy:()=>ME,late:()=>Cg,isValid:()=>In,isDirty:()=>Re,isAsync:()=>Ss,isAborted:()=>Ee,intersection:()=>hE,instanceof:()=>ag,getParsedType:()=>Vt,getErrorMap:()=>Ts,function:()=>AE,enum:()=>gE,effect:()=>bE,discriminatedUnion:()=>cE,defaultErrorMap:()=>wn,datetimeRegex:()=>uu,date:()=>jg,custom:()=>_u,coerce:()=>yE,boolean:()=>Mu,bigint:()=>Vg,array:()=>eE,any:()=>tE,addIssueToContext:()=>$,ZodVoid:()=>dr,ZodUnknown:()=>On,ZodUnion:()=>ys,ZodUndefined:()=>Is,ZodType:()=>W,ZodTuple:()=>pt,ZodTransformer:()=>Jt,ZodSymbol:()=>Mr,ZodString:()=>Wt,ZodSet:()=>pn,ZodSchema:()=>W,ZodRecord:()=>gr,ZodReadonly:()=>Ns,ZodPromise:()=>vn,ZodPipeline:()=>br,ZodParsedType:()=>T,ZodOptional:()=>xt,ZodObject:()=>p,ZodNumber:()=>yn,ZodNullable:()=>Mn,ZodNull:()=>Os,ZodNever:()=>jt,ZodNativeEnum:()=>Fs,ZodNaN:()=>Rr,ZodMap:()=>Er,ZodLiteral:()=>ms,ZodLazy:()=>Bs,ZodIssueCode:()=>R,ZodIntersection:()=>Gs,ZodFunction:()=>Us,ZodFirstPartyTypeKind:()=>P,ZodError:()=>gt,ZodEnum:()=>Bn,ZodEffects:()=>Jt,ZodDiscriminatedUnion:()=>be,ZodDefault:()=>Ps,ZodDate:()=>Vn,ZodCatch:()=>Hs,ZodBranded:()=>Te,ZodBoolean:()=>Ls,ZodBigInt:()=>Gn,ZodArray:()=>Yt,ZodAny:()=>jn,Schema:()=>W,ParseStatus:()=>ht,OK:()=>wt,NEVER:()=>GE,INVALID:()=>F,EMPTY_PATH:()=>$g,DIRTY:()=>Kn,BRAND:()=>qg});var J;(function(t){t.assertEqual=(e)=>{};function n(e){}t.assertIs=n;function s(e){throw Error()}t.assertNever=s,t.arrayToEnum=(e)=>{let i={};for(let f of e)i[f]=f;return i},t.getValidEnumValues=(e)=>{let i=t.objectKeys(e).filter((o)=>typeof e[e[o]]!=="number"),f={};for(let o of i)f[o]=e[o];return t.objectValues(f)},t.objectValues=(e)=>{return t.objectKeys(e).map(function(i){return e[i]})},t.objectKeys=typeof Object.keys==="function"?(e)=>Object.keys(e):(e)=>{let i=[];for(let f in e)if(Object.prototype.hasOwnProperty.call(e,f))i.push(f);return i},t.find=(e,i)=>{for(let f of e)if(i(f))return f;return},t.isInteger=typeof Number.isInteger==="function"?(e)=>Number.isInteger(e):(e)=>typeof e==="number"&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,i=" | "){return e.map((f)=>typeof f==="string"?`'${f}'`:f).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(e,i)=>{if(typeof i==="bigint")return i.toString();return i}})(J||(J={}));var Po;(function(t){t.mergeShapes=(n,s)=>{return{...n,...s}}})(Po||(Po={}));var T=J.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Vt=(t)=>{switch(typeof t){case"undefined":return T.undefined;case"string":return T.string;case"number":return Number.isNaN(t)?T.nan:T.number;case"boolean":return T.boolean;case"function":return T.function;case"bigint":return T.bigint;case"symbol":return T.symbol;case"object":if(Array.isArray(t))return T.array;if(t===null)return T.null;if(t.then&&typeof t.then==="function"&&t.catch&&typeof t.catch==="function")return T.promise;if(typeof Map<"u"&&t instanceof Map)return T.map;if(typeof Set<"u"&&t instanceof Set)return T.set;if(typeof Date<"u"&&t instanceof Date)return T.date;return T.object;default:return T.unknown}};var R=J.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"]),bg=(t)=>{return JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:")};class gt extends Error{get errors(){return this.issues}constructor(t){super();this.issues=[],this.addIssue=(s)=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};let n=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,n);else this.__proto__=n;this.name="ZodError",this.issues=t}format(t){let n=t||function(e){return e.message},s={_errors:[]},r=(e)=>{for(let i of e.issues)if(i.code==="invalid_union")i.unionErrors.map(r);else if(i.code==="invalid_return_type")r(i.returnTypeError);else if(i.code==="invalid_arguments")r(i.argumentsError);else if(i.path.length===0)s._errors.push(n(i));else{let f=s,o=0;while(o<i.path.length){let c=i.path[o];if(o!==i.path.length-1)f[c]=f[c]||{_errors:[]};else f[c]=f[c]||{_errors:[]},f[c]._errors.push(n(i));f=f[c],o++}}};return r(this),s}static assert(t){if(!(t instanceof gt))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,J.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=(n)=>n.message){let n={},s=[];for(let r of this.issues)if(r.path.length>0){let e=r.path[0];n[e]=n[e]||[],n[e].push(t(r))}else s.push(t(r));return{formErrors:s,fieldErrors:n}}get formErrors(){return this.flatten()}}gt.create=(t)=>{return new gt(t)};var Tg=(t,n)=>{let s;switch(t.code){case R.invalid_type:if(t.received===T.undefined)s="Required";else s=`Expected ${t.expected}, received ${t.received}`;break;case R.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(t.expected,J.jsonStringifyReplacer)}`;break;case R.unrecognized_keys:s=`Unrecognized key(s) in object: ${J.joinValues(t.keys,", ")}`;break;case R.invalid_union:s="Invalid input";break;case R.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${J.joinValues(t.options)}`;break;case R.invalid_enum_value:s=`Invalid enum value. Expected ${J.joinValues(t.options)}, received '${t.received}'`;break;case R.invalid_arguments:s="Invalid function arguments";break;case R.invalid_return_type:s="Invalid function return type";break;case R.invalid_date:s="Invalid date";break;case R.invalid_string:if(typeof t.validation==="object")if("includes"in t.validation){if(s=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position==="number")s=`${s} at one or more positions greater than or equal to ${t.validation.position}`}else if("startsWith"in t.validation)s=`Invalid input: must start with "${t.validation.startsWith}"`;else if("endsWith"in t.validation)s=`Invalid input: must end with "${t.validation.endsWith}"`;else J.assertNever(t.validation);else if(t.validation!=="regex")s=`Invalid ${t.validation}`;else s="Invalid";break;case R.too_small:if(t.type==="array")s=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`;else if(t.type==="string")s=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`;else if(t.type==="number")s=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`;else if(t.type==="bigint")s=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`;else if(t.type==="date")s=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`;else s="Invalid input";break;case R.too_big:if(t.type==="array")s=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`;else if(t.type==="string")s=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`;else if(t.type==="number")s=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`;else if(t.type==="bigint")s=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`;else if(t.type==="date")s=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`;else s="Invalid input";break;case R.custom:s="Invalid input";break;case R.invalid_intersection_types:s="Intersection results could not be merged";break;case R.not_multiple_of:s=`Number must be a multiple of ${t.multipleOf}`;break;case R.not_finite:s="Number must be finite";break;default:s=n.defaultError,J.assertNever(t)}return{message:s}},wn=Tg;var iu=wn;function Sg(t){iu=t}function Ts(){return iu}var Ar=(t)=>{let{data:n,path:s,errorMaps:r,issueData:e}=t,i=[...s,...e.path||[]],f={...e,path:i};if(e.message!==void 0)return{...e,path:i,message:e.message};let o="",c=r.filter((h)=>!!h).slice().reverse();for(let h of c)o=h(f,{data:n,defaultError:o}).message;return{...e,path:i,message:o}},$g=[];function $(t,n){let s=Ts(),r=Ar({issueData:n,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,s,s===wn?void 0:wn].filter((e)=>!!e)});t.common.issues.push(r)}class ht{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(t,n){let s=[];for(let r of n){if(r.status==="aborted")return F;if(r.status==="dirty")t.dirty();s.push(r.value)}return{status:t.value,value:s}}static async mergeObjectAsync(t,n){let s=[];for(let r of n){let e=await r.key,i=await r.value;s.push({key:e,value:i})}return ht.mergeObjectSync(t,s)}static mergeObjectSync(t,n){let s={};for(let r of n){let{key:e,value:i}=r;if(e.status==="aborted")return F;if(i.status==="aborted")return F;if(e.status==="dirty")t.dirty();if(i.status==="dirty")t.dirty();if(e.value!=="__proto__"&&(typeof i.value<"u"||r.alwaysSet))s[e.value]=i.value}return{status:t.value,value:s}}}var F=Object.freeze({status:"aborted"}),Kn=(t)=>({status:"dirty",value:t}),wt=(t)=>({status:"valid",value:t}),Ee=(t)=>t.status==="aborted",Re=(t)=>t.status==="dirty",In=(t)=>t.status==="valid",Ss=(t)=>typeof Promise<"u"&&t instanceof Promise;var y;(function(t){t.errToObj=(n)=>typeof n==="string"?{message:n}:n||{},t.toString=(n)=>typeof n==="string"?n:n?.message})(y||(y={}));class Qt{constructor(t,n,s,r){this._cachedPath=[],this.parent=t,this.data=n,this._path=s,this._key=r}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var ou=(t,n)=>{if(In(n))return{success:!0,data:n.value};else{if(!t.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let s=new gt(t.common.issues);return this._error=s,this._error}}}};function D(t){if(!t)return{};let{errorMap:n,invalid_type_error:s,required_error:r,description:e}=t;if(n&&(s||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(n)return{errorMap:n,description:e};return{errorMap:(f,o)=>{let{message:c}=t;if(f.code==="invalid_enum_value")return{message:c??o.defaultError};if(typeof o.data>"u")return{message:c??r??o.defaultError};if(f.code!=="invalid_type")return{message:o.defaultError};return{message:c??s??o.defaultError}},description:e}}class W{get description(){return this._def.description}_getType(t){return Vt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Vt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ht,ctx:{common:t.parent.common,data:t.data,parsedType:Vt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Ss(n))throw Error("Synchronous parse encountered promise.");return n}_parseAsync(t){let n=this._parse(t);return Promise.resolve(n)}parse(t,n){let s=this.safeParse(t,n);if(s.success)return s.data;throw s.error}safeParse(t,n){let s={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Vt(t)},r=this._parseSync({data:t,path:s.path,parent:s});return ou(s,r)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Vt(t)};if(!this["~standard"].async)try{let s=this._parseSync({data:t,path:[],parent:n});return In(s)?{value:s.value}:{issues:n.common.issues}}catch(s){if(s?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then((s)=>In(s)?{value:s.value}:{issues:n.common.issues})}async parseAsync(t,n){let s=await this.safeParseAsync(t,n);if(s.success)return s.data;throw s.error}async safeParseAsync(t,n){let s={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Vt(t)},r=this._parse({data:t,path:s.path,parent:s}),e=await(Ss(r)?r:Promise.resolve(r));return ou(s,e)}refine(t,n){let s=(r)=>{if(typeof n==="string"||typeof n>"u")return{message:n};else if(typeof n==="function")return n(r);else return n};return this._refinement((r,e)=>{let i=t(r),f=()=>e.addIssue({code:R.custom,...s(r)});if(typeof Promise<"u"&&i instanceof Promise)return i.then((o)=>{if(!o)return f(),!1;else return!0});if(!i)return f(),!1;else return!0})}refinement(t,n){return this._refinement((s,r)=>{if(!t(s))return r.addIssue(typeof n==="function"?n(s,r):n),!1;else return!0})}_refinement(t){return new Jt({schema:this,typeName:P.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,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:(n)=>this["~validate"](n)}}optional(){return xt.create(this,this._def)}nullable(){return Mn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Yt.create(this)}promise(){return vn.create(this,this._def)}or(t){return ys.create([this,t],this._def)}and(t){return Gs.create(this,t,this._def)}transform(t){return new Jt({...D(this._def),schema:this,typeName:P.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t==="function"?t:()=>t;return new Ps({...D(this._def),innerType:this,defaultValue:n,typeName:P.ZodDefault})}brand(){return new Te({typeName:P.ZodBranded,type:this,...D(this._def)})}catch(t){let n=typeof t==="function"?t:()=>t;return new Hs({...D(this._def),innerType:this,catchValue:n,typeName:P.ZodCatch})}describe(t){return new this.constructor({...this._def,description:t})}pipe(t){return br.create(this,t)}readonly(){return Ns.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var Ug=/^c[^\s-]{8,}$/i,Lg=/^[0-9a-z]+$/,Ig=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Og=/^[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,yg=/^[a-z0-9_-]{21}$/i,Gg=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Bg=/^[-+]?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)?)??$/,mg=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Fg="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ho,Pg=/^(?:(?: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])$/,Hg=/^(?:(?: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])$/,Ng=/^(([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]))$/,Dg=/^(([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])$/,Wg=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Yg=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,cu="((\\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])))",xg=new RegExp(`^${cu}$`);function hu(t){let n="[0-5]\\d";if(t.precision)n=`${n}\\.\\d{${t.precision}}`;else if(t.precision==null)n=`${n}(\\.\\d+)?`;let s=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${n})${s}`}function Qg(t){return new RegExp(`^${hu(t)}$`)}function uu(t){let n=`${cu}T${hu(t)}`,s=[];if(s.push(t.local?"Z?":"Z"),t.offset)s.push("([+-]\\d{2}:?\\d{2})");return n=`${n}(${s.join("|")})`,new RegExp(`^${n}$`)}function Jg(t,n){if((n==="v4"||!n)&&Pg.test(t))return!0;if((n==="v6"||!n)&&Ng.test(t))return!0;return!1}function zg(t,n){if(!Gg.test(t))return!1;try{let[s]=t.split(".");if(!s)return!1;let r=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(s.length+(4-s.length%4)%4,"="),e=JSON.parse(atob(r));if(typeof e!=="object"||e===null)return!1;if("typ"in e&&e?.typ!=="JWT")return!1;if(!e.alg)return!1;if(n&&e.alg!==n)return!1;return!0}catch{return!1}}function kg(t,n){if((n==="v4"||!n)&&Hg.test(t))return!0;if((n==="v6"||!n)&&Dg.test(t))return!0;return!1}class Wt extends W{_parse(t){if(this._def.coerce)t.data=String(t.data);if(this._getType(t)!==T.string){let e=this._getOrReturnCtx(t);return $(e,{code:R.invalid_type,expected:T.string,received:e.parsedType}),F}let s=new ht,r=void 0;for(let e of this._def.checks)if(e.kind==="min"){if(t.data.length<e.value)r=this._getOrReturnCtx(t,r),$(r,{code:R.too_small,minimum:e.value,type:"string",inclusive:!0,exact:!1,message:e.message}),s.dirty()}else if(e.kind==="max"){if(t.data.length>e.value)r=this._getOrReturnCtx(t,r),$(r,{code:R.too_big,maximum:e.value,type:"string",inclusive:!0,exact:!1,message:e.message}),s.dirty()}else if(e.kind==="length"){let i=t.data.length>e.value,f=t.data.length<e.value;if(i||f){if(r=this._getOrReturnCtx(t,r),i)$(r,{code:R.too_big,maximum:e.value,type:"string",inclusive:!0,exact:!0,message:e.message});else if(f)$(r,{code:R.too_small,minimum:e.value,type:"string",inclusive:!0,exact:!0,message:e.message});s.dirty()}}else if(e.kind==="email"){if(!mg.test(t.data))r=this._getOrReturnCtx(t,r),$(r,{validation:"email",code:R.invalid_string,message:e.message}),s.dirty()}else if(e.kind==="emoji"){if(!Ho)Ho=new RegExp(Fg,"u");if(!Ho.test(t.data))r=this._getOrReturnCtx(t,r),$(r,{validation:"emoji",code:R.invalid_string,message:e.message}),s.dirty()}else if(e.kind==="uuid"){if(!Og.test(t.data))r=this._getOrReturnCtx(t,r),$(r,{validation:"uuid",code:R.invalid_string,message:e.message}),s.dirty()}else if(e.kind==="nanoid"){if(!yg.test(t.data))r=this._getOrReturnCtx(t,r),$(r,{validation:"nanoid",code:R.invalid_string,message:e.message}),s.dirty()}else if(e.kind==="cuid"){if(!Ug.test(t.data))r=this._getOrReturnCtx(t,r),$(r,{validation:"cuid",code:R.invalid_string,message:e.message}),s.dirty()}else if(e.kind==="cuid2"){if(!Lg.test(t.data))r=this._getOrReturnCtx(t,r),$(r,{validation:"cuid2",code:R.invalid_string,message:e.message}),s.dirty()}else if(e.kind==="ulid"){if(!Ig.test(t.data))r=this._getOrReturnCtx(t,r),$(r,{validation:"ulid",code:R.invalid_string,message:e.message}),s.dirty()}else if(e.kind==="url")try{new URL(t.data)}catch{r=this._getOrReturnCtx(t,r),$(r,{validation:"url",code:R.invalid_string,message:e.message}),s.dirty()}else if(e.kind==="regex"){if(e.regex.lastIndex=0,!e.regex.test(t.data))r=this._getOrReturnCtx(t,r),$(r,{validation:"regex",code:R.invalid_string,message:e.message}),s.dirty()}else if(e.kind==="trim")t.data=t.data.trim();else if(e.kind==="includes"){if(!t.data.includes(e.value,e.position))r=this._getOrReturnCtx(t,r),$(r,{code:R.invalid_string,validation:{includes:e.value,position:e.position},message:e.message}),s.dirty()}else if(e.kind==="toLowerCase")t.data=t.data.toLowerCase();else if(e.kind==="toUpperCase")t.data=t.data.toUpperCase();else if(e.kind==="startsWith"){if(!t.data.startsWith(e.value))r=this._getOrReturnCtx(t,r),$(r,{code:R.invalid_string,validation:{startsWith:e.value},message:e.message}),s.dirty()}else if(e.kind==="endsWith"){if(!t.data.endsWith(e.value))r=this._getOrReturnCtx(t,r),$(r,{code:R.invalid_string,validation:{endsWith:e.value},message:e.message}),s.dirty()}else if(e.kind==="datetime"){if(!uu(e).test(t.data))r=this._getOrReturnCtx(t,r),$(r,{code:R.invalid_string,validation:"datetime",message:e.message}),s.dirty()}else if(e.kind==="date"){if(!xg.test(t.data))r=this._getOrReturnCtx(t,r),$(r,{code:R.invalid_string,validation:"date",message:e.message}),s.dirty()}else if(e.kind==="time"){if(!Qg(e).test(t.data))r=this._getOrReturnCtx(t,r),$(r,{code:R.invalid_string,validation:"time",message:e.message}),s.dirty()}else if(e.kind==="duration"){if(!Bg.test(t.data))r=this._getOrReturnCtx(t,r),$(r,{validation:"duration",code:R.invalid_string,message:e.message}),s.dirty()}else if(e.kind==="ip"){if(!Jg(t.data,e.version))r=this._getOrReturnCtx(t,r),$(r,{validation:"ip",code:R.invalid_string,message:e.message}),s.dirty()}else if(e.kind==="jwt"){if(!zg(t.data,e.alg))r=this._getOrReturnCtx(t,r),$(r,{validation:"jwt",code:R.invalid_string,message:e.message}),s.dirty()}else if(e.kind==="cidr"){if(!kg(t.data,e.version))r=this._getOrReturnCtx(t,r),$(r,{validation:"cidr",code:R.invalid_string,message:e.message}),s.dirty()}else if(e.kind==="base64"){if(!Wg.test(t.data))r=this._getOrReturnCtx(t,r),$(r,{validation:"base64",code:R.invalid_string,message:e.message}),s.dirty()}else if(e.kind==="base64url"){if(!Yg.test(t.data))r=this._getOrReturnCtx(t,r),$(r,{validation:"base64url",code:R.invalid_string,message:e.message}),s.dirty()}else J.assertNever(e);return{status:s.value,value:t.data}}_regex(t,n,s){return this.refinement((r)=>t.test(r),{validation:n,code:R.invalid_string,...y.errToObj(s)})}_addCheck(t){return new Wt({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...y.errToObj(t)})}url(t){return this._addCheck({kind:"url",...y.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...y.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...y.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...y.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...y.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...y.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...y.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...y.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...y.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...y.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...y.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...y.errToObj(t)})}datetime(t){if(typeof t==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t});return this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...y.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){if(typeof t==="string")return this._addCheck({kind:"time",precision:null,message:t});return this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...y.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...y.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...y.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...y.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...y.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...y.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...y.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...y.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...y.errToObj(n)})}nonempty(t){return this.min(1,y.errToObj(t))}trim(){return new Wt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Wt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Wt({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((t)=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find((t)=>t.kind==="date")}get isTime(){return!!this._def.checks.find((t)=>t.kind==="time")}get isDuration(){return!!this._def.checks.find((t)=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find((t)=>t.kind==="email")}get isURL(){return!!this._def.checks.find((t)=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find((t)=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find((t)=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((t)=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((t)=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((t)=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find((t)=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find((t)=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find((t)=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find((t)=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find((t)=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)if(n.kind==="min"){if(t===null||n.value>t)t=n.value}return t}get maxLength(){let t=null;for(let n of this._def.checks)if(n.kind==="max"){if(t===null||n.value<t)t=n.value}return t}}Wt.create=(t)=>{return new Wt({checks:[],typeName:P.ZodString,coerce:t?.coerce??!1,...D(t)})};function Xg(t,n){let s=(t.toString().split(".")[1]||"").length,r=(n.toString().split(".")[1]||"").length,e=s>r?s:r,i=Number.parseInt(t.toFixed(e).replace(".","")),f=Number.parseInt(n.toFixed(e).replace(".",""));return i%f/10**e}class yn extends W{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce)t.data=Number(t.data);if(this._getType(t)!==T.number){let e=this._getOrReturnCtx(t);return $(e,{code:R.invalid_type,expected:T.number,received:e.parsedType}),F}let s=void 0,r=new ht;for(let e of this._def.checks)if(e.kind==="int"){if(!J.isInteger(t.data))s=this._getOrReturnCtx(t,s),$(s,{code:R.invalid_type,expected:"integer",received:"float",message:e.message}),r.dirty()}else if(e.kind==="min"){if(e.inclusive?t.data<e.value:t.data<=e.value)s=this._getOrReturnCtx(t,s),$(s,{code:R.too_small,minimum:e.value,type:"number",inclusive:e.inclusive,exact:!1,message:e.message}),r.dirty()}else if(e.kind==="max"){if(e.inclusive?t.data>e.value:t.data>=e.value)s=this._getOrReturnCtx(t,s),$(s,{code:R.too_big,maximum:e.value,type:"number",inclusive:e.inclusive,exact:!1,message:e.message}),r.dirty()}else if(e.kind==="multipleOf"){if(Xg(t.data,e.value)!==0)s=this._getOrReturnCtx(t,s),$(s,{code:R.not_multiple_of,multipleOf:e.value,message:e.message}),r.dirty()}else if(e.kind==="finite"){if(!Number.isFinite(t.data))s=this._getOrReturnCtx(t,s),$(s,{code:R.not_finite,message:e.message}),r.dirty()}else J.assertNever(e);return{status:r.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,y.toString(n))}gt(t,n){return this.setLimit("min",t,!1,y.toString(n))}lte(t,n){return this.setLimit("max",t,!0,y.toString(n))}lt(t,n){return this.setLimit("max",t,!1,y.toString(n))}setLimit(t,n,s,r){return new yn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:s,message:y.toString(r)}]})}_addCheck(t){return new yn({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:y.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:y.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:y.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:y.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:y.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:y.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:y.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:y.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:y.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)if(n.kind==="min"){if(t===null||n.value>t)t=n.value}return t}get maxValue(){let t=null;for(let n of this._def.checks)if(n.kind==="max"){if(t===null||n.value<t)t=n.value}return t}get isInt(){return!!this._def.checks.find((t)=>t.kind==="int"||t.kind==="multipleOf"&&J.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let s of this._def.checks)if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;else if(s.kind==="min"){if(n===null||s.value>n)n=s.value}else if(s.kind==="max"){if(t===null||s.value<t)t=s.value}return Number.isFinite(n)&&Number.isFinite(t)}}yn.create=(t)=>{return new yn({checks:[],typeName:P.ZodNumber,coerce:t?.coerce||!1,...D(t)})};class Gn extends W{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==T.bigint)return this._getInvalidInput(t);let s=void 0,r=new ht;for(let e of this._def.checks)if(e.kind==="min"){if(e.inclusive?t.data<e.value:t.data<=e.value)s=this._getOrReturnCtx(t,s),$(s,{code:R.too_small,type:"bigint",minimum:e.value,inclusive:e.inclusive,message:e.message}),r.dirty()}else if(e.kind==="max"){if(e.inclusive?t.data>e.value:t.data>=e.value)s=this._getOrReturnCtx(t,s),$(s,{code:R.too_big,type:"bigint",maximum:e.value,inclusive:e.inclusive,message:e.message}),r.dirty()}else if(e.kind==="multipleOf"){if(t.data%e.value!==BigInt(0))s=this._getOrReturnCtx(t,s),$(s,{code:R.not_multiple_of,multipleOf:e.value,message:e.message}),r.dirty()}else J.assertNever(e);return{status:r.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return $(n,{code:R.invalid_type,expected:T.bigint,received:n.parsedType}),F}gte(t,n){return this.setLimit("min",t,!0,y.toString(n))}gt(t,n){return this.setLimit("min",t,!1,y.toString(n))}lte(t,n){return this.setLimit("max",t,!0,y.toString(n))}lt(t,n){return this.setLimit("max",t,!1,y.toString(n))}setLimit(t,n,s,r){return new Gn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:s,message:y.toString(r)}]})}_addCheck(t){return new Gn({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:y.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:y.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:y.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:y.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:y.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)if(n.kind==="min"){if(t===null||n.value>t)t=n.value}return t}get maxValue(){let t=null;for(let n of this._def.checks)if(n.kind==="max"){if(t===null||n.value<t)t=n.value}return t}}Gn.create=(t)=>{return new Gn({checks:[],typeName:P.ZodBigInt,coerce:t?.coerce??!1,...D(t)})};class Ls extends W{_parse(t){if(this._def.coerce)t.data=Boolean(t.data);if(this._getType(t)!==T.boolean){let s=this._getOrReturnCtx(t);return $(s,{code:R.invalid_type,expected:T.boolean,received:s.parsedType}),F}return wt(t.data)}}Ls.create=(t)=>{return new Ls({typeName:P.ZodBoolean,coerce:t?.coerce||!1,...D(t)})};class Vn extends W{_parse(t){if(this._def.coerce)t.data=new Date(t.data);if(this._getType(t)!==T.date){let e=this._getOrReturnCtx(t);return $(e,{code:R.invalid_type,expected:T.date,received:e.parsedType}),F}if(Number.isNaN(t.data.getTime())){let e=this._getOrReturnCtx(t);return $(e,{code:R.invalid_date}),F}let s=new ht,r=void 0;for(let e of this._def.checks)if(e.kind==="min"){if(t.data.getTime()<e.value)r=this._getOrReturnCtx(t,r),$(r,{code:R.too_small,message:e.message,inclusive:!0,exact:!1,minimum:e.value,type:"date"}),s.dirty()}else if(e.kind==="max"){if(t.data.getTime()>e.value)r=this._getOrReturnCtx(t,r),$(r,{code:R.too_big,message:e.message,inclusive:!0,exact:!1,maximum:e.value,type:"date"}),s.dirty()}else J.assertNever(e);return{status:s.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Vn({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:y.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:y.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)if(n.kind==="min"){if(t===null||n.value>t)t=n.value}return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)if(n.kind==="max"){if(t===null||n.value<t)t=n.value}return t!=null?new Date(t):null}}Vn.create=(t)=>{return new Vn({checks:[],coerce:t?.coerce||!1,typeName:P.ZodDate,...D(t)})};class Mr extends W{_parse(t){if(this._getType(t)!==T.symbol){let s=this._getOrReturnCtx(t);return $(s,{code:R.invalid_type,expected:T.symbol,received:s.parsedType}),F}return wt(t.data)}}Mr.create=(t)=>{return new Mr({typeName:P.ZodSymbol,...D(t)})};class Is extends W{_parse(t){if(this._getType(t)!==T.undefined){let s=this._getOrReturnCtx(t);return $(s,{code:R.invalid_type,expected:T.undefined,received:s.parsedType}),F}return wt(t.data)}}Is.create=(t)=>{return new Is({typeName:P.ZodUndefined,...D(t)})};class Os extends W{_parse(t){if(this._getType(t)!==T.null){let s=this._getOrReturnCtx(t);return $(s,{code:R.invalid_type,expected:T.null,received:s.parsedType}),F}return wt(t.data)}}Os.create=(t)=>{return new Os({typeName:P.ZodNull,...D(t)})};class jn extends W{constructor(){super(...arguments);this._any=!0}_parse(t){return wt(t.data)}}jn.create=(t)=>{return new jn({typeName:P.ZodAny,...D(t)})};class On extends W{constructor(){super(...arguments);this._unknown=!0}_parse(t){return wt(t.data)}}On.create=(t)=>{return new On({typeName:P.ZodUnknown,...D(t)})};class jt extends W{_parse(t){let n=this._getOrReturnCtx(t);return $(n,{code:R.invalid_type,expected:T.never,received:n.parsedType}),F}}jt.create=(t)=>{return new jt({typeName:P.ZodNever,...D(t)})};class dr extends W{_parse(t){if(this._getType(t)!==T.undefined){let s=this._getOrReturnCtx(t);return $(s,{code:R.invalid_type,expected:T.void,received:s.parsedType}),F}return wt(t.data)}}dr.create=(t)=>{return new dr({typeName:P.ZodVoid,...D(t)})};class Yt extends W{_parse(t){let{ctx:n,status:s}=this._processInputParams(t),r=this._def;if(n.parsedType!==T.array)return $(n,{code:R.invalid_type,expected:T.array,received:n.parsedType}),F;if(r.exactLength!==null){let i=n.data.length>r.exactLength.value,f=n.data.length<r.exactLength.value;if(i||f)$(n,{code:i?R.too_big:R.too_small,minimum:f?r.exactLength.value:void 0,maximum:i?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),s.dirty()}if(r.minLength!==null){if(n.data.length<r.minLength.value)$(n,{code:R.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),s.dirty()}if(r.maxLength!==null){if(n.data.length>r.maxLength.value)$(n,{code:R.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),s.dirty()}if(n.common.async)return Promise.all([...n.data].map((i,f)=>{return r.type._parseAsync(new Qt(n,i,n.path,f))})).then((i)=>{return ht.mergeArray(s,i)});let e=[...n.data].map((i,f)=>{return r.type._parseSync(new Qt(n,i,n.path,f))});return ht.mergeArray(s,e)}get element(){return this._def.type}min(t,n){return new Yt({...this._def,minLength:{value:t,message:y.toString(n)}})}max(t,n){return new Yt({...this._def,maxLength:{value:t,message:y.toString(n)}})}length(t,n){return new Yt({...this._def,exactLength:{value:t,message:y.toString(n)}})}nonempty(t){return this.min(1,t)}}Yt.create=(t,n)=>{return new Yt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:P.ZodArray,...D(n)})};function $s(t){if(t instanceof p){let n={};for(let s in t.shape){let r=t.shape[s];n[s]=xt.create($s(r))}return new p({...t._def,shape:()=>n})}else if(t instanceof Yt)return new Yt({...t._def,type:$s(t.element)});else if(t instanceof xt)return xt.create($s(t.unwrap()));else if(t instanceof Mn)return Mn.create($s(t.unwrap()));else if(t instanceof pt)return pt.create(t.items.map((n)=>$s(n)));else return t}class p extends W{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=J.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==T.object){let c=this._getOrReturnCtx(t);return $(c,{code:R.invalid_type,expected:T.object,received:c.parsedType}),F}let{status:s,ctx:r}=this._processInputParams(t),{shape:e,keys:i}=this._getCached(),f=[];if(!(this._def.catchall instanceof jt&&this._def.unknownKeys==="strip")){for(let c in r.data)if(!i.includes(c))f.push(c)}let o=[];for(let c of i){let h=e[c],u=r.data[c];o.push({key:{status:"valid",value:c},value:h._parse(new Qt(r,u,r.path,c)),alwaysSet:c in r.data})}if(this._def.catchall instanceof jt){let c=this._def.unknownKeys;if(c==="passthrough")for(let h of f)o.push({key:{status:"valid",value:h},value:{status:"valid",value:r.data[h]}});else if(c==="strict"){if(f.length>0)$(r,{code:R.unrecognized_keys,keys:f}),s.dirty()}else if(c==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let h of f){let u=r.data[h];o.push({key:{status:"valid",value:h},value:c._parse(new Qt(r,u,r.path,h)),alwaysSet:h in r.data})}}if(r.common.async)return Promise.resolve().then(async()=>{let c=[];for(let h of o){let u=await h.key,l=await h.value;c.push({key:u,value:l,alwaysSet:h.alwaysSet})}return c}).then((c)=>{return ht.mergeObjectSync(s,c)});else return ht.mergeObjectSync(s,o)}get shape(){return this._def.shape()}strict(t){return y.errToObj,new p({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,s)=>{let r=this._def.errorMap?.(n,s).message??s.defaultError;if(n.code==="unrecognized_keys")return{message:y.errToObj(t).message??r};return{message:r}}}:{}})}strip(){return new p({...this._def,unknownKeys:"strip"})}passthrough(){return new p({...this._def,unknownKeys:"passthrough"})}extend(t){return new p({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new p({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:P.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new p({...this._def,catchall:t})}pick(t){let n={};for(let s of J.objectKeys(t))if(t[s]&&this.shape[s])n[s]=this.shape[s];return new p({...this._def,shape:()=>n})}omit(t){let n={};for(let s of J.objectKeys(this.shape))if(!t[s])n[s]=this.shape[s];return new p({...this._def,shape:()=>n})}deepPartial(){return $s(this)}partial(t){let n={};for(let s of J.objectKeys(this.shape)){let r=this.shape[s];if(t&&!t[s])n[s]=r;else n[s]=r.optional()}return new p({...this._def,shape:()=>n})}required(t){let n={};for(let s of J.objectKeys(this.shape))if(t&&!t[s])n[s]=this.shape[s];else{let e=this.shape[s];while(e instanceof xt)e=e._def.innerType;n[s]=e}return new p({...this._def,shape:()=>n})}keyof(){return lu(J.objectKeys(this.shape))}}p.create=(t,n)=>{return new p({shape:()=>t,unknownKeys:"strip",catchall:jt.create(),typeName:P.ZodObject,...D(n)})};p.strictCreate=(t,n)=>{return new p({shape:()=>t,unknownKeys:"strict",catchall:jt.create(),typeName:P.ZodObject,...D(n)})};p.lazycreate=(t,n)=>{return new p({shape:t,unknownKeys:"strip",catchall:jt.create(),typeName:P.ZodObject,...D(n)})};class ys extends W{_parse(t){let{ctx:n}=this._processInputParams(t),s=this._def.options;function r(e){for(let f of e)if(f.result.status==="valid")return f.result;for(let f of e)if(f.result.status==="dirty")return n.common.issues.push(...f.ctx.common.issues),f.result;let i=e.map((f)=>new gt(f.ctx.common.issues));return $(n,{code:R.invalid_union,unionErrors:i}),F}if(n.common.async)return Promise.all(s.map(async(e)=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await e._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(r);else{let e=void 0,i=[];for(let o of s){let c={...n,common:{...n.common,issues:[]},parent:null},h=o._parseSync({data:n.data,path:n.path,parent:c});if(h.status==="valid")return h;else if(h.status==="dirty"&&!e)e={result:h,ctx:c};if(c.common.issues.length)i.push(c.common.issues)}if(e)return n.common.issues.push(...e.ctx.common.issues),e.result;let f=i.map((o)=>new gt(o));return $(n,{code:R.invalid_union,unionErrors:f}),F}}get options(){return this._def.options}}ys.create=(t,n)=>{return new ys({options:t,typeName:P.ZodUnion,...D(n)})};var An=(t)=>{if(t instanceof Bs)return An(t.schema);else if(t instanceof Jt)return An(t.innerType());else if(t instanceof ms)return[t.value];else if(t instanceof Bn)return t.options;else if(t instanceof Fs)return J.objectValues(t.enum);else if(t instanceof Ps)return An(t._def.innerType);else if(t instanceof Is)return[void 0];else if(t instanceof Os)return[null];else if(t instanceof xt)return[void 0,...An(t.unwrap())];else if(t instanceof Mn)return[null,...An(t.unwrap())];else if(t instanceof Te)return An(t.unwrap());else if(t instanceof Ns)return An(t.unwrap());else if(t instanceof Hs)return An(t._def.innerType);else return[]};class be extends W{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==T.object)return $(n,{code:R.invalid_type,expected:T.object,received:n.parsedType}),F;let s=this.discriminator,r=n.data[s],e=this.optionsMap.get(r);if(!e)return $(n,{code:R.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),F;if(n.common.async)return e._parseAsync({data:n.data,path:n.path,parent:n});else return e._parseSync({data:n.data,path:n.path,parent:n})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,s){let r=new Map;for(let e of n){let i=An(e.shape[t]);if(!i.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let f of i){if(r.has(f))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(f)}`);r.set(f,e)}}return new be({typeName:P.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:r,...D(s)})}}function No(t,n){let s=Vt(t),r=Vt(n);if(t===n)return{valid:!0,data:t};else if(s===T.object&&r===T.object){let e=J.objectKeys(n),i=J.objectKeys(t).filter((o)=>e.indexOf(o)!==-1),f={...t,...n};for(let o of i){let c=No(t[o],n[o]);if(!c.valid)return{valid:!1};f[o]=c.data}return{valid:!0,data:f}}else if(s===T.array&&r===T.array){if(t.length!==n.length)return{valid:!1};let e=[];for(let i=0;i<t.length;i++){let f=t[i],o=n[i],c=No(f,o);if(!c.valid)return{valid:!1};e.push(c.data)}return{valid:!0,data:e}}else if(s===T.date&&r===T.date&&+t===+n)return{valid:!0,data:t};else return{valid:!1}}class Gs extends W{_parse(t){let{status:n,ctx:s}=this._processInputParams(t),r=(e,i)=>{if(Ee(e)||Ee(i))return F;let f=No(e.value,i.value);if(!f.valid)return $(s,{code:R.invalid_intersection_types}),F;if(Re(e)||Re(i))n.dirty();return{status:n.value,value:f.data}};if(s.common.async)return Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([e,i])=>r(e,i));else return r(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}Gs.create=(t,n,s)=>{return new Gs({left:t,right:n,typeName:P.ZodIntersection,...D(s)})};class pt extends W{_parse(t){let{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==T.array)return $(s,{code:R.invalid_type,expected:T.array,received:s.parsedType}),F;if(s.data.length<this._def.items.length)return $(s,{code:R.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),F;if(!this._def.rest&&s.data.length>this._def.items.length)$(s,{code:R.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty();let e=[...s.data].map((i,f)=>{let o=this._def.items[f]||this._def.rest;if(!o)return null;return o._parse(new Qt(s,i,s.path,f))}).filter((i)=>!!i);if(s.common.async)return Promise.all(e).then((i)=>{return ht.mergeArray(n,i)});else return ht.mergeArray(n,e)}get items(){return this._def.items}rest(t){return new pt({...this._def,rest:t})}}pt.create=(t,n)=>{if(!Array.isArray(t))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new pt({items:t,typeName:P.ZodTuple,rest:null,...D(n)})};class gr extends W{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==T.object)return $(s,{code:R.invalid_type,expected:T.object,received:s.parsedType}),F;let r=[],e=this._def.keyType,i=this._def.valueType;for(let f in s.data)r.push({key:e._parse(new Qt(s,f,s.path,f)),value:i._parse(new Qt(s,s.data[f],s.path,f)),alwaysSet:f in s.data});if(s.common.async)return ht.mergeObjectAsync(n,r);else return ht.mergeObjectSync(n,r)}get element(){return this._def.valueType}static create(t,n,s){if(n instanceof W)return new gr({keyType:t,valueType:n,typeName:P.ZodRecord,...D(s)});return new gr({keyType:Wt.create(),valueType:t,typeName:P.ZodRecord,...D(n)})}}class Er extends W{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==T.map)return $(s,{code:R.invalid_type,expected:T.map,received:s.parsedType}),F;let r=this._def.keyType,e=this._def.valueType,i=[...s.data.entries()].map(([f,o],c)=>{return{key:r._parse(new Qt(s,f,s.path,[c,"key"])),value:e._parse(new Qt(s,o,s.path,[c,"value"]))}});if(s.common.async){let f=new Map;return Promise.resolve().then(async()=>{for(let o of i){let c=await o.key,h=await o.value;if(c.status==="aborted"||h.status==="aborted")return F;if(c.status==="dirty"||h.status==="dirty")n.dirty();f.set(c.value,h.value)}return{status:n.value,value:f}})}else{let f=new Map;for(let o of i){let{key:c,value:h}=o;if(c.status==="aborted"||h.status==="aborted")return F;if(c.status==="dirty"||h.status==="dirty")n.dirty();f.set(c.value,h.value)}return{status:n.value,value:f}}}}Er.create=(t,n,s)=>{return new Er({valueType:n,keyType:t,typeName:P.ZodMap,...D(s)})};class pn extends W{_parse(t){let{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==T.set)return $(s,{code:R.invalid_type,expected:T.set,received:s.parsedType}),F;let r=this._def;if(r.minSize!==null){if(s.data.size<r.minSize.value)$(s,{code:R.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),n.dirty()}if(r.maxSize!==null){if(s.data.size>r.maxSize.value)$(s,{code:R.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),n.dirty()}let e=this._def.valueType;function i(o){let c=new Set;for(let h of o){if(h.status==="aborted")return F;if(h.status==="dirty")n.dirty();c.add(h.value)}return{status:n.value,value:c}}let f=[...s.data.values()].map((o,c)=>e._parse(new Qt(s,o,s.path,c)));if(s.common.async)return Promise.all(f).then((o)=>i(o));else return i(f)}min(t,n){return new pn({...this._def,minSize:{value:t,message:y.toString(n)}})}max(t,n){return new pn({...this._def,maxSize:{value:t,message:y.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}pn.create=(t,n)=>{return new pn({valueType:t,minSize:null,maxSize:null,typeName:P.ZodSet,...D(n)})};class Us extends W{constructor(){super(...arguments);this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==T.function)return $(n,{code:R.invalid_type,expected:T.function,received:n.parsedType}),F;function s(f,o){return Ar({data:f,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Ts(),wn].filter((c)=>!!c),issueData:{code:R.invalid_arguments,argumentsError:o}})}function r(f,o){return Ar({data:f,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Ts(),wn].filter((c)=>!!c),issueData:{code:R.invalid_return_type,returnTypeError:o}})}let e={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof vn){let f=this;return wt(async function(...o){let c=new gt([]),h=await f._def.args.parseAsync(o,e).catch((_)=>{throw c.addIssue(s(o,_)),c}),u=await Reflect.apply(i,this,h);return await f._def.returns._def.type.parseAsync(u,e).catch((_)=>{throw c.addIssue(r(u,_)),c})})}else{let f=this;return wt(function(...o){let c=f._def.args.safeParse(o,e);if(!c.success)throw new gt([s(o,c.error)]);let h=Reflect.apply(i,this,c.data),u=f._def.returns.safeParse(h,e);if(!u.success)throw new gt([r(h,u.error)]);return u.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Us({...this._def,args:pt.create(t).rest(On.create())})}returns(t){return new Us({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,s){return new Us({args:t?t:pt.create([]).rest(On.create()),returns:n||On.create(),typeName:P.ZodFunction,...D(s)})}}class Bs extends W{get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Bs.create=(t,n)=>{return new Bs({getter:t,typeName:P.ZodLazy,...D(n)})};class ms extends W{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return $(n,{received:n.data,code:R.invalid_literal,expected:this._def.value}),F}return{status:"valid",value:t.data}}get value(){return this._def.value}}ms.create=(t,n)=>{return new ms({value:t,typeName:P.ZodLiteral,...D(n)})};function lu(t,n){return new Bn({values:t,typeName:P.ZodEnum,...D(n)})}class Bn extends W{_parse(t){if(typeof t.data!=="string"){let n=this._getOrReturnCtx(t),s=this._def.values;return $(n,{expected:J.joinValues(s),received:n.parsedType,code:R.invalid_type}),F}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),s=this._def.values;return $(n,{received:n.data,code:R.invalid_enum_value,options:s}),F}return wt(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return Bn.create(t,{...this._def,...n})}exclude(t,n=this._def){return Bn.create(this.options.filter((s)=>!t.includes(s)),{...this._def,...n})}}Bn.create=lu;class Fs extends W{_parse(t){let n=J.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(t);if(s.parsedType!==T.string&&s.parsedType!==T.number){let r=J.objectValues(n);return $(s,{expected:J.joinValues(r),received:s.parsedType,code:R.invalid_type}),F}if(!this._cache)this._cache=new Set(J.getValidEnumValues(this._def.values));if(!this._cache.has(t.data)){let r=J.objectValues(n);return $(s,{received:s.data,code:R.invalid_enum_value,options:r}),F}return wt(t.data)}get enum(){return this._def.values}}Fs.create=(t,n)=>{return new Fs({values:t,typeName:P.ZodNativeEnum,...D(n)})};class vn extends W{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==T.promise&&n.common.async===!1)return $(n,{code:R.invalid_type,expected:T.promise,received:n.parsedType}),F;let s=n.parsedType===T.promise?n.data:Promise.resolve(n.data);return wt(s.then((r)=>{return this._def.type.parseAsync(r,{path:n.path,errorMap:n.common.contextualErrorMap})}))}}vn.create=(t,n)=>{return new vn({type:t,typeName:P.ZodPromise,...D(n)})};class Jt extends W{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===P.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:s}=this._processInputParams(t),r=this._def.effect||null,e={addIssue:(i)=>{if($(s,i),i.fatal)n.abort();else n.dirty()},get path(){return s.path}};if(e.addIssue=e.addIssue.bind(e),r.type==="preprocess"){let i=r.transform(s.data,e);if(s.common.async)return Promise.resolve(i).then(async(f)=>{if(n.value==="aborted")return F;let o=await this._def.schema._parseAsync({data:f,path:s.path,parent:s});if(o.status==="aborted")return F;if(o.status==="dirty")return Kn(o.value);if(n.value==="dirty")return Kn(o.value);return o});else{if(n.value==="aborted")return F;let f=this._def.schema._parseSync({data:i,path:s.path,parent:s});if(f.status==="aborted")return F;if(f.status==="dirty")return Kn(f.value);if(n.value==="dirty")return Kn(f.value);return f}}if(r.type==="refinement"){let i=(f)=>{let o=r.refinement(f,e);if(s.common.async)return Promise.resolve(o);if(o instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return f};if(s.common.async===!1){let f=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(f.status==="aborted")return F;if(f.status==="dirty")n.dirty();return i(f.value),{status:n.value,value:f.value}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then((f)=>{if(f.status==="aborted")return F;if(f.status==="dirty")n.dirty();return i(f.value).then(()=>{return{status:n.value,value:f.value}})})}if(r.type==="transform")if(s.common.async===!1){let i=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!In(i))return F;let f=r.transform(i.value,e);if(f instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:f}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then((i)=>{if(!In(i))return F;return Promise.resolve(r.transform(i.value,e)).then((f)=>({status:n.value,value:f}))});J.assertNever(r)}}Jt.create=(t,n,s)=>{return new Jt({schema:t,typeName:P.ZodEffects,effect:n,...D(s)})};Jt.createWithPreprocess=(t,n,s)=>{return new Jt({schema:n,effect:{type:"preprocess",transform:t},typeName:P.ZodEffects,...D(s)})};class xt extends W{_parse(t){if(this._getType(t)===T.undefined)return wt(void 0);return this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}xt.create=(t,n)=>{return new xt({innerType:t,typeName:P.ZodOptional,...D(n)})};class Mn extends W{_parse(t){if(this._getType(t)===T.null)return wt(null);return this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Mn.create=(t,n)=>{return new Mn({innerType:t,typeName:P.ZodNullable,...D(n)})};class Ps extends W{_parse(t){let{ctx:n}=this._processInputParams(t),s=n.data;if(n.parsedType===T.undefined)s=this._def.defaultValue();return this._def.innerType._parse({data:s,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Ps.create=(t,n)=>{return new Ps({innerType:t,typeName:P.ZodDefault,defaultValue:typeof n.default==="function"?n.default:()=>n.default,...D(n)})};class Hs extends W{_parse(t){let{ctx:n}=this._processInputParams(t),s={...n,common:{...n.common,issues:[]}},r=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});if(Ss(r))return r.then((e)=>{return{status:"valid",value:e.status==="valid"?e.value:this._def.catchValue({get error(){return new gt(s.common.issues)},input:s.data})}});else return{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new gt(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}Hs.create=(t,n)=>{return new Hs({innerType:t,typeName:P.ZodCatch,catchValue:typeof n.catch==="function"?n.catch:()=>n.catch,...D(n)})};class Rr extends W{_parse(t){if(this._getType(t)!==T.nan){let s=this._getOrReturnCtx(t);return $(s,{code:R.invalid_type,expected:T.nan,received:s.parsedType}),F}return{status:"valid",value:t.data}}}Rr.create=(t)=>{return new Rr({typeName:P.ZodNaN,...D(t)})};var qg=Symbol("zod_brand");class Te extends W{_parse(t){let{ctx:n}=this._processInputParams(t),s=n.data;return this._def.type._parse({data:s,path:n.path,parent:n})}unwrap(){return this._def.type}}class br extends W{_parse(t){let{status:n,ctx:s}=this._processInputParams(t);if(s.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});if(e.status==="aborted")return F;if(e.status==="dirty")return n.dirty(),Kn(e.value);else return this._def.out._parseAsync({data:e.value,path:s.path,parent:s})})();else{let r=this._def.in._parseSync({data:s.data,path:s.path,parent:s});if(r.status==="aborted")return F;if(r.status==="dirty")return n.dirty(),{status:"dirty",value:r.value};else return this._def.out._parseSync({data:r.value,path:s.path,parent:s})}}static create(t,n){return new br({in:t,out:n,typeName:P.ZodPipeline})}}class Ns extends W{_parse(t){let n=this._def.innerType._parse(t),s=(r)=>{if(In(r))r.value=Object.freeze(r.value);return r};return Ss(n)?n.then((r)=>s(r)):s(n)}unwrap(){return this._def.innerType}}Ns.create=(t,n)=>{return new Ns({innerType:t,typeName:P.ZodReadonly,...D(n)})};function fu(t,n){let s=typeof t==="function"?t(n):typeof t==="string"?{message:t}:t;return typeof s==="string"?{message:s}:s}function _u(t,n={},s){if(t)return jn.create().superRefine((r,e)=>{let i=t(r);if(i instanceof Promise)return i.then((f)=>{if(!f){let o=fu(n,r),c=o.fatal??s??!0;e.addIssue({code:"custom",...o,fatal:c})}});if(!i){let f=fu(n,r),o=f.fatal??s??!0;e.addIssue({code:"custom",...f,fatal:o})}return});return jn.create()}var Cg={object:p.lazycreate},P;(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"})(P||(P={}));var ag=(t,n={message:`Input not instance of ${t.name}`})=>_u((s)=>s instanceof t,n),wu=Wt.create,Au=yn.create,Kg=Rr.create,Vg=Gn.create,Mu=Ls.create,jg=Vn.create,pg=Mr.create,vg=Is.create,Zg=Os.create,tE=jn.create,nE=On.create,sE=jt.create,rE=dr.create,eE=Yt.create,iE=p.create,oE=p.strictCreate,fE=ys.create,cE=be.create,hE=Gs.create,uE=pt.create,lE=gr.create,_E=Er.create,wE=pn.create,AE=Us.create,ME=Bs.create,dE=ms.create,gE=Bn.create,EE=Fs.create,RE=vn.create,bE=Jt.create,TE=xt.create,SE=Mn.create,$E=Jt.createWithPreprocess,UE=br.create,LE=()=>wu().optional(),IE=()=>Au().optional(),OE=()=>Mu().optional(),yE={string:(t)=>Wt.create({...t,coerce:!0}),number:(t)=>yn.create({...t,coerce:!0}),boolean:(t)=>Ls.create({...t,coerce:!0}),bigint:(t)=>Gn.create({...t,coerce:!0}),date:(t)=>Vn.create({...t,coerce:!0})};var GE=F;var Se=g.enum(["low","medium","high","xhigh","max"]),Zn=g.enum(["us-east-1","us-east-2","us-west-1","us-west-2","af-south-1","ap-east-1","ap-south-2","ap-southeast-3","ap-southeast-5","ap-southeast-4","ap-south-1","ap-southeast-6","ap-northeast-3","ap-northeast-2","ap-southeast-1","ap-southeast-2","ap-east-2","ap-southeast-7","ap-northeast-1","ca-central-1","ca-west-1","eu-central-1","eu-west-1","eu-west-2","eu-south-1","eu-west-3","eu-south-2","eu-north-1","eu-central-2","il-central-1","mx-central-1","me-south-1","me-central-1","sa-east-1"]);var BE=g.array(g.string()).transform((t)=>t.map((n)=>n.trim()).filter((n)=>n.length>0)).refine((t)=>t.length>0,{message:"api_keys must contain at least one non-empty key"}),mE=g.preprocess((t)=>typeof t==="string"&&t.trim().length===0?null:t,g.string().trim().refine((t)=>URL.canParse(t),{message:"proxy_url must be a valid URL"}).refine((t)=>{if(!URL.canParse(t))return!1;let n=new URL(t).protocol;return n==="http:"||n==="https:"},{message:"proxy_url must be http(s)"}).nullable()).default(null),Do=g.object({host:g.string().default("127.0.0.1"),port:g.number().default(8787),api_keys:BE,proxy_url:mE,default_region:g.string().default("us-east-1"),account_selection_strategy:g.enum(["sticky","round-robin","lowest-usage"]).default("lowest-usage"),rate_limit_max_retries:g.number().default(3),rate_limit_retry_delay_ms:g.number().default(5000),max_request_iterations:g.number().default(20),request_timeout_ms:g.number().default(120000),stream_idle_timeout_ms:g.number().default(60000),max_request_body_bytes:g.number().default(10485760),token_expiry_buffer_ms:g.number().default(300000),effort:Se.nullable().default(null),auto_effort_mapping:g.boolean().default(!0),log_level:g.string().default("info"),test_upstream_endpoint:g.string().url().optional()});class Tr extends Error{constructor(t,n){super(t,n);this.name="ConfigLoadError"}}var NE=Do.partial();function DE(t){let n=t.XDG_CONFIG_HOME??du(HE(),".config");return du(n,"kiro-provider","config.json")}function WE(t){if(!FE(t))return{};try{let n=JSON.parse(PE(t,"utf8"));return NE.parse(n)}catch(n){if(n instanceof g.ZodError)throw new Tr(`Invalid configuration file ${t}: ${gu(n)}`,{cause:n});if(n instanceof Error)throw new Tr(`Unable to read configuration file ${t}: ${n.message}`,{cause:n});throw n}}function YE(t){let n=t.trim().toLowerCase();if(n==="true"||n==="1")return!0;if(n==="false"||n==="0")return!1;return t}function xE(t){let n={},s={KIRO_PROVIDER_HOST:"host",KIRO_PROVIDER_DEFAULT_REGION:"default_region",KIRO_PROVIDER_ACCOUNT_SELECTION_STRATEGY:"account_selection_strategy",KIRO_PROVIDER_EFFORT:"effort",KIRO_PROVIDER_LOG_LEVEL:"log_level",KIRO_PROVIDER_TEST_UPSTREAM:"test_upstream_endpoint"};for(let[o,c]of Object.entries(s)){let h=t[o];if(h!==void 0)n[c]=h}let r={KIRO_PROVIDER_PORT:"port",KIRO_PROVIDER_RATE_LIMIT_MAX_RETRIES:"rate_limit_max_retries",KIRO_PROVIDER_RATE_LIMIT_RETRY_DELAY_MS:"rate_limit_retry_delay_ms",KIRO_PROVIDER_MAX_REQUEST_ITERATIONS:"max_request_iterations",KIRO_PROVIDER_REQUEST_TIMEOUT_MS:"request_timeout_ms",KIRO_PROVIDER_STREAM_IDLE_TIMEOUT_MS:"stream_idle_timeout_ms",KIRO_PROVIDER_MAX_REQUEST_BODY_BYTES:"max_request_body_bytes",KIRO_PROVIDER_TOKEN_EXPIRY_BUFFER_MS:"token_expiry_buffer_ms"};for(let[o,c]of Object.entries(r)){let h=t[o];if(h!==void 0)n[c]=Number(h)}let e=t.KIRO_PROVIDER_API_KEYS;if(e!==void 0)n.api_keys=e.split(",");let i=t.KIRO_PROVIDER_PROXY_URL;if(i!==void 0)n.proxy_url=i.trim();let f=t.KIRO_PROVIDER_AUTO_EFFORT_MAPPING;if(f!==void 0)n.auto_effort_mapping=YE(f);return n}function gu(t){return t.issues.map((n)=>`${n.path.length>0?n.path.join("."):"config"}: ${n.message}`).join(", ")}function Eu(t={}){let n=t.env??process.env,s=t.configPath??DE(n);try{return Do.parse({...WE(s),...xE(n),...t.overrides})}catch(r){if(r instanceof Tr)throw r;if(r instanceof g.ZodError)throw new Tr(`Invalid configuration: ${gu(r)}`,{cause:r});throw r}}function $e(t){let n=t.split("|"),s=n[0]??"";if(n.length<2)return{refreshToken:s,authMethod:"desktop"};if(n.at(-1)==="idc")return{refreshToken:s,clientId:n[1],clientSecret:n[2],authMethod:"idc"};return{refreshToken:s,authMethod:"desktop"}}function Ru(t,n=120000){if(!t.access||!t.expires)return!0;return Date.now()>=t.expires-n}function Ue(t){if(t.authMethod==="idc"){if(!t.clientId||!t.clientSecret)throw Error("Missing credentials");return`${t.refreshToken}|${t.clientId}|${t.clientSecret}|idc`}return`${t.refreshToken}|desktop`}function QE(t){if(!t)return!1;return t.includes("Invalid refresh token")||t.includes("Invalid grant provided")||t.includes("invalid_grant")||t.includes("ExpiredTokenException")||t.includes("InvalidTokenException")||t.includes("ExpiredClientException")||t.includes("Client is expired")||t.includes("HTTP_401")||t.includes("HTTP_403")}function Le(t){if(!t)return!1;let n=t.toLowerCase();return n.includes("bearer token included in the request is invalid")||n.includes("access token has expired")||n.includes("access_token expired")||n.includes("the access token expired")}function Wo(t){return QE(t)}var bu=4;class Tu extends Error{accountId;constructor(t){super(`Account ${t} changed too frequently to update`);this.accountId=t;this.name="AccountConcurrentUpdateError"}}function JE(t){throw TypeError(`Unsupported account selection strategy: ${String(t)}`)}function Sr(t){return{...t}}function zE(t){return{refresh:Ue({refreshToken:t.refreshToken,authMethod:t.authMethod,...t.clientId?{clientId:t.clientId}:{},...t.clientSecret?{clientSecret:t.clientSecret}:{},...t.profileArn?{profileArn:t.profileArn}:{}}),access:t.accessToken,expires:t.expiresAt,authMethod:t.authMethod,region:t.region,...t.oidcRegion?{oidcRegion:t.oidcRegion}:{},...t.clientId?{clientId:t.clientId}:{},...t.clientSecret?{clientSecret:t.clientSecret}:{},...t.email?{email:t.email}:{},...t.profileArn?{profileArn:t.profileArn}:{}}}class Yo{strategy;database;accounts;stickyId;roundRobinCursor=0;constructor(t,n,s){this.strategy=n;this.database=s;this.accounts=t.map(Sr)}getAccountCount(){return this.accounts.length}getAccounts(){return this.accounts.map(Sr)}getMinWaitTime(){let t=Date.now(),n=this.accounts.map(({rateLimitResetTime:s})=>s-t).filter((s)=>s>0);return n.length===0?0:Math.min(...n)}reconcileFromDb(t=this.database){let n=new Map(this.accounts.map((s)=>[s.id,s]));if(this.accounts=t.getAccounts().map((s)=>{let r=n.get(s.id);return r?.generation===s.generation?r:Sr(s)}),this.stickyId&&!this.accounts.some(({id:s})=>s===this.stickyId))this.stickyId=void 0;return this.getAccounts()}selectHealthyAccount(){let t=Date.now(),n=this.accounts.filter((r)=>this.isSelectable(r,t)).sort((r,e)=>r.id.localeCompare(e.id));if(n.length===0)return null;let s=this.selectCandidate(n);return this.patchAccount(s.id,(r)=>({...r,isHealthy:!0,unhealthyReason:void 0,recoveryTime:void 0,lastUsed:t,usedCount:(r.usedCount??0)+1}))??null}getCurrentOrNext(){return this.selectHealthyAccount()}markRateLimited(t,n){return this.patchAccount(t.id,(s)=>({...s,rateLimitResetTime:n}))}markUnhealthy(t,n,s){let r=Date.now();return this.patchAccount(t.id,(e)=>{if(Wo(n))return{...e,failCount:10,isHealthy:!1,unhealthyReason:n,recoveryTime:void 0,lastUsed:r};let i=e.failCount+1;return{...e,failCount:i,isHealthy:i<10,unhealthyReason:n,recoveryTime:i>=10?s??r+3600000:void 0,lastUsed:r}})}updateFromAuth(t,n){let s=$e(n.refresh);for(let r=0;r<bu;r+=1){let e=r===0?t:this.database.getById(t.id);if(!e||!this.isSameLogin(t,e)){this.reconcileFromDb();return}let i={...e,refreshToken:s.refreshToken,accessToken:n.access,expiresAt:n.expires};if(this.database.updateExistingAccounts([i])===1){let f={...i,generation:e.generation+1};return this.replaceAccount(f),Sr(f)}}this.reconcileFromDb();return}toAuthDetails(t){return zE(t)}isSelectable(t,n){if(Wo(t.unhealthyReason))return!1;if(t.rateLimitResetTime>n)return!1;if(t.isHealthy||Le(t.unhealthyReason))return!0;return t.recoveryTime!==void 0&&t.recoveryTime<=n}isSameLogin(t,n){return n.refreshToken===t.refreshToken&&n.authMethod===t.authMethod&&n.clientId===t.clientId&&n.email===t.email&&n.startUrl===t.startUrl}selectCandidate(t){switch(this.strategy){case"sticky":{let s=t.find(({id:r})=>r===this.stickyId)??t[0];if(!s)throw RangeError("Candidate list cannot be empty");return this.stickyId=s.id,s}case"round-robin":{let n=t[this.roundRobinCursor%t.length];if(!n)throw RangeError("Candidate list cannot be empty");return this.roundRobinCursor+=1,n}case"lowest-usage":{let n=[...t].sort((s,r)=>(s.usedCount??0)-(r.usedCount??0)||(s.lastUsed??0)-(r.lastUsed??0)||s.id.localeCompare(r.id))[0];if(!n)throw RangeError("Candidate list cannot be empty");return n}default:return JE(this.strategy)}}patchAccount(t,n){for(let s=0;s<bu;s+=1){let r=this.database.getById(t);if(!r){this.accounts=this.accounts.filter((i)=>i.id!==t);return}let e=n(r);if(this.database.updateExistingAccounts([e])===1){let i={...e,generation:r.generation+1};return this.replaceAccount(i),Sr(i)}}throw this.reconcileFromDb(),new Tu(t)}replaceAccount(t){let n=this.accounts.findIndex(({id:s})=>s===t.id);if(n===-1)this.accounts.push(t);else this.accounts[n]=t}}var Du=H(Jo(),1);import*as Zt from"net";import*as Ur from"tls";import UR from"assert";import*as mu from"net";import*as Fu from"http";import{Agent as $R}from"https";var vt=Symbol("AgentBaseInternalState");class zo extends Fu.Agent{constructor(t){super(t);this[vt]={}}isSecureEndpoint(t){if(t){if(typeof t.secureEndpoint==="boolean")return t.secureEndpoint;if(typeof t.protocol==="string")return t.protocol==="https:"}let{stack:n}=Error();if(typeof n!=="string")return!1;return n.split(`
|
|
50
|
+
`).some((s)=>s.indexOf("(https.js:")!==-1||s.indexOf("node:https:")!==-1)}incrementSockets(t){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;if(!this.sockets[t])this.sockets[t]=[];let n=new mu.Socket({writable:!1});return this.sockets[t].push(n),this.totalSocketCount++,n}decrementSockets(t,n){if(!this.sockets[t]||n===null)return;let s=this.sockets[t],r=s.indexOf(n);if(r!==-1){if(s.splice(r,1),this.totalSocketCount--,s.length===0)delete this.sockets[t]}}getName(t){if(this.isSecureEndpoint(t))return $R.prototype.getName.call(this,t);return super.getName(t)}createSocket(t,n,s){let r={...n,secureEndpoint:this.isSecureEndpoint(n)},e=this.getName(r),i=this.incrementSockets(e);Promise.resolve().then(()=>this.connect(t,r)).then((f)=>{if(this.decrementSockets(e,i),typeof f.addRequest==="function")try{return f.addRequest(t,r)}catch(o){return s(o)}this[vt].currentSocket=f,super.createSocket(t,n,s)},(f)=>{this.decrementSockets(e,i),s(f)})}createConnection(){let t=this[vt].currentSocket;if(this[vt].currentSocket=void 0,!t)throw Error("No socket was returned in the `connect()` function");return t}get defaultPort(){return this[vt].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(t){if(this[vt])this[vt].defaultPort=t}get protocol(){return this[vt].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(t){if(this[vt])this[vt].protocol=t}}import{URL as LR}from"url";var Pu=H(Jo(),1),Be=Pu.default("https-proxy-agent:parse-proxy-response");function ko(t){return new Promise((n,s)=>{let r=0,e=[];function i(){let u=t.read();if(u)h(u);else t.once("readable",i)}function f(){t.removeListener("end",o),t.removeListener("error",c),t.removeListener("readable",i)}function o(){f(),Be("onend"),s(Error("Proxy connection ended before receiving CONNECT response"))}function c(u){f(),Be("onerror %o",u),s(u)}function h(u){e.push(u),r+=u.length;let l=Buffer.concat(e,r),_=l.indexOf(`\r
|
|
51
|
+
\r
|
|
52
|
+
`);if(_===-1){Be("have not received end of HTTP headers yet..."),i();return}let w=l.slice(0,_).toString("ascii").split(`\r
|
|
53
|
+
`),A=w.shift();if(!A)return t.destroy(),s(Error("No header received from proxy CONNECT response"));let M=A.split(" "),d=+M[1],E=M.slice(2).join(" "),b={};for(let L of w){if(!L)continue;let S=L.indexOf(":");if(S===-1)return t.destroy(),s(Error(`Invalid header from proxy CONNECT response: "${L}"`));let O=L.slice(0,S).toLowerCase(),x=L.slice(S+1).trimStart(),X=b[O];if(typeof X==="string")b[O]=[X,x];else if(Array.isArray(X))X.push(x);else b[O]=x}Be("got proxy server response: %o %o",A,b),f(),n({connect:{statusCode:d,statusText:E,headers:b},buffered:l})}t.on("error",c),t.on("end",o),i()})}function Hu(){return async({response:t,scheme:n})=>{if(n.toLowerCase()!=="negotiate")throw Error(`Expected Negotiate scheme but got "${n}"`);let s;try{s=await import("kerberos")}catch{throw Error('The "kerberos" package is required for Negotiate proxy authentication. Install it with: npm install kerberos')}let r=t.headers["proxy-authenticate"]||"",e=Array.isArray(r)?r[0]:r,i=typeof e==="string"&&e.includes(" ")?e.split(" ").slice(1).join(" "):void 0,o=await(await s.initializeClient("HTTP@proxy",{mechOID:s.GSS_MECH_OID_SPNEGO})).step(i||"");if(!o)throw Error("Kerberos client.step() returned no token");return{headers:{"Proxy-Authorization":`Negotiate ${o}`}}}}var ss=Du.default("https-proxy-agent"),me=(t)=>{if(t.servername===void 0&&t.host&&!Zt.isIP(t.host))return{...t,servername:t.host};return t};class Fe extends zo{constructor(t,n){super(n);if(this.options={path:void 0},this.proxy=typeof t==="string"?new LR(t):t,this.proxyHeaders=n?.headers??{},ss("Creating new HttpsProxyAgent instance: %o",this.proxy.href),n?.negotiate)this.onProxyAuth=Hu();else if(n?.onProxyAuth)this.onProxyAuth=n.onProxyAuth;let s=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),r=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...n?Xo(n,"headers","onProxyAuth","negotiate"):null,host:s,port:r}}async connect(t,n){let{proxy:s}=this;if(!n.host)throw TypeError('No "host" provided');let r;if(s.protocol==="https:")ss("Creating `tls.Socket`: %o",this.connectOpts),r=Ur.connect(me(this.connectOpts));else ss("Creating `net.Socket`: %o",this.connectOpts),r=Zt.connect(this.connectOpts);let e=typeof this.proxyHeaders==="function"?this.proxyHeaders():{...this.proxyHeaders},i=Zt.isIPv6(n.host)?`[${n.host}]`:n.host,f=`CONNECT ${i}:${n.port} HTTP/1.1\r
|
|
54
|
+
`;if(s.username||s.password){let l=`${decodeURIComponent(s.username)}:${decodeURIComponent(s.password)}`;e["Proxy-Authorization"]=`Basic ${Buffer.from(l).toString("base64")}`}if(e.Host=`${i}:${n.port}`,!e["Proxy-Connection"])e["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close";for(let l of Object.keys(e))f+=`${l}: ${e[l]}\r
|
|
55
|
+
`;let o=ko(r);r.write(`${f}\r
|
|
56
|
+
`);let{connect:c,buffered:h}=await o;if(t.emit("proxyConnect",c),this.emit("proxyConnect",c,t),t.emit("proxy",{proxy:this.proxy.href,socket:r}),c.statusCode===200){if(t.once("socket",Nu),n.secureEndpoint)return ss("Upgrading socket connection to TLS"),Ur.connect({...Xo(me(n),"host","path","port"),socket:r});return r}if(c.statusCode===407&&this.onProxyAuth){ss("Got 407 response, invoking onProxyAuth callback"),r.destroy();let l=c.headers["proxy-authenticate"]||"",_=Array.isArray(l)?l[0].split(/\s/)[0]:l.split(/\s/)[0],w=await this.onProxyAuth({response:c,scheme:_});return this._connectWithAuth(t,n,w.headers)}r.destroy();let u=new Zt.Socket({writable:!1});return u.readable=!0,t.once("socket",(l)=>{ss("Replaying proxy buffer for failed request"),UR(l.listenerCount("data")>0),l.push(h),l.push(null)}),u}async _connectWithAuth(t,n,s){let{proxy:r}=this,e;if(r.protocol==="https:")e=Ur.connect(me(this.connectOpts));else e=Zt.connect(this.connectOpts);let i=typeof this.proxyHeaders==="function"?this.proxyHeaders():{...this.proxyHeaders},f=Zt.isIPv6(n.host)?`[${n.host}]`:n.host,o=`CONNECT ${f}:${n.port} HTTP/1.1\r
|
|
57
|
+
`;if(r.username||r.password){let u=`${decodeURIComponent(r.username)}:${decodeURIComponent(r.password)}`;i["Proxy-Authorization"]=`Basic ${Buffer.from(u).toString("base64")}`}if(Object.assign(i,s),i.Host=`${f}:${n.port}`,!i["Proxy-Connection"])i["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close";for(let u of Object.keys(i))o+=`${u}: ${i[u]}\r
|
|
58
|
+
`;let c=ko(e);e.write(`${o}\r
|
|
59
|
+
`);let{connect:h}=await c;if(t.emit("proxyConnect",h),this.emit("proxyConnect",h,t),h.statusCode===200){if(t.once("socket",Nu),n.secureEndpoint)return ss("Upgrading socket connection to TLS"),Ur.connect({...Xo(me(n),"host","path","port"),socket:e});return e}throw e.destroy(),Error(`Proxy authentication failed with status ${h.statusCode} after retry`)}}Fe.protocols=["http","https"];function Nu(t){setImmediate(()=>{t.resume()})}function Xo(t,...n){let s={},r;for(r in t)if(!n.includes(r))s[r]=t[r];return s}var Wu=new Map;function xs(t){return t.proxy_url||void 0}function Yu(t){let n=Wu.get(t);if(n!==void 0)return n;let s=new Fe(t,{keepAlive:!0,maxSockets:50});return Wu.set(t,s),s}function xu(t){return t===void 0?{}:{proxy:t}}var IR=Zn.options;function Qu(t){return IR.includes(t)}function qo(t){if(!t||!Qu(t))return"us-east-1";return t}function Lr(t,n){let s=t.replace("{{region}}",n);try{return new URL(s),s}catch{throw Error(`Invalid URL generated: ${s}`)}}function Ju(t){if(!t)return;let n=t.split(":");if(n.length<6)return;if(n[0]!=="arn")return;let s=n[3];if(typeof s!=="string"||!s)return;return Qu(s)?s:void 0}var st={REFRESH_URL:"https://prod.{{region}}.auth.desktop.kiro.dev/refreshToken",REFRESH_IDC_URL:"https://oidc.{{region}}.amazonaws.com/token",BASE_URL:"https://q.{{region}}.amazonaws.com/generateAssistantResponse",USAGE_LIMITS_URL:"https://q.{{region}}.amazonaws.com/getUsageLimits",DEFAULT_REGION:"us-east-1",AXIOS_TIMEOUT:120000,USER_AGENT:"KiroIDE",SDK_VERSION:"3.738.0",SDK_VERSION_USAGE:"3.0.0",CHAT_TRIGGER_TYPE_MANUAL:"MANUAL",ORIGIN_AI_EDITOR:"AI_EDITOR"},Ir={"claude-haiku-4-5":"claude-haiku-4.5","claude-haiku-4-5-thinking":"claude-haiku-4.5","claude-sonnet-4":"claude-sonnet-4","claude-sonnet-4-5":"claude-sonnet-4.5","claude-sonnet-4-5-thinking":"claude-sonnet-4.5","claude-sonnet-4-5-1m":"claude-sonnet-4.5-1m","claude-sonnet-4-5-1m-thinking":"claude-sonnet-4.5-1m","claude-sonnet-4-6":"claude-sonnet-4.6","claude-sonnet-4-6-thinking":"claude-sonnet-4.6","claude-sonnet-4-6-1m":"claude-sonnet-4.6-1m","claude-sonnet-4-6-1m-thinking":"claude-sonnet-4.6-1m","claude-sonnet-5":"claude-sonnet-5","claude-sonnet-5-thinking":"claude-sonnet-5","claude-opus-4-5":"claude-opus-4.5","claude-opus-4-5-thinking":"claude-opus-4.5","claude-opus-4-6":"claude-opus-4.6","claude-opus-4-6-thinking":"claude-opus-4.6","claude-opus-4-6-1m":"claude-opus-4.6-1m","claude-opus-4-6-1m-thinking":"claude-opus-4.6-1m","claude-opus-4-7":"claude-opus-4.7","claude-opus-4-7-thinking":"claude-opus-4.7","claude-opus-4-8":"claude-opus-4.8","claude-opus-4-8-thinking":"claude-opus-4.8",auto:"auto","deepseek-3.2":"deepseek-3.2","glm-5":"glm-5","minimax-m2.5":"minimax-m2.5","minimax-m2.1":"minimax-m2.1","qwen3-coder-next":"qwen3-coder-next","gpt-5.6-sol":"gpt-5.6-sol","gpt-5.6-terra":"gpt-5.6-terra","gpt-5.6-luna":"gpt-5.6-luna","claude-3-7-sonnet":"CLAUDE_3_7_SONNET_20250219_V1_0","nova-swe":"AGI_NOVA_SWE_V1_5","gpt-oss-120b":"OPENAI_GPT_OSS_120B_1_0","minimax-m2":"MINIMAX_MINIMAX_M2","kimi-k2-thinking":"MOONSHOT_KIMI_K2_THINKING"},zu=Object.keys(Ir),V9=new Set(Object.keys(Ir).filter((t)=>t.includes("-1m")));var OR=200000,yR={auto:200000,"claude-haiku-4-5":200000,"claude-sonnet-4":200000,"claude-sonnet-4-5":200000,"claude-sonnet-4-5-1m":1e6,"claude-sonnet-4-6":1e6,"claude-sonnet-4-6-1m":1e6,"claude-sonnet-5":1e6,"claude-opus-4-5":200000,"claude-opus-4-6":1e6,"claude-opus-4-6-1m":1e6,"claude-opus-4-7":1e6,"claude-opus-4-8":1e6,"deepseek-3.2":128000,"glm-5":200000,"minimax-m2.5":200000,"minimax-m2.1":200000,"qwen3-coder-next":256000,"gpt-5.6-sol":272000,"gpt-5.6-terra":272000,"gpt-5.6-luna":272000};function G(t){return yR[t]??OR}var Or={ENDPOINT:"https://prod.{{region}}.auth.desktop.kiro.dev",SSO_OIDC_ENDPOINT:"https://oidc.{{region}}.amazonaws.com",BUILDER_ID_START_URL:"https://view.awsapps.com/start",USER_INFO_URL:"https://view.awsapps.com/api/user/info",SCOPES:["codewhisperer:completions","codewhisperer:analysis","codewhisperer:conversations","codewhisperer:transformations","codewhisperer:taskassist"]};class mn extends Error{code;originalError;constructor(t,n,s){super(t);this.name="KiroTokenRefreshError",this.code=n,this.originalError=s}}function Co(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function Pe(t,n,s){let r=t[n];if(typeof r==="string"&&r)return r;let e=t[s];return typeof e==="string"&&e?e:void 0}function GR(t,n,s){let r=t[n];if(typeof r==="number")return r;let e=t[s];return typeof e==="number"?e:void 0}function BR(t,n){let s;try{s=JSON.parse(t)}catch{return{message:t,code:`HTTP_${n}`}}if(!Co(s))return{message:t,code:`HTTP_${n}`};let r=Pe(s,"message","error_description")??t,e=Pe(s,"__type","error")??`HTTP_${n}`;return{message:r,code:e}}function ku(t){let n=t.userInfo;if(!Co(n))return;let s=n.email;return typeof s==="string"?s:void 0}async function Xu(t,n,s){let r=$e(t.refresh),e=t.authMethod==="idc",i=e?t.oidcRegion??t.region:t.region,f=Lr(e?st.REFRESH_IDC_URL:st.REFRESH_URL,i);if(e&&(!r.clientId||!r.clientSecret))throw new mn("Missing creds","MISSING_CREDENTIALS");let o=e?{refreshToken:r.refreshToken,clientId:r.clientId,clientSecret:r.clientSecret,grantType:"refresh_token"}:{refreshToken:r.refreshToken},c=e?`aws-sdk-js/${st.SDK_VERSION} ua/2.1 os/other lang/js md/browser#unknown_unknown api/sso-oidc#${st.SDK_VERSION} m/E ${st.USER_AGENT}`:`aws-sdk-js/3.0.0 ${st.USER_AGENT}-0.1.0 os/macos lang/js md/nodejs/18.0.0`;try{let h=await fetch(f,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","amz-sdk-request":"attempt=1; max=1","x-amzn-kiro-agent-mode":"vibe","user-agent":c,Connection:"close"},body:JSON.stringify(o),...n?{signal:n}:{},...xu(s)});if(!h.ok){let w=BR(await h.text(),h.status);throw new mn(`Refresh failed: ${w.message}`,w.code)}let u=await h.json();if(!Co(u))throw new mn("No access token","INVALID_RESPONSE");let l=Pe(u,"access_token","accessToken");if(!l)throw new mn("No access token","INVALID_RESPONSE");let _={refreshToken:Pe(u,"refresh_token","refreshToken")??r.refreshToken,authMethod:t.authMethod,...r.clientId?{clientId:r.clientId}:{},...r.clientSecret?{clientSecret:r.clientSecret}:{}};return{refresh:Ue(_),access:l,expires:Date.now()+(GR(u,"expires_in","expiresIn")??3600)*1000,authMethod:t.authMethod,region:t.region,...t.oidcRegion?{oidcRegion:t.oidcRegion}:{},...t.profileArn?{profileArn:t.profileArn}:{},...t.clientId?{clientId:t.clientId}:{},...t.clientSecret?{clientSecret:t.clientSecret}:{},...t.email||ku(u)?{email:t.email??ku(u)}:{}}}catch(h){if(h instanceof mn)throw h;if(h instanceof Error&&h.name==="AbortError")throw h;throw new mn(`Token refresh failed: ${h instanceof Error?h.message:"Unknown error"}`,"NETWORK_ERROR",h instanceof Error?h:void 0)}}class He extends Error{accountId;constructor(t){super(`Account ${t} is no longer available`);this.accountId=t;this.name="AccountUnavailableError"}}class ao{accountManager;tokenExpiryBufferMs;proxyUrl;inFlight=new Map;constructor(t,n,s){this.accountManager=t;this.tokenExpiryBufferMs=n;this.proxyUrl=s}async refreshIfNeeded(t,n,s){if(!Ru(n,this.tokenExpiryBufferMs)){let r=this.accountManager.getAccounts().find(({id:e})=>e===t.id);if(!r)throw new He(t.id);return r}return this.startOrJoinRefresh(t,n,s)}async forceRefresh(t,n){return this.startOrJoinRefresh(t,this.accountManager.toAuthDetails(t),n)}startOrJoinRefresh(t,n,s){if(!("generation"in t)||typeof t.generation!=="number")throw new He(t.id);let r={...t,generation:t.generation},e=`${r.id}:${r.generation}`,i=this.inFlight.get(e);if(i)return i;let f=this.runRefresh(r,n,s).finally(()=>{if(this.inFlight.get(e)===f)this.inFlight.delete(e)});return this.inFlight.set(e,f),f}async runRefresh(t,n,s){let r=await Xu(n,s,this.proxyUrl),e=this.accountManager.updateFromAuth(t,r);if(!e)throw new He(t.id);return e}}import{Database as mR}from"bun:sqlite";import{chmodSync as FR,existsSync as PR,mkdirSync as HR}from"fs";import{homedir as qu}from"os";import{dirname as NR,join as jo}from"path";function Ko(t,n){return{id:t.id,email:t.email,auth_method:t.authMethod,region:t.region,oidc_region:t.oidcRegion??null,client_id:t.clientId??null,client_secret:t.clientSecret??null,profile_arn:t.profileArn??null,start_url:t.startUrl??null,refresh_token:t.refreshToken,access_token:t.accessToken,expires_at:t.expiresAt,rate_limit_reset:t.rateLimitResetTime,is_healthy:t.isHealthy?1:0,unhealthy_reason:t.unhealthyReason??null,recovery_time:t.recoveryTime??null,fail_count:t.failCount,last_used:t.lastUsed??0,used_count:t.usedCount??0,limit_count:t.limitCount??0,last_sync:t.lastSync??0,overage_count:t.overageCount??0,generation:n}}function Ne(t){return{id:t.id,email:t.email,authMethod:t.auth_method,region:t.region,oidcRegion:t.oidc_region??void 0,clientId:t.client_id??void 0,clientSecret:t.client_secret??void 0,profileArn:t.profile_arn??void 0,startUrl:t.start_url??void 0,refreshToken:t.refresh_token,accessToken:t.access_token,expiresAt:t.expires_at,rateLimitResetTime:t.rate_limit_reset,isHealthy:t.is_healthy===1,unhealthyReason:t.unhealthy_reason??void 0,recoveryTime:t.recovery_time??void 0,failCount:t.fail_count,lastUsed:t.last_used,usedCount:t.used_count,limitCount:t.limit_count,lastSync:t.last_sync,overageCount:t.overage_count,generation:t.generation}}function Vo(t){return[t.id,t.email,t.auth_method,t.region??null,t.oidc_region??null,t.client_id??null,t.client_secret??null,t.profile_arn??null,t.start_url??null,t.refresh_token,t.access_token,t.expires_at,t.rate_limit_reset,t.is_healthy,t.unhealthy_reason??null,t.recovery_time??null,t.fail_count,t.last_used,t.used_count,t.limit_count,t.last_sync,t.overage_count,t.generation]}function DR(){let t=process.platform==="win32"?process.env.APPDATA??jo(qu(),"AppData","Roaming"):process.env.XDG_CONFIG_HOME??jo(qu(),".config");return jo(t,"kiro-provider","accounts.db")}var Fn=DR();class rs{db;path;constructor(t=Fn){if(this.path=t,t!==":memory:")HR(NR(t),{recursive:!0});this.db=new mR(t,{create:!0,strict:!0}),this.tightenPermissions(),this.db.run("PRAGMA busy_timeout = 5000"),this.db.run("PRAGMA journal_mode = WAL"),this.withImmediateTransaction(()=>{if(this.db.run(`
|
|
60
|
+
CREATE TABLE IF NOT EXISTS accounts (
|
|
61
|
+
id TEXT PRIMARY KEY, email TEXT NOT NULL, auth_method TEXT NOT NULL,
|
|
62
|
+
region TEXT NOT NULL, oidc_region TEXT, client_id TEXT, client_secret TEXT,
|
|
63
|
+
profile_arn TEXT, start_url TEXT, refresh_token TEXT NOT NULL,
|
|
64
|
+
access_token TEXT NOT NULL, expires_at INTEGER NOT NULL,
|
|
65
|
+
rate_limit_reset INTEGER DEFAULT 0, is_healthy INTEGER DEFAULT 1,
|
|
66
|
+
unhealthy_reason TEXT, recovery_time INTEGER, fail_count INTEGER DEFAULT 0,
|
|
67
|
+
last_used INTEGER DEFAULT 0, used_count INTEGER DEFAULT 0,
|
|
68
|
+
limit_count INTEGER DEFAULT 0, last_sync INTEGER DEFAULT 0,
|
|
69
|
+
overage_count INTEGER DEFAULT 0, generation INTEGER NOT NULL DEFAULT 1
|
|
70
|
+
)
|
|
71
|
+
`),!this.db.query("PRAGMA table_info(accounts)").all().some(({name:s})=>s==="generation"))this.db.run("ALTER TABLE accounts ADD COLUMN generation INTEGER NOT NULL DEFAULT 1");this.db.run(`
|
|
72
|
+
CREATE TABLE IF NOT EXISTS removed_accounts (
|
|
73
|
+
id TEXT PRIMARY KEY,
|
|
74
|
+
removed_at INTEGER NOT NULL,
|
|
75
|
+
last_generation INTEGER NOT NULL
|
|
76
|
+
)
|
|
77
|
+
`)})}getAccounts(){return this.db.query(`
|
|
78
|
+
SELECT accounts.* FROM accounts
|
|
79
|
+
WHERE NOT EXISTS (
|
|
80
|
+
SELECT 1 FROM removed_accounts WHERE removed_accounts.id = accounts.id
|
|
81
|
+
)
|
|
82
|
+
`).all().map(Ne)}getById(t){let n=this.db.query(`
|
|
83
|
+
SELECT accounts.* FROM accounts
|
|
84
|
+
WHERE accounts.id = ? AND NOT EXISTS (
|
|
85
|
+
SELECT 1 FROM removed_accounts WHERE removed_accounts.id = accounts.id
|
|
86
|
+
)
|
|
87
|
+
`).get(t);return n===null?void 0:Ne(n)}insertAccount(t){return this.withImmediateTransaction(()=>{let n=this.db.query("SELECT generation FROM accounts WHERE id = ?").get(t.id),s=this.db.query("SELECT last_generation FROM removed_accounts WHERE id = ?").get(t.id),r=Math.max(n?.generation??0,s?.last_generation??0)+1,e=Ko(t,r);return this.db.query(`
|
|
88
|
+
INSERT OR REPLACE INTO accounts (
|
|
89
|
+
id, email, auth_method, region, oidc_region, client_id, client_secret,
|
|
90
|
+
profile_arn, start_url, refresh_token, access_token, expires_at,
|
|
91
|
+
rate_limit_reset, is_healthy, unhealthy_reason, recovery_time, fail_count,
|
|
92
|
+
last_used, used_count, limit_count, last_sync, overage_count, generation
|
|
93
|
+
) VALUES (${Array.from({length:23},()=>"?").join(", ")})
|
|
94
|
+
`).run(...Vo(e)),this.clearRemovedAccountInternal(t.id),Ne(e)})}updateExistingAccounts(t){return this.withImmediateTransaction(()=>{let n=0,s=this.db.query(`
|
|
95
|
+
UPDATE accounts SET
|
|
96
|
+
email = ?, auth_method = ?, region = ?, oidc_region = ?, client_id = ?,
|
|
97
|
+
client_secret = ?, profile_arn = ?, start_url = ?, refresh_token = ?,
|
|
98
|
+
access_token = ?, expires_at = ?, rate_limit_reset = ?, is_healthy = ?,
|
|
99
|
+
unhealthy_reason = ?, recovery_time = ?, fail_count = ?, last_used = ?,
|
|
100
|
+
used_count = ?, limit_count = ?, last_sync = ?, overage_count = ?,
|
|
101
|
+
generation = generation + 1
|
|
102
|
+
WHERE id = ? AND generation = ? AND NOT EXISTS (
|
|
103
|
+
SELECT 1 FROM removed_accounts WHERE removed_accounts.id = accounts.id
|
|
104
|
+
)
|
|
105
|
+
`);for(let r of t){let e=Vo(Ko(r,r.generation)),i=e.shift();e.pop(),n+=s.run(...e,i??r.id,r.generation).changes}return n})}removeAccount(t){this.withImmediateTransaction(()=>{let n=this.db.query("SELECT generation FROM accounts WHERE id = ?").get(t),s=this.db.query("SELECT last_generation FROM removed_accounts WHERE id = ?").get(t),r=n?.generation??s?.last_generation??0;this.db.query("DELETE FROM accounts WHERE id = ?").run(t),this.db.query(`
|
|
106
|
+
INSERT OR REPLACE INTO removed_accounts (id, removed_at, last_generation)
|
|
107
|
+
VALUES (?, ?, ?)
|
|
108
|
+
`).run(t,Date.now(),r)})}clearRemovedAccount(t){this.withImmediateTransaction(()=>this.clearRemovedAccountInternal(t))}close(){this.db.close()}clearRemovedAccountInternal(t){this.db.query("DELETE FROM removed_accounts WHERE id = ?").run(t)}withImmediateTransaction(t){this.db.exec("BEGIN IMMEDIATE");try{let n=t();return this.db.exec("COMMIT"),n}catch(n){throw this.db.exec("ROLLBACK"),n}finally{this.tightenPermissions()}}tightenPermissions(){if(this.path===":memory:")return;for(let t of[this.path,`${this.path}-wal`,`${this.path}-shm`])if(PR(t))FR(t,384)}}function Z(t,n,s,r){let e={message:n,type:s};if(r!==void 0)e.code=r;return new Response(JSON.stringify({error:e}),{status:t,headers:{"Content-Type":"application/json"}})}var Cu="Bearer ";function au(t,n){let s=t.headers.get("Authorization");if(s===null)return{ok:!1,response:Z(401,"Missing Authorization header.","authentication_error","missing_api_key")};if(!s.startsWith(Cu))return{ok:!1,response:Z(401,"Authorization header must use the Bearer scheme.","authentication_error","invalid_api_key")};let r=s.slice(Cu.length);if(!n.includes(r))return{ok:!1,response:Z(401,"Incorrect API key provided.","authentication_error","invalid_api_key")};return{ok:!0}}var Jn=H(kt(),1);var Zr=H(kt(),1);var te=H(kt(),1);var $n=H(kt(),1);var Bt=H(kt(),1);var a=H(Rt(),1);var lr=H(Qn(),1),cd=H(Pn(),1);var Gc=H(_i(),1);var ne=H(Tt(),1);var Ft=H(fs(),1);var V=H(pr(),1);var Y=H(En(),1);var tr=H(Qn(),1);var Zs=H(En(),1);var nA=async(t,n,s)=>{return{operation:Zs.getSmithyContext(n).operation}};function dG(t){return{schemeId:"smithy.api#httpBearerAuth",propertiesExtractor:({profile:n,filepath:s,configFilepath:r,ignoreCache:e},i)=>({identityProperties:{profile:n,filepath:s,configFilepath:r,ignoreCache:e}})}}var sA=(t)=>{let n=[];switch(t.operation){default:n.push(dG(t))}return n},rA=(t)=>{let n=tr.memoizeIdentityProvider(t.token,tr.isIdentityExpired,tr.doesIdentityRequireRefresh);return Object.assign(t,{authSchemePreference:Zs.normalizeProvider(t.authSchemePreference??[]),token:n})};var eA=(t)=>{return Object.assign(t,{useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,defaultSigningName:"amazoncodewhispererstreamingservice"})},iA={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}};var oA={name:"@aws/codewhisperer-streaming-client",description:"@aws/codewhisperer-streaming-client",version:"1.0.45",scripts:{build:"concurrently 'npm:build:cjs' 'npm:build:es' 'npm:build:types'","build:cjs":"tsc -p tsconfig.cjs.json","build:es":"tsc -p tsconfig.es.json","build: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 tsconfig.cjs.tsbuildinfo tsconfig.es.tsbuildinfo tsconfig.types.tsbuildinfo",prepack:"npm run clean && npm run build"},main:"./dist-cjs/index.js",types:"./dist-types/index.d.ts",module:"./dist-es/index.js",sideEffects:!1,dependencies:{tslib:"^2.6.2","@aws-crypto/sha256-browser":"5.2.0","@aws-crypto/sha256-js":"5.2.0","@aws-sdk/core":"^3.974.7","@aws-sdk/middleware-host-header":"^3.972.10","@aws-sdk/middleware-logger":"^3.972.10","@aws-sdk/middleware-recursion-detection":"^3.972.11","@aws-sdk/middleware-user-agent":"^3.972.37","@aws-sdk/region-config-resolver":"^3.972.13","@aws-sdk/token-providers":"^3.1040.0","@aws-sdk/types":"^3.973.8","@aws-sdk/util-endpoints":"^3.996.8","@aws-sdk/util-user-agent-browser":"^3.972.10","@aws-sdk/util-user-agent-node":"^3.973.23","@smithy/config-resolver":"^4.4.17","@smithy/core":"^3.23.17","@smithy/eventstream-serde-browser":"^4.2.14","@smithy/eventstream-serde-config-resolver":"^4.3.14","@smithy/eventstream-serde-node":"^4.2.14","@smithy/fetch-http-handler":"^5.3.17","@smithy/hash-node":"^4.2.14","@smithy/invalid-dependency":"^4.2.14","@smithy/middleware-content-length":"^4.2.14","@smithy/middleware-endpoint":"^4.4.32","@smithy/middleware-retry":"^4.5.7","@smithy/middleware-serde":"^4.2.20","@smithy/middleware-stack":"^4.2.14","@smithy/node-config-provider":"^4.3.14","@smithy/node-http-handler":"^4.6.1","@smithy/protocol-http":"^5.3.14","@smithy/smithy-client":"^4.12.13","@smithy/types":"^4.14.1","@smithy/url-parser":"^4.2.14","@smithy/util-base64":"^4.3.2","@smithy/util-body-length-browser":"^4.2.2","@smithy/util-body-length-node":"^4.2.3","@smithy/util-defaults-mode-browser":"^4.3.49","@smithy/util-defaults-mode-node":"^4.2.54","@smithy/util-endpoints":"^3.4.2","@smithy/util-middleware":"^4.2.14","@smithy/util-retry":"^4.3.6","@smithy/util-utf8":"^4.2.2"},devDependencies:{"@tsconfig/node20":"20.1.8",concurrently:"7.0.0","downlevel-dts":"0.10.1",premove:"4.0.0",typescript:"~5.8.3","@types/node":"^20.14.8"},engines:{node:">=20.0.0"},typesVersions:{"<4.5":{"dist-types/*":["dist-types/ts3.4/*"]}},files:["dist-*/**"],browser:{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.browser"},"react-native":{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.native"},license:"Apache-2.0"};var nd=H(kt(),1),sd=H(zc(),1);var cr=H(Rt(),1);var $t=H(Rt(),1);var qA=300000,sr="To refresh this SSO session run 'aws sso login' with the corresponding profile.";var b1=async(t,n={},s)=>{let{SSOOIDCClient:r}=await Promise.resolve().then(() => H(Ih(),1)),e=(f)=>n.clientConfig?.[f]??n.parentClientConfig?.[f]??s?.[f];return new r(Object.assign({},n.clientConfig??{},{region:t??n.clientConfig?.region,logger:e("logger"),userAgentAppId:e("userAgentAppId")}))};var T1=async(t,n,s={},r)=>{let{CreateTokenCommand:e}=await Promise.resolve().then(() => H(Ih(),1));return(await b1(n,s,r)).send(new e({clientId:t.clientId,clientSecret:t.clientSecret,refreshToken:t.refreshToken,grantType:"refresh_token"}))};var S1=H(Rt(),1);var Oh=(t)=>{if(t.expiration&&t.expiration.getTime()<Date.now())throw new S1.TokenProviderError(`Token is expired. ${sr}`,!1)};var $1=H(Rt(),1);var Xn=(t,n,s=!1)=>{if(typeof n>"u")throw new $1.TokenProviderError(`Value not present for '${t}' in SSO Token${s?". Cannot refresh":""}. ${sr}`,!1)};var U1=H(Rt(),1);import{promises as JH}from"fs";var{writeFile:zH}=JH,L1=(t,n)=>{let s=U1.getSSOTokenFilepath(t),r=JSON.stringify(n,null,2);return zH(s,r)};var I1=new Date(0),O1=(t={})=>async({callerClientConfig:n}={})=>{t.logger?.debug("@aws-sdk/token-providers - fromSso");let s=await $t.parseKnownFiles(t),r=$t.getProfileName({profile:t.profile??n?.profile}),e=s[r];if(!e)throw new $t.TokenProviderError(`Profile '${r}' could not be found in shared credentials file.`,!1);else if(!e.sso_session)throw new $t.TokenProviderError(`Profile '${r}' is missing required property 'sso_session'.`);let i=e.sso_session,o=(await $t.loadSsoSessionData(t))[i];if(!o)throw new $t.TokenProviderError(`Sso session '${i}' could not be found in shared credentials file.`,!1);for(let A of["sso_start_url","sso_region"])if(!o[A])throw new $t.TokenProviderError(`Sso session '${i}' is missing required property '${A}'.`,!1);let{sso_start_url:c,sso_region:h}=o,u;try{u=await $t.getSSOTokenFromFile(i)}catch(A){throw new $t.TokenProviderError(`The SSO session token associated with profile=${r} was not found or is invalid. ${sr}`,!1)}Xn("accessToken",u.accessToken),Xn("expiresAt",u.expiresAt);let{accessToken:l,expiresAt:_}=u,w={token:l,expiration:new Date(_)};if(w.expiration.getTime()-Date.now()>qA)return w;if(Date.now()-I1.getTime()<30000)return Oh(w),w;Xn("clientId",u.clientId,!0),Xn("clientSecret",u.clientSecret,!0),Xn("refreshToken",u.refreshToken,!0);try{I1.setTime(Date.now());let A=await T1(u,h,t,n);Xn("accessToken",A.accessToken),Xn("expiresIn",A.expiresIn);let M=new Date(Date.now()+A.expiresIn*1000);try{await L1(i,{...u,accessToken:A.accessToken,expiresAt:M.toISOString(),refreshToken:A.refreshToken})}catch(d){}return{token:A.accessToken,expiration:M}}catch(A){return Oh(w),w}};var yh=(t={})=>cr.memoize(cr.chain(O1(t),async()=>{throw new cr.TokenProviderError("Could not load token from any providers",!1)}),(n)=>n.expiration!==void 0&&n.expiration.getTime()-Date.now()<300000,(n)=>n.expiration!==void 0);var un=H(kt(),1);var rd=H(Qn(),1);var ro=H(_i(),1);var Gh=H(bt(),1);var Un=H(Rt(),1);var go=H(Ni(),1);var Bh=H(bt(),1);var mh=H(Rt(),1);var ot=H(pr(),1);var v1=H(bh(),1),Z1=H(Qn(),1);var Fh=H(Tt(),1);var hr=H(bt(),1);var ds=H(bt(),1);var Mt=H(fs(),1);var le="ref",gs=-1,eo=!0,y1="isSet",F1="PartitionResult",io="booleanEquals",Ph="getAttr",G1={[le]:"Endpoint"},Hh={[le]:F1},ur={},B1=[{[le]:"Region"}],m1={conditions:[[y1,[G1]],[y1,B1],["aws.partition",B1,F1],[io,[{[le]:"UseFIPS"},eo]],[io,[{[le]:"UseDualStack"},eo]],[io,[{fn:Ph,argv:[Hh,"supportsDualStack"]},eo]],[io,[{fn:Ph,argv:[Hh,"supportsFIPS"]},eo]],["stringEquals",[{fn:Ph,argv:[Hh,"name"]},"aws-us-gov"]]],results:[[gs],[gs,"Invalid Configuration: FIPS and custom endpoint are not supported"],[gs,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[G1,ur],["https://amazoncodewhispererstreamingservice-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",ur],[gs,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://amazoncodewhispererstreamingservice.{Region}.amazonaws.com",ur],["https://amazoncodewhispererstreamingservice-fips.{Region}.{PartitionResult#dnsSuffix}",ur],[gs,"FIPS is enabled but this partition does not support FIPS"],["https://amazoncodewhispererstreamingservice.{Region}.{PartitionResult#dualStackDnsSuffix}",ur],[gs,"DualStack is enabled but this partition does not support DualStack"],["https://amazoncodewhispererstreamingservice.{Region}.{PartitionResult#dnsSuffix}",ur],[gs,"Invalid Configuration: Missing Region"]]},kH=2,Ut=1e8,XH=new Int32Array([-1,1,-1,0,13,3,1,4,Ut+12,2,5,Ut+12,3,8,6,4,7,Ut+11,5,Ut+9,Ut+10,4,11,9,6,10,Ut+8,7,Ut+6,Ut+7,5,12,Ut+5,6,Ut+4,Ut+5,3,Ut+1,14,4,Ut+2,Ut+3]),P1=Mt.BinaryDecisionDiagram.from(XH,kH,m1.conditions,m1.results);var qH=new Mt.EndpointCache({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),H1=(t,n={})=>{return qH.get(t,()=>Mt.decideEndpoint(P1,{endpointParams:t,logger:n.logger}))};Mt.customEndpointFunctions.aws=Bt.awsEndpointFunctions;var Wh=H(Pn(),1);class Lt extends Y.ServiceException{constructor(t){super(t);Object.setPrototypeOf(this,Lt.prototype)}}class oo extends Lt{name="AccessDeniedException";$fault="client";reason;constructor(t){super({name:"AccessDeniedException",$fault:"client",...t});Object.setPrototypeOf(this,oo.prototype),this.reason=t.reason}}class fo extends Lt{name="ConflictException";$fault="client";reason;constructor(t){super({name:"ConflictException",$fault:"client",...t});Object.setPrototypeOf(this,fo.prototype),this.reason=t.reason}}class co extends Lt{name="InternalServerException";$fault="server";$retryable={};reason;constructor(t){super({name:"InternalServerException",$fault:"server",...t});Object.setPrototypeOf(this,co.prototype),this.reason=t.reason}}class ho extends Lt{name="ThrottlingException";$fault="client";$retryable={throttling:!0};reason;constructor(t){super({name:"ThrottlingException",$fault:"client",...t});Object.setPrototypeOf(this,ho.prototype),this.reason=t.reason}}class uo extends Lt{name="ValidationException";$fault="client";reason;constructor(t){super({name:"ValidationException",$fault:"client",...t});Object.setPrototypeOf(this,uo.prototype),this.reason=t.reason}}class lo extends Lt{name="ResourceNotFoundException";$fault="client";constructor(t){super({name:"ResourceNotFoundException",$fault:"client",...t});Object.setPrototypeOf(this,lo.prototype)}}class _o extends Lt{name="ServiceUnavailableException";$fault="server";constructor(t){super({name:"ServiceUnavailableException",$fault:"server",...t});Object.setPrototypeOf(this,_o.prototype)}}class wo extends Lt{name="ServiceQuotaExceededException";$fault="client";reason;constructor(t){super({name:"ServiceQuotaExceededException",$fault:"client",...t});Object.setPrototypeOf(this,wo.prototype),this.reason=t.reason}}class Ao extends Lt{name="DryRunOperationException";$fault="client";responseCode;constructor(t){super({name:"DryRunOperationException",$fault:"client",...t});Object.setPrototypeOf(this,Ao.prototype),this.responseCode=t.responseCode}}var N1=Wh.TypeRegistry.for("smithy.ts.sdk.synthetic.com.amazon.aws.codewhisperer.streaming"),CH=[-3,"smithy.ts.sdk.synthetic.com.amazon.aws.codewhisperer.streaming","CodeWhispererStreamingServiceException",0,[],[]];N1.registerError(CH,Lt);var ln=Wh.TypeRegistry.for("com.amazon.aws.codewhisperer"),aH=[-3,"com.amazon.aws.codewhisperer","AccessDeniedException",{["error"]:"client",["httpError"]:403},["message","reason"],[0,0],1];ln.registerError(aH,oo);var KH=[-3,"com.amazon.aws.codewhisperer","ConflictException",{["error"]:"client",["httpError"]:409},["message","reason"],[0,0],1];ln.registerError(KH,fo);var VH=[-3,"com.amazon.aws.codewhisperer","DryRunOperationException",{["error"]:"client"},["message","responseCode"],[0,[1,32]]];ln.registerError(VH,Ao);var D1=[-3,"com.amazon.aws.codewhisperer","InternalServerException",{["error"]:"server",["httpError"]:500},["message","reason"],[0,0],1];ln.registerError(D1,co);var jH=[-3,"com.amazon.aws.codewhisperer","ResourceNotFoundException",{["error"]:"client",["httpError"]:404},["message"],[0],1];ln.registerError(jH,lo);var pH=[-3,"com.amazon.aws.codewhisperer","ServiceQuotaExceededException",{["error"]:"client",["httpError"]:402},["message","reason"],[0,0],1];ln.registerError(pH,wo);var vH=[-3,"com.amazon.aws.codewhisperer","ServiceUnavailableException",{["error"]:"server",["httpError"]:503},["message"],[0],1];ln.registerError(vH,_o);var ZH=[-3,"com.amazon.aws.codewhisperer","ThrottlingException",{["error"]:"client",["httpError"]:429},["message","reason"],[0,0],1];ln.registerError(ZH,ho);var tN=[-3,"com.amazon.aws.codewhisperer","ValidationException",{["error"]:"client",["httpError"]:400},["message","reason"],[0,0],1];ln.registerError(tN,uo);var W1=[N1,ln];var Yh=[0,"com.amazon.aws.codewhisperer","SensitiveDocument",8,15],B=[0,"com.amazon.aws.codewhisperer","SensitiveString",8,0],nN=[0,"com.amazon.aws.codewhisperer","ToolDescription",8,0],Mo=[0,"com.amazon.aws.codewhisperer","ToolName",8,0],q=[0,"com.amazon.aws.q","SensitiveString",8,0],sN=[3,"com.amazon.aws.codewhisperer","AdditionalContentEntry",0,["name","description","innerContext"],[[()=>B,0],[()=>B,0],[()=>B,0]],2],rN=[3,"com.amazon.aws.codewhisperer","AppStudioState",0,["namespace","propertyName","propertyContext","propertyValue"],[[()=>B,0],[()=>B,0],[()=>B,0],[()=>B,0]],3],eN=[3,"com.amazon.aws.codewhisperer","AssistantResponseEvent",0,["content","modelId"],[[()=>B,0],0],1],iN=[3,"com.amazon.aws.codewhisperer","AssistantResponseMessage",0,["content","messageId","supplementaryWebLinks","references","followupPrompt","toolUses","cachePoint","reasoningContent"],[[()=>B,0],0,[()=>V1,0],()=>K1,[()=>Y1,0],[()=>YD,0],()=>xh,[()=>cW,0]],1];var xh=[3,"com.amazon.aws.codewhisperer","CachePoint",0,["type"],[0],1],oN=[3,"com.amazon.aws.codewhisperer","CitationEvent",0,["target","citationLink","citationText"],[()=>nW,[()=>B,0],[()=>B,0]],2],fN=[3,"com.amazon.aws.codewhisperer","ClientCacheConfig",0,["useClientCachingOnly"],[2]],cN=[3,"com.amazon.aws.codewhisperer","CodeDescription",0,["href"],[[()=>B,0]],1],hN=[3,"com.amazon.aws.codewhisperer","CodeEvent",0,["content"],[[()=>B,0]],1],uN=[3,"com.amazon.aws.codewhisperer","CodeReferenceEvent",0,["references"],[()=>K1]],lN=[3,"com.amazon.aws.codewhisperer","ConsoleState",0,["region","consoleUrl","serviceId","serviceConsolePage","serviceSubconsolePage","taskName","uxErrorMessage"],[0,[()=>B,0],0,0,0,[()=>B,0],[()=>B,0]]],_N=[3,"com.amazon.aws.codewhisperer","ContextUsageEvent",0,["contextUsagePercentage"],[1]],wN=[3,"com.amazon.aws.codewhisperer","ConversationState",0,["currentMessage","chatTriggerType","conversationId","workspaceId","history","customizationArn","agentContinuationId","agentTaskType"],[[()=>j1,0],0,0,0,[()=>OD,0],0,0,0],2],AN=[3,"com.amazon.aws.codewhisperer","DiagnosticLocation",0,["uri","range"],[[()=>B,0],()=>Qh],2],MN=[3,"com.amazon.aws.codewhisperer","DiagnosticRelatedInformation",0,["location","message"],[[()=>AN,0],[()=>B,0]],2],dN=[3,"com.amazon.aws.codewhisperer","DocumentBlock",0,["name","format","source"],[0,0,[()=>iW,0]],3],gN=[3,"com.amazon.aws.codewhisperer","DocumentCitationEvent",0,["source","title","location","sourceContent"],[[()=>B,0],[()=>B,0],[()=>eW,0],[()=>BD,0]]],EN=[3,"com.amazon.aws.codewhisperer","DocumentCitationSearchResultSpan",0,["searchResultIndex","start","end"],[1,1,1]],RN=[3,"com.amazon.aws.codewhisperer","DocumentCitationSourceContent",0,["text"],[[()=>B,0]]],Nh=[3,"com.amazon.aws.codewhisperer","DocumentCitationSpan",0,["documentIndex","start","end"],[1,1,1]],bN=[3,"com.amazon.aws.codewhisperer","DocumentCitationWebLocation",0,["url","domain"],[[()=>B,0],[()=>B,0]]],TN=[3,"com.amazon.aws.codewhisperer","DocumentSymbol",0,["name","type","source"],[0,0,0],2],SN=[3,"com.amazon.aws.codewhisperer","DryRunSucceedEvent",0,[],[]],$N=[3,"com.amazon.aws.codewhisperer","EditorState",0,["document","cursorState","relevantDocuments","useRelevantDocuments","workspaceFolders"],[[()=>J1,0],()=>sW,[()=>PD,0],2,[()=>xD,0]]],UN=[3,"com.amazon.aws.codewhisperer","EnvironmentVariable",0,["key","value"],[[()=>B,0],[()=>B,0]]],LN=[3,"com.amazon.aws.codewhisperer","EnvState",0,["operatingSystem","currentWorkingDirectory","environmentVariables","timezoneOffset"],[0,[()=>B,0],[()=>mD,0],1]],Y1=[3,"com.amazon.aws.codewhisperer","FollowupPrompt",0,["content","userIntent"],[[()=>B,0],0],1],IN=[3,"com.amazon.aws.codewhisperer","FollowupPromptEvent",0,["followupPrompt"],[[()=>Y1,0]]],ON=[3,"com.amazon.aws.codewhisperer","GitState",0,["status"],[[()=>B,0]]],yN=[3,"com.amazon.aws.codewhisperer","ImageBlock",0,["format","source"],[0,[()=>oW,0]],2],GN=[3,"com.amazon.aws.codewhisperer","IntentsEvent",0,["intents"],[[()=>vD,0]]],BN=[3,"com.amazon.aws.codewhisperer","InvalidStateEvent",0,["reason","message"],[0,0],2],mN=[3,"com.amazon.aws.codewhisperer","MessageMetadataEvent",0,["conversationId","utteranceId"],[0,0]],FN=[3,"com.amazon.aws.codewhisperer","MetadataEvent",0,["tokenUsage"],[()=>vN]],PN=[3,"com.amazon.aws.codewhisperer","MeteringEvent",0,["usage","unit","unitPlural"],[1,0,0]],Dh=[3,"com.amazon.aws.codewhisperer","Position",0,["line","character"],[1,1],2],x1=[3,"com.amazon.aws.codewhisperer","ProgrammingLanguage",0,["languageName"],[0],1],Qh=[3,"com.amazon.aws.codewhisperer","Range",0,["start","end"],[()=>Dh,()=>Dh],2],HN=[3,"com.amazon.aws.codewhisperer","ReasoningContentEvent",8,["text","redactedContent","signature"],[[()=>B,0],21,[()=>B,0]]],NN=[3,"com.amazon.aws.codewhisperer","ReasoningText",8,["text","signature"],[[()=>B,0],[()=>B,0]],1],DN=[3,"com.amazon.aws.codewhisperer","Reference",0,["licenseName","repository","url","recommendationContentSpan"],[0,0,0,()=>Q1]],WN=[3,"com.amazon.aws.codewhisperer","RelevantTextDocument",0,["relativeFilePath","programmingLanguage","text","documentSymbols","type"],[[()=>B,0],()=>x1,[()=>B,0],()=>a1,0],1],YN=[3,"com.amazon.aws.codewhisperer","RuntimeDiagnostic",0,["source","severity","message"],[[()=>B,0],0,[()=>B,0]],3],xN=[3,"com.amazon.aws.codewhisperer","ShellHistoryEntry",0,["command","directory","exitCode","stdout","stderr"],[[()=>B,0],[()=>B,0],1,[()=>B,0],[()=>B,0]],1],QN=[3,"com.amazon.aws.codewhisperer","ShellState",0,["shellName","shellHistory"],[0,[()=>HD,0]],1],Q1=[3,"com.amazon.aws.codewhisperer","Span",0,["start","end"],[1,1]],JN=[3,"com.amazon.aws.codewhisperer","SupplementaryWebLink",0,["url","title","snippet"],[[()=>B,0],[()=>B,0],[()=>B,0]],2],zN=[3,"com.amazon.aws.codewhisperer","SupplementaryWebLinksEvent",0,["supplementaryWebLinks"],[[()=>V1,0]]],J1=[3,"com.amazon.aws.codewhisperer","TextDocument",0,["relativeFilePath","programmingLanguage","text","documentSymbols"],[[()=>B,0],()=>x1,[()=>B,0],()=>a1],1],kN=[3,"com.amazon.aws.codewhisperer","TextDocumentDiagnostic",0,["document","range","source","severity","message","code","codeDescription","tags","relatedInformation","data"],[[()=>J1,0],()=>Qh,[()=>B,0],0,[()=>B,0],[()=>B,0],[()=>cN,0],64,[()=>yD,0],[()=>B,0]],5],XN=[3,"com.amazon.aws.codewhisperer","ToolInputSchema",0,["json"],[[()=>Yh,0]]],z1=[3,"com.amazon.aws.codewhisperer","ToolResult",0,["toolUseId","content","status","toolName"],[0,[()=>ND,0],0,[()=>Mo,0]],2],qN=[3,"com.amazon.aws.codewhisperer","ToolResultEvent",0,["toolResult"],[[()=>z1,0]]],CN=[3,"com.amazon.aws.codewhisperer","ToolSpecification",0,["inputSchema","name","description"],[[()=>XN,0],[()=>Mo,0],[()=>nN,0]],2],aN=[3,"com.amazon.aws.codewhisperer","ToolUse",0,["toolUseId","name","input"],[0,[()=>Mo,0],[()=>Yh,0]],3],KN=[3,"com.amazon.aws.codewhisperer","ToolUseEvent",0,["toolUseId","name","input","stop"],[0,[()=>Mo,0],[()=>B,0],2],2];var VN=[3,"com.amazon.aws.codewhisperer","UserInputMessage",0,["content","userInputMessageContext","userIntent","origin","images","documents","modelId","cachePoint","clientCacheConfig"],[[()=>B,0],[()=>jN,0],0,0,[()=>FD,0],[()=>GD,0],0,()=>xh,()=>fN],1],jN=[3,"com.amazon.aws.codewhisperer","UserInputMessageContext",0,["editorState","shellState","gitState","envState","appStudioContext","diagnostic","consoleState","userSettings","additionalContext","toolResults","tools"],[[()=>$N,0],[()=>QN,0],[()=>ON,0],[()=>LN,0],[()=>rN,0],[()=>rW,0],[()=>lN,0],()=>pN,[()=>ID,0],[()=>DD,0],[()=>WD,0]]],pN=[3,"com.amazon.aws.codewhisperer","UserSettings",0,["hasConsentedToCrossRegionCalls"],[2]];var vN=[3,"com.amazon.aws.codewhisperer.internal","TokenUsage",0,["uncachedInputTokens","outputTokens","totalTokens","cacheReadInputTokens","cacheWriteInputTokens","contextUsagePercentage","normalizedTokenUsage"],[1,1,1,1,1,1,1],3];var ZN=[3,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponseRequest",0,["conversationState","profileArn","agentMode","additionalModelRequestFields"],[[()=>wN,0],0,[0,{["httpHeader"]:"x-amzn-kiro-agent-mode"}],15],1],tD=[3,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponseResponse",0,["conversationId","generateAssistantResponseResponse"],[[0,{["httpHeader"]:"x-amzn-codewhisperer-conversation-id"}],[()=>tW,16]],2];var nD=[3,"com.amazon.aws.q","InteractionComponentsEvent",0,["interactionComponentEntries"],[[()=>kD,0]],1],Jh=[3,"com.amazon.aws.q.interactioncomponents","Action",0,["webLink","moduleLink"],[[()=>LD,0],[()=>lD,0]]],zh=[3,"com.amazon.aws.q.interactioncomponents","Alert",0,["type","content"],[0,[()=>QD,0]],2],sD=[3,"com.amazon.aws.q.interactioncomponents","AlertComponent",0,["text"],[[()=>_e,0]]],rD=[3,"com.amazon.aws.q.interactioncomponents","Clarification",0,["questions","dismissible"],[[()=>zD,0],2],1],eD=[3,"com.amazon.aws.q.interactioncomponents","ClarificationAnswerOption",0,["label","value"],[[()=>q,0],[()=>q,0]],2],iD=[3,"com.amazon.aws.q.interactioncomponents","ClarificationQuestion",0,["question","options","allowCustom","skippable"],[[()=>q,0],[()=>JD,0],2,2],2],oD=[3,"com.amazon.aws.q.interactioncomponents","CloudWatchTroubleshootingLink",0,["label","investigationPayload","defaultText"],[[()=>q,0],[()=>q,0],[()=>q,0]],2],k1=[3,"com.amazon.aws.q.interactioncomponents","InfrastructureUpdate",0,["transition"],[[()=>fD,0]]],fD=[3,"com.amazon.aws.q.interactioncomponents","InfrastructureUpdateTransition",0,["currentState","nextState"],[[()=>q,0],[()=>q,0]],2],cD=[3,"com.amazon.aws.q.interactioncomponents","InlineArtifact",0,["dsl","summary","title","artifactLabel"],[[()=>q,0],[()=>q,0],[()=>q,0],[()=>q,0]],4],hD=[3,"com.amazon.aws.q.interactioncomponents","InteractionComponent",0,["text","alert","infrastructureUpdate","progress","step","taskDetails","taskReference","suggestions","section","resource","resourceList","action","clarification","inlineArtifact"],[[()=>_e,0],[()=>zh,0],[()=>k1,0],[()=>X1,0],[()=>C1,0],[()=>SD,0],()=>UD,[()=>gD,0],[()=>wD,0],[()=>kh,0],[()=>q1,0],[()=>Jh,0],[()=>rD,0],[()=>cD,0]]],uD=[3,"com.amazon.aws.q.interactioncomponents","InteractionComponentEntry",0,["interactionComponent","interactionComponentId"],[[()=>hD,0],0],1],lD=[3,"com.amazon.aws.q.interactioncomponents","ModuleLink",0,["cloudWatchTroubleshootingLink"],[[()=>oD,0]]],X1=[3,"com.amazon.aws.q.interactioncomponents","Progress",0,["content"],[[()=>XD,0]],1],_D=[3,"com.amazon.aws.q.interactioncomponents","ProgressComponent",0,["step"],[[()=>C1,0]]],kh=[3,"com.amazon.aws.q.interactioncomponents","Resource",0,["title","link","description","type","ARN","resourceJsonString"],[[()=>q,0],[()=>q,0],[()=>q,0],[()=>q,0],[()=>q,0],[()=>q,0]],6],q1=[3,"com.amazon.aws.q.interactioncomponents","ResourceList",0,["items","action"],[[()=>qD,0],[()=>Jh,0]],1],wD=[3,"com.amazon.aws.q.interactioncomponents","Section",0,["title","content","action"],[[()=>q,0],[()=>CD,0],[()=>Jh,0]],2],AD=[3,"com.amazon.aws.q.interactioncomponents","SectionComponent",0,["text","alert","resource","resourceList"],[[()=>_e,0],[()=>zh,0],[()=>kh,0],[()=>q1,0]]],C1=[3,"com.amazon.aws.q.interactioncomponents","Step",0,["id","state","label","content"],[1,0,[()=>q,0],[()=>aD,0]],3],MD=[3,"com.amazon.aws.q.interactioncomponents","StepComponent",0,["text"],[[()=>_e,0]]],dD=[3,"com.amazon.aws.q.interactioncomponents","Suggestion",0,["value"],[[()=>q,0]],1],gD=[3,"com.amazon.aws.q.interactioncomponents","Suggestions",0,["items"],[[()=>KD,0]],1],ED=[3,"com.amazon.aws.q.interactioncomponents","TaskAction",0,["label","payload","note","primary","disabled","confirmation"],[[()=>q,0],[()=>ZD,0],[()=>bD,0],2,2,[()=>RD,0]],2],RD=[3,"com.amazon.aws.q.interactioncomponents","TaskActionConfirmation",0,["content"],[[()=>q,0]]],bD=[3,"com.amazon.aws.q.interactioncomponents","TaskActionNote",0,["content","type"],[[()=>q,0],0],1],TD=[3,"com.amazon.aws.q.interactioncomponents","TaskComponent",0,["text","infrastructureUpdate","alert","progress"],[[()=>_e,0],[()=>k1,0],[()=>zh,0],[()=>X1,0]]],SD=[3,"com.amazon.aws.q.interactioncomponents","TaskDetails",0,["overview","content","actions"],[[()=>$D,0],[()=>jD,0],[()=>VD,0]],2],$D=[3,"com.amazon.aws.q.interactioncomponents","TaskOverview",0,["label","description"],[[()=>q,0],[()=>q,0]],2],UD=[3,"com.amazon.aws.q.interactioncomponents","TaskReference",0,["taskId"],[0],1],_e=[3,"com.amazon.aws.q.interactioncomponents","Text",0,["content"],[[()=>q,0]],1],LD=[3,"com.amazon.aws.q.interactioncomponents","WebLink",0,["label","url"],[[()=>q,0],[()=>q,0]],2];var ID=[1,"com.amazon.aws.codewhisperer","AdditionalContentList",0,[()=>sN,0]],OD=[1,"com.amazon.aws.codewhisperer","ChatHistory",0,[()=>j1,0]],yD=[1,"com.amazon.aws.codewhisperer","DiagnosticRelatedInformationList",0,[()=>MN,0]];var GD=[1,"com.amazon.aws.codewhisperer","DocumentBlocks",0,[()=>dN,0]],BD=[1,"com.amazon.aws.codewhisperer","DocumentCitationSourceContents",0,[()=>RN,0]],a1=[1,"com.amazon.aws.codewhisperer","DocumentSymbols",0,()=>TN],mD=[1,"com.amazon.aws.codewhisperer","EnvironmentVariables",0,[()=>UN,0]],FD=[1,"com.amazon.aws.codewhisperer","ImageBlocks",0,[()=>yN,0]],K1=[1,"com.amazon.aws.codewhisperer","References",0,()=>DN],PD=[1,"com.amazon.aws.codewhisperer","RelevantDocumentList",0,[()=>WN,0]],HD=[1,"com.amazon.aws.codewhisperer","ShellHistory",0,[()=>xN,0]],V1=[1,"com.amazon.aws.codewhisperer","SupplementaryWebLinks",0,[()=>JN,0]],ND=[1,"com.amazon.aws.codewhisperer","ToolResultContent",0,[()=>uW,0]],DD=[1,"com.amazon.aws.codewhisperer","ToolResults",0,[()=>z1,0]],WD=[1,"com.amazon.aws.codewhisperer","Tools",0,[()=>hW,0]],YD=[1,"com.amazon.aws.codewhisperer","ToolUses",0,[()=>aN,0]],xD=[1,"com.amazon.aws.codewhisperer","WorkspaceFolderList",0,[()=>B,0]],QD=[1,"com.amazon.aws.q.interactioncomponents","AlertComponentList",0,[()=>sD,0]],JD=[1,"com.amazon.aws.q.interactioncomponents","ClarificationAnswerOptionsList",0,[()=>eD,0]],zD=[1,"com.amazon.aws.q.interactioncomponents","ClarificationQuestionList",0,[()=>iD,0]],kD=[1,"com.amazon.aws.q.interactioncomponents","InteractionComponentEntryList",0,[()=>uD,0]],XD=[1,"com.amazon.aws.q.interactioncomponents","ProgressComponentList",0,[()=>_D,0]],qD=[1,"com.amazon.aws.q.interactioncomponents","Resources",0,[()=>kh,0]],CD=[1,"com.amazon.aws.q.interactioncomponents","SectionComponentList",0,[()=>AD,0]],aD=[1,"com.amazon.aws.q.interactioncomponents","StepComponentList",0,[()=>MD,0]],KD=[1,"com.amazon.aws.q.interactioncomponents","SuggestionList",0,[()=>dD,0]],VD=[1,"com.amazon.aws.q.interactioncomponents","TaskActionList",0,[()=>ED,0]],jD=[1,"com.amazon.aws.q.interactioncomponents","TaskComponentList",0,[()=>TD,0]],pD=[2,"com.amazon.aws.codewhisperer","IntentData",8,0,()=>fW],vD=[2,"com.amazon.aws.codewhisperer","IntentMap",0,[0,0],[()=>pD,0]],ZD=[2,"com.amazon.aws.q.interactioncomponents","TaskActionPayload",0,[0,0],[()=>q,0]],j1=[4,"com.amazon.aws.codewhisperer","ChatMessage",0,["userInputMessage","assistantResponseMessage"],[[()=>VN,0],[()=>iN,0]]],tW=[4,"com.amazon.aws.codewhisperer","ChatResponseStream",{["streaming"]:1},["messageMetadataEvent","assistantResponseEvent","reasoningContentEvent","dryRunSucceedEvent","codeReferenceEvent","supplementaryWebLinksEvent","followupPromptEvent","codeEvent","intentsEvent","interactionComponentsEvent","toolUseEvent","toolResultEvent","metadataEvent","meteringEvent","contextUsageEvent","citationEvent","documentCitationEvent","invalidStateEvent","error"],[()=>mN,[()=>eN,0],[()=>HN,0],()=>SN,()=>uN,[()=>zN,0],[()=>IN,0],[()=>hN,0],[()=>GN,0],[()=>nD,0],[()=>KN,0],[()=>qN,0],()=>FN,()=>PN,()=>_N,[()=>oN,0],[()=>gN,0],()=>BN,[()=>D1,0]]],nW=[4,"com.amazon.aws.codewhisperer","CitationTarget",0,["location","range"],[1,()=>Q1]],sW=[4,"com.amazon.aws.codewhisperer","CursorState",0,["position","range"],[()=>Dh,()=>Qh]],rW=[4,"com.amazon.aws.codewhisperer","Diagnostic",0,["textDocumentDiagnostic","runtimeDiagnostic"],[[()=>kN,0],[()=>YN,0]]],eW=[4,"com.amazon.aws.codewhisperer","DocumentCitationLocation",0,["documentPage","documentChar","documentChunk","searchResult","web"],[()=>Nh,()=>Nh,()=>Nh,()=>EN,[()=>bN,0]]],iW=[4,"com.amazon.aws.codewhisperer","DocumentSource",8,["bytes"],[21]];var oW=[4,"com.amazon.aws.codewhisperer","ImageSource",8,["bytes"],[21]],fW=[4,"com.amazon.aws.codewhisperer","IntentDataType",0,["string"],[0]],cW=[4,"com.amazon.aws.codewhisperer","ReasoningContent",8,["reasoningText","redactedContent"],[[()=>NN,0],21]];var hW=[4,"com.amazon.aws.codewhisperer","Tool",0,["toolSpecification","cachePoint"],[[()=>CN,0],()=>xh]],uW=[4,"com.amazon.aws.codewhisperer","ToolResultContentBlock",0,["text","json"],[[()=>B,0],[()=>Yh,0]]];var p1=[9,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponse",{["http"]:["POST","/generateAssistantResponse",200]},()=>ZN,()=>tD];var td=(t)=>{return{apiVersion:"2023-11-27",base64Decoder:t?.base64Decoder??hr.fromBase64,base64Encoder:t?.base64Encoder??hr.toBase64,disableHostPrefix:t?.disableHostPrefix??!1,endpointProvider:t?.endpointProvider??H1,extensions:t?.extensions??[],httpAuthSchemeProvider:t?.httpAuthSchemeProvider??sA,httpAuthSchemes:t?.httpAuthSchemes??[{schemeId:"smithy.api#httpBearerAuth",identityProvider:(n)=>n.getIdentityProvider("smithy.api#httpBearerAuth"),signer:new Z1.HttpBearerAuthSigner}],logger:t?.logger??new Y.NoOpLogger,protocol:t?.protocol??v1.AwsRestJsonProtocol,protocolSettings:t?.protocolSettings??{defaultNamespace:"com.amazon.aws.codewhisperer.streaming",errorTypeRegistries:W1,version:"2023-11-27",serviceTarget:"AmazonCodeWhispererStreamingService"},serviceId:t?.serviceId??"CodeWhispererStreaming",urlParser:t?.urlParser??Fh.parseUrl,utf8Decoder:t?.utf8Decoder??ds.fromUtf8,utf8Encoder:t?.utf8Encoder??ds.toUtf8}};var ed=(t)=>{Y.emitWarningIfUnsupportedVersion(process.version);let n=mh.resolveDefaultsModeConfig(t),s=()=>n().then(Y.loadConfigsForDefaultMode),r=td(t);nd.emitWarningIfUnsupportedVersion(process.version);let e={profile:t?.profile,logger:r.logger};return{...r,...t,runtime:"node",defaultsMode:n,authSchemePreference:t?.authSchemePreference??Un.loadConfig(sd.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS,e),bodyLengthChecker:t?.bodyLengthChecker??Bh.calculateBodyLength,defaultUserAgentProvider:t?.defaultUserAgentProvider??un.createDefaultUserAgentProvider({serviceId:r.serviceId,clientVersion:oA.version}),eventStreamSerdeProvider:t?.eventStreamSerdeProvider??ro.eventStreamSerdeProvider,httpAuthSchemes:t?.httpAuthSchemes??[{schemeId:"smithy.api#httpBearerAuth",identityProvider:(i)=>i.getIdentityProvider("smithy.api#httpBearerAuth")||(async(f)=>{return await yh(f)(f)}),signer:new rd.HttpBearerAuthSigner}],maxAttempts:t?.maxAttempts??Un.loadConfig(V.NODE_MAX_ATTEMPT_CONFIG_OPTIONS,t),region:t?.region??Un.loadConfig(a.NODE_REGION_CONFIG_OPTIONS,{...a.NODE_REGION_CONFIG_FILE_OPTIONS,...e}),requestHandler:go.NodeHttpHandler.create(t?.requestHandler??s),retryMode:t?.retryMode??Un.loadConfig({...V.NODE_RETRY_MODE_CONFIG_OPTIONS,default:async()=>(await s()).retryMode||ot.DEFAULT_RETRY_MODE},t),sha256:t?.sha256??Gh.Hash.bind(null,"sha256"),streamCollector:t?.streamCollector??go.streamCollector,useDualstackEndpoint:t?.useDualstackEndpoint??Un.loadConfig(a.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS,e),useFipsEndpoint:t?.useFipsEndpoint??Un.loadConfig(a.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS,e),userAgentAppId:t?.userAgentAppId??Un.loadConfig(un.NODE_APP_ID_CONFIG_OPTIONS,e)}};var mt=H(kt(),1);var It=H(Tt(),1);var id=(t)=>{let{httpAuthSchemes:n,httpAuthSchemeProvider:s,token:r}=t;return{setHttpAuthScheme(e){let i=n.findIndex((f)=>f.schemeId===e.schemeId);if(i===-1)n.push(e);else n.splice(i,1,e)},httpAuthSchemes(){return n},setHttpAuthSchemeProvider(e){s=e},httpAuthSchemeProvider(){return s},setToken(e){r=e},token(){return r}}},od=(t)=>{return{httpAuthSchemes:t.httpAuthSchemes(),httpAuthSchemeProvider:t.httpAuthSchemeProvider(),token:t.token()}};var fd=(t,n)=>{let s=Object.assign(mt.getAwsRegionExtensionConfiguration(t),Y.getDefaultExtensionConfiguration(t),It.getHttpHandlerExtensionConfiguration(t),id(t));return n.forEach((r)=>r.configure(s)),Object.assign(t,mt.resolveAwsRegionExtensionConfiguration(s),Y.resolveDefaultRuntimeConfig(s),It.resolveHttpHandlerRuntimeConfig(s),od(s))};class Xh extends Y.Client{config;constructor(...[t]){let n=ed(t||{});super(n);this.initConfig=n;let s=eA(n),r=$n.resolveUserAgentConfig(s),e=V.resolveRetryConfig(r),i=a.resolveRegionConfig(e),f=Jn.resolveHostHeaderConfig(i),o=Ft.resolveEndpointConfig(f),c=Bt.resolveDefaultAwsRegionalEndpointsConfig(o),h=Gc.resolveEventStreamSerdeConfig(c),u=rA(h),l=fd(u,t?.extensions||[]);this.config=l,this.middlewareStack.use(cd.getSchemaSerdePlugin(this.config)),this.middlewareStack.use($n.getUserAgentPlugin(this.config)),this.middlewareStack.use(V.getRetryPlugin(this.config)),this.middlewareStack.use(ne.getContentLengthPlugin(this.config)),this.middlewareStack.use(Jn.getHostHeaderPlugin(this.config)),this.middlewareStack.use(Zr.getLoggerPlugin(this.config)),this.middlewareStack.use(te.getRecursionDetectionPlugin(this.config)),this.middlewareStack.use(lr.getHttpAuthSchemeEndpointRuleSetPlugin(this.config,{httpAuthSchemeParametersProvider:nA,identityProviderConfigProvider:async(_)=>new lr.DefaultIdentityProviderConfig({"smithy.api#httpBearerAuth":_.token})})),this.middlewareStack.use(lr.getHttpSigningPlugin(this.config))}destroy(){super.destroy()}}class qh extends Y.Command.classBuilder().ep(iA).m(function(t,n,s,r){return[Ft.getEndpointPlugin(s,t.getEndpointParameterInstructions())]}).s("AmazonCodeWhispererStreamingService","GenerateAssistantResponse",{eventStream:{output:!0}}).n("CodeWhispererStreamingClient","GenerateAssistantResponseCommand").sc(p1).build(){}function hd(t){let n=Ir[t];if(!n)throw Error(`Unsupported model: ${t}. Supported models: ${zu.join(", ")}`);return n}var ud=new Set(["claude-opus-4-8","claude-opus-4-7","claude-sonnet-5","claude-sonnet-4-6","gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"]),ld=["low","medium","high","xhigh","max"];function Eo(t){for(let n of ld){let s=`-${n}`;if(t.endsWith(s)){let r=t.slice(0,-s.length);if(ud.has(r))return{wireId:hd(r),effort:n}}}return{wireId:hd(t),effort:void 0}}function lW(t){for(let n of ld){let s=`-${n}`;if(t.endsWith(s)){let r=t.slice(0,-s.length);if(ud.has(r))return r}}if(t.endsWith("-thinking")){let n=t.slice(0,-9);if(Ir[n])return n}return t}function _d(t){return G(lW(t))}var _W=["low","medium","high","xhigh","max"];function wW(t){return typeof t==="string"&&_W.some((n)=>n===t)}var wd=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"]),Ad=new Set(["claude-opus-4.7","claude-opus-4.8","claude-sonnet-5",...wd]),AW=new Set(["claude-opus-4.5","claude-opus-4.6","claude-opus-4.6-1m","claude-sonnet-4.5","claude-sonnet-4.5-1m","claude-sonnet-4.6","claude-sonnet-4.6-1m",...Ad]);function Ro(t){return AW.has(t)}function MW(t){return Ad.has(t)}function Md(t,n){if(wd.has(t))return{reasoning:{effort:n}};return{output_config:{effort:n}}}function dW(t,n){if(!Ro(t))return;if(n==="xhigh"&&!MW(t))return"max";return n}function gW(t,n){if(!Ro(n))return;let s;if(t<=1e4)s="low";else if(t<=20000)s="medium";else if(t<=28000)s="high";else s="max";return s}function dd(t){let n;if(Ro(t.model))n={wireId:t.model,effort:void 0};else try{n=Eo(t.model)}catch(r){if(r instanceof Error&&r.message.startsWith("Unsupported model:"))return;throw r}if(!Ro(n.wireId))return;let s=[n.effort,t.reasoningEffort,t.configEffort];for(let r of s)if(wW(r))return dW(n.wireId,r);if(!t.think)return;if(t.autoEffortMapping??!0)return gW(t.budget,n.wireId);return"medium"}import{randomUUID as $W}from"crypto";function we(t){return typeof t==="object"&&t!==null}function EW(t){let n=atob(t),s=new Uint8Array(n.length);for(let r=0;r<n.length;r++)s[r]=n.charCodeAt(r);return s}function RW(t){let n=[];for(let s of t){if(!we(s)||s.type!=="image"||!we(s.source))continue;let r=s.source;if(r.type!=="base64"||typeof r.data!=="string")continue;n.push({mediaType:typeof r.media_type==="string"?r.media_type:"image/jpeg",data:r.data})}return n}function bW(t){let n=[];for(let s of t){if(!we(s)||s.type!=="image_url"||!we(s.image_url))continue;let r=s.image_url.url;if(typeof r!=="string"||!r.startsWith("data:"))continue;let[e="",i]=r.split(",",2);if(!i)continue;let f=e.split(";")[0]?.replace("data:","");n.push({mediaType:f||"image/jpeg",data:i})}return n}function bo(t){if(!Array.isArray(t))return[];return[...RW(t),...bW(t)]}function To(t){let n=[],s=0;for(let r of t){if(n.length>=4)break;if(s+r.data.length>3750000)break;n.push(r),s+=r.data.length}return{images:n.map((r)=>({format:r.mediaType.split("/")[1]||"png",source:{bytes:EW(r.data)}})),omitted:t.length-n.length}}function So(t){let n=[];for(let s of t){if(!we(s))continue;if(typeof s.text==="string")n.push(s.text);else if(s.type==="text"&&s.text)n.push(String(s.text))}return n.join("")}function Ch(t){return typeof t==="object"&&t!==null}function gd(t,n){for(let s of t){if(s.role!=="assistant")continue;if(s.tool_calls){for(let r of s.tool_calls)if(r.id===n)return r}if(Array.isArray(s.content)){for(let r of s.content)if(Ch(r)&&r.type==="tool_use"&&r.id===n)return r}}return null}function Ed(t){let n=[];for(let s of t){if(n.length===0){n.push({...s});continue}let r=n[n.length-1];if(!r||s.role!==r.role){n.push({...s});continue}if(Array.isArray(r.content)&&Array.isArray(s.content))r.content.push(...s.content);else if(typeof r.content==="string"&&typeof s.content==="string")r.content+=`
|
|
109
|
+
${s.content}`;else if(Array.isArray(r.content)&&typeof s.content==="string")r.content.push({type:"text",text:s.content});else if(typeof r.content==="string"&&Array.isArray(s.content))r.content=[{type:"text",text:r.content},...s.content];if(s.tool_calls){if(!r.tool_calls)r.tool_calls=[];r.tool_calls.push(...s.tool_calls)}if(s.role==="tool"){if(!r.tool_results)r.tool_results=[{content:r.content,tool_call_id:r.tool_call_id}];r.tool_results.push({content:s.content,tool_call_id:s.tool_call_id})}}return n}function Ot(t){if(t===null||t===void 0)return"";if(typeof t==="string")return t;if(!Ch(t))return"";if(typeof t.content==="string")return t.content;if(Array.isArray(t.content))return t.content.filter((n)=>Ch(n)&&n.type==="text").map((n)=>typeof n.text==="string"?n.text:"").join("");return typeof t.text==="string"?t.text:""}function Rd(t){return t.map((n)=>({toolSpecification:{name:n.name||n.function?.name,description:(n.description||n.function?.description||"").substring(0,9216),inputSchema:{json:n.input_schema||n.function?.parameters||{}}}}))}function Ae(t){let n=[],s=new Set;for(let r of t)if(!s.has(r.toolUseId))s.add(r.toolUseId),n.push(r);return n}function bd(t){return typeof t==="object"&&t!==null}function TW(t){let n=t.function?.arguments;return{input:typeof n==="string"?JSON.parse(n):n,name:t.function?.name??"",toolUseId:t.id??""}}function SW(t){if(t.length<4)return t;let n=[],s=0;while(s<t.length){let r=t[s];if(r?.assistantResponseMessage?.toolUses&&s+1<t.length&&t[s+1]?.userInputMessage?.userInputMessageContext?.toolResults){let e=s,i=s;while(i<t.length){let o=t[i],c=i+1<t.length?t[i+1]:void 0;if(!o?.assistantResponseMessage?.toolUses||!c?.userInputMessage?.userInputMessageContext?.toolResults)break;i+=2}let f=(i-e)/2;for(let o=e;o<i;o+=2){let c=t[o],h=t[o+1];if(!c||!h)continue;if(f>1&&o!==e)n.push({assistantResponseMessage:{content:"[system: tool calling continues]",toolUses:c.assistantResponseMessage?.toolUses}});else n.push(c);n.push(h)}s=i}else{if(r)n.push(r);s++}}return n}function Td(t,n){let s=[];for(let r=0;r<t.length-1;r++){let e=t[r];if(!e)continue;if(e.role==="user"){let h={content:"",modelId:n,origin:st.ORIGIN_AI_EDITOR},u=[];if(Array.isArray(e.content)){h.content=So(e.content);for(let _ of e.content){if(!bd(_)||_.type!=="tool_result"||typeof _.tool_use_id!=="string")continue;u.push({content:[{text:Ot(_.content??_)}],status:"success",toolUseId:_.tool_use_id})}let l=bo(e.content);if(l.length>0){let _=To(l);if(h.images=_.images,_.omitted>0)h.content+=`
|
|
110
|
+
|
|
111
|
+
[${_.omitted} image(s) omitted due to API limits]`}}else h.content=Ot(e);if(u.length>0)h.userInputMessageContext={toolResults:Ae(u)};if(s[s.length-1]?.userInputMessage)s.push({assistantResponseMessage:{content:"[system: conversation continues]"}});s.push({userInputMessage:h});continue}if(e.role==="tool"){let h=[];if(e.tool_results)for(let u of e.tool_results){if(!u.tool_call_id)continue;h.push({content:[{text:Ot(u)}],status:"success",toolUseId:u.tool_call_id})}else if(e.tool_call_id)h.push({content:[{text:Ot(e)}],status:"success",toolUseId:e.tool_call_id});if(s[s.length-1]?.userInputMessage)s.push({assistantResponseMessage:{content:"[system: conversation continues]"}});s.push({userInputMessage:{content:"Tool results provided.",modelId:n,origin:st.ORIGIN_AI_EDITOR,userInputMessageContext:{toolResults:Ae(h)}}});continue}if(e.role!=="assistant")continue;let i={content:""},f=[],o="";if(Array.isArray(e.content))for(let h of e.content){if(!bd(h))continue;if(h.type==="text")i.content+=typeof h.text==="string"?h.text:"";else if(h.type==="thinking")o+=typeof h.thinking==="string"?h.thinking:typeof h.text==="string"?h.text:"";else if(h.type==="tool_use"&&typeof h.id==="string"&&typeof h.name==="string")f.push({input:h.input,name:h.name,toolUseId:h.id})}else i.content=Ot(e);if(e.tool_calls)for(let h of e.tool_calls)f.push(TW(h));if(o)i.content=i.content?`<thinking>${o}</thinking>
|
|
112
|
+
|
|
113
|
+
${i.content}`:`<thinking>${o}</thinking>`;if(f.length>0)i.toolUses=f;if(!i.content&&!i.toolUses)continue;let c=s[s.length-1]?.assistantResponseMessage;if(c){if(i.content)c.content=c.content?`${c.content}
|
|
114
|
+
|
|
115
|
+
${i.content}`:i.content;if(i.toolUses)c.toolUses=[...c.toolUses??[],...i.toolUses]}else s.push({assistantResponseMessage:i})}return SW(s)}function Sd(t,n,s){if(!n)return t;let r=t.find((e)=>e.userInputMessage);if(r?.userInputMessage)r.userInputMessage.content=`${n}
|
|
116
|
+
|
|
117
|
+
${r.userInputMessage.content||""}`;else t.unshift({userInputMessage:{content:n,modelId:s,origin:st.ORIGIN_AI_EDITOR}});return t}function $d(t){return t.some((n)=>Boolean(n.assistantResponseMessage?.toolUses)||Boolean(n.userInputMessage?.userInputMessageContext?.toolResults))}function Ud(t){let n=new Set;for(let s of t)for(let r of s.assistantResponseMessage?.toolUses??[])if(r.name)n.add(r.name);return n}function _n(t){return typeof t==="object"&&t!==null}function UW(t){return _n(t)}function LW(t){return _n(t)}function IW(t){let n=typeof t==="string"?JSON.parse(t):t;if(!_n(n))return{messages:[],tools:[],system:""};return{messages:Array.isArray(n.messages)?n.messages.filter(UW):[],tools:Array.isArray(n.tools)?n.tools.filter(LW):[],system:typeof n.system==="string"?n.system:""}}function OW(t){if(Array.isArray(t))return"array";if(t===null)return"string";let n=typeof t;return n==="number"||n==="boolean"||n==="string"||n==="object"?n:"string"}function yW(t,n){let s=n?.find((i)=>i.name===t&&_n(i.input)),r={};if(s&&_n(s.input))for(let[i,f]of Object.entries(s.input))r[i]={type:OW(f)};let e=Object.keys(r).length>0?{type:"object",properties:r}:{type:"object"};return{toolSpecification:{name:t,description:`Tool ${t}`,inputSchema:{json:e}}}}function GW(t,n){let s={content:""},r=[],e="";if(Array.isArray(n.content))for(let i of n.content){if(!_n(i))continue;if(i.type==="text"&&typeof i.text==="string")s.content+=i.text;else if(i.type==="thinking")e+=typeof i.thinking==="string"?i.thinking:typeof i.text==="string"?i.text:"";else if(i.type==="tool_use"&&typeof i.id==="string"&&typeof i.name==="string")r.push({input:i.input,name:i.name,toolUseId:i.id})}else s.content=Ot(n);for(let i of n.tool_calls??[]){if(typeof i.id!=="string"||typeof i.function?.name!=="string")continue;let f=i.function.arguments;r.push({input:typeof f==="string"?JSON.parse(f):f,name:i.function.name,toolUseId:i.id})}if(e)s.content=s.content?`<thinking>${e}</thinking>
|
|
118
|
+
|
|
119
|
+
${s.content}`:`<thinking>${e}</thinking>`;if(r.length>0)s.toolUses=r;if(s.content||s.toolUses)t.push({assistantResponseMessage:s})}function BW(t){let n="",s=[],r=[];if(t.role==="tool"){let e=t.tool_results??[{content:t.content,tool_call_id:t.tool_call_id}];for(let i of e){if(typeof i.tool_call_id!=="string")continue;s.push({content:[{text:Ot(i)}],status:"success",toolUseId:i.tool_call_id})}}else if(Array.isArray(t.content)){n=So(t.content);for(let i of t.content){if(!_n(i)||i.type!=="tool_result"||typeof i.tool_use_id!=="string")continue;s.push({content:[{text:Ot(i.content??i)}],status:"success",toolUseId:i.tool_use_id})}let e=To(bo(t.content));if(r.push(...e.images),e.omitted>0)n+=`
|
|
120
|
+
|
|
121
|
+
[${e.omitted} image(s) omitted due to API limits]`}else n=Ot(t);if(!n)n=s.length>0?"Tool results provided.":"[system: conversation continues]";return{content:n,toolResults:s,images:r}}function mW(t,n){let s=gd(t,n.toolUseId);if(!_n(s))return;let r=_n(s.function)?s.function:void 0,e=typeof s.name==="string"?s.name:typeof r?.name==="string"?r.name:"tool",i=s.input??r?.arguments;return{name:e,toolUseId:n.toolUseId,input:typeof i==="string"?JSON.parse(i):i??{}}}function Ld(t,n,s,r=!1,e=20000){let i=IW(t);if(i.messages.length===0)throw Error("No messages");let{wireId:f,effort:o}=Eo(n),c=i.messages.filter((U)=>U.role==="system"),h=Ed(i.messages.filter((U)=>U.role!=="system")),u=i.system,l=c.map(Ot).join(`
|
|
122
|
+
|
|
123
|
+
`);if(l)u=u?`${u}
|
|
124
|
+
|
|
125
|
+
${l}`:l;if(r&&!u.includes("<thinking_mode>")){let U=`<thinking_mode>enabled</thinking_mode><max_thinking_length>${e}</max_thinking_length>`;u=u?`${U}
|
|
126
|
+
${u}`:U}let _=h.at(-1);if(_?.role==="assistant"&&Ot(_)==="{")h.pop();let w=h.at(-1);if(!w)throw Error("Empty");let A=Td(h,f),M=w.role==="user"&&!(Array.isArray(w.content)&&w.content.some((U)=>_n(U)&&U.type==="tool_result")),d=h.at(-2);if(M&&d?.role==="assistant"&&A.at(-1)?.userInputMessage){let U=Ot(d);if(U)A.push({assistantResponseMessage:{content:U}})}A=Sd(A,u,f);let E="[system: conversation continues]",b=[],L=[];if(w.role==="assistant")GW(A,w);else{if(A.at(-1)&&!A.at(-1)?.assistantResponseMessage)A.push({assistantResponseMessage:{content:"[system: conversation continues]"}});let U=BW(w);E=U.content,b=U.toolResults,L=U.images}let S=A.flatMap((U)=>U.assistantResponseMessage?.toolUses??[]),O=new Set(S.map((U)=>U.toolUseId)),x=[],X=[];for(let U of b)if(O.has(U.toolUseId))x.push(U);else{let z=mW(i.messages,U);if(z)X.push({call:z,result:U});else E+=`
|
|
127
|
+
|
|
128
|
+
[Output for tool call ${U.toolUseId}]:
|
|
129
|
+
${U.content[0]?.text??""}`}if(X.length>0){if(!A.at(-1)||A.at(-1)?.assistantResponseMessage)A.push({userInputMessage:{content:"Running tools...",modelId:f,origin:st.ORIGIN_AI_EDITOR}});A.push({assistantResponseMessage:{content:"I will execute the following tools.",toolUses:X.map(({call:U})=>U)}}),x.push(...X.map(({result:U})=>U))}let v={content:E,modelId:f,origin:st.ORIGIN_AI_EDITOR};if(L.length>0)v.images=L;let Q=Rd(i.tools).filter((U)=>typeof U.toolSpecification.name==="string").map((U)=>({toolSpecification:{...U.toolSpecification,name:U.toolSpecification.name??""}}));if(x.length>0||Q.length>0){if(v.userInputMessageContext={},x.length>0)v.userInputMessageContext.toolResults=Ae(x);if(Q.length>0)v.userInputMessageContext.tools=Q}if($d(A)){let U=v.userInputMessageContext?.tools??[],z=new Set(U.map((an)=>an.toolSpecification.name)),Gt=[...Ud(A)].filter((an)=>!z.has(an));if(Gt.length>0)v.userInputMessageContext??={},v.userInputMessageContext.tools=[...U,...Gt.map((an)=>yW(an,S))]}let rt=$W(),Dt={conversationState:{chatTriggerType:st.CHAT_TRIGGER_TYPE_MANUAL,conversationId:rt,currentMessage:{userInputMessage:v},...A.length>0?{history:A}:{}},...s.profileArn?{profileArn:s.profileArn}:{}};return o===void 0?{request:Dt,resolved:f,convId:rt}:{request:Dt,resolved:f,convId:rt,variantEffort:o}}function FW(t){let n=typeof t==="string"?JSON.parse(t):t;if(typeof n!=="object"||n===null||!("reasoning_effort"in n))return;let s=n.reasoning_effort;return typeof s==="string"||s===null?s:void 0}function Id(t,n,s,r=!1,e=20000,i){let{request:f,resolved:o,convId:c}=Ld(t,n,s,r,e),h=dd({model:n,think:r,budget:e,reasoningEffort:FW(t),configEffort:i?.effort,autoEffortMapping:i?.autoEffortMapping});return{conversationState:f.conversationState,...f.profileArn?{profileArn:f.profileArn}:{},streaming:!0,effectiveModel:o,conversationId:c,region:Ju(s.profileArn)??s.region,...h?{effort:h}:{}}}function Od(t){return Math.ceil(t.length/4)}async function $o(t,n){if(n?.aborted)return{kind:"aborted"};let s=t.next();if(!n)return{kind:"event",result:await s};return new Promise((r,e)=>{let i=()=>r({kind:"aborted"});n.addEventListener("abort",i,{once:!0}),s.then((f)=>{n.removeEventListener("abort",i),r({kind:"event",result:f})},(f)=>{n.removeEventListener("abort",i),e(f)})})}function Me(t,n){if(!n?.name||!n.toolUseId)return;let s=t.get(n.toolUseId);if(s){s.input+=n.input??"";return}t.set(n.toolUseId,{toolUseId:n.toolUseId,name:n.name,input:n.input??""})}function yd(t){let n=[],s=0;for(let r of t.values()){let e=r.input;try{e=JSON.stringify(JSON.parse(r.input))}catch{e=r.input}n.push({type:"content_block_start",index:s,content_block:{type:"tool_use",id:r.toolUseId,name:r.name,input:{}}},{type:"content_block_delta",index:s,delta:{type:"input_json_delta",partial_json:e}},{type:"content_block_stop",index:s}),s+=1}return n}function Uo(t,n){let s=n.metadataEvent?.tokenUsage;if(s)t.outputTokens=s.outputTokens??t.outputTokens,t.totalTokens=s.totalTokens??t.totalTokens,t.inputTokens=s.inputTokens??(s.uncachedInputTokens===void 0?t.inputTokens:s.uncachedInputTokens+(s.cacheReadInputTokens??0)+(s.cacheWriteInputTokens??0));t.contextUsagePercentage=n.contextUsageEvent?.contextUsagePercentage??n.metadataEvent?.contextUsagePercentage??s?.contextUsagePercentage??t.contextUsagePercentage}function Lo(t,n,s){let r=t.outputTokens??Od(n),e=t.inputTokens;if(e===void 0&&t.totalTokens!==void 0)e=Math.max(0,t.totalTokens-r);if(e===void 0&&t.contextUsagePercentage!==void 0&&t.contextUsagePercentage>0){let i=Math.round(_d(s)*t.contextUsagePercentage/100);e=Math.max(0,i-r)}return{inputTokens:e??0,outputTokens:r}}class Gd extends Error{name="MissingSdkEventStreamError";constructor(){super("SDK response has no event stream")}}async function Bd(t,n,s,r){let e=t.generateAssistantResponseResponse;if(!e)throw new Gd;let i=e[Symbol.asyncIterator](),f=new Map,o={},c="",h="",u=!1,l=!1;try{while(!0){let A=await $o(i,r);if(A.kind==="aborted"){if(i.return)await i.return();l=!0;break}if(A.result.done){u=!0;break}let M=A.result.value;Uo(o,M),h+=M.reasoningContentEvent?.text??"",c+=M.assistantResponseEvent?.content??"",Me(f,M.toolUseEvent)}}finally{if(!u&&!l&&i.return)await i.return()}let _=Lo(o,c,n),w={role:"assistant",content:c,...h?{reasoning_content:h}:{},...f.size>0?{tool_calls:Array.from(f.values(),(A)=>({id:A.toolUseId,type:"function",function:{name:A.name,arguments:A.input}}))}:{}};return{id:s,object:"chat.completion",created:Math.floor(Date.now()/1000),model:n,choices:[{index:0,message:w,finish_reason:f.size>0?"tool_calls":"stop"}],usage:{prompt_tokens:_.inputTokens,completion_tokens:_.outputTokens,total_tokens:_.inputTokens+_.outputTokens}}}var PW=[/input is too long/i,/CONTENT_LENGTH_EXCEEDS_THRESHOLD/i],HW=/econnreset|etimedout|enotfound|network|fetch failed|socket/i;function Io(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function ah(t,n){let s=t[n];return typeof s==="string"?s:void 0}function NW(t){let n=t.$metadata;if(!Io(n))return;let s=n.httpStatusCode;return typeof s==="number"?s:void 0}function DW(t){let n=t.$response;if(!Io(n))return;let s=n.headers;if(!Io(s))return;let r={};for(let[e,i]of Object.entries(s))if(typeof i==="string")r[e]=i;else if(typeof i==="number")r[e]=String(i);return Object.keys(r).length>0?r:void 0}function Kh(t){if(!Io(t))return{message:t instanceof Error?t.message:String(t)};let n=NW(t),s=ah(t,"message")??String(t),r=ah(t,"name"),e=ah(t,"reason"),i=DW(t);return{message:s,...n!==void 0?{status:n}:{},...r!==void 0?{code:r}:{},...e!==void 0?{reason:e}:{},...i!==void 0?{headers:i}:{}}}function WW(t){let n=Object.entries(t??{}).find(([r])=>r.toLowerCase()==="retry-after"),s=Number.parseInt(n?.[1]??"60",10);return Number.isFinite(s)&&s>=0?s*1000:60000}function YW(t){return PW.some((n)=>n.test(t))}function md(t,n){if(t.reason==="INVALID_MODEL_ID"){let s=t.status??400;return{action:"fail",status:s,terminalStatus:s}}if(t.reason==="TEMPORARILY_SUSPENDED")return n.accountCount>1?{action:"switch",...t.status!==void 0?{status:t.status}:{}}:{action:"fail",...t.status!==void 0?{status:t.status}:{},terminalStatus:t.status??403};switch(t.status){case 400:return{action:"fail",status:400,terminalStatus:YW(t.message)?413:400};case 401:return n.retryCount<n.maxRetries?{action:"retry",status:401}:{action:"fail",status:401,terminalStatus:401};case 402:return{action:"fail",status:402,terminalStatus:402};case 403:if(Le(t.message)){if(!n.forcedRefreshAccountIds.has(n.accountId))return n.forcedRefreshAccountIds.add(n.accountId),{action:"refresh-then-retry",status:403};return n.accountCount>1?{action:"switch",status:403}:{action:"fail",status:403,terminalStatus:403}}if(n.accountCount>1)return{action:"switch",status:403};return n.retryCount<n.maxRetries?{action:"retry",status:403,retryAfterMs:n.retryDelayMs*2**n.retryCount}:{action:"fail",status:403,terminalStatus:403};case 429:{let s=WW(t.headers);return n.accountCount>1?{action:"switch",status:429,retryAfterMs:s}:{action:"retry",status:429,retryAfterMs:s}}case 500:return n.serverErrorCount<5?{action:"retry",status:500,retryAfterMs:1000*2**Math.max(0,n.serverErrorCount-1)}:{action:"switch",status:500};case void 0:if(HW.test(t.message))return n.retryCount<n.maxRetries?{action:"retry",retryAfterMs:n.retryDelayMs*2**n.retryCount}:{action:"fail",terminalStatus:500};return{action:"fail",terminalStatus:500};default:return{action:"fail",status:t.status,terminalStatus:t.status}}}var Fd=Promise.resolve();function Ln(t){return t.reason instanceof Error?t.reason:new DOMException("The request was aborted","AbortError")}function _r(t,n){if(n.aborted)return Promise.reject(Ln(n));return new Promise((s,r)=>{let e=()=>r(Ln(n));n.addEventListener("abort",e,{once:!0}),t.then((i)=>{n.removeEventListener("abort",e),s(i)},(i)=>{n.removeEventListener("abort",e),r(i)})})}function Pd(t,n){if(t<=0)return Promise.resolve();return _r(Bun.sleep(t),n)}async function Hd(t){let n=Fd,s,r=new Promise((f)=>{s=f});if(!s)throw TypeError("Queue release was not initialized");let e=s;Fd=n.catch(()=>{return}).then(()=>r);try{await _r(n,t)}catch(f){throw e(),f}let i=!1;return()=>{if(i)return;i=!0,e()}}function Nd(t,n){if(t)return{signal:t,dispose:()=>{return}};let s=new AbortController,r=setTimeout(()=>s.abort(new DOMException("Request deadline exceeded","TimeoutError")),n);return{signal:s.signal,dispose:()=>clearTimeout(r)}}var de="<\uFF5CDSML\uFF5Cfunction_calls";function Vh(){return`tool_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}function xW(t){let n=[],s=/```[\s\S]*?```/g;for(let i=s.exec(t);i!==null;i=s.exec(t))n.push([i.index,i.index+i[0].length]);let r=(i)=>n.some(([f,o])=>i>=f&&i<o),e=/`[^`\n]+`/g;for(let i=e.exec(t);i!==null;i=e.exec(t))if(!r(i.index))n.push([i.index,i.index+i[0].length]);return n}function Es(t,n,s){return s.some(([r,e])=>t<e&&n>r)}function QW(t){let n={},s=/<parameter\s+name="([^"]+)"\s*>([\s\S]*?)<\/parameter>/g;for(let r=s.exec(t);r!==null;r=s.exec(t)){let e=r[1];if(e===void 0)continue;let i=r[2]??"";try{n[e]=JSON.parse(i)}catch{n[e]=i}}return n}function Dd(t,n){return{toolUseId:Vh(),name:t,input:QW(n)}}function JW(t,n,s){let r=[],e=/<function_calls>[\s\S]*?<\/function_calls>/g;for(let f=e.exec(t);f!==null;f=e.exec(t)){let o=f.index,c=o+f[0].length;if(Es(o,c,n))continue;let h=/<invoke\s+name="([^"]+)"\s*>([\s\S]*?)<\/invoke>/g,u=[];for(let l=h.exec(f[0]);l!==null;l=h.exec(f[0])){let _=l[1];if(_)u.push(Dd(_,l[2]??""))}if(u.length===0)continue;r.push({start:o,end:c,toolCalls:u}),s.push([o,c])}let i=/<invoke\s+name="([^"]+)"\s*>([\s\S]*?)<\/invoke>/g;for(let f=i.exec(t);f!==null;f=i.exec(t)){let o=f.index,c=o+f[0].length,h=f[1];if(!h||Es(o,c,n)||Es(o,c,s))continue;r.push({start:o,end:c,toolCalls:[Dd(h,f[2]??"")]}),s.push([o,c])}return r}function zW(t,n,s){let r=[],e=0;for(;;){let i=t.indexOf(de,e);if(i===-1)break;let f=t.slice(i+de.length),o=/<\uFF5C[^>]*?end[^>]*?>|<\/\uFF5CDSML[^>]*?>/.exec(f),c=o!==null?i+de.length+o.index+o[0].length:t.length;if(e=c,Es(i,c,n)||Es(i,c,s))continue;let h=t.slice(i,c),u=[],l=/name["\uFF5C=:\s]+["']?([A-Za-z0-9_]+)/.exec(h),_=/(\{[\s\S]*\})/.exec(h);if(l?.[1]&&_?.[1])try{u.push({toolUseId:Vh(),name:l[1],input:JSON.parse(_[1])})}catch{}r.push({start:i,end:c,toolCalls:u}),s.push([i,c])}return r}function kW(t,n,s){let r=[],e=/\[Called\s+(\w+)\s+with\s+args:\s*(\{[^}]*(?:\{[^}]*\}[^}]*)*\})\]/gs;for(let i=e.exec(t);i!==null;i=e.exec(t)){let f=i.index,o=f+i[0].length,c=i[1],h=i[2];if(!c||!h||Es(f,o,n)||Es(f,o,s))continue;let u;try{u=JSON.parse(h)}catch{continue}r.push({start:f,end:o,toolCalls:[{toolUseId:Vh(),name:c,input:u}]}),s.push([f,o])}return r}function Wd(t){if(!t)return{toolCalls:[],cleanedText:t};let n=xW(t),s=[],r=[...JW(t,n,s),...zW(t,n,s),...kW(t,n,s)];if(r.length===0)return{toolCalls:[],cleanedText:t};r.sort((o,c)=>o.start-c.start);let e=[],i="",f=0;for(let o of r){if(o.start<f)continue;i+=t.slice(f,o.start),f=o.end,e.push(...o.toolCalls)}return i+=t.slice(f),{toolCalls:e,cleanedText:i}}var jh=["<function_calls","<invoke name=",de],XW=Math.max(...jh.map((t)=>t.length));function Yd(t){let n=-1;for(let s of jh){let r=t.indexOf(s);if(r!==-1&&(n===-1||r<n))n=r}return n}function qW(t){let n=Math.min(t.length,XW-1);for(let s=n;s>0;s--){let r=t.slice(t.length-s);for(let e of jh)if(e.length>s&&e.startsWith(r))return s}return 0}class ph{accumulated="";emitted=0;markerSeen=!1;push(t){if(!t)return"";if(this.accumulated+=t,!this.markerSeen&&Yd(this.accumulated)!==-1)this.markerSeen=!0;let n;if(this.markerSeen){let r=Yd(this.accumulated);n=r===-1?this.accumulated.length:r}else n=this.accumulated.length-qW(this.accumulated);if(n<=this.emitted)return"";let s=this.accumulated.slice(this.emitted,n);return this.emitted=n,s}get suppressing(){return this.markerSeen}finalize(){let{toolCalls:t,cleanedText:n}=Wd(this.accumulated),s=n.length>this.emitted?n.slice(this.emitted):"";return{toolCalls:t,remainderText:s}}}function vh(t,n,s){let r=[];if(t.type==="content_block_delta"){if(t.delta?.type==="text_delta")r.push({index:0,delta:{content:t.delta.text??""},finish_reason:null});else if(t.delta?.type==="thinking_delta"){if(t.delta.thinking)r.push({index:0,delta:{reasoning_content:t.delta.thinking},finish_reason:null})}else if(t.delta?.type==="input_json_delta")r.push({index:0,delta:{tool_calls:[{index:t.index,function:{arguments:t.delta.partial_json??""}}]},finish_reason:null})}else if(t.type==="content_block_start"&&t.content_block?.type==="tool_use")r.push({index:0,delta:{tool_calls:[{index:t.index,id:t.content_block.id,type:"function",function:{name:t.content_block.name,arguments:""}}]},finish_reason:null});else if(t.type==="message_delta")r.push({index:0,delta:{},finish_reason:t.delta?.stop_reason==="tool_use"?"tool_calls":"stop"});else return null;if(r.length===0)return null;let e={id:n,object:"chat.completion.chunk",created:Math.floor(Date.now()/1000),model:s,choices:r};if(t.type!=="message_delta")return e;let i=t.usage?.input_tokens??0,f=t.usage?.output_tokens??0;return{...e,usage:{prompt_tokens:i,completion_tokens:f,total_tokens:i+f}}}function Zh(t,n){let s=/```[\s\S]*?```/g,r=[],e=s.exec(t);while(e!==null)r.push([e.index,e.index+e[0].length]),e=s.exec(t);let i=t.indexOf(n,0);while(i!==-1){if(!r.some(([o,c])=>i>=o&&i<c))return i;i=t.indexOf(n,i+n.length)}return-1}function xd(t,n){if(t==="thinking"){if(n.thinkingBlockIndex!==null)return[];let r=n.nextBlockIndex++;return n.thinkingBlockIndex=r,[{type:"content_block_start",index:r,content_block:{type:"thinking",thinking:""}}]}if(n.textBlockIndex!==null)return[];let s=n.nextBlockIndex++;return n.textBlockIndex=s,[{type:"content_block_start",index:s,content_block:{type:"text",text:""}}]}function Rs(t,n){if(t===null||n.stoppedBlocks.has(t))return[];return n.stoppedBlocks.add(t),[{type:"content_block_stop",index:t}]}function qn(t,n){if(!t)return[];let s=xd("text",n),r=n.textBlockIndex;if(r===null)return s;return s.push({type:"content_block_delta",index:r,delta:{type:"text_delta",text:t}}),s}function Cn(t,n){let s=xd("thinking",n),r=n.thinkingBlockIndex;if(r===null)return s;return s.push({type:"content_block_delta",index:r,delta:{type:"thinking_delta",thinking:t}}),s}var Oo="<thinking>",yo="</thinking>";function Qd(t,n){n.buffer+=t;let s=[];while(n.buffer.length>0){if(!n.inThinking&&!n.thinkingExtracted){let e=Zh(n.buffer,Oo);if(e!==-1){let f=n.buffer.slice(0,e);s.push(...qn(f,n)),n.buffer=n.buffer.slice(e+Oo.length),n.inThinking=!0;continue}let i=Math.max(0,n.buffer.length-Oo.length);if(i>0)s.push(...qn(n.buffer.slice(0,i),n)),n.buffer=n.buffer.slice(i);break}if(n.inThinking){let e=Zh(n.buffer,yo);if(e!==-1){if(s.push(...Cn(n.buffer.slice(0,e),n)),n.buffer=n.buffer.slice(e+yo.length),n.inThinking=!1,n.thinkingExtracted=!0,s.push(...Cn("",n)),s.push(...Rs(n.thinkingBlockIndex,n)),n.buffer.startsWith(`
|
|
130
|
+
|
|
131
|
+
`))n.buffer=n.buffer.slice(2);continue}let i=Math.max(0,n.buffer.length-yo.length);if(i>0)s.push(...Cn(n.buffer.slice(0,i),n)),n.buffer=n.buffer.slice(i);break}let r=n.buffer;n.buffer="",s.push(...qn(r,n))}return s}function Jd(t){if(!t.buffer)return[];let n=t.buffer;if(t.buffer="",!t.inThinking)return qn(n,t);return[...Cn(n,t),...Cn("",t),...Rs(t.thinkingBlockIndex,t)]}class zd extends Error{name="MissingSdkEventStreamError";constructor(){super("SDK response has no event stream")}}async function*kd(t,n,s,r){let e=t.generateAssistantResponseResponse;if(!e)throw new zd;let i={thinkingRequested:!0,buffer:"",inThinking:!1,thinkingExtracted:!1,thinkingBlockIndex:null,textBlockIndex:null,nextBlockIndex:0,stoppedBlocks:new Set},f=new ph,o=new Map,c={},h=e[Symbol.asyncIterator](),u="",l=!1,_=!1,w=!1,A=!1,M=(S,O=!1)=>{if(O&&S.type==="content_block_delta"&&S.delta?.type==="text_delta"){let x=f.push(S.delta.text??"");if(!x)return null;return vh({...S,delta:{...S.delta,text:x}},s,n)}return vh(S,s,n)};try{while(!0){let S=await $o(h,r);if(S.kind==="aborted"){if(h.return)await h.return();A=!0;return}if(S.result.done){w=!0;break}let O=S.result.value;Uo(c,O);let x=O.reasoningContentEvent?.text;if(x){if(_)i.thinkingBlockIndex=null,_=!1;l=!0;for(let v of Cn(x,i)){let Q=M(v);if(Q)yield Q}continue}let X=O.assistantResponseEvent?.content;if(X){if(u+=X,l&&!_){for(let Q of Rs(i.thinkingBlockIndex,i)){let rt=M(Q);if(rt)yield rt}_=!0}let v=l?qn(X,i):Qd(X,i);for(let Q of v){let rt=M(Q,!0);if(rt)yield rt}continue}if(O.toolUseEvent)Me(o,O.toolUseEvent)}}finally{if(!w&&!A&&h.return)await h.return()}if(l&&!_)for(let S of Rs(i.thinkingBlockIndex,i)){let O=M(S);if(O)yield O}for(let S of Jd(i)){let O=M(S,S.delta?.type==="text_delta");if(O)yield O}let{toolCalls:d,remainderText:E}=f.finalize();for(let S of qn(E,i)){let O=M(S);if(O)yield O}for(let S of Rs(i.textBlockIndex,i)){let O=M(S);if(O)yield O}for(let S of d)Me(o,{toolUseId:S.toolUseId,name:S.name,input:typeof S.input==="string"?S.input:JSON.stringify(S.input),stop:!0});for(let S of yd(o)){let O=M(S);if(O)yield O}let b=Lo(c,u,n),L=M({type:"message_delta",delta:{type:"message_delta",stop_reason:o.size>0?"tool_use":"end_turn"},usage:{input_tokens:b.inputTokens,output_tokens:b.outputTokens,cache_creation_input_tokens:0,cache_read_input_tokens:0}});if(L)yield L;M({type:"message_stop"})}class Xd extends Error{timeoutMs;name="StreamIdleTimeoutError";constructor(t){super(`SDK stream idle timeout after ${t}ms`);this.timeoutMs=t}}function qd(t,n,s,r){let e=new AbortController,i=AbortSignal.any([n,e.signal]),f=kd(t.sdkResponse,t.model,t.conversationId,i)[Symbol.asyncIterator](),o=new TextEncoder,c=!1,h,u=()=>{if(h===void 0)return;clearTimeout(h),h=void 0},l=()=>{if(c)return;c=!0,r()},_=async()=>{await f.return?.(void 0)};return new Response(new ReadableStream({async pull(w){let A;try{let M=await Promise.race([f.next(),new Promise((d,E)=>{let b=()=>{u(),E(Ln(i))};if(A=()=>i.removeEventListener("abort",b),i.addEventListener("abort",b,{once:!0}),h=setTimeout(()=>{h=void 0,E(new Xd(s))},s),i.aborted)b()})]);if(i.aborted)throw Ln(i);if(M.done){w.close(),l();return}w.enqueue(o.encode(`${JSON.stringify(M.value)}
|
|
132
|
+
`))}catch(M){if(u(),A?.(),e.signal.aborted)return;let d=M instanceof Error?M:TypeError("SDK stream failed with a non-Error reason",{cause:M});e.abort(d),w.error(d);try{await _()}finally{l()}}finally{u(),A?.()}},async cancel(){u(),e.abort();try{await _()}catch{return}finally{l()}}}),{headers:{"Content-Type":"application/x-ndjson; charset=utf-8"}})}var ad=H(Ni(),1);var Cd=new Map,CW=3;function Go(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function aW(t){let n=t.conversationState;if(!Go(n))return;let s=n.currentMessage;if(!Go(s))return;let r=s.userInputMessage;if(!Go(r))return;let e=r.modelId;return typeof e==="string"?e:void 0}function KW(t,n,s,r){let e=r?(()=>{let i=Yu(r);return new ad.NodeHttpHandler({httpAgent:i,httpsAgent:i})})():void 0;return{region:n,endpoint:s,token:()=>Promise.resolve({token:t.access}),maxAttempts:CW,retryMode:"standard",customUserAgent:[[st.USER_AGENT]],...e?{requestHandler:e}:{}}}function Kd(t,n,s,r,e){let i=r??`https://q.${n}.amazonaws.com`,f=JSON.stringify([n,t.email??null,s??null,i,e??null]),o=Cd.get(f);if(o?.token===t.access)return o.client;let c=new Xh(KW(t,n,i,e));if(c.middlewareStack.add((h)=>async(u)=>{if(u.request instanceof It.HttpRequest)u.request.headers["x-amzn-kiro-agent-mode"]="vibe";return h(u)},{step:"build",name:"addKiroHeaders"}),s)c.middlewareStack.add((h)=>async(u)=>{if(u.request instanceof It.HttpRequest&&typeof u.request.body==="string")try{let l=JSON.parse(u.request.body);if(Go(l)){let _=aW(l);if(_)l.additionalModelRequestFields=Md(_,s),u.request.body=JSON.stringify(l)}}catch(l){if(!(l instanceof SyntaxError))throw l}return h(u)},{step:"build",name:"addEffortConfig",priority:"high"});return Cd.set(f,{client:c,token:t.access}),c}function bs(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function VW(t){if(!bs(t))return!1;let n=t.conversationState;return bs(n)&&typeof n.conversationId==="string"&&bs(n.currentMessage)&&typeof n.chatTriggerType==="string"}function jW(t,n){let s=typeof t==="string"?JSON.parse(t):t;if(!bs(s))return{think:n.endsWith("-thinking"),budget:20000};let r=s.providerOptions,e=bs(r)?r.thinkingConfig:void 0,i=s.thinkingConfig,f=bs(e)?e:bs(i)?i:void 0,o=f?.thinkingBudget??f?.budget_tokens;return{think:n.endsWith("-thinking")||f!==void 0,budget:typeof o==="number"?o:20000}}function pW(t,n,s){return Z(t,n,"upstream_error",s)}async function vW(t,n){let{think:s,budget:r}=jW(t.body,t.model),e=new Set,i=new Map,f=0,o=0;while(!0){if(n.aborted)throw Ln(n);if(o+=1,o>t.config.max_request_iterations)return{kind:"response",response:Z(500,`Exceeded max iterations (${t.config.max_request_iterations})`,"request_error","max_request_iterations")};t.accountManager.reconcileFromDb();let c=t.accountManager.selectHealthyAccount();if(!c)return{kind:"response",response:Z(503,"All accounts are unhealthy or rate-limited","service_unavailable","no_healthy_accounts")};let h=t.accountManager.toAuthDetails(c),u=await _r(t.tokenRefresher.refreshIfNeeded(c,h,n),n),l=t.accountManager.toAuthDetails(u),_=Se.safeParse(t.config.effort),w=Id(t.body,t.model,l,s,r,{autoEffortMapping:t.config.auto_effort_mapping,..._.success?{effort:_.data}:{}}),M=(t.makeClient??Kd)(l,w.region,w.effort,t.config.test_upstream_endpoint,xs(t.config)),d={conversationState:w.conversationState,...w.profileArn?{profileArn:w.profileArn}:{}};if(!VW(d))throw TypeError("Transformed request is not a valid SDK command input");let E=new qh(d);try{let b=await _r(M.send(E,{abortSignal:n}),n);if(t.stream)return{kind:"stream",sdkResponse:b,model:t.model,conversationId:w.conversationId};let L=await Bd(b,t.model,w.conversationId,n);if(n.aborted)throw Ln(n);return{kind:"response",response:Response.json(L,{headers:{"Content-Type":"application/json"}})}}catch(b){if(n.aborted)throw Ln(n);let L=Kh(b),S=L.status===500?(i.get(u.id)??0)+1:0;if(L.status===500)i.set(u.id,S);let O=md(L,{accountId:u.id,accountCount:t.accountManager.getAccountCount(),retryCount:f,maxRetries:t.config.rate_limit_max_retries,serverErrorCount:S,retryDelayMs:t.config.rate_limit_retry_delay_ms,forcedRefreshAccountIds:e});switch(O.action){case"refresh-then-retry":await _r(t.tokenRefresher.forceRefresh(u,n),n);continue;case"retry":f+=1,await Pd(O.retryAfterMs??0,n);continue;case"switch":if(L.reason==="TEMPORARILY_SUSPENDED")t.accountManager.markUnhealthy(u,`InvalidTokenException: Account Suspended: ${L.message}`);else t.accountManager.markRateLimited(u,Date.now()+(O.retryAfterMs??t.config.rate_limit_retry_delay_ms));continue;case"fail":if(L.reason==="TEMPORARILY_SUSPENDED")t.accountManager.markUnhealthy(u,`InvalidTokenException: Account Suspended: ${L.message}`);return{kind:"response",response:pW(O.terminalStatus??O.status??500,L.message,L.code)}}}}}async function Vd(t){let n=Nd(t.deadlineSignal,t.config.request_timeout_ms),s,r=!1;try{s=await Hd(n.signal);let e=await vW(t,n.signal);if(e.kind==="response")return e.response;let i=s;return s=void 0,r=!0,qd(e,n.signal,t.config.stream_idle_timeout_ms,()=>{i(),n.dispose()})}catch(e){if(n.signal.aborted)return Z(504,"Request deadline exceeded","timeout_error","request_timeout");let i=Kh(e);return Z(500,i.message,"internal_error",i.code)}finally{if(!r)s?.(),n.dispose()}}var ge=Object.freeze({input:Object.freeze(["text"]),output:Object.freeze(["text"])}),ft=Object.freeze({input:Object.freeze(["text","image"]),output:Object.freeze(["text"])}),C=Object.freeze({input:Object.freeze(["text","image","pdf"]),output:Object.freeze(["text"])}),jd=Object.freeze(["auto","claude-sonnet-4","claude-sonnet-4-5","claude-sonnet-4-6","claude-sonnet-4-6-low","claude-sonnet-4-6-medium","claude-sonnet-4-6-high","claude-sonnet-4-6-max","claude-sonnet-5","claude-sonnet-5-low","claude-sonnet-5-medium","claude-sonnet-5-high","claude-sonnet-5-xhigh","claude-sonnet-5-max","claude-haiku-4-5","claude-opus-4-5","claude-opus-4-6","claude-opus-4-7","claude-opus-4-7-low","claude-opus-4-7-medium","claude-opus-4-7-high","claude-opus-4-7-xhigh","claude-opus-4-7-max","claude-opus-4-8","claude-opus-4-8-low","claude-opus-4-8-medium","claude-opus-4-8-high","claude-opus-4-8-xhigh","claude-opus-4-8-max","claude-opus-4-8-thinking","deepseek-3.2","glm-5","minimax-m2.5","minimax-m2.1","qwen3-coder-next","gpt-5.6-sol","gpt-5.6-sol-low","gpt-5.6-sol-medium","gpt-5.6-sol-high","gpt-5.6-sol-xhigh","gpt-5.6-sol-max","gpt-5.6-terra","gpt-5.6-terra-low","gpt-5.6-terra-medium","gpt-5.6-terra-high","gpt-5.6-terra-xhigh","gpt-5.6-terra-max","gpt-5.6-luna","gpt-5.6-luna-low","gpt-5.6-luna-medium","gpt-5.6-luna-high","gpt-5.6-luna-xhigh","gpt-5.6-luna-max"]),pd=Object.freeze([{id:"auto",wireId:"auto",name:"Auto (1.0x)",contextLimit:G("auto"),outputLimit:64000,modalities:C},{id:"claude-sonnet-4",wireId:"claude-sonnet-4",name:"Claude Sonnet 4.0 (1.3x)",contextLimit:G("claude-sonnet-4"),outputLimit:64000,modalities:C},{id:"claude-sonnet-4-5",wireId:"claude-sonnet-4.5",name:"Claude Sonnet 4.5 (1.3x)",contextLimit:G("claude-sonnet-4-5"),outputLimit:64000,modalities:C},{id:"claude-sonnet-4-6",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (1.3x)",contextLimit:G("claude-sonnet-4-6"),outputLimit:64000,modalities:C},{id:"claude-sonnet-4-6-low",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (low) (1.3x)",contextLimit:G("claude-sonnet-4-6"),outputLimit:64000,modalities:C},{id:"claude-sonnet-4-6-medium",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (medium) (1.3x)",contextLimit:G("claude-sonnet-4-6"),outputLimit:64000,modalities:C},{id:"claude-sonnet-4-6-high",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (high) (1.3x)",contextLimit:G("claude-sonnet-4-6"),outputLimit:64000,modalities:C},{id:"claude-sonnet-4-6-max",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (max) (1.3x)",contextLimit:G("claude-sonnet-4-6"),outputLimit:64000,modalities:C},{id:"claude-sonnet-5",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (1.3x)",contextLimit:G("claude-sonnet-5"),outputLimit:64000,modalities:C},{id:"claude-sonnet-5-low",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (low) (1.3x)",contextLimit:G("claude-sonnet-5"),outputLimit:64000,modalities:C},{id:"claude-sonnet-5-medium",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (medium) (1.3x)",contextLimit:G("claude-sonnet-5"),outputLimit:64000,modalities:C},{id:"claude-sonnet-5-high",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (high) (1.3x)",contextLimit:G("claude-sonnet-5"),outputLimit:64000,modalities:C},{id:"claude-sonnet-5-xhigh",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (xhigh) (1.3x)",contextLimit:G("claude-sonnet-5"),outputLimit:64000,modalities:C},{id:"claude-sonnet-5-max",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (max) (1.3x)",contextLimit:G("claude-sonnet-5"),outputLimit:64000,modalities:C},{id:"claude-haiku-4-5",wireId:"claude-haiku-4.5",name:"Claude Haiku 4.5 (0.4x)",contextLimit:G("claude-haiku-4-5"),outputLimit:64000,modalities:ft},{id:"claude-opus-4-5",wireId:"claude-opus-4.5",name:"Claude Opus 4.5 (2.2x)",contextLimit:G("claude-opus-4-5"),outputLimit:64000,modalities:C},{id:"claude-opus-4-6",wireId:"claude-opus-4.6",name:"Claude Opus 4.6 (2.2x)",contextLimit:G("claude-opus-4-6"),outputLimit:64000,modalities:C},{id:"claude-opus-4-7",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (2.2x)",contextLimit:G("claude-opus-4-7"),outputLimit:64000,modalities:C},{id:"claude-opus-4-7-low",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (low) (2.2x)",contextLimit:G("claude-opus-4-7"),outputLimit:64000,modalities:C},{id:"claude-opus-4-7-medium",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (medium) (2.2x)",contextLimit:G("claude-opus-4-7"),outputLimit:64000,modalities:C},{id:"claude-opus-4-7-high",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (high) (2.2x)",contextLimit:G("claude-opus-4-7"),outputLimit:64000,modalities:C},{id:"claude-opus-4-7-xhigh",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (xhigh) (2.2x)",contextLimit:G("claude-opus-4-7"),outputLimit:64000,modalities:C},{id:"claude-opus-4-7-max",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (max) (2.2x)",contextLimit:G("claude-opus-4-7"),outputLimit:64000,modalities:C},{id:"claude-opus-4-8",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (2.2x)",contextLimit:G("claude-opus-4-8"),outputLimit:64000,modalities:C},{id:"claude-opus-4-8-low",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (low) (2.2x)",contextLimit:G("claude-opus-4-8"),outputLimit:64000,modalities:C},{id:"claude-opus-4-8-medium",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (medium) (2.2x)",contextLimit:G("claude-opus-4-8"),outputLimit:64000,modalities:C},{id:"claude-opus-4-8-high",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (high) (2.2x)",contextLimit:G("claude-opus-4-8"),outputLimit:64000,modalities:C},{id:"claude-opus-4-8-xhigh",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (xhigh) (2.2x)",contextLimit:G("claude-opus-4-8"),outputLimit:64000,modalities:C},{id:"claude-opus-4-8-max",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (max) (2.2x)",contextLimit:G("claude-opus-4-8"),outputLimit:64000,modalities:C},{id:"claude-opus-4-8-thinking",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 Thinking (2.2x)",contextLimit:G("claude-opus-4-8"),outputLimit:64000,modalities:C},{id:"deepseek-3.2",wireId:"deepseek-3.2",name:"DeepSeek 3.2 (0.25x)",contextLimit:G("deepseek-3.2"),outputLimit:64000,modalities:ge},{id:"glm-5",wireId:"glm-5",name:"GLM-5 (0.5x)",contextLimit:G("glm-5"),outputLimit:64000,modalities:ge},{id:"minimax-m2.5",wireId:"minimax-m2.5",name:"MiniMax M2.5 (0.25x)",contextLimit:G("minimax-m2.5"),outputLimit:64000,modalities:ge},{id:"minimax-m2.1",wireId:"minimax-m2.1",name:"MiniMax M2.1 (0.15x)",contextLimit:G("minimax-m2.1"),outputLimit:64000,modalities:ge},{id:"qwen3-coder-next",wireId:"qwen3-coder-next",name:"Qwen3 Coder Next (0.05x)",contextLimit:G("qwen3-coder-next"),outputLimit:64000,modalities:ge},{id:"gpt-5.6-sol",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (2.4x)",contextLimit:G("gpt-5.6-sol"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-sol-low",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (low) (2.4x)",contextLimit:G("gpt-5.6-sol"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-sol-medium",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (medium) (2.4x)",contextLimit:G("gpt-5.6-sol"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-sol-high",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (high) (2.4x)",contextLimit:G("gpt-5.6-sol"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-sol-xhigh",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (xhigh) (2.4x)",contextLimit:G("gpt-5.6-sol"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-sol-max",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (max) (2.4x)",contextLimit:G("gpt-5.6-sol"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-terra",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (1.2x)",contextLimit:G("gpt-5.6-terra"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-terra-low",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (low) (1.2x)",contextLimit:G("gpt-5.6-terra"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-terra-medium",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (medium) (1.2x)",contextLimit:G("gpt-5.6-terra"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-terra-high",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (high) (1.2x)",contextLimit:G("gpt-5.6-terra"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-terra-xhigh",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (xhigh) (1.2x)",contextLimit:G("gpt-5.6-terra"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-terra-max",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (max) (1.2x)",contextLimit:G("gpt-5.6-terra"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-luna",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna",contextLimit:G("gpt-5.6-luna"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-luna-low",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (low)",contextLimit:G("gpt-5.6-luna"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-luna-medium",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (medium)",contextLimit:G("gpt-5.6-luna"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-luna-high",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (high)",contextLimit:G("gpt-5.6-luna"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-luna-xhigh",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (xhigh)",contextLimit:G("gpt-5.6-luna"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-luna-max",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (max)",contextLimit:G("gpt-5.6-luna"),outputLimit:64000,modalities:ft}]);var vd=g.record(g.unknown()),ZW=new Set(jd),t7=g.object({type:g.literal("text"),text:g.string()}).passthrough(),n7=g.object({type:g.literal("image_url"),image_url:g.object({url:g.string(),detail:g.string().optional()}).passthrough()}).passthrough(),s7=g.object({type:g.literal("image"),source:g.object({type:g.string(),data:g.string(),media_type:g.string().optional()}).passthrough()}).passthrough(),r7=g.object({type:g.literal("tool_result"),tool_use_id:g.string().min(1),content:g.unknown()}).passthrough(),e7=g.object({type:g.literal("tool_use"),id:g.string().min(1),name:g.string().min(1),input:g.unknown()}).passthrough(),i7=g.object({type:g.literal("thinking"),thinking:g.string().optional(),text:g.string().optional()}).passthrough(),o7=g.discriminatedUnion("type",[t7,n7,s7,r7,e7,i7]),Bo=g.union([g.string(),g.array(o7)]);function f7(t){try{return JSON.parse(t),!0}catch(n){if(n instanceof SyntaxError)return!1;throw n}}var c7=g.object({id:g.string().min(1),type:g.literal("function"),function:g.object({name:g.string().min(1),arguments:g.string().refine(f7,"function arguments must contain valid JSON")}).passthrough()}).passthrough(),h7=g.object({role:g.literal("system"),content:Bo}).passthrough(),u7=g.object({role:g.literal("user"),content:Bo}).passthrough(),l7=g.object({role:g.literal("assistant"),content:Bo.nullable().optional(),tool_calls:g.array(c7).min(1).optional()}).passthrough().refine((t)=>t.content!==null&&t.content!==void 0?!0:t.tool_calls!==void 0,{message:"assistant message requires content or tool_calls"}),_7=g.object({role:g.literal("tool"),content:Bo,tool_call_id:g.string().min(1)}).passthrough(),w7=g.union([h7,u7,l7,_7]),A7=g.object({type:g.literal("function"),function:g.object({name:g.string().min(1),description:g.string().optional(),parameters:vd.optional()}).passthrough()}).passthrough(),M7=g.object({name:g.string().min(1),description:g.string().optional(),input_schema:vd.optional()}).passthrough(),d7=g.object({model:g.string().refine((t)=>ZW.has(t),{message:"model is not supported"}),stream:g.boolean().default(!1),messages:g.array(w7).min(1),tools:g.array(g.union([A7,M7])).optional(),reasoning_effort:g.enum(["low","medium","high","xhigh","max"]).optional()}).passthrough();function Zd(t){let n=d7.safeParse(t);if(n.success)return{ok:!0,value:n.data};let s=n.error.issues.map((r)=>{return`${r.path.length>0?r.path.join("."):"request"}: ${r.message}`}).join(", ");return{ok:!1,response:Z(400,`Invalid request: ${s}`,"invalid_request_error","invalid_request")}}class nu extends Error{limit;name="RequestBodyTooLargeError";constructor(t){super(`Request body exceeds the ${t} byte limit`);this.limit=t}}function tu(t){return t.reason instanceof Error?t.reason:new DOMException("Request deadline exceeded","TimeoutError")}async function g7(t,n,s){let r=t.body?.getReader();if(!r)return{ok:!0,text:""};let e=[],i=0,f,o=new Promise((h,u)=>{f=u}),c=()=>{let h=tu(s.combined);f?.(h),r.cancel(h)};s.combined.addEventListener("abort",c,{once:!0});try{while(!0){if(s.combined.aborted)throw tu(s.combined);let l=await Promise.race([r.read(),o]);if(s.combined.aborted)throw tu(s.combined);if(l.done)break;if(i+=l.value.byteLength,i>n)throw new nu(n);e.push(l.value)}let h=new Uint8Array(i),u=0;for(let l of e)h.set(l,u),u+=l.byteLength;return{ok:!0,text:new TextDecoder().decode(h)}}catch(h){if(h instanceof nu)return r.cancel(h).catch(()=>{return}),{ok:!1,response:Z(413,h.message,"invalid_request_error","request_too_large")};if(s.deadline.aborted)return r.cancel(h).catch(()=>{return}),{ok:!1,response:Z(504,"Request deadline exceeded","timeout_error","request_timeout")};if(s.client.aborted)return r.cancel(h).catch(()=>{return}),{ok:!1,response:Z(499,"Client closed request","request_aborted","client_disconnected")};throw h}finally{s.combined.removeEventListener("abort",c)}}function E7(t,n){let s=t.body;if(!s)return t;let r=s.getReader(),e=new TextDecoder,i=new TextEncoder,f="",o=!1,c=!1,h=()=>{if(c)return;c=!0,n()};return new Response(new ReadableStream({async pull(u){try{while(!0){let l=f.indexOf(`
|
|
133
|
+
`);if(l>=0){let A=f.slice(0,l).trimEnd();if(f=f.slice(l+1),A.length>0){u.enqueue(i.encode(`data: ${A}
|
|
134
|
+
|
|
135
|
+
`));return}continue}let _=await r.read();if(!_.done){f+=e.decode(_.value,{stream:!0});continue}f+=e.decode();let w=f.trim();if(f="",w.length>0){u.enqueue(i.encode(`data: ${w}
|
|
136
|
+
|
|
137
|
+
`));return}if(!o){o=!0,u.enqueue(i.encode(`data: [DONE]
|
|
138
|
+
|
|
139
|
+
`));return}u.close(),h();return}}catch{let l=JSON.stringify({error:{message:"Upstream stream error",type:"upstream_error"}});u.enqueue(i.encode(`data: ${l}
|
|
140
|
+
|
|
141
|
+
`)),u.close(),h()}},cancel(u){r.cancel(u).catch(()=>{return}),h()}}),{status:t.status,headers:{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive"}})}async function tg(t,n,s){let r=new AbortController,e=setTimeout(()=>r.abort(new DOMException("Request deadline exceeded","TimeoutError")),n.request_timeout_ms),i=AbortSignal.any([r.signal,t.signal]),f={combined:i,deadline:r.signal,client:t.signal},o=await g7(t,n.max_request_body_bytes,f);if(!o.ok)return clearTimeout(e),o.response;let c;try{c=JSON.parse(o.text)}catch(_){if(clearTimeout(e),!(_ instanceof SyntaxError))throw _;return Z(400,"Request body must contain valid JSON","invalid_request_error","invalid_json")}let h=Zd(c);if(!h.ok)return clearTimeout(e),h.response;let u=await Vd({body:h.value,model:h.value.model,stream:h.value.stream,config:n,accountManager:s.accountManager,tokenRefresher:s.tokenRefresher,deadlineSignal:i,...s.makeClient?{makeClient:s.makeClient}:{}});if(t.signal.aborted&&!r.signal.aborted)return clearTimeout(e),Z(499,"Client closed request","request_aborted","client_disconnected");let l=u.headers.get("Content-Type")??"";if(!h.value.stream||l.includes("application/json"))return clearTimeout(e),u;if(!l.includes("application/x-ndjson"))return clearTimeout(e),Z(500,"Pipeline returned an unsupported streaming response","internal_error","invalid_pipeline_response");return E7(u,()=>clearTimeout(e))}function ng(){return new Response(JSON.stringify({status:"ok"}),{status:200,headers:{"Content-Type":"application/json"}})}var R7=1700000000;function sg(){let t=pd.map((n)=>({id:n.id,object:"model",created:R7,owned_by:"kiro",name:n.name,context_limit:n.contextLimit,output_limit:n.outputLimit,modalities:n.modalities}));return new Response(JSON.stringify({object:"list",data:t}),{status:200,headers:{"Content-Type":"application/json"}})}function b7(t,n){return async(s)=>{let r=au(s,t.api_keys);if(!r.ok)return r.response;let e=new URL(s.url);try{if(s.method==="POST"&&e.pathname==="/v1/chat/completions")return await tg(s,t,n);if(s.method==="GET"&&e.pathname==="/v1/models")return sg();if(s.method==="GET"&&e.pathname==="/health")return ng();return Z(404,"Route not found","invalid_request_error","not_found")}catch(i){let f=i instanceof Error?i.message:"Internal server error";return Z(500,f,"internal_error","internal_error")}}}function T7(t,n={}){let s=n.createDatabase?.()??new rs,r=new Yo(s.getAccounts(),t.account_selection_strategy,s),e=xs(t),i=n.createTokenRefresher?n.createTokenRefresher(r,t.token_expiry_buffer_ms,e):new ao(r,t.token_expiry_buffer_ms,e);return{accountManager:r,tokenRefresher:i}}function rg(t){return Bun.serve({hostname:t.host,port:t.port,fetch:b7(t,T7(t))})}import{parseArgs as su}from"util";var mo=`Usage: kiro-provider <command> [options]
|
|
142
|
+
|
|
143
|
+
Commands:
|
|
144
|
+
serve [--config <path>] [--host <host>] [--port <port>] [--proxy <url>]
|
|
145
|
+
Start the OpenAI-compatible gateway (default bind: 127.0.0.1:8787).
|
|
146
|
+
login [--config <path>] [--start-url <url>] [--region <region>]
|
|
147
|
+
Sign in with AWS Builder ID or an IAM Identity Center start URL.
|
|
148
|
+
accounts list
|
|
149
|
+
List stored accounts.
|
|
150
|
+
accounts import [--from <path>] [--config <path>]
|
|
151
|
+
Import authenticated accounts from the OpenCode Kiro database.
|
|
152
|
+
accounts remove <id|email>
|
|
153
|
+
Remove an account and write a tombstone.
|
|
154
|
+
|
|
155
|
+
Options:
|
|
156
|
+
-h, --help Show this help.`;class wr extends Error{constructor(t){super(t);this.name="CliUsageError"}}function S7(t){let n=su({args:[...t],options:{config:{type:"string"},host:{type:"string"},port:{type:"string"},proxy:{type:"string"},help:{type:"boolean",short:"h"}},strict:!0,allowPositionals:!1});if(n.values.help)return{kind:"help"};let s=n.values.port===void 0?void 0:Number(n.values.port);if(s!==void 0&&(!Number.isInteger(s)||s<1||s>65535))throw new wr(`Invalid port: ${n.values.port}`);return{kind:"serve",...n.values.config?{configPath:n.values.config}:{},...n.values.host?{host:n.values.host}:{},...s!==void 0?{port:s}:{},...n.values.proxy!==void 0?{proxy:n.values.proxy}:{}}}function $7(t){let n=su({args:[...t],options:{config:{type:"string"},"start-url":{type:"string"},region:{type:"string"}},strict:!0,allowPositionals:!1});return{kind:"login",...n.values.config?{configPath:n.values.config}:{},...n.values["start-url"]?{startUrl:n.values["start-url"]}:{},...n.values.region?{region:n.values.region}:{}}}function U7(t){let n=su({args:[...t],options:{from:{type:"string"},config:{type:"string"},help:{type:"boolean",short:"h"}},strict:!0,allowPositionals:!1});if(n.values.help)return{kind:"help"};return{kind:"accounts-import",...n.values.from?{from:n.values.from}:{},...n.values.config?{configPath:n.values.config}:{}}}function L7(t){let n=t[0];switch(n){case"list":if(t.length!==1)throw new wr("accounts list takes no arguments");return{kind:"accounts-list"};case"import":return U7(t.slice(1));case"remove":{let s=t[1];if(!s||t.length!==2)throw new wr("accounts remove requires exactly one <id|email>");return{kind:"accounts-remove",identifier:s}}default:throw new wr(n===void 0?"accounts requires list, import, or remove":`Unknown accounts command: ${n}`)}}function ru(t){let n=t[0];switch(n){case void 0:case"--help":case"-h":return{kind:"help"};case"serve":return S7(t.slice(1));case"login":return $7(t.slice(1));case"accounts":return L7(t.slice(1));default:throw new wr(`Unknown command: ${n}`)}}import{Database as I7}from"bun:sqlite";import{homedir as O7}from"os";import{join as eg}from"path";var y7=g.object({id:g.string().min(1),email:g.string().min(1),auth_method:g.string(),region:g.string(),oidc_region:g.string().nullable(),client_id:g.string().nullable(),client_secret:g.string().nullable(),profile_arn:g.string().nullable(),start_url:g.string().nullable(),refresh_token:g.string(),access_token:g.string(),expires_at:g.number(),rate_limit_reset:g.number().nullable(),is_healthy:g.number().nullable(),unhealthy_reason:g.string().nullable(),recovery_time:g.number().nullable(),fail_count:g.number().nullable(),last_used:g.number().nullable(),used_count:g.number().nullable(),limit_count:g.number().nullable(),last_sync:g.number().nullable(),overage_count:g.number().nullable()});function G7(t=process.env){let n=t.XDG_CONFIG_HOME??eg(O7(),".config");return eg(n,"opencode","kiro.db")}function Kt(t){return t===null||t===""?void 0:t}function B7(t){if(!t.refresh_token)return{kind:"skipped",reason:"missing refresh token"};if(!t.access_token)return{kind:"skipped",reason:"missing access token"};let n=Zn.safeParse(t.region);if(!n.success)return{kind:"skipped",reason:"missing or unsupported region"};if(t.auth_method!=="idc"&&t.auth_method!=="desktop")return{kind:"skipped",reason:"unsupported auth method"};if(t.auth_method==="idc"&&(!t.client_id||!t.client_secret))return{kind:"skipped",reason:"IDC client credentials missing"};let s=Kt(t.oidc_region),r=s===void 0?void 0:Zn.safeParse(s);if(r!==void 0&&!r.success)return{kind:"skipped",reason:"unsupported OIDC region"};return{kind:"usable",account:{id:t.id,email:t.email,authMethod:t.auth_method,region:n.data,...r?.success?{oidcRegion:r.data}:{},...Kt(t.client_id)?{clientId:Kt(t.client_id)}:{},...Kt(t.client_secret)?{clientSecret:Kt(t.client_secret)}:{},...Kt(t.profile_arn)?{profileArn:Kt(t.profile_arn)}:{},...Kt(t.start_url)?{startUrl:Kt(t.start_url)}:{},refreshToken:t.refresh_token,accessToken:t.access_token,expiresAt:t.expires_at,rateLimitResetTime:t.rate_limit_reset??0,isHealthy:t.is_healthy!==0,...Kt(t.unhealthy_reason)?{unhealthyReason:Kt(t.unhealthy_reason)}:{},...t.recovery_time===null?{}:{recoveryTime:t.recovery_time},failCount:t.fail_count??0,lastUsed:t.last_used??0,usedCount:t.used_count??0,limitCount:t.limit_count??0,lastSync:t.last_sync??0,overageCount:t.overage_count??0}}}function ig(t,n){let s=t.from??G7(),r=new I7(s,{readonly:!0,strict:!0}),e=0,i=0;try{let o=r.query(`SELECT
|
|
157
|
+
id, email, auth_method, region, oidc_region, client_id, client_secret,
|
|
158
|
+
profile_arn, start_url, refresh_token, access_token, expires_at,
|
|
159
|
+
rate_limit_reset, is_healthy, unhealthy_reason, recovery_time, fail_count,
|
|
160
|
+
last_used, used_count, limit_count, last_sync, overage_count
|
|
161
|
+
FROM accounts`).all();for(let c of o){let h=y7.safeParse(c);if(!h.success){i+=1,n.stdout("Skipped malformed source account row");continue}let u=B7(h.data);if(u.kind==="skipped"){i+=1,n.stdout(`Skipped ${h.data.email}: ${u.reason}`);continue}n.database.insertAccount(u.account),e+=1,n.stdout(`Imported ${u.account.email} ${u.account.authMethod} ${u.account.region}`)}}finally{r.close()}let f=n.database.getAccounts().length;return n.stdout(`Imported ${e}, skipped ${i}, total in DB now ${f}`),{imported:e,skipped:i,total:f}}import{createHash as H7}from"crypto";var m7=g.object({clientId:g.string().min(1),clientSecret:g.string().min(1)}),F7=g.object({verificationUri:g.string().min(1),verificationUriComplete:g.string().min(1),userCode:g.string().min(1),deviceCode:g.string().min(1),interval:g.number().positive().default(5),expiresIn:g.number().positive().default(600)}),P7=g.object({error:g.string().optional(),error_description:g.string().optional(),access_token:g.string().optional(),accessToken:g.string().optional(),refresh_token:g.string().optional(),refreshToken:g.string().optional(),expires_in:g.number().optional(),expiresIn:g.number().optional()}).passthrough();class yt extends Error{constructor(t,n){super(t,n);this.name="KiroIDCError"}}async function eu(t){try{return await t.text()}catch(n){if(n instanceof Error)return"";throw n}}async function og(t,n,s){let r=qo(t),e=Lr(Or.SSO_OIDC_ENDPOINT,r),i=n??Or.BUILDER_ID_START_URL,f=await fetch(`${e}/client/register`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":st.USER_AGENT},body:JSON.stringify({clientName:"Kiro IDE",clientType:"public",scopes:Or.SCOPES,grantTypes:["urn:ietf:params:oauth:grant-type:device_code","refresh_token"]}),...s?{proxy:s}:{}});if(!f.ok)throw new yt(`Client registration failed: ${f.status} ${await eu(f)}`);let o=m7.safeParse(await f.json());if(!o.success)throw new yt("Client registration response missing clientId or clientSecret",{cause:o.error});let c=await fetch(`${e}/device_authorization`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":st.USER_AGENT},body:JSON.stringify({clientId:o.data.clientId,clientSecret:o.data.clientSecret,startUrl:i}),...s?{proxy:s}:{}});if(!c.ok)throw new yt(`Device authorization failed: ${c.status} ${await eu(c)}`);let h=F7.safeParse(await c.json());if(!h.success)throw new yt("Device authorization response missing required fields",{cause:h.error});return{verificationUrl:h.data.verificationUri,verificationUriComplete:h.data.verificationUriComplete,userCode:h.data.userCode,deviceCode:h.data.deviceCode,clientId:o.data.clientId,clientSecret:o.data.clientSecret,interval:h.data.interval,expiresIn:h.data.expiresIn,region:r,startUrl:i}}async function fg(t,n,s,r,e,i,f=(c)=>new Promise((h)=>setTimeout(h,c)),o){if(!t||!n||!s)throw new yt("Missing required parameters for token polling");let c=qo(i),h=Lr(Or.SSO_OIDC_ENDPOINT,c),u=Math.floor(e/r),l=r*1000;for(let _=1;_<=u;_+=1){await f(l);let w=await fetch(`${h}/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":st.USER_AGENT},body:JSON.stringify({clientId:t,clientSecret:n,deviceCode:s,grantType:"urn:ietf:params:oauth:grant-type:device_code"}),...o?{proxy:o}:{}}),A=await eu(w),M={};if(A)try{M=JSON.parse(A)}catch(S){throw new yt(`Token polling failed: invalid JSON response (HTTP ${w.status}): ${A.slice(0,300)}`,{cause:S})}let d=P7.safeParse(M);if(!d.success)throw new yt(`Token polling failed: invalid response (HTTP ${w.status})`,{cause:d.error});let E=d.data;switch(E.error){case void 0:break;case"authorization_pending":continue;case"slow_down":l+=5000;continue;case"expired_token":throw new yt("Device code has expired. Please restart the authorization process.");case"access_denied":throw new yt("Authorization was denied by the user.");default:throw new yt(`Token polling failed: ${E.error} - ${E.error_description??""}`)}let b=E.access_token??E.accessToken,L=E.refresh_token??E.refreshToken;if(b&&L)return{refreshToken:L,accessToken:b,expiresAt:Date.now()+(E.expires_in??E.expiresIn??3600)*1000,email:"builder-id@aws.amazon.com",clientId:t,clientSecret:n,region:c,authMethod:"idc"};if(!w.ok)throw new yt(`Token request failed with status: ${w.status} ${A?`(${A.slice(0,200)})`:""}`);throw new yt(`Token polling failed: missing tokens in response: ${A?A.slice(0,300):"[empty]"}`)}throw new yt("Token polling timed out. Authorization may have expired.")}function N7(t){if(t===void 0||t.trim()==="")return;let n=new URL(t.trim());return n.hash="",n.search="",n.pathname=`${n.pathname.replace(/\/start\/?$/,"").replace(/\/+$/,"")}/start`,n.toString()}function D7(t,n){return H7("sha256").update(`${t}:idc:${n}:`).digest("hex")}async function cg(t,n={},s={}){let r=s.authorize??og,e=s.poll??fg,i=s.stdout??console.log,f=N7(n.startUrl),o=Zn.parse(n.region??t.default_region),c=xs(t),h=await r(o,f,c);i(`Open this URL to sign in:
|
|
162
|
+
${h.verificationUriComplete}`);let u=await e(h.clientId,h.clientSecret,h.deviceCode,h.interval,h.expiresIn,o,void 0,c),l={id:D7(u.email,u.clientId),email:u.email,authMethod:"idc",region:o,oidcRegion:o,clientId:u.clientId,clientSecret:u.clientSecret,...f?{startUrl:f}:{},refreshToken:u.refreshToken,accessToken:u.accessToken,expiresAt:u.expiresAt,rateLimitResetTime:0,isHealthy:!0,failCount:0,usedCount:0,limitCount:0},_=s.openDb?.(Fn)??new rs(Fn);try{_.insertAccount(l)}finally{_.close()}i(`Login successful: ${l.email}`)}function W7(t){let n=t.isHealthy?"healthy":"unhealthy";return`${t.email} ${t.region} ${n} generation=${t.generation} used=${t.usedCount??0}/${t.limitCount??0}`}var Y7={loadConfig:Eu,startServer:rg,runLogin:cg,runImportAccounts:ig,openDb:(t)=>new rs(t),stdout:console.log,stderr:console.error};async function x7(t,n){switch(t.kind){case"help":return n.stdout(mo),0;case"serve":{let s={...t.host?{host:t.host}:{},...t.port!==void 0?{port:t.port}:{},...t.proxy!==void 0?{proxy_url:t.proxy}:{}},r=n.loadConfig({...t.configPath?{configPath:t.configPath}:{},overrides:s});if(r.test_upstream_endpoint)n.stderr(`WARNING: test_upstream_endpoint is set (${r.test_upstream_endpoint}); routing upstream to a NON-production endpoint. Unset it for normal use.`);let e=n.startServer(r);return n.stdout(`Listening on http://${e.hostname??r.host}:${e.port??r.port}`),0}case"login":{let s=n.loadConfig({...t.configPath?{configPath:t.configPath}:{}});return await n.runLogin(s,{...t.startUrl?{startUrl:t.startUrl}:{},...t.region?{region:t.region}:{}}),0}case"accounts-list":{let s=n.openDb(Fn);try{for(let r of s.getAccounts())n.stdout(W7(r))}finally{s.close()}return 0}case"accounts-import":{let s=n.openDb(Fn);try{n.runImportAccounts({...t.from?{from:t.from}:{}},{database:s,stdout:n.stdout})}finally{s.close()}return 0}case"accounts-remove":{let s=n.openDb(Fn);try{let r=s.getAccounts().find((e)=>e.id===t.identifier||e.email===t.identifier);if(!r)return n.stderr(`Account not found: ${t.identifier}`),1;s.removeAccount(r.id),n.stdout(`Removed account ${r.email}`)}finally{s.close()}return 0}}}async function hg(t=process.argv.slice(2),n=Y7){let s;try{s=ru(t)}catch(r){return n.stderr(r instanceof Error?r.message:String(r)),n.stderr(mo),1}try{return await x7(s,n)}catch(r){return n.stderr(r instanceof Error?r.message:String(r)),1}}process.exitCode=await hg();
|