@sunerpy/kiro-provider 0.3.0 → 0.4.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/README.md +305 -23
- package/dist/cli.js +207 -91
- package/package.json +5 -3
package/dist/cli.js
CHANGED
|
@@ -1,62 +1,129 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var
|
|
3
|
+
var BT=Object.create;var{getPrototypeOf:NT,defineProperty:Zf,getOwnPropertyNames:GT}=Object;var HT=Object.prototype.hasOwnProperty;function WT(n){return this[n]}var FT,PT,Q=(n,t,i)=>{var s=n!=null&&typeof n==="object";if(s){var r=t?FT??=new WeakMap:PT??=new WeakMap,e=r.get(n);if(e)return e}i=n!=null?BT(NT(n)):{};let f=t||!n||!n.__esModule?Zf(i,"default",{value:n,enumerable:!0}):i;for(let o of GT(n))if(!HT.call(f,o))Zf(f,o,{get:WT.bind(n,o),enumerable:!0});if(s)r.set(n,f);return f};var k=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports);var DT=(n)=>n;function YT(n,t){this[n]=DT.bind(null,t)}var mT=(n,t)=>{for(var i in t)Zf(n,i,{get:t[i],enumerable:!0,configurable:!0,set:YT.bind(t,i)})};var p=import.meta.require;var L0=k((CC,$0)=>{var Zt=p("constants"),R2=process.cwd,Be=null,E2=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){if(!Be)Be=R2.call(process);return Be};try{process.cwd()}catch(n){}if(typeof process.chdir==="function"){if(Ne=process.chdir,process.chdir=function(n){Be=null,Ne.call(process,n)},Object.setPrototypeOf)Object.setPrototypeOf(process.chdir,Ne)}var Ne;$0.exports=y2;function y2(n){if(Zt.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./))t(n);if(!n.lutimes)i(n);if(n.chown=e(n.chown),n.fchown=e(n.fchown),n.lchown=e(n.lchown),n.chmod=s(n.chmod),n.fchmod=s(n.fchmod),n.lchmod=s(n.lchmod),n.chownSync=f(n.chownSync),n.fchownSync=f(n.fchownSync),n.lchownSync=f(n.lchownSync),n.chmodSync=r(n.chmodSync),n.fchmodSync=r(n.fchmodSync),n.lchmodSync=r(n.lchmodSync),n.stat=o(n.stat),n.fstat=o(n.fstat),n.lstat=o(n.lstat),n.statSync=h(n.statSync),n.fstatSync=h(n.fstatSync),n.lstatSync=h(n.lstatSync),n.chmod&&!n.lchmod)n.lchmod=function(c,_,w){if(w)process.nextTick(w)},n.lchmodSync=function(){};if(n.chown&&!n.lchown)n.lchown=function(c,_,w,l){if(l)process.nextTick(l)},n.lchownSync=function(){};if(E2==="win32")n.rename=typeof n.rename!=="function"?n.rename:function(c){function _(w,l,A){var d=Date.now(),E=0;c(w,l,function R(y){if(y&&(y.code==="EACCES"||y.code==="EPERM"||y.code==="EBUSY")&&Date.now()-d<60000){if(setTimeout(function(){n.stat(l,function(T,S){if(T&&T.code==="ENOENT")c(w,l,R);else A(y)})},E),E<100)E+=10;return}if(A)A(y)})}if(Object.setPrototypeOf)Object.setPrototypeOf(_,c);return _}(n.rename);n.read=typeof n.read!=="function"?n.read:function(c){function _(w,l,A,d,E,R){var y;if(R&&typeof R==="function"){var T=0;y=function(S,I,F){if(S&&S.code==="EAGAIN"&&T<10)return T++,c.call(n,w,l,A,d,E,y);R.apply(this,arguments)}}return c.call(n,w,l,A,d,E,y)}if(Object.setPrototypeOf)Object.setPrototypeOf(_,c);return _}(n.read),n.readSync=typeof n.readSync!=="function"?n.readSync:function(c){return function(_,w,l,A,d){var E=0;while(!0)try{return c.call(n,_,w,l,A,d)}catch(R){if(R.code==="EAGAIN"&&E<10){E++;continue}throw R}}}(n.readSync);function t(c){c.lchmod=function(_,w,l){c.open(_,Zt.O_WRONLY|Zt.O_SYMLINK,w,function(A,d){if(A){if(l)l(A);return}c.fchmod(d,w,function(E){c.close(d,function(R){if(l)l(E||R)})})})},c.lchmodSync=function(_,w){var l=c.openSync(_,Zt.O_WRONLY|Zt.O_SYMLINK,w),A=!0,d;try{d=c.fchmodSync(l,w),A=!1}finally{if(A)try{c.closeSync(l)}catch(E){}else c.closeSync(l)}return d}}function i(c){if(Zt.hasOwnProperty("O_SYMLINK")&&c.futimes)c.lutimes=function(_,w,l,A){c.open(_,Zt.O_SYMLINK,function(d,E){if(d){if(A)A(d);return}c.futimes(E,w,l,function(R){c.close(E,function(y){if(A)A(R||y)})})})},c.lutimesSync=function(_,w,l){var A=c.openSync(_,Zt.O_SYMLINK),d,E=!0;try{d=c.futimesSync(A,w,l),E=!1}finally{if(E)try{c.closeSync(A)}catch(R){}else c.closeSync(A)}return d};else if(c.futimes)c.lutimes=function(_,w,l,A){if(A)process.nextTick(A)},c.lutimesSync=function(){}}function s(c){if(!c)return c;return function(_,w,l){return c.call(n,_,w,function(A){if(u(A))A=null;if(l)l.apply(this,arguments)})}}function r(c){if(!c)return c;return function(_,w){try{return c.call(n,_,w)}catch(l){if(!u(l))throw l}}}function e(c){if(!c)return c;return function(_,w,l,A){return c.call(n,_,w,l,function(d){if(u(d))d=null;if(A)A.apply(this,arguments)})}}function f(c){if(!c)return c;return function(_,w,l){try{return c.call(n,_,w,l)}catch(A){if(!u(A))throw A}}}function o(c){if(!c)return c;return function(_,w,l){if(typeof w==="function")l=w,w=null;function A(d,E){if(E){if(E.uid<0)E.uid+=4294967296;if(E.gid<0)E.gid+=4294967296}if(l)l.apply(this,arguments)}return w?c.call(n,_,w,A):c.call(n,_,A)}}function h(c){if(!c)return c;return function(_,w){var l=w?c.call(n,_,w):c.call(n,_);if(l){if(l.uid<0)l.uid+=4294967296;if(l.gid<0)l.gid+=4294967296}return l}}function u(c){if(!c)return!0;if(c.code==="ENOSYS")return!0;var _=!process.getuid||process.getuid()!==0;if(_){if(c.code==="EINVAL"||c.code==="EPERM")return!0}return!1}}});var N0=k((xC,B0)=>{var O0=p("stream").Stream;B0.exports=T2;function T2(n){return{ReadStream:t,WriteStream:i};function t(s,r){if(!(this instanceof t))return new t(s,r);O0.call(this);var e=this;this.path=s,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=65536,r=r||{};var f=Object.keys(r);for(var o=0,h=f.length;o<h;o++){var u=f[o];this[u]=r[u]}if(this.encoding)this.setEncoding(this.encoding);if(this.start!==void 0){if(typeof this.start!=="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!=="number")throw TypeError("end must be a Number");if(this.start>this.end)throw Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){e._read()});return}n.open(this.path,this.flags,this.mode,function(c,_){if(c){e.emit("error",c),e.readable=!1;return}e.fd=_,e.emit("open",_),e._read()})}function i(s,r){if(!(this instanceof i))return new i(s,r);O0.call(this),this.path=s,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,r=r||{};var e=Object.keys(r);for(var f=0,o=e.length;f<o;f++){var h=e[f];this[h]=r[h]}if(this.start!==void 0){if(typeof this.start!=="number")throw TypeError("start must be a Number");if(this.start<0)throw Error("start must be >= zero");this.pos=this.start}if(this.busy=!1,this._queue=[],this.fd===null)this._open=n.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush()}}});var H0=k((KC,G0)=>{G0.exports=S2;var g2=Object.getPrototypeOf||function(n){return n.__proto__};function S2(n){if(n===null||typeof n!=="object")return n;if(n instanceof Object)var t={__proto__:g2(n)};else var t=Object.create(null);return Object.getOwnPropertyNames(n).forEach(function(i){Object.defineProperty(t,i,Object.getOwnPropertyDescriptor(n,i))}),t}});var ch=k((kC,uh)=>{var ln=p("fs"),I2=L0(),U2=N0(),b2=H0(),Ge=p("util"),$n,We;if(typeof Symbol==="function"&&typeof Symbol.for==="function")$n=Symbol.for("graceful-fs.queue"),We=Symbol.for("graceful-fs.previous");else $n="___graceful-fs.queue",We="___graceful-fs.previous";function $2(){}function F0(n,t){Object.defineProperty(n,$n,{get:function(){return t}})}var Oi=$2;if(Ge.debuglog)Oi=Ge.debuglog("gfs4");else if(/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))Oi=function(){var n=Ge.format.apply(Ge,arguments);n="GFS4: "+n.split(/\n/).join(`
|
|
4
|
+
GFS4: `),console.error(n)};if(!ln[$n]){if(oh=global[$n]||[],F0(ln,oh),ln.close=function(n){function t(i,s){return n.call(ln,i,function(r){if(!r)W0();if(typeof s==="function")s.apply(this,arguments)})}return Object.defineProperty(t,We,{value:n}),t}(ln.close),ln.closeSync=function(n){function t(i){n.apply(ln,arguments),W0()}return Object.defineProperty(t,We,{value:n}),t}(ln.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){Oi(ln[$n]),p("assert").equal(ln[$n].length,0)})}var oh;if(!global[$n])F0(global,ln[$n]);uh.exports=fh(b2(ln));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!ln.__patched)uh.exports=fh(ln),ln.__patched=!0;function fh(n){I2(n),n.gracefulify=fh,n.createReadStream=I,n.createWriteStream=F;var t=n.readFile;n.readFile=i;function i(b,$,N){if(typeof $==="function")N=$,$=null;return B(b,$,N);function B(g,X,Z,tn){return t(g,X,function(en){if(en&&(en.code==="EMFILE"||en.code==="ENFILE"))ys([B,[g,X,Z],en,tn||Date.now(),Date.now()]);else if(typeof Z==="function")Z.apply(this,arguments)})}}var s=n.writeFile;n.writeFile=r;function r(b,$,N,B){if(typeof N==="function")B=N,N=null;return g(b,$,N,B);function g(X,Z,tn,en,H){return s(X,Z,tn,function(W){if(W&&(W.code==="EMFILE"||W.code==="ENFILE"))ys([g,[X,Z,tn,en],W,H||Date.now(),Date.now()]);else if(typeof en==="function")en.apply(this,arguments)})}}var e=n.appendFile;if(e)n.appendFile=f;function f(b,$,N,B){if(typeof N==="function")B=N,N=null;return g(b,$,N,B);function g(X,Z,tn,en,H){return e(X,Z,tn,function(W){if(W&&(W.code==="EMFILE"||W.code==="ENFILE"))ys([g,[X,Z,tn,en],W,H||Date.now(),Date.now()]);else if(typeof en==="function")en.apply(this,arguments)})}}var o=n.copyFile;if(o)n.copyFile=h;function h(b,$,N,B){if(typeof N==="function")B=N,N=0;return g(b,$,N,B);function g(X,Z,tn,en,H){return o(X,Z,tn,function(W){if(W&&(W.code==="EMFILE"||W.code==="ENFILE"))ys([g,[X,Z,tn,en],W,H||Date.now(),Date.now()]);else if(typeof en==="function")en.apply(this,arguments)})}}var u=n.readdir;n.readdir=_;var c=/^v[0-5]\./;function _(b,$,N){if(typeof $==="function")N=$,$=null;var B=c.test(process.version)?function(Z,tn,en,H){return u(Z,g(Z,tn,en,H))}:function(Z,tn,en,H){return u(Z,tn,g(Z,tn,en,H))};return B(b,$,N);function g(X,Z,tn,en){return function(H,W){if(H&&(H.code==="EMFILE"||H.code==="ENFILE"))ys([B,[X,Z,tn],H,en||Date.now(),Date.now()]);else{if(W&&W.sort)W.sort();if(typeof tn==="function")tn.call(this,H,W)}}}}if(process.version.substr(0,4)==="v0.8"){var w=U2(n);R=w.ReadStream,T=w.WriteStream}var l=n.ReadStream;if(l)R.prototype=Object.create(l.prototype),R.prototype.open=y;var A=n.WriteStream;if(A)T.prototype=Object.create(A.prototype),T.prototype.open=S;Object.defineProperty(n,"ReadStream",{get:function(){return R},set:function(b){R=b},enumerable:!0,configurable:!0}),Object.defineProperty(n,"WriteStream",{get:function(){return T},set:function(b){T=b},enumerable:!0,configurable:!0});var d=R;Object.defineProperty(n,"FileReadStream",{get:function(){return d},set:function(b){d=b},enumerable:!0,configurable:!0});var E=T;Object.defineProperty(n,"FileWriteStream",{get:function(){return E},set:function(b){E=b},enumerable:!0,configurable:!0});function R(b,$){if(this instanceof R)return l.apply(this,arguments),this;else return R.apply(Object.create(R.prototype),arguments)}function y(){var b=this;sn(b.path,b.flags,b.mode,function($,N){if($){if(b.autoClose)b.destroy();b.emit("error",$)}else b.fd=N,b.emit("open",N),b.read()})}function T(b,$){if(this instanceof T)return A.apply(this,arguments),this;else return T.apply(Object.create(T.prototype),arguments)}function S(){var b=this;sn(b.path,b.flags,b.mode,function($,N){if($)b.destroy(),b.emit("error",$);else b.fd=N,b.emit("open",N)})}function I(b,$){return new n.ReadStream(b,$)}function F(b,$){return new n.WriteStream(b,$)}var C=n.open;n.open=sn;function sn(b,$,N,B){if(typeof N==="function")B=N,N=null;return g(b,$,N,B);function g(X,Z,tn,en,H){return C(X,Z,tn,function(W,on){if(W&&(W.code==="EMFILE"||W.code==="ENFILE"))ys([g,[X,Z,tn,en],W,H||Date.now(),Date.now()]);else if(typeof en==="function")en.apply(this,arguments)})}}return n}function ys(n){Oi("ENQUEUE",n[0].name,n[1]),ln[$n].push(n),hh()}var He;function W0(){var n=Date.now();for(var t=0;t<ln[$n].length;++t)if(ln[$n][t].length>2)ln[$n][t][3]=n,ln[$n][t][4]=n;hh()}function hh(){if(clearTimeout(He),He=void 0,ln[$n].length===0)return;var n=ln[$n].shift(),t=n[0],i=n[1],s=n[2],r=n[3],e=n[4];if(r===void 0)Oi("RETRY",t.name,i),t.apply(null,i);else if(Date.now()-r>=60000){Oi("TIMEOUT",t.name,i);var f=i.pop();if(typeof f==="function")f.call(null,s)}else{var o=Date.now()-e,h=Math.max(e-r,1),u=Math.min(h*1.2,100);if(o>=u)Oi("RETRY",t.name,i),t.apply(null,i.concat([r]));else ln[$n].push(n)}if(He===void 0)He=setTimeout(hh,0)}});var D0=k((qC,P0)=>{function vn(n,t){if(typeof t==="boolean")t={forever:t};if(this._originalTimeouts=JSON.parse(JSON.stringify(n)),this._timeouts=n,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever)this._cachedTimeouts=this._timeouts.slice(0)}P0.exports=vn;vn.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};vn.prototype.stop=function(){if(this._timeout)clearTimeout(this._timeout);this._timeouts=[],this._cachedTimeouts=null};vn.prototype.retry=function(n){if(this._timeout)clearTimeout(this._timeout);if(!n)return!1;var t=new Date().getTime();if(n&&t-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(n);var i=this._timeouts.shift();if(i===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),i=this._timeouts.shift();else return!1;var s=this,r=setTimeout(function(){if(s._attempts++,s._operationTimeoutCb){if(s._timeout=setTimeout(function(){s._operationTimeoutCb(s._attempts)},s._operationTimeout),s._options.unref)s._timeout.unref()}s._fn(s._attempts)},i);if(this._options.unref)r.unref();return!0};vn.prototype.attempt=function(n,t){if(this._fn=n,t){if(t.timeout)this._operationTimeout=t.timeout;if(t.cb)this._operationTimeoutCb=t.cb}var i=this;if(this._operationTimeoutCb)this._timeout=setTimeout(function(){i._operationTimeoutCb()},i._operationTimeout);this._operationStart=new Date().getTime(),this._fn(this._attempts)};vn.prototype.try=function(n){console.log("Using RetryOperation.try() is deprecated"),this.attempt(n)};vn.prototype.start=function(n){console.log("Using RetryOperation.start() is deprecated"),this.attempt(n)};vn.prototype.start=vn.prototype.try;vn.prototype.errors=function(){return this._errors};vn.prototype.attempts=function(){return this._attempts};vn.prototype.mainError=function(){if(this._errors.length===0)return null;var n={},t=null,i=0;for(var s=0;s<this._errors.length;s++){var r=this._errors[s],e=r.message,f=(n[e]||0)+1;if(n[e]=f,f>=i)t=r,i=f}return t}});var m0=k((O2)=>{var L2=D0();O2.operation=function(n){var t=O2.timeouts(n);return new L2(t,{forever:n&&n.forever,unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})};O2.timeouts=function(n){if(n instanceof Array)return[].concat(n);var t={retries:10,factor:2,minTimeout:1000,maxTimeout:1/0,randomize:!1};for(var i in n)t[i]=n[i];if(t.minTimeout>t.maxTimeout)throw Error("minTimeout is greater than maxTimeout");var s=[];for(var r=0;r<t.retries;r++)s.push(this.createTimeout(r,t));if(n&&n.forever&&!s.length)s.push(this.createTimeout(r,t));return s.sort(function(e,f){return e-f}),s};O2.createTimeout=function(n,t){var i=t.randomize?Math.random()+1:1,s=Math.round(i*t.minTimeout*Math.pow(t.factor,n));return s=Math.min(s,t.maxTimeout),s};O2.wrap=function(n,t,i){if(t instanceof Array)i=t,t=null;if(!i){i=[];for(var s in n)if(typeof n[s]==="function")i.push(s)}for(var r=0;r<i.length;r++){var e=i[r],f=n[e];n[e]=function(h){var u=O2.operation(t),c=Array.prototype.slice.call(arguments,1),_=c.pop();c.push(function(w){if(u.retry(w))return;if(w)arguments[0]=u.mainError();_.apply(this,arguments)}),u.attempt(function(){h.apply(n,c)})}.bind(n,f),n[e].options=t}}});var J0=k((jC,Fe)=>{Fe.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32")Fe.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")Fe.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var X0=k((aC,gs)=>{var _n=global.process,Bi=function(n){return n&&typeof n==="object"&&typeof n.removeListener==="function"&&typeof n.emit==="function"&&typeof n.reallyExit==="function"&&typeof n.listeners==="function"&&typeof n.kill==="function"&&typeof n.pid==="number"&&typeof n.on==="function"};if(!Bi(_n))gs.exports=function(){return function(){}};else{if(_h=p("assert"),Ni=J0(),wh=/^win/i.test(_n.platform),Ts=p("events"),typeof Ts!=="function")Ts=Ts.EventEmitter;if(_n.__signal_exit_emitter__)Tn=_n.__signal_exit_emitter__;else Tn=_n.__signal_exit_emitter__=new Ts,Tn.count=0,Tn.emitted={};if(!Tn.infinite)Tn.setMaxListeners(1/0),Tn.infinite=!0;gs.exports=function(n,t){if(!Bi(global.process))return function(){};if(_h.equal(typeof n,"function","a callback must be provided for exit handler"),Gi===!1)Pe();var i="exit";if(t&&t.alwaysLast)i="afterexit";var s=function(){if(Tn.removeListener(i,n),Tn.listeners("exit").length===0&&Tn.listeners("afterexit").length===0)Er()};return Tn.on(i,n),s},Er=function(){if(!Gi||!Bi(global.process))return;Gi=!1,Ni.forEach(function(t){try{_n.removeListener(t,yr[t])}catch(i){}}),_n.emit=Tr,_n.reallyExit=De,Tn.count-=1},gs.exports.unload=Er,pt=function(t,i,s){if(Tn.emitted[t])return;Tn.emitted[t]=!0,Tn.emit(t,i,s)},yr={},Ni.forEach(function(n){yr[n]=function(){if(!Bi(global.process))return;var i=_n.listeners(n);if(i.length===Tn.count){if(Er(),pt("exit",null,n),pt("afterexit",null,n),wh&&n==="SIGHUP")n="SIGINT";_n.kill(_n.pid,n)}}}),gs.exports.signals=function(){return Ni},Gi=!1,Pe=function(){if(Gi||!Bi(global.process))return;Gi=!0,Tn.count+=1,Ni=Ni.filter(function(t){try{return _n.on(t,yr[t]),!0}catch(i){return!1}}),_n.emit=Ah,_n.reallyExit=lh},gs.exports.load=Pe,De=_n.reallyExit,lh=function(t){if(!Bi(global.process))return;_n.exitCode=t||0,pt("exit",_n.exitCode,null),pt("afterexit",_n.exitCode,null),De.call(_n,_n.exitCode)},Tr=_n.emit,Ah=function(t,i){if(t==="exit"&&Bi(global.process)){if(i!==void 0)_n.exitCode=i;var s=Tr.apply(this,arguments);return pt("exit",_n.exitCode,null),pt("afterexit",_n.exitCode,null),s}else return Tr.apply(this,arguments)}}var _h,Ni,wh,Ts,Tn,Er,pt,yr,Gi,Pe,De,lh,Tr,Ah});var Q0=k((F2,Mh)=>{var z0=Symbol();function H2(n,t,i){let s=t[z0];if(s)return t.stat(n,(e,f)=>{if(e)return i(e);i(null,f.mtime,s)});let r=new Date(Math.ceil(Date.now()/1000)*1000+5);t.utimes(n,r,r,(e)=>{if(e)return i(e);t.stat(n,(f,o)=>{if(f)return i(f);let h=o.mtime.getTime()%1000===0?"s":"ms";Object.defineProperty(t,z0,{value:h}),i(null,o.mtime,h)})})}function W2(n){let t=Date.now();if(n==="s")t=Math.ceil(t/1000)*1000;return new Date(t)}F2.probe=H2;F2.getMtime=W2});var q0=k((C2,Sr)=>{var Y2=p("path"),Eh=ch(),m2=m0(),J2=X0(),C0=Q0(),Yt={};function gr(n,t){return t.lockfilePath||`${n}.lock`}function yh(n,t,i){if(!t.realpath)return i(null,Y2.resolve(n));t.fs.realpath(n,i)}function Rh(n,t,i){let s=gr(n,t);t.fs.mkdir(s,(r)=>{if(!r)return C0.probe(s,t.fs,(e,f,o)=>{if(e)return t.fs.rmdir(s,()=>{}),i(e);i(null,f,o)});if(r.code!=="EEXIST")return i(r);if(t.stale<=0)return i(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:n}));t.fs.stat(s,(e,f)=>{if(e){if(e.code==="ENOENT")return Rh(n,{...t,stale:0},i);return i(e)}if(!x0(f,t))return i(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:n}));K0(n,t,(o)=>{if(o)return i(o);Rh(n,{...t,stale:0},i)})})})}function x0(n,t){return n.mtime.getTime()<Date.now()-t.stale}function K0(n,t,i){t.fs.rmdir(gr(n,t),(s)=>{if(s&&s.code!=="ENOENT")return i(s);i()})}function Ye(n,t){let i=Yt[n];if(i.updateTimeout)return;if(i.updateDelay=i.updateDelay||t.update,i.updateTimeout=setTimeout(()=>{i.updateTimeout=null,t.fs.stat(i.lockfilePath,(s,r)=>{let e=i.lastUpdate+t.stale<Date.now();if(s){if(s.code==="ENOENT"||e)return dh(n,i,Object.assign(s,{code:"ECOMPROMISED"}));return i.updateDelay=1000,Ye(n,t)}if(i.mtime.getTime()!==r.mtime.getTime())return dh(n,i,Object.assign(Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let o=C0.getMtime(i.mtimePrecision);t.fs.utimes(i.lockfilePath,o,o,(h)=>{let u=i.lastUpdate+t.stale<Date.now();if(i.released)return;if(h){if(h.code==="ENOENT"||u)return dh(n,i,Object.assign(h,{code:"ECOMPROMISED"}));return i.updateDelay=1000,Ye(n,t)}i.mtime=o,i.lastUpdate=Date.now(),i.updateDelay=null,Ye(n,t)})})},i.updateDelay),i.updateTimeout.unref)i.updateTimeout.unref()}function dh(n,t,i){if(t.released=!0,t.updateTimeout)clearTimeout(t.updateTimeout);if(Yt[n]===t)delete Yt[n];t.options.onCompromised(i)}function X2(n,t,i){t={stale:1e4,update:null,realpath:!0,retries:0,fs:Eh,onCompromised:(s)=>{throw s},...t},t.retries=t.retries||0,t.retries=typeof t.retries==="number"?{retries:t.retries}:t.retries,t.stale=Math.max(t.stale||0,2000),t.update=t.update==null?t.stale/2:t.update||0,t.update=Math.max(Math.min(t.update,t.stale/2),1000),yh(n,t,(s,r)=>{if(s)return i(s);let e=m2.operation(t.retries);e.attempt(()=>{Rh(r,t,(f,o,h)=>{if(e.retry(f))return;if(f)return i(e.mainError());let u=Yt[r]={lockfilePath:gr(r,t),mtime:o,mtimePrecision:h,options:t,lastUpdate:Date.now()};Ye(r,t),i(null,(c)=>{if(u.released)return c&&c(Object.assign(Error("Lock is already released"),{code:"ERELEASED"}));k0(r,{...t,realpath:!1},c)})})})})}function k0(n,t,i){t={fs:Eh,realpath:!0,...t},yh(n,t,(s,r)=>{if(s)return i(s);let e=Yt[r];if(!e)return i(Object.assign(Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));e.updateTimeout&&clearTimeout(e.updateTimeout),e.released=!0,delete Yt[r],K0(r,t,i)})}function z2(n,t,i){t={stale:1e4,realpath:!0,fs:Eh,...t},t.stale=Math.max(t.stale||0,2000),yh(n,t,(s,r)=>{if(s)return i(s);t.fs.stat(gr(r,t),(e,f)=>{if(e)return e.code==="ENOENT"?i(null,!1):i(e);return i(null,!x0(f,t))})})}function Q2(){return Yt}J2(()=>{for(let n in Yt){let t=Yt[n].options;try{t.fs.rmdirSync(gr(n,t))}catch(i){}}});C2.lock=X2;C2.unlock=k0;C2.check=z2;C2.getLocks=Q2});var j0=k((vC,V0)=>{var V2=ch();function j2(n){let t=["mkdir","realpath","stat","rmdir","utimes"],i={...n};return t.forEach((s)=>{i[s]=(...r)=>{let e=r.pop(),f;try{f=n[`${s}Sync`](...r)}catch(o){return e(o)}e(null,f)}}),i}function a2(n){return(...t)=>new Promise((i,s)=>{t.push((r,e)=>{if(r)s(r);else i(e)}),n(...t)})}function v2(n){return(...t)=>{let i,s;if(t.push((r,e)=>{i=r,s=e}),n(...t),i)throw i;return s}}function Z2(n){if(n={...n},n.fs=j2(n.fs||V2),typeof n.retries==="number"&&n.retries>0||n.retries&&typeof n.retries.retries==="number"&&n.retries.retries>0)throw Object.assign(Error("Cannot use retries with the sync api"),{code:"ESYNC"});return n}V0.exports={toPromise:a2,toSync:v2,toSyncOptions:Z2}});var v0=k((ZC,ni)=>{var Ss=q0(),{toPromise:me,toSync:Je,toSyncOptions:Th}=j0();async function a0(n,t){let i=await me(Ss.lock)(n,t);return me(i)}function p2(n,t){let i=Je(Ss.lock)(n,Th(t));return Je(i)}function n6(n,t){return me(Ss.unlock)(n,t)}function t6(n,t){return Je(Ss.unlock)(n,Th(t))}function i6(n,t){return me(Ss.check)(n,t)}function s6(n,t){return Je(Ss.check)(n,Th(t))}ni.exports=a0;ni.exports.lock=a0;ni.exports.unlock=n6;ni.exports.lockSync=p2;ni.exports.unlockSync=t6;ni.exports.check=i6;ni.exports.checkSync=s6});var iw=k((ix,tw)=>{var Is=1000,Us=Is*60,bs=Us*60,Hi=bs*24,A6=Hi*7,M6=Hi*365.25;tw.exports=function(n,t){t=t||{};var i=typeof n;if(i==="string"&&n.length>0)return d6(n);else if(i==="number"&&isFinite(n))return t.long?E6(n):R6(n);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(n))};function d6(n){if(n=String(n),n.length>100)return;var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(n);if(!t)return;var i=parseFloat(t[1]),s=(t[2]||"ms").toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return i*M6;case"weeks":case"week":case"w":return i*A6;case"days":case"day":case"d":return i*Hi;case"hours":case"hour":case"hrs":case"hr":case"h":return i*bs;case"minutes":case"minute":case"mins":case"min":case"m":return i*Us;case"seconds":case"second":case"secs":case"sec":case"s":return i*Is;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return i;default:return}}function R6(n){var t=Math.abs(n);if(t>=Hi)return Math.round(n/Hi)+"d";if(t>=bs)return Math.round(n/bs)+"h";if(t>=Us)return Math.round(n/Us)+"m";if(t>=Is)return Math.round(n/Is)+"s";return n+"ms"}function E6(n){var t=Math.abs(n);if(t>=Hi)return Xe(n,t,Hi,"day");if(t>=bs)return Xe(n,t,bs,"hour");if(t>=Us)return Xe(n,t,Us,"minute");if(t>=Is)return Xe(n,t,Is,"second");return n+" ms"}function Xe(n,t,i,s){var r=t>=i*1.5;return Math.round(n/i)+" "+s+(r?"s":"")}});var Sh=k((sx,sw)=>{function y6(n){i.debug=i,i.default=i,i.coerce=h,i.disable=f,i.enable=r,i.enabled=o,i.humanize=iw(),i.destroy=u,Object.keys(n).forEach((c)=>{i[c]=n[c]}),i.names=[],i.skips=[],i.formatters={};function t(c){let _=0;for(let w=0;w<c.length;w++)_=(_<<5)-_+c.charCodeAt(w),_|=0;return i.colors[Math.abs(_)%i.colors.length]}i.selectColor=t;function i(c){let _,w=null,l,A;function d(...E){if(!d.enabled)return;let R=d,y=Number(new Date),T=y-(_||y);if(R.diff=T,R.prev=_,R.curr=y,_=y,E[0]=i.coerce(E[0]),typeof E[0]!=="string")E.unshift("%O");let S=0;E[0]=E[0].replace(/%([a-zA-Z%])/g,(F,C)=>{if(F==="%%")return"%";S++;let sn=i.formatters[C];if(typeof sn==="function"){let b=E[S];F=sn.call(R,b),E.splice(S,1),S--}return F}),i.formatArgs.call(R,E),(R.log||i.log).apply(R,E)}if(d.namespace=c,d.useColors=i.useColors(),d.color=i.selectColor(c),d.extend=s,d.destroy=i.destroy,Object.defineProperty(d,"enabled",{enumerable:!0,configurable:!1,get:()=>{if(w!==null)return w;if(l!==i.namespaces)l=i.namespaces,A=i.enabled(c);return A},set:(E)=>{w=E}}),typeof i.init==="function")i.init(d);return d}function s(c,_){let w=i(this.namespace+(typeof _>"u"?":":_)+c);return w.log=this.log,w}function r(c){i.save(c),i.namespaces=c,i.names=[],i.skips=[];let _=(typeof c==="string"?c:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let w of _)if(w[0]==="-")i.skips.push(w.slice(1));else i.names.push(w)}function e(c,_){let w=0,l=0,A=-1,d=0;while(w<c.length)if(l<_.length&&(_[l]===c[w]||_[l]==="*"))if(_[l]==="*")A=l,d=w,l++;else w++,l++;else if(A!==-1)l=A+1,d++,w=d;else return!1;while(l<_.length&&_[l]==="*")l++;return l===_.length}function f(){let c=[...i.names,...i.skips.map((_)=>"-"+_)].join(",");return i.enable(""),c}function o(c){for(let _ of i.skips)if(e(c,_))return!1;for(let _ of i.names)if(e(c,_))return!0;return!1}function h(c){if(c instanceof Error)return c.stack||c.message;return c}function u(){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 i.enable(i.load()),i}sw.exports=y6});var ew=k((rw,ze)=>{rw.formatArgs=g6;rw.save=S6;rw.load=I6;rw.useColors=T6;rw.storage=U6();rw.destroy=(()=>{let n=!1;return()=>{if(!n)n=!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`.")}})();rw.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 T6(){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 n;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&&(n=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(n[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function g6(n){if(n[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+n[0]+(this.useColors?"%c ":" ")+"+"+ze.exports.humanize(this.diff),!this.useColors)return;let t="color: "+this.color;n.splice(1,0,t,"color: inherit");let i=0,s=0;n[0].replace(/%[a-zA-Z%]/g,(r)=>{if(r==="%%")return;if(i++,r==="%c")s=i}),n.splice(s,0,t)}rw.log=console.debug||console.log||(()=>{});function S6(n){try{if(n)rw.storage.setItem("debug",n);else rw.storage.removeItem("debug")}catch(t){}}function I6(){let n;try{n=rw.storage.getItem("debug")||rw.storage.getItem("DEBUG")}catch(t){}if(!n&&typeof process<"u"&&"env"in process)n=process.env.DEBUG;return n}function U6(){try{return localStorage}catch(n){}}ze.exports=Sh()(rw);var{formatters:b6}=ze.exports;b6.j=function(n){try{return JSON.stringify(n)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}});var uw=k((fw,Ce)=>{var W6=p("tty"),Qe=p("util");fw.init=X6;fw.log=Y6;fw.formatArgs=P6;fw.save=m6;fw.load=J6;fw.useColors=F6;fw.destroy=Qe.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");fw.colors=[6,2,3,4,5,1];try{let n=(()=>{throw new Error("Cannot require module "+"supports-color");})();if(n&&(n.stderr||n).level>=2)fw.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(n){}fw.inspectOpts=Object.keys(process.env).filter((n)=>{return/^debug_/i.test(n)}).reduce((n,t)=>{let i=t.substring(6).toLowerCase().replace(/_([a-z])/g,(r,e)=>{return e.toUpperCase()}),s=process.env[t];if(/^(yes|on|true|enabled)$/i.test(s))s=!0;else if(/^(no|off|false|disabled)$/i.test(s))s=!1;else if(s==="null")s=null;else s=Number(s);return n[i]=s,n},{});function F6(){return"colors"in fw.inspectOpts?Boolean(fw.inspectOpts.colors):W6.isatty(process.stderr.fd)}function P6(n){let{namespace:t,useColors:i}=this;if(i){let s=this.color,r="\x1B[3"+(s<8?s:"8;5;"+s),e=` ${r};1m${t} \x1B[0m`;n[0]=e+n[0].split(`
|
|
4
5
|
`).join(`
|
|
5
|
-
`+e),
|
|
6
|
-
`)}function
|
|
7
|
-
`).map((
|
|
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 _.$responseBodyText<"u"){if(_.$response)_.$response.body=_.$responseBodyText}try{if(Qb.isInstance(i)){let{headers:w={},statusCode:A}=i,M=Object.entries(w);_.$metadata={httpStatusCode:A,requestId:_f(/^x-[\w-]+-request-?id$/,M),extendedRequestId:_f(/^x-[\w-]+-id-2$/,M),cfId:_f(/^x-[\w-]+-cf-id$/,M)}}}catch(w){}}throw _}},_f=(t,n)=>{return(n.find(([s])=>{return s.match(t)})||[void 0,void 0])[1]},Xb=(t)=>(n,s)=>async(r)=>{let{operationSchema:i}=_u(s),[,e,f,o,c,h]=i??[],u=s.endpointV2?async()=>Jb(s.endpointV2):t.endpoint,_=await t.protocol.serializeRequest(wf(e,f,o,c,h),r.input,{...t,...s,endpoint:u});return n({...r,request:_})},lu={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},wu={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function zb(t){return{applyToStack:(n)=>{n.add(Xb(t),wu),n.add(kb(t),lu),t.protocol.setSerdeContext(t)}}}class Tt{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 qi extends Tt{static symbol=Symbol.for("@smithy/lis");name;traits;valueSchema;symbol=qi.symbol}var xb=(t,n,s,r)=>Tt.assign(new qi,{name:n,namespace:t,traits:s,valueSchema:r});class Ci extends Tt{static symbol=Symbol.for("@smithy/map");name;traits;keySchema;valueSchema;symbol=Ci.symbol}var qb=(t,n,s,r,i)=>Tt.assign(new Ci,{name:n,namespace:t,traits:s,keySchema:r,valueSchema:i});class Ki extends Tt{static symbol=Symbol.for("@smithy/ope");name;traits;input;output;symbol=Ki.symbol}var Cb=(t,n,s,r,i)=>Tt.assign(new Ki,{name:n,namespace:t,traits:s,input:r,output:i});class Nr extends Tt{static symbol=Symbol.for("@smithy/str");name;traits;memberNames;memberList;symbol=Nr.symbol}var Kb=(t,n,s,r,i)=>Tt.assign(new Nr,{name:n,namespace:t,traits:s,memberNames:r,memberList:i});class Vi extends Nr{static symbol=Symbol.for("@smithy/err");ctor;symbol=Vi.symbol}var Vb=(t,n,s,r,i,e)=>Tt.assign(new Vi,{name:n,namespace:t,traits:s,memberNames:r,memberList:i,ctor:null}),Xi=[];function Pr(t){if(typeof t==="object")return t;if(t=t|0,Xi[t])return Xi[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 Xi[t]=n}var Fr={it:Symbol.for("@smithy/nor-struct-it"),ns:Symbol.for("@smithy/ns")},zi=[],xi={};class dn{ref;memberName;static symbol=Symbol.for("@smithy/nor");symbol=dn.symbol;name;schema;_isMemberSchema;traits;memberTraits;normalizedTraits;constructor(t,n){this.ref=t,this.memberName=n;let s=[],r=t,i=t;this._isMemberSchema=!1;while(lf(r))s.push(r[1]),r=r[0],i=ki(r),this._isMemberSchema=!0;if(s.length>0){this.memberTraits={};for(let e=s.length-1;e>=0;--e){let f=s[e];Object.assign(this.memberTraits,Pr(f))}}else this.memberTraits=0;if(i instanceof dn){let e=this.memberTraits;Object.assign(this,i),this.memberTraits=Object.assign({},e,i.getMemberTraits(),this.getMemberTraits()),this.normalizedTraits=void 0,this.memberName=n??i.memberName;return}if(this.schema=ki(i),Au(this.schema))this.name=`${this.schema[1]}#${this.schema[2]}`,this.traits=this.schema[3];else this.name=this.memberName??String(i),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(zi[t])return zi[t]}else if(typeof t==="string"){if(xi[t])return xi[t]}else if(n){if(t[Fr.ns])return t[Fr.ns]}let s=ki(t);if(s instanceof dn)return s;if(lf(s)){let[i,e]=s;if(i instanceof dn)return Object.assign(i.getMergedTraits(),Pr(e)),i;throw Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(t,null,2)}.`)}let r=new dn(s);if(n)return t[Fr.ns]=r;if(typeof s==="string")return xi[s]=r;if(typeof s==="number")return zi[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 Pr(this.memberTraits)}getOwnTraits(){return Pr(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 Hr([r,0],"key")}getValueSchema(){let t=this.getSchema(),[n,s,r]=[this.isDocumentSchema(),this.isMapSchema(),this.isListSchema()],i=typeof t==="number"?63&t:t&&typeof t==="object"&&(s||r)?t[3+t[0]]:n?15:void 0;if(i!=null)return Hr([i,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 Hr(lf(r)?r:[r,0],t)}if(this.isDocumentSchema())return Hr([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[Fr.it];if(s&&n===s.length){yield*s;return}s=Array(n);for(let r=0;r<n;++r){let i=t[4][r],e=Hr([t[5][r],0],i);yield s[r]=[i,e]}t[Fr.it]=s}}function Hr(t,n){if(t instanceof dn)return Object.assign(t,{memberName:n,_isMemberSchema:!0});return new dn(t,n)}var lf=(t)=>Array.isArray(t)&&t.length===2,Au=(t)=>Array.isArray(t)&&t.length>=5;class Wr extends Tt{static symbol=Symbol.for("@smithy/sim");name;schemaRef;traits;symbol=Wr.symbol}var jb=(t,n,s,r)=>Tt.assign(new Wr,{name:n,namespace:t,traits:r,schemaRef:s}),ab=(t,n,s,r)=>Tt.assign(new Wr,{name:n,namespace:t,traits:s,schemaRef:r}),pb={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 En{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(!En.registries.has(t))En.registries.set(t,new En(t));return En.registries.get(t)}copyFrom(t){let{schemas:n,exceptions:s}=this;for(let[r,i]of t.schemas)if(!n.has(r))n.set(r,i);for(let[r,i]of t.exceptions)if(!s.has(r))s.set(r,i)}register(t,n){let s=this.normalizeShapeId(t);for(let r of[this,En.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[i,e]of this.schemas.entries())if(i.endsWith(s))r.push(e);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 i of[this,En.for(r)])i.schemas.set(r+"#"+s[2],s),i.exceptions.set(s,n)}getErrorCtor(t){let n=t;if(this.exceptions.has(n))return this.exceptions.get(n);return En.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}}Zb.ErrorSchema=Vi;Zb.ListSchema=qi;Zb.MapSchema=Ci;Zb.NormalizedSchema=dn;Zb.OperationSchema=Ki;Zb.SCHEMA=pb;Zb.Schema=Tt;Zb.SimpleSchema=Wr;Zb.StructureSchema=Nr;Zb.TypeRegistry=En;Zb.deref=ki;Zb.deserializerMiddlewareOption=lu;Zb.error=Vb;Zb.getSchemaSerdePlugin=zb;Zb.isStaticSchema=Au;Zb.list=xb;Zb.map=qb;Zb.op=Cb;Zb.operation=wf;Zb.serializerMiddlewareOption=wu;Zb.sim=jb;Zb.simAdapter=ab;Zb.simpleSchemaCacheN=zi;Zb.simpleSchemaCacheS=xi;Zb.struct=Kb;Zb.traitsCache=Xi;Zb.translateTraits=Pr});var Rn=Z((e2)=>{var{getSmithyContext:I4,normalizeProvider:O4}=nn();e2.getSmithyContext=I4;e2.normalizeProvider=O4;var{SMITHY_CONTEXT_KEY:y4,AlgorithmId:ai}=is();e2.AlgorithmId=ai;var{NormalizedSchema:G4}=Nn(),es=(t,n)=>{let s=[];if(t)s.push(t);if(n)for(let r of n)s.push(r);return s},Wn=(t,n)=>{return`${t||"anonymous"}${n&&n.length>0?` (a.k.a. ${n.join(",")})`:""}`},Dr=()=>{let t=[],n=[],s=!1,r=new Set,i=(_)=>_.sort((l,w)=>Mu[w.step]-Mu[l.step]||gu[w.priority||"normal"]-gu[l.priority||"normal"]),e=(_)=>{let l=!1,w=(A)=>{let M=es(A.name,A.aliases);if(M.includes(_)){l=!0;for(let E of M)r.delete(E);return!1}return!0};return t=t.filter(w),n=n.filter(w),l},f=(_)=>{let l=!1,w=(A)=>{if(A.middleware===_){l=!0;for(let M of es(A.name,A.aliases))r.delete(M);return!1}return!0};return t=t.filter(w),n=n.filter(w),l},o=(_)=>{return t.forEach((l)=>{_.add(l.middleware,{...l})}),n.forEach((l)=>{_.addRelativeTo(l.middleware,{...l})}),_.identifyOnResolve?.(u.identifyOnResolve()),_},c=(_)=>{let l=[];return _.before.forEach((w)=>{if(w.before.length===0&&w.after.length===0)l.push(w);else l.push(...c(w))}),l.push(_),_.after.reverse().forEach((w)=>{if(w.before.length===0&&w.after.length===0)l.push(w);else l.push(...c(w))}),l},h=(_=!1)=>{let l=[],w=[],A={};return t.forEach((E)=>{let d={...E,before:[],after:[]};for(let T of es(d.name,d.aliases))A[T]=d;l.push(d)}),n.forEach((E)=>{let d={...E,before:[],after:[]};for(let T of es(d.name,d.aliases))A[T]=d;w.push(d)}),w.forEach((E)=>{if(E.toMiddleware){let d=A[E.toMiddleware];if(d===void 0){if(_)return;throw Error(`${E.toMiddleware} is not found when adding ${Wn(E.name,E.aliases)} middleware ${E.relation} ${E.toMiddleware}`)}if(E.relation==="after")d.after.push(E);if(E.relation==="before")d.before.push(E)}}),i(l).map(c).reduce((E,d)=>{return E.push(...d),E},[])},u={add:(_,l={})=>{let{name:w,override:A,aliases:M}=l,E={step:"initialize",priority:"normal",middleware:_,...l},d=es(w,M);if(d.length>0){if(d.some((T)=>r.has(T))){if(!A)throw Error(`Duplicate middleware name '${Wn(w,M)}'`);for(let T of d){let U=t.findIndex((O)=>O.name===T||O.aliases?.some((D)=>D===T));if(U===-1)continue;let S=t[U];if(S.step!==E.step||E.priority!==S.priority)throw Error(`"${Wn(S.name,S.aliases)}" middleware with ${S.priority} priority in ${S.step} step cannot be overridden by "${Wn(w,M)}" middleware with ${E.priority} priority in ${E.step} step.`);t.splice(U,1)}}for(let T of d)r.add(T)}t.push(E)},addRelativeTo:(_,l)=>{let{name:w,override:A,aliases:M}=l,E={middleware:_,...l},d=es(w,M);if(d.length>0){if(d.some((T)=>r.has(T))){if(!A)throw Error(`Duplicate middleware name '${Wn(w,M)}'`);for(let T of d){let U=n.findIndex((O)=>O.name===T||O.aliases?.some((D)=>D===T));if(U===-1)continue;let S=n[U];if(S.toMiddleware!==E.toMiddleware||S.relation!==E.relation)throw Error(`"${Wn(S.name,S.aliases)}" middleware ${S.relation} "${S.toMiddleware}" middleware cannot be overridden by "${Wn(w,M)}" middleware ${E.relation} "${E.toMiddleware}" middleware.`);n.splice(U,1)}}for(let T of d)r.add(T)}n.push(E)},clone:()=>o(Dr()),use:(_)=>{_.applyToStack(u)},remove:(_)=>{if(typeof _==="string")return e(_);else return f(_)},removeByTag:(_)=>{let l=!1,w=(A)=>{let{tags:M,name:E,aliases:d}=A;if(M&&M.includes(_)){let T=es(E,d);for(let U of T)r.delete(U);return l=!0,!1}return!0};return t=t.filter(w),n=n.filter(w),l},concat:(_)=>{let l=o(Dr());return l.use(_),l.identifyOnResolve(s||l.identifyOnResolve()||(_.identifyOnResolve?.()??!1)),l},applyToStack:o,identify:()=>{return h(!0).map((_)=>{let l=_.step??_.relation+" "+_.toMiddleware;return Wn(_.name,_.aliases)+" - "+l})},identifyOnResolve(_){if(typeof _==="boolean")s=_;return s},resolve:(_,l)=>{for(let w of h().map((A)=>A.middleware).reverse())_=w(_,l);if(s)console.log(u.identify());return _}};return u},Mu={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},gu={high:3,normal:2,low:1},B4=(t)=>()=>{throw Error(t)},F4=(t)=>()=>Promise.reject(t),ji=()=>{let t=new WeakSet;return(n,s)=>{if(typeof s==="object"&&s!==null){if(t.has(s))return"[Circular]";t.add(s)}return s}},H4=(t)=>{return new Promise((n)=>setTimeout(n,t*1000))},Ru={minDelay:2,maxDelay:120},sn;(function(t){t.ABORTED="ABORTED",t.FAILURE="FAILURE",t.SUCCESS="SUCCESS",t.RETRY="RETRY",t.TIMEOUT="TIMEOUT"})(sn||(sn={}));var P4=(t)=>{if(t.state===sn.ABORTED){let n=Error(`${JSON.stringify({...t,reason:"Request was aborted"},ji())}`);throw n.name="AbortError",n}else if(t.state===sn.TIMEOUT){let n=Error(`${JSON.stringify({...t,reason:"Waiter has timed out"},ji())}`);throw n.name="TimeoutError",n}else if(t.state!==sn.SUCCESS)throw Error(`${JSON.stringify(t,ji())}`);return t},N4=async({minDelay:t,maxDelay:n,maxWaitTime:s,abortController:r,client:i,abortSignal:e},f,o)=>{let c={},[h,u]=[t*1000,n*1000],_=0,l=Date.now()+s*1000,w=Date.now()+60000,A=!1;while(!0){if(_>0){let d=Y4(h,u,_,l);if(r?.signal?.aborted||e?.aborted)return c["AbortController signal aborted."]|=0,c["AbortController signal aborted."]+=1,{state:sn.ABORTED,observedResponses:c};if(Date.now()+d>l)return{state:sn.TIMEOUT,observedResponses:c};await H4(d/1000)}let{state:M,reason:E}=await o(i,f);if(E){let d=D4(E);c[d]|=0,c[d]+=1}if(M!==sn.RETRY)return{state:M,reason:E,final:E,observedResponses:c};if(_+=1,!A&&Date.now()>=w)W4(c,i),A=!0}},W4=(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 i=n?.config?.logger,e=typeof i?.warn==="function"&&!i.constructor?.name?.includes?.("NoOpLogger")?i:console;if(r>=3||s[s.length-1]?.startsWith("403:"))e.warn("@smithy/util-waiter WARN - 403 status code encountered during waiter polling.")},D4=(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,ji())??"Unknown")},Y4=(t,n,s,r)=>{let i=Math.log(n/t)/Math.log(2)+1;if(s>i)return n;let e=t*2**(s-1),f=Math.min(e,n),o=m4(t,f);if(Date.now()+o>r){let c=r-Date.now();return Math.max(0,c-500)}return o},m4=(t,n)=>t+Math.random()*(n-t),Q4=(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`)},Eu=(t)=>{let n,s=new Promise((r)=>{if(n=()=>r({state:sn.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}},J4=async(t,n,s)=>{let r={...Ru,...t};Q4(r);let i=[N4(r,n,s)],e=[];if(t.abortSignal){let{aborted:f,clearListener:o}=Eu(t.abortSignal);e.push(o),i.push(f)}if(t.abortController?.signal){let{aborted:f,clearListener:o}=Eu(t.abortController.signal);e.push(o),i.push(f)}return Promise.race(i).then((f)=>{for(let o of e)o();return f})};class bu{config;middlewareStack=Dr();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,i=typeof n==="function"?n:s,e=r===void 0&&this.config.cacheMiddleware===!0,f;if(e){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(i)f(t).then((o)=>i(null,o.output),(o)=>i(o)).catch(()=>{});else return f(t).then((o)=>o.output)}destroy(){this.config?.requestHandler?.destroy?.(),delete this.handlers}}var Af="***SensitiveInformation***";function pi(t,n){if(n==null)return n;let s=G4.of(t);if(s.getMergedTraits().sensitive)return Af;if(s.isListSchema()){if(!!s.getValueSchema().getMergedTraits().sensitive)return Af}else if(s.isMapSchema()){if(!!s.getKeySchema().getMergedTraits().sensitive||!!s.getValueSchema().getMergedTraits().sensitive)return Af}else if(s.isStructSchema()&&typeof n==="object"){let r=n,i={};for(let[e,f]of s.structIterator())if(r[e]!=null)i[e]=pi(f,r[e]);return i}return n}class Zi{middlewareStack=Dr();schema;static classBuilder(){return new Tu}resolveMiddlewareWithContext(t,n,s,{middlewareFn:r,clientName:i,commandName:e,inputFilterSensitiveLog:f,outputFilterSensitiveLog:o,smithyContext:c,additionalContext:h,CommandCtor:u}){for(let E of r.bind(this)(u,t,n,s))this.middlewareStack.use(E);let _=t.concat(this.middlewareStack),{logger:l}=n,w={logger:l,clientName:i,commandName:e,inputFilterSensitiveLog:f,outputFilterSensitiveLog:o,[y4]:{commandInstance:this,...c},...h},{requestHandler:A}=n,M=s??{};if(c.eventStream)M={isEventStream:!0,...M};return _.resolve((E)=>A.handle(E.request,M),w)}}class Tu{_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 Zi{input;static getEndpointParameterInstructions(){return t._ep}constructor(...[s]){super();this.input=s??{},t._init(this),this.schema=t._operationSchema}resolveMiddleware(s,r,i){let e=t._operationSchema,f=e?.[4]??e?.input,o=e?.[5]??e?.output;return this.resolveMiddlewareWithContext(s,r,i,{CommandCtor:n,middlewareFn:t._middlewareFn,clientName:t._clientName,commandName:t._commandName,inputFilterSensitiveLog:t._inputFilterSensitiveLog??(e?pi.bind(null,f):(c)=>c),outputFilterSensitiveLog:t._outputFilterSensitiveLog??(e?pi.bind(null,o):(c)=>c),smithyContext:t._smithyContext,additionalContext:t._additionalContext})}serialize=t._serializer;deserialize=t._deserializer}}}var k4="***SensitiveInformation***",X4=(t,n,s)=>{for(let[e,f]of Object.entries(t)){let o=async function(h,u,_){let l=new f(h);if(typeof u==="function")this.send(l,u);else if(typeof _==="function"){if(typeof u!=="object")throw Error(`Expected http options but got ${typeof u}`);this.send(l,u||{},_)}else return this.send(l,u)},c=(e[0].toLowerCase()+e.slice(1)).replace(/Command$/,"");n.prototype[c]=o}let{paginators:r={},waiters:i={}}=s??{};for(let[e,f]of Object.entries(r))if(n.prototype[e]===void 0)n.prototype[e]=function(o={},c,...h){return f({...c,client:this},o,...h)};for(let[e,f]of Object.entries(i))if(n.prototype[e]===void 0)n.prototype[e]=async function(o={},c,...h){let u=c;if(typeof c==="number")u={maxWaitTime:c};return f({...u,client:this},o,...h)}};class Js 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 Js.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===Js)return Js.isInstance(t);if(Js.isInstance(t)){if(n.name&&this.name)return this.prototype.isPrototypeOf(t)||n.name===this.name;return this.prototype.isPrototypeOf(t)}return!1}}var Su=(t,n={})=>{Object.entries(n).filter(([,r])=>r!==void 0).forEach(([r,i])=>{if(t[r]==null||t[r]==="")t[r]=i});let s=t.message||t.Message||"UnknownError";return t.message=s,delete t.Message,t},$u=({output:t,parsedBody:n,exceptionCtor:s,errorCode:r})=>{let i=x4(t),e=i.httpStatusCode?i.httpStatusCode+"":void 0,f=new s({name:n?.code||n?.Code||r||e||"UnknownError",$fault:"client",$metadata:i});throw Su(f,n)},z4=(t)=>{return({output:n,parsedBody:s,errorCode:r})=>{$u({output:n,parsedBody:s,exceptionCtor:t,errorCode:r})}},x4=(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"]}),q4=(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{}}},du=!1,C4=(t)=>{if(t&&!du&&parseInt(t.substring(1,t.indexOf(".")))<16)du=!0},Uu=Object.values(ai),Lu=(t)=>{let n=[];for(let s in ai){let r=ai[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(),i=s.checksumConstructor();if(Uu.includes(r))t.checksumAlgorithms[r.toUpperCase()]=i;else t.checksumAlgorithms[r]=i;n.push(s)},checksumAlgorithms(){return n}}},Iu=(t)=>{let n={};return t.checksumAlgorithms().forEach((s)=>{let r=s.algorithmId();if(Uu.includes(r))n[r]=s.checksumConstructor()}),n},Ou=(t)=>{return{setRetryStrategy(n){t.retryStrategy=n},retryStrategy(){return t.retryStrategy}}},yu=(t)=>{let n={};return n.retryStrategy=t.retryStrategy(),n},Gu=(t)=>{return Object.assign(Lu(t),Ou(t))},K4=Gu,V4=(t)=>{return Object.assign(Iu(t),yu(t))},j4=(t)=>Array.isArray(t)?t:[t],Bu=(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]=Bu(t[s]);return t},a4=(t)=>{return t!=null};class Fu{trace(){}debug(){}info(){}warn(){}error(){}}function Hu(t,n,s){let r,i,e;if(typeof n>"u"&&typeof s>"u")r={},e=t;else if(r=t,typeof n==="function")return i=n,e=s,v4(r,i,e);else e=n;for(let f of Object.keys(e)){if(!Array.isArray(e[f])){r[f]=e[f];continue}Pu(r,null,e,f)}return r}var p4=(t)=>{let n={};for(let[s,r]of Object.entries(t||{}))n[s]=[,r];return n},Z4=(t,n)=>{let s={};for(let r in n)Pu(s,t,n,r);return s},v4=(t,n,s)=>{return Hu(t,Object.entries(s).reduce((r,[i,e])=>{if(Array.isArray(e))r[i]=e;else if(typeof e==="function")r[i]=[n,e()];else r[i]=[n,e];return r},{}))},Pu=(t,n,s,r)=>{if(n!==null){let f=s[r];if(typeof f==="function")f=[,f];let[o=t2,c=n2,h=r]=f;if(typeof o==="function"&&o(n[h])||typeof o!=="function"&&!!o)t[r]=c(n[h]);return}let[i,e]=s[r];if(typeof e==="function"){let f,o=i===void 0&&(f=e())!=null,c=typeof i==="function"&&!!i(void 0)||typeof i!=="function"&&!!i;if(o)t[r]=f;else if(c)t[r]=e()}else{let f=i===void 0&&e!=null,o=typeof i==="function"&&!!i(e)||typeof i!=="function"&&!!i;if(f||o)t[r]=e}},t2=(t)=>t!=null,n2=(t)=>t,s2=(t)=>{if(t!==t)return"NaN";switch(t){case 1/0:return"Infinity";case-1/0:return"-Infinity";default:return t}},r2=(t)=>t.toISOString().replace(".000Z","Z"),Mf=(t)=>{if(t==null)return{};if(Array.isArray(t))return t.filter((n)=>n!=null).map(Mf);if(typeof t==="object"){let n={};for(let s of Object.keys(t)){if(t[s]==null)continue;n[s]=Mf(t[s])}return n}return t};function i2(t,n,s,r){return function(e,f,o,c,h={}){let u=Object.assign({},t,e);return Zi.classBuilder().ep(u).m(function(_,l,w,A){let M=f.call(this,_,l,w,A);return M.unshift(r(w,_.getEndpointParameterInstructions())),M}).s(n,o,h).n(s,o.charAt(0).toUpperCase()+o.slice(1)+"Command").sc(c).build()}}e2.Client=bu;e2.Command=Zi;e2.NoOpLogger=Fu;e2.SENSITIVE_STRING=k4;e2.ServiceException=Js;e2.WaiterState=sn;e2._json=Mf;e2.checkExceptions=P4;e2.constructStack=Dr;e2.convertMap=p4;e2.createAggregatedClient=X4;e2.createWaiter=J4;e2.decorateServiceException=Su;e2.emitWarningIfUnsupportedVersion=C4;e2.getArrayIfSingleItem=j4;e2.getChecksumConfiguration=Lu;e2.getDefaultClientConfiguration=K4;e2.getDefaultExtensionConfiguration=Gu;e2.getRetryConfiguration=Ou;e2.getValueFromTextNode=Bu;e2.invalidFunction=B4;e2.invalidProvider=F4;e2.isSerializableHeaderValue=a4;e2.loadConfigsForDefaultMode=q4;e2.makeBuilder=i2;e2.map=Hu;e2.resolveChecksumRuntimeConfig=Iu;e2.resolveDefaultRuntimeConfig=V4;e2.resolveRetryRuntimeConfig=yu;e2.schemaLogFilter=pi;e2.serializeDateTime=r2;e2.serializeFloat=s2;e2.take=Z4;e2.throwDefaultError=$u;e2.waiterServiceDefaults=Ru;e2.withBaseException=z4});var St=Z((qT)=>{var{homedir:q2}=nt("os"),{sep:C2,join:Yr}=nt("path"),{createHash:K2}=nt("crypto"),{readFile:Xu}=nt("fs/promises"),{IniSectionType:vi}=is(),{normalizeProvider:te}=Rn(),{isValidHostLabel:V2}=nn();class ks 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,ks.prototype),s?.debug?.(`@smithy/property-provider ${r?"->":"(!)"} ${t}`)}static from(t,n=!0){return Object.assign(new this(t.message,n),t)}}class mr extends ks{name="CredentialsProviderError";constructor(t,n=!0){super(t,n);Object.setPrototypeOf(this,mr.prototype)}}class bf extends ks{name="TokenProviderError";constructor(t,n=!0){super(t,n);Object.setPrototypeOf(this,bf.prototype)}}var zu=(...t)=>async()=>{if(t.length===0)throw new ks("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},xu=(t)=>()=>Promise.resolve(t),Tf=(t,n,s)=>{let r,i,e,f=!1,o=async()=>{if(!i)i=t();try{r=await i,e=!0,f=!1}finally{i=void 0}return r};if(n===void 0)return async(c)=>{if(!e||c?.forceRefresh)r=await o();return r};return async(c)=>{if(!e||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}},bn=(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]}.`)},j2=(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 gf={},a2=()=>{if(process&&process.geteuid)return`${process.geteuid()}`;return"DEFAULT"},Qr=()=>{let{HOME:t,USERPROFILE:n,HOMEPATH:s,HOMEDRIVE:r=`C:${C2}`}=process.env;if(t)return t;if(n)return n;if(s)return`${r}${s}`;let i=a2();if(!gf[i])gf[i]=q2();return gf[i]},qu="AWS_PROFILE",Cu="default",Ku=(t)=>t.profile||process.env[qu]||Cu,Vu=(t)=>{let s=K2("sha1").update(t).digest("hex");return Yr(Qr(),".aws","sso","cache",`${s}.json`)},ne={},p2=async(t)=>{if(ne[t])return ne[t];let n=Vu(t),s=await Xu(n,"utf8");return JSON.parse(s)},os=".",Z2=(t)=>Object.entries(t).filter(([n])=>{let s=n.indexOf(os);if(s===-1)return!1;return Object.values(vi).includes(n.substring(0,s))}).reduce((n,[s,r])=>{let i=s.indexOf(os),e=s.substring(0,i)===vi.PROFILE?s.substring(i+1):s;return n[e]=r,n},{...t.default&&{default:t.default}}),v2="AWS_CONFIG_FILE",ju=()=>process.env[v2]||Yr(Qr(),".aws","config"),tT="AWS_SHARED_CREDENTIALS_FILE",nT=()=>process.env[tT]||Yr(Qr(),".aws","credentials"),sT=/^([\w-]+)\s(["'])?([\w-@+.%:/]+)\2$/,rT=["__proto__","profile __proto__"],df=(t)=>{let n={},s,r;for(let i of t.split(/\r?\n/)){let e=i.split(/(^|\s)[;#]/)[0].trim();if(e[0]==="["&&e[e.length-1]==="]"){s=void 0,r=void 0;let o=e.substring(1,e.length-1),c=sT.exec(o);if(c){let[,h,,u]=c;if(Object.values(vi).includes(h))s=[h,u].join(os)}else s=o;if(rT.includes(o))throw Error(`Found invalid profile name "${o}"`)}else if(s){let o=e.indexOf("=");if(![0,-1].includes(o)){let[c,h]=[e.substring(0,o).trim(),e.substring(o+1).trim()];if(h==="")r=c;else{if(r&&i.trimStart()===i)r=void 0;n[s]=n[s]||{};let u=r?[r,c].join(os):c;n[s][u]=h}}}}return n},Ef={},se={},re=(t,n)=>{if(se[t]!==void 0)return se[t];if(!Ef[t]||n?.ignoreCache)Ef[t]=Xu(t,"utf8");return Ef[t]},Nu=()=>({}),Sf=async(t={})=>{let{filepath:n=nT(),configFilepath:s=ju()}=t,r=Qr(),i="~/",e=n;if(n.startsWith("~/"))e=Yr(r,n.slice(2));let f=s;if(s.startsWith("~/"))f=Yr(r,s.slice(2));let o=await Promise.all([re(f,{ignoreCache:t.ignoreCache}).then(df).then(Z2).catch(Nu),re(e,{ignoreCache:t.ignoreCache}).then(df).catch(Nu)]);return{configFile:o[0],credentialsFile:o[1]}},iT=(t)=>Object.entries(t).filter(([n])=>n.startsWith(vi.SSO_SESSION+os)).reduce((n,[s,r])=>({...n,[s.substring(s.indexOf(os)+1)]:r}),{}),eT=()=>({}),oT=async(t={})=>re(t.configFilepath??ju()).then(df).then(iT).catch(eT),fT=(...t)=>{let n={};for(let s of t)for(let[r,i]of Object.entries(s))if(n[r]!==void 0)Object.assign(n[r],i);else n[r]=i;return n},cT=async(t)=>{let n=await Sf(t);return fT(n.configFile,n.credentialsFile)},hT={getFileRecord(){return se},interceptFile(t,n){se[t]=Promise.resolve(n)},getTokenRecord(){return ne},interceptToken(t,n){ne[t]=n}};function au(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 uT=(t,n)=>async()=>{try{let s=t(process.env,n);if(s===void 0)throw Error();return s}catch(s){throw new mr(s.message||`Not found in ENV: ${au(t.toString())}`,{logger:n?.logger})}},_T=(t,{preferredFile:n="config",...s}={})=>async()=>{let r=Ku(s),{configFile:i,credentialsFile:e}=await Sf(s),f=e[r]||{},o=i[r]||{},c=n==="config"?{...f,...o}:{...o,...f};try{let u=t(c,n==="config"?i:e);if(u===void 0)throw Error();return u}catch(h){throw new mr(h.message||`Not found in config files w/ profile [${r}]: ${au(t.toString())}`,{logger:s.logger})}},lT=(t)=>typeof t==="function",pu=(t)=>lT(t)?async()=>await t():xu(t),Rf=({environmentVariableSelector:t,configFileSelector:n,default:s},r={})=>{let{signingName:i,logger:e}=r;return Tf(zu(uT(t,{signingName:i,logger:e}),_T(n,r),pu(s)))},$f="AWS_USE_DUALSTACK_ENDPOINT",Uf="use_dualstack_endpoint",wT=!1,AT={environmentVariableSelector:(t)=>bn(t,$f,zt.ENV),configFileSelector:(t)=>bn(t,Uf,zt.CONFIG),default:!1},MT={environmentVariableSelector:(t)=>bn(t,$f,zt.ENV),configFileSelector:(t)=>bn(t,Uf,zt.CONFIG),default:void 0},Lf="AWS_USE_FIPS_ENDPOINT",If="use_fips_endpoint",gT=!1,ET={environmentVariableSelector:(t)=>bn(t,Lf,zt.ENV),configFileSelector:(t)=>bn(t,If,zt.CONFIG),default:!1},dT={environmentVariableSelector:(t)=>bn(t,Lf,zt.ENV),configFileSelector:(t)=>bn(t,If,zt.CONFIG),default:void 0},RT=(t)=>{let{tls:n,endpoint:s,urlParser:r,useDualstackEndpoint:i}=t;return Object.assign(t,{tls:n??!0,endpoint:te(typeof s==="string"?r(s):s),isCustomEndpoint:!0,useDualstackEndpoint:te(i??!1)})},bT=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 i=await t.useDualstackEndpoint(),e=await t.useFipsEndpoint(),{hostname:f}=await t.regionInfoProvider(s,{useDualstackEndpoint:i,useFipsEndpoint:e})??{};if(!f)throw Error("Cannot resolve hostname from client config");return t.urlParser(`${n?"https:":"http:"}//${f}`)},TT=(t)=>{let n=te(t.useDualstackEndpoint??!1),{endpoint:s,useFipsEndpoint:r,urlParser:i,tls:e}=t;return Object.assign(t,{tls:e??!0,endpoint:s?te(typeof s==="string"?i(s):s):()=>bT({...t,useDualstackEndpoint:n,useFipsEndpoint:r}),isCustomEndpoint:!!s,useDualstackEndpoint:n})},ST="AWS_EXECUTION_ENV",Wu="AWS_REGION",Du="AWS_DEFAULT_REGION",$T="AWS_EC2_METADATA_DISABLED",UT=["in-region","cross-region","mobile","standard","legacy"],LT="/latest/meta-data/placement/region",IT="/latest/api/token",OT="x-aws-ec2-metadata-token",yT="x-aws-ec2-metadata-token-ttl-seconds",Yu=1000,GT=60000,Zu=0,vu=async()=>{if(process.env[$T])return;if(Date.now()<Zu)return;try{let t=BT(),n=(await Qu({...t,path:IT,method:"PUT",headers:{[yT]:"21600"}})).toString();return(await Qu({...t,path:LT,method:"GET",headers:{[OT]:n}})).toString().trim()||mu()}catch{return mu()}},mu=()=>{Zu=Date.now()+GT;return},BT=()=>{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"}},Qu=async(t)=>{let{request:n}=nt("http");return new Promise((s,r)=>{let i=n({hostname:t.hostname,port:t.port,path:t.path,method:t.method,headers:t.headers,timeout:Yu,signal:AbortSignal.timeout(Yu)});i.on("error",(e)=>{r(e),i.destroy()}),i.on("timeout",()=>{r(Error("TimeoutError from instance metadata service")),i.destroy()}),i.on("response",(e)=>{let{statusCode:f=400}=e;if(f<200||f>=300){r(Object.assign(Error("Error response received from instance metadata service"),{statusCode:f})),i.destroy();return}let o=[];e.on("data",(c)=>o.push(c)),e.on("end",()=>{s(Buffer.concat(o)),i.destroy()})}),i.end()})},t_="AWS_REGION",n_="region",s_={environmentVariableSelector:(t)=>t[t_],configFileSelector:(t)=>t[n_],default:async()=>{let t=await vu();if(t)return t;throw Error("Region is missing")}},FT={preferredFile:"credentials"},Ju=new Set,HT=(t,n=V2)=>{if(!Ju.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 Ju.add(t)},r_=(t)=>typeof t==="string"&&(t.startsWith("fips-")||t.endsWith("-fips")),PT=(t)=>r_(t)?["fips-aws-global","aws-fips"].includes(t)?"us-east-1":t.replace(/fips-(dkr-|prod-)?|-fips/,""):t,NT=(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,i=PT(r);return HT(i),i},useFipsEndpoint:async()=>{let r=typeof n==="string"?n:await n();if(r_(r))return!0;return typeof s!=="function"?Promise.resolve(!!s):s()}})},ku=(t=[],{useFipsEndpoint:n,useDualstackEndpoint:s})=>t.find(({tags:r})=>n===r.includes("fips")&&s===r.includes("dualstack"))?.hostname,WT=(t,{regionHostname:n,partitionHostname:s})=>n?n:s?s.replace("{region}",t):void 0,DT=(t,{partitionHash:n})=>Object.keys(n||{}).find((s)=>n[s].regions.includes(t))??"aws",YT=(t,{signingRegion:n,regionRegex:s,useFipsEndpoint:r})=>{if(n)return n;else if(r){let i=s.replace("\\\\","\\").replace(/^\^/g,"\\.").replace(/\$$/g,"\\."),e=t.match(i);if(e)return e[0].slice(1,-1)}},mT=(t,{useFipsEndpoint:n=!1,useDualstackEndpoint:s=!1,signingService:r,regionHash:i,partitionHash:e})=>{let f=DT(t,{partitionHash:e}),o=t in i?t:e[f]?.endpoint??t,c={useFipsEndpoint:n,useDualstackEndpoint:s},h=ku(i[o]?.variants,c),u=ku(e[f]?.variants,c),_=WT(o,{regionHostname:h,partitionHostname:u});if(_===void 0)throw Error(`Endpoint resolution failed for: ${{resolvedRegion:o,useFipsEndpoint:n,useDualstackEndpoint:s}}`);let l=YT(_,{signingRegion:i[o]?.signingRegion,regionRegex:e[f].regionRegex,useFipsEndpoint:n});return{partition:f,signingService:r,hostname:_,...l&&{signingRegion:l},...i[o]?.signingService&&{signingService:i[o].signingService}}},QT="AWS_DEFAULTS_MODE",JT="defaults_mode",kT={environmentVariableSelector:(t)=>{return t[QT]},configFileSelector:(t)=>{return t[JT]},default:"legacy"},XT=({region:t=Rf(s_),defaultsMode:n=Rf(kT)}={})=>Tf(async()=>{let s=typeof n==="function"?await n():n;switch(s?.toLowerCase()){case"auto":return zT(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 ${UT.join(", ")}, got ${s}`)}}),zT=async(t)=>{if(t){let n=typeof t==="function"?await t():t,s=await xT();if(!s)return"standard";if(n===s)return"in-region";else return"cross-region"}return"standard"},xT=async()=>{if(process.env[ST]&&(process.env[Wu]||process.env[Du]))return process.env[Wu]??process.env[Du];return vu()};qT.CONFIG_PREFIX_SEPARATOR=os;qT.CONFIG_USE_DUALSTACK_ENDPOINT=Uf;qT.CONFIG_USE_FIPS_ENDPOINT=If;qT.CredentialsProviderError=mr;qT.DEFAULT_PROFILE=Cu;qT.DEFAULT_USE_DUALSTACK_ENDPOINT=wT;qT.DEFAULT_USE_FIPS_ENDPOINT=gT;qT.ENV_PROFILE=qu;qT.ENV_USE_DUALSTACK_ENDPOINT=$f;qT.ENV_USE_FIPS_ENDPOINT=Lf;qT.NODE_REGION_CONFIG_FILE_OPTIONS=FT;qT.NODE_REGION_CONFIG_OPTIONS=s_;qT.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS=AT;qT.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS=ET;qT.ProviderError=ks;qT.REGION_ENV_NAME=t_;qT.REGION_INI_NAME=n_;qT.SelectorType=zt;qT.TokenProviderError=bf;qT.booleanSelector=bn;qT.chain=zu;qT.externalDataInterceptor=hT;qT.fromStatic=pu;qT.fromValue=xu;qT.getHomeDir=Qr;qT.getProfileName=Ku;qT.getRegionInfo=mT;qT.getSSOTokenFilepath=Vu;qT.getSSOTokenFromFile=p2;qT.loadConfig=Rf;qT.loadSharedConfigFiles=Sf;qT.loadSsoSessionData=oT;qT.memoize=Tf;qT.nodeDualstackConfigSelectors=MT;qT.nodeFipsConfigSelectors=dT;qT.numberSelector=j2;qT.parseKnownFiles=cT;qT.readFile=re;qT.resolveCustomEndpointsConfig=RT;qT.resolveDefaultsModeConfig=XT;qT.resolveEndpointsConfig=TT;qT.resolveRegionConfig=NT});var fs=Z((d5)=>{var{CONFIG_PREFIX_SEPARATOR:i_,loadConfig:N6}=St(),{toEndpointV1:ie,getSmithyContext:W6,normalizeProvider:Of,isValidHostLabel:f_}=nn();d5.isValidHostLabel=f_;d5.middlewareEndpointToEndpointV1=ie;d5.toEndpointV1=ie;var{EndpointURLScheme:Bf}=is(),e_="AWS_ENDPOINT_URL",o_="endpoint_url",D6=(t)=>({environmentVariableSelector:(n)=>{let s=t.split(" ").map((e)=>e.toUpperCase()),r=n[[e_,...s].join("_")];if(r)return r;let i=n[e_];if(i)return i;return},configFileSelector:(n,s)=>{if(s&&n.services){let i=s[["services",n.services].join(i_)];if(i){let e=t.split(" ").map((o)=>o.toLowerCase()),f=i[[e.join("_"),o_].join(i_)];if(f)return f}}let r=n[o_];if(r)return r;return},default:void 0}),ee=async(t)=>N6(D6(t??""))(),Y6=async(t)=>{let n=t?.Bucket||"";if(typeof t.Bucket==="string")t.Bucket=n.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"));if(X6(n)){if(t.ForcePathStyle===!0)throw Error("Path-style addressing cannot be used with ARN buckets")}else if(!k6(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},m6=/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/,Q6=/(\d+\.){3}\d+/,J6=/\.\./,k6=(t)=>m6.test(t)&&!Q6.test(t)&&!J6.test(t),X6=(t)=>{let[n,s,r,,,i]=t.split(":"),e=n==="arn"&&t.split(":").length>=6,f=Boolean(e&&s&&r&&i);if(e&&!f)throw Error(`Invalid ARN: ${t} was an invalid ARN.`);return f},z6=(t,n,s,r=!1)=>{let i=async()=>{let e;if(r)e=s.clientContextParams?.[t]??s[t]??s[n];else e=s[t]??s[n];if(typeof e==="function")return e();return e};if(t==="credentialScope"||n==="CredentialScope")return async()=>{let e=typeof s.credentials==="function"?await s.credentials():s.credentials;return e?.credentialScope??e?.CredentialScope};if(t==="accountId"||n==="AccountId")return async()=>{let e=typeof s.credentials==="function"?await s.credentials():s.credentials;return e?.accountId??e?.AccountId};if(t==="endpoint"||n==="endpoint")return async()=>{if(s.isCustomEndpoint===!1)return;let e=await i();if(e&&typeof e==="object"){if("url"in e)return e.url.href;if("hostname"in e){let{protocol:f,hostname:o,port:c,path:h}=e;return`${f}//${o}${c?":"+c:""}${h}`}}return e};return i};function c_(t){return async(n,s,r,i)=>{if(!r.isCustomEndpoint){let o;if(r.serviceConfiguredEndpoint)o=await r.serviceConfiguredEndpoint();else o=await t(r.serviceId);if(o)r.endpoint=()=>Promise.resolve(ie(o)),r.isCustomEndpoint=!0}let e=await h_(n,s,r);if(typeof r.endpointProvider!=="function")throw Error("config.endpointProvider is not set.");let f=r.endpointProvider(e,i);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 h_=async(t,n,s)=>{let r={},i=n?.getEndpointParameterInstructions?.()||{};for(let[e,f]of Object.entries(i))switch(f.type){case"staticContextParams":r[e]=f.value;break;case"contextParams":r[e]=t[f.name];break;case"clientContextParams":case"builtInParams":r[e]=await z6(f.name,e,s,f.type!=="builtInParams")();break;case"operationContextParams":r[e]=f.get(t);break;default:throw Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(f))}if(Object.keys(i).length===0)Object.assign(r,s);if(String(s.serviceId).toLowerCase()==="s3")await Y6(r);return r};function x6(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 u_(t){let n=c_(t);return({config:s,instructions:r})=>{return(i,e)=>async(f)=>{if(s.isCustomEndpoint)x6(e,"ENDPOINT_OVERRIDE","N");let o=await n(f.input,{getEndpointParameterInstructions(){return r}},{...s},e);e.endpointV2=o,e.authSchemes=o.properties?.authSchemes;let c=e.authSchemes?.[0];if(c){e.signing_region=c.signingRegion,e.signing_service=c.signingName;let u=W6(e)?.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 i({...f})}}}var q6={name:"serializerMiddleware"},__={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:q6.name};function C6(t){let n=u_(t);return(s,r)=>({applyToStack:(i)=>{i.addRelativeTo(n({config:s,instructions:r}),__)}})}function K6(t){return(n)=>{let s=n.tls??!0,{endpoint:r,useDualstackEndpoint:i,useFipsEndpoint:e}=n,f=r!=null?async()=>ie(await Of(r)()):void 0,c=Object.assign(n,{endpoint:f,tls:s,isCustomEndpoint:!!r,useDualstackEndpoint:Of(i??!1),useFipsEndpoint:Of(e??!1)}),h=void 0;return c.serviceConfiguredEndpoint=async()=>{if(n.serviceId&&!h)h=t(n.serviceId);return h},c}}class Ff{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 Ff(t,n,s,r)}}class l_{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(),i=0;while(!0){let{value:e,done:f}=r.next();if(this.data.delete(e),f||++i>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 i=String(t[r]??"");if(i.includes("|;"))return!1;n+=i+"|;"}return n}}class wt extends Error{constructor(t){super(t);this.name="EndpointError"}}var Jr="endpoints";function Dn(t){if(typeof t!=="object"||t==null)return t;if("ref"in t)return`$${Dn(t.ref)}`;if("fn"in t)return`${t.fn}(${(t.argv||[]).map(Dn).join(", ")})`;return JSON.stringify(t,null,2)}var w_={},V6=(t,n)=>t===n;function j6(...t){for(let n of t)if(n!=null)return n;return}var a6=(t)=>{let n=t.split("."),s=[];for(let r of n){let i=r.indexOf("[");if(i!==-1){if(r.indexOf("]")!==r.length-1)throw new wt(`Path: '${t}' does not end with ']'`);let e=r.slice(i+1,-1);if(Number.isNaN(parseInt(e)))throw new wt(`Invalid array index: '${e}' in path: '${t}'`);if(i!==0)s.push(r.slice(0,i));s.push(e)}else s.push(r)}return s},A_=(t,n)=>a6(n).reduce((s,r)=>{if(typeof s!=="object")throw new wt(`Index '${r}' in '${n}' not found in '${JSON.stringify(t)}'`);else if(Array.isArray(s)){let i=parseInt(r);return s[i<0?s.length+i:i]}return s[r]},t),p6=(t)=>t!=null;function Z6(t,n,s){return t?n:s}var v6=(t)=>!t,t5=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}$"),M_=(t)=>t5.test(t)||t.startsWith("[")&&t.endsWith("]"),yf={[Bf.HTTP]:80,[Bf.HTTPS]:443},n5=(t)=>{let n=(()=>{try{if(t instanceof URL)return t;if(typeof t==="object"&&"hostname"in t){let{hostname:l,port:w,protocol:A="",path:M="",query:E={}}=t,d=new URL(`${A}//${l}${w?`:${w}`:""}${M}`);return d.search=Object.entries(E).map(([T,U])=>`${T}=${U}`).join("&"),d}return new URL(t)}catch(l){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:i,pathname:e,protocol:f,search:o}=n;if(o)return null;let c=f.slice(0,-1);if(!Object.values(Bf).includes(c))return null;let h=M_(i),u=s.includes(`${r}:${yf[c]}`)||typeof t==="string"&&t.includes(`${r}:${yf[c]}`),_=`${r}${u?`:${yf[c]}`:""}`;return{scheme:c,authority:_,path:e,normalizedPath:e.endsWith("/")?e:`${e}/`,isIp:h}};function s5(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 r5=(t,n)=>t===n,i5=(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)},e5=(t)=>encodeURIComponent(t).replace(/[!*'()]/g,(n)=>`%${n.charCodeAt(0).toString(16).toUpperCase()}`),o5={booleanEquals:V6,coalesce:j6,getAttr:A_,isSet:p6,isValidHostLabel:f_,ite:Z6,not:v6,parseURL:n5,split:s5,stringEquals:r5,substring:i5,uriEncode:e5},g_=(t,n)=>{let s=[],{referenceRecord:r,endpointParams:i}=n,e=0;while(e<t.length){let f=t.indexOf("{",e);if(f===-1){s.push(t.slice(e));break}s.push(t.slice(e,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)),e=o+2;let c=t.substring(f+1,o);if(c.includes("#")){let[h,u]=c.split("#");s.push(A_(r[h]??i[h],u))}else s.push(r[c]??i[c]);e=o+1}return s.join("")},f5=({ref:t},n)=>{return n.referenceRecord[t]??n.endpointParams[t]},kr=(t,n,s)=>{if(typeof t==="string")return g_(t,s);else if(t.fn)return d_.callFunction(t,s);else if(t.ref)return f5(t,s);throw new wt(`'${n}': ${String(t)} is not a string, function or reference.`)},E_=({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]=d_.evaluateExpression(o,"arg",s)}let i=t.indexOf(".");if(i!==-1){let o=w_[t.slice(0,i)]?.[t.slice(i+1)];if(typeof o==="function")return o(...r)}let e=o5[t];if(typeof e==="function")return e(...r);throw Error(`function ${t} not loaded in endpointFunctions.`)},d_={evaluateExpression:kr,callFunction:E_},R_=(t,n)=>{let{assign:s}=t;if(s&&s in n.referenceRecord)throw new wt(`'${s}' is already defined in Reference Record.`);let r=E_(t,n);n.logger?.debug?.(`${Jr} evaluateCondition: ${Dn(t)} = ${Dn(r)}`);let i=r===""?!0:!!r;if(s!=null)return{result:i,toAssign:{name:s,value:r}};return{result:i}},b_=(t,n)=>Object.entries(t??{}).reduce((s,[r,i])=>{return s[r]=i.map((e)=>{let f=kr(e,"Header value entry",n);if(typeof f!=="string")throw new wt(`Header '${r}' value '${f}' is not a string`);return f}),s},{}),Hf=(t,n)=>Object.entries(t).reduce((s,[r,i])=>{return s[r]=S_.getEndpointProperty(i,n),s},{}),T_=(t,n)=>{if(Array.isArray(t))return t.map((s)=>T_(s,n));switch(typeof t){case"string":return g_(t,n);case"object":if(t===null)throw new wt(`Unexpected endpoint property: ${t}`);return S_.getEndpointProperties(t,n);case"boolean":return t;default:throw new wt(`Unexpected endpoint property type: ${typeof t}`)}},S_={getEndpointProperty:T_,getEndpointProperties:Hf},$_=(t,n)=>{let s=kr(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 wt(`Endpoint URL must be a string, got ${typeof s}`)},Gf=1e8,c5=(t,n)=>{let{nodes:s,root:r,results:i,conditions:e}=t,f=r,o={},c={referenceRecord:o,endpointParams:n.endpointParams,logger:n.logger};while(f!==1&&f!==-1&&f<Gf){let h=3*(Math.abs(f)-1),[u,_,l]=[s[h],s[h+1],s[h+2]],[w,A,M]=e[u],E=R_({fn:w,assign:M,argv:A},c);if(E.toAssign){let{name:d,value:T}=E.toAssign;o[d]=T}f=f>=0===E.result?_:l}if(f>=Gf){let h=i[f-Gf];if(h[0]===-1){let[,w]=h;throw new wt(kr(w,"Error",c))}let[u,_,l]=h;return{url:$_(u,c),properties:Hf(_,c),headers:b_(l??{},c)}}throw new wt("No matching endpoint.")},Pf=(t=[],n)=>{let s={},r={...n,referenceRecord:{...n.referenceRecord}},i=!1;for(let e of t){let{result:f,toAssign:o}=R_(e,r);if(!f)return{result:f};if(o)i=!0,s[o.name]=o.value,r.referenceRecord[o.name]=o.value,n.logger?.debug?.(`${Jr} assign: ${o.name} := ${Dn(o.value)}`)}if(i)return{result:!0,referenceRecord:s};return{result:!0}},h5=(t,n)=>{let{conditions:s,endpoint:r}=t,{result:i,referenceRecord:e}=Pf(s,n);if(!i)return;let f=e?{...n,referenceRecord:{...n.referenceRecord,...e}}:n,{url:o,properties:c,headers:h}=r;n.logger?.debug?.(`${Jr} Resolving endpoint from template: ${Dn(r)}`);let u={url:$_(o,f)};if(h!=null)u.headers=b_(h,f);if(c!=null)u.properties=Hf(c,f);return u},u5=(t,n)=>{let{conditions:s,error:r}=t,{result:i,referenceRecord:e}=Pf(s,n);if(!i)return;let f=e?{...n,referenceRecord:{...n.referenceRecord,...e}}:n;throw new wt(kr(r,"Error",f))},U_=(t,n)=>{for(let s of t)if(s.type==="endpoint"){let r=h5(s,n);if(r)return r}else if(s.type==="error")u5(s,n);else if(s.type==="tree"){let r=L_.evaluateTreeRule(s,n);if(r)return r}else throw new wt(`Unknown endpoint rule: ${s}`);throw new wt("Rules evaluation failed")},_5=(t,n)=>{let{conditions:s,rules:r}=t,{result:i,referenceRecord:e}=Pf(s,n);if(!i)return;let f=e?{...n,referenceRecord:{...n.referenceRecord,...e}}:n;return L_.evaluateRules(r,f)},L_={evaluateRules:U_,evaluateTreeRule:_5},l5=(t,n)=>{let{endpointParams:s,logger:r}=n,{parameters:i,rules:e}=t;n.logger?.debug?.(`${Jr} Initial EndpointParams: ${Dn(s)}`);for(let o in i){let c=i[o],h=s[o];if(h==null&&c.default!=null){s[o]=c.default;continue}if(c.required&&h==null)throw new wt(`Missing required parameter: '${o}'`)}let f=U_(e,{endpointParams:s,logger:r,referenceRecord:{}});return n.logger?.debug?.(`${Jr} Resolved endpoint: ${Dn(f)}`),f},w5=(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},A5=c_(ee),M5=K6(ee),g5=u_(ee),E5=C6(ee);d5.BinaryDecisionDiagram=Ff;d5.EndpointCache=l_;d5.EndpointError=wt;d5.customEndpointFunctions=w_;d5.decideEndpoint=c5;d5.endpointMiddleware=g5;d5.endpointMiddlewareOptions=__;d5.getEndpointFromInstructions=A5;d5.getEndpointPlugin=E5;d5.isIpAddress=M_;d5.resolveEndpoint=l5;d5.resolveEndpointConfig=M5;d5.resolveEndpointRequiredConfig=w5;d5.resolveParams=h_});var $t=Z((uS)=>{var{createHmac:D5,createHash:Y5,getRandomValues:m5}=nt("crypto"),{ReadStream:Q5,lstatSync:J5,fstatSync:k5}=nt("fs"),{HttpResponse:X5}=nn(),{toEndpointV1:z5}=fs(),{Readable:Xs,Writable:P_,PassThrough:I_}=nt("stream"),N_=(t)=>typeof ArrayBuffer==="function"&&t instanceof ArrayBuffer||Object.prototype.toString.call(t)==="[object ArrayBuffer]",xs=(t,n=0,s=t.byteLength-n)=>{if(!N_(t))throw TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof t} (${t})`);return Buffer.from(t,n,s)},he=(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)},x5=/^[A-Za-z0-9+/]*={0,2}$/,W_=(t)=>{if(t.length*3%4!==0)throw TypeError("Incorrect padding on base64 string.");if(!x5.exec(t))throw TypeError("Invalid base64 string.");let n=he(t,"base64");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)},ue=(t)=>{let n=he(t,"utf8");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength/Uint8Array.BYTES_PER_ELEMENT)},kf=(t)=>{let n;if(typeof t==="string")n=ue(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 q5(t,n,s,r){return class i extends Uint8Array{static fromString(e,f="utf-8"){if(typeof e==="string"){if(f==="base64")return i.mutate(r(e));return i.mutate(n(e))}throw Error(`Unsupported conversion from ${typeof e} to Uint8ArrayBlobAdapter.`)}static mutate(e){return Object.setPrototypeOf(e,i.prototype),e}transformToString(e="utf-8"){if(e==="base64")return s(this);return t(this)}}}var D_=(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")},Et=Array.from({length:256},(t,n)=>n.toString(16).padStart(2,"0"));function C5(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,Et[n[0]]+Et[n[1]]+Et[n[2]]+Et[n[3]]+"-"+Et[n[4]]+Et[n[5]]+"-"+Et[n[6]]+Et[n[7]]+"-"+Et[n[8]]+Et[n[9]]+"-"+Et[n[10]]+Et[n[11]]+Et[n[12]]+Et[n[13]]+Et[n[14]]+Et[n[15]]}}var K5=(t,n,s=(r)=>r)=>t,V5=(t)=>{switch(t){case"true":return!0;case"false":return!1;default:throw Error(`Unable to parse boolean value "${t}"`)}},j5=(t)=>{if(t===null||t===void 0)return;if(typeof t==="number"){if(t===0||t===1)qr.warn(fe(`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")qr.warn(fe(`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}`)},zr=(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))qr.warn(fe(`Expected number but observed string: ${t}`));return n}}if(typeof t==="number")return t;throw TypeError(`Expected number, got ${typeof t}: ${t}`)},a5=Math.ceil(340282346638528860000000000000000000000),oe=(t)=>{let n=zr(t);if(n!==void 0&&!Number.isNaN(n)&&n!==1/0&&n!==-1/0){if(Math.abs(n)>a5)throw TypeError(`Expected 32-bit float, got ${t}`)}return n},xr=(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}`)},p5=xr,Yf=(t)=>Xf(t,32),mf=(t)=>Xf(t,16),Qf=(t)=>Xf(t,8),Xf=(t,n)=>{let s=xr(t);if(s!==void 0&&Z5(s,n)!==s)throw TypeError(`Expected ${n}-bit integer, got ${t}`);return s},Z5=(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]}},v5=(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},Y_=(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}`)},t8=(t)=>{if(t===null||t===void 0)return;if(typeof t==="string")return t;if(["boolean","number","bigint"].includes(typeof t))return qr.warn(fe(`Expected string, got ${typeof t}: ${t}`)),String(t);throw TypeError(`Expected string, got ${typeof t}: ${t}`)},n8=(t)=>{if(t===null||t===void 0)return;let n=Y_(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},zf=(t)=>{if(typeof t=="string")return zr(Ks(t));return zr(t)},s8=zf,m_=(t)=>{if(typeof t=="string")return oe(Ks(t));return oe(t)},r8=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,Ks=(t)=>{let n=t.match(r8);if(n===null||n[0].length!==t.length)throw TypeError("Expected real number, got implicit NaN");return parseFloat(t)},xf=(t)=>{if(typeof t=="string")return Q_(t);return zr(t)},i8=xf,e8=xf,o8=(t)=>{if(typeof t=="string")return Q_(t);return oe(t)},Q_=(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}`)}},J_=(t)=>{if(typeof t==="string")return xr(Ks(t));return xr(t)},f8=J_,c8=(t)=>{if(typeof t==="string")return Yf(Ks(t));return Yf(t)},qs=(t)=>{if(typeof t==="string")return mf(Ks(t));return mf(t)},k_=(t)=>{if(typeof t==="string")return Qf(Ks(t));return Qf(t)},fe=(t)=>{return String(TypeError(t).stack||t).split(`
|
|
9
|
-
`).slice(0,5).filter((
|
|
10
|
-
`)},
|
|
11
|
-
Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`}catch(
|
|
12
|
-
`),o){let
|
|
13
|
-
`),
|
|
14
|
-
`)}
|
|
6
|
+
`+e),n.push(r+"m+"+Ce.exports.humanize(this.diff)+"\x1B[0m")}else n[0]=D6()+t+" "+n[0]}function D6(){if(fw.inspectOpts.hideDate)return"";return new Date().toISOString()+" "}function Y6(...n){return process.stderr.write(Qe.formatWithOptions(fw.inspectOpts,...n)+`
|
|
7
|
+
`)}function m6(n){if(n)process.env.DEBUG=n;else delete process.env.DEBUG}function J6(){return process.env.DEBUG}function X6(n){n.inspectOpts={};let t=Object.keys(fw.inspectOpts);for(let i=0;i<t.length;i++)n.inspectOpts[t[i]]=fw.inspectOpts[t[i]]}Ce.exports=Sh()(fw);var{formatters:ow}=Ce.exports;ow.o=function(n){return this.inspectOpts.colors=this.useColors,Qe.inspect(n,this.inspectOpts).split(`
|
|
8
|
+
`).map((t)=>t.trim()).join(" ")};ow.O=function(n){return this.inspectOpts.colors=this.useColors,Qe.inspect(n,this.inspectOpts)}});var Uh=k((ox,Ih)=>{if(typeof process>"u"||process.type==="renderer"||!1||process.__nwjs)Ih.exports=ew();else Ih.exports=uw()});var Di=k((yg)=>{var mh;(function(n){n.HEADER="header",n.QUERY="query"})(mh||(mh={}));var Jh;(function(n){n.HEADER="header",n.QUERY="query"})(Jh||(Jh={}));var Xh;(function(n){n.HTTP="http",n.HTTPS="https"})(Xh||(Xh={}));var Br;(function(n){n.MD5="md5",n.CRC32="crc32",n.CRC32C="crc32c",n.SHA1="sha1",n.SHA256="sha256"})(Br||(Br={}));var Ag=(n)=>{let t=[];if(n.sha256!==void 0)t.push({algorithmId:()=>Br.SHA256,checksumConstructor:()=>n.sha256});if(n.md5!=null)t.push({algorithmId:()=>Br.MD5,checksumConstructor:()=>n.md5});return{addChecksumAlgorithm(i){t.push(i)},checksumAlgorithms(){return t}}},Mg=(n)=>{let t={};return n.checksumAlgorithms().forEach((i)=>{t[i.algorithmId()]=i.checksumConstructor()}),t},dg=(n)=>{return Ag(n)},Rg=(n)=>{return Mg(n)},zh;(function(n){n[n.HEADER=0]="HEADER",n[n.TRAILER=1]="TRAILER"})(zh||(zh={}));var Eg="__smithy_context",Qh;(function(n){n.PROFILE="profile",n.SSO_SESSION="sso-session",n.SERVICES="services"})(Qh||(Qh={}));var Ch;(function(n){n.HTTP_0_9="http/0.9",n.HTTP_1_0="http/1.0",n.TDS_8_0="tds/8.0"})(Ch||(Ch={}));yg.AlgorithmId=Br;yg.EndpointURLScheme=Xh;yg.FieldPosition=zh;yg.HttpApiKeyAuthLocation=Jh;yg.HttpAuthLocation=mh;yg.IniSectionType=Qh;yg.RequestHandlerProtocol=Ch;yg.SMITHY_CONTEXT_KEY=Eg;yg.getDefaultClientConfiguration=dg;yg.resolveDefaultRuntimeConfig=Rg});var St=k((Dg)=>{var{SMITHY_CONTEXT_KEY:Lw}=Di(),Ng=(n)=>n[Lw]||(n[Lw]={});class je{method;protocol;hostname;port;path;query;headers;username;password;fragment;body;constructor(n){this.method=n.method||"GET",this.hostname=n.hostname||"localhost",this.port=n.port,this.query=n.query||{},this.headers=n.headers||{},this.body=n.body,this.protocol=n.protocol?n.protocol.slice(-1)!==":"?`${n.protocol}:`:n.protocol:"https:",this.path=n.path?n.path.charAt(0)!=="/"?`/${n.path}`:n.path:"/",this.username=n.username,this.password=n.password,this.fragment=n.fragment}static clone(n){let t=new je({...n,headers:{...n.headers}});if(t.query)t.query=Gg(t.query);return t}static isInstance(n){if(!n)return!1;let t=n;return"method"in t&&"protocol"in t&&"hostname"in t&&"path"in t&&typeof t.query==="object"&&typeof t.headers==="object"}clone(){return je.clone(this)}}function Gg(n){return Object.keys(n).reduce((t,i)=>{let s=n[i];return{...t,[i]:Array.isArray(s)?[...s]:s}},{})}class Ow{statusCode;reason;headers;body;constructor(n){this.statusCode=n.statusCode,this.reason=n.reason,this.headers=n.headers||{},this.body=n.body}static isInstance(n){if(!n)return!1;let t=n;return typeof t.statusCode==="number"&&typeof t.headers==="object"}}var Hg=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),Bw=(n,t=!1)=>{if(!t)return Hg.test(n);let i=n.split(".");for(let s of i)if(!Bw(s))return!1;return!0};function Wg(n){return/^[a-z0-9][a-z0-9.-]*[a-z0-9]$/.test(n)}var Fg=(n)=>{if(typeof n==="function")return n;let t=Promise.resolve(n);return()=>t};function Nw(n){let t={};if(n=n.replace(/^\?/,""),n)for(let i of n.split("&")){let[s,r=null]=i.split("=");if(s=decodeURIComponent(s),r)r=decodeURIComponent(r);if(!(s in t))t[s]=r;else if(Array.isArray(t[s]))t[s].push(r);else t[s]=[t[s],r]}return t}var ae=(n)=>{if(typeof n==="string")return ae(new URL(n));let{hostname:t,pathname:i,port:s,protocol:r,search:e}=n,f;if(e)f=Nw(e);return{hostname:t,port:s?parseInt(s):void 0,protocol:r,path:i,query:f}},Pg=(n)=>{if(typeof n==="object"){if("url"in n){let t=ae(n.url);if(n.headers){t.headers={};for(let i in n.headers)t.headers[i.toLowerCase()]=n.headers[i].join(", ")}return t}return n}return ae(n)};Dg.HttpRequest=je;Dg.HttpResponse=Ow;Dg.getSmithyContext=Ng;Dg.isValidHostLabel=Bw;Dg.isValidHostname=Wg;Dg.normalizeProvider=Fg;Dg.parseQueryString=Nw;Dg.parseUrl=ae;Dg.toEndpointV1=Pg});var ri=k((eS)=>{var{getSmithyContext:Gw,HttpResponse:kg,toEndpointV1:qg}=St(),ve=(n)=>{if(typeof n==="function")return n();return n},kh=(n,t,i,s,r)=>({name:t,namespace:n,traits:i,input:s,output:r}),Vg=(n)=>(t,i)=>async(s)=>{let{response:r}=await t(s),{operationSchema:e}=Gw(i),[,f,o,h,u,c]=e??[];try{let _=await n.protocol.deserializeResponse(kh(f,o,h,u,c),{...n,...i},r);return{response:r,output:_}}catch(_){if(Object.defineProperty(_,"$response",{value:r,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in _)){try{_.message+=`
|
|
9
|
+
Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`}catch(l){if(!i.logger||i.logger?.constructor?.name==="NoOpLogger")console.warn("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.");else i.logger?.warn?.("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.")}if(typeof _.$responseBodyText<"u"){if(_.$response)_.$response.body=_.$responseBodyText}try{if(kg.isInstance(r)){let{headers:l={},statusCode:A}=r,d=Object.entries(l);_.$metadata={httpStatusCode:A,requestId:xh(/^x-[\w-]+-request-?id$/,d),extendedRequestId:xh(/^x-[\w-]+-id-2$/,d),cfId:xh(/^x-[\w-]+-cf-id$/,d)}}}catch(l){}}throw _}},xh=(n,t)=>{return(t.find(([i])=>{return i.match(n)})||[void 0,void 0])[1]},jg=(n)=>(t,i)=>async(s)=>{let{operationSchema:r}=Gw(i),[,e,f,o,h,u]=r??[],c=i.endpointV2?async()=>qg(i.endpointV2):n.endpoint,_=await n.protocol.serializeRequest(kh(e,f,o,h,u),s.input,{...n,...i,endpoint:c});return t({...s,request:_})},Hw={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},Ww={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function ag(n){return{applyToStack:(t)=>{t.add(jg(n),Ww),t.add(Vg(n),Hw),n.protocol.setSerdeContext(n)}}}class Dn{name;namespace;traits;static assign(n,t){return Object.assign(n,t)}static[Symbol.hasInstance](n){let t=this.prototype.isPrototypeOf(n);if(!t&&typeof n==="object"&&n!==null)return n.symbol===this.symbol;return t}getName(){return this.namespace+"#"+this.name}}class to extends Dn{static symbol=Symbol.for("@smithy/lis");name;traits;valueSchema;symbol=to.symbol}var vg=(n,t,i,s)=>Dn.assign(new to,{name:t,namespace:n,traits:i,valueSchema:s});class io extends Dn{static symbol=Symbol.for("@smithy/map");name;traits;keySchema;valueSchema;symbol=io.symbol}var Zg=(n,t,i,s,r)=>Dn.assign(new io,{name:t,namespace:n,traits:i,keySchema:s,valueSchema:r});class so extends Dn{static symbol=Symbol.for("@smithy/ope");name;traits;input;output;symbol=so.symbol}var pg=(n,t,i,s,r)=>Dn.assign(new so,{name:t,namespace:n,traits:i,input:s,output:r});class Wr extends Dn{static symbol=Symbol.for("@smithy/str");name;traits;memberNames;memberList;symbol=Wr.symbol}var nS=(n,t,i,s,r)=>Dn.assign(new Wr,{name:t,namespace:n,traits:i,memberNames:s,memberList:r});class ro extends Wr{static symbol=Symbol.for("@smithy/err");ctor;symbol=ro.symbol}var tS=(n,t,i,s,r,e)=>Dn.assign(new ro,{name:t,namespace:n,traits:i,memberNames:s,memberList:r,ctor:null}),Ze=[];function Hr(n){if(typeof n==="object")return n;if(n=n|0,Ze[n])return Ze[n];let t={},i=0;for(let s of["httpLabel","idempotent","idempotencyToken","sensitive","httpPayload","httpResponseCode","httpQueryParams"])if((n>>i++&1)===1)t[s]=1;return Ze[n]=t}var Nr={it:Symbol.for("@smithy/nor-struct-it"),ns:Symbol.for("@smithy/ns")},pe=[],no={};class Jt{ref;memberName;static symbol=Symbol.for("@smithy/nor");symbol=Jt.symbol;name;schema;_isMemberSchema;traits;memberTraits;normalizedTraits;constructor(n,t){this.ref=n,this.memberName=t;let i=[],s=n,r=n;this._isMemberSchema=!1;while(Kh(s))i.push(s[1]),s=s[0],r=ve(s),this._isMemberSchema=!0;if(i.length>0){this.memberTraits={};for(let e=i.length-1;e>=0;--e){let f=i[e];Object.assign(this.memberTraits,Hr(f))}}else this.memberTraits=0;if(r instanceof Jt){let e=this.memberTraits;Object.assign(this,r),this.memberTraits=Object.assign({},e,r.getMemberTraits(),this.getMemberTraits()),this.normalizedTraits=void 0,this.memberName=t??r.memberName;return}if(this.schema=ve(r),Fw(this.schema))this.name=`${this.schema[1]}#${this.schema[2]}`,this.traits=this.schema[3];else this.name=this.memberName??String(r),this.traits=0;if(this._isMemberSchema&&!t)throw Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(!0)} missing member name.`)}static[Symbol.hasInstance](n){let t=this.prototype.isPrototypeOf(n);if(!t&&typeof n==="object"&&n!==null)return n.symbol===this.symbol;return t}static of(n){let t=typeof n==="function"||typeof n==="object"&&n!==null;if(typeof n==="number"){if(pe[n])return pe[n]}else if(typeof n==="string"){if(no[n])return no[n]}else if(t){if(n[Nr.ns])return n[Nr.ns]}let i=ve(n);if(i instanceof Jt)return i;if(Kh(i)){let[r,e]=i;if(r instanceof Jt)return Object.assign(r.getMergedTraits(),Hr(e)),r;throw Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(n,null,2)}.`)}let s=new Jt(i);if(t)return n[Nr.ns]=s;if(typeof i==="string")return no[i]=s;if(typeof i==="number")return pe[i]=s;return s}getSchema(){let n=this.schema;if(Array.isArray(n)&&n[0]===0)return n[4];return n}getName(n=!1){let{name:t}=this;return!n&&t&&t.includes("#")?t.split("#")[1]:t||void 0}getMemberName(){return this.memberName}isMemberSchema(){return this._isMemberSchema}isListSchema(){let n=this.getSchema();return typeof n==="number"?n>=64&&n<128:n[0]===1}isMapSchema(){let n=this.getSchema();return typeof n==="number"?n>=128&&n<=255:n[0]===2}isStructSchema(){let n=this.getSchema();if(typeof n!=="object")return!1;let t=n[0];return t===3||t===-3||t===4}isUnionSchema(){let n=this.getSchema();if(typeof n!=="object")return!1;return n[0]===4}isBlobSchema(){let n=this.getSchema();return n===21||n===42}isTimestampSchema(){let n=this.getSchema();return typeof n==="number"&&n>=4&&n<=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:n}=this.getMergedTraits();return!!n||this.getSchema()===42}isIdempotencyToken(){return!!this.getMergedTraits().idempotencyToken}getMergedTraits(){return this.normalizedTraits??(this.normalizedTraits={...this.getOwnTraits(),...this.getMemberTraits()})}getMemberTraits(){return Hr(this.memberTraits)}getOwnTraits(){return Hr(this.traits)}getKeySchema(){let[n,t]=[this.isDocumentSchema(),this.isMapSchema()];if(!n&&!t)throw Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(!0)}`);let i=this.getSchema(),s=n?15:i[4]??0;return Gr([s,0],"key")}getValueSchema(){let n=this.getSchema(),[t,i,s]=[this.isDocumentSchema(),this.isMapSchema(),this.isListSchema()],r=typeof n==="number"?63&n:n&&typeof n==="object"&&(i||s)?n[3+n[0]]:t?15:void 0;if(r!=null)return Gr([r,0],i?"value":"member");throw Error(`@smithy/core/schema - ${this.getName(!0)} has no value member.`)}getMemberSchema(n){let t=this.getSchema();if(this.isStructSchema()&&t[4].includes(n)){let i=t[4].indexOf(n),s=t[5][i];return Gr(Kh(s)?s:[s,0],n)}if(this.isDocumentSchema())return Gr([15,0],n);throw Error(`@smithy/core/schema - ${this.getName(!0)} has no member=${n}.`)}getMemberSchemas(){let n={};try{for(let[t,i]of this.structIterator())n[t]=i}catch(t){}return n}getEventStreamMember(){if(this.isStructSchema()){for(let[n,t]of this.structIterator())if(t.isStreaming()&&t.isStructSchema())return n}return""}*structIterator(){if(this.isUnitSchema())return;if(!this.isStructSchema())throw Error("@smithy/core/schema - cannot iterate non-struct schema.");let n=this.getSchema(),t=n[4].length,i=n[Nr.it];if(i&&t===i.length){yield*i;return}i=Array(t);for(let s=0;s<t;++s){let r=n[4][s],e=Gr([n[5][s],0],r);yield i[s]=[r,e]}n[Nr.it]=i}}function Gr(n,t){if(n instanceof Jt)return Object.assign(n,{memberName:t,_isMemberSchema:!0});return new Jt(n,t)}var Kh=(n)=>Array.isArray(n)&&n.length===2,Fw=(n)=>Array.isArray(n)&&n.length>=5;class Fr extends Dn{static symbol=Symbol.for("@smithy/sim");name;schemaRef;traits;symbol=Fr.symbol}var iS=(n,t,i,s)=>Dn.assign(new Fr,{name:t,namespace:n,traits:s,schemaRef:i}),sS=(n,t,i,s)=>Dn.assign(new Fr,{name:t,namespace:n,traits:i,schemaRef:s}),rS={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 mt{namespace;schemas;exceptions;static registries=new Map;constructor(n,t=new Map,i=new Map){this.namespace=n,this.schemas=t,this.exceptions=i}static for(n){if(!mt.registries.has(n))mt.registries.set(n,new mt(n));return mt.registries.get(n)}copyFrom(n){let{schemas:t,exceptions:i}=this;for(let[s,r]of n.schemas)if(!t.has(s))t.set(s,r);for(let[s,r]of n.exceptions)if(!i.has(s))i.set(s,r)}register(n,t){let i=this.normalizeShapeId(n);for(let s of[this,mt.for(i.split("#")[0])])s.schemas.set(i,t)}getSchema(n){let t=this.normalizeShapeId(n);if(!this.schemas.has(t)){if(!n.includes("#")){let i="#"+n,s=[];for(let[r,e]of this.schemas.entries())if(r.endsWith(i))s.push(e);if(s.length===1)return s[0]}throw Error(`@smithy/core/schema - schema not found for ${t}`)}return this.schemas.get(t)}registerError(n,t){let i=n,s=i[1];for(let r of[this,mt.for(s)])r.schemas.set(s+"#"+i[2],i),r.exceptions.set(i,t)}getErrorCtor(n){let t=n;if(this.exceptions.has(t))return this.exceptions.get(t);return mt.for(t[1]).exceptions.get(t)}getBaseException(){for(let n of this.exceptions.keys())if(Array.isArray(n)){let[,t,i]=n,s=t+"#"+i;if(s.startsWith("smithy.ts.sdk.synthetic.")&&s.endsWith("ServiceException"))return n}return}find(n){for(let t of this.schemas.values())if(n(t))return t;return}clear(){this.schemas.clear(),this.exceptions.clear()}normalizeShapeId(n){if(n.includes("#"))return n;return this.namespace+"#"+n}}eS.ErrorSchema=ro;eS.ListSchema=to;eS.MapSchema=io;eS.NormalizedSchema=Jt;eS.OperationSchema=so;eS.SCHEMA=rS;eS.Schema=Dn;eS.SimpleSchema=Fr;eS.StructureSchema=Wr;eS.TypeRegistry=mt;eS.deref=ve;eS.deserializerMiddlewareOption=Hw;eS.error=tS;eS.getSchemaSerdePlugin=ag;eS.isStaticSchema=Fw;eS.list=vg;eS.map=Zg;eS.op=pg;eS.operation=kh;eS.serializerMiddlewareOption=Ww;eS.sim=iS;eS.simAdapter=sS;eS.simpleSchemaCacheN=pe;eS.simpleSchemaCacheS=no;eS.struct=nS;eS.traitsCache=Ze;eS.translateTraits=Hr});var Xt=k((wI)=>{var{getSmithyContext:WS,normalizeProvider:FS}=St();wI.getSmithyContext=WS;wI.normalizeProvider=FS;var{SMITHY_CONTEXT_KEY:PS,AlgorithmId:oo}=Di();wI.AlgorithmId=oo;var{NormalizedSchema:DS}=ri(),Yi=(n,t)=>{let i=[];if(n)i.push(n);if(t)for(let s of t)i.push(s);return i},ei=(n,t)=>{return`${n||"anonymous"}${t&&t.length>0?` (a.k.a. ${t.join(",")})`:""}`},Pr=()=>{let n=[],t=[],i=!1,s=new Set,r=(_)=>_.sort((w,l)=>Pw[l.step]-Pw[w.step]||Dw[l.priority||"normal"]-Dw[w.priority||"normal"]),e=(_)=>{let w=!1,l=(A)=>{let d=Yi(A.name,A.aliases);if(d.includes(_)){w=!0;for(let E of d)s.delete(E);return!1}return!0};return n=n.filter(l),t=t.filter(l),w},f=(_)=>{let w=!1,l=(A)=>{if(A.middleware===_){w=!0;for(let d of Yi(A.name,A.aliases))s.delete(d);return!1}return!0};return n=n.filter(l),t=t.filter(l),w},o=(_)=>{return n.forEach((w)=>{_.add(w.middleware,{...w})}),t.forEach((w)=>{_.addRelativeTo(w.middleware,{...w})}),_.identifyOnResolve?.(c.identifyOnResolve()),_},h=(_)=>{let w=[];return _.before.forEach((l)=>{if(l.before.length===0&&l.after.length===0)w.push(l);else w.push(...h(l))}),w.push(_),_.after.reverse().forEach((l)=>{if(l.before.length===0&&l.after.length===0)w.push(l);else w.push(...h(l))}),w},u=(_=!1)=>{let w=[],l=[],A={};return n.forEach((E)=>{let R={...E,before:[],after:[]};for(let y of Yi(R.name,R.aliases))A[y]=R;w.push(R)}),t.forEach((E)=>{let R={...E,before:[],after:[]};for(let y of Yi(R.name,R.aliases))A[y]=R;l.push(R)}),l.forEach((E)=>{if(E.toMiddleware){let R=A[E.toMiddleware];if(R===void 0){if(_)return;throw Error(`${E.toMiddleware} is not found when adding ${ei(E.name,E.aliases)} middleware ${E.relation} ${E.toMiddleware}`)}if(E.relation==="after")R.after.push(E);if(E.relation==="before")R.before.push(E)}}),r(w).map(h).reduce((E,R)=>{return E.push(...R),E},[])},c={add:(_,w={})=>{let{name:l,override:A,aliases:d}=w,E={step:"initialize",priority:"normal",middleware:_,...w},R=Yi(l,d);if(R.length>0){if(R.some((y)=>s.has(y))){if(!A)throw Error(`Duplicate middleware name '${ei(l,d)}'`);for(let y of R){let T=n.findIndex((I)=>I.name===y||I.aliases?.some((F)=>F===y));if(T===-1)continue;let S=n[T];if(S.step!==E.step||E.priority!==S.priority)throw Error(`"${ei(S.name,S.aliases)}" middleware with ${S.priority} priority in ${S.step} step cannot be overridden by "${ei(l,d)}" middleware with ${E.priority} priority in ${E.step} step.`);n.splice(T,1)}}for(let y of R)s.add(y)}n.push(E)},addRelativeTo:(_,w)=>{let{name:l,override:A,aliases:d}=w,E={middleware:_,...w},R=Yi(l,d);if(R.length>0){if(R.some((y)=>s.has(y))){if(!A)throw Error(`Duplicate middleware name '${ei(l,d)}'`);for(let y of R){let T=t.findIndex((I)=>I.name===y||I.aliases?.some((F)=>F===y));if(T===-1)continue;let S=t[T];if(S.toMiddleware!==E.toMiddleware||S.relation!==E.relation)throw Error(`"${ei(S.name,S.aliases)}" middleware ${S.relation} "${S.toMiddleware}" middleware cannot be overridden by "${ei(l,d)}" middleware ${E.relation} "${E.toMiddleware}" middleware.`);t.splice(T,1)}}for(let y of R)s.add(y)}t.push(E)},clone:()=>o(Pr()),use:(_)=>{_.applyToStack(c)},remove:(_)=>{if(typeof _==="string")return e(_);else return f(_)},removeByTag:(_)=>{let w=!1,l=(A)=>{let{tags:d,name:E,aliases:R}=A;if(d&&d.includes(_)){let y=Yi(E,R);for(let T of y)s.delete(T);return w=!0,!1}return!0};return n=n.filter(l),t=t.filter(l),w},concat:(_)=>{let w=o(Pr());return w.use(_),w.identifyOnResolve(i||w.identifyOnResolve()||(_.identifyOnResolve?.()??!1)),w},applyToStack:o,identify:()=>{return u(!0).map((_)=>{let w=_.step??_.relation+" "+_.toMiddleware;return ei(_.name,_.aliases)+" - "+w})},identifyOnResolve(_){if(typeof _==="boolean")i=_;return i},resolve:(_,w)=>{for(let l of u().map((A)=>A.middleware).reverse())_=l(_,w);if(i)console.log(c.identify());return _}};return c},Pw={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},Dw={high:3,normal:2,low:1},YS=(n)=>()=>{throw Error(n)},mS=(n)=>()=>Promise.reject(n),eo=()=>{let n=new WeakSet;return(t,i)=>{if(typeof i==="object"&&i!==null){if(n.has(i))return"[Circular]";n.add(i)}return i}},JS=(n)=>{return new Promise((t)=>setTimeout(t,n*1000))},Jw={minDelay:2,maxDelay:120},It;(function(n){n.ABORTED="ABORTED",n.FAILURE="FAILURE",n.SUCCESS="SUCCESS",n.RETRY="RETRY",n.TIMEOUT="TIMEOUT"})(It||(It={}));var XS=(n)=>{if(n.state===It.ABORTED){let t=Error(`${JSON.stringify({...n,reason:"Request was aborted"},eo())}`);throw t.name="AbortError",t}else if(n.state===It.TIMEOUT){let t=Error(`${JSON.stringify({...n,reason:"Waiter has timed out"},eo())}`);throw t.name="TimeoutError",t}else if(n.state!==It.SUCCESS)throw Error(`${JSON.stringify(n,eo())}`);return n},zS=async({minDelay:n,maxDelay:t,maxWaitTime:i,abortController:s,client:r,abortSignal:e},f,o)=>{let h={},[u,c]=[n*1000,t*1000],_=0,w=Date.now()+i*1000,l=Date.now()+60000,A=!1;while(!0){if(_>0){let R=xS(u,c,_,w);if(s?.signal?.aborted||e?.aborted)return h["AbortController signal aborted."]|=0,h["AbortController signal aborted."]+=1,{state:It.ABORTED,observedResponses:h};if(Date.now()+R>w)return{state:It.TIMEOUT,observedResponses:h};await JS(R/1000)}let{state:d,reason:E}=await o(r,f);if(E){let R=CS(E);h[R]|=0,h[R]+=1}if(d!==It.RETRY)return{state:d,reason:E,final:E,observedResponses:h};if(_+=1,!A&&Date.now()>=l)QS(h,r),A=!0}},QS=(n={},t)=>{let i=Object.keys(n),s=0;for(let f of i){let o=n[f]|0;if(f.startsWith("403:"))s+=o}let r=t?.config?.logger,e=typeof r?.warn==="function"&&!r.constructor?.name?.includes?.("NoOpLogger")?r:console;if(s>=3||i[i.length-1]?.startsWith("403:"))e.warn("@smithy/util-waiter WARN - 403 status code encountered during waiter polling.")},CS=(n)=>{let t=n?.$response?.statusCode??n?.$metadata?.httpStatusCode;if(n?.$responseBodyText)return`${t?t+": ":""}Deserialization error for body: ${n.$responseBodyText}`;if(t){if(n?.$response||n?.message)return`${t??"Unknown"}: ${n?.message}`;return`${t}: OK`}return String(n?.message??JSON.stringify(n,eo())??"Unknown")},xS=(n,t,i,s)=>{let r=Math.log(t/n)/Math.log(2)+1;if(i>r)return t;let e=n*2**(i-1),f=Math.min(e,t),o=KS(n,f);if(Date.now()+o>s){let h=s-Date.now();return Math.max(0,h-500)}return o},KS=(n,t)=>n+Math.random()*(t-n),kS=(n)=>{if(n.maxWaitTime<=0)throw Error("WaiterConfiguration.maxWaitTime must be greater than 0");else if(n.minDelay<=0)throw Error("WaiterConfiguration.minDelay must be greater than 0");else if(n.maxDelay<=0)throw Error("WaiterConfiguration.maxDelay must be greater than 0");else if(n.maxWaitTime<=n.minDelay)throw Error(`WaiterConfiguration.maxWaitTime [${n.maxWaitTime}] must be greater than WaiterConfiguration.minDelay [${n.minDelay}] for this waiter`);else if(n.maxDelay<n.minDelay)throw Error(`WaiterConfiguration.maxDelay [${n.maxDelay}] must be greater than WaiterConfiguration.minDelay [${n.minDelay}] for this waiter`)},Yw=(n)=>{let t,i=new Promise((s)=>{if(t=()=>s({state:It.ABORTED}),typeof n.addEventListener==="function")n.addEventListener("abort",t);else n.onabort=t});return{clearListener(){if(typeof n.removeEventListener==="function")n.removeEventListener("abort",t)},aborted:i}},qS=async(n,t,i)=>{let s={...Jw,...n};kS(s);let r=[zS(s,t,i)],e=[];if(n.abortSignal){let{aborted:f,clearListener:o}=Yw(n.abortSignal);e.push(o),r.push(f)}if(n.abortController?.signal){let{aborted:f,clearListener:o}=Yw(n.abortController.signal);e.push(o),r.push(f)}return Promise.race(r).then((f)=>{for(let o of e)o();return f})};class Xw{config;middlewareStack=Pr();initConfig;handlers;constructor(n){this.config=n;let{protocol:t,protocolSettings:i}=n;if(i){if(typeof t==="function")n.protocol=new t(i)}}send(n,t,i){let s=typeof t!=="function"?t:void 0,r=typeof t==="function"?t:i,e=s===void 0&&this.config.cacheMiddleware===!0,f;if(e){if(!this.handlers)this.handlers=new WeakMap;let o=this.handlers;if(o.has(n.constructor))f=o.get(n.constructor);else f=n.resolveMiddleware(this.middlewareStack,this.config,s),o.set(n.constructor,f)}else delete this.handlers,f=n.resolveMiddleware(this.middlewareStack,this.config,s);if(r)f(n).then((o)=>r(null,o.output),(o)=>r(o)).catch(()=>{});else return f(n).then((o)=>o.output)}destroy(){this.config?.requestHandler?.destroy?.(),delete this.handlers}}var qh="***SensitiveInformation***";function fo(n,t){if(t==null)return t;let i=DS.of(n);if(i.getMergedTraits().sensitive)return qh;if(i.isListSchema()){if(!!i.getValueSchema().getMergedTraits().sensitive)return qh}else if(i.isMapSchema()){if(!!i.getKeySchema().getMergedTraits().sensitive||!!i.getValueSchema().getMergedTraits().sensitive)return qh}else if(i.isStructSchema()&&typeof t==="object"){let s=t,r={};for(let[e,f]of i.structIterator())if(s[e]!=null)r[e]=fo(f,s[e]);return r}return t}class ho{middlewareStack=Pr();schema;static classBuilder(){return new zw}resolveMiddlewareWithContext(n,t,i,{middlewareFn:s,clientName:r,commandName:e,inputFilterSensitiveLog:f,outputFilterSensitiveLog:o,smithyContext:h,additionalContext:u,CommandCtor:c}){for(let E of s.bind(this)(c,n,t,i))this.middlewareStack.use(E);let _=n.concat(this.middlewareStack),{logger:w}=t,l={logger:w,clientName:r,commandName:e,inputFilterSensitiveLog:f,outputFilterSensitiveLog:o,[PS]:{commandInstance:this,...h},...u},{requestHandler:A}=t,d=i??{};if(h.eventStream)d={isEventStream:!0,...d};return _.resolve((E)=>A.handle(E.request,d),l)}}class zw{_init=()=>{};_ep={};_middlewareFn=()=>[];_commandName="";_clientName="";_additionalContext={};_smithyContext={};_inputFilterSensitiveLog=void 0;_outputFilterSensitiveLog=void 0;_serializer=null;_deserializer=null;_operationSchema;init(n){this._init=n}ep(n){return this._ep=n,this}m(n){return this._middlewareFn=n,this}s(n,t,i={}){return this._smithyContext={service:n,operation:t,...i},this}c(n={}){return this._additionalContext=n,this}n(n,t){return this._clientName=n,this._commandName=t,this}f(n=(i)=>i,t=(i)=>i){return this._inputFilterSensitiveLog=n,this._outputFilterSensitiveLog=t,this}ser(n){return this._serializer=n,this}de(n){return this._deserializer=n,this}sc(n){return this._operationSchema=n,this._smithyContext.operationSchema=n,this}build(){let n=this,t;return t=class extends ho{input;static getEndpointParameterInstructions(){return n._ep}constructor(...[i]){super();this.input=i??{},n._init(this),this.schema=n._operationSchema}resolveMiddleware(i,s,r){let e=n._operationSchema,f=e?.[4]??e?.input,o=e?.[5]??e?.output;return this.resolveMiddlewareWithContext(i,s,r,{CommandCtor:t,middlewareFn:n._middlewareFn,clientName:n._clientName,commandName:n._commandName,inputFilterSensitiveLog:n._inputFilterSensitiveLog??(e?fo.bind(null,f):(h)=>h),outputFilterSensitiveLog:n._outputFilterSensitiveLog??(e?fo.bind(null,o):(h)=>h),smithyContext:n._smithyContext,additionalContext:n._additionalContext})}serialize=n._serializer;deserialize=n._deserializer}}}var VS="***SensitiveInformation***",jS=(n,t,i)=>{for(let[e,f]of Object.entries(n)){let o=async function(u,c,_){let w=new f(u);if(typeof c==="function")this.send(w,c);else if(typeof _==="function"){if(typeof c!=="object")throw Error(`Expected http options but got ${typeof c}`);this.send(w,c||{},_)}else return this.send(w,c)},h=(e[0].toLowerCase()+e.slice(1)).replace(/Command$/,"");t.prototype[h]=o}let{paginators:s={},waiters:r={}}=i??{};for(let[e,f]of Object.entries(s))if(t.prototype[e]===void 0)t.prototype[e]=function(o={},h,...u){return f({...h,client:this},o,...u)};for(let[e,f]of Object.entries(r))if(t.prototype[e]===void 0)t.prototype[e]=async function(o={},h,...u){let c=h;if(typeof h==="number")c={maxWaitTime:h};return f({...c,client:this},o,...u)}};class Os extends Error{$fault;$response;$retryable;$metadata;constructor(n){super(n.message);Object.setPrototypeOf(this,Object.getPrototypeOf(this).constructor.prototype),this.name=n.name,this.$fault=n.$fault,this.$metadata=n.$metadata}static isInstance(n){if(!n)return!1;let t=n;return Os.prototype.isPrototypeOf(t)||Boolean(t.$fault)&&Boolean(t.$metadata)&&(t.$fault==="client"||t.$fault==="server")}static[Symbol.hasInstance](n){if(!n)return!1;let t=n;if(this===Os)return Os.isInstance(n);if(Os.isInstance(n)){if(t.name&&this.name)return this.prototype.isPrototypeOf(n)||t.name===this.name;return this.prototype.isPrototypeOf(n)}return!1}}var Qw=(n,t={})=>{Object.entries(t).filter(([,s])=>s!==void 0).forEach(([s,r])=>{if(n[s]==null||n[s]==="")n[s]=r});let i=n.message||n.Message||"UnknownError";return n.message=i,delete n.Message,n},Cw=({output:n,parsedBody:t,exceptionCtor:i,errorCode:s})=>{let r=vS(n),e=r.httpStatusCode?r.httpStatusCode+"":void 0,f=new i({name:t?.code||t?.Code||s||e||"UnknownError",$fault:"client",$metadata:r});throw Qw(f,t)},aS=(n)=>{return({output:t,parsedBody:i,errorCode:s})=>{Cw({output:t,parsedBody:i,exceptionCtor:n,errorCode:s})}},vS=(n)=>({httpStatusCode:n.statusCode,requestId:n.headers["x-amzn-requestid"]??n.headers["x-amzn-request-id"]??n.headers["x-amz-request-id"],extendedRequestId:n.headers["x-amz-id-2"],cfId:n.headers["x-amz-cf-id"]}),ZS=(n)=>{switch(n){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{}}},mw=!1,pS=(n)=>{if(n&&!mw&&parseInt(n.substring(1,n.indexOf(".")))<16)mw=!0},xw=Object.values(oo),Kw=(n)=>{let t=[];for(let i in oo){let s=oo[i];if(n[s]===void 0)continue;t.push({algorithmId:()=>s,checksumConstructor:()=>n[s]})}for(let[i,s]of Object.entries(n.checksumAlgorithms??{}))t.push({algorithmId:()=>i,checksumConstructor:()=>s});return{addChecksumAlgorithm(i){n.checksumAlgorithms=n.checksumAlgorithms??{};let s=i.algorithmId(),r=i.checksumConstructor();if(xw.includes(s))n.checksumAlgorithms[s.toUpperCase()]=r;else n.checksumAlgorithms[s]=r;t.push(i)},checksumAlgorithms(){return t}}},kw=(n)=>{let t={};return n.checksumAlgorithms().forEach((i)=>{let s=i.algorithmId();if(xw.includes(s))t[s]=i.checksumConstructor()}),t},qw=(n)=>{return{setRetryStrategy(t){n.retryStrategy=t},retryStrategy(){return n.retryStrategy}}},Vw=(n)=>{let t={};return t.retryStrategy=n.retryStrategy(),t},jw=(n)=>{return Object.assign(Kw(n),qw(n))},nI=jw,tI=(n)=>{return Object.assign(kw(n),Vw(n))},iI=(n)=>Array.isArray(n)?n:[n],aw=(n)=>{for(let i in n)if(Object.prototype.hasOwnProperty.call(n,i)&&n[i]["#text"]!==void 0)n[i]=n[i]["#text"];else if(typeof n[i]==="object"&&n[i]!==null)n[i]=aw(n[i]);return n},sI=(n)=>{return n!=null};class vw{trace(){}debug(){}info(){}warn(){}error(){}}function Zw(n,t,i){let s,r,e;if(typeof t>"u"&&typeof i>"u")s={},e=n;else if(s=n,typeof t==="function")return r=t,e=i,oI(s,r,e);else e=t;for(let f of Object.keys(e)){if(!Array.isArray(e[f])){s[f]=e[f];continue}pw(s,null,e,f)}return s}var rI=(n)=>{let t={};for(let[i,s]of Object.entries(n||{}))t[i]=[,s];return t},eI=(n,t)=>{let i={};for(let s in t)pw(i,n,t,s);return i},oI=(n,t,i)=>{return Zw(n,Object.entries(i).reduce((s,[r,e])=>{if(Array.isArray(e))s[r]=e;else if(typeof e==="function")s[r]=[t,e()];else s[r]=[t,e];return s},{}))},pw=(n,t,i,s)=>{if(t!==null){let f=i[s];if(typeof f==="function")f=[,f];let[o=fI,h=hI,u=s]=f;if(typeof o==="function"&&o(t[u])||typeof o!=="function"&&!!o)n[s]=h(t[u]);return}let[r,e]=i[s];if(typeof e==="function"){let f,o=r===void 0&&(f=e())!=null,h=typeof r==="function"&&!!r(void 0)||typeof r!=="function"&&!!r;if(o)n[s]=f;else if(h)n[s]=e()}else{let f=r===void 0&&e!=null,o=typeof r==="function"&&!!r(e)||typeof r!=="function"&&!!r;if(f||o)n[s]=e}},fI=(n)=>n!=null,hI=(n)=>n,uI=(n)=>{if(n!==n)return"NaN";switch(n){case 1/0:return"Infinity";case-1/0:return"-Infinity";default:return n}},cI=(n)=>n.toISOString().replace(".000Z","Z"),Vh=(n)=>{if(n==null)return{};if(Array.isArray(n))return n.filter((t)=>t!=null).map(Vh);if(typeof n==="object"){let t={};for(let i of Object.keys(n)){if(n[i]==null)continue;t[i]=Vh(n[i])}return t}return n};function _I(n,t,i,s){return function(e,f,o,h,u={}){let c=Object.assign({},n,e);return ho.classBuilder().ep(c).m(function(_,w,l,A){let d=f.call(this,_,w,l,A);return d.unshift(s(l,_.getEndpointParameterInstructions())),d}).s(t,o,u).n(i,o.charAt(0).toUpperCase()+o.slice(1)+"Command").sc(h).build()}}wI.Client=Xw;wI.Command=ho;wI.NoOpLogger=vw;wI.SENSITIVE_STRING=VS;wI.ServiceException=Os;wI.WaiterState=It;wI._json=Vh;wI.checkExceptions=XS;wI.constructStack=Pr;wI.convertMap=rI;wI.createAggregatedClient=jS;wI.createWaiter=qS;wI.decorateServiceException=Qw;wI.emitWarningIfUnsupportedVersion=pS;wI.getArrayIfSingleItem=iI;wI.getChecksumConfiguration=Kw;wI.getDefaultClientConfiguration=nI;wI.getDefaultExtensionConfiguration=jw;wI.getRetryConfiguration=qw;wI.getValueFromTextNode=aw;wI.invalidFunction=YS;wI.invalidProvider=mS;wI.isSerializableHeaderValue=sI;wI.loadConfigsForDefaultMode=ZS;wI.makeBuilder=_I;wI.map=Zw;wI.resolveChecksumRuntimeConfig=kw;wI.resolveDefaultRuntimeConfig=tI;wI.resolveRetryRuntimeConfig=Vw;wI.schemaLogFilter=fo;wI.serializeDateTime=cI;wI.serializeFloat=uI;wI.take=eI;wI.throwDefaultError=Cw;wI.waiterServiceDefaults=Jw;wI.withBaseException=aS});var Yn=k((Z5)=>{var{homedir:ZI}=p("os"),{sep:pI,join:Dr}=p("path"),{createHash:n5}=p("crypto"),{readFile:hl}=p("fs/promises"),{IniSectionType:uo}=Di(),{normalizeProvider:co}=Xt(),{isValidHostLabel:t5}=St();class Bs extends Error{name="ProviderError";tryNextLink;constructor(n,t=!0){let i,s=!0;if(typeof t==="boolean")i=void 0,s=t;else if(t!=null&&typeof t==="object")i=t.logger,s=t.tryNextLink??!0;super(n);this.tryNextLink=s,Object.setPrototypeOf(this,Bs.prototype),i?.debug?.(`@smithy/property-provider ${s?"->":"(!)"} ${n}`)}static from(n,t=!0){return Object.assign(new this(n.message,t),n)}}class Yr extends Bs{name="CredentialsProviderError";constructor(n,t=!0){super(n,t);Object.setPrototypeOf(this,Yr.prototype)}}class ph extends Bs{name="TokenProviderError";constructor(n,t=!0){super(n,t);Object.setPrototypeOf(this,ph.prototype)}}var ul=(...n)=>async()=>{if(n.length===0)throw new Bs("No providers in chain");let t;for(let i of n)try{return await i()}catch(s){if(t=s,s?.tryNextLink)continue;throw s}throw t},cl=(n)=>()=>Promise.resolve(n),nu=(n,t,i)=>{let s,r,e,f=!1,o=async()=>{if(!r)r=n();try{s=await r,e=!0,f=!1}finally{r=void 0}return s};if(t===void 0)return async(h)=>{if(!e||h?.forceRefresh)s=await o();return s};return async(h)=>{if(!e||h?.forceRefresh)s=await o();if(f)return s;if(i&&!i(s))return f=!0,s;if(t(s))return await o(),s;return s}},zt=(n,t,i)=>{if(!(t in n))return;if(n[t]==="true")return!0;if(n[t]==="false")return!1;throw Error(`Cannot load ${i} "${t}". Expected "true" or "false", got ${n[t]}.`)},i5=(n,t,i)=>{if(!(t in n))return;let s=parseInt(n[t],10);if(Number.isNaN(s))throw TypeError(`Cannot load ${i} '${t}'. Expected number, got '${n[t]}'.`);return s},ut;(function(n){n.ENV="env",n.CONFIG="shared config entry"})(ut||(ut={}));var jh={},s5=()=>{if(process&&process.geteuid)return`${process.geteuid()}`;return"DEFAULT"},mr=()=>{let{HOME:n,USERPROFILE:t,HOMEPATH:i,HOMEDRIVE:s=`C:${pI}`}=process.env;if(n)return n;if(t)return t;if(i)return`${s}${i}`;let r=s5();if(!jh[r])jh[r]=ZI();return jh[r]},_l="AWS_PROFILE",wl="default",ll=(n)=>n.profile||process.env[_l]||wl,Al=(n)=>{let i=n5("sha1").update(n).digest("hex");return Dr(mr(),".aws","sso","cache",`${i}.json`)},_o={},r5=async(n)=>{if(_o[n])return _o[n];let t=Al(n),i=await hl(t,"utf8");return JSON.parse(i)},mi=".",e5=(n)=>Object.entries(n).filter(([t])=>{let i=t.indexOf(mi);if(i===-1)return!1;return Object.values(uo).includes(t.substring(0,i))}).reduce((t,[i,s])=>{let r=i.indexOf(mi),e=i.substring(0,r)===uo.PROFILE?i.substring(r+1):i;return t[e]=s,t},{...n.default&&{default:n.default}}),o5="AWS_CONFIG_FILE",Ml=()=>process.env[o5]||Dr(mr(),".aws","config"),f5="AWS_SHARED_CREDENTIALS_FILE",h5=()=>process.env[f5]||Dr(mr(),".aws","credentials"),u5=/^([\w-]+)\s(["'])?([\w-@+.%:/]+)\2$/,c5=["__proto__","profile __proto__"],vh=(n)=>{let t={},i,s;for(let r of n.split(/\r?\n/)){let e=r.split(/(^|\s)[;#]/)[0].trim();if(e[0]==="["&&e[e.length-1]==="]"){i=void 0,s=void 0;let o=e.substring(1,e.length-1),h=u5.exec(o);if(h){let[,u,,c]=h;if(Object.values(uo).includes(u))i=[u,c].join(mi)}else i=o;if(c5.includes(o))throw Error(`Found invalid profile name "${o}"`)}else if(i){let o=e.indexOf("=");if(![0,-1].includes(o)){let[h,u]=[e.substring(0,o).trim(),e.substring(o+1).trim()];if(u==="")s=h;else{if(s&&r.trimStart()===r)s=void 0;t[i]=t[i]||{};let c=s?[s,h].join(mi):h;t[i][c]=u}}}}return t},ah={},wo={},lo=(n,t)=>{if(wo[n]!==void 0)return wo[n];if(!ah[n]||t?.ignoreCache)ah[n]=hl(n,"utf8");return ah[n]},nl=()=>({}),tu=async(n={})=>{let{filepath:t=h5(),configFilepath:i=Ml()}=n,s=mr(),r="~/",e=t;if(t.startsWith("~/"))e=Dr(s,t.slice(2));let f=i;if(i.startsWith("~/"))f=Dr(s,i.slice(2));let o=await Promise.all([lo(f,{ignoreCache:n.ignoreCache}).then(vh).then(e5).catch(nl),lo(e,{ignoreCache:n.ignoreCache}).then(vh).catch(nl)]);return{configFile:o[0],credentialsFile:o[1]}},_5=(n)=>Object.entries(n).filter(([t])=>t.startsWith(uo.SSO_SESSION+mi)).reduce((t,[i,s])=>({...t,[i.substring(i.indexOf(mi)+1)]:s}),{}),w5=()=>({}),l5=async(n={})=>lo(n.configFilepath??Ml()).then(vh).then(_5).catch(w5),A5=(...n)=>{let t={};for(let i of n)for(let[s,r]of Object.entries(i))if(t[s]!==void 0)Object.assign(t[s],r);else t[s]=r;return t},M5=async(n)=>{let t=await tu(n);return A5(t.configFile,t.credentialsFile)},d5={getFileRecord(){return wo},interceptFile(n,t){wo[n]=Promise.resolve(t)},getTokenRecord(){return _o},interceptToken(n,t){_o[n]=t}};function dl(n){try{let t=new Set(Array.from(n.match(/([A-Z_]){3,}/g)??[]));return t.delete("CONFIG"),t.delete("CONFIG_PREFIX_SEPARATOR"),t.delete("ENV"),[...t].join(", ")}catch(t){return n}}var R5=(n,t)=>async()=>{try{let i=n(process.env,t);if(i===void 0)throw Error();return i}catch(i){throw new Yr(i.message||`Not found in ENV: ${dl(n.toString())}`,{logger:t?.logger})}},E5=(n,{preferredFile:t="config",...i}={})=>async()=>{let s=ll(i),{configFile:r,credentialsFile:e}=await tu(i),f=e[s]||{},o=r[s]||{},h=t==="config"?{...f,...o}:{...o,...f};try{let c=n(h,t==="config"?r:e);if(c===void 0)throw Error();return c}catch(u){throw new Yr(u.message||`Not found in config files w/ profile [${s}]: ${dl(n.toString())}`,{logger:i.logger})}},y5=(n)=>typeof n==="function",Rl=(n)=>y5(n)?async()=>await n():cl(n),Zh=({environmentVariableSelector:n,configFileSelector:t,default:i},s={})=>{let{signingName:r,logger:e}=s;return nu(ul(R5(n,{signingName:r,logger:e}),E5(t,s),Rl(i)))},iu="AWS_USE_DUALSTACK_ENDPOINT",su="use_dualstack_endpoint",T5=!1,g5={environmentVariableSelector:(n)=>zt(n,iu,ut.ENV),configFileSelector:(n)=>zt(n,su,ut.CONFIG),default:!1},S5={environmentVariableSelector:(n)=>zt(n,iu,ut.ENV),configFileSelector:(n)=>zt(n,su,ut.CONFIG),default:void 0},ru="AWS_USE_FIPS_ENDPOINT",eu="use_fips_endpoint",I5=!1,U5={environmentVariableSelector:(n)=>zt(n,ru,ut.ENV),configFileSelector:(n)=>zt(n,eu,ut.CONFIG),default:!1},b5={environmentVariableSelector:(n)=>zt(n,ru,ut.ENV),configFileSelector:(n)=>zt(n,eu,ut.CONFIG),default:void 0},$5=(n)=>{let{tls:t,endpoint:i,urlParser:s,useDualstackEndpoint:r}=n;return Object.assign(n,{tls:t??!0,endpoint:co(typeof i==="string"?s(i):i),isCustomEndpoint:!0,useDualstackEndpoint:co(r??!1)})},L5=async(n)=>{let{tls:t=!0}=n,i=await n.region();if(!new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/).test(i))throw Error("Invalid region in client config");let r=await n.useDualstackEndpoint(),e=await n.useFipsEndpoint(),{hostname:f}=await n.regionInfoProvider(i,{useDualstackEndpoint:r,useFipsEndpoint:e})??{};if(!f)throw Error("Cannot resolve hostname from client config");return n.urlParser(`${t?"https:":"http:"}//${f}`)},O5=(n)=>{let t=co(n.useDualstackEndpoint??!1),{endpoint:i,useFipsEndpoint:s,urlParser:r,tls:e}=n;return Object.assign(n,{tls:e??!0,endpoint:i?co(typeof i==="string"?r(i):i):()=>L5({...n,useDualstackEndpoint:t,useFipsEndpoint:s}),isCustomEndpoint:!!i,useDualstackEndpoint:t})},B5="AWS_EXECUTION_ENV",tl="AWS_REGION",il="AWS_DEFAULT_REGION",N5="AWS_EC2_METADATA_DISABLED",G5=["in-region","cross-region","mobile","standard","legacy"],H5="/latest/meta-data/placement/region",W5="/latest/api/token",F5="x-aws-ec2-metadata-token",P5="x-aws-ec2-metadata-token-ttl-seconds",sl=1000,D5=60000,El=0,yl=async()=>{if(process.env[N5])return;if(Date.now()<El)return;try{let n=Y5(),t=(await el({...n,path:W5,method:"PUT",headers:{[P5]:"21600"}})).toString();return(await el({...n,path:H5,method:"GET",headers:{[F5]:t}})).toString().trim()||rl()}catch{return rl()}},rl=()=>{El=Date.now()+D5;return},Y5=()=>{let n=process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT;if(n){let t=new URL(n);return{hostname:t.hostname.replace(/^\[(.+)]$/,"$1"),port:t.port?Number(t.port):void 0}}if(process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE==="IPv6")return{hostname:"fd00:ec2::254"};return{hostname:"169.254.169.254"}},el=async(n)=>{let{request:t}=p("http");return new Promise((i,s)=>{let r=t({hostname:n.hostname,port:n.port,path:n.path,method:n.method,headers:n.headers,timeout:sl,signal:AbortSignal.timeout(sl)});r.on("error",(e)=>{s(e),r.destroy()}),r.on("timeout",()=>{s(Error("TimeoutError from instance metadata service")),r.destroy()}),r.on("response",(e)=>{let{statusCode:f=400}=e;if(f<200||f>=300){s(Object.assign(Error("Error response received from instance metadata service"),{statusCode:f})),r.destroy();return}let o=[];e.on("data",(h)=>o.push(h)),e.on("end",()=>{i(Buffer.concat(o)),r.destroy()})}),r.end()})},Tl="AWS_REGION",gl="region",Sl={environmentVariableSelector:(n)=>n[Tl],configFileSelector:(n)=>n[gl],default:async()=>{let n=await yl();if(n)return n;throw Error("Region is missing")}},m5={preferredFile:"credentials"},ol=new Set,J5=(n,t=t5)=>{if(!ol.has(n)&&!t(n))if(n==="*")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="${n}" is not a valid hostname component.`);else ol.add(n)},Il=(n)=>typeof n==="string"&&(n.startsWith("fips-")||n.endsWith("-fips")),X5=(n)=>Il(n)?["fips-aws-global","aws-fips"].includes(n)?"us-east-1":n.replace(/fips-(dkr-|prod-)?|-fips/,""):n,z5=(n)=>{let{region:t,useFipsEndpoint:i}=n;if(!t)throw Error("Region is missing");return Object.assign(n,{region:async()=>{let s=typeof t==="function"?await t():t,r=X5(s);return J5(r),r},useFipsEndpoint:async()=>{let s=typeof t==="string"?t:await t();if(Il(s))return!0;return typeof i!=="function"?Promise.resolve(!!i):i()}})},fl=(n=[],{useFipsEndpoint:t,useDualstackEndpoint:i})=>n.find(({tags:s})=>t===s.includes("fips")&&i===s.includes("dualstack"))?.hostname,Q5=(n,{regionHostname:t,partitionHostname:i})=>t?t:i?i.replace("{region}",n):void 0,C5=(n,{partitionHash:t})=>Object.keys(t||{}).find((i)=>t[i].regions.includes(n))??"aws",x5=(n,{signingRegion:t,regionRegex:i,useFipsEndpoint:s})=>{if(t)return t;else if(s){let r=i.replace("\\\\","\\").replace(/^\^/g,"\\.").replace(/\$$/g,"\\."),e=n.match(r);if(e)return e[0].slice(1,-1)}},K5=(n,{useFipsEndpoint:t=!1,useDualstackEndpoint:i=!1,signingService:s,regionHash:r,partitionHash:e})=>{let f=C5(n,{partitionHash:e}),o=n in r?n:e[f]?.endpoint??n,h={useFipsEndpoint:t,useDualstackEndpoint:i},u=fl(r[o]?.variants,h),c=fl(e[f]?.variants,h),_=Q5(o,{regionHostname:u,partitionHostname:c});if(_===void 0)throw Error(`Endpoint resolution failed for: ${{resolvedRegion:o,useFipsEndpoint:t,useDualstackEndpoint:i}}`);let w=x5(_,{signingRegion:r[o]?.signingRegion,regionRegex:e[f].regionRegex,useFipsEndpoint:t});return{partition:f,signingService:s,hostname:_,...w&&{signingRegion:w},...r[o]?.signingService&&{signingService:r[o].signingService}}},k5="AWS_DEFAULTS_MODE",q5="defaults_mode",V5={environmentVariableSelector:(n)=>{return n[k5]},configFileSelector:(n)=>{return n[q5]},default:"legacy"},j5=({region:n=Zh(Sl),defaultsMode:t=Zh(V5)}={})=>nu(async()=>{let i=typeof t==="function"?await t():t;switch(i?.toLowerCase()){case"auto":return a5(n);case"in-region":case"cross-region":case"mobile":case"standard":case"legacy":return Promise.resolve(i?.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw Error(`Invalid parameter for "defaultsMode", expect ${G5.join(", ")}, got ${i}`)}}),a5=async(n)=>{if(n){let t=typeof n==="function"?await n():n,i=await v5();if(!i)return"standard";if(t===i)return"in-region";else return"cross-region"}return"standard"},v5=async()=>{if(process.env[B5]&&(process.env[tl]||process.env[il]))return process.env[tl]??process.env[il];return yl()};Z5.CONFIG_PREFIX_SEPARATOR=mi;Z5.CONFIG_USE_DUALSTACK_ENDPOINT=su;Z5.CONFIG_USE_FIPS_ENDPOINT=eu;Z5.CredentialsProviderError=Yr;Z5.DEFAULT_PROFILE=wl;Z5.DEFAULT_USE_DUALSTACK_ENDPOINT=T5;Z5.DEFAULT_USE_FIPS_ENDPOINT=I5;Z5.ENV_PROFILE=_l;Z5.ENV_USE_DUALSTACK_ENDPOINT=iu;Z5.ENV_USE_FIPS_ENDPOINT=ru;Z5.NODE_REGION_CONFIG_FILE_OPTIONS=m5;Z5.NODE_REGION_CONFIG_OPTIONS=Sl;Z5.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS=g5;Z5.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS=U5;Z5.ProviderError=Bs;Z5.REGION_ENV_NAME=Tl;Z5.REGION_INI_NAME=gl;Z5.SelectorType=ut;Z5.TokenProviderError=ph;Z5.booleanSelector=zt;Z5.chain=ul;Z5.externalDataInterceptor=d5;Z5.fromStatic=Rl;Z5.fromValue=cl;Z5.getHomeDir=mr;Z5.getProfileName=ll;Z5.getRegionInfo=K5;Z5.getSSOTokenFilepath=Al;Z5.getSSOTokenFromFile=r5;Z5.loadConfig=Zh;Z5.loadSharedConfigFiles=tu;Z5.loadSsoSessionData=l5;Z5.memoize=nu;Z5.nodeDualstackConfigSelectors=S5;Z5.nodeFipsConfigSelectors=b5;Z5.numberSelector=i5;Z5.parseKnownFiles=M5;Z5.readFile=lo;Z5.resolveCustomEndpointsConfig=$5;Z5.resolveDefaultsModeConfig=j5;Z5.resolveEndpointsConfig=O5;Z5.resolveRegionConfig=z5});var Ji=k((bU)=>{var{CONFIG_PREFIX_SEPARATOR:Ul,loadConfig:z8}=Yn(),{toEndpointV1:Ao,getSmithyContext:Q8,normalizeProvider:ou,isValidHostLabel:Ll}=St();bU.isValidHostLabel=Ll;bU.middlewareEndpointToEndpointV1=Ao;bU.toEndpointV1=Ao;var{EndpointURLScheme:uu}=Di(),bl="AWS_ENDPOINT_URL",$l="endpoint_url",C8=(n)=>({environmentVariableSelector:(t)=>{let i=n.split(" ").map((e)=>e.toUpperCase()),s=t[[bl,...i].join("_")];if(s)return s;let r=t[bl];if(r)return r;return},configFileSelector:(t,i)=>{if(i&&t.services){let r=i[["services",t.services].join(Ul)];if(r){let e=n.split(" ").map((o)=>o.toLowerCase()),f=r[[e.join("_"),$l].join(Ul)];if(f)return f}}let s=t[$l];if(s)return s;return},default:void 0}),Mo=async(n)=>z8(C8(n??""))(),x8=async(n)=>{let t=n?.Bucket||"";if(typeof n.Bucket==="string")n.Bucket=t.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"));if(j8(t)){if(n.ForcePathStyle===!0)throw Error("Path-style addressing cannot be used with ARN buckets")}else if(!V8(t)||t.indexOf(".")!==-1&&!String(n.Endpoint).startsWith("http:")||t.toLowerCase()!==t||t.length<3)n.ForcePathStyle=!0;if(n.DisableMultiRegionAccessPoints)n.disableMultiRegionAccessPoints=!0,n.DisableMRAP=!0;return n},K8=/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/,k8=/(\d+\.){3}\d+/,q8=/\.\./,V8=(n)=>K8.test(n)&&!k8.test(n)&&!q8.test(n),j8=(n)=>{let[t,i,s,,,r]=n.split(":"),e=t==="arn"&&n.split(":").length>=6,f=Boolean(e&&i&&s&&r);if(e&&!f)throw Error(`Invalid ARN: ${n} was an invalid ARN.`);return f},a8=(n,t,i,s=!1)=>{let r=async()=>{let e;if(s)e=i.clientContextParams?.[n]??i[n]??i[t];else e=i[n]??i[t];if(typeof e==="function")return e();return e};if(n==="credentialScope"||t==="CredentialScope")return async()=>{let e=typeof i.credentials==="function"?await i.credentials():i.credentials;return e?.credentialScope??e?.CredentialScope};if(n==="accountId"||t==="AccountId")return async()=>{let e=typeof i.credentials==="function"?await i.credentials():i.credentials;return e?.accountId??e?.AccountId};if(n==="endpoint"||t==="endpoint")return async()=>{if(i.isCustomEndpoint===!1)return;let e=await r();if(e&&typeof e==="object"){if("url"in e)return e.url.href;if("hostname"in e){let{protocol:f,hostname:o,port:h,path:u}=e;return`${f}//${o}${h?":"+h:""}${u}`}}return e};return r};function Ol(n){return async(t,i,s,r)=>{if(!s.isCustomEndpoint){let o;if(s.serviceConfiguredEndpoint)o=await s.serviceConfiguredEndpoint();else o=await n(s.serviceId);if(o)s.endpoint=()=>Promise.resolve(Ao(o)),s.isCustomEndpoint=!0}let e=await Bl(t,i,s);if(typeof s.endpointProvider!=="function")throw Error("config.endpointProvider is not set.");let f=s.endpointProvider(e,r);if(s.isCustomEndpoint&&s.endpoint){let o=await s.endpoint();if(o?.headers){f.headers??={};for(let[h,u]of Object.entries(o.headers))f.headers[h]=Array.isArray(u)?u:[u]}}return f}}var Bl=async(n,t,i)=>{let s={},r=t?.getEndpointParameterInstructions?.()||{};for(let[e,f]of Object.entries(r))switch(f.type){case"staticContextParams":s[e]=f.value;break;case"contextParams":s[e]=n[f.name];break;case"clientContextParams":case"builtInParams":s[e]=await a8(f.name,e,i,f.type!=="builtInParams")();break;case"operationContextParams":s[e]=f.get(n);break;default:throw Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(f))}if(Object.keys(r).length===0)Object.assign(s,i);if(String(i.serviceId).toLowerCase()==="s3")await x8(s);return s};function v8(n,t,i){if(!n.__smithy_context)n.__smithy_context={features:{}};else if(!n.__smithy_context.features)n.__smithy_context.features={};n.__smithy_context.features[t]=i}function Nl(n){let t=Ol(n);return({config:i,instructions:s})=>{return(r,e)=>async(f)=>{if(i.isCustomEndpoint)v8(e,"ENDPOINT_OVERRIDE","N");let o=await t(f.input,{getEndpointParameterInstructions(){return s}},{...i},e);e.endpointV2=o,e.authSchemes=o.properties?.authSchemes;let h=e.authSchemes?.[0];if(h){e.signing_region=h.signingRegion,e.signing_service=h.signingName;let c=Q8(e)?.selectedHttpAuthScheme?.httpAuthOption;if(c)c.signingProperties=Object.assign(c.signingProperties||{},{signing_region:h.signingRegion,signingRegion:h.signingRegion,signing_service:h.signingName,signingName:h.signingName,signingRegionSet:h.signingRegionSet},h.properties)}return r({...f})}}}var Z8={name:"serializerMiddleware"},Gl={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:Z8.name};function p8(n){let t=Nl(n);return(i,s)=>({applyToStack:(r)=>{r.addRelativeTo(t({config:i,instructions:s}),Gl)}})}function nU(n){return(t)=>{let i=t.tls??!0,{endpoint:s,useDualstackEndpoint:r,useFipsEndpoint:e}=t,f=s!=null?async()=>Ao(await ou(s)()):void 0,h=Object.assign(t,{endpoint:f,tls:i,isCustomEndpoint:!!s,useDualstackEndpoint:ou(r??!1),useFipsEndpoint:ou(e??!1)}),u=void 0;return h.serviceConfiguredEndpoint=async()=>{if(t.serviceId&&!u)u=n(t.serviceId);return u},h}}class cu{nodes;root;conditions;results;constructor(n,t,i,s){this.nodes=n,this.root=t,this.conditions=i,this.results=s}static from(n,t,i,s){return new cu(n,t,i,s)}}class Hl{capacity;data=new Map;parameters=[];constructor({size:n,params:t}){if(this.capacity=n??50,t)this.parameters=t}get(n,t){let i=this.hash(n);if(i===!1)return t();if(!this.data.has(i)){if(this.data.size>this.capacity+10){let s=this.data.keys(),r=0;while(!0){let{value:e,done:f}=s.next();if(this.data.delete(e),f||++r>10)break}}this.data.set(i,t())}return this.data.get(i)}size(){return this.data.size}hash(n){let t="",{parameters:i}=this;if(i.length===0)return!1;for(let s of i){let r=String(n[s]??"");if(r.includes("|;"))return!1;t+=r+"|;"}return t}}class Ln extends Error{constructor(n){super(n);this.name="EndpointError"}}var Jr="endpoints";function oi(n){if(typeof n!=="object"||n==null)return n;if("ref"in n)return`$${oi(n.ref)}`;if("fn"in n)return`${n.fn}(${(n.argv||[]).map(oi).join(", ")})`;return JSON.stringify(n,null,2)}var Wl={},tU=(n,t)=>n===t;function iU(...n){for(let t of n)if(t!=null)return t;return}var sU=(n)=>{let t=n.split("."),i=[];for(let s of t){let r=s.indexOf("[");if(r!==-1){if(s.indexOf("]")!==s.length-1)throw new Ln(`Path: '${n}' does not end with ']'`);let e=s.slice(r+1,-1);if(Number.isNaN(parseInt(e)))throw new Ln(`Invalid array index: '${e}' in path: '${n}'`);if(r!==0)i.push(s.slice(0,r));i.push(e)}else i.push(s)}return i},Fl=(n,t)=>sU(t).reduce((i,s)=>{if(typeof i!=="object")throw new Ln(`Index '${s}' in '${t}' not found in '${JSON.stringify(n)}'`);else if(Array.isArray(i)){let r=parseInt(s);return i[r<0?i.length+r:r]}return i[s]},n),rU=(n)=>n!=null;function eU(n,t,i){return n?t:i}var oU=(n)=>!n,fU=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}$"),Pl=(n)=>fU.test(n)||n.startsWith("[")&&n.endsWith("]"),fu={[uu.HTTP]:80,[uu.HTTPS]:443},hU=(n)=>{let t=(()=>{try{if(n instanceof URL)return n;if(typeof n==="object"&&"hostname"in n){let{hostname:w,port:l,protocol:A="",path:d="",query:E={}}=n,R=new URL(`${A}//${w}${l?`:${l}`:""}${d}`);return R.search=Object.entries(E).map(([y,T])=>`${y}=${T}`).join("&"),R}return new URL(n)}catch(w){return null}})();if(!t)return console.error(`Unable to parse ${JSON.stringify(n)} as a whatwg URL.`),null;let i=t.href,{host:s,hostname:r,pathname:e,protocol:f,search:o}=t;if(o)return null;let h=f.slice(0,-1);if(!Object.values(uu).includes(h))return null;let u=Pl(r),c=i.includes(`${s}:${fu[h]}`)||typeof n==="string"&&n.includes(`${s}:${fu[h]}`),_=`${s}${c?`:${fu[h]}`:""}`;return{scheme:h,authority:_,path:e,normalizedPath:e.endsWith("/")?e:`${e}/`,isIp:u}};function uU(n,t,i){if(i===1)return[n];if(n==="")return[""];let s=n.split(t);if(i===0)return s;return s.slice(0,i-1).concat(s.slice(1).join(t))}var cU=(n,t)=>n===t,_U=(n,t,i,s)=>{if(n==null||t>=i||n.length<i||/[^\u0000-\u007f]/.test(n))return null;if(!s)return n.substring(t,i);return n.substring(n.length-i,n.length-t)},wU=(n)=>encodeURIComponent(n).replace(/[!*'()]/g,(t)=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),lU={booleanEquals:tU,coalesce:iU,getAttr:Fl,isSet:rU,isValidHostLabel:Ll,ite:eU,not:oU,parseURL:hU,split:uU,stringEquals:cU,substring:_U,uriEncode:wU},Dl=(n,t)=>{let i=[],{referenceRecord:s,endpointParams:r}=t,e=0;while(e<n.length){let f=n.indexOf("{",e);if(f===-1){i.push(n.slice(e));break}i.push(n.slice(e,f));let o=n.indexOf("}",f);if(o===-1){i.push(n.slice(f));break}if(n[f+1]==="{"&&n[o+1]==="}")i.push(n.slice(f+1,o)),e=o+2;let h=n.substring(f+1,o);if(h.includes("#")){let[u,c]=h.split("#");i.push(Fl(s[u]??r[u],c))}else i.push(s[h]??r[h]);e=o+1}return i.join("")},AU=({ref:n},t)=>{return t.referenceRecord[n]??t.endpointParams[n]},Xr=(n,t,i)=>{if(typeof n==="string")return Dl(n,i);else if(n.fn)return ml.callFunction(n,i);else if(n.ref)return AU(n,i);throw new Ln(`'${t}': ${String(n)} is not a string, function or reference.`)},Yl=({fn:n,argv:t},i)=>{let s=Array(t.length);for(let f=0;f<s.length;++f){let o=t[f];if(typeof o==="boolean"||typeof o==="number")s[f]=o;else s[f]=ml.evaluateExpression(o,"arg",i)}let r=n.indexOf(".");if(r!==-1){let o=Wl[n.slice(0,r)]?.[n.slice(r+1)];if(typeof o==="function")return o(...s)}let e=lU[n];if(typeof e==="function")return e(...s);throw Error(`function ${n} not loaded in endpointFunctions.`)},ml={evaluateExpression:Xr,callFunction:Yl},Jl=(n,t)=>{let{assign:i}=n;if(i&&i in t.referenceRecord)throw new Ln(`'${i}' is already defined in Reference Record.`);let s=Yl(n,t);t.logger?.debug?.(`${Jr} evaluateCondition: ${oi(n)} = ${oi(s)}`);let r=s===""?!0:!!s;if(i!=null)return{result:r,toAssign:{name:i,value:s}};return{result:r}},Xl=(n,t)=>Object.entries(n??{}).reduce((i,[s,r])=>{return i[s]=r.map((e)=>{let f=Xr(e,"Header value entry",t);if(typeof f!=="string")throw new Ln(`Header '${s}' value '${f}' is not a string`);return f}),i},{}),_u=(n,t)=>Object.entries(n).reduce((i,[s,r])=>{return i[s]=Ql.getEndpointProperty(r,t),i},{}),zl=(n,t)=>{if(Array.isArray(n))return n.map((i)=>zl(i,t));switch(typeof n){case"string":return Dl(n,t);case"object":if(n===null)throw new Ln(`Unexpected endpoint property: ${n}`);return Ql.getEndpointProperties(n,t);case"boolean":return n;default:throw new Ln(`Unexpected endpoint property type: ${typeof n}`)}},Ql={getEndpointProperty:zl,getEndpointProperties:_u},Cl=(n,t)=>{let i=Xr(n,"Endpoint URL",t);if(typeof i==="string")try{return new URL(i)}catch(s){throw console.error(`Failed to construct URL with ${i}`,s),s}throw new Ln(`Endpoint URL must be a string, got ${typeof i}`)},hu=1e8,MU=(n,t)=>{let{nodes:i,root:s,results:r,conditions:e}=n,f=s,o={},h={referenceRecord:o,endpointParams:t.endpointParams,logger:t.logger};while(f!==1&&f!==-1&&f<hu){let u=3*(Math.abs(f)-1),[c,_,w]=[i[u],i[u+1],i[u+2]],[l,A,d]=e[c],E=Jl({fn:l,assign:d,argv:A},h);if(E.toAssign){let{name:R,value:y}=E.toAssign;o[R]=y}f=f>=0===E.result?_:w}if(f>=hu){let u=r[f-hu];if(u[0]===-1){let[,l]=u;throw new Ln(Xr(l,"Error",h))}let[c,_,w]=u;return{url:Cl(c,h),properties:_u(_,h),headers:Xl(w??{},h)}}throw new Ln("No matching endpoint.")},wu=(n=[],t)=>{let i={},s={...t,referenceRecord:{...t.referenceRecord}},r=!1;for(let e of n){let{result:f,toAssign:o}=Jl(e,s);if(!f)return{result:f};if(o)r=!0,i[o.name]=o.value,s.referenceRecord[o.name]=o.value,t.logger?.debug?.(`${Jr} assign: ${o.name} := ${oi(o.value)}`)}if(r)return{result:!0,referenceRecord:i};return{result:!0}},dU=(n,t)=>{let{conditions:i,endpoint:s}=n,{result:r,referenceRecord:e}=wu(i,t);if(!r)return;let f=e?{...t,referenceRecord:{...t.referenceRecord,...e}}:t,{url:o,properties:h,headers:u}=s;t.logger?.debug?.(`${Jr} Resolving endpoint from template: ${oi(s)}`);let c={url:Cl(o,f)};if(u!=null)c.headers=Xl(u,f);if(h!=null)c.properties=_u(h,f);return c},RU=(n,t)=>{let{conditions:i,error:s}=n,{result:r,referenceRecord:e}=wu(i,t);if(!r)return;let f=e?{...t,referenceRecord:{...t.referenceRecord,...e}}:t;throw new Ln(Xr(s,"Error",f))},xl=(n,t)=>{for(let i of n)if(i.type==="endpoint"){let s=dU(i,t);if(s)return s}else if(i.type==="error")RU(i,t);else if(i.type==="tree"){let s=Kl.evaluateTreeRule(i,t);if(s)return s}else throw new Ln(`Unknown endpoint rule: ${i}`);throw new Ln("Rules evaluation failed")},EU=(n,t)=>{let{conditions:i,rules:s}=n,{result:r,referenceRecord:e}=wu(i,t);if(!r)return;let f=e?{...t,referenceRecord:{...t.referenceRecord,...e}}:t;return Kl.evaluateRules(s,f)},Kl={evaluateRules:xl,evaluateTreeRule:EU},yU=(n,t)=>{let{endpointParams:i,logger:s}=t,{parameters:r,rules:e}=n;t.logger?.debug?.(`${Jr} Initial EndpointParams: ${oi(i)}`);for(let o in r){let h=r[o],u=i[o];if(u==null&&h.default!=null){i[o]=h.default;continue}if(h.required&&u==null)throw new Ln(`Missing required parameter: '${o}'`)}let f=xl(e,{endpointParams:i,logger:s,referenceRecord:{}});return t.logger?.debug?.(`${Jr} Resolved endpoint: ${oi(f)}`),f},TU=(n)=>{let{endpoint:t}=n;if(t===void 0)n.endpoint=async()=>{throw Error("@smithy/middleware-endpoint: (default endpointRuleSet) endpoint is not set - you must configure an endpoint.")};return n},gU=Ol(Mo),SU=nU(Mo),IU=Nl(Mo),UU=p8(Mo);bU.BinaryDecisionDiagram=cu;bU.EndpointCache=Hl;bU.EndpointError=Ln;bU.customEndpointFunctions=Wl;bU.decideEndpoint=MU;bU.endpointMiddleware=IU;bU.endpointMiddlewareOptions=Gl;bU.getEndpointFromInstructions=gU;bU.getEndpointPlugin=UU;bU.isIpAddress=Pl;bU.resolveEndpoint=yU;bU.resolveEndpointConfig=SU;bU.resolveEndpointRequiredConfig=TU;bU.resolveParams=Bl});var mn=k((R$)=>{var{createHmac:CU,createHash:xU,getRandomValues:KU}=p("crypto"),{ReadStream:kU,lstatSync:qU,fstatSync:VU}=p("fs"),{HttpResponse:jU}=St(),{toEndpointV1:aU}=Ji(),{Readable:Ns,Writable:pl,PassThrough:kl}=p("stream"),nA=(n)=>typeof ArrayBuffer==="function"&&n instanceof ArrayBuffer||Object.prototype.toString.call(n)==="[object ArrayBuffer]",Hs=(n,t=0,i=n.byteLength-t)=>{if(!nA(n))throw TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof n} (${n})`);return Buffer.from(n,t,i)},To=(n,t)=>{if(typeof n!=="string")throw TypeError(`The "input" argument must be of type string. Received type ${typeof n} (${n})`);return t?Buffer.from(n,t):Buffer.from(n)},vU=/^[A-Za-z0-9+/]*={0,2}$/,tA=(n)=>{if(n.length*3%4!==0)throw TypeError("Incorrect padding on base64 string.");if(!vU.exec(n))throw TypeError("Invalid base64 string.");let t=To(n,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)},go=(n)=>{let t=To(n,"utf8");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength/Uint8Array.BYTES_PER_ELEMENT)},Tu=(n)=>{let t;if(typeof n==="string")t=go(n);else t=n;if(typeof t!=="object"||typeof t.byteOffset!=="number"||typeof t.byteLength!=="number")throw Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");return Hs(t.buffer,t.byteOffset,t.byteLength).toString("base64")};function ZU(n,t,i,s){return class r extends Uint8Array{static fromString(e,f="utf-8"){if(typeof e==="string"){if(f==="base64")return r.mutate(s(e));return r.mutate(t(e))}throw Error(`Unsupported conversion from ${typeof e} to Uint8ArrayBlobAdapter.`)}static mutate(e){return Object.setPrototypeOf(e,r.prototype),e}transformToString(e="utf-8"){if(e==="base64")return i(this);return n(this)}}}var iA=(n)=>{if(typeof n==="string")return n;if(typeof n!=="object"||typeof n.byteOffset!=="number"||typeof n.byteLength!=="number")throw Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return Hs(n.buffer,n.byteOffset,n.byteLength).toString("utf8")},Gn=Array.from({length:256},(n,t)=>t.toString(16).padStart(2,"0"));function pU(n){if(typeof crypto<"u"&&typeof crypto.randomUUID==="function")return()=>crypto.randomUUID();return()=>{let t=new Uint8Array(16);return n(t),t[6]=t[6]&15|64,t[8]=t[8]&63|128,Gn[t[0]]+Gn[t[1]]+Gn[t[2]]+Gn[t[3]]+"-"+Gn[t[4]]+Gn[t[5]]+"-"+Gn[t[6]]+Gn[t[7]]+"-"+Gn[t[8]]+Gn[t[9]]+"-"+Gn[t[10]]+Gn[t[11]]+Gn[t[12]]+Gn[t[13]]+Gn[t[14]]+Gn[t[15]]}}var nb=(n,t,i=(s)=>s)=>n,tb=(n)=>{switch(n){case"true":return!0;case"false":return!1;default:throw Error(`Unable to parse boolean value "${n}"`)}},ib=(n)=>{if(n===null||n===void 0)return;if(typeof n==="number"){if(n===0||n===1)xr.warn(Eo(`Expected boolean, got ${typeof n}: ${n}`));if(n===0)return!1;if(n===1)return!0}if(typeof n==="string"){let t=n.toLowerCase();if(t==="false"||t==="true")xr.warn(Eo(`Expected boolean, got ${typeof n}: ${n}`));if(t==="false")return!1;if(t==="true")return!0}if(typeof n==="boolean")return n;throw TypeError(`Expected boolean, got ${typeof n}: ${n}`)},Qr=(n)=>{if(n===null||n===void 0)return;if(typeof n==="string"){let t=parseFloat(n);if(!Number.isNaN(t)){if(String(t)!==String(n))xr.warn(Eo(`Expected number but observed string: ${n}`));return t}}if(typeof n==="number")return n;throw TypeError(`Expected number, got ${typeof n}: ${n}`)},sb=Math.ceil(340282346638528860000000000000000000000),Ro=(n)=>{let t=Qr(n);if(t!==void 0&&!Number.isNaN(t)&&t!==1/0&&t!==-1/0){if(Math.abs(t)>sb)throw TypeError(`Expected 32-bit float, got ${n}`)}return t},Cr=(n)=>{if(n===null||n===void 0)return;if(Number.isInteger(n)&&!Number.isNaN(n))return n;throw TypeError(`Expected integer, got ${typeof n}: ${n}`)},rb=Cr,du=(n)=>gu(n,32),Ru=(n)=>gu(n,16),Eu=(n)=>gu(n,8),gu=(n,t)=>{let i=Cr(n);if(i!==void 0&&eb(i,t)!==i)throw TypeError(`Expected ${t}-bit integer, got ${n}`);return i},eb=(n,t)=>{switch(t){case 32:return Int32Array.of(n)[0];case 16:return Int16Array.of(n)[0];case 8:return Int8Array.of(n)[0]}},ob=(n,t)=>{if(n===null||n===void 0){if(t)throw TypeError(`Expected a non-null value for ${t}`);throw TypeError("Expected a non-null value")}return n},sA=(n)=>{if(n===null||n===void 0)return;if(typeof n==="object"&&!Array.isArray(n))return n;let t=Array.isArray(n)?"array":typeof n;throw TypeError(`Expected object, got ${t}: ${n}`)},fb=(n)=>{if(n===null||n===void 0)return;if(typeof n==="string")return n;if(["boolean","number","bigint"].includes(typeof n))return xr.warn(Eo(`Expected string, got ${typeof n}: ${n}`)),String(n);throw TypeError(`Expected string, got ${typeof n}: ${n}`)},hb=(n)=>{if(n===null||n===void 0)return;let t=sA(n),i=[];for(let s in t)if(t[s]!=null)i.push(s);if(i.length===0)throw TypeError("Unions must have exactly one non-null member. None were found.");if(i.length>1)throw TypeError(`Unions must have exactly one non-null member. Keys ${i} were not null.`);return t},Su=(n)=>{if(typeof n=="string")return Qr(Ps(n));return Qr(n)},ub=Su,rA=(n)=>{if(typeof n=="string")return Ro(Ps(n));return Ro(n)},cb=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,Ps=(n)=>{let t=n.match(cb);if(t===null||t[0].length!==n.length)throw TypeError("Expected real number, got implicit NaN");return parseFloat(n)},Iu=(n)=>{if(typeof n=="string")return eA(n);return Qr(n)},_b=Iu,wb=Iu,lb=(n)=>{if(typeof n=="string")return eA(n);return Ro(n)},eA=(n)=>{switch(n){case"NaN":return NaN;case"Infinity":return 1/0;case"-Infinity":return-1/0;default:throw Error(`Unable to parse float value: ${n}`)}},oA=(n)=>{if(typeof n==="string")return Cr(Ps(n));return Cr(n)},Ab=oA,Mb=(n)=>{if(typeof n==="string")return du(Ps(n));return du(n)},Ws=(n)=>{if(typeof n==="string")return Ru(Ps(n));return Ru(n)},fA=(n)=>{if(typeof n==="string")return Eu(Ps(n));return Eu(n)},Eo=(n)=>{return String(TypeError(n).stack||n).split(`
|
|
10
|
+
`).slice(0,5).filter((t)=>!t.includes("stackTraceWarning")).join(`
|
|
11
|
+
`)},xr={warn:console.warn},db=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],Uu=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Rb(n){let t=n.getUTCFullYear(),i=n.getUTCMonth(),s=n.getUTCDay(),r=n.getUTCDate(),e=n.getUTCHours(),f=n.getUTCMinutes(),o=n.getUTCSeconds(),h=r<10?`0${r}`:`${r}`,u=e<10?`0${e}`:`${e}`,c=f<10?`0${f}`:`${f}`,_=o<10?`0${o}`:`${o}`;return`${db[s]}, ${h} ${Uu[i]} ${t} ${u}:${c}:${_} GMT`}var Eb=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),yb=(n)=>{if(n===null||n===void 0)return;if(typeof n!=="string")throw TypeError("RFC-3339 date-times must be expressed as strings");let t=Eb.exec(n);if(!t)throw TypeError("Invalid RFC-3339 date-time value");let[i,s,r,e,f,o,h,u]=t,c=Ws(Fs(s)),_=Ut(r,"month",1,12),w=Ut(e,"day",1,31);return zr(c,_,w,{hours:f,minutes:o,seconds:h,fractionalMilliseconds:u})},Tb=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}:\d{2})|[zZ])$/),gb=(n)=>{if(n===null||n===void 0)return;if(typeof n!=="string")throw TypeError("RFC-3339 date-times must be expressed as strings");let t=Tb.exec(n);if(!t)throw TypeError("Invalid RFC-3339 date-time value");let[i,s,r,e,f,o,h,u,c]=t,_=Ws(Fs(s)),w=Ut(r,"month",1,12),l=Ut(e,"day",1,31),A=zr(_,w,l,{hours:f,minutes:o,seconds:h,fractionalMilliseconds:u});if(c.toUpperCase()!="Z")A.setTime(A.getTime()-Fb(c));return A},Sb=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$/),Ib=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$/),Ub=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})$/),bb=(n)=>{if(n===null||n===void 0)return;if(typeof n!=="string")throw TypeError("RFC-7231 date-times must be expressed as strings");let t=Sb.exec(n);if(t){let[i,s,r,e,f,o,h,u]=t;return zr(Ws(Fs(e)),lu(r),Ut(s,"day",1,31),{hours:f,minutes:o,seconds:h,fractionalMilliseconds:u})}if(t=Ib.exec(n),t){let[i,s,r,e,f,o,h,u]=t;return Bb(zr(Lb(e),lu(r),Ut(s,"day",1,31),{hours:f,minutes:o,seconds:h,fractionalMilliseconds:u}))}if(t=Ub.exec(n),t){let[i,s,r,e,f,o,h,u]=t;return zr(Ws(Fs(u)),lu(s),Ut(r.trimLeft(),"day",1,31),{hours:e,minutes:f,seconds:o,fractionalMilliseconds:h})}throw TypeError("Invalid RFC-7231 date-time value")},$b=(n)=>{if(n===null||n===void 0)return;let t;if(typeof n==="number")t=n;else if(typeof n==="string")t=Su(n);else if(typeof n==="object"&&n.tag===1)t=n.value;else throw TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");if(Number.isNaN(t)||t===1/0||t===-1/0)throw TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(t*1000))},zr=(n,t,i,s)=>{let r=t-1;return Gb(n,r,i),new Date(Date.UTC(n,r,i,Ut(s.hours,"hour",0,23),Ut(s.minutes,"minute",0,59),Ut(s.seconds,"seconds",0,60),Wb(s.fractionalMilliseconds)))},Lb=(n)=>{let t=new Date().getUTCFullYear(),i=Math.floor(t/100)*100+Ws(Fs(n));if(i<t)return i+100;return i},Ob=1576800000000,Bb=(n)=>{if(n.getTime()-new Date().getTime()>Ob)return new Date(Date.UTC(n.getUTCFullYear()-100,n.getUTCMonth(),n.getUTCDate(),n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()));return n},lu=(n)=>{let t=Uu.indexOf(n);if(t<0)throw TypeError(`Invalid month: ${n}`);return t+1},Nb=[31,28,31,30,31,30,31,31,30,31,30,31],Gb=(n,t,i)=>{let s=Nb[t];if(t===1&&Hb(n))s=29;if(i>s)throw TypeError(`Invalid day for ${Uu[t]} in ${n}: ${i}`)},Hb=(n)=>{return n%4===0&&(n%100!==0||n%400===0)},Ut=(n,t,i,s)=>{let r=fA(Fs(n));if(r<i||r>s)throw TypeError(`${t} must be between ${i} and ${s}, inclusive`);return r},Wb=(n)=>{if(n===null||n===void 0)return 0;return rA("0."+n)*1000},Fb=(n)=>{let t=n[0],i=1;if(t=="+")i=1;else if(t=="-")i=-1;else throw TypeError(`Offset direction, ${t}, must be "+" or "-"`);let s=Number(n.substring(1,3)),r=Number(n.substring(4,6));return i*(s*60+r)*60*1000},Fs=(n)=>{let t=0;while(t<n.length-1&&n.charAt(t)==="0")t++;if(t===0)return n;return n.slice(t)},Xi=function(t){return Object.assign(new String(t),{deserializeJSON(){return JSON.parse(String(t))},toString(){return String(t)},toJSON(){return String(t)}})};Xi.from=(n)=>{if(n&&typeof n==="object"&&(n instanceof Xi||("deserializeJSON"in n)))return n;else if(typeof n==="string"||Object.getPrototypeOf(n)===String.prototype)return Xi(String(n));return Xi(JSON.stringify(n))};Xi.fromObject=Xi.from;function Pb(n){if(n.includes(",")||n.includes('"'))n=`"${n.replace(/"/g,"\\\"")}"`;return n}var bu="(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?",$u="(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)",Lu="(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?",hA="(\\d?\\d)",uA="(\\d{4})",Db=new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/),Yb=new RegExp(`^${bu}, ${hA} ${$u} ${uA} ${Lu} GMT$`),mb=new RegExp(`^${bu}, ${hA}-${$u}-(\\d\\d) ${Lu} GMT$`),Jb=new RegExp(`^${bu} ${$u} ( [1-9]|\\d\\d) ${Lu} ${uA}$`),Xb=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],zb=(n)=>{if(n==null)return;let t=NaN;if(typeof n==="number")t=n;else if(typeof n==="string"){if(!/^-?\d*\.?\d+$/.test(n))throw TypeError("parseEpochTimestamp - numeric string invalid.");t=Number.parseFloat(n)}else if(typeof n==="object"&&n.tag===1)t=n.value;if(isNaN(t)||Math.abs(t)===1/0)throw TypeError("Epoch timestamps must be valid finite numbers.");return new Date(Math.round(t*1000))},Qb=(n)=>{if(n==null)return;if(typeof n!=="string")throw TypeError("RFC3339 timestamps must be strings");let t=Db.exec(n);if(!t)throw TypeError(`Invalid RFC3339 timestamp format ${n}`);let[,i,s,r,e,f,o,,h,u]=t;Qt(s,1,12),Qt(r,1,31),Qt(e,0,23),Qt(f,0,59),Qt(o,0,60);let c=new Date(Date.UTC(Number(i),Number(s)-1,Number(r),Number(e),Number(f),Number(o),Number(h)?Math.round(parseFloat(`0.${h}`)*1000):0));if(c.setUTCFullYear(Number(i)),u.toUpperCase()!="Z"){let[,_,w,l]=/([+-])(\d\d):(\d\d)/.exec(u)||[void 0,"+",0,0],A=_==="-"?1:-1;c.setTime(c.getTime()+A*(Number(w)*60*60*1000+Number(l)*60*1000))}return c},Cb=(n)=>{if(n==null)return;if(typeof n!=="string")throw TypeError("RFC7231 timestamps must be strings.");let t,i,s,r,e,f,o,h;if(h=Yb.exec(n))[,t,i,s,r,e,f,o]=h;else if(h=mb.exec(n))[,t,i,s,r,e,f,o]=h,s=(Number(s)+1900).toString();else if(h=Jb.exec(n))[,i,t,r,e,f,o,s]=h;if(s&&f){let u=Date.UTC(Number(s),Xb.indexOf(i),Number(t),Number(r),Number(e),Number(f),o?Math.round(parseFloat(`0.${o}`)*1000):0);Qt(t,1,31),Qt(r,0,23),Qt(e,0,59),Qt(f,0,60);let c=new Date(u);return c.setUTCFullYear(Number(s)),c}throw TypeError(`Invalid RFC7231 date-time value ${n}.`)};function Qt(n,t,i){let s=Number(n);if(s<t||s>i)throw Error(`Value ${s} out of range [${t}, ${i}]`)}function xb(n,t,i){if(i<=0||!Number.isInteger(i))throw Error("Invalid number of delimiters ("+i+") for splitEvery.");let s=n.split(t);if(i===1)return s;let r=[],e="";for(let f=0;f<s.length;f++){if(e==="")e=s[f];else e+=t+s[f];if((f+1)%i===0)r.push(e),e=""}if(e!=="")r.push(e);return r}var Kb=(n)=>{let t=n.length,i=[],s=!1,r=void 0,e=0;for(let f=0;f<t;++f){let o=n[f];switch(o){case'"':if(r!=="\\")s=!s;break;case",":if(!s)i.push(n.slice(e,f)),e=f+1;break}r=o}return i.push(n.slice(e)),i.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,'"')})},ql=/^-?\d*(\.\d+)?$/;class So{string;type;constructor(n,t){if(this.string=n,this.type=t,!ql.test(n))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](n){if(!n||typeof n!=="object")return!1;let t=n;return So.prototype.isPrototypeOf(n)||t.type==="bigDecimal"&&ql.test(t.string)}}function kb(n){return new So(String(n),"bigDecimal")}var cA={},yu={};for(let n=0;n<256;n++){let t=n.toString(16).toLowerCase();if(t.length===1)t=`0${t}`;cA[n]=t,yu[t]=n}function qb(n){if(n.length%2!==0)throw Error("Hex encoded strings must have an even number length");let t=new Uint8Array(n.length/2);for(let i=0;i<n.length;i+=2){let s=n.slice(i,i+2).toLowerCase();if(s in yu)t[i/2]=yu[s];else throw Error(`Cannot decode unrecognized sequence ${s} as hexadecimal`)}return t}function _A(n){let t="";for(let i=0;i<n.byteLength;i++)t+=cA[n[i]];return t}var Vb=(n)=>{if(!n)return 0;if(typeof n==="string")return Buffer.byteLength(n);else if(typeof n.byteLength==="number")return n.byteLength;else if(typeof n.size==="number")return n.size;else if(typeof n.start==="number"&&typeof n.end==="number")return n.end+1-n.start;else if(n instanceof kU){if(n.path!=null)return qU(n.path).size;else if(typeof n.fd==="number")return VU(n.fd).size}throw Error(`Body Length computation failed for ${n}`)},wA=(n)=>{if(n instanceof Uint8Array)return n;if(typeof n==="string")return go(n);if(ArrayBuffer.isView(n))return new Uint8Array(n.buffer,n.byteOffset,n.byteLength/Uint8Array.BYTES_PER_ELEMENT);return new Uint8Array(n)};function Io(n,t){if(t===void 0){t=0;for(let r of n)t+=r.byteLength}let i=new Uint8Array(t),s=0;for(let r of n)i.set(r,s),s+=r.byteLength;return i}var lA=(n,t)=>(i,s)=>async(r)=>{let{response:e}=await i(r);try{let f=await t(e,n);return{response:e,output:f}}catch(f){if(Object.defineProperty(f,"$response",{value:e,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in f)){try{f.message+=`
|
|
12
|
+
Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`}catch(h){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 f.$responseBodyText<"u"){if(f.$response)f.$response.body=f.$responseBodyText}try{if(jU.isInstance(e)){let{headers:h={}}=e,u=Object.entries(h);f.$metadata={httpStatusCode:e.statusCode,requestId:Au(/^x-[\w-]+-request-?id$/,u),extendedRequestId:Au(/^x-[\w-]+-id-2$/,u),cfId:Au(/^x-[\w-]+-cf-id$/,u)}}}catch(h){}}throw f}},Au=(n,t)=>{return(t.find(([i])=>{return i.match(n)})||[void 0,void 0])[1]},AA=(n,t)=>(i,s)=>async(r)=>{let e=n,f=s.endpointV2?async()=>aU(s.endpointV2):e.endpoint;if(!f)throw Error("No valid endpoint provider available.");let o=await t(r.input,{...n,endpoint:f});return i({...r,request:o})},MA={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},dA={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function jb(n,t,i){return{applyToStack:(s)=>{s.add(lA(n,i),MA),s.add(AA(n,t),dA)}}}class RA{algorithmIdentifier;secret;hash;constructor(n,t){this.algorithmIdentifier=n,this.secret=t,this.reset()}update(n,t){this.hash.update(wA(Vl(n,t)))}digest(){return Promise.resolve(this.hash.digest())}reset(){this.hash=this.secret?CU(this.algorithmIdentifier,Vl(this.secret)):xU(this.algorithmIdentifier)}}function Vl(n,t){if(Buffer.isBuffer(n))return n;if(typeof n==="string")return To(n,t);if(ArrayBuffer.isView(n))return Hs(n.buffer,n.byteOffset,n.byteLength);return Hs(n)}var EA=class extends Ns{expectedChecksum;checksumSourceLocation;checksum;source;base64Encoder;constructor({expectedChecksum:t,checksum:i,source:s,checksumSourceLocation:r,base64Encoder:e}){super();if(typeof s.pipe!=="function")throw Error(`@smithy/util-stream: unsupported source type ${s?.constructor?.name??s} in ChecksumStream.`);this.source=s,this.base64Encoder=e??Tu,this.expectedChecksum=t,this.checksum=i,this.checksumSourceLocation=r,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=(t)=>{if(this.destroyed)return;try{this.checksum.update(t)}catch(i){this.destroy(i);return}if(!this.push(t))this.source.pause()};onSourceEnd=async()=>{if(this.destroyed)return;try{let t=await this.checksum.digest(),i=this.base64Encoder(t);if(this.expectedChecksum!==i){this.destroy(Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${i}" in response header "${this.checksumSourceLocation}".`));return}}catch(t){this.destroy(t);return}this.push(null)};onSourceError=(t)=>{this.destroy(t)};onSourceClose=()=>{if(!this.destroyed&&!this.source.readableEnded)this.destroy(Error("Connection lost or stream closed before all data was received."))};_read(t){this.source.resume()}_destroy(t,i){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(),i(t)}},bt=(n)=>typeof ReadableStream==="function"&&(n?.constructor?.name===ReadableStream.name||n instanceof ReadableStream),Uo=(n)=>{return typeof Blob==="function"&&(n?.constructor?.name===Blob.name||n instanceof Blob)},ab=(n)=>new TextEncoder().encode(n),yA="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";Object.entries(yA).reduce((n,[t,i])=>{return n[i]=Number(t),n},{});var vb=yA.split(""),Mu=6,jl=8,Zb=63;function TA(n){let t;if(typeof n==="string")t=ab(n);else t=n;let i=typeof t==="object"&&typeof t.length==="number",s=typeof t==="object"&&typeof t.byteOffset==="number"&&typeof t.byteLength==="number";if(!i&&!s)throw Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");let r="";for(let e=0;e<t.length;e+=3){let f=0,o=0;for(let u=e,c=Math.min(e+3,t.length);u<c;u++)f|=t[u]<<(c-u-1)*jl,o+=jl;let h=Math.ceil(o/Mu);f<<=h*Mu-o;for(let u=1;u<=h;u++){let c=(h-u)*Mu;r+=vb[(f&Zb<<c)>>c]}r+="==".slice(0,4-h)}return r}var pb=typeof ReadableStream==="function"?ReadableStream:function(){};class gA extends pb{}var n$=({expectedChecksum:n,checksum:t,source:i,checksumSourceLocation:s,base64Encoder:r})=>{if(!bt(i))throw Error(`@smithy/util-stream: unsupported source type ${i?.constructor?.name??i} in ChecksumStream.`);let e=r??TA;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(h,u){t.update(h),u.enqueue(h)},async flush(h){let u=await t.digest(),c=e(u);if(n!==c){let _=Error(`Checksum mismatch: expected "${n}" but received "${c}" in response header "${s}".`);h.error(_)}else h.terminate()}});i.pipeThrough(f);let o=f.readable;return Object.setPrototypeOf(o,gA.prototype),o};function t$(n){if(typeof ReadableStream==="function"&&bt(n.source))return n$(n);return new EA(n)}class yo{allocByteArray;byteLength=0;byteArrays=[];constructor(n){this.allocByteArray=n}push(n){this.byteArrays.push(n),this.byteLength+=n.byteLength}flush(){if(this.byteArrays.length===1){let i=this.byteArrays[0];return this.reset(),i}let n=this.allocByteArray(this.byteLength),t=0;for(let i=0;i<this.byteArrays.length;++i){let s=this.byteArrays[i];n.set(s,t),t+=s.byteLength}return this.reset(),n}reset(){this.byteArrays=[],this.byteLength=0}}function i$(n,t,i){let s=n.getReader(),r=!1,e=0,f=["",new yo((u)=>new Uint8Array(u))],o=-1,h=async(u)=>{let{value:c,done:_}=await s.read(),w=c;if(_){if(o!==-1){let l=Gs(f,o);if(fi(l)>0)u.enqueue(l)}u.close()}else{let l=IA(w,!1);if(o!==l){if(o>=0)u.enqueue(Gs(f,o));o=l}if(o===-1){u.enqueue(w);return}let A=fi(w);e+=A;let d=fi(f[o]);if(A>=t&&d===0)u.enqueue(w);else{let E=SA(f,o,w);if(!r&&e>t*2)r=!0,i?.warn(`@smithy/util-stream - stream chunk size ${A} is below threshold of ${t}, automatically buffering.`);if(E>=t)u.enqueue(Gs(f,o));else await h(u)}}};return new ReadableStream({pull:h})}function SA(n,t,i){switch(t){case 0:return n[0]+=i,fi(n[0]);case 1:case 2:return n[t].push(i),fi(n[t])}}function Gs(n,t){switch(t){case 0:let i=n[0];return n[0]="",i;case 1:case 2:return n[t].flush()}throw Error(`@smithy/util-stream - invalid index ${t} given to flush()`)}function fi(n){return n?.byteLength??n?.length??0}function IA(n,t=!0){if(t&&typeof Buffer<"u"&&n instanceof Buffer)return 2;if(n instanceof Uint8Array)return 1;if(typeof n==="string")return 0;return-1}function s$(n,t,i){if(bt(n))return i$(n,t,i);let s=new Ns({read(){}}),r=!1,e=0,f=["",new yo((h)=>new Uint8Array(h)),new yo((h)=>Buffer.from(new Uint8Array(h)))],o=-1;return n.on("data",(h)=>{let u=IA(h,!0);if(o!==u){if(o>=0)s.push(Gs(f,o));o=u}if(o===-1){s.push(h);return}let c=fi(h);e+=c;let _=fi(f[o]);if(c>=t&&_===0)s.push(h);else{let w=SA(f,o,h);if(!r&&e>t*2)r=!0,i?.warn(`@smithy/util-stream - stream chunk size ${c} is below threshold of ${t}, automatically buffering.`);if(w>=t)s.push(Gs(f,o))}}),n.on("end",()=>{if(o!==-1){let h=Gs(f,o);if(fi(h)>0)s.push(h)}s.push(null)}),s}var r$=(n,t)=>{let{base64Encoder:i,bodyLengthChecker:s,checksumAlgorithmFn:r,checksumLocationName:e,streamHasher:f}=t,o=i!==void 0&&s!==void 0&&r!==void 0&&e!==void 0&&f!==void 0,h=o?f(r,n):void 0,u=n.getReader();return new ReadableStream({async pull(c){let{value:_,done:w}=await u.read();if(w){if(c.enqueue(`0\r
|
|
13
|
+
`),o){let l=i(await h);c.enqueue(`${e}:${l}\r
|
|
14
|
+
`),c.enqueue(`\r
|
|
15
|
+
`)}c.close()}else c.enqueue(`${(s(_)||0).toString(16)}\r
|
|
15
16
|
${_}\r
|
|
16
|
-
`)}})};function
|
|
17
|
-
`),_.push(
|
|
18
|
-
`)}),
|
|
19
|
-
`),
|
|
17
|
+
`)}})};function e$(n,t){let i=n,s=n;if(bt(s))return r$(s,t);let{base64Encoder:r,bodyLengthChecker:e,checksumAlgorithmFn:f,checksumLocationName:o,streamHasher:h}=t,u=r!==void 0&&f!==void 0&&o!==void 0&&h!==void 0,c=u?h(f,i):void 0,_=new Ns({read:()=>{}});return i.on("data",(w)=>{let l=e(w)||0;if(l===0)return;_.push(`${l.toString(16)}\r
|
|
18
|
+
`),_.push(w),_.push(`\r
|
|
19
|
+
`)}),i.on("end",async()=>{if(_.push(`0\r
|
|
20
|
+
`),u){let w=r(await c);_.push(`${o}:${w}\r
|
|
20
21
|
`),_.push(`\r
|
|
21
|
-
`)}_.push(null)}),_}async function
|
|
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 i.stream()};return Object.assign(t,{transformToByteArray:s,transformToString:async(i)=>{let e=await s();if(i==="base64")return tl(e);else if(i==="hex")return q_(e);else if(i===void 0||i==="utf8"||i==="utf-8")return sS(e);else if(typeof TextDecoder==="function")return new TextDecoder(i).decode(e);else throw Error("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(n)throw Error(B_);if(n=!0,F_(t))return r(t);else if(en(t))return t;else throw Error(`Cannot transform payload to web stream, got ${t}`)}})},F_=(t)=>typeof Blob==="function"&&t instanceof Blob,ol=(t)=>{if(we(t))return il(t);if(en(t))return el(t);return new Promise((n,s)=>{let r=new fl,i=t;i.pipe(r),i.on("error",(e)=>{r.end(),s(e)}),r.on("error",s),r.on("finish",function(){let e=le(this.bufferedBytes);n(e)})})};class fl extends P_{bufferedBytes=[];_write(t,n,s){this.bufferedBytes.push(t),s()}}var H_="The stream has already been transformed.",eS=(t)=>{if(!(t instanceof Xs))try{return iS(t)}catch(r){let i=t?.__proto__?.constructor?.name||t;throw Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${i}`)}let n=!1,s=async()=>{if(n)throw Error(H_);return n=!0,await ol(t)};return Object.assign(t,{transformToByteArray:s,transformToString:async(r)=>{let i=await s();if(r===void 0||Buffer.isEncoding(r))return xs(i.buffer,i.byteOffset,i.byteLength).toString(r);else return new TextDecoder(r).decode(i)},transformToWebStream:()=>{if(n)throw Error(H_);if(t.readableFlowing!==null)throw Error("The stream has been consumed by other callbacks.");if(typeof Xs.toWeb!=="function")throw Error("Readable.toWeb() is not supported. Please ensure a polyfill is available.");return n=!0,Xs.toWeb(t)}})};async function oS(t){if(typeof t.stream==="function")t=t.stream();return t.tee()}async function fS(t){if(en(t)||we(t))return oS(t);let n=new I_,s=new I_;return t.pipe(n),t.pipe(s),[n,s]}class cl extends q5(D_,ue,kf,W_){}var cS=m5,hl=C5(cS),hS=hl;uS.ChecksumStream=Z_;uS.Hash=p_;uS.LazyJsonString=cs;uS.NumericValue=_e;uS.Uint8ArrayBlobAdapter=cl;uS._parseEpochTimestamp=N8;uS._parseRfc3339DateTimeWithOffset=W8;uS._parseRfc7231DateTime=D8;uS.calculateBodyLength=k8;uS.concatBytes=le;uS.copyDocumentWithTransform=K5;uS.createBufferedReadable=a8;uS.createChecksumStream=V8;uS.dateToUtcString=u8;uS.deserializerMiddleware=K_;uS.deserializerMiddlewareOption=j_;uS.expectBoolean=j5;uS.expectByte=Qf;uS.expectFloat32=oe;uS.expectInt=p5;uS.expectInt32=Yf;uS.expectLong=xr;uS.expectNonNull=v5;uS.expectNumber=zr;uS.expectObject=Y_;uS.expectShort=mf;uS.expectString=t8;uS.expectUnion=n8;uS.fromArrayBuffer=xs;uS.fromBase64=W_;uS.fromHex=J8;uS.fromString=he;uS.fromUtf8=ue;uS.generateIdempotencyToken=hS;uS.getAwsChunkedEncodingStream=Z8;uS.getSerdePlugin=X8;uS.handleFloat=i8;uS.headStream=tS;uS.isArrayBuffer=N_;uS.isBlob=we;uS.isReadableStream=en;uS.limitedParseDouble=xf;uS.limitedParseFloat=e8;uS.limitedParseFloat32=o8;uS.logger=qr;uS.nv=Q8;uS.parseBoolean=V5;uS.parseEpochTimestamp=R8;uS.parseRfc3339DateTime=l8;uS.parseRfc3339DateTimeWithOffset=A8;uS.parseRfc7231DateTime=d8;uS.quoteHeader=y8;uS.sdkStreamMixin=eS;uS.serializerMiddleware=V_;uS.serializerMiddlewareOption=a_;uS.splitEvery=Y8;uS.splitHeader=m8;uS.splitStream=fS;uS.streamCollector=ol;uS.strictParseByte=k_;uS.strictParseDouble=zf;uS.strictParseFloat=s8;uS.strictParseFloat32=m_;uS.strictParseInt=f8;uS.strictParseInt32=c8;uS.strictParseLong=J_;uS.strictParseShort=qs;uS.toBase64=kf;uS.toHex=q_;uS.toUint8Array=C_;uS.toUtf8=D_;uS.v4=hl});var tc=Z((p$)=>{var{createReadStream:G$}=nt("fs"),{Writable:B$}=nt("stream"),{toUint8Array:Vs,concatBytes:F$}=$t(),{createHash:Cr,createHmac:H$}=nt("crypto"),ul=nt("zlib");async function Ml(t,n,s=1048576){let r=t.size,i=0;while(i<r){let e=t.slice(i,Math.min(r,i+s));n(new Uint8Array(await e.arrayBuffer())),i+=e.size}}var P$=async function(n,s){let r=new n;return await Ml(s,(i)=>{r.update(i)}),r.digest()};class pf extends B${hash;constructor(t,n){super(n);this.hash=t}_write(t,n,s){try{this.hash.update(Vs(t))}catch(r){return s(r)}s()}}var N$=(t,n)=>new Promise((s,r)=>{if(!W$(n)){r(Error("Unable to calculate hash for non-file streams."));return}let i=G$(n.path,{start:n.start,end:n.end}),e=new t,f=new pf(e);i.pipe(f),i.on("error",(o)=>{f.end(),r(o)}),f.on("error",r),f.on("finish",function(){e.digest().then(s).catch(r)})}),W$=(t)=>typeof t.path==="string",D$=(t,n)=>{if(n.readableFlowing!==null)throw Error("Unable to calculate hash for flowing readable stream");let s=new t,r=new pf(s);return n.pipe(r),new Promise((i,e)=>{n.on("error",(f)=>{r.end(),e(f)}),r.on("error",e),r.on("finish",()=>{s.digest().then(i).catch(e)})})};class Zf{digestLength=16;state=Uint32Array.from(_l);writeBuffer=new DataView(new ArrayBuffer(64));bufferLength=0;bytesHashed=0;update(t){let n=Vs(t),s=0,r=n.byteLength;this.bytesHashed+=r;while(r>0)if(this.writeBuffer.setUint8(this.bufferLength++,n[s++]),--r,this.bufferLength===64)jf(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);jf(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),jf(t,n);let i=new Uint8Array(16),e=new DataView(i.buffer);for(let f=0;f<4;++f)e.setUint32(f*4,t[f],!0);return i}reset(){this.state.set(_l),this.writeBuffer=new DataView(new ArrayBuffer(64)),this.bufferLength=0,this.bytesHashed=0}}var _l=[1732584193,4023233417,2562383102,271733878],mn=4294967295,Y$=Uint8Array.of(7,12,17,22,5,9,14,20,4,11,16,23,6,10,15,21),m$=Array.from({length:64},(t,n)=>Math.abs(Math.sin(n+1))*4294967296>>>0);function jf(t,n){let s=t[0],r=t[1],i=t[2],e=t[3];for(let f=0;f<64;++f){let o,c;if(f<16)o=r&i|~r&e,c=f;else if(f<32)o=e&r|i&~e,c=(5*f+1)%16;else if(f<48)o=r^i^e,c=(3*f+5)%16;else o=i^(r|~e),c=7*f%16;let h=n.getUint32(c*4,!0),u=e;e=i,i=r;let _=Y$[(f>>4)*4+(f&3)],l=(s+o&mn)+(h+m$[f]&mn)&mn;r=r+((l<<_|l>>>32-_)>>>0)&mn,s=u}t[0]=t[0]+s&mn,t[1]=t[1]+r&mn,t[2]=t[2]+i&mn,t[3]=t[3]+e&mn}var Q$=(()=>{try{return Cr("md5"),!0}catch{return!1}})(),gl=Q$?J$():Zf;function J$(){return class{digestLength=16;hash=Cr("md5");update(n){this.hash.update(Vs(n))}async digest(){let n=this.hash.copy().digest();return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}reset(){this.hash=Cr("md5")}}}var El=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;El[t]=n>>>0}var af=4294967295;class vf{digestLength=4;checksum=af;update(t){for(let n=0;n<t.length;++n)this.checksum=this.checksum>>>8^El[(this.checksum^t[n])&255]}digestSync(){return(this.checksum^af)>>>0}async digest(){let t=this.digestSync(),n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t,!1),n}reset(){this.checksum=af}}var ll=typeof ul.crc32==="function"?ul.crc32:void 0,dl=ll?k$(ll):vf;function k$(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 At=64,wl=32,X$=9007199254740991;class Sn{digestLength=wl;state=Int32Array.from(Al);w;buffer=new Uint8Array(64);bufferLength=0;bytesHashed=0;finished=!1;inner;outer;constructor(t){if(t){let n=Sn.normalizeKey(t);this.inner=new Sn,this.outer=new Sn;let{inner:s,outer:r}=this,i=new Uint8Array(At*2);for(let e=0;e<At;++e)i[e]=54^n[e],i[e+At]=92^n[e];s.update(i.subarray(0,At)),r.update(i.subarray(At))}}update(t){if(this.finished)throw Error("Attempted to update an already finished HMAC.");if(this.inner){this.inner.update(t);return}let n=Vs(t),s=0,{byteLength:r}=n;if(this.bytesHashed+=r,this.bytesHashed*8>X$)throw Error("Cannot hash more than 2^53 - 1 bits");while(r>0)if(this.buffer[this.bufferLength++]=n[s++],r--,this.bufferLength===At)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(Al),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,i=new DataView(n.buffer,n.byteOffset,n.byteLength);if(i.setUint8(s++,128),(s-1)%At>=At-8){for(let f=s;f<At;++f)i.setUint8(f,0);this.hashBufferWith(t,n),s=0}for(let f=s;f<At-8;++f)i.setUint8(f,0);i.setUint32(At-8,Math.floor(r/4294967296),!1),i.setUint32(At-4,r,!1),this.hashBufferWith(t,n);let e=new Uint8Array(wl);for(let f=0;f<8;++f)e[f*4]=t[f]>>>24&255,e[f*4+1]=t[f]>>>16&255,e[f*4+2]=t[f]>>>8&255,e[f*4+3]=t[f]>>>0&255;return e}static normalizeKey(t){let n=Vs(t);if(n.byteLength>At){let s=new Sn;s.update(n);let r=s.digestSync(),i=new Uint8Array(At);return i.set(r),i}if(n.byteLength<At){let s=new Uint8Array(At);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],i=t[1],e=t[2],f=t[3],o=t[4],c=t[5],h=t[6],u=t[7];for(let _=0;_<At;++_){if(_<16)s[_]=(n[_*4]&255)<<24|(n[_*4+1]&255)<<16|(n[_*4+2]&255)<<8|n[_*4+3]&255;else{let A=s[_-2],M=(A>>>17|A<<15)^(A>>>19|A<<13)^A>>>10;A=s[_-15];let E=(A>>>7|A<<25)^(A>>>18|A<<14)^A>>>3;s[_]=(M+s[_-7]|0)+(E+s[_-16]|0)}let l=(((o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7))+(o&c^~o&h)|0)+(u+(z$[_]+s[_]|0)|0)|0,w=((r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10))+(r&i^r&e^i&e)|0;u=h,h=c,c=o,o=f+l|0,f=e,e=i,i=r,r=l+w|0}t[0]+=r,t[1]+=i,t[2]+=e,t[3]+=f,t[4]+=o,t[5]+=c,t[6]+=h,t[7]+=u}}var Al=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),z$=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]),x$=(()=>{try{return Cr("sha256"),!0}catch{return!1}})(),Rl=x$?q$():Sn;function q$(){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?H$("sha256",C$(this.secret)):Cr("sha256")}}}function C$(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:K$,sign:V$,importKey:j$}=globalThis?.crypto?.subtle??{},Ae=typeof K$==="function"&&typeof V$==="function"&&typeof j$==="function"?globalThis.crypto.subtle:void 0,a$=8388608;class bl{digestLength=32;secret;pending=[];pendingBytes=0;fallback;finished=!1;constructor(t){if(t)this.secret=Vs(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>=a$)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(Ae){if(this.secret){this.finished=!0;let r=await Ae.importKey("raw",this.secret,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=await Ae.sign("HMAC",r,t);return new Uint8Array(i)}let s=await Ae.digest("SHA-256",t);return new Uint8Array(s)}let n=new Sn(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 Sn(this.secret);for(let n of this.pending)t.update(n);this.fallback=t,this.pending=[],this.pendingBytes=0}}p$.Crc32=dl;p$.Crc32Js=vf;p$.Crc32Node=dl;p$.Md5=gl;p$.Md5Js=Zf;p$.Md5Node=gl;p$.Sha256=Rl;p$.Sha256Js=Sn;p$.Sha256Node=Rl;p$.Sha256WebCrypto=bl;p$.blobHasher=P$;p$.blobReader=Ml;p$.fileStreamHasher=N$;p$.readableStreamHasher=D$});var Me=Z((NU)=>{var{Crc32:$l}=tc(),{toHex:js,fromHex:lU,toUtf8:wU,fromUtf8:AU}=$t(),{Readable:MU}=nt("stream");class as{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)Tl(n);return new as(n)}valueOf(){let t=this.bytes.slice(0),n=t[0]&128;if(n)Tl(t);return parseInt(js(t),16)*(n?-1:1)}toString(){return String(this.valueOf())}}function Tl(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 nc{toUtf8;fromUtf8;constructor(t,n){this.toUtf8=t,this.fromUtf8=n}format(t){let n=[];for(let i of Object.keys(t)){let e=this.fromUtf8(i);n.push(Uint8Array.from([e.byteLength]),e,this.formatHeaderValue(t[i]))}let s=new Uint8Array(n.reduce((i,e)=>i+e.byteLength,0)),r=0;for(let i of n)s.set(i,r),r+=i.byteLength;return s}formatHeaderValue(t){switch(t.type){case"boolean":return Uint8Array.from([t.value?it.boolTrue:it.boolFalse]);case"byte":return Uint8Array.from([it.byte,t.value]);case"short":let n=new DataView(new ArrayBuffer(3));return n.setUint8(0,it.short),n.setInt16(1,t.value,!1),new Uint8Array(n.buffer);case"integer":let s=new DataView(new ArrayBuffer(5));return s.setUint8(0,it.integer),s.setInt32(1,t.value,!1),new Uint8Array(s.buffer);case"long":let r=new Uint8Array(9);return r[0]=it.long,r.set(t.value.bytes,1),r;case"binary":let i=new DataView(new ArrayBuffer(3+t.value.byteLength));i.setUint8(0,it.byteArray),i.setUint16(1,t.value.byteLength,!1);let e=new Uint8Array(i.buffer);return e.set(t.value,3),e;case"string":let f=this.fromUtf8(t.value),o=new DataView(new ArrayBuffer(3+f.byteLength));o.setUint8(0,it.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]=it.timestamp,h.set(as.fromNumber(t.value.valueOf()).bytes,1),h;case"uuid":if(!UU.test(t.value))throw Error(`Invalid UUID received: ${t.value}`);let u=new Uint8Array(17);return u[0]=it.uuid,u.set(lU(t.value.replace(/-/g,"")),1),u}}parse(t){let n={},s=0;while(s<t.byteLength){let r=t.getUint8(s++),i=this.toUtf8(new Uint8Array(t.buffer,t.byteOffset+s,r));switch(s+=r,t.getUint8(s++)){case it.boolTrue:n[i]={type:Sl,value:!0};break;case it.boolFalse:n[i]={type:Sl,value:!1};break;case it.byte:n[i]={type:gU,value:t.getInt8(s++)};break;case it.short:n[i]={type:EU,value:t.getInt16(s,!1)},s+=2;break;case it.integer:n[i]={type:dU,value:t.getInt32(s,!1)},s+=4;break;case it.long:n[i]={type:RU,value:new as(new Uint8Array(t.buffer,t.byteOffset+s,8))},s+=8;break;case it.byteArray:let e=t.getUint16(s,!1);s+=2,n[i]={type:bU,value:new Uint8Array(t.buffer,t.byteOffset+s,e)},s+=e;break;case it.string:let f=t.getUint16(s,!1);s+=2,n[i]={type:TU,value:this.toUtf8(new Uint8Array(t.buffer,t.byteOffset+s,f))},s+=f;break;case it.timestamp:n[i]={type:SU,value:new Date(new as(new Uint8Array(t.buffer,t.byteOffset+s,8)).valueOf())},s+=8;break;case it.uuid:let o=new Uint8Array(t.buffer,t.byteOffset+s,16);s+=16,n[i]={type:$U,value:`${js(o.subarray(0,4))}-${js(o.subarray(4,6))}-${js(o.subarray(6,8))}-${js(o.subarray(8,10))}-${js(o.subarray(10))}`};break;default:throw Error("Unrecognized header type tag")}}return n}}var it;(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"})(it||(it={}));var Sl="boolean",gU="byte",EU="short",dU="integer",RU="long",bU="binary",TU="string",SU="timestamp",$U="uuid",UU=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,Ul=4,Qn=Ul*2,hs=4,LU=Qn+hs*2;function IU({byteLength:t,byteOffset:n,buffer:s}){if(t<LU)throw Error("Provided message too short to accommodate event stream message overhead");let r=new DataView(s,n,t),i=r.getUint32(0,!1);if(t!==i)throw Error("Reported message length does not match received message length");let e=r.getUint32(Ul,!1),f=r.getUint32(Qn,!1),o=r.getUint32(t-hs,!1),c=new $l;if(c.update(new Uint8Array(s,n,Qn)),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+Qn,t-(Qn+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+Qn+hs,e),body:new Uint8Array(s,n+Qn+hs+e,i-e-(Qn+hs+hs))}}class sc{headerMarshaller;messageBuffer;isEndOfStream;constructor(t,n){this.headerMarshaller=new nc(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,i=new Uint8Array(r),e=new DataView(i.buffer,i.byteOffset,i.byteLength),f=new $l;return e.setUint32(0,r,!1),e.setUint32(4,s.byteLength,!1),f.update(i.subarray(0,8)),e.setUint32(8,f.digestSync(),!1),i.set(s,12),i.set(n,s.byteLength+12),f.update(i.subarray(8,r-4)),e.setUint32(r-4,f.digestSync(),!1),i}decode(t){let{headers:n,body:s}=IU(t);return{headers:this.headerMarshaller.parse(n),body:s}}formatHeaders(t){return this.headerMarshaller.format(t)}}class rc{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 ic{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 ec{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 oc{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 Ll(t){let n=0,s=0,r=null,i=null,e=(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,_=0;while(_<u){if(!r){let w=u-_;if(!i)i=new Uint8Array(4);let A=Math.min(4-s,w);if(i.set(c.slice(_,_+A),s),s+=A,_+=A,s<4)break;e(new DataView(i.buffer).getUint32(0,!1)),i=null}let l=Math.min(n-s,u-_);if(r.set(c.slice(_,_+l),s),s+=l,_+=l,n&&n===s)yield r,r=null,n=0,s=0}}};return{[Symbol.asyncIterator]:f}}function OU(t,n){let s=fc(n.deserializer,n.toUtf8);return{[Symbol.asyncIterator]:async function*(){for await(let r of t){let i=n.eventStreamCodec.decode(r),e=await s(i);if(e===void 0)continue;yield e}}}}function fc(t,n){return async function(s){let{value:r}=s.headers[":message-type"];if(r==="error"){let i=Error(s.headers[":error-message"].value||"UnknownError");throw i.name=s.headers[":error-code"].value,i}else if(r==="exception"){let i=s.headers[":exception-type"].value,e={[i]:s},f=await t(e);if(f.$unknown){let o=Error(n(s.body));throw o.name=i,o}throw f[i]}else if(r==="event"){let i={[s.headers[":event-type"].value]:s},e=await t(i);if(e.$unknown)return;return e}else throw Error(`Unrecognizable event type: ${s.headers[":event-type"].value}`)}}var cc=class{eventStreamCodec;utfEncoder;constructor({utf8Encoder:n,utf8Decoder:s}){this.eventStreamCodec=new sc(n,s),this.utfEncoder=n}deserialize(n,s){let r=Ll(n);return new ec({messageStream:new rc({inputStream:r,decoder:this.eventStreamCodec}),deserializer:fc(s,this.utfEncoder)})}serialize(n,s){return new ic({messageStream:new oc({inputStream:n,serializer:s}),encoder:this.eventStreamCodec,includeEndFrame:!0})}},yU=(t)=>new cc(t);class hc{universalMarshaller;constructor({utf8Encoder:t,utf8Decoder:n}){this.universalMarshaller=new cc({utf8Decoder:n,utf8Encoder:t})}deserialize(t,n){let s=typeof t[Symbol.asyncIterator]==="function"?t:BU(t);return this.universalMarshaller.deserialize(s,n)}serialize(t,n){return MU.from(this.universalMarshaller.serialize(t,n))}}var GU=(t)=>new hc(t);async function*BU(t){let n=!1,s=!1,r=[];t.on("error",(i)=>{if(!n)n=!0;if(i)throw i}),t.on("data",(i)=>{r.push(i)}),t.on("end",()=>{n=!0});while(!s){let i=await new Promise((e)=>setTimeout(()=>e(r.shift()),0));if(i)yield i;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()}}}),HU=(t)=>{let n=t[Symbol.asyncIterator]();return new ReadableStream({async pull(s){let{done:r,value:i}=await n.next();if(r)return s.close();s.enqueue(i)}})},PU=(t)=>Object.assign(t,{eventStreamMarshaller:t.eventStreamSerdeProvider(t)});class Il{marshaller;serializer;deserializer;serdeContext;defaultContentType;constructor({marshaller:t,serializer:n,deserializer:s,serdeContext:r,defaultContentType:i}){this.marshaller=t,this.serializer=n,this.deserializer=s,this.serdeContext=r,this.defaultContentType=i}async serializeEventStream({eventStream:t,requestSchema:n,initialRequest:s}){let r=this.marshaller,i=n.getEventStreamMember(),e=n.getMemberSchema(i),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 _=f.flush();yield{[c]:!0,headers:u,body:_}}for await(let u of t)yield u}};return r.serialize(h,(u)=>{if(u[c])return{headers:u.headers,body:u.body};let _="";for(let d in u)if(d!=="__type"){_=d;break}let{additionalHeaders:l,body:w,eventType:A,explicitPayloadContentType:M}=this.writeEventBody(_,e,u);return{headers:{":event-type":{type:"string",value:A},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:M??o},...l},body:w}})}async deserializeEventStream({response:t,responseSchema:n,initialResponseContainer:s}){let r=this.marshaller,i=n.getEventStreamMember(),f=n.getMemberSchema(i).getMemberSchemas(),o=Symbol("initialResponseMarker"),c=r.deserialize(t.body,async(_)=>{let l="";for(let A in _)if(A!=="__type"){l=A;break}let w=_[l].body;if(l==="initial-response"){let A=await this.deserializer.read(n,w);return delete A[i],{[o]:!0,...A}}else if(l in f){let A=f[l];if(A.isStructSchema()){let M={},E=!1;for(let[d,T]of A.structIterator()){let{eventHeader:U,eventPayload:S}=T.getMergedTraits();if(E=E||Boolean(U||S),S){if(T.isBlobSchema())M[d]=w;else if(T.isStringSchema())M[d]=(this.serdeContext?.utf8Encoder??wU)(w);else if(T.isStructSchema())M[d]=await this.deserializer.read(T,w)}else if(U){let O=_[l].headers[d]?.value;if(O!=null)if(T.isNumericSchema())if(O&&typeof O==="object"&&"bytes"in O)M[d]=BigInt(O.toString());else M[d]=Number(O);else M[d]=O}}if(E)return{[l]:M};if(w.byteLength===0)return{[l]:{}}}return{[l]:await this.deserializer.read(A,w)}}else return{$unknown:_}}),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 _ in u.value)s[_]=u.value[_]}return{async*[Symbol.asyncIterator](){if(!u?.value?.[o])yield u.value;while(!0){let{done:_,value:l}=await h.next();if(_)break;yield l}}}}writeEventBody(t,n,s){let r=this.serializer,i=t,e=null,f,o=(()=>{return n.getSchema()[4].includes(t)})(),c={};if(!o){let[_,l]=s[t];i=_,r.write(15,l)}else{let _=n.getMemberSchema(t);if(_.isStructSchema()){for(let[l,w]of _.structIterator()){let{eventHeader:A,eventPayload:M}=w.getMergedTraits();if(M)e=l;else if(A){let E=s[t][l],d="binary";if(w.isNumericSchema())if(-2147483648<=E&&E<=2147483647)d="integer";else d="long";else if(w.isTimestampSchema())d="timestamp";else if(w.isStringSchema())d="string";else if(w.isBooleanSchema())d="boolean";if(E!=null)c[l]={type:d,value:E},delete s[t][l]}}if(e!==null){let l=_.getMemberSchema(e);if(l.isBlobSchema())f="application/octet-stream";else if(l.isStringSchema())f="text/plain";r.write(l,s[t][e])}else r.write(_,s[t])}else if(_.isUnitSchema())r.write(_,{});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??AU)(h):h,eventType:i,explicitPayloadContentType:f,additionalHeaders:c}}}NU.EventStreamCodec=sc;NU.EventStreamMarshaller=hc;NU.EventStreamSerde=Il;NU.HeaderMarshaller=nc;NU.Int64=as;NU.MessageDecoderStream=rc;NU.MessageEncoderStream=ic;NU.SmithyMessageDecoderStream=ec;NU.SmithyMessageEncoderStream=oc;NU.UniversalEventStreamMarshaller=cc;NU.eventStreamSerdeProvider=GU;NU.getChunkedStream=Ll;NU.getMessageUnmarshaller=fc;NU.getUnmarshalledStream=OU;NU.iterableToReadableStream=HU;NU.readableStreamToIterable=FU;NU.resolveEventStreamSerdeConfig=PU;NU.universalEventStreamSerdeProvider=yU});var Ut=Z((bL)=>{var{Uint8ArrayBlobAdapter:uc,sdkStreamMixin:vU,splitEvery:tL,splitHeader:Bl,fromBase64:Ol,_parseEpochTimestamp:nL,_parseRfc7231DateTime:sL,_parseRfc3339DateTimeWithOffset:rL,LazyJsonString:Fl,NumericValue:iL,toUtf8:Hl,fromUtf8:eL,generateIdempotencyToken:oL,toBase64:yl,dateToUtcString:fL,quoteHeader:cL}=$t(),{TypeRegistry:hL,NormalizedSchema:on,translateTraits:Pl}=Nn(),{HttpRequest:ps,HttpResponse:Nl,isValidHostname:Wl}=nn(),{parseQueryString:uL,parseUrl:_L}=nn();bL.HttpRequest=ps;bL.HttpResponse=Nl;bL.isValidHostname=Wl;bL.parseQueryString=uL;bL.parseUrl=_L;var{FieldPosition:lL}=is(),us=async(t=new Uint8Array,n)=>{if(t instanceof Uint8Array)return uc.mutate(t);if(!t)return uc.mutate(new Uint8Array);let s=n.streamCollector(t);return uc.mutate(await s)};function Vr(t){return encodeURIComponent(t).replace(/[!'()*]/g,function(n){return"%"+n.charCodeAt(0).toString(16).toUpperCase()})}class Zs{serdeContext;setSerdeContext(t){this.serdeContext=t}}class ge extends Zs{options;compositeErrorRegistry;constructor(t){super();this.options=t,this.compositeErrorRegistry=hL.for(t.defaultNamespace);for(let n of t.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(n)}getRequestType(){return ps}getResponseType(){return Nl}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=on.of(n.input),i=Pl(n.traits??{});if(i.endpoint){let e=i.endpoint?.[0];if(typeof e==="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.`);e=e.replace(`{${f}}`,c)}if(t.hostname=e+t.hostname,!Wl(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}=Me(),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,i){return[]}getEventStreamMarshaller(){let t=this.serdeContext;if(!t.eventStreamMarshaller)throw Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");return t.eventStreamMarshaller}}class Dl extends ge{async serializeRequest(t,n,s){let r=n&&typeof n==="object"?n:{},i=this.serializer,e={},f={},o=await s.endpoint(),c=on.of(t?.input),h=[],u=[],_=!1,l,w=new ps({protocol:"",hostname:"",port:void 0,path:"",fragment:void 0,query:e,headers:f,body:void 0});if(o){this.updateServiceEndpoint(w,o),this.setHostPrefix(w,t,r);let A=Pl(t.traits);if(A.http){w.method=A.http[0];let[M,E]=A.http[1].split("?");if(w.path=="/")w.path=M;else w.path+=M;let d=new URLSearchParams(E??"");for(let[T,U]of d)e[T]=U}}for(let[A,M]of c.structIterator()){let E=M.getMergedTraits()??{},d=r[A];if(d==null&&!M.isIdempotencyToken()){if(E.httpLabel){if(w.path.includes(`{${A}+}`)||w.path.includes(`{${A}}`))throw Error(`No value provided for input HTTP label: ${A}.`)}continue}if(E.httpPayload)if(M.isStreaming())if(M.isStructSchema()){if(r[A])l=await this.serializeEventStream({eventStream:r[A],requestSchema:c})}else l=d;else i.write(M,d),l=i.flush();else if(E.httpLabel){i.write(M,d);let T=i.flush();if(w.path.includes(`{${A}+}`))w.path=w.path.replace(`{${A}+}`,T.split("/").map(Vr).join("/"));else if(w.path.includes(`{${A}}`))w.path=w.path.replace(`{${A}}`,Vr(T))}else if(E.httpHeader)i.write(M,d),f[E.httpHeader.toLowerCase()]=String(i.flush());else if(typeof E.httpPrefixHeaders==="string")for(let T in d){let U=d[T],S=E.httpPrefixHeaders+T;i.write([M.getValueSchema(),{httpHeader:S}],U),f[S.toLowerCase()]=i.flush()}else if(E.httpQuery||E.httpQueryParams)this.serializeQuery(M,d,e);else _=!0,h.push(A),u.push(M)}if(_&&r){let[A,M]=(c.getName(!0)??"#Unknown").split("#"),E=c.getSchema()[6],d=[3,A,M,c.getMergedTraits(),h,u,void 0];if(E)d[6]=E;else d.pop();i.write(d,r),l=i.flush()}return w.headers=f,w.query=e,w.body=l,w}serializeQuery(t,n,s){let r=this.serializer,i=t.getMergedTraits();if(i.httpQueryParams){for(let e in n)if(!(e in s)){let f=n[e],o=t.getValueSchema();Object.assign(o.getMergedTraits(),{...i,httpQuery:e,httpQueryParams:void 0}),this.serializeQuery(o,f,s)}return}if(t.isListSchema()){let e=!!t.getMergedTraits().sparse,f=[];for(let o of n){r.write([t.getValueSchema(),i],o);let c=r.flush();if(e||c!==void 0)f.push(c)}s[i.httpQuery]=f}else r.write([t,i],n),s[i.httpQuery]=r.flush()}async deserializeResponse(t,n,s){let r=this.deserializer,i=on.of(t.output),e={};if(s.statusCode>=300){let o=await us(s.body,n);if(o.byteLength>0)Object.assign(e,await r.read(15,o));throw await this.handleError(t,n,s,e,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(i,n,s,e);if(f.length){let o=await us(s.body,n);if(o.byteLength>0){let c=await r.read(i,o);for(let h of f)if(c[h]!=null)e[h]=c[h]}}else if(f.discardResponseBody)await us(s.body,n);return e.$metadata=this.deserializeMetadata(s),e}async deserializeHttpMessage(t,n,s,r,i){let e;if(r instanceof Set)e=i;else e=r;let f=!0,o=this.deserializer,c=on.of(t),h=[];for(let[u,_]of c.structIterator()){let l=_.getMemberTraits();if(l.httpPayload){if(f=!1,_.isStreaming())if(_.isStructSchema())e[u]=await this.deserializeEventStream({response:s,responseSchema:c});else e[u]=vU(s.body);else if(s.body){let A=await us(s.body,n);if(A.byteLength>0)e[u]=await o.read(_,A)}}else if(l.httpHeader){let w=String(l.httpHeader).toLowerCase(),A=s.headers[w];if(A!=null)if(_.isListSchema()){let M=_.getValueSchema();M.getMergedTraits().httpHeader=w;let E;if(M.isTimestampSchema()&&M.getSchema()===4)E=tL(A,",",2);else E=Bl(A);let d=[];for(let T of E)d.push(await o.read(M,T.trim()));e[u]=d}else e[u]=await o.read(_,A)}else if(l.httpPrefixHeaders!==void 0){e[u]={};for(let w in s.headers)if(w.startsWith(l.httpPrefixHeaders)){let A=s.headers[w],M=_.getValueSchema();M.getMergedTraits().httpHeader=w,e[u][w.slice(l.httpPrefixHeaders.length)]=await o.read(M,A)}}else if(l.httpResponseCode)e[u]=s.statusCode;else h.push(u)}return h.discardResponseBody=f,h}}class Yl extends ge{async serializeRequest(t,n,s){let r=this.serializer,i={},e={},f=await s.endpoint(),o=on.of(t?.input),c=o.getSchema(),h,u=n&&typeof n==="object"?n:{},_=new ps({protocol:"",hostname:"",port:void 0,path:"/",fragment:void 0,query:i,headers:e,body:void 0});if(f)this.updateServiceEndpoint(_,f),this.setHostPrefix(_,t,u);if(u){let l=o.getEventStreamMember();if(l){if(u[l]){let w={};for(let[A,M]of o.structIterator())if(A!==l&&u[A])r.write(M,u[A]),w[A]=r.flush();h=await this.serializeEventStream({eventStream:u[l],requestSchema:o,initialRequest:w})}}else r.write(c,u),h=r.flush()}return _.headers=Object.assign(_.headers,e),_.query=i,_.body=h,_.method="POST",_}async deserializeResponse(t,n,s){let r=this.deserializer,i=on.of(t.output),e={};if(s.statusCode>=300){let o=await us(s.body,n);if(o.byteLength>0)Object.assign(e,await r.read(15,o));throw await this.handleError(t,n,s,e,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=i.getEventStreamMember();if(f)e[f]=await this.deserializeEventStream({response:s,responseSchema:i,initialResponseContainer:e});else{let o=await us(s.body,n);if(o.byteLength>0)Object.assign(e,await r.read(i,o))}return e.$metadata=this.deserializeMetadata(s),e}}var ml=(t,n,s,r,i,e)=>{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(i,e?f.split("/").map((o)=>Vr(o)).join("/"):Vr(f))}else throw Error("No value provided for input HTTP label: "+s+".");return t};function wL(t,n){return new _c(t,n)}class _c{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 i of this.resolvePathStack)i(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((i)=>{this.path=ml(i,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 lc(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:i,httpQuery:e}=t.getMergedTraits();return(n.httpBindings?typeof r==="string"||Boolean(i)?6:Boolean(e)||Boolean(s)?5:void 0:void 0)??n.timestampFormat.default}class wc extends Zs{settings;constructor(t){super();this.settings=t}read(t,n){let s=on.of(t);if(s.isListSchema())return Bl(n).map((r)=>this.read(s.getValueSchema(),r));if(s.isBlobSchema())return(this.serdeContext?.base64Decoder??Ol)(n);if(s.isTimestampSchema())switch(lc(s,this.settings)){case 5:return rL(n);case 6:return sL(n);case 7:return nL(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,i=n;if(r){if(s.getMergedTraits().httpHeader)i=this.base64ToUtf8(i);if(r==="application/json"||r.endsWith("+json"))i=Fl.from(i);return i}}if(s.isNumericSchema())return Number(n);if(s.isBigIntegerSchema())return BigInt(n);if(s.isBigDecimalSchema())return new iL(n,"bigDecimal");if(s.isBooleanSchema())return String(n).toLowerCase()==="true";return n}base64ToUtf8(t){return(this.serdeContext?.utf8Encoder??Hl)((this.serdeContext?.base64Decoder??Ol)(t))}}class Ql extends Zs{codecDeserializer;stringDeserializer;constructor(t,n){super();this.codecDeserializer=t,this.stringDeserializer=new wc(n)}setSerdeContext(t){this.stringDeserializer.setSerdeContext(t),this.codecDeserializer.setSerdeContext(t),this.serdeContext=t}read(t,n){let s=on.of(t),r=s.getMergedTraits(),i=this.serdeContext?.utf8Encoder??Hl;if(r.httpHeader||r.httpResponseCode)return this.stringDeserializer.read(s,i(n));if(r.httpPayload){if(s.isBlobSchema()){let e=this.serdeContext?.utf8Decoder??eL;if(typeof n==="string")return e(n);return n}else if(s.isStringSchema()){if("byteLength"in n)return i(n);return n}}return this.codecDeserializer.read(s,n)}}class Ac extends Zs{settings;stringBuffer="";constructor(t){super();this.settings=t}write(t,n){let s=on.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(lc(s,this.settings)){case 5:this.stringBuffer=n.toISOString().replace(".000Z","Z");break;case 6:this.stringBuffer=fL(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??yl)(n);return}if(s.isListSchema()&&Array.isArray(n)){let e="";for(let f of n){this.write([s.getValueSchema(),s.getMergedTraits()],f);let o=this.flush(),c=s.getValueSchema().isTimestampSchema()?o:cL(o);if(e!=="")e+=", ";e+=c}this.stringBuffer=e;return}this.stringBuffer=JSON.stringify(n,null,2);break;case"string":let r=s.getMergedTraits().mediaType,i=n;if(r){if(r==="application/json"||r.endsWith("+json"))i=Fl.from(i);if(s.getMergedTraits().httpHeader){this.stringBuffer=(this.serdeContext?.base64Encoder??yl)(i.toString());return}}this.stringBuffer=n;break;default:if(s.isIdempotencyToken())this.stringBuffer=oL();else this.stringBuffer=String(n)}}flush(){let t=this.stringBuffer;return this.stringBuffer="",t}}class Jl{codecSerializer;stringSerializer;buffer;constructor(t,n,s=new Ac(n)){this.codecSerializer=t,this.stringSerializer=s}setSerdeContext(t){this.codecSerializer.setSerdeContext(t),this.stringSerializer.setSerdeContext(t)}write(t,n){let s=on.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 kl{name;kind;values;constructor({name:t,kind:n=lL.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 Xl{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 AL=(t)=>{return{setHttpHandler(n){t.httpHandler=n},httpHandler(){return t.httpHandler},updateHttpClientConfig(n,s){t.httpHandler?.updateHttpClientConfig(n,s)},httpHandlerConfigs(){return t.httpHandler.httpHandlerConfigs()}}},ML=(t)=>{return{httpHandler:t.httpHandler()}},Gl="content-length";function zl(t){return(n)=>async(s)=>{let r=s.request;if(ps.isInstance(r)){let{body:i,headers:e}=r;if(i&&Object.keys(e).map((f)=>f.toLowerCase()).indexOf(Gl)===-1)try{let f=t(i);r.headers={...r.headers,[Gl]:String(f)}}catch(f){}}return n({...s,request:r})}}var xl={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},gL=(t)=>({applyToStack:(n)=>{n.add(zl(t.bodyLengthChecker),xl)}}),Kr=(t)=>encodeURIComponent(t).replace(/[!'()*]/g,EL),EL=(t)=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`,dL=(t)=>t.split("/").map(Kr).join("/");function RL(t){let n=[];for(let s of Object.keys(t).sort()){let r=t[s];if(s=Kr(s),Array.isArray(r))for(let i=0,e=r.length;i<e;i++)n.push(`${s}=${Kr(r[i])}`);else{let i=s;if(r||typeof r==="string")i+=`=${Kr(r)}`;n.push(i)}}return n.join("&")}bL.Field=kl;bL.Fields=Xl;bL.FromStringShapeDeserializer=wc;bL.HttpBindingProtocol=Dl;bL.HttpInterceptingShapeDeserializer=Ql;bL.HttpInterceptingShapeSerializer=Jl;bL.HttpProtocol=ge;bL.RequestBuilder=_c;bL.RpcProtocol=Yl;bL.SerdeContext=Zs;bL.ToStringShapeSerializer=Ac;bL.buildQueryString=RL;bL.collectBody=us;bL.contentLengthMiddleware=zl;bL.contentLengthMiddlewareOptions=xl;bL.determineTimestampFormat=lc;bL.escapeUri=Kr;bL.escapeUriPath=dL;bL.extendedEncodeURIComponent=Vr;bL.getContentLengthPlugin=gL;bL.getHttpHandlerExtensionConfiguration=AL;bL.requestBuilder=wL;bL.resolveHttpHandlerRuntimeConfig=ML;bL.resolvedPath=ml});var vr=Z((RI)=>{var{Readable:aL}=nt("stream"),{NoOpLogger:pL,normalizeProvider:ql}=Rn(),{HttpResponse:Cl,HttpRequest:de}=Ut(),{parseRfc7231DateTime:ZL,v4:Kl}=$t(),Vl=(t)=>t?.body instanceof aL||typeof ReadableStream<"u"&&t?.body instanceof ReadableStream,vL=["AuthFailure","InvalidSignatureException","RequestExpired","RequestInTheFuture","RequestTimeTooSkewed","SignatureDoesNotMatch"],tI=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],nI=["TimeoutError","RequestTimeout","RequestTimeoutException"],sI=[500,502,503,504],rI=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],iI=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN"],dc=(t)=>t?.$retryable!==void 0,jl=(t)=>vL.includes(t.name),al=(t)=>t.$metadata?.clockSkewCorrected,pl=(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)},ar=(t)=>t.$metadata?.httpStatusCode===429||tI.includes(t.name)||t.$retryable?.throttling==!0,pr=(t,n=0)=>dc(t)||al(t)||t.name==="InvalidSignatureException"&&t.message?.includes("Signature expired")||nI.includes(t.name)||rI.includes(t?.code||"")||iI.includes(t?.code||"")||sI.includes(t.$metadata?.httpStatusCode||0)||pl(t)||vl(t)||t.cause!==void 0&&n<=10&&pr(t.cause,n+1),Zl=(t)=>{if(t.$metadata?.httpStatusCode!==void 0){let n=t.$metadata.httpStatusCode;if(500<=n&&n<=599&&!pr(t))return!0;return!1}return!1};function vl(t){return t.code==="ERR_HTTP2_STREAM_ERROR"&&t.message.includes("NGHTTP2_REFUSED_STREAM")}var tw=100,be=20000,nw=500,Re=500,sw=5,rw=10,Rc=1,Te="amz-sdk-invocation-id",Se="amz-sdk-request";function iw(t,n){if(!Cl.isInstance(t))return;for(let s of Object.keys(t.headers)){let r=s.toLowerCase();if(r==="retry-after"){let i=t.headers[s],e=NaN;if(i.endsWith("GMT"))try{e=(ZL(i).getTime()-Date.now())/1000}catch(f){n?.trace?.("Failed to parse retry-after header"),n?.trace?.(f)}else if(i.match(/ GMT, ((\d+)|(\d+\.\d+))$/))e=Number(i.match(/ GMT, ([\d.]+)$/)?.[1]);else if(i.match(/^((\d+)|(\d+\.\d+))$/))e=Number(i);else if(Date.parse(i)>=Date.now())e=(Date.parse(i)-Date.now())/1000;if(isNaN(e))return;return new Date(Date.now()+e*1000)}else if(r==="x-amz-retry-after"){let i=t.headers[s],e=Number(i);if(isNaN(e)){n?.trace?.(`Failed to parse x-amz-retry-after=${i}`);return}return new Date(Date.now()+e)}}}function eI(t,n){return iw(t,n)}var ew=(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 ow(t){return(n)=>(s,r)=>async(i)=>{let e=await n.retryStrategy(),f=await n.maxAttempts();if(fI(e)){e=e;let o=await e.acquireInitialRetryToken((r.partition_id??"")+(r.__retryLongPoll?":longpoll":"")),c=Error(),h=0,u=0,{request:_}=i,l=de.isInstance(_);if(l)_.headers[Te]=Kl();while(!0)try{if(l)_.headers[Se]=`attempt=${h+1}; max=${f}`;let{response:w,output:A}=await s(i);return e.recordSuccess(o),A.$metadata.attempts=h+1,A.$metadata.totalRetryDelay=u,{response:w,output:A}}catch(w){let A=cI(w,n.logger);if(c=ew(w),l&&t(_))throw(r.logger instanceof pL?console:r.logger)?.warn("An error was encountered in a non-retryable streaming request."),c;try{o=await e.refreshRetryTokenForRetry(o,A)}catch(E){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 oI(M)}}else{if(e=e,e?.mode)r.userAgent=[...r.userAgent||[],["cfg/retry-mode",e.mode]];return e.retry(s,i)}}}var oI=(t)=>new Promise((n)=>setTimeout(n,t)),fI=(t)=>typeof t.acquireInitialRetryToken<"u"&&typeof t.refreshRetryTokenForRetry<"u"&&typeof t.recordSuccess<"u",cI=(t,n)=>{let s={error:t,errorType:hI(t)},r=iw(t.$response,n);if(r)s.retryAfterHint=r;return s},hI=(t)=>{if(ar(t))return"THROTTLING";if(pr(t))return"TRANSIENT";if(Zl(t))return"SERVER_ERROR";return"CLIENT_ERROR"},fw={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0};function uI(t){let n=ow(t);return(s)=>({applyToStack:(r)=>{r.add(n(s),fw)}})}class Zr{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"||ar(s?.error??t)){let e=!this.enabled?this.measuredTxRate:Math.min(this.measuredTxRate,this.fillRate);this.lastMaxRate=e,this.calculateTimeWindow(),this.lastThrottleTime=this.getCurrentTimeInSeconds(),n=this.cubicThrottle(e),this.enableTokenBucket()}else this.calculateTimeWindow(),n=this.cubicSuccess(this.getCurrentTimeInSeconds());let i=Math.min(n,2*this.measuredTxRate);this.updateTokenBucketRate(i)}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)=>Zr.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 _t{static v2026=typeof process<"u"&&process.env?.SMITHY_NEW_RETRIES_2026==="true";static delay(){return _t.v2026?50:100}static throttlingDelay(){return _t.v2026?1000:500}static cost(){return _t.v2026?14:5}static throttlingCost(){return _t.v2026?5:10}static modifiedCostType(){return _t.v2026?"THROTTLING":"TRANSIENT"}}class cw{x=_t.delay();computeNextBackoffDelay(t){let n=Math.random(),s=2,r=n*Math.min(this.x*2**t,be);return Math.floor(r)}setDelayBase(t){this.x=t}}class Mc{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(be,this.delay)}getRetryCost(){return this.cost}isLongPoll(){return this.longPoll}}var $n;(function(t){t.STANDARD="standard",t.ADAPTIVE="adaptive"})($n||($n={}));var _s=3,hw=$n.STANDARD,Ee={incompatible:1,attempts:2,capacity:3},jr=class{mode=$n.STANDARD;retryBackoffStrategy;capacity=Re;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()=>_s,this.baseDelay??=_t.delay(),this.retryBackoffStrategy??=new cw}async acquireInitialRetryToken(n){return new Mc(_t.delay(),0,void 0,_t.v2026&&n.includes(":longpoll"))}async refreshRetryTokenForRetry(n,s){let r=await this.getMaxAttempts(),i=this.retryCode(n,s,r),e=i===0,f=n.isLongPoll?.();if(e||f){let o=s.errorType;this.retryBackoffStrategy.setDelayBase(o==="THROTTLING"?_t.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(!e){let u=_t.v2026&&i===Ee.capacity&&f?h:0;if(u>0)await new Promise((_)=>setTimeout(_,u))}else{let u=this.getCapacityCost(o);this.capacity-=u;let _=new Mc(0,n.getRetryCount()+1,u,n.isLongPoll?.()??!1);return await new Promise((l)=>setTimeout(l,h)),_.$retryLog.acquisitionDelay=h,_}}throw Error("No retry token available")}recordSuccess(n){this.capacity=Math.min(Re,this.capacity+(n.getRetryCost()??Rc))}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 ${_s}`),_s}}retryCode(n,s,r){let i=n.getRetryCount()+1,e=this.isRetryableError(s.errorType)?0:Ee.incompatible,f=i<r?0:Ee.attempts,o=this.capacity>=this.getCapacityCost(s.errorType)?0:Ee.capacity;return e||f||o}getCapacityCost(n){return n===_t.modifiedCostType()?_t.throttlingCost():_t.cost()}isRetryableError(n){return n==="THROTTLING"||n==="TRANSIENT"}},uw=class{mode=$n.ADAPTIVE;rateLimiter;standardRetryStrategy;constructor(n,s){let{rateLimiter:r}=s??{};this.rateLimiter=r??new Zr,this.standardRetryStrategy=s?new jr({maxAttempts:typeof n==="number"?n:3,...s}):new jr(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 _w extends jr{computeNextBackoffDelay;constructor(t,n=_t.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 _I=(t,n)=>{let s=t,r=Rc,i=sw,e=rw,f=t,o=(_)=>_.name==="TimeoutError"?e:i,c=(_)=>o(_)<=f;return Object.freeze({hasRetryTokens:c,retrieveRetryTokens:(_)=>{if(!c(_))throw Error("No retry token available");let l=o(_);return f-=l,l},releaseRetryTokens:(_)=>{f+=_??r,f=Math.min(f,s)}})},lw=(t,n)=>Math.floor(Math.min(be,Math.random()*2**n*t)),ww=(t)=>{if(!t)return!1;return dc(t)||jl(t)||ar(t)||pr(t)};class bc{maxAttemptsProvider;retryDecider;delayDecider;retryQuota;mode=$n.STANDARD;constructor(t,n){this.maxAttemptsProvider=t,this.retryDecider=n?.retryDecider??ww,this.delayDecider=n?.delayDecider??lw,this.retryQuota=n?.retryQuota??_I(Re)}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=_s}return t}async retry(t,n,s){let r,i=0,e=0,f=await this.getMaxAttempts(),{request:o}=n;if(de.isInstance(o))o.headers[Te]=Kl();while(!0)try{if(de.isInstance(o))o.headers[Se]=`attempt=${i+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=i+1,h.$metadata.totalRetryDelay=e,{response:c,output:h}}catch(c){let h=ew(c);if(i++,this.shouldRetry(h,i,f)){r=this.retryQuota.retrieveRetryTokens(h);let u=this.delayDecider(ar(h)?nw:tw,i),_=lI(h.$response),l=Math.max(_||0,u);e+=l,await new Promise((w)=>setTimeout(w,l));continue}if(!h.$metadata)h.$metadata={};throw h.$metadata.attempts=i,h.$metadata.totalRetryDelay=e,h}}}var lI=(t)=>{if(!Cl.isInstance(t))return;let n=Object.keys(t.headers).find((e)=>e.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 i=new Date(s);return Math.min(i.getTime()-Date.now(),20000)};class Aw extends bc{rateLimiter;constructor(t,n){let{rateLimiter:s,...r}=n??{};super(t,r);this.rateLimiter=s??new Zr,this.mode=$n.ADAPTIVE}async retry(t,n){return super.retry(t,n,{beforeRequest:async()=>{return this.rateLimiter.getSendToken()},afterRequest:(s)=>{this.rateLimiter.updateClientSendingRate(s)}})}}var gc="AWS_MAX_ATTEMPTS",Ec="max_attempts",wI={environmentVariableSelector:(t)=>{let n=t[gc];if(!n)return;let s=parseInt(n);if(Number.isNaN(s))throw Error(`Environment variable ${gc} mast be a number, got "${n}"`);return s},configFileSelector:(t)=>{let n=t[Ec];if(!n)return;let s=parseInt(n);if(Number.isNaN(s))throw Error(`Shared config file entry ${Ec} mast be a number, got "${n}"`);return s},default:_s},AI=(t,n)=>{let{retryStrategy:s,retryMode:r}=t,{defaultMaxAttempts:i=_s,defaultBaseDelay:e=_t.delay()}=n??{},f=ql(t.maxAttempts??i),o=s?Promise.resolve(s):void 0,c=async()=>{let h=await f();if(await ql(r)()===$n.ADAPTIVE)return new uw(f,{maxAttempts:h,baseDelay:e});return new jr({maxAttempts:h,baseDelay:e})};return Object.assign(t,{maxAttempts:f,retryStrategy:()=>o??=c()})},Mw="AWS_RETRY_MODE",gw="retry_mode",MI={environmentVariableSelector:(t)=>t[Mw],configFileSelector:(t)=>t[gw],default:hw},Ew=()=>(t)=>async(n)=>{let{request:s}=n;if(de.isInstance(s))delete s.headers[Te],delete s.headers[Se];return t(n)},dw={name:"omitRetryHeadersMiddleware",tags:["RETRY","HEADERS","OMIT_RETRY_HEADERS"],relation:"before",toMiddleware:"awsAuthMiddleware",override:!0},gI=(t)=>({applyToStack:(n)=>{n.addRelativeTo(Ew(),dw)}}),EI=ow(Vl),dI=uI(Vl);RI.AdaptiveRetryStrategy=uw;RI.CONFIG_MAX_ATTEMPTS=Ec;RI.CONFIG_RETRY_MODE=gw;RI.ConfiguredRetryStrategy=_w;RI.DEFAULT_MAX_ATTEMPTS=_s;RI.DEFAULT_RETRY_DELAY_BASE=tw;RI.DEFAULT_RETRY_MODE=hw;RI.DefaultRateLimiter=Zr;RI.DeprecatedAdaptiveRetryStrategy=Aw;RI.DeprecatedStandardRetryStrategy=bc;RI.ENV_MAX_ATTEMPTS=gc;RI.ENV_RETRY_MODE=Mw;RI.INITIAL_RETRY_TOKENS=Re;RI.INVOCATION_ID_HEADER=Te;RI.MAXIMUM_RETRY_DELAY=be;RI.NODE_MAX_ATTEMPT_CONFIG_OPTIONS=wI;RI.NODE_RETRY_MODE_CONFIG_OPTIONS=MI;RI.NO_RETRY_INCREMENT=Rc;RI.REQUEST_HEADER=Se;RI.RETRY_COST=sw;RI.RETRY_MODES=$n;RI.Retry=_t;RI.StandardRetryStrategy=jr;RI.THROTTLING_RETRY_DELAY_BASE=nw;RI.TIMEOUT_RETRY_COST=rw;RI.defaultDelayDecider=lw;RI.defaultRetryDecider=ww;RI.getOmitRetryHeadersPlugin=gI;RI.getRetryAfterHint=eI;RI.getRetryPlugin=dI;RI.isBrowserNetworkError=pl;RI.isClockSkewCorrectedError=al;RI.isClockSkewError=jl;RI.isNodeJsHttp2TransientError=vl;RI.isRetryableByTrait=dc;RI.isServerError=Zl;RI.isThrottlingError=ar;RI.isTransientError=pr;RI.omitRetryHeadersMiddleware=Ew;RI.omitRetryHeadersMiddlewareOptions=dw;RI.resolveRetryConfig=AI;RI.retryMiddleware=EI;RI.retryMiddlewareOptions=fw});var bw=Z((hO)=>{var Jn={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")},Tc=["true","1"].includes(process.env?.AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA??"");if(!Tc)globalThis.awslambda=globalThis.awslambda||{};class $e{static PROTECTED_KEYS=Jn;isProtectedKey(t){return Object.values(Jn).includes(t)}getRequestId(){return this.get(Jn.REQUEST_ID)??"-"}getXRayTraceId(){return this.get(Jn.X_RAY_TRACE_ID)}getTenantId(){return this.get(Jn.TENANT_ID)}getTraceparent(){return this.get(Jn.TRACEPARENT)}getTracestate(){return this.get(Jn.TRACESTATE)}getBaggage(){return this.get(Jn.BAGGAGE)}}class Rw extends $e{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 $c extends $e{als;static async create(){let t=new $c,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)}}hO.InvokeStore=void 0;(function(t){let n=null;async function s(r){if(!n)n=(async()=>{let e=r===!0||"AWS_LAMBDA_MAX_CONCURRENCY"in process.env?await $c.create():new Rw;if(!Tc&&globalThis.awslambda?.InvokeStore)return globalThis.awslambda.InvokeStore;else if(!Tc&&globalThis.awslambda)return globalThis.awslambda.InvokeStore=e,e;else return e})();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})(hO.InvokeStore||(hO.InvokeStore={}));hO.InvokeStoreBase=$e});var kn=Z((IO)=>{var{getSmithyContext:Uc}=nn();IO.getSmithyContext=Uc;var{HttpRequest:Lc}=Ut(),{requestBuilder:_O}=Ut();IO.requestBuilder=_O;var{HttpApiKeyAuthLocation:Tw}=is(),lO=(t,n)=>{if(!n||n.length===0)return t;let s=[];for(let r of n)for(let i of t)if(i.schemeId.split("#")[1]===r)s.push(i);for(let r of t)if(!s.find(({schemeId:i})=>i===r.schemeId))s.push(r);return s};function wO(t){let n=new Map;for(let s of t)n.set(s.schemeId,s);return n}var Ic=(t,n)=>(s,r)=>async(i)=>{let e=t.httpAuthSchemeProvider(await n.httpAuthSchemeParametersProvider(t,r,i.input)),f=t.authSchemePreference?await t.authSchemePreference():[],o=lO(e,f),c=wO(t.httpAuthSchemes),h=Uc(r),u=[];for(let _ of o){let l=c.get(_.schemeId);if(!l){u.push(`HttpAuthScheme \`${_.schemeId}\` was not enabled for this service.`);continue}let w=l.identityProvider(await n.identityProviderConfigProvider(t));if(!w){u.push(`HttpAuthScheme \`${_.schemeId}\` did not have an IdentityProvider configured.`);continue}let{identityProperties:A={},signingProperties:M={}}=_.propertiesExtractor?.(t,r)||{};_.identityProperties=Object.assign(_.identityProperties||{},A),_.signingProperties=Object.assign(_.signingProperties||{},M),h.selectedHttpAuthScheme={httpAuthOption:_,identity:await w(_.identityProperties),signer:l.signer};break}if(!h.selectedHttpAuthScheme)throw Error(u.join(`
|
|
23
|
-
`));return s(i)},Sw={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},AO=(t,{httpAuthSchemeParametersProvider:n,identityProviderConfigProvider:s})=>({applyToStack:(r)=>{r.addRelativeTo(Ic(t,{httpAuthSchemeParametersProvider:n,identityProviderConfigProvider:s}),Sw)}}),$w={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"serializerMiddleware"},MO=(t,{httpAuthSchemeParametersProvider:n,identityProviderConfigProvider:s})=>({applyToStack:(r)=>{r.addRelativeTo(Ic(t,{httpAuthSchemeParametersProvider:n,identityProviderConfigProvider:s}),$w)}}),gO=(t)=>(n)=>{throw n},EO=(t,n)=>{},Uw=(t)=>(n,s)=>async(r)=>{if(!Lc.isInstance(r.request))return n(r);let e=Uc(s).selectedHttpAuthScheme;if(!e)throw Error("No HttpAuthScheme was selected: unable to sign request");let{httpAuthOption:{signingProperties:f={}},identity:o,signer:c}=e,h=await n({...r,request:await c.sign(r.request,o,f)}).catch((c.errorHandler||gO)(f));return(c.successHandler||EO)(h.response,f),h},Lw={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},dO=(t)=>({applyToStack:(n)=>{n.addRelativeTo(Uw(),Lw)}}),RO=(t)=>{if(typeof t==="function")return t;let n=Promise.resolve(t);return()=>n},bO=async(t,n,s,r=(e)=>e,...i)=>{let e=new t(s);return e=r(e)??e,await n.send(e,...i)};function TO(t,n,s,r,i){return async function*(f,o,...c){let h=o,u=f.startingToken??h[s],_=!0,l;while(_){if(h[s]=u,i)h[i]=h[i]??f.pageSize;if(f.client instanceof t)l=await bO(n,f.client,o,f.withCommand,...c);else throw Error(`Invalid client, expected instance of ${t.name}`);yield l;let w=u;u=SO(l,r),_=!!(u&&(!f.stopOnSameToken||u!==w))}return}}var SO=(t,n)=>{let s=t,r=n.split(".");for(let i of r){if(!s||typeof s!=="object")return;s=s[i]}return s};function $O(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 Iw{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 Ow{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=Lc.clone(t);if(s.in===Tw.QUERY)r.query[s.name]=n.apiKey;else if(s.in===Tw.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 yw{async sign(t,n,s){let r=Lc.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 Gw{async sign(t,n,s){return t}}var Bw=(t)=>function(s){return Hw(s)&&s.expiration.getTime()-Date.now()<t},Fw=300000,UO=Bw(Fw),Hw=(t)=>t.expiration!==void 0,LO=(t,n,s)=>{if(t===void 0)return;let r=typeof t!=="function"?async()=>Promise.resolve(t):t,i,e,f,o=!1,c=async(h)=>{if(!e)e=r(h);try{i=await e,f=!0,o=!1}finally{e=void 0}return i};if(n===void 0)return async(h)=>{if(!f||h?.forceRefresh)i=await c(h);return i};return async(h)=>{if(!f||h?.forceRefresh)i=await c(h);if(o)return i;if(!s(i))return o=!0,i;if(n(i))return await c(h),i;return i}};IO.DefaultIdentityProviderConfig=Iw;IO.EXPIRATION_MS=Fw;IO.HttpApiKeyAuthSigner=Ow;IO.HttpBearerAuthSigner=yw;IO.NoAuthSigner=Gw;IO.createIsIdentityExpiredFunction=Bw;IO.createPaginator=TO;IO.doesIdentityRequireRefresh=Hw;IO.getHttpAuthSchemeEndpointRuleSetPlugin=AO;IO.getHttpAuthSchemePlugin=MO;IO.getHttpSigningPlugin=dO;IO.httpAuthSchemeEndpointRuleSetMiddlewareOptions=Sw;IO.httpAuthSchemeMiddleware=Ic;IO.httpAuthSchemeMiddlewareOptions=$w;IO.httpSigningMiddleware=Uw;IO.httpSigningMiddlewareOptions=Lw;IO.isIdentityExpired=UO;IO.memoizeIdentityProvider=LO;IO.normalizeProvider=RO;IO.setFeature=$O});var Pw=Z((ti,Oc)=>{(function(t,n){typeof ti=="object"&&typeof Oc=="object"?Oc.exports=n():typeof define=="function"&&define.amd?define([],n):typeof ti=="object"?ti.bowser=n():t.bowser=n()})(ti,function(){return function(t){var n={};function s(r){if(n[r])return n[r].exports;var i=n[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,s),i.l=!0,i.exports}return s.m=t,s.c=n,s.d=function(r,i,e){s.o(r,i)||Object.defineProperty(r,i,{enumerable:!0,get:e})},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,i){if(1&i&&(r=s(r)),8&i)return r;if(4&i&&typeof r=="object"&&r&&r.__esModule)return r;var e=Object.create(null);if(s.r(e),Object.defineProperty(e,"default",{enumerable:!0,value:r}),2&i&&typeof r!="string")for(var f in r)s.d(e,f,function(o){return r[o]}.bind(null,f));return e},s.n=function(r){var i=r&&r.__esModule?function(){return r.default}:function(){return r};return s.d(i,"a",i),i},s.o=function(r,i){return Object.prototype.hasOwnProperty.call(r,i)},s.p="",s(s.s=90)}({17:function(t,n,s){n.__esModule=!0,n.default=void 0;var r=s(18),i=function(){function e(){}return e.getFirstMatch=function(f,o){var c=o.match(f);return c&&c.length>0&&c[1]||""},e.getSecondMatch=function(f,o){var c=o.match(f);return c&&c.length>1&&c[2]||""},e.matchAndReturnConst=function(f,o,c){if(f.test(o))return c},e.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}},e.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}},e.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},e.getVersionPrecision=function(f){return f.split(".").length},e.compareVersions=function(f,o,c){c===void 0&&(c=!1);var h=e.getVersionPrecision(f),u=e.getVersionPrecision(o),_=Math.max(h,u),l=0,w=e.map([f,o],function(A){var M=_-e.getVersionPrecision(A),E=A+Array(M+1).join(".0");return e.map(E.split("."),function(d){return Array(20-d.length).join("0")+d}).reverse()});for(c&&(l=_-Math.min(h,u)),_-=1;_>=l;){if(w[0][_]>w[1][_])return 1;if(w[0][_]===w[1][_]){if(_===l)return 0;_-=1}else if(w[0][_]<w[1][_])return-1}},e.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},e.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}},e.assign=function(f){for(var o,c,h=f,u=arguments.length,_=Array(u>1?u-1:0),l=1;l<u;l++)_[l-1]=arguments[l];if(Object.assign)return Object.assign.apply(Object,[f].concat(_));var w=function(){var A=_[o];typeof A=="object"&&A!==null&&Object.keys(A).forEach(function(M){h[M]=A[M]})};for(o=0,c=_.length;o<c;o+=1)w();return f},e.getBrowserAlias=function(f){return r.BROWSER_ALIASES_MAP[f]},e.getBrowserTypeByAlias=function(f){return r.BROWSER_MAP[f]||""},e}();n.default=i,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,i=(r=s(91))&&r.__esModule?r:{default:r},e=s(18);function f(c,h){for(var u=0;u<h.length;u++){var _=h[u];_.enumerable=_.enumerable||!1,_.configurable=!0,"value"in _&&(_.writable=!0),Object.defineProperty(c,_.key,_)}}var o=function(){function c(){}var h,u,_;return c.getParser=function(l,w,A){if(w===void 0&&(w=!1),A===void 0&&(A=null),typeof l!="string")throw Error("UserAgent should be a string");return new i.default(l,w,A)},c.parse=function(l,w){return w===void 0&&(w=null),new i.default(l,w).getResult()},h=c,_=[{key:"BROWSER_MAP",get:function(){return e.BROWSER_MAP}},{key:"ENGINE_MAP",get:function(){return e.ENGINE_MAP}},{key:"OS_MAP",get:function(){return e.OS_MAP}},{key:"PLATFORMS_MAP",get:function(){return e.PLATFORMS_MAP}}],(u=null)&&f(h.prototype,u),_&&f(h,_),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)),i=c(s(93)),e=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(l,w,A){if(w===void 0&&(w=!1),A===void 0&&(A=null),l==null||l==="")throw Error("UserAgent parameter can't be empty");this._ua=l;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 _=u.prototype;return _.getHints=function(){return this._hints},_.hasBrand=function(l){if(!this._hints||!Array.isArray(this._hints.brands))return!1;var w=l.toLowerCase();return this._hints.brands.some(function(A){return A.brand&&A.brand.toLowerCase()===w})},_.getBrandVersion=function(l){if(this._hints&&Array.isArray(this._hints.brands)){var w=l.toLowerCase(),A=this._hints.brands.find(function(M){return M.brand&&M.brand.toLowerCase()===w});return A?A.version:void 0}},_.getUA=function(){return this._ua},_.test=function(l){return l.test(this._ua)},_.parseBrowser=function(){var l=this;this.parsedResult.browser={};var w=o.default.find(r.default,function(A){if(typeof A.test=="function")return A.test(l);if(Array.isArray(A.test))return A.test.some(function(M){return l.test(M)});throw Error("Browser's test function is not valid")});return w&&(this.parsedResult.browser=w.describe(this.getUA(),this)),this.parsedResult.browser},_.getBrowser=function(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()},_.getBrowserName=function(l){return l?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""},_.getBrowserVersion=function(){return this.getBrowser().version},_.getOS=function(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()},_.parseOS=function(){var l=this;this.parsedResult.os={};var w=o.default.find(i.default,function(A){if(typeof A.test=="function")return A.test(l);if(Array.isArray(A.test))return A.test.some(function(M){return l.test(M)});throw Error("Browser's test function is not valid")});return w&&(this.parsedResult.os=w.describe(this.getUA())),this.parsedResult.os},_.getOSName=function(l){var w=this.getOS().name;return l?String(w).toLowerCase()||"":w||""},_.getOSVersion=function(){return this.getOS().version},_.getPlatform=function(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()},_.getPlatformType=function(l){l===void 0&&(l=!1);var w=this.getPlatform().type;return l?String(w).toLowerCase()||"":w||""},_.parsePlatform=function(){var l=this;this.parsedResult.platform={};var w=o.default.find(e.default,function(A){if(typeof A.test=="function")return A.test(l);if(Array.isArray(A.test))return A.test.some(function(M){return l.test(M)});throw Error("Browser's test function is not valid")});return w&&(this.parsedResult.platform=w.describe(this.getUA())),this.parsedResult.platform},_.getEngine=function(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()},_.getEngineName=function(l){return l?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""},_.parseEngine=function(){var l=this;this.parsedResult.engine={};var w=o.default.find(f.default,function(A){if(typeof A.test=="function")return A.test(l);if(Array.isArray(A.test))return A.test.some(function(M){return l.test(M)});throw Error("Browser's test function is not valid")});return w&&(this.parsedResult.engine=w.describe(this.getUA())),this.parsedResult.engine},_.parse=function(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this},_.getResult=function(){return o.default.assign({},this.parsedResult)},_.satisfies=function(l){var w=this,A={},M=0,E={},d=0;if(Object.keys(l).forEach(function(J){var G=l[J];typeof G=="string"?(E[J]=G,d+=1):typeof G=="object"&&(A[J]=G,M+=1)}),M>0){var T=Object.keys(A),U=o.default.find(T,function(J){return w.isOS(J)});if(U){var S=this.satisfies(A[U]);if(S!==void 0)return S}var O=o.default.find(T,function(J){return w.isPlatform(J)});if(O){var D=this.satisfies(A[O]);if(D!==void 0)return D}}if(d>0){var q=Object.keys(E),tt=o.default.find(q,function(J){return w.isBrowser(J,!0)});if(tt!==void 0)return this.compareVersion(E[tt])}},_.isBrowser=function(l,w){w===void 0&&(w=!1);var A=this.getBrowserName().toLowerCase(),M=l.toLowerCase(),E=o.default.getBrowserTypeByAlias(M);return w&&E&&(M=E.toLowerCase()),M===A},_.compareVersion=function(l){var w=[0],A=l,M=!1,E=this.getBrowserVersion();if(typeof E=="string")return l[0]===">"||l[0]==="<"?(A=l.substr(1),l[1]==="="?(M=!0,A=l.substr(2)):w=[],l[0]===">"?w.push(1):w.push(-1)):l[0]==="="?A=l.substr(1):l[0]==="~"&&(M=!0,A=l.substr(1)),w.indexOf(o.default.compareVersions(E,A,M))>-1},_.isOS=function(l){return this.getOSName(!0)===String(l).toLowerCase()},_.isPlatform=function(l){return this.getPlatformType(!0)===String(l).toLowerCase()},_.isEngine=function(l){return this.getEngineName(!0)===String(l).toLowerCase()},_.is=function(l,w){return w===void 0&&(w=!1),this.isBrowser(l,w)||this.isOS(l)||this.isPlatform(l)},_.some=function(l){var w=this;return l===void 0&&(l=[]),l.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,i=(r=s(17))&&r.__esModule?r:{default:r},e=/version\/(\d+(\.?_?\d+)+)/i,f=[{test:[/gptbot/i],describe:function(o){var c={name:"GPTBot"},h=i.default.getFirstMatch(/gptbot\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/chatgpt-user/i],describe:function(o){var c={name:"ChatGPT-User"},h=i.default.getFirstMatch(/chatgpt-user\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/oai-searchbot/i],describe:function(o){var c={name:"OAI-SearchBot"},h=i.default.getFirstMatch(/oai-searchbot\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,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=i.default.getFirstMatch(/(?:claudebot|claude-web|claude-user|claude-searchbot)\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(o){var c={name:"Omgilibot"},h=i.default.getFirstMatch(/(?:omgilibot|webzio-extended)\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/diffbot/i],describe:function(o){var c={name:"Diffbot"},h=i.default.getFirstMatch(/diffbot\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/perplexitybot/i],describe:function(o){var c={name:"PerplexityBot"},h=i.default.getFirstMatch(/perplexitybot\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/perplexity-user/i],describe:function(o){var c={name:"Perplexity-User"},h=i.default.getFirstMatch(/perplexity-user\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/youbot/i],describe:function(o){var c={name:"YouBot"},h=i.default.getFirstMatch(/youbot\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/meta-webindexer/i],describe:function(o){var c={name:"Meta-WebIndexer"},h=i.default.getFirstMatch(/meta-webindexer\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/meta-externalads/i],describe:function(o){var c={name:"Meta-ExternalAds"},h=i.default.getFirstMatch(/meta-externalads\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/meta-externalagent/i],describe:function(o){var c={name:"Meta-ExternalAgent"},h=i.default.getFirstMatch(/meta-externalagent\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/meta-externalfetcher/i],describe:function(o){var c={name:"Meta-ExternalFetcher"},h=i.default.getFirstMatch(/meta-externalfetcher\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/googlebot/i],describe:function(o){var c={name:"Googlebot"},h=i.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/linespider/i],describe:function(o){var c={name:"Linespider"},h=i.default.getFirstMatch(/(?:linespider)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/amazonbot/i],describe:function(o){var c={name:"AmazonBot"},h=i.default.getFirstMatch(/amazonbot\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/bingbot/i],describe:function(o){var c={name:"BingCrawler"},h=i.default.getFirstMatch(/bingbot\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/baiduspider/i],describe:function(o){var c={name:"BaiduSpider"},h=i.default.getFirstMatch(/baiduspider\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/duckduckbot/i],describe:function(o){var c={name:"DuckDuckBot"},h=i.default.getFirstMatch(/duckduckbot\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/ia_archiver/i],describe:function(o){var c={name:"InternetArchiveCrawler"},h=i.default.getFirstMatch(/ia_archiver\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,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=i.default.getFirstMatch(/(?:slackbot|slack-imgproxy)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,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=i.default.getFirstMatch(e,o)||i.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=i.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/SamsungBrowser/i],describe:function(o){var c={name:"Samsung Internet for Android"},h=i.default.getFirstMatch(e,o)||i.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=i.default.getFirstMatch(e,o)||i.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=i.default.getFirstMatch(e,o)||i.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=i.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/focus/i],describe:function(o){var c={name:"Focus"},h=i.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/swing/i],describe:function(o){var c={name:"Swing"},h=i.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/coast/i],describe:function(o){var c={name:"Opera Coast"},h=i.default.getFirstMatch(e,o)||i.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=i.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/yabrowser/i],describe:function(o){var c={name:"Yandex Browser"},h=i.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/ucbrowser/i],describe:function(o){var c={name:"UC Browser"},h=i.default.getFirstMatch(e,o)||i.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=i.default.getFirstMatch(e,o)||i.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=i.default.getFirstMatch(e,o)||i.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=i.default.getFirstMatch(e,o)||i.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=i.default.getFirstMatch(e,o)||i.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=i.default.getFirstMatch(e,o)||i.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=i.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,o)||i.default.getFirstMatch(e,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=i.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/msie|trident/i],describe:function(o){var c={name:"Internet Explorer"},h=i.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=i.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=i.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=i.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/seamonkey/i],describe:function(o){var c={name:"SeaMonkey"},h=i.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/sailfish/i],describe:function(o){var c={name:"Sailfish"},h=i.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=i.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/phantom/i],describe:function(o){var c={name:"PhantomJS"},h=i.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/slimerjs/i],describe:function(o){var c={name:"SlimerJS"},h=i.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=i.default.getFirstMatch(e,o)||i.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=i.default.getFirstMatch(e,o)||i.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=i.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/tizen/i],describe:function(o){var c={name:"Tizen"},h=i.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/qupzilla/i],describe:function(o){var c={name:"QupZilla"},h=i.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/librewolf/i],describe:function(o){var c={name:"LibreWolf"},h=i.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=i.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=i.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=i.default.getFirstMatch(/(?:sogoumobilebrowser)[\s/](\d+(\.?_?\d+)+)/i,o),u=i.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,o),_=i.default.getFirstMatch(/se ([\d.]+)x/i,o),l=h||u||_;return l&&(c.version=l),c}},{test:[/MiuiBrowser/i],describe:function(o){var c={name:"Miui"},h=i.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 _=i.default.getFirstMatch(/\sDdg\/([\d.]+)$/i,o);return _&&(h.version=_),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=i.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/chrome|crios|crmo/i],describe:function(o){var c={name:"Chrome"},h=i.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=i.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=i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/playstation 4/i],describe:function(o){var c={name:"PlayStation 4"},h=i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/safari|applewebkit/i],describe:function(o){var c={name:"Safari"},h=i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/.*/i],describe:function(o){var c=o.search("\\(")!==-1?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:i.default.getFirstMatch(c,o),version:i.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,i=(r=s(17))&&r.__esModule?r:{default:r},e=s(18),f=[{test:[/Roku\/DVP/],describe:function(o){var c=i.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,o);return{name:e.OS_MAP.Roku,version:c}}},{test:[/windows phone/i],describe:function(o){var c=i.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,o);return{name:e.OS_MAP.WindowsPhone,version:c}}},{test:[/windows /i],describe:function(o){var c=i.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,o),h=i.default.getWindowsVersionName(c);return{name:e.OS_MAP.Windows,version:c,versionName:h}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(o){var c={name:e.OS_MAP.iOS},h=i.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,o);return h&&(c.version=h),c}},{test:[/macintosh/i],describe:function(o){var c=i.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,o).replace(/[_\s]/g,"."),h=i.default.getMacOSVersionName(c),u={name:e.OS_MAP.MacOS,version:c};return h&&(u.versionName=h),u}},{test:[/(ipod|iphone|ipad)/i],describe:function(o){var c=i.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,o).replace(/[_\s]/g,".");return{name:e.OS_MAP.iOS,version:c}}},{test:[/OpenHarmony/i],describe:function(o){var c=i.default.getFirstMatch(/OpenHarmony\s+(\d+(\.\d+)*)/i,o);return{name:e.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=i.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,o),h=i.default.getAndroidVersionName(c),u={name:e.OS_MAP.Android,version:c};return h&&(u.versionName=h),u}},{test:[/(web|hpw)[o0]s/i],describe:function(o){var c=i.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,o),h={name:e.OS_MAP.WebOS};return c&&c.length&&(h.version=c),h}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(o){var c=i.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,o)||i.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,o)||i.default.getFirstMatch(/\bbb(\d+)/i,o);return{name:e.OS_MAP.BlackBerry,version:c}}},{test:[/bada/i],describe:function(o){var c=i.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,o);return{name:e.OS_MAP.Bada,version:c}}},{test:[/tizen/i],describe:function(o){var c=i.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,o);return{name:e.OS_MAP.Tizen,version:c}}},{test:[/linux/i],describe:function(){return{name:e.OS_MAP.Linux}}},{test:[/CrOS/],describe:function(){return{name:e.OS_MAP.ChromeOS}}},{test:[/PlayStation 4/],describe:function(o){var c=i.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,o);return{name:e.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,i=(r=s(17))&&r.__esModule?r:{default:r},e=s(18),f=[{test:[/googlebot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Google"}}},{test:[/linespider/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Line"}}},{test:[/amazonbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Amazon"}}},{test:[/gptbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/chatgpt-user/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/oai-searchbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/baiduspider/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Baidu"}}},{test:[/bingbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Bing"}}},{test:[/duckduckbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"DuckDuckGo"}}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Anthropic"}}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Webz.io"}}},{test:[/diffbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Diffbot"}}},{test:[/perplexitybot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Perplexity AI"}}},{test:[/perplexity-user/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Perplexity AI"}}},{test:[/youbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"You.com"}}},{test:[/ia_archiver/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Internet Archive"}}},{test:[/meta-webindexer/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalads/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalagent/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalfetcher/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Slack"}}},{test:[/yahoo/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Yahoo"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Yandex"}}},{test:[/pingdom/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Pingdom"}}},{test:[/huawei/i],describe:function(o){var c=i.default.getFirstMatch(/(can-l01)/i,o)&&"Nova",h={type:e.PLATFORMS_MAP.mobile,vendor:"Huawei"};return c&&(h.model=c),h}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return{type:e.PLATFORMS_MAP.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe:function(){return{type:e.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(){return{type:e.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe:function(){return{type:e.PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe:function(){return{type:e.PLATFORMS_MAP.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe:function(){return{type:e.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=i.default.getFirstMatch(/(ipod|iphone)/i,o);return{type:e.PLATFORMS_MAP.mobile,vendor:"Apple",model:c}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:e.PLATFORMS_MAP.mobile,vendor:"Nexus"}}},{test:[/Nokia/i],describe:function(o){var c=i.default.getFirstMatch(/Nokia\s+([0-9]+(\.[0-9]+)?)/i,o),h={type:e.PLATFORMS_MAP.mobile,vendor:"Nokia"};return c&&(h.model=c),h}},{test:[/[^-]mobi/i],describe:function(){return{type:e.PLATFORMS_MAP.mobile}}},{test:function(o){return o.getBrowserName(!0)==="blackberry"},describe:function(){return{type:e.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(o){return o.getBrowserName(!0)==="bada"},describe:function(){return{type:e.PLATFORMS_MAP.mobile}}},{test:function(o){return o.getBrowserName()==="windows phone"},describe:function(){return{type:e.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:e.PLATFORMS_MAP.tablet}}},{test:function(o){return o.getOSName(!0)==="android"},describe:function(){return{type:e.PLATFORMS_MAP.mobile}}},{test:[/smart-?tv|smarttv/i],describe:function(){return{type:e.PLATFORMS_MAP.tv}}},{test:[/netcast/i],describe:function(){return{type:e.PLATFORMS_MAP.tv}}},{test:function(o){return o.getOSName(!0)==="macos"},describe:function(){return{type:e.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(o){return o.getOSName(!0)==="windows"},describe:function(){return{type:e.PLATFORMS_MAP.desktop}}},{test:function(o){return o.getOSName(!0)==="linux"},describe:function(){return{type:e.PLATFORMS_MAP.desktop}}},{test:function(o){return o.getOSName(!0)==="playstation 4"},describe:function(){return{type:e.PLATFORMS_MAP.tv}}},{test:function(o){return o.getOSName(!0)==="roku"},describe:function(){return{type:e.PLATFORMS_MAP.tv}}}];n.default=f,t.exports=n.default},95:function(t,n,s){n.__esModule=!0,n.default=void 0;var r,i=(r=s(17))&&r.__esModule?r:{default:r},e=s(18),f=[{test:function(o){return o.getBrowserName(!0)==="microsoft edge"},describe:function(o){if(/\sedg\//i.test(o))return{name:e.ENGINE_MAP.Blink};var c=i.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,o);return{name:e.ENGINE_MAP.EdgeHTML,version:c}}},{test:[/trident/i],describe:function(o){var c={name:e.ENGINE_MAP.Trident},h=i.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:e.ENGINE_MAP.Presto},h=i.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:e.ENGINE_MAP.Gecko},h=i.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:e.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(o){var c={name:e.ENGINE_MAP.WebKit},h=i.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}}];n.default=f,t.exports=n.default}})})});var xt=Z((zy)=>{var{Retry:jO,RETRY_MODES:Nw}=vr(),{HttpRequest:Pc,parseUrl:aO}=Ut(),{InvokeStore:Ww}=bw(),{normalizeProvider:pO}=kn(),{platform:ZO,release:vO}=nt("os"),{versions:yc,env:Dw}=nt("process"),{isValidHostLabel:ty,isIpAddress:kw,customEndpointFunctions:ny}=fs(),{EndpointError:sy,resolveEndpoint:ry}=fs();zy.EndpointError=sy;zy.isIpAddress=kw;zy.resolveEndpoint=ry;var{loadConfig:iy,NODE_REGION_CONFIG_OPTIONS:Xw,NODE_REGION_CONFIG_FILE_OPTIONS:zw}=St(),{REGION_ENV_NAME:ey,REGION_INI_NAME:oy,resolveRegionConfig:fy}=St();zy.NODE_REGION_CONFIG_FILE_OPTIONS=zw;zy.NODE_REGION_CONFIG_OPTIONS=Xw;zy.REGION_ENV_NAME=ey;zy.REGION_INI_NAME=oy;zy.resolveRegionConfig=fy;var Le={warningEmitted:!1},cy=(t)=>{if(t&&!Le.warningEmitted){if(process.env.AWS_SDK_JS_NODE_VERSION_SUPPORT_WARNING_DISABLED==="true"){Le.warningEmitted=!0;return}let n=parseInt(t.substring(1,t.indexOf("."))),s=22;if(n<s)Le.warningEmitted=!0,process.emitWarning(`NodeVersionSupportWarning: The AWS SDK for JavaScript (v3)
|
|
22
|
+
`)}_.push(null)}),_}async function o$(n,t){let i=0,s=[],r=n.getReader(),e=!1;while(!e){let{done:h,value:u}=await r.read();if(u)s.push(u),i+=u?.byteLength??0;if(i>=t)break;e=h}r.releaseLock();let f=new Uint8Array(Math.min(t,i)),o=0;for(let h of s){if(h.byteLength>f.byteLength-o){f.set(h.subarray(0,f.byteLength-o),o);break}else f.set(h,o);o+=h.length}return f}var f$=(n,t)=>{if(bt(n))return o$(n,t);return new Promise((i,s)=>{let r=new h$;r.limit=t,n.pipe(r),n.on("error",(e)=>{r.end(),s(e)}),r.on("error",s),r.on("finish",function(){let e=Io(this.buffers);i(e)})})},h$=class extends pl{buffers=[];limit=1/0;bytesBuffered=0;_write(t,i,s){if(this.buffers.push(t),this.bytesBuffered+=t.byteLength??0,this.bytesBuffered>=this.limit){let r=this.bytesBuffered-this.limit,e=this.buffers[this.buffers.length-1];this.buffers[this.buffers.length-1]=e.subarray(0,e.byteLength-r),this.emit("finish")}s()}},u$=(n)=>{if(typeof n==="string")return n;if(typeof n!=="object"||typeof n.byteOffset!=="number"||typeof n.byteLength!=="number")throw Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return new TextDecoder("utf-8").decode(n)},c$=async(n)=>{if(Uo(n))return UA(n);return bA(n)};async function UA(n){return n.arrayBuffer().then((t)=>new Uint8Array(t))}async function bA(n){let t=[],i=n.getReader(),s=0;while(!0){let{done:r,value:e}=await i.read();if(e)t.push(e),s+=e.length;if(r)break}return Io(t,s)}var al="The stream has already been transformed.",_$=(n)=>{if(!vl(n)&&!bt(n)){let r=n?.__proto__?.constructor?.name||n;throw Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${r}`)}let t=!1,i=async()=>{if(t)throw Error(al);return t=!0,await c$(n)},s=(r)=>{if(typeof r.stream!=="function")throw Error(`Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.
|
|
23
|
+
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 r.stream()};return Object.assign(n,{transformToByteArray:i,transformToString:async(r)=>{let e=await i();if(r==="base64")return TA(e);else if(r==="hex")return _A(e);else if(r===void 0||r==="utf8"||r==="utf-8")return u$(e);else if(typeof TextDecoder==="function")return new TextDecoder(r).decode(e);else throw Error("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(t)throw Error(al);if(t=!0,vl(n))return s(n);else if(bt(n))return n;else throw Error(`Cannot transform payload to web stream, got ${n}`)}})},vl=(n)=>typeof Blob==="function"&&n instanceof Blob,$A=(n)=>{if(Uo(n))return UA(n);if(bt(n))return bA(n);return new Promise((t,i)=>{let s=new LA,r=n;r.pipe(s),r.on("error",(e)=>{s.end(),i(e)}),s.on("error",i),s.on("finish",function(){let e=Io(this.bufferedBytes);t(e)})})};class LA extends pl{bufferedBytes=[];_write(n,t,i){this.bufferedBytes.push(n),i()}}var Zl="The stream has already been transformed.",w$=(n)=>{if(!(n instanceof Ns))try{return _$(n)}catch(s){let r=n?.__proto__?.constructor?.name||n;throw Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${r}`)}let t=!1,i=async()=>{if(t)throw Error(Zl);return t=!0,await $A(n)};return Object.assign(n,{transformToByteArray:i,transformToString:async(s)=>{let r=await i();if(s===void 0||Buffer.isEncoding(s))return Hs(r.buffer,r.byteOffset,r.byteLength).toString(s);else return new TextDecoder(s).decode(r)},transformToWebStream:()=>{if(t)throw Error(Zl);if(n.readableFlowing!==null)throw Error("The stream has been consumed by other callbacks.");if(typeof Ns.toWeb!=="function")throw Error("Readable.toWeb() is not supported. Please ensure a polyfill is available.");return t=!0,Ns.toWeb(n)}})};async function l$(n){if(typeof n.stream==="function")n=n.stream();return n.tee()}async function A$(n){if(bt(n)||Uo(n))return l$(n);let t=new kl,i=new kl;return n.pipe(t),n.pipe(i),[t,i]}class OA extends ZU(iA,go,Tu,tA){}var M$=KU,BA=pU(M$),d$=BA;R$.ChecksumStream=EA;R$.Hash=RA;R$.LazyJsonString=Xi;R$.NumericValue=So;R$.Uint8ArrayBlobAdapter=OA;R$._parseEpochTimestamp=zb;R$._parseRfc3339DateTimeWithOffset=Qb;R$._parseRfc7231DateTime=Cb;R$.calculateBodyLength=Vb;R$.concatBytes=Io;R$.copyDocumentWithTransform=nb;R$.createBufferedReadable=s$;R$.createChecksumStream=t$;R$.dateToUtcString=Rb;R$.deserializerMiddleware=lA;R$.deserializerMiddlewareOption=MA;R$.expectBoolean=ib;R$.expectByte=Eu;R$.expectFloat32=Ro;R$.expectInt=rb;R$.expectInt32=du;R$.expectLong=Cr;R$.expectNonNull=ob;R$.expectNumber=Qr;R$.expectObject=sA;R$.expectShort=Ru;R$.expectString=fb;R$.expectUnion=hb;R$.fromArrayBuffer=Hs;R$.fromBase64=tA;R$.fromHex=qb;R$.fromString=To;R$.fromUtf8=go;R$.generateIdempotencyToken=d$;R$.getAwsChunkedEncodingStream=e$;R$.getSerdePlugin=jb;R$.handleFloat=_b;R$.headStream=f$;R$.isArrayBuffer=nA;R$.isBlob=Uo;R$.isReadableStream=bt;R$.limitedParseDouble=Iu;R$.limitedParseFloat=wb;R$.limitedParseFloat32=lb;R$.logger=xr;R$.nv=kb;R$.parseBoolean=tb;R$.parseEpochTimestamp=$b;R$.parseRfc3339DateTime=yb;R$.parseRfc3339DateTimeWithOffset=gb;R$.parseRfc7231DateTime=bb;R$.quoteHeader=Pb;R$.sdkStreamMixin=w$;R$.serializerMiddleware=AA;R$.serializerMiddlewareOption=dA;R$.splitEvery=xb;R$.splitHeader=Kb;R$.splitStream=A$;R$.streamCollector=$A;R$.strictParseByte=fA;R$.strictParseDouble=Su;R$.strictParseFloat=ub;R$.strictParseFloat32=rA;R$.strictParseInt=Ab;R$.strictParseInt32=Mb;R$.strictParseLong=oA;R$.strictParseShort=Ws;R$.toBase64=Tu;R$.toHex=_A;R$.toUint8Array=wA;R$.toUtf8=iA;R$.v4=BA});var Wu=k((rO)=>{var{createReadStream:DL}=p("fs"),{Writable:YL}=p("stream"),{toUint8Array:Ds,concatBytes:mL}=mn(),{createHash:Kr,createHmac:JL}=p("crypto"),NA=p("zlib");async function PA(n,t,i=1048576){let s=n.size,r=0;while(r<s){let e=n.slice(r,Math.min(s,r+i));t(new Uint8Array(await e.arrayBuffer())),r+=e.size}}var XL=async function(t,i){let s=new t;return await PA(i,(r)=>{s.update(r)}),s.digest()};class Nu extends YL{hash;constructor(n,t){super(t);this.hash=n}_write(n,t,i){try{this.hash.update(Ds(n))}catch(s){return i(s)}i()}}var zL=(n,t)=>new Promise((i,s)=>{if(!QL(t)){s(Error("Unable to calculate hash for non-file streams."));return}let r=DL(t.path,{start:t.start,end:t.end}),e=new n,f=new Nu(e);r.pipe(f),r.on("error",(o)=>{f.end(),s(o)}),f.on("error",s),f.on("finish",function(){e.digest().then(i).catch(s)})}),QL=(n)=>typeof n.path==="string",CL=(n,t)=>{if(t.readableFlowing!==null)throw Error("Unable to calculate hash for flowing readable stream");let i=new n,s=new Nu(i);return t.pipe(s),new Promise((r,e)=>{t.on("error",(f)=>{s.end(),e(f)}),s.on("error",e),s.on("finish",()=>{i.digest().then(r).catch(e)})})};class Gu{digestLength=16;state=Uint32Array.from(GA);writeBuffer=new DataView(new ArrayBuffer(64));bufferLength=0;bytesHashed=0;update(n){let t=Ds(n),i=0,s=t.byteLength;this.bytesHashed+=s;while(s>0)if(this.writeBuffer.setUint8(this.bufferLength++,t[i++]),--s,this.bufferLength===64)Ou(this.state,this.writeBuffer),this.bufferLength=0}async digest(){let n=Uint32Array.from(this.state),t=new DataView(this.writeBuffer.buffer.slice(0)),i=this.bufferLength,s=this.bytesHashed*8;if(t.setUint8(i++,128),this.bufferLength%64>=56){for(let f=i;f<64;++f)t.setUint8(f,0);Ou(n,t),i=0}for(let f=i;f<56;++f)t.setUint8(f,0);t.setUint32(56,s>>>0,!0),t.setUint32(60,Math.floor(s/4294967296),!0),Ou(n,t);let r=new Uint8Array(16),e=new DataView(r.buffer);for(let f=0;f<4;++f)e.setUint32(f*4,n[f],!0);return r}reset(){this.state.set(GA),this.writeBuffer=new DataView(new ArrayBuffer(64)),this.bufferLength=0,this.bytesHashed=0}}var GA=[1732584193,4023233417,2562383102,271733878],hi=4294967295,xL=Uint8Array.of(7,12,17,22,5,9,14,20,4,11,16,23,6,10,15,21),KL=Array.from({length:64},(n,t)=>Math.abs(Math.sin(t+1))*4294967296>>>0);function Ou(n,t){let i=n[0],s=n[1],r=n[2],e=n[3];for(let f=0;f<64;++f){let o,h;if(f<16)o=s&r|~s&e,h=f;else if(f<32)o=e&s|r&~e,h=(5*f+1)%16;else if(f<48)o=s^r^e,h=(3*f+5)%16;else o=r^(s|~e),h=7*f%16;let u=t.getUint32(h*4,!0),c=e;e=r,r=s;let _=xL[(f>>4)*4+(f&3)],w=(i+o&hi)+(u+KL[f]&hi)&hi;s=s+((w<<_|w>>>32-_)>>>0)&hi,i=c}n[0]=n[0]+i&hi,n[1]=n[1]+s&hi,n[2]=n[2]+r&hi,n[3]=n[3]+e&hi}var kL=(()=>{try{return Kr("md5"),!0}catch{return!1}})(),DA=kL?qL():Gu;function qL(){return class{digestLength=16;hash=Kr("md5");update(t){this.hash.update(Ds(t))}async digest(){let t=this.hash.copy().digest();return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}reset(){this.hash=Kr("md5")}}}var YA=new Uint32Array(256);for(let n=0;n<256;++n){let t=n;for(let i=0;i<8;++i)t=t&1?3988292384^t>>>1:t>>>1;YA[n]=t>>>0}var Bu=4294967295;class Hu{digestLength=4;checksum=Bu;update(n){for(let t=0;t<n.length;++t)this.checksum=this.checksum>>>8^YA[(this.checksum^n[t])&255]}digestSync(){return(this.checksum^Bu)>>>0}async digest(){let n=this.digestSync(),t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,n,!1),t}reset(){this.checksum=Bu}}var HA=typeof NA.crc32==="function"?NA.crc32:void 0,mA=HA?VL(HA):Hu;function VL(n){return class{digestLength=4;value=0;update(i){this.value=n(i,this.value)}digestSync(){return this.value>>>0}async digest(){let i=new Uint8Array(4);return new DataView(i.buffer).setUint32(0,this.digestSync(),!1),i}reset(){this.value=0}}}var On=64,WA=32,jL=9007199254740991;class Ct{digestLength=WA;state=Int32Array.from(FA);w;buffer=new Uint8Array(64);bufferLength=0;bytesHashed=0;finished=!1;inner;outer;constructor(n){if(n){let t=Ct.normalizeKey(n);this.inner=new Ct,this.outer=new Ct;let{inner:i,outer:s}=this,r=new Uint8Array(On*2);for(let e=0;e<On;++e)r[e]=54^t[e],r[e+On]=92^t[e];i.update(r.subarray(0,On)),s.update(r.subarray(On))}}update(n){if(this.finished)throw Error("Attempted to update an already finished HMAC.");if(this.inner){this.inner.update(n);return}let t=Ds(n),i=0,{byteLength:s}=t;if(this.bytesHashed+=s,this.bytesHashed*8>jL)throw Error("Cannot hash more than 2^53 - 1 bits");while(s>0)if(this.buffer[this.bufferLength++]=t[i++],s--,this.bufferLength===On)this.hashBuffer(),this.bufferLength=0}async digest(){let{inner:n,outer:t}=this;if(n&&t){if(this.finished)throw Error("Attempted to digest an already finished HMAC.");this.finished=!0;let i=n.digestSync();return t.update(i),t.digestSync()}return this.digestSync()}reset(){this.state=Int32Array.from(FA),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0}digestSync(){let n=this.state.slice(),t=this.buffer.slice(),i=this.bufferLength,s=this.bytesHashed*8,r=new DataView(t.buffer,t.byteOffset,t.byteLength);if(r.setUint8(i++,128),(i-1)%On>=On-8){for(let f=i;f<On;++f)r.setUint8(f,0);this.hashBufferWith(n,t),i=0}for(let f=i;f<On-8;++f)r.setUint8(f,0);r.setUint32(On-8,Math.floor(s/4294967296),!1),r.setUint32(On-4,s,!1),this.hashBufferWith(n,t);let e=new Uint8Array(WA);for(let f=0;f<8;++f)e[f*4]=n[f]>>>24&255,e[f*4+1]=n[f]>>>16&255,e[f*4+2]=n[f]>>>8&255,e[f*4+3]=n[f]>>>0&255;return e}static normalizeKey(n){let t=Ds(n);if(t.byteLength>On){let i=new Ct;i.update(t);let s=i.digestSync(),r=new Uint8Array(On);return r.set(s),r}if(t.byteLength<On){let i=new Uint8Array(On);return i.set(t),i}return t}hashBuffer(){this.hashBufferWith(this.state,this.buffer)}hashBufferWith(n,t){let i=this.w??=new Int32Array(64),s=n[0],r=n[1],e=n[2],f=n[3],o=n[4],h=n[5],u=n[6],c=n[7];for(let _=0;_<On;++_){if(_<16)i[_]=(t[_*4]&255)<<24|(t[_*4+1]&255)<<16|(t[_*4+2]&255)<<8|t[_*4+3]&255;else{let A=i[_-2],d=(A>>>17|A<<15)^(A>>>19|A<<13)^A>>>10;A=i[_-15];let E=(A>>>7|A<<25)^(A>>>18|A<<14)^A>>>3;i[_]=(d+i[_-7]|0)+(E+i[_-16]|0)}let w=(((o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7))+(o&h^~o&u)|0)+(c+(aL[_]+i[_]|0)|0)|0,l=((s>>>2|s<<30)^(s>>>13|s<<19)^(s>>>22|s<<10))+(s&r^s&e^r&e)|0;c=u,u=h,h=o,o=f+w|0,f=e,e=r,r=s,s=w+l|0}n[0]+=s,n[1]+=r,n[2]+=e,n[3]+=f,n[4]+=o,n[5]+=h,n[6]+=u,n[7]+=c}}var FA=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),aL=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]),vL=(()=>{try{return Kr("sha256"),!0}catch{return!1}})(),JA=vL?ZL():Ct;function ZL(){return class{digestLength=32;secret;hash;isHmac;finished=!1;constructor(t){this.secret=t,this.isHmac=!!t,this.hash=this.createHash()}update(t){if(this.finished)throw Error("Attempted to update an already finished hash.");this.hash.update(t)}async digest(){let t;if(this.isHmac)this.finished=!0,t=this.hash.digest();else t=this.hash.copy().digest();return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}reset(){this.hash=this.createHash(),this.finished=!1}createHash(){return this.secret?JL("sha256",pL(this.secret)):Kr("sha256")}}}function pL(n){if(typeof n==="string")return n;if(ArrayBuffer.isView(n))return Buffer.from(n.buffer,n.byteOffset,n.byteLength);return Buffer.from(n)}var{digest:nO,sign:tO,importKey:iO}=globalThis?.crypto?.subtle??{},bo=typeof nO==="function"&&typeof tO==="function"&&typeof iO==="function"?globalThis.crypto.subtle:void 0,sO=8388608;class XA{digestLength=32;secret;pending=[];pendingBytes=0;fallback;finished=!1;constructor(n){if(n)this.secret=Ds(n)}update(n){if(this.finished)throw Error("Attempted to update an already finished HMAC.");if(this.fallback){this.fallback.update(n);return}if(this.pending.push(n.slice()),this.pendingBytes+=n.byteLength,this.pendingBytes>=sO)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 n=mL(this.pending);if(bo){if(this.secret){this.finished=!0;let s=await bo.importKey("raw",this.secret,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),r=await bo.sign("HMAC",s,n);return new Uint8Array(r)}let i=await bo.digest("SHA-256",n);return new Uint8Array(i)}let t=new Ct(this.secret);return t.update(n),t.digest()}reset(){this.pending=[],this.pendingBytes=0,this.fallback=void 0,this.finished=!1}switchToFallback(){let n=new Ct(this.secret);for(let t of this.pending)n.update(t);this.fallback=n,this.pending=[],this.pendingBytes=0}}rO.Crc32=mA;rO.Crc32Js=Hu;rO.Crc32Node=mA;rO.Md5=DA;rO.Md5Js=Gu;rO.Md5Node=DA;rO.Sha256=JA;rO.Sha256Js=Ct;rO.Sha256Node=JA;rO.Sha256WebCrypto=XA;rO.blobHasher=XL;rO.blobReader=PA;rO.fileStreamHasher=zL;rO.readableStreamHasher=CL});var $o=k((zO)=>{var{Crc32:CA}=Wu(),{toHex:Ys,fromHex:yO,toUtf8:TO,fromUtf8:gO}=mn(),{Readable:SO}=p("stream");class ms{bytes;constructor(n){if(this.bytes=n,n.byteLength!==8)throw Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(n){if(n>9223372036854776000||n<-9223372036854776000)throw Error(`${n} is too large (or, if negative, too small) to represent as an Int64`);let t=new Uint8Array(8);for(let i=7,s=Math.abs(Math.round(n));i>-1&&s>0;i--,s/=256)t[i]=s;if(n<0)zA(t);return new ms(t)}valueOf(){let n=this.bytes.slice(0),t=n[0]&128;if(t)zA(n);return parseInt(Ys(n),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function zA(n){for(let t=0;t<8;t++)n[t]^=255;for(let t=7;t>-1;t--)if(n[t]++,n[t]!==0)break}class Fu{toUtf8;fromUtf8;constructor(n,t){this.toUtf8=n,this.fromUtf8=t}format(n){let t=[];for(let r of Object.keys(n)){let e=this.fromUtf8(r);t.push(Uint8Array.from([e.byteLength]),e,this.formatHeaderValue(n[r]))}let i=new Uint8Array(t.reduce((r,e)=>r+e.byteLength,0)),s=0;for(let r of t)i.set(r,s),s+=r.byteLength;return i}formatHeaderValue(n){switch(n.type){case"boolean":return Uint8Array.from([n.value?Mn.boolTrue:Mn.boolFalse]);case"byte":return Uint8Array.from([Mn.byte,n.value]);case"short":let t=new DataView(new ArrayBuffer(3));return t.setUint8(0,Mn.short),t.setInt16(1,n.value,!1),new Uint8Array(t.buffer);case"integer":let i=new DataView(new ArrayBuffer(5));return i.setUint8(0,Mn.integer),i.setInt32(1,n.value,!1),new Uint8Array(i.buffer);case"long":let s=new Uint8Array(9);return s[0]=Mn.long,s.set(n.value.bytes,1),s;case"binary":let r=new DataView(new ArrayBuffer(3+n.value.byteLength));r.setUint8(0,Mn.byteArray),r.setUint16(1,n.value.byteLength,!1);let e=new Uint8Array(r.buffer);return e.set(n.value,3),e;case"string":let f=this.fromUtf8(n.value),o=new DataView(new ArrayBuffer(3+f.byteLength));o.setUint8(0,Mn.string),o.setUint16(1,f.byteLength,!1);let h=new Uint8Array(o.buffer);return h.set(f,3),h;case"timestamp":let u=new Uint8Array(9);return u[0]=Mn.timestamp,u.set(ms.fromNumber(n.value.valueOf()).bytes,1),u;case"uuid":if(!GO.test(n.value))throw Error(`Invalid UUID received: ${n.value}`);let c=new Uint8Array(17);return c[0]=Mn.uuid,c.set(yO(n.value.replace(/-/g,"")),1),c}}parse(n){let t={},i=0;while(i<n.byteLength){let s=n.getUint8(i++),r=this.toUtf8(new Uint8Array(n.buffer,n.byteOffset+i,s));switch(i+=s,n.getUint8(i++)){case Mn.boolTrue:t[r]={type:QA,value:!0};break;case Mn.boolFalse:t[r]={type:QA,value:!1};break;case Mn.byte:t[r]={type:IO,value:n.getInt8(i++)};break;case Mn.short:t[r]={type:UO,value:n.getInt16(i,!1)},i+=2;break;case Mn.integer:t[r]={type:bO,value:n.getInt32(i,!1)},i+=4;break;case Mn.long:t[r]={type:$O,value:new ms(new Uint8Array(n.buffer,n.byteOffset+i,8))},i+=8;break;case Mn.byteArray:let e=n.getUint16(i,!1);i+=2,t[r]={type:LO,value:new Uint8Array(n.buffer,n.byteOffset+i,e)},i+=e;break;case Mn.string:let f=n.getUint16(i,!1);i+=2,t[r]={type:OO,value:this.toUtf8(new Uint8Array(n.buffer,n.byteOffset+i,f))},i+=f;break;case Mn.timestamp:t[r]={type:BO,value:new Date(new ms(new Uint8Array(n.buffer,n.byteOffset+i,8)).valueOf())},i+=8;break;case Mn.uuid:let o=new Uint8Array(n.buffer,n.byteOffset+i,16);i+=16,t[r]={type:NO,value:`${Ys(o.subarray(0,4))}-${Ys(o.subarray(4,6))}-${Ys(o.subarray(6,8))}-${Ys(o.subarray(8,10))}-${Ys(o.subarray(10))}`};break;default:throw Error("Unrecognized header type tag")}}return t}}var Mn;(function(n){n[n.boolTrue=0]="boolTrue",n[n.boolFalse=1]="boolFalse",n[n.byte=2]="byte",n[n.short=3]="short",n[n.integer=4]="integer",n[n.long=5]="long",n[n.byteArray=6]="byteArray",n[n.string=7]="string",n[n.timestamp=8]="timestamp",n[n.uuid=9]="uuid"})(Mn||(Mn={}));var QA="boolean",IO="byte",UO="short",bO="integer",$O="long",LO="binary",OO="string",BO="timestamp",NO="uuid",GO=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,xA=4,ui=xA*2,zi=4,HO=ui+zi*2;function WO({byteLength:n,byteOffset:t,buffer:i}){if(n<HO)throw Error("Provided message too short to accommodate event stream message overhead");let s=new DataView(i,t,n),r=s.getUint32(0,!1);if(n!==r)throw Error("Reported message length does not match received message length");let e=s.getUint32(xA,!1),f=s.getUint32(ui,!1),o=s.getUint32(n-zi,!1),h=new CA;if(h.update(new Uint8Array(i,t,ui)),f!==h.digestSync())throw Error(`The prelude checksum specified in the message (${f}) does not match the calculated CRC32 checksum (${h.digestSync()})`);if(h.update(new Uint8Array(i,t+ui,n-(ui+zi))),o!==h.digestSync())throw Error(`The message checksum (${h.digestSync()}) did not match the expected value of ${o}`);return{headers:new DataView(i,t+ui+zi,e),body:new Uint8Array(i,t+ui+zi+e,r-e-(ui+zi+zi))}}class Pu{headerMarshaller;messageBuffer;isEndOfStream;constructor(n,t){this.headerMarshaller=new Fu(n,t),this.messageBuffer=[],this.isEndOfStream=!1}feed(n){this.messageBuffer.push(this.decode(n))}endOfStream(){this.isEndOfStream=!0}getMessage(){let n=this.messageBuffer.pop(),t=this.isEndOfStream;return{getMessage(){return n},isEndOfStream(){return t}}}getAvailableMessages(){let n=this.messageBuffer;this.messageBuffer=[];let t=this.isEndOfStream;return{getMessages(){return n},isEndOfStream(){return t}}}encode({headers:n,body:t}){let i=this.headerMarshaller.format(n),s=i.byteLength+t.byteLength+16,r=new Uint8Array(s),e=new DataView(r.buffer,r.byteOffset,r.byteLength),f=new CA;return e.setUint32(0,s,!1),e.setUint32(4,i.byteLength,!1),f.update(r.subarray(0,8)),e.setUint32(8,f.digestSync(),!1),r.set(i,12),r.set(t,i.byteLength+12),f.update(r.subarray(8,s-4)),e.setUint32(s-4,f.digestSync(),!1),r}decode(n){let{headers:t,body:i}=WO(n);return{headers:this.headerMarshaller.parse(t),body:i}}formatHeaders(n){return this.headerMarshaller.format(n)}}class Du{options;constructor(n){this.options=n}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let n of this.options.inputStream)yield this.options.decoder.decode(n)}}class Yu{options;constructor(n){this.options=n}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let n of this.options.messageStream)yield this.options.encoder.encode(n);if(this.options.includeEndFrame)yield new Uint8Array(0)}}class mu{options;constructor(n){this.options=n}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let n of this.options.messageStream){let t=await this.options.deserializer(n);if(t===void 0)continue;yield t}}}class Ju{options;constructor(n){this.options=n}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let n of this.options.inputStream)yield this.options.serializer(n)}}function KA(n){let t=0,i=0,s=null,r=null,e=(o)=>{if(typeof o!=="number")throw Error("Attempted to allocate an event message where size was not a number: "+o);t=o,i=4,s=new Uint8Array(o),new DataView(s.buffer).setUint32(0,o,!1)},f=async function*(){let o=n[Symbol.asyncIterator]();while(!0){let{value:h,done:u}=await o.next();if(u){if(!t)return;else if(t===i)yield s;else throw Error("Truncated event message received.");return}let c=h.length,_=0;while(_<c){if(!s){let l=c-_;if(!r)r=new Uint8Array(4);let A=Math.min(4-i,l);if(r.set(h.slice(_,_+A),i),i+=A,_+=A,i<4)break;e(new DataView(r.buffer).getUint32(0,!1)),r=null}let w=Math.min(t-i,c-_);if(s.set(h.slice(_,_+w),i),i+=w,_+=w,t&&t===i)yield s,s=null,t=0,i=0}}};return{[Symbol.asyncIterator]:f}}function FO(n,t){let i=Xu(t.deserializer,t.toUtf8);return{[Symbol.asyncIterator]:async function*(){for await(let s of n){let r=t.eventStreamCodec.decode(s),e=await i(r);if(e===void 0)continue;yield e}}}}function Xu(n,t){return async function(i){let{value:s}=i.headers[":message-type"];if(s==="error"){let r=Error(i.headers[":error-message"].value||"UnknownError");throw r.name=i.headers[":error-code"].value,r}else if(s==="exception"){let r=i.headers[":exception-type"].value,e={[r]:i},f=await n(e);if(f.$unknown){let o=Error(t(i.body));throw o.name=r,o}throw f[r]}else if(s==="event"){let r={[i.headers[":event-type"].value]:i},e=await n(r);if(e.$unknown)return;return e}else throw Error(`Unrecognizable event type: ${i.headers[":event-type"].value}`)}}var zu=class{eventStreamCodec;utfEncoder;constructor({utf8Encoder:t,utf8Decoder:i}){this.eventStreamCodec=new Pu(t,i),this.utfEncoder=t}deserialize(t,i){let s=KA(t);return new mu({messageStream:new Du({inputStream:s,decoder:this.eventStreamCodec}),deserializer:Xu(i,this.utfEncoder)})}serialize(t,i){return new Yu({messageStream:new Ju({inputStream:t,serializer:i}),encoder:this.eventStreamCodec,includeEndFrame:!0})}},PO=(n)=>new zu(n);class Qu{universalMarshaller;constructor({utf8Encoder:n,utf8Decoder:t}){this.universalMarshaller=new zu({utf8Decoder:t,utf8Encoder:n})}deserialize(n,t){let i=typeof n[Symbol.asyncIterator]==="function"?n:YO(n);return this.universalMarshaller.deserialize(i,t)}serialize(n,t){return SO.from(this.universalMarshaller.serialize(n,t))}}var DO=(n)=>new Qu(n);async function*YO(n){let t=!1,i=!1,s=[];n.on("error",(r)=>{if(!t)t=!0;if(r)throw r}),n.on("data",(r)=>{s.push(r)}),n.on("end",()=>{t=!0});while(!i){let r=await new Promise((e)=>setTimeout(()=>e(s.shift()),0));if(r)yield r;i=t&&s.length===0}}var mO=(n)=>({[Symbol.asyncIterator]:async function*(){let t=n.getReader();try{while(!0){let{done:i,value:s}=await t.read();if(i)return;yield s}}finally{t.releaseLock()}}}),JO=(n)=>{let t=n[Symbol.asyncIterator]();return new ReadableStream({async pull(i){let{done:s,value:r}=await t.next();if(s)return i.close();i.enqueue(r)}})},XO=(n)=>Object.assign(n,{eventStreamMarshaller:n.eventStreamSerdeProvider(n)});class kA{marshaller;serializer;deserializer;serdeContext;defaultContentType;constructor({marshaller:n,serializer:t,deserializer:i,serdeContext:s,defaultContentType:r}){this.marshaller=n,this.serializer=t,this.deserializer=i,this.serdeContext=s,this.defaultContentType=r}async serializeEventStream({eventStream:n,requestSchema:t,initialRequest:i}){let s=this.marshaller,r=t.getEventStreamMember(),e=t.getMemberSchema(r),f=this.serializer,o=this.defaultContentType,h=Symbol("initialRequestMarker"),u={async*[Symbol.asyncIterator](){if(i){let c={":event-type":{type:"string",value:"initial-request"},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:o}};f.write(t,i);let _=f.flush();yield{[h]:!0,headers:c,body:_}}for await(let c of n)yield c}};return s.serialize(u,(c)=>{if(c[h])return{headers:c.headers,body:c.body};let _="";for(let R in c)if(R!=="__type"){_=R;break}let{additionalHeaders:w,body:l,eventType:A,explicitPayloadContentType:d}=this.writeEventBody(_,e,c);return{headers:{":event-type":{type:"string",value:A},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:d??o},...w},body:l}})}async deserializeEventStream({response:n,responseSchema:t,initialResponseContainer:i}){let s=this.marshaller,r=t.getEventStreamMember(),f=t.getMemberSchema(r).getMemberSchemas(),o=Symbol("initialResponseMarker"),h=s.deserialize(n.body,async(_)=>{let w="";for(let A in _)if(A!=="__type"){w=A;break}let l=_[w].body;if(w==="initial-response"){let A=await this.deserializer.read(t,l);return delete A[r],{[o]:!0,...A}}else if(w in f){let A=f[w];if(A.isStructSchema()){let d={},E=!1;for(let[R,y]of A.structIterator()){let{eventHeader:T,eventPayload:S}=y.getMergedTraits();if(E=E||Boolean(T||S),S){if(y.isBlobSchema())d[R]=l;else if(y.isStringSchema())d[R]=(this.serdeContext?.utf8Encoder??TO)(l);else if(y.isStructSchema())d[R]=await this.deserializer.read(y,l)}else if(T){let I=_[w].headers[R]?.value;if(I!=null)if(y.isNumericSchema())if(I&&typeof I==="object"&&"bytes"in I)d[R]=BigInt(I.toString());else d[R]=Number(I);else d[R]=I}}if(E)return{[w]:d};if(l.byteLength===0)return{[w]:{}}}return{[w]:await this.deserializer.read(A,l)}}else return{$unknown:_}}),u=h[Symbol.asyncIterator](),c=await u.next();if(c.done)return h;if(c.value?.[o]){if(!t)throw Error("@smithy::core/protocols - initial-response event encountered in event stream but no response schema given.");for(let _ in c.value)i[_]=c.value[_]}return{async*[Symbol.asyncIterator](){if(!c?.value?.[o])yield c.value;while(!0){let{done:_,value:w}=await u.next();if(_)break;yield w}}}}writeEventBody(n,t,i){let s=this.serializer,r=n,e=null,f,o=(()=>{return t.getSchema()[4].includes(n)})(),h={};if(!o){let[_,w]=i[n];r=_,s.write(15,w)}else{let _=t.getMemberSchema(n);if(_.isStructSchema()){for(let[w,l]of _.structIterator()){let{eventHeader:A,eventPayload:d}=l.getMergedTraits();if(d)e=w;else if(A){let E=i[n][w],R="binary";if(l.isNumericSchema())if(-2147483648<=E&&E<=2147483647)R="integer";else R="long";else if(l.isTimestampSchema())R="timestamp";else if(l.isStringSchema())R="string";else if(l.isBooleanSchema())R="boolean";if(E!=null)h[w]={type:R,value:E},delete i[n][w]}}if(e!==null){let w=_.getMemberSchema(e);if(w.isBlobSchema())f="application/octet-stream";else if(w.isStringSchema())f="text/plain";s.write(w,i[n][e])}else s.write(_,i[n])}else if(_.isUnitSchema())s.write(_,{});else throw Error("@smithy/core/event-streams - non-struct member not supported in event stream union.")}let u=s.flush()??new Uint8Array;return{body:typeof u==="string"?(this.serdeContext?.utf8Decoder??gO)(u):u,eventType:r,explicitPayloadContentType:f,additionalHeaders:h}}}zO.EventStreamCodec=Pu;zO.EventStreamMarshaller=Qu;zO.EventStreamSerde=kA;zO.HeaderMarshaller=Fu;zO.Int64=ms;zO.MessageDecoderStream=Du;zO.MessageEncoderStream=Yu;zO.SmithyMessageDecoderStream=mu;zO.SmithyMessageEncoderStream=Ju;zO.UniversalEventStreamMarshaller=zu;zO.eventStreamSerdeProvider=DO;zO.getChunkedStream=KA;zO.getMessageUnmarshaller=Xu;zO.getUnmarshalledStream=FO;zO.iterableToReadableStream=JO;zO.readableStreamToIterable=mO;zO.resolveEventStreamSerdeConfig=XO;zO.universalEventStreamSerdeProvider=PO});var Jn=k((LB)=>{var{Uint8ArrayBlobAdapter:Cu,sdkStreamMixin:oB,splitEvery:fB,splitHeader:aA,fromBase64:qA,_parseEpochTimestamp:hB,_parseRfc7231DateTime:uB,_parseRfc3339DateTimeWithOffset:cB,LazyJsonString:vA,NumericValue:_B,toUtf8:ZA,fromUtf8:wB,generateIdempotencyToken:lB,toBase64:VA,dateToUtcString:AB,quoteHeader:MB}=mn(),{TypeRegistry:dB,NormalizedSchema:$t,translateTraits:pA}=ri(),{HttpRequest:Js,HttpResponse:nM,isValidHostname:tM}=St(),{parseQueryString:RB,parseUrl:EB}=St();LB.HttpRequest=Js;LB.HttpResponse=nM;LB.isValidHostname=tM;LB.parseQueryString=RB;LB.parseUrl=EB;var{FieldPosition:yB}=Di(),Qi=async(n=new Uint8Array,t)=>{if(n instanceof Uint8Array)return Cu.mutate(n);if(!n)return Cu.mutate(new Uint8Array);let i=t.streamCollector(n);return Cu.mutate(await i)};function qr(n){return encodeURIComponent(n).replace(/[!'()*]/g,function(t){return"%"+t.charCodeAt(0).toString(16).toUpperCase()})}class Xs{serdeContext;setSerdeContext(n){this.serdeContext=n}}class Lo extends Xs{options;compositeErrorRegistry;constructor(n){super();this.options=n,this.compositeErrorRegistry=dB.for(n.defaultNamespace);for(let t of n.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(t)}getRequestType(){return Js}getResponseType(){return nM}setSerdeContext(n){if(this.serdeContext=n,this.serializer.setSerdeContext(n),this.deserializer.setSerdeContext(n),this.getPayloadCodec())this.getPayloadCodec().setSerdeContext(n)}updateServiceEndpoint(n,t){if("url"in t){if(n.protocol=t.url.protocol,n.hostname=t.url.hostname,n.port=t.url.port?Number(t.url.port):void 0,n.path=t.url.pathname,n.fragment=t.url.hash||void 0,n.username=t.url.username||void 0,n.password=t.url.password||void 0,!n.query)n.query={};for(let[i,s]of t.url.searchParams.entries())n.query[i]=s;if(t.headers)for(let i in t.headers)n.headers[i]=t.headers[i].join(", ");return n}else{if(n.protocol=t.protocol,n.hostname=t.hostname,n.port=t.port?Number(t.port):void 0,n.path=t.path,n.query={...t.query},t.headers)for(let i in t.headers)n.headers[i]=t.headers[i];return n}}setHostPrefix(n,t,i){if(this.serdeContext?.disableHostPrefix)return;let s=$t.of(t.input),r=pA(t.traits??{});if(r.endpoint){let e=r.endpoint?.[0];if(typeof e==="string"){for(let[f,o]of s.structIterator()){if(!o.getMergedTraits().hostLabel)continue;let h=i[f];if(typeof h!=="string")throw Error(`@smithy/core/schema - ${f} in input must be a string as hostLabel.`);e=e.replace(`{${f}}`,h)}if(n.hostname=e+n.hostname,!tM(n.hostname))throw Error(`[${n.hostname}] is not a valid hostname.`)}}}deserializeMetadata(n){return{httpStatusCode:n.statusCode,requestId:n.headers["x-amzn-requestid"]??n.headers["x-amzn-request-id"]??n.headers["x-amz-request-id"],extendedRequestId:n.headers["x-amz-id-2"],cfId:n.headers["x-amz-cf-id"]}}async serializeEventStream({eventStream:n,requestSchema:t,initialRequest:i}){return(await this.loadEventStreamCapability()).serializeEventStream({eventStream:n,requestSchema:t,initialRequest:i})}async deserializeEventStream({response:n,responseSchema:t,initialResponseContainer:i}){return(await this.loadEventStreamCapability()).deserializeEventStream({response:n,responseSchema:t,initialResponseContainer:i})}async loadEventStreamCapability(){let{EventStreamSerde:n,eventStreamSerdeProvider:t}=$o(),i=this.resolveEventStreamMarshaller(t);return new n({marshaller:i,serializer:this.serializer,deserializer:this.deserializer,serdeContext:this.serdeContext,defaultContentType:this.getDefaultContentType()})}resolveEventStreamMarshaller(n){let t=this.serdeContext;if(t.eventStreamMarshaller)return t.eventStreamMarshaller;return n(this.serdeContext)}getDefaultContentType(){throw Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`)}async deserializeHttpMessage(n,t,i,s,r){return[]}getEventStreamMarshaller(){let n=this.serdeContext;if(!n.eventStreamMarshaller)throw Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");return n.eventStreamMarshaller}}class iM extends Lo{async serializeRequest(n,t,i){let s=t&&typeof t==="object"?t:{},r=this.serializer,e={},f={},o=await i.endpoint(),h=$t.of(n?.input),u=[],c=[],_=!1,w,l=new Js({protocol:"",hostname:"",port:void 0,path:"",fragment:void 0,query:e,headers:f,body:void 0});if(o){this.updateServiceEndpoint(l,o),this.setHostPrefix(l,n,s);let A=pA(n.traits);if(A.http){l.method=A.http[0];let[d,E]=A.http[1].split("?");if(l.path=="/")l.path=d;else l.path+=d;let R=new URLSearchParams(E??"");for(let[y,T]of R)e[y]=T}}for(let[A,d]of h.structIterator()){let E=d.getMergedTraits()??{},R=s[A];if(R==null&&!d.isIdempotencyToken()){if(E.httpLabel){if(l.path.includes(`{${A}+}`)||l.path.includes(`{${A}}`))throw Error(`No value provided for input HTTP label: ${A}.`)}continue}if(E.httpPayload)if(d.isStreaming())if(d.isStructSchema()){if(s[A])w=await this.serializeEventStream({eventStream:s[A],requestSchema:h})}else w=R;else r.write(d,R),w=r.flush();else if(E.httpLabel){r.write(d,R);let y=r.flush();if(l.path.includes(`{${A}+}`))l.path=l.path.replace(`{${A}+}`,y.split("/").map(qr).join("/"));else if(l.path.includes(`{${A}}`))l.path=l.path.replace(`{${A}}`,qr(y))}else if(E.httpHeader)r.write(d,R),f[E.httpHeader.toLowerCase()]=String(r.flush());else if(typeof E.httpPrefixHeaders==="string")for(let y in R){let T=R[y],S=E.httpPrefixHeaders+y;r.write([d.getValueSchema(),{httpHeader:S}],T),f[S.toLowerCase()]=r.flush()}else if(E.httpQuery||E.httpQueryParams)this.serializeQuery(d,R,e);else _=!0,u.push(A),c.push(d)}if(_&&s){let[A,d]=(h.getName(!0)??"#Unknown").split("#"),E=h.getSchema()[6],R=[3,A,d,h.getMergedTraits(),u,c,void 0];if(E)R[6]=E;else R.pop();r.write(R,s),w=r.flush()}return l.headers=f,l.query=e,l.body=w,l}serializeQuery(n,t,i){let s=this.serializer,r=n.getMergedTraits();if(r.httpQueryParams){for(let e in t)if(!(e in i)){let f=t[e],o=n.getValueSchema();Object.assign(o.getMergedTraits(),{...r,httpQuery:e,httpQueryParams:void 0}),this.serializeQuery(o,f,i)}return}if(n.isListSchema()){let e=!!n.getMergedTraits().sparse,f=[];for(let o of t){s.write([n.getValueSchema(),r],o);let h=s.flush();if(e||h!==void 0)f.push(h)}i[r.httpQuery]=f}else s.write([n,r],t),i[r.httpQuery]=s.flush()}async deserializeResponse(n,t,i){let s=this.deserializer,r=$t.of(n.output),e={};if(i.statusCode>=300){let o=await Qi(i.body,t);if(o.byteLength>0)Object.assign(e,await s.read(15,o));throw await this.handleError(n,t,i,e,this.deserializeMetadata(i)),Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw.")}for(let o in i.headers){let h=i.headers[o];delete i.headers[o],i.headers[o.toLowerCase()]=h}let f=await this.deserializeHttpMessage(r,t,i,e);if(f.length){let o=await Qi(i.body,t);if(o.byteLength>0){let h=await s.read(r,o);for(let u of f)if(h[u]!=null)e[u]=h[u]}}else if(f.discardResponseBody)await Qi(i.body,t);return e.$metadata=this.deserializeMetadata(i),e}async deserializeHttpMessage(n,t,i,s,r){let e;if(s instanceof Set)e=r;else e=s;let f=!0,o=this.deserializer,h=$t.of(n),u=[];for(let[c,_]of h.structIterator()){let w=_.getMemberTraits();if(w.httpPayload){if(f=!1,_.isStreaming())if(_.isStructSchema())e[c]=await this.deserializeEventStream({response:i,responseSchema:h});else e[c]=oB(i.body);else if(i.body){let A=await Qi(i.body,t);if(A.byteLength>0)e[c]=await o.read(_,A)}}else if(w.httpHeader){let l=String(w.httpHeader).toLowerCase(),A=i.headers[l];if(A!=null)if(_.isListSchema()){let d=_.getValueSchema();d.getMergedTraits().httpHeader=l;let E;if(d.isTimestampSchema()&&d.getSchema()===4)E=fB(A,",",2);else E=aA(A);let R=[];for(let y of E)R.push(await o.read(d,y.trim()));e[c]=R}else e[c]=await o.read(_,A)}else if(w.httpPrefixHeaders!==void 0){e[c]={};for(let l in i.headers)if(l.startsWith(w.httpPrefixHeaders)){let A=i.headers[l],d=_.getValueSchema();d.getMergedTraits().httpHeader=l,e[c][l.slice(w.httpPrefixHeaders.length)]=await o.read(d,A)}}else if(w.httpResponseCode)e[c]=i.statusCode;else u.push(c)}return u.discardResponseBody=f,u}}class sM extends Lo{async serializeRequest(n,t,i){let s=this.serializer,r={},e={},f=await i.endpoint(),o=$t.of(n?.input),h=o.getSchema(),u,c=t&&typeof t==="object"?t:{},_=new Js({protocol:"",hostname:"",port:void 0,path:"/",fragment:void 0,query:r,headers:e,body:void 0});if(f)this.updateServiceEndpoint(_,f),this.setHostPrefix(_,n,c);if(c){let w=o.getEventStreamMember();if(w){if(c[w]){let l={};for(let[A,d]of o.structIterator())if(A!==w&&c[A])s.write(d,c[A]),l[A]=s.flush();u=await this.serializeEventStream({eventStream:c[w],requestSchema:o,initialRequest:l})}}else s.write(h,c),u=s.flush()}return _.headers=Object.assign(_.headers,e),_.query=r,_.body=u,_.method="POST",_}async deserializeResponse(n,t,i){let s=this.deserializer,r=$t.of(n.output),e={};if(i.statusCode>=300){let o=await Qi(i.body,t);if(o.byteLength>0)Object.assign(e,await s.read(15,o));throw await this.handleError(n,t,i,e,this.deserializeMetadata(i)),Error("@smithy/core/protocols - RPC Protocol error handler failed to throw.")}for(let o in i.headers){let h=i.headers[o];delete i.headers[o],i.headers[o.toLowerCase()]=h}let f=r.getEventStreamMember();if(f)e[f]=await this.deserializeEventStream({response:i,responseSchema:r,initialResponseContainer:e});else{let o=await Qi(i.body,t);if(o.byteLength>0)Object.assign(e,await s.read(r,o))}return e.$metadata=this.deserializeMetadata(i),e}}var rM=(n,t,i,s,r,e)=>{if(t!=null&&t[i]!==void 0){let f=s();if(f==null||f.length<=0)throw Error("Empty value provided for input HTTP label: "+i+".");n=n.replace(r,e?f.split("/").map((o)=>qr(o)).join("/"):qr(f))}else throw Error("No value provided for input HTTP label: "+i+".");return n};function TB(n,t){return new xu(n,t)}class xu{input;context;query={};method="";headers={};path="";body=null;hostname="";resolvePathStack=[];constructor(n,t){this.input=n,this.context=t}async build(){let{hostname:n,protocol:t="https",port:i,path:s}=await this.context.endpoint();this.path=s;for(let r of this.resolvePathStack)r(this.path);return new Js({protocol:t,hostname:this.hostname||n,port:i,method:this.method,path:this.path,query:this.query,body:this.body,headers:this.headers})}hn(n){return this.hostname=n,this}bp(n){return this.resolvePathStack.push((t)=>{this.path=`${t?.endsWith("/")?t.slice(0,-1):t||""}`+n}),this}p(n,t,i,s){return this.resolvePathStack.push((r)=>{this.path=rM(r,this.input,n,t,i,s)}),this}h(n){return this.headers=n,this}q(n){return this.query=n,this}b(n){return this.body=n,this}m(n){return this.method=n,this}}function Ku(n,t){if(t.timestampFormat.useTrait){if(n.isTimestampSchema()&&(n.getSchema()===5||n.getSchema()===6||n.getSchema()===7))return n.getSchema()}let{httpLabel:i,httpPrefixHeaders:s,httpHeader:r,httpQuery:e}=n.getMergedTraits();return(t.httpBindings?typeof s==="string"||Boolean(r)?6:Boolean(e)||Boolean(i)?5:void 0:void 0)??t.timestampFormat.default}class ku extends Xs{settings;constructor(n){super();this.settings=n}read(n,t){let i=$t.of(n);if(i.isListSchema())return aA(t).map((s)=>this.read(i.getValueSchema(),s));if(i.isBlobSchema())return(this.serdeContext?.base64Decoder??qA)(t);if(i.isTimestampSchema())switch(Ku(i,this.settings)){case 5:return cB(t);case 6:return uB(t);case 7:return hB(t);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",t),new Date(t)}if(i.isStringSchema()){let s=i.getMergedTraits().mediaType,r=t;if(s){if(i.getMergedTraits().httpHeader)r=this.base64ToUtf8(r);if(s==="application/json"||s.endsWith("+json"))r=vA.from(r);return r}}if(i.isNumericSchema())return Number(t);if(i.isBigIntegerSchema())return BigInt(t);if(i.isBigDecimalSchema())return new _B(t,"bigDecimal");if(i.isBooleanSchema())return String(t).toLowerCase()==="true";return t}base64ToUtf8(n){return(this.serdeContext?.utf8Encoder??ZA)((this.serdeContext?.base64Decoder??qA)(n))}}class eM extends Xs{codecDeserializer;stringDeserializer;constructor(n,t){super();this.codecDeserializer=n,this.stringDeserializer=new ku(t)}setSerdeContext(n){this.stringDeserializer.setSerdeContext(n),this.codecDeserializer.setSerdeContext(n),this.serdeContext=n}read(n,t){let i=$t.of(n),s=i.getMergedTraits(),r=this.serdeContext?.utf8Encoder??ZA;if(s.httpHeader||s.httpResponseCode)return this.stringDeserializer.read(i,r(t));if(s.httpPayload){if(i.isBlobSchema()){let e=this.serdeContext?.utf8Decoder??wB;if(typeof t==="string")return e(t);return t}else if(i.isStringSchema()){if("byteLength"in t)return r(t);return t}}return this.codecDeserializer.read(i,t)}}class qu extends Xs{settings;stringBuffer="";constructor(n){super();this.settings=n}write(n,t){let i=$t.of(n);switch(typeof t){case"object":if(t===null){this.stringBuffer="null";return}if(i.isTimestampSchema()){if(!(t instanceof Date))throw Error(`@smithy/core/protocols - received non-Date value ${t} when schema expected Date in ${i.getName(!0)}`);switch(Ku(i,this.settings)){case 5:this.stringBuffer=t.toISOString().replace(".000Z","Z");break;case 6:this.stringBuffer=AB(t);break;case 7:this.stringBuffer=String(t.getTime()/1000);break;default:console.warn("Missing timestamp format, using epoch seconds",t),this.stringBuffer=String(t.getTime()/1000)}return}if(i.isBlobSchema()&&"byteLength"in t){this.stringBuffer=(this.serdeContext?.base64Encoder??VA)(t);return}if(i.isListSchema()&&Array.isArray(t)){let e="";for(let f of t){this.write([i.getValueSchema(),i.getMergedTraits()],f);let o=this.flush(),h=i.getValueSchema().isTimestampSchema()?o:MB(o);if(e!=="")e+=", ";e+=h}this.stringBuffer=e;return}this.stringBuffer=JSON.stringify(t,null,2);break;case"string":let s=i.getMergedTraits().mediaType,r=t;if(s){if(s==="application/json"||s.endsWith("+json"))r=vA.from(r);if(i.getMergedTraits().httpHeader){this.stringBuffer=(this.serdeContext?.base64Encoder??VA)(r.toString());return}}this.stringBuffer=t;break;default:if(i.isIdempotencyToken())this.stringBuffer=lB();else this.stringBuffer=String(t)}}flush(){let n=this.stringBuffer;return this.stringBuffer="",n}}class oM{codecSerializer;stringSerializer;buffer;constructor(n,t,i=new qu(t)){this.codecSerializer=n,this.stringSerializer=i}setSerdeContext(n){this.codecSerializer.setSerdeContext(n),this.stringSerializer.setSerdeContext(n)}write(n,t){let i=$t.of(n),s=i.getMergedTraits();if(s.httpHeader||s.httpLabel||s.httpQuery){this.stringSerializer.write(i,t),this.buffer=this.stringSerializer.flush();return}return this.codecSerializer.write(i,t)}flush(){if(this.buffer!==void 0){let n=this.buffer;return this.buffer=void 0,n}return this.codecSerializer.flush()}}class fM{name;kind;values;constructor({name:n,kind:t=yB.HEADER,values:i=[]}){this.name=n,this.kind=t,this.values=i}add(n){this.values.push(n)}set(n){this.values=n}remove(n){this.values=this.values.filter((t)=>t!==n)}toString(){return this.values.map((n)=>n.includes(",")||n.includes(" ")?`"${n}"`:n).join(", ")}get(){return this.values}}class hM{entries={};encoding;constructor({fields:n=[],encoding:t="utf-8"}){n.forEach(this.setField.bind(this)),this.encoding=t}setField(n){this.entries[n.name.toLowerCase()]=n}getField(n){return this.entries[n.toLowerCase()]}removeField(n){delete this.entries[n.toLowerCase()]}getByType(n){return Object.values(this.entries).filter((t)=>t.kind===n)}}var gB=(n)=>{return{setHttpHandler(t){n.httpHandler=t},httpHandler(){return n.httpHandler},updateHttpClientConfig(t,i){n.httpHandler?.updateHttpClientConfig(t,i)},httpHandlerConfigs(){return n.httpHandler.httpHandlerConfigs()}}},SB=(n)=>{return{httpHandler:n.httpHandler()}},jA="content-length";function uM(n){return(t)=>async(i)=>{let s=i.request;if(Js.isInstance(s)){let{body:r,headers:e}=s;if(r&&Object.keys(e).map((f)=>f.toLowerCase()).indexOf(jA)===-1)try{let f=n(r);s.headers={...s.headers,[jA]:String(f)}}catch(f){}}return t({...i,request:s})}}var cM={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},IB=(n)=>({applyToStack:(t)=>{t.add(uM(n.bodyLengthChecker),cM)}}),kr=(n)=>encodeURIComponent(n).replace(/[!'()*]/g,UB),UB=(n)=>`%${n.charCodeAt(0).toString(16).toUpperCase()}`,bB=(n)=>n.split("/").map(kr).join("/");function $B(n){let t=[];for(let i of Object.keys(n).sort()){let s=n[i];if(i=kr(i),Array.isArray(s))for(let r=0,e=s.length;r<e;r++)t.push(`${i}=${kr(s[r])}`);else{let r=i;if(s||typeof s==="string")r+=`=${kr(s)}`;t.push(r)}}return t.join("&")}LB.Field=fM;LB.Fields=hM;LB.FromStringShapeDeserializer=ku;LB.HttpBindingProtocol=iM;LB.HttpInterceptingShapeDeserializer=eM;LB.HttpInterceptingShapeSerializer=oM;LB.HttpProtocol=Lo;LB.RequestBuilder=xu;LB.RpcProtocol=sM;LB.SerdeContext=Xs;LB.ToStringShapeSerializer=qu;LB.buildQueryString=$B;LB.collectBody=Qi;LB.contentLengthMiddleware=uM;LB.contentLengthMiddlewareOptions=cM;LB.determineTimestampFormat=Ku;LB.escapeUri=kr;LB.escapeUriPath=bB;LB.extendedEncodeURIComponent=qr;LB.getContentLengthPlugin=IB;LB.getHttpHandlerExtensionConfiguration=gB;LB.requestBuilder=TB;LB.resolveHttpHandlerRuntimeConfig=SB;LB.resolvedPath=rM});var Zr=k(($N)=>{var{Readable:sN}=p("stream"),{NoOpLogger:rN,normalizeProvider:_M}=Xt(),{HttpResponse:wM,HttpRequest:Bo}=Jn(),{parseRfc7231DateTime:eN,v4:lM}=mn(),AM=(n)=>n?.body instanceof sN||typeof ReadableStream<"u"&&n?.body instanceof ReadableStream,oN=["AuthFailure","InvalidSignatureException","RequestExpired","RequestInTheFuture","RequestTimeTooSkewed","SignatureDoesNotMatch"],fN=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],hN=["TimeoutError","RequestTimeout","RequestTimeoutException"],uN=[500,502,503,504],cN=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],_N=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN"],vu=(n)=>n?.$retryable!==void 0,MM=(n)=>oN.includes(n.name),dM=(n)=>n.$metadata?.clockSkewCorrected,RM=(n)=>{let t=new Set(["Failed to fetch","NetworkError when attempting to fetch resource","The Internet connection appears to be offline","Load failed","Network request failed"]);if(!(n&&n instanceof TypeError))return!1;return t.has(n.message)},jr=(n)=>n.$metadata?.httpStatusCode===429||fN.includes(n.name)||n.$retryable?.throttling==!0,ar=(n,t=0)=>vu(n)||dM(n)||n.name==="InvalidSignatureException"&&n.message?.includes("Signature expired")||hN.includes(n.name)||cN.includes(n?.code||"")||_N.includes(n?.code||"")||uN.includes(n.$metadata?.httpStatusCode||0)||RM(n)||yM(n)||n.cause!==void 0&&t<=10&&ar(n.cause,t+1),EM=(n)=>{if(n.$metadata?.httpStatusCode!==void 0){let t=n.$metadata.httpStatusCode;if(500<=t&&t<=599&&!ar(n))return!0;return!1}return!1};function yM(n){return n.code==="ERR_HTTP2_STREAM_ERROR"&&n.message.includes("NGHTTP2_REFUSED_STREAM")}var TM=100,Go=20000,gM=500,No=500,SM=5,IM=10,Zu=1,Ho="amz-sdk-invocation-id",Wo="amz-sdk-request";function UM(n,t){if(!wM.isInstance(n))return;for(let i of Object.keys(n.headers)){let s=i.toLowerCase();if(s==="retry-after"){let r=n.headers[i],e=NaN;if(r.endsWith("GMT"))try{e=(eN(r).getTime()-Date.now())/1000}catch(f){t?.trace?.("Failed to parse retry-after header"),t?.trace?.(f)}else if(r.match(/ GMT, ((\d+)|(\d+\.\d+))$/))e=Number(r.match(/ GMT, ([\d.]+)$/)?.[1]);else if(r.match(/^((\d+)|(\d+\.\d+))$/))e=Number(r);else if(Date.parse(r)>=Date.now())e=(Date.parse(r)-Date.now())/1000;if(isNaN(e))return;return new Date(Date.now()+e*1000)}else if(s==="x-amz-retry-after"){let r=n.headers[i],e=Number(r);if(isNaN(e)){t?.trace?.(`Failed to parse x-amz-retry-after=${r}`);return}return new Date(Date.now()+e)}}}function wN(n,t){return UM(n,t)}var bM=(n)=>{if(n instanceof Error)return n;if(n instanceof Object)return Object.assign(Error(),n);if(typeof n==="string")return Error(n);return Error(`AWS SDK error wrapper for ${n}`)};function $M(n){return(t)=>(i,s)=>async(r)=>{let e=await t.retryStrategy(),f=await t.maxAttempts();if(AN(e)){e=e;let o=await e.acquireInitialRetryToken((s.partition_id??"")+(s.__retryLongPoll?":longpoll":"")),h=Error(),u=0,c=0,{request:_}=r,w=Bo.isInstance(_);if(w)_.headers[Ho]=lM();while(!0)try{if(w)_.headers[Wo]=`attempt=${u+1}; max=${f}`;let{response:l,output:A}=await i(r);return e.recordSuccess(o),A.$metadata.attempts=u+1,A.$metadata.totalRetryDelay=c,{response:l,output:A}}catch(l){let A=MN(l,t.logger);if(h=bM(l),w&&n(_))throw(s.logger instanceof rN?console:s.logger)?.warn("An error was encountered in a non-retryable streaming request."),h;try{o=await e.refreshRetryTokenForRetry(o,A)}catch(E){if(!h.$metadata)h.$metadata={};throw h.$metadata.attempts=u+1,h.$metadata.totalRetryDelay=c,h}u=o.getRetryCount();let d=o.getRetryDelay();if(c+=(o?.$retryLog?.acquisitionDelay??0)+d,d>0)await lN(d)}}else{if(e=e,e?.mode)s.userAgent=[...s.userAgent||[],["cfg/retry-mode",e.mode]];return e.retry(i,r)}}}var lN=(n)=>new Promise((t)=>setTimeout(t,n)),AN=(n)=>typeof n.acquireInitialRetryToken<"u"&&typeof n.refreshRetryTokenForRetry<"u"&&typeof n.recordSuccess<"u",MN=(n,t)=>{let i={error:n,errorType:dN(n)},s=UM(n.$response,t);if(s)i.retryAfterHint=s;return i},dN=(n)=>{if(jr(n))return"THROTTLING";if(ar(n))return"TRANSIENT";if(EM(n))return"SERVER_ERROR";return"CLIENT_ERROR"},LM={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0};function RN(n){let t=$M(n);return(i)=>({applyToStack:(s)=>{s.add(t(i),LM)}})}class vr{static setTimeoutFn=(n,t)=>setTimeout(n,t);beta;minCapacity;minFillRate;scaleConstant;smooth;enabled=!1;availableTokens=0;lastMaxRate=0;measuredTxRate=0;requestCount=0;fillRate;lastThrottleTime;lastTimestamp=0;lastTxRateBucket;maxCapacity;timeWindow=0;constructor(n){this.beta=n?.beta??0.7,this.minCapacity=n?.minCapacity??1,this.minFillRate=n?.minFillRate??0.5,this.scaleConstant=n?.scaleConstant??0.4,this.smooth=n?.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(n){let t;this.updateMeasuredRate();let i=n;if(i?.errorType==="THROTTLING"||jr(i?.error??n)){let e=!this.enabled?this.measuredTxRate:Math.min(this.measuredTxRate,this.fillRate);this.lastMaxRate=e,this.calculateTimeWindow(),this.lastThrottleTime=this.getCurrentTimeInSeconds(),t=this.cubicThrottle(e),this.enableTokenBucket()}else this.calculateTimeWindow(),t=this.cubicSuccess(this.getCurrentTimeInSeconds());let r=Math.min(t,2*this.measuredTxRate);this.updateTokenBucketRate(r)}getCurrentTimeInSeconds(){return Date.now()/1000}async acquireTokenBucket(n){if(!this.enabled)return;this.refillTokenBucket();while(n>this.availableTokens){let t=(n-this.availableTokens)/this.fillRate*1000;await new Promise((i)=>vr.setTimeoutFn(i,t)),this.refillTokenBucket()}this.availableTokens=this.availableTokens-n}refillTokenBucket(){let n=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=n;return}let t=(n-this.lastTimestamp)*this.fillRate;this.availableTokens=Math.min(this.maxCapacity,this.availableTokens+t),this.lastTimestamp=n}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,0.3333333333333333))}cubicThrottle(n){return this.getPrecise(n*this.beta)}cubicSuccess(n){return this.getPrecise(this.scaleConstant*Math.pow(n-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(n){this.refillTokenBucket(),this.fillRate=Math.max(n,this.minFillRate),this.maxCapacity=Math.max(n,this.minCapacity),this.availableTokens=Math.min(this.availableTokens,this.maxCapacity)}updateMeasuredRate(){let n=this.getCurrentTimeInSeconds(),t=Math.floor(n*2)/2;if(this.requestCount++,t>this.lastTxRateBucket){let i=this.requestCount/(t-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(i*this.smooth+this.measuredTxRate*(1-this.smooth)),this.requestCount=0,this.lastTxRateBucket=t}}getPrecise(n){return parseFloat(n.toFixed(8))}}class Un{static v2026=typeof process<"u"&&process.env?.SMITHY_NEW_RETRIES_2026==="true";static delay(){return Un.v2026?50:100}static throttlingDelay(){return Un.v2026?1000:500}static cost(){return Un.v2026?14:5}static throttlingCost(){return Un.v2026?5:10}static modifiedCostType(){return Un.v2026?"THROTTLING":"TRANSIENT"}}class OM{x=Un.delay();computeNextBackoffDelay(n){let t=Math.random(),i=2,s=t*Math.min(this.x*2**n,Go);return Math.floor(s)}setDelayBase(n){this.x=n}}class Vu{delay;count;cost;longPoll;$retryLog={acquisitionDelay:0};constructor(n,t,i,s){this.delay=n,this.count=t,this.cost=i,this.longPoll=s}getRetryCount(){return this.count}getRetryDelay(){return Math.min(Go,this.delay)}getRetryCost(){return this.cost}isLongPoll(){return this.longPoll}}var xt;(function(n){n.STANDARD="standard",n.ADAPTIVE="adaptive"})(xt||(xt={}));var Ci=3,BM=xt.STANDARD,Oo={incompatible:1,attempts:2,capacity:3},Vr=class{mode=xt.STANDARD;retryBackoffStrategy;capacity=No;maxAttemptsProvider;baseDelay;constructor(t){if(typeof t==="number")this.maxAttemptsProvider=async()=>t;else if(typeof t==="function")this.maxAttemptsProvider=t;else if(t&&typeof t==="object")this.maxAttemptsProvider=async()=>t.maxAttempts,this.baseDelay=t.baseDelay,this.retryBackoffStrategy=t.backoff;this.maxAttemptsProvider??=async()=>Ci,this.baseDelay??=Un.delay(),this.retryBackoffStrategy??=new OM}async acquireInitialRetryToken(t){return new Vu(Un.delay(),0,void 0,Un.v2026&&t.includes(":longpoll"))}async refreshRetryTokenForRetry(t,i){let s=await this.getMaxAttempts(),r=this.retryCode(t,i,s),e=r===0,f=t.isLongPoll?.();if(e||f){let o=i.errorType;this.retryBackoffStrategy.setDelayBase(o==="THROTTLING"?Un.throttlingDelay():this.baseDelay);let h=this.retryBackoffStrategy.computeNextBackoffDelay(t.getRetryCount()),u=h;if(i.retryAfterHint instanceof Date)u=Math.max(h,Math.min(i.retryAfterHint.getTime()-Date.now(),h+5000));if(!e){let c=Un.v2026&&r===Oo.capacity&&f?u:0;if(c>0)await new Promise((_)=>setTimeout(_,c))}else{let c=this.getCapacityCost(o);this.capacity-=c;let _=new Vu(0,t.getRetryCount()+1,c,t.isLongPoll?.()??!1);return await new Promise((w)=>setTimeout(w,u)),_.$retryLog.acquisitionDelay=u,_}}throw Error("No retry token available")}recordSuccess(t){this.capacity=Math.min(No,this.capacity+(t.getRetryCost()??Zu))}getCapacity(){return this.capacity}async maxAttempts(){return this.maxAttemptsProvider()}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch(t){return console.warn(`Max attempts provider could not resolve. Using default of ${Ci}`),Ci}}retryCode(t,i,s){let r=t.getRetryCount()+1,e=this.isRetryableError(i.errorType)?0:Oo.incompatible,f=r<s?0:Oo.attempts,o=this.capacity>=this.getCapacityCost(i.errorType)?0:Oo.capacity;return e||f||o}getCapacityCost(t){return t===Un.modifiedCostType()?Un.throttlingCost():Un.cost()}isRetryableError(t){return t==="THROTTLING"||t==="TRANSIENT"}},NM=class{mode=xt.ADAPTIVE;rateLimiter;standardRetryStrategy;constructor(t,i){let{rateLimiter:s}=i??{};this.rateLimiter=s??new vr,this.standardRetryStrategy=i?new Vr({maxAttempts:typeof t==="number"?t:3,...i}):new Vr(t)}async acquireInitialRetryToken(t){let i=await this.standardRetryStrategy.acquireInitialRetryToken(t);return await this.rateLimiter.getSendToken(),i}async refreshRetryTokenForRetry(t,i){this.rateLimiter.updateClientSendingRate(i);let s=await this.standardRetryStrategy.refreshRetryTokenForRetry(t,i);return await this.rateLimiter.getSendToken(),s}recordSuccess(t){this.rateLimiter.updateClientSendingRate({}),this.standardRetryStrategy.recordSuccess(t)}async maxAttemptsProvider(){return this.standardRetryStrategy.maxAttempts()}};class GM extends Vr{computeNextBackoffDelay;constructor(n,t=Un.delay()){super(typeof n==="function"?n:async()=>n);if(typeof t==="number")this.computeNextBackoffDelay=()=>t;else this.computeNextBackoffDelay=t;this.retryBackoffStrategy.computeNextBackoffDelay=(i)=>{let s=i+1;return this.computeNextBackoffDelay(s)}}}var EN=(n,t)=>{let i=n,s=Zu,r=SM,e=IM,f=n,o=(_)=>_.name==="TimeoutError"?e:r,h=(_)=>o(_)<=f;return Object.freeze({hasRetryTokens:h,retrieveRetryTokens:(_)=>{if(!h(_))throw Error("No retry token available");let w=o(_);return f-=w,w},releaseRetryTokens:(_)=>{f+=_??s,f=Math.min(f,i)}})},HM=(n,t)=>Math.floor(Math.min(Go,Math.random()*2**t*n)),WM=(n)=>{if(!n)return!1;return vu(n)||MM(n)||jr(n)||ar(n)};class pu{maxAttemptsProvider;retryDecider;delayDecider;retryQuota;mode=xt.STANDARD;constructor(n,t){this.maxAttemptsProvider=n,this.retryDecider=t?.retryDecider??WM,this.delayDecider=t?.delayDecider??HM,this.retryQuota=t?.retryQuota??EN(No)}shouldRetry(n,t,i){return t<i&&this.retryDecider(n)&&this.retryQuota.hasRetryTokens(n)}async getMaxAttempts(){let n;try{n=await this.maxAttemptsProvider()}catch(t){n=Ci}return n}async retry(n,t,i){let s,r=0,e=0,f=await this.getMaxAttempts(),{request:o}=t;if(Bo.isInstance(o))o.headers[Ho]=lM();while(!0)try{if(Bo.isInstance(o))o.headers[Wo]=`attempt=${r+1}; max=${f}`;if(i?.beforeRequest)await i.beforeRequest();let{response:h,output:u}=await n(t);if(i?.afterRequest)i.afterRequest(h);return this.retryQuota.releaseRetryTokens(s),u.$metadata.attempts=r+1,u.$metadata.totalRetryDelay=e,{response:h,output:u}}catch(h){let u=bM(h);if(r++,this.shouldRetry(u,r,f)){s=this.retryQuota.retrieveRetryTokens(u);let c=this.delayDecider(jr(u)?gM:TM,r),_=yN(u.$response),w=Math.max(_||0,c);e+=w,await new Promise((l)=>setTimeout(l,w));continue}if(!u.$metadata)u.$metadata={};throw u.$metadata.attempts=r,u.$metadata.totalRetryDelay=e,u}}}var yN=(n)=>{if(!wM.isInstance(n))return;let t=Object.keys(n.headers).find((e)=>e.toLowerCase()==="retry-after");if(!t)return;let i=n.headers[t],s=Number(i);if(!Number.isNaN(s))return Math.min(s*1000,20000);let r=new Date(i);return Math.min(r.getTime()-Date.now(),20000)};class FM extends pu{rateLimiter;constructor(n,t){let{rateLimiter:i,...s}=t??{};super(n,s);this.rateLimiter=i??new vr,this.mode=xt.ADAPTIVE}async retry(n,t){return super.retry(n,t,{beforeRequest:async()=>{return this.rateLimiter.getSendToken()},afterRequest:(i)=>{this.rateLimiter.updateClientSendingRate(i)}})}}var ju="AWS_MAX_ATTEMPTS",au="max_attempts",TN={environmentVariableSelector:(n)=>{let t=n[ju];if(!t)return;let i=parseInt(t);if(Number.isNaN(i))throw Error(`Environment variable ${ju} mast be a number, got "${t}"`);return i},configFileSelector:(n)=>{let t=n[au];if(!t)return;let i=parseInt(t);if(Number.isNaN(i))throw Error(`Shared config file entry ${au} mast be a number, got "${t}"`);return i},default:Ci},gN=(n,t)=>{let{retryStrategy:i,retryMode:s}=n,{defaultMaxAttempts:r=Ci,defaultBaseDelay:e=Un.delay()}=t??{},f=_M(n.maxAttempts??r),o=i?Promise.resolve(i):void 0,h=async()=>{let u=await f();if(await _M(s)()===xt.ADAPTIVE)return new NM(f,{maxAttempts:u,baseDelay:e});return new Vr({maxAttempts:u,baseDelay:e})};return Object.assign(n,{maxAttempts:f,retryStrategy:()=>o??=h()})},PM="AWS_RETRY_MODE",DM="retry_mode",SN={environmentVariableSelector:(n)=>n[PM],configFileSelector:(n)=>n[DM],default:BM},YM=()=>(n)=>async(t)=>{let{request:i}=t;if(Bo.isInstance(i))delete i.headers[Ho],delete i.headers[Wo];return n(t)},mM={name:"omitRetryHeadersMiddleware",tags:["RETRY","HEADERS","OMIT_RETRY_HEADERS"],relation:"before",toMiddleware:"awsAuthMiddleware",override:!0},IN=(n)=>({applyToStack:(t)=>{t.addRelativeTo(YM(),mM)}}),UN=$M(AM),bN=RN(AM);$N.AdaptiveRetryStrategy=NM;$N.CONFIG_MAX_ATTEMPTS=au;$N.CONFIG_RETRY_MODE=DM;$N.ConfiguredRetryStrategy=GM;$N.DEFAULT_MAX_ATTEMPTS=Ci;$N.DEFAULT_RETRY_DELAY_BASE=TM;$N.DEFAULT_RETRY_MODE=BM;$N.DefaultRateLimiter=vr;$N.DeprecatedAdaptiveRetryStrategy=FM;$N.DeprecatedStandardRetryStrategy=pu;$N.ENV_MAX_ATTEMPTS=ju;$N.ENV_RETRY_MODE=PM;$N.INITIAL_RETRY_TOKENS=No;$N.INVOCATION_ID_HEADER=Ho;$N.MAXIMUM_RETRY_DELAY=Go;$N.NODE_MAX_ATTEMPT_CONFIG_OPTIONS=TN;$N.NODE_RETRY_MODE_CONFIG_OPTIONS=SN;$N.NO_RETRY_INCREMENT=Zu;$N.REQUEST_HEADER=Wo;$N.RETRY_COST=SM;$N.RETRY_MODES=xt;$N.Retry=Un;$N.StandardRetryStrategy=Vr;$N.THROTTLING_RETRY_DELAY_BASE=gM;$N.TIMEOUT_RETRY_COST=IM;$N.defaultDelayDecider=HM;$N.defaultRetryDecider=WM;$N.getOmitRetryHeadersPlugin=IN;$N.getRetryAfterHint=wN;$N.getRetryPlugin=bN;$N.isBrowserNetworkError=RM;$N.isClockSkewCorrectedError=dM;$N.isClockSkewError=MM;$N.isNodeJsHttp2TransientError=yM;$N.isRetryableByTrait=vu;$N.isServerError=EM;$N.isThrottlingError=jr;$N.isTransientError=ar;$N.omitRetryHeadersMiddleware=YM;$N.omitRetryHeadersMiddlewareOptions=mM;$N.resolveRetryConfig=gN;$N.retryMiddleware=UN;$N.retryMiddlewareOptions=LM});var XM=k((dG)=>{var ci={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")},nc=["true","1"].includes(process.env?.AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA??"");if(!nc)globalThis.awslambda=globalThis.awslambda||{};class Fo{static PROTECTED_KEYS=ci;isProtectedKey(n){return Object.values(ci).includes(n)}getRequestId(){return this.get(ci.REQUEST_ID)??"-"}getXRayTraceId(){return this.get(ci.X_RAY_TRACE_ID)}getTenantId(){return this.get(ci.TENANT_ID)}getTraceparent(){return this.get(ci.TRACEPARENT)}getTracestate(){return this.get(ci.TRACESTATE)}getBaggage(){return this.get(ci.BAGGAGE)}}class JM extends Fo{currentContext;getContext(){return this.currentContext}hasContext(){return this.currentContext!==void 0}get(n){return this.currentContext?.[n]}set(n,t){if(this.isProtectedKey(n))throw Error(`Cannot modify protected Lambda context field: ${String(n)}`);this.currentContext=this.currentContext||{},this.currentContext[n]=t}run(n,t){return this.currentContext=n,t()}}class ic extends Fo{als;static async create(){let n=new ic,t=await import("async_hooks");return n.als=new t.AsyncLocalStorage,n}getContext(){return this.als.getStore()}hasContext(){return this.als.getStore()!==void 0}get(n){return this.als.getStore()?.[n]}set(n,t){if(this.isProtectedKey(n))throw Error(`Cannot modify protected Lambda context field: ${String(n)}`);let i=this.als.getStore();if(!i)throw Error("No context available");i[n]=t}run(n,t){return this.als.run(n,t)}}dG.InvokeStore=void 0;(function(n){let t=null;async function i(s){if(!t)t=(async()=>{let e=s===!0||"AWS_LAMBDA_MAX_CONCURRENCY"in process.env?await ic.create():new JM;if(!nc&&globalThis.awslambda?.InvokeStore)return globalThis.awslambda.InvokeStore;else if(!nc&&globalThis.awslambda)return globalThis.awslambda.InvokeStore=e,e;else return e})();return t}n.getInstanceAsync=i,n._testing=process.env.AWS_LAMBDA_BENCHMARK_MODE==="1"?{reset:()=>{if(t=null,globalThis.awslambda?.InvokeStore)delete globalThis.awslambda.InvokeStore;globalThis.awslambda={InvokeStore:void 0}}}:void 0})(dG.InvokeStore||(dG.InvokeStore={}));dG.InvokeStoreBase=Fo});var _i=k((WG)=>{var{getSmithyContext:sc}=St();WG.getSmithyContext=sc;var{HttpRequest:rc}=Jn(),{requestBuilder:EG}=Jn();WG.requestBuilder=EG;var{HttpApiKeyAuthLocation:zM}=Di(),yG=(n,t)=>{if(!t||t.length===0)return n;let i=[];for(let s of t)for(let r of n)if(r.schemeId.split("#")[1]===s)i.push(r);for(let s of n)if(!i.find(({schemeId:r})=>r===s.schemeId))i.push(s);return i};function TG(n){let t=new Map;for(let i of n)t.set(i.schemeId,i);return t}var ec=(n,t)=>(i,s)=>async(r)=>{let e=n.httpAuthSchemeProvider(await t.httpAuthSchemeParametersProvider(n,s,r.input)),f=n.authSchemePreference?await n.authSchemePreference():[],o=yG(e,f),h=TG(n.httpAuthSchemes),u=sc(s),c=[];for(let _ of o){let w=h.get(_.schemeId);if(!w){c.push(`HttpAuthScheme \`${_.schemeId}\` was not enabled for this service.`);continue}let l=w.identityProvider(await t.identityProviderConfigProvider(n));if(!l){c.push(`HttpAuthScheme \`${_.schemeId}\` did not have an IdentityProvider configured.`);continue}let{identityProperties:A={},signingProperties:d={}}=_.propertiesExtractor?.(n,s)||{};_.identityProperties=Object.assign(_.identityProperties||{},A),_.signingProperties=Object.assign(_.signingProperties||{},d),u.selectedHttpAuthScheme={httpAuthOption:_,identity:await l(_.identityProperties),signer:w.signer};break}if(!u.selectedHttpAuthScheme)throw Error(c.join(`
|
|
24
|
+
`));return i(r)},QM={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},gG=(n,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:i})=>({applyToStack:(s)=>{s.addRelativeTo(ec(n,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:i}),QM)}}),CM={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"serializerMiddleware"},SG=(n,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:i})=>({applyToStack:(s)=>{s.addRelativeTo(ec(n,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:i}),CM)}}),IG=(n)=>(t)=>{throw t},UG=(n,t)=>{},xM=(n)=>(t,i)=>async(s)=>{if(!rc.isInstance(s.request))return t(s);let e=sc(i).selectedHttpAuthScheme;if(!e)throw Error("No HttpAuthScheme was selected: unable to sign request");let{httpAuthOption:{signingProperties:f={}},identity:o,signer:h}=e,u=await t({...s,request:await h.sign(s.request,o,f)}).catch((h.errorHandler||IG)(f));return(h.successHandler||UG)(u.response,f),u},KM={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},bG=(n)=>({applyToStack:(t)=>{t.addRelativeTo(xM(),KM)}}),$G=(n)=>{if(typeof n==="function")return n;let t=Promise.resolve(n);return()=>t},LG=async(n,t,i,s=(e)=>e,...r)=>{let e=new n(i);return e=s(e)??e,await t.send(e,...r)};function OG(n,t,i,s,r){return async function*(f,o,...h){let u=o,c=f.startingToken??u[i],_=!0,w;while(_){if(u[i]=c,r)u[r]=u[r]??f.pageSize;if(f.client instanceof n)w=await LG(t,f.client,o,f.withCommand,...h);else throw Error(`Invalid client, expected instance of ${n.name}`);yield w;let l=c;c=BG(w,s),_=!!(c&&(!f.stopOnSameToken||c!==l))}return}}var BG=(n,t)=>{let i=n,s=t.split(".");for(let r of s){if(!i||typeof i!=="object")return;i=i[r]}return i};function NG(n,t,i){if(!n.__smithy_context)n.__smithy_context={features:{}};else if(!n.__smithy_context.features)n.__smithy_context.features={};n.__smithy_context.features[t]=i}class kM{authSchemes=new Map;constructor(n){for(let t in n){let i=n[t];if(i!==void 0)this.authSchemes.set(t,i)}}getIdentityProvider(n){return this.authSchemes.get(n)}}class qM{async sign(n,t,i){if(!i)throw Error("request could not be signed with `apiKey` since the `name` and `in` signer properties are missing");if(!i.name)throw Error("request could not be signed with `apiKey` since the `name` signer property is missing");if(!i.in)throw Error("request could not be signed with `apiKey` since the `in` signer property is missing");if(!t.apiKey)throw Error("request could not be signed with `apiKey` since the `apiKey` is not defined");let s=rc.clone(n);if(i.in===zM.QUERY)s.query[i.name]=t.apiKey;else if(i.in===zM.HEADER)s.headers[i.name]=i.scheme?`${i.scheme} ${t.apiKey}`:t.apiKey;else throw Error("request can only be signed with `apiKey` locations `query` or `header`, but found: `"+i.in+"`");return s}}class VM{async sign(n,t,i){let s=rc.clone(n);if(!t.token)throw Error("request could not be signed with `token` since the `token` is not defined");return s.headers.Authorization=`Bearer ${t.token}`,s}}class jM{async sign(n,t,i){return n}}var aM=(n)=>function(i){return ZM(i)&&i.expiration.getTime()-Date.now()<n},vM=300000,GG=aM(vM),ZM=(n)=>n.expiration!==void 0,HG=(n,t,i)=>{if(n===void 0)return;let s=typeof n!=="function"?async()=>Promise.resolve(n):n,r,e,f,o=!1,h=async(u)=>{if(!e)e=s(u);try{r=await e,f=!0,o=!1}finally{e=void 0}return r};if(t===void 0)return async(u)=>{if(!f||u?.forceRefresh)r=await h(u);return r};return async(u)=>{if(!f||u?.forceRefresh)r=await h(u);if(o)return r;if(!i(r))return o=!0,r;if(t(r))return await h(u),r;return r}};WG.DefaultIdentityProviderConfig=kM;WG.EXPIRATION_MS=vM;WG.HttpApiKeyAuthSigner=qM;WG.HttpBearerAuthSigner=VM;WG.NoAuthSigner=jM;WG.createIsIdentityExpiredFunction=aM;WG.createPaginator=OG;WG.doesIdentityRequireRefresh=ZM;WG.getHttpAuthSchemeEndpointRuleSetPlugin=gG;WG.getHttpAuthSchemePlugin=SG;WG.getHttpSigningPlugin=bG;WG.httpAuthSchemeEndpointRuleSetMiddlewareOptions=QM;WG.httpAuthSchemeMiddleware=ec;WG.httpAuthSchemeMiddlewareOptions=CM;WG.httpSigningMiddleware=xM;WG.httpSigningMiddlewareOptions=KM;WG.isIdentityExpired=GG;WG.memoizeIdentityProvider=HG;WG.normalizeProvider=$G;WG.setFeature=NG});var pM=k((pr,oc)=>{(function(n,t){typeof pr=="object"&&typeof oc=="object"?oc.exports=t():typeof define=="function"&&define.amd?define([],t):typeof pr=="object"?pr.bowser=t():n.bowser=t()})(pr,function(){return function(n){var t={};function i(s){if(t[s])return t[s].exports;var r=t[s]={i:s,l:!1,exports:{}};return n[s].call(r.exports,r,r.exports,i),r.l=!0,r.exports}return i.m=n,i.c=t,i.d=function(s,r,e){i.o(s,r)||Object.defineProperty(s,r,{enumerable:!0,get:e})},i.r=function(s){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(s,"__esModule",{value:!0})},i.t=function(s,r){if(1&r&&(s=i(s)),8&r)return s;if(4&r&&typeof s=="object"&&s&&s.__esModule)return s;var e=Object.create(null);if(i.r(e),Object.defineProperty(e,"default",{enumerable:!0,value:s}),2&r&&typeof s!="string")for(var f in s)i.d(e,f,function(o){return s[o]}.bind(null,f));return e},i.n=function(s){var r=s&&s.__esModule?function(){return s.default}:function(){return s};return i.d(r,"a",r),r},i.o=function(s,r){return Object.prototype.hasOwnProperty.call(s,r)},i.p="",i(i.s=90)}({17:function(n,t,i){t.__esModule=!0,t.default=void 0;var s=i(18),r=function(){function e(){}return e.getFirstMatch=function(f,o){var h=o.match(f);return h&&h.length>0&&h[1]||""},e.getSecondMatch=function(f,o){var h=o.match(f);return h&&h.length>1&&h[2]||""},e.matchAndReturnConst=function(f,o,h){if(f.test(o))return h},e.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}},e.getMacOSVersionName=function(f){var o=f.split(".").splice(0,2).map(function(c){return parseInt(c,10)||0});o.push(0);var h=o[0],u=o[1];if(h===10)switch(u){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}switch(h){case 11:return"Big Sur";case 12:return"Monterey";case 13:return"Ventura";case 14:return"Sonoma";case 15:return"Sequoia";default:return}},e.getAndroidVersionName=function(f){var o=f.split(".").splice(0,2).map(function(h){return parseInt(h,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},e.getVersionPrecision=function(f){return f.split(".").length},e.compareVersions=function(f,o,h){h===void 0&&(h=!1);var u=e.getVersionPrecision(f),c=e.getVersionPrecision(o),_=Math.max(u,c),w=0,l=e.map([f,o],function(A){var d=_-e.getVersionPrecision(A),E=A+Array(d+1).join(".0");return e.map(E.split("."),function(R){return Array(20-R.length).join("0")+R}).reverse()});for(h&&(w=_-Math.min(u,c)),_-=1;_>=w;){if(l[0][_]>l[1][_])return 1;if(l[0][_]===l[1][_]){if(_===w)return 0;_-=1}else if(l[0][_]<l[1][_])return-1}},e.map=function(f,o){var h,u=[];if(Array.prototype.map)return Array.prototype.map.call(f,o);for(h=0;h<f.length;h+=1)u.push(o(f[h]));return u},e.find=function(f,o){var h,u;if(Array.prototype.find)return Array.prototype.find.call(f,o);for(h=0,u=f.length;h<u;h+=1){var c=f[h];if(o(c,h))return c}},e.assign=function(f){for(var o,h,u=f,c=arguments.length,_=Array(c>1?c-1:0),w=1;w<c;w++)_[w-1]=arguments[w];if(Object.assign)return Object.assign.apply(Object,[f].concat(_));var l=function(){var A=_[o];typeof A=="object"&&A!==null&&Object.keys(A).forEach(function(d){u[d]=A[d]})};for(o=0,h=_.length;o<h;o+=1)l();return f},e.getBrowserAlias=function(f){return s.BROWSER_ALIASES_MAP[f]},e.getBrowserTypeByAlias=function(f){return s.BROWSER_MAP[f]||""},e}();t.default=r,n.exports=t.default},18:function(n,t,i){t.__esModule=!0,t.ENGINE_MAP=t.OS_MAP=t.PLATFORMS_MAP=t.BROWSER_MAP=t.BROWSER_ALIASES_MAP=void 0,t.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"},t.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"},t.PLATFORMS_MAP={bot:"bot",desktop:"desktop",mobile:"mobile",tablet:"tablet",tv:"tv"},t.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"},t.ENGINE_MAP={Blink:"Blink",EdgeHTML:"EdgeHTML",Gecko:"Gecko",Presto:"Presto",Trident:"Trident",WebKit:"WebKit"}},90:function(n,t,i){t.__esModule=!0,t.default=void 0;var s,r=(s=i(91))&&s.__esModule?s:{default:s},e=i(18);function f(h,u){for(var c=0;c<u.length;c++){var _=u[c];_.enumerable=_.enumerable||!1,_.configurable=!0,"value"in _&&(_.writable=!0),Object.defineProperty(h,_.key,_)}}var o=function(){function h(){}var u,c,_;return h.getParser=function(w,l,A){if(l===void 0&&(l=!1),A===void 0&&(A=null),typeof w!="string")throw Error("UserAgent should be a string");return new r.default(w,l,A)},h.parse=function(w,l){return l===void 0&&(l=null),new r.default(w,l).getResult()},u=h,_=[{key:"BROWSER_MAP",get:function(){return e.BROWSER_MAP}},{key:"ENGINE_MAP",get:function(){return e.ENGINE_MAP}},{key:"OS_MAP",get:function(){return e.OS_MAP}},{key:"PLATFORMS_MAP",get:function(){return e.PLATFORMS_MAP}}],(c=null)&&f(u.prototype,c),_&&f(u,_),h}();t.default=o,n.exports=t.default},91:function(n,t,i){t.__esModule=!0,t.default=void 0;var s=h(i(92)),r=h(i(93)),e=h(i(94)),f=h(i(95)),o=h(i(17));function h(c){return c&&c.__esModule?c:{default:c}}var u=function(){function c(w,l,A){if(l===void 0&&(l=!1),A===void 0&&(A=null),w==null||w==="")throw Error("UserAgent parameter can't be empty");this._ua=w;var d=!1;typeof l=="boolean"?(d=l,this._hints=A):this._hints=l!=null&&typeof l=="object"?l:null,this.parsedResult={},d!==!0&&this.parse()}var _=c.prototype;return _.getHints=function(){return this._hints},_.hasBrand=function(w){if(!this._hints||!Array.isArray(this._hints.brands))return!1;var l=w.toLowerCase();return this._hints.brands.some(function(A){return A.brand&&A.brand.toLowerCase()===l})},_.getBrandVersion=function(w){if(this._hints&&Array.isArray(this._hints.brands)){var l=w.toLowerCase(),A=this._hints.brands.find(function(d){return d.brand&&d.brand.toLowerCase()===l});return A?A.version:void 0}},_.getUA=function(){return this._ua},_.test=function(w){return w.test(this._ua)},_.parseBrowser=function(){var w=this;this.parsedResult.browser={};var l=o.default.find(s.default,function(A){if(typeof A.test=="function")return A.test(w);if(Array.isArray(A.test))return A.test.some(function(d){return w.test(d)});throw Error("Browser's test function is not valid")});return l&&(this.parsedResult.browser=l.describe(this.getUA(),this)),this.parsedResult.browser},_.getBrowser=function(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()},_.getBrowserName=function(w){return w?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""},_.getBrowserVersion=function(){return this.getBrowser().version},_.getOS=function(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()},_.parseOS=function(){var w=this;this.parsedResult.os={};var l=o.default.find(r.default,function(A){if(typeof A.test=="function")return A.test(w);if(Array.isArray(A.test))return A.test.some(function(d){return w.test(d)});throw Error("Browser's test function is not valid")});return l&&(this.parsedResult.os=l.describe(this.getUA())),this.parsedResult.os},_.getOSName=function(w){var l=this.getOS().name;return w?String(l).toLowerCase()||"":l||""},_.getOSVersion=function(){return this.getOS().version},_.getPlatform=function(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()},_.getPlatformType=function(w){w===void 0&&(w=!1);var l=this.getPlatform().type;return w?String(l).toLowerCase()||"":l||""},_.parsePlatform=function(){var w=this;this.parsedResult.platform={};var l=o.default.find(e.default,function(A){if(typeof A.test=="function")return A.test(w);if(Array.isArray(A.test))return A.test.some(function(d){return w.test(d)});throw Error("Browser's test function is not valid")});return l&&(this.parsedResult.platform=l.describe(this.getUA())),this.parsedResult.platform},_.getEngine=function(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()},_.getEngineName=function(w){return w?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""},_.parseEngine=function(){var w=this;this.parsedResult.engine={};var l=o.default.find(f.default,function(A){if(typeof A.test=="function")return A.test(w);if(Array.isArray(A.test))return A.test.some(function(d){return w.test(d)});throw Error("Browser's test function is not valid")});return l&&(this.parsedResult.engine=l.describe(this.getUA())),this.parsedResult.engine},_.parse=function(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this},_.getResult=function(){return o.default.assign({},this.parsedResult)},_.satisfies=function(w){var l=this,A={},d=0,E={},R=0;if(Object.keys(w).forEach(function(b){var $=w[b];typeof $=="string"?(E[b]=$,R+=1):typeof $=="object"&&(A[b]=$,d+=1)}),d>0){var y=Object.keys(A),T=o.default.find(y,function(b){return l.isOS(b)});if(T){var S=this.satisfies(A[T]);if(S!==void 0)return S}var I=o.default.find(y,function(b){return l.isPlatform(b)});if(I){var F=this.satisfies(A[I]);if(F!==void 0)return F}}if(R>0){var C=Object.keys(E),sn=o.default.find(C,function(b){return l.isBrowser(b,!0)});if(sn!==void 0)return this.compareVersion(E[sn])}},_.isBrowser=function(w,l){l===void 0&&(l=!1);var A=this.getBrowserName().toLowerCase(),d=w.toLowerCase(),E=o.default.getBrowserTypeByAlias(d);return l&&E&&(d=E.toLowerCase()),d===A},_.compareVersion=function(w){var l=[0],A=w,d=!1,E=this.getBrowserVersion();if(typeof E=="string")return w[0]===">"||w[0]==="<"?(A=w.substr(1),w[1]==="="?(d=!0,A=w.substr(2)):l=[],w[0]===">"?l.push(1):l.push(-1)):w[0]==="="?A=w.substr(1):w[0]==="~"&&(d=!0,A=w.substr(1)),l.indexOf(o.default.compareVersions(E,A,d))>-1},_.isOS=function(w){return this.getOSName(!0)===String(w).toLowerCase()},_.isPlatform=function(w){return this.getPlatformType(!0)===String(w).toLowerCase()},_.isEngine=function(w){return this.getEngineName(!0)===String(w).toLowerCase()},_.is=function(w,l){return l===void 0&&(l=!1),this.isBrowser(w,l)||this.isOS(w)||this.isPlatform(w)},_.some=function(w){var l=this;return w===void 0&&(w=[]),w.some(function(A){return l.is(A)})},c}();t.default=u,n.exports=t.default},92:function(n,t,i){t.__esModule=!0,t.default=void 0;var s,r=(s=i(17))&&s.__esModule?s:{default:s},e=/version\/(\d+(\.?_?\d+)+)/i,f=[{test:[/gptbot/i],describe:function(o){var h={name:"GPTBot"},u=r.default.getFirstMatch(/gptbot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/chatgpt-user/i],describe:function(o){var h={name:"ChatGPT-User"},u=r.default.getFirstMatch(/chatgpt-user\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/oai-searchbot/i],describe:function(o){var h={name:"OAI-SearchBot"},u=r.default.getFirstMatch(/oai-searchbot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(o){var h={name:"ClaudeBot"},u=r.default.getFirstMatch(/(?:claudebot|claude-web|claude-user|claude-searchbot)\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(o){var h={name:"Omgilibot"},u=r.default.getFirstMatch(/(?:omgilibot|webzio-extended)\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/diffbot/i],describe:function(o){var h={name:"Diffbot"},u=r.default.getFirstMatch(/diffbot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/perplexitybot/i],describe:function(o){var h={name:"PerplexityBot"},u=r.default.getFirstMatch(/perplexitybot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/perplexity-user/i],describe:function(o){var h={name:"Perplexity-User"},u=r.default.getFirstMatch(/perplexity-user\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/youbot/i],describe:function(o){var h={name:"YouBot"},u=r.default.getFirstMatch(/youbot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/meta-webindexer/i],describe:function(o){var h={name:"Meta-WebIndexer"},u=r.default.getFirstMatch(/meta-webindexer\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/meta-externalads/i],describe:function(o){var h={name:"Meta-ExternalAds"},u=r.default.getFirstMatch(/meta-externalads\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/meta-externalagent/i],describe:function(o){var h={name:"Meta-ExternalAgent"},u=r.default.getFirstMatch(/meta-externalagent\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/meta-externalfetcher/i],describe:function(o){var h={name:"Meta-ExternalFetcher"},u=r.default.getFirstMatch(/meta-externalfetcher\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/googlebot/i],describe:function(o){var h={name:"Googlebot"},u=r.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/linespider/i],describe:function(o){var h={name:"Linespider"},u=r.default.getFirstMatch(/(?:linespider)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/amazonbot/i],describe:function(o){var h={name:"AmazonBot"},u=r.default.getFirstMatch(/amazonbot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/bingbot/i],describe:function(o){var h={name:"BingCrawler"},u=r.default.getFirstMatch(/bingbot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/baiduspider/i],describe:function(o){var h={name:"BaiduSpider"},u=r.default.getFirstMatch(/baiduspider\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/duckduckbot/i],describe:function(o){var h={name:"DuckDuckBot"},u=r.default.getFirstMatch(/duckduckbot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/ia_archiver/i],describe:function(o){var h={name:"InternetArchiveCrawler"},u=r.default.getFirstMatch(/ia_archiver\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{name:"FacebookExternalHit"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(o){var h={name:"SlackBot"},u=r.default.getFirstMatch(/(?:slackbot|slack-imgproxy)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{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 h={name:"Opera"},u=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/opr\/|opios/i],describe:function(o){var h={name:"Opera"},u=r.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/SamsungBrowser/i],describe:function(o){var h={name:"Samsung Internet for Android"},u=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/Whale/i],describe:function(o){var h={name:"NAVER Whale Browser"},u=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/PaleMoon/i],describe:function(o){var h={name:"Pale Moon"},u=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:PaleMoon)[\s/](\d+(?:\.\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/MZBrowser/i],describe:function(o){var h={name:"MZ Browser"},u=r.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/focus/i],describe:function(o){var h={name:"Focus"},u=r.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/swing/i],describe:function(o){var h={name:"Swing"},u=r.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/coast/i],describe:function(o){var h={name:"Opera Coast"},u=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(o){var h={name:"Opera Touch"},u=r.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/yabrowser/i],describe:function(o){var h={name:"Yandex Browser"},u=r.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/ucbrowser/i],describe:function(o){var h={name:"UC Browser"},u=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/Maxthon|mxios/i],describe:function(o){var h={name:"Maxthon"},u=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/epiphany/i],describe:function(o){var h={name:"Epiphany"},u=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/puffin/i],describe:function(o){var h={name:"Puffin"},u=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/sleipnir/i],describe:function(o){var h={name:"Sleipnir"},u=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/k-meleon/i],describe:function(o){var h={name:"K-Meleon"},u=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/micromessenger/i],describe:function(o){var h={name:"WeChat"},u=r.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/qqbrowser/i],describe:function(o){var h={name:/qqbrowserlite/i.test(o)?"QQ Browser Lite":"QQ Browser"},u=r.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/msie|trident/i],describe:function(o){var h={name:"Internet Explorer"},u=r.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/\sedg\//i],describe:function(o){var h={name:"Microsoft Edge"},u=r.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/edg([ea]|ios)/i],describe:function(o){var h={name:"Microsoft Edge"},u=r.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/vivaldi/i],describe:function(o){var h={name:"Vivaldi"},u=r.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/seamonkey/i],describe:function(o){var h={name:"SeaMonkey"},u=r.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/sailfish/i],describe:function(o){var h={name:"Sailfish"},u=r.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,o);return u&&(h.version=u),h}},{test:[/silk/i],describe:function(o){var h={name:"Amazon Silk"},u=r.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/phantom/i],describe:function(o){var h={name:"PhantomJS"},u=r.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/slimerjs/i],describe:function(o){var h={name:"SlimerJS"},u=r.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(o){var h={name:"BlackBerry"},u=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/(web|hpw)[o0]s/i],describe:function(o){var h={name:"WebOS Browser"},u=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/bada/i],describe:function(o){var h={name:"Bada"},u=r.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/tizen/i],describe:function(o){var h={name:"Tizen"},u=r.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/qupzilla/i],describe:function(o){var h={name:"QupZilla"},u=r.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/librewolf/i],describe:function(o){var h={name:"LibreWolf"},u=r.default.getFirstMatch(/(?:librewolf)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/firefox|iceweasel|fxios/i],describe:function(o){var h={name:"Firefox"},u=r.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/electron/i],describe:function(o){var h={name:"Electron"},u=r.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/sogoumobilebrowser/i,/metasr/i,/se 2\.[x]/i],describe:function(o){var h={name:"Sogou Browser"},u=r.default.getFirstMatch(/(?:sogoumobilebrowser)[\s/](\d+(\.?_?\d+)+)/i,o),c=r.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,o),_=r.default.getFirstMatch(/se ([\d.]+)x/i,o),w=u||c||_;return w&&(h.version=w),h}},{test:[/MiuiBrowser/i],describe:function(o){var h={name:"Miui"},u=r.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:function(o){return!!o.hasBrand("DuckDuckGo")||o.test(/\sDdg\/[\d.]+$/i)},describe:function(o,h){var u={name:"DuckDuckGo"};if(h){var c=h.getBrandVersion("DuckDuckGo");if(c)return u.version=c,u}var _=r.default.getFirstMatch(/\sDdg\/([\d.]+)$/i,o);return _&&(u.version=_),u}},{test:function(o){return o.hasBrand("Brave")},describe:function(o,h){var u={name:"Brave"};if(h){var c=h.getBrandVersion("Brave");if(c)return u.version=c,u}return u}},{test:[/chromium/i],describe:function(o){var h={name:"Chromium"},u=r.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,o)||r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/chrome|crios|crmo/i],describe:function(o){var h={name:"Chrome"},u=r.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/GSA/i],describe:function(o){var h={name:"Google Search"},u=r.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:function(o){var h=!o.test(/like android/i),u=o.test(/android/i);return h&&u},describe:function(o){var h={name:"Android Browser"},u=r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/playstation 4/i],describe:function(o){var h={name:"PlayStation 4"},u=r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/safari|applewebkit/i],describe:function(o){var h={name:"Safari"},u=r.default.getFirstMatch(e,o);return u&&(h.version=u),h}},{test:[/.*/i],describe:function(o){var h=o.search("\\(")!==-1?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:r.default.getFirstMatch(h,o),version:r.default.getSecondMatch(h,o)}}}];t.default=f,n.exports=t.default},93:function(n,t,i){t.__esModule=!0,t.default=void 0;var s,r=(s=i(17))&&s.__esModule?s:{default:s},e=i(18),f=[{test:[/Roku\/DVP/],describe:function(o){var h=r.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,o);return{name:e.OS_MAP.Roku,version:h}}},{test:[/windows phone/i],describe:function(o){var h=r.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,o);return{name:e.OS_MAP.WindowsPhone,version:h}}},{test:[/windows /i],describe:function(o){var h=r.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,o),u=r.default.getWindowsVersionName(h);return{name:e.OS_MAP.Windows,version:h,versionName:u}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(o){var h={name:e.OS_MAP.iOS},u=r.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,o);return u&&(h.version=u),h}},{test:[/macintosh/i],describe:function(o){var h=r.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,o).replace(/[_\s]/g,"."),u=r.default.getMacOSVersionName(h),c={name:e.OS_MAP.MacOS,version:h};return u&&(c.versionName=u),c}},{test:[/(ipod|iphone|ipad)/i],describe:function(o){var h=r.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,o).replace(/[_\s]/g,".");return{name:e.OS_MAP.iOS,version:h}}},{test:[/OpenHarmony/i],describe:function(o){var h=r.default.getFirstMatch(/OpenHarmony\s+(\d+(\.\d+)*)/i,o);return{name:e.OS_MAP.HarmonyOS,version:h}}},{test:function(o){var h=!o.test(/like android/i),u=o.test(/android/i);return h&&u},describe:function(o){var h=r.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,o),u=r.default.getAndroidVersionName(h),c={name:e.OS_MAP.Android,version:h};return u&&(c.versionName=u),c}},{test:[/(web|hpw)[o0]s/i],describe:function(o){var h=r.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,o),u={name:e.OS_MAP.WebOS};return h&&h.length&&(u.version=h),u}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(o){var h=r.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,o)||r.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,o)||r.default.getFirstMatch(/\bbb(\d+)/i,o);return{name:e.OS_MAP.BlackBerry,version:h}}},{test:[/bada/i],describe:function(o){var h=r.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,o);return{name:e.OS_MAP.Bada,version:h}}},{test:[/tizen/i],describe:function(o){var h=r.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,o);return{name:e.OS_MAP.Tizen,version:h}}},{test:[/linux/i],describe:function(){return{name:e.OS_MAP.Linux}}},{test:[/CrOS/],describe:function(){return{name:e.OS_MAP.ChromeOS}}},{test:[/PlayStation 4/],describe:function(o){var h=r.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,o);return{name:e.OS_MAP.PlayStation4,version:h}}}];t.default=f,n.exports=t.default},94:function(n,t,i){t.__esModule=!0,t.default=void 0;var s,r=(s=i(17))&&s.__esModule?s:{default:s},e=i(18),f=[{test:[/googlebot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Google"}}},{test:[/linespider/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Line"}}},{test:[/amazonbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Amazon"}}},{test:[/gptbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/chatgpt-user/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/oai-searchbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/baiduspider/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Baidu"}}},{test:[/bingbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Bing"}}},{test:[/duckduckbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"DuckDuckGo"}}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Anthropic"}}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Webz.io"}}},{test:[/diffbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Diffbot"}}},{test:[/perplexitybot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Perplexity AI"}}},{test:[/perplexity-user/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Perplexity AI"}}},{test:[/youbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"You.com"}}},{test:[/ia_archiver/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Internet Archive"}}},{test:[/meta-webindexer/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalads/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalagent/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalfetcher/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Slack"}}},{test:[/yahoo/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Yahoo"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Yandex"}}},{test:[/pingdom/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Pingdom"}}},{test:[/huawei/i],describe:function(o){var h=r.default.getFirstMatch(/(can-l01)/i,o)&&"Nova",u={type:e.PLATFORMS_MAP.mobile,vendor:"Huawei"};return h&&(u.model=h),u}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return{type:e.PLATFORMS_MAP.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe:function(){return{type:e.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(){return{type:e.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe:function(){return{type:e.PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe:function(){return{type:e.PLATFORMS_MAP.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe:function(){return{type:e.PLATFORMS_MAP.tablet}}},{test:function(o){var h=o.test(/ipod|iphone/i),u=o.test(/like (ipod|iphone)/i);return h&&!u},describe:function(o){var h=r.default.getFirstMatch(/(ipod|iphone)/i,o);return{type:e.PLATFORMS_MAP.mobile,vendor:"Apple",model:h}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:e.PLATFORMS_MAP.mobile,vendor:"Nexus"}}},{test:[/Nokia/i],describe:function(o){var h=r.default.getFirstMatch(/Nokia\s+([0-9]+(\.[0-9]+)?)/i,o),u={type:e.PLATFORMS_MAP.mobile,vendor:"Nokia"};return h&&(u.model=h),u}},{test:[/[^-]mobi/i],describe:function(){return{type:e.PLATFORMS_MAP.mobile}}},{test:function(o){return o.getBrowserName(!0)==="blackberry"},describe:function(){return{type:e.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(o){return o.getBrowserName(!0)==="bada"},describe:function(){return{type:e.PLATFORMS_MAP.mobile}}},{test:function(o){return o.getBrowserName()==="windows phone"},describe:function(){return{type:e.PLATFORMS_MAP.mobile,vendor:"Microsoft"}}},{test:function(o){var h=Number(String(o.getOSVersion()).split(".")[0]);return o.getOSName(!0)==="android"&&h>=3},describe:function(){return{type:e.PLATFORMS_MAP.tablet}}},{test:function(o){return o.getOSName(!0)==="android"},describe:function(){return{type:e.PLATFORMS_MAP.mobile}}},{test:[/smart-?tv|smarttv/i],describe:function(){return{type:e.PLATFORMS_MAP.tv}}},{test:[/netcast/i],describe:function(){return{type:e.PLATFORMS_MAP.tv}}},{test:function(o){return o.getOSName(!0)==="macos"},describe:function(){return{type:e.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(o){return o.getOSName(!0)==="windows"},describe:function(){return{type:e.PLATFORMS_MAP.desktop}}},{test:function(o){return o.getOSName(!0)==="linux"},describe:function(){return{type:e.PLATFORMS_MAP.desktop}}},{test:function(o){return o.getOSName(!0)==="playstation 4"},describe:function(){return{type:e.PLATFORMS_MAP.tv}}},{test:function(o){return o.getOSName(!0)==="roku"},describe:function(){return{type:e.PLATFORMS_MAP.tv}}}];t.default=f,n.exports=t.default},95:function(n,t,i){t.__esModule=!0,t.default=void 0;var s,r=(s=i(17))&&s.__esModule?s:{default:s},e=i(18),f=[{test:function(o){return o.getBrowserName(!0)==="microsoft edge"},describe:function(o){if(/\sedg\//i.test(o))return{name:e.ENGINE_MAP.Blink};var h=r.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,o);return{name:e.ENGINE_MAP.EdgeHTML,version:h}}},{test:[/trident/i],describe:function(o){var h={name:e.ENGINE_MAP.Trident},u=r.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:function(o){return o.test(/presto/i)},describe:function(o){var h={name:e.ENGINE_MAP.Presto},u=r.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:function(o){var h=o.test(/gecko/i),u=o.test(/like gecko/i);return h&&!u},describe:function(o){var h={name:e.ENGINE_MAP.Gecko},u=r.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:e.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(o){var h={name:e.ENGINE_MAP.WebKit},u=r.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,o);return u&&(h.version=u),h}}];t.default=f,n.exports=t.default}})})});var ct=k((a3)=>{var{Retry:i3,RETRY_MODES:nd}=Zr(),{HttpRequest:wc,parseUrl:s3}=Jn(),{InvokeStore:td}=XM(),{normalizeProvider:r3}=_i(),{platform:e3,release:o3}=p("os"),{versions:fc,env:id}=p("process"),{isValidHostLabel:f3,isIpAddress:fd,customEndpointFunctions:h3}=Ji(),{EndpointError:u3,resolveEndpoint:c3}=Ji();a3.EndpointError=u3;a3.isIpAddress=fd;a3.resolveEndpoint=c3;var{loadConfig:_3,NODE_REGION_CONFIG_OPTIONS:hd,NODE_REGION_CONFIG_FILE_OPTIONS:ud}=Yn(),{REGION_ENV_NAME:w3,REGION_INI_NAME:l3,resolveRegionConfig:A3}=Yn();a3.NODE_REGION_CONFIG_FILE_OPTIONS=ud;a3.NODE_REGION_CONFIG_OPTIONS=hd;a3.REGION_ENV_NAME=w3;a3.REGION_INI_NAME=l3;a3.resolveRegionConfig=A3;var Do={warningEmitted:!1},M3=(n)=>{if(n&&!Do.warningEmitted){if(process.env.AWS_SDK_JS_NODE_VERSION_SUPPORT_WARNING_DISABLED==="true"){Do.warningEmitted=!0;return}let t=parseInt(n.substring(1,n.indexOf("."))),i=22;if(t<i)Do.warningEmitted=!0,process.emitWarning(`NodeVersionSupportWarning: The AWS SDK for JavaScript (v3)
|
|
24
25
|
versions published after the first week of January 2027
|
|
25
|
-
will require node >=${
|
|
26
|
+
will require node >=${i}. You are running node ${n}.
|
|
26
27
|
|
|
27
28
|
To continue receiving updates to AWS services, bug fixes,
|
|
28
|
-
and security updates please upgrade to node >=${
|
|
29
|
+
and security updates please upgrade to node >=${i}.
|
|
29
30
|
|
|
30
|
-
More information can be found at: https://a.co/c895JFp`)}},hy=()=>(t,n)=>async(s)=>{return n.__retryLongPoll=!0,t(s)},uy={name:"longPollMiddleware",tags:["RETRY"],step:"initialize",override:!0},_y=(t)=>({applyToStack:(n)=>{n.add(hy(),uy)}});function ly(t,n,s){if(!t.$source)t.$source={};return t.$source[n]=s,t}jO.v2026||=typeof process==="object"&&process.env?.AWS_NEW_RETRIES_2026==="true";function fn(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 wy(t,n,s){if(!t.$source)t.$source={};return t.$source[n]=s,t}function Ay(t){return t}var xw=(t)=>(n)=>async(s)=>{if(!Pc.isInstance(s.request))return n(s);let{request:r}=s,{handlerProtocol:i=""}=t.requestHandler.metadata||{};if(i.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 e=r.hostname;if(r.port!=null)e+=`:${r.port}`;r.headers.host=e}return n(s)},qw={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},My=(t)=>({applyToStack:(n)=>{n.add(xw(t),qw)}}),Cw=()=>(t,n)=>async(s)=>{try{let r=await t(s),{clientName:i,commandName:e,logger:f,dynamoDbDocumentClientOptions:o={}}=n,{overrideInputFilterSensitiveLog:c,overrideOutputFilterSensitiveLog:h}=o,u=c??n.inputFilterSensitiveLog,_=h??n.outputFilterSensitiveLog,{$metadata:l,...w}=r.output;return f?.info?.({clientName:i,commandName:e,input:u(s.input),output:_(w),metadata:l}),r}catch(r){let{clientName:i,commandName:e,logger:f,dynamoDbDocumentClientOptions:o={}}=n,{overrideInputFilterSensitiveLog:c}=o,h=c??n.inputFilterSensitiveLog;throw f?.error?.({clientName:i,commandName:e,input:h(s.input),error:r,metadata:r.$metadata}),r}},Kw={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},gy=(t)=>({applyToStack:(n)=>{n.add(Cw(),Kw)}}),Vw={step:"build",tags:["RECURSION_DETECTION","TRACE_CONTEXT_PROPAGATION"],name:"recursionDetectionMiddleware",override:!0,priority:"low"},Ey="AWS_LAMBDA_FUNCTION_NAME",dy="_X_AMZN_TRACE_ID",Gc="X-Amzn-Trace-Id",Hc="traceparent",jw="tracestate",aw="baggage",pw=()=>(t)=>async(n)=>{let{request:s}=n;if(!Pc.isInstance(s))return t(n);let r;{let i=Object.keys(s.headers??{}).find((e)=>e.toLowerCase()===Gc.toLowerCase())??Gc;if(!s.headers.hasOwnProperty(i)){let e=process.env[Ey],f=process.env[dy];r??=await Ww.getInstanceAsync();let c=r?.getXRayTraceId()??f,h=(u)=>typeof u==="string"&&u.length>0;if(h(e)&&h(c))s.headers[Gc]=c}}if(Ry(s.headers),!s.headers[Hc]){let e=(r??=await Ww.getInstanceAsync())?.getTraceparent?.();if(e){s.headers[Hc]=e;let f=r?.getTracestate?.();if(f)s.headers[jw]=f;let o=r?.getBaggage?.();if(o)s.headers[aw]=o}}return t(n)};function Ry(t){for(let n of Object.keys(t)){let s=n.toLowerCase();if(n!==s&&(s===Hc||s===jw||s===aw))t[s]=t[n],delete t[n]}}var by=(t)=>({applyToStack:(n)=>{n.add(pw(),Vw)}}),Nc=void 0;function Ty(t){if(t===void 0)return!0;return typeof t==="string"&&t.length<=50}function Sy(t){let n=pO(t.userAgentAppId??Nc),{customUserAgent:s}=t;return Object.assign(t,{customUserAgent:typeof s==="string"?[[s]]:s,userAgentAppId:async()=>{let r=await n();if(!Ty(r)){let i=t.logger?.constructor?.name==="NoOpLogger"||!t.logger?console:t.logger;if(typeof r!=="string")i?.warn("userAgentAppId must be a string or undefined.");else if(r.length>50)i?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.")}return r}})}var Zw={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"},vw=Zw,tA="",nA=(t)=>{let{partitions:n}=vw;for(let r of n){let{regions:i,outputs:e}=r;for(let[f,o]of Object.entries(i))if(f===t)return{...e,...o}}for(let r of n){let{regionRegex:i,outputs:e}=r;if(new RegExp(i).test(t))return{...e}}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}},sA=(t,n="")=>{vw=t,tA=n},$y=()=>{sA(Zw,"")},rA=()=>tA,Uy=/\d{12}\.ddb/;async function Ly(t,n,s){if(s.request?.headers?.["smithy-protocol"]==="rpc-v2-cbor")fn(t,"PROTOCOL_RPC_V2_CBOR","M");if(typeof n.retryStrategy==="function"){let e=await n.retryStrategy();if(typeof e.mode==="string")switch(e.mode){case Nw.ADAPTIVE:fn(t,"RETRY_MODE_ADAPTIVE","F");break;case Nw.STANDARD:fn(t,"RETRY_MODE_STANDARD","E");break}}if(typeof n.accountIdEndpointMode==="function"){let e=t.endpointV2;if(String(e?.url?.hostname).match(Uy))fn(t,"ACCOUNT_ID_ENDPOINT","O");switch(await n.accountIdEndpointMode?.()){case"disabled":fn(t,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":fn(t,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":fn(t,"ACCOUNT_ID_MODE_REQUIRED","R");break}}let i=t.__smithy_context?.selectedHttpAuthScheme?.identity;if(i?.$source){let e=i;if(e.accountId)fn(t,"RESOLVED_ACCOUNT_ID","T");for(let[f,o]of Object.entries(e.$source??{}))fn(t,f,o)}}var Yw="user-agent",Bc="x-amz-user-agent",mw=" ",Fc="/",Iy=/[^!$%&'*+\-.^_`|~\w]/g,Oy=/[^!$%&'*+\-.^_`|~\w#]/g,Qw="-",yy=1024;function Gy(t){let n="";for(let s in t){let r=t[s];if(n.length+r.length+1<=yy){if(n.length)n+=","+r;else n+=r;continue}break}return n}var iA=(t)=>(n,s)=>async(r)=>{let{request:i}=r;if(!Pc.isInstance(i))return n(r);let{headers:e}=i,f=s?.userAgent?.map(Ue)||[],o=(await t.defaultUserAgentProvider()).map(Ue);await Ly(s,t,r);let c=s;o.push(`m/${Gy(Object.assign({},s.__smithy_context?.features,c.__aws_sdk_context?.features))}`);let h=t?.customUserAgent?.map(Ue)||[],u=await t.userAgentAppId();if(u)o.push(Ue(["app",`${u}`]));let _=rA(),l=(_?[_]:[]).concat([...o,...f,...h]).join(mw),w=[...o.filter((A)=>A.startsWith("aws-sdk-")),...h].join(mw);if(t.runtime!=="browser"){if(w)e[Bc]=e[Bc]?`${e[Yw]} ${w}`:w;e[Yw]=l}else e[Bc]=l;return n({...r,request:i})},Ue=(t)=>{let n=t[0].split(Fc).map((f)=>f.replace(Iy,Qw)).join(Fc),s=t[1]?.replace(Oy,Qw),r=n.indexOf(Fc),i=n.substring(0,r),e=n.substring(r+1);if(i==="api")e=e.toLowerCase();return[i,e,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}`}},"")},eA={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},By=(t)=>({applyToStack:(n)=>{n.add(iA(t),eA)}}),Fy=()=>{let t=["deno","bun","llrt"];for(let n of t)if(yc[n])return[`md/${n}`,yc[n]];return["md/nodejs",yc.node]},oA={isCrtAvailable:!1},Hy=()=>{if(oA.isCrtAvailable)return["md/crt-avail"];return null},fA=({serviceId:t,clientVersion:n})=>{let s=Fy();return async(r)=>{let i=[["aws-sdk-js",n],["ua","2.1"],[`os/${ZO()}`,vO()],["lang/js"],s],e=Hy();if(e)i.push(e);if(t)i.push([`api/${t}`,n]);if(Dw.AWS_EXECUTION_ENV)i.push([`exec-env/${Dw.AWS_EXECUTION_ENV}`]);let f=await r?.userAgentAppId?.();return f?[...i,[`app/${f}`]]:[...i]}},Py=fA,cA="AWS_SDK_UA_APP_ID",hA="sdk_ua_app_id",Ny="sdk-ua-app-id",Wy={environmentVariableSelector:(t)=>t[cA],configFileSelector:(t)=>t[hA]??t[Ny],default:Nc},Dy=({serviceId:t,clientVersion:n})=>async(s)=>{let r=Pw(),i=r.parse??r.default.parse??(()=>""),e=typeof window<"u"&&window?.navigator?.userAgent?i(window.navigator.userAgent):void 0,f=[["aws-sdk-js",n],["ua","2.1"],[`os/${e?.os?.name||"other"}`,e?.os?.version],["lang/js"],["md/browser",`${e?.browser?.name??"unknown"}_${e?.browser?.version??"unknown"}`]];if(t)f.push([`api/${t}`,n]);let o=await s?.userAgentAppId?.();if(o)f.push([`app/${o}`]);return f},Yy={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}},Wc=(t,n=!1)=>{if(n){for(let s of t.split("."))if(!Wc(s))return!1;return!0}if(!ty(t))return!1;if(t.length<3||t.length>63)return!1;if(t!==t.toLowerCase())return!1;if(kw(t))return!1;return!0},Jw=":",my="/",uA=(t)=>{let n=t.split(Jw);if(n.length<6)return null;let[s,r,i,e,f,...o]=n;if(s!=="arn"||r===""||i===""||o.join(Jw)==="")return null;let c=o.map((h)=>h.split(my)).flat();return{partition:r,service:i,region:e,accountId:f,resourceId:c}},_A={isVirtualHostableS3Bucket:Wc,parseArn:uA,partition:nA};ny.aws=_A;var Qy=(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 lA(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},lA=(t)=>aO(t.url);function Jy(t={}){return iy({...Xw,async default(){if(!wA.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"}},{...zw,...t})}var wA={silence:!1},ky=(t)=>{return{setRegion(n){t.region=n},region(){return t.region}}},Xy=(t)=>{return{region:t.region()}};zy.DEFAULT_UA_APP_ID=Nc;zy.NODE_APP_ID_CONFIG_OPTIONS=Wy;zy.UA_APP_ID_ENV_NAME=cA;zy.UA_APP_ID_INI_NAME=hA;zy.awsEndpointFunctions=_A;zy.createDefaultUserAgentProvider=fA;zy.createUserAgentStringParsingProvider=Dy;zy.crtAvailability=oA;zy.defaultUserAgent=Py;zy.emitWarningIfUnsupportedVersion=cy;zy.fallback=Yy;zy.getAwsRegionExtensionConfiguration=ky;zy.getHostHeaderPlugin=My;zy.getLoggerPlugin=gy;zy.getLongPollPlugin=_y;zy.getRecursionDetectionPlugin=by;zy.getUserAgentMiddlewareOptions=eA;zy.getUserAgentPlugin=By;zy.getUserAgentPrefix=rA;zy.hostHeaderMiddleware=xw;zy.hostHeaderMiddlewareOptions=qw;zy.isVirtualHostableS3Bucket=Wc;zy.loggerMiddleware=Cw;zy.loggerMiddlewareOptions=Kw;zy.parseArn=uA;zy.partition=nA;zy.recursionDetectionMiddleware=pw;zy.recursionDetectionMiddlewareOptions=Vw;zy.resolveAwsRegionExtensionConfiguration=Xy;zy.resolveDefaultAwsRegionalEndpointsConfig=Qy;zy.resolveHostHeaderConfig=Ay;zy.resolveUserAgentConfig=Sy;zy.setCredentialFeature=ly;zy.setFeature=fn;zy.setPartitionInfo=sA;zy.setTokenFeature=wy;zy.state=Le;zy.stsRegionDefaultResolver=Jy;zy.stsRegionWarning=wA;zy.toEndpointV1=lA;zy.useDefaultPartitionInfo=$y;zy.userAgentMiddleware=iA});var CA=Z((vG)=>{var{fromUtf8:bA,fromHex:XG,toHex:ls,toUint8Array:ii,isArrayBuffer:zG}=$t(),{normalizeProvider:TA}=Rn(),{escapeUri:Ie,HttpRequest:UA}=Ut();class LA{format(t){let n=[];for(let i of Object.keys(t)){let e=bA(i);n.push(Uint8Array.from([e.byteLength]),e,this.formatHeaderValue(t[i]))}let s=new Uint8Array(n.reduce((i,e)=>i+e.byteLength,0)),r=0;for(let i of n)s.set(i,r),r+=i.byteLength;return s}formatHeaderValue(t){switch(t.type){case"boolean":return Uint8Array.from([t.value?Wt.boolTrue:Wt.boolFalse]);case"byte":return Uint8Array.from([Wt.byte,t.value]);case"short":let n=new DataView(new ArrayBuffer(3));return n.setUint8(0,Wt.short),n.setInt16(1,t.value,!1),new Uint8Array(n.buffer);case"integer":let s=new DataView(new ArrayBuffer(5));return s.setUint8(0,Wt.integer),s.setInt32(1,t.value,!1),new Uint8Array(s.buffer);case"long":let r=new Uint8Array(9);return r[0]=Wt.long,r.set(t.value.bytes,1),r;case"binary":let i=new DataView(new ArrayBuffer(3+t.value.byteLength));i.setUint8(0,Wt.byteArray),i.setUint16(1,t.value.byteLength,!1);let e=new Uint8Array(i.buffer);return e.set(t.value,3),e;case"string":let f=bA(t.value),o=new DataView(new ArrayBuffer(3+f.byteLength));o.setUint8(0,Wt.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]=Wt.timestamp,h.set(Qc.fromNumber(t.value.valueOf()).bytes,1),h;case"uuid":if(!xG.test(t.value))throw Error(`Invalid UUID received: ${t.value}`);let u=new Uint8Array(17);return u[0]=Wt.uuid,u.set(XG(t.value.replace(/-/g,"")),1),u}}}var Wt;(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"})(Wt||(Wt={}));var xG=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class Qc{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)SA(n);return new Qc(n)}valueOf(){let t=this.bytes.slice(0),n=t[0]&128;if(n)SA(t);return parseInt(ls(t),16)*(n?-1:1)}toString(){return String(this.valueOf())}}function SA(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 IA="X-Amz-Algorithm",OA="X-Amz-Credential",Jc="X-Amz-Date",yA="X-Amz-SignedHeaders",GA="X-Amz-Expires",kc="X-Amz-Signature",Xc="X-Amz-Security-Token",qG="X-Amz-Region-Set",zc="authorization",xc=Jc.toLowerCase(),BA="date",FA=[zc,xc,BA],HA=kc.toLowerCase(),Fe="x-amz-content-sha256",PA=Xc.toLowerCase(),CG="host",NA={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},WA=/^proxy-/,DA=/^sec-/,KG=[/^proxy-/i,/^sec-/i],Oe="AWS4-HMAC-SHA256",VG="AWS4-ECDSA-P256-SHA256",YA="AWS4-HMAC-SHA256-PAYLOAD",mA="UNSIGNED-PAYLOAD",QA=50,qc="aws4_request",JA=604800,kA=({query:t={}})=>{let n=[],s={};for(let r of Object.keys(t)){if(r.toLowerCase()===HA)continue;let i=Ie(r);n.push(i);let e=t[r];if(typeof e==="string")s[i]=`${i}=${Ie(e)}`;else if(Array.isArray(e))s[i]=e.slice(0).reduce((f,o)=>f.concat([`${i}=${Ie(o)}`]),[]).sort().join("&")}return n.sort().map((r)=>s[r]).filter((r)=>r).join("&")},jG=(t)=>aG(t).toISOString().replace(/\.\d{3}Z$/,"Z"),aG=(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 Cc{service;regionProvider;credentialProvider;sha256;uriEscapePath;applyChecksum;constructor({applyChecksum:t,credentials:n,region:s,service:r,sha256:i,uriEscapePath:e=!0}){this.service=r,this.sha256=i,this.uriEscapePath=e,this.applyChecksum=typeof t==="boolean"?t:!0,this.regionProvider=TA(s),this.credentialProvider=TA(n)}createCanonicalRequest(t,n,s){let r=Object.keys(n).sort();return`${t.method}
|
|
31
|
-
${this.getCanonicalPath(
|
|
32
|
-
${
|
|
33
|
-
${
|
|
31
|
+
More information can be found at: https://a.co/c895JFp`)}},d3=()=>(n,t)=>async(i)=>{return t.__retryLongPoll=!0,n(i)},R3={name:"longPollMiddleware",tags:["RETRY"],step:"initialize",override:!0},E3=(n)=>({applyToStack:(t)=>{t.add(d3(),R3)}});function y3(n,t,i){if(!n.$source)n.$source={};return n.$source[t]=i,n}i3.v2026||=typeof process==="object"&&process.env?.AWS_NEW_RETRIES_2026==="true";function Lt(n,t,i){if(!n.__aws_sdk_context)n.__aws_sdk_context={features:{}};else if(!n.__aws_sdk_context.features)n.__aws_sdk_context.features={};n.__aws_sdk_context.features[t]=i}function T3(n,t,i){if(!n.$source)n.$source={};return n.$source[t]=i,n}function g3(n){return n}var cd=(n)=>(t)=>async(i)=>{if(!wc.isInstance(i.request))return t(i);let{request:s}=i,{handlerProtocol:r=""}=n.requestHandler.metadata||{};if(r.indexOf("h2")>=0&&!s.headers[":authority"])delete s.headers.host,s.headers[":authority"]=s.hostname+(s.port?":"+s.port:"");else if(!s.headers.host){let e=s.hostname;if(s.port!=null)e+=`:${s.port}`;s.headers.host=e}return t(i)},_d={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},S3=(n)=>({applyToStack:(t)=>{t.add(cd(n),_d)}}),wd=()=>(n,t)=>async(i)=>{try{let s=await n(i),{clientName:r,commandName:e,logger:f,dynamoDbDocumentClientOptions:o={}}=t,{overrideInputFilterSensitiveLog:h,overrideOutputFilterSensitiveLog:u}=o,c=h??t.inputFilterSensitiveLog,_=u??t.outputFilterSensitiveLog,{$metadata:w,...l}=s.output;return f?.info?.({clientName:r,commandName:e,input:c(i.input),output:_(l),metadata:w}),s}catch(s){let{clientName:r,commandName:e,logger:f,dynamoDbDocumentClientOptions:o={}}=t,{overrideInputFilterSensitiveLog:h}=o,u=h??t.inputFilterSensitiveLog;throw f?.error?.({clientName:r,commandName:e,input:u(i.input),error:s,metadata:s.$metadata}),s}},ld={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},I3=(n)=>({applyToStack:(t)=>{t.add(wd(),ld)}}),Ad={step:"build",tags:["RECURSION_DETECTION","TRACE_CONTEXT_PROPAGATION"],name:"recursionDetectionMiddleware",override:!0,priority:"low"},U3="AWS_LAMBDA_FUNCTION_NAME",b3="_X_AMZN_TRACE_ID",hc="X-Amzn-Trace-Id",_c="traceparent",Md="tracestate",dd="baggage",Rd=()=>(n)=>async(t)=>{let{request:i}=t;if(!wc.isInstance(i))return n(t);let s;{let r=Object.keys(i.headers??{}).find((e)=>e.toLowerCase()===hc.toLowerCase())??hc;if(!i.headers.hasOwnProperty(r)){let e=process.env[U3],f=process.env[b3];s??=await td.getInstanceAsync();let h=s?.getXRayTraceId()??f,u=(c)=>typeof c==="string"&&c.length>0;if(u(e)&&u(h))i.headers[hc]=h}}if($3(i.headers),!i.headers[_c]){let e=(s??=await td.getInstanceAsync())?.getTraceparent?.();if(e){i.headers[_c]=e;let f=s?.getTracestate?.();if(f)i.headers[Md]=f;let o=s?.getBaggage?.();if(o)i.headers[dd]=o}}return n(t)};function $3(n){for(let t of Object.keys(n)){let i=t.toLowerCase();if(t!==i&&(i===_c||i===Md||i===dd))n[i]=n[t],delete n[t]}}var L3=(n)=>({applyToStack:(t)=>{t.add(Rd(),Ad)}}),lc=void 0;function O3(n){if(n===void 0)return!0;return typeof n==="string"&&n.length<=50}function B3(n){let t=r3(n.userAgentAppId??lc),{customUserAgent:i}=n;return Object.assign(n,{customUserAgent:typeof i==="string"?[[i]]:i,userAgentAppId:async()=>{let s=await t();if(!O3(s)){let r=n.logger?.constructor?.name==="NoOpLogger"||!n.logger?console:n.logger;if(typeof s!=="string")r?.warn("userAgentAppId must be a string or undefined.");else if(s.length>50)r?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.")}return s}})}var Ed={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"},yd=Ed,Td="",gd=(n)=>{let{partitions:t}=yd;for(let s of t){let{regions:r,outputs:e}=s;for(let[f,o]of Object.entries(r))if(f===n)return{...e,...o}}for(let s of t){let{regionRegex:r,outputs:e}=s;if(new RegExp(r).test(n))return{...e}}let i=t.find((s)=>s.id==="aws");if(!i)throw Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");return{...i.outputs}},Sd=(n,t="")=>{yd=n,Td=t},N3=()=>{Sd(Ed,"")},Id=()=>Td,G3=/\d{12}\.ddb/;async function H3(n,t,i){if(i.request?.headers?.["smithy-protocol"]==="rpc-v2-cbor")Lt(n,"PROTOCOL_RPC_V2_CBOR","M");if(typeof t.retryStrategy==="function"){let e=await t.retryStrategy();if(typeof e.mode==="string")switch(e.mode){case nd.ADAPTIVE:Lt(n,"RETRY_MODE_ADAPTIVE","F");break;case nd.STANDARD:Lt(n,"RETRY_MODE_STANDARD","E");break}}if(typeof t.accountIdEndpointMode==="function"){let e=n.endpointV2;if(String(e?.url?.hostname).match(G3))Lt(n,"ACCOUNT_ID_ENDPOINT","O");switch(await t.accountIdEndpointMode?.()){case"disabled":Lt(n,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":Lt(n,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":Lt(n,"ACCOUNT_ID_MODE_REQUIRED","R");break}}let r=n.__smithy_context?.selectedHttpAuthScheme?.identity;if(r?.$source){let e=r;if(e.accountId)Lt(n,"RESOLVED_ACCOUNT_ID","T");for(let[f,o]of Object.entries(e.$source??{}))Lt(n,f,o)}}var sd="user-agent",uc="x-amz-user-agent",rd=" ",cc="/",W3=/[^!$%&'*+\-.^_`|~\w]/g,F3=/[^!$%&'*+\-.^_`|~\w#]/g,ed="-",P3=1024;function D3(n){let t="";for(let i in n){let s=n[i];if(t.length+s.length+1<=P3){if(t.length)t+=","+s;else t+=s;continue}break}return t}var Ud=(n)=>(t,i)=>async(s)=>{let{request:r}=s;if(!wc.isInstance(r))return t(s);let{headers:e}=r,f=i?.userAgent?.map(Po)||[],o=(await n.defaultUserAgentProvider()).map(Po);await H3(i,n,s);let h=i;o.push(`m/${D3(Object.assign({},i.__smithy_context?.features,h.__aws_sdk_context?.features))}`);let u=n?.customUserAgent?.map(Po)||[],c=await n.userAgentAppId();if(c)o.push(Po(["app",`${c}`]));let _=Id(),w=(_?[_]:[]).concat([...o,...f,...u]).join(rd),l=[...o.filter((A)=>A.startsWith("aws-sdk-")),...u].join(rd);if(n.runtime!=="browser"){if(l)e[uc]=e[uc]?`${e[sd]} ${l}`:l;e[sd]=w}else e[uc]=w;return t({...s,request:r})},Po=(n)=>{let t=n[0].split(cc).map((f)=>f.replace(W3,ed)).join(cc),i=n[1]?.replace(F3,ed),s=t.indexOf(cc),r=t.substring(0,s),e=t.substring(s+1);if(r==="api")e=e.toLowerCase();return[r,e,i].filter((f)=>f&&f.length>0).reduce((f,o,h)=>{switch(h){case 0:return o;case 1:return`${f}/${o}`;default:return`${f}#${o}`}},"")},bd={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},Y3=(n)=>({applyToStack:(t)=>{t.add(Ud(n),bd)}}),m3=()=>{let n=["deno","bun","llrt"];for(let t of n)if(fc[t])return[`md/${t}`,fc[t]];return["md/nodejs",fc.node]},$d={isCrtAvailable:!1},J3=()=>{if($d.isCrtAvailable)return["md/crt-avail"];return null},Ld=({serviceId:n,clientVersion:t})=>{let i=m3();return async(s)=>{let r=[["aws-sdk-js",t],["ua","2.1"],[`os/${e3()}`,o3()],["lang/js"],i],e=J3();if(e)r.push(e);if(n)r.push([`api/${n}`,t]);if(id.AWS_EXECUTION_ENV)r.push([`exec-env/${id.AWS_EXECUTION_ENV}`]);let f=await s?.userAgentAppId?.();return f?[...r,[`app/${f}`]]:[...r]}},X3=Ld,Od="AWS_SDK_UA_APP_ID",Bd="sdk_ua_app_id",z3="sdk-ua-app-id",Q3={environmentVariableSelector:(n)=>n[Od],configFileSelector:(n)=>n[Bd]??n[z3],default:lc},C3=({serviceId:n,clientVersion:t})=>async(i)=>{let s=pM(),r=s.parse??s.default.parse??(()=>""),e=typeof window<"u"&&window?.navigator?.userAgent?r(window.navigator.userAgent):void 0,f=[["aws-sdk-js",t],["ua","2.1"],[`os/${e?.os?.name||"other"}`,e?.os?.version],["lang/js"],["md/browser",`${e?.browser?.name??"unknown"}_${e?.browser?.version??"unknown"}`]];if(n)f.push([`api/${n}`,t]);let o=await i?.userAgentAppId?.();if(o)f.push([`app/${o}`]);return f},x3={os(n){if(/iPhone|iPad|iPod/.test(n))return"iOS";if(/Macintosh|Mac OS X/.test(n))return"macOS";if(/Windows NT/.test(n))return"Windows";if(/Android/.test(n))return"Android";if(/Linux/.test(n))return"Linux";return},browser(n){if(/EdgiOS|EdgA|Edg\//.test(n))return"Microsoft Edge";if(/Firefox\//.test(n))return"Firefox";if(/Chrome\//.test(n))return"Chrome";if(/Safari\//.test(n))return"Safari";return}},Ac=(n,t=!1)=>{if(t){for(let i of n.split("."))if(!Ac(i))return!1;return!0}if(!f3(n))return!1;if(n.length<3||n.length>63)return!1;if(n!==n.toLowerCase())return!1;if(fd(n))return!1;return!0},od=":",K3="/",Nd=(n)=>{let t=n.split(od);if(t.length<6)return null;let[i,s,r,e,f,...o]=t;if(i!=="arn"||s===""||r===""||o.join(od)==="")return null;let h=o.map((u)=>u.split(K3)).flat();return{partition:s,service:r,region:e,accountId:f,resourceId:h}},Gd={isVirtualHostableS3Bucket:Ac,parseArn:Nd,partition:gd};h3.aws=Gd;var k3=(n)=>{if(typeof n.endpointProvider!=="function")throw Error("@aws-sdk/util-endpoint - endpointProvider and endpoint missing in config for this client.");let{endpoint:t}=n;if(t===void 0)n.endpoint=async()=>{return Hd(n.endpointProvider({Region:typeof n.region==="function"?await n.region():n.region,UseDualStack:typeof n.useDualstackEndpoint==="function"?await n.useDualstackEndpoint():n.useDualstackEndpoint,UseFIPS:typeof n.useFipsEndpoint==="function"?await n.useFipsEndpoint():n.useFipsEndpoint,Endpoint:void 0},{logger:n.logger}))};return n},Hd=(n)=>s3(n.url);function q3(n={}){return _3({...hd,async default(){if(!Wd.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"}},{...ud,...n})}var Wd={silence:!1},V3=(n)=>{return{setRegion(t){n.region=t},region(){return n.region}}},j3=(n)=>{return{region:n.region()}};a3.DEFAULT_UA_APP_ID=lc;a3.NODE_APP_ID_CONFIG_OPTIONS=Q3;a3.UA_APP_ID_ENV_NAME=Od;a3.UA_APP_ID_INI_NAME=Bd;a3.awsEndpointFunctions=Gd;a3.createDefaultUserAgentProvider=Ld;a3.createUserAgentStringParsingProvider=C3;a3.crtAvailability=$d;a3.defaultUserAgent=X3;a3.emitWarningIfUnsupportedVersion=M3;a3.fallback=x3;a3.getAwsRegionExtensionConfiguration=V3;a3.getHostHeaderPlugin=S3;a3.getLoggerPlugin=I3;a3.getLongPollPlugin=E3;a3.getRecursionDetectionPlugin=L3;a3.getUserAgentMiddlewareOptions=bd;a3.getUserAgentPlugin=Y3;a3.getUserAgentPrefix=Id;a3.hostHeaderMiddleware=cd;a3.hostHeaderMiddlewareOptions=_d;a3.isVirtualHostableS3Bucket=Ac;a3.loggerMiddleware=wd;a3.loggerMiddlewareOptions=ld;a3.parseArn=Nd;a3.partition=gd;a3.recursionDetectionMiddleware=Rd;a3.recursionDetectionMiddlewareOptions=Ad;a3.resolveAwsRegionExtensionConfiguration=j3;a3.resolveDefaultAwsRegionalEndpointsConfig=k3;a3.resolveHostHeaderConfig=g3;a3.resolveUserAgentConfig=B3;a3.setCredentialFeature=y3;a3.setFeature=Lt;a3.setPartitionInfo=Sd;a3.setTokenFeature=T3;a3.state=Do;a3.stsRegionDefaultResolver=q3;a3.stsRegionWarning=Wd;a3.toEndpointV1=Hd;a3.useDefaultPartitionInfo=N3;a3.userAgentMiddleware=Ud});var w1=k((oW)=>{var{fromUtf8:Xd,fromHex:jH,toHex:xi,toUint8Array:se,isArrayBuffer:aH}=mn(),{normalizeProvider:zd}=Xt(),{escapeUri:Yo,HttpRequest:xd}=Jn();class Kd{format(n){let t=[];for(let r of Object.keys(n)){let e=Xd(r);t.push(Uint8Array.from([e.byteLength]),e,this.formatHeaderValue(n[r]))}let i=new Uint8Array(t.reduce((r,e)=>r+e.byteLength,0)),s=0;for(let r of t)i.set(r,s),s+=r.byteLength;return i}formatHeaderValue(n){switch(n.type){case"boolean":return Uint8Array.from([n.value?pn.boolTrue:pn.boolFalse]);case"byte":return Uint8Array.from([pn.byte,n.value]);case"short":let t=new DataView(new ArrayBuffer(3));return t.setUint8(0,pn.short),t.setInt16(1,n.value,!1),new Uint8Array(t.buffer);case"integer":let i=new DataView(new ArrayBuffer(5));return i.setUint8(0,pn.integer),i.setInt32(1,n.value,!1),new Uint8Array(i.buffer);case"long":let s=new Uint8Array(9);return s[0]=pn.long,s.set(n.value.bytes,1),s;case"binary":let r=new DataView(new ArrayBuffer(3+n.value.byteLength));r.setUint8(0,pn.byteArray),r.setUint16(1,n.value.byteLength,!1);let e=new Uint8Array(r.buffer);return e.set(n.value,3),e;case"string":let f=Xd(n.value),o=new DataView(new ArrayBuffer(3+f.byteLength));o.setUint8(0,pn.string),o.setUint16(1,f.byteLength,!1);let h=new Uint8Array(o.buffer);return h.set(f,3),h;case"timestamp":let u=new Uint8Array(9);return u[0]=pn.timestamp,u.set(Ec.fromNumber(n.value.valueOf()).bytes,1),u;case"uuid":if(!vH.test(n.value))throw Error(`Invalid UUID received: ${n.value}`);let c=new Uint8Array(17);return c[0]=pn.uuid,c.set(jH(n.value.replace(/-/g,"")),1),c}}}var pn;(function(n){n[n.boolTrue=0]="boolTrue",n[n.boolFalse=1]="boolFalse",n[n.byte=2]="byte",n[n.short=3]="short",n[n.integer=4]="integer",n[n.long=5]="long",n[n.byteArray=6]="byteArray",n[n.string=7]="string",n[n.timestamp=8]="timestamp",n[n.uuid=9]="uuid"})(pn||(pn={}));var vH=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class Ec{bytes;constructor(n){if(this.bytes=n,n.byteLength!==8)throw Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(n){if(n>9223372036854776000||n<-9223372036854776000)throw Error(`${n} is too large (or, if negative, too small) to represent as an Int64`);let t=new Uint8Array(8);for(let i=7,s=Math.abs(Math.round(n));i>-1&&s>0;i--,s/=256)t[i]=s;if(n<0)Qd(t);return new Ec(t)}valueOf(){let n=this.bytes.slice(0),t=n[0]&128;if(t)Qd(n);return parseInt(xi(n),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function Qd(n){for(let t=0;t<8;t++)n[t]^=255;for(let t=7;t>-1;t--)if(n[t]++,n[t]!==0)break}var kd="X-Amz-Algorithm",qd="X-Amz-Credential",yc="X-Amz-Date",Vd="X-Amz-SignedHeaders",jd="X-Amz-Expires",Tc="X-Amz-Signature",gc="X-Amz-Security-Token",ZH="X-Amz-Region-Set",Sc="authorization",Ic=yc.toLowerCase(),ad="date",vd=[Sc,Ic,ad],Zd=Tc.toLowerCase(),Qo="x-amz-content-sha256",pd=gc.toLowerCase(),pH="host",n1={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},t1=/^proxy-/,i1=/^sec-/,nW=[/^proxy-/i,/^sec-/i],mo="AWS4-HMAC-SHA256",tW="AWS4-ECDSA-P256-SHA256",s1="AWS4-HMAC-SHA256-PAYLOAD",r1="UNSIGNED-PAYLOAD",e1=50,Uc="aws4_request",o1=604800,f1=({query:n={}})=>{let t=[],i={};for(let s of Object.keys(n)){if(s.toLowerCase()===Zd)continue;let r=Yo(s);t.push(r);let e=n[s];if(typeof e==="string")i[r]=`${r}=${Yo(e)}`;else if(Array.isArray(e))i[r]=e.slice(0).reduce((f,o)=>f.concat([`${r}=${Yo(o)}`]),[]).sort().join("&")}return t.sort().map((s)=>i[s]).filter((s)=>s).join("&")},iW=(n)=>sW(n).toISOString().replace(/\.\d{3}Z$/,"Z"),sW=(n)=>{if(typeof n==="number")return new Date(n*1000);if(typeof n==="string"){if(Number(n))return new Date(Number(n)*1000);return new Date(n)}return n};class bc{service;regionProvider;credentialProvider;sha256;uriEscapePath;applyChecksum;constructor({applyChecksum:n,credentials:t,region:i,service:s,sha256:r,uriEscapePath:e=!0}){this.service=s,this.sha256=r,this.uriEscapePath=e,this.applyChecksum=typeof n==="boolean"?n:!0,this.regionProvider=zd(i),this.credentialProvider=zd(t)}createCanonicalRequest(n,t,i){let s=Object.keys(t).sort();return`${n.method}
|
|
32
|
+
${this.getCanonicalPath(n)}
|
|
33
|
+
${f1(n)}
|
|
34
|
+
${s.map((r)=>`${r}:${t[r]}`).join(`
|
|
34
35
|
`)}
|
|
35
36
|
|
|
36
|
-
${
|
|
37
|
-
${
|
|
38
|
-
${t}
|
|
37
|
+
${s.join(";")}
|
|
38
|
+
${i}`}async createStringToSign(n,t,i,s){let r=new this.sha256;r.update(se(i));let e=await r.digest();return`${s}
|
|
39
39
|
${n}
|
|
40
|
-
${
|
|
41
|
-
`);return this.signString(A,{signingDate:s,signingRegion:o,signingService:e,eventStreamCredentials:f})}async signMessage(t,{signingDate:n=new Date,signingRegion:s,signingService:r,eventStreamCredentials:i}){return this.signEvent({headers:this.headerFormatter.format(t.message.headers),payload:t.message.body},{signingDate:n,signingRegion:s,signingService:r,priorSignature:t.priorSignature,eventStreamCredentials:i}).then((f)=>{return{message:t.message,signature:f}})}async signString(t,{signingDate:n=new Date,signingRegion:s,signingService:r,eventStreamCredentials:i}={}){let e=i??await this.credentialProvider();this.validateResolvedCredentials(e);let f=s??await this.regionProvider(),{shortDate:o}=this.formatDate(n),c=new this.sha256(await this.getSigningKey(e,f,o,r));return c.update(ii(t)),ls(await c.digest())}async signRequest(t,{signingDate:n=new Date,signableHeaders:s,unsignableHeaders:r,signingRegion:i,signingService:e}={}){let f=await this.credentialProvider();this.validateResolvedCredentials(f);let o=i??await this.regionProvider(),c=mc(t),{longDate:h,shortDate:u}=this.formatDate(n),_=Ge(u,o,e??this.service);if(c.headers[xc]=h,f.sessionToken)c.headers[PA]=f.sessionToken;let l=await Be(c,this.sha256);if(!zA(Fe,c.headers)&&this.applyChecksum)c.headers[Fe]=l;let w=Yc(c,r,s),A=await this.getSignature(h,_,this.getSigningKey(f,o,u,e),this.createCanonicalRequest(c,w,l));return c.headers[zc]=`${Oe} Credential=${f.accessKeyId}/${_}, SignedHeaders=${this.getCanonicalHeaderList(w)}, Signature=${A}`,c}async getSignature(t,n,s,r){let i=await this.createStringToSign(t,n,r,Oe),e=new this.sha256(await s);return e.update(ii(i)),ls(await e.digest())}getSigningKey(t,n,s,r){return XA(this.sha256,t,s,n,r||this.service)}}var ZG={SignatureV4a:null};vG.ALGORITHM_IDENTIFIER=Oe;vG.ALGORITHM_IDENTIFIER_V4A=VG;vG.ALGORITHM_QUERY_PARAM=IA;vG.ALWAYS_UNSIGNABLE_HEADERS=NA;vG.AMZ_DATE_HEADER=xc;vG.AMZ_DATE_QUERY_PARAM=Jc;vG.AUTH_HEADER=zc;vG.CREDENTIAL_QUERY_PARAM=OA;vG.DATE_HEADER=BA;vG.EVENT_ALGORITHM_IDENTIFIER=YA;vG.EXPIRES_QUERY_PARAM=GA;vG.GENERATED_HEADERS=FA;vG.HOST_HEADER=CG;vG.KEY_TYPE_IDENTIFIER=qc;vG.MAX_CACHE_SIZE=QA;vG.MAX_PRESIGNED_TTL=JA;vG.PROXY_HEADER_PATTERN=WA;vG.REGION_SET_PARAM=qG;vG.SEC_HEADER_PATTERN=DA;vG.SHA256_HEADER=Fe;vG.SIGNATURE_HEADER=HA;vG.SIGNATURE_QUERY_PARAM=kc;vG.SIGNED_HEADERS_QUERY_PARAM=yA;vG.SignatureV4=qA;vG.SignatureV4Base=Cc;vG.TOKEN_HEADER=PA;vG.TOKEN_QUERY_PARAM=Xc;vG.UNSIGNABLE_PATTERNS=KG;vG.UNSIGNED_PAYLOAD=mA;vG.clearCredentialCache=pG;vG.createScope=Ge;vG.getCanonicalHeaders=Yc;vG.getCanonicalQuery=kA;vG.getPayloadHash=Be;vG.getSigningKey=XA;vG.hasHeader=zA;vG.moveHeadersToQuery=xA;vG.prepareRequest=mc;vG.signatureV4aContainer=ZG});var jc=Z((ZB)=>{var{HttpResponse:QB,HttpRequest:tM}=Ut(),{normalizeProvider:ei,memoizeIdentityProvider:JB,isIdentityExpired:kB,doesIdentityRequireRefresh:XB}=kn(),{ProviderError:KA}=St(),{setCredentialFeature:zB}=xt(),{SignatureV4:VA}=CA(),jA=(t)=>QB.isInstance(t)?t.headers?.date??t.headers?.Date:void 0,Kc=(t)=>new Date(Date.now()+t),xB=(t,n)=>Math.abs(Kc(n).getTime()-t)>=300000,aA=(t,n)=>{let s=Date.parse(t);if(xB(s,n))return s-Date.now();return n},oi=(t,n)=>{if(!n)throw Error(`Property \`${t}\` is not resolved for AWS SDK SigV4Auth`);return n},Vc=async(t)=>{let n=oi("context",t.context),s=oi("config",t.config),r=n.endpointV2?.properties?.authSchemes?.[0],e=await oi("signer",s.signer)(r),f=t?.signingRegion,o=t?.signingRegionSet,c=t?.signingName;return{config:s,signer:e,signingRegion:f,signingRegionSet:o,signingName:c}};class He{async sign(t,n,s){if(!tM.isInstance(t))throw Error("The request is not an instance of `HttpRequest` and cannot be signed");let r=await Vc(s),{config:i,signer:e}=r,{signingRegion:f,signingName:o}=r,c=s.context;if(c?.authSchemes?.length??!1){let[u,_]=c.authSchemes;if(u?.name==="sigv4a"&&_?.name==="sigv4")f=_?.signingRegion??f,o=_?.signingName??o}return s._preRequestSystemClockOffset=i.systemClockOffset,await e.sign(t,{signingDate:Kc(i.systemClockOffset),signingRegion:f,signingService:o})}errorHandler(t){return(n)=>{let s=n,r=s.ServerTime??jA(s.$response);if(r){let i=oi("config",t.config),e=t._preRequestSystemClockOffset,f=aA(r,i.systemClockOffset);if((f!==i.systemClockOffset||e!==void 0&&e!==f)&&s.$metadata)i.systemClockOffset=f,s.$metadata.clockSkewCorrected=!0}throw n}}successHandler(t,n){let s=jA(t);if(s){let r=oi("config",n.config);r.systemClockOffset=aA(s,r.systemClockOffset)}}}var qB=He;class nM extends He{async sign(t,n,s){if(!tM.isInstance(t))throw Error("The request is not an instance of `HttpRequest` and cannot be signed");let{config:r,signer:i,signingRegion:e,signingRegionSet:f,signingName:o}=await Vc(s),h=(await r.sigv4aSigningRegionSet?.()??f??[e]).join(",");return s._preRequestSystemClockOffset=r.systemClockOffset,await i.sign(t,{signingDate:Kc(r.systemClockOffset),signingRegion:h,signingService:o})}}var pA=(t)=>typeof t==="string"&&t.length>0?t.split(",").map((n)=>n.trim()):[],sM=(t)=>`AWS_BEARER_TOKEN_${t.replace(/[\s-]/g,"_").toUpperCase()}`,ZA="AWS_AUTH_SCHEME_PREFERENCE",vA="auth_scheme_preference",CB={environmentVariableSelector:(t,n)=>{if(n?.signingName){if(sM(n.signingName)in t)return["httpBearerAuth"]}if(!(ZA in t))return;return pA(t[ZA])},configFileSelector:(t)=>{if(!(vA in t))return;return pA(t[vA])},default:[]},KB=(t)=>{return t.sigv4aSigningRegionSet=ei(t.sigv4aSigningRegionSet),t},VB={environmentVariableSelector(t){if(t.AWS_SIGV4A_SIGNING_REGION_SET)return t.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((n)=>n.trim());throw new KA("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 KA("sigv4a_signing_region_set not set in profile.",{tryNextLink:!0})},default:void 0},rM=(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=aB(t,{credentials:n,credentialDefaultProvider:t.credentialDefaultProvider}),_=pB(t,u);if(s&&!_.attributed){let l=typeof n==="object"&&n!==null;r=async(w)=>{let M=await _(w);if(l&&(!M.$source||Object.keys(M.$source).length===0))return zB(M,"CREDENTIALS_CODE","e");return M},r.memoized=_.memoized,r.configBound=_.configBound,r.attributed=!0}else r=_},get(){return r},enumerable:!0,configurable:!0}),t.credentials=n;let{signingEscapePath:i=!0,systemClockOffset:e=t.systemClockOffset||0,sha256:f}=t,o;if(t.signer)o=ei(t.signer);else if(t.regionInfoProvider)o=()=>ei(t.region)().then(async(h)=>[await t.regionInfoProvider(h,{useFipsEndpoint:await t.useFipsEndpoint(),useDualstackEndpoint:await t.useDualstackEndpoint()})||{},h]).then(([h,u])=>{let{signingRegion:_,signingService:l}=h;t.signingRegion=t.signingRegion||_||u,t.signingName=t.signingName||l||t.serviceId;let w={...t,credentials:t.credentials,region:t.signingRegion,service:t.signingName,sha256:f,uriEscapePath:i};return new(t.signerConstructor||VA)(w)});else o=async(h)=>{h=Object.assign({},{name:"sigv4",signingName:t.signingName||t.defaultSigningName,signingRegion:await ei(t.region)(),properties:{}},h);let{signingRegion:u,signingName:_}=h;t.signingRegion=t.signingRegion||u,t.signingName=t.signingName||_||t.serviceId;let l={...t,credentials:t.credentials,region:t.signingRegion,service:t.signingName,sha256:f,uriEscapePath:i};return new(t.signerConstructor||VA)(l)};return Object.assign(t,{systemClockOffset:e,signingEscapePath:i,signer:o})},jB=rM;function aB(t,{credentials:n,credentialDefaultProvider:s}){let r;if(n)if(!n?.memoized)r=JB(n,kB,XB);else r=n;else if(s)r=ei(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 pB(t,n){if(n.configBound)return n;let s=async(r)=>n({...r,callerClientConfig:t});return s.memoized=n.memoized,s.configBound=!0,s}ZB.AWSSDKSigV4Signer=qB;ZB.AwsSdkSigV4ASigner=nM;ZB.AwsSdkSigV4Signer=He;ZB.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS=CB;ZB.NODE_SIGV4A_CONFIG_OPTIONS=VB;ZB.getBearerTokenEnvKey=sM;ZB.resolveAWSSDKSigV4Config=jB;ZB.resolveAwsSdkSigV4AConfig=KB;ZB.resolveAwsSdkSigV4Config=rM;ZB.validateSigningProperties=Vc});var me=Z((b3)=>{var{buildQueryString:uM,HttpResponse:_M}=Ut(),Pe=nt("https"),{Readable:h3}=nt("stream"),ac=nt("http2"),{streamCollector:u3}=$t();b3.streamCollector=u3;function We(t){let n=t&&typeof t==="object"&&"reason"in t?t.reason:void 0;if(n){if(n instanceof Error){let i=Error("Request aborted");return i.name="AbortError",i.cause=n,i}let r=Error(String(n));return r.name="AbortError",r}let s=Error("Request aborted");return s.name="AbortError",s}var _3=["ECONNRESET","EPIPE","ETIMEDOUT"],lM=(t)=>{let n={};for(let s in t){let r=t[s];n[s]=Array.isArray(r)?r.join(","):r}return n},Mt={setTimeout:(t,n)=>setTimeout(t,n),clearTimeout:(t)=>clearTimeout(t)},eM=1000,l3=(t,n,s=0)=>{if(!s)return-1;let r=(i)=>{let e=Mt.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-i),f=(o)=>{if(o?.connecting)o.on("connect",()=>{Mt.clearTimeout(e)});else Mt.clearTimeout(e)};if(t.socket)f(t.socket);else t.on("socket",f)};if(s<2000)return r(0),0;return Mt.setTimeout(r.bind(null,eM),eM)},w3=(t,n,s=0,r,i)=>{if(s)return Mt.setTimeout(()=>{let e=`@smithy/node-http-handler - [${r?"ERROR":"WARN"}] a request has exceeded the configured ${s} ms requestTimeout.`;if(r){let f=Object.assign(Error(e),{name:"TimeoutError",code:"ETIMEDOUT"});t.destroy(f),n(f)}else e+=" Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.",i?.warn?.(e)},s);return-1},A3=3000,M3=(t,{keepAlive:n,keepAliveMsecs:s},r=A3)=>{if(n!==!0)return-1;let i=()=>{if(t.socket)t.socket.setKeepAlive(n,s||0);else t.on("socket",(e)=>{e.setKeepAlive(n,s||0)})};if(r===0)return i(),0;return Mt.setTimeout(i,r)},oM=3000,g3=(t,n,s=0)=>{let r=(i)=>{let e=s-i,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(e,f),t.on("close",()=>t.socket?.removeListener("timeout",f));else t.setTimeout(e,f)};if(0<s&&s<6000)return r(0),0;return Mt.setTimeout(r.bind(null,s===0?0:oM),oM)},fM=6000;async function wM(t,n,s=fM,r=!1){let i=n.headers,e=i?i.Expect||i.expect:void 0,f=-1,o=!0;if(!r&&e==="100-continue")o=await Promise.race([new Promise((c)=>{f=Number(Mt.setTimeout(()=>c(!0),Math.max(fM,s)))}),new Promise((c)=>{t.on("continue",()=>{Mt.clearTimeout(f),c(!0)}),t.on("response",()=>{Mt.clearTimeout(f),c(!1)}),t.on("error",()=>{Mt.clearTimeout(f),c(!1)})})]);if(o)E3(t,n.body)}function E3(t,n){if(n instanceof h3){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 i=n;if(typeof i==="object"&&i.buffer&&typeof i.byteOffset==="number"&&typeof i.byteLength==="number"){t.end(Buffer.from(i.buffer,i.byteOffset,i.byteLength));return}t.end(Buffer.from(n));return}t.end()}var d3=0,Ne=void 0,cM=void 0;class De{config;configProvider;socketWarningTimestamp=0;externalAgent=!1;metadata={handlerProtocol:"http/1.1"};static create(t){if(typeof t?.handle==="function")return t;return new De(t)}static checkSocketUsage(t,n,s=console){let{sockets:r,requests:i,maxSockets:e}=t;if(typeof e!=="number"||e===1/0)return n;let f=15000;if(Date.now()-f<n)return n;if(r&&i)for(let o in r){let c=r[o]?.length??0,h=i[o]?.length??0;if(c>=e&&h>=2*e)return s?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${c} and ${h} additional requests are enqueued.
|
|
40
|
+
${t}
|
|
41
|
+
${xi(e)}`}getCanonicalPath({path:n}){if(this.uriEscapePath){let t=[];for(let r of n.split("/")){if(r?.length===0)continue;if(r===".")continue;if(r==="..")t.pop();else t.push(r)}let i=`${n?.startsWith("/")?"/":""}${t.join("/")}${t.length>0&&n?.endsWith("/")?"/":""}`;return Yo(i).replace(/%2F/g,"/")}return n}validateResolvedCredentials(n){if(typeof n!=="object"||typeof n.accessKeyId!=="string"||typeof n.secretAccessKey!=="string")throw Error("Resolved credential object is not valid")}formatDate(n){let t=iW(n).replace(/[-:]/g,"");return{longDate:t,shortDate:t.slice(0,8)}}getCanonicalHeaderList(n){return Object.keys(n).sort().join(";")}}var Cs={},Jo=[],Xo=(n,t,i)=>`${n}/${t}/${i}/${Uc}`,h1=async(n,t,i,s,r)=>{let e=await Cd(n,t.secretAccessKey,t.accessKeyId),f=`${i}:${s}:${r}:${xi(e)}:${t.sessionToken}`;if(f in Cs)return Cs[f];Jo.push(f);while(Jo.length>e1)delete Cs[Jo.shift()];let o=`AWS4${t.secretAccessKey}`;for(let h of[i,s,r,Uc])o=await Cd(n,o,h);return Cs[f]=o},rW=()=>{Jo.length=0,Object.keys(Cs).forEach((n)=>{delete Cs[n]})},Cd=(n,t,i)=>{let s=new n(t);return s.update(se(i)),s.digest()},dc=({headers:n},t,i)=>{let s={};for(let r of Object.keys(n).sort()){if(n[r]==null)continue;let e=r.toLowerCase();if(e in n1||t?.has(e)||t1.test(e)||i1.test(e)){if(!i||i&&!i.has(e))continue}s[e]=n[r].trim().replace(/\s+/g," ")}return s},zo=async({headers:n,body:t},i)=>{for(let s of Object.keys(n))if(s.toLowerCase()===Qo)return n[s];if(t==null)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";else if(typeof t==="string"||ArrayBuffer.isView(t)||aH(t)){let s=new i;return s.update(se(t)),xi(await s.digest())}return r1},u1=(n,t)=>{n=n.toLowerCase();for(let i of Object.keys(t))if(n===i.toLowerCase())return!0;return!1},c1=(n,t={})=>{let{headers:i,query:s={}}=xd.clone(n);for(let r of Object.keys(i)){let e=r.toLowerCase();if(e.slice(0,6)==="x-amz-"&&!t.unhoistableHeaders?.has(e)||t.hoistableHeaders?.has(e))s[r]=i[r],delete i[r]}return{...n,headers:i,query:s}},Rc=(n)=>{n=xd.clone(n);for(let t of Object.keys(n.headers))if(vd.indexOf(t.toLowerCase())>-1)delete n.headers[t];return n};class _1 extends bc{headerFormatter=new Kd;constructor({applyChecksum:n,credentials:t,region:i,service:s,sha256:r,uriEscapePath:e=!0}){super({applyChecksum:n,credentials:t,region:i,service:s,sha256:r,uriEscapePath:e})}async presign(n,t={}){let{signingDate:i=new Date,expiresIn:s=3600,unsignableHeaders:r,unhoistableHeaders:e,signableHeaders:f,hoistableHeaders:o,signingRegion:h,signingService:u}=t,c=await this.credentialProvider();this.validateResolvedCredentials(c);let _=h??await this.regionProvider(),{longDate:w,shortDate:l}=this.formatDate(i);if(s>o1)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");let A=Xo(l,_,u??this.service),d=c1(Rc(n),{unhoistableHeaders:e,hoistableHeaders:o});if(c.sessionToken)d.query[gc]=c.sessionToken;d.query[kd]=mo,d.query[qd]=`${c.accessKeyId}/${A}`,d.query[yc]=w,d.query[jd]=s.toString(10);let E=dc(d,r,f);return d.query[Vd]=this.getCanonicalHeaderList(E),d.query[Tc]=await this.getSignature(w,A,this.getSigningKey(c,_,l,u),this.createCanonicalRequest(d,E,await zo(n,this.sha256))),d}async sign(n,t){if(typeof n==="string")return this.signString(n,t);else if(n.headers&&n.payload)return this.signEvent(n,t);else if(n.message)return this.signMessage(n,t);else return this.signRequest(n,t)}async signEvent({headers:n,payload:t},{signingDate:i=new Date,priorSignature:s,signingRegion:r,signingService:e,eventStreamCredentials:f}){let o=r??await this.regionProvider(),{shortDate:h,longDate:u}=this.formatDate(i),c=Xo(h,o,e??this.service),_=await zo({headers:{},body:t},this.sha256),w=new this.sha256;w.update(n);let l=xi(await w.digest()),A=[s1,u,c,s,l,_].join(`
|
|
42
|
+
`);return this.signString(A,{signingDate:i,signingRegion:o,signingService:e,eventStreamCredentials:f})}async signMessage(n,{signingDate:t=new Date,signingRegion:i,signingService:s,eventStreamCredentials:r}){return this.signEvent({headers:this.headerFormatter.format(n.message.headers),payload:n.message.body},{signingDate:t,signingRegion:i,signingService:s,priorSignature:n.priorSignature,eventStreamCredentials:r}).then((f)=>{return{message:n.message,signature:f}})}async signString(n,{signingDate:t=new Date,signingRegion:i,signingService:s,eventStreamCredentials:r}={}){let e=r??await this.credentialProvider();this.validateResolvedCredentials(e);let f=i??await this.regionProvider(),{shortDate:o}=this.formatDate(t),h=new this.sha256(await this.getSigningKey(e,f,o,s));return h.update(se(n)),xi(await h.digest())}async signRequest(n,{signingDate:t=new Date,signableHeaders:i,unsignableHeaders:s,signingRegion:r,signingService:e}={}){let f=await this.credentialProvider();this.validateResolvedCredentials(f);let o=r??await this.regionProvider(),h=Rc(n),{longDate:u,shortDate:c}=this.formatDate(t),_=Xo(c,o,e??this.service);if(h.headers[Ic]=u,f.sessionToken)h.headers[pd]=f.sessionToken;let w=await zo(h,this.sha256);if(!u1(Qo,h.headers)&&this.applyChecksum)h.headers[Qo]=w;let l=dc(h,s,i),A=await this.getSignature(u,_,this.getSigningKey(f,o,c,e),this.createCanonicalRequest(h,l,w));return h.headers[Sc]=`${mo} Credential=${f.accessKeyId}/${_}, SignedHeaders=${this.getCanonicalHeaderList(l)}, Signature=${A}`,h}async getSignature(n,t,i,s){let r=await this.createStringToSign(n,t,s,mo),e=new this.sha256(await i);return e.update(se(r)),xi(await e.digest())}getSigningKey(n,t,i,s){return h1(this.sha256,n,i,t,s||this.service)}}var eW={SignatureV4a:null};oW.ALGORITHM_IDENTIFIER=mo;oW.ALGORITHM_IDENTIFIER_V4A=tW;oW.ALGORITHM_QUERY_PARAM=kd;oW.ALWAYS_UNSIGNABLE_HEADERS=n1;oW.AMZ_DATE_HEADER=Ic;oW.AMZ_DATE_QUERY_PARAM=yc;oW.AUTH_HEADER=Sc;oW.CREDENTIAL_QUERY_PARAM=qd;oW.DATE_HEADER=ad;oW.EVENT_ALGORITHM_IDENTIFIER=s1;oW.EXPIRES_QUERY_PARAM=jd;oW.GENERATED_HEADERS=vd;oW.HOST_HEADER=pH;oW.KEY_TYPE_IDENTIFIER=Uc;oW.MAX_CACHE_SIZE=e1;oW.MAX_PRESIGNED_TTL=o1;oW.PROXY_HEADER_PATTERN=t1;oW.REGION_SET_PARAM=ZH;oW.SEC_HEADER_PATTERN=i1;oW.SHA256_HEADER=Qo;oW.SIGNATURE_HEADER=Zd;oW.SIGNATURE_QUERY_PARAM=Tc;oW.SIGNED_HEADERS_QUERY_PARAM=Vd;oW.SignatureV4=_1;oW.SignatureV4Base=bc;oW.TOKEN_HEADER=pd;oW.TOKEN_QUERY_PARAM=gc;oW.UNSIGNABLE_PATTERNS=nW;oW.UNSIGNED_PAYLOAD=r1;oW.clearCredentialCache=rW;oW.createScope=Xo;oW.getCanonicalHeaders=dc;oW.getCanonicalQuery=f1;oW.getPayloadHash=zo;oW.getSigningKey=h1;oW.hasHeader=u1;oW.moveHeadersToQuery=c1;oW.prepareRequest=Rc;oW.signatureV4aContainer=eW});var Oc=k((eF)=>{var{HttpResponse:kW,HttpRequest:T1}=Jn(),{normalizeProvider:re,memoizeIdentityProvider:qW,isIdentityExpired:VW,doesIdentityRequireRefresh:jW}=_i(),{ProviderError:l1}=Yn(),{setCredentialFeature:aW}=ct(),{SignatureV4:A1}=w1(),M1=(n)=>kW.isInstance(n)?n.headers?.date??n.headers?.Date:void 0,$c=(n)=>new Date(Date.now()+n),vW=(n,t)=>Math.abs($c(t).getTime()-n)>=300000,d1=(n,t)=>{let i=Date.parse(n);if(vW(i,t))return i-Date.now();return t},ee=(n,t)=>{if(!t)throw Error(`Property \`${n}\` is not resolved for AWS SDK SigV4Auth`);return t},Lc=async(n)=>{let t=ee("context",n.context),i=ee("config",n.config),s=t.endpointV2?.properties?.authSchemes?.[0],e=await ee("signer",i.signer)(s),f=n?.signingRegion,o=n?.signingRegionSet,h=n?.signingName;return{config:i,signer:e,signingRegion:f,signingRegionSet:o,signingName:h}};class Co{async sign(n,t,i){if(!T1.isInstance(n))throw Error("The request is not an instance of `HttpRequest` and cannot be signed");let s=await Lc(i),{config:r,signer:e}=s,{signingRegion:f,signingName:o}=s,h=i.context;if(h?.authSchemes?.length??!1){let[c,_]=h.authSchemes;if(c?.name==="sigv4a"&&_?.name==="sigv4")f=_?.signingRegion??f,o=_?.signingName??o}return i._preRequestSystemClockOffset=r.systemClockOffset,await e.sign(n,{signingDate:$c(r.systemClockOffset),signingRegion:f,signingService:o})}errorHandler(n){return(t)=>{let i=t,s=i.ServerTime??M1(i.$response);if(s){let r=ee("config",n.config),e=n._preRequestSystemClockOffset,f=d1(s,r.systemClockOffset);if((f!==r.systemClockOffset||e!==void 0&&e!==f)&&i.$metadata)r.systemClockOffset=f,i.$metadata.clockSkewCorrected=!0}throw t}}successHandler(n,t){let i=M1(n);if(i){let s=ee("config",t.config);s.systemClockOffset=d1(i,s.systemClockOffset)}}}var ZW=Co;class g1 extends Co{async sign(n,t,i){if(!T1.isInstance(n))throw Error("The request is not an instance of `HttpRequest` and cannot be signed");let{config:s,signer:r,signingRegion:e,signingRegionSet:f,signingName:o}=await Lc(i),u=(await s.sigv4aSigningRegionSet?.()??f??[e]).join(",");return i._preRequestSystemClockOffset=s.systemClockOffset,await r.sign(n,{signingDate:$c(s.systemClockOffset),signingRegion:u,signingService:o})}}var R1=(n)=>typeof n==="string"&&n.length>0?n.split(",").map((t)=>t.trim()):[],S1=(n)=>`AWS_BEARER_TOKEN_${n.replace(/[\s-]/g,"_").toUpperCase()}`,E1="AWS_AUTH_SCHEME_PREFERENCE",y1="auth_scheme_preference",pW={environmentVariableSelector:(n,t)=>{if(t?.signingName){if(S1(t.signingName)in n)return["httpBearerAuth"]}if(!(E1 in n))return;return R1(n[E1])},configFileSelector:(n)=>{if(!(y1 in n))return;return R1(n[y1])},default:[]},nF=(n)=>{return n.sigv4aSigningRegionSet=re(n.sigv4aSigningRegionSet),n},tF={environmentVariableSelector(n){if(n.AWS_SIGV4A_SIGNING_REGION_SET)return n.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((t)=>t.trim());throw new l1("AWS_SIGV4A_SIGNING_REGION_SET not set in env.",{tryNextLink:!0})},configFileSelector(n){if(n.sigv4a_signing_region_set)return(n.sigv4a_signing_region_set??"").split(",").map((t)=>t.trim());throw new l1("sigv4a_signing_region_set not set in profile.",{tryNextLink:!0})},default:void 0},I1=(n)=>{let t=n.credentials,i=!!n.credentials,s=void 0;Object.defineProperty(n,"credentials",{set(u){if(u&&u!==t&&u!==s)i=!0;t=u;let c=sF(n,{credentials:t,credentialDefaultProvider:n.credentialDefaultProvider}),_=rF(n,c);if(i&&!_.attributed){let w=typeof t==="object"&&t!==null;s=async(l)=>{let d=await _(l);if(w&&(!d.$source||Object.keys(d.$source).length===0))return aW(d,"CREDENTIALS_CODE","e");return d},s.memoized=_.memoized,s.configBound=_.configBound,s.attributed=!0}else s=_},get(){return s},enumerable:!0,configurable:!0}),n.credentials=t;let{signingEscapePath:r=!0,systemClockOffset:e=n.systemClockOffset||0,sha256:f}=n,o;if(n.signer)o=re(n.signer);else if(n.regionInfoProvider)o=()=>re(n.region)().then(async(u)=>[await n.regionInfoProvider(u,{useFipsEndpoint:await n.useFipsEndpoint(),useDualstackEndpoint:await n.useDualstackEndpoint()})||{},u]).then(([u,c])=>{let{signingRegion:_,signingService:w}=u;n.signingRegion=n.signingRegion||_||c,n.signingName=n.signingName||w||n.serviceId;let l={...n,credentials:n.credentials,region:n.signingRegion,service:n.signingName,sha256:f,uriEscapePath:r};return new(n.signerConstructor||A1)(l)});else o=async(u)=>{u=Object.assign({},{name:"sigv4",signingName:n.signingName||n.defaultSigningName,signingRegion:await re(n.region)(),properties:{}},u);let{signingRegion:c,signingName:_}=u;n.signingRegion=n.signingRegion||c,n.signingName=n.signingName||_||n.serviceId;let w={...n,credentials:n.credentials,region:n.signingRegion,service:n.signingName,sha256:f,uriEscapePath:r};return new(n.signerConstructor||A1)(w)};return Object.assign(n,{systemClockOffset:e,signingEscapePath:r,signer:o})},iF=I1;function sF(n,{credentials:t,credentialDefaultProvider:i}){let s;if(t)if(!t?.memoized)s=qW(t,VW,jW);else s=t;else if(i)s=re(i(Object.assign({},n,{parentClientConfig:n})));else s=async()=>{throw Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.")};return s.memoized=!0,s}function rF(n,t){if(t.configBound)return t;let i=async(s)=>t({...s,callerClientConfig:n});return i.memoized=t.memoized,i.configBound=!0,i}eF.AWSSDKSigV4Signer=ZW;eF.AwsSdkSigV4ASigner=g1;eF.AwsSdkSigV4Signer=Co;eF.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS=pW;eF.NODE_SIGV4A_CONFIG_OPTIONS=tF;eF.getBearerTokenEnvKey=S1;eF.resolveAWSSDKSigV4Config=iF;eF.resolveAwsSdkSigV4AConfig=nF;eF.resolveAwsSdkSigV4Config=I1;eF.validateSigningProperties=Lc});var jo=k((LF)=>{var{buildQueryString:N1,HttpResponse:G1}=Jn(),xo=p("https"),{Readable:dF}=p("stream"),Bc=p("http2"),{streamCollector:RF}=mn();LF.streamCollector=RF;function ko(n){let t=n&&typeof n==="object"&&"reason"in n?n.reason:void 0;if(t){if(t instanceof Error){let r=Error("Request aborted");return r.name="AbortError",r.cause=t,r}let s=Error(String(t));return s.name="AbortError",s}let i=Error("Request aborted");return i.name="AbortError",i}var EF=["ECONNRESET","EPIPE","ETIMEDOUT"],H1=(n)=>{let t={};for(let i in n){let s=n[i];t[i]=Array.isArray(s)?s.join(","):s}return t},Bn={setTimeout:(n,t)=>setTimeout(n,t),clearTimeout:(n)=>clearTimeout(n)},b1=1000,yF=(n,t,i=0)=>{if(!i)return-1;let s=(r)=>{let e=Bn.setTimeout(()=>{n.destroy(),t(Object.assign(Error(`@smithy/node-http-handler - the request socket did not establish a connection with the server within the configured timeout of ${i} ms.`),{name:"TimeoutError"}))},i-r),f=(o)=>{if(o?.connecting)o.on("connect",()=>{Bn.clearTimeout(e)});else Bn.clearTimeout(e)};if(n.socket)f(n.socket);else n.on("socket",f)};if(i<2000)return s(0),0;return Bn.setTimeout(s.bind(null,b1),b1)},TF=(n,t,i=0,s,r)=>{if(i)return Bn.setTimeout(()=>{let e=`@smithy/node-http-handler - [${s?"ERROR":"WARN"}] a request has exceeded the configured ${i} ms requestTimeout.`;if(s){let f=Object.assign(Error(e),{name:"TimeoutError",code:"ETIMEDOUT"});n.destroy(f),t(f)}else e+=" Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.",r?.warn?.(e)},i);return-1},gF=3000,SF=(n,{keepAlive:t,keepAliveMsecs:i},s=gF)=>{if(t!==!0)return-1;let r=()=>{if(n.socket)n.socket.setKeepAlive(t,i||0);else n.on("socket",(e)=>{e.setKeepAlive(t,i||0)})};if(s===0)return r(),0;return Bn.setTimeout(r,s)},$1=3000,IF=(n,t,i=0)=>{let s=(r)=>{let e=i-r,f=()=>{n.destroy(),t(Object.assign(Error(`@smithy/node-http-handler - the request socket timed out after ${i} ms of inactivity (configured by client requestHandler).`),{name:"TimeoutError"}))};if(n.socket)n.socket.setTimeout(e,f),n.on("close",()=>n.socket?.removeListener("timeout",f));else n.setTimeout(e,f)};if(0<i&&i<6000)return s(0),0;return Bn.setTimeout(s.bind(null,i===0?0:$1),$1)},L1=6000;async function W1(n,t,i=L1,s=!1){let r=t.headers,e=r?r.Expect||r.expect:void 0,f=-1,o=!0;if(!s&&e==="100-continue")o=await Promise.race([new Promise((h)=>{f=Number(Bn.setTimeout(()=>h(!0),Math.max(L1,i)))}),new Promise((h)=>{n.on("continue",()=>{Bn.clearTimeout(f),h(!0)}),n.on("response",()=>{Bn.clearTimeout(f),h(!1)}),n.on("error",()=>{Bn.clearTimeout(f),h(!1)})})]);if(o)UF(n,t.body)}function UF(n,t){if(t instanceof dF){t.pipe(n);return}if(t){let i=Buffer.isBuffer(t);if(i||typeof t==="string"){if(i&&t.byteLength===0)n.end();else n.end(t);return}let r=t;if(typeof r==="object"&&r.buffer&&typeof r.byteOffset==="number"&&typeof r.byteLength==="number"){n.end(Buffer.from(r.buffer,r.byteOffset,r.byteLength));return}n.end(Buffer.from(t));return}n.end()}var bF=0,Ko=void 0,O1=void 0;class qo{config;configProvider;socketWarningTimestamp=0;externalAgent=!1;metadata={handlerProtocol:"http/1.1"};static create(n){if(typeof n?.handle==="function")return n;return new qo(n)}static checkSocketUsage(n,t,i=console){let{sockets:s,requests:r,maxSockets:e}=n;if(typeof e!=="number"||e===1/0)return t;let f=15000;if(Date.now()-f<t)return t;if(s&&r)for(let o in s){let h=s[o]?.length??0,u=r[o]?.length??0;if(h>=e&&u>=2*e)return i?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${h} and ${u} additional requests are enqueued.
|
|
42
43
|
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,i=t.protocol==="https:";if(!i&&!this.config.httpAgent)this.config.httpAgent=await this.config.httpAgentProvider();return new Promise((e,f)=>{let o=void 0,c=-1,h=-1,u=-1,_=-1,l=-1,w=()=>{Mt.clearTimeout(c),Mt.clearTimeout(h),Mt.clearTimeout(u),Mt.clearTimeout(_),Mt.clearTimeout(l)},A=async(R)=>{await o,w(),e(R)},M=async(R)=>{await o,w(),f(R)};if(n?.aborted){let R=We(n);M(R);return}let E=t.headers,d=E?(E.Expect??E.expect)==="100-continue":!1,T=i?r.httpsAgent:r.httpAgent;if(d&&!this.externalAgent)T=new(i?Pe.Agent:Ne)({keepAlive:!1,maxSockets:1/0});c=Mt.setTimeout(()=>{this.socketWarningTimestamp=De.checkSocketUsage(T,this.socketWarningTimestamp,r.logger)},r.socketAcquisitionWarningTimeout??(r.requestTimeout??2000)+(r.connectionTimeout??1000));let U=t.query?uM(t.query):"",S=void 0;if(t.username!=null||t.password!=null){let R=t.username??"",W=t.password??"";S=`${R}:${W}`}let O=t.path;if(U)O+=`?${U}`;if(t.fragment)O+=`#${t.fragment}`;let D=t.hostname??"";if(D[0]==="["&&D.endsWith("]"))D=t.hostname.slice(1,-1);else D=t.hostname;let q={headers:t.headers,host:D,method:t.method,path:O,port:t.port,agent:T,auth:S},J=(i?Pe.request:cM)(q,(R)=>{let W=new _M({statusCode:R.statusCode||-1,reason:R.statusMessage,headers:lM(R.headers),body:R});A({response:W})});if(J.on("error",(R)=>{if(_3.includes(R.code))M(Object.assign(R,{name:"TimeoutError"}));else M(R)}),n){let R=()=>{J.destroy();let W=We(n);M(W)};if(typeof n.addEventListener==="function"){let W=n;W.addEventListener("abort",R,{once:!0}),J.once("close",()=>W.removeEventListener("abort",R))}else n.onabort=R}let G=s??r.requestTimeout;h=l3(J,M,r.connectionTimeout),u=w3(J,M,G,r.throwOnRequestTimeout,r.logger??console),_=g3(J,M,r.socketTimeout);let K=q.agent;if(typeof K==="object"&&"keepAlive"in K)l=M3(J,{keepAlive:K.keepAlive,keepAliveMsecs:K.keepAliveMsecs});o=wM(J,t,G,this.externalAgent).catch((R)=>{return w(),f(R)})})}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:i,httpAgent:e,httpsAgent:f,throwOnRequestTimeout:o,logger:c}=t||{},h=!0,u=50;return{connectionTimeout:s,requestTimeout:n,socketTimeout:r,socketAcquisitionWarningTimeout:i,throwOnRequestTimeout:o,httpAgentProvider:async()=>{let _=nt("http"),{Agent:l,request:w}=_.default??_;if(cM=w,Ne=l,e instanceof Ne||typeof e?.destroy==="function")return this.externalAgent=!0,e;return new Ne({keepAlive:!0,maxSockets:50,...e})},httpsAgent:(()=>{if(f instanceof Pe.Agent||typeof f?.destroy==="function")return this.externalAgent=!0,f;return new Pe.Agent({keepAlive:!0,maxSockets:50,...f})})(),logger:c}}}var R3=new Uint16Array(1);class Ye{id=R3[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 AM{sessions=[];maxConcurrency=0;constructor(t){this.sessions=(t??[]).map((n)=>new Ye(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 MM{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 i=new Ye(this.connect(s)),e=i.deref();if(this.config.maxConcurrency)e.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,i)},o=()=>{this.removeFromPoolAndCheckedDestroy(s,i)};if(e.on("goaway",f),e.on("error",o),e.on("frameError",o),e.on("close",o),n.requestTimeout)e.setTimeout(n.requestTimeout,o);return r.offerLast(i),i.retain(),i}release(t,n){n.free()}createIsolatedSession(t,n){let s=this.getUrlString(t),r=new Ye(this.connect(s)),i=r.deref();i.settings({maxConcurrentStreams:1});let e=()=>{r.destroy()};if(i.on("error",e),i.on("frameError",e),i.on("close",e),n.requestTimeout)i.setTimeout(n.requestTimeout,e);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 i of s)r.push({id:i.id,active:i.useCount(),maxConcurrent:i.max,totalRequests:i.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 AM;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?ac.connect(t):ac.connect(t,this.connectOptions)}}var{constants:hM}=ac;class pc{config;configProvider;metadata={handlerProtocol:"h2"};connectionManager=new MM({});static create(t){if(typeof t?.handle==="function")return t;return new pc(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:i,disableConcurrentStreams:e}=this.config,f=e||r,o=s??i;return new Promise((c,h)=>{let u=!1,_=void 0,l=async(W)=>{await _,c(W)},w=async(W)=>{await _,h(W)};if(n?.aborted){u=!0;let W=We(n);w(W);return}let{hostname:A,method:M,port:E,protocol:d,query:T}=t,U="";if(t.username!=null||t.password!=null){let W=t.username??"",k=t.password??"";U=`${W}:${k}@`}let S=`${d}//${U}${A}${E?`:${E}`:""}`,O={destination:new URL(S)},D={requestTimeout:this.config?.sessionTimeout,isEventStream:r},q=f?this.connectionManager.createIsolatedSession(O,D):this.connectionManager.lease(O,D),tt=q.deref(),J=(W)=>{if(f)q.destroy();u=!0,w(W)},G=T?uM(T):"",K=t.path;if(G)K+=`?${G}`;if(t.fragment)K+=`#${t.fragment}`;let R=tt.request({...t.headers,[hM.HTTP2_HEADER_PATH]:K,[hM.HTTP2_HEADER_METHOD]:M});if(o)R.setTimeout(o,()=>{R.close();let W=Error(`Stream timed out because of no activity for ${o} ms`);W.name="TimeoutError",J(W)});if(n){let W=()=>{R.close();let k=We(n);J(k)};if(typeof n.addEventListener==="function"){let k=n;k.addEventListener("abort",W,{once:!0}),R.once("close",()=>k.removeEventListener("abort",W))}else n.onabort=W}R.on("frameError",(W,k,st)=>{J(Error(`Frame type id ${W} in stream id ${st} has failed with code ${k}.`))}),R.on("error",J),R.on("aborted",()=>{J(Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${R.rstCode}.`))}),R.on("response",(W)=>{let k=new _M({statusCode:W[":status"]??-1,headers:lM(W),body:R});if(u=!0,l({response:k}),f)tt.close()}),R.on("close",()=>{if(f)q.destroy();else this.connectionManager.release(O,q);if(!u)J(Error("Unexpected error: http2 request did not get a response"))}),_=wM(R,t,o)})}updateHttpClientConfig(t,n){this.config=void 0,this.configProvider=this.configProvider.then((s)=>{return{...s,[t]:n}})}httpHandlerConfigs(){return this.config??{}}}b3.DEFAULT_REQUEST_TIMEOUT=d3;b3.NodeHttp2Handler=pc;b3.NodeHttpHandler=De});var OM=Z((rF)=>{var{nv:L3,NumericValue:bM,calculateBodyLength:I3,_parseEpochTimestamp:gM,fromBase64:TM,generateIdempotencyToken:O3}=$t(),{HttpRequest:y3,collectBody:G3,SerdeContext:rh,RpcProtocol:B3}=Ut(),{NormalizedSchema:ih,deref:F3,TypeRegistry:EM}=Nn(),{getSmithyContext:H3}=nn();function er(t){return typeof Buffer<"u"?Buffer.alloc(t):new Uint8Array(t)}var eh=Symbol("@smithy/core/cbor::tagSymbol");function oh(t){return t[eh]=!0,t}var SM=typeof Buffer<"u",fh=new TextDecoder,C=er(0),ch=!1,qt=new DataView(C.buffer,C.byteOffset,C.byteLength),m=0;function P3(t){C=t,ch=SM&&C instanceof Buffer,qt=new DataView(C.buffer,C.byteOffset,C.byteLength)}function zn(t,n){if(t>=n)throw Error("unexpected end of (decode) payload.");let s=(C[t]&224)>>5,r=C[t]&31;if(r===31&&2<=s&&s<=5)return N3(t,n);switch(s){case 0:case 1:case 6:{let i,e;if(r<24)i=r,e=1;else switch(r){case 24:if(n-t<2)cn(1);i=C[t+1],e=2;break;case 25:if(n-t<3)cn(2);i=qt.getUint16(t+1),e=3;break;case 26:if(n-t<5)cn(4);i=qt.getUint32(t+1),e=5;break;case 27:if(n-t<9)cn(8);{let f=qt.getUint32(t+1);if(f<2097152)i=f*4294967296+qt.getUint32(t+5);else i=qt.getBigUint64(t+1)}e=9;break;default:uh(r)}if(s===0)return m=e,th(i);else if(s===1){let f;if(typeof i==="bigint")f=BigInt(-1)-i;else f=-1-i;return m=e,th(f)}else return X3(t,n,r,i,e)}case 3:return hi(t,n);case 5:return D3(t,n);case 4:return Q3(t,n);case 2:return hh(t,n);default:return z3(t,n)}}function N3(t,n){let s=(C[t]&224)>>5;if((C[t]&31)===31)switch(s){case 3:return C3(t,n);case 5:return x3(t,n);case 4:return q3(t,n);case 2:return K3(t,n)}}function W3(t,n){let s=t>>7,r=(t&124)>>2,i=(t&3)<<8|n,e=s===0?1:-1;if(r===0){if(i===0)return 0;return e*(Math.pow(2,-14)*(i/1024))}else if(r===31){if(i===0)return e*(1/0);return NaN}return e*(Math.pow(2,r-15)*(1+i/1024))}function D3(t,n){let s=ui(t,n);if(s<15)return m3(t,n,s);return Y3(t,n,s)}function Y3(t,n,s){let r=m;t+=r;let i=t,e=Object.create(null);for(let f=0;f<s;++f){let o=hi(t,n);if(t+=m,(C[t]&224)>>5===3)e[o]=hi(t,n);else e[o]=zn(t,n);t+=m}return m=r+(t-i),Object.setPrototypeOf(e,Object.prototype),e}function m3(t,n,s){let r=m;t+=r;let i=t,e={};for(let f=0;f<s;++f){let o=hi(t,n);t+=m,e[o]=zn(t,n),t+=m}return m=r+(t-i),e}function Q3(t,n){let s=ui(t,n),r=m;t+=r;let i=t,e=Array(s);for(let f=0;f<s;++f)e[f]=zn(t,n),t+=m;return m=r+(t-i),e}function hi(t,n){let s=ui(t,n),r=m;if(t+=r,n-t<s)cn(s);if(m=r+s,s<24)return k3(t,s);if(ch)return C.toString("utf-8",t,t+s);return fh.decode(C.subarray(t,t+s))}var dM=Array(2048),Zc=new Uint16Array(2048),fi=0;function J3(){fi=fi+1&65535}function k3(t,n){let s=n;for(let f=0;f<n;++f)s=s*31+C[t+f]|0;let r=s>>>0&2047,i=dM[r];if(i!==void 0){if(i.length===n){let f=!0;for(let o=0;o<n;++o)if(i.charCodeAt(o)!==C[t+o]){f=!1;break}if(f)return Zc[r]=fi,i}}let e=ch?C.toString("utf-8",t,t+n):fh.decode(C.subarray(t,t+n));if(Zc[r]!==fi)dM[r]=e,Zc[r]=fi;return e}function hh(t,n){let s=ui(t,n),r=m;if(t+=r,n-t<s)cn(s);let i=C.subarray(t,t+s);return m=r+s,i}function X3(t,n,s,r,i){if(s===2||s===3){let e=ui(t+i,n),f=BigInt(0),o=t+i+m;for(let c=o;c<o+e;++c)f=f<<BigInt(8)|BigInt(C[c]);return m=i+m+e,s===3?-f-BigInt(1):f}else if(s===4){let e=zn(t+i,n),[f,o]=e,c=o<0?-1:1,h="0".repeat(Math.abs(f)+1)+String(BigInt(c)*BigInt(o)),u,_=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=_+u,m=i+m,L3(u)}else{let e=zn(t+i,n);return m=i+m,oh({tag:th(r),value:e})}}function z3(t,n){let s=C[t]&31;switch(s){case 21:case 20:return m=1,s===21;case 22:return m=1,null;case 23:return m=1,null;case 25:if(n-t<3)throw Error("incomplete float16 at end of buf.");return m=3,W3(C[t+1],C[t+2]);case 26:if(n-t<5)throw Error("incomplete float32 at end of buf.");return m=5,qt.getFloat32(t+1);case 27:if(n-t<9)throw Error("incomplete float64 at end of buf.");return m=9,qt.getFloat64(t+1);default:uh(s)}}function ui(t,n){let s=C[t]&31;if(s<24)return m=1,s;switch(s){case 24:if(n-t<2)cn(1);return m=2,C[t+1];case 25:if(n-t<3)cn(2);return m=3,qt.getUint16(t+1);case 26:if(n-t<5)cn(4);return m=5,qt.getUint32(t+1);case 27:if(n-t<9)cn(8);return m=9,V3(qt.getBigUint64(t+1));default:uh(s)}}function x3(t,n){t+=1;let s=t,r={};for(;t<n;){if(C[t]===255)return m=t-s+2,r;let i=hi(t,n);t+=m,r[i]=zn(t,n),t+=m}throw Error("expected break marker.")}function q3(t,n){t+=1;let s=[];for(let r=t;t<n;){if(C[t]===255)return m=t-r+2,s;s.push(zn(t,n)),t+=m}throw Error("expected break marker.")}function C3(t,n){t+=1;let s=[];for(let r=t;t<n;){if(C[t]===255){let c=er(s.length);if(c.set(s,0),m=t-r+2,SM)return c.toString("utf-8",0,c.length);return fh.decode(c)}let i=(C[t]&224)>>5,e=C[t]&31;if(i!==3)$M(i);if(e===31)throw Error("nested indefinite string.");let f=hh(t,n);t+=m;for(let c=0;c<f.length;++c)s.push(f[c])}throw Error("expected break marker.")}function K3(t,n){t+=1;let s=[];for(let r=t;t<n;){if(C[t]===255){let c=er(s.length);return c.set(s,0),m=t-r+2,c}let i=(C[t]&224)>>5,e=C[t]&31;if(i!==2)$M(i);if(e===31)throw Error("nested indefinite string.");let f=hh(t,n);t+=m;for(let c=0;c<f.length;++c)s.push(f[c])}throw Error("expected break marker.")}function th(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 V3(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 cn(t){throw Error(`length ${t} greater than remaining buf len.`)}function uh(t){throw Error(`unexpected minor value ${t}.`)}function $M(t){throw Error(`unexpected major type ${t} in indefinite string.`)}var j3=typeof Buffer<"u",rr=new Map,ci=0,nh=!1,a3=2048,H=er(a3),Dt=new DataView(H.buffer,H.byteOffset,H.byteLength),I=0;function p3(t){let n=[t];while(n.length){let s=n.pop();if(typeof s==="string"){let r=s.length;if(j3)if(ir(r*3+9),r>23)vc(3,Buffer.byteLength(s)),I+=H.write(s,I);else v3(s);else{let i=r*3;ir(i+9);let e=I,o=new TextEncoder().encodeInto(s,H.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)H.copyWithin(e+c,e+9,e+9+o);I=e,ws(3,o),I+=o}continue}if(H.byteLength-I<9)ir(64);if(typeof s==="number"){if(Number.isInteger(s)){let r=s>=0,i=r?0:1,e=r?s:-s-1;if(e<24)H[I++]=i<<5|e;else if(e<256)H[I++]=i<<5|24,H[I++]=e;else if(e<65536)H[I++]=i<<5|25,H[I++]=e>>8,H[I++]=e&255;else if(e<4294967296)H[I++]=i<<5|26,Dt.setUint32(I,e),I+=4;else{H[I++]=i<<5|27;let f=e/4294967296|0,o=e-f*4294967296|0;Dt.setUint32(I,f),Dt.setUint32(I+4,o),I+=8}continue}H[I++]=251,Dt.setFloat64(I,s),I+=8;continue}else if(typeof s==="bigint"){let r=s>=0,i=r?0:1,e=r?s:-s-BigInt(1);if(e<BigInt("18446744073709551616")){let f=Number(e);if(f<4294967296)ws(i,f);else H[I++]=i<<5|27,Dt.setBigUint64(I,e),I+=8}else{let f=e.toString(2),o=new Uint8Array(Math.ceil(f.length/8)),c=e,h=0;while(o.byteLength-++h>=0)o[o.byteLength-h]=Number(c&BigInt(255)),c>>=BigInt(8);ir(o.byteLength*2+16),H[I++]=r?194:195,vc(2,o.byteLength),H.set(o,I),I+=o.byteLength}continue}else if(s===null){H[I++]=246;continue}else if(typeof s==="boolean"){H[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),ir(s.length*9+64);for(let r=s.length-1;r>=0;--r)n.push(s[r]);continue}else if(typeof s.byteLength==="number"){ir(s.length*2+9),ws(2,s.length),H.set(s,I),I+=s.byteLength;continue}else if(typeof s==="object"){if(s instanceof bM){let e=s.string.indexOf("."),f=e===-1?0:e-s.string.length+1,o=BigInt(s.string.replace(".",""));H[I++]=196,ws(4,2),n.push(o),n.push(f);continue}if(s[eh])if("tag"in s&&"value"in s){n.push(s.value),vc(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),i=r.length;ws(5,i);for(let e=i-1;e>=0;--e)n.push(s[r[e]]),n.push(r[e]);continue}throw Error(`data type ${s?.constructor?.name??typeof s} not compatible for encoding.`)}}function Z3(){ci=ci+1&65535,nh=!1}function RM(){let t=er(I);return t.set(H.subarray(0,I),0),I=0,t}function sh(t){let n=H;if(H=er(t),n)if(n.copy)n.copy(H,0,0,n.byteLength);else H.set(n,0);Dt=new DataView(H.buffer,H.byteOffset,H.byteLength)}function v3(t){let n=rr.get(t);if(n!==void 0){H.set(n.bytes,I),I+=n.bytes.length,n.epoch=ci;return}let s=I,r=Buffer.byteLength(t);ws(3,r),I+=H.write(t,I);let i=Uint8Array.prototype.slice.call(H,s,I);if(rr.size>=2048){if(nh)return;let e=0;for(let[f,o]of rr){if(e>=1024)break;if(o.epoch!==ci)rr.delete(f),e++}if(e===0){nh=!0;return}}if(rr.size<2048)rr.set(t,{epoch:ci,bytes:i})}function ir(t){if(H.byteLength-I<t)if(I<16000000)sh(Math.max(H.byteLength*4,H.byteLength+t));else sh(H.byteLength+t+16000000)}function vc(t,n){if(n<24)H[I++]=t<<5|n;else if(n<256)H[I++]=t<<5|24,H[I++]=n;else if(n<65536)H[I++]=t<<5|25,Dt.setUint16(I,n),I+=2;else if(n<4294967296)H[I++]=t<<5|26,Dt.setUint32(I,n),I+=4;else H[I++]=t<<5|27,Dt.setBigUint64(I,typeof n==="bigint"?n:BigInt(n)),I+=8}function ws(t,n){if(n<24)H[I++]=t<<5|n;else if(n<256)H[I++]=t<<5|24,H[I++]=n;else if(n<65536)H[I++]=t<<5|25,H[I++]=n>>8,H[I++]=n&255;else if(n<4294967296)H[I++]=t<<5|26,Dt.setUint32(I,n),I+=4;else{H[I++]=t<<5|27;let s=n/4294967296|0,r=n-s*4294967296|0;Dt.setUint32(I,s),Dt.setUint32(I+4,r),I+=8}}var Je={deserialize(t){return J3(),P3(t),zn(0,t.length)},serialize(t){Z3();try{return p3(t),RM()}catch(n){throw RM(),n}},resizeEncodingBuffer(t){sh(t)}},UM=(t,n)=>{return G3(t,n).then(async(s)=>{if(s.length)try{return Je.deserialize(s)}catch(r){throw Object.defineProperty(r,"$responseBodyText",{value:n.utf8Encoder(s)}),r}return{}})},Qe=(t)=>{return oh({tag:1,value:t.getTime()/1000})},tF=async(t,n)=>{let s=await UM(t,n);return s.message=s.message??s.Message,s},LM=(t,n)=>{let s=(i)=>{let e=i;if(typeof e==="number")e=e.toString();if(e.indexOf(",")>=0)e=e.split(",")[0];if(e.indexOf(":")>=0)e=e.split(":")[0];if(e.indexOf("#")>=0)e=e.split("#")[1];return e};if(n.__type!==void 0)return s(n.__type);let r;for(let i in n)if(i.toLowerCase()==="code"){r=i;break}if(r&&n[r]!==void 0)return s(n[r])},nF=(t)=>{if(String(t.headers["smithy-protocol"]).toLowerCase()!=="rpc-v2-cbor")throw Error("Malformed RPCv2 CBOR response, status: "+t.statusCode)},sF=async(t,n,s,r,i)=>{let e=await t.endpoint(),{hostname:f,protocol:o="https",port:c,path:h}=e,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(e.headers)for(let _ in e.headers)u.headers[_]=e.headers[_];if(i!==void 0){u.body=i;try{u.headers["content-length"]=String(I3(i))}catch(_){}}return new y3(u)};class _h extends rh{createSerializer(){let t=new lh;return t.setSerdeContext(this.serdeContext),t}createDeserializer(){let t=new wh;return t.setSerdeContext(this.serdeContext),t}}class lh extends rh{value;write(t,n){this.value=this.serialize(t,n)}serialize(t,n){let s=ih.of(t);if(n==null){if(s.isIdempotencyToken())return O3();return n}if(s.isBlobSchema()){if(typeof n==="string")return(this.serdeContext?.base64Decoder??TM)(n);return n}if(s.isTimestampSchema()){if(typeof n==="number"||typeof n==="bigint")return Qe(new Date(Number(n)/1000|0));return Qe(n)}if(typeof n==="function"||typeof n==="object"){let r=n;if(s.isListSchema()&&Array.isArray(r)){let e=!!s.getMergedTraits().sparse,f=[],o=0;for(let c of r){let h=this.serialize(s.getValueSchema(),c);if(h!=null||e)f[o++]=h}return f}if(r instanceof Date)return Qe(r);let i={};if(s.isMapSchema()){let e=!!s.getMergedTraits().sparse;for(let f in r){let o=this.serialize(s.getValueSchema(),r[f]);if(o!=null||e)i[f]=o}}else if(s.isStructSchema()){for(let[f,o]of s.structIterator()){let c=this.serialize(o,r[f]);if(c!=null)i[f]=c}if(s.isUnionSchema()&&Array.isArray(r.$unknown)){let[f,o]=r.$unknown;i[f]=o}else if(typeof r.__type==="string"){for(let f in r)if(!(f in i))i[f]=this.serialize(15,r[f])}}else if(s.isDocumentSchema())for(let e in r)i[e]=this.serialize(s.getValueSchema(),r[e]);else if(s.isBigDecimalSchema())return r;return i}return n}flush(){let t=Je.serialize(this.value);return this.value=void 0,t}}class wh extends rh{read(t,n){let s=Je.deserialize(n);return this.readValue(t,s)}readValue(t,n){let s=ih.of(t);if(s.isTimestampSchema()){if(typeof n==="number")return gM(n);if(typeof n==="object"){if(n.tag===1&&"value"in n)return gM(n.value)}}if(s.isBlobSchema()){if(typeof n==="string")return(this.serdeContext?.base64Decoder??TM)(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 i=[],e=s.getValueSchema();for(let f of n){let o=this.readValue(e,f);i.push(o)}return i}let r={};if(s.isMapSchema()){let i=s.getValueSchema();for(let e in n){let f=this.readValue(i,n[e]);r[e]=f}}else if(s.isStructSchema()){let i=s.isUnionSchema(),e;if(i){e=new Set;for(let f in n)if(f!=="__type")e.add(f)}for(let[f,o]of s.structIterator()){if(i)e.delete(f);if(n[f]!=null)r[f]=this.readValue(o,n[f])}if(i&&e?.size===1){let f=!0;for(let o in r){f=!1;break}if(f){let o=e.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 bM)return n;return r}else return n}}class IM extends B3{codec=new _h;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:i,operation:e}=H3(s),f=`/service/${i}/operation/${e}`;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,i){let e=LM(s,r)??"Unknown",f={$metadata:i,$fault:s.statusCode<=500?"client":"server"},o=this.options.defaultNamespace;if(e.includes("#"))[o]=e.split("#");let c=this.compositeErrorRegistry,h=EM.for(o);c.copyFrom(h);let u;try{u=c.getSchema(e)}catch(E){if(r.Message)r.message=r.Message;let d=EM.for("smithy.ts.sdk.synthetic."+o);c.copyFrom(d);let T=c.getBaseException();if(T){let U=c.getErrorCtor(T);throw Object.assign(new U({name:e}),f,r)}throw Object.assign(Error(e),f,r)}let _=ih.of(u),l=c.getErrorCtor(u),w=r.message??r.Message??"Unknown",A=new l({}),M={};for(let[E,d]of _.structIterator())M[E]=this.deserializer.readValue(d,r[E]);throw Object.assign(A,f,{$fault:_.getMergedTraits().error,message:w},M)}getDefaultContentType(){return"application/cbor"}}rF.CborCodec=_h;rF.CborShapeDeserializer=wh;rF.CborShapeSerializer=lh;rF.SmithyRpcV2CborProtocol=IM;rF.buildHttpRpcRequest=sF;rF.cbor=Je;rF.checkCborResponse=nF;rF.dateToTag=Qe;rF.loadSmithyRpcV2CborErrorCode=LM;rF.parseCborBody=UM;rF.parseCborErrorBody=tF;rF.tag=oh;rF.tagSymbol=eh});var yM=Z((UF)=>{var EF=/[&<>"]/g,dF={"&":"&","<":"<",">":">",'"':"""};function RF(t){return t.replace(EF,(n)=>dF[n])}var bF=/[&"'<>\r\n\u0085\u2028]/g,TF={"&":"&",'"':""","'":"'","<":"<",">":">","\r":"
","\n":"
","\x85":"…","\u2028":"
"};function SF(t){return t.replace(bF,(n)=>TF[n])}class Ah{value;constructor(t){this.value=t}toString(){return SF(""+this.value)}}class _i{name;children;attributes={};static of(t,n,s){let r=new _i(t);if(n!==void 0)r.addChildNode(new Ah(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=_i.of(n,t[n]).withName(s);this.c(r)}}l(t,n,s,r){if(t[n]!=null)r().map((e)=>{e.withName(s),this.c(e)})}lc(t,n,s,r){if(t[n]!=null){let i=r(),e=new _i(s);i.map((f)=>{e.c(f)}),this.c(e)}}toString(){let t=Boolean(this.children.length),n=`<${this.name}`,s=this.attributes;for(let r of Object.keys(s)){let i=s[r];if(i!=null)n+=` ${r}="${RF(""+i)}"`}return n+=!t?"/>":`>${this.children.map((r)=>r.toString()).join("")}</${this.name}>`}}function $F(t){return new Mh(t).parse()}class Mh{x;i=0;z;constructor(t){this.x=t,this.x=t.replace(/\r\n?/g,`
|
|
44
|
-
`),this.z=this.x.length}parse(){let
|
|
45
|
-
`.includes(
|
|
46
|
-
>/`.includes(
|
|
47
|
-
>/?`.includes(
|
|
48
|
-
`))return{tag:
|
|
49
|
-
`))continue;c["#text"]="#text"in c?c["#text"]+h:h}for(let h of e)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,i)=>{if(s)return String.fromCharCode(parseInt(s,16));if(r)return String.fromCharCode(parseInt(r,10));return Mh.ENTITIES[i]??""})}}UF.XmlNode=_i;UF.XmlText=Ah;UF.parseXML=$F});var Oh=Z((XF)=>{var{SmithyRpcV2CborProtocol:yF,loadSmithyRpcV2CborErrorCode:GF}=OM(),{TypeRegistry:GM,NormalizedSchema:ft,deref:WM}=Nn(),{decorateServiceException:BM,getValueFromTextNode:DM}=Rn(),{collectBody:Eh,determineTimestampFormat:ze,RpcProtocol:YM,HttpBindingProtocol:mM,HttpInterceptingShapeSerializer:QM,HttpInterceptingShapeDeserializer:JM,FromStringShapeDeserializer:BF,extendedEncodeURIComponent:FM}=Ut(),{NumericValue:hn,toUtf8:kM,fromBase64:XM,LazyJsonString:zM,parseEpochTimestamp:FF,parseRfc7231DateTime:HF,parseRfc3339DateTimeWithOffset:PF,toBase64:ke,dateToUtcString:Xe,generateIdempotencyToken:dh,expectUnion:NF}=$t(),{parseXML:xM,XmlNode:Ct,XmlText:HM}=yM();class or{queryCompat;errorRegistry;constructor(t=!1){this.queryCompat=t}resolveRestContentType(t,n){let s=n.getMemberSchemas(),r=Object.values(s).find((i)=>{return!!i.getMergedTraits().httpPayload});if(r){let i=r.getMergedTraits().mediaType;if(i)return i;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((e)=>{let{httpQuery:f,httpQueryParams:o,httpHeader:c,httpLabel:h,httpPrefixHeaders:u}=e.getMergedTraits();return!f&&!o&&!c&&!h&&u===void 0}))return t}}async getErrorSchemaOrThrowBaseException(t,n,s,r,i,e){let f=t;if(t.includes("#"))[,f]=t.split("#");let o={$metadata:i,$fault:s.statusCode<500?"client":"server"};if(!this.errorRegistry)throw Error("@aws-sdk/core/protocols - error handler not initialized.");try{return{errorSchema:e?.(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 _=r,l=_?.message??_?.Message??_?.Error?.Message??_?.Error?.message;throw this.decorateServiceException(Object.assign(Error(l),{name:f},o),r)}}compose(t,n,s){let r=s;if(n.includes("#"))[r]=n.split("#");let i=GM.for(r),e=GM.for("smithy.ts.sdk.synthetic."+s);t.copyFrom(i),t.copyFrom(e),this.errorRegistry=t}decorateServiceException(t,n={}){if(this.queryCompat){let s=t.Message??n.Message,r=BM(t,n);if(s)r.message=s;let i=r.Error??{};i.Type=r.Error?.Type,i.Code=r.Error?.Code,i.Message=r.Error?.message??r.Error?.Message??s,r.Error=i;let e=r.$metadata.requestId;if(e)r.RequestId=e;return r}return BM(t,n)}setQueryCompatError(t,n){let s=n.headers?.["x-amzn-query-error"];if(t!==void 0&&s!=null){let[r,i]=s.split(";"),e=Object.keys(t),f={Code:r,Type:i};t.Code=r,t.Type=i;for(let o=0;o<e.length;o++){let c=e[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)=>ft.of(r).getMergedTraits().awsQueryError?.[0]===n)}}}class qM extends yF{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,i){if(this.awsQueryCompatible)this.mixin.setQueryCompatError(r,s);let e=(()=>{let w=s.headers["x-amzn-query-error"];if(w&&this.awsQueryCompatible)return w.split(";")[0];return GF(s,r)??"Unknown"})();this.mixin.compose(this.compositeErrorRegistry,e,this.options.defaultNamespace);let{errorSchema:f,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(e,this.options.defaultNamespace,s,r,i,this.awsQueryCompatible?this.mixin.findQueryCompatibleError:void 0),c=ft.of(f),h=r.message??r.Message??"UnknownError",_=new(this.compositeErrorRegistry.getErrorCtor(f)??Error)({}),l={};for(let[w,A]of c.structIterator())if(r[w]!=null)l[w]=this.deserializer.readValue(A,r[w]);if(this.awsQueryCompatible)this.mixin.queryCompatOutput(r,l);throw this.mixin.decorateServiceException(Object.assign(_,o,{$fault:c.getMergedTraits().error,message:h},l),r)}}var WF=(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},DF=(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},YF=(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 xn{serdeContext;setSerdeContext(t){this.serdeContext=t}}class Rh{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 mF(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 hn(r,"bigDecimal");else return BigInt(r)}}return n}var CM=(t,n)=>Eh(t,n).then((s)=>(n?.utf8Encoder??kM)(s)),bh=(t,n)=>CM(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{}}),QF=async(t,n)=>{let s=await bh(t,n);return s.message=s.message??s.Message,s},PM=(t,n)=>Object.keys(t).find((s)=>s.toLowerCase()===n.toLowerCase()),gh=(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},KM=(t,n)=>{return jM(t,n,["header","code","type"])},VM=(t,n,s=!1)=>{return jM(t,n,s?["code","header","type"]:["type","code","header"])},jM=({headers:t},n,s)=>{while(s.length>0)switch(s.shift()){case"header":let i=PM(t??{},"x-amzn-errortype");if(i!==void 0)return gh(t[i]);break;case"code":let e=PM(n??{},"code");if(e&&n[e]!==void 0)return gh(n[e]);break;case"type":if(n?.__type!==void 0)return gh(n.__type);break}};class Th extends xn{settings;constructor(t){super();this.settings=t}async read(t,n){return this._read(t,typeof n==="string"?JSON.parse(n,mF):await bh(n,this.serdeContext))}readObject(t,n){return this._read(t,n)}_read(t,n){let s=n!==null&&typeof n==="object",r=ft.of(t);if(s){if(r.isStructSchema()){let e=n,f=r.isUnionSchema(),o={},c=void 0,{jsonName:h}=this.settings;if(h)c={};let u;if(f)u=new Rh(e,o);for(let[_,l]of r.structIterator()){let w=_;if(h)w=l.getMergedTraits().jsonName??w,c[w]=_;if(f)u.mark(w);if(e[w]!=null)o[_]=this._read(l,e[w])}if(f)u.writeUnknown();else if(typeof e.__type==="string")for(let _ in e){let l=e[_],w=h?c[_]??_:_;if(!(w in o))o[w]=l}return o}if(Array.isArray(n)&&r.isListSchema()){let e=r.getValueSchema(),f=[];for(let o of n)f.push(this._read(e,o));return f}if(r.isMapSchema()){let e=r.getValueSchema(),f={};for(let o in n)f[o]=this._read(e,n[o]);return f}}if(r.isBlobSchema()&&typeof n==="string")return XM(n);let i=r.getMergedTraits().mediaType;if(r.isStringSchema()&&typeof n==="string"&&i){if(i==="application/json"||i.endsWith("+json"))return zM.from(n);return n}if(r.isTimestampSchema()&&n!=null)switch(ze(r,this.settings)){case 5:return PF(n);case 6:return HF(n);case 7:return FF(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 hn)return n;let e=n;if(e.type==="bigDecimal"&&"string"in e)return new hn(e.string,e.type);return new hn(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 e=Array.isArray(n)?[]:{};for(let f in n){let o=n[f];if(o instanceof hn)e[f]=o;else e[f]=this._read(r,o)}return e}else return structuredClone(n);return n}}var NM=String.fromCharCode(925);class aM{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 hn){let s=`${NM+"nv"+this.counter++}_`+n.string;return this.values.set(`"${s}"`,n.string),s}if(typeof n==="bigint"){let s=n.toString(),r=`${NM+"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 Sh extends xn{settings;buffer;useReplacer=!1;rootSchema;constructor(t){super();this.settings=t}write(t,n){this.rootSchema=ft.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 aM;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=ft.of(t).getName(!0)}_write(t,n,s){let r=n!==null&&typeof n==="object",i=ft.of(t);if(r){if(i.isStructSchema()){let e=n,f={},{jsonName:o}=this.settings,c=void 0;if(o)c={};let h=0;for(let[u,_]of i.structIterator()){let l=this._write(_,e[u],i);if(l!==void 0){let w=u;if(o)w=_.getMergedTraits().jsonName??u,c[u]=w;f[w]=l,h++}}if(i.isUnionSchema()&&h===0){let{$unknown:u}=e;if(Array.isArray(u)){let[_,l]=u;f[_]=this._write(15,l)}}else if(typeof e.__type==="string")for(let u in e){let _=e[u],l=o?c[u]??u:u;if(!(l in f))f[l]=this._write(15,_)}return f}if(Array.isArray(n)&&i.isListSchema()){let e=i.getValueSchema(),f=[],o=!!i.getMergedTraits().sparse;for(let c of n)if(o||c!=null)f.push(this._write(e,c));return f}if(i.isMapSchema()){let e=i.getValueSchema(),f={},o=!!i.getMergedTraits().sparse;for(let c in n){let h=n[c];if(o||h!=null)f[c]=this._write(e,h)}return f}if(n instanceof Uint8Array&&(i.isBlobSchema()||i.isDocumentSchema())){if(i===this.rootSchema)return n;return(this.serdeContext?.base64Encoder??ke)(n)}if(n instanceof Date&&(i.isTimestampSchema()||i.isDocumentSchema()))switch(ze(i,this.settings)){case 5:return n.toISOString().replace(".000Z","Z");case 6:return Xe(n);case 7:return n.getTime()/1000;default:return console.warn("Missing timestamp format, using epoch seconds",n),n.getTime()/1000}if(n instanceof hn)this.useReplacer=!0}if(n===null&&s?.isStructSchema())return;if(i.isStringSchema()){if(typeof n>"u"&&i.isIdempotencyToken())return dh();let e=i.getMergedTraits().mediaType;if(n!=null&&e){if(e==="application/json"||e.endsWith("+json"))return zM.from(n)}return n}if(typeof n==="number"&&i.isNumericSchema()){if(Math.abs(n)===1/0||isNaN(n))return String(n);return n}if(typeof n==="string"&&i.isBlobSchema()){if(i===this.rootSchema)return n;return(this.serdeContext?.base64Encoder??ke)(n)}if(typeof n==="bigint")this.useReplacer=!0;if(i.isDocumentSchema())if(r){let e=Array.isArray(n)?[]:{};for(let f in n){let o=n[f];if(o instanceof hn)this.useReplacer=!0,e[f]=o;else e[f]=this._write(i,o)}return e}else return structuredClone(n);return n}}class xe extends xn{settings;constructor(t){super();this.settings=t}createSerializer(){let t=new Sh(this.settings);return t.setSerdeContext(this.serdeContext),t}createDeserializer(){let t=new Th(this.settings);return t.setSerdeContext(this.serdeContext),t}}class qe extends YM{serializer;deserializer;serviceTarget;codec;mixin;awsQueryCompatible;constructor({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:r,jsonCodec:i}){super({defaultNamespace:t,errorTypeRegistries:n});this.serviceTarget=s,this.codec=i??new xe({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(WM(t.input)==="unit"||!r.body)r.body="{}";return r}getPayloadCodec(){return this.codec}async handleError(t,n,s,r,i){let{awsQueryCompatible:e}=this;if(e)this.mixin.setQueryCompatError(r,s);let f=VM(s,r,e)??"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,i,e?this.mixin.findQueryCompatibleError:void 0),h=ft.of(o),u=r.message??r.Message??"UnknownError",l=new(this.compositeErrorRegistry.getErrorCtor(o)??Error)({}),w={},A=this.codec.createDeserializer();for(let[M,E]of h.structIterator())if(r[M]!=null)w[M]=A.readObject(E,r[M]);if(e)this.mixin.queryCompatOutput(r,w);throw this.mixin.decorateServiceException(Object.assign(l,c,{$fault:h.getMergedTraits().error,message:u},w),r)}}class pM extends qe{constructor({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:r,jsonCodec:i}){super({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:r,jsonCodec:i})}getShapeId(){return"aws.protocols#awsJson1_0"}getJsonRpcVersion(){return"1.0"}getDefaultContentType(){return"application/x-amz-json-1.0"}}class ZM extends qe{constructor({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:r,jsonCodec:i}){super({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:r,jsonCodec:i})}getShapeId(){return"aws.protocols#awsJson1_1"}getJsonRpcVersion(){return"1.1"}getDefaultContentType(){return"application/x-amz-json-1.1"}}class vM extends mM{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 xe(s),this.serializer=new QM(this.codec.createSerializer(),s),this.deserializer=new JM(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),i=ft.of(t.input);if(!r.headers["content-type"]){let e=this.mixin.resolveRestContentType(this.getDefaultContentType(),i);if(e)r.headers["content-type"]=e}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),i=ft.of(t.output);for(let[e,f]of i.structIterator())if(f.getMemberTraits().httpPayload&&!(e in r))r[e]=null;return r}async handleError(t,n,s,r,i){let e=KM(s,r)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,e,this.options.defaultNamespace);let{errorSchema:f,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(e,this.options.defaultNamespace,s,r,i),c=ft.of(f),h=r.message??r.Message??"UnknownError",_=new(this.compositeErrorRegistry.getErrorCtor(f)??Error)({});await this.deserializeHttpMessage(f,n,s,r);let l={},w=this.codec.createDeserializer();for(let[A,M]of c.structIterator()){let E=M.getMergedTraits().jsonName??A;l[A]=w.readObject(M,r[E])}throw this.mixin.decorateServiceException(Object.assign(_,o,{$fault:c.getMergedTraits().error,message:h},l),r)}getDefaultContentType(){return"application/json"}}var JF=(t)=>{if(t==null)return;if(typeof t==="object"&&"__type"in t)delete t.__type;return NF(t)};class Ce extends xn{settings;stringDeserializer;constructor(t){super();this.settings=t,this.stringDeserializer=new BF(t)}setSerdeContext(t){this.serdeContext=t,this.stringDeserializer.setSerdeContext(t)}read(t,n,s){let r=ft.of(t),i=r.getMemberSchemas();if(r.isStructSchema()&&r.isMemberSchema()&&!!Object.values(i).find((c)=>{return!!c.getMemberTraits().eventPayload})){let c={},h=Object.keys(i)[0];if(i[h].isBlobSchema())c[h]=n;else c[h]=this.read(i[h],n);return c}let f=(this.serdeContext?.utf8Encoder??kM)(n),o=this.parseXml(f);return this.readSchema(t,s?o[s]:o)}readSchema(t,n){let s=ft.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 i=!!r.xmlFlattened;if(s.isListSchema()){let f=s.getValueSchema(),o=[],c=f.getMergedTraits().xmlName??"member",h=i?n:(n[0]??n)[c];if(h==null)return o;let u=Array.isArray(h)?h:[h];for(let _ of u)o.push(this.readSchema(f,_));return o}let e={};if(s.isMapSchema()){let f=s.getKeySchema(),o=s.getValueSchema(),c;if(i)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 _ of c){let l=_[h],w=_[u];e[l]=this.readSchema(o,w)}return e}if(s.isStructSchema()){let f=s.isUnionSchema(),o;if(f)o=new Rh(n,e);for(let[c,h]of s.structIterator()){let u=h.getMergedTraits(),_=!u.httpPayload?h.getMemberTraits().xmlName??c:u.xmlName??h.getName();if(f)o.mark(_);if(n[_]!=null)e[c]=this.readSchema(h,n[_])}if(f)o.writeUnknown();return e}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=xM(t)}catch(e){if(e&&typeof e==="object")Object.defineProperty(e,"$responseBodyText",{value:t});throw e}let s="#text",r=Object.keys(n)[0],i=n[r];if(i[s])i[r]=i[s],delete i[s];return DM(i)}return{}}}class $h extends xn{settings;buffer;constructor(t){super();this.settings=t}write(t,n,s=""){if(this.buffer===void 0)this.buffer="";let r=ft.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??ke)(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(dh())}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 hn?n.string:String(n))}else if(r.isTimestampSchema()){if(n instanceof Date)switch(this.writeKey(s),ze(r,this.settings)){case 5:this.writeValue(n.toISOString().replace(".000Z","Z"));break;case 6:this.writeValue(Xe(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 i=r.getValueSchema(),e=this.settings.flattenLists||r.getMergedTraits().xmlFlattened,f=1;for(let o of n){if(o==null)continue;let c=i.getMergedTraits(),h=this.getKey("member",c.xmlName,c.ec2QueryName),u=e?`${s}${f}`:`${s}${h}.${f}`;this.write(i,o,u),++f}}}else if(r.isMapSchema()){if(n&&typeof n==="object"){let i=r.getKeySchema(),e=r.getValueSchema(),f=r.getMergedTraits().xmlFlattened,o=1;for(let c in n){let h=n[c];if(h==null)continue;let u=i.getMergedTraits(),_=this.getKey("key",u.xmlName,u.ec2QueryName),l=f?`${s}${o}.${_}`:`${s}entry.${o}.${_}`,w=e.getMergedTraits(),A=this.getKey("value",w.xmlName,w.ec2QueryName),M=f?`${s}${o}.${A}`:`${s}entry.${o}.${A}`;this.write(i,c,l),this.write(e,h,M),++o}}}else if(r.isStructSchema()){if(n&&typeof n==="object"){let i=!1;for(let[e,f]of r.structIterator()){if(n[e]==null&&!f.isIdempotencyToken())continue;let o=f.getMergedTraits(),c=this.getKey(e,o.xmlName,o.ec2QueryName,"struct"),h=`${s}${c}`;this.write(f,n[e],h),i=!0}if(!i&&r.isUnionSchema()){let{$unknown:e}=n;if(Array.isArray(e)){let[f,o]=e,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:i,capitalizeKeys:e}=this.settings;if(i&&s)return s;let f=n??t;if(e&&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+=`&${FM(t)}=`}writeValue(t){this.buffer+=FM(t)}}class Uh extends YM{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 $h(n),this.deserializer=new Ce(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",WM(t.input)==="unit"||!r.body)r.body="";let i=t.name.split("#")[1]??t.name;if(r.body=`Action=${i}&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,i=ft.of(t.output),e={};if(s.statusCode>=300){let h=await Eh(s.body,n);if(h.byteLength>0)Object.assign(e,await r.read(15,h));await this.handleError(t,n,s,e,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=i.isStructSchema()&&this.useNestedResult()?f+"Result":void 0,c=await Eh(s.body,n);if(c.byteLength>0)Object.assign(e,await r.read(i,c,o));return e.$metadata=this.deserializeMetadata(s),e}useNestedResult(){return!0}async handleError(t,n,s,r,i){let e=this.loadQueryErrorCode(s,r)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,e,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(e,this.options.defaultNamespace,s,f,i,this.mixin.findQueryCompatibleError),u=ft.of(c),l=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 E=M.getMergedTraits().xmlName??A,d=f[E]??r[E];w[A]=this.deserializer.readSchema(M,d)}throw this.mixin.decorateServiceException(Object.assign(l,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 t1 extends Uh{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 n1=(t,n)=>CM(t,n).then((s)=>{if(s.length){let r;try{r=xM(s)}catch(o){if(o&&typeof o==="object")Object.defineProperty(o,"$responseBodyText",{value:s});throw o}let i="#text",e=Object.keys(r)[0],f=r[e];if(f[i])f[e]=f[i],delete f[i];return DM(f)}return{}}),kF=async(t,n)=>{let s=await n1(t,n);if(s.Error)s.Error.message=s.Error.message??s.Error.Message;return s},s1=(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 Lh extends xn{settings;stringBuffer;byteBuffer;buffer;constructor(t){super();this.settings=t}write(t,n){let s=ft.of(t);if(s.isStringSchema()&&typeof n==="string")this.stringBuffer=n;else if(s.isBlobSchema())this.byteBuffer="byteLength"in n?n:(this.serdeContext?.base64Decoder??XM)(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(),i=t.isMemberSchema()&&!r.httpPayload?t.getMemberTraits().xmlName??t.getMemberName():r.xmlName??t.getName();if(!i||!t.isStructSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${t.getName(!0)}.`);let e=Ct.of(i),[f,o]=this.getXmlnsAttribute(t,s);for(let[h,u]of t.structIterator()){let _=n[h];if(_!=null||u.isIdempotencyToken()){if(u.getMergedTraits().xmlAttribute){e.addAttribute(u.getMergedTraits().xmlName??h,this.writeSimple(u,_));continue}if(u.isListSchema())this.writeList(u,_,e,o);else if(u.isMapSchema())this.writeMap(u,_,e,o);else if(u.isStructSchema())e.addChildNode(this.writeStruct(u,_,o));else{let l=Ct.of(u.getMergedTraits().xmlName??u.getMemberName());this.writeSimpleInto(u,_,l,o),e.addChildNode(l)}}}let{$unknown:c}=n;if(c&&t.isUnionSchema()&&Array.isArray(c)&&Object.keys(n).length===1){let[h,u]=c,_=Ct.of(h);if(typeof u!=="string")if(n instanceof Ct||n instanceof HM)e.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,_,o),e.addChildNode(_)}if(o)e.addAttribute(f,o);return e}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 i=t.getMergedTraits(),e=t.getValueSchema(),f=e.getMergedTraits(),o=!!f.sparse,c=!!i.xmlFlattened,[h,u]=this.getXmlnsAttribute(t,r),_=(l,w)=>{if(e.isListSchema())this.writeList(e,Array.isArray(w)?w:[w],l,u);else if(e.isMapSchema())this.writeMap(e,w,l,u);else if(e.isStructSchema()){let A=this.writeStruct(e,w,u);l.addChildNode(A.withName(c?i.xmlName??t.getMemberName():f.xmlName??"member"))}else{let A=Ct.of(c?i.xmlName??t.getMemberName():f.xmlName??"member");this.writeSimpleInto(e,w,A,u),l.addChildNode(A)}};if(c){for(let l of n)if(o||l!=null)_(s,l)}else{let l=Ct.of(i.xmlName??t.getMemberName());if(u)l.addAttribute(h,u);for(let w of n)if(o||w!=null)_(l,w);s.addChildNode(l)}}writeMap(t,n,s,r,i=!1){if(!t.isMemberSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${t.getName(!0)}`);let e=t.getMergedTraits(),f=t.getKeySchema(),c=f.getMergedTraits().xmlName??"key",h=t.getValueSchema(),u=h.getMergedTraits(),_=u.xmlName??"value",l=!!u.sparse,w=!!e.xmlFlattened,[A,M]=this.getXmlnsAttribute(t,r),E=(d,T,U)=>{let S=Ct.of(c,T),[O,D]=this.getXmlnsAttribute(f,M);if(D)S.addAttribute(O,D);d.addChildNode(S);let q=Ct.of(_);if(h.isListSchema())this.writeList(h,U,q,M);else if(h.isMapSchema())this.writeMap(h,U,q,M,!0);else if(h.isStructSchema())q=this.writeStruct(h,U,M);else this.writeSimpleInto(h,U,q,M);d.addChildNode(q)};if(w)for(let d in n){let T=n[d];if(l||T!=null){let U=Ct.of(e.xmlName??t.getMemberName());E(U,d,T),s.addChildNode(U)}}else{let d;if(!i){if(d=Ct.of(e.xmlName??t.getMemberName()),M)d.addAttribute(A,M);s.addChildNode(d)}for(let T in n){let U=n[T];if(l||U!=null){let S=Ct.of("entry");E(S,T,U),(i?s:d).addChildNode(S)}}}}writeSimple(t,n){if(n===null)throw Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value.");let s=ft.of(t),r=null;if(n&&typeof n==="object")if(s.isBlobSchema())r=(this.serdeContext?.base64Encoder??ke)(n);else if(s.isTimestampSchema()&&n instanceof Date)switch(ze(s,this.settings)){case 5:r=n.toISOString().replace(".000Z","Z");break;case 6:r=Xe(n);break;case 7:r=String(n.getTime()/1000);break;default:console.warn("Missing timestamp format, using http date",n),r=Xe(n);break}else if(s.isBigDecimalSchema()&&n){if(n instanceof hn)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=dh();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 i=this.writeSimple(t,n),e=ft.of(t),f=new HM(i),[o,c]=this.getXmlnsAttribute(e,r);if(c)s.addAttribute(o,c);s.addChildNode(f)}getXmlnsAttribute(t,n){let s=t.getMergedTraits(),[r,i]=s.xmlNamespace??[];if(i&&i!==n)return[r?`xmlns:${r}`:"xmlns",i];return[void 0,void 0]}}class Ih extends xn{settings;constructor(t){super();this.settings=t}createSerializer(){let t=new Lh(this.settings);return t.setSerdeContext(this.serdeContext),t}createDeserializer(){let t=new Ce(this.settings);return t.setSerdeContext(this.serdeContext),t}}class r1 extends mM{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 Ih(n),this.serializer=new QM(this.codec.createSerializer(),n),this.deserializer=new JM(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),i=ft.of(t.input);if(!r.headers["content-type"]){let e=this.mixin.resolveRestContentType(this.getDefaultContentType(),i);if(e)r.headers["content-type"]=e}if(typeof r.body==="string"&&r.headers["content-type"]===this.getDefaultContentType()&&!r.body.startsWith("<?xml ")&&!this.hasUnstructuredPayloadBinding(i))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,i){let e=s1(s,r)??"Unknown";if(this.mixin.compose(this.compositeErrorRegistry,e,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&&!i.requestId)i.requestId=r.RequestId;let{errorSchema:f,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(e,this.options.defaultNamespace,s,r,i),c=ft.of(f),h=r.Error?.message??r.Error?.Message??r.message??r.Message??"UnknownError",_=new(this.compositeErrorRegistry.getErrorCtor(f)??Error)({});await this.deserializeHttpMessage(f,n,s,r);let l={},w=this.codec.createDeserializer();for(let[A,M]of c.structIterator()){let E=M.getMergedTraits().xmlName??A,d=r.Error?.[E]??r[E];l[A]=w.readSchema(M,d)}throw this.mixin.decorateServiceException(Object.assign(_,o,{$fault:c.getMergedTraits().error,message:h},l),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}}XF.AwsEc2QueryProtocol=t1;XF.AwsJson1_0Protocol=pM;XF.AwsJson1_1Protocol=ZM;XF.AwsJsonRpcProtocol=qe;XF.AwsQueryProtocol=Uh;XF.AwsRestJsonProtocol=vM;XF.AwsRestXmlProtocol=r1;XF.AwsSmithyRpcV2CborProtocol=qM;XF.JsonCodec=xe;XF.JsonShapeDeserializer=Th;XF.JsonShapeSerializer=Sh;XF.QueryShapeSerializer=$h;XF.XmlCodec=Ih;XF.XmlShapeDeserializer=Ce;XF.XmlShapeSerializer=Lh;XF._toBool=DF;XF._toNum=YF;XF._toStr=WF;XF.awsExpectUnion=JF;XF.loadJsonRpcErrorCode=VM;XF.loadRestJsonErrorCode=KM;XF.loadRestXmlErrorCode=s1;XF.parseJsonBody=bh;XF.parseJsonErrorBody=QF;XF.parseXmlBody=n1;XF.parseXmlErrorBody=kF});var Ph=Z((GN)=>{var{awsEndpointFunctions:MH,emitWarningIfUnsupportedVersion:gH,createDefaultUserAgentProvider:EH,NODE_APP_ID_CONFIG_OPTIONS:dH,getAwsRegionExtensionConfiguration:RH,resolveAwsRegionExtensionConfiguration:bH,resolveUserAgentConfig:TH,resolveHostHeaderConfig:SH,getUserAgentPlugin:$H,getHostHeaderPlugin:UH,getLoggerPlugin:LH,getRecursionDetectionPlugin:IH}=xt(),{NoAuthSigner:OH,getHttpAuthSchemeEndpointRuleSetPlugin:yH,DefaultIdentityProviderConfig:GH,getHttpSigningPlugin:BH}=kn(),{normalizeProvider:c1,getSmithyContext:FH,ServiceException:HH,NoOpLogger:PH,emitWarningIfUnsupportedVersion:NH,loadConfigsForDefaultMode:WH,getDefaultExtensionConfiguration:DH,resolveDefaultRuntimeConfig:YH,Client:h1,makeBuilder:mH,createAggregatedClient:QH}=Rn(),{Command:JH}=Rn();GN.$Command=JH;GN.__Client=h1;var{resolveDefaultsModeConfig:kH,loadConfig:As,NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS:XH,NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS:zH,NODE_REGION_CONFIG_OPTIONS:xH,NODE_REGION_CONFIG_FILE_OPTIONS:qH,resolveRegionConfig:CH}=St(),{BinaryDecisionDiagram:KH,EndpointCache:VH,decideEndpoint:jH,customEndpointFunctions:aH,resolveEndpointConfig:pH,getEndpointPlugin:ZH}=fs(),{parseUrl:vH,getHttpHandlerExtensionConfiguration:tP,resolveHttpHandlerRuntimeConfig:nP,getContentLengthPlugin:sP}=Ut(),{DEFAULT_RETRY_MODE:rP,NODE_RETRY_MODE_CONFIG_OPTIONS:iP,NODE_MAX_ATTEMPT_CONFIG_OPTIONS:eP,resolveRetryConfig:oP,getRetryPlugin:fP}=vr(),{TypeRegistry:u1,getSchemaSerdePlugin:cP}=Nn(),{resolveAwsSdkSigV4Config:hP,AwsSdkSigV4Signer:uP,NODE_AUTH_SCHEME_PREFERENCE_OPTIONS:_P}=jc(),{toUtf8:lP,fromUtf8:wP,toBase64:AP,fromBase64:MP,calculateBodyLength:gP}=$t(),{streamCollector:EP,NodeHttpHandler:dP}=me(),{AwsRestJsonProtocol:RP}=Oh(),{Sha256:bP}=tc(),TP=async(t,n,s)=>{return{operation:FH(n).operation,region:await c1(t.region)()||(()=>{throw Error("expected `region` to be configured for `aws.auth#sigv4`")})()}};function SP(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sso-oauth",region:t.region},propertiesExtractor:(n,s)=>({signingProperties:{config:n,context:s}})}}function $P(t){return{schemeId:"smithy.api#noAuth"}}var UP=(t)=>{let n=[];switch(t.operation){case"CreateToken":{n.push($P());break}default:n.push(SP(t))}return n},LP=(t)=>{let n=hP(t);return Object.assign(n,{authSchemePreference:c1(t.authSchemePreference??[])})},IP=(t)=>{return Object.assign(t,{useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,defaultSigningName:"sso-oauth"})},OP={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},yP="3.997.32",GP={version:yP},li="ref",Ms=-1,Ke=!0,i1="isSet",_1="PartitionResult",Ve="booleanEquals",yh="getAttr",e1={[li]:"Endpoint"},Gh={[li]:_1},fr={},o1=[{[li]:"Region"}],f1={conditions:[[i1,[e1]],[i1,o1],["aws.partition",o1,_1],[Ve,[{[li]:"UseFIPS"},Ke]],[Ve,[{[li]:"UseDualStack"},Ke]],[Ve,[{fn:yh,argv:[Gh,"supportsDualStack"]},Ke]],[Ve,[{fn:yh,argv:[Gh,"supportsFIPS"]},Ke]],["stringEquals",[{fn:yh,argv:[Gh,"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"],[e1,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"]]},BP=2,Lt=1e8,FP=new Int32Array([-1,1,-1,0,13,3,1,4,Lt+12,2,5,Lt+12,3,8,6,4,7,Lt+11,5,Lt+9,Lt+10,4,11,9,6,10,Lt+8,7,Lt+6,Lt+7,5,12,Lt+5,6,Lt+4,Lt+5,3,Lt+1,14,4,Lt+2,Lt+3]),HP=KH.from(FP,BP,f1.conditions,f1.results),PP=new VH({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),NP=(t,n={})=>{return PP.get(t,()=>jH(HP,{endpointParams:t,logger:n.logger}))};aH.aws=MH;class Rt extends HH{constructor(t){super(t);Object.setPrototypeOf(this,Rt.prototype)}}class je extends Rt{name="AccessDeniedException";$fault="client";error;reason;error_description;constructor(t){super({name:"AccessDeniedException",$fault:"client",...t});Object.setPrototypeOf(this,je.prototype),this.error=t.error,this.reason=t.reason,this.error_description=t.error_description}}class ae extends Rt{name="AuthorizationPendingException";$fault="client";error;error_description;constructor(t){super({name:"AuthorizationPendingException",$fault:"client",...t});Object.setPrototypeOf(this,ae.prototype),this.error=t.error,this.error_description=t.error_description}}class pe extends Rt{name="ExpiredTokenException";$fault="client";error;error_description;constructor(t){super({name:"ExpiredTokenException",$fault:"client",...t});Object.setPrototypeOf(this,pe.prototype),this.error=t.error,this.error_description=t.error_description}}class Ze extends Rt{name="InternalServerException";$fault="server";error;error_description;constructor(t){super({name:"InternalServerException",$fault:"server",...t});Object.setPrototypeOf(this,Ze.prototype),this.error=t.error,this.error_description=t.error_description}}class ve extends Rt{name="InvalidClientException";$fault="client";error;error_description;constructor(t){super({name:"InvalidClientException",$fault:"client",...t});Object.setPrototypeOf(this,ve.prototype),this.error=t.error,this.error_description=t.error_description}}class to extends Rt{name="InvalidGrantException";$fault="client";error;error_description;constructor(t){super({name:"InvalidGrantException",$fault:"client",...t});Object.setPrototypeOf(this,to.prototype),this.error=t.error,this.error_description=t.error_description}}class no extends Rt{name="InvalidRequestException";$fault="client";error;reason;error_description;constructor(t){super({name:"InvalidRequestException",$fault:"client",...t});Object.setPrototypeOf(this,no.prototype),this.error=t.error,this.reason=t.reason,this.error_description=t.error_description}}class so extends Rt{name="InvalidScopeException";$fault="client";error;error_description;constructor(t){super({name:"InvalidScopeException",$fault:"client",...t});Object.setPrototypeOf(this,so.prototype),this.error=t.error,this.error_description=t.error_description}}class ro extends Rt{name="SlowDownException";$fault="client";error;error_description;constructor(t){super({name:"SlowDownException",$fault:"client",...t});Object.setPrototypeOf(this,ro.prototype),this.error=t.error,this.error_description=t.error_description}}class io extends Rt{name="UnauthorizedClientException";$fault="client";error;error_description;constructor(t){super({name:"UnauthorizedClientException",$fault:"client",...t});Object.setPrototypeOf(this,io.prototype),this.error=t.error,this.error_description=t.error_description}}class eo extends Rt{name="UnsupportedGrantTypeException";$fault="client";error;error_description;constructor(t){super({name:"UnsupportedGrantTypeException",$fault:"client",...t});Object.setPrototypeOf(this,eo.prototype),this.error=t.error,this.error_description=t.error_description}}var WP="AccessDeniedException",DP="AuthorizationPendingException",YP="AccessToken",mP="ClientSecret",QP="CreateToken",JP="CreateTokenRequest",kP="CreateTokenResponse",XP="CodeVerifier",zP="ExpiredTokenException",xP="InvalidClientException",qP="InvalidGrantException",CP="InvalidRequestException",KP="InternalServerException",VP="InvalidScopeException",jP="IdToken",aP="RefreshToken",pP="SlowDownException",ZP="UnauthorizedClientException",vP="UnsupportedGrantTypeException",tN="accessToken",un="client",nN="clientId",sN="clientSecret",rN="codeVerifier",iN="code",eN="deviceCode",et="error",oN="expiresIn",Kt="error_description",fN="grantType",cN="http",Vt="httpError",hN="idToken",l1="reason",w1="refreshToken",uN="redirectUri",A1="smithy.ts.sdk.synthetic.com.amazonaws.ssooidc",_N="scope",lN="server",wN="tokenType",ct="com.amazonaws.ssooidc",M1=u1.for(A1),g1=[-3,A1,"SSOOIDCServiceException",0,[],[]];M1.registerError(g1,Rt);var Yt=u1.for(ct),E1=[-3,ct,WP,{[et]:un,[Vt]:400},[et,l1,Kt],[0,0,0]];Yt.registerError(E1,je);var d1=[-3,ct,DP,{[et]:un,[Vt]:400},[et,Kt],[0,0]];Yt.registerError(d1,ae);var R1=[-3,ct,zP,{[et]:un,[Vt]:400},[et,Kt],[0,0]];Yt.registerError(R1,pe);var b1=[-3,ct,KP,{[et]:lN,[Vt]:500},[et,Kt],[0,0]];Yt.registerError(b1,Ze);var T1=[-3,ct,xP,{[et]:un,[Vt]:401},[et,Kt],[0,0]];Yt.registerError(T1,ve);var S1=[-3,ct,qP,{[et]:un,[Vt]:400},[et,Kt],[0,0]];Yt.registerError(S1,to);var $1=[-3,ct,CP,{[et]:un,[Vt]:400},[et,l1,Kt],[0,0,0]];Yt.registerError($1,no);var U1=[-3,ct,VP,{[et]:un,[Vt]:400},[et,Kt],[0,0]];Yt.registerError(U1,so);var L1=[-3,ct,pP,{[et]:un,[Vt]:400},[et,Kt],[0,0]];Yt.registerError(L1,ro);var I1=[-3,ct,ZP,{[et]:un,[Vt]:400},[et,Kt],[0,0]];Yt.registerError(I1,io);var O1=[-3,ct,vP,{[et]:un,[Vt]:400},[et,Kt],[0,0]];Yt.registerError(O1,eo);var y1=[M1,Yt],AN=[0,ct,YP,8,0],MN=[0,ct,mP,8,0],gN=[0,ct,XP,8,0],EN=[0,ct,jP,8,0],G1=[0,ct,aP,8,0],B1=[3,ct,JP,0,[nN,sN,fN,eN,iN,w1,_N,uN,rN],[0,[()=>MN,0],0,0,0,[()=>G1,0],64,0,[()=>gN,0]],3],F1=[3,ct,kP,0,[tN,wN,oN,w1,hN],[[()=>AN,0],0,1,[()=>G1,0],[()=>EN,0]]],H1=[9,ct,QP,{[cN]:["POST","/token",200]},()=>B1,()=>F1],dN=(t)=>{return{apiVersion:"2019-06-10",base64Decoder:t?.base64Decoder??MP,base64Encoder:t?.base64Encoder??AP,disableHostPrefix:t?.disableHostPrefix??!1,endpointProvider:t?.endpointProvider??NP,extensions:t?.extensions??[],httpAuthSchemeProvider:t?.httpAuthSchemeProvider??UP,httpAuthSchemes:t?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(n)=>n.getIdentityProvider("aws.auth#sigv4"),signer:new uP},{schemeId:"smithy.api#noAuth",identityProvider:(n)=>n.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new OH}],logger:t?.logger??new PH,protocol:t?.protocol??RP,protocolSettings:t?.protocolSettings??{defaultNamespace:"com.amazonaws.ssooidc",errorTypeRegistries:y1,version:"2019-06-10",serviceTarget:"AWSSSOOIDCService"},serviceId:t?.serviceId??"SSO OIDC",sha256:t?.sha256??bP,urlParser:t?.urlParser??vH,utf8Decoder:t?.utf8Decoder??wP,utf8Encoder:t?.utf8Encoder??lP}},RN=(t)=>{NH(process.version);let n=kH(t),s=()=>n().then(WH),r=dN(t);gH(process.version);let i={profile:t?.profile,logger:r.logger};return{...r,...t,runtime:"node",defaultsMode:n,authSchemePreference:t?.authSchemePreference??As(_P,i),bodyLengthChecker:t?.bodyLengthChecker??gP,defaultUserAgentProvider:t?.defaultUserAgentProvider??EH({serviceId:r.serviceId,clientVersion:GP.version}),maxAttempts:t?.maxAttempts??As(eP,t),region:t?.region??As(xH,{...qH,...i}),requestHandler:dP.create(t?.requestHandler??s),retryMode:t?.retryMode??As({...iP,default:async()=>(await s()).retryMode||rP},t),streamCollector:t?.streamCollector??EP,useDualstackEndpoint:t?.useDualstackEndpoint??As(zH,i),useFipsEndpoint:t?.useFipsEndpoint??As(XH,i),userAgentAppId:t?.userAgentAppId??As(dH,i)}},bN=(t)=>{let{httpAuthSchemes:n,httpAuthSchemeProvider:s,credentials:r}=t;return{setHttpAuthScheme(i){let e=n.findIndex((f)=>f.schemeId===i.schemeId);if(e===-1)n.push(i);else n.splice(e,1,i)},httpAuthSchemes(){return n},setHttpAuthSchemeProvider(i){s=i},httpAuthSchemeProvider(){return s},setCredentials(i){r=i},credentials(){return r}}},TN=(t)=>{return{httpAuthSchemes:t.httpAuthSchemes(),httpAuthSchemeProvider:t.httpAuthSchemeProvider(),credentials:t.credentials()}},SN=(t,n)=>{let s=Object.assign(RH(t),DH(t),tP(t),bN(t));return n.forEach((r)=>r.configure(s)),Object.assign(t,bH(s),YH(s),nP(s),TN(s))};class Bh extends h1{config;constructor(...[t]){let n=RN(t||{});super(n);this.initConfig=n;let s=IP(n),r=TH(s),i=oP(r),e=CH(i),f=SH(e),o=pH(f),c=LP(o),h=SN(c,t?.extensions||[]);this.config=h,this.middlewareStack.use(cP(this.config)),this.middlewareStack.use($H(this.config)),this.middlewareStack.use(fP(this.config)),this.middlewareStack.use(sP(this.config)),this.middlewareStack.use(UH(this.config)),this.middlewareStack.use(LH(this.config)),this.middlewareStack.use(IH(this.config)),this.middlewareStack.use(yH(this.config,{httpAuthSchemeParametersProvider:TP,identityProviderConfigProvider:async(u)=>new GH({"aws.auth#sigv4":u.credentials})})),this.middlewareStack.use(BH(this.config))}destroy(){super.destroy()}}var $N=mH(OP,"AWSSSOOIDCService","SSOOIDCClient",ZH),UN={},LN=(t,n,s,r)=>[];class Fh extends $N(UN,LN,"CreateToken",H1){}var IN={CreateTokenCommand:Fh};class Hh extends Bh{}QH(IN,Hh);var ON={KMS_ACCESS_DENIED:"KMS_AccessDeniedException"},yN={KMS_DISABLED_KEY:"KMS_DisabledException",KMS_INVALID_KEY_USAGE:"KMS_InvalidKeyUsageException",KMS_INVALID_STATE:"KMS_InvalidStateException",KMS_KEY_NOT_FOUND:"KMS_NotFoundException"};GN.AccessDeniedException=je;GN.AccessDeniedException$=E1;GN.AccessDeniedExceptionReason=ON;GN.AuthorizationPendingException=ae;GN.AuthorizationPendingException$=d1;GN.CreateToken$=H1;GN.CreateTokenCommand=Fh;GN.CreateTokenRequest$=B1;GN.CreateTokenResponse$=F1;GN.ExpiredTokenException=pe;GN.ExpiredTokenException$=R1;GN.InternalServerException=Ze;GN.InternalServerException$=b1;GN.InvalidClientException=ve;GN.InvalidClientException$=T1;GN.InvalidGrantException=to;GN.InvalidGrantException$=S1;GN.InvalidRequestException=no;GN.InvalidRequestException$=$1;GN.InvalidRequestExceptionReason=yN;GN.InvalidScopeException=so;GN.InvalidScopeException$=U1;GN.SSOOIDC=Hh;GN.SSOOIDCClient=Bh;GN.SSOOIDCServiceException=Rt;GN.SSOOIDCServiceException$=g1;GN.SlowDownException=ro;GN.SlowDownException$=L1;GN.UnauthorizedClientException=io;GN.UnauthorizedClientException$=I1;GN.UnsupportedGrantTypeException=eo;GN.UnsupportedGrantTypeException$=O1;GN.errorTypeRegistries=y1});import{existsSync as sR,readFileSync as rR}from"fs";import{homedir as iR}from"os";import{join as G0}from"path";var g={};zE(g,{void:()=>Od,util:()=>x,unknown:()=>Ld,union:()=>Fd,undefined:()=>Sd,tuple:()=>Nd,transformer:()=>xd,symbol:()=>Td,string:()=>I0,strictObject:()=>Bd,setErrorMap:()=>CE,set:()=>Yd,record:()=>Wd,quotelessJson:()=>xE,promise:()=>zd,preprocess:()=>Kd,pipeline:()=>Vd,ostring:()=>jd,optional:()=>qd,onumber:()=>ad,oboolean:()=>pd,objectUtil:()=>Jo,object:()=>Gd,number:()=>O0,nullable:()=>Cd,null:()=>$d,never:()=>Id,nativeEnum:()=>Xd,nan:()=>dd,map:()=>Dd,makeIssue:()=>gr,literal:()=>Jd,lazy:()=>Qd,late:()=>gd,isValid:()=>On,isDirty:()=>Si,isAsync:()=>Ss,isAborted:()=>Ti,intersection:()=>Pd,instanceof:()=>Ed,getParsedType:()=>at,getErrorMap:()=>Ts,function:()=>md,enum:()=>kd,effect:()=>xd,discriminatedUnion:()=>Hd,defaultErrorMap:()=>An,datetimeRegex:()=>$0,date:()=>bd,custom:()=>L0,coerce:()=>Zd,boolean:()=>y0,bigint:()=>Rd,array:()=>yd,any:()=>Ud,addIssueToContext:()=>L,ZodVoid:()=>dr,ZodUnknown:()=>yn,ZodUnion:()=>ys,ZodUndefined:()=>Is,ZodType:()=>X,ZodTuple:()=>Zt,ZodTransformer:()=>Xt,ZodSymbol:()=>Er,ZodString:()=>mt,ZodSet:()=>pn,ZodSchema:()=>X,ZodRecord:()=>Rr,ZodReadonly:()=>Ws,ZodPromise:()=>Zn,ZodPipeline:()=>Sr,ZodParsedType:()=>$,ZodOptional:()=>Jt,ZodObject:()=>rt,ZodNumber:()=>Gn,ZodNullable:()=>gn,ZodNull:()=>Os,ZodNever:()=>pt,ZodNativeEnum:()=>Hs,ZodNaN:()=>Tr,ZodMap:()=>br,ZodLiteral:()=>Fs,ZodLazy:()=>Bs,ZodIssueCode:()=>b,ZodIntersection:()=>Gs,ZodFunction:()=>Us,ZodFirstPartyTypeKind:()=>N,ZodError:()=>bt,ZodEnum:()=>Fn,ZodEffects:()=>Xt,ZodDiscriminatedUnion:()=>$i,ZodDefault:()=>Ps,ZodDate:()=>jn,ZodCatch:()=>Ns,ZodBranded:()=>Ui,ZodBoolean:()=>Ls,ZodBigInt:()=>Bn,ZodArray:()=>Qt,ZodAny:()=>an,Schema:()=>X,ParseStatus:()=>lt,OK:()=>gt,NEVER:()=>vd,INVALID:()=>P,EMPTY_PATH:()=>KE,DIRTY:()=>Vn,BRAND:()=>Md});var x;(function(t){t.assertEqual=(i)=>{};function n(i){}t.assertIs=n;function s(i){throw Error()}t.assertNever=s,t.arrayToEnum=(i)=>{let e={};for(let f of i)e[f]=f;return e},t.getValidEnumValues=(i)=>{let e=t.objectKeys(i).filter((o)=>typeof i[i[o]]!=="number"),f={};for(let o of e)f[o]=i[o];return t.objectValues(f)},t.objectValues=(i)=>{return t.objectKeys(i).map(function(e){return i[e]})},t.objectKeys=typeof Object.keys==="function"?(i)=>Object.keys(i):(i)=>{let e=[];for(let f in i)if(Object.prototype.hasOwnProperty.call(i,f))e.push(f);return e},t.find=(i,e)=>{for(let f of i)if(e(f))return f;return},t.isInteger=typeof Number.isInteger==="function"?(i)=>Number.isInteger(i):(i)=>typeof i==="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,e=" | "){return i.map((f)=>typeof f==="string"?`'${f}'`:f).join(e)}t.joinValues=r,t.jsonStringifyReplacer=(i,e)=>{if(typeof e==="bigint")return e.toString();return e}})(x||(x={}));var Jo;(function(t){t.mergeShapes=(n,s)=>{return{...n,...s}}})(Jo||(Jo={}));var $=x.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),at=(t)=>{switch(typeof t){case"undefined":return $.undefined;case"string":return $.string;case"number":return Number.isNaN(t)?$.nan:$.number;case"boolean":return $.boolean;case"function":return $.function;case"bigint":return $.bigint;case"symbol":return $.symbol;case"object":if(Array.isArray(t))return $.array;if(t===null)return $.null;if(t.then&&typeof t.then==="function"&&t.catch&&typeof t.catch==="function")return $.promise;if(typeof Map<"u"&&t instanceof Map)return $.map;if(typeof Set<"u"&&t instanceof Set)return $.set;if(typeof Date<"u"&&t instanceof Date)return $.date;return $.object;default:return $.unknown}};var b=x.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"]),xE=(t)=>{return JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:")};class bt 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(i){return i.message},s={_errors:[]},r=(i)=>{for(let e of i.issues)if(e.code==="invalid_union")e.unionErrors.map(r);else if(e.code==="invalid_return_type")r(e.returnTypeError);else if(e.code==="invalid_arguments")r(e.argumentsError);else if(e.path.length===0)s._errors.push(n(e));else{let f=s,o=0;while(o<e.path.length){let c=e.path[o];if(o!==e.path.length-1)f[c]=f[c]||{_errors:[]};else f[c]=f[c]||{_errors:[]},f[c]._errors.push(n(e));f=f[c],o++}}};return r(this),s}static assert(t){if(!(t instanceof bt))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,x.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 i=r.path[0];n[i]=n[i]||[],n[i].push(t(r))}else s.push(t(r));return{formErrors:s,fieldErrors:n}}get formErrors(){return this.flatten()}}bt.create=(t)=>{return new bt(t)};var qE=(t,n)=>{let s;switch(t.code){case b.invalid_type:if(t.received===$.undefined)s="Required";else s=`Expected ${t.expected}, received ${t.received}`;break;case b.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(t.expected,x.jsonStringifyReplacer)}`;break;case b.unrecognized_keys:s=`Unrecognized key(s) in object: ${x.joinValues(t.keys,", ")}`;break;case b.invalid_union:s="Invalid input";break;case b.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${x.joinValues(t.options)}`;break;case b.invalid_enum_value:s=`Invalid enum value. Expected ${x.joinValues(t.options)}, received '${t.received}'`;break;case b.invalid_arguments:s="Invalid function arguments";break;case b.invalid_return_type:s="Invalid function return type";break;case b.invalid_date:s="Invalid date";break;case b.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 x.assertNever(t.validation);else if(t.validation!=="regex")s=`Invalid ${t.validation}`;else s="Invalid";break;case b.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 b.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 b.custom:s="Invalid input";break;case b.invalid_intersection_types:s="Intersection results could not be merged";break;case b.not_multiple_of:s=`Number must be a multiple of ${t.multipleOf}`;break;case b.not_finite:s="Number must be finite";break;default:s=n.defaultError,x.assertNever(t)}return{message:s}},An=qE;var d0=An;function CE(t){d0=t}function Ts(){return d0}var gr=(t)=>{let{data:n,path:s,errorMaps:r,issueData:i}=t,e=[...s,...i.path||[]],f={...i,path:e};if(i.message!==void 0)return{...i,path:e,message:i.message};let o="",c=r.filter((h)=>!!h).slice().reverse();for(let h of c)o=h(f,{data:n,defaultError:o}).message;return{...i,path:e,message:o}},KE=[];function L(t,n){let s=Ts(),r=gr({issueData:n,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,s,s===An?void 0:An].filter((i)=>!!i)});t.common.issues.push(r)}class lt{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 P;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 i=await r.key,e=await r.value;s.push({key:i,value:e})}return lt.mergeObjectSync(t,s)}static mergeObjectSync(t,n){let s={};for(let r of n){let{key:i,value:e}=r;if(i.status==="aborted")return P;if(e.status==="aborted")return P;if(i.status==="dirty")t.dirty();if(e.status==="dirty")t.dirty();if(i.value!=="__proto__"&&(typeof e.value<"u"||r.alwaysSet))s[i.value]=e.value}return{status:t.value,value:s}}}var P=Object.freeze({status:"aborted"}),Vn=(t)=>({status:"dirty",value:t}),gt=(t)=>({status:"valid",value:t}),Ti=(t)=>t.status==="aborted",Si=(t)=>t.status==="dirty",On=(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 kt{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 R0=(t,n)=>{if(On(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 bt(t.common.issues);return this._error=s,this._error}}}};function Q(t){if(!t)return{};let{errorMap:n,invalid_type_error:s,required_error:r,description:i}=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:i};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:i}}class X{get description(){return this._def.description}_getType(t){return at(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:at(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new lt,ctx:{common:t.parent.common,data:t.data,parsedType:at(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:at(t)},r=this._parseSync({data:t,path:s.path,parent:s});return R0(s,r)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:at(t)};if(!this["~standard"].async)try{let s=this._parseSync({data:t,path:[],parent:n});return On(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)=>On(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:at(t)},r=this._parse({data:t,path:s.path,parent:s}),i=await(Ss(r)?r:Promise.resolve(r));return R0(s,i)}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,i)=>{let e=t(r),f=()=>i.addIssue({code:b.custom,...s(r)});if(typeof Promise<"u"&&e instanceof Promise)return e.then((o)=>{if(!o)return f(),!1;else return!0});if(!e)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 Xt({schema:this,typeName:N.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 Jt.create(this,this._def)}nullable(){return gn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Qt.create(this)}promise(){return Zn.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 Xt({...Q(this._def),schema:this,typeName:N.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t==="function"?t:()=>t;return new Ps({...Q(this._def),innerType:this,defaultValue:n,typeName:N.ZodDefault})}brand(){return new Ui({typeName:N.ZodBranded,type:this,...Q(this._def)})}catch(t){let n=typeof t==="function"?t:()=>t;return new Ns({...Q(this._def),innerType:this,catchValue:n,typeName:N.ZodCatch})}describe(t){return new this.constructor({...this._def,description:t})}pipe(t){return Sr.create(this,t)}readonly(){return Ws.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var VE=/^c[^\s-]{8,}$/i,jE=/^[0-9a-z]+$/,aE=/^[0-9A-HJKMNP-TV-Z]{26}$/i,pE=/^[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,ZE=/^[a-z0-9_-]{21}$/i,vE=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,td=/^[-+]?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)?)??$/,nd=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,sd="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ko,rd=/^(?:(?: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])$/,id=/^(?:(?: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])$/,ed=/^(([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]))$/,od=/^(([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])$/,fd=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,cd=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,T0="((\\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])))",hd=new RegExp(`^${T0}$`);function S0(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 ud(t){return new RegExp(`^${S0(t)}$`)}function $0(t){let n=`${T0}T${S0(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 _d(t,n){if((n==="v4"||!n)&&rd.test(t))return!0;if((n==="v6"||!n)&&ed.test(t))return!0;return!1}function ld(t,n){if(!vE.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,"="),i=JSON.parse(atob(r));if(typeof i!=="object"||i===null)return!1;if("typ"in i&&i?.typ!=="JWT")return!1;if(!i.alg)return!1;if(n&&i.alg!==n)return!1;return!0}catch{return!1}}function wd(t,n){if((n==="v4"||!n)&&id.test(t))return!0;if((n==="v6"||!n)&&od.test(t))return!0;return!1}class mt extends X{_parse(t){if(this._def.coerce)t.data=String(t.data);if(this._getType(t)!==$.string){let i=this._getOrReturnCtx(t);return L(i,{code:b.invalid_type,expected:$.string,received:i.parsedType}),P}let s=new lt,r=void 0;for(let i of this._def.checks)if(i.kind==="min"){if(t.data.length<i.value)r=this._getOrReturnCtx(t,r),L(r,{code:b.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty()}else if(i.kind==="max"){if(t.data.length>i.value)r=this._getOrReturnCtx(t,r),L(r,{code:b.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty()}else if(i.kind==="length"){let e=t.data.length>i.value,f=t.data.length<i.value;if(e||f){if(r=this._getOrReturnCtx(t,r),e)L(r,{code:b.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message});else if(f)L(r,{code:b.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message});s.dirty()}}else if(i.kind==="email"){if(!nd.test(t.data))r=this._getOrReturnCtx(t,r),L(r,{validation:"email",code:b.invalid_string,message:i.message}),s.dirty()}else if(i.kind==="emoji"){if(!ko)ko=new RegExp(sd,"u");if(!ko.test(t.data))r=this._getOrReturnCtx(t,r),L(r,{validation:"emoji",code:b.invalid_string,message:i.message}),s.dirty()}else if(i.kind==="uuid"){if(!pE.test(t.data))r=this._getOrReturnCtx(t,r),L(r,{validation:"uuid",code:b.invalid_string,message:i.message}),s.dirty()}else if(i.kind==="nanoid"){if(!ZE.test(t.data))r=this._getOrReturnCtx(t,r),L(r,{validation:"nanoid",code:b.invalid_string,message:i.message}),s.dirty()}else if(i.kind==="cuid"){if(!VE.test(t.data))r=this._getOrReturnCtx(t,r),L(r,{validation:"cuid",code:b.invalid_string,message:i.message}),s.dirty()}else if(i.kind==="cuid2"){if(!jE.test(t.data))r=this._getOrReturnCtx(t,r),L(r,{validation:"cuid2",code:b.invalid_string,message:i.message}),s.dirty()}else if(i.kind==="ulid"){if(!aE.test(t.data))r=this._getOrReturnCtx(t,r),L(r,{validation:"ulid",code:b.invalid_string,message:i.message}),s.dirty()}else if(i.kind==="url")try{new URL(t.data)}catch{r=this._getOrReturnCtx(t,r),L(r,{validation:"url",code:b.invalid_string,message:i.message}),s.dirty()}else if(i.kind==="regex"){if(i.regex.lastIndex=0,!i.regex.test(t.data))r=this._getOrReturnCtx(t,r),L(r,{validation:"regex",code:b.invalid_string,message:i.message}),s.dirty()}else if(i.kind==="trim")t.data=t.data.trim();else if(i.kind==="includes"){if(!t.data.includes(i.value,i.position))r=this._getOrReturnCtx(t,r),L(r,{code:b.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),s.dirty()}else if(i.kind==="toLowerCase")t.data=t.data.toLowerCase();else if(i.kind==="toUpperCase")t.data=t.data.toUpperCase();else if(i.kind==="startsWith"){if(!t.data.startsWith(i.value))r=this._getOrReturnCtx(t,r),L(r,{code:b.invalid_string,validation:{startsWith:i.value},message:i.message}),s.dirty()}else if(i.kind==="endsWith"){if(!t.data.endsWith(i.value))r=this._getOrReturnCtx(t,r),L(r,{code:b.invalid_string,validation:{endsWith:i.value},message:i.message}),s.dirty()}else if(i.kind==="datetime"){if(!$0(i).test(t.data))r=this._getOrReturnCtx(t,r),L(r,{code:b.invalid_string,validation:"datetime",message:i.message}),s.dirty()}else if(i.kind==="date"){if(!hd.test(t.data))r=this._getOrReturnCtx(t,r),L(r,{code:b.invalid_string,validation:"date",message:i.message}),s.dirty()}else if(i.kind==="time"){if(!ud(i).test(t.data))r=this._getOrReturnCtx(t,r),L(r,{code:b.invalid_string,validation:"time",message:i.message}),s.dirty()}else if(i.kind==="duration"){if(!td.test(t.data))r=this._getOrReturnCtx(t,r),L(r,{validation:"duration",code:b.invalid_string,message:i.message}),s.dirty()}else if(i.kind==="ip"){if(!_d(t.data,i.version))r=this._getOrReturnCtx(t,r),L(r,{validation:"ip",code:b.invalid_string,message:i.message}),s.dirty()}else if(i.kind==="jwt"){if(!ld(t.data,i.alg))r=this._getOrReturnCtx(t,r),L(r,{validation:"jwt",code:b.invalid_string,message:i.message}),s.dirty()}else if(i.kind==="cidr"){if(!wd(t.data,i.version))r=this._getOrReturnCtx(t,r),L(r,{validation:"cidr",code:b.invalid_string,message:i.message}),s.dirty()}else if(i.kind==="base64"){if(!fd.test(t.data))r=this._getOrReturnCtx(t,r),L(r,{validation:"base64",code:b.invalid_string,message:i.message}),s.dirty()}else if(i.kind==="base64url"){if(!cd.test(t.data))r=this._getOrReturnCtx(t,r),L(r,{validation:"base64url",code:b.invalid_string,message:i.message}),s.dirty()}else x.assertNever(i);return{status:s.value,value:t.data}}_regex(t,n,s){return this.refinement((r)=>t.test(r),{validation:n,code:b.invalid_string,...y.errToObj(s)})}_addCheck(t){return new mt({...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 mt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new mt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new mt({...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}}mt.create=(t)=>{return new mt({checks:[],typeName:N.ZodString,coerce:t?.coerce??!1,...Q(t)})};function Ad(t,n){let s=(t.toString().split(".")[1]||"").length,r=(n.toString().split(".")[1]||"").length,i=s>r?s:r,e=Number.parseInt(t.toFixed(i).replace(".","")),f=Number.parseInt(n.toFixed(i).replace(".",""));return e%f/10**i}class Gn extends X{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)!==$.number){let i=this._getOrReturnCtx(t);return L(i,{code:b.invalid_type,expected:$.number,received:i.parsedType}),P}let s=void 0,r=new lt;for(let i of this._def.checks)if(i.kind==="int"){if(!x.isInteger(t.data))s=this._getOrReturnCtx(t,s),L(s,{code:b.invalid_type,expected:"integer",received:"float",message:i.message}),r.dirty()}else if(i.kind==="min"){if(i.inclusive?t.data<i.value:t.data<=i.value)s=this._getOrReturnCtx(t,s),L(s,{code:b.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()}else if(i.kind==="max"){if(i.inclusive?t.data>i.value:t.data>=i.value)s=this._getOrReturnCtx(t,s),L(s,{code:b.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()}else if(i.kind==="multipleOf"){if(Ad(t.data,i.value)!==0)s=this._getOrReturnCtx(t,s),L(s,{code:b.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()}else if(i.kind==="finite"){if(!Number.isFinite(t.data))s=this._getOrReturnCtx(t,s),L(s,{code:b.not_finite,message:i.message}),r.dirty()}else x.assertNever(i);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 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]})}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"&&x.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)}}Gn.create=(t)=>{return new Gn({checks:[],typeName:N.ZodNumber,coerce:t?.coerce||!1,...Q(t)})};class Bn extends X{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)!==$.bigint)return this._getInvalidInput(t);let s=void 0,r=new lt;for(let i of this._def.checks)if(i.kind==="min"){if(i.inclusive?t.data<i.value:t.data<=i.value)s=this._getOrReturnCtx(t,s),L(s,{code:b.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()}else if(i.kind==="max"){if(i.inclusive?t.data>i.value:t.data>=i.value)s=this._getOrReturnCtx(t,s),L(s,{code:b.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()}else if(i.kind==="multipleOf"){if(t.data%i.value!==BigInt(0))s=this._getOrReturnCtx(t,s),L(s,{code:b.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()}else x.assertNever(i);return{status:r.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return L(n,{code:b.invalid_type,expected:$.bigint,received:n.parsedType}),P}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 Bn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:s,message:y.toString(r)}]})}_addCheck(t){return new Bn({...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}}Bn.create=(t)=>{return new Bn({checks:[],typeName:N.ZodBigInt,coerce:t?.coerce??!1,...Q(t)})};class Ls extends X{_parse(t){if(this._def.coerce)t.data=Boolean(t.data);if(this._getType(t)!==$.boolean){let s=this._getOrReturnCtx(t);return L(s,{code:b.invalid_type,expected:$.boolean,received:s.parsedType}),P}return gt(t.data)}}Ls.create=(t)=>{return new Ls({typeName:N.ZodBoolean,coerce:t?.coerce||!1,...Q(t)})};class jn extends X{_parse(t){if(this._def.coerce)t.data=new Date(t.data);if(this._getType(t)!==$.date){let i=this._getOrReturnCtx(t);return L(i,{code:b.invalid_type,expected:$.date,received:i.parsedType}),P}if(Number.isNaN(t.data.getTime())){let i=this._getOrReturnCtx(t);return L(i,{code:b.invalid_date}),P}let s=new lt,r=void 0;for(let i of this._def.checks)if(i.kind==="min"){if(t.data.getTime()<i.value)r=this._getOrReturnCtx(t,r),L(r,{code:b.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),s.dirty()}else if(i.kind==="max"){if(t.data.getTime()>i.value)r=this._getOrReturnCtx(t,r),L(r,{code:b.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),s.dirty()}else x.assertNever(i);return{status:s.value,value:new Date(t.data.getTime())}}_addCheck(t){return new jn({...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}}jn.create=(t)=>{return new jn({checks:[],coerce:t?.coerce||!1,typeName:N.ZodDate,...Q(t)})};class Er extends X{_parse(t){if(this._getType(t)!==$.symbol){let s=this._getOrReturnCtx(t);return L(s,{code:b.invalid_type,expected:$.symbol,received:s.parsedType}),P}return gt(t.data)}}Er.create=(t)=>{return new Er({typeName:N.ZodSymbol,...Q(t)})};class Is extends X{_parse(t){if(this._getType(t)!==$.undefined){let s=this._getOrReturnCtx(t);return L(s,{code:b.invalid_type,expected:$.undefined,received:s.parsedType}),P}return gt(t.data)}}Is.create=(t)=>{return new Is({typeName:N.ZodUndefined,...Q(t)})};class Os extends X{_parse(t){if(this._getType(t)!==$.null){let s=this._getOrReturnCtx(t);return L(s,{code:b.invalid_type,expected:$.null,received:s.parsedType}),P}return gt(t.data)}}Os.create=(t)=>{return new Os({typeName:N.ZodNull,...Q(t)})};class an extends X{constructor(){super(...arguments);this._any=!0}_parse(t){return gt(t.data)}}an.create=(t)=>{return new an({typeName:N.ZodAny,...Q(t)})};class yn extends X{constructor(){super(...arguments);this._unknown=!0}_parse(t){return gt(t.data)}}yn.create=(t)=>{return new yn({typeName:N.ZodUnknown,...Q(t)})};class pt extends X{_parse(t){let n=this._getOrReturnCtx(t);return L(n,{code:b.invalid_type,expected:$.never,received:n.parsedType}),P}}pt.create=(t)=>{return new pt({typeName:N.ZodNever,...Q(t)})};class dr extends X{_parse(t){if(this._getType(t)!==$.undefined){let s=this._getOrReturnCtx(t);return L(s,{code:b.invalid_type,expected:$.void,received:s.parsedType}),P}return gt(t.data)}}dr.create=(t)=>{return new dr({typeName:N.ZodVoid,...Q(t)})};class Qt extends X{_parse(t){let{ctx:n,status:s}=this._processInputParams(t),r=this._def;if(n.parsedType!==$.array)return L(n,{code:b.invalid_type,expected:$.array,received:n.parsedType}),P;if(r.exactLength!==null){let e=n.data.length>r.exactLength.value,f=n.data.length<r.exactLength.value;if(e||f)L(n,{code:e?b.too_big:b.too_small,minimum:f?r.exactLength.value:void 0,maximum:e?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)L(n,{code:b.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)L(n,{code:b.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((e,f)=>{return r.type._parseAsync(new kt(n,e,n.path,f))})).then((e)=>{return lt.mergeArray(s,e)});let i=[...n.data].map((e,f)=>{return r.type._parseSync(new kt(n,e,n.path,f))});return lt.mergeArray(s,i)}get element(){return this._def.type}min(t,n){return new Qt({...this._def,minLength:{value:t,message:y.toString(n)}})}max(t,n){return new Qt({...this._def,maxLength:{value:t,message:y.toString(n)}})}length(t,n){return new Qt({...this._def,exactLength:{value:t,message:y.toString(n)}})}nonempty(t){return this.min(1,t)}}Qt.create=(t,n)=>{return new Qt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:N.ZodArray,...Q(n)})};function $s(t){if(t instanceof rt){let n={};for(let s in t.shape){let r=t.shape[s];n[s]=Jt.create($s(r))}return new rt({...t._def,shape:()=>n})}else if(t instanceof Qt)return new Qt({...t._def,type:$s(t.element)});else if(t instanceof Jt)return Jt.create($s(t.unwrap()));else if(t instanceof gn)return gn.create($s(t.unwrap()));else if(t instanceof Zt)return Zt.create(t.items.map((n)=>$s(n)));else return t}class rt extends X{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=x.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==$.object){let c=this._getOrReturnCtx(t);return L(c,{code:b.invalid_type,expected:$.object,received:c.parsedType}),P}let{status:s,ctx:r}=this._processInputParams(t),{shape:i,keys:e}=this._getCached(),f=[];if(!(this._def.catchall instanceof pt&&this._def.unknownKeys==="strip")){for(let c in r.data)if(!e.includes(c))f.push(c)}let o=[];for(let c of e){let h=i[c],u=r.data[c];o.push({key:{status:"valid",value:c},value:h._parse(new kt(r,u,r.path,c)),alwaysSet:c in r.data})}if(this._def.catchall instanceof pt){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)L(r,{code:b.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 kt(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,_=await h.value;c.push({key:u,value:_,alwaysSet:h.alwaysSet})}return c}).then((c)=>{return lt.mergeObjectSync(s,c)});else return lt.mergeObjectSync(s,o)}get shape(){return this._def.shape()}strict(t){return y.errToObj,new rt({...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 rt({...this._def,unknownKeys:"strip"})}passthrough(){return new rt({...this._def,unknownKeys:"passthrough"})}extend(t){return new rt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new rt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:N.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new rt({...this._def,catchall:t})}pick(t){let n={};for(let s of x.objectKeys(t))if(t[s]&&this.shape[s])n[s]=this.shape[s];return new rt({...this._def,shape:()=>n})}omit(t){let n={};for(let s of x.objectKeys(this.shape))if(!t[s])n[s]=this.shape[s];return new rt({...this._def,shape:()=>n})}deepPartial(){return $s(this)}partial(t){let n={};for(let s of x.objectKeys(this.shape)){let r=this.shape[s];if(t&&!t[s])n[s]=r;else n[s]=r.optional()}return new rt({...this._def,shape:()=>n})}required(t){let n={};for(let s of x.objectKeys(this.shape))if(t&&!t[s])n[s]=this.shape[s];else{let i=this.shape[s];while(i instanceof Jt)i=i._def.innerType;n[s]=i}return new rt({...this._def,shape:()=>n})}keyof(){return U0(x.objectKeys(this.shape))}}rt.create=(t,n)=>{return new rt({shape:()=>t,unknownKeys:"strip",catchall:pt.create(),typeName:N.ZodObject,...Q(n)})};rt.strictCreate=(t,n)=>{return new rt({shape:()=>t,unknownKeys:"strict",catchall:pt.create(),typeName:N.ZodObject,...Q(n)})};rt.lazycreate=(t,n)=>{return new rt({shape:t,unknownKeys:"strip",catchall:pt.create(),typeName:N.ZodObject,...Q(n)})};class ys extends X{_parse(t){let{ctx:n}=this._processInputParams(t),s=this._def.options;function r(i){for(let f of i)if(f.result.status==="valid")return f.result;for(let f of i)if(f.result.status==="dirty")return n.common.issues.push(...f.ctx.common.issues),f.result;let e=i.map((f)=>new bt(f.ctx.common.issues));return L(n,{code:b.invalid_union,unionErrors:e}),P}if(n.common.async)return Promise.all(s.map(async(i)=>{let e={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:e}),ctx:e}})).then(r);else{let i=void 0,e=[];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"&&!i)i={result:h,ctx:c};if(c.common.issues.length)e.push(c.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let f=e.map((o)=>new bt(o));return L(n,{code:b.invalid_union,unionErrors:f}),P}}get options(){return this._def.options}}ys.create=(t,n)=>{return new ys({options:t,typeName:N.ZodUnion,...Q(n)})};var Mn=(t)=>{if(t instanceof Bs)return Mn(t.schema);else if(t instanceof Xt)return Mn(t.innerType());else if(t instanceof Fs)return[t.value];else if(t instanceof Fn)return t.options;else if(t instanceof Hs)return x.objectValues(t.enum);else if(t instanceof Ps)return Mn(t._def.innerType);else if(t instanceof Is)return[void 0];else if(t instanceof Os)return[null];else if(t instanceof Jt)return[void 0,...Mn(t.unwrap())];else if(t instanceof gn)return[null,...Mn(t.unwrap())];else if(t instanceof Ui)return Mn(t.unwrap());else if(t instanceof Ws)return Mn(t.unwrap());else if(t instanceof Ns)return Mn(t._def.innerType);else return[]};class $i extends X{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==$.object)return L(n,{code:b.invalid_type,expected:$.object,received:n.parsedType}),P;let s=this.discriminator,r=n.data[s],i=this.optionsMap.get(r);if(!i)return L(n,{code:b.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),P;if(n.common.async)return i._parseAsync({data:n.data,path:n.path,parent:n});else return i._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 i of n){let e=Mn(i.shape[t]);if(!e.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let f of e){if(r.has(f))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(f)}`);r.set(f,i)}}return new $i({typeName:N.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:r,...Q(s)})}}function Xo(t,n){let s=at(t),r=at(n);if(t===n)return{valid:!0,data:t};else if(s===$.object&&r===$.object){let i=x.objectKeys(n),e=x.objectKeys(t).filter((o)=>i.indexOf(o)!==-1),f={...t,...n};for(let o of e){let c=Xo(t[o],n[o]);if(!c.valid)return{valid:!1};f[o]=c.data}return{valid:!0,data:f}}else if(s===$.array&&r===$.array){if(t.length!==n.length)return{valid:!1};let i=[];for(let e=0;e<t.length;e++){let f=t[e],o=n[e],c=Xo(f,o);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else if(s===$.date&&r===$.date&&+t===+n)return{valid:!0,data:t};else return{valid:!1}}class Gs extends X{_parse(t){let{status:n,ctx:s}=this._processInputParams(t),r=(i,e)=>{if(Ti(i)||Ti(e))return P;let f=Xo(i.value,e.value);if(!f.valid)return L(s,{code:b.invalid_intersection_types}),P;if(Si(i)||Si(e))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(([i,e])=>r(i,e));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:N.ZodIntersection,...Q(s)})};class Zt extends X{_parse(t){let{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==$.array)return L(s,{code:b.invalid_type,expected:$.array,received:s.parsedType}),P;if(s.data.length<this._def.items.length)return L(s,{code:b.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),P;if(!this._def.rest&&s.data.length>this._def.items.length)L(s,{code:b.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty();let i=[...s.data].map((e,f)=>{let o=this._def.items[f]||this._def.rest;if(!o)return null;return o._parse(new kt(s,e,s.path,f))}).filter((e)=>!!e);if(s.common.async)return Promise.all(i).then((e)=>{return lt.mergeArray(n,e)});else return lt.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new Zt({...this._def,rest:t})}}Zt.create=(t,n)=>{if(!Array.isArray(t))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new Zt({items:t,typeName:N.ZodTuple,rest:null,...Q(n)})};class Rr extends X{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!==$.object)return L(s,{code:b.invalid_type,expected:$.object,received:s.parsedType}),P;let r=[],i=this._def.keyType,e=this._def.valueType;for(let f in s.data)r.push({key:i._parse(new kt(s,f,s.path,f)),value:e._parse(new kt(s,s.data[f],s.path,f)),alwaysSet:f in s.data});if(s.common.async)return lt.mergeObjectAsync(n,r);else return lt.mergeObjectSync(n,r)}get element(){return this._def.valueType}static create(t,n,s){if(n instanceof X)return new Rr({keyType:t,valueType:n,typeName:N.ZodRecord,...Q(s)});return new Rr({keyType:mt.create(),valueType:t,typeName:N.ZodRecord,...Q(n)})}}class br extends X{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!==$.map)return L(s,{code:b.invalid_type,expected:$.map,received:s.parsedType}),P;let r=this._def.keyType,i=this._def.valueType,e=[...s.data.entries()].map(([f,o],c)=>{return{key:r._parse(new kt(s,f,s.path,[c,"key"])),value:i._parse(new kt(s,o,s.path,[c,"value"]))}});if(s.common.async){let f=new Map;return Promise.resolve().then(async()=>{for(let o of e){let c=await o.key,h=await o.value;if(c.status==="aborted"||h.status==="aborted")return P;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 e){let{key:c,value:h}=o;if(c.status==="aborted"||h.status==="aborted")return P;if(c.status==="dirty"||h.status==="dirty")n.dirty();f.set(c.value,h.value)}return{status:n.value,value:f}}}}br.create=(t,n,s)=>{return new br({valueType:n,keyType:t,typeName:N.ZodMap,...Q(s)})};class pn extends X{_parse(t){let{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==$.set)return L(s,{code:b.invalid_type,expected:$.set,received:s.parsedType}),P;let r=this._def;if(r.minSize!==null){if(s.data.size<r.minSize.value)L(s,{code:b.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)L(s,{code:b.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),n.dirty()}let i=this._def.valueType;function e(o){let c=new Set;for(let h of o){if(h.status==="aborted")return P;if(h.status==="dirty")n.dirty();c.add(h.value)}return{status:n.value,value:c}}let f=[...s.data.values()].map((o,c)=>i._parse(new kt(s,o,s.path,c)));if(s.common.async)return Promise.all(f).then((o)=>e(o));else return e(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:N.ZodSet,...Q(n)})};class Us extends X{constructor(){super(...arguments);this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==$.function)return L(n,{code:b.invalid_type,expected:$.function,received:n.parsedType}),P;function s(f,o){return gr({data:f,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Ts(),An].filter((c)=>!!c),issueData:{code:b.invalid_arguments,argumentsError:o}})}function r(f,o){return gr({data:f,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Ts(),An].filter((c)=>!!c),issueData:{code:b.invalid_return_type,returnTypeError:o}})}let i={errorMap:n.common.contextualErrorMap},e=n.data;if(this._def.returns instanceof Zn){let f=this;return gt(async function(...o){let c=new bt([]),h=await f._def.args.parseAsync(o,i).catch((l)=>{throw c.addIssue(s(o,l)),c}),u=await Reflect.apply(e,this,h);return await f._def.returns._def.type.parseAsync(u,i).catch((l)=>{throw c.addIssue(r(u,l)),c})})}else{let f=this;return gt(function(...o){let c=f._def.args.safeParse(o,i);if(!c.success)throw new bt([s(o,c.error)]);let h=Reflect.apply(e,this,c.data),u=f._def.returns.safeParse(h,i);if(!u.success)throw new bt([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:Zt.create(t).rest(yn.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:Zt.create([]).rest(yn.create()),returns:n||yn.create(),typeName:N.ZodFunction,...Q(s)})}}class Bs extends X{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:N.ZodLazy,...Q(n)})};class Fs extends X{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return L(n,{received:n.data,code:b.invalid_literal,expected:this._def.value}),P}return{status:"valid",value:t.data}}get value(){return this._def.value}}Fs.create=(t,n)=>{return new Fs({value:t,typeName:N.ZodLiteral,...Q(n)})};function U0(t,n){return new Fn({values:t,typeName:N.ZodEnum,...Q(n)})}class Fn extends X{_parse(t){if(typeof t.data!=="string"){let n=this._getOrReturnCtx(t),s=this._def.values;return L(n,{expected:x.joinValues(s),received:n.parsedType,code:b.invalid_type}),P}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 L(n,{received:n.data,code:b.invalid_enum_value,options:s}),P}return gt(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 Fn.create(t,{...this._def,...n})}exclude(t,n=this._def){return Fn.create(this.options.filter((s)=>!t.includes(s)),{...this._def,...n})}}Fn.create=U0;class Hs extends X{_parse(t){let n=x.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(t);if(s.parsedType!==$.string&&s.parsedType!==$.number){let r=x.objectValues(n);return L(s,{expected:x.joinValues(r),received:s.parsedType,code:b.invalid_type}),P}if(!this._cache)this._cache=new Set(x.getValidEnumValues(this._def.values));if(!this._cache.has(t.data)){let r=x.objectValues(n);return L(s,{received:s.data,code:b.invalid_enum_value,options:r}),P}return gt(t.data)}get enum(){return this._def.values}}Hs.create=(t,n)=>{return new Hs({values:t,typeName:N.ZodNativeEnum,...Q(n)})};class Zn extends X{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==$.promise&&n.common.async===!1)return L(n,{code:b.invalid_type,expected:$.promise,received:n.parsedType}),P;let s=n.parsedType===$.promise?n.data:Promise.resolve(n.data);return gt(s.then((r)=>{return this._def.type.parseAsync(r,{path:n.path,errorMap:n.common.contextualErrorMap})}))}}Zn.create=(t,n)=>{return new Zn({type:t,typeName:N.ZodPromise,...Q(n)})};class Xt extends X{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===N.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:s}=this._processInputParams(t),r=this._def.effect||null,i={addIssue:(e)=>{if(L(s,e),e.fatal)n.abort();else n.dirty()},get path(){return s.path}};if(i.addIssue=i.addIssue.bind(i),r.type==="preprocess"){let e=r.transform(s.data,i);if(s.common.async)return Promise.resolve(e).then(async(f)=>{if(n.value==="aborted")return P;let o=await this._def.schema._parseAsync({data:f,path:s.path,parent:s});if(o.status==="aborted")return P;if(o.status==="dirty")return Vn(o.value);if(n.value==="dirty")return Vn(o.value);return o});else{if(n.value==="aborted")return P;let f=this._def.schema._parseSync({data:e,path:s.path,parent:s});if(f.status==="aborted")return P;if(f.status==="dirty")return Vn(f.value);if(n.value==="dirty")return Vn(f.value);return f}}if(r.type==="refinement"){let e=(f)=>{let o=r.refinement(f,i);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 P;if(f.status==="dirty")n.dirty();return e(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 P;if(f.status==="dirty")n.dirty();return e(f.value).then(()=>{return{status:n.value,value:f.value}})})}if(r.type==="transform")if(s.common.async===!1){let e=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!On(e))return P;let f=r.transform(e.value,i);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((e)=>{if(!On(e))return P;return Promise.resolve(r.transform(e.value,i)).then((f)=>({status:n.value,value:f}))});x.assertNever(r)}}Xt.create=(t,n,s)=>{return new Xt({schema:t,typeName:N.ZodEffects,effect:n,...Q(s)})};Xt.createWithPreprocess=(t,n,s)=>{return new Xt({schema:n,effect:{type:"preprocess",transform:t},typeName:N.ZodEffects,...Q(s)})};class Jt extends X{_parse(t){if(this._getType(t)===$.undefined)return gt(void 0);return this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Jt.create=(t,n)=>{return new Jt({innerType:t,typeName:N.ZodOptional,...Q(n)})};class gn extends X{_parse(t){if(this._getType(t)===$.null)return gt(null);return this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}gn.create=(t,n)=>{return new gn({innerType:t,typeName:N.ZodNullable,...Q(n)})};class Ps extends X{_parse(t){let{ctx:n}=this._processInputParams(t),s=n.data;if(n.parsedType===$.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:N.ZodDefault,defaultValue:typeof n.default==="function"?n.default:()=>n.default,...Q(n)})};class Ns extends X{_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((i)=>{return{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new bt(s.common.issues)},input:s.data})}});else return{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new bt(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}Ns.create=(t,n)=>{return new Ns({innerType:t,typeName:N.ZodCatch,catchValue:typeof n.catch==="function"?n.catch:()=>n.catch,...Q(n)})};class Tr extends X{_parse(t){if(this._getType(t)!==$.nan){let s=this._getOrReturnCtx(t);return L(s,{code:b.invalid_type,expected:$.nan,received:s.parsedType}),P}return{status:"valid",value:t.data}}}Tr.create=(t)=>{return new Tr({typeName:N.ZodNaN,...Q(t)})};var Md=Symbol("zod_brand");class Ui extends X{_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 Sr extends X{_parse(t){let{status:n,ctx:s}=this._processInputParams(t);if(s.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});if(i.status==="aborted")return P;if(i.status==="dirty")return n.dirty(),Vn(i.value);else return this._def.out._parseAsync({data:i.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 P;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 Sr({in:t,out:n,typeName:N.ZodPipeline})}}class Ws extends X{_parse(t){let n=this._def.innerType._parse(t),s=(r)=>{if(On(r))r.value=Object.freeze(r.value);return r};return Ss(n)?n.then((r)=>s(r)):s(n)}unwrap(){return this._def.innerType}}Ws.create=(t,n)=>{return new Ws({innerType:t,typeName:N.ZodReadonly,...Q(n)})};function b0(t,n){let s=typeof t==="function"?t(n):typeof t==="string"?{message:t}:t;return typeof s==="string"?{message:s}:s}function L0(t,n={},s){if(t)return an.create().superRefine((r,i)=>{let e=t(r);if(e instanceof Promise)return e.then((f)=>{if(!f){let o=b0(n,r),c=o.fatal??s??!0;i.addIssue({code:"custom",...o,fatal:c})}});if(!e){let f=b0(n,r),o=f.fatal??s??!0;i.addIssue({code:"custom",...f,fatal:o})}return});return an.create()}var gd={object:rt.lazycreate},N;(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"})(N||(N={}));var Ed=(t,n={message:`Input not instance of ${t.name}`})=>L0((s)=>s instanceof t,n),I0=mt.create,O0=Gn.create,dd=Tr.create,Rd=Bn.create,y0=Ls.create,bd=jn.create,Td=Er.create,Sd=Is.create,$d=Os.create,Ud=an.create,Ld=yn.create,Id=pt.create,Od=dr.create,yd=Qt.create,Gd=rt.create,Bd=rt.strictCreate,Fd=ys.create,Hd=$i.create,Pd=Gs.create,Nd=Zt.create,Wd=Rr.create,Dd=br.create,Yd=pn.create,md=Us.create,Qd=Bs.create,Jd=Fs.create,kd=Fn.create,Xd=Hs.create,zd=Zn.create,xd=Xt.create,qd=Jt.create,Cd=gn.create,Kd=Xt.createWithPreprocess,Vd=Sr.create,jd=()=>I0().optional(),ad=()=>O0().optional(),pd=()=>y0().optional(),Zd={string:(t)=>mt.create({...t,coerce:!0}),number:(t)=>Gn.create({...t,coerce:!0}),boolean:(t)=>Ls.create({...t,coerce:!0}),bigint:(t)=>Bn.create({...t,coerce:!0}),date:(t)=>jn.create({...t,coerce:!0})};var vd=P;var Li=g.enum(["low","medium","high","xhigh","max"]),vn=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 tR=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"}),nR=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),zo=g.object({host:g.string().default("127.0.0.1"),port:g.number().default(8787),api_keys:tR,proxy_url:nR,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:Li.nullable().default(null),auto_effort_mapping:g.boolean().default(!0),log_level:g.string().default("info"),test_upstream_endpoint:g.string().url().optional()});class $r extends Error{constructor(t,n){super(t,n);this.name="ConfigLoadError"}}var eR=zo.partial();function oR(t){let n=t.XDG_CONFIG_HOME??G0(iR(),".config");return G0(n,"kiro-provider","config.json")}function fR(t){if(!sR(t))return{};try{let n=JSON.parse(rR(t,"utf8"));return eR.parse(n)}catch(n){if(n instanceof g.ZodError)throw new $r(`Invalid configuration file ${t}: ${B0(n)}`,{cause:n});if(n instanceof Error)throw new $r(`Unable to read configuration file ${t}: ${n.message}`,{cause:n});throw n}}function cR(t){let n=t.trim().toLowerCase();if(n==="true"||n==="1")return!0;if(n==="false"||n==="0")return!1;return t}function hR(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 i=t.KIRO_PROVIDER_API_KEYS;if(i!==void 0)n.api_keys=i.split(",");let e=t.KIRO_PROVIDER_PROXY_URL;if(e!==void 0)n.proxy_url=e.trim();let f=t.KIRO_PROVIDER_AUTO_EFFORT_MAPPING;if(f!==void 0)n.auto_effort_mapping=cR(f);return n}function B0(t){return t.issues.map((n)=>`${n.path.length>0?n.path.join("."):"config"}: ${n.message}`).join(", ")}function F0(t={}){let n=t.env??process.env,s=t.configPath??oR(n);try{return zo.parse({...fR(s),...hR(n),...t.overrides})}catch(r){if(r instanceof $r)throw r;if(r instanceof g.ZodError)throw new $r(`Invalid configuration: ${B0(r)}`,{cause:r});throw r}}function Ii(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 H0(t,n=120000){if(!t.access||!t.expires)return!0;return Date.now()>=t.expires-n}function Oi(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 uR(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 yi(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 xo(t){return uR(t)}var P0=4;class N0 extends Error{accountId;constructor(t){super(`Account ${t} changed too frequently to update`);this.accountId=t;this.name="AccountConcurrentUpdateError"}}function _R(t){throw TypeError(`Unsupported account selection strategy: ${String(t)}`)}function Ur(t){return{...t}}function lR(t){return{refresh:Oi({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 qo{strategy;database;accounts;stickyId;roundRobinCursor=0;constructor(t,n,s){this.strategy=n;this.database=s;this.accounts=t.map(Ur)}getAccountCount(){return this.accounts.length}getAccounts(){return this.accounts.map(Ur)}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:Ur(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,i)=>r.id.localeCompare(i.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,(i)=>{if(xo(n))return{...i,failCount:10,isHealthy:!1,unhealthyReason:n,recoveryTime:void 0,lastUsed:r};let e=i.failCount+1;return{...i,failCount:e,isHealthy:e<10,unhealthyReason:n,recoveryTime:e>=10?s??r+3600000:void 0,lastUsed:r}})}updateFromAuth(t,n){let s=Ii(n.refresh);for(let r=0;r<P0;r+=1){let i=r===0?t:this.database.getById(t.id);if(!i||!this.isSameLogin(t,i)){this.reconcileFromDb();return}let e={...i,refreshToken:s.refreshToken,accessToken:n.access,expiresAt:n.expires};if(this.database.updateExistingAccounts([e])===1){let f={...e,generation:i.generation+1};return this.replaceAccount(f),Ur(f)}}this.reconcileFromDb();return}toAuthDetails(t){return lR(t)}isSelectable(t,n){if(xo(t.unhealthyReason))return!1;if(t.rateLimitResetTime>n)return!1;if(t.isHealthy||yi(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 _R(this.strategy)}}patchAccount(t,n){for(let s=0;s<P0;s+=1){let r=this.database.getById(t);if(!r){this.accounts=this.accounts.filter((e)=>e.id!==t);return}let i=n(r);if(this.database.updateExistingAccounts([i])===1){let e={...i,generation:r.generation+1};return this.replaceAccount(e),Ur(e)}}throw this.reconcileFromDb(),new N0(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 j0=Y(Vo(),1);import*as tn from"net";import*as Ir from"tls";import VR from"assert";import*as x0 from"net";import*as q0 from"http";import{Agent as KR}from"https";var vt=Symbol("AgentBaseInternalState");class jo extends q0.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
|
-
|
|
44
|
+
or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`),Date.now()}return t}constructor(n){this.configProvider=new Promise((t,i)=>{if(typeof n==="function")n().then((s)=>{t(this.resolveDefaultConfig(s))}).catch(i);else t(this.resolveDefaultConfig(n))})}destroy(){this.config?.httpAgent?.destroy(),this.config?.httpsAgent?.destroy()}async handle(n,{abortSignal:t,requestTimeout:i}={}){if(!this.config)this.config=await this.configProvider;let s=this.config,r=n.protocol==="https:";if(!r&&!this.config.httpAgent)this.config.httpAgent=await this.config.httpAgentProvider();return new Promise((e,f)=>{let o=void 0,h=-1,u=-1,c=-1,_=-1,w=-1,l=()=>{Bn.clearTimeout(h),Bn.clearTimeout(u),Bn.clearTimeout(c),Bn.clearTimeout(_),Bn.clearTimeout(w)},A=async(B)=>{await o,l(),e(B)},d=async(B)=>{await o,l(),f(B)};if(t?.aborted){let B=ko(t);d(B);return}let E=n.headers,R=E?(E.Expect??E.expect)==="100-continue":!1,y=r?s.httpsAgent:s.httpAgent;if(R&&!this.externalAgent)y=new(r?xo.Agent:Ko)({keepAlive:!1,maxSockets:1/0});h=Bn.setTimeout(()=>{this.socketWarningTimestamp=qo.checkSocketUsage(y,this.socketWarningTimestamp,s.logger)},s.socketAcquisitionWarningTimeout??(s.requestTimeout??2000)+(s.connectionTimeout??1000));let T=n.query?N1(n.query):"",S=void 0;if(n.username!=null||n.password!=null){let B=n.username??"",g=n.password??"";S=`${B}:${g}`}let I=n.path;if(T)I+=`?${T}`;if(n.fragment)I+=`#${n.fragment}`;let F=n.hostname??"";if(F[0]==="["&&F.endsWith("]"))F=n.hostname.slice(1,-1);else F=n.hostname;let C={headers:n.headers,host:F,method:n.method,path:I,port:n.port,agent:y,auth:S},b=(r?xo.request:O1)(C,(B)=>{let g=new G1({statusCode:B.statusCode||-1,reason:B.statusMessage,headers:H1(B.headers),body:B});A({response:g})});if(b.on("error",(B)=>{if(EF.includes(B.code))d(Object.assign(B,{name:"TimeoutError"}));else d(B)}),t){let B=()=>{b.destroy();let g=ko(t);d(g)};if(typeof t.addEventListener==="function"){let g=t;g.addEventListener("abort",B,{once:!0}),b.once("close",()=>g.removeEventListener("abort",B))}else t.onabort=B}let $=i??s.requestTimeout;u=yF(b,d,s.connectionTimeout),c=TF(b,d,$,s.throwOnRequestTimeout,s.logger??console),_=IF(b,d,s.socketTimeout);let N=C.agent;if(typeof N==="object"&&"keepAlive"in N)w=SF(b,{keepAlive:N.keepAlive,keepAliveMsecs:N.keepAliveMsecs});o=W1(b,n,$,this.externalAgent).catch((B)=>{return l(),f(B)})})}updateHttpClientConfig(n,t){this.config=void 0,this.configProvider=this.configProvider.then((i)=>{return{...i,[n]:t}})}httpHandlerConfigs(){return this.config??{}}resolveDefaultConfig(n){let{requestTimeout:t,connectionTimeout:i,socketTimeout:s,socketAcquisitionWarningTimeout:r,httpAgent:e,httpsAgent:f,throwOnRequestTimeout:o,logger:h}=n||{},u=!0,c=50;return{connectionTimeout:i,requestTimeout:t,socketTimeout:s,socketAcquisitionWarningTimeout:r,throwOnRequestTimeout:o,httpAgentProvider:async()=>{let _=p("http"),{Agent:w,request:l}=_.default??_;if(O1=l,Ko=w,e instanceof Ko||typeof e?.destroy==="function")return this.externalAgent=!0,e;return new Ko({keepAlive:!0,maxSockets:50,...e})},httpsAgent:(()=>{if(f instanceof xo.Agent||typeof f?.destroy==="function")return this.externalAgent=!0,f;return new xo.Agent({keepAlive:!0,maxSockets:50,...f})})(),logger:h}}}var $F=new Uint16Array(1);class Vo{id=$F[0]++;total=0;max=0;session;refs=0;constructor(n){n.unref(),this.session=n}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 F1{sessions=[];maxConcurrency=0;constructor(n){this.sessions=(n??[]).map((t)=>new Vo(t))}poll(){let n=!1;for(let t of this.sessions){if(t.deref().destroyed){n=!0;continue}if(!this.maxConcurrency||t.useCount()<this.maxConcurrency)return t}if(n){for(let t of this.sessions)if(t.deref().destroyed)this.remove(t)}}offerLast(n){this.sessions.push(n)}remove(n){let t=this.sessions.indexOf(n);if(t>-1)this.sessions.splice(t,1)}[Symbol.iterator](){return this.sessions[Symbol.iterator]()}setMaxConcurrency(n){this.maxConcurrency=n}destroy(n){this.remove(n),n.destroy()}}class P1{config;connectOptions;connectionPools=new Map;constructor(n){if(this.config=n,this.config.maxConcurrency&&this.config.maxConcurrency<=0)throw RangeError("maxConcurrency must be greater than zero.")}lease(n,t){let i=this.getUrlString(n),s=this.getPool(i);if(!this.config.disableConcurrency&&!t.isEventStream){let h=s.poll();if(h)return h.retain(),h}let r=new Vo(this.connect(i)),e=r.deref();if(this.config.maxConcurrency)e.settings({maxConcurrentStreams:this.config.maxConcurrency},(h)=>{if(h)throw Error("Fail to set maxConcurrentStreams to "+this.config.maxConcurrency+"when creating new session for "+n.destination.toString())});let f=()=>{this.removeFromPoolAndClose(i,r)},o=()=>{this.removeFromPoolAndCheckedDestroy(i,r)};if(e.on("goaway",f),e.on("error",o),e.on("frameError",o),e.on("close",o),t.requestTimeout)e.setTimeout(t.requestTimeout,o);return s.offerLast(r),r.retain(),r}release(n,t){t.free()}createIsolatedSession(n,t){let i=this.getUrlString(n),s=new Vo(this.connect(i)),r=s.deref();r.settings({maxConcurrentStreams:1});let e=()=>{s.destroy()};if(r.on("error",e),r.on("frameError",e),r.on("close",e),t.requestTimeout)r.setTimeout(t.requestTimeout,e);return s.retain(),s}destroy(){for(let[n,t]of this.connectionPools){for(let i of[...t])i.destroy();this.connectionPools.delete(n)}}setMaxConcurrentStreams(n){if(n&&n<=0)throw RangeError("maxConcurrentStreams must be greater than zero.");this.config.maxConcurrency=n;for(let t of this.connectionPools.values())t.setMaxConcurrency(n)}setDisableConcurrentStreams(n){this.config.disableConcurrency=n}setNodeHttp2ConnectOptions(n){this.connectOptions=n}debug(){let n={};for(let[t,i]of this.connectionPools){let s=[];for(let r of i)s.push({id:r.id,active:r.useCount(),maxConcurrent:r.max,totalRequests:r.total});n[t]={sessions:s}}return n}removeFromPoolAndClose(n,t){this.connectionPools.get(n)?.remove(t),t.close()}removeFromPoolAndCheckedDestroy(n,t){this.connectionPools.get(n)?.remove(t),t.destroy()}getPool(n){if(!this.connectionPools.has(n)){let t=new F1;if(this.config.maxConcurrency)t.setMaxConcurrency(this.config.maxConcurrency);this.connectionPools.set(n,t)}return this.connectionPools.get(n)}getUrlString(n){return n.destination.toString()}connect(n){return this.connectOptions===void 0?Bc.connect(n):Bc.connect(n,this.connectOptions)}}var{constants:B1}=Bc;class Nc{config;configProvider;metadata={handlerProtocol:"h2"};connectionManager=new P1({});static create(n){if(typeof n?.handle==="function")return n;return new Nc(n)}constructor(n){this.configProvider=new Promise((t,i)=>{if(typeof n==="function")n().then((s)=>{t(s||{})}).catch(i);else t(n||{})})}destroy(){this.connectionManager.destroy()}async handle(n,{abortSignal:t,requestTimeout:i,isEventStream:s}={}){if(!this.config){this.config=await this.configProvider;let{disableConcurrentStreams:h,maxConcurrentStreams:u,nodeHttp2ConnectOptions:c}=this.config;if(this.connectionManager.setDisableConcurrentStreams(h??!1),u)this.connectionManager.setMaxConcurrentStreams(u);if(c)this.connectionManager.setNodeHttp2ConnectOptions(c)}let{requestTimeout:r,disableConcurrentStreams:e}=this.config,f=e||s,o=i??r;return new Promise((h,u)=>{let c=!1,_=void 0,w=async(g)=>{await _,h(g)},l=async(g)=>{await _,u(g)};if(t?.aborted){c=!0;let g=ko(t);l(g);return}let{hostname:A,method:d,port:E,protocol:R,query:y}=n,T="";if(n.username!=null||n.password!=null){let g=n.username??"",X=n.password??"";T=`${g}:${X}@`}let S=`${R}//${T}${A}${E?`:${E}`:""}`,I={destination:new URL(S)},F={requestTimeout:this.config?.sessionTimeout,isEventStream:s},C=f?this.connectionManager.createIsolatedSession(I,F):this.connectionManager.lease(I,F),sn=C.deref(),b=(g)=>{if(f)C.destroy();c=!0,l(g)},$=y?N1(y):"",N=n.path;if($)N+=`?${$}`;if(n.fragment)N+=`#${n.fragment}`;let B=sn.request({...n.headers,[B1.HTTP2_HEADER_PATH]:N,[B1.HTTP2_HEADER_METHOD]:d});if(o)B.setTimeout(o,()=>{B.close();let g=Error(`Stream timed out because of no activity for ${o} ms`);g.name="TimeoutError",b(g)});if(t){let g=()=>{B.close();let X=ko(t);b(X)};if(typeof t.addEventListener==="function"){let X=t;X.addEventListener("abort",g,{once:!0}),B.once("close",()=>X.removeEventListener("abort",g))}else t.onabort=g}B.on("frameError",(g,X,Z)=>{b(Error(`Frame type id ${g} in stream id ${Z} has failed with code ${X}.`))}),B.on("error",b),B.on("aborted",()=>{b(Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${B.rstCode}.`))}),B.on("response",(g)=>{let X=new G1({statusCode:g[":status"]??-1,headers:H1(g),body:B});if(c=!0,w({response:X}),f)sn.close()}),B.on("close",()=>{if(f)C.destroy();else this.connectionManager.release(I,C);if(!c)b(Error("Unexpected error: http2 request did not get a response"))}),_=W1(B,n,o)})}updateHttpClientConfig(n,t){this.config=void 0,this.configProvider=this.configProvider.then((i)=>{return{...i,[n]:t}})}httpHandlerConfigs(){return this.config??{}}}LF.DEFAULT_REQUEST_TIMEOUT=bF;LF.NodeHttp2Handler=Nc;LF.NodeHttpHandler=qo});var q1=k((cP)=>{var{nv:HF,NumericValue:X1,calculateBodyLength:WF,_parseEpochTimestamp:D1,fromBase64:z1,generateIdempotencyToken:FF}=mn(),{HttpRequest:PF,collectBody:DF,SerdeContext:Dc,RpcProtocol:YF}=Jn(),{NormalizedSchema:Yc,deref:mF,TypeRegistry:Y1}=ri(),{getSmithyContext:JF}=St();function qs(n){return typeof Buffer<"u"?Buffer.alloc(n):new Uint8Array(n)}var mc=Symbol("@smithy/core/cbor::tagSymbol");function Jc(n){return n[mc]=!0,n}var Q1=typeof Buffer<"u",Xc=new TextDecoder,a=qs(0),zc=!1,_t=new DataView(a.buffer,a.byteOffset,a.byteLength),x=0;function XF(n){a=n,zc=Q1&&a instanceof Buffer,_t=new DataView(a.buffer,a.byteOffset,a.byteLength)}function li(n,t){if(n>=t)throw Error("unexpected end of (decode) payload.");let i=(a[n]&224)>>5,s=a[n]&31;if(s===31&&2<=i&&i<=5)return zF(n,t);switch(i){case 0:case 1:case 6:{let r,e;if(s<24)r=s,e=1;else switch(s){case 24:if(t-n<2)Ot(1);r=a[n+1],e=2;break;case 25:if(t-n<3)Ot(2);r=_t.getUint16(n+1),e=3;break;case 26:if(t-n<5)Ot(4);r=_t.getUint32(n+1),e=5;break;case 27:if(t-n<9)Ot(8);{let f=_t.getUint32(n+1);if(f<2097152)r=f*4294967296+_t.getUint32(n+5);else r=_t.getBigUint64(n+1)}e=9;break;default:Cc(s)}if(i===0)return x=e,Wc(r);else if(i===1){let f;if(typeof r==="bigint")f=BigInt(-1)-r;else f=-1-r;return x=e,Wc(f)}else return jF(n,t,s,r,e)}case 3:return he(n,t);case 5:return CF(n,t);case 4:return kF(n,t);case 2:return Qc(n,t);default:return aF(n,t)}}function zF(n,t){let i=(a[n]&224)>>5;if((a[n]&31)===31)switch(i){case 3:return pF(n,t);case 5:return vF(n,t);case 4:return ZF(n,t);case 2:return nP(n,t)}}function QF(n,t){let i=n>>7,s=(n&124)>>2,r=(n&3)<<8|t,e=i===0?1:-1;if(s===0){if(r===0)return 0;return e*(Math.pow(2,-14)*(r/1024))}else if(s===31){if(r===0)return e*(1/0);return NaN}return e*(Math.pow(2,s-15)*(1+r/1024))}function CF(n,t){let i=ue(n,t);if(i<15)return KF(n,t,i);return xF(n,t,i)}function xF(n,t,i){let s=x;n+=s;let r=n,e=Object.create(null);for(let f=0;f<i;++f){let o=he(n,t);if(n+=x,(a[n]&224)>>5===3)e[o]=he(n,t);else e[o]=li(n,t);n+=x}return x=s+(n-r),Object.setPrototypeOf(e,Object.prototype),e}function KF(n,t,i){let s=x;n+=s;let r=n,e={};for(let f=0;f<i;++f){let o=he(n,t);n+=x,e[o]=li(n,t),n+=x}return x=s+(n-r),e}function kF(n,t){let i=ue(n,t),s=x;n+=s;let r=n,e=Array(i);for(let f=0;f<i;++f)e[f]=li(n,t),n+=x;return x=s+(n-r),e}function he(n,t){let i=ue(n,t),s=x;if(n+=s,t-n<i)Ot(i);if(x=s+i,i<24)return VF(n,i);if(zc)return a.toString("utf-8",n,n+i);return Xc.decode(a.subarray(n,n+i))}var m1=Array(2048),Gc=new Uint16Array(2048),oe=0;function qF(){oe=oe+1&65535}function VF(n,t){let i=t;for(let f=0;f<t;++f)i=i*31+a[n+f]|0;let s=i>>>0&2047,r=m1[s];if(r!==void 0){if(r.length===t){let f=!0;for(let o=0;o<t;++o)if(r.charCodeAt(o)!==a[n+o]){f=!1;break}if(f)return Gc[s]=oe,r}}let e=zc?a.toString("utf-8",n,n+t):Xc.decode(a.subarray(n,n+t));if(Gc[s]!==oe)m1[s]=e,Gc[s]=oe;return e}function Qc(n,t){let i=ue(n,t),s=x;if(n+=s,t-n<i)Ot(i);let r=a.subarray(n,n+i);return x=s+i,r}function jF(n,t,i,s,r){if(i===2||i===3){let e=ue(n+r,t),f=BigInt(0),o=n+r+x;for(let h=o;h<o+e;++h)f=f<<BigInt(8)|BigInt(a[h]);return x=r+x+e,i===3?-f-BigInt(1):f}else if(i===4){let e=li(n+r,t),[f,o]=e,h=o<0?-1:1,u="0".repeat(Math.abs(f)+1)+String(BigInt(h)*BigInt(o)),c,_=o<0?"-":"";if(c=f===0?u:u.slice(0,u.length+f)+"."+u.slice(f),c=c.replace(/^0+/g,""),c==="")c="0";if(c[0]===".")c="0"+c;return c=_+c,x=r+x,HF(c)}else{let e=li(n+r,t);return x=r+x,Jc({tag:Wc(s),value:e})}}function aF(n,t){let i=a[n]&31;switch(i){case 21:case 20:return x=1,i===21;case 22:return x=1,null;case 23:return x=1,null;case 25:if(t-n<3)throw Error("incomplete float16 at end of buf.");return x=3,QF(a[n+1],a[n+2]);case 26:if(t-n<5)throw Error("incomplete float32 at end of buf.");return x=5,_t.getFloat32(n+1);case 27:if(t-n<9)throw Error("incomplete float64 at end of buf.");return x=9,_t.getFloat64(n+1);default:Cc(i)}}function ue(n,t){let i=a[n]&31;if(i<24)return x=1,i;switch(i){case 24:if(t-n<2)Ot(1);return x=2,a[n+1];case 25:if(t-n<3)Ot(2);return x=3,_t.getUint16(n+1);case 26:if(t-n<5)Ot(4);return x=5,_t.getUint32(n+1);case 27:if(t-n<9)Ot(8);return x=9,tP(_t.getBigUint64(n+1));default:Cc(i)}}function vF(n,t){n+=1;let i=n,s={};for(;n<t;){if(a[n]===255)return x=n-i+2,s;let r=he(n,t);n+=x,s[r]=li(n,t),n+=x}throw Error("expected break marker.")}function ZF(n,t){n+=1;let i=[];for(let s=n;n<t;){if(a[n]===255)return x=n-s+2,i;i.push(li(n,t)),n+=x}throw Error("expected break marker.")}function pF(n,t){n+=1;let i=[];for(let s=n;n<t;){if(a[n]===255){let h=qs(i.length);if(h.set(i,0),x=n-s+2,Q1)return h.toString("utf-8",0,h.length);return Xc.decode(h)}let r=(a[n]&224)>>5,e=a[n]&31;if(r!==3)C1(r);if(e===31)throw Error("nested indefinite string.");let f=Qc(n,t);n+=x;for(let h=0;h<f.length;++h)i.push(f[h])}throw Error("expected break marker.")}function nP(n,t){n+=1;let i=[];for(let s=n;n<t;){if(a[n]===255){let h=qs(i.length);return h.set(i,0),x=n-s+2,h}let r=(a[n]&224)>>5,e=a[n]&31;if(r!==2)C1(r);if(e===31)throw Error("nested indefinite string.");let f=Qc(n,t);n+=x;for(let h=0;h<f.length;++h)i.push(f[h])}throw Error("expected break marker.")}function Wc(n){if(typeof n==="number")return n;let t=Number(n);if(Number.MIN_SAFE_INTEGER<=t&&t<=Number.MAX_SAFE_INTEGER)return t;return n}function tP(n){let t=Number(n);if(t<Number.MIN_SAFE_INTEGER||Number.MAX_SAFE_INTEGER<t)console.warn(Error(`@smithy/core/cbor - truncating BigInt(${n}) to ${t} with loss of precision.`));return t}function Ot(n){throw Error(`length ${n} greater than remaining buf len.`)}function Cc(n){throw Error(`unexpected minor value ${n}.`)}function C1(n){throw Error(`unexpected major type ${n} in indefinite string.`)}var iP=typeof Buffer<"u",Ks=new Map,fe=0,Fc=!1,sP=2048,m=qs(sP),nt=new DataView(m.buffer,m.byteOffset,m.byteLength),G=0;function rP(n){let t=[n];while(t.length){let i=t.pop();if(typeof i==="string"){let s=i.length;if(iP)if(ks(s*3+9),s>23)Hc(3,Buffer.byteLength(i)),G+=m.write(i,G);else oP(i);else{let r=s*3;ks(r+9);let e=G,o=new TextEncoder().encodeInto(i,m.subarray(G+9)).written,h;if(o<24)h=1;else if(o<256)h=2;else if(o<65536)h=3;else if(o<4294967296)h=5;else h=9;if(h<9)m.copyWithin(e+h,e+9,e+9+o);G=e,Ki(3,o),G+=o}continue}if(m.byteLength-G<9)ks(64);if(typeof i==="number"){if(Number.isInteger(i)){let s=i>=0,r=s?0:1,e=s?i:-i-1;if(e<24)m[G++]=r<<5|e;else if(e<256)m[G++]=r<<5|24,m[G++]=e;else if(e<65536)m[G++]=r<<5|25,m[G++]=e>>8,m[G++]=e&255;else if(e<4294967296)m[G++]=r<<5|26,nt.setUint32(G,e),G+=4;else{m[G++]=r<<5|27;let f=e/4294967296|0,o=e-f*4294967296|0;nt.setUint32(G,f),nt.setUint32(G+4,o),G+=8}continue}m[G++]=251,nt.setFloat64(G,i),G+=8;continue}else if(typeof i==="bigint"){let s=i>=0,r=s?0:1,e=s?i:-i-BigInt(1);if(e<BigInt("18446744073709551616")){let f=Number(e);if(f<4294967296)Ki(r,f);else m[G++]=r<<5|27,nt.setBigUint64(G,e),G+=8}else{let f=e.toString(2),o=new Uint8Array(Math.ceil(f.length/8)),h=e,u=0;while(o.byteLength-++u>=0)o[o.byteLength-u]=Number(h&BigInt(255)),h>>=BigInt(8);ks(o.byteLength*2+16),m[G++]=s?194:195,Hc(2,o.byteLength),m.set(o,G),G+=o.byteLength}continue}else if(i===null){m[G++]=246;continue}else if(typeof i==="boolean"){m[G++]=224|(i?21:20);continue}else if(typeof i>"u")throw Error("@smithy/core/cbor: client may not serialize undefined value.");else if(Array.isArray(i)){Ki(4,i.length),ks(i.length*9+64);for(let s=i.length-1;s>=0;--s)t.push(i[s]);continue}else if(typeof i.byteLength==="number"){ks(i.length*2+9),Ki(2,i.length),m.set(i,G),G+=i.byteLength;continue}else if(typeof i==="object"){if(i instanceof X1){let e=i.string.indexOf("."),f=e===-1?0:e-i.string.length+1,o=BigInt(i.string.replace(".",""));m[G++]=196,Ki(4,2),t.push(o),t.push(f);continue}if(i[mc])if("tag"in i&&"value"in i){t.push(i.value),Hc(6,i.tag);continue}else throw Error("tag encountered with missing fields, need 'tag' and 'value', found: "+JSON.stringify(i));let s=Object.keys(i),r=s.length;Ki(5,r);for(let e=r-1;e>=0;--e)t.push(i[s[e]]),t.push(s[e]);continue}throw Error(`data type ${i?.constructor?.name??typeof i} not compatible for encoding.`)}}function eP(){fe=fe+1&65535,Fc=!1}function J1(){let n=qs(G);return n.set(m.subarray(0,G),0),G=0,n}function Pc(n){let t=m;if(m=qs(n),t)if(t.copy)t.copy(m,0,0,t.byteLength);else m.set(t,0);nt=new DataView(m.buffer,m.byteOffset,m.byteLength)}function oP(n){let t=Ks.get(n);if(t!==void 0){m.set(t.bytes,G),G+=t.bytes.length,t.epoch=fe;return}let i=G,s=Buffer.byteLength(n);Ki(3,s),G+=m.write(n,G);let r=Uint8Array.prototype.slice.call(m,i,G);if(Ks.size>=2048){if(Fc)return;let e=0;for(let[f,o]of Ks){if(e>=1024)break;if(o.epoch!==fe)Ks.delete(f),e++}if(e===0){Fc=!0;return}}if(Ks.size<2048)Ks.set(n,{epoch:fe,bytes:r})}function ks(n){if(m.byteLength-G<n)if(G<16000000)Pc(Math.max(m.byteLength*4,m.byteLength+n));else Pc(m.byteLength+n+16000000)}function Hc(n,t){if(t<24)m[G++]=n<<5|t;else if(t<256)m[G++]=n<<5|24,m[G++]=t;else if(t<65536)m[G++]=n<<5|25,nt.setUint16(G,t),G+=2;else if(t<4294967296)m[G++]=n<<5|26,nt.setUint32(G,t),G+=4;else m[G++]=n<<5|27,nt.setBigUint64(G,typeof t==="bigint"?t:BigInt(t)),G+=8}function Ki(n,t){if(t<24)m[G++]=n<<5|t;else if(t<256)m[G++]=n<<5|24,m[G++]=t;else if(t<65536)m[G++]=n<<5|25,m[G++]=t>>8,m[G++]=t&255;else if(t<4294967296)m[G++]=n<<5|26,nt.setUint32(G,t),G+=4;else{m[G++]=n<<5|27;let i=t/4294967296|0,s=t-i*4294967296|0;nt.setUint32(G,i),nt.setUint32(G+4,s),G+=8}}var vo={deserialize(n){return qF(),XF(n),li(0,n.length)},serialize(n){eP();try{return rP(n),J1()}catch(t){throw J1(),t}},resizeEncodingBuffer(n){Pc(n)}},x1=(n,t)=>{return DF(n,t).then(async(i)=>{if(i.length)try{return vo.deserialize(i)}catch(s){throw Object.defineProperty(s,"$responseBodyText",{value:t.utf8Encoder(i)}),s}return{}})},ao=(n)=>{return Jc({tag:1,value:n.getTime()/1000})},fP=async(n,t)=>{let i=await x1(n,t);return i.message=i.message??i.Message,i},K1=(n,t)=>{let i=(r)=>{let e=r;if(typeof e==="number")e=e.toString();if(e.indexOf(",")>=0)e=e.split(",")[0];if(e.indexOf(":")>=0)e=e.split(":")[0];if(e.indexOf("#")>=0)e=e.split("#")[1];return e};if(t.__type!==void 0)return i(t.__type);let s;for(let r in t)if(r.toLowerCase()==="code"){s=r;break}if(s&&t[s]!==void 0)return i(t[s])},hP=(n)=>{if(String(n.headers["smithy-protocol"]).toLowerCase()!=="rpc-v2-cbor")throw Error("Malformed RPCv2 CBOR response, status: "+n.statusCode)},uP=async(n,t,i,s,r)=>{let e=await n.endpoint(),{hostname:f,protocol:o="https",port:h,path:u}=e,c={protocol:o,hostname:f,port:h,method:"POST",path:u.endsWith("/")?u.slice(0,-1)+i:u+i,headers:{...t}};if(s!==void 0)c.hostname=s;if(e.headers)for(let _ in e.headers)c.headers[_]=e.headers[_];if(r!==void 0){c.body=r;try{c.headers["content-length"]=String(WF(r))}catch(_){}}return new PF(c)};class xc extends Dc{createSerializer(){let n=new Kc;return n.setSerdeContext(this.serdeContext),n}createDeserializer(){let n=new kc;return n.setSerdeContext(this.serdeContext),n}}class Kc extends Dc{value;write(n,t){this.value=this.serialize(n,t)}serialize(n,t){let i=Yc.of(n);if(t==null){if(i.isIdempotencyToken())return FF();return t}if(i.isBlobSchema()){if(typeof t==="string")return(this.serdeContext?.base64Decoder??z1)(t);return t}if(i.isTimestampSchema()){if(typeof t==="number"||typeof t==="bigint")return ao(new Date(Number(t)/1000|0));return ao(t)}if(typeof t==="function"||typeof t==="object"){let s=t;if(i.isListSchema()&&Array.isArray(s)){let e=!!i.getMergedTraits().sparse,f=[],o=0;for(let h of s){let u=this.serialize(i.getValueSchema(),h);if(u!=null||e)f[o++]=u}return f}if(s instanceof Date)return ao(s);let r={};if(i.isMapSchema()){let e=!!i.getMergedTraits().sparse;for(let f in s){let o=this.serialize(i.getValueSchema(),s[f]);if(o!=null||e)r[f]=o}}else if(i.isStructSchema()){for(let[f,o]of i.structIterator()){let h=this.serialize(o,s[f]);if(h!=null)r[f]=h}if(i.isUnionSchema()&&Array.isArray(s.$unknown)){let[f,o]=s.$unknown;r[f]=o}else if(typeof s.__type==="string"){for(let f in s)if(!(f in r))r[f]=this.serialize(15,s[f])}}else if(i.isDocumentSchema())for(let e in s)r[e]=this.serialize(i.getValueSchema(),s[e]);else if(i.isBigDecimalSchema())return s;return r}return t}flush(){let n=vo.serialize(this.value);return this.value=void 0,n}}class kc extends Dc{read(n,t){let i=vo.deserialize(t);return this.readValue(n,i)}readValue(n,t){let i=Yc.of(n);if(i.isTimestampSchema()){if(typeof t==="number")return D1(t);if(typeof t==="object"){if(t.tag===1&&"value"in t)return D1(t.value)}}if(i.isBlobSchema()){if(typeof t==="string")return(this.serdeContext?.base64Decoder??z1)(t);return t}if(typeof t>"u"||typeof t==="boolean"||typeof t==="number"||typeof t==="string"||typeof t==="bigint"||typeof t==="symbol")return t;else if(typeof t==="object"){if(t===null)return null;if("byteLength"in t)return t;if(t instanceof Date)return t;if(i.isDocumentSchema())return t;if(i.isListSchema()){let r=[],e=i.getValueSchema();for(let f of t){let o=this.readValue(e,f);r.push(o)}return r}let s={};if(i.isMapSchema()){let r=i.getValueSchema();for(let e in t){let f=this.readValue(r,t[e]);s[e]=f}}else if(i.isStructSchema()){let r=i.isUnionSchema(),e;if(r){e=new Set;for(let f in t)if(f!=="__type")e.add(f)}for(let[f,o]of i.structIterator()){if(r)e.delete(f);if(t[f]!=null)s[f]=this.readValue(o,t[f])}if(r&&e?.size===1){let f=!0;for(let o in s){f=!1;break}if(f){let o=e.values().next().value;s.$unknown=[o,t[o]]}}else if(typeof t.__type==="string"){for(let f in t)if(!(f in s))s[f]=t[f]}}else if(t instanceof X1)return t;return s}else return t}}class k1 extends YF{codec=new xc;serializer=this.codec.createSerializer();deserializer=this.codec.createDeserializer();constructor({defaultNamespace:n,errorTypeRegistries:t}){super({defaultNamespace:n,errorTypeRegistries:t})}getShapeId(){return"smithy.protocols#rpcv2Cbor"}getPayloadCodec(){return this.codec}async serializeRequest(n,t,i){let s=await super.serializeRequest(n,t,i);if(Object.assign(s.headers,{"content-type":this.getDefaultContentType(),"smithy-protocol":"rpc-v2-cbor",accept:this.getDefaultContentType()}),mF(n.input)==="unit")delete s.body,delete s.headers["content-type"];else{if(!s.body)this.serializer.write(15,{}),s.body=this.serializer.flush();try{s.headers["content-length"]=String(s.body.byteLength)}catch(o){}}let{service:r,operation:e}=JF(i),f=`/service/${r}/operation/${e}`;if(s.path.endsWith("/"))s.path+=f.slice(1);else s.path+=f;return s}async deserializeResponse(n,t,i){return super.deserializeResponse(n,t,i)}async handleError(n,t,i,s,r){let e=K1(i,s)??"Unknown",f={$metadata:r,$fault:i.statusCode<=500?"client":"server"},o=this.options.defaultNamespace;if(e.includes("#"))[o]=e.split("#");let h=this.compositeErrorRegistry,u=Y1.for(o);h.copyFrom(u);let c;try{c=h.getSchema(e)}catch(E){if(s.Message)s.message=s.Message;let R=Y1.for("smithy.ts.sdk.synthetic."+o);h.copyFrom(R);let y=h.getBaseException();if(y){let T=h.getErrorCtor(y);throw Object.assign(new T({name:e}),f,s)}throw Object.assign(Error(e),f,s)}let _=Yc.of(c),w=h.getErrorCtor(c),l=s.message??s.Message??"Unknown",A=new w({}),d={};for(let[E,R]of _.structIterator())d[E]=this.deserializer.readValue(R,s[E]);throw Object.assign(A,f,{$fault:_.getMergedTraits().error,message:l},d)}getDefaultContentType(){return"application/cbor"}}cP.CborCodec=xc;cP.CborShapeDeserializer=kc;cP.CborShapeSerializer=Kc;cP.SmithyRpcV2CborProtocol=k1;cP.buildHttpRpcRequest=uP;cP.cbor=vo;cP.checkCborResponse=hP;cP.dateToTag=ao;cP.loadSmithyRpcV2CborErrorCode=K1;cP.parseCborBody=x1;cP.parseCborErrorBody=fP;cP.tag=Jc;cP.tagSymbol=mc});var V1=k((GP)=>{var UP=/[&<>"]/g,bP={"&":"&","<":"<",">":">",'"':"""};function $P(n){return n.replace(UP,(t)=>bP[t])}var LP=/[&"'<>\r\n\u0085\u2028]/g,OP={"&":"&",'"':""","'":"'","<":"<",">":">","\r":"
","\n":"
","\x85":"…","\u2028":"
"};function BP(n){return n.replace(LP,(t)=>OP[t])}class qc{value;constructor(n){this.value=n}toString(){return BP(""+this.value)}}class ce{name;children;attributes={};static of(n,t,i){let s=new ce(n);if(t!==void 0)s.addChildNode(new qc(t));if(i!==void 0)s.withName(i);return s}constructor(n,t=[]){this.name=n,this.children=t}withName(n){return this.name=n,this}addAttribute(n,t){return this.attributes[n]=t,this}addChildNode(n){return this.children.push(n),this}removeAttribute(n){return delete this.attributes[n],this}n(n){return this.name=n,this}c(n){return this.children.push(n),this}a(n,t){if(t!=null)this.attributes[n]=t;return this}cc(n,t,i=t){if(n[t]!=null){let s=ce.of(t,n[t]).withName(i);this.c(s)}}l(n,t,i,s){if(n[t]!=null)s().map((e)=>{e.withName(i),this.c(e)})}lc(n,t,i,s){if(n[t]!=null){let r=s(),e=new ce(i);r.map((f)=>{e.c(f)}),this.c(e)}}toString(){let n=Boolean(this.children.length),t=`<${this.name}`,i=this.attributes;for(let s of Object.keys(i)){let r=i[s];if(r!=null)t+=` ${s}="${$P(""+r)}"`}return t+=!n?"/>":`>${this.children.map((s)=>s.toString()).join("")}</${this.name}>`}}function NP(n){return new Vc(n).parse()}class Vc{x;i=0;z;constructor(n){this.x=n,this.x=n.replace(/\r\n?/g,`
|
|
45
|
+
`),this.z=this.x.length}parse(){let n=this,{z:t}=n;while(n.i<t){if(n.trim(),n.i>=t)break;if(n.isNext("<?"))n.readTo("?>"),n.trim();else if(n.isNext("<!--"))n.readTo("-->"),n.trim();else if(n.isNext("<!DOCTYPE",!1))n.skipDoctype(),n.trim();else if(n.x[n.i]==="<"){let i=n.parseTag();return{[i.tag]:i.value}}else throw Error("@aws-sdk XML parse error: unexpected content.")}throw Error("@aws-sdk XML parse error: no root element.")}isNext(n,t=!0){let i=this;if(t)return i.x.startsWith(n,i.i);return i.x.toLowerCase().startsWith(n.toLowerCase(),i.i)}readTo(n){let t=this,i=t.x.indexOf(n,t.i);if(i===-1)throw Error(`@aws-sdk XML parse error: expected "${n}" not found.`);let s=t.x.slice(t.i,i);return t.i=i+n.length,s}trim(){let n=this;while(n.i<n.z&&` \r
|
|
46
|
+
`.includes(n.x[n.i]))++n.i}readAttrValue(){let n=this,t=n.x[n.i];++n.i;let i="";while(n.i<n.z&&n.x[n.i]!==t)i+=n.x[n.i++];return++n.i,n.decodeEntities(i)}parseTag(){let n=this;++n.i;let t="";while(n.i<n.z&&!` \r
|
|
47
|
+
>/`.includes(n.x[n.i]))t+=n.x[n.i++];let i=!1,s=Object.create(null);while(n.i<n.z){if(n.trim(),">/".includes(n.x[n.i]))break;let u="";while(n.i<n.z&&!`= \r
|
|
48
|
+
>/?`.includes(n.x[n.i]))u+=n.x[n.i++];if(n.trim(),n.x[n.i]!=="=")break;++n.i,n.trim(),s[u]=n.readAttrValue(),i=!0}if(n.i>=n.z)throw Error("@aws-sdk XML parse error: unexpected end of input.");if(n.x[n.i]==="/"){if(++n.i,n.i>=n.z||n.x[n.i]!==">")throw Error("@aws-sdk XML parse error: expected > at the end of self-closing tag.");return++n.i,Object.setPrototypeOf(s,Object.prototype),{tag:t,value:i?s:""}}if(n.x[n.i]!==">")throw Error("@aws-sdk XML parse error: expected > at the end of opening tag.");++n.i;let r=[],e=[],f=!1;while(n.i<n.z){if(n.isNext("</"))break;if(n.x[n.i]==="<")if(n.isNext("<!--"))n.readTo("-->");else if(n.isNext("<![CDATA["))n.i+=9,r.push(n.readTo("]]>"));else if(n.isNext("<?"))n.readTo("?>");else f=!0,e.push(n.parseTag());else{let u="";while(n.i<n.z&&n.x[n.i]!=="<")u+=n.x[n.i++];r.push(n.decodeEntities(u))}}if(!n.isNext("</"))throw Error(`@aws-sdk XML parse error: missing closing tag </${t}>.`);n.i+=2;let o=n.readTo(">").trim();if(o!==t)throw Error(`@aws-sdk XML parse error: mismatched tags <${t}> and </${o}>.`);if(!i&&r.length===0&&!f)return{tag:t,value:""};if(!i&&!f){let u=r.length===1?r[0]:r.join("");if(u.trim()===""&&u.includes(`
|
|
49
|
+
`))return{tag:t,value:""};return{tag:t,value:u}}let h=Object.create(null);for(let u of r){if(u.trim()===""&&u.includes(`
|
|
50
|
+
`))continue;h["#text"]="#text"in h?h["#text"]+u:u}for(let u of e)if(u.tag in h)if(Array.isArray(h[u.tag]))h[u.tag].push(u.value);else h[u.tag]=[h[u.tag],u.value];else h[u.tag]=u.value;for(let[u,c]of Object.entries(s))h[u]=c;return Object.setPrototypeOf(h,Object.prototype),{tag:t,value:h}}static ENTITIES={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};skipDoctype(){let n=this;n.i+=9;let t=0;while(n.i<n.z){let i=n.x[n.i];if(i==="[")++t;else if(i==="]")--t;else if(i===">"&&t===0){++n.i;return}++n.i}throw Error("@aws-sdk XML parse error: unclosed DOCTYPE.")}decodeEntities(n){return n.replace(/&(?:#x([0-9a-fA-F]{1,6})|#(\d{1,7})|([a-zA-Z][a-zA-Z0-9]{0,30}));/g,(t,i,s,r)=>{if(i)return String.fromCharCode(parseInt(i,16));if(s)return String.fromCharCode(parseInt(s,10));return Vc.ENTITIES[r]??""})}}GP.XmlNode=ce;GP.XmlText=qc;GP.parseXML=NP});var o_=k((jP)=>{var{SmithyRpcV2CborProtocol:PP,loadSmithyRpcV2CborErrorCode:DP}=q1(),{TypeRegistry:j1,NormalizedSchema:En,deref:tR}=ri(),{decorateServiceException:a1,getValueFromTextNode:iR}=Xt(),{collectBody:ac,determineTimestampFormat:nf,RpcProtocol:sR,HttpBindingProtocol:rR,HttpInterceptingShapeSerializer:eR,HttpInterceptingShapeDeserializer:oR,FromStringShapeDeserializer:YP,extendedEncodeURIComponent:v1}=Jn(),{NumericValue:Bt,toUtf8:fR,fromBase64:hR,LazyJsonString:uR,parseEpochTimestamp:mP,parseRfc7231DateTime:JP,parseRfc3339DateTimeWithOffset:XP,toBase64:Zo,dateToUtcString:po,generateIdempotencyToken:vc,expectUnion:zP}=mn(),{parseXML:cR,XmlNode:wt,XmlText:Z1}=V1();class Vs{queryCompat;errorRegistry;constructor(n=!1){this.queryCompat=n}resolveRestContentType(n,t){let i=t.getMemberSchemas(),s=Object.values(i).find((r)=>{return!!r.getMergedTraits().httpPayload});if(s){let r=s.getMergedTraits().mediaType;if(r)return r;else if(s.isStringSchema())return"text/plain";else if(s.isBlobSchema())return"application/octet-stream";else return n}else if(!t.isUnitSchema()){if(Object.values(i).find((e)=>{let{httpQuery:f,httpQueryParams:o,httpHeader:h,httpLabel:u,httpPrefixHeaders:c}=e.getMergedTraits();return!f&&!o&&!h&&!u&&c===void 0}))return n}}async getErrorSchemaOrThrowBaseException(n,t,i,s,r,e){let f=n;if(n.includes("#"))[,f]=n.split("#");let o={$metadata:r,$fault:i.statusCode<500?"client":"server"};if(!this.errorRegistry)throw Error("@aws-sdk/core/protocols - error handler not initialized.");try{return{errorSchema:e?.(this.errorRegistry,f)??this.errorRegistry.getSchema(n),errorMetadata:o}}catch(h){s.message=s.message??s.Message??"UnknownError";let u=this.errorRegistry,c=u.getBaseException();if(c){let l=u.getErrorCtor(c)??Error;throw this.decorateServiceException(Object.assign(new l({name:f}),o),s)}let _=s,w=_?.message??_?.Message??_?.Error?.Message??_?.Error?.message;throw this.decorateServiceException(Object.assign(Error(w),{name:f},o),s)}}compose(n,t,i){let s=i;if(t.includes("#"))[s]=t.split("#");let r=j1.for(s),e=j1.for("smithy.ts.sdk.synthetic."+i);n.copyFrom(r),n.copyFrom(e),this.errorRegistry=n}decorateServiceException(n,t={}){if(this.queryCompat){let i=n.Message??t.Message,s=a1(n,t);if(i)s.message=i;let r=s.Error??{};r.Type=s.Error?.Type,r.Code=s.Error?.Code,r.Message=s.Error?.message??s.Error?.Message??i,s.Error=r;let e=s.$metadata.requestId;if(e)s.RequestId=e;return s}return a1(n,t)}setQueryCompatError(n,t){let i=t.headers?.["x-amzn-query-error"];if(n!==void 0&&i!=null){let[s,r]=i.split(";"),e=Object.keys(n),f={Code:s,Type:r};n.Code=s,n.Type=r;for(let o=0;o<e.length;o++){let h=e[o];f[h==="message"?"Message":h]=n[h]}delete f.__type,n.Error=f}}queryCompatOutput(n,t){if(n.Error)t.Error=n.Error;if(n.Type)t.Type=n.Type;if(n.Code)t.Code=n.Code}findQueryCompatibleError(n,t){try{return n.getSchema(t)}catch(i){return n.find((s)=>En.of(s).getMergedTraits().awsQueryError?.[0]===t)}}}class _R extends PP{awsQueryCompatible;mixin;constructor({defaultNamespace:n,errorTypeRegistries:t,awsQueryCompatible:i}){super({defaultNamespace:n,errorTypeRegistries:t});this.awsQueryCompatible=!!i,this.mixin=new Vs(this.awsQueryCompatible)}async serializeRequest(n,t,i){let s=await super.serializeRequest(n,t,i);if(this.awsQueryCompatible)s.headers["x-amzn-query-mode"]="true";return s}async handleError(n,t,i,s,r){if(this.awsQueryCompatible)this.mixin.setQueryCompatError(s,i);let e=(()=>{let l=i.headers["x-amzn-query-error"];if(l&&this.awsQueryCompatible)return l.split(";")[0];return DP(i,s)??"Unknown"})();this.mixin.compose(this.compositeErrorRegistry,e,this.options.defaultNamespace);let{errorSchema:f,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(e,this.options.defaultNamespace,i,s,r,this.awsQueryCompatible?this.mixin.findQueryCompatibleError:void 0),h=En.of(f),u=s.message??s.Message??"UnknownError",_=new(this.compositeErrorRegistry.getErrorCtor(f)??Error)({}),w={};for(let[l,A]of h.structIterator())if(s[l]!=null)w[l]=this.deserializer.readValue(A,s[l]);if(this.awsQueryCompatible)this.mixin.queryCompatOutput(s,w);throw this.mixin.decorateServiceException(Object.assign(_,o,{$fault:h.getMergedTraits().error,message:u},w),s)}}var QP=(n)=>{if(n==null)return n;if(typeof n==="number"||typeof n==="bigint"){let t=Error(`Received number ${n} where a string was expected.`);return t.name="Warning",console.warn(t),String(n)}if(typeof n==="boolean"){let t=Error(`Received boolean ${n} where a string was expected.`);return t.name="Warning",console.warn(t),String(n)}return n},CP=(n)=>{if(n==null)return n;if(typeof n==="string"){let t=n.toLowerCase();if(n!==""&&t!=="false"&&t!=="true"){let i=Error(`Received string "${n}" where a boolean was expected.`);i.name="Warning",console.warn(i)}return n!==""&&t!=="false"}return n},xP=(n)=>{if(n==null)return n;if(typeof n==="string"){let t=Number(n);if(t.toString()!==n){let i=Error(`Received string "${n}" where a number was expected.`);return i.name="Warning",console.warn(i),n}return t}return n};class Ai{serdeContext;setSerdeContext(n){this.serdeContext=n}}class Zc{from;to;keys;constructor(n,t){this.from=n,this.to=t;let i=Object.keys(this.from),s=new Set(i);s.delete("__type"),this.keys=s}mark(n){this.keys.delete(n)}hasUnknown(){return this.keys.size===1&&Object.keys(this.to).length===0}writeUnknown(){if(this.hasUnknown()){let n=this.keys.values().next().value,t=this.from[n];this.to.$unknown=[n,t]}}}function KP(n,t,i){if(i?.source){let s=i.source;if(typeof t==="number"){if(t>Number.MAX_SAFE_INTEGER||t<Number.MIN_SAFE_INTEGER||s!==String(t))if(s.includes("."))return new Bt(s,"bigDecimal");else return BigInt(s)}}return t}var wR=(n,t)=>ac(n,t).then((i)=>(t?.utf8Encoder??fR)(i)),pc=(n,t)=>wR(n,t).then((i)=>{if(i.length)try{return JSON.parse(i)}catch(s){if(s?.name==="SyntaxError")Object.defineProperty(s,"$responseBodyText",{value:i});throw s}return{}}),kP=async(n,t)=>{let i=await pc(n,t);return i.message=i.message??i.Message,i},p1=(n,t)=>Object.keys(n).find((i)=>i.toLowerCase()===t.toLowerCase()),jc=(n)=>{let t=n;if(typeof t==="number")t=t.toString();if(t.indexOf(",")>=0)t=t.split(",")[0];if(t.indexOf(":")>=0)t=t.split(":")[0];if(t.indexOf("#")>=0)t=t.split("#")[1];return t},lR=(n,t)=>{return MR(n,t,["header","code","type"])},AR=(n,t,i=!1)=>{return MR(n,t,i?["code","header","type"]:["type","code","header"])},MR=({headers:n},t,i)=>{while(i.length>0)switch(i.shift()){case"header":let r=p1(n??{},"x-amzn-errortype");if(r!==void 0)return jc(n[r]);break;case"code":let e=p1(t??{},"code");if(e&&t[e]!==void 0)return jc(t[e]);break;case"type":if(t?.__type!==void 0)return jc(t.__type);break}};class n_ extends Ai{settings;constructor(n){super();this.settings=n}async read(n,t){return this._read(n,typeof t==="string"?JSON.parse(t,KP):await pc(t,this.serdeContext))}readObject(n,t){return this._read(n,t)}_read(n,t){let i=t!==null&&typeof t==="object",s=En.of(n);if(i){if(s.isStructSchema()){let e=t,f=s.isUnionSchema(),o={},h=void 0,{jsonName:u}=this.settings;if(u)h={};let c;if(f)c=new Zc(e,o);for(let[_,w]of s.structIterator()){let l=_;if(u)l=w.getMergedTraits().jsonName??l,h[l]=_;if(f)c.mark(l);if(e[l]!=null)o[_]=this._read(w,e[l])}if(f)c.writeUnknown();else if(typeof e.__type==="string")for(let _ in e){let w=e[_],l=u?h[_]??_:_;if(!(l in o))o[l]=w}return o}if(Array.isArray(t)&&s.isListSchema()){let e=s.getValueSchema(),f=[];for(let o of t)f.push(this._read(e,o));return f}if(s.isMapSchema()){let e=s.getValueSchema(),f={};for(let o in t)f[o]=this._read(e,t[o]);return f}}if(s.isBlobSchema()&&typeof t==="string")return hR(t);let r=s.getMergedTraits().mediaType;if(s.isStringSchema()&&typeof t==="string"&&r){if(r==="application/json"||r.endsWith("+json"))return uR.from(t);return t}if(s.isTimestampSchema()&&t!=null)switch(nf(s,this.settings)){case 5:return XP(t);case 6:return JP(t);case 7:return mP(t);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",t),new Date(t)}if(s.isBigIntegerSchema()&&(typeof t==="number"||typeof t==="string"))return BigInt(t);if(s.isBigDecimalSchema()&&t!=null){if(t instanceof Bt)return t;let e=t;if(e.type==="bigDecimal"&&"string"in e)return new Bt(e.string,e.type);return new Bt(String(t),"bigDecimal")}if(s.isNumericSchema()&&typeof t==="string"){switch(t){case"Infinity":return 1/0;case"-Infinity":return-1/0;case"NaN":return NaN}return t}if(s.isDocumentSchema())if(i){let e=Array.isArray(t)?[]:{};for(let f in t){let o=t[f];if(o instanceof Bt)e[f]=o;else e[f]=this._read(s,o)}return e}else return structuredClone(t);return t}}var nR=String.fromCharCode(925);class dR{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,(n,t)=>{if(t instanceof Bt){let i=`${nR+"nv"+this.counter++}_`+t.string;return this.values.set(`"${i}"`,t.string),i}if(typeof t==="bigint"){let i=t.toString(),s=`${nR+"b"+this.counter++}_`+i;return this.values.set(`"${s}"`,i),s}return t}}replaceInJson(n){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 n;for(let[t,i]of this.values)n=n.replace(t,i);return n}}class t_ extends Ai{settings;buffer;useReplacer=!1;rootSchema;constructor(n){super();this.settings=n}write(n,t){this.rootSchema=En.of(n),this.buffer=this._write(this.rootSchema,t)}flush(){let{rootSchema:n,useReplacer:t}=this;if(this.rootSchema=void 0,this.useReplacer=!1,n?.isStructSchema()||n?.isDocumentSchema()){if(!t)return JSON.stringify(this.buffer);let i=new dR;return i.replaceInJson(JSON.stringify(this.buffer,i.createReplacer(),0))}return this.buffer}writeDiscriminatedDocument(n,t){if(this.write(n,t),typeof this.buffer==="object")this.buffer.__type=En.of(n).getName(!0)}_write(n,t,i){let s=t!==null&&typeof t==="object",r=En.of(n);if(s){if(r.isStructSchema()){let e=t,f={},{jsonName:o}=this.settings,h=void 0;if(o)h={};let u=0;for(let[c,_]of r.structIterator()){let w=this._write(_,e[c],r);if(w!==void 0){let l=c;if(o)l=_.getMergedTraits().jsonName??c,h[c]=l;f[l]=w,u++}}if(r.isUnionSchema()&&u===0){let{$unknown:c}=e;if(Array.isArray(c)){let[_,w]=c;f[_]=this._write(15,w)}}else if(typeof e.__type==="string")for(let c in e){let _=e[c],w=o?h[c]??c:c;if(!(w in f))f[w]=this._write(15,_)}return f}if(Array.isArray(t)&&r.isListSchema()){let e=r.getValueSchema(),f=[],o=!!r.getMergedTraits().sparse;for(let h of t)if(o||h!=null)f.push(this._write(e,h));return f}if(r.isMapSchema()){let e=r.getValueSchema(),f={},o=!!r.getMergedTraits().sparse;for(let h in t){let u=t[h];if(o||u!=null)f[h]=this._write(e,u)}return f}if(t instanceof Uint8Array&&(r.isBlobSchema()||r.isDocumentSchema())){if(r===this.rootSchema)return t;return(this.serdeContext?.base64Encoder??Zo)(t)}if(t instanceof Date&&(r.isTimestampSchema()||r.isDocumentSchema()))switch(nf(r,this.settings)){case 5:return t.toISOString().replace(".000Z","Z");case 6:return po(t);case 7:return t.getTime()/1000;default:return console.warn("Missing timestamp format, using epoch seconds",t),t.getTime()/1000}if(t instanceof Bt)this.useReplacer=!0}if(t===null&&i?.isStructSchema())return;if(r.isStringSchema()){if(typeof t>"u"&&r.isIdempotencyToken())return vc();let e=r.getMergedTraits().mediaType;if(t!=null&&e){if(e==="application/json"||e.endsWith("+json"))return uR.from(t)}return t}if(typeof t==="number"&&r.isNumericSchema()){if(Math.abs(t)===1/0||isNaN(t))return String(t);return t}if(typeof t==="string"&&r.isBlobSchema()){if(r===this.rootSchema)return t;return(this.serdeContext?.base64Encoder??Zo)(t)}if(typeof t==="bigint")this.useReplacer=!0;if(r.isDocumentSchema())if(s){let e=Array.isArray(t)?[]:{};for(let f in t){let o=t[f];if(o instanceof Bt)this.useReplacer=!0,e[f]=o;else e[f]=this._write(r,o)}return e}else return structuredClone(t);return t}}class tf extends Ai{settings;constructor(n){super();this.settings=n}createSerializer(){let n=new t_(this.settings);return n.setSerdeContext(this.serdeContext),n}createDeserializer(){let n=new n_(this.settings);return n.setSerdeContext(this.serdeContext),n}}class sf extends sR{serializer;deserializer;serviceTarget;codec;mixin;awsQueryCompatible;constructor({defaultNamespace:n,errorTypeRegistries:t,serviceTarget:i,awsQueryCompatible:s,jsonCodec:r}){super({defaultNamespace:n,errorTypeRegistries:t});this.serviceTarget=i,this.codec=r??new tf({timestampFormat:{useTrait:!0,default:7},jsonName:!1}),this.serializer=this.codec.createSerializer(),this.deserializer=this.codec.createDeserializer(),this.awsQueryCompatible=!!s,this.mixin=new Vs(this.awsQueryCompatible)}async serializeRequest(n,t,i){let s=await super.serializeRequest(n,t,i);if(!s.path.endsWith("/"))s.path+="/";if(s.headers["content-type"]=`application/x-amz-json-${this.getJsonRpcVersion()}`,s.headers["x-amz-target"]=`${this.serviceTarget}.${n.name}`,this.awsQueryCompatible)s.headers["x-amzn-query-mode"]="true";if(tR(n.input)==="unit"||!s.body)s.body="{}";return s}getPayloadCodec(){return this.codec}async handleError(n,t,i,s,r){let{awsQueryCompatible:e}=this;if(e)this.mixin.setQueryCompatError(s,i);let f=AR(i,s,e)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,f,this.options.defaultNamespace);let{errorSchema:o,errorMetadata:h}=await this.mixin.getErrorSchemaOrThrowBaseException(f,this.options.defaultNamespace,i,s,r,e?this.mixin.findQueryCompatibleError:void 0),u=En.of(o),c=s.message??s.Message??"UnknownError",w=new(this.compositeErrorRegistry.getErrorCtor(o)??Error)({}),l={},A=this.codec.createDeserializer();for(let[d,E]of u.structIterator())if(s[d]!=null)l[d]=A.readObject(E,s[d]);if(e)this.mixin.queryCompatOutput(s,l);throw this.mixin.decorateServiceException(Object.assign(w,h,{$fault:u.getMergedTraits().error,message:c},l),s)}}class RR extends sf{constructor({defaultNamespace:n,errorTypeRegistries:t,serviceTarget:i,awsQueryCompatible:s,jsonCodec:r}){super({defaultNamespace:n,errorTypeRegistries:t,serviceTarget:i,awsQueryCompatible:s,jsonCodec:r})}getShapeId(){return"aws.protocols#awsJson1_0"}getJsonRpcVersion(){return"1.0"}getDefaultContentType(){return"application/x-amz-json-1.0"}}class ER extends sf{constructor({defaultNamespace:n,errorTypeRegistries:t,serviceTarget:i,awsQueryCompatible:s,jsonCodec:r}){super({defaultNamespace:n,errorTypeRegistries:t,serviceTarget:i,awsQueryCompatible:s,jsonCodec:r})}getShapeId(){return"aws.protocols#awsJson1_1"}getJsonRpcVersion(){return"1.1"}getDefaultContentType(){return"application/x-amz-json-1.1"}}class yR extends rR{serializer;deserializer;codec;mixin=new Vs;constructor({defaultNamespace:n,errorTypeRegistries:t}){super({defaultNamespace:n,errorTypeRegistries:t});let i={timestampFormat:{useTrait:!0,default:7},httpBindings:!0,jsonName:!0};this.codec=new tf(i),this.serializer=new eR(this.codec.createSerializer(),i),this.deserializer=new oR(this.codec.createDeserializer(),i)}getShapeId(){return"aws.protocols#restJson1"}getPayloadCodec(){return this.codec}setSerdeContext(n){this.codec.setSerdeContext(n),super.setSerdeContext(n)}async serializeRequest(n,t,i){let s=await super.serializeRequest(n,t,i),r=En.of(n.input);if(!s.headers["content-type"]){let e=this.mixin.resolveRestContentType(this.getDefaultContentType(),r);if(e)s.headers["content-type"]=e}if(s.body==null&&s.headers["content-type"]===this.getDefaultContentType())s.body="{}";return s}async deserializeResponse(n,t,i){let s=await super.deserializeResponse(n,t,i),r=En.of(n.output);for(let[e,f]of r.structIterator())if(f.getMemberTraits().httpPayload&&!(e in s))s[e]=null;return s}async handleError(n,t,i,s,r){let e=lR(i,s)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,e,this.options.defaultNamespace);let{errorSchema:f,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(e,this.options.defaultNamespace,i,s,r),h=En.of(f),u=s.message??s.Message??"UnknownError",_=new(this.compositeErrorRegistry.getErrorCtor(f)??Error)({});await this.deserializeHttpMessage(f,t,i,s);let w={},l=this.codec.createDeserializer();for(let[A,d]of h.structIterator()){let E=d.getMergedTraits().jsonName??A;w[A]=l.readObject(d,s[E])}throw this.mixin.decorateServiceException(Object.assign(_,o,{$fault:h.getMergedTraits().error,message:u},w),s)}getDefaultContentType(){return"application/json"}}var qP=(n)=>{if(n==null)return;if(typeof n==="object"&&"__type"in n)delete n.__type;return zP(n)};class rf extends Ai{settings;stringDeserializer;constructor(n){super();this.settings=n,this.stringDeserializer=new YP(n)}setSerdeContext(n){this.serdeContext=n,this.stringDeserializer.setSerdeContext(n)}read(n,t,i){let s=En.of(n),r=s.getMemberSchemas();if(s.isStructSchema()&&s.isMemberSchema()&&!!Object.values(r).find((h)=>{return!!h.getMemberTraits().eventPayload})){let h={},u=Object.keys(r)[0];if(r[u].isBlobSchema())h[u]=t;else h[u]=this.read(r[u],t);return h}let f=(this.serdeContext?.utf8Encoder??fR)(t),o=this.parseXml(f);return this.readSchema(n,i?o[i]:o)}readSchema(n,t){let i=En.of(n);if(i.isUnitSchema())return;let s=i.getMergedTraits();if(i.isListSchema()&&!Array.isArray(t))return this.readSchema(i,[t]);if(t==null)return t;if(typeof t==="object"){let r=!!s.xmlFlattened;if(i.isListSchema()){let f=i.getValueSchema(),o=[],h=f.getMergedTraits().xmlName??"member",u=r?t:(t[0]??t)[h];if(u==null)return o;let c=Array.isArray(u)?u:[u];for(let _ of c)o.push(this.readSchema(f,_));return o}let e={};if(i.isMapSchema()){let f=i.getKeySchema(),o=i.getValueSchema(),h;if(r)h=Array.isArray(t)?t:[t];else h=Array.isArray(t.entry)?t.entry:[t.entry];let u=f.getMergedTraits().xmlName??"key",c=o.getMergedTraits().xmlName??"value";for(let _ of h){let w=_[u],l=_[c];e[w]=this.readSchema(o,l)}return e}if(i.isStructSchema()){let f=i.isUnionSchema(),o;if(f)o=new Zc(t,e);for(let[h,u]of i.structIterator()){let c=u.getMergedTraits(),_=!c.httpPayload?u.getMemberTraits().xmlName??h:c.xmlName??u.getName();if(f)o.mark(_);if(t[_]!=null)e[h]=this.readSchema(u,t[_])}if(f)o.writeUnknown();return e}if(i.isDocumentSchema())return t;throw Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${i.getName(!0)}`)}if(i.isListSchema())return[];if(i.isMapSchema()||i.isStructSchema())return{};return this.stringDeserializer.read(i,t)}parseXml(n){if(n.length){let t;try{t=cR(n)}catch(e){if(e&&typeof e==="object")Object.defineProperty(e,"$responseBodyText",{value:n});throw e}let i="#text",s=Object.keys(t)[0],r=t[s];if(r[i])r[s]=r[i],delete r[i];return iR(r)}return{}}}class i_ extends Ai{settings;buffer;constructor(n){super();this.settings=n}write(n,t,i=""){if(this.buffer===void 0)this.buffer="";let s=En.of(n);if(i&&!i.endsWith("."))i+=".";if(s.isBlobSchema()){if(typeof t==="string"||t instanceof Uint8Array)this.writeKey(i),this.writeValue((this.serdeContext?.base64Encoder??Zo)(t))}else if(s.isBooleanSchema()||s.isNumericSchema()||s.isStringSchema()){if(t!=null)this.writeKey(i),this.writeValue(String(t));else if(s.isIdempotencyToken())this.writeKey(i),this.writeValue(vc())}else if(s.isBigIntegerSchema()){if(t!=null)this.writeKey(i),this.writeValue(String(t))}else if(s.isBigDecimalSchema()){if(t!=null)this.writeKey(i),this.writeValue(t instanceof Bt?t.string:String(t))}else if(s.isTimestampSchema()){if(t instanceof Date)switch(this.writeKey(i),nf(s,this.settings)){case 5:this.writeValue(t.toISOString().replace(".000Z","Z"));break;case 6:this.writeValue(po(t));break;case 7:this.writeValue(String(t.getTime()/1000));break}}else if(s.isDocumentSchema())if(Array.isArray(t))this.write(79,t,i);else if(t instanceof Date)this.write(4,t,i);else if(t instanceof Uint8Array)this.write(21,t,i);else if(t&&typeof t==="object")this.write(143,t,i);else this.writeKey(i),this.writeValue(String(t));else if(s.isListSchema()){if(Array.isArray(t))if(t.length===0){if(this.settings.serializeEmptyLists)this.writeKey(i),this.writeValue("")}else{let r=s.getValueSchema(),e=this.settings.flattenLists||s.getMergedTraits().xmlFlattened,f=1;for(let o of t){if(o==null)continue;let h=r.getMergedTraits(),u=this.getKey("member",h.xmlName,h.ec2QueryName),c=e?`${i}${f}`:`${i}${u}.${f}`;this.write(r,o,c),++f}}}else if(s.isMapSchema()){if(t&&typeof t==="object"){let r=s.getKeySchema(),e=s.getValueSchema(),f=s.getMergedTraits().xmlFlattened,o=1;for(let h in t){let u=t[h];if(u==null)continue;let c=r.getMergedTraits(),_=this.getKey("key",c.xmlName,c.ec2QueryName),w=f?`${i}${o}.${_}`:`${i}entry.${o}.${_}`,l=e.getMergedTraits(),A=this.getKey("value",l.xmlName,l.ec2QueryName),d=f?`${i}${o}.${A}`:`${i}entry.${o}.${A}`;this.write(r,h,w),this.write(e,u,d),++o}}}else if(s.isStructSchema()){if(t&&typeof t==="object"){let r=!1;for(let[e,f]of s.structIterator()){if(t[e]==null&&!f.isIdempotencyToken())continue;let o=f.getMergedTraits(),h=this.getKey(e,o.xmlName,o.ec2QueryName,"struct"),u=`${i}${h}`;this.write(f,t[e],u),r=!0}if(!r&&s.isUnionSchema()){let{$unknown:e}=t;if(Array.isArray(e)){let[f,o]=e,h=`${i}${f}`;this.write(15,o,h)}}}}else if(s.isUnitSchema());else throw Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${s.getName(!0)}`)}flush(){if(this.buffer===void 0)throw Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer.");let n=this.buffer;return delete this.buffer,n}getKey(n,t,i,s){let{ec2:r,capitalizeKeys:e}=this.settings;if(r&&i)return i;let f=t??n;if(e&&s==="struct")return f[0].toUpperCase()+f.slice(1);return f}writeKey(n){if(n.endsWith("."))n=n.slice(0,n.length-1);this.buffer+=`&${v1(n)}=`}writeValue(n){this.buffer+=v1(n)}}class s_ extends sR{options;serializer;deserializer;mixin=new Vs;constructor(n){super({defaultNamespace:n.defaultNamespace,errorTypeRegistries:n.errorTypeRegistries});this.options=n;let t={timestampFormat:{useTrait:!0,default:5},httpBindings:!1,xmlNamespace:n.xmlNamespace,serviceNamespace:n.defaultNamespace,serializeEmptyLists:!0};this.serializer=new i_(t),this.deserializer=new rf(t)}getShapeId(){return"aws.protocols#awsQuery"}setSerdeContext(n){this.serializer.setSerdeContext(n),this.deserializer.setSerdeContext(n)}getPayloadCodec(){throw Error("AWSQuery protocol has no payload codec.")}async serializeRequest(n,t,i){let s=await super.serializeRequest(n,t,i);if(!s.path.endsWith("/"))s.path+="/";if(s.headers["content-type"]="application/x-www-form-urlencoded",tR(n.input)==="unit"||!s.body)s.body="";let r=n.name.split("#")[1]??n.name;if(s.body=`Action=${r}&Version=${this.options.version}`+s.body,s.body.endsWith("&"))s.body=s.body.slice(-1);return s}async deserializeResponse(n,t,i){let s=this.deserializer,r=En.of(n.output),e={};if(i.statusCode>=300){let u=await ac(i.body,t);if(u.byteLength>0)Object.assign(e,await s.read(15,u));await this.handleError(n,t,i,e,this.deserializeMetadata(i))}for(let u in i.headers){let c=i.headers[u];delete i.headers[u],i.headers[u.toLowerCase()]=c}let f=n.name.split("#")[1]??n.name,o=r.isStructSchema()&&this.useNestedResult()?f+"Result":void 0,h=await ac(i.body,t);if(h.byteLength>0)Object.assign(e,await s.read(r,h,o));return e.$metadata=this.deserializeMetadata(i),e}useNestedResult(){return!0}async handleError(n,t,i,s,r){let e=this.loadQueryErrorCode(i,s)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,e,this.options.defaultNamespace);let f=this.loadQueryError(s)??{},o=this.loadQueryErrorMessage(s);f.message=o,f.Error={Type:f.Type,Code:f.Code,Message:o};let{errorSchema:h,errorMetadata:u}=await this.mixin.getErrorSchemaOrThrowBaseException(e,this.options.defaultNamespace,i,f,r,this.mixin.findQueryCompatibleError),c=En.of(h),w=new(this.compositeErrorRegistry.getErrorCtor(h)??Error)({}),l={Type:f.Error.Type,Code:f.Error.Code,Error:f.Error};for(let[A,d]of c.structIterator()){let E=d.getMergedTraits().xmlName??A,R=f[E]??s[E];l[A]=this.deserializer.readSchema(d,R)}throw this.mixin.decorateServiceException(Object.assign(w,u,{$fault:c.getMergedTraits().error,message:o},l),s)}loadQueryErrorCode(n,t){let i=(t.Errors?.[0]?.Error??t.Errors?.Error??t.Error)?.Code;if(i!==void 0)return i;if(n.statusCode==404)return"NotFound"}loadQueryError(n){return n.Errors?.[0]?.Error??n.Errors?.Error??n.Error}loadQueryErrorMessage(n){let t=this.loadQueryError(n);return t?.message??t?.Message??n.message??n.Message??"Unknown"}getDefaultContentType(){return"application/x-www-form-urlencoded"}}class TR extends s_{options;constructor(n){super(n);this.options=n;let t={capitalizeKeys:!0,flattenLists:!0,serializeEmptyLists:!1,ec2:!0};Object.assign(this.serializer.settings,t)}getShapeId(){return"aws.protocols#ec2Query"}useNestedResult(){return!1}}var gR=(n,t)=>wR(n,t).then((i)=>{if(i.length){let s;try{s=cR(i)}catch(o){if(o&&typeof o==="object")Object.defineProperty(o,"$responseBodyText",{value:i});throw o}let r="#text",e=Object.keys(s)[0],f=s[e];if(f[r])f[e]=f[r],delete f[r];return iR(f)}return{}}),VP=async(n,t)=>{let i=await gR(n,t);if(i.Error)i.Error.message=i.Error.message??i.Error.Message;return i},SR=(n,t)=>{if(t?.Error?.Code!==void 0)return t.Error.Code;if(t?.Code!==void 0)return t.Code;if(n.statusCode==404)return"NotFound"};class r_ extends Ai{settings;stringBuffer;byteBuffer;buffer;constructor(n){super();this.settings=n}write(n,t){let i=En.of(n);if(i.isStringSchema()&&typeof t==="string")this.stringBuffer=t;else if(i.isBlobSchema())this.byteBuffer="byteLength"in t?t:(this.serdeContext?.base64Decoder??hR)(t);else{this.buffer=this.writeStruct(i,t,void 0);let s=i.getMergedTraits();if(s.httpPayload&&!s.xmlName)this.buffer.withName(i.getName())}}flush(){if(this.byteBuffer!==void 0){let t=this.byteBuffer;return delete this.byteBuffer,t}if(this.stringBuffer!==void 0){let t=this.stringBuffer;return delete this.stringBuffer,t}let n=this.buffer;if(this.settings.xmlNamespace){if(!n?.attributes?.xmlns)n.addAttribute("xmlns",this.settings.xmlNamespace)}return delete this.buffer,n.toString()}writeStruct(n,t,i){let s=n.getMergedTraits(),r=n.isMemberSchema()&&!s.httpPayload?n.getMemberTraits().xmlName??n.getMemberName():s.xmlName??n.getName();if(!r||!n.isStructSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${n.getName(!0)}.`);let e=wt.of(r),[f,o]=this.getXmlnsAttribute(n,i);for(let[u,c]of n.structIterator()){let _=t[u];if(_!=null||c.isIdempotencyToken()){if(c.getMergedTraits().xmlAttribute){e.addAttribute(c.getMergedTraits().xmlName??u,this.writeSimple(c,_));continue}if(c.isListSchema())this.writeList(c,_,e,o);else if(c.isMapSchema())this.writeMap(c,_,e,o);else if(c.isStructSchema())e.addChildNode(this.writeStruct(c,_,o));else{let w=wt.of(c.getMergedTraits().xmlName??c.getMemberName());this.writeSimpleInto(c,_,w,o),e.addChildNode(w)}}}let{$unknown:h}=t;if(h&&n.isUnionSchema()&&Array.isArray(h)&&Object.keys(t).length===1){let[u,c]=h,_=wt.of(u);if(typeof c!=="string")if(t instanceof wt||t instanceof Z1)e.addChildNode(t);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,c,_,o),e.addChildNode(_)}if(o)e.addAttribute(f,o);return e}writeList(n,t,i,s){if(!n.isMemberSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${n.getName(!0)}`);let r=n.getMergedTraits(),e=n.getValueSchema(),f=e.getMergedTraits(),o=!!f.sparse,h=!!r.xmlFlattened,[u,c]=this.getXmlnsAttribute(n,s),_=(w,l)=>{if(e.isListSchema())this.writeList(e,Array.isArray(l)?l:[l],w,c);else if(e.isMapSchema())this.writeMap(e,l,w,c);else if(e.isStructSchema()){let A=this.writeStruct(e,l,c);w.addChildNode(A.withName(h?r.xmlName??n.getMemberName():f.xmlName??"member"))}else{let A=wt.of(h?r.xmlName??n.getMemberName():f.xmlName??"member");this.writeSimpleInto(e,l,A,c),w.addChildNode(A)}};if(h){for(let w of t)if(o||w!=null)_(i,w)}else{let w=wt.of(r.xmlName??n.getMemberName());if(c)w.addAttribute(u,c);for(let l of t)if(o||l!=null)_(w,l);i.addChildNode(w)}}writeMap(n,t,i,s,r=!1){if(!n.isMemberSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${n.getName(!0)}`);let e=n.getMergedTraits(),f=n.getKeySchema(),h=f.getMergedTraits().xmlName??"key",u=n.getValueSchema(),c=u.getMergedTraits(),_=c.xmlName??"value",w=!!c.sparse,l=!!e.xmlFlattened,[A,d]=this.getXmlnsAttribute(n,s),E=(R,y,T)=>{let S=wt.of(h,y),[I,F]=this.getXmlnsAttribute(f,d);if(F)S.addAttribute(I,F);R.addChildNode(S);let C=wt.of(_);if(u.isListSchema())this.writeList(u,T,C,d);else if(u.isMapSchema())this.writeMap(u,T,C,d,!0);else if(u.isStructSchema())C=this.writeStruct(u,T,d);else this.writeSimpleInto(u,T,C,d);R.addChildNode(C)};if(l)for(let R in t){let y=t[R];if(w||y!=null){let T=wt.of(e.xmlName??n.getMemberName());E(T,R,y),i.addChildNode(T)}}else{let R;if(!r){if(R=wt.of(e.xmlName??n.getMemberName()),d)R.addAttribute(A,d);i.addChildNode(R)}for(let y in t){let T=t[y];if(w||T!=null){let S=wt.of("entry");E(S,y,T),(r?i:R).addChildNode(S)}}}}writeSimple(n,t){if(t===null)throw Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value.");let i=En.of(n),s=null;if(t&&typeof t==="object")if(i.isBlobSchema())s=(this.serdeContext?.base64Encoder??Zo)(t);else if(i.isTimestampSchema()&&t instanceof Date)switch(nf(i,this.settings)){case 5:s=t.toISOString().replace(".000Z","Z");break;case 6:s=po(t);break;case 7:s=String(t.getTime()/1000);break;default:console.warn("Missing timestamp format, using http date",t),s=po(t);break}else if(i.isBigDecimalSchema()&&t){if(t instanceof Bt)return t.string;return String(t)}else if(i.isMapSchema()||i.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: ${i.getName(!0)}`);if(i.isBooleanSchema()||i.isNumericSchema()||i.isBigIntegerSchema()||i.isBigDecimalSchema())s=String(t);if(i.isStringSchema())if(t===void 0&&i.isIdempotencyToken())s=vc();else s=String(t);if(s===null)throw Error(`Unhandled schema-value pair ${i.getName(!0)}=${t}`);return s}writeSimpleInto(n,t,i,s){let r=this.writeSimple(n,t),e=En.of(n),f=new Z1(r),[o,h]=this.getXmlnsAttribute(e,s);if(h)i.addAttribute(o,h);i.addChildNode(f)}getXmlnsAttribute(n,t){let i=n.getMergedTraits(),[s,r]=i.xmlNamespace??[];if(r&&r!==t)return[s?`xmlns:${s}`:"xmlns",r];return[void 0,void 0]}}class e_ extends Ai{settings;constructor(n){super();this.settings=n}createSerializer(){let n=new r_(this.settings);return n.setSerdeContext(this.serdeContext),n}createDeserializer(){let n=new rf(this.settings);return n.setSerdeContext(this.serdeContext),n}}class IR extends rR{codec;serializer;deserializer;mixin=new Vs;constructor(n){super(n);let t={timestampFormat:{useTrait:!0,default:5},httpBindings:!0,xmlNamespace:n.xmlNamespace,serviceNamespace:n.defaultNamespace};this.codec=new e_(t),this.serializer=new eR(this.codec.createSerializer(),t),this.deserializer=new oR(this.codec.createDeserializer(),t)}getPayloadCodec(){return this.codec}getShapeId(){return"aws.protocols#restXml"}async serializeRequest(n,t,i){let s=await super.serializeRequest(n,t,i),r=En.of(n.input);if(!s.headers["content-type"]){let e=this.mixin.resolveRestContentType(this.getDefaultContentType(),r);if(e)s.headers["content-type"]=e}if(typeof s.body==="string"&&s.headers["content-type"]===this.getDefaultContentType()&&!s.body.startsWith("<?xml ")&&!this.hasUnstructuredPayloadBinding(r))s.body='<?xml version="1.0" encoding="UTF-8"?>'+s.body;return s}async deserializeResponse(n,t,i){return super.deserializeResponse(n,t,i)}async handleError(n,t,i,s,r){let e=SR(i,s)??"Unknown";if(this.mixin.compose(this.compositeErrorRegistry,e,this.options.defaultNamespace),s.Error&&typeof s.Error==="object"){for(let A of Object.keys(s.Error))if(s[A]=s.Error[A],A.toLowerCase()==="message")s.message=s.Error[A]}if(s.RequestId&&!r.requestId)r.requestId=s.RequestId;let{errorSchema:f,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(e,this.options.defaultNamespace,i,s,r),h=En.of(f),u=s.Error?.message??s.Error?.Message??s.message??s.Message??"UnknownError",_=new(this.compositeErrorRegistry.getErrorCtor(f)??Error)({});await this.deserializeHttpMessage(f,t,i,s);let w={},l=this.codec.createDeserializer();for(let[A,d]of h.structIterator()){let E=d.getMergedTraits().xmlName??A,R=s.Error?.[E]??s[E];w[A]=l.readSchema(d,R)}throw this.mixin.decorateServiceException(Object.assign(_,o,{$fault:h.getMergedTraits().error,message:u},w),s)}getDefaultContentType(){return"application/xml"}hasUnstructuredPayloadBinding(n){for(let[,t]of n.structIterator())if(t.getMergedTraits().httpPayload)return!(t.isStructSchema()||t.isMapSchema()||t.isListSchema());return!1}}jP.AwsEc2QueryProtocol=TR;jP.AwsJson1_0Protocol=RR;jP.AwsJson1_1Protocol=ER;jP.AwsJsonRpcProtocol=sf;jP.AwsQueryProtocol=s_;jP.AwsRestJsonProtocol=yR;jP.AwsRestXmlProtocol=IR;jP.AwsSmithyRpcV2CborProtocol=_R;jP.JsonCodec=tf;jP.JsonShapeDeserializer=n_;jP.JsonShapeSerializer=t_;jP.QueryShapeSerializer=i_;jP.XmlCodec=e_;jP.XmlShapeDeserializer=rf;jP.XmlShapeSerializer=r_;jP._toBool=CP;jP._toNum=xP;jP._toStr=QP;jP.awsExpectUnion=qP;jP.loadJsonRpcErrorCode=AR;jP.loadRestJsonErrorCode=lR;jP.loadRestXmlErrorCode=SR;jP.parseJsonBody=pc;jP.parseJsonErrorBody=kP;jP.parseXmlBody=gR;jP.parseXmlErrorBody=VP});var w_=k((D9)=>{var{awsEndpointFunctions:SD,emitWarningIfUnsupportedVersion:ID,createDefaultUserAgentProvider:UD,NODE_APP_ID_CONFIG_OPTIONS:bD,getAwsRegionExtensionConfiguration:$D,resolveAwsRegionExtensionConfiguration:LD,resolveUserAgentConfig:OD,resolveHostHeaderConfig:BD,getUserAgentPlugin:ND,getHostHeaderPlugin:GD,getLoggerPlugin:HD,getRecursionDetectionPlugin:WD}=ct(),{NoAuthSigner:FD,getHttpAuthSchemeEndpointRuleSetPlugin:PD,DefaultIdentityProviderConfig:DD,getHttpSigningPlugin:YD}=_i(),{normalizeProvider:OR,getSmithyContext:mD,ServiceException:JD,NoOpLogger:XD,emitWarningIfUnsupportedVersion:zD,loadConfigsForDefaultMode:QD,getDefaultExtensionConfiguration:CD,resolveDefaultRuntimeConfig:xD,Client:BR,makeBuilder:KD,createAggregatedClient:kD}=Xt(),{Command:qD}=Xt();D9.$Command=qD;D9.__Client=BR;var{resolveDefaultsModeConfig:VD,loadConfig:ki,NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS:jD,NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS:aD,NODE_REGION_CONFIG_OPTIONS:vD,NODE_REGION_CONFIG_FILE_OPTIONS:ZD,resolveRegionConfig:pD}=Yn(),{BinaryDecisionDiagram:n7,EndpointCache:t7,decideEndpoint:i7,customEndpointFunctions:s7,resolveEndpointConfig:r7,getEndpointPlugin:e7}=Ji(),{parseUrl:o7,getHttpHandlerExtensionConfiguration:f7,resolveHttpHandlerRuntimeConfig:h7,getContentLengthPlugin:u7}=Jn(),{DEFAULT_RETRY_MODE:c7,NODE_RETRY_MODE_CONFIG_OPTIONS:_7,NODE_MAX_ATTEMPT_CONFIG_OPTIONS:w7,resolveRetryConfig:l7,getRetryPlugin:A7}=Zr(),{TypeRegistry:NR,getSchemaSerdePlugin:M7}=ri(),{resolveAwsSdkSigV4Config:d7,AwsSdkSigV4Signer:R7,NODE_AUTH_SCHEME_PREFERENCE_OPTIONS:E7}=Oc(),{toUtf8:y7,fromUtf8:T7,toBase64:g7,fromBase64:S7,calculateBodyLength:I7}=mn(),{streamCollector:U7,NodeHttpHandler:b7}=jo(),{AwsRestJsonProtocol:$7}=o_(),{Sha256:L7}=Wu(),O7=async(n,t,i)=>{return{operation:mD(t).operation,region:await OR(n.region)()||(()=>{throw Error("expected `region` to be configured for `aws.auth#sigv4`")})()}};function B7(n){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sso-oauth",region:n.region},propertiesExtractor:(t,i)=>({signingProperties:{config:t,context:i}})}}function N7(n){return{schemeId:"smithy.api#noAuth"}}var G7=(n)=>{let t=[];switch(n.operation){case"CreateToken":{t.push(N7());break}default:t.push(B7(n))}return t},H7=(n)=>{let t=d7(n);return Object.assign(t,{authSchemePreference:OR(n.authSchemePreference??[])})},W7=(n)=>{return Object.assign(n,{useDualstackEndpoint:n.useDualstackEndpoint??!1,useFipsEndpoint:n.useFipsEndpoint??!1,defaultSigningName:"sso-oauth"})},F7={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},P7="3.997.32",D7={version:P7},_e="ref",qi=-1,ef=!0,UR="isSet",GR="PartitionResult",of="booleanEquals",f_="getAttr",bR={[_e]:"Endpoint"},h_={[_e]:GR},js={},$R=[{[_e]:"Region"}],LR={conditions:[[UR,[bR]],[UR,$R],["aws.partition",$R,GR],[of,[{[_e]:"UseFIPS"},ef]],[of,[{[_e]:"UseDualStack"},ef]],[of,[{fn:f_,argv:[h_,"supportsDualStack"]},ef]],[of,[{fn:f_,argv:[h_,"supportsFIPS"]},ef]],["stringEquals",[{fn:f_,argv:[h_,"name"]},"aws-us-gov"]]],results:[[qi],[qi,"Invalid Configuration: FIPS and custom endpoint are not supported"],[qi,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[bR,js],["https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",js],[qi,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://oidc.{Region}.amazonaws.com",js],["https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}",js],[qi,"FIPS is enabled but this partition does not support FIPS"],["https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}",js],[qi,"DualStack is enabled but this partition does not support DualStack"],["https://oidc.{Region}.{PartitionResult#dnsSuffix}",js],[qi,"Invalid Configuration: Missing Region"]]},Y7=2,Xn=1e8,m7=new Int32Array([-1,1,-1,0,13,3,1,4,Xn+12,2,5,Xn+12,3,8,6,4,7,Xn+11,5,Xn+9,Xn+10,4,11,9,6,10,Xn+8,7,Xn+6,Xn+7,5,12,Xn+5,6,Xn+4,Xn+5,3,Xn+1,14,4,Xn+2,Xn+3]),J7=n7.from(m7,Y7,LR.conditions,LR.results),X7=new t7({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),z7=(n,t={})=>{return X7.get(n,()=>i7(J7,{endpointParams:n,logger:t.logger}))};s7.aws=SD;class Fn extends JD{constructor(n){super(n);Object.setPrototypeOf(this,Fn.prototype)}}class ff extends Fn{name="AccessDeniedException";$fault="client";error;reason;error_description;constructor(n){super({name:"AccessDeniedException",$fault:"client",...n});Object.setPrototypeOf(this,ff.prototype),this.error=n.error,this.reason=n.reason,this.error_description=n.error_description}}class hf extends Fn{name="AuthorizationPendingException";$fault="client";error;error_description;constructor(n){super({name:"AuthorizationPendingException",$fault:"client",...n});Object.setPrototypeOf(this,hf.prototype),this.error=n.error,this.error_description=n.error_description}}class uf extends Fn{name="ExpiredTokenException";$fault="client";error;error_description;constructor(n){super({name:"ExpiredTokenException",$fault:"client",...n});Object.setPrototypeOf(this,uf.prototype),this.error=n.error,this.error_description=n.error_description}}class cf extends Fn{name="InternalServerException";$fault="server";error;error_description;constructor(n){super({name:"InternalServerException",$fault:"server",...n});Object.setPrototypeOf(this,cf.prototype),this.error=n.error,this.error_description=n.error_description}}class _f extends Fn{name="InvalidClientException";$fault="client";error;error_description;constructor(n){super({name:"InvalidClientException",$fault:"client",...n});Object.setPrototypeOf(this,_f.prototype),this.error=n.error,this.error_description=n.error_description}}class wf extends Fn{name="InvalidGrantException";$fault="client";error;error_description;constructor(n){super({name:"InvalidGrantException",$fault:"client",...n});Object.setPrototypeOf(this,wf.prototype),this.error=n.error,this.error_description=n.error_description}}class lf extends Fn{name="InvalidRequestException";$fault="client";error;reason;error_description;constructor(n){super({name:"InvalidRequestException",$fault:"client",...n});Object.setPrototypeOf(this,lf.prototype),this.error=n.error,this.reason=n.reason,this.error_description=n.error_description}}class Af extends Fn{name="InvalidScopeException";$fault="client";error;error_description;constructor(n){super({name:"InvalidScopeException",$fault:"client",...n});Object.setPrototypeOf(this,Af.prototype),this.error=n.error,this.error_description=n.error_description}}class Mf extends Fn{name="SlowDownException";$fault="client";error;error_description;constructor(n){super({name:"SlowDownException",$fault:"client",...n});Object.setPrototypeOf(this,Mf.prototype),this.error=n.error,this.error_description=n.error_description}}class df extends Fn{name="UnauthorizedClientException";$fault="client";error;error_description;constructor(n){super({name:"UnauthorizedClientException",$fault:"client",...n});Object.setPrototypeOf(this,df.prototype),this.error=n.error,this.error_description=n.error_description}}class Rf extends Fn{name="UnsupportedGrantTypeException";$fault="client";error;error_description;constructor(n){super({name:"UnsupportedGrantTypeException",$fault:"client",...n});Object.setPrototypeOf(this,Rf.prototype),this.error=n.error,this.error_description=n.error_description}}var Q7="AccessDeniedException",C7="AuthorizationPendingException",x7="AccessToken",K7="ClientSecret",k7="CreateToken",q7="CreateTokenRequest",V7="CreateTokenResponse",j7="CodeVerifier",a7="ExpiredTokenException",v7="InvalidClientException",Z7="InvalidGrantException",p7="InvalidRequestException",n9="InternalServerException",t9="InvalidScopeException",i9="IdToken",s9="RefreshToken",r9="SlowDownException",e9="UnauthorizedClientException",o9="UnsupportedGrantTypeException",f9="accessToken",Nt="client",h9="clientId",u9="clientSecret",c9="codeVerifier",_9="code",w9="deviceCode",dn="error",l9="expiresIn",lt="error_description",A9="grantType",M9="http",At="httpError",d9="idToken",HR="reason",WR="refreshToken",R9="redirectUri",FR="smithy.ts.sdk.synthetic.com.amazonaws.ssooidc",E9="scope",y9="server",T9="tokenType",yn="com.amazonaws.ssooidc",PR=NR.for(FR),DR=[-3,FR,"SSOOIDCServiceException",0,[],[]];PR.registerError(DR,Fn);var tt=NR.for(yn),YR=[-3,yn,Q7,{[dn]:Nt,[At]:400},[dn,HR,lt],[0,0,0]];tt.registerError(YR,ff);var mR=[-3,yn,C7,{[dn]:Nt,[At]:400},[dn,lt],[0,0]];tt.registerError(mR,hf);var JR=[-3,yn,a7,{[dn]:Nt,[At]:400},[dn,lt],[0,0]];tt.registerError(JR,uf);var XR=[-3,yn,n9,{[dn]:y9,[At]:500},[dn,lt],[0,0]];tt.registerError(XR,cf);var zR=[-3,yn,v7,{[dn]:Nt,[At]:401},[dn,lt],[0,0]];tt.registerError(zR,_f);var QR=[-3,yn,Z7,{[dn]:Nt,[At]:400},[dn,lt],[0,0]];tt.registerError(QR,wf);var CR=[-3,yn,p7,{[dn]:Nt,[At]:400},[dn,HR,lt],[0,0,0]];tt.registerError(CR,lf);var xR=[-3,yn,t9,{[dn]:Nt,[At]:400},[dn,lt],[0,0]];tt.registerError(xR,Af);var KR=[-3,yn,r9,{[dn]:Nt,[At]:400},[dn,lt],[0,0]];tt.registerError(KR,Mf);var kR=[-3,yn,e9,{[dn]:Nt,[At]:400},[dn,lt],[0,0]];tt.registerError(kR,df);var qR=[-3,yn,o9,{[dn]:Nt,[At]:400},[dn,lt],[0,0]];tt.registerError(qR,Rf);var VR=[PR,tt],g9=[0,yn,x7,8,0],S9=[0,yn,K7,8,0],I9=[0,yn,j7,8,0],U9=[0,yn,i9,8,0],jR=[0,yn,s9,8,0],aR=[3,yn,q7,0,[h9,u9,A9,w9,_9,WR,E9,R9,c9],[0,[()=>S9,0],0,0,0,[()=>jR,0],64,0,[()=>I9,0]],3],vR=[3,yn,V7,0,[f9,T9,l9,WR,d9],[[()=>g9,0],0,1,[()=>jR,0],[()=>U9,0]]],ZR=[9,yn,k7,{[M9]:["POST","/token",200]},()=>aR,()=>vR],b9=(n)=>{return{apiVersion:"2019-06-10",base64Decoder:n?.base64Decoder??S7,base64Encoder:n?.base64Encoder??g7,disableHostPrefix:n?.disableHostPrefix??!1,endpointProvider:n?.endpointProvider??z7,extensions:n?.extensions??[],httpAuthSchemeProvider:n?.httpAuthSchemeProvider??G7,httpAuthSchemes:n?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(t)=>t.getIdentityProvider("aws.auth#sigv4"),signer:new R7},{schemeId:"smithy.api#noAuth",identityProvider:(t)=>t.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new FD}],logger:n?.logger??new XD,protocol:n?.protocol??$7,protocolSettings:n?.protocolSettings??{defaultNamespace:"com.amazonaws.ssooidc",errorTypeRegistries:VR,version:"2019-06-10",serviceTarget:"AWSSSOOIDCService"},serviceId:n?.serviceId??"SSO OIDC",sha256:n?.sha256??L7,urlParser:n?.urlParser??o7,utf8Decoder:n?.utf8Decoder??T7,utf8Encoder:n?.utf8Encoder??y7}},$9=(n)=>{zD(process.version);let t=VD(n),i=()=>t().then(QD),s=b9(n);ID(process.version);let r={profile:n?.profile,logger:s.logger};return{...s,...n,runtime:"node",defaultsMode:t,authSchemePreference:n?.authSchemePreference??ki(E7,r),bodyLengthChecker:n?.bodyLengthChecker??I7,defaultUserAgentProvider:n?.defaultUserAgentProvider??UD({serviceId:s.serviceId,clientVersion:D7.version}),maxAttempts:n?.maxAttempts??ki(w7,n),region:n?.region??ki(vD,{...ZD,...r}),requestHandler:b7.create(n?.requestHandler??i),retryMode:n?.retryMode??ki({..._7,default:async()=>(await i()).retryMode||c7},n),streamCollector:n?.streamCollector??U7,useDualstackEndpoint:n?.useDualstackEndpoint??ki(aD,r),useFipsEndpoint:n?.useFipsEndpoint??ki(jD,r),userAgentAppId:n?.userAgentAppId??ki(bD,r)}},L9=(n)=>{let{httpAuthSchemes:t,httpAuthSchemeProvider:i,credentials:s}=n;return{setHttpAuthScheme(r){let e=t.findIndex((f)=>f.schemeId===r.schemeId);if(e===-1)t.push(r);else t.splice(e,1,r)},httpAuthSchemes(){return t},setHttpAuthSchemeProvider(r){i=r},httpAuthSchemeProvider(){return i},setCredentials(r){s=r},credentials(){return s}}},O9=(n)=>{return{httpAuthSchemes:n.httpAuthSchemes(),httpAuthSchemeProvider:n.httpAuthSchemeProvider(),credentials:n.credentials()}},B9=(n,t)=>{let i=Object.assign($D(n),CD(n),f7(n),L9(n));return t.forEach((s)=>s.configure(i)),Object.assign(n,LD(i),xD(i),h7(i),O9(i))};class u_ extends BR{config;constructor(...[n]){let t=$9(n||{});super(t);this.initConfig=t;let i=W7(t),s=OD(i),r=l7(s),e=pD(r),f=BD(e),o=r7(f),h=H7(o),u=B9(h,n?.extensions||[]);this.config=u,this.middlewareStack.use(M7(this.config)),this.middlewareStack.use(ND(this.config)),this.middlewareStack.use(A7(this.config)),this.middlewareStack.use(u7(this.config)),this.middlewareStack.use(GD(this.config)),this.middlewareStack.use(HD(this.config)),this.middlewareStack.use(WD(this.config)),this.middlewareStack.use(PD(this.config,{httpAuthSchemeParametersProvider:O7,identityProviderConfigProvider:async(c)=>new DD({"aws.auth#sigv4":c.credentials})})),this.middlewareStack.use(YD(this.config))}destroy(){super.destroy()}}var N9=KD(F7,"AWSSSOOIDCService","SSOOIDCClient",e7),G9={},H9=(n,t,i,s)=>[];class c_ extends N9(G9,H9,"CreateToken",ZR){}var W9={CreateTokenCommand:c_};class __ extends u_{}kD(W9,__);var F9={KMS_ACCESS_DENIED:"KMS_AccessDeniedException"},P9={KMS_DISABLED_KEY:"KMS_DisabledException",KMS_INVALID_KEY_USAGE:"KMS_InvalidKeyUsageException",KMS_INVALID_STATE:"KMS_InvalidStateException",KMS_KEY_NOT_FOUND:"KMS_NotFoundException"};D9.AccessDeniedException=ff;D9.AccessDeniedException$=YR;D9.AccessDeniedExceptionReason=F9;D9.AuthorizationPendingException=hf;D9.AuthorizationPendingException$=mR;D9.CreateToken$=ZR;D9.CreateTokenCommand=c_;D9.CreateTokenRequest$=aR;D9.CreateTokenResponse$=vR;D9.ExpiredTokenException=uf;D9.ExpiredTokenException$=JR;D9.InternalServerException=cf;D9.InternalServerException$=XR;D9.InvalidClientException=_f;D9.InvalidClientException$=zR;D9.InvalidGrantException=wf;D9.InvalidGrantException$=QR;D9.InvalidRequestException=lf;D9.InvalidRequestException$=CR;D9.InvalidRequestExceptionReason=P9;D9.InvalidScopeException=Af;D9.InvalidScopeException$=xR;D9.SSOOIDC=__;D9.SSOOIDCClient=u_;D9.SSOOIDCServiceException=Fn;D9.SSOOIDCServiceException$=DR;D9.SlowDownException=Mf;D9.SlowDownException$=KR;D9.UnauthorizedClientException=df;D9.UnauthorizedClientException$=kR;D9.UnsupportedGrantTypeException=Rf;D9.UnsupportedGrantTypeException$=qR;D9.errorTypeRegistries=VR});import{Database as JT}from"bun:sqlite";import{existsSync as XT}from"fs";import{homedir as o0}from"os";import{dirname as zT,join as ge}from"path";var f0=5000,QT=30000,CT=25,xT=500,KT=new Set(["id","email","auth_method","region","oidc_region","client_id","client_secret","profile_arn","start_url","refresh_token","access_token","expires_at","rate_limit_reset","is_healthy","unhealthy_reason","recovery_time","fail_count","last_used","used_count","limit_count","last_sync","overage_count"]);class or extends Error{constructor(n,t){super(n,t);this.name="OpenCodeAuthStoreError"}}function kT(n){if(typeof n!=="object"||n===null||!("code"in n))return!1;return String(n.code).toUpperCase().startsWith("SQLITE_BUSY")}function qT(n,t){let i=Math.min(CT*2**Math.min(n,5),xT,t),s=Math.max(1,Math.floor(i/2)),r=s+Math.floor(Math.random()*(i-s+1));Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,r)}function gi(n){return{id:n.id,email:n.email,authMethod:n.auth_method,region:n.region,oidcRegion:n.oidc_region??void 0,clientId:n.client_id??void 0,clientSecret:n.client_secret??void 0,profileArn:n.profile_arn??void 0,startUrl:n.start_url??void 0,refreshToken:n.refresh_token,accessToken:n.access_token,expiresAt:n.expires_at,rateLimitResetTime:n.rate_limit_reset??0,isHealthy:(n.is_healthy??1)===1,unhealthyReason:n.unhealthy_reason??void 0,recoveryTime:n.recovery_time??void 0,failCount:n.fail_count??0,lastUsed:n.last_used??0,usedCount:n.used_count??0,limitCount:n.limit_count??0,lastSync:n.last_sync??0,overageCount:n.overage_count??0}}function VT(n,t){return t.refreshToken===n.refreshToken&&t.accessToken===n.accessToken&&t.expiresAt===n.expiresAt&&t.authMethod===n.authMethod&&t.clientId===n.clientId&&t.clientSecret===n.clientSecret&&t.profileArn===n.profileArn&&t.email===n.email&&t.startUrl===n.startUrl}function fr(n=process.env){let t=process.platform==="win32"?n.APPDATA??ge(o0(),"AppData","Roaming"):n.XDG_CONFIG_HOME??ge(o0(),".config");return ge(t,"opencode","kiro.db")}function h0(n){return ge(zT(n),"kiro-auth-plugin")}class pf{path;db;constructor(n=fr()){this.path=n;if(!XT(n))throw new or(`OpenCode Kiro auth database not found: ${n}. Run OpenCode Kiro authentication first or set auth_source to "local".`);this.db=new JT(n,{strict:!0}),this.db.run(`PRAGMA busy_timeout = ${f0}`),this.validateSchema()}getAccounts(){return this.db.query(`
|
|
51
|
+
SELECT accounts.*
|
|
52
|
+
FROM accounts
|
|
53
|
+
WHERE NOT EXISTS (
|
|
54
|
+
SELECT 1 FROM removed_accounts
|
|
55
|
+
WHERE removed_accounts.id = accounts.id
|
|
56
|
+
)
|
|
57
|
+
`).all().map(gi)}getById(n){let t=this.selectById(n);return t===void 0?void 0:gi(t)}recordSelection(n,t){return this.withImmediateTransaction(()=>{if(this.db.query(`
|
|
58
|
+
UPDATE accounts
|
|
59
|
+
SET last_used = ?,
|
|
60
|
+
used_count = COALESCE(used_count, 0) + 1
|
|
61
|
+
WHERE id = ?
|
|
62
|
+
AND NOT EXISTS (
|
|
63
|
+
SELECT 1 FROM removed_accounts
|
|
64
|
+
WHERE removed_accounts.id = accounts.id
|
|
65
|
+
)
|
|
66
|
+
`).run(t,n).changes!==1)return;let s=this.selectById(n);return s===void 0?void 0:gi(s)})}markRateLimited(n,t){return this.withImmediateTransaction(()=>{this.db.query(`
|
|
67
|
+
UPDATE accounts
|
|
68
|
+
SET rate_limit_reset = MAX(COALESCE(rate_limit_reset, 0), ?)
|
|
69
|
+
WHERE id = ?
|
|
70
|
+
`).run(t,n);let i=this.selectById(n);return i===void 0?void 0:gi(i)})}markUnhealthy(n,t,i,s,r){return this.withImmediateTransaction(()=>{if(i)this.db.query(`
|
|
71
|
+
UPDATE accounts
|
|
72
|
+
SET fail_count = 10,
|
|
73
|
+
is_healthy = 0,
|
|
74
|
+
unhealthy_reason = ?,
|
|
75
|
+
recovery_time = NULL,
|
|
76
|
+
last_used = ?
|
|
77
|
+
WHERE id = ?
|
|
78
|
+
`).run(t,r,n);else this.db.query(`
|
|
79
|
+
UPDATE accounts
|
|
80
|
+
SET fail_count = COALESCE(fail_count, 0) + 1,
|
|
81
|
+
is_healthy =
|
|
82
|
+
CASE WHEN COALESCE(fail_count, 0) + 1 >= 10 THEN 0 ELSE 1 END,
|
|
83
|
+
unhealthy_reason = ?,
|
|
84
|
+
recovery_time =
|
|
85
|
+
CASE
|
|
86
|
+
WHEN COALESCE(fail_count, 0) + 1 >= 10 THEN ?
|
|
87
|
+
ELSE NULL
|
|
88
|
+
END,
|
|
89
|
+
last_used = ?
|
|
90
|
+
WHERE id = ?
|
|
91
|
+
`).run(t,s??r+3600000,r,n);let e=this.selectById(n);return e===void 0?void 0:gi(e)})}persistRefreshedAccount(n,t){return this.withImmediateTransaction(()=>{let i=this.selectById(n.id);if(i===void 0)return;let s=gi(i);if(!VT(n,s))return s;this.db.query(`
|
|
92
|
+
UPDATE accounts
|
|
93
|
+
SET email = ?,
|
|
94
|
+
oidc_region = ?,
|
|
95
|
+
client_id = ?,
|
|
96
|
+
client_secret = ?,
|
|
97
|
+
profile_arn = ?,
|
|
98
|
+
start_url = ?,
|
|
99
|
+
refresh_token = ?,
|
|
100
|
+
access_token = ?,
|
|
101
|
+
expires_at = ?,
|
|
102
|
+
is_healthy = 1,
|
|
103
|
+
unhealthy_reason = NULL,
|
|
104
|
+
recovery_time = NULL,
|
|
105
|
+
fail_count = 0,
|
|
106
|
+
last_used = ?
|
|
107
|
+
WHERE id = ?
|
|
108
|
+
`).run(t.email,t.oidcRegion??null,t.clientId??null,t.clientSecret??null,t.profileArn??null,t.startUrl??null,t.refreshToken,t.accessToken,t.expiresAt,t.lastUsed??Date.now(),t.id);let r=this.selectById(t.id);return r===void 0?void 0:gi(r)})}close(){this.db.close()}selectById(n){let t=this.db.query(`
|
|
109
|
+
SELECT accounts.*
|
|
110
|
+
FROM accounts
|
|
111
|
+
WHERE accounts.id = ?
|
|
112
|
+
AND NOT EXISTS (
|
|
113
|
+
SELECT 1 FROM removed_accounts
|
|
114
|
+
WHERE removed_accounts.id = accounts.id
|
|
115
|
+
)
|
|
116
|
+
`).get(n);return t===null?void 0:t}validateSchema(){let n=new Set(this.db.query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map(({name:s})=>s));for(let s of["accounts","removed_accounts"])if(!n.has(s))throw new or(`OpenCode Kiro auth database ${this.path} is missing table ${s}; update opencode-kiro-auth and authenticate again.`);let t=new Set(this.db.query("PRAGMA table_info(accounts)").all().map(({name:s})=>s)),i=[...KT].filter((s)=>!t.has(s));if(i.length>0)throw new or(`OpenCode Kiro auth database ${this.path} is missing required account columns: ${i.join(", ")}`)}withImmediateTransaction(n){let t=Date.now()+QT,i=0;for(;;){let s=!1,r;try{this.db.run("PRAGMA busy_timeout = 0"),this.db.exec("BEGIN IMMEDIATE"),s=!0}catch(e){r=e}finally{this.db.run(`PRAGMA busy_timeout = ${f0}`)}if(!s){if(!kT(r))throw r;let e=t-Date.now();if(e<=0)throw new or(`Timed out waiting for the OpenCode Kiro auth database write lock: ${this.path}`,{cause:r});qT(i,e),i+=1;continue}try{let e=n();return this.db.exec("COMMIT"),e}catch(e){throw this.db.exec("ROLLBACK"),e}}}}import{existsSync as h2,readFileSync as u2}from"fs";import{homedir as c2}from"os";import{join as T0}from"path";var M={};mT(M,{void:()=>H4,util:()=>j,unknown:()=>N4,union:()=>D4,undefined:()=>L4,tuple:()=>J4,transformer:()=>j4,symbol:()=>$4,string:()=>R0,strictObject:()=>P4,setErrorMap:()=>vT,set:()=>Q4,record:()=>X4,quotelessJson:()=>jT,promise:()=>V4,preprocess:()=>Z4,pipeline:()=>p4,ostring:()=>n2,optional:()=>a4,onumber:()=>t2,oboolean:()=>i2,objectUtil:()=>nh,object:()=>F4,number:()=>E0,nullable:()=>v4,null:()=>O4,never:()=>G4,nativeEnum:()=>q4,nan:()=>I4,map:()=>z4,makeIssue:()=>hr,literal:()=>K4,lazy:()=>x4,late:()=>g4,isValid:()=>qt,isDirty:()=>Ie,isAsync:()=>is,isAborted:()=>Se,intersection:()=>m4,instanceof:()=>S4,getParsedType:()=>Rt,getErrorMap:()=>ts,function:()=>C4,enum:()=>k4,effect:()=>j4,discriminatedUnion:()=>Y4,defaultErrorMap:()=>Ft,datetimeRegex:()=>A0,date:()=>b4,custom:()=>d0,coerce:()=>s2,boolean:()=>y0,bigint:()=>U4,array:()=>W4,any:()=>B4,addIssueToContext:()=>O,ZodVoid:()=>cr,ZodUnknown:()=>Vt,ZodUnion:()=>hs,ZodUndefined:()=>os,ZodType:()=>q,ZodTuple:()=>yt,ZodTransformer:()=>ht,ZodSymbol:()=>ur,ZodString:()=>rt,ZodSet:()=>bi,ZodSchema:()=>q,ZodRecord:()=>_r,ZodReadonly:()=>Ms,ZodPromise:()=>$i,ZodPipeline:()=>Ar,ZodParsedType:()=>L,ZodOptional:()=>ot,ZodObject:()=>wn,ZodNumber:()=>jt,ZodNullable:()=>Dt,ZodNull:()=>fs,ZodNever:()=>Et,ZodNativeEnum:()=>ws,ZodNaN:()=>lr,ZodMap:()=>wr,ZodLiteral:()=>_s,ZodLazy:()=>cs,ZodIssueCode:()=>U,ZodIntersection:()=>us,ZodFunction:()=>rs,ZodFirstPartyTypeKind:()=>z,ZodError:()=>Pn,ZodEnum:()=>vt,ZodEffects:()=>ht,ZodDiscriminatedUnion:()=>Ue,ZodDefault:()=>ls,ZodDate:()=>Ii,ZodCatch:()=>As,ZodBranded:()=>be,ZodBoolean:()=>es,ZodBigInt:()=>at,ZodArray:()=>et,ZodAny:()=>Ui,Schema:()=>q,ParseStatus:()=>bn,OK:()=>Nn,NEVER:()=>r2,INVALID:()=>J,EMPTY_PATH:()=>ZT,DIRTY:()=>Si,BRAND:()=>T4});var j;(function(n){n.assertEqual=(r)=>{};function t(r){}n.assertIs=t;function i(r){throw Error()}n.assertNever=i,n.arrayToEnum=(r)=>{let e={};for(let f of r)e[f]=f;return e},n.getValidEnumValues=(r)=>{let e=n.objectKeys(r).filter((o)=>typeof r[r[o]]!=="number"),f={};for(let o of e)f[o]=r[o];return n.objectValues(f)},n.objectValues=(r)=>{return n.objectKeys(r).map(function(e){return r[e]})},n.objectKeys=typeof Object.keys==="function"?(r)=>Object.keys(r):(r)=>{let e=[];for(let f in r)if(Object.prototype.hasOwnProperty.call(r,f))e.push(f);return e},n.find=(r,e)=>{for(let f of r)if(e(f))return f;return},n.isInteger=typeof Number.isInteger==="function"?(r)=>Number.isInteger(r):(r)=>typeof r==="number"&&Number.isFinite(r)&&Math.floor(r)===r;function s(r,e=" | "){return r.map((f)=>typeof f==="string"?`'${f}'`:f).join(e)}n.joinValues=s,n.jsonStringifyReplacer=(r,e)=>{if(typeof e==="bigint")return e.toString();return e}})(j||(j={}));var nh;(function(n){n.mergeShapes=(t,i)=>{return{...t,...i}}})(nh||(nh={}));var L=j.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Rt=(n)=>{switch(typeof n){case"undefined":return L.undefined;case"string":return L.string;case"number":return Number.isNaN(n)?L.nan:L.number;case"boolean":return L.boolean;case"function":return L.function;case"bigint":return L.bigint;case"symbol":return L.symbol;case"object":if(Array.isArray(n))return L.array;if(n===null)return L.null;if(n.then&&typeof n.then==="function"&&n.catch&&typeof n.catch==="function")return L.promise;if(typeof Map<"u"&&n instanceof Map)return L.map;if(typeof Set<"u"&&n instanceof Set)return L.set;if(typeof Date<"u"&&n instanceof Date)return L.date;return L.object;default:return L.unknown}};var U=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"]),jT=(n)=>{return JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:")};class Pn extends Error{get errors(){return this.issues}constructor(n){super();this.issues=[],this.addIssue=(i)=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};let t=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,t);else this.__proto__=t;this.name="ZodError",this.issues=n}format(n){let t=n||function(r){return r.message},i={_errors:[]},s=(r)=>{for(let e of r.issues)if(e.code==="invalid_union")e.unionErrors.map(s);else if(e.code==="invalid_return_type")s(e.returnTypeError);else if(e.code==="invalid_arguments")s(e.argumentsError);else if(e.path.length===0)i._errors.push(t(e));else{let f=i,o=0;while(o<e.path.length){let h=e.path[o];if(o!==e.path.length-1)f[h]=f[h]||{_errors:[]};else f[h]=f[h]||{_errors:[]},f[h]._errors.push(t(e));f=f[h],o++}}};return s(this),i}static assert(n){if(!(n instanceof Pn))throw Error(`Not a ZodError: ${n}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,j.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(n=(t)=>t.message){let t={},i=[];for(let s of this.issues)if(s.path.length>0){let r=s.path[0];t[r]=t[r]||[],t[r].push(n(s))}else i.push(n(s));return{formErrors:i,fieldErrors:t}}get formErrors(){return this.flatten()}}Pn.create=(n)=>{return new Pn(n)};var aT=(n,t)=>{let i;switch(n.code){case U.invalid_type:if(n.received===L.undefined)i="Required";else i=`Expected ${n.expected}, received ${n.received}`;break;case U.invalid_literal:i=`Invalid literal value, expected ${JSON.stringify(n.expected,j.jsonStringifyReplacer)}`;break;case U.unrecognized_keys:i=`Unrecognized key(s) in object: ${j.joinValues(n.keys,", ")}`;break;case U.invalid_union:i="Invalid input";break;case U.invalid_union_discriminator:i=`Invalid discriminator value. Expected ${j.joinValues(n.options)}`;break;case U.invalid_enum_value:i=`Invalid enum value. Expected ${j.joinValues(n.options)}, received '${n.received}'`;break;case U.invalid_arguments:i="Invalid function arguments";break;case U.invalid_return_type:i="Invalid function return type";break;case U.invalid_date:i="Invalid date";break;case U.invalid_string:if(typeof n.validation==="object")if("includes"in n.validation){if(i=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position==="number")i=`${i} at one or more positions greater than or equal to ${n.validation.position}`}else if("startsWith"in n.validation)i=`Invalid input: must start with "${n.validation.startsWith}"`;else if("endsWith"in n.validation)i=`Invalid input: must end with "${n.validation.endsWith}"`;else j.assertNever(n.validation);else if(n.validation!=="regex")i=`Invalid ${n.validation}`;else i="Invalid";break;case U.too_small:if(n.type==="array")i=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`;else if(n.type==="string")i=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`;else if(n.type==="number")i=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`;else if(n.type==="bigint")i=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`;else if(n.type==="date")i=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`;else i="Invalid input";break;case U.too_big:if(n.type==="array")i=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`;else if(n.type==="string")i=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`;else if(n.type==="number")i=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`;else if(n.type==="bigint")i=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`;else if(n.type==="date")i=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`;else i="Invalid input";break;case U.custom:i="Invalid input";break;case U.invalid_intersection_types:i="Intersection results could not be merged";break;case U.not_multiple_of:i=`Number must be a multiple of ${n.multipleOf}`;break;case U.not_finite:i="Number must be finite";break;default:i=t.defaultError,j.assertNever(n)}return{message:i}},Ft=aT;var u0=Ft;function vT(n){u0=n}function ts(){return u0}var hr=(n)=>{let{data:t,path:i,errorMaps:s,issueData:r}=n,e=[...i,...r.path||[]],f={...r,path:e};if(r.message!==void 0)return{...r,path:e,message:r.message};let o="",h=s.filter((u)=>!!u).slice().reverse();for(let u of h)o=u(f,{data:t,defaultError:o}).message;return{...r,path:e,message:o}},ZT=[];function O(n,t){let i=ts(),s=hr({issueData:t,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,i,i===Ft?void 0:Ft].filter((r)=>!!r)});n.common.issues.push(s)}class bn{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(n,t){let i=[];for(let s of t){if(s.status==="aborted")return J;if(s.status==="dirty")n.dirty();i.push(s.value)}return{status:n.value,value:i}}static async mergeObjectAsync(n,t){let i=[];for(let s of t){let r=await s.key,e=await s.value;i.push({key:r,value:e})}return bn.mergeObjectSync(n,i)}static mergeObjectSync(n,t){let i={};for(let s of t){let{key:r,value:e}=s;if(r.status==="aborted")return J;if(e.status==="aborted")return J;if(r.status==="dirty")n.dirty();if(e.status==="dirty")n.dirty();if(r.value!=="__proto__"&&(typeof e.value<"u"||s.alwaysSet))i[r.value]=e.value}return{status:n.value,value:i}}}var J=Object.freeze({status:"aborted"}),Si=(n)=>({status:"dirty",value:n}),Nn=(n)=>({status:"valid",value:n}),Se=(n)=>n.status==="aborted",Ie=(n)=>n.status==="dirty",qt=(n)=>n.status==="valid",is=(n)=>typeof Promise<"u"&&n instanceof Promise;var P;(function(n){n.errToObj=(t)=>typeof t==="string"?{message:t}:t||{},n.toString=(t)=>typeof t==="string"?t:t?.message})(P||(P={}));class ft{constructor(n,t,i,s){this._cachedPath=[],this.parent=n,this.data=t,this._path=i,this._key=s}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 c0=(n,t)=>{if(qt(t))return{success:!0,data:t.value};else{if(!n.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let i=new Pn(n.common.issues);return this._error=i,this._error}}}};function K(n){if(!n)return{};let{errorMap:t,invalid_type_error:i,required_error:s,description:r}=n;if(t&&(i||s))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(t)return{errorMap:t,description:r};return{errorMap:(f,o)=>{let{message:h}=n;if(f.code==="invalid_enum_value")return{message:h??o.defaultError};if(typeof o.data>"u")return{message:h??s??o.defaultError};if(f.code!=="invalid_type")return{message:o.defaultError};return{message:h??i??o.defaultError}},description:r}}class q{get description(){return this._def.description}_getType(n){return Rt(n.data)}_getOrReturnCtx(n,t){return t||{common:n.parent.common,data:n.data,parsedType:Rt(n.data),schemaErrorMap:this._def.errorMap,path:n.path,parent:n.parent}}_processInputParams(n){return{status:new bn,ctx:{common:n.parent.common,data:n.data,parsedType:Rt(n.data),schemaErrorMap:this._def.errorMap,path:n.path,parent:n.parent}}}_parseSync(n){let t=this._parse(n);if(is(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(n){let t=this._parse(n);return Promise.resolve(t)}parse(n,t){let i=this.safeParse(n,t);if(i.success)return i.data;throw i.error}safeParse(n,t){let i={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:n,parsedType:Rt(n)},s=this._parseSync({data:n,path:i.path,parent:i});return c0(i,s)}"~validate"(n){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:n,parsedType:Rt(n)};if(!this["~standard"].async)try{let i=this._parseSync({data:n,path:[],parent:t});return qt(i)?{value:i.value}:{issues:t.common.issues}}catch(i){if(i?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;t.common={issues:[],async:!0}}return this._parseAsync({data:n,path:[],parent:t}).then((i)=>qt(i)?{value:i.value}:{issues:t.common.issues})}async parseAsync(n,t){let i=await this.safeParseAsync(n,t);if(i.success)return i.data;throw i.error}async safeParseAsync(n,t){let i={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:n,parsedType:Rt(n)},s=this._parse({data:n,path:i.path,parent:i}),r=await(is(s)?s:Promise.resolve(s));return c0(i,r)}refine(n,t){let i=(s)=>{if(typeof t==="string"||typeof t>"u")return{message:t};else if(typeof t==="function")return t(s);else return t};return this._refinement((s,r)=>{let e=n(s),f=()=>r.addIssue({code:U.custom,...i(s)});if(typeof Promise<"u"&&e instanceof Promise)return e.then((o)=>{if(!o)return f(),!1;else return!0});if(!e)return f(),!1;else return!0})}refinement(n,t){return this._refinement((i,s)=>{if(!n(i))return s.addIssue(typeof t==="function"?t(i,s):t),!1;else return!0})}_refinement(n){return new ht({schema:this,typeName:z.ZodEffects,effect:{type:"refinement",refinement:n}})}superRefine(n){return this._refinement(n)}constructor(n){this.spa=this.safeParseAsync,this._def=n,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(t)=>this["~validate"](t)}}optional(){return ot.create(this,this._def)}nullable(){return Dt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return et.create(this)}promise(){return $i.create(this,this._def)}or(n){return hs.create([this,n],this._def)}and(n){return us.create(this,n,this._def)}transform(n){return new ht({...K(this._def),schema:this,typeName:z.ZodEffects,effect:{type:"transform",transform:n}})}default(n){let t=typeof n==="function"?n:()=>n;return new ls({...K(this._def),innerType:this,defaultValue:t,typeName:z.ZodDefault})}brand(){return new be({typeName:z.ZodBranded,type:this,...K(this._def)})}catch(n){let t=typeof n==="function"?n:()=>n;return new As({...K(this._def),innerType:this,catchValue:t,typeName:z.ZodCatch})}describe(n){return new this.constructor({...this._def,description:n})}pipe(n){return Ar.create(this,n)}readonly(){return Ms.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var pT=/^c[^\s-]{8,}$/i,n4=/^[0-9a-z]+$/,t4=/^[0-9A-HJKMNP-TV-Z]{26}$/i,i4=/^[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,s4=/^[a-z0-9_-]{21}$/i,r4=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,e4=/^[-+]?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)?)??$/,o4=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,f4="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",th,h4=/^(?:(?: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])$/,u4=/^(?:(?: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])$/,c4=/^(([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]))$/,_4=/^(([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])$/,w4=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,l4=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,w0="((\\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])))",A4=new RegExp(`^${w0}$`);function l0(n){let t="[0-5]\\d";if(n.precision)t=`${t}\\.\\d{${n.precision}}`;else if(n.precision==null)t=`${t}(\\.\\d+)?`;let i=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${i}`}function M4(n){return new RegExp(`^${l0(n)}$`)}function A0(n){let t=`${w0}T${l0(n)}`,i=[];if(i.push(n.local?"Z?":"Z"),n.offset)i.push("([+-]\\d{2}:?\\d{2})");return t=`${t}(${i.join("|")})`,new RegExp(`^${t}$`)}function d4(n,t){if((t==="v4"||!t)&&h4.test(n))return!0;if((t==="v6"||!t)&&c4.test(n))return!0;return!1}function R4(n,t){if(!r4.test(n))return!1;try{let[i]=n.split(".");if(!i)return!1;let s=i.replace(/-/g,"+").replace(/_/g,"/").padEnd(i.length+(4-i.length%4)%4,"="),r=JSON.parse(atob(s));if(typeof r!=="object"||r===null)return!1;if("typ"in r&&r?.typ!=="JWT")return!1;if(!r.alg)return!1;if(t&&r.alg!==t)return!1;return!0}catch{return!1}}function E4(n,t){if((t==="v4"||!t)&&u4.test(n))return!0;if((t==="v6"||!t)&&_4.test(n))return!0;return!1}class rt extends q{_parse(n){if(this._def.coerce)n.data=String(n.data);if(this._getType(n)!==L.string){let r=this._getOrReturnCtx(n);return O(r,{code:U.invalid_type,expected:L.string,received:r.parsedType}),J}let i=new bn,s=void 0;for(let r of this._def.checks)if(r.kind==="min"){if(n.data.length<r.value)s=this._getOrReturnCtx(n,s),O(s,{code:U.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),i.dirty()}else if(r.kind==="max"){if(n.data.length>r.value)s=this._getOrReturnCtx(n,s),O(s,{code:U.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),i.dirty()}else if(r.kind==="length"){let e=n.data.length>r.value,f=n.data.length<r.value;if(e||f){if(s=this._getOrReturnCtx(n,s),e)O(s,{code:U.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message});else if(f)O(s,{code:U.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message});i.dirty()}}else if(r.kind==="email"){if(!o4.test(n.data))s=this._getOrReturnCtx(n,s),O(s,{validation:"email",code:U.invalid_string,message:r.message}),i.dirty()}else if(r.kind==="emoji"){if(!th)th=new RegExp(f4,"u");if(!th.test(n.data))s=this._getOrReturnCtx(n,s),O(s,{validation:"emoji",code:U.invalid_string,message:r.message}),i.dirty()}else if(r.kind==="uuid"){if(!i4.test(n.data))s=this._getOrReturnCtx(n,s),O(s,{validation:"uuid",code:U.invalid_string,message:r.message}),i.dirty()}else if(r.kind==="nanoid"){if(!s4.test(n.data))s=this._getOrReturnCtx(n,s),O(s,{validation:"nanoid",code:U.invalid_string,message:r.message}),i.dirty()}else if(r.kind==="cuid"){if(!pT.test(n.data))s=this._getOrReturnCtx(n,s),O(s,{validation:"cuid",code:U.invalid_string,message:r.message}),i.dirty()}else if(r.kind==="cuid2"){if(!n4.test(n.data))s=this._getOrReturnCtx(n,s),O(s,{validation:"cuid2",code:U.invalid_string,message:r.message}),i.dirty()}else if(r.kind==="ulid"){if(!t4.test(n.data))s=this._getOrReturnCtx(n,s),O(s,{validation:"ulid",code:U.invalid_string,message:r.message}),i.dirty()}else if(r.kind==="url")try{new URL(n.data)}catch{s=this._getOrReturnCtx(n,s),O(s,{validation:"url",code:U.invalid_string,message:r.message}),i.dirty()}else if(r.kind==="regex"){if(r.regex.lastIndex=0,!r.regex.test(n.data))s=this._getOrReturnCtx(n,s),O(s,{validation:"regex",code:U.invalid_string,message:r.message}),i.dirty()}else if(r.kind==="trim")n.data=n.data.trim();else if(r.kind==="includes"){if(!n.data.includes(r.value,r.position))s=this._getOrReturnCtx(n,s),O(s,{code:U.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),i.dirty()}else if(r.kind==="toLowerCase")n.data=n.data.toLowerCase();else if(r.kind==="toUpperCase")n.data=n.data.toUpperCase();else if(r.kind==="startsWith"){if(!n.data.startsWith(r.value))s=this._getOrReturnCtx(n,s),O(s,{code:U.invalid_string,validation:{startsWith:r.value},message:r.message}),i.dirty()}else if(r.kind==="endsWith"){if(!n.data.endsWith(r.value))s=this._getOrReturnCtx(n,s),O(s,{code:U.invalid_string,validation:{endsWith:r.value},message:r.message}),i.dirty()}else if(r.kind==="datetime"){if(!A0(r).test(n.data))s=this._getOrReturnCtx(n,s),O(s,{code:U.invalid_string,validation:"datetime",message:r.message}),i.dirty()}else if(r.kind==="date"){if(!A4.test(n.data))s=this._getOrReturnCtx(n,s),O(s,{code:U.invalid_string,validation:"date",message:r.message}),i.dirty()}else if(r.kind==="time"){if(!M4(r).test(n.data))s=this._getOrReturnCtx(n,s),O(s,{code:U.invalid_string,validation:"time",message:r.message}),i.dirty()}else if(r.kind==="duration"){if(!e4.test(n.data))s=this._getOrReturnCtx(n,s),O(s,{validation:"duration",code:U.invalid_string,message:r.message}),i.dirty()}else if(r.kind==="ip"){if(!d4(n.data,r.version))s=this._getOrReturnCtx(n,s),O(s,{validation:"ip",code:U.invalid_string,message:r.message}),i.dirty()}else if(r.kind==="jwt"){if(!R4(n.data,r.alg))s=this._getOrReturnCtx(n,s),O(s,{validation:"jwt",code:U.invalid_string,message:r.message}),i.dirty()}else if(r.kind==="cidr"){if(!E4(n.data,r.version))s=this._getOrReturnCtx(n,s),O(s,{validation:"cidr",code:U.invalid_string,message:r.message}),i.dirty()}else if(r.kind==="base64"){if(!w4.test(n.data))s=this._getOrReturnCtx(n,s),O(s,{validation:"base64",code:U.invalid_string,message:r.message}),i.dirty()}else if(r.kind==="base64url"){if(!l4.test(n.data))s=this._getOrReturnCtx(n,s),O(s,{validation:"base64url",code:U.invalid_string,message:r.message}),i.dirty()}else j.assertNever(r);return{status:i.value,value:n.data}}_regex(n,t,i){return this.refinement((s)=>n.test(s),{validation:t,code:U.invalid_string,...P.errToObj(i)})}_addCheck(n){return new rt({...this._def,checks:[...this._def.checks,n]})}email(n){return this._addCheck({kind:"email",...P.errToObj(n)})}url(n){return this._addCheck({kind:"url",...P.errToObj(n)})}emoji(n){return this._addCheck({kind:"emoji",...P.errToObj(n)})}uuid(n){return this._addCheck({kind:"uuid",...P.errToObj(n)})}nanoid(n){return this._addCheck({kind:"nanoid",...P.errToObj(n)})}cuid(n){return this._addCheck({kind:"cuid",...P.errToObj(n)})}cuid2(n){return this._addCheck({kind:"cuid2",...P.errToObj(n)})}ulid(n){return this._addCheck({kind:"ulid",...P.errToObj(n)})}base64(n){return this._addCheck({kind:"base64",...P.errToObj(n)})}base64url(n){return this._addCheck({kind:"base64url",...P.errToObj(n)})}jwt(n){return this._addCheck({kind:"jwt",...P.errToObj(n)})}ip(n){return this._addCheck({kind:"ip",...P.errToObj(n)})}cidr(n){return this._addCheck({kind:"cidr",...P.errToObj(n)})}datetime(n){if(typeof n==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:n});return this._addCheck({kind:"datetime",precision:typeof n?.precision>"u"?null:n?.precision,offset:n?.offset??!1,local:n?.local??!1,...P.errToObj(n?.message)})}date(n){return this._addCheck({kind:"date",message:n})}time(n){if(typeof n==="string")return this._addCheck({kind:"time",precision:null,message:n});return this._addCheck({kind:"time",precision:typeof n?.precision>"u"?null:n?.precision,...P.errToObj(n?.message)})}duration(n){return this._addCheck({kind:"duration",...P.errToObj(n)})}regex(n,t){return this._addCheck({kind:"regex",regex:n,...P.errToObj(t)})}includes(n,t){return this._addCheck({kind:"includes",value:n,position:t?.position,...P.errToObj(t?.message)})}startsWith(n,t){return this._addCheck({kind:"startsWith",value:n,...P.errToObj(t)})}endsWith(n,t){return this._addCheck({kind:"endsWith",value:n,...P.errToObj(t)})}min(n,t){return this._addCheck({kind:"min",value:n,...P.errToObj(t)})}max(n,t){return this._addCheck({kind:"max",value:n,...P.errToObj(t)})}length(n,t){return this._addCheck({kind:"length",value:n,...P.errToObj(t)})}nonempty(n){return this.min(1,P.errToObj(n))}trim(){return new rt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new rt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new rt({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((n)=>n.kind==="datetime")}get isDate(){return!!this._def.checks.find((n)=>n.kind==="date")}get isTime(){return!!this._def.checks.find((n)=>n.kind==="time")}get isDuration(){return!!this._def.checks.find((n)=>n.kind==="duration")}get isEmail(){return!!this._def.checks.find((n)=>n.kind==="email")}get isURL(){return!!this._def.checks.find((n)=>n.kind==="url")}get isEmoji(){return!!this._def.checks.find((n)=>n.kind==="emoji")}get isUUID(){return!!this._def.checks.find((n)=>n.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((n)=>n.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((n)=>n.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((n)=>n.kind==="cuid2")}get isULID(){return!!this._def.checks.find((n)=>n.kind==="ulid")}get isIP(){return!!this._def.checks.find((n)=>n.kind==="ip")}get isCIDR(){return!!this._def.checks.find((n)=>n.kind==="cidr")}get isBase64(){return!!this._def.checks.find((n)=>n.kind==="base64")}get isBase64url(){return!!this._def.checks.find((n)=>n.kind==="base64url")}get minLength(){let n=null;for(let t of this._def.checks)if(t.kind==="min"){if(n===null||t.value>n)n=t.value}return n}get maxLength(){let n=null;for(let t of this._def.checks)if(t.kind==="max"){if(n===null||t.value<n)n=t.value}return n}}rt.create=(n)=>{return new rt({checks:[],typeName:z.ZodString,coerce:n?.coerce??!1,...K(n)})};function y4(n,t){let i=(n.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,r=i>s?i:s,e=Number.parseInt(n.toFixed(r).replace(".","")),f=Number.parseInt(t.toFixed(r).replace(".",""));return e%f/10**r}class jt extends q{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(n){if(this._def.coerce)n.data=Number(n.data);if(this._getType(n)!==L.number){let r=this._getOrReturnCtx(n);return O(r,{code:U.invalid_type,expected:L.number,received:r.parsedType}),J}let i=void 0,s=new bn;for(let r of this._def.checks)if(r.kind==="int"){if(!j.isInteger(n.data))i=this._getOrReturnCtx(n,i),O(i,{code:U.invalid_type,expected:"integer",received:"float",message:r.message}),s.dirty()}else if(r.kind==="min"){if(r.inclusive?n.data<r.value:n.data<=r.value)i=this._getOrReturnCtx(n,i),O(i,{code:U.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),s.dirty()}else if(r.kind==="max"){if(r.inclusive?n.data>r.value:n.data>=r.value)i=this._getOrReturnCtx(n,i),O(i,{code:U.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),s.dirty()}else if(r.kind==="multipleOf"){if(y4(n.data,r.value)!==0)i=this._getOrReturnCtx(n,i),O(i,{code:U.not_multiple_of,multipleOf:r.value,message:r.message}),s.dirty()}else if(r.kind==="finite"){if(!Number.isFinite(n.data))i=this._getOrReturnCtx(n,i),O(i,{code:U.not_finite,message:r.message}),s.dirty()}else j.assertNever(r);return{status:s.value,value:n.data}}gte(n,t){return this.setLimit("min",n,!0,P.toString(t))}gt(n,t){return this.setLimit("min",n,!1,P.toString(t))}lte(n,t){return this.setLimit("max",n,!0,P.toString(t))}lt(n,t){return this.setLimit("max",n,!1,P.toString(t))}setLimit(n,t,i,s){return new jt({...this._def,checks:[...this._def.checks,{kind:n,value:t,inclusive:i,message:P.toString(s)}]})}_addCheck(n){return new jt({...this._def,checks:[...this._def.checks,n]})}int(n){return this._addCheck({kind:"int",message:P.toString(n)})}positive(n){return this._addCheck({kind:"min",value:0,inclusive:!1,message:P.toString(n)})}negative(n){return this._addCheck({kind:"max",value:0,inclusive:!1,message:P.toString(n)})}nonpositive(n){return this._addCheck({kind:"max",value:0,inclusive:!0,message:P.toString(n)})}nonnegative(n){return this._addCheck({kind:"min",value:0,inclusive:!0,message:P.toString(n)})}multipleOf(n,t){return this._addCheck({kind:"multipleOf",value:n,message:P.toString(t)})}finite(n){return this._addCheck({kind:"finite",message:P.toString(n)})}safe(n){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:P.toString(n)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:P.toString(n)})}get minValue(){let n=null;for(let t of this._def.checks)if(t.kind==="min"){if(n===null||t.value>n)n=t.value}return n}get maxValue(){let n=null;for(let t of this._def.checks)if(t.kind==="max"){if(n===null||t.value<n)n=t.value}return n}get isInt(){return!!this._def.checks.find((n)=>n.kind==="int"||n.kind==="multipleOf"&&j.isInteger(n.value))}get isFinite(){let n=null,t=null;for(let i of this._def.checks)if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;else if(i.kind==="min"){if(t===null||i.value>t)t=i.value}else if(i.kind==="max"){if(n===null||i.value<n)n=i.value}return Number.isFinite(t)&&Number.isFinite(n)}}jt.create=(n)=>{return new jt({checks:[],typeName:z.ZodNumber,coerce:n?.coerce||!1,...K(n)})};class at extends q{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(n){if(this._def.coerce)try{n.data=BigInt(n.data)}catch{return this._getInvalidInput(n)}if(this._getType(n)!==L.bigint)return this._getInvalidInput(n);let i=void 0,s=new bn;for(let r of this._def.checks)if(r.kind==="min"){if(r.inclusive?n.data<r.value:n.data<=r.value)i=this._getOrReturnCtx(n,i),O(i,{code:U.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),s.dirty()}else if(r.kind==="max"){if(r.inclusive?n.data>r.value:n.data>=r.value)i=this._getOrReturnCtx(n,i),O(i,{code:U.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),s.dirty()}else if(r.kind==="multipleOf"){if(n.data%r.value!==BigInt(0))i=this._getOrReturnCtx(n,i),O(i,{code:U.not_multiple_of,multipleOf:r.value,message:r.message}),s.dirty()}else j.assertNever(r);return{status:s.value,value:n.data}}_getInvalidInput(n){let t=this._getOrReturnCtx(n);return O(t,{code:U.invalid_type,expected:L.bigint,received:t.parsedType}),J}gte(n,t){return this.setLimit("min",n,!0,P.toString(t))}gt(n,t){return this.setLimit("min",n,!1,P.toString(t))}lte(n,t){return this.setLimit("max",n,!0,P.toString(t))}lt(n,t){return this.setLimit("max",n,!1,P.toString(t))}setLimit(n,t,i,s){return new at({...this._def,checks:[...this._def.checks,{kind:n,value:t,inclusive:i,message:P.toString(s)}]})}_addCheck(n){return new at({...this._def,checks:[...this._def.checks,n]})}positive(n){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:P.toString(n)})}negative(n){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:P.toString(n)})}nonpositive(n){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:P.toString(n)})}nonnegative(n){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:P.toString(n)})}multipleOf(n,t){return this._addCheck({kind:"multipleOf",value:n,message:P.toString(t)})}get minValue(){let n=null;for(let t of this._def.checks)if(t.kind==="min"){if(n===null||t.value>n)n=t.value}return n}get maxValue(){let n=null;for(let t of this._def.checks)if(t.kind==="max"){if(n===null||t.value<n)n=t.value}return n}}at.create=(n)=>{return new at({checks:[],typeName:z.ZodBigInt,coerce:n?.coerce??!1,...K(n)})};class es extends q{_parse(n){if(this._def.coerce)n.data=Boolean(n.data);if(this._getType(n)!==L.boolean){let i=this._getOrReturnCtx(n);return O(i,{code:U.invalid_type,expected:L.boolean,received:i.parsedType}),J}return Nn(n.data)}}es.create=(n)=>{return new es({typeName:z.ZodBoolean,coerce:n?.coerce||!1,...K(n)})};class Ii extends q{_parse(n){if(this._def.coerce)n.data=new Date(n.data);if(this._getType(n)!==L.date){let r=this._getOrReturnCtx(n);return O(r,{code:U.invalid_type,expected:L.date,received:r.parsedType}),J}if(Number.isNaN(n.data.getTime())){let r=this._getOrReturnCtx(n);return O(r,{code:U.invalid_date}),J}let i=new bn,s=void 0;for(let r of this._def.checks)if(r.kind==="min"){if(n.data.getTime()<r.value)s=this._getOrReturnCtx(n,s),O(s,{code:U.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),i.dirty()}else if(r.kind==="max"){if(n.data.getTime()>r.value)s=this._getOrReturnCtx(n,s),O(s,{code:U.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),i.dirty()}else j.assertNever(r);return{status:i.value,value:new Date(n.data.getTime())}}_addCheck(n){return new Ii({...this._def,checks:[...this._def.checks,n]})}min(n,t){return this._addCheck({kind:"min",value:n.getTime(),message:P.toString(t)})}max(n,t){return this._addCheck({kind:"max",value:n.getTime(),message:P.toString(t)})}get minDate(){let n=null;for(let t of this._def.checks)if(t.kind==="min"){if(n===null||t.value>n)n=t.value}return n!=null?new Date(n):null}get maxDate(){let n=null;for(let t of this._def.checks)if(t.kind==="max"){if(n===null||t.value<n)n=t.value}return n!=null?new Date(n):null}}Ii.create=(n)=>{return new Ii({checks:[],coerce:n?.coerce||!1,typeName:z.ZodDate,...K(n)})};class ur extends q{_parse(n){if(this._getType(n)!==L.symbol){let i=this._getOrReturnCtx(n);return O(i,{code:U.invalid_type,expected:L.symbol,received:i.parsedType}),J}return Nn(n.data)}}ur.create=(n)=>{return new ur({typeName:z.ZodSymbol,...K(n)})};class os extends q{_parse(n){if(this._getType(n)!==L.undefined){let i=this._getOrReturnCtx(n);return O(i,{code:U.invalid_type,expected:L.undefined,received:i.parsedType}),J}return Nn(n.data)}}os.create=(n)=>{return new os({typeName:z.ZodUndefined,...K(n)})};class fs extends q{_parse(n){if(this._getType(n)!==L.null){let i=this._getOrReturnCtx(n);return O(i,{code:U.invalid_type,expected:L.null,received:i.parsedType}),J}return Nn(n.data)}}fs.create=(n)=>{return new fs({typeName:z.ZodNull,...K(n)})};class Ui extends q{constructor(){super(...arguments);this._any=!0}_parse(n){return Nn(n.data)}}Ui.create=(n)=>{return new Ui({typeName:z.ZodAny,...K(n)})};class Vt extends q{constructor(){super(...arguments);this._unknown=!0}_parse(n){return Nn(n.data)}}Vt.create=(n)=>{return new Vt({typeName:z.ZodUnknown,...K(n)})};class Et extends q{_parse(n){let t=this._getOrReturnCtx(n);return O(t,{code:U.invalid_type,expected:L.never,received:t.parsedType}),J}}Et.create=(n)=>{return new Et({typeName:z.ZodNever,...K(n)})};class cr extends q{_parse(n){if(this._getType(n)!==L.undefined){let i=this._getOrReturnCtx(n);return O(i,{code:U.invalid_type,expected:L.void,received:i.parsedType}),J}return Nn(n.data)}}cr.create=(n)=>{return new cr({typeName:z.ZodVoid,...K(n)})};class et extends q{_parse(n){let{ctx:t,status:i}=this._processInputParams(n),s=this._def;if(t.parsedType!==L.array)return O(t,{code:U.invalid_type,expected:L.array,received:t.parsedType}),J;if(s.exactLength!==null){let e=t.data.length>s.exactLength.value,f=t.data.length<s.exactLength.value;if(e||f)O(t,{code:e?U.too_big:U.too_small,minimum:f?s.exactLength.value:void 0,maximum:e?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),i.dirty()}if(s.minLength!==null){if(t.data.length<s.minLength.value)O(t,{code:U.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),i.dirty()}if(s.maxLength!==null){if(t.data.length>s.maxLength.value)O(t,{code:U.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),i.dirty()}if(t.common.async)return Promise.all([...t.data].map((e,f)=>{return s.type._parseAsync(new ft(t,e,t.path,f))})).then((e)=>{return bn.mergeArray(i,e)});let r=[...t.data].map((e,f)=>{return s.type._parseSync(new ft(t,e,t.path,f))});return bn.mergeArray(i,r)}get element(){return this._def.type}min(n,t){return new et({...this._def,minLength:{value:n,message:P.toString(t)}})}max(n,t){return new et({...this._def,maxLength:{value:n,message:P.toString(t)}})}length(n,t){return new et({...this._def,exactLength:{value:n,message:P.toString(t)}})}nonempty(n){return this.min(1,n)}}et.create=(n,t)=>{return new et({type:n,minLength:null,maxLength:null,exactLength:null,typeName:z.ZodArray,...K(t)})};function ss(n){if(n instanceof wn){let t={};for(let i in n.shape){let s=n.shape[i];t[i]=ot.create(ss(s))}return new wn({...n._def,shape:()=>t})}else if(n instanceof et)return new et({...n._def,type:ss(n.element)});else if(n instanceof ot)return ot.create(ss(n.unwrap()));else if(n instanceof Dt)return Dt.create(ss(n.unwrap()));else if(n instanceof yt)return yt.create(n.items.map((t)=>ss(t)));else return n}class wn extends q{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let n=this._def.shape(),t=j.objectKeys(n);return this._cached={shape:n,keys:t},this._cached}_parse(n){if(this._getType(n)!==L.object){let h=this._getOrReturnCtx(n);return O(h,{code:U.invalid_type,expected:L.object,received:h.parsedType}),J}let{status:i,ctx:s}=this._processInputParams(n),{shape:r,keys:e}=this._getCached(),f=[];if(!(this._def.catchall instanceof Et&&this._def.unknownKeys==="strip")){for(let h in s.data)if(!e.includes(h))f.push(h)}let o=[];for(let h of e){let u=r[h],c=s.data[h];o.push({key:{status:"valid",value:h},value:u._parse(new ft(s,c,s.path,h)),alwaysSet:h in s.data})}if(this._def.catchall instanceof Et){let h=this._def.unknownKeys;if(h==="passthrough")for(let u of f)o.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(h==="strict"){if(f.length>0)O(s,{code:U.unrecognized_keys,keys:f}),i.dirty()}else if(h==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let h=this._def.catchall;for(let u of f){let c=s.data[u];o.push({key:{status:"valid",value:u},value:h._parse(new ft(s,c,s.path,u)),alwaysSet:u in s.data})}}if(s.common.async)return Promise.resolve().then(async()=>{let h=[];for(let u of o){let c=await u.key,_=await u.value;h.push({key:c,value:_,alwaysSet:u.alwaysSet})}return h}).then((h)=>{return bn.mergeObjectSync(i,h)});else return bn.mergeObjectSync(i,o)}get shape(){return this._def.shape()}strict(n){return P.errToObj,new wn({...this._def,unknownKeys:"strict",...n!==void 0?{errorMap:(t,i)=>{let s=this._def.errorMap?.(t,i).message??i.defaultError;if(t.code==="unrecognized_keys")return{message:P.errToObj(n).message??s};return{message:s}}}:{}})}strip(){return new wn({...this._def,unknownKeys:"strip"})}passthrough(){return new wn({...this._def,unknownKeys:"passthrough"})}extend(n){return new wn({...this._def,shape:()=>({...this._def.shape(),...n})})}merge(n){return new wn({unknownKeys:n._def.unknownKeys,catchall:n._def.catchall,shape:()=>({...this._def.shape(),...n._def.shape()}),typeName:z.ZodObject})}setKey(n,t){return this.augment({[n]:t})}catchall(n){return new wn({...this._def,catchall:n})}pick(n){let t={};for(let i of j.objectKeys(n))if(n[i]&&this.shape[i])t[i]=this.shape[i];return new wn({...this._def,shape:()=>t})}omit(n){let t={};for(let i of j.objectKeys(this.shape))if(!n[i])t[i]=this.shape[i];return new wn({...this._def,shape:()=>t})}deepPartial(){return ss(this)}partial(n){let t={};for(let i of j.objectKeys(this.shape)){let s=this.shape[i];if(n&&!n[i])t[i]=s;else t[i]=s.optional()}return new wn({...this._def,shape:()=>t})}required(n){let t={};for(let i of j.objectKeys(this.shape))if(n&&!n[i])t[i]=this.shape[i];else{let r=this.shape[i];while(r instanceof ot)r=r._def.innerType;t[i]=r}return new wn({...this._def,shape:()=>t})}keyof(){return M0(j.objectKeys(this.shape))}}wn.create=(n,t)=>{return new wn({shape:()=>n,unknownKeys:"strip",catchall:Et.create(),typeName:z.ZodObject,...K(t)})};wn.strictCreate=(n,t)=>{return new wn({shape:()=>n,unknownKeys:"strict",catchall:Et.create(),typeName:z.ZodObject,...K(t)})};wn.lazycreate=(n,t)=>{return new wn({shape:n,unknownKeys:"strip",catchall:Et.create(),typeName:z.ZodObject,...K(t)})};class hs extends q{_parse(n){let{ctx:t}=this._processInputParams(n),i=this._def.options;function s(r){for(let f of r)if(f.result.status==="valid")return f.result;for(let f of r)if(f.result.status==="dirty")return t.common.issues.push(...f.ctx.common.issues),f.result;let e=r.map((f)=>new Pn(f.ctx.common.issues));return O(t,{code:U.invalid_union,unionErrors:e}),J}if(t.common.async)return Promise.all(i.map(async(r)=>{let e={...t,common:{...t.common,issues:[]},parent:null};return{result:await r._parseAsync({data:t.data,path:t.path,parent:e}),ctx:e}})).then(s);else{let r=void 0,e=[];for(let o of i){let h={...t,common:{...t.common,issues:[]},parent:null},u=o._parseSync({data:t.data,path:t.path,parent:h});if(u.status==="valid")return u;else if(u.status==="dirty"&&!r)r={result:u,ctx:h};if(h.common.issues.length)e.push(h.common.issues)}if(r)return t.common.issues.push(...r.ctx.common.issues),r.result;let f=e.map((o)=>new Pn(o));return O(t,{code:U.invalid_union,unionErrors:f}),J}}get options(){return this._def.options}}hs.create=(n,t)=>{return new hs({options:n,typeName:z.ZodUnion,...K(t)})};var Pt=(n)=>{if(n instanceof cs)return Pt(n.schema);else if(n instanceof ht)return Pt(n.innerType());else if(n instanceof _s)return[n.value];else if(n instanceof vt)return n.options;else if(n instanceof ws)return j.objectValues(n.enum);else if(n instanceof ls)return Pt(n._def.innerType);else if(n instanceof os)return[void 0];else if(n instanceof fs)return[null];else if(n instanceof ot)return[void 0,...Pt(n.unwrap())];else if(n instanceof Dt)return[null,...Pt(n.unwrap())];else if(n instanceof be)return Pt(n.unwrap());else if(n instanceof Ms)return Pt(n.unwrap());else if(n instanceof As)return Pt(n._def.innerType);else return[]};class Ue extends q{_parse(n){let{ctx:t}=this._processInputParams(n);if(t.parsedType!==L.object)return O(t,{code:U.invalid_type,expected:L.object,received:t.parsedType}),J;let i=this.discriminator,s=t.data[i],r=this.optionsMap.get(s);if(!r)return O(t,{code:U.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),J;if(t.common.async)return r._parseAsync({data:t.data,path:t.path,parent:t});else return r._parseSync({data:t.data,path:t.path,parent:t})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(n,t,i){let s=new Map;for(let r of t){let e=Pt(r.shape[n]);if(!e.length)throw Error(`A discriminator value for key \`${n}\` could not be extracted from all schema options`);for(let f of e){if(s.has(f))throw Error(`Discriminator property ${String(n)} has duplicate value ${String(f)}`);s.set(f,r)}}return new Ue({typeName:z.ZodDiscriminatedUnion,discriminator:n,options:t,optionsMap:s,...K(i)})}}function ih(n,t){let i=Rt(n),s=Rt(t);if(n===t)return{valid:!0,data:n};else if(i===L.object&&s===L.object){let r=j.objectKeys(t),e=j.objectKeys(n).filter((o)=>r.indexOf(o)!==-1),f={...n,...t};for(let o of e){let h=ih(n[o],t[o]);if(!h.valid)return{valid:!1};f[o]=h.data}return{valid:!0,data:f}}else if(i===L.array&&s===L.array){if(n.length!==t.length)return{valid:!1};let r=[];for(let e=0;e<n.length;e++){let f=n[e],o=t[e],h=ih(f,o);if(!h.valid)return{valid:!1};r.push(h.data)}return{valid:!0,data:r}}else if(i===L.date&&s===L.date&&+n===+t)return{valid:!0,data:n};else return{valid:!1}}class us extends q{_parse(n){let{status:t,ctx:i}=this._processInputParams(n),s=(r,e)=>{if(Se(r)||Se(e))return J;let f=ih(r.value,e.value);if(!f.valid)return O(i,{code:U.invalid_intersection_types}),J;if(Ie(r)||Ie(e))t.dirty();return{status:t.value,value:f.data}};if(i.common.async)return Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([r,e])=>s(r,e));else return s(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}us.create=(n,t,i)=>{return new us({left:n,right:t,typeName:z.ZodIntersection,...K(i)})};class yt extends q{_parse(n){let{status:t,ctx:i}=this._processInputParams(n);if(i.parsedType!==L.array)return O(i,{code:U.invalid_type,expected:L.array,received:i.parsedType}),J;if(i.data.length<this._def.items.length)return O(i,{code:U.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J;if(!this._def.rest&&i.data.length>this._def.items.length)O(i,{code:U.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty();let r=[...i.data].map((e,f)=>{let o=this._def.items[f]||this._def.rest;if(!o)return null;return o._parse(new ft(i,e,i.path,f))}).filter((e)=>!!e);if(i.common.async)return Promise.all(r).then((e)=>{return bn.mergeArray(t,e)});else return bn.mergeArray(t,r)}get items(){return this._def.items}rest(n){return new yt({...this._def,rest:n})}}yt.create=(n,t)=>{if(!Array.isArray(n))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new yt({items:n,typeName:z.ZodTuple,rest:null,...K(t)})};class _r extends q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(n){let{status:t,ctx:i}=this._processInputParams(n);if(i.parsedType!==L.object)return O(i,{code:U.invalid_type,expected:L.object,received:i.parsedType}),J;let s=[],r=this._def.keyType,e=this._def.valueType;for(let f in i.data)s.push({key:r._parse(new ft(i,f,i.path,f)),value:e._parse(new ft(i,i.data[f],i.path,f)),alwaysSet:f in i.data});if(i.common.async)return bn.mergeObjectAsync(t,s);else return bn.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(n,t,i){if(t instanceof q)return new _r({keyType:n,valueType:t,typeName:z.ZodRecord,...K(i)});return new _r({keyType:rt.create(),valueType:n,typeName:z.ZodRecord,...K(t)})}}class wr extends q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(n){let{status:t,ctx:i}=this._processInputParams(n);if(i.parsedType!==L.map)return O(i,{code:U.invalid_type,expected:L.map,received:i.parsedType}),J;let s=this._def.keyType,r=this._def.valueType,e=[...i.data.entries()].map(([f,o],h)=>{return{key:s._parse(new ft(i,f,i.path,[h,"key"])),value:r._parse(new ft(i,o,i.path,[h,"value"]))}});if(i.common.async){let f=new Map;return Promise.resolve().then(async()=>{for(let o of e){let h=await o.key,u=await o.value;if(h.status==="aborted"||u.status==="aborted")return J;if(h.status==="dirty"||u.status==="dirty")t.dirty();f.set(h.value,u.value)}return{status:t.value,value:f}})}else{let f=new Map;for(let o of e){let{key:h,value:u}=o;if(h.status==="aborted"||u.status==="aborted")return J;if(h.status==="dirty"||u.status==="dirty")t.dirty();f.set(h.value,u.value)}return{status:t.value,value:f}}}}wr.create=(n,t,i)=>{return new wr({valueType:t,keyType:n,typeName:z.ZodMap,...K(i)})};class bi extends q{_parse(n){let{status:t,ctx:i}=this._processInputParams(n);if(i.parsedType!==L.set)return O(i,{code:U.invalid_type,expected:L.set,received:i.parsedType}),J;let s=this._def;if(s.minSize!==null){if(i.data.size<s.minSize.value)O(i,{code:U.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()}if(s.maxSize!==null){if(i.data.size>s.maxSize.value)O(i,{code:U.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty()}let r=this._def.valueType;function e(o){let h=new Set;for(let u of o){if(u.status==="aborted")return J;if(u.status==="dirty")t.dirty();h.add(u.value)}return{status:t.value,value:h}}let f=[...i.data.values()].map((o,h)=>r._parse(new ft(i,o,i.path,h)));if(i.common.async)return Promise.all(f).then((o)=>e(o));else return e(f)}min(n,t){return new bi({...this._def,minSize:{value:n,message:P.toString(t)}})}max(n,t){return new bi({...this._def,maxSize:{value:n,message:P.toString(t)}})}size(n,t){return this.min(n,t).max(n,t)}nonempty(n){return this.min(1,n)}}bi.create=(n,t)=>{return new bi({valueType:n,minSize:null,maxSize:null,typeName:z.ZodSet,...K(t)})};class rs extends q{constructor(){super(...arguments);this.validate=this.implement}_parse(n){let{ctx:t}=this._processInputParams(n);if(t.parsedType!==L.function)return O(t,{code:U.invalid_type,expected:L.function,received:t.parsedType}),J;function i(f,o){return hr({data:f,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ts(),Ft].filter((h)=>!!h),issueData:{code:U.invalid_arguments,argumentsError:o}})}function s(f,o){return hr({data:f,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ts(),Ft].filter((h)=>!!h),issueData:{code:U.invalid_return_type,returnTypeError:o}})}let r={errorMap:t.common.contextualErrorMap},e=t.data;if(this._def.returns instanceof $i){let f=this;return Nn(async function(...o){let h=new Pn([]),u=await f._def.args.parseAsync(o,r).catch((w)=>{throw h.addIssue(i(o,w)),h}),c=await Reflect.apply(e,this,u);return await f._def.returns._def.type.parseAsync(c,r).catch((w)=>{throw h.addIssue(s(c,w)),h})})}else{let f=this;return Nn(function(...o){let h=f._def.args.safeParse(o,r);if(!h.success)throw new Pn([i(o,h.error)]);let u=Reflect.apply(e,this,h.data),c=f._def.returns.safeParse(u,r);if(!c.success)throw new Pn([s(u,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...n){return new rs({...this._def,args:yt.create(n).rest(Vt.create())})}returns(n){return new rs({...this._def,returns:n})}implement(n){return this.parse(n)}strictImplement(n){return this.parse(n)}static create(n,t,i){return new rs({args:n?n:yt.create([]).rest(Vt.create()),returns:t||Vt.create(),typeName:z.ZodFunction,...K(i)})}}class cs extends q{get schema(){return this._def.getter()}_parse(n){let{ctx:t}=this._processInputParams(n);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}cs.create=(n,t)=>{return new cs({getter:n,typeName:z.ZodLazy,...K(t)})};class _s extends q{_parse(n){if(n.data!==this._def.value){let t=this._getOrReturnCtx(n);return O(t,{received:t.data,code:U.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:n.data}}get value(){return this._def.value}}_s.create=(n,t)=>{return new _s({value:n,typeName:z.ZodLiteral,...K(t)})};function M0(n,t){return new vt({values:n,typeName:z.ZodEnum,...K(t)})}class vt extends q{_parse(n){if(typeof n.data!=="string"){let t=this._getOrReturnCtx(n),i=this._def.values;return O(t,{expected:j.joinValues(i),received:t.parsedType,code:U.invalid_type}),J}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(n.data)){let t=this._getOrReturnCtx(n),i=this._def.values;return O(t,{received:t.data,code:U.invalid_enum_value,options:i}),J}return Nn(n.data)}get options(){return this._def.values}get enum(){let n={};for(let t of this._def.values)n[t]=t;return n}get Values(){let n={};for(let t of this._def.values)n[t]=t;return n}get Enum(){let n={};for(let t of this._def.values)n[t]=t;return n}extract(n,t=this._def){return vt.create(n,{...this._def,...t})}exclude(n,t=this._def){return vt.create(this.options.filter((i)=>!n.includes(i)),{...this._def,...t})}}vt.create=M0;class ws extends q{_parse(n){let t=j.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(n);if(i.parsedType!==L.string&&i.parsedType!==L.number){let s=j.objectValues(t);return O(i,{expected:j.joinValues(s),received:i.parsedType,code:U.invalid_type}),J}if(!this._cache)this._cache=new Set(j.getValidEnumValues(this._def.values));if(!this._cache.has(n.data)){let s=j.objectValues(t);return O(i,{received:i.data,code:U.invalid_enum_value,options:s}),J}return Nn(n.data)}get enum(){return this._def.values}}ws.create=(n,t)=>{return new ws({values:n,typeName:z.ZodNativeEnum,...K(t)})};class $i extends q{unwrap(){return this._def.type}_parse(n){let{ctx:t}=this._processInputParams(n);if(t.parsedType!==L.promise&&t.common.async===!1)return O(t,{code:U.invalid_type,expected:L.promise,received:t.parsedType}),J;let i=t.parsedType===L.promise?t.data:Promise.resolve(t.data);return Nn(i.then((s)=>{return this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})}))}}$i.create=(n,t)=>{return new $i({type:n,typeName:z.ZodPromise,...K(t)})};class ht extends q{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===z.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(n){let{status:t,ctx:i}=this._processInputParams(n),s=this._def.effect||null,r={addIssue:(e)=>{if(O(i,e),e.fatal)t.abort();else t.dirty()},get path(){return i.path}};if(r.addIssue=r.addIssue.bind(r),s.type==="preprocess"){let e=s.transform(i.data,r);if(i.common.async)return Promise.resolve(e).then(async(f)=>{if(t.value==="aborted")return J;let o=await this._def.schema._parseAsync({data:f,path:i.path,parent:i});if(o.status==="aborted")return J;if(o.status==="dirty")return Si(o.value);if(t.value==="dirty")return Si(o.value);return o});else{if(t.value==="aborted")return J;let f=this._def.schema._parseSync({data:e,path:i.path,parent:i});if(f.status==="aborted")return J;if(f.status==="dirty")return Si(f.value);if(t.value==="dirty")return Si(f.value);return f}}if(s.type==="refinement"){let e=(f)=>{let o=s.refinement(f,r);if(i.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(i.common.async===!1){let f=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(f.status==="aborted")return J;if(f.status==="dirty")t.dirty();return e(f.value),{status:t.value,value:f.value}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then((f)=>{if(f.status==="aborted")return J;if(f.status==="dirty")t.dirty();return e(f.value).then(()=>{return{status:t.value,value:f.value}})})}if(s.type==="transform")if(i.common.async===!1){let e=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!qt(e))return J;let f=s.transform(e.value,r);if(f instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:f}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then((e)=>{if(!qt(e))return J;return Promise.resolve(s.transform(e.value,r)).then((f)=>({status:t.value,value:f}))});j.assertNever(s)}}ht.create=(n,t,i)=>{return new ht({schema:n,typeName:z.ZodEffects,effect:t,...K(i)})};ht.createWithPreprocess=(n,t,i)=>{return new ht({schema:t,effect:{type:"preprocess",transform:n},typeName:z.ZodEffects,...K(i)})};class ot extends q{_parse(n){if(this._getType(n)===L.undefined)return Nn(void 0);return this._def.innerType._parse(n)}unwrap(){return this._def.innerType}}ot.create=(n,t)=>{return new ot({innerType:n,typeName:z.ZodOptional,...K(t)})};class Dt extends q{_parse(n){if(this._getType(n)===L.null)return Nn(null);return this._def.innerType._parse(n)}unwrap(){return this._def.innerType}}Dt.create=(n,t)=>{return new Dt({innerType:n,typeName:z.ZodNullable,...K(t)})};class ls extends q{_parse(n){let{ctx:t}=this._processInputParams(n),i=t.data;if(t.parsedType===L.undefined)i=this._def.defaultValue();return this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ls.create=(n,t)=>{return new ls({innerType:n,typeName:z.ZodDefault,defaultValue:typeof t.default==="function"?t.default:()=>t.default,...K(t)})};class As extends q{_parse(n){let{ctx:t}=this._processInputParams(n),i={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});if(is(s))return s.then((r)=>{return{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new Pn(i.common.issues)},input:i.data})}});else return{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Pn(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}As.create=(n,t)=>{return new As({innerType:n,typeName:z.ZodCatch,catchValue:typeof t.catch==="function"?t.catch:()=>t.catch,...K(t)})};class lr extends q{_parse(n){if(this._getType(n)!==L.nan){let i=this._getOrReturnCtx(n);return O(i,{code:U.invalid_type,expected:L.nan,received:i.parsedType}),J}return{status:"valid",value:n.data}}}lr.create=(n)=>{return new lr({typeName:z.ZodNaN,...K(n)})};var T4=Symbol("zod_brand");class be extends q{_parse(n){let{ctx:t}=this._processInputParams(n),i=t.data;return this._def.type._parse({data:i,path:t.path,parent:t})}unwrap(){return this._def.type}}class Ar extends q{_parse(n){let{status:t,ctx:i}=this._processInputParams(n);if(i.common.async)return(async()=>{let r=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});if(r.status==="aborted")return J;if(r.status==="dirty")return t.dirty(),Si(r.value);else return this._def.out._parseAsync({data:r.value,path:i.path,parent:i})})();else{let s=this._def.in._parseSync({data:i.data,path:i.path,parent:i});if(s.status==="aborted")return J;if(s.status==="dirty")return t.dirty(),{status:"dirty",value:s.value};else return this._def.out._parseSync({data:s.value,path:i.path,parent:i})}}static create(n,t){return new Ar({in:n,out:t,typeName:z.ZodPipeline})}}class Ms extends q{_parse(n){let t=this._def.innerType._parse(n),i=(s)=>{if(qt(s))s.value=Object.freeze(s.value);return s};return is(t)?t.then((s)=>i(s)):i(t)}unwrap(){return this._def.innerType}}Ms.create=(n,t)=>{return new Ms({innerType:n,typeName:z.ZodReadonly,...K(t)})};function _0(n,t){let i=typeof n==="function"?n(t):typeof n==="string"?{message:n}:n;return typeof i==="string"?{message:i}:i}function d0(n,t={},i){if(n)return Ui.create().superRefine((s,r)=>{let e=n(s);if(e instanceof Promise)return e.then((f)=>{if(!f){let o=_0(t,s),h=o.fatal??i??!0;r.addIssue({code:"custom",...o,fatal:h})}});if(!e){let f=_0(t,s),o=f.fatal??i??!0;r.addIssue({code:"custom",...f,fatal:o})}return});return Ui.create()}var g4={object:wn.lazycreate},z;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(z||(z={}));var S4=(n,t={message:`Input not instance of ${n.name}`})=>d0((i)=>i instanceof n,t),R0=rt.create,E0=jt.create,I4=lr.create,U4=at.create,y0=es.create,b4=Ii.create,$4=ur.create,L4=os.create,O4=fs.create,B4=Ui.create,N4=Vt.create,G4=Et.create,H4=cr.create,W4=et.create,F4=wn.create,P4=wn.strictCreate,D4=hs.create,Y4=Ue.create,m4=us.create,J4=yt.create,X4=_r.create,z4=wr.create,Q4=bi.create,C4=rs.create,x4=cs.create,K4=_s.create,k4=vt.create,q4=ws.create,V4=$i.create,j4=ht.create,a4=ot.create,v4=Dt.create,Z4=ht.createWithPreprocess,p4=Ar.create,n2=()=>R0().optional(),t2=()=>E0().optional(),i2=()=>y0().optional(),s2={string:(n)=>rt.create({...n,coerce:!0}),number:(n)=>jt.create({...n,coerce:!0}),boolean:(n)=>es.create({...n,coerce:!0}),bigint:(n)=>at.create({...n,coerce:!0}),date:(n)=>Ii.create({...n,coerce:!0})};var r2=J;var $e=M.enum(["low","medium","high","xhigh","max"]),Li=M.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 e2=M.array(M.string()).transform((n)=>n.map((t)=>t.trim()).filter((t)=>t.length>0)).refine((n)=>n.length>0,{message:"api_keys must contain at least one non-empty key"}),o2=M.preprocess((n)=>typeof n==="string"&&n.trim().length===0?null:n,M.string().trim().refine((n)=>URL.canParse(n),{message:"proxy_url must be a valid URL"}).refine((n)=>{if(!URL.canParse(n))return!1;let t=new URL(n).protocol;return t==="http:"||t==="https:"},{message:"proxy_url must be http(s)"}).nullable()).default(null),f2=M.preprocess((n)=>typeof n==="string"&&n.trim().length===0?null:n,M.string().trim().min(1).nullable()).default(null),sh=M.object({host:M.string().default("127.0.0.1"),port:M.number().default(8787),api_keys:e2,enable_legacy_chat_completions:M.boolean().default(!1),proxy_url:o2,auth_source:M.enum(["opencode-shared","local"]).default("opencode-shared"),opencode_auth_db_path:f2,default_region:M.string().default("us-east-1"),account_selection_strategy:M.enum(["sticky","round-robin","lowest-usage"]).default("lowest-usage"),rate_limit_max_retries:M.number().default(3),rate_limit_retry_delay_ms:M.number().default(5000),max_request_iterations:M.number().default(20),request_timeout_ms:M.number().int().min(1).max(2147483647).default(120000),stream_idle_timeout_ms:M.number().int().min(1).max(2147483647).default(60000),max_request_body_bytes:M.number().default(10485760),token_expiry_buffer_ms:M.number().default(300000),session_affinity_ttl_ms:M.number().int().min(1).max(2147483647).default(86400000),session_affinity_max_entries:M.number().int().min(1).max(1e6).default(1e4),effort:$e.nullable().default(null),auto_effort_mapping:M.boolean().default(!0),log_level:M.string().default("info"),test_upstream_endpoint:M.string().url().optional()});class Mr extends Error{constructor(n,t){super(n,t);this.name="ConfigLoadError"}}var _2=sh.partial();function w2(n){let t=n.XDG_CONFIG_HOME??T0(c2(),".config");return T0(t,"kiro-provider","config.json")}function l2(n){if(!h2(n))return{};try{let t=JSON.parse(u2(n,"utf8"));return _2.parse(t)}catch(t){if(t instanceof M.ZodError)throw new Mr(`Invalid configuration file ${n}: ${g0(t)}`,{cause:t});if(t instanceof Error)throw new Mr(`Unable to read configuration file ${n}: ${t.message}`,{cause:t});throw t}}function A2(n){let t=n.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;return n}function M2(n){let t={},i={KIRO_PROVIDER_HOST:"host",KIRO_PROVIDER_AUTH_SOURCE:"auth_source",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[h,u]of Object.entries(i)){let c=n[h];if(c!==void 0)t[u]=c}let s={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",KIRO_PROVIDER_SESSION_AFFINITY_TTL_MS:"session_affinity_ttl_ms",KIRO_PROVIDER_SESSION_AFFINITY_MAX_ENTRIES:"session_affinity_max_entries"};for(let[h,u]of Object.entries(s)){let c=n[h];if(c!==void 0)t[u]=Number(c)}let r=n.KIRO_PROVIDER_API_KEYS;if(r!==void 0)t.api_keys=r.split(",");let e=n.KIRO_PROVIDER_PROXY_URL;if(e!==void 0)t.proxy_url=e.trim();let f=n.KIRO_PROVIDER_OPENCODE_AUTH_DB_PATH;if(f!==void 0)t.opencode_auth_db_path=f.trim();let o={KIRO_PROVIDER_ENABLE_LEGACY_CHAT_COMPLETIONS:"enable_legacy_chat_completions",KIRO_PROVIDER_AUTO_EFFORT_MAPPING:"auto_effort_mapping"};for(let[h,u]of Object.entries(o)){let c=n[h];if(c!==void 0)t[u]=A2(c)}return t}function g0(n){return n.issues.map((t)=>`${t.path.length>0?t.path.join("."):"config"}: ${t.message}`).join(", ")}function S0(n={}){let t=n.env??process.env,i=n.configPath??w2(t);try{return sh.parse({...l2(i),...M2(t),...n.overrides})}catch(s){if(s instanceof Mr)throw s;if(s instanceof M.ZodError)throw new Mr(`Invalid configuration: ${g0(s)}`,{cause:s});throw s}}function ds(n){let t=n.split("|"),i=t[0]??"";if(t.length<2)return{refreshToken:i,authMethod:"desktop"};if(t.at(-1)==="idc")return{refreshToken:i,clientId:t[1],clientSecret:t[2],authMethod:"idc"};return{refreshToken:i,authMethod:"desktop"}}function dr(n,t=120000){if(!n.access||!n.expires)return!0;return Date.now()>=n.expires-t}function Le(n){if(n.authMethod==="idc"){if(!n.clientId||!n.clientSecret)throw Error("Missing credentials");return`${n.refreshToken}|${n.clientId}|${n.clientSecret}|idc`}return`${n.refreshToken}|desktop`}function Oe(n){if(!n)return!1;return n.includes("Invalid refresh token")||n.includes("Invalid grant provided")||n.includes("invalid_grant")||n.includes("ExpiredTokenException")||n.includes("InvalidTokenException")||n.includes("ExpiredClientException")||n.includes("Client is expired")||n.includes("HTTP_401")||n.includes("HTTP_403")}function Rs(n){if(!n)return!1;let t=n.toLowerCase();return t.includes("bearer token included in the request is invalid")||t.includes("access token has expired")||t.includes("access_token expired")||t.includes("the access token expired")}function Es(n){return Oe(n)}function I0(n){let t=n&&n.length>0?n:"Account needs re-authentication";return Oe(t)?t:`InvalidTokenException: ${t}`}var U0=4;class b0 extends Error{accountId;constructor(n){super(`Account ${n} changed too frequently to update`);this.accountId=n;this.name="AccountConcurrentUpdateError"}}function d2(n){throw TypeError(`Unsupported account selection strategy: ${String(n)}`)}function Rr(n){return{...n}}function rh(n){return{refresh:Le({refreshToken:n.refreshToken,authMethod:n.authMethod,...n.clientId?{clientId:n.clientId}:{},...n.clientSecret?{clientSecret:n.clientSecret}:{},...n.profileArn?{profileArn:n.profileArn}:{}}),access:n.accessToken,expires:n.expiresAt,authMethod:n.authMethod,region:n.region,...n.oidcRegion?{oidcRegion:n.oidcRegion}:{},...n.clientId?{clientId:n.clientId}:{},...n.clientSecret?{clientSecret:n.clientSecret}:{},...n.email?{email:n.email}:{},...n.profileArn?{profileArn:n.profileArn}:{}}}class eh{strategy;database;accounts;stickyId;roundRobinCursor=0;constructor(n,t,i){this.strategy=t;this.database=i;this.accounts=n.map(Rr)}getAccountCount(){return this.accounts.length}getAccounts(){return this.accounts.map(Rr)}getMinWaitTime(){let n=Date.now(),t=this.accounts.map(({rateLimitResetTime:i})=>i-n).filter((i)=>i>0);return t.length===0?0:Math.min(...t)}reconcileFromDb(n=this.database){let t=new Map(this.accounts.map((i)=>[i.id,i]));if(this.accounts=n.getAccounts().map((i)=>{let s=t.get(i.id);return s?.generation===i.generation?s:Rr(i)}),this.stickyId&&!this.accounts.some(({id:i})=>i===this.stickyId))this.stickyId=void 0;return this.getAccounts()}selectHealthyAccount(n){let t=Date.now(),i=this.accounts.filter((r)=>this.isSelectable(r,t)).sort((r,e)=>r.id.localeCompare(e.id));if(i.length===0)return null;let s=i.find(({id:r})=>r===n)??this.selectCandidate(i);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(n,t){return this.patchAccount(n.id,(i)=>({...i,rateLimitResetTime:t}))}markUnhealthy(n,t,i){let s=Date.now();return this.patchAccount(n.id,(r)=>{if(Es(t))return{...r,failCount:10,isHealthy:!1,unhealthyReason:t,recoveryTime:void 0,lastUsed:s};let e=r.failCount+1;return{...r,failCount:e,isHealthy:e<10,unhealthyReason:t,recoveryTime:e>=10?i??s+3600000:void 0,lastUsed:s}})}updateFromAuth(n,t){let i=ds(t.refresh);for(let s=0;s<U0;s+=1){let r=s===0?n:this.database.getById(n.id);if(!r||!this.isSameLogin(n,r)){this.reconcileFromDb();return}let e={...r,refreshToken:i.refreshToken,accessToken:t.access,expiresAt:t.expires};if(this.database.updateExistingAccounts([e])===1){let f={...e,generation:r.generation+1};return this.replaceAccount(f),Rr(f)}}this.reconcileFromDb();return}toAuthDetails(n){return rh(n)}isSelectable(n,t){if(Es(n.unhealthyReason))return!1;if(n.rateLimitResetTime>t)return!1;if(n.isHealthy||Rs(n.unhealthyReason))return!0;return n.recoveryTime!==void 0&&n.recoveryTime<=t}isSameLogin(n,t){return t.refreshToken===n.refreshToken&&t.authMethod===n.authMethod&&t.clientId===n.clientId&&t.email===n.email&&t.startUrl===n.startUrl}selectCandidate(n){switch(this.strategy){case"sticky":{let i=n.find(({id:s})=>s===this.stickyId)??n[0];if(!i)throw RangeError("Candidate list cannot be empty");return this.stickyId=i.id,i}case"round-robin":{let t=n[this.roundRobinCursor%n.length];if(!t)throw RangeError("Candidate list cannot be empty");return this.roundRobinCursor+=1,t}case"lowest-usage":{let t=[...n].sort((i,s)=>(i.usedCount??0)-(s.usedCount??0)||(i.lastUsed??0)-(s.lastUsed??0)||i.id.localeCompare(s.id))[0];if(!t)throw RangeError("Candidate list cannot be empty");return t}default:return d2(this.strategy)}}patchAccount(n,t){for(let i=0;i<U0;i+=1){let s=this.database.getById(n);if(!s){this.accounts=this.accounts.filter((e)=>e.id!==n);return}let r=t(s);if(this.database.updateExistingAccounts([r])===1){let e={...r,generation:s.generation+1};return this.replaceAccount(e),Rr(e)}}throw this.reconcileFromDb(),new b0(n)}replaceAccount(n){let t=this.accounts.findIndex(({id:i})=>i===n.id);if(t===-1)this.accounts.push(n);else this.accounts[t]=n}}var p0=Q(v0(),1);import{existsSync as r6,promises as Z0}from"fs";import{join as e6}from"path";var o6={stale:15000,retries:0,realpath:!1},f6=15000,h6=25,u6=250;function c6(n){if(typeof n!=="object"||n===null||!("code"in n))return!1;return n.code==="ELOCKED"||n.code==="ENOENT"}function gh(n){return n.reason??new DOMException("The operation was aborted","AbortError")}function _6(n,t){if(t?.aborted)return Promise.reject(gh(t));return new Promise((i,s)=>{let r=setTimeout(()=>{t?.removeEventListener("abort",e),i()},n),e=()=>{clearTimeout(r),s(gh(t))};t?.addEventListener("abort",e,{once:!0})})}function w6(n,t){let i=t.replace(/[^A-Za-z0-9_-]/g,"");return e6(n,`.kiro-refresh-${i}.lock`)}async function l6(n,t){let i=Date.now()+f6,s=0;for(;;){if(t?.aborted)throw gh(t);try{return await p0.default.lock(n,o6)}catch(r){let e=i-Date.now();if(!c6(r)||e<=0)throw r;let f=Math.min(h6*2**Math.min(s,4),u6,e),o=Math.max(1,Math.floor(f/2)),h=o+Math.floor(Math.random()*(f-o+1));s+=1,await _6(h,t)}}}async function nw(n,t,i,s){let r=w6(n,t);if(await Z0.mkdir(n,{recursive:!0}),!r6(r))await(await Z0.open(r,"a")).close();let e=await l6(r,s);try{return await i()}finally{try{await e()}catch{}}}var Mw=Q(Uh(),1);import*as gt from"net";import*as Ur from"tls";import j6 from"assert";import*as cw from"net";import*as _w from"http";import{Agent as V6}from"https";var Tt=Symbol("AgentBaseInternalState");class bh extends _w.Agent{constructor(n){super(n);this[Tt]={}}isSecureEndpoint(n){if(n){if(typeof n.secureEndpoint==="boolean")return n.secureEndpoint;if(typeof n.protocol==="string")return n.protocol==="https:"}let{stack:t}=Error();if(typeof t!=="string")return!1;return t.split(`
|
|
117
|
+
`).some((i)=>i.indexOf("(https.js:")!==-1||i.indexOf("node:https:")!==-1)}incrementSockets(n){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;if(!this.sockets[n])this.sockets[n]=[];let t=new cw.Socket({writable:!1});return this.sockets[n].push(t),this.totalSocketCount++,t}decrementSockets(n,t){if(!this.sockets[n]||t===null)return;let i=this.sockets[n],s=i.indexOf(t);if(s!==-1){if(i.splice(s,1),this.totalSocketCount--,i.length===0)delete this.sockets[n]}}getName(n){if(this.isSecureEndpoint(n))return V6.prototype.getName.call(this,n);return super.getName(n)}createSocket(n,t,i){let s={...t,secureEndpoint:this.isSecureEndpoint(t)},r=this.getName(s),e=this.incrementSockets(r);Promise.resolve().then(()=>this.connect(n,s)).then((f)=>{if(this.decrementSockets(r,e),typeof f.addRequest==="function")try{return f.addRequest(n,s)}catch(o){return i(o)}this[Tt].currentSocket=f,super.createSocket(n,t,i)},(f)=>{this.decrementSockets(r,e),i(f)})}createConnection(){let n=this[Tt].currentSocket;if(this[Tt].currentSocket=void 0,!n)throw Error("No socket was returned in the `connect()` function");return n}get defaultPort(){return this[Tt].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(n){if(this[Tt])this[Tt].defaultPort=n}get protocol(){return this[Tt].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(n){if(this[Tt])this[Tt].protocol=n}}import{URL as a6}from"url";var ww=Q(Uh(),1),xe=ww.default("https-proxy-agent:parse-proxy-response");function $h(n){return new Promise((t,i)=>{let s=0,r=[];function e(){let c=n.read();if(c)u(c);else n.once("readable",e)}function f(){n.removeListener("end",o),n.removeListener("error",h),n.removeListener("readable",e)}function o(){f(),xe("onend"),i(Error("Proxy connection ended before receiving CONNECT response"))}function h(c){f(),xe("onerror %o",c),i(c)}function u(c){r.push(c),s+=c.length;let _=Buffer.concat(r,s),w=_.indexOf(`\r
|
|
51
118
|
\r
|
|
52
|
-
`);if(
|
|
53
|
-
`),A=
|
|
54
|
-
`;if(
|
|
55
|
-
`;let o
|
|
56
|
-
`);let{connect:
|
|
57
|
-
`;if(
|
|
58
|
-
`;let
|
|
59
|
-
`);let{connect:h}=await c;if(t.emit("proxyConnect",h),this.emit("proxyConnect",h,t),h.statusCode===200){if(t.once("socket",V0),n.secureEndpoint)return ss("Upgrading socket connection to TLS"),Ir.connect({...po(Ni(n),"host","path","port"),socket:i});return i}throw i.destroy(),Error(`Proxy authentication failed with status ${h.statusCode} after retry`)}}Wi.protocols=["http","https"];function V0(t){setImmediate(()=>{t.resume()})}function po(t,...n){let s={},r;for(r in t)if(!n.includes(r))s[r]=t[r];return s}var a0=new Map;function Qs(t){return t.proxy_url||void 0}function p0(t){let n=a0.get(t);if(n!==void 0)return n;let s=new Wi(t,{keepAlive:!0,maxSockets:50});return a0.set(t,s),s}function Z0(t){return t===void 0?{}:{proxy:t}}var aR=vn.options;function v0(t){return aR.includes(t)}function Zo(t){if(!t||!v0(t))return"us-east-1";return t}function Or(t,n){let s=t.replace("{{region}}",n);try{return new URL(s),s}catch{throw Error(`Invalid URL generated: ${s}`)}}function tu(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 v0(s)?s:void 0}var ot={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"},yr={"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"},nu=Object.keys(yr),jm=new Set(Object.keys(yr).filter((t)=>t.includes("-1m")));var pR=200000,ZR={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 B(t){return ZR[t]??pR}var Gr={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 Hn extends Error{code;originalError;constructor(t,n,s){super(t);this.name="KiroTokenRefreshError",this.code=n,this.originalError=s}}function vo(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function Di(t,n,s){let r=t[n];if(typeof r==="string"&&r)return r;let i=t[s];return typeof i==="string"&&i?i:void 0}function vR(t,n,s){let r=t[n];if(typeof r==="number")return r;let i=t[s];return typeof i==="number"?i:void 0}function tb(t,n){let s;try{s=JSON.parse(t)}catch{return{message:t,code:`HTTP_${n}`}}if(!vo(s))return{message:t,code:`HTTP_${n}`};let r=Di(s,"message","error_description")??t,i=Di(s,"__type","error")??`HTTP_${n}`;return{message:r,code:i}}function su(t){let n=t.userInfo;if(!vo(n))return;let s=n.email;return typeof s==="string"?s:void 0}async function ru(t,n,s){let r=Ii(t.refresh),i=t.authMethod==="idc",e=i?t.oidcRegion??t.region:t.region,f=Or(i?ot.REFRESH_IDC_URL:ot.REFRESH_URL,e);if(i&&(!r.clientId||!r.clientSecret))throw new Hn("Missing creds","MISSING_CREDENTIALS");let o=i?{refreshToken:r.refreshToken,clientId:r.clientId,clientSecret:r.clientSecret,grantType:"refresh_token"}:{refreshToken:r.refreshToken},c=i?`aws-sdk-js/${ot.SDK_VERSION} ua/2.1 os/other lang/js md/browser#unknown_unknown api/sso-oidc#${ot.SDK_VERSION} m/E ${ot.USER_AGENT}`:`aws-sdk-js/3.0.0 ${ot.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}:{},...Z0(s)});if(!h.ok){let w=tb(await h.text(),h.status);throw new Hn(`Refresh failed: ${w.message}`,w.code)}let u=await h.json();if(!vo(u))throw new Hn("No access token","INVALID_RESPONSE");let _=Di(u,"access_token","accessToken");if(!_)throw new Hn("No access token","INVALID_RESPONSE");let l={refreshToken:Di(u,"refresh_token","refreshToken")??r.refreshToken,authMethod:t.authMethod,...r.clientId?{clientId:r.clientId}:{},...r.clientSecret?{clientSecret:r.clientSecret}:{}};return{refresh:Oi(l),access:_,expires:Date.now()+(vR(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||su(u)?{email:t.email??su(u)}:{}}}catch(h){if(h instanceof Hn)throw h;if(h instanceof Error&&h.name==="AbortError")throw h;throw new Hn(`Token refresh failed: ${h instanceof Error?h.message:"Unknown error"}`,"NETWORK_ERROR",h instanceof Error?h:void 0)}}class Yi extends Error{accountId;constructor(t){super(`Account ${t} is no longer available`);this.accountId=t;this.name="AccountUnavailableError"}}class tf{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(!H0(n,this.tokenExpiryBufferMs)){let r=this.accountManager.getAccounts().find(({id:i})=>i===t.id);if(!r)throw new Yi(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 Yi(t.id);let r={...t,generation:t.generation},i=`${r.id}:${r.generation}`,e=this.inFlight.get(i);if(e)return e;let f=this.runRefresh(r,n,s).finally(()=>{if(this.inFlight.get(i)===f)this.inFlight.delete(i)});return this.inFlight.set(i,f),f}async runRefresh(t,n,s){let r=await ru(n,s,this.proxyUrl),i=this.accountManager.updateFromAuth(t,r);if(!i)throw new Yi(t.id);return i}}import{Database as nb}from"bun:sqlite";import{chmodSync as sb,existsSync as rb,mkdirSync as ib}from"fs";import{homedir as iu}from"os";import{dirname as eb,join as rf}from"path";function nf(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 mi(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 sf(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 ob(){let t=process.platform==="win32"?process.env.APPDATA??rf(iu(),"AppData","Roaming"):process.env.XDG_CONFIG_HOME??rf(iu(),".config");return rf(t,"kiro-provider","accounts.db")}var Pn=ob();class rs{db;path;constructor(t=Pn){if(this.path=t,t!==":memory:")ib(eb(t),{recursive:!0});this.db=new nb(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(`
|
|
119
|
+
`);if(w===-1){xe("have not received end of HTTP headers yet..."),e();return}let l=_.slice(0,w).toString("ascii").split(`\r
|
|
120
|
+
`),A=l.shift();if(!A)return n.destroy(),i(Error("No header received from proxy CONNECT response"));let d=A.split(" "),E=+d[1],R=d.slice(2).join(" "),y={};for(let T of l){if(!T)continue;let S=T.indexOf(":");if(S===-1)return n.destroy(),i(Error(`Invalid header from proxy CONNECT response: "${T}"`));let I=T.slice(0,S).toLowerCase(),F=T.slice(S+1).trimStart(),C=y[I];if(typeof C==="string")y[I]=[C,F];else if(Array.isArray(C))C.push(F);else y[I]=F}xe("got proxy server response: %o %o",A,y),f(),t({connect:{statusCode:E,statusText:R,headers:y},buffered:_})}n.on("error",h),n.on("end",o),e()})}function lw(){return async({response:n,scheme:t})=>{if(t.toLowerCase()!=="negotiate")throw Error(`Expected Negotiate scheme but got "${t}"`);let i;try{i=await import("kerberos")}catch{throw Error('The "kerberos" package is required for Negotiate proxy authentication. Install it with: npm install kerberos')}let s=n.headers["proxy-authenticate"]||"",r=Array.isArray(s)?s[0]:s,e=typeof r==="string"&&r.includes(" ")?r.split(" ").slice(1).join(" "):void 0,o=await(await i.initializeClient("HTTP@proxy",{mechOID:i.GSS_MECH_OID_SPNEGO})).step(e||"");if(!o)throw Error("Kerberos client.step() returned no token");return{headers:{"Proxy-Authorization":`Negotiate ${o}`}}}}var Fi=Mw.default("https-proxy-agent"),Ke=(n)=>{if(n.servername===void 0&&n.host&&!gt.isIP(n.host))return{...n,servername:n.host};return n};class br extends bh{constructor(n,t){super(t);if(this.options={path:void 0},this.proxy=typeof n==="string"?new a6(n):n,this.proxyHeaders=t?.headers??{},Fi("Creating new HttpsProxyAgent instance: %o",this.proxy.href),t?.negotiate)this.onProxyAuth=lw();else if(t?.onProxyAuth)this.onProxyAuth=t.onProxyAuth;let i=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),s=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...t?Lh(t,"headers","onProxyAuth","negotiate"):null,host:i,port:s}}async connect(n,t){let{proxy:i}=this;if(!t.host)throw TypeError('No "host" provided');let s;if(i.protocol==="https:")Fi("Creating `tls.Socket`: %o",this.connectOpts),s=Ur.connect(Ke(this.connectOpts));else Fi("Creating `net.Socket`: %o",this.connectOpts),s=gt.connect(this.connectOpts);let r=typeof this.proxyHeaders==="function"?this.proxyHeaders():{...this.proxyHeaders},e=gt.isIPv6(t.host)?`[${t.host}]`:t.host,f=`CONNECT ${e}:${t.port} HTTP/1.1\r
|
|
121
|
+
`;if(i.username||i.password){let _=`${decodeURIComponent(i.username)}:${decodeURIComponent(i.password)}`;r["Proxy-Authorization"]=`Basic ${Buffer.from(_).toString("base64")}`}if(r.Host=`${e}:${t.port}`,!r["Proxy-Connection"])r["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close";for(let _ of Object.keys(r))f+=`${_}: ${r[_]}\r
|
|
122
|
+
`;let o=$h(s);s.write(`${f}\r
|
|
123
|
+
`);let{connect:h,buffered:u}=await o;if(n.emit("proxyConnect",h),this.emit("proxyConnect",h,n),n.emit("proxy",{proxy:this.proxy.href,socket:s}),h.statusCode===200){if(n.once("socket",Aw),t.secureEndpoint)return Fi("Upgrading socket connection to TLS"),Ur.connect({...Lh(Ke(t),"host","path","port"),socket:s});return s}if(h.statusCode===407&&this.onProxyAuth){Fi("Got 407 response, invoking onProxyAuth callback"),s.destroy();let _=h.headers["proxy-authenticate"]||"",w=Array.isArray(_)?_[0].split(/\s/)[0]:_.split(/\s/)[0],l=await this.onProxyAuth({response:h,scheme:w});return this._connectWithAuth(n,t,l.headers)}s.destroy();let c=new gt.Socket({writable:!1});return c.readable=!0,n.once("socket",(_)=>{Fi("Replaying proxy buffer for failed request"),j6(_.listenerCount("data")>0),_.push(u),_.push(null)}),c}async _connectWithAuth(n,t,i){let{proxy:s}=this,r;if(s.protocol==="https:")r=Ur.connect(Ke(this.connectOpts));else r=gt.connect(this.connectOpts);let e=typeof this.proxyHeaders==="function"?this.proxyHeaders():{...this.proxyHeaders},f=gt.isIPv6(t.host)?`[${t.host}]`:t.host,o=`CONNECT ${f}:${t.port} HTTP/1.1\r
|
|
124
|
+
`;if(s.username||s.password){let c=`${decodeURIComponent(s.username)}:${decodeURIComponent(s.password)}`;e["Proxy-Authorization"]=`Basic ${Buffer.from(c).toString("base64")}`}if(Object.assign(e,i),e.Host=`${f}:${t.port}`,!e["Proxy-Connection"])e["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close";for(let c of Object.keys(e))o+=`${c}: ${e[c]}\r
|
|
125
|
+
`;let h=$h(r);r.write(`${o}\r
|
|
126
|
+
`);let{connect:u}=await h;if(n.emit("proxyConnect",u),this.emit("proxyConnect",u,n),u.statusCode===200){if(n.once("socket",Aw),t.secureEndpoint)return Fi("Upgrading socket connection to TLS"),Ur.connect({...Lh(Ke(t),"host","path","port"),socket:r});return r}throw r.destroy(),Error(`Proxy authentication failed with status ${u.statusCode} after retry`)}}br.protocols=["http","https"];function Aw(n){setImmediate(()=>{n.resume()})}function Lh(n,...t){let i={},s;for(s in n)if(!t.includes(s))i[s]=n[s];return i}function $s(n){return n.proxy_url||void 0}function dw(n){return n===void 0?{}:{proxy:n}}var v6=Li.options;function Rw(n){return v6.includes(n)}function Oh(n){if(!n||!Rw(n))return"us-east-1";return n}function $r(n,t){let i=n.replace("{{region}}",t);try{return new URL(i),i}catch{throw Error(`Invalid URL generated: ${i}`)}}function Ew(n){if(!n)return;let t=n.split(":");if(t.length<6)return;if(t[0]!=="arn")return;let i=t[3];if(typeof i!=="string"||!i)return;return Rw(i)?i:void 0}var Rn={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"},Lr={"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"},yw=Object.keys(Lr),Sx=new Set(Object.keys(Lr).filter((n)=>n.includes("-1m")));var Z6=200000,p6={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 D(n){return p6[n]??Z6}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 ti extends Error{code;originalError;constructor(n,t,i){super(n);this.name="KiroTokenRefreshError",this.code=t,this.originalError=i}}function Bh(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function ke(n,t,i){let s=n[t];if(typeof s==="string"&&s)return s;let r=n[i];return typeof r==="string"&&r?r:void 0}function ng(n,t,i){let s=n[t];if(typeof s==="number")return s;let r=n[i];return typeof r==="number"?r:void 0}function tg(n,t){let i;try{i=JSON.parse(n)}catch{return{message:n,code:`HTTP_${t}`}}if(!Bh(i))return{message:n,code:`HTTP_${t}`};let s=ke(i,"message","error_description")??n,r=ke(i,"__type","error")??`HTTP_${t}`;return{message:s,code:r}}function Tw(n){let t=n.userInfo;if(!Bh(t))return;let i=t.email;return typeof i==="string"?i:void 0}async function qe(n,t,i){let s=ds(n.refresh),r=n.authMethod==="idc",e=r?n.oidcRegion??n.region:n.region,f=$r(r?Rn.REFRESH_IDC_URL:Rn.REFRESH_URL,e);if(r&&(!s.clientId||!s.clientSecret))throw new ti("Missing creds","MISSING_CREDENTIALS");let o=r?{refreshToken:s.refreshToken,clientId:s.clientId,clientSecret:s.clientSecret,grantType:"refresh_token"}:{refreshToken:s.refreshToken},h=r?`aws-sdk-js/${Rn.SDK_VERSION} ua/2.1 os/other lang/js md/browser#unknown_unknown api/sso-oidc#${Rn.SDK_VERSION} m/E ${Rn.USER_AGENT}`:`aws-sdk-js/3.0.0 ${Rn.USER_AGENT}-0.1.0 os/macos lang/js md/nodejs/18.0.0`;try{let u=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":h,Connection:"close"},body:JSON.stringify(o),...t?{signal:t}:{},...dw(i)});if(!u.ok){let l=tg(await u.text(),u.status);throw new ti(`Refresh failed: ${l.message}`,l.code)}let c=await u.json();if(!Bh(c))throw new ti("No access token","INVALID_RESPONSE");let _=ke(c,"access_token","accessToken");if(!_)throw new ti("No access token","INVALID_RESPONSE");let w={refreshToken:ke(c,"refresh_token","refreshToken")??s.refreshToken,authMethod:n.authMethod,...s.clientId?{clientId:s.clientId}:{},...s.clientSecret?{clientSecret:s.clientSecret}:{}};return{refresh:Le(w),access:_,expires:Date.now()+(ng(c,"expires_in","expiresIn")??3600)*1000,authMethod:n.authMethod,region:n.region,...n.oidcRegion?{oidcRegion:n.oidcRegion}:{},...n.profileArn?{profileArn:n.profileArn}:{},...n.clientId?{clientId:n.clientId}:{},...n.clientSecret?{clientSecret:n.clientSecret}:{},...n.email||Tw(c)?{email:n.email??Tw(c)}:{}}}catch(u){if(u instanceof ti)throw u;if(u instanceof Error&&u.name==="AbortError")throw u;throw new ti(`Token refresh failed: ${u instanceof Error?u.message:"Unknown error"}`,"NETWORK_ERROR",u instanceof Error?u:void 0)}}class ii extends Error{accountId;constructor(n){super(`Account ${n} is no longer available`);this.accountId=n;this.name="AccountUnavailableError"}}class Nh{accountManager;tokenExpiryBufferMs;proxyUrl;inFlight=new Map;constructor(n,t,i){this.accountManager=n;this.tokenExpiryBufferMs=t;this.proxyUrl=i}async refreshIfNeeded(n,t,i){if(!dr(t,this.tokenExpiryBufferMs)){let s=this.accountManager.getAccounts().find(({id:r})=>r===n.id);if(!s)throw new ii(n.id);return s}return this.startOrJoinRefresh(n,t,i)}async forceRefresh(n,t){return this.startOrJoinRefresh(n,this.accountManager.toAuthDetails(n),t)}startOrJoinRefresh(n,t,i){if(!("generation"in n)||typeof n.generation!=="number")throw new ii(n.id);let s={...n,generation:n.generation},r=`${s.id}:${s.generation}`,e=this.inFlight.get(r);if(e)return e;let f=this.runRefresh(s,t,i).finally(()=>{if(this.inFlight.get(r)===f)this.inFlight.delete(r)});return this.inFlight.set(r,f),f}async runRefresh(n,t,i){let s=await qe(t,i,this.proxyUrl),r=this.accountManager.updateFromAuth(n,s);if(!r)throw new ii(n.id);return r}}function Ls(n){return{...n}}function ig(n){throw TypeError(`Unsupported account selection strategy: ${String(n)}`)}function sg(n,t){return n.refreshToken===t.refreshToken&&n.accessToken===t.accessToken&&n.expiresAt===t.expiresAt&&n.authMethod===t.authMethod&&n.clientId===t.clientId&&n.clientSecret===t.clientSecret&&n.profileArn===t.profileArn&&n.email===t.email&&n.startUrl===t.startUrl}class Gh{store;strategy;accounts=[];stickyId;roundRobinCursor=0;constructor(n,t){this.store=n;this.strategy=t;this.reconcileFromDb()}reconcileFromDb(){if(this.accounts=this.store.getAccounts(),this.stickyId&&!this.accounts.some(({id:n})=>n===this.stickyId))this.stickyId=void 0;return this.accounts.map(Ls)}selectHealthyAccount(n){for(let t=0;t<2;t+=1){let i=Date.now(),s=this.accounts.filter((f)=>this.isSelectable(f,i)).sort((f,o)=>f.id.localeCompare(o.id));if(s.length===0)return null;let r=s.find(({id:f})=>f===n)??this.selectCandidate(s),e=this.store.recordSelection(r.id,i);if(e)return this.publishLatest(e),Ls(e);this.reconcileFromDb()}return null}getAccountCount(){return this.accounts.length}toAuthDetails(n){return rh(n)}markRateLimited(n,t){let i=this.store.markRateLimited(n.id,t);if(i)this.publishLatest(i);else this.reconcileFromDb();return i===void 0?void 0:Ls(i)}markUnhealthy(n,t,i){let s=this.store.markUnhealthy(n.id,t,Es(t),i,Date.now());if(s)this.publishLatest(s);else this.reconcileFromDb();return s===void 0?void 0:Ls(s)}publishLatest(n){let t=this.accounts.findIndex(({id:i})=>i===n.id);if(t===-1)this.accounts.push(Ls(n));else this.accounts[t]=Ls(n)}isSelectable(n,t){if(Es(n.unhealthyReason))return!1;if(n.rateLimitResetTime>t)return!1;if(n.isHealthy||Rs(n.unhealthyReason))return!0;return n.recoveryTime!==void 0&&n.recoveryTime<=t}selectCandidate(n){switch(this.strategy){case"sticky":{let i=n.find(({id:s})=>s===this.stickyId)??n[0];if(!i)throw RangeError("Candidate list cannot be empty");return this.stickyId=i.id,i}case"round-robin":{let t=n[this.roundRobinCursor%n.length];if(!t)throw RangeError("Candidate list cannot be empty");return this.roundRobinCursor+=1,t}case"lowest-usage":{let t=[...n].sort((i,s)=>(i.usedCount??0)-(s.usedCount??0)||(i.lastUsed??0)-(s.lastUsed??0)||i.id.localeCompare(s.id))[0];if(!t)throw RangeError("Candidate list cannot be empty");return t}default:return ig(this.strategy)}}}class Hh{accountManager;store;tokenExpiryBufferMs;proxyUrl;inFlight=new Map;lockDirectory;constructor(n,t,i,s,r=h0(t.path)){this.accountManager=n;this.store=t;this.tokenExpiryBufferMs=i;this.proxyUrl=s;this.lockDirectory=r}async refreshIfNeeded(n,t,i){let s=this.store.getById(n.id);if(!s)throw new ii(n.id);if(this.accountManager.publishLatest(s),!dr(this.accountManager.toAuthDetails(s),this.tokenExpiryBufferMs))return s;return this.startOrJoinRefresh(n,!1,i)}async forceRefresh(n,t){return this.startOrJoinRefresh(n,!0,t)}startOrJoinRefresh(n,t,i){let s=this.inFlight.get(n.id);if(s)return s;let r=this.runLockedRefresh(n,t,i).finally(()=>{if(this.inFlight.get(n.id)===r)this.inFlight.delete(n.id)});return this.inFlight.set(n.id,r),r}async runLockedRefresh(n,t,i){return nw(this.lockDirectory,n.id,async()=>{let s=this.store.getById(n.id);if(!s)throw new ii(n.id);let r=this.accountManager.toAuthDetails(s);if(t&&!sg(n,s)||!t&&!dr(r,this.tokenExpiryBufferMs))return this.accountManager.publishLatest(s),s;try{let e=await qe(r,i,this.proxyUrl),f=ds(e.refresh),o={...s,refreshToken:f.refreshToken,accessToken:e.access,expiresAt:e.expires,lastUsed:Date.now(),isHealthy:!0,failCount:0,unhealthyReason:void 0,recoveryTime:void 0,...e.email?{email:e.email}:{},...f.clientId?{clientId:f.clientId}:{},...f.clientSecret?{clientSecret:f.clientSecret}:{}},h=this.store.persistRefreshedAccount(s,o);if(!h)throw new ii(n.id);return this.accountManager.publishLatest(h),h}catch(e){let f=typeof e==="object"&&e!==null&&"code"in e?String(e.code):"",o=e instanceof Error?e.message:String(e),h=f?`${f}: ${o}`:o;if(Oe(h))this.accountManager.markUnhealthy(s,I0(h));throw e}},i)}}function rg(n){console.error("stream-cleanup: cleanup step failed",n)}function gw(n,t){try{n()}catch(i){let s=t??rg;try{s(i)}catch{}}}function Wn(...n){for(let t of n)gw(t)}function cn(n){let t,i=Promise.resolve().then(n).then(()=>{return},()=>{return}),s=new Promise((r)=>{t=setTimeout(r,500)});return Promise.race([i,s]).then(()=>{if(t!==void 0)clearTimeout(t)},()=>{if(t!==void 0)clearTimeout(t)})}import{Database as eg}from"bun:sqlite";import{chmodSync as og,existsSync as fg,mkdirSync as hg}from"fs";import{homedir as Sw}from"os";import{dirname as ug,join as Ph}from"path";function Wh(n,t){return{id:n.id,email:n.email,auth_method:n.authMethod,region:n.region,oidc_region:n.oidcRegion??null,client_id:n.clientId??null,client_secret:n.clientSecret??null,profile_arn:n.profileArn??null,start_url:n.startUrl??null,refresh_token:n.refreshToken,access_token:n.accessToken,expires_at:n.expiresAt,rate_limit_reset:n.rateLimitResetTime,is_healthy:n.isHealthy?1:0,unhealthy_reason:n.unhealthyReason??null,recovery_time:n.recoveryTime??null,fail_count:n.failCount,last_used:n.lastUsed??0,used_count:n.usedCount??0,limit_count:n.limitCount??0,last_sync:n.lastSync??0,overage_count:n.overageCount??0,generation:t}}function Ve(n){return{id:n.id,email:n.email,authMethod:n.auth_method,region:n.region,oidcRegion:n.oidc_region??void 0,clientId:n.client_id??void 0,clientSecret:n.client_secret??void 0,profileArn:n.profile_arn??void 0,startUrl:n.start_url??void 0,refreshToken:n.refresh_token,accessToken:n.access_token,expiresAt:n.expires_at,rateLimitResetTime:n.rate_limit_reset,isHealthy:n.is_healthy===1,unhealthyReason:n.unhealthy_reason??void 0,recoveryTime:n.recovery_time??void 0,failCount:n.fail_count,lastUsed:n.last_used,usedCount:n.used_count,limitCount:n.limit_count,lastSync:n.last_sync,overageCount:n.overage_count,generation:n.generation}}function Fh(n){return[n.id,n.email,n.auth_method,n.region??null,n.oidc_region??null,n.client_id??null,n.client_secret??null,n.profile_arn??null,n.start_url??null,n.refresh_token,n.access_token,n.expires_at,n.rate_limit_reset,n.is_healthy,n.unhealthy_reason??null,n.recovery_time??null,n.fail_count,n.last_used,n.used_count,n.limit_count,n.last_sync,n.overage_count,n.generation]}function Dh(n){return{keyHash:n.key_hash,accountId:n.account_id,conversationId:n.conversation_id,createdAt:n.created_at,lastSeen:n.last_seen,expiresAt:n.expires_at}}function cg(){let n=process.platform==="win32"?process.env.APPDATA??Ph(Sw(),"AppData","Roaming"):process.env.XDG_CONFIG_HOME??Ph(Sw(),".config");return Ph(n,"kiro-provider","accounts.db")}var si=cg();class Pi{db;path;constructor(n=si){if(this.path=n,n!==":memory:")hg(ug(n),{recursive:!0});this.db=new eg(n,{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
127
|
CREATE TABLE IF NOT EXISTS accounts (
|
|
61
128
|
id TEXT PRIMARY KEY, email TEXT NOT NULL, auth_method TEXT NOT NULL,
|
|
62
129
|
region TEXT NOT NULL, oidc_region TEXT, client_id TEXT, client_secret TEXT,
|
|
@@ -68,30 +135,45 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
|
|
|
68
135
|
limit_count INTEGER DEFAULT 0, last_sync INTEGER DEFAULT 0,
|
|
69
136
|
overage_count INTEGER DEFAULT 0, generation INTEGER NOT NULL DEFAULT 1
|
|
70
137
|
)
|
|
71
|
-
`),!this.db.query("PRAGMA table_info(accounts)").all().some(({name:
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
138
|
+
`),!this.db.query("PRAGMA table_info(accounts)").all().some(({name:i})=>i==="generation"))this.db.run("ALTER TABLE accounts ADD COLUMN generation INTEGER NOT NULL DEFAULT 1");this.db.run(`
|
|
139
|
+
CREATE TABLE IF NOT EXISTS removed_accounts (
|
|
140
|
+
id TEXT PRIMARY KEY,
|
|
141
|
+
removed_at INTEGER NOT NULL,
|
|
142
|
+
last_generation INTEGER NOT NULL
|
|
143
|
+
)
|
|
144
|
+
`),this.db.run(`
|
|
145
|
+
CREATE TABLE IF NOT EXISTS session_affinity (
|
|
146
|
+
key_hash TEXT PRIMARY KEY,
|
|
147
|
+
account_id TEXT NOT NULL,
|
|
148
|
+
conversation_id TEXT NOT NULL,
|
|
149
|
+
created_at INTEGER NOT NULL,
|
|
150
|
+
last_seen INTEGER NOT NULL,
|
|
151
|
+
expires_at INTEGER NOT NULL
|
|
152
|
+
)
|
|
153
|
+
`),this.db.run(`
|
|
154
|
+
CREATE INDEX IF NOT EXISTS session_affinity_expires_at_idx
|
|
155
|
+
ON session_affinity (expires_at)
|
|
156
|
+
`),this.db.run(`
|
|
157
|
+
CREATE INDEX IF NOT EXISTS session_affinity_last_seen_idx
|
|
158
|
+
ON session_affinity (last_seen)
|
|
159
|
+
`)})}getAccounts(){return this.db.query(`
|
|
78
160
|
SELECT accounts.* FROM accounts
|
|
79
161
|
WHERE NOT EXISTS (
|
|
80
162
|
SELECT 1 FROM removed_accounts WHERE removed_accounts.id = accounts.id
|
|
81
163
|
)
|
|
82
|
-
`).all().map(
|
|
164
|
+
`).all().map(Ve)}getById(n){let t=this.db.query(`
|
|
83
165
|
SELECT accounts.* FROM accounts
|
|
84
166
|
WHERE accounts.id = ? AND NOT EXISTS (
|
|
85
167
|
SELECT 1 FROM removed_accounts WHERE removed_accounts.id = accounts.id
|
|
86
168
|
)
|
|
87
|
-
`).get(
|
|
169
|
+
`).get(n);return t===null?void 0:Ve(t)}insertAccount(n){return this.withImmediateTransaction(()=>{let t=this.db.query("SELECT generation FROM accounts WHERE id = ?").get(n.id),i=this.db.query("SELECT last_generation FROM removed_accounts WHERE id = ?").get(n.id),s=Math.max(t?.generation??0,i?.last_generation??0)+1,r=Wh(n,s);return this.db.query(`
|
|
88
170
|
INSERT OR REPLACE INTO accounts (
|
|
89
171
|
id, email, auth_method, region, oidc_region, client_id, client_secret,
|
|
90
172
|
profile_arn, start_url, refresh_token, access_token, expires_at,
|
|
91
173
|
rate_limit_reset, is_healthy, unhealthy_reason, recovery_time, fail_count,
|
|
92
174
|
last_used, used_count, limit_count, last_sync, overage_count, generation
|
|
93
175
|
) VALUES (${Array.from({length:23},()=>"?").join(", ")})
|
|
94
|
-
`).run(...
|
|
176
|
+
`).run(...Fh(r)),this.clearRemovedAccountInternal(n.id),Ve(r)})}updateExistingAccounts(n){return this.withImmediateTransaction(()=>{let t=0,i=this.db.query(`
|
|
95
177
|
UPDATE accounts SET
|
|
96
178
|
email = ?, auth_method = ?, region = ?, oidc_region = ?, client_id = ?,
|
|
97
179
|
client_secret = ?, profile_arn = ?, start_url = ?, refresh_token = ?,
|
|
@@ -102,69 +184,103 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
|
|
|
102
184
|
WHERE id = ? AND generation = ? AND NOT EXISTS (
|
|
103
185
|
SELECT 1 FROM removed_accounts WHERE removed_accounts.id = accounts.id
|
|
104
186
|
)
|
|
105
|
-
`);for(let
|
|
187
|
+
`);for(let s of n){let r=Fh(Wh(s,s.generation)),e=r.shift();r.pop(),t+=i.run(...r,e??s.id,s.generation).changes}return t})}removeAccount(n){this.withImmediateTransaction(()=>{let t=this.db.query("SELECT generation FROM accounts WHERE id = ?").get(n),i=this.db.query("SELECT last_generation FROM removed_accounts WHERE id = ?").get(n),s=t?.generation??i?.last_generation??0;this.db.query("DELETE FROM accounts WHERE id = ?").run(n),this.db.query("DELETE FROM session_affinity WHERE account_id = ?").run(n),this.db.query(`
|
|
106
188
|
INSERT OR REPLACE INTO removed_accounts (id, removed_at, last_generation)
|
|
107
189
|
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(rb(t))sb(t,384)}}function V(t,n,s,r){let i={message:n,type:s};if(r!==void 0)i.code=r;return new Response(JSON.stringify({error:i}),{status:t,headers:{"Content-Type":"application/json"}})}var eu="Bearer ";function ou(t,n){let s=t.headers.get("Authorization");if(s===null)return{ok:!1,response:V(401,"Missing Authorization header.","authentication_error","missing_api_key")};if(!s.startsWith(eu))return{ok:!1,response:V(401,"Authorization header must use the Bearer scheme.","authentication_error","invalid_api_key")};let r=s.slice(eu.length);if(!n.includes(r))return{ok:!1,response:V(401,"Incorrect API key provided.","authentication_error","invalid_api_key")};return{ok:!0}}var Xn=Y(xt(),1);var ni=Y(xt(),1);var si=Y(xt(),1);var Un=Y(xt(),1);var Ht=Y(xt(),1);var p=Y(St(),1);var _r=Y(kn(),1),Tg=Y(Nn(),1);var Dc=Y(Me(),1);var ri=Y(Ut(),1);var Nt=Y(fs(),1);var v=Y(vr(),1);var z=Y(Rn(),1);var tr=Y(kn(),1);var vs=Y(Rn(),1);var AA=async(t,n,s)=>{return{operation:vs.getSmithyContext(n).operation}};function JG(t){return{schemeId:"smithy.api#httpBearerAuth",propertiesExtractor:({profile:n,filepath:s,configFilepath:r,ignoreCache:i},e)=>({identityProperties:{profile:n,filepath:s,configFilepath:r,ignoreCache:i}})}}var MA=(t)=>{let n=[];switch(t.operation){default:n.push(JG(t))}return n},gA=(t)=>{let n=tr.memoizeIdentityProvider(t.token,tr.isIdentityExpired,tr.doesIdentityRequireRefresh);return Object.assign(t,{authSchemePreference:vs.normalizeProvider(t.authSchemePreference??[]),token:n})};var EA=(t)=>{return Object.assign(t,{useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,defaultSigningName:"amazoncodewhispererstreamingservice"})},dA={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}};var RA={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 Ag=Y(xt(),1),Mg=Y(jc(),1);var cr=Y(St(),1);var It=Y(St(),1);var iM=300000,sr="To refresh this SSO session run 'aws sso login' with the corresponding profile.";var P1=async(t,n={},s)=>{let{SSOOIDCClient:r}=await Promise.resolve().then(() => Y(Ph(),1)),i=(f)=>n.clientConfig?.[f]??n.parentClientConfig?.[f]??s?.[f];return new r(Object.assign({},n.clientConfig??{},{region:t??n.clientConfig?.region,logger:i("logger"),userAgentAppId:i("userAgentAppId")}))};var N1=async(t,n,s={},r)=>{let{CreateTokenCommand:i}=await Promise.resolve().then(() => Y(Ph(),1));return(await P1(n,s,r)).send(new i({clientId:t.clientId,clientSecret:t.clientSecret,refreshToken:t.refreshToken,grantType:"refresh_token"}))};var W1=Y(St(),1);var Nh=(t)=>{if(t.expiration&&t.expiration.getTime()<Date.now())throw new W1.TokenProviderError(`Token is expired. ${sr}`,!1)};var D1=Y(St(),1);var qn=(t,n,s=!1)=>{if(typeof n>"u")throw new D1.TokenProviderError(`Value not present for '${t}' in SSO Token${s?". Cannot refresh":""}. ${sr}`,!1)};var Y1=Y(St(),1);import{promises as _W}from"fs";var{writeFile:lW}=_W,m1=(t,n)=>{let s=Y1.getSSOTokenFilepath(t),r=JSON.stringify(n,null,2);return lW(s,r)};var Q1=new Date(0),J1=(t={})=>async({callerClientConfig:n}={})=>{t.logger?.debug("@aws-sdk/token-providers - fromSso");let s=await It.parseKnownFiles(t),r=It.getProfileName({profile:t.profile??n?.profile}),i=s[r];if(!i)throw new It.TokenProviderError(`Profile '${r}' could not be found in shared credentials file.`,!1);else if(!i.sso_session)throw new It.TokenProviderError(`Profile '${r}' is missing required property 'sso_session'.`);let e=i.sso_session,o=(await It.loadSsoSessionData(t))[e];if(!o)throw new It.TokenProviderError(`Sso session '${e}' could not be found in shared credentials file.`,!1);for(let A of["sso_start_url","sso_region"])if(!o[A])throw new It.TokenProviderError(`Sso session '${e}' is missing required property '${A}'.`,!1);let{sso_start_url:c,sso_region:h}=o,u;try{u=await It.getSSOTokenFromFile(e)}catch(A){throw new It.TokenProviderError(`The SSO session token associated with profile=${r} was not found or is invalid. ${sr}`,!1)}qn("accessToken",u.accessToken),qn("expiresAt",u.expiresAt);let{accessToken:_,expiresAt:l}=u,w={token:_,expiration:new Date(l)};if(w.expiration.getTime()-Date.now()>iM)return w;if(Date.now()-Q1.getTime()<30000)return Nh(w),w;qn("clientId",u.clientId,!0),qn("clientSecret",u.clientSecret,!0),qn("refreshToken",u.refreshToken,!0);try{Q1.setTime(Date.now());let A=await N1(u,h,t,n);qn("accessToken",A.accessToken),qn("expiresIn",A.expiresIn);let M=new Date(Date.now()+A.expiresIn*1000);try{await m1(e,{...u,accessToken:A.accessToken,expiresAt:M.toISOString(),refreshToken:A.refreshToken})}catch(E){}return{token:A.accessToken,expiration:M}}catch(A){return Nh(w),w}};var Wh=(t={})=>cr.memoize(cr.chain(J1(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 _n=Y(xt(),1);var gg=Y(kn(),1);var oo=Y(Me(),1);var Dh=Y($t(),1);var Ln=Y(St(),1);var bo=Y(me(),1);var Yh=Y($t(),1);var mh=Y(St(),1);var ht=Y(vr(),1);var _g=Y(Oh(),1),lg=Y(kn(),1);var Qh=Y(Ut(),1);var hr=Y($t(),1);var gs=Y($t(),1);var dt=Y(fs(),1);var wi="ref",Es=-1,fo=!0,k1="isSet",q1="PartitionResult",co="booleanEquals",Jh="getAttr",X1={[wi]:"Endpoint"},kh={[wi]:q1},ur={},z1=[{[wi]:"Region"}],x1={conditions:[[k1,[X1]],[k1,z1],["aws.partition",z1,q1],[co,[{[wi]:"UseFIPS"},fo]],[co,[{[wi]:"UseDualStack"},fo]],[co,[{fn:Jh,argv:[kh,"supportsDualStack"]},fo]],[co,[{fn:Jh,argv:[kh,"supportsFIPS"]},fo]],["stringEquals",[{fn:Jh,argv:[kh,"name"]},"aws-us-gov"]]],results:[[Es],[Es,"Invalid Configuration: FIPS and custom endpoint are not supported"],[Es,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[X1,ur],["https://amazoncodewhispererstreamingservice-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",ur],[Es,"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],[Es,"FIPS is enabled but this partition does not support FIPS"],["https://amazoncodewhispererstreamingservice.{Region}.{PartitionResult#dualStackDnsSuffix}",ur],[Es,"DualStack is enabled but this partition does not support DualStack"],["https://amazoncodewhispererstreamingservice.{Region}.{PartitionResult#dnsSuffix}",ur],[Es,"Invalid Configuration: Missing Region"]]},wW=2,Ot=1e8,AW=new Int32Array([-1,1,-1,0,13,3,1,4,Ot+12,2,5,Ot+12,3,8,6,4,7,Ot+11,5,Ot+9,Ot+10,4,11,9,6,10,Ot+8,7,Ot+6,Ot+7,5,12,Ot+5,6,Ot+4,Ot+5,3,Ot+1,14,4,Ot+2,Ot+3]),C1=dt.BinaryDecisionDiagram.from(AW,wW,x1.conditions,x1.results);var MW=new dt.EndpointCache({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),K1=(t,n={})=>{return MW.get(t,()=>dt.decideEndpoint(C1,{endpointParams:t,logger:n.logger}))};dt.customEndpointFunctions.aws=Ht.awsEndpointFunctions;var xh=Y(Nn(),1);class yt extends z.ServiceException{constructor(t){super(t);Object.setPrototypeOf(this,yt.prototype)}}class ho extends yt{name="AccessDeniedException";$fault="client";reason;constructor(t){super({name:"AccessDeniedException",$fault:"client",...t});Object.setPrototypeOf(this,ho.prototype),this.reason=t.reason}}class uo extends yt{name="ConflictException";$fault="client";reason;constructor(t){super({name:"ConflictException",$fault:"client",...t});Object.setPrototypeOf(this,uo.prototype),this.reason=t.reason}}class _o extends yt{name="InternalServerException";$fault="server";$retryable={};reason;constructor(t){super({name:"InternalServerException",$fault:"server",...t});Object.setPrototypeOf(this,_o.prototype),this.reason=t.reason}}class lo extends yt{name="ThrottlingException";$fault="client";$retryable={throttling:!0};reason;constructor(t){super({name:"ThrottlingException",$fault:"client",...t});Object.setPrototypeOf(this,lo.prototype),this.reason=t.reason}}class wo extends yt{name="ValidationException";$fault="client";reason;constructor(t){super({name:"ValidationException",$fault:"client",...t});Object.setPrototypeOf(this,wo.prototype),this.reason=t.reason}}class Ao extends yt{name="ResourceNotFoundException";$fault="client";constructor(t){super({name:"ResourceNotFoundException",$fault:"client",...t});Object.setPrototypeOf(this,Ao.prototype)}}class Mo extends yt{name="ServiceUnavailableException";$fault="server";constructor(t){super({name:"ServiceUnavailableException",$fault:"server",...t});Object.setPrototypeOf(this,Mo.prototype)}}class go extends yt{name="ServiceQuotaExceededException";$fault="client";reason;constructor(t){super({name:"ServiceQuotaExceededException",$fault:"client",...t});Object.setPrototypeOf(this,go.prototype),this.reason=t.reason}}class Eo extends yt{name="DryRunOperationException";$fault="client";responseCode;constructor(t){super({name:"DryRunOperationException",$fault:"client",...t});Object.setPrototypeOf(this,Eo.prototype),this.responseCode=t.responseCode}}var V1=xh.TypeRegistry.for("smithy.ts.sdk.synthetic.com.amazon.aws.codewhisperer.streaming"),gW=[-3,"smithy.ts.sdk.synthetic.com.amazon.aws.codewhisperer.streaming","CodeWhispererStreamingServiceException",0,[],[]];V1.registerError(gW,yt);var ln=xh.TypeRegistry.for("com.amazon.aws.codewhisperer"),EW=[-3,"com.amazon.aws.codewhisperer","AccessDeniedException",{["error"]:"client",["httpError"]:403},["message","reason"],[0,0],1];ln.registerError(EW,ho);var dW=[-3,"com.amazon.aws.codewhisperer","ConflictException",{["error"]:"client",["httpError"]:409},["message","reason"],[0,0],1];ln.registerError(dW,uo);var RW=[-3,"com.amazon.aws.codewhisperer","DryRunOperationException",{["error"]:"client"},["message","responseCode"],[0,[1,32]]];ln.registerError(RW,Eo);var j1=[-3,"com.amazon.aws.codewhisperer","InternalServerException",{["error"]:"server",["httpError"]:500},["message","reason"],[0,0],1];ln.registerError(j1,_o);var bW=[-3,"com.amazon.aws.codewhisperer","ResourceNotFoundException",{["error"]:"client",["httpError"]:404},["message"],[0],1];ln.registerError(bW,Ao);var TW=[-3,"com.amazon.aws.codewhisperer","ServiceQuotaExceededException",{["error"]:"client",["httpError"]:402},["message","reason"],[0,0],1];ln.registerError(TW,go);var SW=[-3,"com.amazon.aws.codewhisperer","ServiceUnavailableException",{["error"]:"server",["httpError"]:503},["message"],[0],1];ln.registerError(SW,Mo);var $W=[-3,"com.amazon.aws.codewhisperer","ThrottlingException",{["error"]:"client",["httpError"]:429},["message","reason"],[0,0],1];ln.registerError($W,lo);var UW=[-3,"com.amazon.aws.codewhisperer","ValidationException",{["error"]:"client",["httpError"]:400},["message","reason"],[0,0],1];ln.registerError(UW,wo);var a1=[V1,ln];var qh=[0,"com.amazon.aws.codewhisperer","SensitiveDocument",8,15],F=[0,"com.amazon.aws.codewhisperer","SensitiveString",8,0],LW=[0,"com.amazon.aws.codewhisperer","ToolDescription",8,0],Ro=[0,"com.amazon.aws.codewhisperer","ToolName",8,0],j=[0,"com.amazon.aws.q","SensitiveString",8,0],IW=[3,"com.amazon.aws.codewhisperer","AdditionalContentEntry",0,["name","description","innerContext"],[[()=>F,0],[()=>F,0],[()=>F,0]],2],OW=[3,"com.amazon.aws.codewhisperer","AppStudioState",0,["namespace","propertyName","propertyContext","propertyValue"],[[()=>F,0],[()=>F,0],[()=>F,0],[()=>F,0]],3],yW=[3,"com.amazon.aws.codewhisperer","AssistantResponseEvent",0,["content","modelId"],[[()=>F,0],0],1],GW=[3,"com.amazon.aws.codewhisperer","AssistantResponseMessage",0,["content","messageId","supplementaryWebLinks","references","followupPrompt","toolUses","cachePoint","reasoningContent"],[[()=>F,0],0,[()=>cg,0],()=>fg,[()=>p1,0],[()=>c7,0],()=>Ch,[()=>H7,0]],1];var Ch=[3,"com.amazon.aws.codewhisperer","CachePoint",0,["type"],[0],1],BW=[3,"com.amazon.aws.codewhisperer","CitationEvent",0,["target","citationLink","citationText"],[()=>L7,[()=>F,0],[()=>F,0]],2],FW=[3,"com.amazon.aws.codewhisperer","ClientCacheConfig",0,["useClientCachingOnly"],[2]],HW=[3,"com.amazon.aws.codewhisperer","CodeDescription",0,["href"],[[()=>F,0]],1],PW=[3,"com.amazon.aws.codewhisperer","CodeEvent",0,["content"],[[()=>F,0]],1],NW=[3,"com.amazon.aws.codewhisperer","CodeReferenceEvent",0,["references"],[()=>fg]],WW=[3,"com.amazon.aws.codewhisperer","ConsoleState",0,["region","consoleUrl","serviceId","serviceConsolePage","serviceSubconsolePage","taskName","uxErrorMessage"],[0,[()=>F,0],0,0,0,[()=>F,0],[()=>F,0]]],DW=[3,"com.amazon.aws.codewhisperer","ContextUsageEvent",0,["contextUsagePercentage"],[1]],YW=[3,"com.amazon.aws.codewhisperer","ConversationState",0,["currentMessage","chatTriggerType","conversationId","workspaceId","history","customizationArn","agentContinuationId","agentTaskType"],[[()=>hg,0],0,0,0,[()=>pD,0],0,0,0],2],mW=[3,"com.amazon.aws.codewhisperer","DiagnosticLocation",0,["uri","range"],[[()=>F,0],()=>Kh],2],QW=[3,"com.amazon.aws.codewhisperer","DiagnosticRelatedInformation",0,["location","message"],[[()=>mW,0],[()=>F,0]],2],JW=[3,"com.amazon.aws.codewhisperer","DocumentBlock",0,["name","format","source"],[0,0,[()=>G7,0]],3],kW=[3,"com.amazon.aws.codewhisperer","DocumentCitationEvent",0,["source","title","location","sourceContent"],[[()=>F,0],[()=>F,0],[()=>y7,0],[()=>t7,0]]],XW=[3,"com.amazon.aws.codewhisperer","DocumentCitationSearchResultSpan",0,["searchResultIndex","start","end"],[1,1,1]],zW=[3,"com.amazon.aws.codewhisperer","DocumentCitationSourceContent",0,["text"],[[()=>F,0]]],Xh=[3,"com.amazon.aws.codewhisperer","DocumentCitationSpan",0,["documentIndex","start","end"],[1,1,1]],xW=[3,"com.amazon.aws.codewhisperer","DocumentCitationWebLocation",0,["url","domain"],[[()=>F,0],[()=>F,0]]],qW=[3,"com.amazon.aws.codewhisperer","DocumentSymbol",0,["name","type","source"],[0,0,0],2],CW=[3,"com.amazon.aws.codewhisperer","DryRunSucceedEvent",0,[],[]],KW=[3,"com.amazon.aws.codewhisperer","EditorState",0,["document","cursorState","relevantDocuments","useRelevantDocuments","workspaceFolders"],[[()=>tg,0],()=>I7,[()=>r7,0],2,[()=>h7,0]]],VW=[3,"com.amazon.aws.codewhisperer","EnvironmentVariable",0,["key","value"],[[()=>F,0],[()=>F,0]]],jW=[3,"com.amazon.aws.codewhisperer","EnvState",0,["operatingSystem","currentWorkingDirectory","environmentVariables","timezoneOffset"],[0,[()=>F,0],[()=>n7,0],1]],p1=[3,"com.amazon.aws.codewhisperer","FollowupPrompt",0,["content","userIntent"],[[()=>F,0],0],1],aW=[3,"com.amazon.aws.codewhisperer","FollowupPromptEvent",0,["followupPrompt"],[[()=>p1,0]]],pW=[3,"com.amazon.aws.codewhisperer","GitState",0,["status"],[[()=>F,0]]],ZW=[3,"com.amazon.aws.codewhisperer","ImageBlock",0,["format","source"],[0,[()=>B7,0]],2],vW=[3,"com.amazon.aws.codewhisperer","IntentsEvent",0,["intents"],[[()=>S7,0]]],tD=[3,"com.amazon.aws.codewhisperer","InvalidStateEvent",0,["reason","message"],[0,0],2],nD=[3,"com.amazon.aws.codewhisperer","MessageMetadataEvent",0,["conversationId","utteranceId"],[0,0]],sD=[3,"com.amazon.aws.codewhisperer","MetadataEvent",0,["tokenUsage"],[()=>SD]],rD=[3,"com.amazon.aws.codewhisperer","MeteringEvent",0,["usage","unit","unitPlural"],[1,0,0]],zh=[3,"com.amazon.aws.codewhisperer","Position",0,["line","character"],[1,1],2],Z1=[3,"com.amazon.aws.codewhisperer","ProgrammingLanguage",0,["languageName"],[0],1],Kh=[3,"com.amazon.aws.codewhisperer","Range",0,["start","end"],[()=>zh,()=>zh],2],iD=[3,"com.amazon.aws.codewhisperer","ReasoningContentEvent",8,["text","redactedContent","signature"],[[()=>F,0],21,[()=>F,0]]],eD=[3,"com.amazon.aws.codewhisperer","ReasoningText",8,["text","signature"],[[()=>F,0],[()=>F,0]],1],oD=[3,"com.amazon.aws.codewhisperer","Reference",0,["licenseName","repository","url","recommendationContentSpan"],[0,0,0,()=>v1]],fD=[3,"com.amazon.aws.codewhisperer","RelevantTextDocument",0,["relativeFilePath","programmingLanguage","text","documentSymbols","type"],[[()=>F,0],()=>Z1,[()=>F,0],()=>og,0],1],cD=[3,"com.amazon.aws.codewhisperer","RuntimeDiagnostic",0,["source","severity","message"],[[()=>F,0],0,[()=>F,0]],3],hD=[3,"com.amazon.aws.codewhisperer","ShellHistoryEntry",0,["command","directory","exitCode","stdout","stderr"],[[()=>F,0],[()=>F,0],1,[()=>F,0],[()=>F,0]],1],uD=[3,"com.amazon.aws.codewhisperer","ShellState",0,["shellName","shellHistory"],[0,[()=>i7,0]],1],v1=[3,"com.amazon.aws.codewhisperer","Span",0,["start","end"],[1,1]],_D=[3,"com.amazon.aws.codewhisperer","SupplementaryWebLink",0,["url","title","snippet"],[[()=>F,0],[()=>F,0],[()=>F,0]],2],lD=[3,"com.amazon.aws.codewhisperer","SupplementaryWebLinksEvent",0,["supplementaryWebLinks"],[[()=>cg,0]]],tg=[3,"com.amazon.aws.codewhisperer","TextDocument",0,["relativeFilePath","programmingLanguage","text","documentSymbols"],[[()=>F,0],()=>Z1,[()=>F,0],()=>og],1],wD=[3,"com.amazon.aws.codewhisperer","TextDocumentDiagnostic",0,["document","range","source","severity","message","code","codeDescription","tags","relatedInformation","data"],[[()=>tg,0],()=>Kh,[()=>F,0],0,[()=>F,0],[()=>F,0],[()=>HW,0],64,[()=>ZD,0],[()=>F,0]],5],AD=[3,"com.amazon.aws.codewhisperer","ToolInputSchema",0,["json"],[[()=>qh,0]]],ng=[3,"com.amazon.aws.codewhisperer","ToolResult",0,["toolUseId","content","status","toolName"],[0,[()=>e7,0],0,[()=>Ro,0]],2],MD=[3,"com.amazon.aws.codewhisperer","ToolResultEvent",0,["toolResult"],[[()=>ng,0]]],gD=[3,"com.amazon.aws.codewhisperer","ToolSpecification",0,["inputSchema","name","description"],[[()=>AD,0],[()=>Ro,0],[()=>LW,0]],2],ED=[3,"com.amazon.aws.codewhisperer","ToolUse",0,["toolUseId","name","input"],[0,[()=>Ro,0],[()=>qh,0]],3],dD=[3,"com.amazon.aws.codewhisperer","ToolUseEvent",0,["toolUseId","name","input","stop"],[0,[()=>Ro,0],[()=>F,0],2],2];var RD=[3,"com.amazon.aws.codewhisperer","UserInputMessage",0,["content","userInputMessageContext","userIntent","origin","images","documents","modelId","cachePoint","clientCacheConfig"],[[()=>F,0],[()=>bD,0],0,0,[()=>s7,0],[()=>vD,0],0,()=>Ch,()=>FW],1],bD=[3,"com.amazon.aws.codewhisperer","UserInputMessageContext",0,["editorState","shellState","gitState","envState","appStudioContext","diagnostic","consoleState","userSettings","additionalContext","toolResults","tools"],[[()=>KW,0],[()=>uD,0],[()=>pW,0],[()=>jW,0],[()=>OW,0],[()=>O7,0],[()=>WW,0],()=>TD,[()=>aD,0],[()=>o7,0],[()=>f7,0]]],TD=[3,"com.amazon.aws.codewhisperer","UserSettings",0,["hasConsentedToCrossRegionCalls"],[2]];var SD=[3,"com.amazon.aws.codewhisperer.internal","TokenUsage",0,["uncachedInputTokens","outputTokens","totalTokens","cacheReadInputTokens","cacheWriteInputTokens","contextUsagePercentage","normalizedTokenUsage"],[1,1,1,1,1,1,1],3];var $D=[3,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponseRequest",0,["conversationState","profileArn","agentMode","additionalModelRequestFields"],[[()=>YW,0],0,[0,{["httpHeader"]:"x-amzn-kiro-agent-mode"}],15],1],UD=[3,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponseResponse",0,["conversationId","generateAssistantResponseResponse"],[[0,{["httpHeader"]:"x-amzn-codewhisperer-conversation-id"}],[()=>U7,16]],2];var LD=[3,"com.amazon.aws.q","InteractionComponentsEvent",0,["interactionComponentEntries"],[[()=>w7,0]],1],Vh=[3,"com.amazon.aws.q.interactioncomponents","Action",0,["webLink","moduleLink"],[[()=>jD,0],[()=>WD,0]]],jh=[3,"com.amazon.aws.q.interactioncomponents","Alert",0,["type","content"],[0,[()=>u7,0]],2],ID=[3,"com.amazon.aws.q.interactioncomponents","AlertComponent",0,["text"],[[()=>Ai,0]]],OD=[3,"com.amazon.aws.q.interactioncomponents","Clarification",0,["questions","dismissible"],[[()=>l7,0],2],1],yD=[3,"com.amazon.aws.q.interactioncomponents","ClarificationAnswerOption",0,["label","value"],[[()=>j,0],[()=>j,0]],2],GD=[3,"com.amazon.aws.q.interactioncomponents","ClarificationQuestion",0,["question","options","allowCustom","skippable"],[[()=>j,0],[()=>_7,0],2,2],2],BD=[3,"com.amazon.aws.q.interactioncomponents","CloudWatchTroubleshootingLink",0,["label","investigationPayload","defaultText"],[[()=>j,0],[()=>j,0],[()=>j,0]],2],sg=[3,"com.amazon.aws.q.interactioncomponents","InfrastructureUpdate",0,["transition"],[[()=>FD,0]]],FD=[3,"com.amazon.aws.q.interactioncomponents","InfrastructureUpdateTransition",0,["currentState","nextState"],[[()=>j,0],[()=>j,0]],2],HD=[3,"com.amazon.aws.q.interactioncomponents","InlineArtifact",0,["dsl","summary","title","artifactLabel"],[[()=>j,0],[()=>j,0],[()=>j,0],[()=>j,0]],4],PD=[3,"com.amazon.aws.q.interactioncomponents","InteractionComponent",0,["text","alert","infrastructureUpdate","progress","step","taskDetails","taskReference","suggestions","section","resource","resourceList","action","clarification","inlineArtifact"],[[()=>Ai,0],[()=>jh,0],[()=>sg,0],[()=>rg,0],[()=>eg,0],[()=>CD,0],()=>VD,[()=>kD,0],[()=>YD,0],[()=>ah,0],[()=>ig,0],[()=>Vh,0],[()=>OD,0],[()=>HD,0]]],ND=[3,"com.amazon.aws.q.interactioncomponents","InteractionComponentEntry",0,["interactionComponent","interactionComponentId"],[[()=>PD,0],0],1],WD=[3,"com.amazon.aws.q.interactioncomponents","ModuleLink",0,["cloudWatchTroubleshootingLink"],[[()=>BD,0]]],rg=[3,"com.amazon.aws.q.interactioncomponents","Progress",0,["content"],[[()=>A7,0]],1],DD=[3,"com.amazon.aws.q.interactioncomponents","ProgressComponent",0,["step"],[[()=>eg,0]]],ah=[3,"com.amazon.aws.q.interactioncomponents","Resource",0,["title","link","description","type","ARN","resourceJsonString"],[[()=>j,0],[()=>j,0],[()=>j,0],[()=>j,0],[()=>j,0],[()=>j,0]],6],ig=[3,"com.amazon.aws.q.interactioncomponents","ResourceList",0,["items","action"],[[()=>M7,0],[()=>Vh,0]],1],YD=[3,"com.amazon.aws.q.interactioncomponents","Section",0,["title","content","action"],[[()=>j,0],[()=>g7,0],[()=>Vh,0]],2],mD=[3,"com.amazon.aws.q.interactioncomponents","SectionComponent",0,["text","alert","resource","resourceList"],[[()=>Ai,0],[()=>jh,0],[()=>ah,0],[()=>ig,0]]],eg=[3,"com.amazon.aws.q.interactioncomponents","Step",0,["id","state","label","content"],[1,0,[()=>j,0],[()=>E7,0]],3],QD=[3,"com.amazon.aws.q.interactioncomponents","StepComponent",0,["text"],[[()=>Ai,0]]],JD=[3,"com.amazon.aws.q.interactioncomponents","Suggestion",0,["value"],[[()=>j,0]],1],kD=[3,"com.amazon.aws.q.interactioncomponents","Suggestions",0,["items"],[[()=>d7,0]],1],XD=[3,"com.amazon.aws.q.interactioncomponents","TaskAction",0,["label","payload","note","primary","disabled","confirmation"],[[()=>j,0],[()=>$7,0],[()=>xD,0],2,2,[()=>zD,0]],2],zD=[3,"com.amazon.aws.q.interactioncomponents","TaskActionConfirmation",0,["content"],[[()=>j,0]]],xD=[3,"com.amazon.aws.q.interactioncomponents","TaskActionNote",0,["content","type"],[[()=>j,0],0],1],qD=[3,"com.amazon.aws.q.interactioncomponents","TaskComponent",0,["text","infrastructureUpdate","alert","progress"],[[()=>Ai,0],[()=>sg,0],[()=>jh,0],[()=>rg,0]]],CD=[3,"com.amazon.aws.q.interactioncomponents","TaskDetails",0,["overview","content","actions"],[[()=>KD,0],[()=>b7,0],[()=>R7,0]],2],KD=[3,"com.amazon.aws.q.interactioncomponents","TaskOverview",0,["label","description"],[[()=>j,0],[()=>j,0]],2],VD=[3,"com.amazon.aws.q.interactioncomponents","TaskReference",0,["taskId"],[0],1],Ai=[3,"com.amazon.aws.q.interactioncomponents","Text",0,["content"],[[()=>j,0]],1],jD=[3,"com.amazon.aws.q.interactioncomponents","WebLink",0,["label","url"],[[()=>j,0],[()=>j,0]],2];var aD=[1,"com.amazon.aws.codewhisperer","AdditionalContentList",0,[()=>IW,0]],pD=[1,"com.amazon.aws.codewhisperer","ChatHistory",0,[()=>hg,0]],ZD=[1,"com.amazon.aws.codewhisperer","DiagnosticRelatedInformationList",0,[()=>QW,0]];var vD=[1,"com.amazon.aws.codewhisperer","DocumentBlocks",0,[()=>JW,0]],t7=[1,"com.amazon.aws.codewhisperer","DocumentCitationSourceContents",0,[()=>zW,0]],og=[1,"com.amazon.aws.codewhisperer","DocumentSymbols",0,()=>qW],n7=[1,"com.amazon.aws.codewhisperer","EnvironmentVariables",0,[()=>VW,0]],s7=[1,"com.amazon.aws.codewhisperer","ImageBlocks",0,[()=>ZW,0]],fg=[1,"com.amazon.aws.codewhisperer","References",0,()=>oD],r7=[1,"com.amazon.aws.codewhisperer","RelevantDocumentList",0,[()=>fD,0]],i7=[1,"com.amazon.aws.codewhisperer","ShellHistory",0,[()=>hD,0]],cg=[1,"com.amazon.aws.codewhisperer","SupplementaryWebLinks",0,[()=>_D,0]],e7=[1,"com.amazon.aws.codewhisperer","ToolResultContent",0,[()=>N7,0]],o7=[1,"com.amazon.aws.codewhisperer","ToolResults",0,[()=>ng,0]],f7=[1,"com.amazon.aws.codewhisperer","Tools",0,[()=>P7,0]],c7=[1,"com.amazon.aws.codewhisperer","ToolUses",0,[()=>ED,0]],h7=[1,"com.amazon.aws.codewhisperer","WorkspaceFolderList",0,[()=>F,0]],u7=[1,"com.amazon.aws.q.interactioncomponents","AlertComponentList",0,[()=>ID,0]],_7=[1,"com.amazon.aws.q.interactioncomponents","ClarificationAnswerOptionsList",0,[()=>yD,0]],l7=[1,"com.amazon.aws.q.interactioncomponents","ClarificationQuestionList",0,[()=>GD,0]],w7=[1,"com.amazon.aws.q.interactioncomponents","InteractionComponentEntryList",0,[()=>ND,0]],A7=[1,"com.amazon.aws.q.interactioncomponents","ProgressComponentList",0,[()=>DD,0]],M7=[1,"com.amazon.aws.q.interactioncomponents","Resources",0,[()=>ah,0]],g7=[1,"com.amazon.aws.q.interactioncomponents","SectionComponentList",0,[()=>mD,0]],E7=[1,"com.amazon.aws.q.interactioncomponents","StepComponentList",0,[()=>QD,0]],d7=[1,"com.amazon.aws.q.interactioncomponents","SuggestionList",0,[()=>JD,0]],R7=[1,"com.amazon.aws.q.interactioncomponents","TaskActionList",0,[()=>XD,0]],b7=[1,"com.amazon.aws.q.interactioncomponents","TaskComponentList",0,[()=>qD,0]],T7=[2,"com.amazon.aws.codewhisperer","IntentData",8,0,()=>F7],S7=[2,"com.amazon.aws.codewhisperer","IntentMap",0,[0,0],[()=>T7,0]],$7=[2,"com.amazon.aws.q.interactioncomponents","TaskActionPayload",0,[0,0],[()=>j,0]],hg=[4,"com.amazon.aws.codewhisperer","ChatMessage",0,["userInputMessage","assistantResponseMessage"],[[()=>RD,0],[()=>GW,0]]],U7=[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"],[()=>nD,[()=>yW,0],[()=>iD,0],()=>CW,()=>NW,[()=>lD,0],[()=>aW,0],[()=>PW,0],[()=>vW,0],[()=>LD,0],[()=>dD,0],[()=>MD,0],()=>sD,()=>rD,()=>DW,[()=>BW,0],[()=>kW,0],()=>tD,[()=>j1,0]]],L7=[4,"com.amazon.aws.codewhisperer","CitationTarget",0,["location","range"],[1,()=>v1]],I7=[4,"com.amazon.aws.codewhisperer","CursorState",0,["position","range"],[()=>zh,()=>Kh]],O7=[4,"com.amazon.aws.codewhisperer","Diagnostic",0,["textDocumentDiagnostic","runtimeDiagnostic"],[[()=>wD,0],[()=>cD,0]]],y7=[4,"com.amazon.aws.codewhisperer","DocumentCitationLocation",0,["documentPage","documentChar","documentChunk","searchResult","web"],[()=>Xh,()=>Xh,()=>Xh,()=>XW,[()=>xW,0]]],G7=[4,"com.amazon.aws.codewhisperer","DocumentSource",8,["bytes"],[21]];var B7=[4,"com.amazon.aws.codewhisperer","ImageSource",8,["bytes"],[21]],F7=[4,"com.amazon.aws.codewhisperer","IntentDataType",0,["string"],[0]],H7=[4,"com.amazon.aws.codewhisperer","ReasoningContent",8,["reasoningText","redactedContent"],[[()=>eD,0],21]];var P7=[4,"com.amazon.aws.codewhisperer","Tool",0,["toolSpecification","cachePoint"],[[()=>gD,0],()=>Ch]],N7=[4,"com.amazon.aws.codewhisperer","ToolResultContentBlock",0,["text","json"],[[()=>F,0],[()=>qh,0]]];var ug=[9,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponse",{["http"]:["POST","/generateAssistantResponse",200]},()=>$D,()=>UD];var wg=(t)=>{return{apiVersion:"2023-11-27",base64Decoder:t?.base64Decoder??hr.fromBase64,base64Encoder:t?.base64Encoder??hr.toBase64,disableHostPrefix:t?.disableHostPrefix??!1,endpointProvider:t?.endpointProvider??K1,extensions:t?.extensions??[],httpAuthSchemeProvider:t?.httpAuthSchemeProvider??MA,httpAuthSchemes:t?.httpAuthSchemes??[{schemeId:"smithy.api#httpBearerAuth",identityProvider:(n)=>n.getIdentityProvider("smithy.api#httpBearerAuth"),signer:new lg.HttpBearerAuthSigner}],logger:t?.logger??new z.NoOpLogger,protocol:t?.protocol??_g.AwsRestJsonProtocol,protocolSettings:t?.protocolSettings??{defaultNamespace:"com.amazon.aws.codewhisperer.streaming",errorTypeRegistries:a1,version:"2023-11-27",serviceTarget:"AmazonCodeWhispererStreamingService"},serviceId:t?.serviceId??"CodeWhispererStreaming",urlParser:t?.urlParser??Qh.parseUrl,utf8Decoder:t?.utf8Decoder??gs.fromUtf8,utf8Encoder:t?.utf8Encoder??gs.toUtf8}};var Eg=(t)=>{z.emitWarningIfUnsupportedVersion(process.version);let n=mh.resolveDefaultsModeConfig(t),s=()=>n().then(z.loadConfigsForDefaultMode),r=wg(t);Ag.emitWarningIfUnsupportedVersion(process.version);let i={profile:t?.profile,logger:r.logger};return{...r,...t,runtime:"node",defaultsMode:n,authSchemePreference:t?.authSchemePreference??Ln.loadConfig(Mg.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS,i),bodyLengthChecker:t?.bodyLengthChecker??Yh.calculateBodyLength,defaultUserAgentProvider:t?.defaultUserAgentProvider??_n.createDefaultUserAgentProvider({serviceId:r.serviceId,clientVersion:RA.version}),eventStreamSerdeProvider:t?.eventStreamSerdeProvider??oo.eventStreamSerdeProvider,httpAuthSchemes:t?.httpAuthSchemes??[{schemeId:"smithy.api#httpBearerAuth",identityProvider:(e)=>e.getIdentityProvider("smithy.api#httpBearerAuth")||(async(f)=>{return await Wh(f)(f)}),signer:new gg.HttpBearerAuthSigner}],maxAttempts:t?.maxAttempts??Ln.loadConfig(v.NODE_MAX_ATTEMPT_CONFIG_OPTIONS,t),region:t?.region??Ln.loadConfig(p.NODE_REGION_CONFIG_OPTIONS,{...p.NODE_REGION_CONFIG_FILE_OPTIONS,...i}),requestHandler:bo.NodeHttpHandler.create(t?.requestHandler??s),retryMode:t?.retryMode??Ln.loadConfig({...v.NODE_RETRY_MODE_CONFIG_OPTIONS,default:async()=>(await s()).retryMode||ht.DEFAULT_RETRY_MODE},t),sha256:t?.sha256??Dh.Hash.bind(null,"sha256"),streamCollector:t?.streamCollector??bo.streamCollector,useDualstackEndpoint:t?.useDualstackEndpoint??Ln.loadConfig(p.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS,i),useFipsEndpoint:t?.useFipsEndpoint??Ln.loadConfig(p.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS,i),userAgentAppId:t?.userAgentAppId??Ln.loadConfig(_n.NODE_APP_ID_CONFIG_OPTIONS,i)}};var Pt=Y(xt(),1);var Gt=Y(Ut(),1);var dg=(t)=>{let{httpAuthSchemes:n,httpAuthSchemeProvider:s,token:r}=t;return{setHttpAuthScheme(i){let e=n.findIndex((f)=>f.schemeId===i.schemeId);if(e===-1)n.push(i);else n.splice(e,1,i)},httpAuthSchemes(){return n},setHttpAuthSchemeProvider(i){s=i},httpAuthSchemeProvider(){return s},setToken(i){r=i},token(){return r}}},Rg=(t)=>{return{httpAuthSchemes:t.httpAuthSchemes(),httpAuthSchemeProvider:t.httpAuthSchemeProvider(),token:t.token()}};var bg=(t,n)=>{let s=Object.assign(Pt.getAwsRegionExtensionConfiguration(t),z.getDefaultExtensionConfiguration(t),Gt.getHttpHandlerExtensionConfiguration(t),dg(t));return n.forEach((r)=>r.configure(s)),Object.assign(t,Pt.resolveAwsRegionExtensionConfiguration(s),z.resolveDefaultRuntimeConfig(s),Gt.resolveHttpHandlerRuntimeConfig(s),Rg(s))};class ph extends z.Client{config;constructor(...[t]){let n=Eg(t||{});super(n);this.initConfig=n;let s=EA(n),r=Un.resolveUserAgentConfig(s),i=v.resolveRetryConfig(r),e=p.resolveRegionConfig(i),f=Xn.resolveHostHeaderConfig(e),o=Nt.resolveEndpointConfig(f),c=Ht.resolveDefaultAwsRegionalEndpointsConfig(o),h=Dc.resolveEventStreamSerdeConfig(c),u=gA(h),_=bg(u,t?.extensions||[]);this.config=_,this.middlewareStack.use(Tg.getSchemaSerdePlugin(this.config)),this.middlewareStack.use(Un.getUserAgentPlugin(this.config)),this.middlewareStack.use(v.getRetryPlugin(this.config)),this.middlewareStack.use(ri.getContentLengthPlugin(this.config)),this.middlewareStack.use(Xn.getHostHeaderPlugin(this.config)),this.middlewareStack.use(ni.getLoggerPlugin(this.config)),this.middlewareStack.use(si.getRecursionDetectionPlugin(this.config)),this.middlewareStack.use(_r.getHttpAuthSchemeEndpointRuleSetPlugin(this.config,{httpAuthSchemeParametersProvider:AA,identityProviderConfigProvider:async(l)=>new _r.DefaultIdentityProviderConfig({"smithy.api#httpBearerAuth":l.token})})),this.middlewareStack.use(_r.getHttpSigningPlugin(this.config))}destroy(){super.destroy()}}class Zh extends z.Command.classBuilder().ep(dA).m(function(t,n,s,r){return[Nt.getEndpointPlugin(s,t.getEndpointParameterInstructions())]}).s("AmazonCodeWhispererStreamingService","GenerateAssistantResponse",{eventStream:{output:!0}}).n("CodeWhispererStreamingClient","GenerateAssistantResponseCommand").sc(ug).build(){}function Sg(t){let n=yr[t];if(!n)throw Error(`Unsupported model: ${t}. Supported models: ${nu.join(", ")}`);return n}var $g=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"]),Ug=["low","medium","high","xhigh","max"];function To(t){for(let n of Ug){let s=`-${n}`;if(t.endsWith(s)){let r=t.slice(0,-s.length);if($g.has(r))return{wireId:Sg(r),effort:n}}}return{wireId:Sg(t),effort:void 0}}function W7(t){for(let n of Ug){let s=`-${n}`;if(t.endsWith(s)){let r=t.slice(0,-s.length);if($g.has(r))return r}}if(t.endsWith("-thinking")){let n=t.slice(0,-9);if(yr[n])return n}return t}function Lg(t){return B(W7(t))}var D7=["low","medium","high","xhigh","max"];function Y7(t){return typeof t==="string"&&D7.some((n)=>n===t)}var Ig=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"]),Og=new Set(["claude-opus-4.7","claude-opus-4.8","claude-sonnet-5",...Ig]),m7=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",...Og]);function So(t){return m7.has(t)}function Q7(t){return Og.has(t)}function yg(t,n){if(Ig.has(t))return{reasoning:{effort:n}};return{output_config:{effort:n}}}function J7(t,n){if(!So(t))return;if(n==="xhigh"&&!Q7(t))return"max";return n}function k7(t,n){if(!So(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 Gg(t){let n;if(So(t.model))n={wireId:t.model,effort:void 0};else try{n=To(t.model)}catch(r){if(r instanceof Error&&r.message.startsWith("Unsupported model:"))return;throw r}if(!So(n.wireId))return;let s=[n.effort,t.reasoningEffort,t.configEffort];for(let r of s)if(Y7(r))return J7(n.wireId,r);if(!t.think)return;if(t.autoEffortMapping??!0)return k7(t.budget,n.wireId);return"medium"}import{randomUUID as K7}from"crypto";function Mi(t){return typeof t==="object"&&t!==null}function X7(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 z7(t){let n=[];for(let s of t){if(!Mi(s)||s.type!=="image"||!Mi(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 x7(t){let n=[];for(let s of t){if(!Mi(s)||s.type!=="image_url"||!Mi(s.image_url))continue;let r=s.image_url.url;if(typeof r!=="string"||!r.startsWith("data:"))continue;let[i="",e]=r.split(",",2);if(!e)continue;let f=i.split(";")[0]?.replace("data:","");n.push({mediaType:f||"image/jpeg",data:e})}return n}function $o(t){if(!Array.isArray(t))return[];return[...z7(t),...x7(t)]}function Uo(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:X7(r.data)}})),omitted:t.length-n.length}}function Lo(t){let n=[];for(let s of t){if(!Mi(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 vh(t){return typeof t==="object"&&t!==null}function Bg(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(vh(r)&&r.type==="tool_use"&&r.id===n)return r}}return null}function Fg(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
|
-
|
|
190
|
+
`).run(n,Date.now(),s)})}clearRemovedAccount(n){this.withImmediateTransaction(()=>this.clearRemovedAccountInternal(n))}getSessionAffinity(n,t=Date.now()){let i=this.db.query(`
|
|
191
|
+
SELECT * FROM session_affinity
|
|
192
|
+
WHERE key_hash = ? AND expires_at > ?
|
|
193
|
+
`).get(n,t);return i===null?void 0:Dh(i)}claimSessionAffinity(n,t,i,s,r,e){return this.withImmediateTransaction(()=>{this.db.query("DELETE FROM session_affinity WHERE key_hash = ? AND expires_at <= ?").run(n,s),this.db.query(`
|
|
194
|
+
INSERT OR IGNORE INTO session_affinity (
|
|
195
|
+
key_hash, account_id, conversation_id, created_at, last_seen, expires_at
|
|
196
|
+
) VALUES (?, ?, ?, ?, ?, ?)
|
|
197
|
+
`).run(n,t,i,s,s,s+r),this.db.query(`
|
|
198
|
+
UPDATE session_affinity
|
|
199
|
+
SET last_seen = ?, expires_at = ?
|
|
200
|
+
WHERE key_hash = ?
|
|
201
|
+
`).run(s,s+r,n),this.pruneSessionAffinitiesInternal(s,e,n);let f=this.selectSessionAffinity(n);if(f===void 0)throw TypeError("Session affinity claim did not persist");return Dh(f)})}rebindSessionAffinity(n,t,i,s,r,e){return this.withImmediateTransaction(()=>{this.db.query(`
|
|
202
|
+
INSERT INTO session_affinity (
|
|
203
|
+
key_hash, account_id, conversation_id, created_at, last_seen, expires_at
|
|
204
|
+
) VALUES (?, ?, ?, ?, ?, ?)
|
|
205
|
+
ON CONFLICT(key_hash) DO UPDATE SET
|
|
206
|
+
account_id = excluded.account_id,
|
|
207
|
+
conversation_id = excluded.conversation_id,
|
|
208
|
+
created_at = excluded.created_at,
|
|
209
|
+
last_seen = excluded.last_seen,
|
|
210
|
+
expires_at = excluded.expires_at
|
|
211
|
+
`).run(n,t,i,s,s,s+r),this.pruneSessionAffinitiesInternal(s,e,n);let f=this.selectSessionAffinity(n);if(f===void 0)throw TypeError("Session affinity rebind did not persist");return Dh(f)})}pruneSessionAffinities(n=Date.now(),t=1e4){return this.withImmediateTransaction(()=>this.pruneSessionAffinitiesInternal(n,t))}close(){this.db.close()}clearRemovedAccountInternal(n){this.db.query("DELETE FROM removed_accounts WHERE id = ?").run(n)}selectSessionAffinity(n){let t=this.db.query("SELECT * FROM session_affinity WHERE key_hash = ?").get(n);return t===null?void 0:t}pruneSessionAffinitiesInternal(n,t,i){let s=this.db.query("DELETE FROM session_affinity WHERE expires_at <= ?").run(n).changes,r=this.db.query("SELECT COUNT(*) AS count FROM session_affinity").get(),e=Math.max(0,(r?.count??0)-t);if(e>0){let f=i?this.db.query(`
|
|
212
|
+
DELETE FROM session_affinity
|
|
213
|
+
WHERE key_hash IN (
|
|
214
|
+
SELECT key_hash FROM session_affinity
|
|
215
|
+
WHERE key_hash != ?
|
|
216
|
+
ORDER BY last_seen ASC, key_hash ASC
|
|
217
|
+
LIMIT ?
|
|
218
|
+
)
|
|
219
|
+
`):this.db.query(`
|
|
220
|
+
DELETE FROM session_affinity
|
|
221
|
+
WHERE key_hash IN (
|
|
222
|
+
SELECT key_hash FROM session_affinity
|
|
223
|
+
ORDER BY last_seen ASC, key_hash ASC
|
|
224
|
+
LIMIT ?
|
|
225
|
+
)
|
|
226
|
+
`);s+=(i?f.run(i,e):f.run(e)).changes}return s}withImmediateTransaction(n){this.db.exec("BEGIN IMMEDIATE");try{let t=n();return this.db.exec("COMMIT"),t}catch(t){throw this.db.exec("ROLLBACK"),t}finally{this.tightenPermissions()}}tightenPermissions(){if(this.path===":memory:")return;for(let n of[this.path,`${this.path}-wal`,`${this.path}-shm`])if(fg(n))og(n,384)}}import{randomUUID as _g}from"crypto";function gn(n,t,i){return Response.json({type:"error",error:{type:i,message:t},request_id:`req_${_g()}`},{status:n})}function Iw(n,t){return`event: error
|
|
227
|
+
data: ${JSON.stringify({type:"error",error:{type:t,message:n}})}
|
|
110
228
|
|
|
111
|
-
[system: tool calling continues]`:"[system: tool calling continues]",toolUses:c.assistantResponseMessage?.toolUses}})}else n.push(c);n.push(h)}s=e}else{if(r)n.push(r);s++}}return n}function Ng(t,n){let s=[];for(let r=0;r<t.length-1;r++){let i=t[r];if(!i)continue;if(i.role==="user"){let h={content:"",modelId:n,origin:ot.ORIGIN_AI_EDITOR},u=[];if(Array.isArray(i.content)){h.content=Lo(i.content);for(let l of i.content){if(!Pg(l)||l.type!=="tool_result"||typeof l.tool_use_id!=="string")continue;u.push({content:[{text:Bt(l.content??l)}],status:"success",toolUseId:l.tool_use_id})}let _=$o(i.content);if(_.length>0){let l=Uo(_);if(h.images=l.images,l.omitted>0)h.content+=`
|
|
229
|
+
`}import{createHash as wg,timingSafeEqual as lg}from"crypto";function v(n,t,i,s){let r={message:t,type:i};if(s!==void 0)r.code=s;return new Response(JSON.stringify({error:r}),{status:n,headers:{"Content-Type":"application/json"}})}var Uw="Bearer ";function bw(n,t){let i=Buffer.from(n);for(let s of t){let r=Buffer.from(s);if(i.byteLength===r.byteLength&&lg(i,r))return s}return}function $w(n){return wg("sha256").update("kiro-provider-tenant-v1\x00").update(n).digest("hex")}function Yh(n,t,i=v){let s=n.headers.get("Authorization");if(s===null){let f=n.headers.get("x-api-key"),o=f===null?void 0:bw(f,t);if(o!==void 0)return{ok:!0,tenantId:$w(o)};return{ok:!1,response:i(401,"Missing Authorization or x-api-key header.","authentication_error","missing_api_key")}}if(!s.startsWith(Uw))return{ok:!1,response:i(401,"Authorization header must use the Bearer scheme.","authentication_error","invalid_api_key")};let r=s.slice(Uw.length),e=bw(r,t);if(e===void 0)return{ok:!1,response:i(401,"Incorrect API key provided.","authentication_error","invalid_api_key")};return{ok:!0,tenantId:$w(e)}}var wi=Q(ct(),1);var ne=Q(ct(),1);var te=Q(ct(),1);var Kt=Q(ct(),1);var jn=Q(ct(),1);var hn=Q(Yn(),1);var ps=Q(_i(),1),zE=Q(ri(),1);var Mc=Q($o(),1);var ie=Q(Jn(),1);var Zn=Q(Ji(),1);var un=Q(Zr(),1);var V=Q(Xt(),1);var Qs=Q(_i(),1);var zs=Q(Xt(),1);var Fd=async(n,t,i)=>{return{operation:zs.getSmithyContext(t).operation}};function qH(n){return{schemeId:"smithy.api#httpBearerAuth",propertiesExtractor:({profile:t,filepath:i,configFilepath:s,ignoreCache:r},e)=>({identityProperties:{profile:t,filepath:i,configFilepath:s,ignoreCache:r}})}}var Pd=(n)=>{let t=[];switch(n.operation){default:t.push(qH(n))}return t},Dd=(n)=>{let t=Qs.memoizeIdentityProvider(n.token,Qs.isIdentityExpired,Qs.doesIdentityRequireRefresh);return Object.assign(n,{authSchemePreference:zs.normalizeProvider(n.authSchemePreference??[]),token:t})};var Yd=(n)=>{return Object.assign(n,{useDualstackEndpoint:n.useDualstackEndpoint??!1,useFipsEndpoint:n.useFipsEndpoint??!1,defaultSigningName:"amazoncodewhispererstreamingservice"})},md={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}};var Jd={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 FE=Q(ct(),1),PE=Q(Oc(),1);var as=Q(Yn(),1);var zn=Q(Yn(),1);var U1=300000,xs="To refresh this SSO session run 'aws sso login' with the corresponding profile.";var pR=async(n,t={},i)=>{let{SSOOIDCClient:s}=await Promise.resolve().then(() => Q(w_(),1)),r=(f)=>t.clientConfig?.[f]??t.parentClientConfig?.[f]??i?.[f];return new s(Object.assign({},t.clientConfig??{},{region:n??t.clientConfig?.region,logger:r("logger"),userAgentAppId:r("userAgentAppId")}))};var nE=async(n,t,i={},s)=>{let{CreateTokenCommand:r}=await Promise.resolve().then(() => Q(w_(),1));return(await pR(t,i,s)).send(new r({clientId:n.clientId,clientSecret:n.clientSecret,refreshToken:n.refreshToken,grantType:"refresh_token"}))};var tE=Q(Yn(),1);var l_=(n)=>{if(n.expiration&&n.expiration.getTime()<Date.now())throw new tE.TokenProviderError(`Token is expired. ${xs}`,!1)};var iE=Q(Yn(),1);var Mi=(n,t,i=!1)=>{if(typeof t>"u")throw new iE.TokenProviderError(`Value not present for '${n}' in SSO Token${i?". Cannot refresh":""}. ${xs}`,!1)};var sE=Q(Yn(),1);import{promises as EY}from"fs";var{writeFile:yY}=EY,rE=(n,t)=>{let i=sE.getSSOTokenFilepath(n),s=JSON.stringify(t,null,2);return yY(i,s)};var eE=new Date(0),oE=(n={})=>async({callerClientConfig:t}={})=>{n.logger?.debug("@aws-sdk/token-providers - fromSso");let i=await zn.parseKnownFiles(n),s=zn.getProfileName({profile:n.profile??t?.profile}),r=i[s];if(!r)throw new zn.TokenProviderError(`Profile '${s}' could not be found in shared credentials file.`,!1);else if(!r.sso_session)throw new zn.TokenProviderError(`Profile '${s}' is missing required property 'sso_session'.`);let e=r.sso_session,o=(await zn.loadSsoSessionData(n))[e];if(!o)throw new zn.TokenProviderError(`Sso session '${e}' could not be found in shared credentials file.`,!1);for(let A of["sso_start_url","sso_region"])if(!o[A])throw new zn.TokenProviderError(`Sso session '${e}' is missing required property '${A}'.`,!1);let{sso_start_url:h,sso_region:u}=o,c;try{c=await zn.getSSOTokenFromFile(e)}catch(A){throw new zn.TokenProviderError(`The SSO session token associated with profile=${s} was not found or is invalid. ${xs}`,!1)}Mi("accessToken",c.accessToken),Mi("expiresAt",c.expiresAt);let{accessToken:_,expiresAt:w}=c,l={token:_,expiration:new Date(w)};if(l.expiration.getTime()-Date.now()>U1)return l;if(Date.now()-eE.getTime()<30000)return l_(l),l;Mi("clientId",c.clientId,!0),Mi("clientSecret",c.clientSecret,!0),Mi("refreshToken",c.refreshToken,!0);try{eE.setTime(Date.now());let A=await nE(c,u,n,t);Mi("accessToken",A.accessToken),Mi("expiresIn",A.expiresIn);let d=new Date(Date.now()+A.expiresIn*1000);try{await rE(e,{...c,accessToken:A.accessToken,expiresAt:d.toISOString(),refreshToken:A.refreshToken})}catch(E){}return{token:A.accessToken,expiration:d}}catch(A){return l_(l),l}};var A_=(n={})=>as.memoize(as.chain(oE(n),async()=>{throw new as.TokenProviderError("Could not load token from any providers",!1)}),(t)=>t.expiration!==void 0&&t.expiration.getTime()-Date.now()<300000,(t)=>t.expiration!==void 0);var Gt=Q(ct(),1);var DE=Q(_i(),1);var Ef=Q($o(),1);var M_=Q(mn(),1);var kt=Q(Yn(),1);var Gf=Q(jo(),1);var d_=Q(mn(),1);var R_=Q(Yn(),1);var Sn=Q(Zr(),1);var GE=Q(o_(),1),HE=Q(_i(),1);var E_=Q(Jn(),1);var vs=Q(mn(),1);var Vi=Q(mn(),1);var Hn=Q(Ji(),1);var we="ref",ji=-1,yf=!0,fE="isSet",_E="PartitionResult",Tf="booleanEquals",y_="getAttr",hE={[we]:"Endpoint"},T_={[we]:_E},Zs={},uE=[{[we]:"Region"}],cE={conditions:[[fE,[hE]],[fE,uE],["aws.partition",uE,_E],[Tf,[{[we]:"UseFIPS"},yf]],[Tf,[{[we]:"UseDualStack"},yf]],[Tf,[{fn:y_,argv:[T_,"supportsDualStack"]},yf]],[Tf,[{fn:y_,argv:[T_,"supportsFIPS"]},yf]],["stringEquals",[{fn:y_,argv:[T_,"name"]},"aws-us-gov"]]],results:[[ji],[ji,"Invalid Configuration: FIPS and custom endpoint are not supported"],[ji,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[hE,Zs],["https://amazoncodewhispererstreamingservice-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",Zs],[ji,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://amazoncodewhispererstreamingservice.{Region}.amazonaws.com",Zs],["https://amazoncodewhispererstreamingservice-fips.{Region}.{PartitionResult#dnsSuffix}",Zs],[ji,"FIPS is enabled but this partition does not support FIPS"],["https://amazoncodewhispererstreamingservice.{Region}.{PartitionResult#dualStackDnsSuffix}",Zs],[ji,"DualStack is enabled but this partition does not support DualStack"],["https://amazoncodewhispererstreamingservice.{Region}.{PartitionResult#dnsSuffix}",Zs],[ji,"Invalid Configuration: Missing Region"]]},TY=2,Qn=1e8,gY=new Int32Array([-1,1,-1,0,13,3,1,4,Qn+12,2,5,Qn+12,3,8,6,4,7,Qn+11,5,Qn+9,Qn+10,4,11,9,6,10,Qn+8,7,Qn+6,Qn+7,5,12,Qn+5,6,Qn+4,Qn+5,3,Qn+1,14,4,Qn+2,Qn+3]),wE=Hn.BinaryDecisionDiagram.from(gY,TY,cE.conditions,cE.results);var SY=new Hn.EndpointCache({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),lE=(n,t={})=>{return SY.get(n,()=>Hn.decideEndpoint(wE,{endpointParams:n,logger:t.logger}))};Hn.customEndpointFunctions.aws=jn.awsEndpointFunctions;var I_=Q(ri(),1);class Cn extends V.ServiceException{constructor(n){super(n);Object.setPrototypeOf(this,Cn.prototype)}}class gf extends Cn{name="AccessDeniedException";$fault="client";reason;constructor(n){super({name:"AccessDeniedException",$fault:"client",...n});Object.setPrototypeOf(this,gf.prototype),this.reason=n.reason}}class Sf extends Cn{name="ConflictException";$fault="client";reason;constructor(n){super({name:"ConflictException",$fault:"client",...n});Object.setPrototypeOf(this,Sf.prototype),this.reason=n.reason}}class If extends Cn{name="InternalServerException";$fault="server";$retryable={};reason;constructor(n){super({name:"InternalServerException",$fault:"server",...n});Object.setPrototypeOf(this,If.prototype),this.reason=n.reason}}class Uf extends Cn{name="ThrottlingException";$fault="client";$retryable={throttling:!0};reason;constructor(n){super({name:"ThrottlingException",$fault:"client",...n});Object.setPrototypeOf(this,Uf.prototype),this.reason=n.reason}}class bf extends Cn{name="ValidationException";$fault="client";reason;constructor(n){super({name:"ValidationException",$fault:"client",...n});Object.setPrototypeOf(this,bf.prototype),this.reason=n.reason}}class $f extends Cn{name="ResourceNotFoundException";$fault="client";constructor(n){super({name:"ResourceNotFoundException",$fault:"client",...n});Object.setPrototypeOf(this,$f.prototype)}}class Lf extends Cn{name="ServiceUnavailableException";$fault="server";constructor(n){super({name:"ServiceUnavailableException",$fault:"server",...n});Object.setPrototypeOf(this,Lf.prototype)}}class Of extends Cn{name="ServiceQuotaExceededException";$fault="client";reason;constructor(n){super({name:"ServiceQuotaExceededException",$fault:"client",...n});Object.setPrototypeOf(this,Of.prototype),this.reason=n.reason}}class Bf extends Cn{name="DryRunOperationException";$fault="client";responseCode;constructor(n){super({name:"DryRunOperationException",$fault:"client",...n});Object.setPrototypeOf(this,Bf.prototype),this.responseCode=n.responseCode}}var AE=I_.TypeRegistry.for("smithy.ts.sdk.synthetic.com.amazon.aws.codewhisperer.streaming"),IY=[-3,"smithy.ts.sdk.synthetic.com.amazon.aws.codewhisperer.streaming","CodeWhispererStreamingServiceException",0,[],[]];AE.registerError(IY,Cn);var Ht=I_.TypeRegistry.for("com.amazon.aws.codewhisperer"),UY=[-3,"com.amazon.aws.codewhisperer","AccessDeniedException",{["error"]:"client",["httpError"]:403},["message","reason"],[0,0],1];Ht.registerError(UY,gf);var bY=[-3,"com.amazon.aws.codewhisperer","ConflictException",{["error"]:"client",["httpError"]:409},["message","reason"],[0,0],1];Ht.registerError(bY,Sf);var $Y=[-3,"com.amazon.aws.codewhisperer","DryRunOperationException",{["error"]:"client"},["message","responseCode"],[0,[1,32]]];Ht.registerError($Y,Bf);var ME=[-3,"com.amazon.aws.codewhisperer","InternalServerException",{["error"]:"server",["httpError"]:500},["message","reason"],[0,0],1];Ht.registerError(ME,If);var LY=[-3,"com.amazon.aws.codewhisperer","ResourceNotFoundException",{["error"]:"client",["httpError"]:404},["message"],[0],1];Ht.registerError(LY,$f);var OY=[-3,"com.amazon.aws.codewhisperer","ServiceQuotaExceededException",{["error"]:"client",["httpError"]:402},["message","reason"],[0,0],1];Ht.registerError(OY,Of);var BY=[-3,"com.amazon.aws.codewhisperer","ServiceUnavailableException",{["error"]:"server",["httpError"]:503},["message"],[0],1];Ht.registerError(BY,Lf);var NY=[-3,"com.amazon.aws.codewhisperer","ThrottlingException",{["error"]:"client",["httpError"]:429},["message","reason"],[0,0],1];Ht.registerError(NY,Uf);var GY=[-3,"com.amazon.aws.codewhisperer","ValidationException",{["error"]:"client",["httpError"]:400},["message","reason"],[0,0],1];Ht.registerError(GY,bf);var dE=[AE,Ht];var U_=[0,"com.amazon.aws.codewhisperer","SensitiveDocument",8,15],Y=[0,"com.amazon.aws.codewhisperer","SensitiveString",8,0],HY=[0,"com.amazon.aws.codewhisperer","ToolDescription",8,0],Nf=[0,"com.amazon.aws.codewhisperer","ToolName",8,0],rn=[0,"com.amazon.aws.q","SensitiveString",8,0],WY=[3,"com.amazon.aws.codewhisperer","AdditionalContentEntry",0,["name","description","innerContext"],[[()=>Y,0],[()=>Y,0],[()=>Y,0]],2],FY=[3,"com.amazon.aws.codewhisperer","AppStudioState",0,["namespace","propertyName","propertyContext","propertyValue"],[[()=>Y,0],[()=>Y,0],[()=>Y,0],[()=>Y,0]],3],PY=[3,"com.amazon.aws.codewhisperer","AssistantResponseEvent",0,["content","modelId"],[[()=>Y,0],0],1],DY=[3,"com.amazon.aws.codewhisperer","AssistantResponseMessage",0,["content","messageId","supplementaryWebLinks","references","followupPrompt","toolUses","cachePoint","reasoningContent"],[[()=>Y,0],0,[()=>OE,0],()=>LE,[()=>RE,0],[()=>MJ,0],()=>b_,[()=>JJ,0]],1];var b_=[3,"com.amazon.aws.codewhisperer","CachePoint",0,["type"],[0],1],YY=[3,"com.amazon.aws.codewhisperer","CitationEvent",0,["target","citationLink","citationText"],[()=>HJ,[()=>Y,0],[()=>Y,0]],2],mY=[3,"com.amazon.aws.codewhisperer","ClientCacheConfig",0,["useClientCachingOnly"],[2]],JY=[3,"com.amazon.aws.codewhisperer","CodeDescription",0,["href"],[[()=>Y,0]],1],XY=[3,"com.amazon.aws.codewhisperer","CodeEvent",0,["content"],[[()=>Y,0]],1],zY=[3,"com.amazon.aws.codewhisperer","CodeReferenceEvent",0,["references"],[()=>LE]],QY=[3,"com.amazon.aws.codewhisperer","ConsoleState",0,["region","consoleUrl","serviceId","serviceConsolePage","serviceSubconsolePage","taskName","uxErrorMessage"],[0,[()=>Y,0],0,0,0,[()=>Y,0],[()=>Y,0]]],CY=[3,"com.amazon.aws.codewhisperer","ContextUsageEvent",0,["contextUsagePercentage"],[1]],xY=[3,"com.amazon.aws.codewhisperer","ConversationState",0,["currentMessage","chatTriggerType","conversationId","workspaceId","history","customizationArn","agentContinuationId","agentTaskType"],[[()=>BE,0],0,0,0,[()=>rJ,0],0,0,0],2],KY=[3,"com.amazon.aws.codewhisperer","DiagnosticLocation",0,["uri","range"],[[()=>Y,0],()=>$_],2],kY=[3,"com.amazon.aws.codewhisperer","DiagnosticRelatedInformation",0,["location","message"],[[()=>KY,0],[()=>Y,0]],2],qY=[3,"com.amazon.aws.codewhisperer","DocumentBlock",0,["name","format","source"],[0,0,[()=>DJ,0]],3],VY=[3,"com.amazon.aws.codewhisperer","DocumentCitationEvent",0,["source","title","location","sourceContent"],[[()=>Y,0],[()=>Y,0],[()=>PJ,0],[()=>fJ,0]]],jY=[3,"com.amazon.aws.codewhisperer","DocumentCitationSearchResultSpan",0,["searchResultIndex","start","end"],[1,1,1]],aY=[3,"com.amazon.aws.codewhisperer","DocumentCitationSourceContent",0,["text"],[[()=>Y,0]]],g_=[3,"com.amazon.aws.codewhisperer","DocumentCitationSpan",0,["documentIndex","start","end"],[1,1,1]],vY=[3,"com.amazon.aws.codewhisperer","DocumentCitationWebLocation",0,["url","domain"],[[()=>Y,0],[()=>Y,0]]],ZY=[3,"com.amazon.aws.codewhisperer","DocumentSymbol",0,["name","type","source"],[0,0,0],2],pY=[3,"com.amazon.aws.codewhisperer","DryRunSucceedEvent",0,[],[]],nm=[3,"com.amazon.aws.codewhisperer","EditorState",0,["document","cursorState","relevantDocuments","useRelevantDocuments","workspaceFolders"],[[()=>TE,0],()=>WJ,[()=>cJ,0],2,[()=>dJ,0]]],tm=[3,"com.amazon.aws.codewhisperer","EnvironmentVariable",0,["key","value"],[[()=>Y,0],[()=>Y,0]]],im=[3,"com.amazon.aws.codewhisperer","EnvState",0,["operatingSystem","currentWorkingDirectory","environmentVariables","timezoneOffset"],[0,[()=>Y,0],[()=>hJ,0],1]],RE=[3,"com.amazon.aws.codewhisperer","FollowupPrompt",0,["content","userIntent"],[[()=>Y,0],0],1],sm=[3,"com.amazon.aws.codewhisperer","FollowupPromptEvent",0,["followupPrompt"],[[()=>RE,0]]],rm=[3,"com.amazon.aws.codewhisperer","GitState",0,["status"],[[()=>Y,0]]],em=[3,"com.amazon.aws.codewhisperer","ImageBlock",0,["format","source"],[0,[()=>YJ,0]],2],om=[3,"com.amazon.aws.codewhisperer","IntentsEvent",0,["intents"],[[()=>BJ,0]]],fm=[3,"com.amazon.aws.codewhisperer","InvalidStateEvent",0,["reason","message"],[0,0],2],hm=[3,"com.amazon.aws.codewhisperer","MessageMetadataEvent",0,["conversationId","utteranceId"],[0,0]],um=[3,"com.amazon.aws.codewhisperer","MetadataEvent",0,["tokenUsage"],[()=>Bm]],cm=[3,"com.amazon.aws.codewhisperer","MeteringEvent",0,["usage","unit","unitPlural"],[1,0,0]],S_=[3,"com.amazon.aws.codewhisperer","Position",0,["line","character"],[1,1],2],EE=[3,"com.amazon.aws.codewhisperer","ProgrammingLanguage",0,["languageName"],[0],1],$_=[3,"com.amazon.aws.codewhisperer","Range",0,["start","end"],[()=>S_,()=>S_],2],_m=[3,"com.amazon.aws.codewhisperer","ReasoningContentEvent",8,["text","redactedContent","signature"],[[()=>Y,0],21,[()=>Y,0]]],wm=[3,"com.amazon.aws.codewhisperer","ReasoningText",8,["text","signature"],[[()=>Y,0],[()=>Y,0]],1],lm=[3,"com.amazon.aws.codewhisperer","Reference",0,["licenseName","repository","url","recommendationContentSpan"],[0,0,0,()=>yE]],Am=[3,"com.amazon.aws.codewhisperer","RelevantTextDocument",0,["relativeFilePath","programmingLanguage","text","documentSymbols","type"],[[()=>Y,0],()=>EE,[()=>Y,0],()=>$E,0],1],Mm=[3,"com.amazon.aws.codewhisperer","RuntimeDiagnostic",0,["source","severity","message"],[[()=>Y,0],0,[()=>Y,0]],3],dm=[3,"com.amazon.aws.codewhisperer","ShellHistoryEntry",0,["command","directory","exitCode","stdout","stderr"],[[()=>Y,0],[()=>Y,0],1,[()=>Y,0],[()=>Y,0]],1],Rm=[3,"com.amazon.aws.codewhisperer","ShellState",0,["shellName","shellHistory"],[0,[()=>_J,0]],1],yE=[3,"com.amazon.aws.codewhisperer","Span",0,["start","end"],[1,1]],Em=[3,"com.amazon.aws.codewhisperer","SupplementaryWebLink",0,["url","title","snippet"],[[()=>Y,0],[()=>Y,0],[()=>Y,0]],2],ym=[3,"com.amazon.aws.codewhisperer","SupplementaryWebLinksEvent",0,["supplementaryWebLinks"],[[()=>OE,0]]],TE=[3,"com.amazon.aws.codewhisperer","TextDocument",0,["relativeFilePath","programmingLanguage","text","documentSymbols"],[[()=>Y,0],()=>EE,[()=>Y,0],()=>$E],1],Tm=[3,"com.amazon.aws.codewhisperer","TextDocumentDiagnostic",0,["document","range","source","severity","message","code","codeDescription","tags","relatedInformation","data"],[[()=>TE,0],()=>$_,[()=>Y,0],0,[()=>Y,0],[()=>Y,0],[()=>JY,0],64,[()=>eJ,0],[()=>Y,0]],5],gm=[3,"com.amazon.aws.codewhisperer","ToolInputSchema",0,["json"],[[()=>U_,0]]],gE=[3,"com.amazon.aws.codewhisperer","ToolResult",0,["toolUseId","content","status","toolName"],[0,[()=>wJ,0],0,[()=>Nf,0]],2],Sm=[3,"com.amazon.aws.codewhisperer","ToolResultEvent",0,["toolResult"],[[()=>gE,0]]],Im=[3,"com.amazon.aws.codewhisperer","ToolSpecification",0,["inputSchema","name","description"],[[()=>gm,0],[()=>Nf,0],[()=>HY,0]],2],Um=[3,"com.amazon.aws.codewhisperer","ToolUse",0,["toolUseId","name","input"],[0,[()=>Nf,0],[()=>U_,0]],3],bm=[3,"com.amazon.aws.codewhisperer","ToolUseEvent",0,["toolUseId","name","input","stop"],[0,[()=>Nf,0],[()=>Y,0],2],2];var $m=[3,"com.amazon.aws.codewhisperer","UserInputMessage",0,["content","userInputMessageContext","userIntent","origin","images","documents","modelId","cachePoint","clientCacheConfig"],[[()=>Y,0],[()=>Lm,0],0,0,[()=>uJ,0],[()=>oJ,0],0,()=>b_,()=>mY],1],Lm=[3,"com.amazon.aws.codewhisperer","UserInputMessageContext",0,["editorState","shellState","gitState","envState","appStudioContext","diagnostic","consoleState","userSettings","additionalContext","toolResults","tools"],[[()=>nm,0],[()=>Rm,0],[()=>rm,0],[()=>im,0],[()=>FY,0],[()=>FJ,0],[()=>QY,0],()=>Om,[()=>sJ,0],[()=>lJ,0],[()=>AJ,0]]],Om=[3,"com.amazon.aws.codewhisperer","UserSettings",0,["hasConsentedToCrossRegionCalls"],[2]];var Bm=[3,"com.amazon.aws.codewhisperer.internal","TokenUsage",0,["uncachedInputTokens","outputTokens","totalTokens","cacheReadInputTokens","cacheWriteInputTokens","contextUsagePercentage","normalizedTokenUsage"],[1,1,1,1,1,1,1],3];var Nm=[3,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponseRequest",0,["conversationState","profileArn","agentMode","additionalModelRequestFields"],[[()=>xY,0],0,[0,{["httpHeader"]:"x-amzn-kiro-agent-mode"}],15],1],Gm=[3,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponseResponse",0,["conversationId","generateAssistantResponseResponse"],[[0,{["httpHeader"]:"x-amzn-codewhisperer-conversation-id"}],[()=>GJ,16]],2];var Hm=[3,"com.amazon.aws.q","InteractionComponentsEvent",0,["interactionComponentEntries"],[[()=>TJ,0]],1],L_=[3,"com.amazon.aws.q.interactioncomponents","Action",0,["webLink","moduleLink"],[[()=>iJ,0],[()=>Qm,0]]],O_=[3,"com.amazon.aws.q.interactioncomponents","Alert",0,["type","content"],[0,[()=>RJ,0]],2],Wm=[3,"com.amazon.aws.q.interactioncomponents","AlertComponent",0,["text"],[[()=>le,0]]],Fm=[3,"com.amazon.aws.q.interactioncomponents","Clarification",0,["questions","dismissible"],[[()=>yJ,0],2],1],Pm=[3,"com.amazon.aws.q.interactioncomponents","ClarificationAnswerOption",0,["label","value"],[[()=>rn,0],[()=>rn,0]],2],Dm=[3,"com.amazon.aws.q.interactioncomponents","ClarificationQuestion",0,["question","options","allowCustom","skippable"],[[()=>rn,0],[()=>EJ,0],2,2],2],Ym=[3,"com.amazon.aws.q.interactioncomponents","CloudWatchTroubleshootingLink",0,["label","investigationPayload","defaultText"],[[()=>rn,0],[()=>rn,0],[()=>rn,0]],2],SE=[3,"com.amazon.aws.q.interactioncomponents","InfrastructureUpdate",0,["transition"],[[()=>mm,0]]],mm=[3,"com.amazon.aws.q.interactioncomponents","InfrastructureUpdateTransition",0,["currentState","nextState"],[[()=>rn,0],[()=>rn,0]],2],Jm=[3,"com.amazon.aws.q.interactioncomponents","InlineArtifact",0,["dsl","summary","title","artifactLabel"],[[()=>rn,0],[()=>rn,0],[()=>rn,0],[()=>rn,0]],4],Xm=[3,"com.amazon.aws.q.interactioncomponents","InteractionComponent",0,["text","alert","infrastructureUpdate","progress","step","taskDetails","taskReference","suggestions","section","resource","resourceList","action","clarification","inlineArtifact"],[[()=>le,0],[()=>O_,0],[()=>SE,0],[()=>IE,0],[()=>bE,0],[()=>pm,0],()=>tJ,[()=>Vm,0],[()=>xm,0],[()=>B_,0],[()=>UE,0],[()=>L_,0],[()=>Fm,0],[()=>Jm,0]]],zm=[3,"com.amazon.aws.q.interactioncomponents","InteractionComponentEntry",0,["interactionComponent","interactionComponentId"],[[()=>Xm,0],0],1],Qm=[3,"com.amazon.aws.q.interactioncomponents","ModuleLink",0,["cloudWatchTroubleshootingLink"],[[()=>Ym,0]]],IE=[3,"com.amazon.aws.q.interactioncomponents","Progress",0,["content"],[[()=>gJ,0]],1],Cm=[3,"com.amazon.aws.q.interactioncomponents","ProgressComponent",0,["step"],[[()=>bE,0]]],B_=[3,"com.amazon.aws.q.interactioncomponents","Resource",0,["title","link","description","type","ARN","resourceJsonString"],[[()=>rn,0],[()=>rn,0],[()=>rn,0],[()=>rn,0],[()=>rn,0],[()=>rn,0]],6],UE=[3,"com.amazon.aws.q.interactioncomponents","ResourceList",0,["items","action"],[[()=>SJ,0],[()=>L_,0]],1],xm=[3,"com.amazon.aws.q.interactioncomponents","Section",0,["title","content","action"],[[()=>rn,0],[()=>IJ,0],[()=>L_,0]],2],Km=[3,"com.amazon.aws.q.interactioncomponents","SectionComponent",0,["text","alert","resource","resourceList"],[[()=>le,0],[()=>O_,0],[()=>B_,0],[()=>UE,0]]],bE=[3,"com.amazon.aws.q.interactioncomponents","Step",0,["id","state","label","content"],[1,0,[()=>rn,0],[()=>UJ,0]],3],km=[3,"com.amazon.aws.q.interactioncomponents","StepComponent",0,["text"],[[()=>le,0]]],qm=[3,"com.amazon.aws.q.interactioncomponents","Suggestion",0,["value"],[[()=>rn,0]],1],Vm=[3,"com.amazon.aws.q.interactioncomponents","Suggestions",0,["items"],[[()=>bJ,0]],1],jm=[3,"com.amazon.aws.q.interactioncomponents","TaskAction",0,["label","payload","note","primary","disabled","confirmation"],[[()=>rn,0],[()=>NJ,0],[()=>vm,0],2,2,[()=>am,0]],2],am=[3,"com.amazon.aws.q.interactioncomponents","TaskActionConfirmation",0,["content"],[[()=>rn,0]]],vm=[3,"com.amazon.aws.q.interactioncomponents","TaskActionNote",0,["content","type"],[[()=>rn,0],0],1],Zm=[3,"com.amazon.aws.q.interactioncomponents","TaskComponent",0,["text","infrastructureUpdate","alert","progress"],[[()=>le,0],[()=>SE,0],[()=>O_,0],[()=>IE,0]]],pm=[3,"com.amazon.aws.q.interactioncomponents","TaskDetails",0,["overview","content","actions"],[[()=>nJ,0],[()=>LJ,0],[()=>$J,0]],2],nJ=[3,"com.amazon.aws.q.interactioncomponents","TaskOverview",0,["label","description"],[[()=>rn,0],[()=>rn,0]],2],tJ=[3,"com.amazon.aws.q.interactioncomponents","TaskReference",0,["taskId"],[0],1],le=[3,"com.amazon.aws.q.interactioncomponents","Text",0,["content"],[[()=>rn,0]],1],iJ=[3,"com.amazon.aws.q.interactioncomponents","WebLink",0,["label","url"],[[()=>rn,0],[()=>rn,0]],2];var sJ=[1,"com.amazon.aws.codewhisperer","AdditionalContentList",0,[()=>WY,0]],rJ=[1,"com.amazon.aws.codewhisperer","ChatHistory",0,[()=>BE,0]],eJ=[1,"com.amazon.aws.codewhisperer","DiagnosticRelatedInformationList",0,[()=>kY,0]];var oJ=[1,"com.amazon.aws.codewhisperer","DocumentBlocks",0,[()=>qY,0]],fJ=[1,"com.amazon.aws.codewhisperer","DocumentCitationSourceContents",0,[()=>aY,0]],$E=[1,"com.amazon.aws.codewhisperer","DocumentSymbols",0,()=>ZY],hJ=[1,"com.amazon.aws.codewhisperer","EnvironmentVariables",0,[()=>tm,0]],uJ=[1,"com.amazon.aws.codewhisperer","ImageBlocks",0,[()=>em,0]],LE=[1,"com.amazon.aws.codewhisperer","References",0,()=>lm],cJ=[1,"com.amazon.aws.codewhisperer","RelevantDocumentList",0,[()=>Am,0]],_J=[1,"com.amazon.aws.codewhisperer","ShellHistory",0,[()=>dm,0]],OE=[1,"com.amazon.aws.codewhisperer","SupplementaryWebLinks",0,[()=>Em,0]],wJ=[1,"com.amazon.aws.codewhisperer","ToolResultContent",0,[()=>zJ,0]],lJ=[1,"com.amazon.aws.codewhisperer","ToolResults",0,[()=>gE,0]],AJ=[1,"com.amazon.aws.codewhisperer","Tools",0,[()=>XJ,0]],MJ=[1,"com.amazon.aws.codewhisperer","ToolUses",0,[()=>Um,0]],dJ=[1,"com.amazon.aws.codewhisperer","WorkspaceFolderList",0,[()=>Y,0]],RJ=[1,"com.amazon.aws.q.interactioncomponents","AlertComponentList",0,[()=>Wm,0]],EJ=[1,"com.amazon.aws.q.interactioncomponents","ClarificationAnswerOptionsList",0,[()=>Pm,0]],yJ=[1,"com.amazon.aws.q.interactioncomponents","ClarificationQuestionList",0,[()=>Dm,0]],TJ=[1,"com.amazon.aws.q.interactioncomponents","InteractionComponentEntryList",0,[()=>zm,0]],gJ=[1,"com.amazon.aws.q.interactioncomponents","ProgressComponentList",0,[()=>Cm,0]],SJ=[1,"com.amazon.aws.q.interactioncomponents","Resources",0,[()=>B_,0]],IJ=[1,"com.amazon.aws.q.interactioncomponents","SectionComponentList",0,[()=>Km,0]],UJ=[1,"com.amazon.aws.q.interactioncomponents","StepComponentList",0,[()=>km,0]],bJ=[1,"com.amazon.aws.q.interactioncomponents","SuggestionList",0,[()=>qm,0]],$J=[1,"com.amazon.aws.q.interactioncomponents","TaskActionList",0,[()=>jm,0]],LJ=[1,"com.amazon.aws.q.interactioncomponents","TaskComponentList",0,[()=>Zm,0]],OJ=[2,"com.amazon.aws.codewhisperer","IntentData",8,0,()=>mJ],BJ=[2,"com.amazon.aws.codewhisperer","IntentMap",0,[0,0],[()=>OJ,0]],NJ=[2,"com.amazon.aws.q.interactioncomponents","TaskActionPayload",0,[0,0],[()=>rn,0]],BE=[4,"com.amazon.aws.codewhisperer","ChatMessage",0,["userInputMessage","assistantResponseMessage"],[[()=>$m,0],[()=>DY,0]]],GJ=[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"],[()=>hm,[()=>PY,0],[()=>_m,0],()=>pY,()=>zY,[()=>ym,0],[()=>sm,0],[()=>XY,0],[()=>om,0],[()=>Hm,0],[()=>bm,0],[()=>Sm,0],()=>um,()=>cm,()=>CY,[()=>YY,0],[()=>VY,0],()=>fm,[()=>ME,0]]],HJ=[4,"com.amazon.aws.codewhisperer","CitationTarget",0,["location","range"],[1,()=>yE]],WJ=[4,"com.amazon.aws.codewhisperer","CursorState",0,["position","range"],[()=>S_,()=>$_]],FJ=[4,"com.amazon.aws.codewhisperer","Diagnostic",0,["textDocumentDiagnostic","runtimeDiagnostic"],[[()=>Tm,0],[()=>Mm,0]]],PJ=[4,"com.amazon.aws.codewhisperer","DocumentCitationLocation",0,["documentPage","documentChar","documentChunk","searchResult","web"],[()=>g_,()=>g_,()=>g_,()=>jY,[()=>vY,0]]],DJ=[4,"com.amazon.aws.codewhisperer","DocumentSource",8,["bytes"],[21]];var YJ=[4,"com.amazon.aws.codewhisperer","ImageSource",8,["bytes"],[21]],mJ=[4,"com.amazon.aws.codewhisperer","IntentDataType",0,["string"],[0]],JJ=[4,"com.amazon.aws.codewhisperer","ReasoningContent",8,["reasoningText","redactedContent"],[[()=>wm,0],21]];var XJ=[4,"com.amazon.aws.codewhisperer","Tool",0,["toolSpecification","cachePoint"],[[()=>Im,0],()=>b_]],zJ=[4,"com.amazon.aws.codewhisperer","ToolResultContentBlock",0,["text","json"],[[()=>Y,0],[()=>U_,0]]];var NE=[9,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponse",{["http"]:["POST","/generateAssistantResponse",200]},()=>Nm,()=>Gm];var WE=(n)=>{return{apiVersion:"2023-11-27",base64Decoder:n?.base64Decoder??vs.fromBase64,base64Encoder:n?.base64Encoder??vs.toBase64,disableHostPrefix:n?.disableHostPrefix??!1,endpointProvider:n?.endpointProvider??lE,extensions:n?.extensions??[],httpAuthSchemeProvider:n?.httpAuthSchemeProvider??Pd,httpAuthSchemes:n?.httpAuthSchemes??[{schemeId:"smithy.api#httpBearerAuth",identityProvider:(t)=>t.getIdentityProvider("smithy.api#httpBearerAuth"),signer:new HE.HttpBearerAuthSigner}],logger:n?.logger??new V.NoOpLogger,protocol:n?.protocol??GE.AwsRestJsonProtocol,protocolSettings:n?.protocolSettings??{defaultNamespace:"com.amazon.aws.codewhisperer.streaming",errorTypeRegistries:dE,version:"2023-11-27",serviceTarget:"AmazonCodeWhispererStreamingService"},serviceId:n?.serviceId??"CodeWhispererStreaming",urlParser:n?.urlParser??E_.parseUrl,utf8Decoder:n?.utf8Decoder??Vi.fromUtf8,utf8Encoder:n?.utf8Encoder??Vi.toUtf8}};var YE=(n)=>{V.emitWarningIfUnsupportedVersion(process.version);let t=R_.resolveDefaultsModeConfig(n),i=()=>t().then(V.loadConfigsForDefaultMode),s=WE(n);FE.emitWarningIfUnsupportedVersion(process.version);let r={profile:n?.profile,logger:s.logger};return{...s,...n,runtime:"node",defaultsMode:t,authSchemePreference:n?.authSchemePreference??kt.loadConfig(PE.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS,r),bodyLengthChecker:n?.bodyLengthChecker??d_.calculateBodyLength,defaultUserAgentProvider:n?.defaultUserAgentProvider??Gt.createDefaultUserAgentProvider({serviceId:s.serviceId,clientVersion:Jd.version}),eventStreamSerdeProvider:n?.eventStreamSerdeProvider??Ef.eventStreamSerdeProvider,httpAuthSchemes:n?.httpAuthSchemes??[{schemeId:"smithy.api#httpBearerAuth",identityProvider:(e)=>e.getIdentityProvider("smithy.api#httpBearerAuth")||(async(f)=>{return await A_(f)(f)}),signer:new DE.HttpBearerAuthSigner}],maxAttempts:n?.maxAttempts??kt.loadConfig(un.NODE_MAX_ATTEMPT_CONFIG_OPTIONS,n),region:n?.region??kt.loadConfig(hn.NODE_REGION_CONFIG_OPTIONS,{...hn.NODE_REGION_CONFIG_FILE_OPTIONS,...r}),requestHandler:Gf.NodeHttpHandler.create(n?.requestHandler??i),retryMode:n?.retryMode??kt.loadConfig({...un.NODE_RETRY_MODE_CONFIG_OPTIONS,default:async()=>(await i()).retryMode||Sn.DEFAULT_RETRY_MODE},n),sha256:n?.sha256??M_.Hash.bind(null,"sha256"),streamCollector:n?.streamCollector??Gf.streamCollector,useDualstackEndpoint:n?.useDualstackEndpoint??kt.loadConfig(hn.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS,r),useFipsEndpoint:n?.useFipsEndpoint??kt.loadConfig(hn.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS,r),userAgentAppId:n?.userAgentAppId??kt.loadConfig(Gt.NODE_APP_ID_CONFIG_OPTIONS,r)}};var an=Q(ct(),1);var xn=Q(Jn(),1);var mE=(n)=>{let{httpAuthSchemes:t,httpAuthSchemeProvider:i,token:s}=n;return{setHttpAuthScheme(r){let e=t.findIndex((f)=>f.schemeId===r.schemeId);if(e===-1)t.push(r);else t.splice(e,1,r)},httpAuthSchemes(){return t},setHttpAuthSchemeProvider(r){i=r},httpAuthSchemeProvider(){return i},setToken(r){s=r},token(){return s}}},JE=(n)=>{return{httpAuthSchemes:n.httpAuthSchemes(),httpAuthSchemeProvider:n.httpAuthSchemeProvider(),token:n.token()}};var XE=(n,t)=>{let i=Object.assign(an.getAwsRegionExtensionConfiguration(n),V.getDefaultExtensionConfiguration(n),xn.getHttpHandlerExtensionConfiguration(n),mE(n));return t.forEach((s)=>s.configure(i)),Object.assign(n,an.resolveAwsRegionExtensionConfiguration(i),V.resolveDefaultRuntimeConfig(i),xn.resolveHttpHandlerRuntimeConfig(i),JE(i))};class N_ extends V.Client{config;constructor(...[n]){let t=YE(n||{});super(t);this.initConfig=t;let i=Yd(t),s=Kt.resolveUserAgentConfig(i),r=un.resolveRetryConfig(s),e=hn.resolveRegionConfig(r),f=wi.resolveHostHeaderConfig(e),o=Zn.resolveEndpointConfig(f),h=jn.resolveDefaultAwsRegionalEndpointsConfig(o),u=Mc.resolveEventStreamSerdeConfig(h),c=Dd(u),_=XE(c,n?.extensions||[]);this.config=_,this.middlewareStack.use(zE.getSchemaSerdePlugin(this.config)),this.middlewareStack.use(Kt.getUserAgentPlugin(this.config)),this.middlewareStack.use(un.getRetryPlugin(this.config)),this.middlewareStack.use(ie.getContentLengthPlugin(this.config)),this.middlewareStack.use(wi.getHostHeaderPlugin(this.config)),this.middlewareStack.use(ne.getLoggerPlugin(this.config)),this.middlewareStack.use(te.getRecursionDetectionPlugin(this.config)),this.middlewareStack.use(ps.getHttpAuthSchemeEndpointRuleSetPlugin(this.config,{httpAuthSchemeParametersProvider:Fd,identityProviderConfigProvider:async(w)=>new ps.DefaultIdentityProviderConfig({"smithy.api#httpBearerAuth":w.token})})),this.middlewareStack.use(ps.getHttpSigningPlugin(this.config))}destroy(){super.destroy()}}class G_ extends V.Command.classBuilder().ep(md).m(function(n,t,i,s){return[Zn.getEndpointPlugin(i,n.getEndpointParameterInstructions())]}).s("AmazonCodeWhispererStreamingService","GenerateAssistantResponse",{eventStream:{output:!0}}).n("CodeWhispererStreamingClient","GenerateAssistantResponseCommand").sc(NE).build(){}import{randomUUID as Q_}from"crypto";function QE(n){let t=Lr[n];if(!t)throw Error(`Unsupported model: ${n}. Supported models: ${yw.join(", ")}`);return t}var CE=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"]),xE=["low","medium","high","xhigh","max"];function Hf(n){for(let t of xE){let i=`-${t}`;if(n.endsWith(i)){let s=n.slice(0,-i.length);if(CE.has(s))return{wireId:QE(s),effort:t}}}return{wireId:QE(n),effort:void 0}}function QJ(n){for(let t of xE){let i=`-${t}`;if(n.endsWith(i)){let s=n.slice(0,-i.length);if(CE.has(s))return s}}if(n.endsWith("-thinking")){let t=n.slice(0,-9);if(Lr[t])return t}return n}function KE(n){return D(QJ(n))}var CJ=["low","medium","high","xhigh","max"];function xJ(n){return typeof n==="string"&&CJ.some((t)=>t===n)}var kE=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"]),qE=new Set(["claude-opus-4.7","claude-opus-4.8","claude-sonnet-5",...kE]),KJ=new Set(["claude-opus-4.5","claude-opus-4.6","claude-opus-4.6-1m","claude-sonnet-4.6","claude-sonnet-4.6-1m",...qE]);function ai(n){return KJ.has(n)}function H_(n){return qE.has(n)}function VE(n,t){if(kE.has(n))return{reasoning:{effort:t}};return{output_config:{effort:t}}}function kJ(n,t){if(!ai(n))return;if(t==="xhigh"&&!H_(n))return"max";return t}function qJ(n,t){if(!ai(t))return;let i;if(n<=1e4)i="low";else if(n<=20000)i="medium";else if(n<=28000)i="high";else i="max";return i}function jE(n){let t;if(ai(n.model))t={wireId:n.model,effort:void 0};else try{t=Hf(n.model)}catch(s){if(s instanceof Error&&s.message.startsWith("Unsupported model:"))return;throw s}if(!ai(t.wireId))return;let i=[t.effort,n.reasoningEffort,n.configEffort];for(let s of i)if(xJ(s))return kJ(t.wireId,s);if(!n.think)return;if(n.autoEffortMapping??!0)return qJ(n.budget,t.wireId);return"medium"}import{randomUUID as pJ}from"crypto";class Kn extends Error{code;name="RequestTransformError";constructor(n,t="invalid_request"){super(n);this.code=t}}function Ae(n){return typeof n==="object"&&n!==null}function VJ(n){let t=atob(n),i=new Uint8Array(t.length);for(let s=0;s<t.length;s++)i[s]=t.charCodeAt(s);return i}function jJ(n){let t=[];for(let i of n){if(!Ae(i)||i.type!=="image"||!Ae(i.source))continue;let s=i.source;if(s.type!=="base64"||typeof s.data!=="string")continue;t.push({mediaType:typeof s.media_type==="string"?s.media_type:"image/jpeg",data:s.data})}return t}function aJ(n){let t=[];for(let i of n){if(!Ae(i)||i.type!=="image_url"||!Ae(i.image_url))continue;let s=i.image_url.url;if(typeof s!=="string"||!s.startsWith("data:"))continue;let[r="",e]=s.split(",",2);if(!e)continue;let f=r.split(";")[0]?.replace("data:","");t.push({mediaType:f||"image/jpeg",data:e})}return t}function Wf(n){if(!Array.isArray(n))return[];return[...jJ(n),...aJ(n)]}function Ff(n){let t=[],i=0;for(let s of n){if(t.length>=4)break;if(i+s.data.length>3750000)break;t.push(s),i+=s.data.length}return{images:t.map((s)=>({format:s.mediaType.split("/")[1]||"png",source:{bytes:VJ(s.data)}})),omitted:n.length-t.length}}function Pf(n){let t=[];for(let i of n){if(!Ae(i))continue;if(typeof i.text==="string")t.push(i.text);else if(i.type==="text"&&i.text)t.push(String(i.text))}return t.join("")}function W_(n){return typeof n==="object"&&n!==null}function aE(n,t){for(let i of n){if(i.role!=="assistant")continue;if(i.tool_calls){for(let s of i.tool_calls)if(s.id===t)return s}if(Array.isArray(i.content)){for(let s of i.content)if(W_(s)&&s.type==="tool_use"&&s.id===t)return s}}return null}function vE(n){let t=[];for(let i of n){if(t.length===0){t.push({...i});continue}let s=t[t.length-1];if(!s||i.role!==s.role){t.push({...i});continue}if(Array.isArray(s.content)&&Array.isArray(i.content))s.content.push(...i.content);else if(typeof s.content==="string"&&typeof i.content==="string")s.content+=`
|
|
230
|
+
${i.content}`;else if(Array.isArray(s.content)&&typeof i.content==="string")s.content.push({type:"text",text:i.content});else if(typeof s.content==="string"&&Array.isArray(i.content))s.content=[{type:"text",text:s.content},...i.content];if(i.tool_calls){if(!s.tool_calls)s.tool_calls=[];s.tool_calls.push(...i.tool_calls)}if(i.role==="tool"){if(!s.tool_results)s.tool_results=[{content:s.content,tool_call_id:s.tool_call_id}];s.tool_results.push({content:i.content,tool_call_id:i.tool_call_id})}}return t}function kn(n){if(n===null||n===void 0)return"";if(typeof n==="string")return n;if(!W_(n))return"";if(typeof n.content==="string")return n.content;if(Array.isArray(n.content))return n.content.filter((t)=>W_(t)&&t.type==="text").map((t)=>typeof t.text==="string"?t.text:"").join("");return typeof n.text==="string"?n.text:""}function ZE(n){return n.map((t)=>({toolSpecification:{name:t.name||t.function?.name,description:(t.description||t.function?.description||"").substring(0,9216),inputSchema:{json:t.input_schema||t.function?.parameters||{}}}}))}function nr(n){let t=[],i=new Set;for(let s of n)if(!i.has(s.toolUseId))i.add(s.toolUseId),t.push(s);return t}function pE(n){return typeof n==="object"&&n!==null}function vJ(n){if(typeof n.id!=="string"||n.id.length===0||typeof n.function?.name!=="string"||n.function.name.length===0)throw new Kn("Assistant tool calls require non-empty id and name","invalid_tool_history");let t=n.function?.arguments,i=t;if(typeof t==="string")try{i=JSON.parse(t)}catch(s){if(s instanceof SyntaxError)throw new Kn(`Tool call ${n.id} contains invalid JSON arguments`,"invalid_tool_history");throw s}return{input:i,name:n.function.name,toolUseId:n.id}}function ZJ(n){if(n.length<4)return n;let t=[],i=0;while(i<n.length){let s=n[i];if(s?.assistantResponseMessage?.toolUses&&i+1<n.length&&n[i+1]?.userInputMessage?.userInputMessageContext?.toolResults){let r=i,e=i;while(e<n.length){let h=n[e],u=e+1<n.length?n[e+1]:void 0;if(!h?.assistantResponseMessage?.toolUses||!u?.userInputMessage?.userInputMessageContext?.toolResults)break;e+=2}let f=(e-r)/2,o;for(let h=r;h<e;h+=2){let u=n[h],c=n[h+1];if(!u||!c)continue;let _=u.assistantResponseMessage,w=f>1&&h!==r&&_!==void 0&&_.content.length>0&&_.content===o;if(o=_?.content,w&&_?.toolUses)t.push({assistantResponseMessage:{content:"",toolUses:_.toolUses}});else t.push(u);t.push(c)}i=e}else{if(s)t.push(s);i++}}return t}function ny(n,t){let i=n.at(-1)?.userInputMessage;if(!i)return!1;if(t.content)i.content=i.content?`${i.content}
|
|
112
231
|
|
|
113
|
-
|
|
232
|
+
${t.content}`:t.content;let s=t.userInputMessageContext?.toolResults;if(s&&s.length>0){i.userInputMessageContext??={};let r=i.userInputMessageContext;r.toolResults=nr([...r.toolResults??[],...s])}if(t.images&&t.images.length>0){if((i.images?.length??0)+t.images.length>4)throw new Kn("A Kiro request supports at most 4 images in one user turn","too_many_images");i.images=[...i.images??[],...t.images]}return!0}function ty(n,t){let i=[];for(let s=0;s<n.length-1;s++){let r=n[s];if(!r)continue;if(r.role==="user"){let h={content:"",modelId:t,origin:Rn.ORIGIN_AI_EDITOR},u=[];if(Array.isArray(r.content)){h.content=Pf(r.content);for(let _ of r.content){if(!pE(_)||_.type!=="tool_result"||typeof _.tool_use_id!=="string")continue;u.push({content:[{text:kn(_.content??_)}],status:_.is_error===!0?"error":"success",toolUseId:_.tool_use_id})}let c=Wf(r.content);if(c.length>0){let _=Ff(c);if(h.images=_.images,_.omitted>0)throw new Kn("A Kiro request supports at most 4 images and 3.75 MB of base64 image data per user turn","too_many_images")}}else h.content=kn(r);if(u.length>0)h.userInputMessageContext={toolResults:nr(u)};if(!ny(i,h))i.push({userInputMessage:h});continue}if(r.role==="tool"){let h=[];if(r.tool_results)for(let c of r.tool_results){if(!c.tool_call_id)continue;h.push({content:[{text:kn(c)}],status:c.is_error===!0?"error":"success",toolUseId:c.tool_call_id})}else if(r.tool_call_id)h.push({content:[{text:kn(r)}],status:r.is_error===!0?"error":"success",toolUseId:r.tool_call_id});let u={content:"",modelId:t,origin:Rn.ORIGIN_AI_EDITOR,userInputMessageContext:{toolResults:nr(h)}};if(!ny(i,u))i.push({userInputMessage:u});continue}if(r.role!=="assistant")continue;let e={content:""},f=[];if(Array.isArray(r.content))for(let h of r.content){if(!pE(h))continue;if(h.type==="text")e.content+=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 e.content=kn(r);if(r.tool_calls)for(let h of r.tool_calls)f.push(vJ(h));if(f.length>0)e.toolUses=f;if(!e.content&&!e.toolUses)continue;let o=i[i.length-1]?.assistantResponseMessage;if(o){if(e.content)o.content=o.content?`${o.content}
|
|
114
233
|
|
|
115
|
-
${e.content}
|
|
234
|
+
${e.content}`:e.content;if(e.toolUses)o.toolUses=[...o.toolUses??[],...e.toolUses]}else i.push({assistantResponseMessage:e})}return ZJ(i)}function iy(n,t,i){if(!t)return n;let s=n.find((r)=>r.userInputMessage);if(s?.userInputMessage)s.userInputMessage.content=`${t}
|
|
116
235
|
|
|
117
|
-
${
|
|
236
|
+
${s.userInputMessage.content||""}`;else n.unshift({userInputMessage:{content:t,modelId:i,origin:Rn.ORIGIN_AI_EDITOR}});return n}function sy(n){return n.some((t)=>Boolean(t.assistantResponseMessage?.toolUses)||Boolean(t.userInputMessage?.userInputMessageContext?.toolResults))}function ry(n){let t=new Set;for(let i of n)for(let s of i.assistantResponseMessage?.toolUses??[])if(s.name)t.add(s.name);return t}function Wt(n){return typeof n==="object"&&n!==null}function nX(n){return Wt(n)}function tX(n){return Wt(n)}function iX(n){let t=typeof n==="string"?JSON.parse(n):n;if(!Wt(t))return{messages:[],tools:[],system:""};return{messages:Array.isArray(t.messages)?t.messages.filter(nX):[],tools:Array.isArray(t.tools)?t.tools.filter(tX):[],system:typeof t.system==="string"?t.system:""}}function sX(n){if(Array.isArray(n))return"array";if(n===null)return"string";let t=typeof n;return t==="number"||t==="boolean"||t==="string"||t==="object"?t:"string"}function rX(n,t){let i=t.find((e)=>e.name===n&&Wt(e.input)),s={};if(i&&Wt(i.input))for(let[e,f]of Object.entries(i.input))s[e]={type:sX(f)};let r=Object.keys(s).length>0?{type:"object",properties:s}:{type:"object"};return{toolSpecification:{name:n,description:"",inputSchema:{json:r}}}}function eX(n,t){let i={content:""},s=[];if(Array.isArray(t.content))for(let r of t.content){if(!Wt(r))continue;if(r.type==="text"&&typeof r.text==="string")i.content+=r.text;else if(r.type==="tool_use"&&typeof r.id==="string"&&typeof r.name==="string")s.push({input:r.input,name:r.name,toolUseId:r.id})}else i.content=kn(t);for(let r of t.tool_calls??[]){if(typeof r.id!=="string"||typeof r.function?.name!=="string")continue;let e=r.function.arguments;try{s.push({input:typeof e==="string"?JSON.parse(e):e,name:r.function.name,toolUseId:r.id})}catch(f){if(f instanceof SyntaxError)throw new Kn(`Tool call ${r.id} contains invalid JSON arguments`,"invalid_tool_history");throw f}}if(s.length>0)i.toolUses=s;if(i.content||i.toolUses)n.push({assistantResponseMessage:i})}function oX(n){let t="",i=[],s=[];if(n.role==="tool"){let r=n.tool_results??[{content:n.content,tool_call_id:n.tool_call_id}];for(let e of r){if(typeof e.tool_call_id!=="string")continue;i.push({content:[{text:kn(e)}],status:e.is_error===!0?"error":"success",toolUseId:e.tool_call_id})}}else if(Array.isArray(n.content)){t=Pf(n.content);for(let e of n.content){if(!Wt(e)||e.type!=="tool_result"||typeof e.tool_use_id!=="string")continue;i.push({content:[{text:kn(e.content??e)}],status:e.is_error===!0?"error":"success",toolUseId:e.tool_use_id})}let r=Ff(Wf(n.content));if(s.push(...r.images),r.omitted>0)throw new Kn("A Kiro request supports at most 4 images and 3.75 MB of base64 image data per user turn","too_many_images")}else t=kn(n);return{content:t,toolResults:i,images:s}}function fX(n,t){let i=aE(n,t.toolUseId);if(!Wt(i))return;let s=Wt(i.function)?i.function:void 0,r=typeof i.name==="string"?i.name:typeof s?.name==="string"?s.name:void 0;if(!r)throw new Kn(`Tool result ${t.toolUseId} references a call without a valid name`,"invalid_tool_history");let e=i.input??s?.arguments,f=e??{};if(typeof e==="string")try{f=JSON.parse(e)}catch(o){if(o instanceof SyntaxError)throw new Kn(`Tool call ${t.toolUseId} contains invalid JSON arguments`,"invalid_tool_history");throw o}return{name:r,toolUseId:t.toolUseId,input:f}}function ey(n,t,i,s=!1,r=20000,e={}){let f=iX(n);if(f.messages.length===0)throw Error("No messages");let{wireId:o,effort:h}=Hf(t),u=f.messages.filter((g)=>g.role==="system"),c=vE(f.messages.filter((g)=>g.role!=="system")),_=f.system,w=u.map(kn).join(`
|
|
118
237
|
|
|
119
|
-
|
|
238
|
+
`);if(w)_=_?`${_}
|
|
120
239
|
|
|
121
|
-
${s.content}`:`<thinking>${e}</thinking>`}if(r.length>0)s.toolUses=r;if(s.content||s.toolUses)t.push({assistantResponseMessage:s})}function t9(t){let n="",s=[],r=[];if(t.role==="tool"){let i=t.tool_results??[{content:t.content,tool_call_id:t.tool_call_id}];for(let e of i){if(typeof e.tool_call_id!=="string")continue;s.push({content:[{text:Bt(e)}],status:"success",toolUseId:e.tool_call_id})}}else if(Array.isArray(t.content)){n=Lo(t.content);for(let e of t.content){if(!wn(e)||e.type!=="tool_result"||typeof e.tool_use_id!=="string")continue;s.push({content:[{text:Bt(e.content??e)}],status:"success",toolUseId:e.tool_use_id})}let i=Uo($o(t.content));if(r.push(...i.images),i.omitted>0)n+=`
|
|
240
|
+
${w}`:w;let l=c.at(-1);if(l?.role==="assistant"&&kn(l)==="{")c.pop();let A=c.at(-1);if(!A)throw Error("Empty");let d=ty(c,o),E=A.role==="user"&&!(Array.isArray(A.content)&&A.content.some((g)=>Wt(g)&&g.type==="tool_result")),R=c.at(-2);if(E&&R?.role==="assistant"&&d.at(-1)?.userInputMessage){let g=kn(R);if(g)d.push({assistantResponseMessage:{content:g}})}d=iy(d,_,o);let y="",T=[],S=[];if(A.role==="assistant")eX(d,A);else{if(d.at(-1)&&!d.at(-1)?.assistantResponseMessage)d.push({assistantResponseMessage:{content:""}});let g=oX(A);y=g.content,T=g.toolResults,S=g.images}let I=d.flatMap((g)=>g.assistantResponseMessage?.toolUses??[]),F=new Set(I.map((g)=>g.toolUseId)),C=[],sn=[];for(let g of T)if(F.has(g.toolUseId))C.push(g);else{let X=fX(f.messages,g);if(X)sn.push({call:X,result:g});else throw new Kn(`Tool result ${g.toolUseId} has no matching tool call`,"invalid_tool_history")}if(sn.length>0){if(!d.at(-1)||d.at(-1)?.assistantResponseMessage)d.push({userInputMessage:{content:"",modelId:o,origin:Rn.ORIGIN_AI_EDITOR}});d.push({assistantResponseMessage:{content:"",toolUses:sn.map(({call:g})=>g)}}),C.push(...sn.map(({result:g})=>g))}let b={content:y,modelId:o,origin:Rn.ORIGIN_AI_EDITOR};if(S.length>0)b.images=S;let $=ZE(f.tools).filter((g)=>typeof g.toolSpecification.name==="string").map((g)=>({toolSpecification:{...g.toolSpecification,name:g.toolSpecification.name??""}}));if(C.length>0||$.length>0){if(b.userInputMessageContext={},C.length>0)b.userInputMessageContext.toolResults=nr(C);if($.length>0)b.userInputMessageContext.tools=$}if(sy(d)){let g=b.userInputMessageContext?.tools??[],X=new Set(g.map((tn)=>tn.toolSpecification.name)),Z=[...ry(d)].filter((tn)=>!X.has(tn));if(Z.length>0)b.userInputMessageContext??={},b.userInputMessageContext.tools=[...g,...Z.map((tn)=>rX(tn,I))]}let N=e.conversationId??pJ(),B={conversationState:{chatTriggerType:Rn.CHAT_TRIGGER_TYPE_MANUAL,conversationId:N,currentMessage:{userInputMessage:b},...d.length>0?{history:d}:{}},...i.profileArn?{profileArn:i.profileArn}:{}};return h===void 0?{request:B,resolved:o,convId:N}:{request:B,resolved:o,convId:N,variantEffort:h}}function hX(n){let t=typeof n==="string"?JSON.parse(n):n;if(typeof t!=="object"||t===null||!("reasoning_effort"in t))return;let i=t.reasoning_effort;return typeof i==="string"||i===null?i:void 0}function oy(n,t,i,s=!1,r=20000,e){let{request:f,resolved:o,convId:h}=ey(n,t,i,s,r,{conversationId:e?.conversationId}),u=jE({model:t,think:s,budget:r,reasoningEffort:hX(n),configEffort:e?.effort,autoEffortMapping:e?.autoEffortMapping});return{conversationState:f.conversationState,...f.profileArn?{profileArn:f.profileArn}:{},streaming:!0,effectiveModel:o,conversationId:h,region:Ew(i.profileArn)??i.region,...u?{effort:u}:{}}}function Df(n){return Math.ceil(n.length/4)}async function Yf(n,t){if(t?.aborted)return{kind:"aborted"};let i=n.next();if(!t)return{kind:"event",result:await i};return new Promise((s,r)=>{let e=()=>s({kind:"aborted"});t.addEventListener("abort",e,{once:!0}),i.then((f)=>{t.removeEventListener("abort",e),s({kind:"event",result:f})},(f)=>{t.removeEventListener("abort",e),r(f)})})}function Me(n,t){if(!t?.name||!t.toolUseId)return;let i=n.get(t.toolUseId);if(i){i.input+=t.input??"";return}n.set(t.toolUseId,{toolUseId:t.toolUseId,name:t.name,input:t.input??""})}function fy(n){let t=[],i=0;for(let s of n.values()){let r=s.input;try{r=JSON.stringify(JSON.parse(s.input))}catch{r=s.input}t.push({type:"content_block_start",index:i,content_block:{type:"tool_use",id:s.toolUseId,name:s.name,input:{}}},{type:"content_block_delta",index:i,delta:{type:"input_json_delta",partial_json:r}},{type:"content_block_stop",index:i}),i+=1}return t}function mf(n,t){let i=t.metadataEvent?.tokenUsage;if(i)n.outputTokens=i.outputTokens??n.outputTokens,n.totalTokens=i.totalTokens??n.totalTokens,n.inputTokens=i.inputTokens??(i.uncachedInputTokens===void 0?n.inputTokens:i.uncachedInputTokens+(i.cacheReadInputTokens??0)+(i.cacheWriteInputTokens??0));n.contextUsagePercentage=t.contextUsageEvent?.contextUsagePercentage??t.metadataEvent?.contextUsagePercentage??i?.contextUsagePercentage??n.contextUsagePercentage}function Jf(n,t,i){let s=n.outputTokens??Df(t),r=n.inputTokens;if(r===void 0&&n.totalTokens!==void 0)r=Math.max(0,n.totalTokens-s);if(r===void 0&&n.contextUsagePercentage!==void 0&&n.contextUsagePercentage>0){let e=Math.round(KE(i)*n.contextUsagePercentage/100);r=Math.max(0,e-s)}return{inputTokens:r??0,outputTokens:s}}class hy extends Error{name="MissingSdkEventStreamError";constructor(){super("SDK response has no event stream")}}async function uy(n,t,i,s){let r=n.generateAssistantResponseResponse;if(!r)throw new hy;let e=r[Symbol.asyncIterator](),f=new Map,o={},h="",u="",c=!1,_=!1;try{while(!0){let A=await Yf(e,s);if(A.kind==="aborted"){if(e.return)await e.return();_=!0;break}if(A.result.done){c=!0;break}let d=A.result.value;mf(o,d),u+=d.reasoningContentEvent?.text??"",h+=d.assistantResponseEvent?.content??"",Me(f,d.toolUseEvent)}}finally{if(!c&&!_&&e.return)await e.return()}let w=Jf(o,h,t),l={role:"assistant",content:h,...u?{reasoning_content:u}:{},...f.size>0?{tool_calls:Array.from(f.values(),(A)=>({id:A.toolUseId,type:"function",function:{name:A.name,arguments:A.input}}))}:{}};return{id:i,object:"chat.completion",created:Math.floor(Date.now()/1000),model:t,choices:[{index:0,message:l,finish_reason:f.size>0?"tool_calls":"stop"}],usage:{prompt_tokens:w.inputTokens,completion_tokens:w.outputTokens,total_tokens:w.inputTokens+w.outputTokens}}}var uX=[/input is too long/i,/CONTENT_LENGTH_EXCEEDS_THRESHOLD/i],cX=/econnreset|etimedout|enotfound|network|fetch failed|socket/i;function Xf(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function F_(n,t){let i=n[t];return typeof i==="string"?i:void 0}function _X(n){let t=n.$metadata;if(!Xf(t))return;let i=t.httpStatusCode;return typeof i==="number"?i:void 0}function wX(n){let t=n.$response;if(!Xf(t))return;let i=t.headers;if(!Xf(i))return;let s={};for(let[r,e]of Object.entries(i))if(typeof e==="string")s[r]=e;else if(typeof e==="number")s[r]=String(e);return Object.keys(s).length>0?s:void 0}function P_(n){if(!Xf(n))return{message:n instanceof Error?n.message:String(n)};let t=_X(n),i=F_(n,"message")??String(n),s=F_(n,"name"),r=F_(n,"reason"),e=wX(n);return{message:i,...t!==void 0?{status:t}:{},...s!==void 0?{code:s}:{},...r!==void 0?{reason:r}:{},...e!==void 0?{headers:e}:{}}}function lX(n){let t=Object.entries(n??{}).find(([s])=>s.toLowerCase()==="retry-after"),i=Number.parseInt(t?.[1]??"60",10);return Number.isFinite(i)&&i>=0?i*1000:60000}function AX(n){return uX.some((t)=>t.test(n))}function cy(n,t){if(n.reason==="INVALID_MODEL_ID"){let i=n.status??400;return{action:"fail",status:i,terminalStatus:i}}if(n.reason==="TEMPORARILY_SUSPENDED")return t.accountCount>1?{action:"switch",...n.status!==void 0?{status:n.status}:{}}:{action:"fail",...n.status!==void 0?{status:n.status}:{},terminalStatus:n.status??403};switch(n.status){case 400:return{action:"fail",status:400,terminalStatus:AX(n.message)?413:400};case 401:return t.retryCount<t.maxRetries?{action:"retry",status:401}:{action:"fail",status:401,terminalStatus:401};case 402:return{action:"fail",status:402,terminalStatus:402};case 403:if(Rs(n.message)){if(!t.forcedRefreshAccountIds.has(t.accountId))return t.forcedRefreshAccountIds.add(t.accountId),{action:"refresh-then-retry",status:403};return t.accountCount>1?{action:"switch",status:403}:{action:"fail",status:403,terminalStatus:403}}if(t.accountCount>1)return{action:"switch",status:403};return t.retryCount<t.maxRetries?{action:"retry",status:403,retryAfterMs:t.retryDelayMs*2**t.retryCount}:{action:"fail",status:403,terminalStatus:403};case 429:{let i=lX(n.headers);return t.accountCount>1?{action:"switch",status:429,retryAfterMs:i}:{action:"retry",status:429,retryAfterMs:i}}case 500:return t.serverErrorCount<5?{action:"retry",status:500,retryAfterMs:1000*2**Math.max(0,t.serverErrorCount-1)}:{action:"switch",status:500};case void 0:if(cX.test(n.message))return t.retryCount<t.maxRetries?{action:"retry",retryAfterMs:t.retryDelayMs*2**t.retryCount}:{action:"fail",terminalStatus:500};return{action:"fail",terminalStatus:500};default:return{action:"fail",status:n.status,terminalStatus:n.status}}}var MX=new Map,dX=new Map;function di(n){return n.reason instanceof Error?n.reason:new DOMException("The request was aborted","AbortError")}function tr(n,t){if(t.aborted)return Promise.reject(di(t));return new Promise((i,s)=>{let r=()=>s(di(t));t.addEventListener("abort",r,{once:!0}),n.then((e)=>{t.removeEventListener("abort",r),i(e)},(e)=>{t.removeEventListener("abort",r),s(e)})})}function _y(n,t){if(n<=0)return Promise.resolve();return tr(Bun.sleep(n),t)}async function wy(n,t,i){let s=n.get(t);if(!s)s={tail:Promise.resolve(),waiters:0},n.set(t,s);let r=s,e=r.tail,f,o=new Promise((_)=>{f=_});if(!f)throw TypeError("Queue release was not initialized");let h=f;r.waiters+=1,r.tail=e.catch(()=>{return}).then(()=>o);let u=()=>{if(r.waiters-=1,r.waiters!==0)return;r.tail.finally(()=>{if(r.waiters===0&&n.get(t)===r)n.delete(t)})};try{await tr(e,i)}catch(_){throw h(),u(),_}let c=!1;return()=>{if(c)return;c=!0,h(),u()}}function ly(n,t){return wy(MX,n,t)}function Ay(n,t){return wy(dX,n,t)}function My(n,t){if(n)return{signal:n,dispose:()=>{return}};let i=new AbortController,s=setTimeout(()=>i.abort(new DOMException("Request deadline exceeded","TimeoutError")),t);return{signal:i.signal,dispose:()=>clearTimeout(s)}}var de="<\uFF5CDSML\uFF5Cfunction_calls";function D_(){return`tool_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}function RX(n){let t=[],i=/```[\s\S]*?```/g;for(let e=i.exec(n);e!==null;e=i.exec(n))t.push([e.index,e.index+e[0].length]);let s=(e)=>t.some(([f,o])=>e>=f&&e<o),r=/`[^`\n]+`/g;for(let e=r.exec(n);e!==null;e=r.exec(n))if(!s(e.index))t.push([e.index,e.index+e[0].length]);return t}function vi(n,t,i){return i.some(([s,r])=>n<r&&t>s)}function EX(n){let t={},i=/<parameter\s+name="([^"]+)"\s*>([\s\S]*?)<\/parameter>/g;for(let s=i.exec(n);s!==null;s=i.exec(n)){let r=s[1];if(r===void 0)continue;let e=s[2]??"";try{t[r]=JSON.parse(e)}catch{t[r]=e}}return t}function dy(n,t){return{toolUseId:D_(),name:n,input:EX(t)}}function yX(n,t,i){let s=[],r=/<function_calls>[\s\S]*?<\/function_calls>/g;for(let f=r.exec(n);f!==null;f=r.exec(n)){let o=f.index,h=o+f[0].length;if(vi(o,h,t))continue;let u=/<invoke\s+name="([^"]+)"\s*>([\s\S]*?)<\/invoke>/g,c=[];for(let _=u.exec(f[0]);_!==null;_=u.exec(f[0])){let w=_[1];if(w)c.push(dy(w,_[2]??""))}if(c.length===0)continue;s.push({start:o,end:h,toolCalls:c}),i.push([o,h])}let e=/<invoke\s+name="([^"]+)"\s*>([\s\S]*?)<\/invoke>/g;for(let f=e.exec(n);f!==null;f=e.exec(n)){let o=f.index,h=o+f[0].length,u=f[1];if(!u||vi(o,h,t)||vi(o,h,i))continue;s.push({start:o,end:h,toolCalls:[dy(u,f[2]??"")]}),i.push([o,h])}return s}function TX(n,t,i){let s=[],r=0;for(;;){let e=n.indexOf(de,r);if(e===-1)break;let f=n.slice(e+de.length),o=/<\uFF5C[^>]*?end[^>]*?>|<\/\uFF5CDSML[^>]*?>/.exec(f),h=o!==null?e+de.length+o.index+o[0].length:n.length;if(r=h,vi(e,h,t)||vi(e,h,i))continue;let u=n.slice(e,h),c=[],_=/name["\uFF5C=:\s]+["']?([A-Za-z0-9_]+)/.exec(u),w=/(\{[\s\S]*\})/.exec(u);if(_?.[1]&&w?.[1])try{c.push({toolUseId:D_(),name:_[1],input:JSON.parse(w[1])})}catch{}s.push({start:e,end:h,toolCalls:c}),i.push([e,h])}return s}function gX(n,t,i){let s=[],r=/\[Called\s+(\w+)\s+with\s+args:\s*(\{[^}]*(?:\{[^}]*\}[^}]*)*\})\]/gs;for(let e=r.exec(n);e!==null;e=r.exec(n)){let f=e.index,o=f+e[0].length,h=e[1],u=e[2];if(!h||!u||vi(f,o,t)||vi(f,o,i))continue;let c;try{c=JSON.parse(u)}catch{continue}s.push({start:f,end:o,toolCalls:[{toolUseId:D_(),name:h,input:c}]}),i.push([f,o])}return s}function Ry(n){if(!n)return{toolCalls:[],cleanedText:n};let t=RX(n),i=[],s=[...yX(n,t,i),...TX(n,t,i),...gX(n,t,i)];if(s.length===0)return{toolCalls:[],cleanedText:n};s.sort((o,h)=>o.start-h.start);let r=[],e="",f=0;for(let o of s){if(o.start<f)continue;e+=n.slice(f,o.start),f=o.end,r.push(...o.toolCalls)}return e+=n.slice(f),{toolCalls:r,cleanedText:e}}var Y_=["<function_calls","<invoke name=",de],SX=Math.max(...Y_.map((n)=>n.length));function Ey(n){let t=-1;for(let i of Y_){let s=n.indexOf(i);if(s!==-1&&(t===-1||s<t))t=s}return t}function IX(n){let t=Math.min(n.length,SX-1);for(let i=t;i>0;i--){let s=n.slice(n.length-i);for(let r of Y_)if(r.length>i&&r.startsWith(s))return i}return 0}class m_{accumulated="";emitted=0;markerSeen=!1;ingest(n){if(!n)return"";if(this.accumulated+=n,!this.markerSeen&&Ey(this.accumulated)!==-1)this.markerSeen=!0;let t;if(this.markerSeen){let s=Ey(this.accumulated);t=s===-1?this.accumulated.length:s}else t=this.accumulated.length-IX(this.accumulated);if(t<=this.emitted)return"";let i=this.accumulated.slice(this.emitted,t);return this.emitted=t,i}get suppressing(){return this.markerSeen}finalize(){let{toolCalls:n,cleanedText:t}=Ry(this.accumulated),i=t.length>this.emitted?t.slice(this.emitted):"";return{toolCalls:n,remainderText:i}}}function J_(n,t,i){let s=[];if(n.type==="content_block_delta"){if(n.delta?.type==="text_delta")s.push({index:0,delta:{content:n.delta.text??""},finish_reason:null});else if(n.delta?.type==="thinking_delta"){if(n.delta.thinking)s.push({index:0,delta:{reasoning_content:n.delta.thinking},finish_reason:null})}else if(n.delta?.type==="input_json_delta")s.push({index:0,delta:{tool_calls:[{index:n.index,function:{arguments:n.delta.partial_json??""}}]},finish_reason:null})}else if(n.type==="content_block_start"&&n.content_block?.type==="tool_use")s.push({index:0,delta:{tool_calls:[{index:n.index,id:n.content_block.id,type:"function",function:{name:n.content_block.name,arguments:""}}]},finish_reason:null});else if(n.type==="message_delta")s.push({index:0,delta:{},finish_reason:n.delta?.stop_reason==="tool_use"?"tool_calls":"stop"});else return null;if(s.length===0)return null;let r={id:t,object:"chat.completion.chunk",created:Math.floor(Date.now()/1000),model:i,choices:s};if(n.type!=="message_delta")return r;let e=n.usage?.input_tokens??0,f=n.usage?.output_tokens??0;return{...r,usage:{prompt_tokens:e,completion_tokens:f,total_tokens:e+f}}}function X_(n,t){let i=/```[\s\S]*?```/g,s=[],r=i.exec(n);while(r!==null)s.push([r.index,r.index+r[0].length]),r=i.exec(n);let e=n.indexOf(t,0);while(e!==-1){if(!s.some(([o,h])=>e>=o&&e<h))return e;e=n.indexOf(t,e+t.length)}return-1}function yy(n,t){if(n==="thinking"){if(t.thinkingBlockIndex!==null)return[];let s=t.nextBlockIndex++;return t.thinkingBlockIndex=s,[{type:"content_block_start",index:s,content_block:{type:"thinking",thinking:""}}]}if(t.textBlockIndex!==null)return[];let i=t.nextBlockIndex++;return t.textBlockIndex=i,[{type:"content_block_start",index:i,content_block:{type:"text",text:""}}]}function Zi(n,t){if(n===null||t.stoppedBlocks.has(n))return[];return t.stoppedBlocks.add(n),[{type:"content_block_stop",index:n}]}function Ri(n,t){if(!n)return[];let i=yy("text",t),s=t.textBlockIndex;if(s===null)return i;return i.push({type:"content_block_delta",index:s,delta:{type:"text_delta",text:n}}),i}function Ei(n,t){let i=yy("thinking",t),s=t.thinkingBlockIndex;if(s===null)return i;return i.push({type:"content_block_delta",index:s,delta:{type:"thinking_delta",thinking:n}}),i}var zf="<thinking>",Qf="</thinking>";function Ty(n,t){t.buffer+=n;let i=[];while(t.buffer.length>0){if(!t.inThinking&&!t.thinkingExtracted){let r=X_(t.buffer,zf);if(r!==-1){let f=t.buffer.slice(0,r);i.push(...Ri(f,t)),t.buffer=t.buffer.slice(r+zf.length),t.inThinking=!0;continue}let e=Math.max(0,t.buffer.length-zf.length);if(e>0)i.push(...Ri(t.buffer.slice(0,e),t)),t.buffer=t.buffer.slice(e);break}if(t.inThinking){let r=X_(t.buffer,Qf);if(r!==-1){if(i.push(...Ei(t.buffer.slice(0,r),t)),t.buffer=t.buffer.slice(r+Qf.length),t.inThinking=!1,t.thinkingExtracted=!0,i.push(...Ei("",t)),i.push(...Zi(t.thinkingBlockIndex,t)),t.buffer.startsWith(`
|
|
122
241
|
|
|
123
|
-
|
|
242
|
+
`))t.buffer=t.buffer.slice(2);continue}let e=Math.max(0,t.buffer.length-Qf.length);if(e>0)i.push(...Ei(t.buffer.slice(0,e),t)),t.buffer=t.buffer.slice(e);break}let s=t.buffer;t.buffer="",i.push(...Ri(s,t))}return i}function gy(n){if(!n.buffer)return[];let t=n.buffer;if(n.buffer="",!n.inThinking)return Ri(t,n);return[...Ei(t,n),...Ei("",n),...Zi(n.thinkingBlockIndex,n)]}class Sy extends Error{name="MissingSdkEventStreamError";constructor(){super("SDK response has no event stream")}}async function*Iy(n,t,i,s){let r=n.generateAssistantResponseResponse;if(!r)throw new Sy;let e={thinkingRequested:!0,buffer:"",inThinking:!1,thinkingExtracted:!1,thinkingBlockIndex:null,textBlockIndex:null,nextBlockIndex:0,stoppedBlocks:new Set},f=new m_,o=new Map,h={},u=r[Symbol.asyncIterator](),c="",_=!1,w=!1,l=!1,A=!1,d=(S,I=!1)=>{if(I&&S.type==="content_block_delta"&&S.delta?.type==="text_delta"){let F=f.ingest(S.delta.text??"");if(!F)return null;return J_({...S,delta:{...S.delta,text:F}},i,t)}return J_(S,i,t)};try{while(!0){let S=await Yf(u,s);if(S.kind==="aborted"){if(u.return)await u.return();A=!0;return}if(S.result.done){l=!0;break}let I=S.result.value;mf(h,I);let F=I.reasoningContentEvent?.text;if(F){if(w)e.thinkingBlockIndex=null,w=!1;_=!0;for(let sn of Ei(F,e)){let b=d(sn);if(b)yield b}continue}let C=I.assistantResponseEvent?.content;if(C){if(c+=C,_&&!w){for(let b of Zi(e.thinkingBlockIndex,e)){let $=d(b);if($)yield $}w=!0}let sn=_?Ri(C,e):Ty(C,e);for(let b of sn){let $=d(b,!0);if($)yield $}continue}if(I.toolUseEvent)Me(o,I.toolUseEvent)}}finally{if(!l&&!A&&u.return)await u.return()}if(_&&!w)for(let S of Zi(e.thinkingBlockIndex,e)){let I=d(S);if(I)yield I}for(let S of gy(e)){let I=d(S,S.delta?.type==="text_delta");if(I)yield I}let{toolCalls:E,remainderText:R}=f.finalize();for(let S of Ri(R,e)){let I=d(S);if(I)yield I}for(let S of Zi(e.textBlockIndex,e)){let I=d(S);if(I)yield I}for(let S of E)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 fy(o)){let I=d(S);if(I)yield I}let y=Jf(h,c,t),T=d({type:"message_delta",delta:{type:"message_delta",stop_reason:o.size>0?"tool_use":"end_turn"},usage:{input_tokens:y.inputTokens,output_tokens:y.outputTokens,cache_creation_input_tokens:0,cache_read_input_tokens:0}});if(T)yield T;d({type:"message_stop"})}class Uy extends Error{timeoutMs;name="StreamIdleTimeoutError";constructor(n){super(`SDK stream idle timeout after ${n}ms`);this.timeoutMs=n}}function by(n,t,i,s){let r=new AbortController,e=AbortSignal.any([t,r.signal]),f=Iy(n.sdkResponse,n.model,n.conversationId,e)[Symbol.asyncIterator](),o=new TextEncoder,h,u,c,_=()=>{if(u===void 0)return;clearTimeout(u),u=void 0},w=(E)=>{if(h!==void 0)return!1;return h=E,!0},l=()=>{e.removeEventListener("abort",d)},A=(E,R)=>{if(!w(E))return;if(Wn(l,_,()=>{if(E==="normal-complete")c?.close();else if(E!=="consumer-cancel")c?.error(R)},s),E!=="normal-complete"&&E!=="consumer-cancel")Wn(()=>{if(!r.signal.aborted)r.abort(R)});cn(()=>f.return?.(void 0))},d=()=>{A("external-abort",di(e))};return new Response(new ReadableStream({start(E){if(c=E,e.addEventListener("abort",d,{once:!0}),e.aborted)d()},async pull(E){if(h!==void 0)return;u=setTimeout(()=>{u=void 0;let R=new Uy(i);A("idle-timeout",R)},i);try{let R=await f.next();if(h!==void 0)return;if(_(),R.done){A("normal-complete");return}E.enqueue(o.encode(`${JSON.stringify(R.value)}
|
|
243
|
+
`))}catch(R){if(h!==void 0)return;let y=R instanceof Error?R:TypeError("SDK stream failed with a non-Error reason",{cause:R});A("upstream-error",y)}},cancel(E){A("consumer-cancel",E)}}),{headers:{"Content-Type":"application/x-ndjson; charset=utf-8"}})}import{createHash as UX}from"crypto";import{Agent as bX}from"http";import{Agent as $X}from"https";var z_=Q(jo(),1);var $y=new Map,Ly=new Map,LX=3;function Cf(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function OX(n){let t=n.conversationState;if(!Cf(t))return;let i=t.currentMessage;if(!Cf(i))return;let s=i.userInputMessage;if(!Cf(s))return;let r=s.modelId;return typeof r==="string"?r:void 0}function BX(n,t,i,s,r=Oy(s),e={value:n.access}){return{region:t,endpoint:i,token:()=>Promise.resolve({token:e.value}),maxAttempts:LX,retryMode:"standard",customUserAgent:[[Rn.USER_AGENT]],requestHandler:r}}function Oy(n){if(n){let t=new br(n,{keepAlive:!0,maxSockets:50});return new z_.NodeHttpHandler({httpAgent:t,httpsAgent:t})}return new z_.NodeHttpHandler({httpAgent:new bX({keepAlive:!0,maxSockets:50}),httpsAgent:new $X({keepAlive:!0,maxSockets:50})})}function NX(n){return UX("sha256").update("kiro-provider-sdk-account-v1\x00").update(n.email??n.refresh).digest("hex")}function By(n,t,i,s,r,e){let f=s??`https://q.${t}.amazonaws.com`,o=JSON.stringify([e??NX(n),t,f,r??null]),h=Ly.get(o);if(!h)h={handler:Oy(r)},Ly.set(o,h);let u=JSON.stringify([o,i??null]),c=$y.get(u);if(c)return c.tokenState.value=n.access,c.client;let _={value:n.access},w=new N_(BX(n,t,f,r,h.handler,_));if(w.middlewareStack.add((l)=>async(A)=>{if(A.request instanceof xn.HttpRequest)A.request.headers["x-amzn-kiro-agent-mode"]="vibe";return l(A)},{step:"build",name:"addKiroHeaders"}),i)w.middlewareStack.add((l)=>async(A)=>{if(A.request instanceof xn.HttpRequest&&typeof A.request.body==="string")try{let d=JSON.parse(A.request.body);if(Cf(d)){let E=OX(d);if(E)d.additionalModelRequestFields=VE(E,i),A.request.body=JSON.stringify(d)}}catch(d){if(!(d instanceof SyntaxError))throw d}return l(A)},{step:"build",name:"addEffortConfig",priority:"high"});return $y.set(u,{client:w,tokenState:_}),w}function pi(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function GX(n){if(!pi(n))return!1;let t=n.conversationState;return pi(t)&&typeof t.conversationId==="string"&&pi(t.currentMessage)&&typeof t.chatTriggerType==="string"}function HX(n,t){let i=typeof n==="string"?JSON.parse(n):n;if(!pi(i))return{think:t.endsWith("-thinking"),budget:20000};let s=i.providerOptions,r=pi(s)?s.thinkingConfig:void 0,e=i.thinkingConfig,f=pi(r)?r:pi(e)?e:void 0,o=f?.thinkingBudget??f?.budget_tokens;return{think:t.endsWith("-thinking")||f!==void 0,budget:typeof o==="number"?o:20000}}function WX(n,t,i){return v(n,t,"upstream_error",i)}async function FX(n,t){let{think:i,budget:s}=HX(n.body,n.model),r=new Set,e=new Map,f=0,o=0,h=n.affinity&&n.affinityStore?n.affinityStore.getSessionAffinity(n.affinity.keyHash):void 0,u=h?.accountId,c,_=h?.conversationId;while(!0){if(t.aborted)throw di(t);if(o+=1,o>n.config.max_request_iterations)return{kind:"response",response:v(500,`Exceeded max iterations (${n.config.max_request_iterations})`,"request_error","max_request_iterations")};n.accountManager.reconcileFromDb();let w=n.accountManager.selectHealthyAccount(u);if(!w)return{kind:"response",response:v(503,"All accounts are unhealthy or rate-limited","service_unavailable","no_healthy_accounts")};let l=Date.now();if(n.affinity&&n.affinityStore)if(!h){let y=n.affinityStore.claimSessionAffinity(n.affinity.keyHash,w.id,Q_(),l,n.config.session_affinity_ttl_ms,n.config.session_affinity_max_entries);if(h=y,u=y.accountId,_=y.conversationId,y.accountId!==w.id)continue}else if(h.accountId===w.id)h=n.affinityStore.claimSessionAffinity(n.affinity.keyHash,w.id,h.conversationId,l,n.config.session_affinity_ttl_ms,n.config.session_affinity_max_entries),_=h.conversationId;else h=n.affinityStore.rebindSessionAffinity(n.affinity.keyHash,w.id,Q_(),l,n.config.session_affinity_ttl_ms,n.config.session_affinity_max_entries),_=h.conversationId;else if(c!==w.id)c=w.id,_=Q_();u=w.id;let A=await Ay(w.id,t),d=!0,E=w,R=!1;try{let y=n.accountManager.toAuthDetails(w);E=await tr(n.tokenRefresher.refreshIfNeeded(w,y,t),t);let T=n.accountManager.toAuthDetails(E),S=$e.safeParse(n.config.effort),I=oy(n.body,n.model,T,i,s,{autoEffortMapping:n.config.auto_effort_mapping,conversationId:_,...S.success?{effort:S.data}:{}}),C=(n.makeClient??By)(T,I.region,I.effort,n.config.test_upstream_endpoint,$s(n.config),E.id),sn={conversationState:I.conversationState,...I.profileArn?{profileArn:I.profileArn}:{}};if(!GX(sn))throw TypeError("Transformed request is not a valid SDK command input");let b=new G_(sn);R=!0;let $=await tr(C.send(b,{abortSignal:t}),t);if(n.stream)return d=!1,{kind:"stream",sdkResponse:$,model:n.model,conversationId:I.conversationId,releaseAccount:A};let N=await uy($,n.model,I.conversationId,t);if(t.aborted)throw di(t);return{kind:"response",response:Response.json(N,{headers:{"Content-Type":"application/json"}})}}catch(y){if(t.aborted)throw di(t);if(!R)throw y;let T=P_(y),S=T.status===500?(e.get(E.id)??0)+1:0;if(T.status===500)e.set(E.id,S);let I=cy(T,{accountId:E.id,accountCount:n.accountManager.getAccountCount(),retryCount:f,maxRetries:n.config.rate_limit_max_retries,serverErrorCount:S,retryDelayMs:n.config.rate_limit_retry_delay_ms,forcedRefreshAccountIds:r});switch(I.action){case"refresh-then-retry":await tr(n.tokenRefresher.forceRefresh(E,t),t);continue;case"retry":f+=1,await _y(I.retryAfterMs??0,t);continue;case"switch":if(T.reason==="TEMPORARILY_SUSPENDED")n.accountManager.markUnhealthy(E,`InvalidTokenException: Account Suspended: ${T.message}`);else n.accountManager.markRateLimited(E,Date.now()+(I.retryAfterMs??n.config.rate_limit_retry_delay_ms));if(u=void 0,c=void 0,!n.affinityStore)_=void 0;continue;case"fail":if(T.reason==="TEMPORARILY_SUSPENDED")n.accountManager.markUnhealthy(E,`InvalidTokenException: Account Suspended: ${T.message}`);return{kind:"response",response:WX(I.terminalStatus??I.status??500,T.message,T.code)}}}finally{if(d)A()}}}async function ir(n){let t=My(n.deadlineSignal,n.config.request_timeout_ms),i,s,r=!1;try{if(n.affinity)i=await ly(n.affinity.keyHash,t.signal);let e=await FX(n,t.signal);if(e.kind==="response")return e.response;s=e.releaseAccount;let f=s,o=i,h=(n.createStreamResponse??by)(e,t.signal,n.config.stream_idle_timeout_ms,()=>{f(),o?.(),t.dispose()});return s=void 0,i=void 0,r=!0,h}catch(e){if(e instanceof Kn)return v(400,e.message,"invalid_request_error",e.code);if(t.signal.aborted)return v(504,"Request deadline exceeded","timeout_error","request_timeout");let f=P_(e);return v(500,f.message,"internal_error",f.code)}finally{if(!r)s?.(),i?.(),t.dispose()}}var Re=Object.freeze({input:Object.freeze(["text"]),output:Object.freeze(["text"])}),In=Object.freeze({input:Object.freeze(["text","image"]),output:Object.freeze(["text"])}),fn=Object.freeze({input:Object.freeze(["text","image","pdf"]),output:Object.freeze(["text"])}),Ny=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"]),xf=Object.freeze([{id:"auto",wireId:"auto",name:"Auto (1.0x)",contextLimit:D("auto"),outputLimit:64000,modalities:fn},{id:"claude-sonnet-4",wireId:"claude-sonnet-4",name:"Claude Sonnet 4.0 (1.3x)",contextLimit:D("claude-sonnet-4"),outputLimit:64000,modalities:fn},{id:"claude-sonnet-4-5",wireId:"claude-sonnet-4.5",name:"Claude Sonnet 4.5 (1.3x)",contextLimit:D("claude-sonnet-4-5"),outputLimit:64000,modalities:fn},{id:"claude-sonnet-4-6",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (1.3x)",contextLimit:D("claude-sonnet-4-6"),outputLimit:64000,modalities:fn},{id:"claude-sonnet-4-6-low",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (low) (1.3x)",contextLimit:D("claude-sonnet-4-6"),outputLimit:64000,modalities:fn},{id:"claude-sonnet-4-6-medium",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (medium) (1.3x)",contextLimit:D("claude-sonnet-4-6"),outputLimit:64000,modalities:fn},{id:"claude-sonnet-4-6-high",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (high) (1.3x)",contextLimit:D("claude-sonnet-4-6"),outputLimit:64000,modalities:fn},{id:"claude-sonnet-4-6-max",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (max) (1.3x)",contextLimit:D("claude-sonnet-4-6"),outputLimit:64000,modalities:fn},{id:"claude-sonnet-5",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (1.3x)",contextLimit:D("claude-sonnet-5"),outputLimit:64000,modalities:fn},{id:"claude-sonnet-5-low",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (low) (1.3x)",contextLimit:D("claude-sonnet-5"),outputLimit:64000,modalities:fn},{id:"claude-sonnet-5-medium",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (medium) (1.3x)",contextLimit:D("claude-sonnet-5"),outputLimit:64000,modalities:fn},{id:"claude-sonnet-5-high",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (high) (1.3x)",contextLimit:D("claude-sonnet-5"),outputLimit:64000,modalities:fn},{id:"claude-sonnet-5-xhigh",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (xhigh) (1.3x)",contextLimit:D("claude-sonnet-5"),outputLimit:64000,modalities:fn},{id:"claude-sonnet-5-max",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (max) (1.3x)",contextLimit:D("claude-sonnet-5"),outputLimit:64000,modalities:fn},{id:"claude-haiku-4-5",wireId:"claude-haiku-4.5",name:"Claude Haiku 4.5 (0.4x)",contextLimit:D("claude-haiku-4-5"),outputLimit:64000,modalities:In},{id:"claude-opus-4-5",wireId:"claude-opus-4.5",name:"Claude Opus 4.5 (2.2x)",contextLimit:D("claude-opus-4-5"),outputLimit:64000,modalities:fn},{id:"claude-opus-4-6",wireId:"claude-opus-4.6",name:"Claude Opus 4.6 (2.2x)",contextLimit:D("claude-opus-4-6"),outputLimit:64000,modalities:fn},{id:"claude-opus-4-7",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (2.2x)",contextLimit:D("claude-opus-4-7"),outputLimit:64000,modalities:fn},{id:"claude-opus-4-7-low",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (low) (2.2x)",contextLimit:D("claude-opus-4-7"),outputLimit:64000,modalities:fn},{id:"claude-opus-4-7-medium",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (medium) (2.2x)",contextLimit:D("claude-opus-4-7"),outputLimit:64000,modalities:fn},{id:"claude-opus-4-7-high",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (high) (2.2x)",contextLimit:D("claude-opus-4-7"),outputLimit:64000,modalities:fn},{id:"claude-opus-4-7-xhigh",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (xhigh) (2.2x)",contextLimit:D("claude-opus-4-7"),outputLimit:64000,modalities:fn},{id:"claude-opus-4-7-max",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (max) (2.2x)",contextLimit:D("claude-opus-4-7"),outputLimit:64000,modalities:fn},{id:"claude-opus-4-8",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (2.2x)",contextLimit:D("claude-opus-4-8"),outputLimit:64000,modalities:fn},{id:"claude-opus-4-8-low",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (low) (2.2x)",contextLimit:D("claude-opus-4-8"),outputLimit:64000,modalities:fn},{id:"claude-opus-4-8-medium",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (medium) (2.2x)",contextLimit:D("claude-opus-4-8"),outputLimit:64000,modalities:fn},{id:"claude-opus-4-8-high",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (high) (2.2x)",contextLimit:D("claude-opus-4-8"),outputLimit:64000,modalities:fn},{id:"claude-opus-4-8-xhigh",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (xhigh) (2.2x)",contextLimit:D("claude-opus-4-8"),outputLimit:64000,modalities:fn},{id:"claude-opus-4-8-max",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (max) (2.2x)",contextLimit:D("claude-opus-4-8"),outputLimit:64000,modalities:fn},{id:"claude-opus-4-8-thinking",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 Thinking (2.2x)",contextLimit:D("claude-opus-4-8"),outputLimit:64000,modalities:fn},{id:"deepseek-3.2",wireId:"deepseek-3.2",name:"DeepSeek 3.2 (0.25x)",contextLimit:D("deepseek-3.2"),outputLimit:64000,modalities:Re},{id:"glm-5",wireId:"glm-5",name:"GLM-5 (0.5x)",contextLimit:D("glm-5"),outputLimit:64000,modalities:Re},{id:"minimax-m2.5",wireId:"minimax-m2.5",name:"MiniMax M2.5 (0.25x)",contextLimit:D("minimax-m2.5"),outputLimit:64000,modalities:Re},{id:"minimax-m2.1",wireId:"minimax-m2.1",name:"MiniMax M2.1 (0.15x)",contextLimit:D("minimax-m2.1"),outputLimit:64000,modalities:Re},{id:"qwen3-coder-next",wireId:"qwen3-coder-next",name:"Qwen3 Coder Next (0.05x)",contextLimit:D("qwen3-coder-next"),outputLimit:64000,modalities:Re},{id:"gpt-5.6-sol",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (2.4x)",contextLimit:D("gpt-5.6-sol"),outputLimit:64000,modalities:In},{id:"gpt-5.6-sol-low",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (low) (2.4x)",contextLimit:D("gpt-5.6-sol"),outputLimit:64000,modalities:In},{id:"gpt-5.6-sol-medium",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (medium) (2.4x)",contextLimit:D("gpt-5.6-sol"),outputLimit:64000,modalities:In},{id:"gpt-5.6-sol-high",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (high) (2.4x)",contextLimit:D("gpt-5.6-sol"),outputLimit:64000,modalities:In},{id:"gpt-5.6-sol-xhigh",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (xhigh) (2.4x)",contextLimit:D("gpt-5.6-sol"),outputLimit:64000,modalities:In},{id:"gpt-5.6-sol-max",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (max) (2.4x)",contextLimit:D("gpt-5.6-sol"),outputLimit:64000,modalities:In},{id:"gpt-5.6-terra",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (1.2x)",contextLimit:D("gpt-5.6-terra"),outputLimit:64000,modalities:In},{id:"gpt-5.6-terra-low",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (low) (1.2x)",contextLimit:D("gpt-5.6-terra"),outputLimit:64000,modalities:In},{id:"gpt-5.6-terra-medium",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (medium) (1.2x)",contextLimit:D("gpt-5.6-terra"),outputLimit:64000,modalities:In},{id:"gpt-5.6-terra-high",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (high) (1.2x)",contextLimit:D("gpt-5.6-terra"),outputLimit:64000,modalities:In},{id:"gpt-5.6-terra-xhigh",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (xhigh) (1.2x)",contextLimit:D("gpt-5.6-terra"),outputLimit:64000,modalities:In},{id:"gpt-5.6-terra-max",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (max) (1.2x)",contextLimit:D("gpt-5.6-terra"),outputLimit:64000,modalities:In},{id:"gpt-5.6-luna",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna",contextLimit:D("gpt-5.6-luna"),outputLimit:64000,modalities:In},{id:"gpt-5.6-luna-low",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (low)",contextLimit:D("gpt-5.6-luna"),outputLimit:64000,modalities:In},{id:"gpt-5.6-luna-medium",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (medium)",contextLimit:D("gpt-5.6-luna"),outputLimit:64000,modalities:In},{id:"gpt-5.6-luna-high",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (high)",contextLimit:D("gpt-5.6-luna"),outputLimit:64000,modalities:In},{id:"gpt-5.6-luna-xhigh",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (xhigh)",contextLimit:D("gpt-5.6-luna"),outputLimit:64000,modalities:In},{id:"gpt-5.6-luna-max",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (max)",contextLimit:D("gpt-5.6-luna"),outputLimit:64000,modalities:In}]);var ns=M.record(M.unknown()),PX=new Set(Ny),DX=M.object({type:M.literal("text"),text:M.string()}).passthrough(),YX=M.object({type:M.literal("image_url"),image_url:M.object({url:M.string(),detail:M.string().optional()}).passthrough()}).passthrough(),mX=M.object({type:M.literal("image"),source:M.object({type:M.string(),data:M.string(),media_type:M.string().optional()}).passthrough()}).passthrough(),JX=M.object({type:M.literal("tool_result"),tool_use_id:M.string().min(1),content:M.unknown()}).passthrough(),XX=M.object({type:M.literal("tool_use"),id:M.string().min(1),name:M.string().min(1),input:M.unknown()}).passthrough(),zX=M.object({type:M.literal("thinking"),thinking:M.string().optional(),text:M.string().optional()}).passthrough(),QX=M.discriminatedUnion("type",[DX,YX,mX,JX,XX,zX]),Kf=M.union([M.string(),M.array(QX)]);function Gy(n){try{return JSON.parse(n),!0}catch(t){if(t instanceof SyntaxError)return!1;throw t}}function CX(n){return n.trim().length===0?"{}":n}var xX=M.object({id:M.string().min(1),type:M.literal("function"),function:M.object({name:M.string().min(1),arguments:M.string().refine(Gy,"function arguments must contain valid JSON")}).passthrough()}).passthrough(),KX=M.object({role:M.literal("system"),content:Kf}).passthrough(),kX=M.object({role:M.literal("user"),content:Kf}).passthrough(),qX=M.object({role:M.literal("assistant"),content:Kf.nullable().optional(),tool_calls:M.array(xX).min(1).optional()}).passthrough().refine((n)=>n.content!==null&&n.content!==void 0?!0:n.tool_calls!==void 0,{message:"assistant message requires content or tool_calls"}),VX=M.object({role:M.literal("tool"),content:Kf,tool_call_id:M.string().min(1)}).passthrough(),jX=M.union([KX,kX,qX,VX]),aX=M.object({type:M.literal("function"),function:M.object({name:M.string().min(1),description:M.string().optional(),parameters:ns.optional()}).passthrough()}).passthrough(),vX=M.object({name:M.string().min(1),description:M.string().optional(),input_schema:ns.optional()}).passthrough(),kf=M.object({model:M.string().refine((n)=>PX.has(n),{message:"model is not supported"}),stream:M.boolean().default(!1),messages:M.array(jX).min(1),tools:M.array(M.union([aX,vX])).optional(),user:M.string().optional(),prompt_cache_key:M.string().optional(),reasoning_effort:M.enum(["low","medium","high","xhigh","max"]).optional()}).passthrough(),ZX=M.object({type:M.literal("input_text"),text:M.string()}).passthrough(),pX=M.object({type:M.literal("output_text"),text:M.string()}).passthrough(),nz=M.object({type:M.literal("input_image"),image_url:M.string()}).passthrough(),tz=M.object({type:M.literal("encrypted_content"),encrypted_content:M.string()}).passthrough(),iz=new Set(["input_text","output_text","input_image","encrypted_content"]),sz=M.object({type:M.string()}).passthrough().refine((n)=>!iz.has(n.type),{message:"known content parts must have a valid payload"}),Hy=M.union([ZX,pX,nz,tz,sz]),rz=M.object({type:M.literal("message").optional(),role:M.enum(["system","developer","user","assistant"]),content:M.union([M.string(),M.array(Hy)])}).passthrough(),ez=M.object({type:M.literal("agent_message"),author:M.string().min(1),recipient:M.string().min(1),content:M.array(Hy)}).passthrough(),oz=M.object({type:M.literal("function_call"),call_id:M.string().min(1),namespace:M.string().min(1).optional(),name:M.string().min(1),arguments:M.string().transform(CX).refine(Gy,"function arguments must contain valid JSON")}).passthrough(),fz=M.object({type:M.literal("custom_tool_call"),call_id:M.string().min(1),namespace:M.string().min(1).optional(),name:M.string().min(1),input:M.string()}).passthrough(),Wy=M.union([M.string(),M.array(M.object({type:M.string(),text:M.string().optional()}).passthrough())]),hz=M.object({type:M.literal("function_call_output"),call_id:M.string().min(1),output:Wy}).passthrough(),uz=M.object({type:M.literal("custom_tool_call_output"),call_id:M.string().min(1),output:Wy}).passthrough(),Fy=M.object({type:M.literal("function"),name:M.string().min(1),description:M.string().optional(),parameters:ns.optional(),strict:M.boolean().optional()}).passthrough(),qf=M.object({type:M.literal("custom"),name:M.string().min(1),description:M.string().optional(),format:M.object({type:M.literal("grammar"),syntax:M.string().min(1),definition:M.string()}).passthrough().optional()}).passthrough(),cz=M.union([Fy,qf]),_z=M.object({type:M.literal("namespace"),name:M.string().min(1),description:M.string().optional(),tools:M.array(cz)}).passthrough(),wz=M.object({type:M.literal("function"),name:M.string().min(1),description:M.string().optional(),parameters:ns.optional(),inputSchema:ns.optional(),strict:M.boolean().optional()}).passthrough().transform((n)=>({type:"function",name:n.name,...n.description!==void 0?{description:n.description}:{},...n.parameters!==void 0?{parameters:n.parameters}:n.inputSchema!==void 0?{parameters:n.inputSchema}:{},...n.strict!==void 0?{strict:n.strict}:{}})),lz=M.object({type:M.literal("function").optional(),name:M.string().min(1),description:M.string().optional(),parameters:ns.optional(),inputSchema:ns.optional(),strict:M.boolean().optional()}).passthrough().transform((n)=>({type:"function",name:n.name,...n.description!==void 0?{description:n.description}:{},...n.parameters!==void 0?{parameters:n.parameters}:n.inputSchema!==void 0?{parameters:n.inputSchema}:{},...n.strict!==void 0?{strict:n.strict}:{}})),Az=M.union([lz,qf]),Mz=M.object({type:M.literal("namespace"),name:M.string().min(1),description:M.string().optional(),tools:M.array(Az)}).passthrough().transform((n)=>({type:"namespace",name:n.name,...n.description!==void 0?{description:n.description}:{},tools:n.tools})),dz=new Set(["function","custom","namespace"]),Py=M.object({type:M.string()}).passthrough().refine((n)=>!dz.has(n.type),{message:"known tools must have a valid payload"}),Rz=M.union([Fy,qf,_z]),Ez=M.union([Rz,Py]),yz=M.union([wz,qf,Mz,Py]),Tz=M.object({type:M.literal("additional_tools"),role:M.string().optional(),tools:M.array(yz)}).passthrough(),gz=M.object({type:M.literal("summary_text"),text:M.string()}).passthrough(),Sz=M.object({type:M.literal("reasoning_text"),reasoning_text:M.string()}).passthrough(),Iz=M.object({type:M.literal("reasoning"),summary:M.array(gz).nullable().optional(),content:M.array(Sz).nullable().optional(),encrypted_content:M.string().nullable().optional()}).passthrough(),Uz=new Set(["message","agent_message","function_call","custom_tool_call","function_call_output","custom_tool_call_output","additional_tools","reasoning"]),bz=M.object({type:M.string()}).passthrough().refine((n)=>!Uz.has(n.type),{message:"known input items must have a valid payload"}),$z=M.union([rz,ez,oz,fz,hz,uz,Tz,Iz,bz]),Lz=M.object({effort:M.enum(["none","minimal","low","medium","high","xhigh","max"]).optional(),summary:M.unknown().optional()}).passthrough(),Oz=M.object({model:M.string(),input:M.union([M.string(),M.array($z)]),instructions:M.string().optional(),stream:M.boolean().default(!1),tools:M.array(Ez).optional(),tool_choice:M.literal("auto").optional(),parallel_tool_calls:M.boolean().optional(),reasoning:Lz.nullable().optional(),include:M.array(M.string()).optional(),store:M.boolean().optional(),text:M.unknown().optional(),service_tier:M.unknown().optional(),prompt_cache_key:M.string().optional(),client_metadata:M.unknown().optional(),previous_response_id:M.string().optional(),conversation:M.unknown().optional()}).passthrough();function Vf(n){let t=kf.safeParse(n);if(t.success)return{ok:!0,value:t.data};let i=t.error.issues.map((s)=>{return`${s.path.length>0?s.path.join("."):"request"}: ${s.message}`}).join(", ");return{ok:!1,response:v(400,`Invalid request: ${i}`,"invalid_request_error","invalid_request")}}function Dy(n){let t=Oz.safeParse(n);if(t.success)return{ok:!0,value:t.data};let i=t.error.issues.map((s)=>{return`${s.path.length>0?s.path.join("."):"request"}: ${s.message}`}).join(", ");return{ok:!1,response:v(400,`Invalid request: ${i}`,"invalid_request_error","invalid_request")}}import{createHash as Bz}from"crypto";function Nz(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function C_(n){if(n===null||typeof n!=="object")return JSON.stringify(n);if(Array.isArray(n))return`[${n.map(C_).join(",")}]`;return`{${Object.entries(n).filter(([,i])=>i!==void 0).sort(([i],[s])=>i.localeCompare(s)).map(([i,s])=>`${JSON.stringify(i)}:${C_(s)}`).join(",")}}`}function yi(n,t,i,s){return{keyHash:Bz("sha256").update("kiro-provider-session-affinity-v1\x00").update(n).update("\x00").update(t).update("\x00").update(i).update("\x00").update(C_(s)).digest("hex"),source:i}}function Gz(n,t){if(!Nz(n))return;let i=n[t];return typeof i==="string"&&i.length>0?i:void 0}function Hz(n){if(typeof n==="string")return{role:"user",content:n};return n.find((i)=>i.type==="message"&&i.role==="user")??n[0]}function Wz(n){return n.messages.find((t)=>t.role==="user")??n.messages[0]}function Fz(n){return n.messages.find((t)=>t.role==="user")??n.messages[0]}function Yy(n,t){if(!t)return;for(let s of["thread_id","session_id","conversation_id"]){let r=Gz(n.client_metadata,s);if(r!==void 0){let e=`responses.client_metadata.${s}`;return yi(t,"responses",e,r)}}if(n.prompt_cache_key&&n.prompt_cache_key.length>0)return yi(t,"responses","responses.prompt_cache_key",n.prompt_cache_key);let i=Hz(n.input);return i===void 0?void 0:yi(t,"responses","responses.initial_input",i)}function my(n,t){if(!t)return;if(n.prompt_cache_key&&n.prompt_cache_key.length>0)return yi(t,"chat","chat.prompt_cache_key",n.prompt_cache_key);let i=Wz(n);if(i===void 0)return;if(n.user&&n.user.length>0)return yi(t,"chat","chat.user_and_initial_input",{user:n.user,initial:i});return yi(t,"chat","chat.initial_input",i)}function Jy(n,t){if(!t)return;let i=Fz(n);if(i===void 0)return;let s=n.metadata?.user_id;if(s)return yi(t,"anthropic","anthropic.user_and_initial_input",{userId:s,initial:i});return yi(t,"anthropic","anthropic.initial_input",i)}class K_ extends Error{limit;name="RequestBodyTooLargeError";constructor(n){super(`Request body exceeds the ${n} byte limit`);this.limit=n}}function x_(n){return n.reason instanceof Error?n.reason:new DOMException("Request deadline exceeded","TimeoutError")}async function Pz(n,t,i){let s=n.body?.getReader();if(!s)return{ok:!0,text:""};let r=[],e=0,f,o=new Promise((u,c)=>{f=c}),h=()=>{let u=x_(i.combined);f?.(u),cn(()=>s.cancel(u))};i.combined.addEventListener("abort",h,{once:!0});try{while(!0){if(i.combined.aborted)throw x_(i.combined);let _=await Promise.race([s.read(),o]);if(i.combined.aborted)throw x_(i.combined);if(_.done)break;if(e+=_.value.byteLength,e>t)throw new K_(t);r.push(_.value)}let u=new Uint8Array(e),c=0;for(let _ of r)u.set(_,c),c+=_.byteLength;return{ok:!0,text:new TextDecoder().decode(u)}}catch(u){if(u instanceof K_)return cn(()=>s.cancel(u)),{ok:!1,response:v(413,u.message,"invalid_request_error","request_too_large")};if(i.deadline.aborted)return cn(()=>s.cancel(u)),{ok:!1,response:v(504,"Request deadline exceeded","timeout_error","request_timeout")};if(i.client.aborted)return cn(()=>s.cancel(u)),{ok:!1,response:v(499,"Client closed request","request_aborted","client_disconnected")};throw u}finally{i.combined.removeEventListener("abort",h)}}function Dz(n,t,i){let r=(n.body??new ReadableStream({start:(R)=>R.close()})).getReader(),e=new TextDecoder,f=new TextEncoder,o="",h,u,c=f.encode(`data: ${JSON.stringify({error:{message:"Upstream stream error",type:"upstream_error"}})}
|
|
124
244
|
|
|
125
|
-
`);if(_)
|
|
245
|
+
`),_=(R)=>{if(h!==void 0)return!1;return h=R,!0},w=()=>{t.deadline.removeEventListener("abort",d)},l=()=>{t.client.removeEventListener("abort",E)},A=(R,y)=>{if(!_(R))return;Wn(w,l,()=>{if(R==="normal-complete")u?.enqueue(f.encode(`data: [DONE]
|
|
126
246
|
|
|
127
|
-
|
|
128
|
-
|
|
247
|
+
`));else if(R==="deadline"||R==="upstream-error")u?.enqueue(c)},()=>{if(R!=="consumer-cancel")u?.close()},i),cn(()=>r.cancel(y))},d=()=>{A("deadline",t.deadline.reason instanceof Error?t.deadline.reason:new DOMException("Request deadline exceeded","TimeoutError"))},E=()=>{A("client-abort",t.client.reason instanceof Error?t.client.reason:new DOMException("Client closed request","AbortError"))};return new Response(new ReadableStream({start(R){if(u=R,t.deadline.addEventListener("abort",d,{once:!0}),t.client.addEventListener("abort",E,{once:!0}),t.deadline.aborted)d();else if(t.client.aborted)E()},async pull(R){if(h!==void 0)return;try{while(!0){if(h!==void 0)return;let y=o.indexOf(`
|
|
248
|
+
`);if(y>=0){let I=o.slice(0,y).trimEnd();if(o=o.slice(y+1),I.length>0){R.enqueue(f.encode(`data: ${I}
|
|
129
249
|
|
|
130
|
-
|
|
131
|
-
${R.content[0]?.text??""}`}if(q.length>0){if(!A.at(-1)||A.at(-1)?.assistantResponseMessage)A.push({userInputMessage:{content:"Running tools...",modelId:f,origin:ot.ORIGIN_AI_EDITOR}});A.push({assistantResponseMessage:{content:"I will execute the following tools.",toolUses:q.map(({call:R})=>R)}}),D.push(...q.map(({result:R})=>R))}let tt={content:d,modelId:f,origin:ot.ORIGIN_AI_EDITOR};if(U.length>0)tt.images=U;let J=Hg(e.tools).filter((R)=>typeof R.toolSpecification.name==="string").map((R)=>({toolSpecification:{...R.toolSpecification,name:R.toolSpecification.name??""}}));if(D.length>0||J.length>0){if(tt.userInputMessageContext={},D.length>0)tt.userInputMessageContext.toolResults=gi(D);if(J.length>0)tt.userInputMessageContext.tools=J}if(Dg(A)){let R=tt.userInputMessageContext?.tools??[],W=new Set(R.map((st)=>st.toolSpecification.name)),k=[...Yg(A)].filter((st)=>!W.has(st));if(k.length>0)tt.userInputMessageContext??={},tt.userInputMessageContext.tools=[...R,...k.map((st)=>Z7(st,S))]}let G=K7(),K={conversationState:{chatTriggerType:ot.CHAT_TRIGGER_TYPE_MANUAL,conversationId:G,currentMessage:{userInputMessage:tt},...A.length>0?{history:A}:{}},...s.profileArn?{profileArn:s.profileArn}:{}};return o===void 0?{request:K,resolved:f,convId:G}:{request:K,resolved:f,convId:G,variantEffort:o}}function s9(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 Qg(t,n,s,r=!1,i=20000,e){let{request:f,resolved:o,convId:c}=mg(t,n,s,r,i),h=Gg({model:n,think:r,budget:i,reasoningEffort:s9(t),configEffort:e?.effort,autoEffortMapping:e?.autoEffortMapping});return{conversationState:f.conversationState,...f.profileArn?{profileArn:f.profileArn}:{},streaming:!0,effectiveModel:o,conversationId:c,region:tu(s.profileArn)??s.region,...h?{effort:h}:{}}}function Jg(t){return Math.ceil(t.length/4)}async function Io(t,n){if(n?.aborted)return{kind:"aborted"};let s=t.next();if(!n)return{kind:"event",result:await s};return new Promise((r,i)=>{let e=()=>r({kind:"aborted"});n.addEventListener("abort",e,{once:!0}),s.then((f)=>{n.removeEventListener("abort",e),r({kind:"event",result:f})},(f)=>{n.removeEventListener("abort",e),i(f)})})}function Ei(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 kg(t){let n=[],s=0;for(let r of t.values()){let i=r.input;try{i=JSON.stringify(JSON.parse(r.input))}catch{i=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:i}},{type:"content_block_stop",index:s}),s+=1}return n}function Oo(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 yo(t,n,s){let r=t.outputTokens??Jg(n),i=t.inputTokens;if(i===void 0&&t.totalTokens!==void 0)i=Math.max(0,t.totalTokens-r);if(i===void 0&&t.contextUsagePercentage!==void 0&&t.contextUsagePercentage>0){let e=Math.round(Lg(s)*t.contextUsagePercentage/100);i=Math.max(0,e-r)}return{inputTokens:i??0,outputTokens:r}}class Xg extends Error{name="MissingSdkEventStreamError";constructor(){super("SDK response has no event stream")}}async function zg(t,n,s,r){let i=t.generateAssistantResponseResponse;if(!i)throw new Xg;let e=i[Symbol.asyncIterator](),f=new Map,o={},c="",h="",u=!1,_=!1;try{while(!0){let A=await Io(e,r);if(A.kind==="aborted"){if(e.return)await e.return();_=!0;break}if(A.result.done){u=!0;break}let M=A.result.value;Oo(o,M),h+=M.reasoningContentEvent?.text??"",c+=M.assistantResponseEvent?.content??"",Ei(f,M.toolUseEvent)}}finally{if(!u&&!_&&e.return)await e.return()}let l=yo(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:l.inputTokens,completion_tokens:l.outputTokens,total_tokens:l.inputTokens+l.outputTokens}}}var r9=[/input is too long/i,/CONTENT_LENGTH_EXCEEDS_THRESHOLD/i],i9=/econnreset|etimedout|enotfound|network|fetch failed|socket/i;function Go(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function t0(t,n){let s=t[n];return typeof s==="string"?s:void 0}function e9(t){let n=t.$metadata;if(!Go(n))return;let s=n.httpStatusCode;return typeof s==="number"?s:void 0}function o9(t){let n=t.$response;if(!Go(n))return;let s=n.headers;if(!Go(s))return;let r={};for(let[i,e]of Object.entries(s))if(typeof e==="string")r[i]=e;else if(typeof e==="number")r[i]=String(e);return Object.keys(r).length>0?r:void 0}function n0(t){if(!Go(t))return{message:t instanceof Error?t.message:String(t)};let n=e9(t),s=t0(t,"message")??String(t),r=t0(t,"name"),i=t0(t,"reason"),e=o9(t);return{message:s,...n!==void 0?{status:n}:{},...r!==void 0?{code:r}:{},...i!==void 0?{reason:i}:{},...e!==void 0?{headers:e}:{}}}function f9(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 c9(t){return r9.some((n)=>n.test(t))}function xg(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:c9(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(yi(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=f9(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(i9.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 qg=Promise.resolve();function In(t){return t.reason instanceof Error?t.reason:new DOMException("The request was aborted","AbortError")}function lr(t,n){if(n.aborted)return Promise.reject(In(n));return new Promise((s,r)=>{let i=()=>r(In(n));n.addEventListener("abort",i,{once:!0}),t.then((e)=>{n.removeEventListener("abort",i),s(e)},(e)=>{n.removeEventListener("abort",i),r(e)})})}function Cg(t,n){if(t<=0)return Promise.resolve();return lr(Bun.sleep(t),n)}async function Kg(t){let n=qg,s,r=new Promise((f)=>{s=f});if(!s)throw TypeError("Queue release was not initialized");let i=s;qg=n.catch(()=>{return}).then(()=>r);try{await lr(n,t)}catch(f){throw i(),f}let e=!1;return()=>{if(e)return;e=!0,i()}}function Vg(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 di="<\uFF5CDSML\uFF5Cfunction_calls";function s0(){return`tool_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}function h9(t){let n=[],s=/```[\s\S]*?```/g;for(let e=s.exec(t);e!==null;e=s.exec(t))n.push([e.index,e.index+e[0].length]);let r=(e)=>n.some(([f,o])=>e>=f&&e<o),i=/`[^`\n]+`/g;for(let e=i.exec(t);e!==null;e=i.exec(t))if(!r(e.index))n.push([e.index,e.index+e[0].length]);return n}function ds(t,n,s){return s.some(([r,i])=>t<i&&n>r)}function u9(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 i=r[1];if(i===void 0)continue;let e=r[2]??"";try{n[i]=JSON.parse(e)}catch{n[i]=e}}return n}function jg(t,n){return{toolUseId:s0(),name:t,input:u9(n)}}function _9(t,n,s){let r=[],i=/<function_calls>[\s\S]*?<\/function_calls>/g;for(let f=i.exec(t);f!==null;f=i.exec(t)){let o=f.index,c=o+f[0].length;if(ds(o,c,n))continue;let h=/<invoke\s+name="([^"]+)"\s*>([\s\S]*?)<\/invoke>/g,u=[];for(let _=h.exec(f[0]);_!==null;_=h.exec(f[0])){let l=_[1];if(l)u.push(jg(l,_[2]??""))}if(u.length===0)continue;r.push({start:o,end:c,toolCalls:u}),s.push([o,c])}let e=/<invoke\s+name="([^"]+)"\s*>([\s\S]*?)<\/invoke>/g;for(let f=e.exec(t);f!==null;f=e.exec(t)){let o=f.index,c=o+f[0].length,h=f[1];if(!h||ds(o,c,n)||ds(o,c,s))continue;r.push({start:o,end:c,toolCalls:[jg(h,f[2]??"")]}),s.push([o,c])}return r}function l9(t,n,s){let r=[],i=0;for(;;){let e=t.indexOf(di,i);if(e===-1)break;let f=t.slice(e+di.length),o=/<\uFF5C[^>]*?end[^>]*?>|<\/\uFF5CDSML[^>]*?>/.exec(f),c=o!==null?e+di.length+o.index+o[0].length:t.length;if(i=c,ds(e,c,n)||ds(e,c,s))continue;let h=t.slice(e,c),u=[],_=/name["\uFF5C=:\s]+["']?([A-Za-z0-9_]+)/.exec(h),l=/(\{[\s\S]*\})/.exec(h);if(_?.[1]&&l?.[1])try{u.push({toolUseId:s0(),name:_[1],input:JSON.parse(l[1])})}catch{}r.push({start:e,end:c,toolCalls:u}),s.push([e,c])}return r}function w9(t,n,s){let r=[],i=/\[Called\s+(\w+)\s+with\s+args:\s*(\{[^}]*(?:\{[^}]*\}[^}]*)*\})\]/gs;for(let e=i.exec(t);e!==null;e=i.exec(t)){let f=e.index,o=f+e[0].length,c=e[1],h=e[2];if(!c||!h||ds(f,o,n)||ds(f,o,s))continue;let u;try{u=JSON.parse(h)}catch{continue}r.push({start:f,end:o,toolCalls:[{toolUseId:s0(),name:c,input:u}]}),s.push([f,o])}return r}function ag(t){if(!t)return{toolCalls:[],cleanedText:t};let n=h9(t),s=[],r=[..._9(t,n,s),...l9(t,n,s),...w9(t,n,s)];if(r.length===0)return{toolCalls:[],cleanedText:t};r.sort((o,c)=>o.start-c.start);let i=[],e="",f=0;for(let o of r){if(o.start<f)continue;e+=t.slice(f,o.start),f=o.end,i.push(...o.toolCalls)}return e+=t.slice(f),{toolCalls:i,cleanedText:e}}var r0=["<function_calls","<invoke name=",di],A9=Math.max(...r0.map((t)=>t.length));function pg(t){let n=-1;for(let s of r0){let r=t.indexOf(s);if(r!==-1&&(n===-1||r<n))n=r}return n}function M9(t){let n=Math.min(t.length,A9-1);for(let s=n;s>0;s--){let r=t.slice(t.length-s);for(let i of r0)if(i.length>s&&i.startsWith(r))return s}return 0}class i0{accumulated="";emitted=0;markerSeen=!1;push(t){if(!t)return"";if(this.accumulated+=t,!this.markerSeen&&pg(this.accumulated)!==-1)this.markerSeen=!0;let n;if(this.markerSeen){let r=pg(this.accumulated);n=r===-1?this.accumulated.length:r}else n=this.accumulated.length-M9(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}=ag(this.accumulated),s=n.length>this.emitted?n.slice(this.emitted):"";return{toolCalls:t,remainderText:s}}}function e0(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 i={id:n,object:"chat.completion.chunk",created:Math.floor(Date.now()/1000),model:s,choices:r};if(t.type!=="message_delta")return i;let e=t.usage?.input_tokens??0,f=t.usage?.output_tokens??0;return{...i,usage:{prompt_tokens:e,completion_tokens:f,total_tokens:e+f}}}function o0(t,n){let s=/```[\s\S]*?```/g,r=[],i=s.exec(t);while(i!==null)r.push([i.index,i.index+i[0].length]),i=s.exec(t);let e=t.indexOf(n,0);while(e!==-1){if(!r.some(([o,c])=>e>=o&&e<c))return e;e=t.indexOf(n,e+n.length)}return-1}function Zg(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 Cn(t,n){if(!t)return[];let s=Zg("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 Kn(t,n){let s=Zg("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 Bo="<thinking>",Fo="</thinking>";function vg(t,n){n.buffer+=t;let s=[];while(n.buffer.length>0){if(!n.inThinking&&!n.thinkingExtracted){let i=o0(n.buffer,Bo);if(i!==-1){let f=n.buffer.slice(0,i);s.push(...Cn(f,n)),n.buffer=n.buffer.slice(i+Bo.length),n.inThinking=!0;continue}let e=Math.max(0,n.buffer.length-Bo.length);if(e>0)s.push(...Cn(n.buffer.slice(0,e),n)),n.buffer=n.buffer.slice(e);break}if(n.inThinking){let i=o0(n.buffer,Fo);if(i!==-1){if(s.push(...Kn(n.buffer.slice(0,i),n)),n.buffer=n.buffer.slice(i+Fo.length),n.inThinking=!1,n.thinkingExtracted=!0,s.push(...Kn("",n)),s.push(...Rs(n.thinkingBlockIndex,n)),n.buffer.startsWith(`
|
|
250
|
+
`));return}continue}let T=await r.read();if(h!==void 0)return;if(!T.done){o+=e.decode(T.value,{stream:!0});continue}o+=e.decode();let S=o.trim();if(o="",S.length>0){R.enqueue(f.encode(`data: ${S}
|
|
132
251
|
|
|
133
|
-
`))
|
|
134
|
-
`))}catch(M){if(u(),A?.(),i.signal.aborted)return;let E=M instanceof Error?M:TypeError("SDK stream failed with a non-Error reason",{cause:M});i.abort(E),w.error(E);try{await l()}finally{_()}}finally{u(),A?.()}},async cancel(){u(),i.abort();try{await l()}catch{return}finally{_()}}}),{headers:{"Content-Type":"application/x-ndjson; charset=utf-8"}})}var oE=Y(me(),1);var eE=new Map,g9=3;function Ho(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function E9(t){let n=t.conversationState;if(!Ho(n))return;let s=n.currentMessage;if(!Ho(s))return;let r=s.userInputMessage;if(!Ho(r))return;let i=r.modelId;return typeof i==="string"?i:void 0}function d9(t,n,s,r){let i=r?(()=>{let e=p0(r);return new oE.NodeHttpHandler({httpAgent:e,httpsAgent:e})})():void 0;return{region:n,endpoint:s,token:()=>Promise.resolve({token:t.access}),maxAttempts:g9,retryMode:"standard",customUserAgent:[[ot.USER_AGENT]],...i?{requestHandler:i}:{}}}function fE(t,n,s,r,i){let e=r??`https://q.${n}.amazonaws.com`,f=JSON.stringify([n,t.email??null,s??null,e,i??null]),o=eE.get(f);if(o?.token===t.access)return o.client;let c=new ph(d9(t,n,e,i));if(c.middlewareStack.add((h)=>async(u)=>{if(u.request instanceof Gt.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 Gt.HttpRequest&&typeof u.request.body==="string")try{let _=JSON.parse(u.request.body);if(Ho(_)){let l=E9(_);if(l)_.additionalModelRequestFields=yg(l,s),u.request.body=JSON.stringify(_)}}catch(_){if(!(_ instanceof SyntaxError))throw _}return h(u)},{step:"build",name:"addEffortConfig",priority:"high"});return eE.set(f,{client:c,token:t.access}),c}function bs(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function R9(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 b9(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,i=bs(r)?r.thinkingConfig:void 0,e=s.thinkingConfig,f=bs(i)?i:bs(e)?e:void 0,o=f?.thinkingBudget??f?.budget_tokens;return{think:n.endsWith("-thinking")||f!==void 0,budget:typeof o==="number"?o:20000}}function T9(t,n,s){return V(t,n,"upstream_error",s)}async function S9(t,n){let{think:s,budget:r}=b9(t.body,t.model),i=new Set,e=new Map,f=0,o=0;while(!0){if(n.aborted)throw In(n);if(o+=1,o>t.config.max_request_iterations)return{kind:"response",response:V(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:V(503,"All accounts are unhealthy or rate-limited","service_unavailable","no_healthy_accounts")};let h=t.accountManager.toAuthDetails(c),u=await lr(t.tokenRefresher.refreshIfNeeded(c,h,n),n),_=t.accountManager.toAuthDetails(u),l=Li.safeParse(t.config.effort),w=Qg(t.body,t.model,_,s,r,{autoEffortMapping:t.config.auto_effort_mapping,...l.success?{effort:l.data}:{}}),M=(t.makeClient??fE)(_,w.region,w.effort,t.config.test_upstream_endpoint,Qs(t.config)),E={conversationState:w.conversationState,...w.profileArn?{profileArn:w.profileArn}:{}};if(!R9(E))throw TypeError("Transformed request is not a valid SDK command input");let d=new Zh(E);try{let T=await lr(M.send(d,{abortSignal:n}),n);if(t.stream)return{kind:"stream",sdkResponse:T,model:t.model,conversationId:w.conversationId};let U=await zg(T,t.model,w.conversationId,n);if(n.aborted)throw In(n);return{kind:"response",response:Response.json(U,{headers:{"Content-Type":"application/json"}})}}catch(T){if(n.aborted)throw In(n);let U=n0(T),S=U.status===500?(e.get(u.id)??0)+1:0;if(U.status===500)e.set(u.id,S);let O=xg(U,{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:i});switch(O.action){case"refresh-then-retry":await lr(t.tokenRefresher.forceRefresh(u,n),n);continue;case"retry":f+=1,await Cg(O.retryAfterMs??0,n);continue;case"switch":if(U.reason==="TEMPORARILY_SUSPENDED")t.accountManager.markUnhealthy(u,`InvalidTokenException: Account Suspended: ${U.message}`);else t.accountManager.markRateLimited(u,Date.now()+(O.retryAfterMs??t.config.rate_limit_retry_delay_ms));continue;case"fail":if(U.reason==="TEMPORARILY_SUSPENDED")t.accountManager.markUnhealthy(u,`InvalidTokenException: Account Suspended: ${U.message}`);return{kind:"response",response:T9(O.terminalStatus??O.status??500,U.message,U.code)}}}}}async function Po(t){let n=Vg(t.deadlineSignal,t.config.request_timeout_ms),s,r=!1;try{s=await Kg(n.signal);let i=await S9(t,n.signal);if(i.kind==="response")return i.response;let e=s;return s=void 0,r=!0,iE(i,n.signal,t.config.stream_idle_timeout_ms,()=>{e(),n.dispose()})}catch(i){if(n.signal.aborted)return V(504,"Request deadline exceeded","timeout_error","request_timeout");let e=n0(i);return V(500,e.message,"internal_error",e.code)}finally{if(!r)s?.(),n.dispose()}}var Ri=Object.freeze({input:Object.freeze(["text"]),output:Object.freeze(["text"])}),ut=Object.freeze({input:Object.freeze(["text","image"]),output:Object.freeze(["text"])}),a=Object.freeze({input:Object.freeze(["text","image","pdf"]),output:Object.freeze(["text"])}),cE=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"]),hE=Object.freeze([{id:"auto",wireId:"auto",name:"Auto (1.0x)",contextLimit:B("auto"),outputLimit:64000,modalities:a},{id:"claude-sonnet-4",wireId:"claude-sonnet-4",name:"Claude Sonnet 4.0 (1.3x)",contextLimit:B("claude-sonnet-4"),outputLimit:64000,modalities:a},{id:"claude-sonnet-4-5",wireId:"claude-sonnet-4.5",name:"Claude Sonnet 4.5 (1.3x)",contextLimit:B("claude-sonnet-4-5"),outputLimit:64000,modalities:a},{id:"claude-sonnet-4-6",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (1.3x)",contextLimit:B("claude-sonnet-4-6"),outputLimit:64000,modalities:a},{id:"claude-sonnet-4-6-low",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (low) (1.3x)",contextLimit:B("claude-sonnet-4-6"),outputLimit:64000,modalities:a},{id:"claude-sonnet-4-6-medium",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (medium) (1.3x)",contextLimit:B("claude-sonnet-4-6"),outputLimit:64000,modalities:a},{id:"claude-sonnet-4-6-high",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (high) (1.3x)",contextLimit:B("claude-sonnet-4-6"),outputLimit:64000,modalities:a},{id:"claude-sonnet-4-6-max",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (max) (1.3x)",contextLimit:B("claude-sonnet-4-6"),outputLimit:64000,modalities:a},{id:"claude-sonnet-5",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (1.3x)",contextLimit:B("claude-sonnet-5"),outputLimit:64000,modalities:a},{id:"claude-sonnet-5-low",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (low) (1.3x)",contextLimit:B("claude-sonnet-5"),outputLimit:64000,modalities:a},{id:"claude-sonnet-5-medium",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (medium) (1.3x)",contextLimit:B("claude-sonnet-5"),outputLimit:64000,modalities:a},{id:"claude-sonnet-5-high",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (high) (1.3x)",contextLimit:B("claude-sonnet-5"),outputLimit:64000,modalities:a},{id:"claude-sonnet-5-xhigh",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (xhigh) (1.3x)",contextLimit:B("claude-sonnet-5"),outputLimit:64000,modalities:a},{id:"claude-sonnet-5-max",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (max) (1.3x)",contextLimit:B("claude-sonnet-5"),outputLimit:64000,modalities:a},{id:"claude-haiku-4-5",wireId:"claude-haiku-4.5",name:"Claude Haiku 4.5 (0.4x)",contextLimit:B("claude-haiku-4-5"),outputLimit:64000,modalities:ut},{id:"claude-opus-4-5",wireId:"claude-opus-4.5",name:"Claude Opus 4.5 (2.2x)",contextLimit:B("claude-opus-4-5"),outputLimit:64000,modalities:a},{id:"claude-opus-4-6",wireId:"claude-opus-4.6",name:"Claude Opus 4.6 (2.2x)",contextLimit:B("claude-opus-4-6"),outputLimit:64000,modalities:a},{id:"claude-opus-4-7",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (2.2x)",contextLimit:B("claude-opus-4-7"),outputLimit:64000,modalities:a},{id:"claude-opus-4-7-low",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (low) (2.2x)",contextLimit:B("claude-opus-4-7"),outputLimit:64000,modalities:a},{id:"claude-opus-4-7-medium",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (medium) (2.2x)",contextLimit:B("claude-opus-4-7"),outputLimit:64000,modalities:a},{id:"claude-opus-4-7-high",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (high) (2.2x)",contextLimit:B("claude-opus-4-7"),outputLimit:64000,modalities:a},{id:"claude-opus-4-7-xhigh",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (xhigh) (2.2x)",contextLimit:B("claude-opus-4-7"),outputLimit:64000,modalities:a},{id:"claude-opus-4-7-max",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (max) (2.2x)",contextLimit:B("claude-opus-4-7"),outputLimit:64000,modalities:a},{id:"claude-opus-4-8",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (2.2x)",contextLimit:B("claude-opus-4-8"),outputLimit:64000,modalities:a},{id:"claude-opus-4-8-low",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (low) (2.2x)",contextLimit:B("claude-opus-4-8"),outputLimit:64000,modalities:a},{id:"claude-opus-4-8-medium",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (medium) (2.2x)",contextLimit:B("claude-opus-4-8"),outputLimit:64000,modalities:a},{id:"claude-opus-4-8-high",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (high) (2.2x)",contextLimit:B("claude-opus-4-8"),outputLimit:64000,modalities:a},{id:"claude-opus-4-8-xhigh",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (xhigh) (2.2x)",contextLimit:B("claude-opus-4-8"),outputLimit:64000,modalities:a},{id:"claude-opus-4-8-max",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (max) (2.2x)",contextLimit:B("claude-opus-4-8"),outputLimit:64000,modalities:a},{id:"claude-opus-4-8-thinking",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 Thinking (2.2x)",contextLimit:B("claude-opus-4-8"),outputLimit:64000,modalities:a},{id:"deepseek-3.2",wireId:"deepseek-3.2",name:"DeepSeek 3.2 (0.25x)",contextLimit:B("deepseek-3.2"),outputLimit:64000,modalities:Ri},{id:"glm-5",wireId:"glm-5",name:"GLM-5 (0.5x)",contextLimit:B("glm-5"),outputLimit:64000,modalities:Ri},{id:"minimax-m2.5",wireId:"minimax-m2.5",name:"MiniMax M2.5 (0.25x)",contextLimit:B("minimax-m2.5"),outputLimit:64000,modalities:Ri},{id:"minimax-m2.1",wireId:"minimax-m2.1",name:"MiniMax M2.1 (0.15x)",contextLimit:B("minimax-m2.1"),outputLimit:64000,modalities:Ri},{id:"qwen3-coder-next",wireId:"qwen3-coder-next",name:"Qwen3 Coder Next (0.05x)",contextLimit:B("qwen3-coder-next"),outputLimit:64000,modalities:Ri},{id:"gpt-5.6-sol",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (2.4x)",contextLimit:B("gpt-5.6-sol"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-sol-low",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (low) (2.4x)",contextLimit:B("gpt-5.6-sol"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-sol-medium",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (medium) (2.4x)",contextLimit:B("gpt-5.6-sol"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-sol-high",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (high) (2.4x)",contextLimit:B("gpt-5.6-sol"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-sol-xhigh",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (xhigh) (2.4x)",contextLimit:B("gpt-5.6-sol"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-sol-max",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (max) (2.4x)",contextLimit:B("gpt-5.6-sol"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-terra",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (1.2x)",contextLimit:B("gpt-5.6-terra"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-terra-low",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (low) (1.2x)",contextLimit:B("gpt-5.6-terra"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-terra-medium",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (medium) (1.2x)",contextLimit:B("gpt-5.6-terra"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-terra-high",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (high) (1.2x)",contextLimit:B("gpt-5.6-terra"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-terra-xhigh",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (xhigh) (1.2x)",contextLimit:B("gpt-5.6-terra"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-terra-max",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (max) (1.2x)",contextLimit:B("gpt-5.6-terra"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-luna",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna",contextLimit:B("gpt-5.6-luna"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-luna-low",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (low)",contextLimit:B("gpt-5.6-luna"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-luna-medium",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (medium)",contextLimit:B("gpt-5.6-luna"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-luna-high",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (high)",contextLimit:B("gpt-5.6-luna"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-luna-xhigh",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (xhigh)",contextLimit:B("gpt-5.6-luna"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-luna-max",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (max)",contextLimit:B("gpt-5.6-luna"),outputLimit:64000,modalities:ut}]);var f0=g.record(g.unknown()),$9=new Set(cE),U9=g.object({type:g.literal("text"),text:g.string()}).passthrough(),L9=g.object({type:g.literal("image_url"),image_url:g.object({url:g.string(),detail:g.string().optional()}).passthrough()}).passthrough(),I9=g.object({type:g.literal("image"),source:g.object({type:g.string(),data:g.string(),media_type:g.string().optional()}).passthrough()}).passthrough(),O9=g.object({type:g.literal("tool_result"),tool_use_id:g.string().min(1),content:g.unknown()}).passthrough(),y9=g.object({type:g.literal("tool_use"),id:g.string().min(1),name:g.string().min(1),input:g.unknown()}).passthrough(),G9=g.object({type:g.literal("thinking"),thinking:g.string().optional(),text:g.string().optional()}).passthrough(),B9=g.discriminatedUnion("type",[U9,L9,I9,O9,y9,G9]),No=g.union([g.string(),g.array(B9)]);function uE(t){try{return JSON.parse(t),!0}catch(n){if(n instanceof SyntaxError)return!1;throw n}}var F9=g.object({id:g.string().min(1),type:g.literal("function"),function:g.object({name:g.string().min(1),arguments:g.string().refine(uE,"function arguments must contain valid JSON")}).passthrough()}).passthrough(),H9=g.object({role:g.literal("system"),content:No}).passthrough(),P9=g.object({role:g.literal("user"),content:No}).passthrough(),N9=g.object({role:g.literal("assistant"),content:No.nullable().optional(),tool_calls:g.array(F9).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"}),W9=g.object({role:g.literal("tool"),content:No,tool_call_id:g.string().min(1)}).passthrough(),D9=g.union([H9,P9,N9,W9]),Y9=g.object({type:g.literal("function"),function:g.object({name:g.string().min(1),description:g.string().optional(),parameters:f0.optional()}).passthrough()}).passthrough(),m9=g.object({name:g.string().min(1),description:g.string().optional(),input_schema:f0.optional()}).passthrough(),Q9=g.object({model:g.string().refine((t)=>$9.has(t),{message:"model is not supported"}),stream:g.boolean().default(!1),messages:g.array(D9).min(1),tools:g.array(g.union([Y9,m9])).optional(),reasoning_effort:g.enum(["low","medium","high","xhigh","max"]).optional()}).passthrough(),J9=g.object({type:g.literal("input_text"),text:g.string()}).passthrough(),k9=g.object({type:g.literal("output_text"),text:g.string()}).passthrough(),X9=g.object({type:g.literal("input_image"),image_url:g.string()}).passthrough(),z9=new Set(["input_text","output_text","input_image"]),x9=g.object({type:g.string()}).passthrough().refine((t)=>!z9.has(t.type),{message:"known content parts must have a valid payload"}),q9=g.union([J9,k9,X9,x9]),C9=g.object({type:g.literal("message"),role:g.enum(["system","user","assistant"]),content:g.array(q9)}).passthrough(),K9=g.object({type:g.literal("function_call"),call_id:g.string().min(1),name:g.string().min(1),arguments:g.string().refine(uE,"function arguments must contain valid JSON")}).passthrough(),V9=g.object({type:g.literal("function_call_output"),call_id:g.string().min(1),output:g.string()}).passthrough(),j9=g.object({type:g.literal("summary_text"),text:g.string()}).passthrough(),a9=g.object({type:g.literal("reasoning_text"),reasoning_text:g.string()}).passthrough(),p9=g.object({type:g.literal("reasoning"),summary:g.array(j9).optional(),content:g.array(a9).optional(),encrypted_content:g.string().optional()}).passthrough(),Z9=new Set(["message","function_call","function_call_output","reasoning"]),v9=g.object({type:g.string()}).passthrough().refine((t)=>!Z9.has(t.type),{message:"known input items must have a valid payload"}),tY=g.union([C9,K9,V9,p9,v9]),nY=g.object({type:g.literal("function"),name:g.string().min(1),description:g.string().optional(),parameters:f0.optional(),strict:g.boolean().optional()}).passthrough(),sY=g.object({effort:g.enum(["none","minimal","low","medium","high","xhigh"]).optional(),summary:g.unknown().optional()}).passthrough(),rY=g.object({model:g.string(),input:g.union([g.string(),g.array(tY)]),instructions:g.string().optional(),stream:g.boolean().default(!1),tools:g.array(nY).optional(),tool_choice:g.literal("auto").optional(),parallel_tool_calls:g.boolean().optional(),reasoning:sY.nullable().optional(),include:g.array(g.string()).optional(),store:g.boolean().optional(),text:g.unknown().optional(),service_tier:g.unknown().optional(),prompt_cache_key:g.string().optional(),client_metadata:g.unknown().optional(),previous_response_id:g.string().optional()}).passthrough();function Wo(t){let n=Q9.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:V(400,`Invalid request: ${s}`,"invalid_request_error","invalid_request")}}function _E(t){let n=rY.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:V(400,`Invalid request: ${s}`,"invalid_request_error","invalid_request")}}class h0 extends Error{limit;name="RequestBodyTooLargeError";constructor(t){super(`Request body exceeds the ${t} byte limit`);this.limit=t}}function c0(t){return t.reason instanceof Error?t.reason:new DOMException("Request deadline exceeded","TimeoutError")}async function iY(t,n,s){let r=t.body?.getReader();if(!r)return{ok:!0,text:""};let i=[],e=0,f,o=new Promise((h,u)=>{f=u}),c=()=>{let h=c0(s.combined);f?.(h),r.cancel(h)};s.combined.addEventListener("abort",c,{once:!0});try{while(!0){if(s.combined.aborted)throw c0(s.combined);let _=await Promise.race([r.read(),o]);if(s.combined.aborted)throw c0(s.combined);if(_.done)break;if(e+=_.value.byteLength,e>n)throw new h0(n);i.push(_.value)}let h=new Uint8Array(e),u=0;for(let _ of i)h.set(_,u),u+=_.byteLength;return{ok:!0,text:new TextDecoder().decode(h)}}catch(h){if(h instanceof h0)return r.cancel(h).catch(()=>{return}),{ok:!1,response:V(413,h.message,"invalid_request_error","request_too_large")};if(s.deadline.aborted)return r.cancel(h).catch(()=>{return}),{ok:!1,response:V(504,"Request deadline exceeded","timeout_error","request_timeout")};if(s.client.aborted)return r.cancel(h).catch(()=>{return}),{ok:!1,response:V(499,"Client closed request","request_aborted","client_disconnected")};throw h}finally{s.combined.removeEventListener("abort",c)}}function eY(t,n){let s=t.body;if(!s)return t;let r=s.getReader(),i=new TextDecoder,e=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 _=f.indexOf(`
|
|
135
|
-
`);if(_>=0){let A=f.slice(0,_).trimEnd();if(f=f.slice(_+1),A.length>0){u.enqueue(e.encode(`data: ${A}
|
|
252
|
+
`));return}A("normal-complete");return}}catch(y){if(h!==void 0)return;A("upstream-error",y)}},cancel(R){A("consumer-cancel",R)}}),{status:n.status,headers:{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive"}})}async function Xy(n,t,i){let s=new AbortController,r=setTimeout(()=>s.abort(new DOMException("Request deadline exceeded","TimeoutError")),t.request_timeout_ms),e=AbortSignal.any([s.signal,n.signal]),f={combined:e,deadline:s.signal,client:n.signal},o=await Pz(n,t.max_request_body_bytes,f);if(!o.ok)return clearTimeout(r),o.response;let h;try{h=JSON.parse(o.text)}catch(A){if(clearTimeout(r),!(A instanceof SyntaxError))throw A;return v(400,"Request body must contain valid JSON","invalid_request_error","invalid_json")}let u=Vf(h);if(!u.ok)return clearTimeout(r),u.response;let c=my(u.value,i.tenantId),_,w=!1,l=()=>{Wn(()=>clearTimeout(r),()=>_?.restore())};try{_=i.createRequestIdleTimeoutLease?.(),_?.disable();let A=await(i.runPipeline??ir)({body:u.value,model:u.value.model,stream:u.value.stream,config:t,accountManager:i.accountManager,tokenRefresher:i.tokenRefresher,...c?{affinity:c}:{},...i.affinityStore?{affinityStore:i.affinityStore}:{},deadlineSignal:e,...i.makeClient?{makeClient:i.makeClient}:{}});if(n.signal.aborted&&!s.signal.aborted)return cn(()=>A.body?.cancel()),v(499,"Client closed request","request_aborted","client_disconnected");let d=A.headers.get("Content-Type")??"";if(!u.value.stream||d.includes("application/json"))return A;if(!d.includes("application/x-ndjson"))return cn(()=>A.body?.cancel()),v(500,"Pipeline returned an unsupported streaming response","internal_error","invalid_pipeline_response");let E=Dz(A,f,l);return w=!0,E}finally{if(!w)l()}}function zy(){return new Response(JSON.stringify({status:"ok"}),{status:200,headers:{"Content-Type":"application/json"}})}var Qy=M.object({type:M.string().min(1)}).passthrough(),Yz=M.object({role:M.enum(["user","assistant"]),content:M.union([M.string(),M.array(Qy)])}).passthrough(),mz=M.object({name:M.string().min(1),description:M.string().optional(),input_schema:M.record(M.unknown()).optional()}).passthrough(),Jz=M.object({type:M.enum(["auto","any","tool","none"]),name:M.string().min(1).optional(),disable_parallel_tool_use:M.boolean().optional()}).passthrough().refine((n)=>n.type!=="tool"||n.name!==void 0,{message:"tool_choice.name is required when tool_choice.type is tool"}),Xz=M.object({type:M.enum(["enabled","adaptive","disabled"]),budget_tokens:M.number().int().positive().optional()}).passthrough(),zz=M.object({model:M.string().min(1),max_tokens:M.number().int().positive().optional(),messages:M.array(Yz).min(1),system:M.union([M.string(),M.array(Qy)]).optional(),stream:M.boolean().default(!1),tools:M.array(mz).optional(),tool_choice:Jz.optional(),thinking:Xz.optional(),output_config:M.object({effort:M.enum(["low","medium","high","xhigh","max"]).optional()}).passthrough().optional(),metadata:M.object({user_id:M.string().min(1).optional()}).passthrough().optional()}).passthrough();function Cy(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function Qz(n){return n.issues.map((t)=>{return`${t.path.length>0?t.path.join("."):"request"}: ${t.message}`}).join(", ")}function Cz(n){if(typeof n==="string")return n;if(!n)return"";return n.flatMap((t)=>t.type==="text"&&typeof t.text==="string"?[t.text]:[]).join(`
|
|
136
253
|
|
|
137
|
-
`));return}continue}let
|
|
138
|
-
|
|
139
|
-
`));return}if(!o){o=!0,u.enqueue(e.encode(`data: [DONE]
|
|
254
|
+
`)}function xz(n){if(typeof n==="string")return n;if(Array.isArray(n)){let t=n.flatMap((i)=>Cy(i)&&i.type==="text"&&typeof i.text==="string"?[i.text]:[]).join("");if(t.length>0)return t}try{return JSON.stringify(n)}catch{return String(n)}}function Kz(n){switch(n.type){case"text":return typeof n.text==="string"?{...n,text:n.text}:void 0;case"image":{if(!Cy(n.source))return;if(typeof n.source.type!=="string"||typeof n.source.data!=="string")return;return{...n}}case"tool_use":return typeof n.id==="string"&&typeof n.name==="string"?{...n,input:n.input??{}}:void 0;case"tool_result":{if(typeof n.tool_use_id!=="string")return;let t=xz(n.content);return{...n,content:t}}case"thinking":case"redacted_thinking":return;default:return}}function kz(n){let t=[];for(let i of n){if(typeof i.content==="string"){t.push({role:i.role,content:i.content});continue}let s=i.content.flatMap((r)=>{let e=Kz(r);return e?[e]:[]});if(s.length===0)return;t.push({role:i.role,content:s})}return t}function k_(n,t={}){let i=zz.safeParse(n);if(!i.success)return{ok:!1,message:`Invalid request: ${Qz(i.error)}`};if(t.requireMaxTokens===!0&&i.data.max_tokens===void 0)return{ok:!1,message:"Invalid request: max_tokens is required"};if(i.data.tool_choice?.type==="any"||i.data.tool_choice?.type==="tool")return{ok:!1,message:`Invalid request: tool_choice.type ${i.data.tool_choice.type} is not supported because the Kiro upstream has no structured forced-tool control`};if(i.data.tool_choice?.disable_parallel_tool_use===!0)return{ok:!1,message:"Invalid request: disable_parallel_tool_use is not supported by the Kiro upstream"};let s=kz(i.data.messages);if(!s)return{ok:!1,message:"Invalid request: every message must contain a supported content block"};let r=Cz(i.data.system),e=new Set;for(let u of i.data.tools??[]){if(e.has(u.name))return{ok:!1,message:`Invalid request: duplicate tool name ${u.name}`};e.add(u.name)}let f=i.data.tool_choice?.type==="none"?[]:i.data.tools,o=i.data.thinking?.type==="enabled"||i.data.thinking?.type==="adaptive"?{budget_tokens:i.data.thinking.budget_tokens??20000}:void 0,h={model:i.data.model,stream:i.data.stream,...i.data.max_tokens!==void 0?{max_tokens:i.data.max_tokens}:{},messages:s,...r?{system:r}:{},...f!==void 0?{tools:f}:{},...o?{thinkingConfig:o}:{},...i.data.output_config?.effort?{reasoning_effort:i.data.output_config.effort}:{}};return{ok:!0,value:{source:i.data,body:h}}}import{randomUUID as Ky}from"crypto";function Mt(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function xy(n){if(!Mt(n))return;if(typeof n.prompt_tokens!=="number"||typeof n.completion_tokens!=="number"||typeof n.total_tokens!=="number")return;return{inputTokens:n.prompt_tokens,outputTokens:n.completion_tokens,totalTokens:n.total_tokens}}function jf(n){if(!Mt(n)||!Array.isArray(n.choices))return;let t=xy(n.usage);if(!t)return;let i=n.choices[0];if(!Mt(i)||!Mt(i.message))return;let s=i.message;if(typeof s.content!=="string")return;let r=s.reasoning_content;if(r!==void 0&&typeof r!=="string")return;let e=[];if(s.tool_calls!==void 0){if(!Array.isArray(s.tool_calls))return;for(let f of s.tool_calls){if(!Mt(f)||typeof f.id!=="string"||!Mt(f.function)||typeof f.function.name!=="string"||typeof f.function.arguments!=="string")return;e.push({id:f.id,name:f.function.name,arguments:f.function.arguments})}}return{message:{content:s.content,reasoningContent:r,toolCalls:e},usage:t}}function qz(n){if(!Mt(n)||typeof n.index!=="number"||!Mt(n.function))return;let t=n.id,i=n.function.name,s=n.function.arguments;if(t!==void 0&&typeof t!=="string"||i!==void 0&&typeof i!=="string"||typeof s!=="string")return;return{index:n.index,id:t,name:i,arguments:s}}function Vz(n){if(!Mt(n))return;let t=["content","reasoning_content","tool_calls"].filter((s)=>n[s]!==void 0);if(t.length===0)return{kind:"empty"};if(t.length!==1)return;if(typeof n.content==="string")return{kind:"text",text:n.content};if(typeof n.reasoning_content==="string")return{kind:"reasoning",text:n.reasoning_content};if(!Array.isArray(n.tool_calls))return;let i=[];for(let s of n.tool_calls){let r=qz(s);if(!r)return;i.push(r)}return{kind:"tool_calls",calls:i}}function sr(n){let t;try{t=JSON.parse(n)}catch(f){if(f instanceof SyntaxError)return;throw f}if(!Mt(t)||t.object!=="chat.completion.chunk"||!Array.isArray(t.choices))return;let i=t.choices[0];if(!Mt(i))return;let s=Vz(i.delta),r=i.finish_reason;if(!s||r!==null&&r!=="stop"&&r!=="tool_calls")return;let e=t.usage===void 0?void 0:xy(t.usage);if(t.usage!==void 0&&!e)return;return{delta:s,finishReason:r,usage:e}}function jz(n,t){return`event: ${n}
|
|
255
|
+
data: ${JSON.stringify(t)}
|
|
140
256
|
|
|
141
|
-
`));return
|
|
257
|
+
`}function az(n){return{input_tokens:n.inputTokens,output_tokens:n.outputTokens,cache_creation_input_tokens:0,cache_read_input_tokens:0}}function q_(n){try{let t=JSON.parse(n);return typeof t==="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch(t){if(t instanceof SyntaxError)return;throw t}}function ky(n,t){let i=[];if(n.message.content.length>0)i.push({type:"text",text:n.message.content});for(let s of n.message.toolCalls){let r=q_(s.arguments);if(!r)return gn(502,`Upstream returned invalid JSON arguments for tool ${s.name}`,"api_error");i.push({type:"tool_use",id:s.id,name:s.name,input:r})}return Response.json({id:`msg_${Ky()}`,type:"message",role:"assistant",model:t,content:i,stop_reason:n.message.toolCalls.length>0?"tool_use":"end_turn",stop_sequence:null,usage:az(n.usage)})}function qy(n,t){let s=(n.body??new ReadableStream({start:($)=>$.close()})).getReader(),r=new TextEncoder,e=new TextDecoder,f=`msg_${Ky()}`,o=new Map,h="",u=0,c,_=!1,w=!1,l,A,d=($,N)=>{A?.enqueue(r.encode(jz($,N)))},E=($)=>{if(l!==void 0)return!1;return l=$,!0},R=()=>{t.signals.deadline.removeEventListener("abort",I)},y=()=>{t.signals.client.removeEventListener("abort",F)},T=($,N,B)=>{if(!E($))return;Wn(R,y,()=>{if(!B||!A)return;A.enqueue(r.encode(Iw(B.message,B.type??"api_error")))},()=>{if($!=="consumer-cancel")A?.close()},t.finalize),cn(()=>s.cancel(N))},S=($)=>{T("upstream-protocol-error",void 0,{message:$})},I=()=>{let $=t.signals.deadline.reason instanceof Error?t.signals.deadline.reason:new DOMException("Request deadline exceeded","TimeoutError");T("deadline",$,{message:"Request deadline exceeded"})},F=()=>{let $=t.signals.client.reason instanceof Error?t.signals.client.reason:new DOMException("Client closed request","AbortError");T("client-abort",$)},C=()=>{if(!_||w||c===void 0)return;w=!0,d("content_block_stop",{type:"content_block_stop",index:c})},sn=($)=>{switch($.kind){case"empty":case"reasoning":return!1;case"text":{if(!_)c=u,u+=1,_=!0,d("content_block_start",{type:"content_block_start",index:c,content_block:{type:"text",text:""}});return d("content_block_delta",{type:"content_block_delta",index:c,delta:{type:"text_delta",text:$.text}}),!0}case"tool_calls":{for(let N of $.calls){let B=o.get(N.index)??{id:"",name:"",arguments:""};if(B.id.length===0&&N.id!==void 0)B.id=N.id;if(B.name.length===0&&N.name!==void 0)B.name=N.name;B.arguments+=N.arguments,o.set(N.index,B)}return!1}}},b=($)=>{let N=[...o.entries()].sort(([g],[X])=>g-X);if(N.some(([,g])=>{return g.id.length===0||g.name.length===0||!q_(g.arguments)})){S("Malformed upstream tool call");return}C();for(let[,g]of N){let X=u;if(u+=1,!q_(g.arguments)||g.id.length===0||g.name.length===0){S("Malformed upstream tool call");return}if(d("content_block_start",{type:"content_block_start",index:X,content_block:{type:"tool_use",id:g.id,name:g.name,input:{}}}),g.arguments.length>0)d("content_block_delta",{type:"content_block_delta",index:X,delta:{type:"input_json_delta",partial_json:g.arguments}});d("content_block_stop",{type:"content_block_stop",index:X})}d("message_delta",{type:"message_delta",delta:{stop_reason:N.length>0?"tool_use":"end_turn",stop_sequence:null},usage:{output_tokens:$.outputTokens}}),d("message_stop",{type:"message_stop"}),T("normal-complete")};return new Response(new ReadableStream({start($){if(A=$,d("message_start",{type:"message_start",message:{id:f,type:"message",role:"assistant",model:t.model,content:[],stop_reason:null,stop_sequence:null,usage:{input_tokens:t.inputTokens,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0}}}),t.signals.deadline.addEventListener("abort",I,{once:!0}),t.signals.client.addEventListener("abort",F,{once:!0}),t.signals.deadline.aborted)I();else if(t.signals.client.aborted)F()},async pull(){if(l!==void 0)return;try{while(l===void 0){let $=h.indexOf(`
|
|
258
|
+
`);if($>=0){let g=h.slice(0,$).trimEnd();if(h=h.slice($+1),g.length===0)continue;let X=sr(g);if(!X){S("Malformed upstream stream");return}let Z=sn(X.delta);if(X.finishReason!==null){if(!X.usage){S("Terminal upstream chunk omitted usage");return}b(X.usage);return}if(Z)return;continue}let N=await s.read();if(l!==void 0)return;if(!N.done){h+=e.decode(N.value,{stream:!0});continue}h+=e.decode();let B=h.trim();if(h="",B.length>0){let g=sr(B);if(!g){S("Malformed upstream stream");return}if(sn(g.delta),g.finishReason!==null&&g.usage){b(g.usage);return}}S("Upstream stream ended before completion");return}}catch($){if(l!==void 0)return;T("upstream-error",$,{message:"Upstream stream error"})}},cancel($){T("consumer-cancel",$)}}),{headers:{"Cache-Control":"no-cache","Content-Type":"text/event-stream; charset=utf-8","x-kiro-token-count-mode":"estimate"}})}class j_ extends Error{limit;name="RequestBodyTooLargeError";constructor(n){super(`Request body exceeds the ${n} byte limit`);this.limit=n}}function V_(n){return n.reason instanceof Error?n.reason:new DOMException("Request deadline exceeded","TimeoutError")}function Vy(n){return n.map((t)=>{return`${t.path.length>0?t.path.join("."):"request"}: ${t.message}`}).join(", ")}async function vz(n,t,i){let s=n.body?.getReader();if(!s)return{ok:!0,text:""};let r=[],e=0,f,o=new Promise((u,c)=>{f=c}),h=()=>{let u=V_(i.combined);f?.(u),cn(()=>s.cancel(u))};i.combined.addEventListener("abort",h,{once:!0});try{while(!0){if(i.combined.aborted)throw V_(i.combined);let _=await Promise.race([s.read(),o]);if(i.combined.aborted)throw V_(i.combined);if(_.done)break;if(e+=_.value.byteLength,e>t)throw new j_(t);r.push(_.value)}let u=new Uint8Array(e),c=0;for(let _ of r)u.set(_,c),c+=_.byteLength;return{ok:!0,text:new TextDecoder().decode(u)}}catch(u){if(u instanceof j_)return cn(()=>s.cancel(u)),{ok:!1,response:gn(413,u.message,"request_too_large")};if(i.deadline.aborted)return cn(()=>s.cancel(u)),{ok:!1,response:gn(504,"Request deadline exceeded","api_error")};if(i.client.aborted)return cn(()=>s.cancel(u)),{ok:!1,response:gn(499,"Client closed request","api_error")};throw u}finally{i.combined.removeEventListener("abort",h)}}async function jy(n,t,i){let s=await vz(n,t.max_request_body_bytes,i);if(!s.ok)return s;try{return{ok:!0,value:JSON.parse(s.text)}}catch(r){if(!(r instanceof SyntaxError))throw r;return{ok:!1,response:gn(400,"Request body must contain valid JSON","invalid_request_error")}}}function Zz(n){if(n===429)return"rate_limit_error";if(n===503)return"overloaded_error";if(n===401)return"authentication_error";if(n===403)return"permission_error";if(n===404)return"not_found_error";if(n>=400&&n<500)return"invalid_request_error";return"api_error"}async function pz(n){let t=`Upstream request failed with HTTP ${n.status}`;try{let i=await n.json();if(typeof i==="object"&&i!==null&&"error"in i&&typeof i.error==="object"&&i.error!==null&&"message"in i.error&&typeof i.error.message==="string")t=i.error.message}catch{}return gn(n.status,t,Zz(n.status))}function ay(n,t){let i=new AbortController,s=setTimeout(()=>i.abort(new DOMException("Request deadline exceeded","TimeoutError")),t.request_timeout_ms);return{signals:{combined:AbortSignal.any([i.signal,n.signal]),deadline:i.signal,client:n.signal},finalize:()=>clearTimeout(s)}}function vy(n){return Math.max(1,Df(JSON.stringify(n)))}async function Zy(n,t,i){let s=ay(n,t),r=await jy(n,t,s.signals);if(!r.ok)return s.finalize(),r.response;let e=k_(r.value,{requireMaxTokens:!0});if(!e.ok)return s.finalize(),gn(400,e.message,"invalid_request_error");let f=kf.safeParse(e.value.body);if(!f.success)return s.finalize(),gn(400,`Invalid request: ${Vy(f.error.issues)}`,"invalid_request_error");let o=Jy(e.value.source,i.tenantId),h,u=!1,c=()=>{Wn(s.finalize,()=>h?.restore())};try{h=i.createRequestIdleTimeoutLease?.(),h?.disable();let _=await(i.runPipeline??ir)({body:f.data,model:f.data.model,stream:e.value.source.stream,config:t,accountManager:i.accountManager,tokenRefresher:i.tokenRefresher,...o?{affinity:o}:{},...i.affinityStore?{affinityStore:i.affinityStore}:{},deadlineSignal:s.signals.combined,...i.makeClient?{makeClient:i.makeClient}:{}});if(n.signal.aborted&&!s.signals.deadline.aborted)return cn(()=>_.body?.cancel()),gn(499,"Client closed request","api_error");let w=_.headers.get("Content-Type")??"";if(!_.ok)return await pz(_);if(e.value.source.stream&&w.includes("application/x-ndjson")){let l=qy(_,{model:f.data.model,inputTokens:vy(f.data),signals:s.signals,finalize:c});return u=!0,l}if(w.includes("application/json")){if(e.value.source.stream)return gn(502,"Pipeline returned a non-streaming response for a streaming request","api_error");let l=jf(await _.json());if(l)return ky(l,f.data.model);return gn(502,"Pipeline returned an invalid non-streaming response","api_error")}return cn(()=>_.body?.cancel()),gn(502,"Pipeline returned an unsupported response","api_error")}finally{if(!u)c()}}async function py(n,t){let i=ay(n,t);try{let s=await jy(n,t,i.signals);if(!s.ok)return s.response;let r=k_(s.value);if(!r.ok)return gn(400,r.message,"invalid_request_error");let e=kf.safeParse(r.value.body);if(!e.success)return gn(400,`Invalid request: ${Vy(e.error.issues)}`,"invalid_request_error");let f=vy(e.data);return Response.json({input_tokens:f},{headers:{"x-kiro-token-count-mode":"estimate"}})}finally{i.finalize()}}var nQ=1700000000,tQ=/-(low|medium|high|xhigh|max)$/;function iQ(n){if(!ai(n))return[];return(H_(n)?["low","medium","high","xhigh","max"]:["low","medium","high","max"]).map((i)=>({effort:i,description:`${i} reasoning effort`}))}function sQ(n){if(!ai(n.wireId))return null;let t=tQ.exec(n.id)?.[1];if(t==="low"||t==="medium"||t==="high"||t==="xhigh"||t==="max")return t;return"medium"}function rQ(n){return n.modalities.input.includes("image")?["text","image"]:["text"]}function eQ(n,t){return{slug:n.id,display_name:n.name,description:null,default_reasoning_level:sQ(n),supported_reasoning_levels:iQ(n.wireId),shell_type:"unified_exec",visibility:"list",supported_in_api:!0,priority:xf.length-t,upgrade:null,base_instructions:"",include_skills_usage_instructions:!1,include_plugin_usage_instructions:!1,include_apps_usage_instructions:!1,supports_reasoning_summary_parameter:!0,support_verbosity:!1,default_verbosity:null,apply_patch_tool_type:null,web_search_tool_type:"text",truncation_policy:{mode:"tokens",limit:n.contextLimit},supports_image_detail_original:!1,context_window:n.contextLimit,max_context_window:n.contextLimit,auto_compact_token_limit:Math.floor(n.contextLimit*0.9),effective_context_window_percent:95,experimental_supported_tools:[],input_modalities:rQ(n),supports_search_tool:!1,use_responses_lite:!1,node_repl_auto_review_required:!1,node_repl_disabled:!1}}function nT(){let n=xf.map((i)=>({id:i.id,object:"model",created:nQ,owned_by:"kiro",name:i.name,context_limit:i.contextLimit,output_limit:i.outputLimit,modalities:i.modalities})),t=xf.map(eQ);return new Response(JSON.stringify({object:"list",data:n,models:t}),{status:200,headers:{"Content-Type":"application/json"}})}function tT(n){try{if(n.reconcileFromDb(),n.getAccountCount()===0)return Response.json({status:"not_ready",reason:"no_active_accounts"},{status:503});return Response.json({status:"ready"})}catch{return Response.json({status:"not_ready",reason:"authentication_store_unavailable"},{status:503})}}import{randomUUID as af}from"crypto";function rr(n){switch(n.kind){case"function":return JSON.stringify(["function",n.name]);case"custom":return JSON.stringify(["custom",n.name]);case"namespace":return JSON.stringify(["namespace",n.toolType,n.namespace,n.name])}}function iT(...n){let t=n.filter((i)=>i!==void 0&&i.length>0);return t.length>0?t.join(`
|
|
142
259
|
|
|
143
|
-
`)
|
|
144
|
-
`)}function
|
|
145
|
-
|
|
146
|
-
data: ${JSON.stringify(t)}
|
|
260
|
+
`):void 0}function a_(n){return{type:"object",properties:{input:{type:"string"}},required:["input"],additionalProperties:!1}}function oQ(n){return{type:"function",function:{name:n.name,...n.description!==void 0?{description:n.description}:{},...n.parameters!==void 0?{parameters:n.parameters}:{}}}}function oT(n){if(n.namespace!==void 0)return{kind:"namespace",namespace:n.namespace,name:n.name,toolType:n.type==="custom_tool_call"?"custom":"function"};if(n.type==="custom_tool_call")return{kind:"custom",name:n.name};return{kind:"function",name:n.name}}function v_(n){return n.kind==="custom"||n.kind==="namespace"&&n.toolType==="custom"}function sT(n){return n.type==="function_call"||n.type==="custom_tool_call"}function fQ(n){return n.type==="additional_tools"}function rT(n){return n.type==="function"||n.type==="custom"||n.type==="namespace"}function hQ(n){return n.type==="function_call_output"||n.type==="custom_tool_call_output"}function uQ(n){return n.startsWith("kiro_custom_")||n.startsWith("kiro_ns_")}function eT(n){return n.trim().length===0?"{}":n}function cQ(n){let t;try{t=JSON.parse(n)}catch(i){if(i instanceof SyntaxError)return{ok:!1,code:"invalid_custom_tool_input",message:"Custom tool arguments must be valid JSON"};throw i}if(typeof t!=="object"||t===null||Array.isArray(t)||Object.keys(t).length!==1||typeof t.input!=="string")return{ok:!1,code:"invalid_custom_tool_input",message:'Custom tool arguments must contain exactly {"input": string}'};return{ok:!0,input:t.input}}class fT{internalTools;#n;#t;constructor(n){this.internalTools=n.internalTools,this.#n=n.wireNameByIdentity,this.#t=n.identityByWireName}lowerCall(n){let t=oT(n),i=this.#n.get(rr(t))??n.name;return{id:n.call_id,type:"function",function:{name:i,arguments:n.type==="custom_tool_call"?JSON.stringify({input:n.input}):n.arguments}}}restoreCalls(n){let t=[];for(let i of n){let s=this.#t.get(i.name);if(!s){if(uQ(i.name))return{ok:!1,code:"unknown_tool_alias",message:`Upstream returned unregistered tool alias ${i.name}`};t.push({id:i.itemId,type:"function_call",call_id:i.id,name:i.name,arguments:eT(i.arguments)});continue}if(v_(s)){let r=cQ(i.arguments);if(!r.ok)return r;t.push({id:i.itemId,type:"custom_tool_call",call_id:i.id,...s.kind==="namespace"?{namespace:s.namespace}:{},name:s.name,input:r.input});continue}t.push({id:i.itemId,type:"function_call",call_id:i.id,...s.kind==="namespace"?{namespace:s.namespace}:{},name:s.name,arguments:eT(i.arguments)})}return{ok:!0,items:t}}}function _Q(n){let t=new Set;for(let i of n.tools){if(t.has(i.name))return!0;t.add(i.name)}return!1}function hT(n){let t=new Map,i=new Map,s=new Set,r=[],e=typeof n.input==="string"?[]:n.input;for(let R of e)if(sT(R)&&R.type==="function_call"&&R.namespace===void 0)s.add(R.name);let f=(R)=>{if(R.type==="namespace"){if(_Q(R))return{ok:!1,code:"invalid_tool_declaration",message:`Namespace ${R.name} contains duplicate child names`};for(let I of R.tools){let F={kind:"namespace",namespace:R.name,name:I.name,toolType:I.type},C=rr(F);if(t.has(C))continue;t.set(C,{identity:F,tool:{type:"function",function:{name:"",...iT(R.description,I.description)!==void 0?{description:iT(R.description,I.description)}:{},parameters:I.type==="custom"?a_(I.format):I.parameters??{type:"object"}}}})}return}let y=i.get(R.name);if(y!==void 0&&y!==R.type)return{ok:!1,code:"invalid_tool_declaration",message:`Tool name ${R.name} is declared as both function and custom`};if(i.set(R.name,R.type),R.type==="function")s.add(R.name);let T={kind:R.type,name:R.name},S=rr(T);if(t.has(S))return;t.set(S,{identity:T,tool:R.type==="function"?oQ(R):{type:"function",function:{name:"",...R.description!==void 0?{description:R.description}:{},parameters:a_(R.format)}}});return};for(let R of n.tools??[]){if(!rT(R))continue;let y=f(R);if(y)return y}for(let R of e){if(!fQ(R))continue;for(let y of R.tools){if(!rT(y))continue;let T=f(y);if(T)return T}}let o=new Map;for(let[R,y]of e.entries()){if(!sT(y))continue;if(o.has(y.call_id))return{ok:!1,code:"invalid_tool_history",message:`Duplicate tool call id ${y.call_id}`};let T={index:R,identity:oT(y)};o.set(y.call_id,T),r.push(T)}let h=new Set;for(let[R,y]of e.entries()){if(!hQ(y))continue;if(h.has(y.call_id))return{ok:!1,code:"invalid_tool_history",message:`Duplicate tool output id ${y.call_id}`};h.add(y.call_id);let T=o.get(y.call_id);if(!T){if(y.type==="custom_tool_call_output")return{ok:!1,code:"invalid_tool_history",message:`Custom output ${y.call_id} has no matching call`};continue}let S=v_(T.identity),I=y.type==="custom_tool_call_output"&&S||y.type==="function_call_output"&&!S;if(T.index>=R||!I)return{ok:!1,code:"invalid_tool_history",message:`Tool output ${y.call_id} is out of order or has the wrong type`}}let u=[...t.values()];for(let R of r){let y=rr(R.identity);if(R.identity.kind==="function"||t.has(y))continue;t.set(y,{identity:R.identity,tool:{type:"function",function:{name:"",parameters:v_(R.identity)?a_(void 0):{type:"object"}}}}),u.push(t.get(y))}let c=new Set(s),_=new Map,w=new Map,l=0,A=0,d=(R)=>{for(;;){let y=R==="custom"?`kiro_custom_${l++}`:`kiro_ns_${A++}`;if(c.has(y))continue;return c.add(y),y}},E=[];for(let R of u){let y=rr(R.identity),T=R.identity.kind==="function"?R.identity.name:d(R.identity.kind);_.set(y,T),w.set(T,R.identity),E.push({type:"function",function:{...R.tool.function,name:T}})}for(let R of s){let y={kind:"function",name:R};_.set(rr(y),R),w.set(R,y)}return{ok:!0,bridge:new fT({internalTools:E,wireNameByIdentity:_,identityByWireName:w})}}function wQ(n){return n.type==="message"||n.type===void 0&&"role"in n&&"content"in n}function lQ(n){return n.type==="agent_message"}function AQ(n){return n.type==="function_call"}function MQ(n){return n.type==="custom_tool_call"}function dQ(n){return n.type==="function_call_output"}function RQ(n){return n.type==="custom_tool_call_output"}function uT(n){return n.type==="additional_tools"}function EQ(n){return n.type==="reasoning"}function cT(n,t){let i=[];for(let s of n){if((s.type==="input_text"||s.type==="output_text")&&"text"in s&&typeof s.text==="string"){i.push({type:"text",text:s.text});continue}if(s.type==="input_image"&&"image_url"in s&&typeof s.image_url==="string"){i.push({type:"image_url",image_url:{url:s.image_url}});continue}t.count++}return i}function yQ(n,t){return typeof n==="string"?n:cT(n,t)}function TQ(n){return typeof n==="string"?[{type:"text",text:n}]:n}function gQ(n){if(n==="minimal")return"low";if(n==="low"||n==="medium"||n==="high"||n==="xhigh"||n==="max")return n;return}function SQ(n){if(typeof n==="string")return n;return n.flatMap((t)=>t.text===void 0?[]:[t.text]).join(`
|
|
261
|
+
`)}function _T(n){let t=hT(n);if(!t.ok)return{ok:!1,code:t.code,message:t.message};let i=t.bridge,s=[],r=[...i.internalTools],e=n.tools!==void 0||typeof n.input!=="string"&&n.input.some((w)=>uT(w)),f={count:0},o=0,h=0,u=!1;if(n.instructions&&n.instructions.length>0)s.push({role:"system",content:n.instructions});if(typeof n.input==="string")s.push({role:"user",content:n.input}),u=!0;else for(let w of n.input){if(EQ(w))continue;if(AQ(w)||MQ(w)){s.push({role:"assistant",tool_calls:[i.lowerCall(w)]}),u=!0;continue}if(wQ(w)){let l=yQ(w.content,f);if(w.role==="assistant")s.push({role:"assistant",content:TQ(l)}),u=!0;else if(s.push({role:w.role==="developer"?"system":w.role,content:l}),w.role==="user")u=!0;continue}if(lQ(w)){let l=cT(w.content,f);s.push({role:"user",content:l}),u=!0;continue}if(dQ(w)||RQ(w)){s.push({role:"user",content:[{type:"tool_result",tool_use_id:w.call_id,content:SQ(w.output)}]}),u=!0;continue}if(uT(w)){h+=w.tools.filter((l)=>l.type!=="function"&&l.type!=="custom"&&l.type!=="namespace").length;continue}o++}if(f.count,!u)return{ok:!1,code:"empty_input"};let c=gQ(n.reasoning?.effort);return{ok:!0,body:{model:n.model,stream:n.stream,messages:s,...r.length>0||e?{tools:r}:{},...n.tool_choice!==void 0?{tool_choice:n.tool_choice}:{},...c!==void 0?{reasoning_effort:c}:{}},bridge:i}}import{randomUUID as Te}from"crypto";function wT(n){return{type:"response.created",sequence_number:n.sequenceNumber,response:{id:n.responseId,object:"response",status:"in_progress",model:n.model,created_at:Math.floor(Date.now()/1000),output:[]}}}function Ee(n){return{type:"response.output_item.added",sequence_number:n.sequenceNumber,output_index:n.outputIndex,item:n.item}}function lT(n){return{type:"response.output_text.delta",sequence_number:n.sequenceNumber,item_id:n.itemId,output_index:n.outputIndex,content_index:n.contentIndex,delta:n.delta}}function Z_(n){return{type:"response.reasoning_summary_text.delta",sequence_number:n.sequenceNumber,item_id:n.itemId,output_index:n.outputIndex,summary_index:n.summaryIndex,delta:n.delta}}function p_(n){return{type:"response.reasoning_summary_text.done",sequence_number:n.sequenceNumber,item_id:n.itemId,output_index:n.outputIndex,summary_index:n.summaryIndex,text:n.text}}function ye(n){return{type:"response.output_item.done",sequence_number:n.sequenceNumber,output_index:n.outputIndex,item:n.item}}function AT(n){return{type:"response.completed",sequence_number:n.sequenceNumber,response:{id:n.responseId,object:"response",status:"completed",model:n.model,output:n.output,usage:n.usage}}}function MT(n){return{type:"response.failed",sequence_number:n.sequenceNumber,response:{id:n.responseId,object:"response",status:"failed",model:n.model,error:n.error}}}function dT(n){return{type:"response.function_call_arguments.delta",sequence_number:n.sequenceNumber,item_id:n.itemId,output_index:n.outputIndex,delta:n.delta}}function RT(n){return{type:"response.custom_tool_call_input.delta",sequence_number:n.sequenceNumber,item_id:n.itemId,output_index:n.outputIndex,delta:n.delta}}function ET(n){return`event: ${n.type}
|
|
262
|
+
data: ${JSON.stringify(n)}
|
|
147
263
|
|
|
148
|
-
`}function
|
|
149
|
-
`);if(
|
|
264
|
+
`}function yT(n,t){let i=t.signals,r=(n.body??new ReadableStream({start:(H)=>H.close()})).getReader(),e=new TextDecoder,f=new TextEncoder,o=`resp_${Te()}`,h=`msg_${Te()}`,u=new Map,c=new Map,_="",w="",l,A,d="",E=0,R=0,y,T,S,I,F=(H,W)=>{H.enqueue(f.encode(ET(W(R)))),R+=1},C=(H)=>{if(y!==void 0)return!1;return y=H,!0},sn=()=>{i.deadline.removeEventListener("abort",B)},b=()=>{i.client.removeEventListener("abort",g)},$=(H,W,on)=>{if(!C(H))return;S=on,Wn(sn,b,()=>{if(!I)return;if(H==="normal-complete"){if(!T)throw TypeError("Responses stream completed without terminal data");F(I,(An)=>AT({responseId:o,model:t.model,output:T?.output??[],usage:T?.usage??{input_tokens:0,output_tokens:0,total_tokens:0},sequenceNumber:An}))}else if(H==="deadline"||H==="upstream-error"||H==="upstream-protocol-error"){let An=S??{code:"upstream_error",message:"Upstream stream error"};F(I,(Vn)=>MT({responseId:o,model:t.model,error:An,sequenceNumber:Vn}))}},()=>{if(H!=="consumer-cancel")I?.close()},t.finalize),cn(()=>r.cancel(W))},N=(H,W="upstream_error")=>{$("upstream-protocol-error",void 0,{code:W,message:H})},B=()=>{let H=i.deadline.reason instanceof Error?i.deadline.reason:new DOMException("Request deadline exceeded","TimeoutError");$("deadline",H,{code:"upstream_error",message:"Request deadline exceeded"})},g=()=>{let H=i.client.reason instanceof Error?i.client.reason:new DOMException("Client closed request","AbortError");$("client-abort",H)},X=(H)=>{if(!A)return;let W={id:A.id,type:"reasoning",summary:[{type:"summary_text",text:A.text}]};F(H,(on)=>p_({itemId:A?.id??"",outputIndex:A?.outputIndex??0,summaryIndex:0,text:A?.text??"",sequenceNumber:on})),F(H,(on)=>ye({item:W,outputIndex:A?.outputIndex??0,sequenceNumber:on})),c.set(A.outputIndex,W),A=void 0},Z=(H)=>{if(d.length===0)return;let W={id:`rs_${Te()}`,outputIndex:E,text:d};E+=1,d="",F(H,(An)=>Ee({item:{id:W.id,type:"reasoning",summary:[]},outputIndex:W.outputIndex,sequenceNumber:An})),F(H,(An)=>Z_({itemId:W.id,outputIndex:W.outputIndex,summaryIndex:0,delta:W.text,sequenceNumber:An})),F(H,(An)=>p_({itemId:W.id,outputIndex:W.outputIndex,summaryIndex:0,text:W.text,sequenceNumber:An}));let on={id:W.id,type:"reasoning",summary:[{type:"summary_text",text:W.text}]};F(H,(An)=>ye({item:on,outputIndex:W.outputIndex,sequenceNumber:An})),c.set(W.outputIndex,on)},tn=(H,W)=>{switch(W.kind){case"empty":return;case"reasoning":{if(l!==void 0){d+=W.text;return}if(!A)A={id:`rs_${Te()}`,outputIndex:E,text:""},E+=1,F(H,(on)=>Ee({item:{id:A?.id??"",type:"reasoning",summary:[]},outputIndex:A?.outputIndex??0,sequenceNumber:on}));A.text+=W.text,F(H,(on)=>Z_({itemId:A?.id??"",outputIndex:A?.outputIndex??0,summaryIndex:0,delta:W.text,sequenceNumber:on}));return}case"text":{if(X(H),l===void 0)l=E,E+=1,F(H,(on)=>Ee({item:{id:h,type:"message",role:"assistant",content:[]},outputIndex:l??0,sequenceNumber:on}));w+=W.text,F(H,(on)=>lT({itemId:h,outputIndex:l??0,contentIndex:0,delta:W.text,sequenceNumber:on}));return}case"tool_calls":X(H);for(let on of W.calls){let An=u.get(on.index)??{itemId:`fc_${Te()}`,id:"",name:"",arguments:""};if(An.id.length===0&&on.id!==void 0)An.id=on.id;if(An.name.length===0&&on.name!==void 0)An.name=on.name;An.arguments+=on.arguments,u.set(on.index,An)}return}},en=(H,W)=>{if([...u.values()].some((nn)=>nn.id.length===0||nn.name.length===0)){N("Malformed upstream tool call");return}let Vn=[...u.entries()].sort(([nn],[st])=>nn-st).map(([,nn])=>({itemId:nn.itemId,id:nn.id,name:nn.name,arguments:nn.arguments.trim().length===0?"{}":nn.arguments})),it=t.bridge?.restoreCalls(Vn)??{ok:!0,items:Vn.map((nn)=>({id:nn.itemId,type:"function_call",call_id:nn.id,name:nn.name,arguments:nn.arguments}))};if(!it.ok){N(it.message,"upstream_protocol_error");return}if(X(H),l!==void 0){let nn={id:h,type:"message",role:"assistant",content:[{type:"output_text",text:w}]};F(H,(st)=>ye({item:nn,outputIndex:l??0,sequenceNumber:st})),c.set(l,nn)}Z(H);for(let nn of it.items){let st=E;E+=1;let OT=nn.type==="function_call"?{...nn,arguments:""}:{...nn,input:""};if(F(H,(Ti)=>Ee({item:OT,outputIndex:st,sequenceNumber:Ti})),nn.type==="function_call")F(H,(Ti)=>dT({itemId:nn.id,outputIndex:st,delta:nn.arguments,sequenceNumber:Ti}));else F(H,(Ti)=>RT({itemId:nn.id,outputIndex:st,delta:nn.input,sequenceNumber:Ti}));let e0={...nn,status:"completed"};F(H,(Ti)=>ye({item:e0,outputIndex:st,sequenceNumber:Ti})),c.set(st,e0)}T={output:[...c.entries()].sort(([nn],[st])=>nn-st).map(([,nn])=>nn),usage:{input_tokens:W.inputTokens,output_tokens:W.outputTokens,total_tokens:W.totalTokens}},$("normal-complete")};return new Response(new ReadableStream({start(H){if(I=H,F(H,(W)=>wT({responseId:o,model:t.model,sequenceNumber:W})),i.deadline.addEventListener("abort",B,{once:!0}),i.client.addEventListener("abort",g,{once:!0}),i.deadline.aborted)B();else if(i.client.aborted)g()},async pull(H){if(y!==void 0)return;try{while(y===void 0){let W=_.indexOf(`
|
|
265
|
+
`);if(W>=0){let Vn=_.slice(0,W).trimEnd();if(_=_.slice(W+1),Vn.length===0)continue;let it=sr(Vn);if(!it){N("Malformed upstream stream");return}if(tn(H,it.delta),it.finishReason!==null){if(!it.usage){N("Terminal upstream chunk omitted usage");return}en(H,it.usage);return}if(it.delta.kind!=="tool_calls"&&it.delta.kind!=="empty")return;continue}let on=await r.read();if(y!==void 0)return;if(!on.done){_+=e.decode(on.value,{stream:!0});continue}_+=e.decode();let An=_.trim();if(_="",An.length>0){let Vn=sr(An);if(!Vn){N("Malformed upstream stream");return}if(tn(H,Vn.delta),Vn.finishReason!==null&&Vn.usage){en(H,Vn.usage);return}}N("Upstream stream ended before completion");return}}catch(W){if(y!==void 0)return;$("upstream-error",W,{code:"upstream_error",message:"Upstream stream error"})}},cancel(H){$("consumer-cancel",H)}}),{headers:{"Cache-Control":"no-cache","Content-Type":"text/event-stream; charset=utf-8"}})}class t0 extends Error{limit;name="RequestBodyTooLargeError";constructor(n){super(`Request body exceeds the ${n} byte limit`);this.limit=n}}function n0(n){return n.reason instanceof Error?n.reason:new DOMException("Request deadline exceeded","TimeoutError")}async function IQ(n,t,i){let s=n.body?.getReader();if(!s)return{ok:!0,text:""};let r=[],e=0,f,o=new Promise((u,c)=>{f=c}),h=()=>{let u=n0(i.combined);f?.(u),s.cancel(u)};i.combined.addEventListener("abort",h,{once:!0});try{while(!0){if(i.combined.aborted)throw n0(i.combined);let _=await Promise.race([s.read(),o]);if(i.combined.aborted)throw n0(i.combined);if(_.done)break;if(e+=_.value.byteLength,e>t)throw new t0(t);r.push(_.value)}let u=new Uint8Array(e),c=0;for(let _ of r)u.set(_,c),c+=_.byteLength;return{ok:!0,text:new TextDecoder().decode(u)}}catch(u){if(u instanceof t0)return s.cancel(u).catch(()=>{return}),{ok:!1,response:v(413,u.message,"invalid_request_error","request_too_large")};if(i.deadline.aborted)return s.cancel(u).catch(()=>{return}),{ok:!1,response:v(504,"Request deadline exceeded","timeout_error","request_timeout")};if(i.client.aborted)return s.cancel(u).catch(()=>{return}),{ok:!1,response:v(499,"Client closed request","request_aborted","client_disconnected")};throw u}finally{i.combined.removeEventListener("abort",h)}}function UQ(n,t,i){let s=i.restoreCalls(n.message.toolCalls.map((e)=>({itemId:`fc_${af()}`,id:e.id,name:e.name,arguments:e.arguments})));if(!s.ok)return v(502,s.message,"upstream_error","upstream_protocol_error");let r=[];if(n.message.reasoningContent){let e={id:`rs_${af()}`,type:"reasoning",summary:[{type:"summary_text",text:n.message.reasoningContent}]};r.push(e)}if(n.message.content.length>0){let e={id:`msg_${af()}`,type:"message",role:"assistant",content:[{type:"output_text",text:n.message.content}]};r.push(e)}return r.push(...s.items),Response.json({id:`resp_${af()}`,object:"response",status:"completed",model:t,output:r,usage:{input_tokens:n.usage.inputTokens,output_tokens:n.usage.outputTokens,total_tokens:n.usage.totalTokens}})}async function TT(n,t,i){let s=new AbortController,r=setTimeout(()=>s.abort(new DOMException("Request deadline exceeded","TimeoutError")),t.request_timeout_ms),e=AbortSignal.any([s.signal,n.signal]),f={combined:e,deadline:s.signal,client:n.signal},o=await IQ(n,t.max_request_body_bytes,f);if(!o.ok)return clearTimeout(r),o.response;let h;try{h=JSON.parse(o.text)}catch(R){if(clearTimeout(r),!(R instanceof SyntaxError))throw R;return v(400,"Request body must contain valid JSON","invalid_request_error","invalid_json")}let u=Dy(h);if(!u.ok)return clearTimeout(r),u.response;if(u.value.previous_response_id!==void 0||u.value.conversation!==void 0)return clearTimeout(r),v(400,"Stateful Responses continuation is not supported; resend the complete input without previous_response_id or conversation","invalid_request_error","unsupported_stateful_responses");let c=Yy(u.value,i.tenantId),_=_T(u.value);if(!_.ok){clearTimeout(r);let R=_.code==="empty_input"?_.code:"invalid_request";return v(400,_.message??"input produced no messages","invalid_request_error",R)}let w=Vf(_.body);if(!w.ok)return clearTimeout(r),w.response;let l=u.value.stream,A,d=!1,E=()=>{Wn(()=>clearTimeout(r),()=>A?.restore())};try{A=i.createRequestIdleTimeoutLease?.(),A?.disable();let R=await(i.runPipeline??ir)({body:w.value,model:w.value.model,stream:l,config:t,accountManager:i.accountManager,tokenRefresher:i.tokenRefresher,...c?{affinity:c}:{},...i.affinityStore?{affinityStore:i.affinityStore}:{},deadlineSignal:e,...i.makeClient?{makeClient:i.makeClient}:{}});if(n.signal.aborted&&!s.signal.aborted)return cn(()=>R.body?.cancel()),v(499,"Client closed request","request_aborted","client_disconnected");let y=R.headers.get("Content-Type")??"";if(l&&y.includes("application/x-ndjson")){let T=yT(R,{model:w.value.model,signals:f,finalize:E,bridge:_.bridge});return d=!0,T}if(y.includes("application/json")){if(l||!R.ok)return R;let T=await R.json(),S=jf(T);if(S)return UQ(S,w.value.model,_.bridge);return v(500,"Pipeline returned an invalid non-streaming response","internal_error","invalid_pipeline_response")}return cn(()=>R.body?.cancel()),v(500,"Pipeline returned an unsupported response","internal_error","invalid_pipeline_response")}finally{if(!d)E()}}var bQ=10;function $Q(n,t){let i="idle";return{disable:()=>{if(i!=="idle")return;i="disabled",t.timeout(n,0)},restore:()=>{if(i!=="disabled")return;i="restored",t.timeout(n,bQ)}}}function LQ(n,t){return async(i,s)=>{let r=new URL(i.url),e=r.pathname==="/v1/messages"||r.pathname==="/v1/messages/count_tokens",f=e?Yh(i,n.api_keys,(c,_)=>gn(c,_,"authentication_error")):Yh(i,n.api_keys);if(!f.ok)return f.response;let o=t.createRequestIdleTimeoutLease??$Q,h=s?()=>o(i,s):void 0,u={accountManager:t.accountManager,tokenRefresher:t.tokenRefresher,tenantId:f.tenantId,...t.affinityStore?{affinityStore:t.affinityStore}:{},...t.makeClient?{makeClient:t.makeClient}:{},...h?{createRequestIdleTimeoutLease:h}:{}};try{if(i.method==="POST"&&r.pathname==="/v1/chat/completions"){if(!n.enable_legacy_chat_completions)return v(404,"Legacy Chat Completions is disabled; set enable_legacy_chat_completions to true","invalid_request_error","legacy_chat_completions_disabled");return await Xy(i,n,u)}if(i.method==="POST"&&r.pathname==="/v1/responses")return await TT(i,n,u);if(i.method==="POST"&&r.pathname==="/v1/messages")return await Zy(i,n,u);if(i.method==="POST"&&r.pathname==="/v1/messages/count_tokens")return await py(i,n);if(i.method==="GET"&&r.pathname==="/v1/models")return nT();if(i.method==="GET"&&r.pathname==="/health")return zy();if(i.method==="GET"&&r.pathname==="/ready")return tT(t.accountManager);return v(404,"Route not found","invalid_request_error","not_found")}catch(c){let _=c instanceof Error?c.message:"Internal server error";if(e)return gn(500,_,"api_error");return v(500,_,"internal_error","internal_error")}}}function OQ(n,t={}){let i=t.createDatabase?.()??new Pi,s=$s(n);if(n.auth_source==="opencode-shared"){let f=n.opencode_auth_db_path??fr(),o=t.createOpenCodeAuthStore?.(f)??new pf(f),h=new Gh(o,n.account_selection_strategy),u=t.createOpenCodeTokenRefresher?t.createOpenCodeTokenRefresher(h,o,n.token_expiry_buffer_ms,s):new Hh(h,o,n.token_expiry_buffer_ms,s);return{accountManager:h,tokenRefresher:u,affinityStore:i}}let r=new eh(i.getAccounts(),n.account_selection_strategy,i),e=t.createTokenRefresher?t.createTokenRefresher(r,n.token_expiry_buffer_ms,s):new Nh(r,n.token_expiry_buffer_ms,s);return{accountManager:r,tokenRefresher:e,affinityStore:i}}function BQ(n,t){return{hostname:n.host,port:n.port,fetch:LQ(n,t)}}function gT(n){return Bun.serve(BQ(n,OQ(n)))}import{parseArgs as i0}from"util";var vf=`Usage: kiro-provider <command> [options]
|
|
150
266
|
|
|
151
267
|
Commands:
|
|
152
268
|
serve [--config <path>] [--host <host>] [--port <port>] [--proxy <url>]
|
|
153
|
-
Start the
|
|
269
|
+
Start the Responses, Messages, and optional legacy Chat gateway.
|
|
154
270
|
login [--config <path>] [--start-url <url>] [--region <region>]
|
|
155
|
-
Sign in
|
|
271
|
+
Sign in to the local auth store. Shared mode uses "opencode auth login".
|
|
156
272
|
accounts list
|
|
157
|
-
List
|
|
273
|
+
List accounts in the local compatibility store.
|
|
158
274
|
accounts import [--from <path>] [--config <path>]
|
|
159
|
-
|
|
275
|
+
Snapshot authenticated accounts into the local compatibility store.
|
|
160
276
|
accounts remove <id|email>
|
|
161
|
-
Remove an account and write a tombstone.
|
|
277
|
+
Remove an account from the local compatibility store and write a tombstone.
|
|
162
278
|
|
|
163
279
|
Options:
|
|
164
|
-
-h, --help Show this help.`;class
|
|
280
|
+
-h, --help Show this help.`;class er extends Error{constructor(n){super(n);this.name="CliUsageError"}}function NQ(n){let t=i0({args:[...n],options:{config:{type:"string"},host:{type:"string"},port:{type:"string"},proxy:{type:"string"},help:{type:"boolean",short:"h"}},strict:!0,allowPositionals:!1});if(t.values.help)return{kind:"help"};let i=t.values.port===void 0?void 0:Number(t.values.port);if(i!==void 0&&(!Number.isInteger(i)||i<1||i>65535))throw new er(`Invalid port: ${t.values.port}`);return{kind:"serve",...t.values.config?{configPath:t.values.config}:{},...t.values.host?{host:t.values.host}:{},...i!==void 0?{port:i}:{},...t.values.proxy!==void 0?{proxy:t.values.proxy}:{}}}function GQ(n){let t=i0({args:[...n],options:{config:{type:"string"},"start-url":{type:"string"},region:{type:"string"}},strict:!0,allowPositionals:!1});return{kind:"login",...t.values.config?{configPath:t.values.config}:{},...t.values["start-url"]?{startUrl:t.values["start-url"]}:{},...t.values.region?{region:t.values.region}:{}}}function HQ(n){let t=i0({args:[...n],options:{from:{type:"string"},config:{type:"string"},help:{type:"boolean",short:"h"}},strict:!0,allowPositionals:!1});if(t.values.help)return{kind:"help"};return{kind:"accounts-import",...t.values.from?{from:t.values.from}:{},...t.values.config?{configPath:t.values.config}:{}}}function WQ(n){let t=n[0];switch(t){case"list":if(n.length!==1)throw new er("accounts list takes no arguments");return{kind:"accounts-list"};case"import":return HQ(n.slice(1));case"remove":{let i=n[1];if(!i||n.length!==2)throw new er("accounts remove requires exactly one <id|email>");return{kind:"accounts-remove",identifier:i}}default:throw new er(t===void 0?"accounts requires list, import, or remove":`Unknown accounts command: ${t}`)}}function s0(n){let t=n[0];switch(t){case void 0:case"--help":case"-h":return{kind:"help"};case"serve":return NQ(n.slice(1));case"login":return GQ(n.slice(1));case"accounts":return WQ(n.slice(1));default:throw new er(`Unknown command: ${t}`)}}import{Database as FQ}from"bun:sqlite";import{homedir as PQ}from"os";import{join as ST}from"path";var DQ=M.object({id:M.string().min(1),email:M.string().min(1),auth_method:M.string(),region:M.string(),oidc_region:M.string().nullable(),client_id:M.string().nullable(),client_secret:M.string().nullable(),profile_arn:M.string().nullable(),start_url:M.string().nullable(),refresh_token:M.string(),access_token:M.string(),expires_at:M.number(),rate_limit_reset:M.number().nullable(),is_healthy:M.number().nullable(),unhealthy_reason:M.string().nullable(),recovery_time:M.number().nullable(),fail_count:M.number().nullable(),last_used:M.number().nullable(),used_count:M.number().nullable(),limit_count:M.number().nullable(),last_sync:M.number().nullable(),overage_count:M.number().nullable()});function YQ(n=process.env){let t=n.XDG_CONFIG_HOME??ST(PQ(),".config");return ST(t,"opencode","kiro.db")}function dt(n){return n===null||n===""?void 0:n}function mQ(n){if(!n.refresh_token)return{kind:"skipped",reason:"missing refresh token"};if(!n.access_token)return{kind:"skipped",reason:"missing access token"};let t=Li.safeParse(n.region);if(!t.success)return{kind:"skipped",reason:"missing or unsupported region"};if(n.auth_method!=="idc"&&n.auth_method!=="desktop")return{kind:"skipped",reason:"unsupported auth method"};if(n.auth_method==="idc"&&(!n.client_id||!n.client_secret))return{kind:"skipped",reason:"IDC client credentials missing"};let i=dt(n.oidc_region),s=i===void 0?void 0:Li.safeParse(i);if(s!==void 0&&!s.success)return{kind:"skipped",reason:"unsupported OIDC region"};return{kind:"usable",account:{id:n.id,email:n.email,authMethod:n.auth_method,region:t.data,...s?.success?{oidcRegion:s.data}:{},...dt(n.client_id)?{clientId:dt(n.client_id)}:{},...dt(n.client_secret)?{clientSecret:dt(n.client_secret)}:{},...dt(n.profile_arn)?{profileArn:dt(n.profile_arn)}:{},...dt(n.start_url)?{startUrl:dt(n.start_url)}:{},refreshToken:n.refresh_token,accessToken:n.access_token,expiresAt:n.expires_at,rateLimitResetTime:n.rate_limit_reset??0,isHealthy:n.is_healthy!==0,...dt(n.unhealthy_reason)?{unhealthyReason:dt(n.unhealthy_reason)}:{},...n.recovery_time===null?{}:{recoveryTime:n.recovery_time},failCount:n.fail_count??0,lastUsed:n.last_used??0,usedCount:n.used_count??0,limitCount:n.limit_count??0,lastSync:n.last_sync??0,overageCount:n.overage_count??0}}}function IT(n,t){let i=n.from??YQ(),s=new FQ(i,{readonly:!0,strict:!0}),r=0,e=0;try{let o=s.query(`SELECT
|
|
165
281
|
id, email, auth_method, region, oidc_region, client_id, client_secret,
|
|
166
282
|
profile_arn, start_url, refresh_token, access_token, expires_at,
|
|
167
283
|
rate_limit_reset, is_healthy, unhealthy_reason, recovery_time, fail_count,
|
|
168
284
|
last_used, used_count, limit_count, last_sync, overage_count
|
|
169
|
-
FROM accounts`).all();for(let
|
|
170
|
-
${
|
|
285
|
+
FROM accounts`).all();for(let h of o){let u=DQ.safeParse(h);if(!u.success){e+=1,t.stdout("Skipped malformed source account row");continue}let c=mQ(u.data);if(c.kind==="skipped"){e+=1,t.stdout(`Skipped ${u.data.email}: ${c.reason}`);continue}t.database.insertAccount(c.account),r+=1,t.stdout(`Imported ${c.account.email} ${c.account.authMethod} ${c.account.region}`)}}finally{s.close()}let f=t.database.getAccounts().length;return t.stdout(`Imported ${r}, skipped ${e}, total in DB now ${f}`),{imported:r,skipped:e,total:f}}import{createHash as QQ}from"crypto";var JQ=M.object({clientId:M.string().min(1),clientSecret:M.string().min(1)}),XQ=M.object({verificationUri:M.string().min(1),verificationUriComplete:M.string().min(1),userCode:M.string().min(1),deviceCode:M.string().min(1),interval:M.number().positive().default(5),expiresIn:M.number().positive().default(600)}),zQ=M.object({error:M.string().optional(),error_description:M.string().optional(),access_token:M.string().optional(),accessToken:M.string().optional(),refresh_token:M.string().optional(),refreshToken:M.string().optional(),expires_in:M.number().optional(),expiresIn:M.number().optional()}).passthrough();class qn extends Error{constructor(n,t){super(n,t);this.name="KiroIDCError"}}async function r0(n){try{return await n.text()}catch(t){if(t instanceof Error)return"";throw t}}async function UT(n,t,i){let s=Oh(n),r=$r(Or.SSO_OIDC_ENDPOINT,s),e=t??Or.BUILDER_ID_START_URL,f=await fetch(`${r}/client/register`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":Rn.USER_AGENT},body:JSON.stringify({clientName:"Kiro IDE",clientType:"public",scopes:Or.SCOPES,grantTypes:["urn:ietf:params:oauth:grant-type:device_code","refresh_token"]}),...i?{proxy:i}:{}});if(!f.ok)throw new qn(`Client registration failed: ${f.status} ${await r0(f)}`);let o=JQ.safeParse(await f.json());if(!o.success)throw new qn("Client registration response missing clientId or clientSecret",{cause:o.error});let h=await fetch(`${r}/device_authorization`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":Rn.USER_AGENT},body:JSON.stringify({clientId:o.data.clientId,clientSecret:o.data.clientSecret,startUrl:e}),...i?{proxy:i}:{}});if(!h.ok)throw new qn(`Device authorization failed: ${h.status} ${await r0(h)}`);let u=XQ.safeParse(await h.json());if(!u.success)throw new qn("Device authorization response missing required fields",{cause:u.error});return{verificationUrl:u.data.verificationUri,verificationUriComplete:u.data.verificationUriComplete,userCode:u.data.userCode,deviceCode:u.data.deviceCode,clientId:o.data.clientId,clientSecret:o.data.clientSecret,interval:u.data.interval,expiresIn:u.data.expiresIn,region:s,startUrl:e}}async function bT(n,t,i,s,r,e,f=(h)=>new Promise((u)=>setTimeout(u,h)),o){if(!n||!t||!i)throw new qn("Missing required parameters for token polling");let h=Oh(e),u=$r(Or.SSO_OIDC_ENDPOINT,h),c=Math.floor(r/s),_=s*1000;for(let w=1;w<=c;w+=1){await f(_);let l=await fetch(`${u}/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":Rn.USER_AGENT},body:JSON.stringify({clientId:n,clientSecret:t,deviceCode:i,grantType:"urn:ietf:params:oauth:grant-type:device_code"}),...o?{proxy:o}:{}}),A=await r0(l),d={};if(A)try{d=JSON.parse(A)}catch(S){throw new qn(`Token polling failed: invalid JSON response (HTTP ${l.status}): ${A.slice(0,300)}`,{cause:S})}let E=zQ.safeParse(d);if(!E.success)throw new qn(`Token polling failed: invalid response (HTTP ${l.status})`,{cause:E.error});let R=E.data;switch(R.error){case void 0:break;case"authorization_pending":continue;case"slow_down":_+=5000;continue;case"expired_token":throw new qn("Device code has expired. Please restart the authorization process.");case"access_denied":throw new qn("Authorization was denied by the user.");default:throw new qn(`Token polling failed: ${R.error} - ${R.error_description??""}`)}let y=R.access_token??R.accessToken,T=R.refresh_token??R.refreshToken;if(y&&T)return{refreshToken:T,accessToken:y,expiresAt:Date.now()+(R.expires_in??R.expiresIn??3600)*1000,email:"builder-id@aws.amazon.com",clientId:n,clientSecret:t,region:h,authMethod:"idc"};if(!l.ok)throw new qn(`Token request failed with status: ${l.status} ${A?`(${A.slice(0,200)})`:""}`);throw new qn(`Token polling failed: missing tokens in response: ${A?A.slice(0,300):"[empty]"}`)}throw new qn("Token polling timed out. Authorization may have expired.")}function CQ(n){if(n===void 0||n.trim()==="")return;let t=new URL(n.trim());return t.hash="",t.search="",t.pathname=`${t.pathname.replace(/\/start\/?$/,"").replace(/\/+$/,"")}/start`,t.toString()}function xQ(n,t){return QQ("sha256").update(`${n}:idc:${t}:`).digest("hex")}async function $T(n,t={},i={}){let s=i.authorize??UT,r=i.poll??bT,e=i.stdout??console.log,f=CQ(t.startUrl),o=Li.parse(t.region??n.default_region),h=$s(n),u=await s(o,f,h);e(`Open this URL to sign in:
|
|
286
|
+
${u.verificationUriComplete}`);let c=await r(u.clientId,u.clientSecret,u.deviceCode,u.interval,u.expiresIn,o,void 0,h),_={id:xQ(c.email,c.clientId),email:c.email,authMethod:"idc",region:o,oidcRegion:o,clientId:c.clientId,clientSecret:c.clientSecret,...f?{startUrl:f}:{},refreshToken:c.refreshToken,accessToken:c.accessToken,expiresAt:c.expiresAt,rateLimitResetTime:0,isHealthy:!0,failCount:0,usedCount:0,limitCount:0},w=i.openDb?.(si)??new Pi(si);try{w.insertAccount(_)}finally{w.close()}e(`Login successful: ${_.email}`)}function KQ(n){let t=n.isHealthy?"healthy":"unhealthy";return`${n.email} ${n.region} ${t} generation=${n.generation} used=${n.usedCount??0}/${n.limitCount??0}`}var kQ={loadConfig:S0,startServer:gT,runLogin:$T,runImportAccounts:IT,openDb:(n)=>new Pi(n),stdout:console.log,stderr:console.error};async function qQ(n,t){switch(n.kind){case"help":return t.stdout(vf),0;case"serve":{let i={...n.host?{host:n.host}:{},...n.port!==void 0?{port:n.port}:{},...n.proxy!==void 0?{proxy_url:n.proxy}:{}},s=t.loadConfig({...n.configPath?{configPath:n.configPath}:{},overrides:i});if(s.test_upstream_endpoint)t.stderr(`WARNING: test_upstream_endpoint is set (${s.test_upstream_endpoint}); routing upstream to a NON-production endpoint. Unset it for normal use.`);let r=t.startServer(s);return t.stdout(`Listening on http://${r.hostname??s.host}:${r.port??s.port}`),0}case"login":{let i=t.loadConfig({...n.configPath?{configPath:n.configPath}:{}});if(i.auth_source==="opencode-shared")return t.stderr(`auth_source=opencode-shared uses ${i.opencode_auth_db_path??fr()} as the authentication authority. Run "opencode auth login" and select Kiro, or set auth_source to "local" before using kiro-provider login.`),1;return await t.runLogin(i,{...n.startUrl?{startUrl:n.startUrl}:{},...n.region?{region:n.region}:{}}),0}case"accounts-list":{let i=t.openDb(si);try{for(let s of i.getAccounts())t.stdout(KQ(s))}finally{i.close()}return 0}case"accounts-import":{let i=t.openDb(si);try{t.runImportAccounts({...n.from?{from:n.from}:{}},{database:i,stdout:t.stdout}),t.stderr("WARNING: accounts import creates a snapshot; it does not share refresh-token state with opencode-kiro-auth.")}finally{i.close()}return 0}case"accounts-remove":{let i=t.openDb(si);try{let s=i.getAccounts().find((r)=>r.id===n.identifier||r.email===n.identifier);if(!s)return t.stderr(`Account not found: ${n.identifier}`),1;i.removeAccount(s.id),t.stdout(`Removed account ${s.email}`)}finally{i.close()}return 0}}}async function LT(n=process.argv.slice(2),t=kQ){let i;try{i=s0(n)}catch(s){return t.stderr(s instanceof Error?s.message:String(s)),t.stderr(vf),1}try{return await qQ(i,t)}catch(s){return t.stderr(s instanceof Error?s.message:String(s)),1}}process.exitCode=await LT();
|