@sunerpy/kiro-provider 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +23 -1
  2. package/dist/cli.js +72 -64
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,62 +1,62 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var ug=Object.create;var{getPrototypeOf:lg,defineProperty:Fo,getOwnPropertyNames:_g}=Object;var wg=Object.prototype.hasOwnProperty;function Ag(t){return this[t]}var Mg,dg,H=(t,n,s)=>{var r=t!=null&&typeof t==="object";if(r){var e=n?Mg??=new WeakMap:dg??=new WeakMap,i=e.get(t);if(i)return i}s=t!=null?ug(lg(t)):{};let f=n||!t||!t.__esModule?Fo(s,"default",{value:t,enumerable:!0}):s;for(let o of _g(t))if(!wg.call(f,o))Fo(f,o,{get:Ag.bind(t,o),enumerable:!0});if(r)e.set(t,f);return f};var K=(t,n)=>()=>(n||t((n={exports:{}}).exports,n),n.exports);var gg=(t)=>t;function Eg(t,n){this[t]=gg.bind(null,n)}var Rg=(t,n)=>{for(var s in n)Fo(t,s,{get:n[s],enumerable:!0,configurable:!0,set:Eg.bind(n,s)})};var j=import.meta.require;var $u=K((G9,Su)=>{var Ds=1000,Ws=Ds*60,Ys=Ws*60,ts=Ys*24,kE=ts*7,XE=ts*365.25;Su.exports=function(t,n){n=n||{};var s=typeof t;if(s==="string"&&t.length>0)return qE(t);else if(s==="number"&&isFinite(t))return n.long?aE(t):CE(t);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function qE(t){if(t=String(t),t.length>100)return;var n=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(!n)return;var s=parseFloat(n[1]),r=(n[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return s*XE;case"weeks":case"week":case"w":return s*kE;case"days":case"day":case"d":return s*ts;case"hours":case"hour":case"hrs":case"hr":case"h":return s*Ys;case"minutes":case"minute":case"mins":case"min":case"m":return s*Ws;case"seconds":case"second":case"secs":case"sec":case"s":return s*Ds;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return s;default:return}}function CE(t){var n=Math.abs(t);if(n>=ts)return Math.round(t/ts)+"d";if(n>=Ys)return Math.round(t/Ys)+"h";if(n>=Ws)return Math.round(t/Ws)+"m";if(n>=Ds)return Math.round(t/Ds)+"s";return t+"ms"}function aE(t){var n=Math.abs(t);if(n>=ts)return Ie(t,n,ts,"day");if(n>=Ys)return Ie(t,n,Ys,"hour");if(n>=Ws)return Ie(t,n,Ws,"minute");if(n>=Ds)return Ie(t,n,Ds,"second");return t+" ms"}function Ie(t,n,s,r){var e=n>=s*1.5;return Math.round(t/s)+" "+r+(e?"s":"")}});var xo=K((B9,Uu)=>{function KE(t){s.debug=s,s.default=s,s.coerce=c,s.disable=f,s.enable=e,s.enabled=o,s.humanize=$u(),s.destroy=h,Object.keys(t).forEach((u)=>{s[u]=t[u]}),s.names=[],s.skips=[],s.formatters={};function n(u){let l=0;for(let _=0;_<u.length;_++)l=(l<<5)-l+u.charCodeAt(_),l|=0;return s.colors[Math.abs(l)%s.colors.length]}s.selectColor=n;function s(u){let l,_=null,w,A;function M(...d){if(!M.enabled)return;let E=M,b=Number(new Date),L=b-(l||b);if(E.diff=L,E.prev=l,E.curr=b,l=b,d[0]=s.coerce(d[0]),typeof d[0]!=="string")d.unshift("%O");let S=0;d[0]=d[0].replace(/%([a-zA-Z%])/g,(x,X)=>{if(x==="%%")return"%";S++;let v=s.formatters[X];if(typeof v==="function"){let Q=d[S];x=v.call(E,Q),d.splice(S,1),S--}return x}),s.formatArgs.call(E,d),(E.log||s.log).apply(E,d)}if(M.namespace=u,M.useColors=s.useColors(),M.color=s.selectColor(u),M.extend=r,M.destroy=s.destroy,Object.defineProperty(M,"enabled",{enumerable:!0,configurable:!1,get:()=>{if(_!==null)return _;if(w!==s.namespaces)w=s.namespaces,A=s.enabled(u);return A},set:(d)=>{_=d}}),typeof s.init==="function")s.init(M);return M}function r(u,l){let _=s(this.namespace+(typeof l>"u"?":":l)+u);return _.log=this.log,_}function e(u){s.save(u),s.namespaces=u,s.names=[],s.skips=[];let l=(typeof u==="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let _ of l)if(_[0]==="-")s.skips.push(_.slice(1));else s.names.push(_)}function i(u,l){let _=0,w=0,A=-1,M=0;while(_<u.length)if(w<l.length&&(l[w]===u[_]||l[w]==="*"))if(l[w]==="*")A=w,M=_,w++;else _++,w++;else if(A!==-1)w=A+1,M++,_=M;else return!1;while(w<l.length&&l[w]==="*")w++;return w===l.length}function f(){let u=[...s.names,...s.skips.map((l)=>"-"+l)].join(",");return s.enable(""),u}function o(u){for(let l of s.skips)if(i(u,l))return!1;for(let l of s.names)if(i(u,l))return!0;return!1}function c(u){if(u instanceof Error)return u.stack||u.message;return u}function h(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return s.enable(s.load()),s}Uu.exports=KE});var Iu=K((Lu,Oe)=>{Lu.formatArgs=jE;Lu.save=pE;Lu.load=vE;Lu.useColors=VE;Lu.storage=ZE();Lu.destroy=(()=>{let t=!1;return()=>{if(!t)t=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}})();Lu.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function VE(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let t;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(t=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(t[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function jE(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+Oe.exports.humanize(this.diff),!this.useColors)return;let n="color: "+this.color;t.splice(1,0,n,"color: inherit");let s=0,r=0;t[0].replace(/%[a-zA-Z%]/g,(e)=>{if(e==="%%")return;if(s++,e==="%c")r=s}),t.splice(r,0,n)}Lu.log=console.debug||console.log||(()=>{});function pE(t){try{if(t)Lu.storage.setItem("debug",t);else Lu.storage.removeItem("debug")}catch(n){}}function vE(){let t;try{t=Lu.storage.getItem("debug")||Lu.storage.getItem("DEBUG")}catch(n){}if(!t&&typeof process<"u"&&"env"in process)t=process.env.DEBUG;return t}function ZE(){try{return localStorage}catch(t){}}Oe.exports=xo()(Lu);var{formatters:tR}=Oe.exports;tR.j=function(t){try{return JSON.stringify(t)}catch(n){return"[UnexpectedJSONParseError]: "+n.message}}});var Bu=K((yu,Ge)=>{var cR=j("tty"),ye=j("util");yu.init=MR;yu.log=_R;yu.formatArgs=uR;yu.save=wR;yu.load=AR;yu.useColors=hR;yu.destroy=ye.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");yu.colors=[6,2,3,4,5,1];try{let t=(()=>{throw new Error("Cannot require module "+"supports-color");})();if(t&&(t.stderr||t).level>=2)yu.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]}catch(t){}yu.inspectOpts=Object.keys(process.env).filter((t)=>{return/^debug_/i.test(t)}).reduce((t,n)=>{let s=n.substring(6).toLowerCase().replace(/_([a-z])/g,(e,i)=>{return i.toUpperCase()}),r=process.env[n];if(/^(yes|on|true|enabled)$/i.test(r))r=!0;else if(/^(no|off|false|disabled)$/i.test(r))r=!1;else if(r==="null")r=null;else r=Number(r);return t[s]=r,t},{});function hR(){return"colors"in yu.inspectOpts?Boolean(yu.inspectOpts.colors):cR.isatty(process.stderr.fd)}function uR(t){let{namespace:n,useColors:s}=this;if(s){let r=this.color,e="\x1B[3"+(r<8?r:"8;5;"+r),i=` ${e};1m${n} \x1B[0m`;t[0]=i+t[0].split(`
3
+ var NE=Object.create;var{getPrototypeOf:WE,defineProperty:Qo,getOwnPropertyNames:DE}=Object;var YE=Object.prototype.hasOwnProperty;function mE(t){return this[t]}var QE,JE,Y=(t,n,s)=>{var r=t!=null&&typeof t==="object";if(r){var i=n?QE??=new WeakMap:JE??=new WeakMap,e=i.get(t);if(e)return e}s=t!=null?NE(WE(t)):{};let f=n||!t||!t.__esModule?Qo(s,"default",{value:t,enumerable:!0}):s;for(let o of DE(t))if(!YE.call(f,o))Qo(f,o,{get:mE.bind(t,o),enumerable:!0});if(r)i.set(t,f);return f};var Z=(t,n)=>()=>(n||t((n={exports:{}}).exports,n),n.exports);var kE=(t)=>t;function XE(t,n){this[t]=kE.bind(null,n)}var zE=(t,n)=>{for(var s in n)Qo(t,s,{get:n[s],enumerable:!0,configurable:!0,set:XE.bind(n,s)})};var nt=import.meta.require;var D0=Z((Gm,W0)=>{var Ds=1000,Ys=Ds*60,ms=Ys*60,ts=ms*24,wR=ts*7,AR=ts*365.25;W0.exports=function(t,n){n=n||{};var s=typeof t;if(s==="string"&&t.length>0)return MR(t);else if(s==="number"&&isFinite(t))return n.long?ER(t):gR(t);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function MR(t){if(t=String(t),t.length>100)return;var n=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(!n)return;var s=parseFloat(n[1]),r=(n[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return s*AR;case"weeks":case"week":case"w":return s*wR;case"days":case"day":case"d":return s*ts;case"hours":case"hour":case"hrs":case"hr":case"h":return s*ms;case"minutes":case"minute":case"mins":case"min":case"m":return s*Ys;case"seconds":case"second":case"secs":case"sec":case"s":return s*Ds;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return s;default:return}}function gR(t){var n=Math.abs(t);if(n>=ts)return Math.round(t/ts)+"d";if(n>=ms)return Math.round(t/ms)+"h";if(n>=Ys)return Math.round(t/Ys)+"m";if(n>=Ds)return Math.round(t/Ds)+"s";return t+"ms"}function ER(t){var n=Math.abs(t);if(n>=ts)return Gi(t,n,ts,"day");if(n>=ms)return Gi(t,n,ms,"hour");if(n>=Ys)return Gi(t,n,Ys,"minute");if(n>=Ds)return Gi(t,n,Ds,"second");return t+" ms"}function Gi(t,n,s,r){var i=n>=s*1.5;return Math.round(t/s)+" "+r+(i?"s":"")}});var Co=Z((Bm,Y0)=>{function dR(t){s.debug=s,s.default=s,s.coerce=c,s.disable=f,s.enable=i,s.enabled=o,s.humanize=D0(),s.destroy=h,Object.keys(t).forEach((u)=>{s[u]=t[u]}),s.names=[],s.skips=[],s.formatters={};function n(u){let _=0;for(let l=0;l<u.length;l++)_=(_<<5)-_+u.charCodeAt(l),_|=0;return s.colors[Math.abs(_)%s.colors.length]}s.selectColor=n;function s(u){let _,l=null,w,A;function M(...E){if(!M.enabled)return;let d=M,T=Number(new Date),U=T-(_||T);if(d.diff=U,d.prev=_,d.curr=T,_=T,E[0]=s.coerce(E[0]),typeof E[0]!=="string")E.unshift("%O");let S=0;E[0]=E[0].replace(/%([a-zA-Z%])/g,(D,q)=>{if(D==="%%")return"%";S++;let tt=s.formatters[q];if(typeof tt==="function"){let J=E[S];D=tt.call(d,J),E.splice(S,1),S--}return D}),s.formatArgs.call(d,E),(d.log||s.log).apply(d,E)}if(M.namespace=u,M.useColors=s.useColors(),M.color=s.selectColor(u),M.extend=r,M.destroy=s.destroy,Object.defineProperty(M,"enabled",{enumerable:!0,configurable:!1,get:()=>{if(l!==null)return l;if(w!==s.namespaces)w=s.namespaces,A=s.enabled(u);return A},set:(E)=>{l=E}}),typeof s.init==="function")s.init(M);return M}function r(u,_){let l=s(this.namespace+(typeof _>"u"?":":_)+u);return l.log=this.log,l}function i(u){s.save(u),s.namespaces=u,s.names=[],s.skips=[];let _=(typeof u==="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let l of _)if(l[0]==="-")s.skips.push(l.slice(1));else s.names.push(l)}function e(u,_){let l=0,w=0,A=-1,M=0;while(l<u.length)if(w<_.length&&(_[w]===u[l]||_[w]==="*"))if(_[w]==="*")A=w,M=l,w++;else l++,w++;else if(A!==-1)w=A+1,M++,l=M;else return!1;while(w<_.length&&_[w]==="*")w++;return w===_.length}function f(){let u=[...s.names,...s.skips.map((_)=>"-"+_)].join(",");return s.enable(""),u}function o(u){for(let _ of s.skips)if(e(u,_))return!1;for(let _ of s.names)if(e(u,_))return!0;return!1}function c(u){if(u instanceof Error)return u.stack||u.message;return u}function h(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return s.enable(s.load()),s}Y0.exports=dR});var Q0=Z((m0,Bi)=>{m0.formatArgs=bR;m0.save=TR;m0.load=SR;m0.useColors=RR;m0.storage=$R();m0.destroy=(()=>{let t=!1;return()=>{if(!t)t=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}})();m0.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 RR(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let t;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(t=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(t[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function bR(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+Bi.exports.humanize(this.diff),!this.useColors)return;let n="color: "+this.color;t.splice(1,0,n,"color: inherit");let s=0,r=0;t[0].replace(/%[a-zA-Z%]/g,(i)=>{if(i==="%%")return;if(s++,i==="%c")r=s}),t.splice(r,0,n)}m0.log=console.debug||console.log||(()=>{});function TR(t){try{if(t)m0.storage.setItem("debug",t);else m0.storage.removeItem("debug")}catch(n){}}function SR(){let t;try{t=m0.storage.getItem("debug")||m0.storage.getItem("DEBUG")}catch(n){}if(!t&&typeof process<"u"&&"env"in process)t=process.env.DEBUG;return t}function $R(){try{return localStorage}catch(t){}}Bi.exports=Co()(m0);var{formatters:UR}=Bi.exports;UR.j=function(t){try{return JSON.stringify(t)}catch(n){return"[UnexpectedJSONParseError]: "+n.message}}});var z0=Z((k0,Hi)=>{var HR=nt("tty"),Fi=nt("util");k0.init=QR;k0.log=DR;k0.formatArgs=NR;k0.save=YR;k0.load=mR;k0.useColors=PR;k0.destroy=Fi.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");k0.colors=[6,2,3,4,5,1];try{let t=(()=>{throw new Error("Cannot require module "+"supports-color");})();if(t&&(t.stderr||t).level>=2)k0.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]}catch(t){}k0.inspectOpts=Object.keys(process.env).filter((t)=>{return/^debug_/i.test(t)}).reduce((t,n)=>{let s=n.substring(6).toLowerCase().replace(/_([a-z])/g,(i,e)=>{return e.toUpperCase()}),r=process.env[n];if(/^(yes|on|true|enabled)$/i.test(r))r=!0;else if(/^(no|off|false|disabled)$/i.test(r))r=!1;else if(r==="null")r=null;else r=Number(r);return t[s]=r,t},{});function PR(){return"colors"in k0.inspectOpts?Boolean(k0.inspectOpts.colors):HR.isatty(process.stderr.fd)}function NR(t){let{namespace:n,useColors:s}=this;if(s){let r=this.color,i="\x1B[3"+(r<8?r:"8;5;"+r),e=` ${i};1m${n} \x1B[0m`;t[0]=e+t[0].split(`
4
4
  `).join(`
5
- `+i),t.push(e+"m+"+Ge.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=lR()+n+" "+t[0]}function lR(){if(yu.inspectOpts.hideDate)return"";return new Date().toISOString()+" "}function _R(...t){return process.stderr.write(ye.formatWithOptions(yu.inspectOpts,...t)+`
6
- `)}function wR(t){if(t)process.env.DEBUG=t;else delete process.env.DEBUG}function AR(){return process.env.DEBUG}function MR(t){t.inspectOpts={};let n=Object.keys(yu.inspectOpts);for(let s=0;s<n.length;s++)t.inspectOpts[n[s]]=yu.inspectOpts[n[s]]}Ge.exports=xo()(yu);var{formatters:Ou}=Ge.exports;Ou.o=function(t){return this.inspectOpts.colors=this.useColors,ye.inspect(t,this.inspectOpts).split(`
7
- `).map((n)=>n.trim()).join(" ")};Ou.O=function(t){return this.inspectOpts.colors=this.useColors,ye.inspect(t,this.inspectOpts)}});var Jo=K((P9,Qo)=>{if(typeof process>"u"||process.type==="renderer"||!1||process.__nwjs)Qo.exports=Iu();else Qo.exports=Bu()});var es=K((zR)=>{var po;(function(t){t.HEADER="header",t.QUERY="query"})(po||(po={}));var vo;(function(t){t.HEADER="header",t.QUERY="query"})(vo||(vo={}));var Zo;(function(t){t.HTTP="http",t.HTTPS="https"})(Zo||(Zo={}));var yr;(function(t){t.MD5="md5",t.CRC32="crc32",t.CRC32C="crc32c",t.SHA1="sha1",t.SHA256="sha256"})(yr||(yr={}));var WR=(t)=>{let n=[];if(t.sha256!==void 0)n.push({algorithmId:()=>yr.SHA256,checksumConstructor:()=>t.sha256});if(t.md5!=null)n.push({algorithmId:()=>yr.MD5,checksumConstructor:()=>t.md5});return{addChecksumAlgorithm(s){n.push(s)},checksumAlgorithms(){return n}}},YR=(t)=>{let n={};return t.checksumAlgorithms().forEach((s)=>{n[s.algorithmId()]=s.checksumConstructor()}),n},xR=(t)=>{return WR(t)},QR=(t)=>{return YR(t)},tf;(function(t){t[t.HEADER=0]="HEADER",t[t.TRAILER=1]="TRAILER"})(tf||(tf={}));var JR="__smithy_context",nf;(function(t){t.PROFILE="profile",t.SSO_SESSION="sso-session",t.SERVICES="services"})(nf||(nf={}));var sf;(function(t){t.HTTP_0_9="http/0.9",t.HTTP_1_0="http/1.0",t.TDS_8_0="tds/8.0"})(sf||(sf={}));zR.AlgorithmId=yr;zR.EndpointURLScheme=Zo;zR.FieldPosition=tf;zR.HttpApiKeyAuthLocation=vo;zR.HttpAuthLocation=po;zR.IniSectionType=nf;zR.RequestHandlerProtocol=sf;zR.SMITHY_CONTEXT_KEY=JR;zR.getDefaultClientConfiguration=xR;zR.resolveDefaultRuntimeConfig=QR});var tn=K((ib)=>{var{SMITHY_CONTEXT_KEY:Ku}=es(),ZR=(t)=>t[Ku]||(t[Ku]={});class De{method;protocol;hostname;port;path;query;headers;username;password;fragment;body;constructor(t){this.method=t.method||"GET",this.hostname=t.hostname||"localhost",this.port=t.port,this.query=t.query||{},this.headers=t.headers||{},this.body=t.body,this.protocol=t.protocol?t.protocol.slice(-1)!==":"?`${t.protocol}:`:t.protocol:"https:",this.path=t.path?t.path.charAt(0)!=="/"?`/${t.path}`:t.path:"/",this.username=t.username,this.password=t.password,this.fragment=t.fragment}static clone(t){let n=new De({...t,headers:{...t.headers}});if(n.query)n.query=tb(n.query);return n}static isInstance(t){if(!t)return!1;let n=t;return"method"in n&&"protocol"in n&&"hostname"in n&&"path"in n&&typeof n.query==="object"&&typeof n.headers==="object"}clone(){return De.clone(this)}}function tb(t){return Object.keys(t).reduce((n,s)=>{let r=t[s];return{...n,[s]:Array.isArray(r)?[...r]:r}},{})}class Vu{statusCode;reason;headers;body;constructor(t){this.statusCode=t.statusCode,this.reason=t.reason,this.headers=t.headers||{},this.body=t.body}static isInstance(t){if(!t)return!1;let n=t;return typeof n.statusCode==="number"&&typeof n.headers==="object"}}var nb=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),ju=(t,n=!1)=>{if(!n)return nb.test(t);let s=t.split(".");for(let r of s)if(!ju(r))return!1;return!0};function sb(t){return/^[a-z0-9][a-z0-9.-]*[a-z0-9]$/.test(t)}var rb=(t)=>{if(typeof t==="function")return t;let n=Promise.resolve(t);return()=>n};function pu(t){let n={};if(t=t.replace(/^\?/,""),t)for(let s of t.split("&")){let[r,e=null]=s.split("=");if(r=decodeURIComponent(r),e)e=decodeURIComponent(e);if(!(r in n))n[r]=e;else if(Array.isArray(n[r]))n[r].push(e);else n[r]=[n[r],e]}return n}var We=(t)=>{if(typeof t==="string")return We(new URL(t));let{hostname:n,pathname:s,port:r,protocol:e,search:i}=t,f;if(i)f=pu(i);return{hostname:n,port:r?parseInt(r):void 0,protocol:e,path:s,query:f}},eb=(t)=>{if(typeof t==="object"){if("url"in t){let n=We(t.url);if(t.headers){n.headers={};for(let s in t.headers)n.headers[s.toLowerCase()]=t.headers[s].join(", ")}return n}return t}return We(t)};ib.HttpRequest=De;ib.HttpResponse=Vu;ib.getSmithyContext=ZR;ib.isValidHostLabel=ju;ib.isValidHostname=sb;ib.normalizeProvider=rb;ib.parseQueryString=pu;ib.parseUrl=We;ib.toEndpointV1=eb});var Pn=K((yb)=>{var{getSmithyContext:vu,HttpResponse:Mb,toEndpointV1:db}=tn(),Ye=(t)=>{if(typeof t==="function")return t();return t},of=(t,n,s,r,e)=>({name:n,namespace:t,traits:s,input:r,output:e}),gb=(t)=>(n,s)=>async(r)=>{let{response:e}=await n(r),{operationSchema:i}=vu(s),[,f,o,c,h,u]=i??[];try{let l=await t.protocol.deserializeResponse(of(f,o,c,h,u),{...t,...s},e);return{response:e,output:l}}catch(l){if(Object.defineProperty(l,"$response",{value:e,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in l)){try{l.message+=`
8
- Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`}catch(w){if(!s.logger||s.logger?.constructor?.name==="NoOpLogger")console.warn("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.");else s.logger?.warn?.("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.")}if(typeof l.$responseBodyText<"u"){if(l.$response)l.$response.body=l.$responseBodyText}try{if(Mb.isInstance(e)){let{headers:w={},statusCode:A}=e,M=Object.entries(w);l.$metadata={httpStatusCode:A,requestId:rf(/^x-[\w-]+-request-?id$/,M),extendedRequestId:rf(/^x-[\w-]+-id-2$/,M),cfId:rf(/^x-[\w-]+-cf-id$/,M)}}}catch(w){}}throw l}},rf=(t,n)=>{return(n.find(([s])=>{return s.match(t)})||[void 0,void 0])[1]},Eb=(t)=>(n,s)=>async(r)=>{let{operationSchema:e}=vu(s),[,i,f,o,c,h]=e??[],u=s.endpointV2?async()=>db(s.endpointV2):t.endpoint,l=await t.protocol.serializeRequest(of(i,f,o,c,h),r.input,{...t,...s,endpoint:u});return n({...r,request:l})},Zu={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},tl={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function Rb(t){return{applyToStack:(n)=>{n.add(Eb(t),tl),n.add(gb(t),Zu),t.protocol.setSerdeContext(t)}}}class Et{name;namespace;traits;static assign(t,n){return Object.assign(t,n)}static[Symbol.hasInstance](t){let n=this.prototype.isPrototypeOf(t);if(!n&&typeof t==="object"&&t!==null)return t.symbol===this.symbol;return n}getName(){return this.namespace+"#"+this.name}}class ze extends Et{static symbol=Symbol.for("@smithy/lis");name;traits;valueSchema;symbol=ze.symbol}var bb=(t,n,s,r)=>Et.assign(new ze,{name:n,namespace:t,traits:s,valueSchema:r});class ke extends Et{static symbol=Symbol.for("@smithy/map");name;traits;keySchema;valueSchema;symbol=ke.symbol}var Tb=(t,n,s,r,e)=>Et.assign(new ke,{name:n,namespace:t,traits:s,keySchema:r,valueSchema:e});class Xe extends Et{static symbol=Symbol.for("@smithy/ope");name;traits;input;output;symbol=Xe.symbol}var Sb=(t,n,s,r,e)=>Et.assign(new Xe,{name:n,namespace:t,traits:s,input:r,output:e});class Fr extends Et{static symbol=Symbol.for("@smithy/str");name;traits;memberNames;memberList;symbol=Fr.symbol}var $b=(t,n,s,r,e)=>Et.assign(new Fr,{name:n,namespace:t,traits:s,memberNames:r,memberList:e});class qe extends Fr{static symbol=Symbol.for("@smithy/err");ctor;symbol=qe.symbol}var Ub=(t,n,s,r,e,i)=>Et.assign(new qe,{name:n,namespace:t,traits:s,memberNames:r,memberList:e,ctor:null}),xe=[];function mr(t){if(typeof t==="object")return t;if(t=t|0,xe[t])return xe[t];let n={},s=0;for(let r of["httpLabel","idempotent","idempotencyToken","sensitive","httpPayload","httpResponseCode","httpQueryParams"])if((t>>s++&1)===1)n[r]=1;return xe[t]=n}var Gr={it:Symbol.for("@smithy/nor-struct-it"),ns:Symbol.for("@smithy/ns")},Qe=[],Je={};class gn{ref;memberName;static symbol=Symbol.for("@smithy/nor");symbol=gn.symbol;name;schema;_isMemberSchema;traits;memberTraits;normalizedTraits;constructor(t,n){this.ref=t,this.memberName=n;let s=[],r=t,e=t;this._isMemberSchema=!1;while(ef(r))s.push(r[1]),r=r[0],e=Ye(r),this._isMemberSchema=!0;if(s.length>0){this.memberTraits={};for(let i=s.length-1;i>=0;--i){let f=s[i];Object.assign(this.memberTraits,mr(f))}}else this.memberTraits=0;if(e instanceof gn){let i=this.memberTraits;Object.assign(this,e),this.memberTraits=Object.assign({},i,e.getMemberTraits(),this.getMemberTraits()),this.normalizedTraits=void 0,this.memberName=n??e.memberName;return}if(this.schema=Ye(e),nl(this.schema))this.name=`${this.schema[1]}#${this.schema[2]}`,this.traits=this.schema[3];else this.name=this.memberName??String(e),this.traits=0;if(this._isMemberSchema&&!n)throw Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(!0)} missing member name.`)}static[Symbol.hasInstance](t){let n=this.prototype.isPrototypeOf(t);if(!n&&typeof t==="object"&&t!==null)return t.symbol===this.symbol;return n}static of(t){let n=typeof t==="function"||typeof t==="object"&&t!==null;if(typeof t==="number"){if(Qe[t])return Qe[t]}else if(typeof t==="string"){if(Je[t])return Je[t]}else if(n){if(t[Gr.ns])return t[Gr.ns]}let s=Ye(t);if(s instanceof gn)return s;if(ef(s)){let[e,i]=s;if(e instanceof gn)return Object.assign(e.getMergedTraits(),mr(i)),e;throw Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(t,null,2)}.`)}let r=new gn(s);if(n)return t[Gr.ns]=r;if(typeof s==="string")return Je[s]=r;if(typeof s==="number")return Qe[s]=r;return r}getSchema(){let t=this.schema;if(Array.isArray(t)&&t[0]===0)return t[4];return t}getName(t=!1){let{name:n}=this;return!t&&n&&n.includes("#")?n.split("#")[1]:n||void 0}getMemberName(){return this.memberName}isMemberSchema(){return this._isMemberSchema}isListSchema(){let t=this.getSchema();return typeof t==="number"?t>=64&&t<128:t[0]===1}isMapSchema(){let t=this.getSchema();return typeof t==="number"?t>=128&&t<=255:t[0]===2}isStructSchema(){let t=this.getSchema();if(typeof t!=="object")return!1;let n=t[0];return n===3||n===-3||n===4}isUnionSchema(){let t=this.getSchema();if(typeof t!=="object")return!1;return t[0]===4}isBlobSchema(){let t=this.getSchema();return t===21||t===42}isTimestampSchema(){let t=this.getSchema();return typeof t==="number"&&t>=4&&t<=7}isUnitSchema(){return this.getSchema()==="unit"}isDocumentSchema(){return this.getSchema()===15}isStringSchema(){return this.getSchema()===0}isBooleanSchema(){return this.getSchema()===2}isNumericSchema(){return this.getSchema()===1}isBigIntegerSchema(){return this.getSchema()===17}isBigDecimalSchema(){return this.getSchema()===19}isStreaming(){let{streaming:t}=this.getMergedTraits();return!!t||this.getSchema()===42}isIdempotencyToken(){return!!this.getMergedTraits().idempotencyToken}getMergedTraits(){return this.normalizedTraits??(this.normalizedTraits={...this.getOwnTraits(),...this.getMemberTraits()})}getMemberTraits(){return mr(this.memberTraits)}getOwnTraits(){return mr(this.traits)}getKeySchema(){let[t,n]=[this.isDocumentSchema(),this.isMapSchema()];if(!t&&!n)throw Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(!0)}`);let s=this.getSchema(),r=t?15:s[4]??0;return Br([r,0],"key")}getValueSchema(){let t=this.getSchema(),[n,s,r]=[this.isDocumentSchema(),this.isMapSchema(),this.isListSchema()],e=typeof t==="number"?63&t:t&&typeof t==="object"&&(s||r)?t[3+t[0]]:n?15:void 0;if(e!=null)return Br([e,0],s?"value":"member");throw Error(`@smithy/core/schema - ${this.getName(!0)} has no value member.`)}getMemberSchema(t){let n=this.getSchema();if(this.isStructSchema()&&n[4].includes(t)){let s=n[4].indexOf(t),r=n[5][s];return Br(ef(r)?r:[r,0],t)}if(this.isDocumentSchema())return Br([15,0],t);throw Error(`@smithy/core/schema - ${this.getName(!0)} has no member=${t}.`)}getMemberSchemas(){let t={};try{for(let[n,s]of this.structIterator())t[n]=s}catch(n){}return t}getEventStreamMember(){if(this.isStructSchema()){for(let[t,n]of this.structIterator())if(n.isStreaming()&&n.isStructSchema())return t}return""}*structIterator(){if(this.isUnitSchema())return;if(!this.isStructSchema())throw Error("@smithy/core/schema - cannot iterate non-struct schema.");let t=this.getSchema(),n=t[4].length,s=t[Gr.it];if(s&&n===s.length){yield*s;return}s=Array(n);for(let r=0;r<n;++r){let e=t[4][r],i=Br([t[5][r],0],e);yield s[r]=[e,i]}t[Gr.it]=s}}function Br(t,n){if(t instanceof gn)return Object.assign(t,{memberName:n,_isMemberSchema:!0});return new gn(t,n)}var ef=(t)=>Array.isArray(t)&&t.length===2,nl=(t)=>Array.isArray(t)&&t.length>=5;class Pr extends Et{static symbol=Symbol.for("@smithy/sim");name;schemaRef;traits;symbol=Pr.symbol}var Lb=(t,n,s,r)=>Et.assign(new Pr,{name:n,namespace:t,traits:r,schemaRef:s}),Ib=(t,n,s,r)=>Et.assign(new Pr,{name:n,namespace:t,traits:s,schemaRef:r}),Ob={BLOB:21,STREAMING_BLOB:42,BOOLEAN:2,STRING:0,NUMERIC:1,BIG_INTEGER:17,BIG_DECIMAL:19,DOCUMENT:15,TIMESTAMP_DEFAULT:4,TIMESTAMP_DATE_TIME:5,TIMESTAMP_HTTP_DATE:6,TIMESTAMP_EPOCH_SECONDS:7,LIST_MODIFIER:64,MAP_MODIFIER:128};class dn{namespace;schemas;exceptions;static registries=new Map;constructor(t,n=new Map,s=new Map){this.namespace=t,this.schemas=n,this.exceptions=s}static for(t){if(!dn.registries.has(t))dn.registries.set(t,new dn(t));return dn.registries.get(t)}copyFrom(t){let{schemas:n,exceptions:s}=this;for(let[r,e]of t.schemas)if(!n.has(r))n.set(r,e);for(let[r,e]of t.exceptions)if(!s.has(r))s.set(r,e)}register(t,n){let s=this.normalizeShapeId(t);for(let r of[this,dn.for(s.split("#")[0])])r.schemas.set(s,n)}getSchema(t){let n=this.normalizeShapeId(t);if(!this.schemas.has(n)){if(!t.includes("#")){let s="#"+t,r=[];for(let[e,i]of this.schemas.entries())if(e.endsWith(s))r.push(i);if(r.length===1)return r[0]}throw Error(`@smithy/core/schema - schema not found for ${n}`)}return this.schemas.get(n)}registerError(t,n){let s=t,r=s[1];for(let e of[this,dn.for(r)])e.schemas.set(r+"#"+s[2],s),e.exceptions.set(s,n)}getErrorCtor(t){let n=t;if(this.exceptions.has(n))return this.exceptions.get(n);return dn.for(n[1]).exceptions.get(n)}getBaseException(){for(let t of this.exceptions.keys())if(Array.isArray(t)){let[,n,s]=t,r=n+"#"+s;if(r.startsWith("smithy.ts.sdk.synthetic.")&&r.endsWith("ServiceException"))return t}return}find(t){for(let n of this.schemas.values())if(t(n))return n;return}clear(){this.schemas.clear(),this.exceptions.clear()}normalizeShapeId(t){if(t.includes("#"))return t;return this.namespace+"#"+t}}yb.ErrorSchema=qe;yb.ListSchema=ze;yb.MapSchema=ke;yb.NormalizedSchema=gn;yb.OperationSchema=Xe;yb.SCHEMA=Ob;yb.Schema=Et;yb.SimpleSchema=Pr;yb.StructureSchema=Fr;yb.TypeRegistry=dn;yb.deref=Ye;yb.deserializerMiddlewareOption=Zu;yb.error=Ub;yb.getSchemaSerdePlugin=Rb;yb.isStaticSchema=nl;yb.list=bb;yb.map=Tb;yb.op=Sb;yb.operation=of;yb.serializerMiddlewareOption=tl;yb.sim=Lb;yb.simAdapter=Ib;yb.simpleSchemaCacheN=Qe;yb.simpleSchemaCacheS=Je;yb.struct=$b;yb.traitsCache=xe;yb.translateTraits=mr});var En=K((N4)=>{var{getSmithyContext:s4,normalizeProvider:r4}=tn();N4.getSmithyContext=s4;N4.normalizeProvider=r4;var{SMITHY_CONTEXT_KEY:e4,AlgorithmId:ae}=es();N4.AlgorithmId=ae;var{NormalizedSchema:i4}=Pn(),is=(t,n)=>{let s=[];if(t)s.push(t);if(n)for(let r of n)s.push(r);return s},Hn=(t,n)=>{return`${t||"anonymous"}${n&&n.length>0?` (a.k.a. ${n.join(",")})`:""}`},Hr=()=>{let t=[],n=[],s=!1,r=new Set,e=(l)=>l.sort((_,w)=>sl[w.step]-sl[_.step]||rl[w.priority||"normal"]-rl[_.priority||"normal"]),i=(l)=>{let _=!1,w=(A)=>{let M=is(A.name,A.aliases);if(M.includes(l)){_=!0;for(let d of M)r.delete(d);return!1}return!0};return t=t.filter(w),n=n.filter(w),_},f=(l)=>{let _=!1,w=(A)=>{if(A.middleware===l){_=!0;for(let M of is(A.name,A.aliases))r.delete(M);return!1}return!0};return t=t.filter(w),n=n.filter(w),_},o=(l)=>{return t.forEach((_)=>{l.add(_.middleware,{..._})}),n.forEach((_)=>{l.addRelativeTo(_.middleware,{..._})}),l.identifyOnResolve?.(u.identifyOnResolve()),l},c=(l)=>{let _=[];return l.before.forEach((w)=>{if(w.before.length===0&&w.after.length===0)_.push(w);else _.push(...c(w))}),_.push(l),l.after.reverse().forEach((w)=>{if(w.before.length===0&&w.after.length===0)_.push(w);else _.push(...c(w))}),_},h=(l=!1)=>{let _=[],w=[],A={};return t.forEach((d)=>{let E={...d,before:[],after:[]};for(let b of is(E.name,E.aliases))A[b]=E;_.push(E)}),n.forEach((d)=>{let E={...d,before:[],after:[]};for(let b of is(E.name,E.aliases))A[b]=E;w.push(E)}),w.forEach((d)=>{if(d.toMiddleware){let E=A[d.toMiddleware];if(E===void 0){if(l)return;throw Error(`${d.toMiddleware} is not found when adding ${Hn(d.name,d.aliases)} middleware ${d.relation} ${d.toMiddleware}`)}if(d.relation==="after")E.after.push(d);if(d.relation==="before")E.before.push(d)}}),e(_).map(c).reduce((d,E)=>{return d.push(...E),d},[])},u={add:(l,_={})=>{let{name:w,override:A,aliases:M}=_,d={step:"initialize",priority:"normal",middleware:l,..._},E=is(w,M);if(E.length>0){if(E.some((b)=>r.has(b))){if(!A)throw Error(`Duplicate middleware name '${Hn(w,M)}'`);for(let b of E){let L=t.findIndex((O)=>O.name===b||O.aliases?.some((x)=>x===b));if(L===-1)continue;let S=t[L];if(S.step!==d.step||d.priority!==S.priority)throw Error(`"${Hn(S.name,S.aliases)}" middleware with ${S.priority} priority in ${S.step} step cannot be overridden by "${Hn(w,M)}" middleware with ${d.priority} priority in ${d.step} step.`);t.splice(L,1)}}for(let b of E)r.add(b)}t.push(d)},addRelativeTo:(l,_)=>{let{name:w,override:A,aliases:M}=_,d={middleware:l,..._},E=is(w,M);if(E.length>0){if(E.some((b)=>r.has(b))){if(!A)throw Error(`Duplicate middleware name '${Hn(w,M)}'`);for(let b of E){let L=n.findIndex((O)=>O.name===b||O.aliases?.some((x)=>x===b));if(L===-1)continue;let S=n[L];if(S.toMiddleware!==d.toMiddleware||S.relation!==d.relation)throw Error(`"${Hn(S.name,S.aliases)}" middleware ${S.relation} "${S.toMiddleware}" middleware cannot be overridden by "${Hn(w,M)}" middleware ${d.relation} "${d.toMiddleware}" middleware.`);n.splice(L,1)}}for(let b of E)r.add(b)}n.push(d)},clone:()=>o(Hr()),use:(l)=>{l.applyToStack(u)},remove:(l)=>{if(typeof l==="string")return i(l);else return f(l)},removeByTag:(l)=>{let _=!1,w=(A)=>{let{tags:M,name:d,aliases:E}=A;if(M&&M.includes(l)){let b=is(d,E);for(let L of b)r.delete(L);return _=!0,!1}return!0};return t=t.filter(w),n=n.filter(w),_},concat:(l)=>{let _=o(Hr());return _.use(l),_.identifyOnResolve(s||_.identifyOnResolve()||(l.identifyOnResolve?.()??!1)),_},applyToStack:o,identify:()=>{return h(!0).map((l)=>{let _=l.step??l.relation+" "+l.toMiddleware;return Hn(l.name,l.aliases)+" - "+_})},identifyOnResolve(l){if(typeof l==="boolean")s=l;return s},resolve:(l,_)=>{for(let w of h().map((A)=>A.middleware).reverse())l=w(l,_);if(s)console.log(u.identify());return l}};return u},sl={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},rl={high:3,normal:2,low:1},o4=(t)=>()=>{throw Error(t)},f4=(t)=>()=>Promise.reject(t),Ce=()=>{let t=new WeakSet;return(n,s)=>{if(typeof s==="object"&&s!==null){if(t.has(s))return"[Circular]";t.add(s)}return s}},c4=(t)=>{return new Promise((n)=>setTimeout(n,t*1000))},ol={minDelay:2,maxDelay:120},nn;(function(t){t.ABORTED="ABORTED",t.FAILURE="FAILURE",t.SUCCESS="SUCCESS",t.RETRY="RETRY",t.TIMEOUT="TIMEOUT"})(nn||(nn={}));var h4=(t)=>{if(t.state===nn.ABORTED){let n=Error(`${JSON.stringify({...t,reason:"Request was aborted"},Ce())}`);throw n.name="AbortError",n}else if(t.state===nn.TIMEOUT){let n=Error(`${JSON.stringify({...t,reason:"Waiter has timed out"},Ce())}`);throw n.name="TimeoutError",n}else if(t.state!==nn.SUCCESS)throw Error(`${JSON.stringify(t,Ce())}`);return t},u4=async({minDelay:t,maxDelay:n,maxWaitTime:s,abortController:r,client:e,abortSignal:i},f,o)=>{let c={},[h,u]=[t*1000,n*1000],l=0,_=Date.now()+s*1000,w=Date.now()+60000,A=!1;while(!0){if(l>0){let E=w4(h,u,l,_);if(r?.signal?.aborted||i?.aborted)return c["AbortController signal aborted."]|=0,c["AbortController signal aborted."]+=1,{state:nn.ABORTED,observedResponses:c};if(Date.now()+E>_)return{state:nn.TIMEOUT,observedResponses:c};await c4(E/1000)}let{state:M,reason:d}=await o(e,f);if(d){let E=_4(d);c[E]|=0,c[E]+=1}if(M!==nn.RETRY)return{state:M,reason:d,final:d,observedResponses:c};if(l+=1,!A&&Date.now()>=w)l4(c,e),A=!0}},l4=(t={},n)=>{let s=Object.keys(t),r=0;for(let f of s){let o=t[f]|0;if(f.startsWith("403:"))r+=o}let e=n?.config?.logger,i=typeof e?.warn==="function"&&!e.constructor?.name?.includes?.("NoOpLogger")?e:console;if(r>=3||s[s.length-1]?.startsWith("403:"))i.warn("@smithy/util-waiter WARN - 403 status code encountered during waiter polling.")},_4=(t)=>{let n=t?.$response?.statusCode??t?.$metadata?.httpStatusCode;if(t?.$responseBodyText)return`${n?n+": ":""}Deserialization error for body: ${t.$responseBodyText}`;if(n){if(t?.$response||t?.message)return`${n??"Unknown"}: ${t?.message}`;return`${n}: OK`}return String(t?.message??JSON.stringify(t,Ce())??"Unknown")},w4=(t,n,s,r)=>{let e=Math.log(n/t)/Math.log(2)+1;if(s>e)return n;let i=t*2**(s-1),f=Math.min(i,n),o=A4(t,f);if(Date.now()+o>r){let c=r-Date.now();return Math.max(0,c-500)}return o},A4=(t,n)=>t+Math.random()*(n-t),M4=(t)=>{if(t.maxWaitTime<=0)throw Error("WaiterConfiguration.maxWaitTime must be greater than 0");else if(t.minDelay<=0)throw Error("WaiterConfiguration.minDelay must be greater than 0");else if(t.maxDelay<=0)throw Error("WaiterConfiguration.maxDelay must be greater than 0");else if(t.maxWaitTime<=t.minDelay)throw Error(`WaiterConfiguration.maxWaitTime [${t.maxWaitTime}] must be greater than WaiterConfiguration.minDelay [${t.minDelay}] for this waiter`);else if(t.maxDelay<t.minDelay)throw Error(`WaiterConfiguration.maxDelay [${t.maxDelay}] must be greater than WaiterConfiguration.minDelay [${t.minDelay}] for this waiter`)},el=(t)=>{let n,s=new Promise((r)=>{if(n=()=>r({state:nn.ABORTED}),typeof t.addEventListener==="function")t.addEventListener("abort",n);else t.onabort=n});return{clearListener(){if(typeof t.removeEventListener==="function")t.removeEventListener("abort",n)},aborted:s}},d4=async(t,n,s)=>{let r={...ol,...t};M4(r);let e=[u4(r,n,s)],i=[];if(t.abortSignal){let{aborted:f,clearListener:o}=el(t.abortSignal);i.push(o),e.push(f)}if(t.abortController?.signal){let{aborted:f,clearListener:o}=el(t.abortController.signal);i.push(o),e.push(f)}return Promise.race(e).then((f)=>{for(let o of i)o();return f})};class fl{config;middlewareStack=Hr();initConfig;handlers;constructor(t){this.config=t;let{protocol:n,protocolSettings:s}=t;if(s){if(typeof n==="function")t.protocol=new n(s)}}send(t,n,s){let r=typeof n!=="function"?n:void 0,e=typeof n==="function"?n:s,i=r===void 0&&this.config.cacheMiddleware===!0,f;if(i){if(!this.handlers)this.handlers=new WeakMap;let o=this.handlers;if(o.has(t.constructor))f=o.get(t.constructor);else f=t.resolveMiddleware(this.middlewareStack,this.config,r),o.set(t.constructor,f)}else delete this.handlers,f=t.resolveMiddleware(this.middlewareStack,this.config,r);if(e)f(t).then((o)=>e(null,o.output),(o)=>e(o)).catch(()=>{});else return f(t).then((o)=>o.output)}destroy(){this.config?.requestHandler?.destroy?.(),delete this.handlers}}var ff="***SensitiveInformation***";function Ke(t,n){if(n==null)return n;let s=i4.of(t);if(s.getMergedTraits().sensitive)return ff;if(s.isListSchema()){if(!!s.getValueSchema().getMergedTraits().sensitive)return ff}else if(s.isMapSchema()){if(!!s.getKeySchema().getMergedTraits().sensitive||!!s.getValueSchema().getMergedTraits().sensitive)return ff}else if(s.isStructSchema()&&typeof n==="object"){let r=n,e={};for(let[i,f]of s.structIterator())if(r[i]!=null)e[i]=Ke(f,r[i]);return e}return n}class Ve{middlewareStack=Hr();schema;static classBuilder(){return new cl}resolveMiddlewareWithContext(t,n,s,{middlewareFn:r,clientName:e,commandName:i,inputFilterSensitiveLog:f,outputFilterSensitiveLog:o,smithyContext:c,additionalContext:h,CommandCtor:u}){for(let d of r.bind(this)(u,t,n,s))this.middlewareStack.use(d);let l=t.concat(this.middlewareStack),{logger:_}=n,w={logger:_,clientName:e,commandName:i,inputFilterSensitiveLog:f,outputFilterSensitiveLog:o,[e4]:{commandInstance:this,...c},...h},{requestHandler:A}=n,M=s??{};if(c.eventStream)M={isEventStream:!0,...M};return l.resolve((d)=>A.handle(d.request,M),w)}}class cl{_init=()=>{};_ep={};_middlewareFn=()=>[];_commandName="";_clientName="";_additionalContext={};_smithyContext={};_inputFilterSensitiveLog=void 0;_outputFilterSensitiveLog=void 0;_serializer=null;_deserializer=null;_operationSchema;init(t){this._init=t}ep(t){return this._ep=t,this}m(t){return this._middlewareFn=t,this}s(t,n,s={}){return this._smithyContext={service:t,operation:n,...s},this}c(t={}){return this._additionalContext=t,this}n(t,n){return this._clientName=t,this._commandName=n,this}f(t=(s)=>s,n=(s)=>s){return this._inputFilterSensitiveLog=t,this._outputFilterSensitiveLog=n,this}ser(t){return this._serializer=t,this}de(t){return this._deserializer=t,this}sc(t){return this._operationSchema=t,this._smithyContext.operationSchema=t,this}build(){let t=this,n;return n=class extends Ve{input;static getEndpointParameterInstructions(){return t._ep}constructor(...[s]){super();this.input=s??{},t._init(this),this.schema=t._operationSchema}resolveMiddleware(s,r,e){let i=t._operationSchema,f=i?.[4]??i?.input,o=i?.[5]??i?.output;return this.resolveMiddlewareWithContext(s,r,e,{CommandCtor:n,middlewareFn:t._middlewareFn,clientName:t._clientName,commandName:t._commandName,inputFilterSensitiveLog:t._inputFilterSensitiveLog??(i?Ke.bind(null,f):(c)=>c),outputFilterSensitiveLog:t._outputFilterSensitiveLog??(i?Ke.bind(null,o):(c)=>c),smithyContext:t._smithyContext,additionalContext:t._additionalContext})}serialize=t._serializer;deserialize=t._deserializer}}}var g4="***SensitiveInformation***",E4=(t,n,s)=>{for(let[i,f]of Object.entries(t)){let o=async function(h,u,l){let _=new f(h);if(typeof u==="function")this.send(_,u);else if(typeof l==="function"){if(typeof u!=="object")throw Error(`Expected http options but got ${typeof u}`);this.send(_,u||{},l)}else return this.send(_,u)},c=(i[0].toLowerCase()+i.slice(1)).replace(/Command$/,"");n.prototype[c]=o}let{paginators:r={},waiters:e={}}=s??{};for(let[i,f]of Object.entries(r))if(n.prototype[i]===void 0)n.prototype[i]=function(o={},c,...h){return f({...c,client:this},o,...h)};for(let[i,f]of Object.entries(e))if(n.prototype[i]===void 0)n.prototype[i]=async function(o={},c,...h){let u=c;if(typeof c==="number")u={maxWaitTime:c};return f({...u,client:this},o,...h)}};class Qs extends Error{$fault;$response;$retryable;$metadata;constructor(t){super(t.message);Object.setPrototypeOf(this,Object.getPrototypeOf(this).constructor.prototype),this.name=t.name,this.$fault=t.$fault,this.$metadata=t.$metadata}static isInstance(t){if(!t)return!1;let n=t;return Qs.prototype.isPrototypeOf(n)||Boolean(n.$fault)&&Boolean(n.$metadata)&&(n.$fault==="client"||n.$fault==="server")}static[Symbol.hasInstance](t){if(!t)return!1;let n=t;if(this===Qs)return Qs.isInstance(t);if(Qs.isInstance(t)){if(n.name&&this.name)return this.prototype.isPrototypeOf(t)||n.name===this.name;return this.prototype.isPrototypeOf(t)}return!1}}var hl=(t,n={})=>{Object.entries(n).filter(([,r])=>r!==void 0).forEach(([r,e])=>{if(t[r]==null||t[r]==="")t[r]=e});let s=t.message||t.Message||"UnknownError";return t.message=s,delete t.Message,t},ul=({output:t,parsedBody:n,exceptionCtor:s,errorCode:r})=>{let e=b4(t),i=e.httpStatusCode?e.httpStatusCode+"":void 0,f=new s({name:n?.code||n?.Code||r||i||"UnknownError",$fault:"client",$metadata:e});throw hl(f,n)},R4=(t)=>{return({output:n,parsedBody:s,errorCode:r})=>{ul({output:n,parsedBody:s,exceptionCtor:t,errorCode:r})}},b4=(t)=>({httpStatusCode:t.statusCode,requestId:t.headers["x-amzn-requestid"]??t.headers["x-amzn-request-id"]??t.headers["x-amz-request-id"],extendedRequestId:t.headers["x-amz-id-2"],cfId:t.headers["x-amz-cf-id"]}),T4=(t)=>{switch(t){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region":return{retryMode:"standard",connectionTimeout:3100};case"mobile":return{retryMode:"standard",connectionTimeout:30000};default:return{}}},il=!1,S4=(t)=>{if(t&&!il&&parseInt(t.substring(1,t.indexOf(".")))<16)il=!0},ll=Object.values(ae),_l=(t)=>{let n=[];for(let s in ae){let r=ae[s];if(t[r]===void 0)continue;n.push({algorithmId:()=>r,checksumConstructor:()=>t[r]})}for(let[s,r]of Object.entries(t.checksumAlgorithms??{}))n.push({algorithmId:()=>s,checksumConstructor:()=>r});return{addChecksumAlgorithm(s){t.checksumAlgorithms=t.checksumAlgorithms??{};let r=s.algorithmId(),e=s.checksumConstructor();if(ll.includes(r))t.checksumAlgorithms[r.toUpperCase()]=e;else t.checksumAlgorithms[r]=e;n.push(s)},checksumAlgorithms(){return n}}},wl=(t)=>{let n={};return t.checksumAlgorithms().forEach((s)=>{let r=s.algorithmId();if(ll.includes(r))n[r]=s.checksumConstructor()}),n},Al=(t)=>{return{setRetryStrategy(n){t.retryStrategy=n},retryStrategy(){return t.retryStrategy}}},Ml=(t)=>{let n={};return n.retryStrategy=t.retryStrategy(),n},dl=(t)=>{return Object.assign(_l(t),Al(t))},$4=dl,U4=(t)=>{return Object.assign(wl(t),Ml(t))},L4=(t)=>Array.isArray(t)?t:[t],gl=(t)=>{for(let s in t)if(Object.prototype.hasOwnProperty.call(t,s)&&t[s]["#text"]!==void 0)t[s]=t[s]["#text"];else if(typeof t[s]==="object"&&t[s]!==null)t[s]=gl(t[s]);return t},I4=(t)=>{return t!=null};class El{trace(){}debug(){}info(){}warn(){}error(){}}function Rl(t,n,s){let r,e,i;if(typeof n>"u"&&typeof s>"u")r={},i=t;else if(r=t,typeof n==="function")return e=n,i=s,G4(r,e,i);else i=n;for(let f of Object.keys(i)){if(!Array.isArray(i[f])){r[f]=i[f];continue}bl(r,null,i,f)}return r}var O4=(t)=>{let n={};for(let[s,r]of Object.entries(t||{}))n[s]=[,r];return n},y4=(t,n)=>{let s={};for(let r in n)bl(s,t,n,r);return s},G4=(t,n,s)=>{return Rl(t,Object.entries(s).reduce((r,[e,i])=>{if(Array.isArray(i))r[e]=i;else if(typeof i==="function")r[e]=[n,i()];else r[e]=[n,i];return r},{}))},bl=(t,n,s,r)=>{if(n!==null){let f=s[r];if(typeof f==="function")f=[,f];let[o=B4,c=m4,h=r]=f;if(typeof o==="function"&&o(n[h])||typeof o!=="function"&&!!o)t[r]=c(n[h]);return}let[e,i]=s[r];if(typeof i==="function"){let f,o=e===void 0&&(f=i())!=null,c=typeof e==="function"&&!!e(void 0)||typeof e!=="function"&&!!e;if(o)t[r]=f;else if(c)t[r]=i()}else{let f=e===void 0&&i!=null,o=typeof e==="function"&&!!e(i)||typeof e!=="function"&&!!e;if(f||o)t[r]=i}},B4=(t)=>t!=null,m4=(t)=>t,F4=(t)=>{if(t!==t)return"NaN";switch(t){case 1/0:return"Infinity";case-1/0:return"-Infinity";default:return t}},P4=(t)=>t.toISOString().replace(".000Z","Z"),cf=(t)=>{if(t==null)return{};if(Array.isArray(t))return t.filter((n)=>n!=null).map(cf);if(typeof t==="object"){let n={};for(let s of Object.keys(t)){if(t[s]==null)continue;n[s]=cf(t[s])}return n}return t};function H4(t,n,s,r){return function(i,f,o,c,h={}){let u=Object.assign({},t,i);return Ve.classBuilder().ep(u).m(function(l,_,w,A){let M=f.call(this,l,_,w,A);return M.unshift(r(w,l.getEndpointParameterInstructions())),M}).s(n,o,h).n(s,o.charAt(0).toUpperCase()+o.slice(1)+"Command").sc(c).build()}}N4.Client=fl;N4.Command=Ve;N4.NoOpLogger=El;N4.SENSITIVE_STRING=g4;N4.ServiceException=Qs;N4.WaiterState=nn;N4._json=cf;N4.checkExceptions=h4;N4.constructStack=Hr;N4.convertMap=O4;N4.createAggregatedClient=E4;N4.createWaiter=d4;N4.decorateServiceException=hl;N4.emitWarningIfUnsupportedVersion=S4;N4.getArrayIfSingleItem=L4;N4.getChecksumConfiguration=_l;N4.getDefaultClientConfiguration=$4;N4.getDefaultExtensionConfiguration=dl;N4.getRetryConfiguration=Al;N4.getValueFromTextNode=gl;N4.invalidFunction=o4;N4.invalidProvider=f4;N4.isSerializableHeaderValue=I4;N4.loadConfigsForDefaultMode=T4;N4.makeBuilder=H4;N4.map=Rl;N4.resolveChecksumRuntimeConfig=wl;N4.resolveDefaultRuntimeConfig=U4;N4.resolveRetryRuntimeConfig=Ml;N4.schemaLogFilter=Ke;N4.serializeDateTime=P4;N4.serializeFloat=F4;N4.take=y4;N4.throwDefaultError=ul;N4.waiterServiceDefaults=ol;N4.withBaseException=R4});var Rt=K((TT)=>{var{homedir:T2}=j("os"),{sep:S2,join:Nr}=j("path"),{createHash:$2}=j("crypto"),{readFile:Gl}=j("fs/promises"),{IniSectionType:je}=es(),{normalizeProvider:pe}=En(),{isValidHostLabel:U2}=tn();class Js extends Error{name="ProviderError";tryNextLink;constructor(t,n=!0){let s,r=!0;if(typeof n==="boolean")s=void 0,r=n;else if(n!=null&&typeof n==="object")s=n.logger,r=n.tryNextLink??!0;super(t);this.tryNextLink=r,Object.setPrototypeOf(this,Js.prototype),s?.debug?.(`@smithy/property-provider ${r?"->":"(!)"} ${t}`)}static from(t,n=!0){return Object.assign(new this(t.message,n),t)}}class Dr extends Js{name="CredentialsProviderError";constructor(t,n=!0){super(t,n);Object.setPrototypeOf(this,Dr.prototype)}}class wf extends Js{name="TokenProviderError";constructor(t,n=!0){super(t,n);Object.setPrototypeOf(this,wf.prototype)}}var Bl=(...t)=>async()=>{if(t.length===0)throw new Js("No providers in chain");let n;for(let s of t)try{return await s()}catch(r){if(n=r,r?.tryNextLink)continue;throw r}throw n},ml=(t)=>()=>Promise.resolve(t),Af=(t,n,s)=>{let r,e,i,f=!1,o=async()=>{if(!e)e=t();try{r=await e,i=!0,f=!1}finally{e=void 0}return r};if(n===void 0)return async(c)=>{if(!i||c?.forceRefresh)r=await o();return r};return async(c)=>{if(!i||c?.forceRefresh)r=await o();if(f)return r;if(s&&!s(r))return f=!0,r;if(n(r))return await o(),r;return r}},Rn=(t,n,s)=>{if(!(n in t))return;if(t[n]==="true")return!0;if(t[n]==="false")return!1;throw Error(`Cannot load ${s} "${n}". Expected "true" or "false", got ${t[n]}.`)},L2=(t,n,s)=>{if(!(n in t))return;let r=parseInt(t[n],10);if(Number.isNaN(r))throw TypeError(`Cannot load ${s} '${n}'. Expected number, got '${t[n]}'.`);return r},zt;(function(t){t.ENV="env",t.CONFIG="shared config entry"})(zt||(zt={}));var hf={},I2=()=>{if(process&&process.geteuid)return`${process.geteuid()}`;return"DEFAULT"},Wr=()=>{let{HOME:t,USERPROFILE:n,HOMEPATH:s,HOMEDRIVE:r=`C:${S2}`}=process.env;if(t)return t;if(n)return n;if(s)return`${r}${s}`;let e=I2();if(!hf[e])hf[e]=T2();return hf[e]},Fl="AWS_PROFILE",Pl="default",Hl=(t)=>t.profile||process.env[Fl]||Pl,Nl=(t)=>{let s=$2("sha1").update(t).digest("hex");return Nr(Wr(),".aws","sso","cache",`${s}.json`)},ve={},O2=async(t)=>{if(ve[t])return ve[t];let n=Nl(t),s=await Gl(n,"utf8");return JSON.parse(s)},os=".",y2=(t)=>Object.entries(t).filter(([n])=>{let s=n.indexOf(os);if(s===-1)return!1;return Object.values(je).includes(n.substring(0,s))}).reduce((n,[s,r])=>{let e=s.indexOf(os),i=s.substring(0,e)===je.PROFILE?s.substring(e+1):s;return n[i]=r,n},{...t.default&&{default:t.default}}),G2="AWS_CONFIG_FILE",Dl=()=>process.env[G2]||Nr(Wr(),".aws","config"),B2="AWS_SHARED_CREDENTIALS_FILE",m2=()=>process.env[B2]||Nr(Wr(),".aws","credentials"),F2=/^([\w-]+)\s(["'])?([\w-@+.%:/]+)\2$/,P2=["__proto__","profile __proto__"],lf=(t)=>{let n={},s,r;for(let e of t.split(/\r?\n/)){let i=e.split(/(^|\s)[;#]/)[0].trim();if(i[0]==="["&&i[i.length-1]==="]"){s=void 0,r=void 0;let o=i.substring(1,i.length-1),c=F2.exec(o);if(c){let[,h,,u]=c;if(Object.values(je).includes(h))s=[h,u].join(os)}else s=o;if(P2.includes(o))throw Error(`Found invalid profile name "${o}"`)}else if(s){let o=i.indexOf("=");if(![0,-1].includes(o)){let[c,h]=[i.substring(0,o).trim(),i.substring(o+1).trim()];if(h==="")r=c;else{if(r&&e.trimStart()===e)r=void 0;n[s]=n[s]||{};let u=r?[r,c].join(os):c;n[s][u]=h}}}}return n},uf={},Ze={},ti=(t,n)=>{if(Ze[t]!==void 0)return Ze[t];if(!uf[t]||n?.ignoreCache)uf[t]=Gl(t,"utf8");return uf[t]},Tl=()=>({}),Mf=async(t={})=>{let{filepath:n=m2(),configFilepath:s=Dl()}=t,r=Wr(),e="~/",i=n;if(n.startsWith("~/"))i=Nr(r,n.slice(2));let f=s;if(s.startsWith("~/"))f=Nr(r,s.slice(2));let o=await Promise.all([ti(f,{ignoreCache:t.ignoreCache}).then(lf).then(y2).catch(Tl),ti(i,{ignoreCache:t.ignoreCache}).then(lf).catch(Tl)]);return{configFile:o[0],credentialsFile:o[1]}},H2=(t)=>Object.entries(t).filter(([n])=>n.startsWith(je.SSO_SESSION+os)).reduce((n,[s,r])=>({...n,[s.substring(s.indexOf(os)+1)]:r}),{}),N2=()=>({}),D2=async(t={})=>ti(t.configFilepath??Dl()).then(lf).then(H2).catch(N2),W2=(...t)=>{let n={};for(let s of t)for(let[r,e]of Object.entries(s))if(n[r]!==void 0)Object.assign(n[r],e);else n[r]=e;return n},Y2=async(t)=>{let n=await Mf(t);return W2(n.configFile,n.credentialsFile)},x2={getFileRecord(){return Ze},interceptFile(t,n){Ze[t]=Promise.resolve(n)},getTokenRecord(){return ve},interceptToken(t,n){ve[t]=n}};function Wl(t){try{let n=new Set(Array.from(t.match(/([A-Z_]){3,}/g)??[]));return n.delete("CONFIG"),n.delete("CONFIG_PREFIX_SEPARATOR"),n.delete("ENV"),[...n].join(", ")}catch(n){return t}}var Q2=(t,n)=>async()=>{try{let s=t(process.env,n);if(s===void 0)throw Error();return s}catch(s){throw new Dr(s.message||`Not found in ENV: ${Wl(t.toString())}`,{logger:n?.logger})}},J2=(t,{preferredFile:n="config",...s}={})=>async()=>{let r=Hl(s),{configFile:e,credentialsFile:i}=await Mf(s),f=i[r]||{},o=e[r]||{},c=n==="config"?{...f,...o}:{...o,...f};try{let u=t(c,n==="config"?e:i);if(u===void 0)throw Error();return u}catch(h){throw new Dr(h.message||`Not found in config files w/ profile [${r}]: ${Wl(t.toString())}`,{logger:s.logger})}},z2=(t)=>typeof t==="function",Yl=(t)=>z2(t)?async()=>await t():ml(t),_f=({environmentVariableSelector:t,configFileSelector:n,default:s},r={})=>{let{signingName:e,logger:i}=r;return Af(Bl(Q2(t,{signingName:e,logger:i}),J2(n,r),Yl(s)))},df="AWS_USE_DUALSTACK_ENDPOINT",gf="use_dualstack_endpoint",k2=!1,X2={environmentVariableSelector:(t)=>Rn(t,df,zt.ENV),configFileSelector:(t)=>Rn(t,gf,zt.CONFIG),default:!1},q2={environmentVariableSelector:(t)=>Rn(t,df,zt.ENV),configFileSelector:(t)=>Rn(t,gf,zt.CONFIG),default:void 0},Ef="AWS_USE_FIPS_ENDPOINT",Rf="use_fips_endpoint",C2=!1,a2={environmentVariableSelector:(t)=>Rn(t,Ef,zt.ENV),configFileSelector:(t)=>Rn(t,Rf,zt.CONFIG),default:!1},K2={environmentVariableSelector:(t)=>Rn(t,Ef,zt.ENV),configFileSelector:(t)=>Rn(t,Rf,zt.CONFIG),default:void 0},V2=(t)=>{let{tls:n,endpoint:s,urlParser:r,useDualstackEndpoint:e}=t;return Object.assign(t,{tls:n??!0,endpoint:pe(typeof s==="string"?r(s):s),isCustomEndpoint:!0,useDualstackEndpoint:pe(e??!1)})},j2=async(t)=>{let{tls:n=!0}=t,s=await t.region();if(!new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/).test(s))throw Error("Invalid region in client config");let e=await t.useDualstackEndpoint(),i=await t.useFipsEndpoint(),{hostname:f}=await t.regionInfoProvider(s,{useDualstackEndpoint:e,useFipsEndpoint:i})??{};if(!f)throw Error("Cannot resolve hostname from client config");return t.urlParser(`${n?"https:":"http:"}//${f}`)},p2=(t)=>{let n=pe(t.useDualstackEndpoint??!1),{endpoint:s,useFipsEndpoint:r,urlParser:e,tls:i}=t;return Object.assign(t,{tls:i??!0,endpoint:s?pe(typeof s==="string"?e(s):s):()=>j2({...t,useDualstackEndpoint:n,useFipsEndpoint:r}),isCustomEndpoint:!!s,useDualstackEndpoint:n})},v2="AWS_EXECUTION_ENV",Sl="AWS_REGION",$l="AWS_DEFAULT_REGION",Z2="AWS_EC2_METADATA_DISABLED",tT=["in-region","cross-region","mobile","standard","legacy"],nT="/latest/meta-data/placement/region",sT="/latest/api/token",rT="x-aws-ec2-metadata-token",eT="x-aws-ec2-metadata-token-ttl-seconds",Ul=1000,iT=60000,xl=0,Ql=async()=>{if(process.env[Z2])return;if(Date.now()<xl)return;try{let t=oT(),n=(await Il({...t,path:sT,method:"PUT",headers:{[eT]:"21600"}})).toString();return(await Il({...t,path:nT,method:"GET",headers:{[rT]:n}})).toString().trim()||Ll()}catch{return Ll()}},Ll=()=>{xl=Date.now()+iT;return},oT=()=>{let t=process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT;if(t){let n=new URL(t);return{hostname:n.hostname.replace(/^\[(.+)]$/,"$1"),port:n.port?Number(n.port):void 0}}if(process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE==="IPv6")return{hostname:"fd00:ec2::254"};return{hostname:"169.254.169.254"}},Il=async(t)=>{let{request:n}=j("http");return new Promise((s,r)=>{let e=n({hostname:t.hostname,port:t.port,path:t.path,method:t.method,headers:t.headers,timeout:Ul,signal:AbortSignal.timeout(Ul)});e.on("error",(i)=>{r(i),e.destroy()}),e.on("timeout",()=>{r(Error("TimeoutError from instance metadata service")),e.destroy()}),e.on("response",(i)=>{let{statusCode:f=400}=i;if(f<200||f>=300){r(Object.assign(Error("Error response received from instance metadata service"),{statusCode:f})),e.destroy();return}let o=[];i.on("data",(c)=>o.push(c)),i.on("end",()=>{s(Buffer.concat(o)),e.destroy()})}),e.end()})},Jl="AWS_REGION",zl="region",kl={environmentVariableSelector:(t)=>t[Jl],configFileSelector:(t)=>t[zl],default:async()=>{let t=await Ql();if(t)return t;throw Error("Region is missing")}},fT={preferredFile:"credentials"},Ol=new Set,cT=(t,n=U2)=>{if(!Ol.has(t)&&!n(t))if(t==="*")console.warn('@smithy/config-resolver WARN - Please use the caller region instead of "*". See "sigv4a" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.');else throw Error(`Region not accepted: region="${t}" is not a valid hostname component.`);else Ol.add(t)},Xl=(t)=>typeof t==="string"&&(t.startsWith("fips-")||t.endsWith("-fips")),hT=(t)=>Xl(t)?["fips-aws-global","aws-fips"].includes(t)?"us-east-1":t.replace(/fips-(dkr-|prod-)?|-fips/,""):t,uT=(t)=>{let{region:n,useFipsEndpoint:s}=t;if(!n)throw Error("Region is missing");return Object.assign(t,{region:async()=>{let r=typeof n==="function"?await n():n,e=hT(r);return cT(e),e},useFipsEndpoint:async()=>{let r=typeof n==="string"?n:await n();if(Xl(r))return!0;return typeof s!=="function"?Promise.resolve(!!s):s()}})},yl=(t=[],{useFipsEndpoint:n,useDualstackEndpoint:s})=>t.find(({tags:r})=>n===r.includes("fips")&&s===r.includes("dualstack"))?.hostname,lT=(t,{regionHostname:n,partitionHostname:s})=>n?n:s?s.replace("{region}",t):void 0,_T=(t,{partitionHash:n})=>Object.keys(n||{}).find((s)=>n[s].regions.includes(t))??"aws",wT=(t,{signingRegion:n,regionRegex:s,useFipsEndpoint:r})=>{if(n)return n;else if(r){let e=s.replace("\\\\","\\").replace(/^\^/g,"\\.").replace(/\$$/g,"\\."),i=t.match(e);if(i)return i[0].slice(1,-1)}},AT=(t,{useFipsEndpoint:n=!1,useDualstackEndpoint:s=!1,signingService:r,regionHash:e,partitionHash:i})=>{let f=_T(t,{partitionHash:i}),o=t in e?t:i[f]?.endpoint??t,c={useFipsEndpoint:n,useDualstackEndpoint:s},h=yl(e[o]?.variants,c),u=yl(i[f]?.variants,c),l=lT(o,{regionHostname:h,partitionHostname:u});if(l===void 0)throw Error(`Endpoint resolution failed for: ${{resolvedRegion:o,useFipsEndpoint:n,useDualstackEndpoint:s}}`);let _=wT(l,{signingRegion:e[o]?.signingRegion,regionRegex:i[f].regionRegex,useFipsEndpoint:n});return{partition:f,signingService:r,hostname:l,..._&&{signingRegion:_},...e[o]?.signingService&&{signingService:e[o].signingService}}},MT="AWS_DEFAULTS_MODE",dT="defaults_mode",gT={environmentVariableSelector:(t)=>{return t[MT]},configFileSelector:(t)=>{return t[dT]},default:"legacy"},ET=({region:t=_f(kl),defaultsMode:n=_f(gT)}={})=>Af(async()=>{let s=typeof n==="function"?await n():n;switch(s?.toLowerCase()){case"auto":return RT(t);case"in-region":case"cross-region":case"mobile":case"standard":case"legacy":return Promise.resolve(s?.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw Error(`Invalid parameter for "defaultsMode", expect ${tT.join(", ")}, got ${s}`)}}),RT=async(t)=>{if(t){let n=typeof t==="function"?await t():t,s=await bT();if(!s)return"standard";if(n===s)return"in-region";else return"cross-region"}return"standard"},bT=async()=>{if(process.env[v2]&&(process.env[Sl]||process.env[$l]))return process.env[Sl]??process.env[$l];return Ql()};TT.CONFIG_PREFIX_SEPARATOR=os;TT.CONFIG_USE_DUALSTACK_ENDPOINT=gf;TT.CONFIG_USE_FIPS_ENDPOINT=Rf;TT.CredentialsProviderError=Dr;TT.DEFAULT_PROFILE=Pl;TT.DEFAULT_USE_DUALSTACK_ENDPOINT=k2;TT.DEFAULT_USE_FIPS_ENDPOINT=C2;TT.ENV_PROFILE=Fl;TT.ENV_USE_DUALSTACK_ENDPOINT=df;TT.ENV_USE_FIPS_ENDPOINT=Ef;TT.NODE_REGION_CONFIG_FILE_OPTIONS=fT;TT.NODE_REGION_CONFIG_OPTIONS=kl;TT.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS=X2;TT.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS=a2;TT.ProviderError=Js;TT.REGION_ENV_NAME=Jl;TT.REGION_INI_NAME=zl;TT.SelectorType=zt;TT.TokenProviderError=wf;TT.booleanSelector=Rn;TT.chain=Bl;TT.externalDataInterceptor=x2;TT.fromStatic=Yl;TT.fromValue=ml;TT.getHomeDir=Wr;TT.getProfileName=Hl;TT.getRegionInfo=AT;TT.getSSOTokenFilepath=Nl;TT.getSSOTokenFromFile=O2;TT.loadConfig=_f;TT.loadSharedConfigFiles=Mf;TT.loadSsoSessionData=D2;TT.memoize=Af;TT.nodeDualstackConfigSelectors=q2;TT.nodeFipsConfigSelectors=K2;TT.numberSelector=L2;TT.parseKnownFiles=Y2;TT.readFile=ti;TT.resolveCustomEndpointsConfig=V2;TT.resolveDefaultsModeConfig=ET;TT.resolveEndpointsConfig=p2;TT.resolveRegionConfig=uT});var fs=K((K6)=>{var{CONFIG_PREFIX_SEPARATOR:ql,loadConfig:u6}=Rt(),{toEndpointV1:ni,getSmithyContext:l6,normalizeProvider:bf,isValidHostLabel:Kl}=tn();K6.isValidHostLabel=Kl;K6.middlewareEndpointToEndpointV1=ni;K6.toEndpointV1=ni;var{EndpointURLScheme:$f}=es(),Cl="AWS_ENDPOINT_URL",al="endpoint_url",_6=(t)=>({environmentVariableSelector:(n)=>{let s=t.split(" ").map((i)=>i.toUpperCase()),r=n[[Cl,...s].join("_")];if(r)return r;let e=n[Cl];if(e)return e;return},configFileSelector:(n,s)=>{if(s&&n.services){let e=s[["services",n.services].join(ql)];if(e){let i=t.split(" ").map((o)=>o.toLowerCase()),f=e[[i.join("_"),al].join(ql)];if(f)return f}}let r=n[al];if(r)return r;return},default:void 0}),si=async(t)=>u6(_6(t??""))(),w6=async(t)=>{let n=t?.Bucket||"";if(typeof t.Bucket==="string")t.Bucket=n.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"));if(E6(n)){if(t.ForcePathStyle===!0)throw Error("Path-style addressing cannot be used with ARN buckets")}else if(!g6(n)||n.indexOf(".")!==-1&&!String(t.Endpoint).startsWith("http:")||n.toLowerCase()!==n||n.length<3)t.ForcePathStyle=!0;if(t.DisableMultiRegionAccessPoints)t.disableMultiRegionAccessPoints=!0,t.DisableMRAP=!0;return t},A6=/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/,M6=/(\d+\.){3}\d+/,d6=/\.\./,g6=(t)=>A6.test(t)&&!M6.test(t)&&!d6.test(t),E6=(t)=>{let[n,s,r,,,e]=t.split(":"),i=n==="arn"&&t.split(":").length>=6,f=Boolean(i&&s&&r&&e);if(i&&!f)throw Error(`Invalid ARN: ${t} was an invalid ARN.`);return f},R6=(t,n,s,r=!1)=>{let e=async()=>{let i;if(r)i=s.clientContextParams?.[t]??s[t]??s[n];else i=s[t]??s[n];if(typeof i==="function")return i();return i};if(t==="credentialScope"||n==="CredentialScope")return async()=>{let i=typeof s.credentials==="function"?await s.credentials():s.credentials;return i?.credentialScope??i?.CredentialScope};if(t==="accountId"||n==="AccountId")return async()=>{let i=typeof s.credentials==="function"?await s.credentials():s.credentials;return i?.accountId??i?.AccountId};if(t==="endpoint"||n==="endpoint")return async()=>{if(s.isCustomEndpoint===!1)return;let i=await e();if(i&&typeof i==="object"){if("url"in i)return i.url.href;if("hostname"in i){let{protocol:f,hostname:o,port:c,path:h}=i;return`${f}//${o}${c?":"+c:""}${h}`}}return i};return e};function Vl(t){return async(n,s,r,e)=>{if(!r.isCustomEndpoint){let o;if(r.serviceConfiguredEndpoint)o=await r.serviceConfiguredEndpoint();else o=await t(r.serviceId);if(o)r.endpoint=()=>Promise.resolve(ni(o)),r.isCustomEndpoint=!0}let i=await jl(n,s,r);if(typeof r.endpointProvider!=="function")throw Error("config.endpointProvider is not set.");let f=r.endpointProvider(i,e);if(r.isCustomEndpoint&&r.endpoint){let o=await r.endpoint();if(o?.headers){f.headers??={};for(let[c,h]of Object.entries(o.headers))f.headers[c]=Array.isArray(h)?h:[h]}}return f}}var jl=async(t,n,s)=>{let r={},e=n?.getEndpointParameterInstructions?.()||{};for(let[i,f]of Object.entries(e))switch(f.type){case"staticContextParams":r[i]=f.value;break;case"contextParams":r[i]=t[f.name];break;case"clientContextParams":case"builtInParams":r[i]=await R6(f.name,i,s,f.type!=="builtInParams")();break;case"operationContextParams":r[i]=f.get(t);break;default:throw Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(f))}if(Object.keys(e).length===0)Object.assign(r,s);if(String(s.serviceId).toLowerCase()==="s3")await w6(r);return r};function b6(t,n,s){if(!t.__smithy_context)t.__smithy_context={features:{}};else if(!t.__smithy_context.features)t.__smithy_context.features={};t.__smithy_context.features[n]=s}function pl(t){let n=Vl(t);return({config:s,instructions:r})=>{return(e,i)=>async(f)=>{if(s.isCustomEndpoint)b6(i,"ENDPOINT_OVERRIDE","N");let o=await n(f.input,{getEndpointParameterInstructions(){return r}},{...s},i);i.endpointV2=o,i.authSchemes=o.properties?.authSchemes;let c=i.authSchemes?.[0];if(c){i.signing_region=c.signingRegion,i.signing_service=c.signingName;let u=l6(i)?.selectedHttpAuthScheme?.httpAuthOption;if(u)u.signingProperties=Object.assign(u.signingProperties||{},{signing_region:c.signingRegion,signingRegion:c.signingRegion,signing_service:c.signingName,signingName:c.signingName,signingRegionSet:c.signingRegionSet},c.properties)}return e({...f})}}}var T6={name:"serializerMiddleware"},vl={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:T6.name};function S6(t){let n=pl(t);return(s,r)=>({applyToStack:(e)=>{e.addRelativeTo(n({config:s,instructions:r}),vl)}})}function $6(t){return(n)=>{let s=n.tls??!0,{endpoint:r,useDualstackEndpoint:e,useFipsEndpoint:i}=n,f=r!=null?async()=>ni(await bf(r)()):void 0,c=Object.assign(n,{endpoint:f,tls:s,isCustomEndpoint:!!r,useDualstackEndpoint:bf(e??!1),useFipsEndpoint:bf(i??!1)}),h=void 0;return c.serviceConfiguredEndpoint=async()=>{if(n.serviceId&&!h)h=t(n.serviceId);return h},c}}class Uf{nodes;root;conditions;results;constructor(t,n,s,r){this.nodes=t,this.root=n,this.conditions=s,this.results=r}static from(t,n,s,r){return new Uf(t,n,s,r)}}class Zl{capacity;data=new Map;parameters=[];constructor({size:t,params:n}){if(this.capacity=t??50,n)this.parameters=n}get(t,n){let s=this.hash(t);if(s===!1)return n();if(!this.data.has(s)){if(this.data.size>this.capacity+10){let r=this.data.keys(),e=0;while(!0){let{value:i,done:f}=r.next();if(this.data.delete(i),f||++e>10)break}}this.data.set(s,n())}return this.data.get(s)}size(){return this.data.size}hash(t){let n="",{parameters:s}=this;if(s.length===0)return!1;for(let r of s){let e=String(t[r]??"");if(e.includes("|;"))return!1;n+=e+"|;"}return n}}class ut extends Error{constructor(t){super(t);this.name="EndpointError"}}var Yr="endpoints";function Nn(t){if(typeof t!=="object"||t==null)return t;if("ref"in t)return`$${Nn(t.ref)}`;if("fn"in t)return`${t.fn}(${(t.argv||[]).map(Nn).join(", ")})`;return JSON.stringify(t,null,2)}var t0={},U6=(t,n)=>t===n;function L6(...t){for(let n of t)if(n!=null)return n;return}var I6=(t)=>{let n=t.split("."),s=[];for(let r of n){let e=r.indexOf("[");if(e!==-1){if(r.indexOf("]")!==r.length-1)throw new ut(`Path: '${t}' does not end with ']'`);let i=r.slice(e+1,-1);if(Number.isNaN(parseInt(i)))throw new ut(`Invalid array index: '${i}' in path: '${t}'`);if(e!==0)s.push(r.slice(0,e));s.push(i)}else s.push(r)}return s},n0=(t,n)=>I6(n).reduce((s,r)=>{if(typeof s!=="object")throw new ut(`Index '${r}' in '${n}' not found in '${JSON.stringify(t)}'`);else if(Array.isArray(s)){let e=parseInt(r);return s[e<0?s.length+e:e]}return s[r]},t),O6=(t)=>t!=null;function y6(t,n,s){return t?n:s}var G6=(t)=>!t,B6=new RegExp("^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$"),s0=(t)=>B6.test(t)||t.startsWith("[")&&t.endsWith("]"),Tf={[$f.HTTP]:80,[$f.HTTPS]:443},m6=(t)=>{let n=(()=>{try{if(t instanceof URL)return t;if(typeof t==="object"&&"hostname"in t){let{hostname:_,port:w,protocol:A="",path:M="",query:d={}}=t,E=new URL(`${A}//${_}${w?`:${w}`:""}${M}`);return E.search=Object.entries(d).map(([b,L])=>`${b}=${L}`).join("&"),E}return new URL(t)}catch(_){return null}})();if(!n)return console.error(`Unable to parse ${JSON.stringify(t)} as a whatwg URL.`),null;let s=n.href,{host:r,hostname:e,pathname:i,protocol:f,search:o}=n;if(o)return null;let c=f.slice(0,-1);if(!Object.values($f).includes(c))return null;let h=s0(e),u=s.includes(`${r}:${Tf[c]}`)||typeof t==="string"&&t.includes(`${r}:${Tf[c]}`),l=`${r}${u?`:${Tf[c]}`:""}`;return{scheme:c,authority:l,path:i,normalizedPath:i.endsWith("/")?i:`${i}/`,isIp:h}};function F6(t,n,s){if(s===1)return[t];if(t==="")return[""];let r=t.split(n);if(s===0)return r;return r.slice(0,s-1).concat(r.slice(1).join(n))}var P6=(t,n)=>t===n,H6=(t,n,s,r)=>{if(t==null||n>=s||t.length<s||/[^\u0000-\u007f]/.test(t))return null;if(!r)return t.substring(n,s);return t.substring(t.length-s,t.length-n)},N6=(t)=>encodeURIComponent(t).replace(/[!*'()]/g,(n)=>`%${n.charCodeAt(0).toString(16).toUpperCase()}`),D6={booleanEquals:U6,coalesce:L6,getAttr:n0,isSet:O6,isValidHostLabel:Kl,ite:y6,not:G6,parseURL:m6,split:F6,stringEquals:P6,substring:H6,uriEncode:N6},r0=(t,n)=>{let s=[],{referenceRecord:r,endpointParams:e}=n,i=0;while(i<t.length){let f=t.indexOf("{",i);if(f===-1){s.push(t.slice(i));break}s.push(t.slice(i,f));let o=t.indexOf("}",f);if(o===-1){s.push(t.slice(f));break}if(t[f+1]==="{"&&t[o+1]==="}")s.push(t.slice(f+1,o)),i=o+2;let c=t.substring(f+1,o);if(c.includes("#")){let[h,u]=c.split("#");s.push(n0(r[h]??e[h],u))}else s.push(r[c]??e[c]);i=o+1}return s.join("")},W6=({ref:t},n)=>{return n.referenceRecord[t]??n.endpointParams[t]},xr=(t,n,s)=>{if(typeof t==="string")return r0(t,s);else if(t.fn)return i0.callFunction(t,s);else if(t.ref)return W6(t,s);throw new ut(`'${n}': ${String(t)} is not a string, function or reference.`)},e0=({fn:t,argv:n},s)=>{let r=Array(n.length);for(let f=0;f<r.length;++f){let o=n[f];if(typeof o==="boolean"||typeof o==="number")r[f]=o;else r[f]=i0.evaluateExpression(o,"arg",s)}let e=t.indexOf(".");if(e!==-1){let o=t0[t.slice(0,e)]?.[t.slice(e+1)];if(typeof o==="function")return o(...r)}let i=D6[t];if(typeof i==="function")return i(...r);throw Error(`function ${t} not loaded in endpointFunctions.`)},i0={evaluateExpression:xr,callFunction:e0},o0=(t,n)=>{let{assign:s}=t;if(s&&s in n.referenceRecord)throw new ut(`'${s}' is already defined in Reference Record.`);let r=e0(t,n);n.logger?.debug?.(`${Yr} evaluateCondition: ${Nn(t)} = ${Nn(r)}`);let e=r===""?!0:!!r;if(s!=null)return{result:e,toAssign:{name:s,value:r}};return{result:e}},f0=(t,n)=>Object.entries(t??{}).reduce((s,[r,e])=>{return s[r]=e.map((i)=>{let f=xr(i,"Header value entry",n);if(typeof f!=="string")throw new ut(`Header '${r}' value '${f}' is not a string`);return f}),s},{}),Lf=(t,n)=>Object.entries(t).reduce((s,[r,e])=>{return s[r]=h0.getEndpointProperty(e,n),s},{}),c0=(t,n)=>{if(Array.isArray(t))return t.map((s)=>c0(s,n));switch(typeof t){case"string":return r0(t,n);case"object":if(t===null)throw new ut(`Unexpected endpoint property: ${t}`);return h0.getEndpointProperties(t,n);case"boolean":return t;default:throw new ut(`Unexpected endpoint property type: ${typeof t}`)}},h0={getEndpointProperty:c0,getEndpointProperties:Lf},u0=(t,n)=>{let s=xr(t,"Endpoint URL",n);if(typeof s==="string")try{return new URL(s)}catch(r){throw console.error(`Failed to construct URL with ${s}`,r),r}throw new ut(`Endpoint URL must be a string, got ${typeof s}`)},Sf=1e8,Y6=(t,n)=>{let{nodes:s,root:r,results:e,conditions:i}=t,f=r,o={},c={referenceRecord:o,endpointParams:n.endpointParams,logger:n.logger};while(f!==1&&f!==-1&&f<Sf){let h=3*(Math.abs(f)-1),[u,l,_]=[s[h],s[h+1],s[h+2]],[w,A,M]=i[u],d=o0({fn:w,assign:M,argv:A},c);if(d.toAssign){let{name:E,value:b}=d.toAssign;o[E]=b}f=f>=0===d.result?l:_}if(f>=Sf){let h=e[f-Sf];if(h[0]===-1){let[,w]=h;throw new ut(xr(w,"Error",c))}let[u,l,_]=h;return{url:u0(u,c),properties:Lf(l,c),headers:f0(_??{},c)}}throw new ut("No matching endpoint.")},If=(t=[],n)=>{let s={},r={...n,referenceRecord:{...n.referenceRecord}},e=!1;for(let i of t){let{result:f,toAssign:o}=o0(i,r);if(!f)return{result:f};if(o)e=!0,s[o.name]=o.value,r.referenceRecord[o.name]=o.value,n.logger?.debug?.(`${Yr} assign: ${o.name} := ${Nn(o.value)}`)}if(e)return{result:!0,referenceRecord:s};return{result:!0}},x6=(t,n)=>{let{conditions:s,endpoint:r}=t,{result:e,referenceRecord:i}=If(s,n);if(!e)return;let f=i?{...n,referenceRecord:{...n.referenceRecord,...i}}:n,{url:o,properties:c,headers:h}=r;n.logger?.debug?.(`${Yr} Resolving endpoint from template: ${Nn(r)}`);let u={url:u0(o,f)};if(h!=null)u.headers=f0(h,f);if(c!=null)u.properties=Lf(c,f);return u},Q6=(t,n)=>{let{conditions:s,error:r}=t,{result:e,referenceRecord:i}=If(s,n);if(!e)return;let f=i?{...n,referenceRecord:{...n.referenceRecord,...i}}:n;throw new ut(xr(r,"Error",f))},l0=(t,n)=>{for(let s of t)if(s.type==="endpoint"){let r=x6(s,n);if(r)return r}else if(s.type==="error")Q6(s,n);else if(s.type==="tree"){let r=_0.evaluateTreeRule(s,n);if(r)return r}else throw new ut(`Unknown endpoint rule: ${s}`);throw new ut("Rules evaluation failed")},J6=(t,n)=>{let{conditions:s,rules:r}=t,{result:e,referenceRecord:i}=If(s,n);if(!e)return;let f=i?{...n,referenceRecord:{...n.referenceRecord,...i}}:n;return _0.evaluateRules(r,f)},_0={evaluateRules:l0,evaluateTreeRule:J6},z6=(t,n)=>{let{endpointParams:s,logger:r}=n,{parameters:e,rules:i}=t;n.logger?.debug?.(`${Yr} Initial EndpointParams: ${Nn(s)}`);for(let o in e){let c=e[o],h=s[o];if(h==null&&c.default!=null){s[o]=c.default;continue}if(c.required&&h==null)throw new ut(`Missing required parameter: '${o}'`)}let f=l0(i,{endpointParams:s,logger:r,referenceRecord:{}});return n.logger?.debug?.(`${Yr} Resolved endpoint: ${Nn(f)}`),f},k6=(t)=>{let{endpoint:n}=t;if(n===void 0)t.endpoint=async()=>{throw Error("@smithy/middleware-endpoint: (default endpointRuleSet) endpoint is not set - you must configure an endpoint.")};return t},X6=Vl(si),q6=$6(si),C6=pl(si),a6=S6(si);K6.BinaryDecisionDiagram=Uf;K6.EndpointCache=Zl;K6.EndpointError=ut;K6.customEndpointFunctions=t0;K6.decideEndpoint=Y6;K6.endpointMiddleware=C6;K6.endpointMiddlewareOptions=vl;K6.getEndpointFromInstructions=X6;K6.getEndpointPlugin=a6;K6.isIpAddress=s0;K6.resolveEndpoint=z6;K6.resolveEndpointConfig=q6;K6.resolveEndpointRequiredConfig=k6;K6.resolveParams=jl});var bt=K((Q5)=>{var{createHmac:_S,createHash:wS,getRandomValues:AS}=j("crypto"),{ReadStream:MS,lstatSync:dS,fstatSync:gS}=j("fs"),{HttpResponse:ES}=tn(),{toEndpointV1:RS}=fs(),{Readable:zs,Writable:b0,PassThrough:w0}=j("stream"),T0=(t)=>typeof ArrayBuffer==="function"&&t instanceof ArrayBuffer||Object.prototype.toString.call(t)==="[object ArrayBuffer]",Xs=(t,n=0,s=t.byteLength-n)=>{if(!T0(t))throw TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof t} (${t})`);return Buffer.from(t,n,s)},oi=(t,n)=>{if(typeof t!=="string")throw TypeError(`The "input" argument must be of type string. Received type ${typeof t} (${t})`);return n?Buffer.from(t,n):Buffer.from(t)},bS=/^[A-Za-z0-9+/]*={0,2}$/,S0=(t)=>{if(t.length*3%4!==0)throw TypeError("Incorrect padding on base64 string.");if(!bS.exec(t))throw TypeError("Invalid base64 string.");let n=oi(t,"base64");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)},fi=(t)=>{let n=oi(t,"utf8");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength/Uint8Array.BYTES_PER_ELEMENT)},Hf=(t)=>{let n;if(typeof t==="string")n=fi(t);else n=t;if(typeof n!=="object"||typeof n.byteOffset!=="number"||typeof n.byteLength!=="number")throw Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");return Xs(n.buffer,n.byteOffset,n.byteLength).toString("base64")};function TS(t,n,s,r){return class e extends Uint8Array{static fromString(i,f="utf-8"){if(typeof i==="string"){if(f==="base64")return e.mutate(r(i));return e.mutate(n(i))}throw Error(`Unsupported conversion from ${typeof i} to Uint8ArrayBlobAdapter.`)}static mutate(i){return Object.setPrototypeOf(i,e.prototype),i}transformToString(i="utf-8"){if(i==="base64")return s(this);return t(this)}}}var $0=(t)=>{if(typeof t==="string")return t;if(typeof t!=="object"||typeof t.byteOffset!=="number"||typeof t.byteLength!=="number")throw Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return Xs(t.buffer,t.byteOffset,t.byteLength).toString("utf8")},At=Array.from({length:256},(t,n)=>n.toString(16).padStart(2,"0"));function SS(t){if(typeof crypto<"u"&&typeof crypto.randomUUID==="function")return()=>crypto.randomUUID();return()=>{let n=new Uint8Array(16);return t(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128,At[n[0]]+At[n[1]]+At[n[2]]+At[n[3]]+"-"+At[n[4]]+At[n[5]]+"-"+At[n[6]]+At[n[7]]+"-"+At[n[8]]+At[n[9]]+"-"+At[n[10]]+At[n[11]]+At[n[12]]+At[n[13]]+At[n[14]]+At[n[15]]}}var $S=(t,n,s=(r)=>r)=>t,US=(t)=>{switch(t){case"true":return!0;case"false":return!1;default:throw Error(`Unable to parse boolean value "${t}"`)}},LS=(t)=>{if(t===null||t===void 0)return;if(typeof t==="number"){if(t===0||t===1)kr.warn(ei(`Expected boolean, got ${typeof t}: ${t}`));if(t===0)return!1;if(t===1)return!0}if(typeof t==="string"){let n=t.toLowerCase();if(n==="false"||n==="true")kr.warn(ei(`Expected boolean, got ${typeof t}: ${t}`));if(n==="false")return!1;if(n==="true")return!0}if(typeof t==="boolean")return t;throw TypeError(`Expected boolean, got ${typeof t}: ${t}`)},Jr=(t)=>{if(t===null||t===void 0)return;if(typeof t==="string"){let n=parseFloat(t);if(!Number.isNaN(n)){if(String(n)!==String(t))kr.warn(ei(`Expected number but observed string: ${t}`));return n}}if(typeof t==="number")return t;throw TypeError(`Expected number, got ${typeof t}: ${t}`)},IS=Math.ceil(340282346638528860000000000000000000000),ri=(t)=>{let n=Jr(t);if(n!==void 0&&!Number.isNaN(n)&&n!==1/0&&n!==-1/0){if(Math.abs(n)>IS)throw TypeError(`Expected 32-bit float, got ${t}`)}return n},zr=(t)=>{if(t===null||t===void 0)return;if(Number.isInteger(t)&&!Number.isNaN(t))return t;throw TypeError(`Expected integer, got ${typeof t}: ${t}`)},OS=zr,Bf=(t)=>Nf(t,32),mf=(t)=>Nf(t,16),Ff=(t)=>Nf(t,8),Nf=(t,n)=>{let s=zr(t);if(s!==void 0&&yS(s,n)!==s)throw TypeError(`Expected ${n}-bit integer, got ${t}`);return s},yS=(t,n)=>{switch(n){case 32:return Int32Array.of(t)[0];case 16:return Int16Array.of(t)[0];case 8:return Int8Array.of(t)[0]}},GS=(t,n)=>{if(t===null||t===void 0){if(n)throw TypeError(`Expected a non-null value for ${n}`);throw TypeError("Expected a non-null value")}return t},U0=(t)=>{if(t===null||t===void 0)return;if(typeof t==="object"&&!Array.isArray(t))return t;let n=Array.isArray(t)?"array":typeof t;throw TypeError(`Expected object, got ${n}: ${t}`)},BS=(t)=>{if(t===null||t===void 0)return;if(typeof t==="string")return t;if(["boolean","number","bigint"].includes(typeof t))return kr.warn(ei(`Expected string, got ${typeof t}: ${t}`)),String(t);throw TypeError(`Expected string, got ${typeof t}: ${t}`)},mS=(t)=>{if(t===null||t===void 0)return;let n=U0(t),s=[];for(let r in n)if(n[r]!=null)s.push(r);if(s.length===0)throw TypeError("Unions must have exactly one non-null member. None were found.");if(s.length>1)throw TypeError(`Unions must have exactly one non-null member. Keys ${s} were not null.`);return n},Df=(t)=>{if(typeof t=="string")return Jr(as(t));return Jr(t)},FS=Df,L0=(t)=>{if(typeof t=="string")return ri(as(t));return ri(t)},PS=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,as=(t)=>{let n=t.match(PS);if(n===null||n[0].length!==t.length)throw TypeError("Expected real number, got implicit NaN");return parseFloat(t)},Wf=(t)=>{if(typeof t=="string")return I0(t);return Jr(t)},HS=Wf,NS=Wf,DS=(t)=>{if(typeof t=="string")return I0(t);return ri(t)},I0=(t)=>{switch(t){case"NaN":return NaN;case"Infinity":return 1/0;case"-Infinity":return-1/0;default:throw Error(`Unable to parse float value: ${t}`)}},O0=(t)=>{if(typeof t==="string")return zr(as(t));return zr(t)},WS=O0,YS=(t)=>{if(typeof t==="string")return Bf(as(t));return Bf(t)},qs=(t)=>{if(typeof t==="string")return mf(as(t));return mf(t)},y0=(t)=>{if(typeof t==="string")return Ff(as(t));return Ff(t)},ei=(t)=>{return String(TypeError(t).stack||t).split(`
5
+ `+e),t.push(i+"m+"+Hi.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=WR()+n+" "+t[0]}function WR(){if(k0.inspectOpts.hideDate)return"";return new Date().toISOString()+" "}function DR(...t){return process.stderr.write(Fi.formatWithOptions(k0.inspectOpts,...t)+`
6
+ `)}function YR(t){if(t)process.env.DEBUG=t;else delete process.env.DEBUG}function mR(){return process.env.DEBUG}function QR(t){t.inspectOpts={};let n=Object.keys(k0.inspectOpts);for(let s=0;s<n.length;s++)t.inspectOpts[n[s]]=k0.inspectOpts[n[s]]}Hi.exports=Co()(k0);var{formatters:J0}=Hi.exports;J0.o=function(t){return this.inspectOpts.colors=this.useColors,Fi.inspect(t,this.inspectOpts).split(`
7
+ `).map((n)=>n.trim()).join(" ")};J0.O=function(t){return this.inspectOpts.colors=this.useColors,Fi.inspect(t,this.inspectOpts)}});var Vo=Z((Pm,Ko)=>{if(typeof process>"u"||process.type==="renderer"||!1||process.__nwjs)Ko.exports=Q0();else Ko.exports=z0()});var is=Z((lb)=>{var ef;(function(t){t.HEADER="header",t.QUERY="query"})(ef||(ef={}));var of;(function(t){t.HEADER="header",t.QUERY="query"})(of||(of={}));var ff;(function(t){t.HTTP="http",t.HTTPS="https"})(ff||(ff={}));var Br;(function(t){t.MD5="md5",t.CRC32="crc32",t.CRC32C="crc32c",t.SHA1="sha1",t.SHA256="sha256"})(Br||(Br={}));var fb=(t)=>{let n=[];if(t.sha256!==void 0)n.push({algorithmId:()=>Br.SHA256,checksumConstructor:()=>t.sha256});if(t.md5!=null)n.push({algorithmId:()=>Br.MD5,checksumConstructor:()=>t.md5});return{addChecksumAlgorithm(s){n.push(s)},checksumAlgorithms(){return n}}},cb=(t)=>{let n={};return t.checksumAlgorithms().forEach((s)=>{n[s.algorithmId()]=s.checksumConstructor()}),n},hb=(t)=>{return fb(t)},ub=(t)=>{return cb(t)},cf;(function(t){t[t.HEADER=0]="HEADER",t[t.TRAILER=1]="TRAILER"})(cf||(cf={}));var _b="__smithy_context",hf;(function(t){t.PROFILE="profile",t.SSO_SESSION="sso-session",t.SERVICES="services"})(hf||(hf={}));var uf;(function(t){t.HTTP_0_9="http/0.9",t.HTTP_1_0="http/1.0",t.TDS_8_0="tds/8.0"})(uf||(uf={}));lb.AlgorithmId=Br;lb.EndpointURLScheme=ff;lb.FieldPosition=cf;lb.HttpApiKeyAuthLocation=of;lb.HttpAuthLocation=ef;lb.IniSectionType=hf;lb.RequestHandlerProtocol=uf;lb.SMITHY_CONTEXT_KEY=_b;lb.getDefaultClientConfiguration=hb;lb.resolveDefaultRuntimeConfig=ub});var nn=Z((Gb)=>{var{SMITHY_CONTEXT_KEY:fu}=is(),$b=(t)=>t[fu]||(t[fu]={});class Qi{method;protocol;hostname;port;path;query;headers;username;password;fragment;body;constructor(t){this.method=t.method||"GET",this.hostname=t.hostname||"localhost",this.port=t.port,this.query=t.query||{},this.headers=t.headers||{},this.body=t.body,this.protocol=t.protocol?t.protocol.slice(-1)!==":"?`${t.protocol}:`:t.protocol:"https:",this.path=t.path?t.path.charAt(0)!=="/"?`/${t.path}`:t.path:"/",this.username=t.username,this.password=t.password,this.fragment=t.fragment}static clone(t){let n=new Qi({...t,headers:{...t.headers}});if(n.query)n.query=Ub(n.query);return n}static isInstance(t){if(!t)return!1;let n=t;return"method"in n&&"protocol"in n&&"hostname"in n&&"path"in n&&typeof n.query==="object"&&typeof n.headers==="object"}clone(){return Qi.clone(this)}}function Ub(t){return Object.keys(t).reduce((n,s)=>{let r=t[s];return{...n,[s]:Array.isArray(r)?[...r]:r}},{})}class cu{statusCode;reason;headers;body;constructor(t){this.statusCode=t.statusCode,this.reason=t.reason,this.headers=t.headers||{},this.body=t.body}static isInstance(t){if(!t)return!1;let n=t;return typeof n.statusCode==="number"&&typeof n.headers==="object"}}var Lb=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),hu=(t,n=!1)=>{if(!n)return Lb.test(t);let s=t.split(".");for(let r of s)if(!hu(r))return!1;return!0};function Ib(t){return/^[a-z0-9][a-z0-9.-]*[a-z0-9]$/.test(t)}var Ob=(t)=>{if(typeof t==="function")return t;let n=Promise.resolve(t);return()=>n};function uu(t){let n={};if(t=t.replace(/^\?/,""),t)for(let s of t.split("&")){let[r,i=null]=s.split("=");if(r=decodeURIComponent(r),i)i=decodeURIComponent(i);if(!(r in n))n[r]=i;else if(Array.isArray(n[r]))n[r].push(i);else n[r]=[n[r],i]}return n}var Ji=(t)=>{if(typeof t==="string")return Ji(new URL(t));let{hostname:n,pathname:s,port:r,protocol:i,search:e}=t,f;if(e)f=uu(e);return{hostname:n,port:r?parseInt(r):void 0,protocol:i,path:s,query:f}},yb=(t)=>{if(typeof t==="object"){if("url"in t){let n=Ji(t.url);if(t.headers){n.headers={};for(let s in t.headers)n.headers[s.toLowerCase()]=t.headers[s].join(", ")}return n}return t}return Ji(t)};Gb.HttpRequest=Qi;Gb.HttpResponse=cu;Gb.getSmithyContext=$b;Gb.isValidHostLabel=hu;Gb.isValidHostname=Ib;Gb.normalizeProvider=Ob;Gb.parseQueryString=uu;Gb.parseUrl=Ji;Gb.toEndpointV1=yb});var Nn=Z((Zb)=>{var{getSmithyContext:_u,HttpResponse:Qb,toEndpointV1:Jb}=nn(),ki=(t)=>{if(typeof t==="function")return t();return t},wf=(t,n,s,r,i)=>({name:n,namespace:t,traits:s,input:r,output:i}),kb=(t)=>(n,s)=>async(r)=>{let{response:i}=await n(r),{operationSchema:e}=_u(s),[,f,o,c,h,u]=e??[];try{let _=await t.protocol.deserializeResponse(wf(f,o,c,h,u),{...t,...s},i);return{response:i,output:_}}catch(_){if(Object.defineProperty(_,"$response",{value:i,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in _)){try{_.message+=`
8
+ Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`}catch(w){if(!s.logger||s.logger?.constructor?.name==="NoOpLogger")console.warn("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.");else s.logger?.warn?.("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.")}if(typeof _.$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
9
  `).slice(0,5).filter((n)=>!n.includes("stackTraceWarning")).join(`
10
- `)},kr={warn:console.warn},xS=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],Yf=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function QS(t){let n=t.getUTCFullYear(),s=t.getUTCMonth(),r=t.getUTCDay(),e=t.getUTCDate(),i=t.getUTCHours(),f=t.getUTCMinutes(),o=t.getUTCSeconds(),c=e<10?`0${e}`:`${e}`,h=i<10?`0${i}`:`${i}`,u=f<10?`0${f}`:`${f}`,l=o<10?`0${o}`:`${o}`;return`${xS[r]}, ${c} ${Yf[s]} ${n} ${h}:${u}:${l} GMT`}var JS=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),zS=(t)=>{if(t===null||t===void 0)return;if(typeof t!=="string")throw TypeError("RFC-3339 date-times must be expressed as strings");let n=JS.exec(t);if(!n)throw TypeError("Invalid RFC-3339 date-time value");let[s,r,e,i,f,o,c,h]=n,u=qs(Cs(r)),l=sn(e,"month",1,12),_=sn(i,"day",1,31);return Qr(u,l,_,{hours:f,minutes:o,seconds:c,fractionalMilliseconds:h})},kS=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}:\d{2})|[zZ])$/),XS=(t)=>{if(t===null||t===void 0)return;if(typeof t!=="string")throw TypeError("RFC-3339 date-times must be expressed as strings");let n=kS.exec(t);if(!n)throw TypeError("Invalid RFC-3339 date-time value");let[s,r,e,i,f,o,c,h,u]=n,l=qs(Cs(r)),_=sn(e,"month",1,12),w=sn(i,"day",1,31),A=Qr(l,_,w,{hours:f,minutes:o,seconds:c,fractionalMilliseconds:h});if(u.toUpperCase()!="Z")A.setTime(A.getTime()-r5(u));return A},qS=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),CS=new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),aS=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/),KS=(t)=>{if(t===null||t===void 0)return;if(typeof t!=="string")throw TypeError("RFC-7231 date-times must be expressed as strings");let n=qS.exec(t);if(n){let[s,r,e,i,f,o,c,h]=n;return Qr(qs(Cs(i)),Of(e),sn(r,"day",1,31),{hours:f,minutes:o,seconds:c,fractionalMilliseconds:h})}if(n=CS.exec(t),n){let[s,r,e,i,f,o,c,h]=n;return vS(Qr(jS(i),Of(e),sn(r,"day",1,31),{hours:f,minutes:o,seconds:c,fractionalMilliseconds:h}))}if(n=aS.exec(t),n){let[s,r,e,i,f,o,c,h]=n;return Qr(qs(Cs(h)),Of(r),sn(e.trimLeft(),"day",1,31),{hours:i,minutes:f,seconds:o,fractionalMilliseconds:c})}throw TypeError("Invalid RFC-7231 date-time value")},VS=(t)=>{if(t===null||t===void 0)return;let n;if(typeof t==="number")n=t;else if(typeof t==="string")n=Df(t);else if(typeof t==="object"&&t.tag===1)n=t.value;else throw TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");if(Number.isNaN(n)||n===1/0||n===-1/0)throw TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(n*1000))},Qr=(t,n,s,r)=>{let e=n-1;return t5(t,e,s),new Date(Date.UTC(t,e,s,sn(r.hours,"hour",0,23),sn(r.minutes,"minute",0,59),sn(r.seconds,"seconds",0,60),s5(r.fractionalMilliseconds)))},jS=(t)=>{let n=new Date().getUTCFullYear(),s=Math.floor(n/100)*100+qs(Cs(t));if(s<n)return s+100;return s},pS=1576800000000,vS=(t)=>{if(t.getTime()-new Date().getTime()>pS)return new Date(Date.UTC(t.getUTCFullYear()-100,t.getUTCMonth(),t.getUTCDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds(),t.getUTCMilliseconds()));return t},Of=(t)=>{let n=Yf.indexOf(t);if(n<0)throw TypeError(`Invalid month: ${t}`);return n+1},ZS=[31,28,31,30,31,30,31,31,30,31,30,31],t5=(t,n,s)=>{let r=ZS[n];if(n===1&&n5(t))r=29;if(s>r)throw TypeError(`Invalid day for ${Yf[n]} in ${t}: ${s}`)},n5=(t)=>{return t%4===0&&(t%100!==0||t%400===0)},sn=(t,n,s,r)=>{let e=y0(Cs(t));if(e<s||e>r)throw TypeError(`${n} must be between ${s} and ${r}, inclusive`);return e},s5=(t)=>{if(t===null||t===void 0)return 0;return L0("0."+t)*1000},r5=(t)=>{let n=t[0],s=1;if(n=="+")s=1;else if(n=="-")s=-1;else throw TypeError(`Offset direction, ${n}, must be "+" or "-"`);let r=Number(t.substring(1,3)),e=Number(t.substring(4,6));return s*(r*60+e)*60*1000},Cs=(t)=>{let n=0;while(n<t.length-1&&t.charAt(n)==="0")n++;if(n===0)return t;return t.slice(n)},cs=function(n){return Object.assign(new String(n),{deserializeJSON(){return JSON.parse(String(n))},toString(){return String(n)},toJSON(){return String(n)}})};cs.from=(t)=>{if(t&&typeof t==="object"&&(t instanceof cs||("deserializeJSON"in t)))return t;else if(typeof t==="string"||Object.getPrototypeOf(t)===String.prototype)return cs(String(t));return cs(JSON.stringify(t))};cs.fromObject=cs.from;function e5(t){if(t.includes(",")||t.includes('"'))t=`"${t.replace(/"/g,"\\\"")}"`;return t}var xf="(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?",Qf="(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)",Jf="(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?",G0="(\\d?\\d)",B0="(\\d{4})",i5=new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/),o5=new RegExp(`^${xf}, ${G0} ${Qf} ${B0} ${Jf} GMT$`),f5=new RegExp(`^${xf}, ${G0}-${Qf}-(\\d\\d) ${Jf} GMT$`),c5=new RegExp(`^${xf} ${Qf} ( [1-9]|\\d\\d) ${Jf} ${B0}$`),h5=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],u5=(t)=>{if(t==null)return;let n=NaN;if(typeof t==="number")n=t;else if(typeof t==="string"){if(!/^-?\d*\.?\d+$/.test(t))throw TypeError("parseEpochTimestamp - numeric string invalid.");n=Number.parseFloat(t)}else if(typeof t==="object"&&t.tag===1)n=t.value;if(isNaN(n)||Math.abs(n)===1/0)throw TypeError("Epoch timestamps must be valid finite numbers.");return new Date(Math.round(n*1000))},l5=(t)=>{if(t==null)return;if(typeof t!=="string")throw TypeError("RFC3339 timestamps must be strings");let n=i5.exec(t);if(!n)throw TypeError(`Invalid RFC3339 timestamp format ${t}`);let[,s,r,e,i,f,o,,c,h]=n;bn(r,1,12),bn(e,1,31),bn(i,0,23),bn(f,0,59),bn(o,0,60);let u=new Date(Date.UTC(Number(s),Number(r)-1,Number(e),Number(i),Number(f),Number(o),Number(c)?Math.round(parseFloat(`0.${c}`)*1000):0));if(u.setUTCFullYear(Number(s)),h.toUpperCase()!="Z"){let[,l,_,w]=/([+-])(\d\d):(\d\d)/.exec(h)||[void 0,"+",0,0],A=l==="-"?1:-1;u.setTime(u.getTime()+A*(Number(_)*60*60*1000+Number(w)*60*1000))}return u},_5=(t)=>{if(t==null)return;if(typeof t!=="string")throw TypeError("RFC7231 timestamps must be strings.");let n,s,r,e,i,f,o,c;if(c=o5.exec(t))[,n,s,r,e,i,f,o]=c;else if(c=f5.exec(t))[,n,s,r,e,i,f,o]=c,r=(Number(r)+1900).toString();else if(c=c5.exec(t))[,s,n,e,i,f,o,r]=c;if(r&&f){let h=Date.UTC(Number(r),h5.indexOf(s),Number(n),Number(e),Number(i),Number(f),o?Math.round(parseFloat(`0.${o}`)*1000):0);bn(n,1,31),bn(e,0,23),bn(i,0,59),bn(f,0,60);let u=new Date(h);return u.setUTCFullYear(Number(r)),u}throw TypeError(`Invalid RFC7231 date-time value ${t}.`)};function bn(t,n,s){let r=Number(t);if(r<n||r>s)throw Error(`Value ${r} out of range [${n}, ${s}]`)}function w5(t,n,s){if(s<=0||!Number.isInteger(s))throw Error("Invalid number of delimiters ("+s+") for splitEvery.");let r=t.split(n);if(s===1)return r;let e=[],i="";for(let f=0;f<r.length;f++){if(i==="")i=r[f];else i+=n+r[f];if((f+1)%s===0)e.push(i),i=""}if(i!=="")e.push(i);return e}var A5=(t)=>{let n=t.length,s=[],r=!1,e=void 0,i=0;for(let f=0;f<n;++f){let o=t[f];switch(o){case'"':if(e!=="\\")r=!r;break;case",":if(!r)s.push(t.slice(i,f)),i=f+1;break}e=o}return s.push(t.slice(i)),s.map((f)=>{f=f.trim();let o=f.length;if(o<2)return f;if(f[0]==='"'&&f[o-1]==='"')f=f.slice(1,o-1);return f.replace(/\\"/g,'"')})},A0=/^-?\d*(\.\d+)?$/;class ci{string;type;constructor(t,n){if(this.string=t,this.type=n,!A0.test(t))throw Error('@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".')}toString(){return this.string}static[Symbol.hasInstance](t){if(!t||typeof t!=="object")return!1;let n=t;return ci.prototype.isPrototypeOf(t)||n.type==="bigDecimal"&&A0.test(n.string)}}function M5(t){return new ci(String(t),"bigDecimal")}var m0={},Pf={};for(let t=0;t<256;t++){let n=t.toString(16).toLowerCase();if(n.length===1)n=`0${n}`;m0[t]=n,Pf[n]=t}function d5(t){if(t.length%2!==0)throw Error("Hex encoded strings must have an even number length");let n=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2){let r=t.slice(s,s+2).toLowerCase();if(r in Pf)n[s/2]=Pf[r];else throw Error(`Cannot decode unrecognized sequence ${r} as hexadecimal`)}return n}function F0(t){let n="";for(let s=0;s<t.byteLength;s++)n+=m0[t[s]];return n}var g5=(t)=>{if(!t)return 0;if(typeof t==="string")return Buffer.byteLength(t);else if(typeof t.byteLength==="number")return t.byteLength;else if(typeof t.size==="number")return t.size;else if(typeof t.start==="number"&&typeof t.end==="number")return t.end+1-t.start;else if(t instanceof MS){if(t.path!=null)return dS(t.path).size;else if(typeof t.fd==="number")return gS(t.fd).size}throw Error(`Body Length computation failed for ${t}`)},P0=(t)=>{if(t instanceof Uint8Array)return t;if(typeof t==="string")return fi(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength/Uint8Array.BYTES_PER_ELEMENT);return new Uint8Array(t)};function hi(t,n){if(n===void 0){n=0;for(let e of t)n+=e.byteLength}let s=new Uint8Array(n),r=0;for(let e of t)s.set(e,r),r+=e.byteLength;return s}var H0=(t,n)=>(s,r)=>async(e)=>{let{response:i}=await s(e);try{let f=await n(i,t);return{response:i,output:f}}catch(f){if(Object.defineProperty(f,"$response",{value:i,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in f)){try{f.message+=`
11
- Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`}catch(c){if(!r.logger||r.logger?.constructor?.name==="NoOpLogger")console.warn("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.");else r.logger?.warn?.("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.")}if(typeof f.$responseBodyText<"u"){if(f.$response)f.$response.body=f.$responseBodyText}try{if(ES.isInstance(i)){let{headers:c={}}=i,h=Object.entries(c);f.$metadata={httpStatusCode:i.statusCode,requestId:yf(/^x-[\w-]+-request-?id$/,h),extendedRequestId:yf(/^x-[\w-]+-id-2$/,h),cfId:yf(/^x-[\w-]+-cf-id$/,h)}}}catch(c){}}throw f}},yf=(t,n)=>{return(n.find(([s])=>{return s.match(t)})||[void 0,void 0])[1]},N0=(t,n)=>(s,r)=>async(e)=>{let i=t,f=r.endpointV2?async()=>RS(r.endpointV2):i.endpoint;if(!f)throw Error("No valid endpoint provider available.");let o=await n(e.input,{...t,endpoint:f});return s({...e,request:o})},D0={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},W0={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function E5(t,n,s){return{applyToStack:(r)=>{r.add(H0(t,s),D0),r.add(N0(t,n),W0)}}}class Y0{algorithmIdentifier;secret;hash;constructor(t,n){this.algorithmIdentifier=t,this.secret=n,this.reset()}update(t,n){this.hash.update(P0(M0(t,n)))}digest(){return Promise.resolve(this.hash.digest())}reset(){this.hash=this.secret?_S(this.algorithmIdentifier,M0(this.secret)):wS(this.algorithmIdentifier)}}function M0(t,n){if(Buffer.isBuffer(t))return t;if(typeof t==="string")return oi(t,n);if(ArrayBuffer.isView(t))return Xs(t.buffer,t.byteOffset,t.byteLength);return Xs(t)}var x0=class extends zs{expectedChecksum;checksumSourceLocation;checksum;source;base64Encoder;constructor({expectedChecksum:n,checksum:s,source:r,checksumSourceLocation:e,base64Encoder:i}){super();if(typeof r.pipe!=="function")throw Error(`@smithy/util-stream: unsupported source type ${r?.constructor?.name??r} in ChecksumStream.`);this.source=r,this.base64Encoder=i??Hf,this.expectedChecksum=n,this.checksum=s,this.checksumSourceLocation=e,this.source.on("data",this.onSourceData),this.source.on("end",this.onSourceEnd),this.source.on("error",this.onSourceError),this.source.on("close",this.onSourceClose),this.source.pause()}onSourceData=(n)=>{if(this.destroyed)return;try{this.checksum.update(n)}catch(s){this.destroy(s);return}if(!this.push(n))this.source.pause()};onSourceEnd=async()=>{if(this.destroyed)return;try{let n=await this.checksum.digest(),s=this.base64Encoder(n);if(this.expectedChecksum!==s){this.destroy(Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${s}" in response header "${this.checksumSourceLocation}".`));return}}catch(n){this.destroy(n);return}this.push(null)};onSourceError=(n)=>{this.destroy(n)};onSourceClose=()=>{if(!this.destroyed&&!this.source.readableEnded)this.destroy(Error("Connection lost or stream closed before all data was received."))};_read(n){this.source.resume()}_destroy(n,s){this.source?.removeListener("data",this.onSourceData),this.source?.removeListener("end",this.onSourceEnd),this.source?.removeListener("error",this.onSourceError),this.source?.removeListener("close",this.onSourceClose),this.source?.destroy(),s(n)}},rn=(t)=>typeof ReadableStream==="function"&&(t?.constructor?.name===ReadableStream.name||t instanceof ReadableStream),ui=(t)=>{return typeof Blob==="function"&&(t?.constructor?.name===Blob.name||t instanceof Blob)},R5=(t)=>new TextEncoder().encode(t),Q0="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";Object.entries(Q0).reduce((t,[n,s])=>{return t[s]=Number(n),t},{});var b5=Q0.split(""),Gf=6,d0=8,T5=63;function J0(t){let n;if(typeof t==="string")n=R5(t);else n=t;let s=typeof n==="object"&&typeof n.length==="number",r=typeof n==="object"&&typeof n.byteOffset==="number"&&typeof n.byteLength==="number";if(!s&&!r)throw Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");let e="";for(let i=0;i<n.length;i+=3){let f=0,o=0;for(let h=i,u=Math.min(i+3,n.length);h<u;h++)f|=n[h]<<(u-h-1)*d0,o+=d0;let c=Math.ceil(o/Gf);f<<=c*Gf-o;for(let h=1;h<=c;h++){let u=(c-h)*Gf;e+=b5[(f&T5<<u)>>u]}e+="==".slice(0,4-c)}return e}var S5=typeof ReadableStream==="function"?ReadableStream:function(){};class z0 extends S5{}var $5=({expectedChecksum:t,checksum:n,source:s,checksumSourceLocation:r,base64Encoder:e})=>{if(!rn(s))throw Error(`@smithy/util-stream: unsupported source type ${s?.constructor?.name??s} in ChecksumStream.`);let i=e??J0;if(typeof TransformStream!=="function")throw Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream.");let f=new TransformStream({start(){},async transform(c,h){n.update(c),h.enqueue(c)},async flush(c){let h=await n.digest(),u=i(h);if(t!==u){let l=Error(`Checksum mismatch: expected "${t}" but received "${u}" in response header "${r}".`);c.error(l)}else c.terminate()}});s.pipeThrough(f);let o=f.readable;return Object.setPrototypeOf(o,z0.prototype),o};function U5(t){if(typeof ReadableStream==="function"&&rn(t.source))return $5(t);return new x0(t)}class ii{allocByteArray;byteLength=0;byteArrays=[];constructor(t){this.allocByteArray=t}push(t){this.byteArrays.push(t),this.byteLength+=t.byteLength}flush(){if(this.byteArrays.length===1){let s=this.byteArrays[0];return this.reset(),s}let t=this.allocByteArray(this.byteLength),n=0;for(let s=0;s<this.byteArrays.length;++s){let r=this.byteArrays[s];t.set(r,n),n+=r.byteLength}return this.reset(),t}reset(){this.byteArrays=[],this.byteLength=0}}function L5(t,n,s){let r=t.getReader(),e=!1,i=0,f=["",new ii((h)=>new Uint8Array(h))],o=-1,c=async(h)=>{let{value:u,done:l}=await r.read(),_=u;if(l){if(o!==-1){let w=ks(f,o);if(Dn(w)>0)h.enqueue(w)}h.close()}else{let w=X0(_,!1);if(o!==w){if(o>=0)h.enqueue(ks(f,o));o=w}if(o===-1){h.enqueue(_);return}let A=Dn(_);i+=A;let M=Dn(f[o]);if(A>=n&&M===0)h.enqueue(_);else{let d=k0(f,o,_);if(!e&&i>n*2)e=!0,s?.warn(`@smithy/util-stream - stream chunk size ${A} is below threshold of ${n}, automatically buffering.`);if(d>=n)h.enqueue(ks(f,o));else await c(h)}}};return new ReadableStream({pull:c})}function k0(t,n,s){switch(n){case 0:return t[0]+=s,Dn(t[0]);case 1:case 2:return t[n].push(s),Dn(t[n])}}function ks(t,n){switch(n){case 0:let s=t[0];return t[0]="",s;case 1:case 2:return t[n].flush()}throw Error(`@smithy/util-stream - invalid index ${n} given to flush()`)}function Dn(t){return t?.byteLength??t?.length??0}function X0(t,n=!0){if(n&&typeof Buffer<"u"&&t instanceof Buffer)return 2;if(t instanceof Uint8Array)return 1;if(typeof t==="string")return 0;return-1}function I5(t,n,s){if(rn(t))return L5(t,n,s);let r=new zs({read(){}}),e=!1,i=0,f=["",new ii((c)=>new Uint8Array(c)),new ii((c)=>Buffer.from(new Uint8Array(c)))],o=-1;return t.on("data",(c)=>{let h=X0(c,!0);if(o!==h){if(o>=0)r.push(ks(f,o));o=h}if(o===-1){r.push(c);return}let u=Dn(c);i+=u;let l=Dn(f[o]);if(u>=n&&l===0)r.push(c);else{let _=k0(f,o,c);if(!e&&i>n*2)e=!0,s?.warn(`@smithy/util-stream - stream chunk size ${u} is below threshold of ${n}, automatically buffering.`);if(_>=n)r.push(ks(f,o))}}),t.on("end",()=>{if(o!==-1){let c=ks(f,o);if(Dn(c)>0)r.push(c)}r.push(null)}),r}var O5=(t,n)=>{let{base64Encoder:s,bodyLengthChecker:r,checksumAlgorithmFn:e,checksumLocationName:i,streamHasher:f}=n,o=s!==void 0&&r!==void 0&&e!==void 0&&i!==void 0&&f!==void 0,c=o?f(e,t):void 0,h=t.getReader();return new ReadableStream({async pull(u){let{value:l,done:_}=await h.read();if(_){if(u.enqueue(`0\r
12
- `),o){let w=s(await c);u.enqueue(`${i}:${w}\r
10
+ `)},qr={warn:console.warn},h8=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],qf=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function u8(t){let n=t.getUTCFullYear(),s=t.getUTCMonth(),r=t.getUTCDay(),i=t.getUTCDate(),e=t.getUTCHours(),f=t.getUTCMinutes(),o=t.getUTCSeconds(),c=i<10?`0${i}`:`${i}`,h=e<10?`0${e}`:`${e}`,u=f<10?`0${f}`:`${f}`,_=o<10?`0${o}`:`${o}`;return`${h8[r]}, ${c} ${qf[s]} ${n} ${h}:${u}:${_} GMT`}var _8=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),l8=(t)=>{if(t===null||t===void 0)return;if(typeof t!=="string")throw TypeError("RFC-3339 date-times must be expressed as strings");let n=_8.exec(t);if(!n)throw TypeError("Invalid RFC-3339 date-time value");let[s,r,i,e,f,o,c,h]=n,u=qs(Cs(r)),_=rn(i,"month",1,12),l=rn(e,"day",1,31);return Xr(u,_,l,{hours:f,minutes:o,seconds:c,fractionalMilliseconds:h})},w8=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}:\d{2})|[zZ])$/),A8=(t)=>{if(t===null||t===void 0)return;if(typeof t!=="string")throw TypeError("RFC-3339 date-times must be expressed as strings");let n=w8.exec(t);if(!n)throw TypeError("Invalid RFC-3339 date-time value");let[s,r,i,e,f,o,c,h,u]=n,_=qs(Cs(r)),l=rn(i,"month",1,12),w=rn(e,"day",1,31),A=Xr(_,l,w,{hours:f,minutes:o,seconds:c,fractionalMilliseconds:h});if(u.toUpperCase()!="Z")A.setTime(A.getTime()-O8(u));return A},M8=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$/),g8=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$/),E8=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})$/),d8=(t)=>{if(t===null||t===void 0)return;if(typeof t!=="string")throw TypeError("RFC-7231 date-times must be expressed as strings");let n=M8.exec(t);if(n){let[s,r,i,e,f,o,c,h]=n;return Xr(qs(Cs(e)),Nf(i),rn(r,"day",1,31),{hours:f,minutes:o,seconds:c,fractionalMilliseconds:h})}if(n=g8.exec(t),n){let[s,r,i,e,f,o,c,h]=n;return S8(Xr(b8(e),Nf(i),rn(r,"day",1,31),{hours:f,minutes:o,seconds:c,fractionalMilliseconds:h}))}if(n=E8.exec(t),n){let[s,r,i,e,f,o,c,h]=n;return Xr(qs(Cs(h)),Nf(r),rn(i.trimLeft(),"day",1,31),{hours:e,minutes:f,seconds:o,fractionalMilliseconds:c})}throw TypeError("Invalid RFC-7231 date-time value")},R8=(t)=>{if(t===null||t===void 0)return;let n;if(typeof t==="number")n=t;else if(typeof t==="string")n=zf(t);else if(typeof t==="object"&&t.tag===1)n=t.value;else throw TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");if(Number.isNaN(n)||n===1/0||n===-1/0)throw TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(n*1000))},Xr=(t,n,s,r)=>{let i=n-1;return U8(t,i,s),new Date(Date.UTC(t,i,s,rn(r.hours,"hour",0,23),rn(r.minutes,"minute",0,59),rn(r.seconds,"seconds",0,60),I8(r.fractionalMilliseconds)))},b8=(t)=>{let n=new Date().getUTCFullYear(),s=Math.floor(n/100)*100+qs(Cs(t));if(s<n)return s+100;return s},T8=1576800000000,S8=(t)=>{if(t.getTime()-new Date().getTime()>T8)return new Date(Date.UTC(t.getUTCFullYear()-100,t.getUTCMonth(),t.getUTCDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds(),t.getUTCMilliseconds()));return t},Nf=(t)=>{let n=qf.indexOf(t);if(n<0)throw TypeError(`Invalid month: ${t}`);return n+1},$8=[31,28,31,30,31,30,31,31,30,31,30,31],U8=(t,n,s)=>{let r=$8[n];if(n===1&&L8(t))r=29;if(s>r)throw TypeError(`Invalid day for ${qf[n]} in ${t}: ${s}`)},L8=(t)=>{return t%4===0&&(t%100!==0||t%400===0)},rn=(t,n,s,r)=>{let i=k_(Cs(t));if(i<s||i>r)throw TypeError(`${n} must be between ${s} and ${r}, inclusive`);return i},I8=(t)=>{if(t===null||t===void 0)return 0;return m_("0."+t)*1000},O8=(t)=>{let n=t[0],s=1;if(n=="+")s=1;else if(n=="-")s=-1;else throw TypeError(`Offset direction, ${n}, must be "+" or "-"`);let r=Number(t.substring(1,3)),i=Number(t.substring(4,6));return s*(r*60+i)*60*1000},Cs=(t)=>{let n=0;while(n<t.length-1&&t.charAt(n)==="0")n++;if(n===0)return t;return t.slice(n)},cs=function(n){return Object.assign(new String(n),{deserializeJSON(){return JSON.parse(String(n))},toString(){return String(n)},toJSON(){return String(n)}})};cs.from=(t)=>{if(t&&typeof t==="object"&&(t instanceof cs||("deserializeJSON"in t)))return t;else if(typeof t==="string"||Object.getPrototypeOf(t)===String.prototype)return cs(String(t));return cs(JSON.stringify(t))};cs.fromObject=cs.from;function y8(t){if(t.includes(",")||t.includes('"'))t=`"${t.replace(/"/g,"\\\"")}"`;return t}var Cf="(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?",Kf="(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)",Vf="(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?",X_="(\\d?\\d)",z_="(\\d{4})",G8=new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/),B8=new RegExp(`^${Cf}, ${X_} ${Kf} ${z_} ${Vf} GMT$`),F8=new RegExp(`^${Cf}, ${X_}-${Kf}-(\\d\\d) ${Vf} GMT$`),H8=new RegExp(`^${Cf} ${Kf} ( [1-9]|\\d\\d) ${Vf} ${z_}$`),P8=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],N8=(t)=>{if(t==null)return;let n=NaN;if(typeof t==="number")n=t;else if(typeof t==="string"){if(!/^-?\d*\.?\d+$/.test(t))throw TypeError("parseEpochTimestamp - numeric string invalid.");n=Number.parseFloat(t)}else if(typeof t==="object"&&t.tag===1)n=t.value;if(isNaN(n)||Math.abs(n)===1/0)throw TypeError("Epoch timestamps must be valid finite numbers.");return new Date(Math.round(n*1000))},W8=(t)=>{if(t==null)return;if(typeof t!=="string")throw TypeError("RFC3339 timestamps must be strings");let n=G8.exec(t);if(!n)throw TypeError(`Invalid RFC3339 timestamp format ${t}`);let[,s,r,i,e,f,o,,c,h]=n;Tn(r,1,12),Tn(i,1,31),Tn(e,0,23),Tn(f,0,59),Tn(o,0,60);let u=new Date(Date.UTC(Number(s),Number(r)-1,Number(i),Number(e),Number(f),Number(o),Number(c)?Math.round(parseFloat(`0.${c}`)*1000):0));if(u.setUTCFullYear(Number(s)),h.toUpperCase()!="Z"){let[,_,l,w]=/([+-])(\d\d):(\d\d)/.exec(h)||[void 0,"+",0,0],A=_==="-"?1:-1;u.setTime(u.getTime()+A*(Number(l)*60*60*1000+Number(w)*60*1000))}return u},D8=(t)=>{if(t==null)return;if(typeof t!=="string")throw TypeError("RFC7231 timestamps must be strings.");let n,s,r,i,e,f,o,c;if(c=B8.exec(t))[,n,s,r,i,e,f,o]=c;else if(c=F8.exec(t))[,n,s,r,i,e,f,o]=c,r=(Number(r)+1900).toString();else if(c=H8.exec(t))[,s,n,i,e,f,o,r]=c;if(r&&f){let h=Date.UTC(Number(r),P8.indexOf(s),Number(n),Number(i),Number(e),Number(f),o?Math.round(parseFloat(`0.${o}`)*1000):0);Tn(n,1,31),Tn(i,0,23),Tn(e,0,59),Tn(f,0,60);let u=new Date(h);return u.setUTCFullYear(Number(r)),u}throw TypeError(`Invalid RFC7231 date-time value ${t}.`)};function Tn(t,n,s){let r=Number(t);if(r<n||r>s)throw Error(`Value ${r} out of range [${n}, ${s}]`)}function Y8(t,n,s){if(s<=0||!Number.isInteger(s))throw Error("Invalid number of delimiters ("+s+") for splitEvery.");let r=t.split(n);if(s===1)return r;let i=[],e="";for(let f=0;f<r.length;f++){if(e==="")e=r[f];else e+=n+r[f];if((f+1)%s===0)i.push(e),e=""}if(e!=="")i.push(e);return i}var m8=(t)=>{let n=t.length,s=[],r=!1,i=void 0,e=0;for(let f=0;f<n;++f){let o=t[f];switch(o){case'"':if(i!=="\\")r=!r;break;case",":if(!r)s.push(t.slice(e,f)),e=f+1;break}i=o}return s.push(t.slice(e)),s.map((f)=>{f=f.trim();let o=f.length;if(o<2)return f;if(f[0]==='"'&&f[o-1]==='"')f=f.slice(1,o-1);return f.replace(/\\"/g,'"')})},O_=/^-?\d*(\.\d+)?$/;class _e{string;type;constructor(t,n){if(this.string=t,this.type=n,!O_.test(t))throw Error('@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".')}toString(){return this.string}static[Symbol.hasInstance](t){if(!t||typeof t!=="object")return!1;let n=t;return _e.prototype.isPrototypeOf(t)||n.type==="bigDecimal"&&O_.test(n.string)}}function Q8(t){return new _e(String(t),"bigDecimal")}var x_={},Jf={};for(let t=0;t<256;t++){let n=t.toString(16).toLowerCase();if(n.length===1)n=`0${n}`;x_[t]=n,Jf[n]=t}function J8(t){if(t.length%2!==0)throw Error("Hex encoded strings must have an even number length");let n=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2){let r=t.slice(s,s+2).toLowerCase();if(r in Jf)n[s/2]=Jf[r];else throw Error(`Cannot decode unrecognized sequence ${r} as hexadecimal`)}return n}function q_(t){let n="";for(let s=0;s<t.byteLength;s++)n+=x_[t[s]];return n}var k8=(t)=>{if(!t)return 0;if(typeof t==="string")return Buffer.byteLength(t);else if(typeof t.byteLength==="number")return t.byteLength;else if(typeof t.size==="number")return t.size;else if(typeof t.start==="number"&&typeof t.end==="number")return t.end+1-t.start;else if(t instanceof Q5){if(t.path!=null)return J5(t.path).size;else if(typeof t.fd==="number")return k5(t.fd).size}throw Error(`Body Length computation failed for ${t}`)},C_=(t)=>{if(t instanceof Uint8Array)return t;if(typeof t==="string")return ue(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength/Uint8Array.BYTES_PER_ELEMENT);return new Uint8Array(t)};function le(t,n){if(n===void 0){n=0;for(let i of t)n+=i.byteLength}let s=new Uint8Array(n),r=0;for(let i of t)s.set(i,r),r+=i.byteLength;return s}var K_=(t,n)=>(s,r)=>async(i)=>{let{response:e}=await s(i);try{let f=await n(e,t);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+=`
11
+ Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`}catch(c){if(!r.logger||r.logger?.constructor?.name==="NoOpLogger")console.warn("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.");else r.logger?.warn?.("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.")}if(typeof f.$responseBodyText<"u"){if(f.$response)f.$response.body=f.$responseBodyText}try{if(X5.isInstance(e)){let{headers:c={}}=e,h=Object.entries(c);f.$metadata={httpStatusCode:e.statusCode,requestId:Wf(/^x-[\w-]+-request-?id$/,h),extendedRequestId:Wf(/^x-[\w-]+-id-2$/,h),cfId:Wf(/^x-[\w-]+-cf-id$/,h)}}}catch(c){}}throw f}},Wf=(t,n)=>{return(n.find(([s])=>{return s.match(t)})||[void 0,void 0])[1]},V_=(t,n)=>(s,r)=>async(i)=>{let e=t,f=r.endpointV2?async()=>z5(r.endpointV2):e.endpoint;if(!f)throw Error("No valid endpoint provider available.");let o=await n(i.input,{...t,endpoint:f});return s({...i,request:o})},j_={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},a_={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function X8(t,n,s){return{applyToStack:(r)=>{r.add(K_(t,s),j_),r.add(V_(t,n),a_)}}}class p_{algorithmIdentifier;secret;hash;constructor(t,n){this.algorithmIdentifier=t,this.secret=n,this.reset()}update(t,n){this.hash.update(C_(y_(t,n)))}digest(){return Promise.resolve(this.hash.digest())}reset(){this.hash=this.secret?D5(this.algorithmIdentifier,y_(this.secret)):Y5(this.algorithmIdentifier)}}function y_(t,n){if(Buffer.isBuffer(t))return t;if(typeof t==="string")return he(t,n);if(ArrayBuffer.isView(t))return xs(t.buffer,t.byteOffset,t.byteLength);return xs(t)}var Z_=class extends Xs{expectedChecksum;checksumSourceLocation;checksum;source;base64Encoder;constructor({expectedChecksum:n,checksum:s,source:r,checksumSourceLocation:i,base64Encoder:e}){super();if(typeof r.pipe!=="function")throw Error(`@smithy/util-stream: unsupported source type ${r?.constructor?.name??r} in ChecksumStream.`);this.source=r,this.base64Encoder=e??kf,this.expectedChecksum=n,this.checksum=s,this.checksumSourceLocation=i,this.source.on("data",this.onSourceData),this.source.on("end",this.onSourceEnd),this.source.on("error",this.onSourceError),this.source.on("close",this.onSourceClose),this.source.pause()}onSourceData=(n)=>{if(this.destroyed)return;try{this.checksum.update(n)}catch(s){this.destroy(s);return}if(!this.push(n))this.source.pause()};onSourceEnd=async()=>{if(this.destroyed)return;try{let n=await this.checksum.digest(),s=this.base64Encoder(n);if(this.expectedChecksum!==s){this.destroy(Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${s}" in response header "${this.checksumSourceLocation}".`));return}}catch(n){this.destroy(n);return}this.push(null)};onSourceError=(n)=>{this.destroy(n)};onSourceClose=()=>{if(!this.destroyed&&!this.source.readableEnded)this.destroy(Error("Connection lost or stream closed before all data was received."))};_read(n){this.source.resume()}_destroy(n,s){this.source?.removeListener("data",this.onSourceData),this.source?.removeListener("end",this.onSourceEnd),this.source?.removeListener("error",this.onSourceError),this.source?.removeListener("close",this.onSourceClose),this.source?.destroy(),s(n)}},en=(t)=>typeof ReadableStream==="function"&&(t?.constructor?.name===ReadableStream.name||t instanceof ReadableStream),we=(t)=>{return typeof Blob==="function"&&(t?.constructor?.name===Blob.name||t instanceof Blob)},z8=(t)=>new TextEncoder().encode(t),v_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";Object.entries(v_).reduce((t,[n,s])=>{return t[s]=Number(n),t},{});var x8=v_.split(""),Df=6,G_=8,q8=63;function tl(t){let n;if(typeof t==="string")n=z8(t);else n=t;let s=typeof n==="object"&&typeof n.length==="number",r=typeof n==="object"&&typeof n.byteOffset==="number"&&typeof n.byteLength==="number";if(!s&&!r)throw Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");let i="";for(let e=0;e<n.length;e+=3){let f=0,o=0;for(let h=e,u=Math.min(e+3,n.length);h<u;h++)f|=n[h]<<(u-h-1)*G_,o+=G_;let c=Math.ceil(o/Df);f<<=c*Df-o;for(let h=1;h<=c;h++){let u=(c-h)*Df;i+=x8[(f&q8<<u)>>u]}i+="==".slice(0,4-c)}return i}var C8=typeof ReadableStream==="function"?ReadableStream:function(){};class nl extends C8{}var K8=({expectedChecksum:t,checksum:n,source:s,checksumSourceLocation:r,base64Encoder:i})=>{if(!en(s))throw Error(`@smithy/util-stream: unsupported source type ${s?.constructor?.name??s} in ChecksumStream.`);let e=i??tl;if(typeof TransformStream!=="function")throw Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream.");let f=new TransformStream({start(){},async transform(c,h){n.update(c),h.enqueue(c)},async flush(c){let h=await n.digest(),u=e(h);if(t!==u){let _=Error(`Checksum mismatch: expected "${t}" but received "${u}" in response header "${r}".`);c.error(_)}else c.terminate()}});s.pipeThrough(f);let o=f.readable;return Object.setPrototypeOf(o,nl.prototype),o};function V8(t){if(typeof ReadableStream==="function"&&en(t.source))return K8(t);return new Z_(t)}class ce{allocByteArray;byteLength=0;byteArrays=[];constructor(t){this.allocByteArray=t}push(t){this.byteArrays.push(t),this.byteLength+=t.byteLength}flush(){if(this.byteArrays.length===1){let s=this.byteArrays[0];return this.reset(),s}let t=this.allocByteArray(this.byteLength),n=0;for(let s=0;s<this.byteArrays.length;++s){let r=this.byteArrays[s];t.set(r,n),n+=r.byteLength}return this.reset(),t}reset(){this.byteArrays=[],this.byteLength=0}}function j8(t,n,s){let r=t.getReader(),i=!1,e=0,f=["",new ce((h)=>new Uint8Array(h))],o=-1,c=async(h)=>{let{value:u,done:_}=await r.read(),l=u;if(_){if(o!==-1){let w=zs(f,o);if(Yn(w)>0)h.enqueue(w)}h.close()}else{let w=rl(l,!1);if(o!==w){if(o>=0)h.enqueue(zs(f,o));o=w}if(o===-1){h.enqueue(l);return}let A=Yn(l);e+=A;let M=Yn(f[o]);if(A>=n&&M===0)h.enqueue(l);else{let E=sl(f,o,l);if(!i&&e>n*2)i=!0,s?.warn(`@smithy/util-stream - stream chunk size ${A} is below threshold of ${n}, automatically buffering.`);if(E>=n)h.enqueue(zs(f,o));else await c(h)}}};return new ReadableStream({pull:c})}function sl(t,n,s){switch(n){case 0:return t[0]+=s,Yn(t[0]);case 1:case 2:return t[n].push(s),Yn(t[n])}}function zs(t,n){switch(n){case 0:let s=t[0];return t[0]="",s;case 1:case 2:return t[n].flush()}throw Error(`@smithy/util-stream - invalid index ${n} given to flush()`)}function Yn(t){return t?.byteLength??t?.length??0}function rl(t,n=!0){if(n&&typeof Buffer<"u"&&t instanceof Buffer)return 2;if(t instanceof Uint8Array)return 1;if(typeof t==="string")return 0;return-1}function a8(t,n,s){if(en(t))return j8(t,n,s);let r=new Xs({read(){}}),i=!1,e=0,f=["",new ce((c)=>new Uint8Array(c)),new ce((c)=>Buffer.from(new Uint8Array(c)))],o=-1;return t.on("data",(c)=>{let h=rl(c,!0);if(o!==h){if(o>=0)r.push(zs(f,o));o=h}if(o===-1){r.push(c);return}let u=Yn(c);e+=u;let _=Yn(f[o]);if(u>=n&&_===0)r.push(c);else{let l=sl(f,o,c);if(!i&&e>n*2)i=!0,s?.warn(`@smithy/util-stream - stream chunk size ${u} is below threshold of ${n}, automatically buffering.`);if(l>=n)r.push(zs(f,o))}}),t.on("end",()=>{if(o!==-1){let c=zs(f,o);if(Yn(c)>0)r.push(c)}r.push(null)}),r}var p8=(t,n)=>{let{base64Encoder:s,bodyLengthChecker:r,checksumAlgorithmFn:i,checksumLocationName:e,streamHasher:f}=n,o=s!==void 0&&r!==void 0&&i!==void 0&&e!==void 0&&f!==void 0,c=o?f(i,t):void 0,h=t.getReader();return new ReadableStream({async pull(u){let{value:_,done:l}=await h.read();if(l){if(u.enqueue(`0\r
12
+ `),o){let w=s(await c);u.enqueue(`${e}:${w}\r
13
13
  `),u.enqueue(`\r
14
- `)}u.close()}else u.enqueue(`${(r(l)||0).toString(16)}\r
15
- ${l}\r
16
- `)}})};function y5(t,n){let s=t,r=t;if(rn(r))return O5(r,n);let{base64Encoder:e,bodyLengthChecker:i,checksumAlgorithmFn:f,checksumLocationName:o,streamHasher:c}=n,h=e!==void 0&&f!==void 0&&o!==void 0&&c!==void 0,u=h?c(f,s):void 0,l=new zs({read:()=>{}});return s.on("data",(_)=>{let w=i(_)||0;if(w===0)return;l.push(`${w.toString(16)}\r
17
- `),l.push(_),l.push(`\r
18
- `)}),s.on("end",async()=>{if(l.push(`0\r
19
- `),h){let _=e(await u);l.push(`${o}:${_}\r
20
- `),l.push(`\r
21
- `)}l.push(null)}),l}async function G5(t,n){let s=0,r=[],e=t.getReader(),i=!1;while(!i){let{done:c,value:h}=await e.read();if(h)r.push(h),s+=h?.byteLength??0;if(s>=n)break;i=c}e.releaseLock();let f=new Uint8Array(Math.min(n,s)),o=0;for(let c of r){if(c.byteLength>f.byteLength-o){f.set(c.subarray(0,f.byteLength-o),o);break}else f.set(c,o);o+=c.length}return f}var B5=(t,n)=>{if(rn(t))return G5(t,n);return new Promise((s,r)=>{let e=new m5;e.limit=n,t.pipe(e),t.on("error",(i)=>{e.end(),r(i)}),e.on("error",r),e.on("finish",function(){let i=hi(this.buffers);s(i)})})},m5=class extends b0{buffers=[];limit=1/0;bytesBuffered=0;_write(n,s,r){if(this.buffers.push(n),this.bytesBuffered+=n.byteLength??0,this.bytesBuffered>=this.limit){let e=this.bytesBuffered-this.limit,i=this.buffers[this.buffers.length-1];this.buffers[this.buffers.length-1]=i.subarray(0,i.byteLength-e),this.emit("finish")}r()}},F5=(t)=>{if(typeof t==="string")return t;if(typeof t!=="object"||typeof t.byteOffset!=="number"||typeof t.byteLength!=="number")throw Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return new TextDecoder("utf-8").decode(t)},P5=async(t)=>{if(ui(t))return q0(t);return C0(t)};async function q0(t){return t.arrayBuffer().then((n)=>new Uint8Array(n))}async function C0(t){let n=[],s=t.getReader(),r=0;while(!0){let{done:e,value:i}=await s.read();if(i)n.push(i),r+=i.length;if(e)break}return hi(n,r)}var g0="The stream has already been transformed.",H5=(t)=>{if(!E0(t)&&!rn(t)){let e=t?.__proto__?.constructor?.name||t;throw Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${e}`)}let n=!1,s=async()=>{if(n)throw Error(g0);return n=!0,await P5(t)},r=(e)=>{if(typeof e.stream!=="function")throw Error(`Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.
22
- If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body`);return e.stream()};return Object.assign(t,{transformToByteArray:s,transformToString:async(e)=>{let i=await s();if(e==="base64")return J0(i);else if(e==="hex")return F0(i);else if(e===void 0||e==="utf8"||e==="utf-8")return F5(i);else if(typeof TextDecoder==="function")return new TextDecoder(e).decode(i);else throw Error("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(n)throw Error(g0);if(n=!0,E0(t))return r(t);else if(rn(t))return t;else throw Error(`Cannot transform payload to web stream, got ${t}`)}})},E0=(t)=>typeof Blob==="function"&&t instanceof Blob,a0=(t)=>{if(ui(t))return q0(t);if(rn(t))return C0(t);return new Promise((n,s)=>{let r=new K0,e=t;e.pipe(r),e.on("error",(i)=>{r.end(),s(i)}),r.on("error",s),r.on("finish",function(){let i=hi(this.bufferedBytes);n(i)})})};class K0 extends b0{bufferedBytes=[];_write(t,n,s){this.bufferedBytes.push(t),s()}}var R0="The stream has already been transformed.",N5=(t)=>{if(!(t instanceof zs))try{return H5(t)}catch(r){let e=t?.__proto__?.constructor?.name||t;throw Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${e}`)}let n=!1,s=async()=>{if(n)throw Error(R0);return n=!0,await a0(t)};return Object.assign(t,{transformToByteArray:s,transformToString:async(r)=>{let e=await s();if(r===void 0||Buffer.isEncoding(r))return Xs(e.buffer,e.byteOffset,e.byteLength).toString(r);else return new TextDecoder(r).decode(e)},transformToWebStream:()=>{if(n)throw Error(R0);if(t.readableFlowing!==null)throw Error("The stream has been consumed by other callbacks.");if(typeof zs.toWeb!=="function")throw Error("Readable.toWeb() is not supported. Please ensure a polyfill is available.");return n=!0,zs.toWeb(t)}})};async function D5(t){if(typeof t.stream==="function")t=t.stream();return t.tee()}async function W5(t){if(rn(t)||ui(t))return D5(t);let n=new w0,s=new w0;return t.pipe(n),t.pipe(s),[n,s]}class V0 extends TS($0,fi,Hf,S0){}var Y5=AS,j0=SS(Y5),x5=j0;Q5.ChecksumStream=x0;Q5.Hash=Y0;Q5.LazyJsonString=cs;Q5.NumericValue=ci;Q5.Uint8ArrayBlobAdapter=V0;Q5._parseEpochTimestamp=u5;Q5._parseRfc3339DateTimeWithOffset=l5;Q5._parseRfc7231DateTime=_5;Q5.calculateBodyLength=g5;Q5.concatBytes=hi;Q5.copyDocumentWithTransform=$S;Q5.createBufferedReadable=I5;Q5.createChecksumStream=U5;Q5.dateToUtcString=QS;Q5.deserializerMiddleware=H0;Q5.deserializerMiddlewareOption=D0;Q5.expectBoolean=LS;Q5.expectByte=Ff;Q5.expectFloat32=ri;Q5.expectInt=OS;Q5.expectInt32=Bf;Q5.expectLong=zr;Q5.expectNonNull=GS;Q5.expectNumber=Jr;Q5.expectObject=U0;Q5.expectShort=mf;Q5.expectString=BS;Q5.expectUnion=mS;Q5.fromArrayBuffer=Xs;Q5.fromBase64=S0;Q5.fromHex=d5;Q5.fromString=oi;Q5.fromUtf8=fi;Q5.generateIdempotencyToken=x5;Q5.getAwsChunkedEncodingStream=y5;Q5.getSerdePlugin=E5;Q5.handleFloat=HS;Q5.headStream=B5;Q5.isArrayBuffer=T0;Q5.isBlob=ui;Q5.isReadableStream=rn;Q5.limitedParseDouble=Wf;Q5.limitedParseFloat=NS;Q5.limitedParseFloat32=DS;Q5.logger=kr;Q5.nv=M5;Q5.parseBoolean=US;Q5.parseEpochTimestamp=VS;Q5.parseRfc3339DateTime=zS;Q5.parseRfc3339DateTimeWithOffset=XS;Q5.parseRfc7231DateTime=KS;Q5.quoteHeader=e5;Q5.sdkStreamMixin=N5;Q5.serializerMiddleware=N0;Q5.serializerMiddlewareOption=W0;Q5.splitEvery=w5;Q5.splitHeader=A5;Q5.splitStream=W5;Q5.streamCollector=a0;Q5.strictParseByte=y0;Q5.strictParseDouble=Df;Q5.strictParseFloat=FS;Q5.strictParseFloat32=L0;Q5.strictParseInt=WS;Q5.strictParseInt32=YS;Q5.strictParseLong=O0;Q5.strictParseShort=qs;Q5.toBase64=Hf;Q5.toHex=F0;Q5.toUint8Array=P0;Q5.toUtf8=$0;Q5.v4=j0});var af=K((O$)=>{var{createReadStream:i$}=j("fs"),{Writable:o$}=j("stream"),{toUint8Array:Ks,concatBytes:f$}=bt(),{createHash:Xr,createHmac:c$}=j("crypto"),p0=j("zlib");async function s_(t,n,s=1048576){let r=t.size,e=0;while(e<r){let i=t.slice(e,Math.min(r,e+s));n(new Uint8Array(await i.arrayBuffer())),e+=i.size}}var h$=async function(n,s){let r=new n;return await s_(s,(e)=>{r.update(e)}),r.digest()};class Xf extends o${hash;constructor(t,n){super(n);this.hash=t}_write(t,n,s){try{this.hash.update(Ks(t))}catch(r){return s(r)}s()}}var u$=(t,n)=>new Promise((s,r)=>{if(!l$(n)){r(Error("Unable to calculate hash for non-file streams."));return}let e=i$(n.path,{start:n.start,end:n.end}),i=new t,f=new Xf(i);e.pipe(f),e.on("error",(o)=>{f.end(),r(o)}),f.on("error",r),f.on("finish",function(){i.digest().then(s).catch(r)})}),l$=(t)=>typeof t.path==="string",_$=(t,n)=>{if(n.readableFlowing!==null)throw Error("Unable to calculate hash for flowing readable stream");let s=new t,r=new Xf(s);return n.pipe(r),new Promise((e,i)=>{n.on("error",(f)=>{r.end(),i(f)}),r.on("error",i),r.on("finish",()=>{s.digest().then(e).catch(i)})})};class qf{digestLength=16;state=Uint32Array.from(v0);writeBuffer=new DataView(new ArrayBuffer(64));bufferLength=0;bytesHashed=0;update(t){let n=Ks(t),s=0,r=n.byteLength;this.bytesHashed+=r;while(r>0)if(this.writeBuffer.setUint8(this.bufferLength++,n[s++]),--r,this.bufferLength===64)zf(this.state,this.writeBuffer),this.bufferLength=0}async digest(){let t=Uint32Array.from(this.state),n=new DataView(this.writeBuffer.buffer.slice(0)),s=this.bufferLength,r=this.bytesHashed*8;if(n.setUint8(s++,128),this.bufferLength%64>=56){for(let f=s;f<64;++f)n.setUint8(f,0);zf(t,n),s=0}for(let f=s;f<56;++f)n.setUint8(f,0);n.setUint32(56,r>>>0,!0),n.setUint32(60,Math.floor(r/4294967296),!0),zf(t,n);let e=new Uint8Array(16),i=new DataView(e.buffer);for(let f=0;f<4;++f)i.setUint32(f*4,t[f],!0);return e}reset(){this.state.set(v0),this.writeBuffer=new DataView(new ArrayBuffer(64)),this.bufferLength=0,this.bytesHashed=0}}var v0=[1732584193,4023233417,2562383102,271733878],Wn=4294967295,w$=Uint8Array.of(7,12,17,22,5,9,14,20,4,11,16,23,6,10,15,21),A$=Array.from({length:64},(t,n)=>Math.abs(Math.sin(n+1))*4294967296>>>0);function zf(t,n){let s=t[0],r=t[1],e=t[2],i=t[3];for(let f=0;f<64;++f){let o,c;if(f<16)o=r&e|~r&i,c=f;else if(f<32)o=i&r|e&~i,c=(5*f+1)%16;else if(f<48)o=r^e^i,c=(3*f+5)%16;else o=e^(r|~i),c=7*f%16;let h=n.getUint32(c*4,!0),u=i;i=e,e=r;let l=w$[(f>>4)*4+(f&3)],_=(s+o&Wn)+(h+A$[f]&Wn)&Wn;r=r+((_<<l|_>>>32-l)>>>0)&Wn,s=u}t[0]=t[0]+s&Wn,t[1]=t[1]+r&Wn,t[2]=t[2]+e&Wn,t[3]=t[3]+i&Wn}var M$=(()=>{try{return Xr("md5"),!0}catch{return!1}})(),r_=M$?d$():qf;function d$(){return class{digestLength=16;hash=Xr("md5");update(n){this.hash.update(Ks(n))}async digest(){let n=this.hash.copy().digest();return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}reset(){this.hash=Xr("md5")}}}var e_=new Uint32Array(256);for(let t=0;t<256;++t){let n=t;for(let s=0;s<8;++s)n=n&1?3988292384^n>>>1:n>>>1;e_[t]=n>>>0}var kf=4294967295;class Cf{digestLength=4;checksum=kf;update(t){for(let n=0;n<t.length;++n)this.checksum=this.checksum>>>8^e_[(this.checksum^t[n])&255]}digestSync(){return(this.checksum^kf)>>>0}async digest(){let t=this.digestSync(),n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t,!1),n}reset(){this.checksum=kf}}var Z0=typeof p0.crc32==="function"?p0.crc32:void 0,i_=Z0?g$(Z0):Cf;function g$(t){return class{digestLength=4;value=0;update(s){this.value=t(s,this.value)}digestSync(){return this.value>>>0}async digest(){let s=new Uint8Array(4);return new DataView(s.buffer).setUint32(0,this.digestSync(),!1),s}reset(){this.value=0}}}var lt=64,t_=32,E$=9007199254740991;class Tn{digestLength=t_;state=Int32Array.from(n_);w;buffer=new Uint8Array(64);bufferLength=0;bytesHashed=0;finished=!1;inner;outer;constructor(t){if(t){let n=Tn.normalizeKey(t);this.inner=new Tn,this.outer=new Tn;let{inner:s,outer:r}=this,e=new Uint8Array(lt*2);for(let i=0;i<lt;++i)e[i]=54^n[i],e[i+lt]=92^n[i];s.update(e.subarray(0,lt)),r.update(e.subarray(lt))}}update(t){if(this.finished)throw Error("Attempted to update an already finished HMAC.");if(this.inner){this.inner.update(t);return}let n=Ks(t),s=0,{byteLength:r}=n;if(this.bytesHashed+=r,this.bytesHashed*8>E$)throw Error("Cannot hash more than 2^53 - 1 bits");while(r>0)if(this.buffer[this.bufferLength++]=n[s++],r--,this.bufferLength===lt)this.hashBuffer(),this.bufferLength=0}async digest(){let{inner:t,outer:n}=this;if(t&&n){if(this.finished)throw Error("Attempted to digest an already finished HMAC.");this.finished=!0;let s=t.digestSync();return n.update(s),n.digestSync()}return this.digestSync()}reset(){this.state=Int32Array.from(n_),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0}digestSync(){let t=this.state.slice(),n=this.buffer.slice(),s=this.bufferLength,r=this.bytesHashed*8,e=new DataView(n.buffer,n.byteOffset,n.byteLength);if(e.setUint8(s++,128),(s-1)%lt>=lt-8){for(let f=s;f<lt;++f)e.setUint8(f,0);this.hashBufferWith(t,n),s=0}for(let f=s;f<lt-8;++f)e.setUint8(f,0);e.setUint32(lt-8,Math.floor(r/4294967296),!1),e.setUint32(lt-4,r,!1),this.hashBufferWith(t,n);let i=new Uint8Array(t_);for(let f=0;f<8;++f)i[f*4]=t[f]>>>24&255,i[f*4+1]=t[f]>>>16&255,i[f*4+2]=t[f]>>>8&255,i[f*4+3]=t[f]>>>0&255;return i}static normalizeKey(t){let n=Ks(t);if(n.byteLength>lt){let s=new Tn;s.update(n);let r=s.digestSync(),e=new Uint8Array(lt);return e.set(r),e}if(n.byteLength<lt){let s=new Uint8Array(lt);return s.set(n),s}return n}hashBuffer(){this.hashBufferWith(this.state,this.buffer)}hashBufferWith(t,n){let s=this.w??=new Int32Array(64),r=t[0],e=t[1],i=t[2],f=t[3],o=t[4],c=t[5],h=t[6],u=t[7];for(let l=0;l<lt;++l){if(l<16)s[l]=(n[l*4]&255)<<24|(n[l*4+1]&255)<<16|(n[l*4+2]&255)<<8|n[l*4+3]&255;else{let A=s[l-2],M=(A>>>17|A<<15)^(A>>>19|A<<13)^A>>>10;A=s[l-15];let d=(A>>>7|A<<25)^(A>>>18|A<<14)^A>>>3;s[l]=(M+s[l-7]|0)+(d+s[l-16]|0)}let _=(((o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7))+(o&c^~o&h)|0)+(u+(R$[l]+s[l]|0)|0)|0,w=((r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10))+(r&e^r&i^e&i)|0;u=h,h=c,c=o,o=f+_|0,f=i,i=e,e=r,r=_+w|0}t[0]+=r,t[1]+=e,t[2]+=i,t[3]+=f,t[4]+=o,t[5]+=c,t[6]+=h,t[7]+=u}}var n_=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),R$=new Int32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),b$=(()=>{try{return Xr("sha256"),!0}catch{return!1}})(),o_=b$?T$():Tn;function T$(){return class{digestLength=32;secret;hash;isHmac;finished=!1;constructor(n){this.secret=n,this.isHmac=!!n,this.hash=this.createHash()}update(n){if(this.finished)throw Error("Attempted to update an already finished hash.");this.hash.update(n)}async digest(){let n;if(this.isHmac)this.finished=!0,n=this.hash.digest();else n=this.hash.copy().digest();return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}reset(){this.hash=this.createHash(),this.finished=!1}createHash(){return this.secret?c$("sha256",S$(this.secret)):Xr("sha256")}}}function S$(t){if(typeof t==="string")return t;if(ArrayBuffer.isView(t))return Buffer.from(t.buffer,t.byteOffset,t.byteLength);return Buffer.from(t)}var{digest:$$,sign:U$,importKey:L$}=globalThis?.crypto?.subtle??{},li=typeof $$==="function"&&typeof U$==="function"&&typeof L$==="function"?globalThis.crypto.subtle:void 0,I$=8388608;class f_{digestLength=32;secret;pending=[];pendingBytes=0;fallback;finished=!1;constructor(t){if(t)this.secret=Ks(t)}update(t){if(this.finished)throw Error("Attempted to update an already finished HMAC.");if(this.fallback){this.fallback.update(t);return}if(this.pending.push(t.slice()),this.pendingBytes+=t.byteLength,this.pendingBytes>=I$)this.switchToFallback()}async digest(){if(this.fallback)return this.fallback.digest();if(this.secret&&this.finished)throw Error("Attempted to digest an already finished HMAC.");let t=f$(this.pending);if(li){if(this.secret){this.finished=!0;let r=await li.importKey("raw",this.secret,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),e=await li.sign("HMAC",r,t);return new Uint8Array(e)}let s=await li.digest("SHA-256",t);return new Uint8Array(s)}let n=new Tn(this.secret);return n.update(t),n.digest()}reset(){this.pending=[],this.pendingBytes=0,this.fallback=void 0,this.finished=!1}switchToFallback(){let t=new Tn(this.secret);for(let n of this.pending)t.update(n);this.fallback=t,this.pending=[],this.pendingBytes=0}}O$.Crc32=i_;O$.Crc32Js=Cf;O$.Crc32Node=i_;O$.Md5=r_;O$.Md5Js=qf;O$.Md5Node=r_;O$.Sha256=o_;O$.Sha256Js=Tn;O$.Sha256Node=o_;O$.Sha256WebCrypto=f_;O$.blobHasher=h$;O$.blobReader=s_;O$.fileStreamHasher=u$;O$.readableStreamHasher=_$});var _i=K((uU)=>{var{Crc32:u_}=af(),{toHex:Vs,fromHex:z$,toUtf8:k$,fromUtf8:X$}=bt(),{Readable:q$}=j("stream");class js{bytes;constructor(t){if(this.bytes=t,t.byteLength!==8)throw Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(t){if(t>9223372036854776000||t<-9223372036854776000)throw Error(`${t} is too large (or, if negative, too small) to represent as an Int64`);let n=new Uint8Array(8);for(let s=7,r=Math.abs(Math.round(t));s>-1&&r>0;s--,r/=256)n[s]=r;if(t<0)c_(n);return new js(n)}valueOf(){let t=this.bytes.slice(0),n=t[0]&128;if(n)c_(t);return parseInt(Vs(t),16)*(n?-1:1)}toString(){return String(this.valueOf())}}function c_(t){for(let n=0;n<8;n++)t[n]^=255;for(let n=7;n>-1;n--)if(t[n]++,t[n]!==0)break}class Kf{toUtf8;fromUtf8;constructor(t,n){this.toUtf8=t,this.fromUtf8=n}format(t){let n=[];for(let e of Object.keys(t)){let i=this.fromUtf8(e);n.push(Uint8Array.from([i.byteLength]),i,this.formatHeaderValue(t[e]))}let s=new Uint8Array(n.reduce((e,i)=>e+i.byteLength,0)),r=0;for(let e of n)s.set(e,r),r+=e.byteLength;return s}formatHeaderValue(t){switch(t.type){case"boolean":return Uint8Array.from([t.value?tt.boolTrue:tt.boolFalse]);case"byte":return Uint8Array.from([tt.byte,t.value]);case"short":let n=new DataView(new ArrayBuffer(3));return n.setUint8(0,tt.short),n.setInt16(1,t.value,!1),new Uint8Array(n.buffer);case"integer":let s=new DataView(new ArrayBuffer(5));return s.setUint8(0,tt.integer),s.setInt32(1,t.value,!1),new Uint8Array(s.buffer);case"long":let r=new Uint8Array(9);return r[0]=tt.long,r.set(t.value.bytes,1),r;case"binary":let e=new DataView(new ArrayBuffer(3+t.value.byteLength));e.setUint8(0,tt.byteArray),e.setUint16(1,t.value.byteLength,!1);let i=new Uint8Array(e.buffer);return i.set(t.value,3),i;case"string":let f=this.fromUtf8(t.value),o=new DataView(new ArrayBuffer(3+f.byteLength));o.setUint8(0,tt.string),o.setUint16(1,f.byteLength,!1);let c=new Uint8Array(o.buffer);return c.set(f,3),c;case"timestamp":let h=new Uint8Array(9);return h[0]=tt.timestamp,h.set(js.fromNumber(t.value.valueOf()).bytes,1),h;case"uuid":if(!tU.test(t.value))throw Error(`Invalid UUID received: ${t.value}`);let u=new Uint8Array(17);return u[0]=tt.uuid,u.set(z$(t.value.replace(/-/g,"")),1),u}}parse(t){let n={},s=0;while(s<t.byteLength){let r=t.getUint8(s++),e=this.toUtf8(new Uint8Array(t.buffer,t.byteOffset+s,r));switch(s+=r,t.getUint8(s++)){case tt.boolTrue:n[e]={type:h_,value:!0};break;case tt.boolFalse:n[e]={type:h_,value:!1};break;case tt.byte:n[e]={type:C$,value:t.getInt8(s++)};break;case tt.short:n[e]={type:a$,value:t.getInt16(s,!1)},s+=2;break;case tt.integer:n[e]={type:K$,value:t.getInt32(s,!1)},s+=4;break;case tt.long:n[e]={type:V$,value:new js(new Uint8Array(t.buffer,t.byteOffset+s,8))},s+=8;break;case tt.byteArray:let i=t.getUint16(s,!1);s+=2,n[e]={type:j$,value:new Uint8Array(t.buffer,t.byteOffset+s,i)},s+=i;break;case tt.string:let f=t.getUint16(s,!1);s+=2,n[e]={type:p$,value:this.toUtf8(new Uint8Array(t.buffer,t.byteOffset+s,f))},s+=f;break;case tt.timestamp:n[e]={type:v$,value:new Date(new js(new Uint8Array(t.buffer,t.byteOffset+s,8)).valueOf())},s+=8;break;case tt.uuid:let o=new Uint8Array(t.buffer,t.byteOffset+s,16);s+=16,n[e]={type:Z$,value:`${Vs(o.subarray(0,4))}-${Vs(o.subarray(4,6))}-${Vs(o.subarray(6,8))}-${Vs(o.subarray(8,10))}-${Vs(o.subarray(10))}`};break;default:throw Error("Unrecognized header type tag")}}return n}}var tt;(function(t){t[t.boolTrue=0]="boolTrue",t[t.boolFalse=1]="boolFalse",t[t.byte=2]="byte",t[t.short=3]="short",t[t.integer=4]="integer",t[t.long=5]="long",t[t.byteArray=6]="byteArray",t[t.string=7]="string",t[t.timestamp=8]="timestamp",t[t.uuid=9]="uuid"})(tt||(tt={}));var h_="boolean",C$="byte",a$="short",K$="integer",V$="long",j$="binary",p$="string",v$="timestamp",Z$="uuid",tU=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,l_=4,Yn=l_*2,hs=4,nU=Yn+hs*2;function sU({byteLength:t,byteOffset:n,buffer:s}){if(t<nU)throw Error("Provided message too short to accommodate event stream message overhead");let r=new DataView(s,n,t),e=r.getUint32(0,!1);if(t!==e)throw Error("Reported message length does not match received message length");let i=r.getUint32(l_,!1),f=r.getUint32(Yn,!1),o=r.getUint32(t-hs,!1),c=new u_;if(c.update(new Uint8Array(s,n,Yn)),f!==c.digestSync())throw Error(`The prelude checksum specified in the message (${f}) does not match the calculated CRC32 checksum (${c.digestSync()})`);if(c.update(new Uint8Array(s,n+Yn,t-(Yn+hs))),o!==c.digestSync())throw Error(`The message checksum (${c.digestSync()}) did not match the expected value of ${o}`);return{headers:new DataView(s,n+Yn+hs,i),body:new Uint8Array(s,n+Yn+hs+i,e-i-(Yn+hs+hs))}}class Vf{headerMarshaller;messageBuffer;isEndOfStream;constructor(t,n){this.headerMarshaller=new Kf(t,n),this.messageBuffer=[],this.isEndOfStream=!1}feed(t){this.messageBuffer.push(this.decode(t))}endOfStream(){this.isEndOfStream=!0}getMessage(){let t=this.messageBuffer.pop(),n=this.isEndOfStream;return{getMessage(){return t},isEndOfStream(){return n}}}getAvailableMessages(){let t=this.messageBuffer;this.messageBuffer=[];let n=this.isEndOfStream;return{getMessages(){return t},isEndOfStream(){return n}}}encode({headers:t,body:n}){let s=this.headerMarshaller.format(t),r=s.byteLength+n.byteLength+16,e=new Uint8Array(r),i=new DataView(e.buffer,e.byteOffset,e.byteLength),f=new u_;return i.setUint32(0,r,!1),i.setUint32(4,s.byteLength,!1),f.update(e.subarray(0,8)),i.setUint32(8,f.digestSync(),!1),e.set(s,12),e.set(n,s.byteLength+12),f.update(e.subarray(8,r-4)),i.setUint32(r-4,f.digestSync(),!1),e}decode(t){let{headers:n,body:s}=sU(t);return{headers:this.headerMarshaller.parse(n),body:s}}formatHeaders(t){return this.headerMarshaller.format(t)}}class jf{options;constructor(t){this.options=t}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let t of this.options.inputStream)yield this.options.decoder.decode(t)}}class pf{options;constructor(t){this.options=t}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let t of this.options.messageStream)yield this.options.encoder.encode(t);if(this.options.includeEndFrame)yield new Uint8Array(0)}}class vf{options;constructor(t){this.options=t}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let t of this.options.messageStream){let n=await this.options.deserializer(t);if(n===void 0)continue;yield n}}}class Zf{options;constructor(t){this.options=t}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let t of this.options.inputStream)yield this.options.serializer(t)}}function __(t){let n=0,s=0,r=null,e=null,i=(o)=>{if(typeof o!=="number")throw Error("Attempted to allocate an event message where size was not a number: "+o);n=o,s=4,r=new Uint8Array(o),new DataView(r.buffer).setUint32(0,o,!1)},f=async function*(){let o=t[Symbol.asyncIterator]();while(!0){let{value:c,done:h}=await o.next();if(h){if(!n)return;else if(n===s)yield r;else throw Error("Truncated event message received.");return}let u=c.length,l=0;while(l<u){if(!r){let w=u-l;if(!e)e=new Uint8Array(4);let A=Math.min(4-s,w);if(e.set(c.slice(l,l+A),s),s+=A,l+=A,s<4)break;i(new DataView(e.buffer).getUint32(0,!1)),e=null}let _=Math.min(n-s,u-l);if(r.set(c.slice(l,l+_),s),s+=_,l+=_,n&&n===s)yield r,r=null,n=0,s=0}}};return{[Symbol.asyncIterator]:f}}function rU(t,n){let s=tc(n.deserializer,n.toUtf8);return{[Symbol.asyncIterator]:async function*(){for await(let r of t){let e=n.eventStreamCodec.decode(r),i=await s(e);if(i===void 0)continue;yield i}}}}function tc(t,n){return async function(s){let{value:r}=s.headers[":message-type"];if(r==="error"){let e=Error(s.headers[":error-message"].value||"UnknownError");throw e.name=s.headers[":error-code"].value,e}else if(r==="exception"){let e=s.headers[":exception-type"].value,i={[e]:s},f=await t(i);if(f.$unknown){let o=Error(n(s.body));throw o.name=e,o}throw f[e]}else if(r==="event"){let e={[s.headers[":event-type"].value]:s},i=await t(e);if(i.$unknown)return;return i}else throw Error(`Unrecognizable event type: ${s.headers[":event-type"].value}`)}}var nc=class{eventStreamCodec;utfEncoder;constructor({utf8Encoder:n,utf8Decoder:s}){this.eventStreamCodec=new Vf(n,s),this.utfEncoder=n}deserialize(n,s){let r=__(n);return new vf({messageStream:new jf({inputStream:r,decoder:this.eventStreamCodec}),deserializer:tc(s,this.utfEncoder)})}serialize(n,s){return new pf({messageStream:new Zf({inputStream:n,serializer:s}),encoder:this.eventStreamCodec,includeEndFrame:!0})}},eU=(t)=>new nc(t);class sc{universalMarshaller;constructor({utf8Encoder:t,utf8Decoder:n}){this.universalMarshaller=new nc({utf8Decoder:n,utf8Encoder:t})}deserialize(t,n){let s=typeof t[Symbol.asyncIterator]==="function"?t:oU(t);return this.universalMarshaller.deserialize(s,n)}serialize(t,n){return q$.from(this.universalMarshaller.serialize(t,n))}}var iU=(t)=>new sc(t);async function*oU(t){let n=!1,s=!1,r=[];t.on("error",(e)=>{if(!n)n=!0;if(e)throw e}),t.on("data",(e)=>{r.push(e)}),t.on("end",()=>{n=!0});while(!s){let e=await new Promise((i)=>setTimeout(()=>i(r.shift()),0));if(e)yield e;s=n&&r.length===0}}var fU=(t)=>({[Symbol.asyncIterator]:async function*(){let n=t.getReader();try{while(!0){let{done:s,value:r}=await n.read();if(s)return;yield r}}finally{n.releaseLock()}}}),cU=(t)=>{let n=t[Symbol.asyncIterator]();return new ReadableStream({async pull(s){let{done:r,value:e}=await n.next();if(r)return s.close();s.enqueue(e)}})},hU=(t)=>Object.assign(t,{eventStreamMarshaller:t.eventStreamSerdeProvider(t)});class w_{marshaller;serializer;deserializer;serdeContext;defaultContentType;constructor({marshaller:t,serializer:n,deserializer:s,serdeContext:r,defaultContentType:e}){this.marshaller=t,this.serializer=n,this.deserializer=s,this.serdeContext=r,this.defaultContentType=e}async serializeEventStream({eventStream:t,requestSchema:n,initialRequest:s}){let r=this.marshaller,e=n.getEventStreamMember(),i=n.getMemberSchema(e),f=this.serializer,o=this.defaultContentType,c=Symbol("initialRequestMarker"),h={async*[Symbol.asyncIterator](){if(s){let u={":event-type":{type:"string",value:"initial-request"},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:o}};f.write(n,s);let l=f.flush();yield{[c]:!0,headers:u,body:l}}for await(let u of t)yield u}};return r.serialize(h,(u)=>{if(u[c])return{headers:u.headers,body:u.body};let l="";for(let E in u)if(E!=="__type"){l=E;break}let{additionalHeaders:_,body:w,eventType:A,explicitPayloadContentType:M}=this.writeEventBody(l,i,u);return{headers:{":event-type":{type:"string",value:A},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:M??o},..._},body:w}})}async deserializeEventStream({response:t,responseSchema:n,initialResponseContainer:s}){let r=this.marshaller,e=n.getEventStreamMember(),f=n.getMemberSchema(e).getMemberSchemas(),o=Symbol("initialResponseMarker"),c=r.deserialize(t.body,async(l)=>{let _="";for(let A in l)if(A!=="__type"){_=A;break}let w=l[_].body;if(_==="initial-response"){let A=await this.deserializer.read(n,w);return delete A[e],{[o]:!0,...A}}else if(_ in f){let A=f[_];if(A.isStructSchema()){let M={},d=!1;for(let[E,b]of A.structIterator()){let{eventHeader:L,eventPayload:S}=b.getMergedTraits();if(d=d||Boolean(L||S),S){if(b.isBlobSchema())M[E]=w;else if(b.isStringSchema())M[E]=(this.serdeContext?.utf8Encoder??k$)(w);else if(b.isStructSchema())M[E]=await this.deserializer.read(b,w)}else if(L){let O=l[_].headers[E]?.value;if(O!=null)if(b.isNumericSchema())if(O&&typeof O==="object"&&"bytes"in O)M[E]=BigInt(O.toString());else M[E]=Number(O);else M[E]=O}}if(d)return{[_]:M};if(w.byteLength===0)return{[_]:{}}}return{[_]:await this.deserializer.read(A,w)}}else return{$unknown:l}}),h=c[Symbol.asyncIterator](),u=await h.next();if(u.done)return c;if(u.value?.[o]){if(!n)throw Error("@smithy::core/protocols - initial-response event encountered in event stream but no response schema given.");for(let l in u.value)s[l]=u.value[l]}return{async*[Symbol.asyncIterator](){if(!u?.value?.[o])yield u.value;while(!0){let{done:l,value:_}=await h.next();if(l)break;yield _}}}}writeEventBody(t,n,s){let r=this.serializer,e=t,i=null,f,o=(()=>{return n.getSchema()[4].includes(t)})(),c={};if(!o){let[l,_]=s[t];e=l,r.write(15,_)}else{let l=n.getMemberSchema(t);if(l.isStructSchema()){for(let[_,w]of l.structIterator()){let{eventHeader:A,eventPayload:M}=w.getMergedTraits();if(M)i=_;else if(A){let d=s[t][_],E="binary";if(w.isNumericSchema())if(-2147483648<=d&&d<=2147483647)E="integer";else E="long";else if(w.isTimestampSchema())E="timestamp";else if(w.isStringSchema())E="string";else if(w.isBooleanSchema())E="boolean";if(d!=null)c[_]={type:E,value:d},delete s[t][_]}}if(i!==null){let _=l.getMemberSchema(i);if(_.isBlobSchema())f="application/octet-stream";else if(_.isStringSchema())f="text/plain";r.write(_,s[t][i])}else r.write(l,s[t])}else if(l.isUnitSchema())r.write(l,{});else throw Error("@smithy/core/event-streams - non-struct member not supported in event stream union.")}let h=r.flush()??new Uint8Array;return{body:typeof h==="string"?(this.serdeContext?.utf8Decoder??X$)(h):h,eventType:e,explicitPayloadContentType:f,additionalHeaders:c}}}uU.EventStreamCodec=Vf;uU.EventStreamMarshaller=sc;uU.EventStreamSerde=w_;uU.HeaderMarshaller=Kf;uU.Int64=js;uU.MessageDecoderStream=jf;uU.MessageEncoderStream=pf;uU.SmithyMessageDecoderStream=vf;uU.SmithyMessageEncoderStream=Zf;uU.UniversalEventStreamMarshaller=nc;uU.eventStreamSerdeProvider=iU;uU.getChunkedStream=__;uU.getMessageUnmarshaller=tc;uU.getUnmarshalledStream=rU;uU.iterableToReadableStream=cU;uU.readableStreamToIterable=fU;uU.resolveEventStreamSerdeConfig=hU;uU.universalEventStreamSerdeProvider=eU});var Tt=K((jU)=>{var{Uint8ArrayBlobAdapter:rc,sdkStreamMixin:GU,splitEvery:BU,splitHeader:g_,fromBase64:A_,_parseEpochTimestamp:mU,_parseRfc7231DateTime:FU,_parseRfc3339DateTimeWithOffset:PU,LazyJsonString:E_,NumericValue:HU,toUtf8:R_,fromUtf8:NU,generateIdempotencyToken:DU,toBase64:M_,dateToUtcString:WU,quoteHeader:YU}=bt(),{TypeRegistry:xU,NormalizedSchema:en,translateTraits:b_}=Pn(),{HttpRequest:ps,HttpResponse:T_,isValidHostname:S_}=tn(),{parseQueryString:QU,parseUrl:JU}=tn();jU.HttpRequest=ps;jU.HttpResponse=T_;jU.isValidHostname=S_;jU.parseQueryString=QU;jU.parseUrl=JU;var{FieldPosition:zU}=es(),us=async(t=new Uint8Array,n)=>{if(t instanceof Uint8Array)return rc.mutate(t);if(!t)return rc.mutate(new Uint8Array);let s=n.streamCollector(t);return rc.mutate(await s)};function Cr(t){return encodeURIComponent(t).replace(/[!'()*]/g,function(n){return"%"+n.charCodeAt(0).toString(16).toUpperCase()})}class vs{serdeContext;setSerdeContext(t){this.serdeContext=t}}class wi extends vs{options;compositeErrorRegistry;constructor(t){super();this.options=t,this.compositeErrorRegistry=xU.for(t.defaultNamespace);for(let n of t.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(n)}getRequestType(){return ps}getResponseType(){return T_}setSerdeContext(t){if(this.serdeContext=t,this.serializer.setSerdeContext(t),this.deserializer.setSerdeContext(t),this.getPayloadCodec())this.getPayloadCodec().setSerdeContext(t)}updateServiceEndpoint(t,n){if("url"in n){if(t.protocol=n.url.protocol,t.hostname=n.url.hostname,t.port=n.url.port?Number(n.url.port):void 0,t.path=n.url.pathname,t.fragment=n.url.hash||void 0,t.username=n.url.username||void 0,t.password=n.url.password||void 0,!t.query)t.query={};for(let[s,r]of n.url.searchParams.entries())t.query[s]=r;if(n.headers)for(let s in n.headers)t.headers[s]=n.headers[s].join(", ");return t}else{if(t.protocol=n.protocol,t.hostname=n.hostname,t.port=n.port?Number(n.port):void 0,t.path=n.path,t.query={...n.query},n.headers)for(let s in n.headers)t.headers[s]=n.headers[s];return t}}setHostPrefix(t,n,s){if(this.serdeContext?.disableHostPrefix)return;let r=en.of(n.input),e=b_(n.traits??{});if(e.endpoint){let i=e.endpoint?.[0];if(typeof i==="string"){for(let[f,o]of r.structIterator()){if(!o.getMergedTraits().hostLabel)continue;let c=s[f];if(typeof c!=="string")throw Error(`@smithy/core/schema - ${f} in input must be a string as hostLabel.`);i=i.replace(`{${f}}`,c)}if(t.hostname=i+t.hostname,!S_(t.hostname))throw Error(`[${t.hostname}] is not a valid hostname.`)}}}deserializeMetadata(t){return{httpStatusCode:t.statusCode,requestId:t.headers["x-amzn-requestid"]??t.headers["x-amzn-request-id"]??t.headers["x-amz-request-id"],extendedRequestId:t.headers["x-amz-id-2"],cfId:t.headers["x-amz-cf-id"]}}async serializeEventStream({eventStream:t,requestSchema:n,initialRequest:s}){return(await this.loadEventStreamCapability()).serializeEventStream({eventStream:t,requestSchema:n,initialRequest:s})}async deserializeEventStream({response:t,responseSchema:n,initialResponseContainer:s}){return(await this.loadEventStreamCapability()).deserializeEventStream({response:t,responseSchema:n,initialResponseContainer:s})}async loadEventStreamCapability(){let{EventStreamSerde:t,eventStreamSerdeProvider:n}=_i(),s=this.resolveEventStreamMarshaller(n);return new t({marshaller:s,serializer:this.serializer,deserializer:this.deserializer,serdeContext:this.serdeContext,defaultContentType:this.getDefaultContentType()})}resolveEventStreamMarshaller(t){let n=this.serdeContext;if(n.eventStreamMarshaller)return n.eventStreamMarshaller;return t(this.serdeContext)}getDefaultContentType(){throw Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`)}async deserializeHttpMessage(t,n,s,r,e){return[]}getEventStreamMarshaller(){let t=this.serdeContext;if(!t.eventStreamMarshaller)throw Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");return t.eventStreamMarshaller}}class $_ extends wi{async serializeRequest(t,n,s){let r=n&&typeof n==="object"?n:{},e=this.serializer,i={},f={},o=await s.endpoint(),c=en.of(t?.input),h=[],u=[],l=!1,_,w=new ps({protocol:"",hostname:"",port:void 0,path:"",fragment:void 0,query:i,headers:f,body:void 0});if(o){this.updateServiceEndpoint(w,o),this.setHostPrefix(w,t,r);let A=b_(t.traits);if(A.http){w.method=A.http[0];let[M,d]=A.http[1].split("?");if(w.path=="/")w.path=M;else w.path+=M;let E=new URLSearchParams(d??"");for(let[b,L]of E)i[b]=L}}for(let[A,M]of c.structIterator()){let d=M.getMergedTraits()??{},E=r[A];if(E==null&&!M.isIdempotencyToken()){if(d.httpLabel){if(w.path.includes(`{${A}+}`)||w.path.includes(`{${A}}`))throw Error(`No value provided for input HTTP label: ${A}.`)}continue}if(d.httpPayload)if(M.isStreaming())if(M.isStructSchema()){if(r[A])_=await this.serializeEventStream({eventStream:r[A],requestSchema:c})}else _=E;else e.write(M,E),_=e.flush();else if(d.httpLabel){e.write(M,E);let b=e.flush();if(w.path.includes(`{${A}+}`))w.path=w.path.replace(`{${A}+}`,b.split("/").map(Cr).join("/"));else if(w.path.includes(`{${A}}`))w.path=w.path.replace(`{${A}}`,Cr(b))}else if(d.httpHeader)e.write(M,E),f[d.httpHeader.toLowerCase()]=String(e.flush());else if(typeof d.httpPrefixHeaders==="string")for(let b in E){let L=E[b],S=d.httpPrefixHeaders+b;e.write([M.getValueSchema(),{httpHeader:S}],L),f[S.toLowerCase()]=e.flush()}else if(d.httpQuery||d.httpQueryParams)this.serializeQuery(M,E,i);else l=!0,h.push(A),u.push(M)}if(l&&r){let[A,M]=(c.getName(!0)??"#Unknown").split("#"),d=c.getSchema()[6],E=[3,A,M,c.getMergedTraits(),h,u,void 0];if(d)E[6]=d;else E.pop();e.write(E,r),_=e.flush()}return w.headers=f,w.query=i,w.body=_,w}serializeQuery(t,n,s){let r=this.serializer,e=t.getMergedTraits();if(e.httpQueryParams){for(let i in n)if(!(i in s)){let f=n[i],o=t.getValueSchema();Object.assign(o.getMergedTraits(),{...e,httpQuery:i,httpQueryParams:void 0}),this.serializeQuery(o,f,s)}return}if(t.isListSchema()){let i=!!t.getMergedTraits().sparse,f=[];for(let o of n){r.write([t.getValueSchema(),e],o);let c=r.flush();if(i||c!==void 0)f.push(c)}s[e.httpQuery]=f}else r.write([t,e],n),s[e.httpQuery]=r.flush()}async deserializeResponse(t,n,s){let r=this.deserializer,e=en.of(t.output),i={};if(s.statusCode>=300){let o=await us(s.body,n);if(o.byteLength>0)Object.assign(i,await r.read(15,o));throw await this.handleError(t,n,s,i,this.deserializeMetadata(s)),Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw.")}for(let o in s.headers){let c=s.headers[o];delete s.headers[o],s.headers[o.toLowerCase()]=c}let f=await this.deserializeHttpMessage(e,n,s,i);if(f.length){let o=await us(s.body,n);if(o.byteLength>0){let c=await r.read(e,o);for(let h of f)if(c[h]!=null)i[h]=c[h]}}else if(f.discardResponseBody)await us(s.body,n);return i.$metadata=this.deserializeMetadata(s),i}async deserializeHttpMessage(t,n,s,r,e){let i;if(r instanceof Set)i=e;else i=r;let f=!0,o=this.deserializer,c=en.of(t),h=[];for(let[u,l]of c.structIterator()){let _=l.getMemberTraits();if(_.httpPayload){if(f=!1,l.isStreaming())if(l.isStructSchema())i[u]=await this.deserializeEventStream({response:s,responseSchema:c});else i[u]=GU(s.body);else if(s.body){let A=await us(s.body,n);if(A.byteLength>0)i[u]=await o.read(l,A)}}else if(_.httpHeader){let w=String(_.httpHeader).toLowerCase(),A=s.headers[w];if(A!=null)if(l.isListSchema()){let M=l.getValueSchema();M.getMergedTraits().httpHeader=w;let d;if(M.isTimestampSchema()&&M.getSchema()===4)d=BU(A,",",2);else d=g_(A);let E=[];for(let b of d)E.push(await o.read(M,b.trim()));i[u]=E}else i[u]=await o.read(l,A)}else if(_.httpPrefixHeaders!==void 0){i[u]={};for(let w in s.headers)if(w.startsWith(_.httpPrefixHeaders)){let A=s.headers[w],M=l.getValueSchema();M.getMergedTraits().httpHeader=w,i[u][w.slice(_.httpPrefixHeaders.length)]=await o.read(M,A)}}else if(_.httpResponseCode)i[u]=s.statusCode;else h.push(u)}return h.discardResponseBody=f,h}}class U_ extends wi{async serializeRequest(t,n,s){let r=this.serializer,e={},i={},f=await s.endpoint(),o=en.of(t?.input),c=o.getSchema(),h,u=n&&typeof n==="object"?n:{},l=new ps({protocol:"",hostname:"",port:void 0,path:"/",fragment:void 0,query:e,headers:i,body:void 0});if(f)this.updateServiceEndpoint(l,f),this.setHostPrefix(l,t,u);if(u){let _=o.getEventStreamMember();if(_){if(u[_]){let w={};for(let[A,M]of o.structIterator())if(A!==_&&u[A])r.write(M,u[A]),w[A]=r.flush();h=await this.serializeEventStream({eventStream:u[_],requestSchema:o,initialRequest:w})}}else r.write(c,u),h=r.flush()}return l.headers=Object.assign(l.headers,i),l.query=e,l.body=h,l.method="POST",l}async deserializeResponse(t,n,s){let r=this.deserializer,e=en.of(t.output),i={};if(s.statusCode>=300){let o=await us(s.body,n);if(o.byteLength>0)Object.assign(i,await r.read(15,o));throw await this.handleError(t,n,s,i,this.deserializeMetadata(s)),Error("@smithy/core/protocols - RPC Protocol error handler failed to throw.")}for(let o in s.headers){let c=s.headers[o];delete s.headers[o],s.headers[o.toLowerCase()]=c}let f=e.getEventStreamMember();if(f)i[f]=await this.deserializeEventStream({response:s,responseSchema:e,initialResponseContainer:i});else{let o=await us(s.body,n);if(o.byteLength>0)Object.assign(i,await r.read(e,o))}return i.$metadata=this.deserializeMetadata(s),i}}var L_=(t,n,s,r,e,i)=>{if(n!=null&&n[s]!==void 0){let f=r();if(f==null||f.length<=0)throw Error("Empty value provided for input HTTP label: "+s+".");t=t.replace(e,i?f.split("/").map((o)=>Cr(o)).join("/"):Cr(f))}else throw Error("No value provided for input HTTP label: "+s+".");return t};function kU(t,n){return new ec(t,n)}class ec{input;context;query={};method="";headers={};path="";body=null;hostname="";resolvePathStack=[];constructor(t,n){this.input=t,this.context=n}async build(){let{hostname:t,protocol:n="https",port:s,path:r}=await this.context.endpoint();this.path=r;for(let e of this.resolvePathStack)e(this.path);return new ps({protocol:n,hostname:this.hostname||t,port:s,method:this.method,path:this.path,query:this.query,body:this.body,headers:this.headers})}hn(t){return this.hostname=t,this}bp(t){return this.resolvePathStack.push((n)=>{this.path=`${n?.endsWith("/")?n.slice(0,-1):n||""}`+t}),this}p(t,n,s,r){return this.resolvePathStack.push((e)=>{this.path=L_(e,this.input,t,n,s,r)}),this}h(t){return this.headers=t,this}q(t){return this.query=t,this}b(t){return this.body=t,this}m(t){return this.method=t,this}}function ic(t,n){if(n.timestampFormat.useTrait){if(t.isTimestampSchema()&&(t.getSchema()===5||t.getSchema()===6||t.getSchema()===7))return t.getSchema()}let{httpLabel:s,httpPrefixHeaders:r,httpHeader:e,httpQuery:i}=t.getMergedTraits();return(n.httpBindings?typeof r==="string"||Boolean(e)?6:Boolean(i)||Boolean(s)?5:void 0:void 0)??n.timestampFormat.default}class oc extends vs{settings;constructor(t){super();this.settings=t}read(t,n){let s=en.of(t);if(s.isListSchema())return g_(n).map((r)=>this.read(s.getValueSchema(),r));if(s.isBlobSchema())return(this.serdeContext?.base64Decoder??A_)(n);if(s.isTimestampSchema())switch(ic(s,this.settings)){case 5:return PU(n);case 6:return FU(n);case 7:return mU(n);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",n),new Date(n)}if(s.isStringSchema()){let r=s.getMergedTraits().mediaType,e=n;if(r){if(s.getMergedTraits().httpHeader)e=this.base64ToUtf8(e);if(r==="application/json"||r.endsWith("+json"))e=E_.from(e);return e}}if(s.isNumericSchema())return Number(n);if(s.isBigIntegerSchema())return BigInt(n);if(s.isBigDecimalSchema())return new HU(n,"bigDecimal");if(s.isBooleanSchema())return String(n).toLowerCase()==="true";return n}base64ToUtf8(t){return(this.serdeContext?.utf8Encoder??R_)((this.serdeContext?.base64Decoder??A_)(t))}}class I_ extends vs{codecDeserializer;stringDeserializer;constructor(t,n){super();this.codecDeserializer=t,this.stringDeserializer=new oc(n)}setSerdeContext(t){this.stringDeserializer.setSerdeContext(t),this.codecDeserializer.setSerdeContext(t),this.serdeContext=t}read(t,n){let s=en.of(t),r=s.getMergedTraits(),e=this.serdeContext?.utf8Encoder??R_;if(r.httpHeader||r.httpResponseCode)return this.stringDeserializer.read(s,e(n));if(r.httpPayload){if(s.isBlobSchema()){let i=this.serdeContext?.utf8Decoder??NU;if(typeof n==="string")return i(n);return n}else if(s.isStringSchema()){if("byteLength"in n)return e(n);return n}}return this.codecDeserializer.read(s,n)}}class fc extends vs{settings;stringBuffer="";constructor(t){super();this.settings=t}write(t,n){let s=en.of(t);switch(typeof n){case"object":if(n===null){this.stringBuffer="null";return}if(s.isTimestampSchema()){if(!(n instanceof Date))throw Error(`@smithy/core/protocols - received non-Date value ${n} when schema expected Date in ${s.getName(!0)}`);switch(ic(s,this.settings)){case 5:this.stringBuffer=n.toISOString().replace(".000Z","Z");break;case 6:this.stringBuffer=WU(n);break;case 7:this.stringBuffer=String(n.getTime()/1000);break;default:console.warn("Missing timestamp format, using epoch seconds",n),this.stringBuffer=String(n.getTime()/1000)}return}if(s.isBlobSchema()&&"byteLength"in n){this.stringBuffer=(this.serdeContext?.base64Encoder??M_)(n);return}if(s.isListSchema()&&Array.isArray(n)){let i="";for(let f of n){this.write([s.getValueSchema(),s.getMergedTraits()],f);let o=this.flush(),c=s.getValueSchema().isTimestampSchema()?o:YU(o);if(i!=="")i+=", ";i+=c}this.stringBuffer=i;return}this.stringBuffer=JSON.stringify(n,null,2);break;case"string":let r=s.getMergedTraits().mediaType,e=n;if(r){if(r==="application/json"||r.endsWith("+json"))e=E_.from(e);if(s.getMergedTraits().httpHeader){this.stringBuffer=(this.serdeContext?.base64Encoder??M_)(e.toString());return}}this.stringBuffer=n;break;default:if(s.isIdempotencyToken())this.stringBuffer=DU();else this.stringBuffer=String(n)}}flush(){let t=this.stringBuffer;return this.stringBuffer="",t}}class O_{codecSerializer;stringSerializer;buffer;constructor(t,n,s=new fc(n)){this.codecSerializer=t,this.stringSerializer=s}setSerdeContext(t){this.codecSerializer.setSerdeContext(t),this.stringSerializer.setSerdeContext(t)}write(t,n){let s=en.of(t),r=s.getMergedTraits();if(r.httpHeader||r.httpLabel||r.httpQuery){this.stringSerializer.write(s,n),this.buffer=this.stringSerializer.flush();return}return this.codecSerializer.write(s,n)}flush(){if(this.buffer!==void 0){let t=this.buffer;return this.buffer=void 0,t}return this.codecSerializer.flush()}}class y_{name;kind;values;constructor({name:t,kind:n=zU.HEADER,values:s=[]}){this.name=t,this.kind=n,this.values=s}add(t){this.values.push(t)}set(t){this.values=t}remove(t){this.values=this.values.filter((n)=>n!==t)}toString(){return this.values.map((t)=>t.includes(",")||t.includes(" ")?`"${t}"`:t).join(", ")}get(){return this.values}}class G_{entries={};encoding;constructor({fields:t=[],encoding:n="utf-8"}){t.forEach(this.setField.bind(this)),this.encoding=n}setField(t){this.entries[t.name.toLowerCase()]=t}getField(t){return this.entries[t.toLowerCase()]}removeField(t){delete this.entries[t.toLowerCase()]}getByType(t){return Object.values(this.entries).filter((n)=>n.kind===t)}}var XU=(t)=>{return{setHttpHandler(n){t.httpHandler=n},httpHandler(){return t.httpHandler},updateHttpClientConfig(n,s){t.httpHandler?.updateHttpClientConfig(n,s)},httpHandlerConfigs(){return t.httpHandler.httpHandlerConfigs()}}},qU=(t)=>{return{httpHandler:t.httpHandler()}},d_="content-length";function B_(t){return(n)=>async(s)=>{let r=s.request;if(ps.isInstance(r)){let{body:e,headers:i}=r;if(e&&Object.keys(i).map((f)=>f.toLowerCase()).indexOf(d_)===-1)try{let f=t(e);r.headers={...r.headers,[d_]:String(f)}}catch(f){}}return n({...s,request:r})}}var m_={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},CU=(t)=>({applyToStack:(n)=>{n.add(B_(t.bodyLengthChecker),m_)}}),qr=(t)=>encodeURIComponent(t).replace(/[!'()*]/g,aU),aU=(t)=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`,KU=(t)=>t.split("/").map(qr).join("/");function VU(t){let n=[];for(let s of Object.keys(t).sort()){let r=t[s];if(s=qr(s),Array.isArray(r))for(let e=0,i=r.length;e<i;e++)n.push(`${s}=${qr(r[e])}`);else{let e=s;if(r||typeof r==="string")e+=`=${qr(r)}`;n.push(e)}}return n.join("&")}jU.Field=y_;jU.Fields=G_;jU.FromStringShapeDeserializer=oc;jU.HttpBindingProtocol=$_;jU.HttpInterceptingShapeDeserializer=I_;jU.HttpInterceptingShapeSerializer=O_;jU.HttpProtocol=wi;jU.RequestBuilder=ec;jU.RpcProtocol=U_;jU.SerdeContext=vs;jU.ToStringShapeSerializer=fc;jU.buildQueryString=VU;jU.collectBody=us;jU.contentLengthMiddleware=B_;jU.contentLengthMiddlewareOptions=m_;jU.determineTimestampFormat=ic;jU.escapeUri=qr;jU.escapeUriPath=KU;jU.extendedEncodeURIComponent=Cr;jU.getContentLengthPlugin=CU;jU.getHttpHandlerExtensionConfiguration=XU;jU.requestBuilder=kU;jU.resolveHttpHandlerRuntimeConfig=qU;jU.resolvedPath=L_});var pr=K((VL)=>{var{Readable:IL}=j("stream"),{NoOpLogger:OL,normalizeProvider:F_}=En(),{HttpResponse:P_,HttpRequest:Mi}=Tt(),{parseRfc7231DateTime:yL,v4:H_}=bt(),N_=(t)=>t?.body instanceof IL||typeof ReadableStream<"u"&&t?.body instanceof ReadableStream,GL=["AuthFailure","InvalidSignatureException","RequestExpired","RequestInTheFuture","RequestTimeTooSkewed","SignatureDoesNotMatch"],BL=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],mL=["TimeoutError","RequestTimeout","RequestTimeoutException"],FL=[500,502,503,504],PL=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],HL=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN"],lc=(t)=>t?.$retryable!==void 0,D_=(t)=>GL.includes(t.name),W_=(t)=>t.$metadata?.clockSkewCorrected,Y_=(t)=>{let n=new Set(["Failed to fetch","NetworkError when attempting to fetch resource","The Internet connection appears to be offline","Load failed","Network request failed"]);if(!(t&&t instanceof TypeError))return!1;return n.has(t.message)},Kr=(t)=>t.$metadata?.httpStatusCode===429||BL.includes(t.name)||t.$retryable?.throttling==!0,Vr=(t,n=0)=>lc(t)||W_(t)||t.name==="InvalidSignatureException"&&t.message?.includes("Signature expired")||mL.includes(t.name)||PL.includes(t?.code||"")||HL.includes(t?.code||"")||FL.includes(t.$metadata?.httpStatusCode||0)||Y_(t)||Q_(t)||t.cause!==void 0&&n<=10&&Vr(t.cause,n+1),x_=(t)=>{if(t.$metadata?.httpStatusCode!==void 0){let n=t.$metadata.httpStatusCode;if(500<=n&&n<=599&&!Vr(t))return!0;return!1}return!1};function Q_(t){return t.code==="ERR_HTTP2_STREAM_ERROR"&&t.message.includes("NGHTTP2_REFUSED_STREAM")}var J_=100,gi=20000,z_=500,di=500,k_=5,X_=10,_c=1,Ei="amz-sdk-invocation-id",Ri="amz-sdk-request";function q_(t,n){if(!P_.isInstance(t))return;for(let s of Object.keys(t.headers)){let r=s.toLowerCase();if(r==="retry-after"){let e=t.headers[s],i=NaN;if(e.endsWith("GMT"))try{i=(yL(e).getTime()-Date.now())/1000}catch(f){n?.trace?.("Failed to parse retry-after header"),n?.trace?.(f)}else if(e.match(/ GMT, ((\d+)|(\d+\.\d+))$/))i=Number(e.match(/ GMT, ([\d.]+)$/)?.[1]);else if(e.match(/^((\d+)|(\d+\.\d+))$/))i=Number(e);else if(Date.parse(e)>=Date.now())i=(Date.parse(e)-Date.now())/1000;if(isNaN(i))return;return new Date(Date.now()+i*1000)}else if(r==="x-amz-retry-after"){let e=t.headers[s],i=Number(e);if(isNaN(i)){n?.trace?.(`Failed to parse x-amz-retry-after=${e}`);return}return new Date(Date.now()+i)}}}function NL(t,n){return q_(t,n)}var C_=(t)=>{if(t instanceof Error)return t;if(t instanceof Object)return Object.assign(Error(),t);if(typeof t==="string")return Error(t);return Error(`AWS SDK error wrapper for ${t}`)};function a_(t){return(n)=>(s,r)=>async(e)=>{let i=await n.retryStrategy(),f=await n.maxAttempts();if(WL(i)){i=i;let o=await i.acquireInitialRetryToken((r.partition_id??"")+(r.__retryLongPoll?":longpoll":"")),c=Error(),h=0,u=0,{request:l}=e,_=Mi.isInstance(l);if(_)l.headers[Ei]=H_();while(!0)try{if(_)l.headers[Ri]=`attempt=${h+1}; max=${f}`;let{response:w,output:A}=await s(e);return i.recordSuccess(o),A.$metadata.attempts=h+1,A.$metadata.totalRetryDelay=u,{response:w,output:A}}catch(w){let A=YL(w,n.logger);if(c=C_(w),_&&t(l))throw(r.logger instanceof OL?console:r.logger)?.warn("An error was encountered in a non-retryable streaming request."),c;try{o=await i.refreshRetryTokenForRetry(o,A)}catch(d){if(!c.$metadata)c.$metadata={};throw c.$metadata.attempts=h+1,c.$metadata.totalRetryDelay=u,c}h=o.getRetryCount();let M=o.getRetryDelay();if(u+=(o?.$retryLog?.acquisitionDelay??0)+M,M>0)await DL(M)}}else{if(i=i,i?.mode)r.userAgent=[...r.userAgent||[],["cfg/retry-mode",i.mode]];return i.retry(s,e)}}}var DL=(t)=>new Promise((n)=>setTimeout(n,t)),WL=(t)=>typeof t.acquireInitialRetryToken<"u"&&typeof t.refreshRetryTokenForRetry<"u"&&typeof t.recordSuccess<"u",YL=(t,n)=>{let s={error:t,errorType:xL(t)},r=q_(t.$response,n);if(r)s.retryAfterHint=r;return s},xL=(t)=>{if(Kr(t))return"THROTTLING";if(Vr(t))return"TRANSIENT";if(x_(t))return"SERVER_ERROR";return"CLIENT_ERROR"},K_={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0};function QL(t){let n=a_(t);return(s)=>({applyToStack:(r)=>{r.add(n(s),K_)}})}class jr{static setTimeoutFn=(t,n)=>setTimeout(t,n);beta;minCapacity;minFillRate;scaleConstant;smooth;enabled=!1;availableTokens=0;lastMaxRate=0;measuredTxRate=0;requestCount=0;fillRate;lastThrottleTime;lastTimestamp=0;lastTxRateBucket;maxCapacity;timeWindow=0;constructor(t){this.beta=t?.beta??0.7,this.minCapacity=t?.minCapacity??1,this.minFillRate=t?.minFillRate??0.5,this.scaleConstant=t?.scaleConstant??0.4,this.smooth=t?.smooth??0.8,this.lastThrottleTime=this.getCurrentTimeInSeconds(),this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds()),this.fillRate=this.minFillRate,this.maxCapacity=this.minCapacity}async getSendToken(){return this.acquireTokenBucket(1)}updateClientSendingRate(t){let n;this.updateMeasuredRate();let s=t;if(s?.errorType==="THROTTLING"||Kr(s?.error??t)){let i=!this.enabled?this.measuredTxRate:Math.min(this.measuredTxRate,this.fillRate);this.lastMaxRate=i,this.calculateTimeWindow(),this.lastThrottleTime=this.getCurrentTimeInSeconds(),n=this.cubicThrottle(i),this.enableTokenBucket()}else this.calculateTimeWindow(),n=this.cubicSuccess(this.getCurrentTimeInSeconds());let e=Math.min(n,2*this.measuredTxRate);this.updateTokenBucketRate(e)}getCurrentTimeInSeconds(){return Date.now()/1000}async acquireTokenBucket(t){if(!this.enabled)return;this.refillTokenBucket();while(t>this.availableTokens){let n=(t-this.availableTokens)/this.fillRate*1000;await new Promise((s)=>jr.setTimeoutFn(s,n)),this.refillTokenBucket()}this.availableTokens=this.availableTokens-t}refillTokenBucket(){let t=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=t;return}let n=(t-this.lastTimestamp)*this.fillRate;this.availableTokens=Math.min(this.maxCapacity,this.availableTokens+n),this.lastTimestamp=t}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,0.3333333333333333))}cubicThrottle(t){return this.getPrecise(t*this.beta)}cubicSuccess(t){return this.getPrecise(this.scaleConstant*Math.pow(t-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(t){this.refillTokenBucket(),this.fillRate=Math.max(t,this.minFillRate),this.maxCapacity=Math.max(t,this.minCapacity),this.availableTokens=Math.min(this.availableTokens,this.maxCapacity)}updateMeasuredRate(){let t=this.getCurrentTimeInSeconds(),n=Math.floor(t*2)/2;if(this.requestCount++,n>this.lastTxRateBucket){let s=this.requestCount/(n-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(s*this.smooth+this.measuredTxRate*(1-this.smooth)),this.requestCount=0,this.lastTxRateBucket=n}}getPrecise(t){return parseFloat(t.toFixed(8))}}class ct{static v2026=typeof process<"u"&&process.env?.SMITHY_NEW_RETRIES_2026==="true";static delay(){return ct.v2026?50:100}static throttlingDelay(){return ct.v2026?1000:500}static cost(){return ct.v2026?14:5}static throttlingCost(){return ct.v2026?5:10}static modifiedCostType(){return ct.v2026?"THROTTLING":"TRANSIENT"}}class V_{x=ct.delay();computeNextBackoffDelay(t){let n=Math.random(),s=2,r=n*Math.min(this.x*2**t,gi);return Math.floor(r)}setDelayBase(t){this.x=t}}class cc{delay;count;cost;longPoll;$retryLog={acquisitionDelay:0};constructor(t,n,s,r){this.delay=t,this.count=n,this.cost=s,this.longPoll=r}getRetryCount(){return this.count}getRetryDelay(){return Math.min(gi,this.delay)}getRetryCost(){return this.cost}isLongPoll(){return this.longPoll}}var Sn;(function(t){t.STANDARD="standard",t.ADAPTIVE="adaptive"})(Sn||(Sn={}));var ls=3,j_=Sn.STANDARD,Ai={incompatible:1,attempts:2,capacity:3},ar=class{mode=Sn.STANDARD;retryBackoffStrategy;capacity=di;maxAttemptsProvider;baseDelay;constructor(n){if(typeof n==="number")this.maxAttemptsProvider=async()=>n;else if(typeof n==="function")this.maxAttemptsProvider=n;else if(n&&typeof n==="object")this.maxAttemptsProvider=async()=>n.maxAttempts,this.baseDelay=n.baseDelay,this.retryBackoffStrategy=n.backoff;this.maxAttemptsProvider??=async()=>ls,this.baseDelay??=ct.delay(),this.retryBackoffStrategy??=new V_}async acquireInitialRetryToken(n){return new cc(ct.delay(),0,void 0,ct.v2026&&n.includes(":longpoll"))}async refreshRetryTokenForRetry(n,s){let r=await this.getMaxAttempts(),e=this.retryCode(n,s,r),i=e===0,f=n.isLongPoll?.();if(i||f){let o=s.errorType;this.retryBackoffStrategy.setDelayBase(o==="THROTTLING"?ct.throttlingDelay():this.baseDelay);let c=this.retryBackoffStrategy.computeNextBackoffDelay(n.getRetryCount()),h=c;if(s.retryAfterHint instanceof Date)h=Math.max(c,Math.min(s.retryAfterHint.getTime()-Date.now(),c+5000));if(!i){let u=ct.v2026&&e===Ai.capacity&&f?h:0;if(u>0)await new Promise((l)=>setTimeout(l,u))}else{let u=this.getCapacityCost(o);this.capacity-=u;let l=new cc(0,n.getRetryCount()+1,u,n.isLongPoll?.()??!1);return await new Promise((_)=>setTimeout(_,h)),l.$retryLog.acquisitionDelay=h,l}}throw Error("No retry token available")}recordSuccess(n){this.capacity=Math.min(di,this.capacity+(n.getRetryCost()??_c))}getCapacity(){return this.capacity}async maxAttempts(){return this.maxAttemptsProvider()}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch(n){return console.warn(`Max attempts provider could not resolve. Using default of ${ls}`),ls}}retryCode(n,s,r){let e=n.getRetryCount()+1,i=this.isRetryableError(s.errorType)?0:Ai.incompatible,f=e<r?0:Ai.attempts,o=this.capacity>=this.getCapacityCost(s.errorType)?0:Ai.capacity;return i||f||o}getCapacityCost(n){return n===ct.modifiedCostType()?ct.throttlingCost():ct.cost()}isRetryableError(n){return n==="THROTTLING"||n==="TRANSIENT"}},p_=class{mode=Sn.ADAPTIVE;rateLimiter;standardRetryStrategy;constructor(n,s){let{rateLimiter:r}=s??{};this.rateLimiter=r??new jr,this.standardRetryStrategy=s?new ar({maxAttempts:typeof n==="number"?n:3,...s}):new ar(n)}async acquireInitialRetryToken(n){let s=await this.standardRetryStrategy.acquireInitialRetryToken(n);return await this.rateLimiter.getSendToken(),s}async refreshRetryTokenForRetry(n,s){this.rateLimiter.updateClientSendingRate(s);let r=await this.standardRetryStrategy.refreshRetryTokenForRetry(n,s);return await this.rateLimiter.getSendToken(),r}recordSuccess(n){this.rateLimiter.updateClientSendingRate({}),this.standardRetryStrategy.recordSuccess(n)}async maxAttemptsProvider(){return this.standardRetryStrategy.maxAttempts()}};class v_ extends ar{computeNextBackoffDelay;constructor(t,n=ct.delay()){super(typeof t==="function"?t:async()=>t);if(typeof n==="number")this.computeNextBackoffDelay=()=>n;else this.computeNextBackoffDelay=n;this.retryBackoffStrategy.computeNextBackoffDelay=(s)=>{let r=s+1;return this.computeNextBackoffDelay(r)}}}var JL=(t,n)=>{let s=t,r=_c,e=k_,i=X_,f=t,o=(l)=>l.name==="TimeoutError"?i:e,c=(l)=>o(l)<=f;return Object.freeze({hasRetryTokens:c,retrieveRetryTokens:(l)=>{if(!c(l))throw Error("No retry token available");let _=o(l);return f-=_,_},releaseRetryTokens:(l)=>{f+=l??r,f=Math.min(f,s)}})},Z_=(t,n)=>Math.floor(Math.min(gi,Math.random()*2**n*t)),tw=(t)=>{if(!t)return!1;return lc(t)||D_(t)||Kr(t)||Vr(t)};class wc{maxAttemptsProvider;retryDecider;delayDecider;retryQuota;mode=Sn.STANDARD;constructor(t,n){this.maxAttemptsProvider=t,this.retryDecider=n?.retryDecider??tw,this.delayDecider=n?.delayDecider??Z_,this.retryQuota=n?.retryQuota??JL(di)}shouldRetry(t,n,s){return n<s&&this.retryDecider(t)&&this.retryQuota.hasRetryTokens(t)}async getMaxAttempts(){let t;try{t=await this.maxAttemptsProvider()}catch(n){t=ls}return t}async retry(t,n,s){let r,e=0,i=0,f=await this.getMaxAttempts(),{request:o}=n;if(Mi.isInstance(o))o.headers[Ei]=H_();while(!0)try{if(Mi.isInstance(o))o.headers[Ri]=`attempt=${e+1}; max=${f}`;if(s?.beforeRequest)await s.beforeRequest();let{response:c,output:h}=await t(n);if(s?.afterRequest)s.afterRequest(c);return this.retryQuota.releaseRetryTokens(r),h.$metadata.attempts=e+1,h.$metadata.totalRetryDelay=i,{response:c,output:h}}catch(c){let h=C_(c);if(e++,this.shouldRetry(h,e,f)){r=this.retryQuota.retrieveRetryTokens(h);let u=this.delayDecider(Kr(h)?z_:J_,e),l=zL(h.$response),_=Math.max(l||0,u);i+=_,await new Promise((w)=>setTimeout(w,_));continue}if(!h.$metadata)h.$metadata={};throw h.$metadata.attempts=e,h.$metadata.totalRetryDelay=i,h}}}var zL=(t)=>{if(!P_.isInstance(t))return;let n=Object.keys(t.headers).find((i)=>i.toLowerCase()==="retry-after");if(!n)return;let s=t.headers[n],r=Number(s);if(!Number.isNaN(r))return Math.min(r*1000,20000);let e=new Date(s);return Math.min(e.getTime()-Date.now(),20000)};class nw extends wc{rateLimiter;constructor(t,n){let{rateLimiter:s,...r}=n??{};super(t,r);this.rateLimiter=s??new jr,this.mode=Sn.ADAPTIVE}async retry(t,n){return super.retry(t,n,{beforeRequest:async()=>{return this.rateLimiter.getSendToken()},afterRequest:(s)=>{this.rateLimiter.updateClientSendingRate(s)}})}}var hc="AWS_MAX_ATTEMPTS",uc="max_attempts",kL={environmentVariableSelector:(t)=>{let n=t[hc];if(!n)return;let s=parseInt(n);if(Number.isNaN(s))throw Error(`Environment variable ${hc} mast be a number, got "${n}"`);return s},configFileSelector:(t)=>{let n=t[uc];if(!n)return;let s=parseInt(n);if(Number.isNaN(s))throw Error(`Shared config file entry ${uc} mast be a number, got "${n}"`);return s},default:ls},XL=(t,n)=>{let{retryStrategy:s,retryMode:r}=t,{defaultMaxAttempts:e=ls,defaultBaseDelay:i=ct.delay()}=n??{},f=F_(t.maxAttempts??e),o=s?Promise.resolve(s):void 0,c=async()=>{let h=await f();if(await F_(r)()===Sn.ADAPTIVE)return new p_(f,{maxAttempts:h,baseDelay:i});return new ar({maxAttempts:h,baseDelay:i})};return Object.assign(t,{maxAttempts:f,retryStrategy:()=>o??=c()})},sw="AWS_RETRY_MODE",rw="retry_mode",qL={environmentVariableSelector:(t)=>t[sw],configFileSelector:(t)=>t[rw],default:j_},ew=()=>(t)=>async(n)=>{let{request:s}=n;if(Mi.isInstance(s))delete s.headers[Ei],delete s.headers[Ri];return t(n)},iw={name:"omitRetryHeadersMiddleware",tags:["RETRY","HEADERS","OMIT_RETRY_HEADERS"],relation:"before",toMiddleware:"awsAuthMiddleware",override:!0},CL=(t)=>({applyToStack:(n)=>{n.addRelativeTo(ew(),iw)}}),aL=a_(N_),KL=QL(N_);VL.AdaptiveRetryStrategy=p_;VL.CONFIG_MAX_ATTEMPTS=uc;VL.CONFIG_RETRY_MODE=rw;VL.ConfiguredRetryStrategy=v_;VL.DEFAULT_MAX_ATTEMPTS=ls;VL.DEFAULT_RETRY_DELAY_BASE=J_;VL.DEFAULT_RETRY_MODE=j_;VL.DefaultRateLimiter=jr;VL.DeprecatedAdaptiveRetryStrategy=nw;VL.DeprecatedStandardRetryStrategy=wc;VL.ENV_MAX_ATTEMPTS=hc;VL.ENV_RETRY_MODE=sw;VL.INITIAL_RETRY_TOKENS=di;VL.INVOCATION_ID_HEADER=Ei;VL.MAXIMUM_RETRY_DELAY=gi;VL.NODE_MAX_ATTEMPT_CONFIG_OPTIONS=kL;VL.NODE_RETRY_MODE_CONFIG_OPTIONS=qL;VL.NO_RETRY_INCREMENT=_c;VL.REQUEST_HEADER=Ri;VL.RETRY_COST=k_;VL.RETRY_MODES=Sn;VL.Retry=ct;VL.StandardRetryStrategy=ar;VL.THROTTLING_RETRY_DELAY_BASE=z_;VL.TIMEOUT_RETRY_COST=X_;VL.defaultDelayDecider=Z_;VL.defaultRetryDecider=tw;VL.getOmitRetryHeadersPlugin=CL;VL.getRetryAfterHint=NL;VL.getRetryPlugin=KL;VL.isBrowserNetworkError=Y_;VL.isClockSkewCorrectedError=W_;VL.isClockSkewError=D_;VL.isNodeJsHttp2TransientError=Q_;VL.isRetryableByTrait=lc;VL.isServerError=x_;VL.isThrottlingError=Kr;VL.isTransientError=Vr;VL.omitRetryHeadersMiddleware=ew;VL.omitRetryHeadersMiddlewareOptions=iw;VL.resolveRetryConfig=XL;VL.retryMiddleware=aL;VL.retryMiddlewareOptions=K_});var fw=K((xI)=>{var xn={REQUEST_ID:Symbol.for("_AWS_LAMBDA_REQUEST_ID"),X_RAY_TRACE_ID:Symbol.for("_AWS_LAMBDA_X_RAY_TRACE_ID"),TENANT_ID:Symbol.for("_AWS_LAMBDA_TENANT_ID"),TRACEPARENT:Symbol.for("_AWS_LAMBDA_TRACEPARENT"),TRACESTATE:Symbol.for("_AWS_LAMBDA_TRACESTATE"),BAGGAGE:Symbol.for("_AWS_LAMBDA_BAGGAGE")},Ac=["true","1"].includes(process.env?.AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA??"");if(!Ac)globalThis.awslambda=globalThis.awslambda||{};class bi{static PROTECTED_KEYS=xn;isProtectedKey(t){return Object.values(xn).includes(t)}getRequestId(){return this.get(xn.REQUEST_ID)??"-"}getXRayTraceId(){return this.get(xn.X_RAY_TRACE_ID)}getTenantId(){return this.get(xn.TENANT_ID)}getTraceparent(){return this.get(xn.TRACEPARENT)}getTracestate(){return this.get(xn.TRACESTATE)}getBaggage(){return this.get(xn.BAGGAGE)}}class ow extends bi{currentContext;getContext(){return this.currentContext}hasContext(){return this.currentContext!==void 0}get(t){return this.currentContext?.[t]}set(t,n){if(this.isProtectedKey(t))throw Error(`Cannot modify protected Lambda context field: ${String(t)}`);this.currentContext=this.currentContext||{},this.currentContext[t]=n}run(t,n){return this.currentContext=t,n()}}class dc extends bi{als;static async create(){let t=new dc,n=await import("async_hooks");return t.als=new n.AsyncLocalStorage,t}getContext(){return this.als.getStore()}hasContext(){return this.als.getStore()!==void 0}get(t){return this.als.getStore()?.[t]}set(t,n){if(this.isProtectedKey(t))throw Error(`Cannot modify protected Lambda context field: ${String(t)}`);let s=this.als.getStore();if(!s)throw Error("No context available");s[t]=n}run(t,n){return this.als.run(t,n)}}xI.InvokeStore=void 0;(function(t){let n=null;async function s(r){if(!n)n=(async()=>{let i=r===!0||"AWS_LAMBDA_MAX_CONCURRENCY"in process.env?await dc.create():new ow;if(!Ac&&globalThis.awslambda?.InvokeStore)return globalThis.awslambda.InvokeStore;else if(!Ac&&globalThis.awslambda)return globalThis.awslambda.InvokeStore=i,i;else return i})();return n}t.getInstanceAsync=s,t._testing=process.env.AWS_LAMBDA_BENCHMARK_MODE==="1"?{reset:()=>{if(n=null,globalThis.awslambda?.InvokeStore)delete globalThis.awslambda.InvokeStore;globalThis.awslambda={InvokeStore:void 0}}}:void 0})(xI.InvokeStore||(xI.InvokeStore={}));xI.InvokeStoreBase=bi});var Qn=K((sO)=>{var{getSmithyContext:gc}=tn();sO.getSmithyContext=gc;var{HttpRequest:Ec}=Tt(),{requestBuilder:JI}=Tt();sO.requestBuilder=JI;var{HttpApiKeyAuthLocation:cw}=es(),zI=(t,n)=>{if(!n||n.length===0)return t;let s=[];for(let r of n)for(let e of t)if(e.schemeId.split("#")[1]===r)s.push(e);for(let r of t)if(!s.find(({schemeId:e})=>e===r.schemeId))s.push(r);return s};function kI(t){let n=new Map;for(let s of t)n.set(s.schemeId,s);return n}var Rc=(t,n)=>(s,r)=>async(e)=>{let i=t.httpAuthSchemeProvider(await n.httpAuthSchemeParametersProvider(t,r,e.input)),f=t.authSchemePreference?await t.authSchemePreference():[],o=zI(i,f),c=kI(t.httpAuthSchemes),h=gc(r),u=[];for(let l of o){let _=c.get(l.schemeId);if(!_){u.push(`HttpAuthScheme \`${l.schemeId}\` was not enabled for this service.`);continue}let w=_.identityProvider(await n.identityProviderConfigProvider(t));if(!w){u.push(`HttpAuthScheme \`${l.schemeId}\` did not have an IdentityProvider configured.`);continue}let{identityProperties:A={},signingProperties:M={}}=l.propertiesExtractor?.(t,r)||{};l.identityProperties=Object.assign(l.identityProperties||{},A),l.signingProperties=Object.assign(l.signingProperties||{},M),h.selectedHttpAuthScheme={httpAuthOption:l,identity:await w(l.identityProperties),signer:_.signer};break}if(!h.selectedHttpAuthScheme)throw Error(u.join(`
23
- `));return s(e)},hw={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},XI=(t,{httpAuthSchemeParametersProvider:n,identityProviderConfigProvider:s})=>({applyToStack:(r)=>{r.addRelativeTo(Rc(t,{httpAuthSchemeParametersProvider:n,identityProviderConfigProvider:s}),hw)}}),uw={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"serializerMiddleware"},qI=(t,{httpAuthSchemeParametersProvider:n,identityProviderConfigProvider:s})=>({applyToStack:(r)=>{r.addRelativeTo(Rc(t,{httpAuthSchemeParametersProvider:n,identityProviderConfigProvider:s}),uw)}}),CI=(t)=>(n)=>{throw n},aI=(t,n)=>{},lw=(t)=>(n,s)=>async(r)=>{if(!Ec.isInstance(r.request))return n(r);let i=gc(s).selectedHttpAuthScheme;if(!i)throw Error("No HttpAuthScheme was selected: unable to sign request");let{httpAuthOption:{signingProperties:f={}},identity:o,signer:c}=i,h=await n({...r,request:await c.sign(r.request,o,f)}).catch((c.errorHandler||CI)(f));return(c.successHandler||aI)(h.response,f),h},_w={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},KI=(t)=>({applyToStack:(n)=>{n.addRelativeTo(lw(),_w)}}),VI=(t)=>{if(typeof t==="function")return t;let n=Promise.resolve(t);return()=>n},jI=async(t,n,s,r=(i)=>i,...e)=>{let i=new t(s);return i=r(i)??i,await n.send(i,...e)};function pI(t,n,s,r,e){return async function*(f,o,...c){let h=o,u=f.startingToken??h[s],l=!0,_;while(l){if(h[s]=u,e)h[e]=h[e]??f.pageSize;if(f.client instanceof t)_=await jI(n,f.client,o,f.withCommand,...c);else throw Error(`Invalid client, expected instance of ${t.name}`);yield _;let w=u;u=vI(_,r),l=!!(u&&(!f.stopOnSameToken||u!==w))}return}}var vI=(t,n)=>{let s=t,r=n.split(".");for(let e of r){if(!s||typeof s!=="object")return;s=s[e]}return s};function ZI(t,n,s){if(!t.__smithy_context)t.__smithy_context={features:{}};else if(!t.__smithy_context.features)t.__smithy_context.features={};t.__smithy_context.features[n]=s}class ww{authSchemes=new Map;constructor(t){for(let n in t){let s=t[n];if(s!==void 0)this.authSchemes.set(n,s)}}getIdentityProvider(t){return this.authSchemes.get(t)}}class Aw{async sign(t,n,s){if(!s)throw Error("request could not be signed with `apiKey` since the `name` and `in` signer properties are missing");if(!s.name)throw Error("request could not be signed with `apiKey` since the `name` signer property is missing");if(!s.in)throw Error("request could not be signed with `apiKey` since the `in` signer property is missing");if(!n.apiKey)throw Error("request could not be signed with `apiKey` since the `apiKey` is not defined");let r=Ec.clone(t);if(s.in===cw.QUERY)r.query[s.name]=n.apiKey;else if(s.in===cw.HEADER)r.headers[s.name]=s.scheme?`${s.scheme} ${n.apiKey}`:n.apiKey;else throw Error("request can only be signed with `apiKey` locations `query` or `header`, but found: `"+s.in+"`");return r}}class Mw{async sign(t,n,s){let r=Ec.clone(t);if(!n.token)throw Error("request could not be signed with `token` since the `token` is not defined");return r.headers.Authorization=`Bearer ${n.token}`,r}}class dw{async sign(t,n,s){return t}}var gw=(t)=>function(s){return Rw(s)&&s.expiration.getTime()-Date.now()<t},Ew=300000,tO=gw(Ew),Rw=(t)=>t.expiration!==void 0,nO=(t,n,s)=>{if(t===void 0)return;let r=typeof t!=="function"?async()=>Promise.resolve(t):t,e,i,f,o=!1,c=async(h)=>{if(!i)i=r(h);try{e=await i,f=!0,o=!1}finally{i=void 0}return e};if(n===void 0)return async(h)=>{if(!f||h?.forceRefresh)e=await c(h);return e};return async(h)=>{if(!f||h?.forceRefresh)e=await c(h);if(o)return e;if(!s(e))return o=!0,e;if(n(e))return await c(h),e;return e}};sO.DefaultIdentityProviderConfig=ww;sO.EXPIRATION_MS=Ew;sO.HttpApiKeyAuthSigner=Aw;sO.HttpBearerAuthSigner=Mw;sO.NoAuthSigner=dw;sO.createIsIdentityExpiredFunction=gw;sO.createPaginator=pI;sO.doesIdentityRequireRefresh=Rw;sO.getHttpAuthSchemeEndpointRuleSetPlugin=XI;sO.getHttpAuthSchemePlugin=qI;sO.getHttpSigningPlugin=KI;sO.httpAuthSchemeEndpointRuleSetMiddlewareOptions=hw;sO.httpAuthSchemeMiddleware=Rc;sO.httpAuthSchemeMiddlewareOptions=uw;sO.httpSigningMiddleware=lw;sO.httpSigningMiddlewareOptions=_w;sO.isIdentityExpired=tO;sO.memoizeIdentityProvider=nO;sO.normalizeProvider=VI;sO.setFeature=ZI});var bw=K((vr,bc)=>{(function(t,n){typeof vr=="object"&&typeof bc=="object"?bc.exports=n():typeof define=="function"&&define.amd?define([],n):typeof vr=="object"?vr.bowser=n():t.bowser=n()})(vr,function(){return function(t){var n={};function s(r){if(n[r])return n[r].exports;var e=n[r]={i:r,l:!1,exports:{}};return t[r].call(e.exports,e,e.exports,s),e.l=!0,e.exports}return s.m=t,s.c=n,s.d=function(r,e,i){s.o(r,e)||Object.defineProperty(r,e,{enumerable:!0,get:i})},s.r=function(r){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(r,"__esModule",{value:!0})},s.t=function(r,e){if(1&e&&(r=s(r)),8&e)return r;if(4&e&&typeof r=="object"&&r&&r.__esModule)return r;var i=Object.create(null);if(s.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:r}),2&e&&typeof r!="string")for(var f in r)s.d(i,f,function(o){return r[o]}.bind(null,f));return i},s.n=function(r){var e=r&&r.__esModule?function(){return r.default}:function(){return r};return s.d(e,"a",e),e},s.o=function(r,e){return Object.prototype.hasOwnProperty.call(r,e)},s.p="",s(s.s=90)}({17:function(t,n,s){n.__esModule=!0,n.default=void 0;var r=s(18),e=function(){function i(){}return i.getFirstMatch=function(f,o){var c=o.match(f);return c&&c.length>0&&c[1]||""},i.getSecondMatch=function(f,o){var c=o.match(f);return c&&c.length>1&&c[2]||""},i.matchAndReturnConst=function(f,o,c){if(f.test(o))return c},i.getWindowsVersionName=function(f){switch(f){case"NT":return"NT";case"XP":return"XP";case"NT 5.0":return"2000";case"NT 5.1":return"XP";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}},i.getMacOSVersionName=function(f){var o=f.split(".").splice(0,2).map(function(u){return parseInt(u,10)||0});o.push(0);var c=o[0],h=o[1];if(c===10)switch(h){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}switch(c){case 11:return"Big Sur";case 12:return"Monterey";case 13:return"Ventura";case 14:return"Sonoma";case 15:return"Sequoia";default:return}},i.getAndroidVersionName=function(f){var o=f.split(".").splice(0,2).map(function(c){return parseInt(c,10)||0});if(o.push(0),!(o[0]===1&&o[1]<5))return o[0]===1&&o[1]<6?"Cupcake":o[0]===1&&o[1]>=6?"Donut":o[0]===2&&o[1]<2?"Eclair":o[0]===2&&o[1]===2?"Froyo":o[0]===2&&o[1]>2?"Gingerbread":o[0]===3?"Honeycomb":o[0]===4&&o[1]<1?"Ice Cream Sandwich":o[0]===4&&o[1]<4?"Jelly Bean":o[0]===4&&o[1]>=4?"KitKat":o[0]===5?"Lollipop":o[0]===6?"Marshmallow":o[0]===7?"Nougat":o[0]===8?"Oreo":o[0]===9?"Pie":void 0},i.getVersionPrecision=function(f){return f.split(".").length},i.compareVersions=function(f,o,c){c===void 0&&(c=!1);var h=i.getVersionPrecision(f),u=i.getVersionPrecision(o),l=Math.max(h,u),_=0,w=i.map([f,o],function(A){var M=l-i.getVersionPrecision(A),d=A+Array(M+1).join(".0");return i.map(d.split("."),function(E){return Array(20-E.length).join("0")+E}).reverse()});for(c&&(_=l-Math.min(h,u)),l-=1;l>=_;){if(w[0][l]>w[1][l])return 1;if(w[0][l]===w[1][l]){if(l===_)return 0;l-=1}else if(w[0][l]<w[1][l])return-1}},i.map=function(f,o){var c,h=[];if(Array.prototype.map)return Array.prototype.map.call(f,o);for(c=0;c<f.length;c+=1)h.push(o(f[c]));return h},i.find=function(f,o){var c,h;if(Array.prototype.find)return Array.prototype.find.call(f,o);for(c=0,h=f.length;c<h;c+=1){var u=f[c];if(o(u,c))return u}},i.assign=function(f){for(var o,c,h=f,u=arguments.length,l=Array(u>1?u-1:0),_=1;_<u;_++)l[_-1]=arguments[_];if(Object.assign)return Object.assign.apply(Object,[f].concat(l));var w=function(){var A=l[o];typeof A=="object"&&A!==null&&Object.keys(A).forEach(function(M){h[M]=A[M]})};for(o=0,c=l.length;o<c;o+=1)w();return f},i.getBrowserAlias=function(f){return r.BROWSER_ALIASES_MAP[f]},i.getBrowserTypeByAlias=function(f){return r.BROWSER_MAP[f]||""},i}();n.default=e,t.exports=n.default},18:function(t,n,s){n.__esModule=!0,n.ENGINE_MAP=n.OS_MAP=n.PLATFORMS_MAP=n.BROWSER_MAP=n.BROWSER_ALIASES_MAP=void 0,n.BROWSER_ALIASES_MAP={AmazonBot:"amazonbot","Amazon Silk":"amazon_silk","Android Browser":"android",BaiduSpider:"baiduspider",Bada:"bada",BingCrawler:"bingcrawler",Brave:"brave",BlackBerry:"blackberry","ChatGPT-User":"chatgpt_user",Chrome:"chrome",ClaudeBot:"claudebot",Chromium:"chromium",Diffbot:"diffbot",DuckDuckBot:"duckduckbot",DuckDuckGo:"duckduckgo",Electron:"electron",Epiphany:"epiphany",FacebookExternalHit:"facebookexternalhit",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot",GPTBot:"gptbot","Internet Explorer":"ie",InternetArchiveCrawler:"internetarchivecrawler","K-Meleon":"k_meleon",LibreWolf:"librewolf",Linespider:"linespider",Maxthon:"maxthon","Meta-ExternalAds":"meta_externalads","Meta-ExternalAgent":"meta_externalagent","Meta-ExternalFetcher":"meta_externalfetcher","Meta-WebIndexer":"meta_webindexer","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver","OAI-SearchBot":"oai_searchbot",Omgilibot:"omgilibot",Opera:"opera","Opera Coast":"opera_coast","Pale Moon":"pale_moon",PerplexityBot:"perplexitybot","Perplexity-User":"perplexity_user",PhantomJS:"phantomjs",PingdomBot:"pingdombot",Puffin:"puffin",QQ:"qq",QQLite:"qqlite",QupZilla:"qupzilla",Roku:"roku",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SlackBot:"slackbot",SeaMonkey:"seamonkey",Sleipnir:"sleipnir","Sogou Browser":"sogou",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat",YahooSlurp:"yahooslurp","Yandex Browser":"yandex",YandexBot:"yandexbot",YouBot:"youbot"},n.BROWSER_MAP={amazonbot:"AmazonBot",amazon_silk:"Amazon Silk",android:"Android Browser",baiduspider:"BaiduSpider",bada:"Bada",bingcrawler:"BingCrawler",blackberry:"BlackBerry",brave:"Brave",chatgpt_user:"ChatGPT-User",chrome:"Chrome",claudebot:"ClaudeBot",chromium:"Chromium",diffbot:"Diffbot",duckduckbot:"DuckDuckBot",duckduckgo:"DuckDuckGo",edge:"Microsoft Edge",electron:"Electron",epiphany:"Epiphany",facebookexternalhit:"FacebookExternalHit",firefox:"Firefox",focus:"Focus",generic:"Generic",google_search:"Google Search",googlebot:"Googlebot",gptbot:"GPTBot",ie:"Internet Explorer",internetarchivecrawler:"InternetArchiveCrawler",k_meleon:"K-Meleon",librewolf:"LibreWolf",linespider:"Linespider",maxthon:"Maxthon",meta_externalads:"Meta-ExternalAds",meta_externalagent:"Meta-ExternalAgent",meta_externalfetcher:"Meta-ExternalFetcher",meta_webindexer:"Meta-WebIndexer",mz:"MZ Browser",naver:"NAVER Whale Browser",oai_searchbot:"OAI-SearchBot",omgilibot:"Omgilibot",opera:"Opera",opera_coast:"Opera Coast",pale_moon:"Pale Moon",perplexitybot:"PerplexityBot",perplexity_user:"Perplexity-User",phantomjs:"PhantomJS",pingdombot:"PingdomBot",puffin:"Puffin",qq:"QQ Browser",qqlite:"QQ Browser Lite",qupzilla:"QupZilla",roku:"Roku",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",slackbot:"SlackBot",sleipnir:"Sleipnir",sogou:"Sogou Browser",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yahooslurp:"YahooSlurp",yandex:"Yandex Browser",yandexbot:"YandexBot",youbot:"YouBot"},n.PLATFORMS_MAP={bot:"bot",desktop:"desktop",mobile:"mobile",tablet:"tablet",tv:"tv"},n.OS_MAP={Android:"Android",Bada:"Bada",BlackBerry:"BlackBerry",ChromeOS:"Chrome OS",HarmonyOS:"HarmonyOS",iOS:"iOS",Linux:"Linux",MacOS:"macOS",PlayStation4:"PlayStation 4",Roku:"Roku",Tizen:"Tizen",WebOS:"WebOS",Windows:"Windows",WindowsPhone:"Windows Phone"},n.ENGINE_MAP={Blink:"Blink",EdgeHTML:"EdgeHTML",Gecko:"Gecko",Presto:"Presto",Trident:"Trident",WebKit:"WebKit"}},90:function(t,n,s){n.__esModule=!0,n.default=void 0;var r,e=(r=s(91))&&r.__esModule?r:{default:r},i=s(18);function f(c,h){for(var u=0;u<h.length;u++){var l=h[u];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(c,l.key,l)}}var o=function(){function c(){}var h,u,l;return c.getParser=function(_,w,A){if(w===void 0&&(w=!1),A===void 0&&(A=null),typeof _!="string")throw Error("UserAgent should be a string");return new e.default(_,w,A)},c.parse=function(_,w){return w===void 0&&(w=null),new e.default(_,w).getResult()},h=c,l=[{key:"BROWSER_MAP",get:function(){return i.BROWSER_MAP}},{key:"ENGINE_MAP",get:function(){return i.ENGINE_MAP}},{key:"OS_MAP",get:function(){return i.OS_MAP}},{key:"PLATFORMS_MAP",get:function(){return i.PLATFORMS_MAP}}],(u=null)&&f(h.prototype,u),l&&f(h,l),c}();n.default=o,t.exports=n.default},91:function(t,n,s){n.__esModule=!0,n.default=void 0;var r=c(s(92)),e=c(s(93)),i=c(s(94)),f=c(s(95)),o=c(s(17));function c(u){return u&&u.__esModule?u:{default:u}}var h=function(){function u(_,w,A){if(w===void 0&&(w=!1),A===void 0&&(A=null),_==null||_==="")throw Error("UserAgent parameter can't be empty");this._ua=_;var M=!1;typeof w=="boolean"?(M=w,this._hints=A):this._hints=w!=null&&typeof w=="object"?w:null,this.parsedResult={},M!==!0&&this.parse()}var l=u.prototype;return l.getHints=function(){return this._hints},l.hasBrand=function(_){if(!this._hints||!Array.isArray(this._hints.brands))return!1;var w=_.toLowerCase();return this._hints.brands.some(function(A){return A.brand&&A.brand.toLowerCase()===w})},l.getBrandVersion=function(_){if(this._hints&&Array.isArray(this._hints.brands)){var w=_.toLowerCase(),A=this._hints.brands.find(function(M){return M.brand&&M.brand.toLowerCase()===w});return A?A.version:void 0}},l.getUA=function(){return this._ua},l.test=function(_){return _.test(this._ua)},l.parseBrowser=function(){var _=this;this.parsedResult.browser={};var w=o.default.find(r.default,function(A){if(typeof A.test=="function")return A.test(_);if(Array.isArray(A.test))return A.test.some(function(M){return _.test(M)});throw Error("Browser's test function is not valid")});return w&&(this.parsedResult.browser=w.describe(this.getUA(),this)),this.parsedResult.browser},l.getBrowser=function(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()},l.getBrowserName=function(_){return _?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""},l.getBrowserVersion=function(){return this.getBrowser().version},l.getOS=function(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()},l.parseOS=function(){var _=this;this.parsedResult.os={};var w=o.default.find(e.default,function(A){if(typeof A.test=="function")return A.test(_);if(Array.isArray(A.test))return A.test.some(function(M){return _.test(M)});throw Error("Browser's test function is not valid")});return w&&(this.parsedResult.os=w.describe(this.getUA())),this.parsedResult.os},l.getOSName=function(_){var w=this.getOS().name;return _?String(w).toLowerCase()||"":w||""},l.getOSVersion=function(){return this.getOS().version},l.getPlatform=function(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()},l.getPlatformType=function(_){_===void 0&&(_=!1);var w=this.getPlatform().type;return _?String(w).toLowerCase()||"":w||""},l.parsePlatform=function(){var _=this;this.parsedResult.platform={};var w=o.default.find(i.default,function(A){if(typeof A.test=="function")return A.test(_);if(Array.isArray(A.test))return A.test.some(function(M){return _.test(M)});throw Error("Browser's test function is not valid")});return w&&(this.parsedResult.platform=w.describe(this.getUA())),this.parsedResult.platform},l.getEngine=function(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()},l.getEngineName=function(_){return _?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""},l.parseEngine=function(){var _=this;this.parsedResult.engine={};var w=o.default.find(f.default,function(A){if(typeof A.test=="function")return A.test(_);if(Array.isArray(A.test))return A.test.some(function(M){return _.test(M)});throw Error("Browser's test function is not valid")});return w&&(this.parsedResult.engine=w.describe(this.getUA())),this.parsedResult.engine},l.parse=function(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this},l.getResult=function(){return o.default.assign({},this.parsedResult)},l.satisfies=function(_){var w=this,A={},M=0,d={},E=0;if(Object.keys(_).forEach(function(Q){var rt=_[Q];typeof rt=="string"?(d[Q]=rt,E+=1):typeof rt=="object"&&(A[Q]=rt,M+=1)}),M>0){var b=Object.keys(A),L=o.default.find(b,function(Q){return w.isOS(Q)});if(L){var S=this.satisfies(A[L]);if(S!==void 0)return S}var O=o.default.find(b,function(Q){return w.isPlatform(Q)});if(O){var x=this.satisfies(A[O]);if(x!==void 0)return x}}if(E>0){var X=Object.keys(d),v=o.default.find(X,function(Q){return w.isBrowser(Q,!0)});if(v!==void 0)return this.compareVersion(d[v])}},l.isBrowser=function(_,w){w===void 0&&(w=!1);var A=this.getBrowserName().toLowerCase(),M=_.toLowerCase(),d=o.default.getBrowserTypeByAlias(M);return w&&d&&(M=d.toLowerCase()),M===A},l.compareVersion=function(_){var w=[0],A=_,M=!1,d=this.getBrowserVersion();if(typeof d=="string")return _[0]===">"||_[0]==="<"?(A=_.substr(1),_[1]==="="?(M=!0,A=_.substr(2)):w=[],_[0]===">"?w.push(1):w.push(-1)):_[0]==="="?A=_.substr(1):_[0]==="~"&&(M=!0,A=_.substr(1)),w.indexOf(o.default.compareVersions(d,A,M))>-1},l.isOS=function(_){return this.getOSName(!0)===String(_).toLowerCase()},l.isPlatform=function(_){return this.getPlatformType(!0)===String(_).toLowerCase()},l.isEngine=function(_){return this.getEngineName(!0)===String(_).toLowerCase()},l.is=function(_,w){return w===void 0&&(w=!1),this.isBrowser(_,w)||this.isOS(_)||this.isPlatform(_)},l.some=function(_){var w=this;return _===void 0&&(_=[]),_.some(function(A){return w.is(A)})},u}();n.default=h,t.exports=n.default},92:function(t,n,s){n.__esModule=!0,n.default=void 0;var r,e=(r=s(17))&&r.__esModule?r:{default:r},i=/version\/(\d+(\.?_?\d+)+)/i,f=[{test:[/gptbot/i],describe:function(o){var c={name:"GPTBot"},h=e.default.getFirstMatch(/gptbot\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/chatgpt-user/i],describe:function(o){var c={name:"ChatGPT-User"},h=e.default.getFirstMatch(/chatgpt-user\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/oai-searchbot/i],describe:function(o){var c={name:"OAI-SearchBot"},h=e.default.getFirstMatch(/oai-searchbot\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(o){var c={name:"ClaudeBot"},h=e.default.getFirstMatch(/(?:claudebot|claude-web|claude-user|claude-searchbot)\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(o){var c={name:"Omgilibot"},h=e.default.getFirstMatch(/(?:omgilibot|webzio-extended)\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/diffbot/i],describe:function(o){var c={name:"Diffbot"},h=e.default.getFirstMatch(/diffbot\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/perplexitybot/i],describe:function(o){var c={name:"PerplexityBot"},h=e.default.getFirstMatch(/perplexitybot\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/perplexity-user/i],describe:function(o){var c={name:"Perplexity-User"},h=e.default.getFirstMatch(/perplexity-user\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/youbot/i],describe:function(o){var c={name:"YouBot"},h=e.default.getFirstMatch(/youbot\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/meta-webindexer/i],describe:function(o){var c={name:"Meta-WebIndexer"},h=e.default.getFirstMatch(/meta-webindexer\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/meta-externalads/i],describe:function(o){var c={name:"Meta-ExternalAds"},h=e.default.getFirstMatch(/meta-externalads\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/meta-externalagent/i],describe:function(o){var c={name:"Meta-ExternalAgent"},h=e.default.getFirstMatch(/meta-externalagent\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/meta-externalfetcher/i],describe:function(o){var c={name:"Meta-ExternalFetcher"},h=e.default.getFirstMatch(/meta-externalfetcher\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/googlebot/i],describe:function(o){var c={name:"Googlebot"},h=e.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/linespider/i],describe:function(o){var c={name:"Linespider"},h=e.default.getFirstMatch(/(?:linespider)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/amazonbot/i],describe:function(o){var c={name:"AmazonBot"},h=e.default.getFirstMatch(/amazonbot\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/bingbot/i],describe:function(o){var c={name:"BingCrawler"},h=e.default.getFirstMatch(/bingbot\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/baiduspider/i],describe:function(o){var c={name:"BaiduSpider"},h=e.default.getFirstMatch(/baiduspider\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/duckduckbot/i],describe:function(o){var c={name:"DuckDuckBot"},h=e.default.getFirstMatch(/duckduckbot\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/ia_archiver/i],describe:function(o){var c={name:"InternetArchiveCrawler"},h=e.default.getFirstMatch(/ia_archiver\/(\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{name:"FacebookExternalHit"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(o){var c={name:"SlackBot"},h=e.default.getFirstMatch(/(?:slackbot|slack-imgproxy)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/yahoo!?[\s/]*slurp/i],describe:function(){return{name:"YahooSlurp"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe:function(){return{name:"YandexBot"}}},{test:[/pingdom/i],describe:function(){return{name:"PingdomBot"}}},{test:[/opera/i],describe:function(o){var c={name:"Opera"},h=e.default.getFirstMatch(i,o)||e.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/opr\/|opios/i],describe:function(o){var c={name:"Opera"},h=e.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/SamsungBrowser/i],describe:function(o){var c={name:"Samsung Internet for Android"},h=e.default.getFirstMatch(i,o)||e.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/Whale/i],describe:function(o){var c={name:"NAVER Whale Browser"},h=e.default.getFirstMatch(i,o)||e.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/PaleMoon/i],describe:function(o){var c={name:"Pale Moon"},h=e.default.getFirstMatch(i,o)||e.default.getFirstMatch(/(?:PaleMoon)[\s/](\d+(?:\.\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/MZBrowser/i],describe:function(o){var c={name:"MZ Browser"},h=e.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/focus/i],describe:function(o){var c={name:"Focus"},h=e.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/swing/i],describe:function(o){var c={name:"Swing"},h=e.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/coast/i],describe:function(o){var c={name:"Opera Coast"},h=e.default.getFirstMatch(i,o)||e.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(o){var c={name:"Opera Touch"},h=e.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/yabrowser/i],describe:function(o){var c={name:"Yandex Browser"},h=e.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/ucbrowser/i],describe:function(o){var c={name:"UC Browser"},h=e.default.getFirstMatch(i,o)||e.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/Maxthon|mxios/i],describe:function(o){var c={name:"Maxthon"},h=e.default.getFirstMatch(i,o)||e.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/epiphany/i],describe:function(o){var c={name:"Epiphany"},h=e.default.getFirstMatch(i,o)||e.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/puffin/i],describe:function(o){var c={name:"Puffin"},h=e.default.getFirstMatch(i,o)||e.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/sleipnir/i],describe:function(o){var c={name:"Sleipnir"},h=e.default.getFirstMatch(i,o)||e.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/k-meleon/i],describe:function(o){var c={name:"K-Meleon"},h=e.default.getFirstMatch(i,o)||e.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/micromessenger/i],describe:function(o){var c={name:"WeChat"},h=e.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/qqbrowser/i],describe:function(o){var c={name:/qqbrowserlite/i.test(o)?"QQ Browser Lite":"QQ Browser"},h=e.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/msie|trident/i],describe:function(o){var c={name:"Internet Explorer"},h=e.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/\sedg\//i],describe:function(o){var c={name:"Microsoft Edge"},h=e.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/edg([ea]|ios)/i],describe:function(o){var c={name:"Microsoft Edge"},h=e.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/vivaldi/i],describe:function(o){var c={name:"Vivaldi"},h=e.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/seamonkey/i],describe:function(o){var c={name:"SeaMonkey"},h=e.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/sailfish/i],describe:function(o){var c={name:"Sailfish"},h=e.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,o);return h&&(c.version=h),c}},{test:[/silk/i],describe:function(o){var c={name:"Amazon Silk"},h=e.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/phantom/i],describe:function(o){var c={name:"PhantomJS"},h=e.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/slimerjs/i],describe:function(o){var c={name:"SlimerJS"},h=e.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(o){var c={name:"BlackBerry"},h=e.default.getFirstMatch(i,o)||e.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/(web|hpw)[o0]s/i],describe:function(o){var c={name:"WebOS Browser"},h=e.default.getFirstMatch(i,o)||e.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/bada/i],describe:function(o){var c={name:"Bada"},h=e.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/tizen/i],describe:function(o){var c={name:"Tizen"},h=e.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/qupzilla/i],describe:function(o){var c={name:"QupZilla"},h=e.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/librewolf/i],describe:function(o){var c={name:"LibreWolf"},h=e.default.getFirstMatch(/(?:librewolf)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/firefox|iceweasel|fxios/i],describe:function(o){var c={name:"Firefox"},h=e.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/electron/i],describe:function(o){var c={name:"Electron"},h=e.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/sogoumobilebrowser/i,/metasr/i,/se 2\.[x]/i],describe:function(o){var c={name:"Sogou Browser"},h=e.default.getFirstMatch(/(?:sogoumobilebrowser)[\s/](\d+(\.?_?\d+)+)/i,o),u=e.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,o),l=e.default.getFirstMatch(/se ([\d.]+)x/i,o),_=h||u||l;return _&&(c.version=_),c}},{test:[/MiuiBrowser/i],describe:function(o){var c={name:"Miui"},h=e.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:function(o){return!!o.hasBrand("DuckDuckGo")||o.test(/\sDdg\/[\d.]+$/i)},describe:function(o,c){var h={name:"DuckDuckGo"};if(c){var u=c.getBrandVersion("DuckDuckGo");if(u)return h.version=u,h}var l=e.default.getFirstMatch(/\sDdg\/([\d.]+)$/i,o);return l&&(h.version=l),h}},{test:function(o){return o.hasBrand("Brave")},describe:function(o,c){var h={name:"Brave"};if(c){var u=c.getBrandVersion("Brave");if(u)return h.version=u,h}return h}},{test:[/chromium/i],describe:function(o){var c={name:"Chromium"},h=e.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,o)||e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/chrome|crios|crmo/i],describe:function(o){var c={name:"Chrome"},h=e.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/GSA/i],describe:function(o){var c={name:"Google Search"},h=e.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:function(o){var c=!o.test(/like android/i),h=o.test(/android/i);return c&&h},describe:function(o){var c={name:"Android Browser"},h=e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/playstation 4/i],describe:function(o){var c={name:"PlayStation 4"},h=e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/safari|applewebkit/i],describe:function(o){var c={name:"Safari"},h=e.default.getFirstMatch(i,o);return h&&(c.version=h),c}},{test:[/.*/i],describe:function(o){var c=o.search("\\(")!==-1?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:e.default.getFirstMatch(c,o),version:e.default.getSecondMatch(c,o)}}}];n.default=f,t.exports=n.default},93:function(t,n,s){n.__esModule=!0,n.default=void 0;var r,e=(r=s(17))&&r.__esModule?r:{default:r},i=s(18),f=[{test:[/Roku\/DVP/],describe:function(o){var c=e.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,o);return{name:i.OS_MAP.Roku,version:c}}},{test:[/windows phone/i],describe:function(o){var c=e.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,o);return{name:i.OS_MAP.WindowsPhone,version:c}}},{test:[/windows /i],describe:function(o){var c=e.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,o),h=e.default.getWindowsVersionName(c);return{name:i.OS_MAP.Windows,version:c,versionName:h}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(o){var c={name:i.OS_MAP.iOS},h=e.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,o);return h&&(c.version=h),c}},{test:[/macintosh/i],describe:function(o){var c=e.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,o).replace(/[_\s]/g,"."),h=e.default.getMacOSVersionName(c),u={name:i.OS_MAP.MacOS,version:c};return h&&(u.versionName=h),u}},{test:[/(ipod|iphone|ipad)/i],describe:function(o){var c=e.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,o).replace(/[_\s]/g,".");return{name:i.OS_MAP.iOS,version:c}}},{test:[/OpenHarmony/i],describe:function(o){var c=e.default.getFirstMatch(/OpenHarmony\s+(\d+(\.\d+)*)/i,o);return{name:i.OS_MAP.HarmonyOS,version:c}}},{test:function(o){var c=!o.test(/like android/i),h=o.test(/android/i);return c&&h},describe:function(o){var c=e.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,o),h=e.default.getAndroidVersionName(c),u={name:i.OS_MAP.Android,version:c};return h&&(u.versionName=h),u}},{test:[/(web|hpw)[o0]s/i],describe:function(o){var c=e.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,o),h={name:i.OS_MAP.WebOS};return c&&c.length&&(h.version=c),h}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(o){var c=e.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,o)||e.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,o)||e.default.getFirstMatch(/\bbb(\d+)/i,o);return{name:i.OS_MAP.BlackBerry,version:c}}},{test:[/bada/i],describe:function(o){var c=e.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,o);return{name:i.OS_MAP.Bada,version:c}}},{test:[/tizen/i],describe:function(o){var c=e.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,o);return{name:i.OS_MAP.Tizen,version:c}}},{test:[/linux/i],describe:function(){return{name:i.OS_MAP.Linux}}},{test:[/CrOS/],describe:function(){return{name:i.OS_MAP.ChromeOS}}},{test:[/PlayStation 4/],describe:function(o){var c=e.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,o);return{name:i.OS_MAP.PlayStation4,version:c}}}];n.default=f,t.exports=n.default},94:function(t,n,s){n.__esModule=!0,n.default=void 0;var r,e=(r=s(17))&&r.__esModule?r:{default:r},i=s(18),f=[{test:[/googlebot/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Google"}}},{test:[/linespider/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Line"}}},{test:[/amazonbot/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Amazon"}}},{test:[/gptbot/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/chatgpt-user/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/oai-searchbot/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/baiduspider/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Baidu"}}},{test:[/bingbot/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Bing"}}},{test:[/duckduckbot/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"DuckDuckGo"}}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Anthropic"}}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Webz.io"}}},{test:[/diffbot/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Diffbot"}}},{test:[/perplexitybot/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Perplexity AI"}}},{test:[/perplexity-user/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Perplexity AI"}}},{test:[/youbot/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"You.com"}}},{test:[/ia_archiver/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Internet Archive"}}},{test:[/meta-webindexer/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalads/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalagent/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalfetcher/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Slack"}}},{test:[/yahoo/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Yahoo"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Yandex"}}},{test:[/pingdom/i],describe:function(){return{type:i.PLATFORMS_MAP.bot,vendor:"Pingdom"}}},{test:[/huawei/i],describe:function(o){var c=e.default.getFirstMatch(/(can-l01)/i,o)&&"Nova",h={type:i.PLATFORMS_MAP.mobile,vendor:"Huawei"};return c&&(h.model=c),h}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return{type:i.PLATFORMS_MAP.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe:function(){return{type:i.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(){return{type:i.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe:function(){return{type:i.PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe:function(){return{type:i.PLATFORMS_MAP.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe:function(){return{type:i.PLATFORMS_MAP.tablet}}},{test:function(o){var c=o.test(/ipod|iphone/i),h=o.test(/like (ipod|iphone)/i);return c&&!h},describe:function(o){var c=e.default.getFirstMatch(/(ipod|iphone)/i,o);return{type:i.PLATFORMS_MAP.mobile,vendor:"Apple",model:c}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:i.PLATFORMS_MAP.mobile,vendor:"Nexus"}}},{test:[/Nokia/i],describe:function(o){var c=e.default.getFirstMatch(/Nokia\s+([0-9]+(\.[0-9]+)?)/i,o),h={type:i.PLATFORMS_MAP.mobile,vendor:"Nokia"};return c&&(h.model=c),h}},{test:[/[^-]mobi/i],describe:function(){return{type:i.PLATFORMS_MAP.mobile}}},{test:function(o){return o.getBrowserName(!0)==="blackberry"},describe:function(){return{type:i.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(o){return o.getBrowserName(!0)==="bada"},describe:function(){return{type:i.PLATFORMS_MAP.mobile}}},{test:function(o){return o.getBrowserName()==="windows phone"},describe:function(){return{type:i.PLATFORMS_MAP.mobile,vendor:"Microsoft"}}},{test:function(o){var c=Number(String(o.getOSVersion()).split(".")[0]);return o.getOSName(!0)==="android"&&c>=3},describe:function(){return{type:i.PLATFORMS_MAP.tablet}}},{test:function(o){return o.getOSName(!0)==="android"},describe:function(){return{type:i.PLATFORMS_MAP.mobile}}},{test:[/smart-?tv|smarttv/i],describe:function(){return{type:i.PLATFORMS_MAP.tv}}},{test:[/netcast/i],describe:function(){return{type:i.PLATFORMS_MAP.tv}}},{test:function(o){return o.getOSName(!0)==="macos"},describe:function(){return{type:i.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(o){return o.getOSName(!0)==="windows"},describe:function(){return{type:i.PLATFORMS_MAP.desktop}}},{test:function(o){return o.getOSName(!0)==="linux"},describe:function(){return{type:i.PLATFORMS_MAP.desktop}}},{test:function(o){return o.getOSName(!0)==="playstation 4"},describe:function(){return{type:i.PLATFORMS_MAP.tv}}},{test:function(o){return o.getOSName(!0)==="roku"},describe:function(){return{type:i.PLATFORMS_MAP.tv}}}];n.default=f,t.exports=n.default},95:function(t,n,s){n.__esModule=!0,n.default=void 0;var r,e=(r=s(17))&&r.__esModule?r:{default:r},i=s(18),f=[{test:function(o){return o.getBrowserName(!0)==="microsoft edge"},describe:function(o){if(/\sedg\//i.test(o))return{name:i.ENGINE_MAP.Blink};var c=e.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,o);return{name:i.ENGINE_MAP.EdgeHTML,version:c}}},{test:[/trident/i],describe:function(o){var c={name:i.ENGINE_MAP.Trident},h=e.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:function(o){return o.test(/presto/i)},describe:function(o){var c={name:i.ENGINE_MAP.Presto},h=e.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:function(o){var c=o.test(/gecko/i),h=o.test(/like gecko/i);return c&&!h},describe:function(o){var c={name:i.ENGINE_MAP.Gecko},h=e.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:i.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(o){var c={name:i.ENGINE_MAP.WebKit},h=e.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}}];n.default=f,t.exports=n.default}})})});var kt=K((Ry)=>{var{Retry:LO,RETRY_MODES:Tw}=pr(),{HttpRequest:Ic,parseUrl:IO}=Tt(),{InvokeStore:Sw}=fw(),{normalizeProvider:OO}=Qn(),{platform:yO,release:GO}=j("os"),{versions:Tc,env:$w}=j("process"),{isValidHostLabel:BO,isIpAddress:yw,customEndpointFunctions:mO}=fs(),{EndpointError:FO,resolveEndpoint:PO}=fs();Ry.EndpointError=FO;Ry.isIpAddress=yw;Ry.resolveEndpoint=PO;var{loadConfig:HO,NODE_REGION_CONFIG_OPTIONS:Gw,NODE_REGION_CONFIG_FILE_OPTIONS:Bw}=Rt(),{REGION_ENV_NAME:NO,REGION_INI_NAME:DO,resolveRegionConfig:WO}=Rt();Ry.NODE_REGION_CONFIG_FILE_OPTIONS=Bw;Ry.NODE_REGION_CONFIG_OPTIONS=Gw;Ry.REGION_ENV_NAME=NO;Ry.REGION_INI_NAME=DO;Ry.resolveRegionConfig=WO;var Si={warningEmitted:!1},YO=(t)=>{if(t&&!Si.warningEmitted){if(process.env.AWS_SDK_JS_NODE_VERSION_SUPPORT_WARNING_DISABLED==="true"){Si.warningEmitted=!0;return}let n=parseInt(t.substring(1,t.indexOf("."))),s=22;if(n<s)Si.warningEmitted=!0,process.emitWarning(`NodeVersionSupportWarning: The AWS SDK for JavaScript (v3)
14
+ `)}u.close()}else u.enqueue(`${(r(_)||0).toString(16)}\r
15
+ ${_}\r
16
+ `)}})};function Z8(t,n){let s=t,r=t;if(en(r))return p8(r,n);let{base64Encoder:i,bodyLengthChecker:e,checksumAlgorithmFn:f,checksumLocationName:o,streamHasher:c}=n,h=i!==void 0&&f!==void 0&&o!==void 0&&c!==void 0,u=h?c(f,s):void 0,_=new Xs({read:()=>{}});return s.on("data",(l)=>{let w=e(l)||0;if(w===0)return;_.push(`${w.toString(16)}\r
17
+ `),_.push(l),_.push(`\r
18
+ `)}),s.on("end",async()=>{if(_.push(`0\r
19
+ `),h){let l=i(await u);_.push(`${o}:${l}\r
20
+ `),_.push(`\r
21
+ `)}_.push(null)}),_}async function v8(t,n){let s=0,r=[],i=t.getReader(),e=!1;while(!e){let{done:c,value:h}=await i.read();if(h)r.push(h),s+=h?.byteLength??0;if(s>=n)break;e=c}i.releaseLock();let f=new Uint8Array(Math.min(n,s)),o=0;for(let c of r){if(c.byteLength>f.byteLength-o){f.set(c.subarray(0,f.byteLength-o),o);break}else f.set(c,o);o+=c.length}return f}var tS=(t,n)=>{if(en(t))return v8(t,n);return new Promise((s,r)=>{let i=new nS;i.limit=n,t.pipe(i),t.on("error",(e)=>{i.end(),r(e)}),i.on("error",r),i.on("finish",function(){let e=le(this.buffers);s(e)})})},nS=class extends P_{buffers=[];limit=1/0;bytesBuffered=0;_write(n,s,r){if(this.buffers.push(n),this.bytesBuffered+=n.byteLength??0,this.bytesBuffered>=this.limit){let i=this.bytesBuffered-this.limit,e=this.buffers[this.buffers.length-1];this.buffers[this.buffers.length-1]=e.subarray(0,e.byteLength-i),this.emit("finish")}r()}},sS=(t)=>{if(typeof t==="string")return t;if(typeof t!=="object"||typeof t.byteOffset!=="number"||typeof t.byteLength!=="number")throw Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return new TextDecoder("utf-8").decode(t)},rS=async(t)=>{if(we(t))return il(t);return el(t)};async function il(t){return t.arrayBuffer().then((n)=>new Uint8Array(n))}async function el(t){let n=[],s=t.getReader(),r=0;while(!0){let{done:i,value:e}=await s.read();if(e)n.push(e),r+=e.length;if(i)break}return le(n,r)}var B_="The stream has already been transformed.",iS=(t)=>{if(!F_(t)&&!en(t)){let i=t?.__proto__?.constructor?.name||t;throw Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${i}`)}let n=!1,s=async()=>{if(n)throw Error(B_);return n=!0,await rS(t)},r=(i)=>{if(typeof i.stream!=="function")throw Error(`Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.
22
+ If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body`);return 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)
24
24
  versions published after the first week of January 2027
25
25
  will require node >=${s}. You are running node ${t}.
26
26
 
27
27
  To continue receiving updates to AWS services, bug fixes,
28
28
  and security updates please upgrade to node >=${s}.
29
29
 
30
- More information can be found at: https://a.co/c895JFp`)}},xO=()=>(t,n)=>async(s)=>{return n.__retryLongPoll=!0,t(s)},QO={name:"longPollMiddleware",tags:["RETRY"],step:"initialize",override:!0},JO=(t)=>({applyToStack:(n)=>{n.add(xO(),QO)}});function zO(t,n,s){if(!t.$source)t.$source={};return t.$source[n]=s,t}LO.v2026||=typeof process==="object"&&process.env?.AWS_NEW_RETRIES_2026==="true";function on(t,n,s){if(!t.__aws_sdk_context)t.__aws_sdk_context={features:{}};else if(!t.__aws_sdk_context.features)t.__aws_sdk_context.features={};t.__aws_sdk_context.features[n]=s}function kO(t,n,s){if(!t.$source)t.$source={};return t.$source[n]=s,t}function XO(t){return t}var mw=(t)=>(n)=>async(s)=>{if(!Ic.isInstance(s.request))return n(s);let{request:r}=s,{handlerProtocol:e=""}=t.requestHandler.metadata||{};if(e.indexOf("h2")>=0&&!r.headers[":authority"])delete r.headers.host,r.headers[":authority"]=r.hostname+(r.port?":"+r.port:"");else if(!r.headers.host){let i=r.hostname;if(r.port!=null)i+=`:${r.port}`;r.headers.host=i}return n(s)},Fw={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},qO=(t)=>({applyToStack:(n)=>{n.add(mw(t),Fw)}}),Pw=()=>(t,n)=>async(s)=>{try{let r=await t(s),{clientName:e,commandName:i,logger:f,dynamoDbDocumentClientOptions:o={}}=n,{overrideInputFilterSensitiveLog:c,overrideOutputFilterSensitiveLog:h}=o,u=c??n.inputFilterSensitiveLog,l=h??n.outputFilterSensitiveLog,{$metadata:_,...w}=r.output;return f?.info?.({clientName:e,commandName:i,input:u(s.input),output:l(w),metadata:_}),r}catch(r){let{clientName:e,commandName:i,logger:f,dynamoDbDocumentClientOptions:o={}}=n,{overrideInputFilterSensitiveLog:c}=o,h=c??n.inputFilterSensitiveLog;throw f?.error?.({clientName:e,commandName:i,input:h(s.input),error:r,metadata:r.$metadata}),r}},Hw={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},CO=(t)=>({applyToStack:(n)=>{n.add(Pw(),Hw)}}),Nw={step:"build",tags:["RECURSION_DETECTION","TRACE_CONTEXT_PROPAGATION"],name:"recursionDetectionMiddleware",override:!0,priority:"low"},aO="AWS_LAMBDA_FUNCTION_NAME",KO="_X_AMZN_TRACE_ID",Sc="X-Amzn-Trace-Id",Lc="traceparent",Dw="tracestate",Ww="baggage",Yw=()=>(t)=>async(n)=>{let{request:s}=n;if(!Ic.isInstance(s))return t(n);let r;{let e=Object.keys(s.headers??{}).find((i)=>i.toLowerCase()===Sc.toLowerCase())??Sc;if(!s.headers.hasOwnProperty(e)){let i=process.env[aO],f=process.env[KO];r??=await Sw.getInstanceAsync();let c=r?.getXRayTraceId()??f,h=(u)=>typeof u==="string"&&u.length>0;if(h(i)&&h(c))s.headers[Sc]=c}}if(VO(s.headers),!s.headers[Lc]){let i=(r??=await Sw.getInstanceAsync())?.getTraceparent?.();if(i){s.headers[Lc]=i;let f=r?.getTracestate?.();if(f)s.headers[Dw]=f;let o=r?.getBaggage?.();if(o)s.headers[Ww]=o}}return t(n)};function VO(t){for(let n of Object.keys(t)){let s=n.toLowerCase();if(n!==s&&(s===Lc||s===Dw||s===Ww))t[s]=t[n],delete t[n]}}var jO=(t)=>({applyToStack:(n)=>{n.add(Yw(),Nw)}}),Oc=void 0;function pO(t){if(t===void 0)return!0;return typeof t==="string"&&t.length<=50}function vO(t){let n=OO(t.userAgentAppId??Oc),{customUserAgent:s}=t;return Object.assign(t,{customUserAgent:typeof s==="string"?[[s]]:s,userAgentAppId:async()=>{let r=await n();if(!pO(r)){let e=t.logger?.constructor?.name==="NoOpLogger"||!t.logger?console:t.logger;if(typeof r!=="string")e?.warn("userAgentAppId must be a string or undefined.");else if(r.length>50)e?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.")}return r}})}var xw={partitions:[{id:"aws",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-east-1",name:"aws",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$",regions:{"af-south-1":{description:"Africa (Cape Town)"},"ap-east-1":{description:"Asia Pacific (Hong Kong)"},"ap-east-2":{description:"Asia Pacific (Taipei)"},"ap-northeast-1":{description:"Asia Pacific (Tokyo)"},"ap-northeast-2":{description:"Asia Pacific (Seoul)"},"ap-northeast-3":{description:"Asia Pacific (Osaka)"},"ap-south-1":{description:"Asia Pacific (Mumbai)"},"ap-south-2":{description:"Asia Pacific (Hyderabad)"},"ap-southeast-1":{description:"Asia Pacific (Singapore)"},"ap-southeast-2":{description:"Asia Pacific (Sydney)"},"ap-southeast-3":{description:"Asia Pacific (Jakarta)"},"ap-southeast-4":{description:"Asia Pacific (Melbourne)"},"ap-southeast-5":{description:"Asia Pacific (Malaysia)"},"ap-southeast-6":{description:"Asia Pacific (New Zealand)"},"ap-southeast-7":{description:"Asia Pacific (Thailand)"},"aws-global":{description:"aws global region"},"ca-central-1":{description:"Canada (Central)"},"ca-west-1":{description:"Canada West (Calgary)"},"eu-central-1":{description:"Europe (Frankfurt)"},"eu-central-2":{description:"Europe (Zurich)"},"eu-north-1":{description:"Europe (Stockholm)"},"eu-south-1":{description:"Europe (Milan)"},"eu-south-2":{description:"Europe (Spain)"},"eu-west-1":{description:"Europe (Ireland)"},"eu-west-2":{description:"Europe (London)"},"eu-west-3":{description:"Europe (Paris)"},"il-central-1":{description:"Israel (Tel Aviv)"},"me-central-1":{description:"Middle East (UAE)"},"me-south-1":{description:"Middle East (Bahrain)"},"mx-central-1":{description:"Mexico (Central)"},"sa-east-1":{description:"South America (Sao Paulo)"},"us-east-1":{description:"US East (N. Virginia)"},"us-east-2":{description:"US East (Ohio)"},"us-west-1":{description:"US West (N. California)"},"us-west-2":{description:"US West (Oregon)"}}},{id:"aws-cn",outputs:{dnsSuffix:"amazonaws.com.cn",dualStackDnsSuffix:"api.amazonwebservices.com.cn",implicitGlobalRegion:"cn-northwest-1",name:"aws-cn",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^cn\\-\\w+\\-\\d+$",regions:{"aws-cn-global":{description:"aws-cn global region"},"cn-north-1":{description:"China (Beijing)"},"cn-northwest-1":{description:"China (Ningxia)"}}},{id:"aws-eusc",outputs:{dnsSuffix:"amazonaws.eu",dualStackDnsSuffix:"api.amazonwebservices.eu",implicitGlobalRegion:"eusc-de-east-1",name:"aws-eusc",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eusc\\-(de)\\-\\w+\\-\\d+$",regions:{"eusc-de-east-1":{description:"AWS European Sovereign Cloud (Germany)"}}},{id:"aws-iso",outputs:{dnsSuffix:"c2s.ic.gov",dualStackDnsSuffix:"api.aws.ic.gov",implicitGlobalRegion:"us-iso-east-1",name:"aws-iso",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-iso\\-\\w+\\-\\d+$",regions:{"aws-iso-global":{description:"aws-iso global region"},"us-iso-east-1":{description:"US ISO East"},"us-iso-west-1":{description:"US ISO WEST"}}},{id:"aws-iso-b",outputs:{dnsSuffix:"sc2s.sgov.gov",dualStackDnsSuffix:"api.aws.scloud",implicitGlobalRegion:"us-isob-east-1",name:"aws-iso-b",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isob\\-\\w+\\-\\d+$",regions:{"aws-iso-b-global":{description:"aws-iso-b global region"},"us-isob-east-1":{description:"US ISOB East (Ohio)"},"us-isob-west-1":{description:"US ISOB West"}}},{id:"aws-iso-e",outputs:{dnsSuffix:"cloud.adc-e.uk",dualStackDnsSuffix:"api.cloud-aws.adc-e.uk",implicitGlobalRegion:"eu-isoe-west-1",name:"aws-iso-e",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eu\\-isoe\\-\\w+\\-\\d+$",regions:{"aws-iso-e-global":{description:"aws-iso-e global region"},"eu-isoe-west-1":{description:"EU ISOE West"}}},{id:"aws-iso-f",outputs:{dnsSuffix:"csp.hci.ic.gov",dualStackDnsSuffix:"api.aws.hci.ic.gov",implicitGlobalRegion:"us-isof-south-1",name:"aws-iso-f",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isof\\-\\w+\\-\\d+$",regions:{"aws-iso-f-global":{description:"aws-iso-f global region"},"us-isof-east-1":{description:"US ISOF EAST"},"us-isof-south-1":{description:"US ISOF SOUTH"}}},{id:"aws-us-gov",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-gov-west-1",name:"aws-us-gov",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-gov\\-\\w+\\-\\d+$",regions:{"aws-us-gov-global":{description:"aws-us-gov global region"},"us-gov-east-1":{description:"AWS GovCloud (US-East)"},"us-gov-west-1":{description:"AWS GovCloud (US-West)"}}}],version:"1.1"},Qw=xw,Jw="",zw=(t)=>{let{partitions:n}=Qw;for(let r of n){let{regions:e,outputs:i}=r;for(let[f,o]of Object.entries(e))if(f===t)return{...i,...o}}for(let r of n){let{regionRegex:e,outputs:i}=r;if(new RegExp(e).test(t))return{...i}}let s=n.find((r)=>r.id==="aws");if(!s)throw Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");return{...s.outputs}},kw=(t,n="")=>{Qw=t,Jw=n},ZO=()=>{kw(xw,"")},Xw=()=>Jw,ty=/\d{12}\.ddb/;async function ny(t,n,s){if(s.request?.headers?.["smithy-protocol"]==="rpc-v2-cbor")on(t,"PROTOCOL_RPC_V2_CBOR","M");if(typeof n.retryStrategy==="function"){let i=await n.retryStrategy();if(typeof i.mode==="string")switch(i.mode){case Tw.ADAPTIVE:on(t,"RETRY_MODE_ADAPTIVE","F");break;case Tw.STANDARD:on(t,"RETRY_MODE_STANDARD","E");break}}if(typeof n.accountIdEndpointMode==="function"){let i=t.endpointV2;if(String(i?.url?.hostname).match(ty))on(t,"ACCOUNT_ID_ENDPOINT","O");switch(await n.accountIdEndpointMode?.()){case"disabled":on(t,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":on(t,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":on(t,"ACCOUNT_ID_MODE_REQUIRED","R");break}}let e=t.__smithy_context?.selectedHttpAuthScheme?.identity;if(e?.$source){let i=e;if(i.accountId)on(t,"RESOLVED_ACCOUNT_ID","T");for(let[f,o]of Object.entries(i.$source??{}))on(t,f,o)}}var Uw="user-agent",$c="x-amz-user-agent",Lw=" ",Uc="/",sy=/[^!$%&'*+\-.^_`|~\w]/g,ry=/[^!$%&'*+\-.^_`|~\w#]/g,Iw="-",ey=1024;function iy(t){let n="";for(let s in t){let r=t[s];if(n.length+r.length+1<=ey){if(n.length)n+=","+r;else n+=r;continue}break}return n}var qw=(t)=>(n,s)=>async(r)=>{let{request:e}=r;if(!Ic.isInstance(e))return n(r);let{headers:i}=e,f=s?.userAgent?.map(Ti)||[],o=(await t.defaultUserAgentProvider()).map(Ti);await ny(s,t,r);let c=s;o.push(`m/${iy(Object.assign({},s.__smithy_context?.features,c.__aws_sdk_context?.features))}`);let h=t?.customUserAgent?.map(Ti)||[],u=await t.userAgentAppId();if(u)o.push(Ti(["app",`${u}`]));let l=Xw(),_=(l?[l]:[]).concat([...o,...f,...h]).join(Lw),w=[...o.filter((A)=>A.startsWith("aws-sdk-")),...h].join(Lw);if(t.runtime!=="browser"){if(w)i[$c]=i[$c]?`${i[Uw]} ${w}`:w;i[Uw]=_}else i[$c]=_;return n({...r,request:e})},Ti=(t)=>{let n=t[0].split(Uc).map((f)=>f.replace(sy,Iw)).join(Uc),s=t[1]?.replace(ry,Iw),r=n.indexOf(Uc),e=n.substring(0,r),i=n.substring(r+1);if(e==="api")i=i.toLowerCase();return[e,i,s].filter((f)=>f&&f.length>0).reduce((f,o,c)=>{switch(c){case 0:return o;case 1:return`${f}/${o}`;default:return`${f}#${o}`}},"")},Cw={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},oy=(t)=>({applyToStack:(n)=>{n.add(qw(t),Cw)}}),fy=()=>{let t=["deno","bun","llrt"];for(let n of t)if(Tc[n])return[`md/${n}`,Tc[n]];return["md/nodejs",Tc.node]},aw={isCrtAvailable:!1},cy=()=>{if(aw.isCrtAvailable)return["md/crt-avail"];return null},Kw=({serviceId:t,clientVersion:n})=>{let s=fy();return async(r)=>{let e=[["aws-sdk-js",n],["ua","2.1"],[`os/${yO()}`,GO()],["lang/js"],s],i=cy();if(i)e.push(i);if(t)e.push([`api/${t}`,n]);if($w.AWS_EXECUTION_ENV)e.push([`exec-env/${$w.AWS_EXECUTION_ENV}`]);let f=await r?.userAgentAppId?.();return f?[...e,[`app/${f}`]]:[...e]}},hy=Kw,Vw="AWS_SDK_UA_APP_ID",jw="sdk_ua_app_id",uy="sdk-ua-app-id",ly={environmentVariableSelector:(t)=>t[Vw],configFileSelector:(t)=>t[jw]??t[uy],default:Oc},_y=({serviceId:t,clientVersion:n})=>async(s)=>{let r=bw(),e=r.parse??r.default.parse??(()=>""),i=typeof window<"u"&&window?.navigator?.userAgent?e(window.navigator.userAgent):void 0,f=[["aws-sdk-js",n],["ua","2.1"],[`os/${i?.os?.name||"other"}`,i?.os?.version],["lang/js"],["md/browser",`${i?.browser?.name??"unknown"}_${i?.browser?.version??"unknown"}`]];if(t)f.push([`api/${t}`,n]);let o=await s?.userAgentAppId?.();if(o)f.push([`app/${o}`]);return f},wy={os(t){if(/iPhone|iPad|iPod/.test(t))return"iOS";if(/Macintosh|Mac OS X/.test(t))return"macOS";if(/Windows NT/.test(t))return"Windows";if(/Android/.test(t))return"Android";if(/Linux/.test(t))return"Linux";return},browser(t){if(/EdgiOS|EdgA|Edg\//.test(t))return"Microsoft Edge";if(/Firefox\//.test(t))return"Firefox";if(/Chrome\//.test(t))return"Chrome";if(/Safari\//.test(t))return"Safari";return}},yc=(t,n=!1)=>{if(n){for(let s of t.split("."))if(!yc(s))return!1;return!0}if(!BO(t))return!1;if(t.length<3||t.length>63)return!1;if(t!==t.toLowerCase())return!1;if(yw(t))return!1;return!0},Ow=":",Ay="/",pw=(t)=>{let n=t.split(Ow);if(n.length<6)return null;let[s,r,e,i,f,...o]=n;if(s!=="arn"||r===""||e===""||o.join(Ow)==="")return null;let c=o.map((h)=>h.split(Ay)).flat();return{partition:r,service:e,region:i,accountId:f,resourceId:c}},vw={isVirtualHostableS3Bucket:yc,parseArn:pw,partition:zw};mO.aws=vw;var My=(t)=>{if(typeof t.endpointProvider!=="function")throw Error("@aws-sdk/util-endpoint - endpointProvider and endpoint missing in config for this client.");let{endpoint:n}=t;if(n===void 0)t.endpoint=async()=>{return Zw(t.endpointProvider({Region:typeof t.region==="function"?await t.region():t.region,UseDualStack:typeof t.useDualstackEndpoint==="function"?await t.useDualstackEndpoint():t.useDualstackEndpoint,UseFIPS:typeof t.useFipsEndpoint==="function"?await t.useFipsEndpoint():t.useFipsEndpoint,Endpoint:void 0},{logger:t.logger}))};return t},Zw=(t)=>IO(t.url);function dy(t={}){return HO({...Gw,async default(){if(!tA.silence)console.warn("@aws-sdk - WARN - default STS region of us-east-1 used. See @aws-sdk/credential-providers README and set a region explicitly.");return"us-east-1"}},{...Bw,...t})}var tA={silence:!1},gy=(t)=>{return{setRegion(n){t.region=n},region(){return t.region}}},Ey=(t)=>{return{region:t.region()}};Ry.DEFAULT_UA_APP_ID=Oc;Ry.NODE_APP_ID_CONFIG_OPTIONS=ly;Ry.UA_APP_ID_ENV_NAME=Vw;Ry.UA_APP_ID_INI_NAME=jw;Ry.awsEndpointFunctions=vw;Ry.createDefaultUserAgentProvider=Kw;Ry.createUserAgentStringParsingProvider=_y;Ry.crtAvailability=aw;Ry.defaultUserAgent=hy;Ry.emitWarningIfUnsupportedVersion=YO;Ry.fallback=wy;Ry.getAwsRegionExtensionConfiguration=gy;Ry.getHostHeaderPlugin=qO;Ry.getLoggerPlugin=CO;Ry.getLongPollPlugin=JO;Ry.getRecursionDetectionPlugin=jO;Ry.getUserAgentMiddlewareOptions=Cw;Ry.getUserAgentPlugin=oy;Ry.getUserAgentPrefix=Xw;Ry.hostHeaderMiddleware=mw;Ry.hostHeaderMiddlewareOptions=Fw;Ry.isVirtualHostableS3Bucket=yc;Ry.loggerMiddleware=Pw;Ry.loggerMiddlewareOptions=Hw;Ry.parseArn=pw;Ry.partition=zw;Ry.recursionDetectionMiddleware=Yw;Ry.recursionDetectionMiddlewareOptions=Nw;Ry.resolveAwsRegionExtensionConfiguration=Ey;Ry.resolveDefaultAwsRegionalEndpointsConfig=My;Ry.resolveHostHeaderConfig=XO;Ry.resolveUserAgentConfig=vO;Ry.setCredentialFeature=zO;Ry.setFeature=on;Ry.setPartitionInfo=kw;Ry.setTokenFeature=kO;Ry.state=Si;Ry.stsRegionDefaultResolver=dy;Ry.stsRegionWarning=tA;Ry.toEndpointV1=Zw;Ry.useDefaultPartitionInfo=ZO;Ry.userAgentMiddleware=qw});var PA=K((GG)=>{var{fromUtf8:fA,fromHex:EG,toHex:_s,toUint8Array:se,isArrayBuffer:RG}=bt(),{normalizeProvider:cA}=En(),{escapeUri:$i,HttpRequest:lA}=Tt();class _A{format(t){let n=[];for(let e of Object.keys(t)){let i=fA(e);n.push(Uint8Array.from([i.byteLength]),i,this.formatHeaderValue(t[e]))}let s=new Uint8Array(n.reduce((e,i)=>e+i.byteLength,0)),r=0;for(let e of n)s.set(e,r),r+=e.byteLength;return s}formatHeaderValue(t){switch(t.type){case"boolean":return Uint8Array.from([t.value?Pt.boolTrue:Pt.boolFalse]);case"byte":return Uint8Array.from([Pt.byte,t.value]);case"short":let n=new DataView(new ArrayBuffer(3));return n.setUint8(0,Pt.short),n.setInt16(1,t.value,!1),new Uint8Array(n.buffer);case"integer":let s=new DataView(new ArrayBuffer(5));return s.setUint8(0,Pt.integer),s.setInt32(1,t.value,!1),new Uint8Array(s.buffer);case"long":let r=new Uint8Array(9);return r[0]=Pt.long,r.set(t.value.bytes,1),r;case"binary":let e=new DataView(new ArrayBuffer(3+t.value.byteLength));e.setUint8(0,Pt.byteArray),e.setUint16(1,t.value.byteLength,!1);let i=new Uint8Array(e.buffer);return i.set(t.value,3),i;case"string":let f=fA(t.value),o=new DataView(new ArrayBuffer(3+f.byteLength));o.setUint8(0,Pt.string),o.setUint16(1,f.byteLength,!1);let c=new Uint8Array(o.buffer);return c.set(f,3),c;case"timestamp":let h=new Uint8Array(9);return h[0]=Pt.timestamp,h.set(Fc.fromNumber(t.value.valueOf()).bytes,1),h;case"uuid":if(!bG.test(t.value))throw Error(`Invalid UUID received: ${t.value}`);let u=new Uint8Array(17);return u[0]=Pt.uuid,u.set(EG(t.value.replace(/-/g,"")),1),u}}}var Pt;(function(t){t[t.boolTrue=0]="boolTrue",t[t.boolFalse=1]="boolFalse",t[t.byte=2]="byte",t[t.short=3]="short",t[t.integer=4]="integer",t[t.long=5]="long",t[t.byteArray=6]="byteArray",t[t.string=7]="string",t[t.timestamp=8]="timestamp",t[t.uuid=9]="uuid"})(Pt||(Pt={}));var bG=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class Fc{bytes;constructor(t){if(this.bytes=t,t.byteLength!==8)throw Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(t){if(t>9223372036854776000||t<-9223372036854776000)throw Error(`${t} is too large (or, if negative, too small) to represent as an Int64`);let n=new Uint8Array(8);for(let s=7,r=Math.abs(Math.round(t));s>-1&&r>0;s--,r/=256)n[s]=r;if(t<0)hA(n);return new Fc(n)}valueOf(){let t=this.bytes.slice(0),n=t[0]&128;if(n)hA(t);return parseInt(_s(t),16)*(n?-1:1)}toString(){return String(this.valueOf())}}function hA(t){for(let n=0;n<8;n++)t[n]^=255;for(let n=7;n>-1;n--)if(t[n]++,t[n]!==0)break}var wA="X-Amz-Algorithm",AA="X-Amz-Credential",Pc="X-Amz-Date",MA="X-Amz-SignedHeaders",dA="X-Amz-Expires",Hc="X-Amz-Signature",Nc="X-Amz-Security-Token",TG="X-Amz-Region-Set",Dc="authorization",Wc=Pc.toLowerCase(),gA="date",EA=[Dc,Wc,gA],RA=Hc.toLowerCase(),yi="x-amz-content-sha256",bA=Nc.toLowerCase(),SG="host",TA={authorization:!0,"cache-control":!0,connection:!0,expect:!0,from:!0,"keep-alive":!0,"max-forwards":!0,pragma:!0,referer:!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0,"user-agent":!0,"x-amzn-trace-id":!0},SA=/^proxy-/,$A=/^sec-/,$G=[/^proxy-/i,/^sec-/i],Ui="AWS4-HMAC-SHA256",UG="AWS4-ECDSA-P256-SHA256",UA="AWS4-HMAC-SHA256-PAYLOAD",LA="UNSIGNED-PAYLOAD",IA=50,Yc="aws4_request",OA=604800,yA=({query:t={}})=>{let n=[],s={};for(let r of Object.keys(t)){if(r.toLowerCase()===RA)continue;let e=$i(r);n.push(e);let i=t[r];if(typeof i==="string")s[e]=`${e}=${$i(i)}`;else if(Array.isArray(i))s[e]=i.slice(0).reduce((f,o)=>f.concat([`${e}=${$i(o)}`]),[]).sort().join("&")}return n.sort().map((r)=>s[r]).filter((r)=>r).join("&")},LG=(t)=>IG(t).toISOString().replace(/\.\d{3}Z$/,"Z"),IG=(t)=>{if(typeof t==="number")return new Date(t*1000);if(typeof t==="string"){if(Number(t))return new Date(Number(t)*1000);return new Date(t)}return t};class xc{service;regionProvider;credentialProvider;sha256;uriEscapePath;applyChecksum;constructor({applyChecksum:t,credentials:n,region:s,service:r,sha256:e,uriEscapePath:i=!0}){this.service=r,this.sha256=e,this.uriEscapePath=i,this.applyChecksum=typeof t==="boolean"?t:!0,this.regionProvider=cA(s),this.credentialProvider=cA(n)}createCanonicalRequest(t,n,s){let r=Object.keys(n).sort();return`${t.method}
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
31
  ${this.getCanonicalPath(t)}
32
- ${yA(t)}
33
- ${r.map((e)=>`${e}:${n[e]}`).join(`
32
+ ${kA(t)}
33
+ ${r.map((i)=>`${i}:${n[i]}`).join(`
34
34
  `)}
35
35
 
36
36
  ${r.join(";")}
37
- ${s}`}async createStringToSign(t,n,s,r){let e=new this.sha256;e.update(se(s));let i=await e.digest();return`${r}
37
+ ${s}`}async createStringToSign(t,n,s,r){let i=new this.sha256;i.update(ii(s));let e=await i.digest();return`${r}
38
38
  ${t}
39
39
  ${n}
40
- ${_s(i)}`}getCanonicalPath({path:t}){if(this.uriEscapePath){let n=[];for(let e of t.split("/")){if(e?.length===0)continue;if(e===".")continue;if(e==="..")n.pop();else n.push(e)}let s=`${t?.startsWith("/")?"/":""}${n.join("/")}${n.length>0&&t?.endsWith("/")?"/":""}`;return $i(s).replace(/%2F/g,"/")}return t}validateResolvedCredentials(t){if(typeof t!=="object"||typeof t.accessKeyId!=="string"||typeof t.secretAccessKey!=="string")throw Error("Resolved credential object is not valid")}formatDate(t){let n=LG(t).replace(/[-:]/g,"");return{longDate:n,shortDate:n.slice(0,8)}}getCanonicalHeaderList(t){return Object.keys(t).sort().join(";")}}var nr={},Li=[],Ii=(t,n,s)=>`${t}/${n}/${s}/${Yc}`,GA=async(t,n,s,r,e)=>{let i=await uA(t,n.secretAccessKey,n.accessKeyId),f=`${s}:${r}:${e}:${_s(i)}:${n.sessionToken}`;if(f in nr)return nr[f];Li.push(f);while(Li.length>IA)delete nr[Li.shift()];let o=`AWS4${n.secretAccessKey}`;for(let c of[s,r,e,Yc])o=await uA(t,o,c);return nr[f]=o},OG=()=>{Li.length=0,Object.keys(nr).forEach((t)=>{delete nr[t]})},uA=(t,n,s)=>{let r=new t(n);return r.update(se(s)),r.digest()},Bc=({headers:t},n,s)=>{let r={};for(let e of Object.keys(t).sort()){if(t[e]==null)continue;let i=e.toLowerCase();if(i in TA||n?.has(i)||SA.test(i)||$A.test(i)){if(!s||s&&!s.has(i))continue}r[i]=t[e].trim().replace(/\s+/g," ")}return r},Oi=async({headers:t,body:n},s)=>{for(let r of Object.keys(t))if(r.toLowerCase()===yi)return t[r];if(n==null)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";else if(typeof n==="string"||ArrayBuffer.isView(n)||RG(n)){let r=new s;return r.update(se(n)),_s(await r.digest())}return LA},BA=(t,n)=>{t=t.toLowerCase();for(let s of Object.keys(n))if(t===s.toLowerCase())return!0;return!1},mA=(t,n={})=>{let{headers:s,query:r={}}=lA.clone(t);for(let e of Object.keys(s)){let i=e.toLowerCase();if(i.slice(0,6)==="x-amz-"&&!n.unhoistableHeaders?.has(i)||n.hoistableHeaders?.has(i))r[e]=s[e],delete s[e]}return{...t,headers:s,query:r}},mc=(t)=>{t=lA.clone(t);for(let n of Object.keys(t.headers))if(EA.indexOf(n.toLowerCase())>-1)delete t.headers[n];return t};class FA extends xc{headerFormatter=new _A;constructor({applyChecksum:t,credentials:n,region:s,service:r,sha256:e,uriEscapePath:i=!0}){super({applyChecksum:t,credentials:n,region:s,service:r,sha256:e,uriEscapePath:i})}async presign(t,n={}){let{signingDate:s=new Date,expiresIn:r=3600,unsignableHeaders:e,unhoistableHeaders:i,signableHeaders:f,hoistableHeaders:o,signingRegion:c,signingService:h}=n,u=await this.credentialProvider();this.validateResolvedCredentials(u);let l=c??await this.regionProvider(),{longDate:_,shortDate:w}=this.formatDate(s);if(r>OA)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");let A=Ii(w,l,h??this.service),M=mA(mc(t),{unhoistableHeaders:i,hoistableHeaders:o});if(u.sessionToken)M.query[Nc]=u.sessionToken;M.query[wA]=Ui,M.query[AA]=`${u.accessKeyId}/${A}`,M.query[Pc]=_,M.query[dA]=r.toString(10);let d=Bc(M,e,f);return M.query[MA]=this.getCanonicalHeaderList(d),M.query[Hc]=await this.getSignature(_,A,this.getSigningKey(u,l,w,h),this.createCanonicalRequest(M,d,await Oi(t,this.sha256))),M}async sign(t,n){if(typeof t==="string")return this.signString(t,n);else if(t.headers&&t.payload)return this.signEvent(t,n);else if(t.message)return this.signMessage(t,n);else return this.signRequest(t,n)}async signEvent({headers:t,payload:n},{signingDate:s=new Date,priorSignature:r,signingRegion:e,signingService:i,eventStreamCredentials:f}){let o=e??await this.regionProvider(),{shortDate:c,longDate:h}=this.formatDate(s),u=Ii(c,o,i??this.service),l=await Oi({headers:{},body:n},this.sha256),_=new this.sha256;_.update(t);let w=_s(await _.digest()),A=[UA,h,u,r,w,l].join(`
41
- `);return this.signString(A,{signingDate:s,signingRegion:o,signingService:i,eventStreamCredentials:f})}async signMessage(t,{signingDate:n=new Date,signingRegion:s,signingService:r,eventStreamCredentials:e}){return this.signEvent({headers:this.headerFormatter.format(t.message.headers),payload:t.message.body},{signingDate:n,signingRegion:s,signingService:r,priorSignature:t.priorSignature,eventStreamCredentials:e}).then((f)=>{return{message:t.message,signature:f}})}async signString(t,{signingDate:n=new Date,signingRegion:s,signingService:r,eventStreamCredentials:e}={}){let i=e??await this.credentialProvider();this.validateResolvedCredentials(i);let f=s??await this.regionProvider(),{shortDate:o}=this.formatDate(n),c=new this.sha256(await this.getSigningKey(i,f,o,r));return c.update(se(t)),_s(await c.digest())}async signRequest(t,{signingDate:n=new Date,signableHeaders:s,unsignableHeaders:r,signingRegion:e,signingService:i}={}){let f=await this.credentialProvider();this.validateResolvedCredentials(f);let o=e??await this.regionProvider(),c=mc(t),{longDate:h,shortDate:u}=this.formatDate(n),l=Ii(u,o,i??this.service);if(c.headers[Wc]=h,f.sessionToken)c.headers[bA]=f.sessionToken;let _=await Oi(c,this.sha256);if(!BA(yi,c.headers)&&this.applyChecksum)c.headers[yi]=_;let w=Bc(c,r,s),A=await this.getSignature(h,l,this.getSigningKey(f,o,u,i),this.createCanonicalRequest(c,w,_));return c.headers[Dc]=`${Ui} Credential=${f.accessKeyId}/${l}, SignedHeaders=${this.getCanonicalHeaderList(w)}, Signature=${A}`,c}async getSignature(t,n,s,r){let e=await this.createStringToSign(t,n,r,Ui),i=new this.sha256(await s);return i.update(se(e)),_s(await i.digest())}getSigningKey(t,n,s,r){return GA(this.sha256,t,s,n,r||this.service)}}var yG={SignatureV4a:null};GG.ALGORITHM_IDENTIFIER=Ui;GG.ALGORITHM_IDENTIFIER_V4A=UG;GG.ALGORITHM_QUERY_PARAM=wA;GG.ALWAYS_UNSIGNABLE_HEADERS=TA;GG.AMZ_DATE_HEADER=Wc;GG.AMZ_DATE_QUERY_PARAM=Pc;GG.AUTH_HEADER=Dc;GG.CREDENTIAL_QUERY_PARAM=AA;GG.DATE_HEADER=gA;GG.EVENT_ALGORITHM_IDENTIFIER=UA;GG.EXPIRES_QUERY_PARAM=dA;GG.GENERATED_HEADERS=EA;GG.HOST_HEADER=SG;GG.KEY_TYPE_IDENTIFIER=Yc;GG.MAX_CACHE_SIZE=IA;GG.MAX_PRESIGNED_TTL=OA;GG.PROXY_HEADER_PATTERN=SA;GG.REGION_SET_PARAM=TG;GG.SEC_HEADER_PATTERN=$A;GG.SHA256_HEADER=yi;GG.SIGNATURE_HEADER=RA;GG.SIGNATURE_QUERY_PARAM=Hc;GG.SIGNED_HEADERS_QUERY_PARAM=MA;GG.SignatureV4=FA;GG.SignatureV4Base=xc;GG.TOKEN_HEADER=bA;GG.TOKEN_QUERY_PARAM=Nc;GG.UNSIGNABLE_PATTERNS=$G;GG.UNSIGNED_PAYLOAD=LA;GG.clearCredentialCache=OG;GG.createScope=Ii;GG.getCanonicalHeaders=Bc;GG.getCanonicalQuery=yA;GG.getPayloadHash=Oi;GG.getSigningKey=GA;GG.hasHeader=BA;GG.moveHeadersToQuery=mA;GG.prepareRequest=mc;GG.signatureV4aContainer=yG});var zc=K((yB)=>{var{HttpResponse:MB,HttpRequest:JA}=Tt(),{normalizeProvider:re,memoizeIdentityProvider:dB,isIdentityExpired:gB,doesIdentityRequireRefresh:EB}=Qn(),{ProviderError:HA}=Rt(),{setCredentialFeature:RB}=kt(),{SignatureV4:NA}=PA(),DA=(t)=>MB.isInstance(t)?t.headers?.date??t.headers?.Date:void 0,Qc=(t)=>new Date(Date.now()+t),bB=(t,n)=>Math.abs(Qc(n).getTime()-t)>=300000,WA=(t,n)=>{let s=Date.parse(t);if(bB(s,n))return s-Date.now();return n},ee=(t,n)=>{if(!n)throw Error(`Property \`${t}\` is not resolved for AWS SDK SigV4Auth`);return n},Jc=async(t)=>{let n=ee("context",t.context),s=ee("config",t.config),r=n.endpointV2?.properties?.authSchemes?.[0],i=await ee("signer",s.signer)(r),f=t?.signingRegion,o=t?.signingRegionSet,c=t?.signingName;return{config:s,signer:i,signingRegion:f,signingRegionSet:o,signingName:c}};class Gi{async sign(t,n,s){if(!JA.isInstance(t))throw Error("The request is not an instance of `HttpRequest` and cannot be signed");let r=await Jc(s),{config:e,signer:i}=r,{signingRegion:f,signingName:o}=r,c=s.context;if(c?.authSchemes?.length??!1){let[u,l]=c.authSchemes;if(u?.name==="sigv4a"&&l?.name==="sigv4")f=l?.signingRegion??f,o=l?.signingName??o}return s._preRequestSystemClockOffset=e.systemClockOffset,await i.sign(t,{signingDate:Qc(e.systemClockOffset),signingRegion:f,signingService:o})}errorHandler(t){return(n)=>{let s=n,r=s.ServerTime??DA(s.$response);if(r){let e=ee("config",t.config),i=t._preRequestSystemClockOffset,f=WA(r,e.systemClockOffset);if((f!==e.systemClockOffset||i!==void 0&&i!==f)&&s.$metadata)e.systemClockOffset=f,s.$metadata.clockSkewCorrected=!0}throw n}}successHandler(t,n){let s=DA(t);if(s){let r=ee("config",n.config);r.systemClockOffset=WA(s,r.systemClockOffset)}}}var TB=Gi;class zA extends Gi{async sign(t,n,s){if(!JA.isInstance(t))throw Error("The request is not an instance of `HttpRequest` and cannot be signed");let{config:r,signer:e,signingRegion:i,signingRegionSet:f,signingName:o}=await Jc(s),h=(await r.sigv4aSigningRegionSet?.()??f??[i]).join(",");return s._preRequestSystemClockOffset=r.systemClockOffset,await e.sign(t,{signingDate:Qc(r.systemClockOffset),signingRegion:h,signingService:o})}}var YA=(t)=>typeof t==="string"&&t.length>0?t.split(",").map((n)=>n.trim()):[],kA=(t)=>`AWS_BEARER_TOKEN_${t.replace(/[\s-]/g,"_").toUpperCase()}`,xA="AWS_AUTH_SCHEME_PREFERENCE",QA="auth_scheme_preference",SB={environmentVariableSelector:(t,n)=>{if(n?.signingName){if(kA(n.signingName)in t)return["httpBearerAuth"]}if(!(xA in t))return;return YA(t[xA])},configFileSelector:(t)=>{if(!(QA in t))return;return YA(t[QA])},default:[]},$B=(t)=>{return t.sigv4aSigningRegionSet=re(t.sigv4aSigningRegionSet),t},UB={environmentVariableSelector(t){if(t.AWS_SIGV4A_SIGNING_REGION_SET)return t.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((n)=>n.trim());throw new HA("AWS_SIGV4A_SIGNING_REGION_SET not set in env.",{tryNextLink:!0})},configFileSelector(t){if(t.sigv4a_signing_region_set)return(t.sigv4a_signing_region_set??"").split(",").map((n)=>n.trim());throw new HA("sigv4a_signing_region_set not set in profile.",{tryNextLink:!0})},default:void 0},XA=(t)=>{let n=t.credentials,s=!!t.credentials,r=void 0;Object.defineProperty(t,"credentials",{set(h){if(h&&h!==n&&h!==r)s=!0;n=h;let u=IB(t,{credentials:n,credentialDefaultProvider:t.credentialDefaultProvider}),l=OB(t,u);if(s&&!l.attributed){let _=typeof n==="object"&&n!==null;r=async(w)=>{let M=await l(w);if(_&&(!M.$source||Object.keys(M.$source).length===0))return RB(M,"CREDENTIALS_CODE","e");return M},r.memoized=l.memoized,r.configBound=l.configBound,r.attributed=!0}else r=l},get(){return r},enumerable:!0,configurable:!0}),t.credentials=n;let{signingEscapePath:e=!0,systemClockOffset:i=t.systemClockOffset||0,sha256:f}=t,o;if(t.signer)o=re(t.signer);else if(t.regionInfoProvider)o=()=>re(t.region)().then(async(h)=>[await t.regionInfoProvider(h,{useFipsEndpoint:await t.useFipsEndpoint(),useDualstackEndpoint:await t.useDualstackEndpoint()})||{},h]).then(([h,u])=>{let{signingRegion:l,signingService:_}=h;t.signingRegion=t.signingRegion||l||u,t.signingName=t.signingName||_||t.serviceId;let w={...t,credentials:t.credentials,region:t.signingRegion,service:t.signingName,sha256:f,uriEscapePath:e};return new(t.signerConstructor||NA)(w)});else o=async(h)=>{h=Object.assign({},{name:"sigv4",signingName:t.signingName||t.defaultSigningName,signingRegion:await re(t.region)(),properties:{}},h);let{signingRegion:u,signingName:l}=h;t.signingRegion=t.signingRegion||u,t.signingName=t.signingName||l||t.serviceId;let _={...t,credentials:t.credentials,region:t.signingRegion,service:t.signingName,sha256:f,uriEscapePath:e};return new(t.signerConstructor||NA)(_)};return Object.assign(t,{systemClockOffset:i,signingEscapePath:e,signer:o})},LB=XA;function IB(t,{credentials:n,credentialDefaultProvider:s}){let r;if(n)if(!n?.memoized)r=dB(n,gB,EB);else r=n;else if(s)r=re(s(Object.assign({},t,{parentClientConfig:t})));else r=async()=>{throw Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.")};return r.memoized=!0,r}function OB(t,n){if(n.configBound)return n;let s=async(r)=>n({...r,callerClientConfig:t});return s.memoized=n.memoized,s.configBound=!0,s}yB.AWSSDKSigV4Signer=TB;yB.AwsSdkSigV4ASigner=zA;yB.AwsSdkSigV4Signer=Gi;yB.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS=SB;yB.NODE_SIGV4A_CONFIG_OPTIONS=UB;yB.getBearerTokenEnvKey=kA;yB.resolveAWSSDKSigV4Config=LB;yB.resolveAwsSdkSigV4AConfig=$B;yB.resolveAwsSdkSigV4Config=XA;yB.validateSigningProperties=Jc});var Ni=K((jB)=>{var{buildQueryString:pA,HttpResponse:vA}=Tt(),Bi=j("https"),{Readable:xB}=j("stream"),kc=j("http2"),{streamCollector:QB}=bt();jB.streamCollector=QB;function Fi(t){let n=t&&typeof t==="object"&&"reason"in t?t.reason:void 0;if(n){if(n instanceof Error){let e=Error("Request aborted");return e.name="AbortError",e.cause=n,e}let r=Error(String(n));return r.name="AbortError",r}let s=Error("Request aborted");return s.name="AbortError",s}var JB=["ECONNRESET","EPIPE","ETIMEDOUT"],ZA=(t)=>{let n={};for(let s in t){let r=t[s];n[s]=Array.isArray(r)?r.join(","):r}return n},_t={setTimeout:(t,n)=>setTimeout(t,n),clearTimeout:(t)=>clearTimeout(t)},CA=1000,zB=(t,n,s=0)=>{if(!s)return-1;let r=(e)=>{let i=_t.setTimeout(()=>{t.destroy(),n(Object.assign(Error(`@smithy/node-http-handler - the request socket did not establish a connection with the server within the configured timeout of ${s} ms.`),{name:"TimeoutError"}))},s-e),f=(o)=>{if(o?.connecting)o.on("connect",()=>{_t.clearTimeout(i)});else _t.clearTimeout(i)};if(t.socket)f(t.socket);else t.on("socket",f)};if(s<2000)return r(0),0;return _t.setTimeout(r.bind(null,CA),CA)},kB=(t,n,s=0,r,e)=>{if(s)return _t.setTimeout(()=>{let i=`@smithy/node-http-handler - [${r?"ERROR":"WARN"}] a request has exceeded the configured ${s} ms requestTimeout.`;if(r){let f=Object.assign(Error(i),{name:"TimeoutError",code:"ETIMEDOUT"});t.destroy(f),n(f)}else i+=" Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.",e?.warn?.(i)},s);return-1},XB=3000,qB=(t,{keepAlive:n,keepAliveMsecs:s},r=XB)=>{if(n!==!0)return-1;let e=()=>{if(t.socket)t.socket.setKeepAlive(n,s||0);else t.on("socket",(i)=>{i.setKeepAlive(n,s||0)})};if(r===0)return e(),0;return _t.setTimeout(e,r)},aA=3000,CB=(t,n,s=0)=>{let r=(e)=>{let i=s-e,f=()=>{t.destroy(),n(Object.assign(Error(`@smithy/node-http-handler - the request socket timed out after ${s} ms of inactivity (configured by client requestHandler).`),{name:"TimeoutError"}))};if(t.socket)t.socket.setTimeout(i,f),t.on("close",()=>t.socket?.removeListener("timeout",f));else t.setTimeout(i,f)};if(0<s&&s<6000)return r(0),0;return _t.setTimeout(r.bind(null,s===0?0:aA),aA)},KA=6000;async function tM(t,n,s=KA,r=!1){let e=n.headers,i=e?e.Expect||e.expect:void 0,f=-1,o=!0;if(!r&&i==="100-continue")o=await Promise.race([new Promise((c)=>{f=Number(_t.setTimeout(()=>c(!0),Math.max(KA,s)))}),new Promise((c)=>{t.on("continue",()=>{_t.clearTimeout(f),c(!0)}),t.on("response",()=>{_t.clearTimeout(f),c(!1)}),t.on("error",()=>{_t.clearTimeout(f),c(!1)})})]);if(o)aB(t,n.body)}function aB(t,n){if(n instanceof xB){n.pipe(t);return}if(n){let s=Buffer.isBuffer(n);if(s||typeof n==="string"){if(s&&n.byteLength===0)t.end();else t.end(n);return}let e=n;if(typeof e==="object"&&e.buffer&&typeof e.byteOffset==="number"&&typeof e.byteLength==="number"){t.end(Buffer.from(e.buffer,e.byteOffset,e.byteLength));return}t.end(Buffer.from(n));return}t.end()}var KB=0,mi=void 0,VA=void 0;class Pi{config;configProvider;socketWarningTimestamp=0;externalAgent=!1;metadata={handlerProtocol:"http/1.1"};static create(t){if(typeof t?.handle==="function")return t;return new Pi(t)}static checkSocketUsage(t,n,s=console){let{sockets:r,requests:e,maxSockets:i}=t;if(typeof i!=="number"||i===1/0)return n;let f=15000;if(Date.now()-f<n)return n;if(r&&e)for(let o in r){let c=r[o]?.length??0,h=e[o]?.length??0;if(c>=i&&h>=2*i)return s?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${c} and ${h} additional requests are enqueued.
40
+ ${ls(e)}`}getCanonicalPath({path:t}){if(this.uriEscapePath){let n=[];for(let i of t.split("/")){if(i?.length===0)continue;if(i===".")continue;if(i==="..")n.pop();else n.push(i)}let s=`${t?.startsWith("/")?"/":""}${n.join("/")}${n.length>0&&t?.endsWith("/")?"/":""}`;return Ie(s).replace(/%2F/g,"/")}return t}validateResolvedCredentials(t){if(typeof t!=="object"||typeof t.accessKeyId!=="string"||typeof t.secretAccessKey!=="string")throw Error("Resolved credential object is not valid")}formatDate(t){let n=jG(t).replace(/[-:]/g,"");return{longDate:n,shortDate:n.slice(0,8)}}getCanonicalHeaderList(t){return Object.keys(t).sort().join(";")}}var nr={},ye=[],Ge=(t,n,s)=>`${t}/${n}/${s}/${qc}`,XA=async(t,n,s,r,i)=>{let e=await $A(t,n.secretAccessKey,n.accessKeyId),f=`${s}:${r}:${i}:${ls(e)}:${n.sessionToken}`;if(f in nr)return nr[f];ye.push(f);while(ye.length>QA)delete nr[ye.shift()];let o=`AWS4${n.secretAccessKey}`;for(let c of[s,r,i,qc])o=await $A(t,o,c);return nr[f]=o},pG=()=>{ye.length=0,Object.keys(nr).forEach((t)=>{delete nr[t]})},$A=(t,n,s)=>{let r=new t(n);return r.update(ii(s)),r.digest()},Yc=({headers:t},n,s)=>{let r={};for(let i of Object.keys(t).sort()){if(t[i]==null)continue;let e=i.toLowerCase();if(e in NA||n?.has(e)||WA.test(e)||DA.test(e)){if(!s||s&&!s.has(e))continue}r[e]=t[i].trim().replace(/\s+/g," ")}return r},Be=async({headers:t,body:n},s)=>{for(let r of Object.keys(t))if(r.toLowerCase()===Fe)return t[r];if(n==null)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";else if(typeof n==="string"||ArrayBuffer.isView(n)||zG(n)){let r=new s;return r.update(ii(n)),ls(await r.digest())}return mA},zA=(t,n)=>{t=t.toLowerCase();for(let s of Object.keys(n))if(t===s.toLowerCase())return!0;return!1},xA=(t,n={})=>{let{headers:s,query:r={}}=UA.clone(t);for(let i of Object.keys(s)){let e=i.toLowerCase();if(e.slice(0,6)==="x-amz-"&&!n.unhoistableHeaders?.has(e)||n.hoistableHeaders?.has(e))r[i]=s[i],delete s[i]}return{...t,headers:s,query:r}},mc=(t)=>{t=UA.clone(t);for(let n of Object.keys(t.headers))if(FA.indexOf(n.toLowerCase())>-1)delete t.headers[n];return t};class qA extends Cc{headerFormatter=new LA;constructor({applyChecksum:t,credentials:n,region:s,service:r,sha256:i,uriEscapePath:e=!0}){super({applyChecksum:t,credentials:n,region:s,service:r,sha256:i,uriEscapePath:e})}async presign(t,n={}){let{signingDate:s=new Date,expiresIn:r=3600,unsignableHeaders:i,unhoistableHeaders:e,signableHeaders:f,hoistableHeaders:o,signingRegion:c,signingService:h}=n,u=await this.credentialProvider();this.validateResolvedCredentials(u);let _=c??await this.regionProvider(),{longDate:l,shortDate:w}=this.formatDate(s);if(r>JA)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");let A=Ge(w,_,h??this.service),M=xA(mc(t),{unhoistableHeaders:e,hoistableHeaders:o});if(u.sessionToken)M.query[Xc]=u.sessionToken;M.query[IA]=Oe,M.query[OA]=`${u.accessKeyId}/${A}`,M.query[Jc]=l,M.query[GA]=r.toString(10);let E=Yc(M,i,f);return M.query[yA]=this.getCanonicalHeaderList(E),M.query[kc]=await this.getSignature(l,A,this.getSigningKey(u,_,w,h),this.createCanonicalRequest(M,E,await Be(t,this.sha256))),M}async sign(t,n){if(typeof t==="string")return this.signString(t,n);else if(t.headers&&t.payload)return this.signEvent(t,n);else if(t.message)return this.signMessage(t,n);else return this.signRequest(t,n)}async signEvent({headers:t,payload:n},{signingDate:s=new Date,priorSignature:r,signingRegion:i,signingService:e,eventStreamCredentials:f}){let o=i??await this.regionProvider(),{shortDate:c,longDate:h}=this.formatDate(s),u=Ge(c,o,e??this.service),_=await Be({headers:{},body:n},this.sha256),l=new this.sha256;l.update(t);let w=ls(await l.digest()),A=[YA,h,u,r,w,_].join(`
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.
42
42
  See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html
43
- or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`),Date.now()}return n}constructor(t){this.configProvider=new Promise((n,s)=>{if(typeof t==="function")t().then((r)=>{n(this.resolveDefaultConfig(r))}).catch(s);else n(this.resolveDefaultConfig(t))})}destroy(){this.config?.httpAgent?.destroy(),this.config?.httpsAgent?.destroy()}async handle(t,{abortSignal:n,requestTimeout:s}={}){if(!this.config)this.config=await this.configProvider;let r=this.config,e=t.protocol==="https:";if(!e&&!this.config.httpAgent)this.config.httpAgent=await this.config.httpAgentProvider();return new Promise((i,f)=>{let o=void 0,c=-1,h=-1,u=-1,l=-1,_=-1,w=()=>{_t.clearTimeout(c),_t.clearTimeout(h),_t.clearTimeout(u),_t.clearTimeout(l),_t.clearTimeout(_)},A=async(U)=>{await o,w(),i(U)},M=async(U)=>{await o,w(),f(U)};if(n?.aborted){let U=Fi(n);M(U);return}let d=t.headers,E=d?(d.Expect??d.expect)==="100-continue":!1,b=e?r.httpsAgent:r.httpAgent;if(E&&!this.externalAgent)b=new(e?Bi.Agent:mi)({keepAlive:!1,maxSockets:1/0});c=_t.setTimeout(()=>{this.socketWarningTimestamp=Pi.checkSocketUsage(b,this.socketWarningTimestamp,r.logger)},r.socketAcquisitionWarningTimeout??(r.requestTimeout??2000)+(r.connectionTimeout??1000));let L=t.query?pA(t.query):"",S=void 0;if(t.username!=null||t.password!=null){let U=t.username??"",z=t.password??"";S=`${U}:${z}`}let O=t.path;if(L)O+=`?${L}`;if(t.fragment)O+=`#${t.fragment}`;let x=t.hostname??"";if(x[0]==="["&&x.endsWith("]"))x=t.hostname.slice(1,-1);else x=t.hostname;let X={headers:t.headers,host:x,method:t.method,path:O,port:t.port,agent:b,auth:S},Q=(e?Bi.request:VA)(X,(U)=>{let z=new vA({statusCode:U.statusCode||-1,reason:U.statusMessage,headers:ZA(U.headers),body:U});A({response:z})});if(Q.on("error",(U)=>{if(JB.includes(U.code))M(Object.assign(U,{name:"TimeoutError"}));else M(U)}),n){let U=()=>{Q.destroy();let z=Fi(n);M(z)};if(typeof n.addEventListener==="function"){let z=n;z.addEventListener("abort",U,{once:!0}),Q.once("close",()=>z.removeEventListener("abort",U))}else n.onabort=U}let rt=s??r.requestTimeout;h=zB(Q,M,r.connectionTimeout),u=kB(Q,M,rt,r.throwOnRequestTimeout,r.logger??console),l=CB(Q,M,r.socketTimeout);let Dt=X.agent;if(typeof Dt==="object"&&"keepAlive"in Dt)_=qB(Q,{keepAlive:Dt.keepAlive,keepAliveMsecs:Dt.keepAliveMsecs});o=tM(Q,t,rt,this.externalAgent).catch((U)=>{return w(),f(U)})})}updateHttpClientConfig(t,n){this.config=void 0,this.configProvider=this.configProvider.then((s)=>{return{...s,[t]:n}})}httpHandlerConfigs(){return this.config??{}}resolveDefaultConfig(t){let{requestTimeout:n,connectionTimeout:s,socketTimeout:r,socketAcquisitionWarningTimeout:e,httpAgent:i,httpsAgent:f,throwOnRequestTimeout:o,logger:c}=t||{},h=!0,u=50;return{connectionTimeout:s,requestTimeout:n,socketTimeout:r,socketAcquisitionWarningTimeout:e,throwOnRequestTimeout:o,httpAgentProvider:async()=>{let l=j("http"),{Agent:_,request:w}=l.default??l;if(VA=w,mi=_,i instanceof mi||typeof i?.destroy==="function")return this.externalAgent=!0,i;return new mi({keepAlive:!0,maxSockets:50,...i})},httpsAgent:(()=>{if(f instanceof Bi.Agent||typeof f?.destroy==="function")return this.externalAgent=!0,f;return new Bi.Agent({keepAlive:!0,maxSockets:50,...f})})(),logger:c}}}var VB=new Uint16Array(1);class Hi{id=VB[0]++;total=0;max=0;session;refs=0;constructor(t){t.unref(),this.session=t}retain(){if(this.session.destroyed)throw Error("@smithy/node-http-handler - cannot acquire reference to destroyed session.");this.refs+=1,this.total+=1,this.max=Math.max(this.refs,this.max),this.session.ref()}free(){if(this.session.destroyed)return;if(this.refs-=1,this.refs===0)this.session.unref();if(this.refs<0)throw Error("@smithy/node-http-handler - ClientHttp2Session refcount at zero, cannot decrement.")}deref(){return this.session}close(){if(!this.session.closed)this.session.close()}destroy(){if(this.refs=0,!this.session.destroyed)this.session.destroy()}useCount(){return this.refs}}class nM{sessions=[];maxConcurrency=0;constructor(t){this.sessions=(t??[]).map((n)=>new Hi(n))}poll(){let t=!1;for(let n of this.sessions){if(n.deref().destroyed){t=!0;continue}if(!this.maxConcurrency||n.useCount()<this.maxConcurrency)return n}if(t){for(let n of this.sessions)if(n.deref().destroyed)this.remove(n)}}offerLast(t){this.sessions.push(t)}remove(t){let n=this.sessions.indexOf(t);if(n>-1)this.sessions.splice(n,1)}[Symbol.iterator](){return this.sessions[Symbol.iterator]()}setMaxConcurrency(t){this.maxConcurrency=t}destroy(t){this.remove(t),t.destroy()}}class sM{config;connectOptions;connectionPools=new Map;constructor(t){if(this.config=t,this.config.maxConcurrency&&this.config.maxConcurrency<=0)throw RangeError("maxConcurrency must be greater than zero.")}lease(t,n){let s=this.getUrlString(t),r=this.getPool(s);if(!this.config.disableConcurrency&&!n.isEventStream){let c=r.poll();if(c)return c.retain(),c}let e=new Hi(this.connect(s)),i=e.deref();if(this.config.maxConcurrency)i.settings({maxConcurrentStreams:this.config.maxConcurrency},(c)=>{if(c)throw Error("Fail to set maxConcurrentStreams to "+this.config.maxConcurrency+"when creating new session for "+t.destination.toString())});let f=()=>{this.removeFromPoolAndClose(s,e)},o=()=>{this.removeFromPoolAndCheckedDestroy(s,e)};if(i.on("goaway",f),i.on("error",o),i.on("frameError",o),i.on("close",o),n.requestTimeout)i.setTimeout(n.requestTimeout,o);return r.offerLast(e),e.retain(),e}release(t,n){n.free()}createIsolatedSession(t,n){let s=this.getUrlString(t),r=new Hi(this.connect(s)),e=r.deref();e.settings({maxConcurrentStreams:1});let i=()=>{r.destroy()};if(e.on("error",i),e.on("frameError",i),e.on("close",i),n.requestTimeout)e.setTimeout(n.requestTimeout,i);return r.retain(),r}destroy(){for(let[t,n]of this.connectionPools){for(let s of[...n])s.destroy();this.connectionPools.delete(t)}}setMaxConcurrentStreams(t){if(t&&t<=0)throw RangeError("maxConcurrentStreams must be greater than zero.");this.config.maxConcurrency=t;for(let n of this.connectionPools.values())n.setMaxConcurrency(t)}setDisableConcurrentStreams(t){this.config.disableConcurrency=t}setNodeHttp2ConnectOptions(t){this.connectOptions=t}debug(){let t={};for(let[n,s]of this.connectionPools){let r=[];for(let e of s)r.push({id:e.id,active:e.useCount(),maxConcurrent:e.max,totalRequests:e.total});t[n]={sessions:r}}return t}removeFromPoolAndClose(t,n){this.connectionPools.get(t)?.remove(n),n.close()}removeFromPoolAndCheckedDestroy(t,n){this.connectionPools.get(t)?.remove(n),n.destroy()}getPool(t){if(!this.connectionPools.has(t)){let n=new nM;if(this.config.maxConcurrency)n.setMaxConcurrency(this.config.maxConcurrency);this.connectionPools.set(t,n)}return this.connectionPools.get(t)}getUrlString(t){return t.destination.toString()}connect(t){return this.connectOptions===void 0?kc.connect(t):kc.connect(t,this.connectOptions)}}var{constants:jA}=kc;class Xc{config;configProvider;metadata={handlerProtocol:"h2"};connectionManager=new sM({});static create(t){if(typeof t?.handle==="function")return t;return new Xc(t)}constructor(t){this.configProvider=new Promise((n,s)=>{if(typeof t==="function")t().then((r)=>{n(r||{})}).catch(s);else n(t||{})})}destroy(){this.connectionManager.destroy()}async handle(t,{abortSignal:n,requestTimeout:s,isEventStream:r}={}){if(!this.config){this.config=await this.configProvider;let{disableConcurrentStreams:c,maxConcurrentStreams:h,nodeHttp2ConnectOptions:u}=this.config;if(this.connectionManager.setDisableConcurrentStreams(c??!1),h)this.connectionManager.setMaxConcurrentStreams(h);if(u)this.connectionManager.setNodeHttp2ConnectOptions(u)}let{requestTimeout:e,disableConcurrentStreams:i}=this.config,f=i||r,o=s??e;return new Promise((c,h)=>{let u=!1,l=void 0,_=async(z)=>{await l,c(z)},w=async(z)=>{await l,h(z)};if(n?.aborted){u=!0;let z=Fi(n);w(z);return}let{hostname:A,method:M,port:d,protocol:E,query:b}=t,L="";if(t.username!=null||t.password!=null){let z=t.username??"",Gt=t.password??"";L=`${z}:${Gt}@`}let S=`${E}//${L}${A}${d?`:${d}`:""}`,O={destination:new URL(S)},x={requestTimeout:this.config?.sessionTimeout,isEventStream:r},X=f?this.connectionManager.createIsolatedSession(O,x):this.connectionManager.lease(O,x),v=X.deref(),Q=(z)=>{if(f)X.destroy();u=!0,w(z)},rt=b?pA(b):"",Dt=t.path;if(rt)Dt+=`?${rt}`;if(t.fragment)Dt+=`#${t.fragment}`;let U=v.request({...t.headers,[jA.HTTP2_HEADER_PATH]:Dt,[jA.HTTP2_HEADER_METHOD]:M});if(o)U.setTimeout(o,()=>{U.close();let z=Error(`Stream timed out because of no activity for ${o} ms`);z.name="TimeoutError",Q(z)});if(n){let z=()=>{U.close();let Gt=Fi(n);Q(Gt)};if(typeof n.addEventListener==="function"){let Gt=n;Gt.addEventListener("abort",z,{once:!0}),U.once("close",()=>Gt.removeEventListener("abort",z))}else n.onabort=z}U.on("frameError",(z,Gt,an)=>{Q(Error(`Frame type id ${z} in stream id ${an} has failed with code ${Gt}.`))}),U.on("error",Q),U.on("aborted",()=>{Q(Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${U.rstCode}.`))}),U.on("response",(z)=>{let Gt=new vA({statusCode:z[":status"]??-1,headers:ZA(z),body:U});if(u=!0,_({response:Gt}),f)v.close()}),U.on("close",()=>{if(f)X.destroy();else this.connectionManager.release(O,X);if(!u)Q(Error("Unexpected error: http2 request did not get a response"))}),l=tM(U,t,o)})}updateHttpClientConfig(t,n){this.config=void 0,this.configProvider=this.configProvider.then((s)=>{return{...s,[t]:n}})}httpHandlerConfigs(){return this.config??{}}}jB.DEFAULT_REQUEST_TIMEOUT=KB;jB.NodeHttp2Handler=Xc;jB.NodeHttpHandler=Pi});var AM=K((P3)=>{var{nv:n3,NumericValue:fM,calculateBodyLength:s3,_parseEpochTimestamp:rM,fromBase64:cM,generateIdempotencyToken:r3}=bt(),{HttpRequest:e3,collectBody:i3,SerdeContext:jc,RpcProtocol:o3}=Tt(),{NormalizedSchema:pc,deref:f3,TypeRegistry:eM}=Pn(),{getSmithyContext:c3}=tn();function ir(t){return typeof Buffer<"u"?Buffer.alloc(t):new Uint8Array(t)}var vc=Symbol("@smithy/core/cbor::tagSymbol");function Zc(t){return t[vc]=!0,t}var hM=typeof Buffer<"u",th=new TextDecoder,k=ir(0),nh=!1,Xt=new DataView(k.buffer,k.byteOffset,k.byteLength),N=0;function h3(t){k=t,nh=hM&&k instanceof Buffer,Xt=new DataView(k.buffer,k.byteOffset,k.byteLength)}function zn(t,n){if(t>=n)throw Error("unexpected end of (decode) payload.");let s=(k[t]&224)>>5,r=k[t]&31;if(r===31&&2<=s&&s<=5)return u3(t,n);switch(s){case 0:case 1:case 6:{let e,i;if(r<24)e=r,i=1;else switch(r){case 24:if(n-t<2)fn(1);e=k[t+1],i=2;break;case 25:if(n-t<3)fn(2);e=Xt.getUint16(t+1),i=3;break;case 26:if(n-t<5)fn(4);e=Xt.getUint32(t+1),i=5;break;case 27:if(n-t<9)fn(8);{let f=Xt.getUint32(t+1);if(f<2097152)e=f*4294967296+Xt.getUint32(t+5);else e=Xt.getBigUint64(t+1)}i=9;break;default:rh(r)}if(s===0)return N=i,ac(e);else if(s===1){let f;if(typeof e==="bigint")f=BigInt(-1)-e;else f=-1-e;return N=i,ac(f)}else return E3(t,n,r,e,i)}case 3:return fe(t,n);case 5:return _3(t,n);case 4:return M3(t,n);case 2:return sh(t,n);default:return R3(t,n)}}function u3(t,n){let s=(k[t]&224)>>5;if((k[t]&31)===31)switch(s){case 3:return S3(t,n);case 5:return b3(t,n);case 4:return T3(t,n);case 2:return $3(t,n)}}function l3(t,n){let s=t>>7,r=(t&124)>>2,e=(t&3)<<8|n,i=s===0?1:-1;if(r===0){if(e===0)return 0;return i*(Math.pow(2,-14)*(e/1024))}else if(r===31){if(e===0)return i*(1/0);return NaN}return i*(Math.pow(2,r-15)*(1+e/1024))}function _3(t,n){let s=ce(t,n);if(s<15)return A3(t,n,s);return w3(t,n,s)}function w3(t,n,s){let r=N;t+=r;let e=t,i=Object.create(null);for(let f=0;f<s;++f){let o=fe(t,n);if(t+=N,(k[t]&224)>>5===3)i[o]=fe(t,n);else i[o]=zn(t,n);t+=N}return N=r+(t-e),Object.setPrototypeOf(i,Object.prototype),i}function A3(t,n,s){let r=N;t+=r;let e=t,i={};for(let f=0;f<s;++f){let o=fe(t,n);t+=N,i[o]=zn(t,n),t+=N}return N=r+(t-e),i}function M3(t,n){let s=ce(t,n),r=N;t+=r;let e=t,i=Array(s);for(let f=0;f<s;++f)i[f]=zn(t,n),t+=N;return N=r+(t-e),i}function fe(t,n){let s=ce(t,n),r=N;if(t+=r,n-t<s)fn(s);if(N=r+s,s<24)return g3(t,s);if(nh)return k.toString("utf-8",t,t+s);return th.decode(k.subarray(t,t+s))}var iM=Array(2048),qc=new Uint16Array(2048),ie=0;function d3(){ie=ie+1&65535}function g3(t,n){let s=n;for(let f=0;f<n;++f)s=s*31+k[t+f]|0;let r=s>>>0&2047,e=iM[r];if(e!==void 0){if(e.length===n){let f=!0;for(let o=0;o<n;++o)if(e.charCodeAt(o)!==k[t+o]){f=!1;break}if(f)return qc[r]=ie,e}}let i=nh?k.toString("utf-8",t,t+n):th.decode(k.subarray(t,t+n));if(qc[r]!==ie)iM[r]=i,qc[r]=ie;return i}function sh(t,n){let s=ce(t,n),r=N;if(t+=r,n-t<s)fn(s);let e=k.subarray(t,t+s);return N=r+s,e}function E3(t,n,s,r,e){if(s===2||s===3){let i=ce(t+e,n),f=BigInt(0),o=t+e+N;for(let c=o;c<o+i;++c)f=f<<BigInt(8)|BigInt(k[c]);return N=e+N+i,s===3?-f-BigInt(1):f}else if(s===4){let i=zn(t+e,n),[f,o]=i,c=o<0?-1:1,h="0".repeat(Math.abs(f)+1)+String(BigInt(c)*BigInt(o)),u,l=o<0?"-":"";if(u=f===0?h:h.slice(0,h.length+f)+"."+h.slice(f),u=u.replace(/^0+/g,""),u==="")u="0";if(u[0]===".")u="0"+u;return u=l+u,N=e+N,n3(u)}else{let i=zn(t+e,n);return N=e+N,Zc({tag:ac(r),value:i})}}function R3(t,n){let s=k[t]&31;switch(s){case 21:case 20:return N=1,s===21;case 22:return N=1,null;case 23:return N=1,null;case 25:if(n-t<3)throw Error("incomplete float16 at end of buf.");return N=3,l3(k[t+1],k[t+2]);case 26:if(n-t<5)throw Error("incomplete float32 at end of buf.");return N=5,Xt.getFloat32(t+1);case 27:if(n-t<9)throw Error("incomplete float64 at end of buf.");return N=9,Xt.getFloat64(t+1);default:rh(s)}}function ce(t,n){let s=k[t]&31;if(s<24)return N=1,s;switch(s){case 24:if(n-t<2)fn(1);return N=2,k[t+1];case 25:if(n-t<3)fn(2);return N=3,Xt.getUint16(t+1);case 26:if(n-t<5)fn(4);return N=5,Xt.getUint32(t+1);case 27:if(n-t<9)fn(8);return N=9,U3(Xt.getBigUint64(t+1));default:rh(s)}}function b3(t,n){t+=1;let s=t,r={};for(;t<n;){if(k[t]===255)return N=t-s+2,r;let e=fe(t,n);t+=N,r[e]=zn(t,n),t+=N}throw Error("expected break marker.")}function T3(t,n){t+=1;let s=[];for(let r=t;t<n;){if(k[t]===255)return N=t-r+2,s;s.push(zn(t,n)),t+=N}throw Error("expected break marker.")}function S3(t,n){t+=1;let s=[];for(let r=t;t<n;){if(k[t]===255){let c=ir(s.length);if(c.set(s,0),N=t-r+2,hM)return c.toString("utf-8",0,c.length);return th.decode(c)}let e=(k[t]&224)>>5,i=k[t]&31;if(e!==3)uM(e);if(i===31)throw Error("nested indefinite string.");let f=sh(t,n);t+=N;for(let c=0;c<f.length;++c)s.push(f[c])}throw Error("expected break marker.")}function $3(t,n){t+=1;let s=[];for(let r=t;t<n;){if(k[t]===255){let c=ir(s.length);return c.set(s,0),N=t-r+2,c}let e=(k[t]&224)>>5,i=k[t]&31;if(e!==2)uM(e);if(i===31)throw Error("nested indefinite string.");let f=sh(t,n);t+=N;for(let c=0;c<f.length;++c)s.push(f[c])}throw Error("expected break marker.")}function ac(t){if(typeof t==="number")return t;let n=Number(t);if(Number.MIN_SAFE_INTEGER<=n&&n<=Number.MAX_SAFE_INTEGER)return n;return t}function U3(t){let n=Number(t);if(n<Number.MIN_SAFE_INTEGER||Number.MAX_SAFE_INTEGER<n)console.warn(Error(`@smithy/core/cbor - truncating BigInt(${t}) to ${n} with loss of precision.`));return n}function fn(t){throw Error(`length ${t} greater than remaining buf len.`)}function rh(t){throw Error(`unexpected minor value ${t}.`)}function uM(t){throw Error(`unexpected major type ${t} in indefinite string.`)}var L3=typeof Buffer<"u",rr=new Map,oe=0,Kc=!1,I3=2048,m=ir(I3),Ht=new DataView(m.buffer,m.byteOffset,m.byteLength),I=0;function O3(t){let n=[t];while(n.length){let s=n.pop();if(typeof s==="string"){let r=s.length;if(L3)if(er(r*3+9),r>23)Cc(3,Buffer.byteLength(s)),I+=m.write(s,I);else G3(s);else{let e=r*3;er(e+9);let i=I,o=new TextEncoder().encodeInto(s,m.subarray(I+9)).written,c;if(o<24)c=1;else if(o<256)c=2;else if(o<65536)c=3;else if(o<4294967296)c=5;else c=9;if(c<9)m.copyWithin(i+c,i+9,i+9+o);I=i,ws(3,o),I+=o}continue}if(m.byteLength-I<9)er(64);if(typeof s==="number"){if(Number.isInteger(s)){let r=s>=0,e=r?0:1,i=r?s:-s-1;if(i<24)m[I++]=e<<5|i;else if(i<256)m[I++]=e<<5|24,m[I++]=i;else if(i<65536)m[I++]=e<<5|25,m[I++]=i>>8,m[I++]=i&255;else if(i<4294967296)m[I++]=e<<5|26,Ht.setUint32(I,i),I+=4;else{m[I++]=e<<5|27;let f=i/4294967296|0,o=i-f*4294967296|0;Ht.setUint32(I,f),Ht.setUint32(I+4,o),I+=8}continue}m[I++]=251,Ht.setFloat64(I,s),I+=8;continue}else if(typeof s==="bigint"){let r=s>=0,e=r?0:1,i=r?s:-s-BigInt(1);if(i<BigInt("18446744073709551616")){let f=Number(i);if(f<4294967296)ws(e,f);else m[I++]=e<<5|27,Ht.setBigUint64(I,i),I+=8}else{let f=i.toString(2),o=new Uint8Array(Math.ceil(f.length/8)),c=i,h=0;while(o.byteLength-++h>=0)o[o.byteLength-h]=Number(c&BigInt(255)),c>>=BigInt(8);er(o.byteLength*2+16),m[I++]=r?194:195,Cc(2,o.byteLength),m.set(o,I),I+=o.byteLength}continue}else if(s===null){m[I++]=246;continue}else if(typeof s==="boolean"){m[I++]=224|(s?21:20);continue}else if(typeof s>"u")throw Error("@smithy/core/cbor: client may not serialize undefined value.");else if(Array.isArray(s)){ws(4,s.length),er(s.length*9+64);for(let r=s.length-1;r>=0;--r)n.push(s[r]);continue}else if(typeof s.byteLength==="number"){er(s.length*2+9),ws(2,s.length),m.set(s,I),I+=s.byteLength;continue}else if(typeof s==="object"){if(s instanceof fM){let i=s.string.indexOf("."),f=i===-1?0:i-s.string.length+1,o=BigInt(s.string.replace(".",""));m[I++]=196,ws(4,2),n.push(o),n.push(f);continue}if(s[vc])if("tag"in s&&"value"in s){n.push(s.value),Cc(6,s.tag);continue}else throw Error("tag encountered with missing fields, need 'tag' and 'value', found: "+JSON.stringify(s));let r=Object.keys(s),e=r.length;ws(5,e);for(let i=e-1;i>=0;--i)n.push(s[r[i]]),n.push(r[i]);continue}throw Error(`data type ${s?.constructor?.name??typeof s} not compatible for encoding.`)}}function y3(){oe=oe+1&65535,Kc=!1}function oM(){let t=ir(I);return t.set(m.subarray(0,I),0),I=0,t}function Vc(t){let n=m;if(m=ir(t),n)if(n.copy)n.copy(m,0,0,n.byteLength);else m.set(n,0);Ht=new DataView(m.buffer,m.byteOffset,m.byteLength)}function G3(t){let n=rr.get(t);if(n!==void 0){m.set(n.bytes,I),I+=n.bytes.length,n.epoch=oe;return}let s=I,r=Buffer.byteLength(t);ws(3,r),I+=m.write(t,I);let e=Uint8Array.prototype.slice.call(m,s,I);if(rr.size>=2048){if(Kc)return;let i=0;for(let[f,o]of rr){if(i>=1024)break;if(o.epoch!==oe)rr.delete(f),i++}if(i===0){Kc=!0;return}}if(rr.size<2048)rr.set(t,{epoch:oe,bytes:e})}function er(t){if(m.byteLength-I<t)if(I<16000000)Vc(Math.max(m.byteLength*4,m.byteLength+t));else Vc(m.byteLength+t+16000000)}function Cc(t,n){if(n<24)m[I++]=t<<5|n;else if(n<256)m[I++]=t<<5|24,m[I++]=n;else if(n<65536)m[I++]=t<<5|25,Ht.setUint16(I,n),I+=2;else if(n<4294967296)m[I++]=t<<5|26,Ht.setUint32(I,n),I+=4;else m[I++]=t<<5|27,Ht.setBigUint64(I,typeof n==="bigint"?n:BigInt(n)),I+=8}function ws(t,n){if(n<24)m[I++]=t<<5|n;else if(n<256)m[I++]=t<<5|24,m[I++]=n;else if(n<65536)m[I++]=t<<5|25,m[I++]=n>>8,m[I++]=n&255;else if(n<4294967296)m[I++]=t<<5|26,Ht.setUint32(I,n),I+=4;else{m[I++]=t<<5|27;let s=n/4294967296|0,r=n-s*4294967296|0;Ht.setUint32(I,s),Ht.setUint32(I+4,r),I+=8}}var Wi={deserialize(t){return d3(),h3(t),zn(0,t.length)},serialize(t){y3();try{return O3(t),oM()}catch(n){throw oM(),n}},resizeEncodingBuffer(t){Vc(t)}},lM=(t,n)=>{return i3(t,n).then(async(s)=>{if(s.length)try{return Wi.deserialize(s)}catch(r){throw Object.defineProperty(r,"$responseBodyText",{value:n.utf8Encoder(s)}),r}return{}})},Di=(t)=>{return Zc({tag:1,value:t.getTime()/1000})},B3=async(t,n)=>{let s=await lM(t,n);return s.message=s.message??s.Message,s},_M=(t,n)=>{let s=(e)=>{let i=e;if(typeof i==="number")i=i.toString();if(i.indexOf(",")>=0)i=i.split(",")[0];if(i.indexOf(":")>=0)i=i.split(":")[0];if(i.indexOf("#")>=0)i=i.split("#")[1];return i};if(n.__type!==void 0)return s(n.__type);let r;for(let e in n)if(e.toLowerCase()==="code"){r=e;break}if(r&&n[r]!==void 0)return s(n[r])},m3=(t)=>{if(String(t.headers["smithy-protocol"]).toLowerCase()!=="rpc-v2-cbor")throw Error("Malformed RPCv2 CBOR response, status: "+t.statusCode)},F3=async(t,n,s,r,e)=>{let i=await t.endpoint(),{hostname:f,protocol:o="https",port:c,path:h}=i,u={protocol:o,hostname:f,port:c,method:"POST",path:h.endsWith("/")?h.slice(0,-1)+s:h+s,headers:{...n}};if(r!==void 0)u.hostname=r;if(i.headers)for(let l in i.headers)u.headers[l]=i.headers[l];if(e!==void 0){u.body=e;try{u.headers["content-length"]=String(s3(e))}catch(l){}}return new e3(u)};class eh extends jc{createSerializer(){let t=new ih;return t.setSerdeContext(this.serdeContext),t}createDeserializer(){let t=new oh;return t.setSerdeContext(this.serdeContext),t}}class ih extends jc{value;write(t,n){this.value=this.serialize(t,n)}serialize(t,n){let s=pc.of(t);if(n==null){if(s.isIdempotencyToken())return r3();return n}if(s.isBlobSchema()){if(typeof n==="string")return(this.serdeContext?.base64Decoder??cM)(n);return n}if(s.isTimestampSchema()){if(typeof n==="number"||typeof n==="bigint")return Di(new Date(Number(n)/1000|0));return Di(n)}if(typeof n==="function"||typeof n==="object"){let r=n;if(s.isListSchema()&&Array.isArray(r)){let i=!!s.getMergedTraits().sparse,f=[],o=0;for(let c of r){let h=this.serialize(s.getValueSchema(),c);if(h!=null||i)f[o++]=h}return f}if(r instanceof Date)return Di(r);let e={};if(s.isMapSchema()){let i=!!s.getMergedTraits().sparse;for(let f in r){let o=this.serialize(s.getValueSchema(),r[f]);if(o!=null||i)e[f]=o}}else if(s.isStructSchema()){for(let[f,o]of s.structIterator()){let c=this.serialize(o,r[f]);if(c!=null)e[f]=c}if(s.isUnionSchema()&&Array.isArray(r.$unknown)){let[f,o]=r.$unknown;e[f]=o}else if(typeof r.__type==="string"){for(let f in r)if(!(f in e))e[f]=this.serialize(15,r[f])}}else if(s.isDocumentSchema())for(let i in r)e[i]=this.serialize(s.getValueSchema(),r[i]);else if(s.isBigDecimalSchema())return r;return e}return n}flush(){let t=Wi.serialize(this.value);return this.value=void 0,t}}class oh extends jc{read(t,n){let s=Wi.deserialize(n);return this.readValue(t,s)}readValue(t,n){let s=pc.of(t);if(s.isTimestampSchema()){if(typeof n==="number")return rM(n);if(typeof n==="object"){if(n.tag===1&&"value"in n)return rM(n.value)}}if(s.isBlobSchema()){if(typeof n==="string")return(this.serdeContext?.base64Decoder??cM)(n);return n}if(typeof n>"u"||typeof n==="boolean"||typeof n==="number"||typeof n==="string"||typeof n==="bigint"||typeof n==="symbol")return n;else if(typeof n==="object"){if(n===null)return null;if("byteLength"in n)return n;if(n instanceof Date)return n;if(s.isDocumentSchema())return n;if(s.isListSchema()){let e=[],i=s.getValueSchema();for(let f of n){let o=this.readValue(i,f);e.push(o)}return e}let r={};if(s.isMapSchema()){let e=s.getValueSchema();for(let i in n){let f=this.readValue(e,n[i]);r[i]=f}}else if(s.isStructSchema()){let e=s.isUnionSchema(),i;if(e){i=new Set;for(let f in n)if(f!=="__type")i.add(f)}for(let[f,o]of s.structIterator()){if(e)i.delete(f);if(n[f]!=null)r[f]=this.readValue(o,n[f])}if(e&&i?.size===1){let f=!0;for(let o in r){f=!1;break}if(f){let o=i.values().next().value;r.$unknown=[o,n[o]]}}else if(typeof n.__type==="string"){for(let f in n)if(!(f in r))r[f]=n[f]}}else if(n instanceof fM)return n;return r}else return n}}class wM extends o3{codec=new eh;serializer=this.codec.createSerializer();deserializer=this.codec.createDeserializer();constructor({defaultNamespace:t,errorTypeRegistries:n}){super({defaultNamespace:t,errorTypeRegistries:n})}getShapeId(){return"smithy.protocols#rpcv2Cbor"}getPayloadCodec(){return this.codec}async serializeRequest(t,n,s){let r=await super.serializeRequest(t,n,s);if(Object.assign(r.headers,{"content-type":this.getDefaultContentType(),"smithy-protocol":"rpc-v2-cbor",accept:this.getDefaultContentType()}),f3(t.input)==="unit")delete r.body,delete r.headers["content-type"];else{if(!r.body)this.serializer.write(15,{}),r.body=this.serializer.flush();try{r.headers["content-length"]=String(r.body.byteLength)}catch(o){}}let{service:e,operation:i}=c3(s),f=`/service/${e}/operation/${i}`;if(r.path.endsWith("/"))r.path+=f.slice(1);else r.path+=f;return r}async deserializeResponse(t,n,s){return super.deserializeResponse(t,n,s)}async handleError(t,n,s,r,e){let i=_M(s,r)??"Unknown",f={$metadata:e,$fault:s.statusCode<=500?"client":"server"},o=this.options.defaultNamespace;if(i.includes("#"))[o]=i.split("#");let c=this.compositeErrorRegistry,h=eM.for(o);c.copyFrom(h);let u;try{u=c.getSchema(i)}catch(d){if(r.Message)r.message=r.Message;let E=eM.for("smithy.ts.sdk.synthetic."+o);c.copyFrom(E);let b=c.getBaseException();if(b){let L=c.getErrorCtor(b);throw Object.assign(new L({name:i}),f,r)}throw Object.assign(Error(i),f,r)}let l=pc.of(u),_=c.getErrorCtor(u),w=r.message??r.Message??"Unknown",A=new _({}),M={};for(let[d,E]of l.structIterator())M[d]=this.deserializer.readValue(E,r[d]);throw Object.assign(A,f,{$fault:l.getMergedTraits().error,message:w},M)}getDefaultContentType(){return"application/cbor"}}P3.CborCodec=eh;P3.CborShapeDeserializer=oh;P3.CborShapeSerializer=ih;P3.SmithyRpcV2CborProtocol=wM;P3.buildHttpRpcRequest=F3;P3.cbor=Wi;P3.checkCborResponse=m3;P3.dateToTag=Di;P3.loadSmithyRpcV2CborErrorCode=_M;P3.parseCborBody=lM;P3.parseCborErrorBody=B3;P3.tag=Zc;P3.tagSymbol=vc});var MM=K((tm)=>{var a3=/[&<>"]/g,K3={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"};function V3(t){return t.replace(a3,(n)=>K3[n])}var j3=/[&"'<>\r\n\u0085\u2028]/g,p3={"&":"&amp;",'"':"&quot;","'":"&apos;","<":"&lt;",">":"&gt;","\r":"&#x0D;","\n":"&#x0A;","\x85":"&#x85;","\u2028":"&#x2028;"};function v3(t){return t.replace(j3,(n)=>p3[n])}class fh{value;constructor(t){this.value=t}toString(){return v3(""+this.value)}}class he{name;children;attributes={};static of(t,n,s){let r=new he(t);if(n!==void 0)r.addChildNode(new fh(n));if(s!==void 0)r.withName(s);return r}constructor(t,n=[]){this.name=t,this.children=n}withName(t){return this.name=t,this}addAttribute(t,n){return this.attributes[t]=n,this}addChildNode(t){return this.children.push(t),this}removeAttribute(t){return delete this.attributes[t],this}n(t){return this.name=t,this}c(t){return this.children.push(t),this}a(t,n){if(n!=null)this.attributes[t]=n;return this}cc(t,n,s=n){if(t[n]!=null){let r=he.of(n,t[n]).withName(s);this.c(r)}}l(t,n,s,r){if(t[n]!=null)r().map((i)=>{i.withName(s),this.c(i)})}lc(t,n,s,r){if(t[n]!=null){let e=r(),i=new he(s);e.map((f)=>{i.c(f)}),this.c(i)}}toString(){let t=Boolean(this.children.length),n=`<${this.name}`,s=this.attributes;for(let r of Object.keys(s)){let e=s[r];if(e!=null)n+=` ${r}="${V3(""+e)}"`}return n+=!t?"/>":`>${this.children.map((r)=>r.toString()).join("")}</${this.name}>`}}function Z3(t){return new ch(t).parse()}class ch{x;i=0;z;constructor(t){this.x=t,this.x=t.replace(/\r\n?/g,`
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={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"};function RF(t){return t.replace(EF,(n)=>dF[n])}var bF=/[&"'<>\r\n\u0085\u2028]/g,TF={"&":"&amp;",'"':"&quot;","'":"&apos;","<":"&lt;",">":"&gt;","\r":"&#x0D;","\n":"&#x0A;","\x85":"&#x85;","\u2028":"&#x2028;"};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
44
  `),this.z=this.x.length}parse(){let t=this,{z:n}=t;while(t.i<n){if(t.trim(),t.i>=n)break;if(t.isNext("<?"))t.readTo("?>"),t.trim();else if(t.isNext("<!--"))t.readTo("-->"),t.trim();else if(t.isNext("<!DOCTYPE",!1))t.skipDoctype(),t.trim();else if(t.x[t.i]==="<"){let s=t.parseTag();return{[s.tag]:s.value}}else throw Error("@aws-sdk XML parse error: unexpected content.")}throw Error("@aws-sdk XML parse error: no root element.")}isNext(t,n=!0){let s=this;if(n)return s.x.startsWith(t,s.i);return s.x.toLowerCase().startsWith(t.toLowerCase(),s.i)}readTo(t){let n=this,s=n.x.indexOf(t,n.i);if(s===-1)throw Error(`@aws-sdk XML parse error: expected "${t}" not found.`);let r=n.x.slice(n.i,s);return n.i=s+t.length,r}trim(){let t=this;while(t.i<t.z&&` \r
45
45
  `.includes(t.x[t.i]))++t.i}readAttrValue(){let t=this,n=t.x[t.i];++t.i;let s="";while(t.i<t.z&&t.x[t.i]!==n)s+=t.x[t.i++];return++t.i,t.decodeEntities(s)}parseTag(){let t=this;++t.i;let n="";while(t.i<t.z&&!` \r
46
46
  >/`.includes(t.x[t.i]))n+=t.x[t.i++];let s=!1,r=Object.create(null);while(t.i<t.z){if(t.trim(),">/".includes(t.x[t.i]))break;let h="";while(t.i<t.z&&!`= \r
47
- >/?`.includes(t.x[t.i]))h+=t.x[t.i++];if(t.trim(),t.x[t.i]!=="=")break;++t.i,t.trim(),r[h]=t.readAttrValue(),s=!0}if(t.i>=t.z)throw Error("@aws-sdk XML parse error: unexpected end of input.");if(t.x[t.i]==="/"){if(++t.i,t.i>=t.z||t.x[t.i]!==">")throw Error("@aws-sdk XML parse error: expected > at the end of self-closing tag.");return++t.i,Object.setPrototypeOf(r,Object.prototype),{tag:n,value:s?r:""}}if(t.x[t.i]!==">")throw Error("@aws-sdk XML parse error: expected > at the end of opening tag.");++t.i;let e=[],i=[],f=!1;while(t.i<t.z){if(t.isNext("</"))break;if(t.x[t.i]==="<")if(t.isNext("<!--"))t.readTo("-->");else if(t.isNext("<![CDATA["))t.i+=9,e.push(t.readTo("]]>"));else if(t.isNext("<?"))t.readTo("?>");else f=!0,i.push(t.parseTag());else{let h="";while(t.i<t.z&&t.x[t.i]!=="<")h+=t.x[t.i++];e.push(t.decodeEntities(h))}}if(!t.isNext("</"))throw Error(`@aws-sdk XML parse error: missing closing tag </${n}>.`);t.i+=2;let o=t.readTo(">").trim();if(o!==n)throw Error(`@aws-sdk XML parse error: mismatched tags <${n}> and </${o}>.`);if(!s&&e.length===0&&!f)return{tag:n,value:""};if(!s&&!f){let h=e.length===1?e[0]:e.join("");if(h.trim()===""&&h.includes(`
48
- `))return{tag:n,value:""};return{tag:n,value:h}}let c=Object.create(null);for(let h of e){if(h.trim()===""&&h.includes(`
49
- `))continue;c["#text"]="#text"in c?c["#text"]+h:h}for(let h of i)if(h.tag in c)if(Array.isArray(c[h.tag]))c[h.tag].push(h.value);else c[h.tag]=[c[h.tag],h.value];else c[h.tag]=h.value;for(let[h,u]of Object.entries(r))c[h]=u;return Object.setPrototypeOf(c,Object.prototype),{tag:n,value:c}}static ENTITIES={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};skipDoctype(){let t=this;t.i+=9;let n=0;while(t.i<t.z){let s=t.x[t.i];if(s==="[")++n;else if(s==="]")--n;else if(s===">"&&n===0){++t.i;return}++t.i}throw Error("@aws-sdk XML parse error: unclosed DOCTYPE.")}decodeEntities(t){return t.replace(/&(?:#x([0-9a-fA-F]{1,6})|#(\d{1,7})|([a-zA-Z][a-zA-Z0-9]{0,30}));/g,(n,s,r,e)=>{if(s)return String.fromCharCode(parseInt(s,16));if(r)return String.fromCharCode(parseInt(r,10));return ch.ENTITIES[e]??""})}}tm.XmlNode=he;tm.XmlText=fh;tm.parseXML=Z3});var bh=K((Em)=>{var{SmithyRpcV2CborProtocol:em,loadSmithyRpcV2CborErrorCode:im}=AM(),{TypeRegistry:dM,NormalizedSchema:et,deref:SM}=Pn(),{decorateServiceException:gM,getValueFromTextNode:$M}=En(),{collectBody:uh,determineTimestampFormat:Qi,RpcProtocol:UM,HttpBindingProtocol:LM,HttpInterceptingShapeSerializer:IM,HttpInterceptingShapeDeserializer:OM,FromStringShapeDeserializer:om,extendedEncodeURIComponent:EM}=Tt(),{NumericValue:cn,toUtf8:yM,fromBase64:GM,LazyJsonString:BM,parseEpochTimestamp:fm,parseRfc7231DateTime:cm,parseRfc3339DateTimeWithOffset:hm,toBase64:Yi,dateToUtcString:xi,generateIdempotencyToken:lh,expectUnion:um}=bt(),{parseXML:mM,XmlNode:qt,XmlText:RM}=MM();class or{queryCompat;errorRegistry;constructor(t=!1){this.queryCompat=t}resolveRestContentType(t,n){let s=n.getMemberSchemas(),r=Object.values(s).find((e)=>{return!!e.getMergedTraits().httpPayload});if(r){let e=r.getMergedTraits().mediaType;if(e)return e;else if(r.isStringSchema())return"text/plain";else if(r.isBlobSchema())return"application/octet-stream";else return t}else if(!n.isUnitSchema()){if(Object.values(s).find((i)=>{let{httpQuery:f,httpQueryParams:o,httpHeader:c,httpLabel:h,httpPrefixHeaders:u}=i.getMergedTraits();return!f&&!o&&!c&&!h&&u===void 0}))return t}}async getErrorSchemaOrThrowBaseException(t,n,s,r,e,i){let f=t;if(t.includes("#"))[,f]=t.split("#");let o={$metadata:e,$fault:s.statusCode<500?"client":"server"};if(!this.errorRegistry)throw Error("@aws-sdk/core/protocols - error handler not initialized.");try{return{errorSchema:i?.(this.errorRegistry,f)??this.errorRegistry.getSchema(t),errorMetadata:o}}catch(c){r.message=r.message??r.Message??"UnknownError";let h=this.errorRegistry,u=h.getBaseException();if(u){let w=h.getErrorCtor(u)??Error;throw this.decorateServiceException(Object.assign(new w({name:f}),o),r)}let l=r,_=l?.message??l?.Message??l?.Error?.Message??l?.Error?.message;throw this.decorateServiceException(Object.assign(Error(_),{name:f},o),r)}}compose(t,n,s){let r=s;if(n.includes("#"))[r]=n.split("#");let e=dM.for(r),i=dM.for("smithy.ts.sdk.synthetic."+s);t.copyFrom(e),t.copyFrom(i),this.errorRegistry=t}decorateServiceException(t,n={}){if(this.queryCompat){let s=t.Message??n.Message,r=gM(t,n);if(s)r.message=s;let e=r.Error??{};e.Type=r.Error?.Type,e.Code=r.Error?.Code,e.Message=r.Error?.message??r.Error?.Message??s,r.Error=e;let i=r.$metadata.requestId;if(i)r.RequestId=i;return r}return gM(t,n)}setQueryCompatError(t,n){let s=n.headers?.["x-amzn-query-error"];if(t!==void 0&&s!=null){let[r,e]=s.split(";"),i=Object.keys(t),f={Code:r,Type:e};t.Code=r,t.Type=e;for(let o=0;o<i.length;o++){let c=i[o];f[c==="message"?"Message":c]=t[c]}delete f.__type,t.Error=f}}queryCompatOutput(t,n){if(t.Error)n.Error=t.Error;if(t.Type)n.Type=t.Type;if(t.Code)n.Code=t.Code}findQueryCompatibleError(t,n){try{return t.getSchema(n)}catch(s){return t.find((r)=>et.of(r).getMergedTraits().awsQueryError?.[0]===n)}}}class FM extends em{awsQueryCompatible;mixin;constructor({defaultNamespace:t,errorTypeRegistries:n,awsQueryCompatible:s}){super({defaultNamespace:t,errorTypeRegistries:n});this.awsQueryCompatible=!!s,this.mixin=new or(this.awsQueryCompatible)}async serializeRequest(t,n,s){let r=await super.serializeRequest(t,n,s);if(this.awsQueryCompatible)r.headers["x-amzn-query-mode"]="true";return r}async handleError(t,n,s,r,e){if(this.awsQueryCompatible)this.mixin.setQueryCompatError(r,s);let i=(()=>{let w=s.headers["x-amzn-query-error"];if(w&&this.awsQueryCompatible)return w.split(";")[0];return im(s,r)??"Unknown"})();this.mixin.compose(this.compositeErrorRegistry,i,this.options.defaultNamespace);let{errorSchema:f,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(i,this.options.defaultNamespace,s,r,e,this.awsQueryCompatible?this.mixin.findQueryCompatibleError:void 0),c=et.of(f),h=r.message??r.Message??"UnknownError",l=new(this.compositeErrorRegistry.getErrorCtor(f)??Error)({}),_={};for(let[w,A]of c.structIterator())if(r[w]!=null)_[w]=this.deserializer.readValue(A,r[w]);if(this.awsQueryCompatible)this.mixin.queryCompatOutput(r,_);throw this.mixin.decorateServiceException(Object.assign(l,o,{$fault:c.getMergedTraits().error,message:h},_),r)}}var lm=(t)=>{if(t==null)return t;if(typeof t==="number"||typeof t==="bigint"){let n=Error(`Received number ${t} where a string was expected.`);return n.name="Warning",console.warn(n),String(t)}if(typeof t==="boolean"){let n=Error(`Received boolean ${t} where a string was expected.`);return n.name="Warning",console.warn(n),String(t)}return t},_m=(t)=>{if(t==null)return t;if(typeof t==="string"){let n=t.toLowerCase();if(t!==""&&n!=="false"&&n!=="true"){let s=Error(`Received string "${t}" where a boolean was expected.`);s.name="Warning",console.warn(s)}return t!==""&&n!=="false"}return t},wm=(t)=>{if(t==null)return t;if(typeof t==="string"){let n=Number(t);if(n.toString()!==t){let s=Error(`Received string "${t}" where a number was expected.`);return s.name="Warning",console.warn(s),t}return n}return t};class kn{serdeContext;setSerdeContext(t){this.serdeContext=t}}class _h{from;to;keys;constructor(t,n){this.from=t,this.to=n;let s=Object.keys(this.from),r=new Set(s);r.delete("__type"),this.keys=r}mark(t){this.keys.delete(t)}hasUnknown(){return this.keys.size===1&&Object.keys(this.to).length===0}writeUnknown(){if(this.hasUnknown()){let t=this.keys.values().next().value,n=this.from[t];this.to.$unknown=[t,n]}}}function Am(t,n,s){if(s?.source){let r=s.source;if(typeof n==="number"){if(n>Number.MAX_SAFE_INTEGER||n<Number.MIN_SAFE_INTEGER||r!==String(n))if(r.includes("."))return new cn(r,"bigDecimal");else return BigInt(r)}}return n}var PM=(t,n)=>uh(t,n).then((s)=>(n?.utf8Encoder??yM)(s)),wh=(t,n)=>PM(t,n).then((s)=>{if(s.length)try{return JSON.parse(s)}catch(r){if(r?.name==="SyntaxError")Object.defineProperty(r,"$responseBodyText",{value:s});throw r}return{}}),Mm=async(t,n)=>{let s=await wh(t,n);return s.message=s.message??s.Message,s},bM=(t,n)=>Object.keys(t).find((s)=>s.toLowerCase()===n.toLowerCase()),hh=(t)=>{let n=t;if(typeof n==="number")n=n.toString();if(n.indexOf(",")>=0)n=n.split(",")[0];if(n.indexOf(":")>=0)n=n.split(":")[0];if(n.indexOf("#")>=0)n=n.split("#")[1];return n},HM=(t,n)=>{return DM(t,n,["header","code","type"])},NM=(t,n,s=!1)=>{return DM(t,n,s?["code","header","type"]:["type","code","header"])},DM=({headers:t},n,s)=>{while(s.length>0)switch(s.shift()){case"header":let e=bM(t??{},"x-amzn-errortype");if(e!==void 0)return hh(t[e]);break;case"code":let i=bM(n??{},"code");if(i&&n[i]!==void 0)return hh(n[i]);break;case"type":if(n?.__type!==void 0)return hh(n.__type);break}};class Ah extends kn{settings;constructor(t){super();this.settings=t}async read(t,n){return this._read(t,typeof n==="string"?JSON.parse(n,Am):await wh(n,this.serdeContext))}readObject(t,n){return this._read(t,n)}_read(t,n){let s=n!==null&&typeof n==="object",r=et.of(t);if(s){if(r.isStructSchema()){let i=n,f=r.isUnionSchema(),o={},c=void 0,{jsonName:h}=this.settings;if(h)c={};let u;if(f)u=new _h(i,o);for(let[l,_]of r.structIterator()){let w=l;if(h)w=_.getMergedTraits().jsonName??w,c[w]=l;if(f)u.mark(w);if(i[w]!=null)o[l]=this._read(_,i[w])}if(f)u.writeUnknown();else if(typeof i.__type==="string")for(let l in i){let _=i[l],w=h?c[l]??l:l;if(!(w in o))o[w]=_}return o}if(Array.isArray(n)&&r.isListSchema()){let i=r.getValueSchema(),f=[];for(let o of n)f.push(this._read(i,o));return f}if(r.isMapSchema()){let i=r.getValueSchema(),f={};for(let o in n)f[o]=this._read(i,n[o]);return f}}if(r.isBlobSchema()&&typeof n==="string")return GM(n);let e=r.getMergedTraits().mediaType;if(r.isStringSchema()&&typeof n==="string"&&e){if(e==="application/json"||e.endsWith("+json"))return BM.from(n);return n}if(r.isTimestampSchema()&&n!=null)switch(Qi(r,this.settings)){case 5:return hm(n);case 6:return cm(n);case 7:return fm(n);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",n),new Date(n)}if(r.isBigIntegerSchema()&&(typeof n==="number"||typeof n==="string"))return BigInt(n);if(r.isBigDecimalSchema()&&n!=null){if(n instanceof cn)return n;let i=n;if(i.type==="bigDecimal"&&"string"in i)return new cn(i.string,i.type);return new cn(String(n),"bigDecimal")}if(r.isNumericSchema()&&typeof n==="string"){switch(n){case"Infinity":return 1/0;case"-Infinity":return-1/0;case"NaN":return NaN}return n}if(r.isDocumentSchema())if(s){let i=Array.isArray(n)?[]:{};for(let f in n){let o=n[f];if(o instanceof cn)i[f]=o;else i[f]=this._read(r,o)}return i}else return structuredClone(n);return n}}var TM=String.fromCharCode(925);class WM{values=new Map;counter=0;stage=0;createReplacer(){if(this.stage===1)throw Error("@aws-sdk/core/protocols - JsonReplacer already created.");if(this.stage===2)throw Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");return this.stage=1,(t,n)=>{if(n instanceof cn){let s=`${TM+"nv"+this.counter++}_`+n.string;return this.values.set(`"${s}"`,n.string),s}if(typeof n==="bigint"){let s=n.toString(),r=`${TM+"b"+this.counter++}_`+s;return this.values.set(`"${r}"`,s),r}return n}}replaceInJson(t){if(this.stage===0)throw Error("@aws-sdk/core/protocols - JsonReplacer not created yet.");if(this.stage===2)throw Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");if(this.stage=2,this.counter===0)return t;for(let[n,s]of this.values)t=t.replace(n,s);return t}}class Mh extends kn{settings;buffer;useReplacer=!1;rootSchema;constructor(t){super();this.settings=t}write(t,n){this.rootSchema=et.of(t),this.buffer=this._write(this.rootSchema,n)}flush(){let{rootSchema:t,useReplacer:n}=this;if(this.rootSchema=void 0,this.useReplacer=!1,t?.isStructSchema()||t?.isDocumentSchema()){if(!n)return JSON.stringify(this.buffer);let s=new WM;return s.replaceInJson(JSON.stringify(this.buffer,s.createReplacer(),0))}return this.buffer}writeDiscriminatedDocument(t,n){if(this.write(t,n),typeof this.buffer==="object")this.buffer.__type=et.of(t).getName(!0)}_write(t,n,s){let r=n!==null&&typeof n==="object",e=et.of(t);if(r){if(e.isStructSchema()){let i=n,f={},{jsonName:o}=this.settings,c=void 0;if(o)c={};let h=0;for(let[u,l]of e.structIterator()){let _=this._write(l,i[u],e);if(_!==void 0){let w=u;if(o)w=l.getMergedTraits().jsonName??u,c[u]=w;f[w]=_,h++}}if(e.isUnionSchema()&&h===0){let{$unknown:u}=i;if(Array.isArray(u)){let[l,_]=u;f[l]=this._write(15,_)}}else if(typeof i.__type==="string")for(let u in i){let l=i[u],_=o?c[u]??u:u;if(!(_ in f))f[_]=this._write(15,l)}return f}if(Array.isArray(n)&&e.isListSchema()){let i=e.getValueSchema(),f=[],o=!!e.getMergedTraits().sparse;for(let c of n)if(o||c!=null)f.push(this._write(i,c));return f}if(e.isMapSchema()){let i=e.getValueSchema(),f={},o=!!e.getMergedTraits().sparse;for(let c in n){let h=n[c];if(o||h!=null)f[c]=this._write(i,h)}return f}if(n instanceof Uint8Array&&(e.isBlobSchema()||e.isDocumentSchema())){if(e===this.rootSchema)return n;return(this.serdeContext?.base64Encoder??Yi)(n)}if(n instanceof Date&&(e.isTimestampSchema()||e.isDocumentSchema()))switch(Qi(e,this.settings)){case 5:return n.toISOString().replace(".000Z","Z");case 6:return xi(n);case 7:return n.getTime()/1000;default:return console.warn("Missing timestamp format, using epoch seconds",n),n.getTime()/1000}if(n instanceof cn)this.useReplacer=!0}if(n===null&&s?.isStructSchema())return;if(e.isStringSchema()){if(typeof n>"u"&&e.isIdempotencyToken())return lh();let i=e.getMergedTraits().mediaType;if(n!=null&&i){if(i==="application/json"||i.endsWith("+json"))return BM.from(n)}return n}if(typeof n==="number"&&e.isNumericSchema()){if(Math.abs(n)===1/0||isNaN(n))return String(n);return n}if(typeof n==="string"&&e.isBlobSchema()){if(e===this.rootSchema)return n;return(this.serdeContext?.base64Encoder??Yi)(n)}if(typeof n==="bigint")this.useReplacer=!0;if(e.isDocumentSchema())if(r){let i=Array.isArray(n)?[]:{};for(let f in n){let o=n[f];if(o instanceof cn)this.useReplacer=!0,i[f]=o;else i[f]=this._write(e,o)}return i}else return structuredClone(n);return n}}class Ji extends kn{settings;constructor(t){super();this.settings=t}createSerializer(){let t=new Mh(this.settings);return t.setSerdeContext(this.serdeContext),t}createDeserializer(){let t=new Ah(this.settings);return t.setSerdeContext(this.serdeContext),t}}class zi extends UM{serializer;deserializer;serviceTarget;codec;mixin;awsQueryCompatible;constructor({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:r,jsonCodec:e}){super({defaultNamespace:t,errorTypeRegistries:n});this.serviceTarget=s,this.codec=e??new Ji({timestampFormat:{useTrait:!0,default:7},jsonName:!1}),this.serializer=this.codec.createSerializer(),this.deserializer=this.codec.createDeserializer(),this.awsQueryCompatible=!!r,this.mixin=new or(this.awsQueryCompatible)}async serializeRequest(t,n,s){let r=await super.serializeRequest(t,n,s);if(!r.path.endsWith("/"))r.path+="/";if(r.headers["content-type"]=`application/x-amz-json-${this.getJsonRpcVersion()}`,r.headers["x-amz-target"]=`${this.serviceTarget}.${t.name}`,this.awsQueryCompatible)r.headers["x-amzn-query-mode"]="true";if(SM(t.input)==="unit"||!r.body)r.body="{}";return r}getPayloadCodec(){return this.codec}async handleError(t,n,s,r,e){let{awsQueryCompatible:i}=this;if(i)this.mixin.setQueryCompatError(r,s);let f=NM(s,r,i)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,f,this.options.defaultNamespace);let{errorSchema:o,errorMetadata:c}=await this.mixin.getErrorSchemaOrThrowBaseException(f,this.options.defaultNamespace,s,r,e,i?this.mixin.findQueryCompatibleError:void 0),h=et.of(o),u=r.message??r.Message??"UnknownError",_=new(this.compositeErrorRegistry.getErrorCtor(o)??Error)({}),w={},A=this.codec.createDeserializer();for(let[M,d]of h.structIterator())if(r[M]!=null)w[M]=A.readObject(d,r[M]);if(i)this.mixin.queryCompatOutput(r,w);throw this.mixin.decorateServiceException(Object.assign(_,c,{$fault:h.getMergedTraits().error,message:u},w),r)}}class YM extends zi{constructor({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:r,jsonCodec:e}){super({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:r,jsonCodec:e})}getShapeId(){return"aws.protocols#awsJson1_0"}getJsonRpcVersion(){return"1.0"}getDefaultContentType(){return"application/x-amz-json-1.0"}}class xM extends zi{constructor({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:r,jsonCodec:e}){super({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:r,jsonCodec:e})}getShapeId(){return"aws.protocols#awsJson1_1"}getJsonRpcVersion(){return"1.1"}getDefaultContentType(){return"application/x-amz-json-1.1"}}class QM extends LM{serializer;deserializer;codec;mixin=new or;constructor({defaultNamespace:t,errorTypeRegistries:n}){super({defaultNamespace:t,errorTypeRegistries:n});let s={timestampFormat:{useTrait:!0,default:7},httpBindings:!0,jsonName:!0};this.codec=new Ji(s),this.serializer=new IM(this.codec.createSerializer(),s),this.deserializer=new OM(this.codec.createDeserializer(),s)}getShapeId(){return"aws.protocols#restJson1"}getPayloadCodec(){return this.codec}setSerdeContext(t){this.codec.setSerdeContext(t),super.setSerdeContext(t)}async serializeRequest(t,n,s){let r=await super.serializeRequest(t,n,s),e=et.of(t.input);if(!r.headers["content-type"]){let i=this.mixin.resolveRestContentType(this.getDefaultContentType(),e);if(i)r.headers["content-type"]=i}if(r.body==null&&r.headers["content-type"]===this.getDefaultContentType())r.body="{}";return r}async deserializeResponse(t,n,s){let r=await super.deserializeResponse(t,n,s),e=et.of(t.output);for(let[i,f]of e.structIterator())if(f.getMemberTraits().httpPayload&&!(i in r))r[i]=null;return r}async handleError(t,n,s,r,e){let i=HM(s,r)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,i,this.options.defaultNamespace);let{errorSchema:f,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(i,this.options.defaultNamespace,s,r,e),c=et.of(f),h=r.message??r.Message??"UnknownError",l=new(this.compositeErrorRegistry.getErrorCtor(f)??Error)({});await this.deserializeHttpMessage(f,n,s,r);let _={},w=this.codec.createDeserializer();for(let[A,M]of c.structIterator()){let d=M.getMergedTraits().jsonName??A;_[A]=w.readObject(M,r[d])}throw this.mixin.decorateServiceException(Object.assign(l,o,{$fault:c.getMergedTraits().error,message:h},_),r)}getDefaultContentType(){return"application/json"}}var dm=(t)=>{if(t==null)return;if(typeof t==="object"&&"__type"in t)delete t.__type;return um(t)};class ki extends kn{settings;stringDeserializer;constructor(t){super();this.settings=t,this.stringDeserializer=new om(t)}setSerdeContext(t){this.serdeContext=t,this.stringDeserializer.setSerdeContext(t)}read(t,n,s){let r=et.of(t),e=r.getMemberSchemas();if(r.isStructSchema()&&r.isMemberSchema()&&!!Object.values(e).find((c)=>{return!!c.getMemberTraits().eventPayload})){let c={},h=Object.keys(e)[0];if(e[h].isBlobSchema())c[h]=n;else c[h]=this.read(e[h],n);return c}let f=(this.serdeContext?.utf8Encoder??yM)(n),o=this.parseXml(f);return this.readSchema(t,s?o[s]:o)}readSchema(t,n){let s=et.of(t);if(s.isUnitSchema())return;let r=s.getMergedTraits();if(s.isListSchema()&&!Array.isArray(n))return this.readSchema(s,[n]);if(n==null)return n;if(typeof n==="object"){let e=!!r.xmlFlattened;if(s.isListSchema()){let f=s.getValueSchema(),o=[],c=f.getMergedTraits().xmlName??"member",h=e?n:(n[0]??n)[c];if(h==null)return o;let u=Array.isArray(h)?h:[h];for(let l of u)o.push(this.readSchema(f,l));return o}let i={};if(s.isMapSchema()){let f=s.getKeySchema(),o=s.getValueSchema(),c;if(e)c=Array.isArray(n)?n:[n];else c=Array.isArray(n.entry)?n.entry:[n.entry];let h=f.getMergedTraits().xmlName??"key",u=o.getMergedTraits().xmlName??"value";for(let l of c){let _=l[h],w=l[u];i[_]=this.readSchema(o,w)}return i}if(s.isStructSchema()){let f=s.isUnionSchema(),o;if(f)o=new _h(n,i);for(let[c,h]of s.structIterator()){let u=h.getMergedTraits(),l=!u.httpPayload?h.getMemberTraits().xmlName??c:u.xmlName??h.getName();if(f)o.mark(l);if(n[l]!=null)i[c]=this.readSchema(h,n[l])}if(f)o.writeUnknown();return i}if(s.isDocumentSchema())return n;throw Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${s.getName(!0)}`)}if(s.isListSchema())return[];if(s.isMapSchema()||s.isStructSchema())return{};return this.stringDeserializer.read(s,n)}parseXml(t){if(t.length){let n;try{n=mM(t)}catch(i){if(i&&typeof i==="object")Object.defineProperty(i,"$responseBodyText",{value:t});throw i}let s="#text",r=Object.keys(n)[0],e=n[r];if(e[s])e[r]=e[s],delete e[s];return $M(e)}return{}}}class dh extends kn{settings;buffer;constructor(t){super();this.settings=t}write(t,n,s=""){if(this.buffer===void 0)this.buffer="";let r=et.of(t);if(s&&!s.endsWith("."))s+=".";if(r.isBlobSchema()){if(typeof n==="string"||n instanceof Uint8Array)this.writeKey(s),this.writeValue((this.serdeContext?.base64Encoder??Yi)(n))}else if(r.isBooleanSchema()||r.isNumericSchema()||r.isStringSchema()){if(n!=null)this.writeKey(s),this.writeValue(String(n));else if(r.isIdempotencyToken())this.writeKey(s),this.writeValue(lh())}else if(r.isBigIntegerSchema()){if(n!=null)this.writeKey(s),this.writeValue(String(n))}else if(r.isBigDecimalSchema()){if(n!=null)this.writeKey(s),this.writeValue(n instanceof cn?n.string:String(n))}else if(r.isTimestampSchema()){if(n instanceof Date)switch(this.writeKey(s),Qi(r,this.settings)){case 5:this.writeValue(n.toISOString().replace(".000Z","Z"));break;case 6:this.writeValue(xi(n));break;case 7:this.writeValue(String(n.getTime()/1000));break}}else if(r.isDocumentSchema())if(Array.isArray(n))this.write(79,n,s);else if(n instanceof Date)this.write(4,n,s);else if(n instanceof Uint8Array)this.write(21,n,s);else if(n&&typeof n==="object")this.write(143,n,s);else this.writeKey(s),this.writeValue(String(n));else if(r.isListSchema()){if(Array.isArray(n))if(n.length===0){if(this.settings.serializeEmptyLists)this.writeKey(s),this.writeValue("")}else{let e=r.getValueSchema(),i=this.settings.flattenLists||r.getMergedTraits().xmlFlattened,f=1;for(let o of n){if(o==null)continue;let c=e.getMergedTraits(),h=this.getKey("member",c.xmlName,c.ec2QueryName),u=i?`${s}${f}`:`${s}${h}.${f}`;this.write(e,o,u),++f}}}else if(r.isMapSchema()){if(n&&typeof n==="object"){let e=r.getKeySchema(),i=r.getValueSchema(),f=r.getMergedTraits().xmlFlattened,o=1;for(let c in n){let h=n[c];if(h==null)continue;let u=e.getMergedTraits(),l=this.getKey("key",u.xmlName,u.ec2QueryName),_=f?`${s}${o}.${l}`:`${s}entry.${o}.${l}`,w=i.getMergedTraits(),A=this.getKey("value",w.xmlName,w.ec2QueryName),M=f?`${s}${o}.${A}`:`${s}entry.${o}.${A}`;this.write(e,c,_),this.write(i,h,M),++o}}}else if(r.isStructSchema()){if(n&&typeof n==="object"){let e=!1;for(let[i,f]of r.structIterator()){if(n[i]==null&&!f.isIdempotencyToken())continue;let o=f.getMergedTraits(),c=this.getKey(i,o.xmlName,o.ec2QueryName,"struct"),h=`${s}${c}`;this.write(f,n[i],h),e=!0}if(!e&&r.isUnionSchema()){let{$unknown:i}=n;if(Array.isArray(i)){let[f,o]=i,c=`${s}${f}`;this.write(15,o,c)}}}}else if(r.isUnitSchema());else throw Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${r.getName(!0)}`)}flush(){if(this.buffer===void 0)throw Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer.");let t=this.buffer;return delete this.buffer,t}getKey(t,n,s,r){let{ec2:e,capitalizeKeys:i}=this.settings;if(e&&s)return s;let f=n??t;if(i&&r==="struct")return f[0].toUpperCase()+f.slice(1);return f}writeKey(t){if(t.endsWith("."))t=t.slice(0,t.length-1);this.buffer+=`&${EM(t)}=`}writeValue(t){this.buffer+=EM(t)}}class gh extends UM{options;serializer;deserializer;mixin=new or;constructor(t){super({defaultNamespace:t.defaultNamespace,errorTypeRegistries:t.errorTypeRegistries});this.options=t;let n={timestampFormat:{useTrait:!0,default:5},httpBindings:!1,xmlNamespace:t.xmlNamespace,serviceNamespace:t.defaultNamespace,serializeEmptyLists:!0};this.serializer=new dh(n),this.deserializer=new ki(n)}getShapeId(){return"aws.protocols#awsQuery"}setSerdeContext(t){this.serializer.setSerdeContext(t),this.deserializer.setSerdeContext(t)}getPayloadCodec(){throw Error("AWSQuery protocol has no payload codec.")}async serializeRequest(t,n,s){let r=await super.serializeRequest(t,n,s);if(!r.path.endsWith("/"))r.path+="/";if(r.headers["content-type"]="application/x-www-form-urlencoded",SM(t.input)==="unit"||!r.body)r.body="";let e=t.name.split("#")[1]??t.name;if(r.body=`Action=${e}&Version=${this.options.version}`+r.body,r.body.endsWith("&"))r.body=r.body.slice(-1);return r}async deserializeResponse(t,n,s){let r=this.deserializer,e=et.of(t.output),i={};if(s.statusCode>=300){let h=await uh(s.body,n);if(h.byteLength>0)Object.assign(i,await r.read(15,h));await this.handleError(t,n,s,i,this.deserializeMetadata(s))}for(let h in s.headers){let u=s.headers[h];delete s.headers[h],s.headers[h.toLowerCase()]=u}let f=t.name.split("#")[1]??t.name,o=e.isStructSchema()&&this.useNestedResult()?f+"Result":void 0,c=await uh(s.body,n);if(c.byteLength>0)Object.assign(i,await r.read(e,c,o));return i.$metadata=this.deserializeMetadata(s),i}useNestedResult(){return!0}async handleError(t,n,s,r,e){let i=this.loadQueryErrorCode(s,r)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,i,this.options.defaultNamespace);let f=this.loadQueryError(r)??{},o=this.loadQueryErrorMessage(r);f.message=o,f.Error={Type:f.Type,Code:f.Code,Message:o};let{errorSchema:c,errorMetadata:h}=await this.mixin.getErrorSchemaOrThrowBaseException(i,this.options.defaultNamespace,s,f,e,this.mixin.findQueryCompatibleError),u=et.of(c),_=new(this.compositeErrorRegistry.getErrorCtor(c)??Error)({}),w={Type:f.Error.Type,Code:f.Error.Code,Error:f.Error};for(let[A,M]of u.structIterator()){let d=M.getMergedTraits().xmlName??A,E=f[d]??r[d];w[A]=this.deserializer.readSchema(M,E)}throw this.mixin.decorateServiceException(Object.assign(_,h,{$fault:u.getMergedTraits().error,message:o},w),r)}loadQueryErrorCode(t,n){let s=(n.Errors?.[0]?.Error??n.Errors?.Error??n.Error)?.Code;if(s!==void 0)return s;if(t.statusCode==404)return"NotFound"}loadQueryError(t){return t.Errors?.[0]?.Error??t.Errors?.Error??t.Error}loadQueryErrorMessage(t){let n=this.loadQueryError(t);return n?.message??n?.Message??t.message??t.Message??"Unknown"}getDefaultContentType(){return"application/x-www-form-urlencoded"}}class JM extends gh{options;constructor(t){super(t);this.options=t;let n={capitalizeKeys:!0,flattenLists:!0,serializeEmptyLists:!1,ec2:!0};Object.assign(this.serializer.settings,n)}getShapeId(){return"aws.protocols#ec2Query"}useNestedResult(){return!1}}var zM=(t,n)=>PM(t,n).then((s)=>{if(s.length){let r;try{r=mM(s)}catch(o){if(o&&typeof o==="object")Object.defineProperty(o,"$responseBodyText",{value:s});throw o}let e="#text",i=Object.keys(r)[0],f=r[i];if(f[e])f[i]=f[e],delete f[e];return $M(f)}return{}}),gm=async(t,n)=>{let s=await zM(t,n);if(s.Error)s.Error.message=s.Error.message??s.Error.Message;return s},kM=(t,n)=>{if(n?.Error?.Code!==void 0)return n.Error.Code;if(n?.Code!==void 0)return n.Code;if(t.statusCode==404)return"NotFound"};class Eh extends kn{settings;stringBuffer;byteBuffer;buffer;constructor(t){super();this.settings=t}write(t,n){let s=et.of(t);if(s.isStringSchema()&&typeof n==="string")this.stringBuffer=n;else if(s.isBlobSchema())this.byteBuffer="byteLength"in n?n:(this.serdeContext?.base64Decoder??GM)(n);else{this.buffer=this.writeStruct(s,n,void 0);let r=s.getMergedTraits();if(r.httpPayload&&!r.xmlName)this.buffer.withName(s.getName())}}flush(){if(this.byteBuffer!==void 0){let n=this.byteBuffer;return delete this.byteBuffer,n}if(this.stringBuffer!==void 0){let n=this.stringBuffer;return delete this.stringBuffer,n}let t=this.buffer;if(this.settings.xmlNamespace){if(!t?.attributes?.xmlns)t.addAttribute("xmlns",this.settings.xmlNamespace)}return delete this.buffer,t.toString()}writeStruct(t,n,s){let r=t.getMergedTraits(),e=t.isMemberSchema()&&!r.httpPayload?t.getMemberTraits().xmlName??t.getMemberName():r.xmlName??t.getName();if(!e||!t.isStructSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${t.getName(!0)}.`);let i=qt.of(e),[f,o]=this.getXmlnsAttribute(t,s);for(let[h,u]of t.structIterator()){let l=n[h];if(l!=null||u.isIdempotencyToken()){if(u.getMergedTraits().xmlAttribute){i.addAttribute(u.getMergedTraits().xmlName??h,this.writeSimple(u,l));continue}if(u.isListSchema())this.writeList(u,l,i,o);else if(u.isMapSchema())this.writeMap(u,l,i,o);else if(u.isStructSchema())i.addChildNode(this.writeStruct(u,l,o));else{let _=qt.of(u.getMergedTraits().xmlName??u.getMemberName());this.writeSimpleInto(u,l,_,o),i.addChildNode(_)}}}let{$unknown:c}=n;if(c&&t.isUnionSchema()&&Array.isArray(c)&&Object.keys(n).length===1){let[h,u]=c,l=qt.of(h);if(typeof u!=="string")if(n instanceof qt||n instanceof RM)i.addChildNode(n);else throw Error("@aws-sdk - $unknown union member in XML requires value of type string, @aws-sdk/xml-builder::XmlNode or XmlText.");this.writeSimpleInto(0,u,l,o),i.addChildNode(l)}if(o)i.addAttribute(f,o);return i}writeList(t,n,s,r){if(!t.isMemberSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${t.getName(!0)}`);let e=t.getMergedTraits(),i=t.getValueSchema(),f=i.getMergedTraits(),o=!!f.sparse,c=!!e.xmlFlattened,[h,u]=this.getXmlnsAttribute(t,r),l=(_,w)=>{if(i.isListSchema())this.writeList(i,Array.isArray(w)?w:[w],_,u);else if(i.isMapSchema())this.writeMap(i,w,_,u);else if(i.isStructSchema()){let A=this.writeStruct(i,w,u);_.addChildNode(A.withName(c?e.xmlName??t.getMemberName():f.xmlName??"member"))}else{let A=qt.of(c?e.xmlName??t.getMemberName():f.xmlName??"member");this.writeSimpleInto(i,w,A,u),_.addChildNode(A)}};if(c){for(let _ of n)if(o||_!=null)l(s,_)}else{let _=qt.of(e.xmlName??t.getMemberName());if(u)_.addAttribute(h,u);for(let w of n)if(o||w!=null)l(_,w);s.addChildNode(_)}}writeMap(t,n,s,r,e=!1){if(!t.isMemberSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${t.getName(!0)}`);let i=t.getMergedTraits(),f=t.getKeySchema(),c=f.getMergedTraits().xmlName??"key",h=t.getValueSchema(),u=h.getMergedTraits(),l=u.xmlName??"value",_=!!u.sparse,w=!!i.xmlFlattened,[A,M]=this.getXmlnsAttribute(t,r),d=(E,b,L)=>{let S=qt.of(c,b),[O,x]=this.getXmlnsAttribute(f,M);if(x)S.addAttribute(O,x);E.addChildNode(S);let X=qt.of(l);if(h.isListSchema())this.writeList(h,L,X,M);else if(h.isMapSchema())this.writeMap(h,L,X,M,!0);else if(h.isStructSchema())X=this.writeStruct(h,L,M);else this.writeSimpleInto(h,L,X,M);E.addChildNode(X)};if(w)for(let E in n){let b=n[E];if(_||b!=null){let L=qt.of(i.xmlName??t.getMemberName());d(L,E,b),s.addChildNode(L)}}else{let E;if(!e){if(E=qt.of(i.xmlName??t.getMemberName()),M)E.addAttribute(A,M);s.addChildNode(E)}for(let b in n){let L=n[b];if(_||L!=null){let S=qt.of("entry");d(S,b,L),(e?s:E).addChildNode(S)}}}}writeSimple(t,n){if(n===null)throw Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value.");let s=et.of(t),r=null;if(n&&typeof n==="object")if(s.isBlobSchema())r=(this.serdeContext?.base64Encoder??Yi)(n);else if(s.isTimestampSchema()&&n instanceof Date)switch(Qi(s,this.settings)){case 5:r=n.toISOString().replace(".000Z","Z");break;case 6:r=xi(n);break;case 7:r=String(n.getTime()/1000);break;default:console.warn("Missing timestamp format, using http date",n),r=xi(n);break}else if(s.isBigDecimalSchema()&&n){if(n instanceof cn)return n.string;return String(n)}else if(s.isMapSchema()||s.isListSchema())throw Error("@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead.");else throw Error(`@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${s.getName(!0)}`);if(s.isBooleanSchema()||s.isNumericSchema()||s.isBigIntegerSchema()||s.isBigDecimalSchema())r=String(n);if(s.isStringSchema())if(n===void 0&&s.isIdempotencyToken())r=lh();else r=String(n);if(r===null)throw Error(`Unhandled schema-value pair ${s.getName(!0)}=${n}`);return r}writeSimpleInto(t,n,s,r){let e=this.writeSimple(t,n),i=et.of(t),f=new RM(e),[o,c]=this.getXmlnsAttribute(i,r);if(c)s.addAttribute(o,c);s.addChildNode(f)}getXmlnsAttribute(t,n){let s=t.getMergedTraits(),[r,e]=s.xmlNamespace??[];if(e&&e!==n)return[r?`xmlns:${r}`:"xmlns",e];return[void 0,void 0]}}class Rh extends kn{settings;constructor(t){super();this.settings=t}createSerializer(){let t=new Eh(this.settings);return t.setSerdeContext(this.serdeContext),t}createDeserializer(){let t=new ki(this.settings);return t.setSerdeContext(this.serdeContext),t}}class XM extends LM{codec;serializer;deserializer;mixin=new or;constructor(t){super(t);let n={timestampFormat:{useTrait:!0,default:5},httpBindings:!0,xmlNamespace:t.xmlNamespace,serviceNamespace:t.defaultNamespace};this.codec=new Rh(n),this.serializer=new IM(this.codec.createSerializer(),n),this.deserializer=new OM(this.codec.createDeserializer(),n)}getPayloadCodec(){return this.codec}getShapeId(){return"aws.protocols#restXml"}async serializeRequest(t,n,s){let r=await super.serializeRequest(t,n,s),e=et.of(t.input);if(!r.headers["content-type"]){let i=this.mixin.resolveRestContentType(this.getDefaultContentType(),e);if(i)r.headers["content-type"]=i}if(typeof r.body==="string"&&r.headers["content-type"]===this.getDefaultContentType()&&!r.body.startsWith("<?xml ")&&!this.hasUnstructuredPayloadBinding(e))r.body='<?xml version="1.0" encoding="UTF-8"?>'+r.body;return r}async deserializeResponse(t,n,s){return super.deserializeResponse(t,n,s)}async handleError(t,n,s,r,e){let i=kM(s,r)??"Unknown";if(this.mixin.compose(this.compositeErrorRegistry,i,this.options.defaultNamespace),r.Error&&typeof r.Error==="object"){for(let A of Object.keys(r.Error))if(r[A]=r.Error[A],A.toLowerCase()==="message")r.message=r.Error[A]}if(r.RequestId&&!e.requestId)e.requestId=r.RequestId;let{errorSchema:f,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(i,this.options.defaultNamespace,s,r,e),c=et.of(f),h=r.Error?.message??r.Error?.Message??r.message??r.Message??"UnknownError",l=new(this.compositeErrorRegistry.getErrorCtor(f)??Error)({});await this.deserializeHttpMessage(f,n,s,r);let _={},w=this.codec.createDeserializer();for(let[A,M]of c.structIterator()){let d=M.getMergedTraits().xmlName??A,E=r.Error?.[d]??r[d];_[A]=w.readSchema(M,E)}throw this.mixin.decorateServiceException(Object.assign(l,o,{$fault:c.getMergedTraits().error,message:h},_),r)}getDefaultContentType(){return"application/xml"}hasUnstructuredPayloadBinding(t){for(let[,n]of t.structIterator())if(n.getMergedTraits().httpPayload)return!(n.isStructSchema()||n.isMapSchema()||n.isListSchema());return!1}}Em.AwsEc2QueryProtocol=JM;Em.AwsJson1_0Protocol=YM;Em.AwsJson1_1Protocol=xM;Em.AwsJsonRpcProtocol=zi;Em.AwsQueryProtocol=gh;Em.AwsRestJsonProtocol=QM;Em.AwsRestXmlProtocol=XM;Em.AwsSmithyRpcV2CborProtocol=FM;Em.JsonCodec=Ji;Em.JsonShapeDeserializer=Ah;Em.JsonShapeSerializer=Mh;Em.QueryShapeSerializer=dh;Em.XmlCodec=Rh;Em.XmlShapeDeserializer=ki;Em.XmlShapeSerializer=Eh;Em._toBool=_m;Em._toNum=wm;Em._toStr=lm;Em.awsExpectUnion=dm;Em.loadJsonRpcErrorCode=NM;Em.loadRestJsonErrorCode=HM;Em.loadRestXmlErrorCode=kM;Em.parseJsonBody=wh;Em.parseJsonErrorBody=Mm;Em.parseXmlBody=zM;Em.parseXmlErrorBody=gm});var Ih=K((iH)=>{var{awsEndpointFunctions:qm,emitWarningIfUnsupportedVersion:Cm,createDefaultUserAgentProvider:am,NODE_APP_ID_CONFIG_OPTIONS:Km,getAwsRegionExtensionConfiguration:Vm,resolveAwsRegionExtensionConfiguration:jm,resolveUserAgentConfig:pm,resolveHostHeaderConfig:vm,getUserAgentPlugin:Zm,getHostHeaderPlugin:tF,getLoggerPlugin:nF,getRecursionDetectionPlugin:sF}=kt(),{NoAuthSigner:rF,getHttpAuthSchemeEndpointRuleSetPlugin:eF,DefaultIdentityProviderConfig:iF,getHttpSigningPlugin:oF}=Qn(),{normalizeProvider:VM,getSmithyContext:fF,ServiceException:cF,NoOpLogger:hF,emitWarningIfUnsupportedVersion:uF,loadConfigsForDefaultMode:lF,getDefaultExtensionConfiguration:_F,resolveDefaultRuntimeConfig:wF,Client:jM,makeBuilder:AF,createAggregatedClient:MF}=En(),{Command:dF}=En();iH.$Command=dF;iH.__Client=jM;var{resolveDefaultsModeConfig:gF,loadConfig:As,NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS:EF,NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS:RF,NODE_REGION_CONFIG_OPTIONS:bF,NODE_REGION_CONFIG_FILE_OPTIONS:TF,resolveRegionConfig:SF}=Rt(),{BinaryDecisionDiagram:$F,EndpointCache:UF,decideEndpoint:LF,customEndpointFunctions:IF,resolveEndpointConfig:OF,getEndpointPlugin:yF}=fs(),{parseUrl:GF,getHttpHandlerExtensionConfiguration:BF,resolveHttpHandlerRuntimeConfig:mF,getContentLengthPlugin:FF}=Tt(),{DEFAULT_RETRY_MODE:PF,NODE_RETRY_MODE_CONFIG_OPTIONS:HF,NODE_MAX_ATTEMPT_CONFIG_OPTIONS:NF,resolveRetryConfig:DF,getRetryPlugin:WF}=pr(),{TypeRegistry:pM,getSchemaSerdePlugin:YF}=Pn(),{resolveAwsSdkSigV4Config:xF,AwsSdkSigV4Signer:QF,NODE_AUTH_SCHEME_PREFERENCE_OPTIONS:JF}=zc(),{toUtf8:zF,fromUtf8:kF,toBase64:XF,fromBase64:qF,calculateBodyLength:CF}=bt(),{streamCollector:aF,NodeHttpHandler:KF}=Ni(),{AwsRestJsonProtocol:VF}=bh(),{Sha256:jF}=af(),pF=async(t,n,s)=>{return{operation:fF(n).operation,region:await VM(t.region)()||(()=>{throw Error("expected `region` to be configured for `aws.auth#sigv4`")})()}};function vF(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sso-oauth",region:t.region},propertiesExtractor:(n,s)=>({signingProperties:{config:n,context:s}})}}function ZF(t){return{schemeId:"smithy.api#noAuth"}}var tP=(t)=>{let n=[];switch(t.operation){case"CreateToken":{n.push(ZF());break}default:n.push(vF(t))}return n},nP=(t)=>{let n=xF(t);return Object.assign(n,{authSchemePreference:VM(t.authSchemePreference??[])})},sP=(t)=>{return Object.assign(t,{useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,defaultSigningName:"sso-oauth"})},rP={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},eP="3.997.32",iP={version:eP},ue="ref",Ms=-1,Xi=!0,qM="isSet",vM="PartitionResult",qi="booleanEquals",Th="getAttr",CM={[ue]:"Endpoint"},Sh={[ue]:vM},fr={},aM=[{[ue]:"Region"}],KM={conditions:[[qM,[CM]],[qM,aM],["aws.partition",aM,vM],[qi,[{[ue]:"UseFIPS"},Xi]],[qi,[{[ue]:"UseDualStack"},Xi]],[qi,[{fn:Th,argv:[Sh,"supportsDualStack"]},Xi]],[qi,[{fn:Th,argv:[Sh,"supportsFIPS"]},Xi]],["stringEquals",[{fn:Th,argv:[Sh,"name"]},"aws-us-gov"]]],results:[[Ms],[Ms,"Invalid Configuration: FIPS and custom endpoint are not supported"],[Ms,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[CM,fr],["https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",fr],[Ms,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://oidc.{Region}.amazonaws.com",fr],["https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}",fr],[Ms,"FIPS is enabled but this partition does not support FIPS"],["https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}",fr],[Ms,"DualStack is enabled but this partition does not support DualStack"],["https://oidc.{Region}.{PartitionResult#dnsSuffix}",fr],[Ms,"Invalid Configuration: Missing Region"]]},oP=2,St=1e8,fP=new Int32Array([-1,1,-1,0,13,3,1,4,St+12,2,5,St+12,3,8,6,4,7,St+11,5,St+9,St+10,4,11,9,6,10,St+8,7,St+6,St+7,5,12,St+5,6,St+4,St+5,3,St+1,14,4,St+2,St+3]),cP=$F.from(fP,oP,KM.conditions,KM.results),hP=new UF({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),uP=(t,n={})=>{return hP.get(t,()=>LF(cP,{endpointParams:t,logger:n.logger}))};IF.aws=qm;class dt extends cF{constructor(t){super(t);Object.setPrototypeOf(this,dt.prototype)}}class Ci extends dt{name="AccessDeniedException";$fault="client";error;reason;error_description;constructor(t){super({name:"AccessDeniedException",$fault:"client",...t});Object.setPrototypeOf(this,Ci.prototype),this.error=t.error,this.reason=t.reason,this.error_description=t.error_description}}class ai extends dt{name="AuthorizationPendingException";$fault="client";error;error_description;constructor(t){super({name:"AuthorizationPendingException",$fault:"client",...t});Object.setPrototypeOf(this,ai.prototype),this.error=t.error,this.error_description=t.error_description}}class Ki extends dt{name="ExpiredTokenException";$fault="client";error;error_description;constructor(t){super({name:"ExpiredTokenException",$fault:"client",...t});Object.setPrototypeOf(this,Ki.prototype),this.error=t.error,this.error_description=t.error_description}}class Vi extends dt{name="InternalServerException";$fault="server";error;error_description;constructor(t){super({name:"InternalServerException",$fault:"server",...t});Object.setPrototypeOf(this,Vi.prototype),this.error=t.error,this.error_description=t.error_description}}class ji extends dt{name="InvalidClientException";$fault="client";error;error_description;constructor(t){super({name:"InvalidClientException",$fault:"client",...t});Object.setPrototypeOf(this,ji.prototype),this.error=t.error,this.error_description=t.error_description}}class pi extends dt{name="InvalidGrantException";$fault="client";error;error_description;constructor(t){super({name:"InvalidGrantException",$fault:"client",...t});Object.setPrototypeOf(this,pi.prototype),this.error=t.error,this.error_description=t.error_description}}class vi extends dt{name="InvalidRequestException";$fault="client";error;reason;error_description;constructor(t){super({name:"InvalidRequestException",$fault:"client",...t});Object.setPrototypeOf(this,vi.prototype),this.error=t.error,this.reason=t.reason,this.error_description=t.error_description}}class Zi extends dt{name="InvalidScopeException";$fault="client";error;error_description;constructor(t){super({name:"InvalidScopeException",$fault:"client",...t});Object.setPrototypeOf(this,Zi.prototype),this.error=t.error,this.error_description=t.error_description}}class to extends dt{name="SlowDownException";$fault="client";error;error_description;constructor(t){super({name:"SlowDownException",$fault:"client",...t});Object.setPrototypeOf(this,to.prototype),this.error=t.error,this.error_description=t.error_description}}class no extends dt{name="UnauthorizedClientException";$fault="client";error;error_description;constructor(t){super({name:"UnauthorizedClientException",$fault:"client",...t});Object.setPrototypeOf(this,no.prototype),this.error=t.error,this.error_description=t.error_description}}class so extends dt{name="UnsupportedGrantTypeException";$fault="client";error;error_description;constructor(t){super({name:"UnsupportedGrantTypeException",$fault:"client",...t});Object.setPrototypeOf(this,so.prototype),this.error=t.error,this.error_description=t.error_description}}var lP="AccessDeniedException",_P="AuthorizationPendingException",wP="AccessToken",AP="ClientSecret",MP="CreateToken",dP="CreateTokenRequest",gP="CreateTokenResponse",EP="CodeVerifier",RP="ExpiredTokenException",bP="InvalidClientException",TP="InvalidGrantException",SP="InvalidRequestException",$P="InternalServerException",UP="InvalidScopeException",LP="IdToken",IP="RefreshToken",OP="SlowDownException",yP="UnauthorizedClientException",GP="UnsupportedGrantTypeException",BP="accessToken",hn="client",mP="clientId",FP="clientSecret",PP="codeVerifier",HP="code",NP="deviceCode",nt="error",DP="expiresIn",Ct="error_description",WP="grantType",YP="http",at="httpError",xP="idToken",ZM="reason",t1="refreshToken",QP="redirectUri",n1="smithy.ts.sdk.synthetic.com.amazonaws.ssooidc",JP="scope",zP="server",kP="tokenType",it="com.amazonaws.ssooidc",s1=pM.for(n1),r1=[-3,n1,"SSOOIDCServiceException",0,[],[]];s1.registerError(r1,dt);var Nt=pM.for(it),e1=[-3,it,lP,{[nt]:hn,[at]:400},[nt,ZM,Ct],[0,0,0]];Nt.registerError(e1,Ci);var i1=[-3,it,_P,{[nt]:hn,[at]:400},[nt,Ct],[0,0]];Nt.registerError(i1,ai);var o1=[-3,it,RP,{[nt]:hn,[at]:400},[nt,Ct],[0,0]];Nt.registerError(o1,Ki);var f1=[-3,it,$P,{[nt]:zP,[at]:500},[nt,Ct],[0,0]];Nt.registerError(f1,Vi);var c1=[-3,it,bP,{[nt]:hn,[at]:401},[nt,Ct],[0,0]];Nt.registerError(c1,ji);var h1=[-3,it,TP,{[nt]:hn,[at]:400},[nt,Ct],[0,0]];Nt.registerError(h1,pi);var u1=[-3,it,SP,{[nt]:hn,[at]:400},[nt,ZM,Ct],[0,0,0]];Nt.registerError(u1,vi);var l1=[-3,it,UP,{[nt]:hn,[at]:400},[nt,Ct],[0,0]];Nt.registerError(l1,Zi);var _1=[-3,it,OP,{[nt]:hn,[at]:400},[nt,Ct],[0,0]];Nt.registerError(_1,to);var w1=[-3,it,yP,{[nt]:hn,[at]:400},[nt,Ct],[0,0]];Nt.registerError(w1,no);var A1=[-3,it,GP,{[nt]:hn,[at]:400},[nt,Ct],[0,0]];Nt.registerError(A1,so);var M1=[s1,Nt],XP=[0,it,wP,8,0],qP=[0,it,AP,8,0],CP=[0,it,EP,8,0],aP=[0,it,LP,8,0],d1=[0,it,IP,8,0],g1=[3,it,dP,0,[mP,FP,WP,NP,HP,t1,JP,QP,PP],[0,[()=>qP,0],0,0,0,[()=>d1,0],64,0,[()=>CP,0]],3],E1=[3,it,gP,0,[BP,kP,DP,t1,xP],[[()=>XP,0],0,1,[()=>d1,0],[()=>aP,0]]],R1=[9,it,MP,{[YP]:["POST","/token",200]},()=>g1,()=>E1],KP=(t)=>{return{apiVersion:"2019-06-10",base64Decoder:t?.base64Decoder??qF,base64Encoder:t?.base64Encoder??XF,disableHostPrefix:t?.disableHostPrefix??!1,endpointProvider:t?.endpointProvider??uP,extensions:t?.extensions??[],httpAuthSchemeProvider:t?.httpAuthSchemeProvider??tP,httpAuthSchemes:t?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(n)=>n.getIdentityProvider("aws.auth#sigv4"),signer:new QF},{schemeId:"smithy.api#noAuth",identityProvider:(n)=>n.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new rF}],logger:t?.logger??new hF,protocol:t?.protocol??VF,protocolSettings:t?.protocolSettings??{defaultNamespace:"com.amazonaws.ssooidc",errorTypeRegistries:M1,version:"2019-06-10",serviceTarget:"AWSSSOOIDCService"},serviceId:t?.serviceId??"SSO OIDC",sha256:t?.sha256??jF,urlParser:t?.urlParser??GF,utf8Decoder:t?.utf8Decoder??kF,utf8Encoder:t?.utf8Encoder??zF}},VP=(t)=>{uF(process.version);let n=gF(t),s=()=>n().then(lF),r=KP(t);Cm(process.version);let e={profile:t?.profile,logger:r.logger};return{...r,...t,runtime:"node",defaultsMode:n,authSchemePreference:t?.authSchemePreference??As(JF,e),bodyLengthChecker:t?.bodyLengthChecker??CF,defaultUserAgentProvider:t?.defaultUserAgentProvider??am({serviceId:r.serviceId,clientVersion:iP.version}),maxAttempts:t?.maxAttempts??As(NF,t),region:t?.region??As(bF,{...TF,...e}),requestHandler:KF.create(t?.requestHandler??s),retryMode:t?.retryMode??As({...HF,default:async()=>(await s()).retryMode||PF},t),streamCollector:t?.streamCollector??aF,useDualstackEndpoint:t?.useDualstackEndpoint??As(RF,e),useFipsEndpoint:t?.useFipsEndpoint??As(EF,e),userAgentAppId:t?.userAgentAppId??As(Km,e)}},jP=(t)=>{let{httpAuthSchemes:n,httpAuthSchemeProvider:s,credentials:r}=t;return{setHttpAuthScheme(e){let i=n.findIndex((f)=>f.schemeId===e.schemeId);if(i===-1)n.push(e);else n.splice(i,1,e)},httpAuthSchemes(){return n},setHttpAuthSchemeProvider(e){s=e},httpAuthSchemeProvider(){return s},setCredentials(e){r=e},credentials(){return r}}},pP=(t)=>{return{httpAuthSchemes:t.httpAuthSchemes(),httpAuthSchemeProvider:t.httpAuthSchemeProvider(),credentials:t.credentials()}},vP=(t,n)=>{let s=Object.assign(Vm(t),_F(t),BF(t),jP(t));return n.forEach((r)=>r.configure(s)),Object.assign(t,jm(s),wF(s),mF(s),pP(s))};class $h extends jM{config;constructor(...[t]){let n=VP(t||{});super(n);this.initConfig=n;let s=sP(n),r=pm(s),e=DF(r),i=SF(e),f=vm(i),o=OF(f),c=nP(o),h=vP(c,t?.extensions||[]);this.config=h,this.middlewareStack.use(YF(this.config)),this.middlewareStack.use(Zm(this.config)),this.middlewareStack.use(WF(this.config)),this.middlewareStack.use(FF(this.config)),this.middlewareStack.use(tF(this.config)),this.middlewareStack.use(nF(this.config)),this.middlewareStack.use(sF(this.config)),this.middlewareStack.use(eF(this.config,{httpAuthSchemeParametersProvider:pF,identityProviderConfigProvider:async(u)=>new iF({"aws.auth#sigv4":u.credentials})})),this.middlewareStack.use(oF(this.config))}destroy(){super.destroy()}}var ZP=AF(rP,"AWSSSOOIDCService","SSOOIDCClient",yF),tH={},nH=(t,n,s,r)=>[];class Uh extends ZP(tH,nH,"CreateToken",R1){}var sH={CreateTokenCommand:Uh};class Lh extends $h{}MF(sH,Lh);var rH={KMS_ACCESS_DENIED:"KMS_AccessDeniedException"},eH={KMS_DISABLED_KEY:"KMS_DisabledException",KMS_INVALID_KEY_USAGE:"KMS_InvalidKeyUsageException",KMS_INVALID_STATE:"KMS_InvalidStateException",KMS_KEY_NOT_FOUND:"KMS_NotFoundException"};iH.AccessDeniedException=Ci;iH.AccessDeniedException$=e1;iH.AccessDeniedExceptionReason=rH;iH.AuthorizationPendingException=ai;iH.AuthorizationPendingException$=i1;iH.CreateToken$=R1;iH.CreateTokenCommand=Uh;iH.CreateTokenRequest$=g1;iH.CreateTokenResponse$=E1;iH.ExpiredTokenException=Ki;iH.ExpiredTokenException$=o1;iH.InternalServerException=Vi;iH.InternalServerException$=f1;iH.InvalidClientException=ji;iH.InvalidClientException$=c1;iH.InvalidGrantException=pi;iH.InvalidGrantException$=h1;iH.InvalidRequestException=vi;iH.InvalidRequestException$=u1;iH.InvalidRequestExceptionReason=eH;iH.InvalidScopeException=Zi;iH.InvalidScopeException$=l1;iH.SSOOIDC=Lh;iH.SSOOIDCClient=$h;iH.SSOOIDCServiceException=dt;iH.SSOOIDCServiceException$=r1;iH.SlowDownException=to;iH.SlowDownException$=_1;iH.UnauthorizedClientException=no;iH.UnauthorizedClientException$=w1;iH.UnsupportedGrantTypeException=so;iH.UnsupportedGrantTypeException$=A1;iH.errorTypeRegistries=M1});import{existsSync as FE,readFileSync as PE}from"fs";import{homedir as HE}from"os";import{join as du}from"path";var g={};Rg(g,{void:()=>rE,util:()=>J,unknown:()=>nE,union:()=>fE,undefined:()=>vg,tuple:()=>uE,transformer:()=>bE,symbol:()=>pg,string:()=>wu,strictObject:()=>oE,setErrorMap:()=>Sg,set:()=>wE,record:()=>lE,quotelessJson:()=>bg,promise:()=>RE,preprocess:()=>$E,pipeline:()=>UE,ostring:()=>LE,optional:()=>TE,onumber:()=>IE,oboolean:()=>OE,objectUtil:()=>Po,object:()=>iE,number:()=>Au,nullable:()=>SE,null:()=>Zg,never:()=>sE,nativeEnum:()=>EE,nan:()=>Kg,map:()=>_E,makeIssue:()=>Ar,literal:()=>dE,lazy:()=>ME,late:()=>Cg,isValid:()=>In,isDirty:()=>Re,isAsync:()=>Ss,isAborted:()=>Ee,intersection:()=>hE,instanceof:()=>ag,getParsedType:()=>Vt,getErrorMap:()=>Ts,function:()=>AE,enum:()=>gE,effect:()=>bE,discriminatedUnion:()=>cE,defaultErrorMap:()=>wn,datetimeRegex:()=>uu,date:()=>jg,custom:()=>_u,coerce:()=>yE,boolean:()=>Mu,bigint:()=>Vg,array:()=>eE,any:()=>tE,addIssueToContext:()=>$,ZodVoid:()=>dr,ZodUnknown:()=>On,ZodUnion:()=>ys,ZodUndefined:()=>Is,ZodType:()=>W,ZodTuple:()=>pt,ZodTransformer:()=>Jt,ZodSymbol:()=>Mr,ZodString:()=>Wt,ZodSet:()=>pn,ZodSchema:()=>W,ZodRecord:()=>gr,ZodReadonly:()=>Ns,ZodPromise:()=>vn,ZodPipeline:()=>br,ZodParsedType:()=>T,ZodOptional:()=>xt,ZodObject:()=>p,ZodNumber:()=>yn,ZodNullable:()=>Mn,ZodNull:()=>Os,ZodNever:()=>jt,ZodNativeEnum:()=>Fs,ZodNaN:()=>Rr,ZodMap:()=>Er,ZodLiteral:()=>ms,ZodLazy:()=>Bs,ZodIssueCode:()=>R,ZodIntersection:()=>Gs,ZodFunction:()=>Us,ZodFirstPartyTypeKind:()=>P,ZodError:()=>gt,ZodEnum:()=>Bn,ZodEffects:()=>Jt,ZodDiscriminatedUnion:()=>be,ZodDefault:()=>Ps,ZodDate:()=>Vn,ZodCatch:()=>Hs,ZodBranded:()=>Te,ZodBoolean:()=>Ls,ZodBigInt:()=>Gn,ZodArray:()=>Yt,ZodAny:()=>jn,Schema:()=>W,ParseStatus:()=>ht,OK:()=>wt,NEVER:()=>GE,INVALID:()=>F,EMPTY_PATH:()=>$g,DIRTY:()=>Kn,BRAND:()=>qg});var J;(function(t){t.assertEqual=(e)=>{};function n(e){}t.assertIs=n;function s(e){throw Error()}t.assertNever=s,t.arrayToEnum=(e)=>{let i={};for(let f of e)i[f]=f;return i},t.getValidEnumValues=(e)=>{let i=t.objectKeys(e).filter((o)=>typeof e[e[o]]!=="number"),f={};for(let o of i)f[o]=e[o];return t.objectValues(f)},t.objectValues=(e)=>{return t.objectKeys(e).map(function(i){return e[i]})},t.objectKeys=typeof Object.keys==="function"?(e)=>Object.keys(e):(e)=>{let i=[];for(let f in e)if(Object.prototype.hasOwnProperty.call(e,f))i.push(f);return i},t.find=(e,i)=>{for(let f of e)if(i(f))return f;return},t.isInteger=typeof Number.isInteger==="function"?(e)=>Number.isInteger(e):(e)=>typeof e==="number"&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,i=" | "){return e.map((f)=>typeof f==="string"?`'${f}'`:f).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(e,i)=>{if(typeof i==="bigint")return i.toString();return i}})(J||(J={}));var Po;(function(t){t.mergeShapes=(n,s)=>{return{...n,...s}}})(Po||(Po={}));var T=J.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Vt=(t)=>{switch(typeof t){case"undefined":return T.undefined;case"string":return T.string;case"number":return Number.isNaN(t)?T.nan:T.number;case"boolean":return T.boolean;case"function":return T.function;case"bigint":return T.bigint;case"symbol":return T.symbol;case"object":if(Array.isArray(t))return T.array;if(t===null)return T.null;if(t.then&&typeof t.then==="function"&&t.catch&&typeof t.catch==="function")return T.promise;if(typeof Map<"u"&&t instanceof Map)return T.map;if(typeof Set<"u"&&t instanceof Set)return T.set;if(typeof Date<"u"&&t instanceof Date)return T.date;return T.object;default:return T.unknown}};var R=J.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),bg=(t)=>{return JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:")};class gt extends Error{get errors(){return this.issues}constructor(t){super();this.issues=[],this.addIssue=(s)=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};let n=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,n);else this.__proto__=n;this.name="ZodError",this.issues=t}format(t){let n=t||function(e){return e.message},s={_errors:[]},r=(e)=>{for(let i of e.issues)if(i.code==="invalid_union")i.unionErrors.map(r);else if(i.code==="invalid_return_type")r(i.returnTypeError);else if(i.code==="invalid_arguments")r(i.argumentsError);else if(i.path.length===0)s._errors.push(n(i));else{let f=s,o=0;while(o<i.path.length){let c=i.path[o];if(o!==i.path.length-1)f[c]=f[c]||{_errors:[]};else f[c]=f[c]||{_errors:[]},f[c]._errors.push(n(i));f=f[c],o++}}};return r(this),s}static assert(t){if(!(t instanceof gt))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,J.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=(n)=>n.message){let n={},s=[];for(let r of this.issues)if(r.path.length>0){let e=r.path[0];n[e]=n[e]||[],n[e].push(t(r))}else s.push(t(r));return{formErrors:s,fieldErrors:n}}get formErrors(){return this.flatten()}}gt.create=(t)=>{return new gt(t)};var Tg=(t,n)=>{let s;switch(t.code){case R.invalid_type:if(t.received===T.undefined)s="Required";else s=`Expected ${t.expected}, received ${t.received}`;break;case R.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(t.expected,J.jsonStringifyReplacer)}`;break;case R.unrecognized_keys:s=`Unrecognized key(s) in object: ${J.joinValues(t.keys,", ")}`;break;case R.invalid_union:s="Invalid input";break;case R.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${J.joinValues(t.options)}`;break;case R.invalid_enum_value:s=`Invalid enum value. Expected ${J.joinValues(t.options)}, received '${t.received}'`;break;case R.invalid_arguments:s="Invalid function arguments";break;case R.invalid_return_type:s="Invalid function return type";break;case R.invalid_date:s="Invalid date";break;case R.invalid_string:if(typeof t.validation==="object")if("includes"in t.validation){if(s=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position==="number")s=`${s} at one or more positions greater than or equal to ${t.validation.position}`}else if("startsWith"in t.validation)s=`Invalid input: must start with "${t.validation.startsWith}"`;else if("endsWith"in t.validation)s=`Invalid input: must end with "${t.validation.endsWith}"`;else J.assertNever(t.validation);else if(t.validation!=="regex")s=`Invalid ${t.validation}`;else s="Invalid";break;case R.too_small:if(t.type==="array")s=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`;else if(t.type==="string")s=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`;else if(t.type==="number")s=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`;else if(t.type==="bigint")s=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`;else if(t.type==="date")s=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`;else s="Invalid input";break;case R.too_big:if(t.type==="array")s=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`;else if(t.type==="string")s=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`;else if(t.type==="number")s=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`;else if(t.type==="bigint")s=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`;else if(t.type==="date")s=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`;else s="Invalid input";break;case R.custom:s="Invalid input";break;case R.invalid_intersection_types:s="Intersection results could not be merged";break;case R.not_multiple_of:s=`Number must be a multiple of ${t.multipleOf}`;break;case R.not_finite:s="Number must be finite";break;default:s=n.defaultError,J.assertNever(t)}return{message:s}},wn=Tg;var iu=wn;function Sg(t){iu=t}function Ts(){return iu}var Ar=(t)=>{let{data:n,path:s,errorMaps:r,issueData:e}=t,i=[...s,...e.path||[]],f={...e,path:i};if(e.message!==void 0)return{...e,path:i,message:e.message};let o="",c=r.filter((h)=>!!h).slice().reverse();for(let h of c)o=h(f,{data:n,defaultError:o}).message;return{...e,path:i,message:o}},$g=[];function $(t,n){let s=Ts(),r=Ar({issueData:n,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,s,s===wn?void 0:wn].filter((e)=>!!e)});t.common.issues.push(r)}class ht{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(t,n){let s=[];for(let r of n){if(r.status==="aborted")return F;if(r.status==="dirty")t.dirty();s.push(r.value)}return{status:t.value,value:s}}static async mergeObjectAsync(t,n){let s=[];for(let r of n){let e=await r.key,i=await r.value;s.push({key:e,value:i})}return ht.mergeObjectSync(t,s)}static mergeObjectSync(t,n){let s={};for(let r of n){let{key:e,value:i}=r;if(e.status==="aborted")return F;if(i.status==="aborted")return F;if(e.status==="dirty")t.dirty();if(i.status==="dirty")t.dirty();if(e.value!=="__proto__"&&(typeof i.value<"u"||r.alwaysSet))s[e.value]=i.value}return{status:t.value,value:s}}}var F=Object.freeze({status:"aborted"}),Kn=(t)=>({status:"dirty",value:t}),wt=(t)=>({status:"valid",value:t}),Ee=(t)=>t.status==="aborted",Re=(t)=>t.status==="dirty",In=(t)=>t.status==="valid",Ss=(t)=>typeof Promise<"u"&&t instanceof Promise;var y;(function(t){t.errToObj=(n)=>typeof n==="string"?{message:n}:n||{},t.toString=(n)=>typeof n==="string"?n:n?.message})(y||(y={}));class Qt{constructor(t,n,s,r){this._cachedPath=[],this.parent=t,this.data=n,this._path=s,this._key=r}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var ou=(t,n)=>{if(In(n))return{success:!0,data:n.value};else{if(!t.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let s=new gt(t.common.issues);return this._error=s,this._error}}}};function D(t){if(!t)return{};let{errorMap:n,invalid_type_error:s,required_error:r,description:e}=t;if(n&&(s||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(n)return{errorMap:n,description:e};return{errorMap:(f,o)=>{let{message:c}=t;if(f.code==="invalid_enum_value")return{message:c??o.defaultError};if(typeof o.data>"u")return{message:c??r??o.defaultError};if(f.code!=="invalid_type")return{message:o.defaultError};return{message:c??s??o.defaultError}},description:e}}class W{get description(){return this._def.description}_getType(t){return Vt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Vt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ht,ctx:{common:t.parent.common,data:t.data,parsedType:Vt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Ss(n))throw Error("Synchronous parse encountered promise.");return n}_parseAsync(t){let n=this._parse(t);return Promise.resolve(n)}parse(t,n){let s=this.safeParse(t,n);if(s.success)return s.data;throw s.error}safeParse(t,n){let s={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Vt(t)},r=this._parseSync({data:t,path:s.path,parent:s});return ou(s,r)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Vt(t)};if(!this["~standard"].async)try{let s=this._parseSync({data:t,path:[],parent:n});return In(s)?{value:s.value}:{issues:n.common.issues}}catch(s){if(s?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then((s)=>In(s)?{value:s.value}:{issues:n.common.issues})}async parseAsync(t,n){let s=await this.safeParseAsync(t,n);if(s.success)return s.data;throw s.error}async safeParseAsync(t,n){let s={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Vt(t)},r=this._parse({data:t,path:s.path,parent:s}),e=await(Ss(r)?r:Promise.resolve(r));return ou(s,e)}refine(t,n){let s=(r)=>{if(typeof n==="string"||typeof n>"u")return{message:n};else if(typeof n==="function")return n(r);else return n};return this._refinement((r,e)=>{let i=t(r),f=()=>e.addIssue({code:R.custom,...s(r)});if(typeof Promise<"u"&&i instanceof Promise)return i.then((o)=>{if(!o)return f(),!1;else return!0});if(!i)return f(),!1;else return!0})}refinement(t,n){return this._refinement((s,r)=>{if(!t(s))return r.addIssue(typeof n==="function"?n(s,r):n),!1;else return!0})}_refinement(t){return new Jt({schema:this,typeName:P.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(n)=>this["~validate"](n)}}optional(){return xt.create(this,this._def)}nullable(){return Mn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Yt.create(this)}promise(){return vn.create(this,this._def)}or(t){return ys.create([this,t],this._def)}and(t){return Gs.create(this,t,this._def)}transform(t){return new Jt({...D(this._def),schema:this,typeName:P.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t==="function"?t:()=>t;return new Ps({...D(this._def),innerType:this,defaultValue:n,typeName:P.ZodDefault})}brand(){return new Te({typeName:P.ZodBranded,type:this,...D(this._def)})}catch(t){let n=typeof t==="function"?t:()=>t;return new Hs({...D(this._def),innerType:this,catchValue:n,typeName:P.ZodCatch})}describe(t){return new this.constructor({...this._def,description:t})}pipe(t){return br.create(this,t)}readonly(){return Ns.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var Ug=/^c[^\s-]{8,}$/i,Lg=/^[0-9a-z]+$/,Ig=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Og=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,yg=/^[a-z0-9_-]{21}$/i,Gg=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Bg=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,mg=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Fg="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ho,Pg=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Hg=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Ng=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Dg=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Wg=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Yg=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,cu="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",xg=new RegExp(`^${cu}$`);function hu(t){let n="[0-5]\\d";if(t.precision)n=`${n}\\.\\d{${t.precision}}`;else if(t.precision==null)n=`${n}(\\.\\d+)?`;let s=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${n})${s}`}function Qg(t){return new RegExp(`^${hu(t)}$`)}function uu(t){let n=`${cu}T${hu(t)}`,s=[];if(s.push(t.local?"Z?":"Z"),t.offset)s.push("([+-]\\d{2}:?\\d{2})");return n=`${n}(${s.join("|")})`,new RegExp(`^${n}$`)}function Jg(t,n){if((n==="v4"||!n)&&Pg.test(t))return!0;if((n==="v6"||!n)&&Ng.test(t))return!0;return!1}function zg(t,n){if(!Gg.test(t))return!1;try{let[s]=t.split(".");if(!s)return!1;let r=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(s.length+(4-s.length%4)%4,"="),e=JSON.parse(atob(r));if(typeof e!=="object"||e===null)return!1;if("typ"in e&&e?.typ!=="JWT")return!1;if(!e.alg)return!1;if(n&&e.alg!==n)return!1;return!0}catch{return!1}}function kg(t,n){if((n==="v4"||!n)&&Hg.test(t))return!0;if((n==="v6"||!n)&&Dg.test(t))return!0;return!1}class Wt extends W{_parse(t){if(this._def.coerce)t.data=String(t.data);if(this._getType(t)!==T.string){let e=this._getOrReturnCtx(t);return $(e,{code:R.invalid_type,expected:T.string,received:e.parsedType}),F}let s=new ht,r=void 0;for(let e of this._def.checks)if(e.kind==="min"){if(t.data.length<e.value)r=this._getOrReturnCtx(t,r),$(r,{code:R.too_small,minimum:e.value,type:"string",inclusive:!0,exact:!1,message:e.message}),s.dirty()}else if(e.kind==="max"){if(t.data.length>e.value)r=this._getOrReturnCtx(t,r),$(r,{code:R.too_big,maximum:e.value,type:"string",inclusive:!0,exact:!1,message:e.message}),s.dirty()}else if(e.kind==="length"){let i=t.data.length>e.value,f=t.data.length<e.value;if(i||f){if(r=this._getOrReturnCtx(t,r),i)$(r,{code:R.too_big,maximum:e.value,type:"string",inclusive:!0,exact:!0,message:e.message});else if(f)$(r,{code:R.too_small,minimum:e.value,type:"string",inclusive:!0,exact:!0,message:e.message});s.dirty()}}else if(e.kind==="email"){if(!mg.test(t.data))r=this._getOrReturnCtx(t,r),$(r,{validation:"email",code:R.invalid_string,message:e.message}),s.dirty()}else if(e.kind==="emoji"){if(!Ho)Ho=new RegExp(Fg,"u");if(!Ho.test(t.data))r=this._getOrReturnCtx(t,r),$(r,{validation:"emoji",code:R.invalid_string,message:e.message}),s.dirty()}else if(e.kind==="uuid"){if(!Og.test(t.data))r=this._getOrReturnCtx(t,r),$(r,{validation:"uuid",code:R.invalid_string,message:e.message}),s.dirty()}else if(e.kind==="nanoid"){if(!yg.test(t.data))r=this._getOrReturnCtx(t,r),$(r,{validation:"nanoid",code:R.invalid_string,message:e.message}),s.dirty()}else if(e.kind==="cuid"){if(!Ug.test(t.data))r=this._getOrReturnCtx(t,r),$(r,{validation:"cuid",code:R.invalid_string,message:e.message}),s.dirty()}else if(e.kind==="cuid2"){if(!Lg.test(t.data))r=this._getOrReturnCtx(t,r),$(r,{validation:"cuid2",code:R.invalid_string,message:e.message}),s.dirty()}else if(e.kind==="ulid"){if(!Ig.test(t.data))r=this._getOrReturnCtx(t,r),$(r,{validation:"ulid",code:R.invalid_string,message:e.message}),s.dirty()}else if(e.kind==="url")try{new URL(t.data)}catch{r=this._getOrReturnCtx(t,r),$(r,{validation:"url",code:R.invalid_string,message:e.message}),s.dirty()}else if(e.kind==="regex"){if(e.regex.lastIndex=0,!e.regex.test(t.data))r=this._getOrReturnCtx(t,r),$(r,{validation:"regex",code:R.invalid_string,message:e.message}),s.dirty()}else if(e.kind==="trim")t.data=t.data.trim();else if(e.kind==="includes"){if(!t.data.includes(e.value,e.position))r=this._getOrReturnCtx(t,r),$(r,{code:R.invalid_string,validation:{includes:e.value,position:e.position},message:e.message}),s.dirty()}else if(e.kind==="toLowerCase")t.data=t.data.toLowerCase();else if(e.kind==="toUpperCase")t.data=t.data.toUpperCase();else if(e.kind==="startsWith"){if(!t.data.startsWith(e.value))r=this._getOrReturnCtx(t,r),$(r,{code:R.invalid_string,validation:{startsWith:e.value},message:e.message}),s.dirty()}else if(e.kind==="endsWith"){if(!t.data.endsWith(e.value))r=this._getOrReturnCtx(t,r),$(r,{code:R.invalid_string,validation:{endsWith:e.value},message:e.message}),s.dirty()}else if(e.kind==="datetime"){if(!uu(e).test(t.data))r=this._getOrReturnCtx(t,r),$(r,{code:R.invalid_string,validation:"datetime",message:e.message}),s.dirty()}else if(e.kind==="date"){if(!xg.test(t.data))r=this._getOrReturnCtx(t,r),$(r,{code:R.invalid_string,validation:"date",message:e.message}),s.dirty()}else if(e.kind==="time"){if(!Qg(e).test(t.data))r=this._getOrReturnCtx(t,r),$(r,{code:R.invalid_string,validation:"time",message:e.message}),s.dirty()}else if(e.kind==="duration"){if(!Bg.test(t.data))r=this._getOrReturnCtx(t,r),$(r,{validation:"duration",code:R.invalid_string,message:e.message}),s.dirty()}else if(e.kind==="ip"){if(!Jg(t.data,e.version))r=this._getOrReturnCtx(t,r),$(r,{validation:"ip",code:R.invalid_string,message:e.message}),s.dirty()}else if(e.kind==="jwt"){if(!zg(t.data,e.alg))r=this._getOrReturnCtx(t,r),$(r,{validation:"jwt",code:R.invalid_string,message:e.message}),s.dirty()}else if(e.kind==="cidr"){if(!kg(t.data,e.version))r=this._getOrReturnCtx(t,r),$(r,{validation:"cidr",code:R.invalid_string,message:e.message}),s.dirty()}else if(e.kind==="base64"){if(!Wg.test(t.data))r=this._getOrReturnCtx(t,r),$(r,{validation:"base64",code:R.invalid_string,message:e.message}),s.dirty()}else if(e.kind==="base64url"){if(!Yg.test(t.data))r=this._getOrReturnCtx(t,r),$(r,{validation:"base64url",code:R.invalid_string,message:e.message}),s.dirty()}else J.assertNever(e);return{status:s.value,value:t.data}}_regex(t,n,s){return this.refinement((r)=>t.test(r),{validation:n,code:R.invalid_string,...y.errToObj(s)})}_addCheck(t){return new Wt({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...y.errToObj(t)})}url(t){return this._addCheck({kind:"url",...y.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...y.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...y.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...y.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...y.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...y.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...y.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...y.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...y.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...y.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...y.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...y.errToObj(t)})}datetime(t){if(typeof t==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t});return this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...y.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){if(typeof t==="string")return this._addCheck({kind:"time",precision:null,message:t});return this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...y.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...y.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...y.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...y.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...y.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...y.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...y.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...y.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...y.errToObj(n)})}nonempty(t){return this.min(1,y.errToObj(t))}trim(){return new Wt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Wt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Wt({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((t)=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find((t)=>t.kind==="date")}get isTime(){return!!this._def.checks.find((t)=>t.kind==="time")}get isDuration(){return!!this._def.checks.find((t)=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find((t)=>t.kind==="email")}get isURL(){return!!this._def.checks.find((t)=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find((t)=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find((t)=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((t)=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((t)=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((t)=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find((t)=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find((t)=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find((t)=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find((t)=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find((t)=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)if(n.kind==="min"){if(t===null||n.value>t)t=n.value}return t}get maxLength(){let t=null;for(let n of this._def.checks)if(n.kind==="max"){if(t===null||n.value<t)t=n.value}return t}}Wt.create=(t)=>{return new Wt({checks:[],typeName:P.ZodString,coerce:t?.coerce??!1,...D(t)})};function Xg(t,n){let s=(t.toString().split(".")[1]||"").length,r=(n.toString().split(".")[1]||"").length,e=s>r?s:r,i=Number.parseInt(t.toFixed(e).replace(".","")),f=Number.parseInt(n.toFixed(e).replace(".",""));return i%f/10**e}class yn extends W{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce)t.data=Number(t.data);if(this._getType(t)!==T.number){let e=this._getOrReturnCtx(t);return $(e,{code:R.invalid_type,expected:T.number,received:e.parsedType}),F}let s=void 0,r=new ht;for(let e of this._def.checks)if(e.kind==="int"){if(!J.isInteger(t.data))s=this._getOrReturnCtx(t,s),$(s,{code:R.invalid_type,expected:"integer",received:"float",message:e.message}),r.dirty()}else if(e.kind==="min"){if(e.inclusive?t.data<e.value:t.data<=e.value)s=this._getOrReturnCtx(t,s),$(s,{code:R.too_small,minimum:e.value,type:"number",inclusive:e.inclusive,exact:!1,message:e.message}),r.dirty()}else if(e.kind==="max"){if(e.inclusive?t.data>e.value:t.data>=e.value)s=this._getOrReturnCtx(t,s),$(s,{code:R.too_big,maximum:e.value,type:"number",inclusive:e.inclusive,exact:!1,message:e.message}),r.dirty()}else if(e.kind==="multipleOf"){if(Xg(t.data,e.value)!==0)s=this._getOrReturnCtx(t,s),$(s,{code:R.not_multiple_of,multipleOf:e.value,message:e.message}),r.dirty()}else if(e.kind==="finite"){if(!Number.isFinite(t.data))s=this._getOrReturnCtx(t,s),$(s,{code:R.not_finite,message:e.message}),r.dirty()}else J.assertNever(e);return{status:r.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,y.toString(n))}gt(t,n){return this.setLimit("min",t,!1,y.toString(n))}lte(t,n){return this.setLimit("max",t,!0,y.toString(n))}lt(t,n){return this.setLimit("max",t,!1,y.toString(n))}setLimit(t,n,s,r){return new yn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:s,message:y.toString(r)}]})}_addCheck(t){return new yn({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:y.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:y.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:y.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:y.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:y.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:y.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:y.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:y.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:y.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)if(n.kind==="min"){if(t===null||n.value>t)t=n.value}return t}get maxValue(){let t=null;for(let n of this._def.checks)if(n.kind==="max"){if(t===null||n.value<t)t=n.value}return t}get isInt(){return!!this._def.checks.find((t)=>t.kind==="int"||t.kind==="multipleOf"&&J.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let s of this._def.checks)if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;else if(s.kind==="min"){if(n===null||s.value>n)n=s.value}else if(s.kind==="max"){if(t===null||s.value<t)t=s.value}return Number.isFinite(n)&&Number.isFinite(t)}}yn.create=(t)=>{return new yn({checks:[],typeName:P.ZodNumber,coerce:t?.coerce||!1,...D(t)})};class Gn extends W{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==T.bigint)return this._getInvalidInput(t);let s=void 0,r=new ht;for(let e of this._def.checks)if(e.kind==="min"){if(e.inclusive?t.data<e.value:t.data<=e.value)s=this._getOrReturnCtx(t,s),$(s,{code:R.too_small,type:"bigint",minimum:e.value,inclusive:e.inclusive,message:e.message}),r.dirty()}else if(e.kind==="max"){if(e.inclusive?t.data>e.value:t.data>=e.value)s=this._getOrReturnCtx(t,s),$(s,{code:R.too_big,type:"bigint",maximum:e.value,inclusive:e.inclusive,message:e.message}),r.dirty()}else if(e.kind==="multipleOf"){if(t.data%e.value!==BigInt(0))s=this._getOrReturnCtx(t,s),$(s,{code:R.not_multiple_of,multipleOf:e.value,message:e.message}),r.dirty()}else J.assertNever(e);return{status:r.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return $(n,{code:R.invalid_type,expected:T.bigint,received:n.parsedType}),F}gte(t,n){return this.setLimit("min",t,!0,y.toString(n))}gt(t,n){return this.setLimit("min",t,!1,y.toString(n))}lte(t,n){return this.setLimit("max",t,!0,y.toString(n))}lt(t,n){return this.setLimit("max",t,!1,y.toString(n))}setLimit(t,n,s,r){return new Gn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:s,message:y.toString(r)}]})}_addCheck(t){return new Gn({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:y.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:y.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:y.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:y.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:y.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)if(n.kind==="min"){if(t===null||n.value>t)t=n.value}return t}get maxValue(){let t=null;for(let n of this._def.checks)if(n.kind==="max"){if(t===null||n.value<t)t=n.value}return t}}Gn.create=(t)=>{return new Gn({checks:[],typeName:P.ZodBigInt,coerce:t?.coerce??!1,...D(t)})};class Ls extends W{_parse(t){if(this._def.coerce)t.data=Boolean(t.data);if(this._getType(t)!==T.boolean){let s=this._getOrReturnCtx(t);return $(s,{code:R.invalid_type,expected:T.boolean,received:s.parsedType}),F}return wt(t.data)}}Ls.create=(t)=>{return new Ls({typeName:P.ZodBoolean,coerce:t?.coerce||!1,...D(t)})};class Vn extends W{_parse(t){if(this._def.coerce)t.data=new Date(t.data);if(this._getType(t)!==T.date){let e=this._getOrReturnCtx(t);return $(e,{code:R.invalid_type,expected:T.date,received:e.parsedType}),F}if(Number.isNaN(t.data.getTime())){let e=this._getOrReturnCtx(t);return $(e,{code:R.invalid_date}),F}let s=new ht,r=void 0;for(let e of this._def.checks)if(e.kind==="min"){if(t.data.getTime()<e.value)r=this._getOrReturnCtx(t,r),$(r,{code:R.too_small,message:e.message,inclusive:!0,exact:!1,minimum:e.value,type:"date"}),s.dirty()}else if(e.kind==="max"){if(t.data.getTime()>e.value)r=this._getOrReturnCtx(t,r),$(r,{code:R.too_big,message:e.message,inclusive:!0,exact:!1,maximum:e.value,type:"date"}),s.dirty()}else J.assertNever(e);return{status:s.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Vn({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:y.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:y.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)if(n.kind==="min"){if(t===null||n.value>t)t=n.value}return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)if(n.kind==="max"){if(t===null||n.value<t)t=n.value}return t!=null?new Date(t):null}}Vn.create=(t)=>{return new Vn({checks:[],coerce:t?.coerce||!1,typeName:P.ZodDate,...D(t)})};class Mr extends W{_parse(t){if(this._getType(t)!==T.symbol){let s=this._getOrReturnCtx(t);return $(s,{code:R.invalid_type,expected:T.symbol,received:s.parsedType}),F}return wt(t.data)}}Mr.create=(t)=>{return new Mr({typeName:P.ZodSymbol,...D(t)})};class Is extends W{_parse(t){if(this._getType(t)!==T.undefined){let s=this._getOrReturnCtx(t);return $(s,{code:R.invalid_type,expected:T.undefined,received:s.parsedType}),F}return wt(t.data)}}Is.create=(t)=>{return new Is({typeName:P.ZodUndefined,...D(t)})};class Os extends W{_parse(t){if(this._getType(t)!==T.null){let s=this._getOrReturnCtx(t);return $(s,{code:R.invalid_type,expected:T.null,received:s.parsedType}),F}return wt(t.data)}}Os.create=(t)=>{return new Os({typeName:P.ZodNull,...D(t)})};class jn extends W{constructor(){super(...arguments);this._any=!0}_parse(t){return wt(t.data)}}jn.create=(t)=>{return new jn({typeName:P.ZodAny,...D(t)})};class On extends W{constructor(){super(...arguments);this._unknown=!0}_parse(t){return wt(t.data)}}On.create=(t)=>{return new On({typeName:P.ZodUnknown,...D(t)})};class jt extends W{_parse(t){let n=this._getOrReturnCtx(t);return $(n,{code:R.invalid_type,expected:T.never,received:n.parsedType}),F}}jt.create=(t)=>{return new jt({typeName:P.ZodNever,...D(t)})};class dr extends W{_parse(t){if(this._getType(t)!==T.undefined){let s=this._getOrReturnCtx(t);return $(s,{code:R.invalid_type,expected:T.void,received:s.parsedType}),F}return wt(t.data)}}dr.create=(t)=>{return new dr({typeName:P.ZodVoid,...D(t)})};class Yt extends W{_parse(t){let{ctx:n,status:s}=this._processInputParams(t),r=this._def;if(n.parsedType!==T.array)return $(n,{code:R.invalid_type,expected:T.array,received:n.parsedType}),F;if(r.exactLength!==null){let i=n.data.length>r.exactLength.value,f=n.data.length<r.exactLength.value;if(i||f)$(n,{code:i?R.too_big:R.too_small,minimum:f?r.exactLength.value:void 0,maximum:i?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),s.dirty()}if(r.minLength!==null){if(n.data.length<r.minLength.value)$(n,{code:R.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),s.dirty()}if(r.maxLength!==null){if(n.data.length>r.maxLength.value)$(n,{code:R.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),s.dirty()}if(n.common.async)return Promise.all([...n.data].map((i,f)=>{return r.type._parseAsync(new Qt(n,i,n.path,f))})).then((i)=>{return ht.mergeArray(s,i)});let e=[...n.data].map((i,f)=>{return r.type._parseSync(new Qt(n,i,n.path,f))});return ht.mergeArray(s,e)}get element(){return this._def.type}min(t,n){return new Yt({...this._def,minLength:{value:t,message:y.toString(n)}})}max(t,n){return new Yt({...this._def,maxLength:{value:t,message:y.toString(n)}})}length(t,n){return new Yt({...this._def,exactLength:{value:t,message:y.toString(n)}})}nonempty(t){return this.min(1,t)}}Yt.create=(t,n)=>{return new Yt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:P.ZodArray,...D(n)})};function $s(t){if(t instanceof p){let n={};for(let s in t.shape){let r=t.shape[s];n[s]=xt.create($s(r))}return new p({...t._def,shape:()=>n})}else if(t instanceof Yt)return new Yt({...t._def,type:$s(t.element)});else if(t instanceof xt)return xt.create($s(t.unwrap()));else if(t instanceof Mn)return Mn.create($s(t.unwrap()));else if(t instanceof pt)return pt.create(t.items.map((n)=>$s(n)));else return t}class p extends W{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=J.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==T.object){let c=this._getOrReturnCtx(t);return $(c,{code:R.invalid_type,expected:T.object,received:c.parsedType}),F}let{status:s,ctx:r}=this._processInputParams(t),{shape:e,keys:i}=this._getCached(),f=[];if(!(this._def.catchall instanceof jt&&this._def.unknownKeys==="strip")){for(let c in r.data)if(!i.includes(c))f.push(c)}let o=[];for(let c of i){let h=e[c],u=r.data[c];o.push({key:{status:"valid",value:c},value:h._parse(new Qt(r,u,r.path,c)),alwaysSet:c in r.data})}if(this._def.catchall instanceof jt){let c=this._def.unknownKeys;if(c==="passthrough")for(let h of f)o.push({key:{status:"valid",value:h},value:{status:"valid",value:r.data[h]}});else if(c==="strict"){if(f.length>0)$(r,{code:R.unrecognized_keys,keys:f}),s.dirty()}else if(c==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let h of f){let u=r.data[h];o.push({key:{status:"valid",value:h},value:c._parse(new Qt(r,u,r.path,h)),alwaysSet:h in r.data})}}if(r.common.async)return Promise.resolve().then(async()=>{let c=[];for(let h of o){let u=await h.key,l=await h.value;c.push({key:u,value:l,alwaysSet:h.alwaysSet})}return c}).then((c)=>{return ht.mergeObjectSync(s,c)});else return ht.mergeObjectSync(s,o)}get shape(){return this._def.shape()}strict(t){return y.errToObj,new p({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,s)=>{let r=this._def.errorMap?.(n,s).message??s.defaultError;if(n.code==="unrecognized_keys")return{message:y.errToObj(t).message??r};return{message:r}}}:{}})}strip(){return new p({...this._def,unknownKeys:"strip"})}passthrough(){return new p({...this._def,unknownKeys:"passthrough"})}extend(t){return new p({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new p({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:P.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new p({...this._def,catchall:t})}pick(t){let n={};for(let s of J.objectKeys(t))if(t[s]&&this.shape[s])n[s]=this.shape[s];return new p({...this._def,shape:()=>n})}omit(t){let n={};for(let s of J.objectKeys(this.shape))if(!t[s])n[s]=this.shape[s];return new p({...this._def,shape:()=>n})}deepPartial(){return $s(this)}partial(t){let n={};for(let s of J.objectKeys(this.shape)){let r=this.shape[s];if(t&&!t[s])n[s]=r;else n[s]=r.optional()}return new p({...this._def,shape:()=>n})}required(t){let n={};for(let s of J.objectKeys(this.shape))if(t&&!t[s])n[s]=this.shape[s];else{let e=this.shape[s];while(e instanceof xt)e=e._def.innerType;n[s]=e}return new p({...this._def,shape:()=>n})}keyof(){return lu(J.objectKeys(this.shape))}}p.create=(t,n)=>{return new p({shape:()=>t,unknownKeys:"strip",catchall:jt.create(),typeName:P.ZodObject,...D(n)})};p.strictCreate=(t,n)=>{return new p({shape:()=>t,unknownKeys:"strict",catchall:jt.create(),typeName:P.ZodObject,...D(n)})};p.lazycreate=(t,n)=>{return new p({shape:t,unknownKeys:"strip",catchall:jt.create(),typeName:P.ZodObject,...D(n)})};class ys extends W{_parse(t){let{ctx:n}=this._processInputParams(t),s=this._def.options;function r(e){for(let f of e)if(f.result.status==="valid")return f.result;for(let f of e)if(f.result.status==="dirty")return n.common.issues.push(...f.ctx.common.issues),f.result;let i=e.map((f)=>new gt(f.ctx.common.issues));return $(n,{code:R.invalid_union,unionErrors:i}),F}if(n.common.async)return Promise.all(s.map(async(e)=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await e._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(r);else{let e=void 0,i=[];for(let o of s){let c={...n,common:{...n.common,issues:[]},parent:null},h=o._parseSync({data:n.data,path:n.path,parent:c});if(h.status==="valid")return h;else if(h.status==="dirty"&&!e)e={result:h,ctx:c};if(c.common.issues.length)i.push(c.common.issues)}if(e)return n.common.issues.push(...e.ctx.common.issues),e.result;let f=i.map((o)=>new gt(o));return $(n,{code:R.invalid_union,unionErrors:f}),F}}get options(){return this._def.options}}ys.create=(t,n)=>{return new ys({options:t,typeName:P.ZodUnion,...D(n)})};var An=(t)=>{if(t instanceof Bs)return An(t.schema);else if(t instanceof Jt)return An(t.innerType());else if(t instanceof ms)return[t.value];else if(t instanceof Bn)return t.options;else if(t instanceof Fs)return J.objectValues(t.enum);else if(t instanceof Ps)return An(t._def.innerType);else if(t instanceof Is)return[void 0];else if(t instanceof Os)return[null];else if(t instanceof xt)return[void 0,...An(t.unwrap())];else if(t instanceof Mn)return[null,...An(t.unwrap())];else if(t instanceof Te)return An(t.unwrap());else if(t instanceof Ns)return An(t.unwrap());else if(t instanceof Hs)return An(t._def.innerType);else return[]};class be extends W{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==T.object)return $(n,{code:R.invalid_type,expected:T.object,received:n.parsedType}),F;let s=this.discriminator,r=n.data[s],e=this.optionsMap.get(r);if(!e)return $(n,{code:R.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),F;if(n.common.async)return e._parseAsync({data:n.data,path:n.path,parent:n});else return e._parseSync({data:n.data,path:n.path,parent:n})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,s){let r=new Map;for(let e of n){let i=An(e.shape[t]);if(!i.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let f of i){if(r.has(f))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(f)}`);r.set(f,e)}}return new be({typeName:P.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:r,...D(s)})}}function No(t,n){let s=Vt(t),r=Vt(n);if(t===n)return{valid:!0,data:t};else if(s===T.object&&r===T.object){let e=J.objectKeys(n),i=J.objectKeys(t).filter((o)=>e.indexOf(o)!==-1),f={...t,...n};for(let o of i){let c=No(t[o],n[o]);if(!c.valid)return{valid:!1};f[o]=c.data}return{valid:!0,data:f}}else if(s===T.array&&r===T.array){if(t.length!==n.length)return{valid:!1};let e=[];for(let i=0;i<t.length;i++){let f=t[i],o=n[i],c=No(f,o);if(!c.valid)return{valid:!1};e.push(c.data)}return{valid:!0,data:e}}else if(s===T.date&&r===T.date&&+t===+n)return{valid:!0,data:t};else return{valid:!1}}class Gs extends W{_parse(t){let{status:n,ctx:s}=this._processInputParams(t),r=(e,i)=>{if(Ee(e)||Ee(i))return F;let f=No(e.value,i.value);if(!f.valid)return $(s,{code:R.invalid_intersection_types}),F;if(Re(e)||Re(i))n.dirty();return{status:n.value,value:f.data}};if(s.common.async)return Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([e,i])=>r(e,i));else return r(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}Gs.create=(t,n,s)=>{return new Gs({left:t,right:n,typeName:P.ZodIntersection,...D(s)})};class pt extends W{_parse(t){let{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==T.array)return $(s,{code:R.invalid_type,expected:T.array,received:s.parsedType}),F;if(s.data.length<this._def.items.length)return $(s,{code:R.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),F;if(!this._def.rest&&s.data.length>this._def.items.length)$(s,{code:R.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty();let e=[...s.data].map((i,f)=>{let o=this._def.items[f]||this._def.rest;if(!o)return null;return o._parse(new Qt(s,i,s.path,f))}).filter((i)=>!!i);if(s.common.async)return Promise.all(e).then((i)=>{return ht.mergeArray(n,i)});else return ht.mergeArray(n,e)}get items(){return this._def.items}rest(t){return new pt({...this._def,rest:t})}}pt.create=(t,n)=>{if(!Array.isArray(t))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new pt({items:t,typeName:P.ZodTuple,rest:null,...D(n)})};class gr extends W{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==T.object)return $(s,{code:R.invalid_type,expected:T.object,received:s.parsedType}),F;let r=[],e=this._def.keyType,i=this._def.valueType;for(let f in s.data)r.push({key:e._parse(new Qt(s,f,s.path,f)),value:i._parse(new Qt(s,s.data[f],s.path,f)),alwaysSet:f in s.data});if(s.common.async)return ht.mergeObjectAsync(n,r);else return ht.mergeObjectSync(n,r)}get element(){return this._def.valueType}static create(t,n,s){if(n instanceof W)return new gr({keyType:t,valueType:n,typeName:P.ZodRecord,...D(s)});return new gr({keyType:Wt.create(),valueType:t,typeName:P.ZodRecord,...D(n)})}}class Er extends W{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==T.map)return $(s,{code:R.invalid_type,expected:T.map,received:s.parsedType}),F;let r=this._def.keyType,e=this._def.valueType,i=[...s.data.entries()].map(([f,o],c)=>{return{key:r._parse(new Qt(s,f,s.path,[c,"key"])),value:e._parse(new Qt(s,o,s.path,[c,"value"]))}});if(s.common.async){let f=new Map;return Promise.resolve().then(async()=>{for(let o of i){let c=await o.key,h=await o.value;if(c.status==="aborted"||h.status==="aborted")return F;if(c.status==="dirty"||h.status==="dirty")n.dirty();f.set(c.value,h.value)}return{status:n.value,value:f}})}else{let f=new Map;for(let o of i){let{key:c,value:h}=o;if(c.status==="aborted"||h.status==="aborted")return F;if(c.status==="dirty"||h.status==="dirty")n.dirty();f.set(c.value,h.value)}return{status:n.value,value:f}}}}Er.create=(t,n,s)=>{return new Er({valueType:n,keyType:t,typeName:P.ZodMap,...D(s)})};class pn extends W{_parse(t){let{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==T.set)return $(s,{code:R.invalid_type,expected:T.set,received:s.parsedType}),F;let r=this._def;if(r.minSize!==null){if(s.data.size<r.minSize.value)$(s,{code:R.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),n.dirty()}if(r.maxSize!==null){if(s.data.size>r.maxSize.value)$(s,{code:R.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),n.dirty()}let e=this._def.valueType;function i(o){let c=new Set;for(let h of o){if(h.status==="aborted")return F;if(h.status==="dirty")n.dirty();c.add(h.value)}return{status:n.value,value:c}}let f=[...s.data.values()].map((o,c)=>e._parse(new Qt(s,o,s.path,c)));if(s.common.async)return Promise.all(f).then((o)=>i(o));else return i(f)}min(t,n){return new pn({...this._def,minSize:{value:t,message:y.toString(n)}})}max(t,n){return new pn({...this._def,maxSize:{value:t,message:y.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}pn.create=(t,n)=>{return new pn({valueType:t,minSize:null,maxSize:null,typeName:P.ZodSet,...D(n)})};class Us extends W{constructor(){super(...arguments);this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==T.function)return $(n,{code:R.invalid_type,expected:T.function,received:n.parsedType}),F;function s(f,o){return Ar({data:f,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Ts(),wn].filter((c)=>!!c),issueData:{code:R.invalid_arguments,argumentsError:o}})}function r(f,o){return Ar({data:f,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Ts(),wn].filter((c)=>!!c),issueData:{code:R.invalid_return_type,returnTypeError:o}})}let e={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof vn){let f=this;return wt(async function(...o){let c=new gt([]),h=await f._def.args.parseAsync(o,e).catch((_)=>{throw c.addIssue(s(o,_)),c}),u=await Reflect.apply(i,this,h);return await f._def.returns._def.type.parseAsync(u,e).catch((_)=>{throw c.addIssue(r(u,_)),c})})}else{let f=this;return wt(function(...o){let c=f._def.args.safeParse(o,e);if(!c.success)throw new gt([s(o,c.error)]);let h=Reflect.apply(i,this,c.data),u=f._def.returns.safeParse(h,e);if(!u.success)throw new gt([r(h,u.error)]);return u.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Us({...this._def,args:pt.create(t).rest(On.create())})}returns(t){return new Us({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,s){return new Us({args:t?t:pt.create([]).rest(On.create()),returns:n||On.create(),typeName:P.ZodFunction,...D(s)})}}class Bs extends W{get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Bs.create=(t,n)=>{return new Bs({getter:t,typeName:P.ZodLazy,...D(n)})};class ms extends W{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return $(n,{received:n.data,code:R.invalid_literal,expected:this._def.value}),F}return{status:"valid",value:t.data}}get value(){return this._def.value}}ms.create=(t,n)=>{return new ms({value:t,typeName:P.ZodLiteral,...D(n)})};function lu(t,n){return new Bn({values:t,typeName:P.ZodEnum,...D(n)})}class Bn extends W{_parse(t){if(typeof t.data!=="string"){let n=this._getOrReturnCtx(t),s=this._def.values;return $(n,{expected:J.joinValues(s),received:n.parsedType,code:R.invalid_type}),F}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),s=this._def.values;return $(n,{received:n.data,code:R.invalid_enum_value,options:s}),F}return wt(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return Bn.create(t,{...this._def,...n})}exclude(t,n=this._def){return Bn.create(this.options.filter((s)=>!t.includes(s)),{...this._def,...n})}}Bn.create=lu;class Fs extends W{_parse(t){let n=J.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(t);if(s.parsedType!==T.string&&s.parsedType!==T.number){let r=J.objectValues(n);return $(s,{expected:J.joinValues(r),received:s.parsedType,code:R.invalid_type}),F}if(!this._cache)this._cache=new Set(J.getValidEnumValues(this._def.values));if(!this._cache.has(t.data)){let r=J.objectValues(n);return $(s,{received:s.data,code:R.invalid_enum_value,options:r}),F}return wt(t.data)}get enum(){return this._def.values}}Fs.create=(t,n)=>{return new Fs({values:t,typeName:P.ZodNativeEnum,...D(n)})};class vn extends W{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==T.promise&&n.common.async===!1)return $(n,{code:R.invalid_type,expected:T.promise,received:n.parsedType}),F;let s=n.parsedType===T.promise?n.data:Promise.resolve(n.data);return wt(s.then((r)=>{return this._def.type.parseAsync(r,{path:n.path,errorMap:n.common.contextualErrorMap})}))}}vn.create=(t,n)=>{return new vn({type:t,typeName:P.ZodPromise,...D(n)})};class Jt extends W{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===P.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:s}=this._processInputParams(t),r=this._def.effect||null,e={addIssue:(i)=>{if($(s,i),i.fatal)n.abort();else n.dirty()},get path(){return s.path}};if(e.addIssue=e.addIssue.bind(e),r.type==="preprocess"){let i=r.transform(s.data,e);if(s.common.async)return Promise.resolve(i).then(async(f)=>{if(n.value==="aborted")return F;let o=await this._def.schema._parseAsync({data:f,path:s.path,parent:s});if(o.status==="aborted")return F;if(o.status==="dirty")return Kn(o.value);if(n.value==="dirty")return Kn(o.value);return o});else{if(n.value==="aborted")return F;let f=this._def.schema._parseSync({data:i,path:s.path,parent:s});if(f.status==="aborted")return F;if(f.status==="dirty")return Kn(f.value);if(n.value==="dirty")return Kn(f.value);return f}}if(r.type==="refinement"){let i=(f)=>{let o=r.refinement(f,e);if(s.common.async)return Promise.resolve(o);if(o instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return f};if(s.common.async===!1){let f=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(f.status==="aborted")return F;if(f.status==="dirty")n.dirty();return i(f.value),{status:n.value,value:f.value}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then((f)=>{if(f.status==="aborted")return F;if(f.status==="dirty")n.dirty();return i(f.value).then(()=>{return{status:n.value,value:f.value}})})}if(r.type==="transform")if(s.common.async===!1){let i=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!In(i))return F;let f=r.transform(i.value,e);if(f instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:f}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then((i)=>{if(!In(i))return F;return Promise.resolve(r.transform(i.value,e)).then((f)=>({status:n.value,value:f}))});J.assertNever(r)}}Jt.create=(t,n,s)=>{return new Jt({schema:t,typeName:P.ZodEffects,effect:n,...D(s)})};Jt.createWithPreprocess=(t,n,s)=>{return new Jt({schema:n,effect:{type:"preprocess",transform:t},typeName:P.ZodEffects,...D(s)})};class xt extends W{_parse(t){if(this._getType(t)===T.undefined)return wt(void 0);return this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}xt.create=(t,n)=>{return new xt({innerType:t,typeName:P.ZodOptional,...D(n)})};class Mn extends W{_parse(t){if(this._getType(t)===T.null)return wt(null);return this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Mn.create=(t,n)=>{return new Mn({innerType:t,typeName:P.ZodNullable,...D(n)})};class Ps extends W{_parse(t){let{ctx:n}=this._processInputParams(t),s=n.data;if(n.parsedType===T.undefined)s=this._def.defaultValue();return this._def.innerType._parse({data:s,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Ps.create=(t,n)=>{return new Ps({innerType:t,typeName:P.ZodDefault,defaultValue:typeof n.default==="function"?n.default:()=>n.default,...D(n)})};class Hs extends W{_parse(t){let{ctx:n}=this._processInputParams(t),s={...n,common:{...n.common,issues:[]}},r=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});if(Ss(r))return r.then((e)=>{return{status:"valid",value:e.status==="valid"?e.value:this._def.catchValue({get error(){return new gt(s.common.issues)},input:s.data})}});else return{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new gt(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}Hs.create=(t,n)=>{return new Hs({innerType:t,typeName:P.ZodCatch,catchValue:typeof n.catch==="function"?n.catch:()=>n.catch,...D(n)})};class Rr extends W{_parse(t){if(this._getType(t)!==T.nan){let s=this._getOrReturnCtx(t);return $(s,{code:R.invalid_type,expected:T.nan,received:s.parsedType}),F}return{status:"valid",value:t.data}}}Rr.create=(t)=>{return new Rr({typeName:P.ZodNaN,...D(t)})};var qg=Symbol("zod_brand");class Te extends W{_parse(t){let{ctx:n}=this._processInputParams(t),s=n.data;return this._def.type._parse({data:s,path:n.path,parent:n})}unwrap(){return this._def.type}}class br extends W{_parse(t){let{status:n,ctx:s}=this._processInputParams(t);if(s.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});if(e.status==="aborted")return F;if(e.status==="dirty")return n.dirty(),Kn(e.value);else return this._def.out._parseAsync({data:e.value,path:s.path,parent:s})})();else{let r=this._def.in._parseSync({data:s.data,path:s.path,parent:s});if(r.status==="aborted")return F;if(r.status==="dirty")return n.dirty(),{status:"dirty",value:r.value};else return this._def.out._parseSync({data:r.value,path:s.path,parent:s})}}static create(t,n){return new br({in:t,out:n,typeName:P.ZodPipeline})}}class Ns extends W{_parse(t){let n=this._def.innerType._parse(t),s=(r)=>{if(In(r))r.value=Object.freeze(r.value);return r};return Ss(n)?n.then((r)=>s(r)):s(n)}unwrap(){return this._def.innerType}}Ns.create=(t,n)=>{return new Ns({innerType:t,typeName:P.ZodReadonly,...D(n)})};function fu(t,n){let s=typeof t==="function"?t(n):typeof t==="string"?{message:t}:t;return typeof s==="string"?{message:s}:s}function _u(t,n={},s){if(t)return jn.create().superRefine((r,e)=>{let i=t(r);if(i instanceof Promise)return i.then((f)=>{if(!f){let o=fu(n,r),c=o.fatal??s??!0;e.addIssue({code:"custom",...o,fatal:c})}});if(!i){let f=fu(n,r),o=f.fatal??s??!0;e.addIssue({code:"custom",...f,fatal:o})}return});return jn.create()}var Cg={object:p.lazycreate},P;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(P||(P={}));var ag=(t,n={message:`Input not instance of ${t.name}`})=>_u((s)=>s instanceof t,n),wu=Wt.create,Au=yn.create,Kg=Rr.create,Vg=Gn.create,Mu=Ls.create,jg=Vn.create,pg=Mr.create,vg=Is.create,Zg=Os.create,tE=jn.create,nE=On.create,sE=jt.create,rE=dr.create,eE=Yt.create,iE=p.create,oE=p.strictCreate,fE=ys.create,cE=be.create,hE=Gs.create,uE=pt.create,lE=gr.create,_E=Er.create,wE=pn.create,AE=Us.create,ME=Bs.create,dE=ms.create,gE=Bn.create,EE=Fs.create,RE=vn.create,bE=Jt.create,TE=xt.create,SE=Mn.create,$E=Jt.createWithPreprocess,UE=br.create,LE=()=>wu().optional(),IE=()=>Au().optional(),OE=()=>Mu().optional(),yE={string:(t)=>Wt.create({...t,coerce:!0}),number:(t)=>yn.create({...t,coerce:!0}),boolean:(t)=>Ls.create({...t,coerce:!0}),bigint:(t)=>Gn.create({...t,coerce:!0}),date:(t)=>Vn.create({...t,coerce:!0})};var GE=F;var Se=g.enum(["low","medium","high","xhigh","max"]),Zn=g.enum(["us-east-1","us-east-2","us-west-1","us-west-2","af-south-1","ap-east-1","ap-south-2","ap-southeast-3","ap-southeast-5","ap-southeast-4","ap-south-1","ap-southeast-6","ap-northeast-3","ap-northeast-2","ap-southeast-1","ap-southeast-2","ap-east-2","ap-southeast-7","ap-northeast-1","ca-central-1","ca-west-1","eu-central-1","eu-west-1","eu-west-2","eu-south-1","eu-west-3","eu-south-2","eu-north-1","eu-central-2","il-central-1","mx-central-1","me-south-1","me-central-1","sa-east-1"]);var BE=g.array(g.string()).transform((t)=>t.map((n)=>n.trim()).filter((n)=>n.length>0)).refine((t)=>t.length>0,{message:"api_keys must contain at least one non-empty key"}),mE=g.preprocess((t)=>typeof t==="string"&&t.trim().length===0?null:t,g.string().trim().refine((t)=>URL.canParse(t),{message:"proxy_url must be a valid URL"}).refine((t)=>{if(!URL.canParse(t))return!1;let n=new URL(t).protocol;return n==="http:"||n==="https:"},{message:"proxy_url must be http(s)"}).nullable()).default(null),Do=g.object({host:g.string().default("127.0.0.1"),port:g.number().default(8787),api_keys:BE,proxy_url:mE,default_region:g.string().default("us-east-1"),account_selection_strategy:g.enum(["sticky","round-robin","lowest-usage"]).default("lowest-usage"),rate_limit_max_retries:g.number().default(3),rate_limit_retry_delay_ms:g.number().default(5000),max_request_iterations:g.number().default(20),request_timeout_ms:g.number().default(120000),stream_idle_timeout_ms:g.number().default(60000),max_request_body_bytes:g.number().default(10485760),token_expiry_buffer_ms:g.number().default(300000),effort:Se.nullable().default(null),auto_effort_mapping:g.boolean().default(!0),log_level:g.string().default("info"),test_upstream_endpoint:g.string().url().optional()});class Tr extends Error{constructor(t,n){super(t,n);this.name="ConfigLoadError"}}var NE=Do.partial();function DE(t){let n=t.XDG_CONFIG_HOME??du(HE(),".config");return du(n,"kiro-provider","config.json")}function WE(t){if(!FE(t))return{};try{let n=JSON.parse(PE(t,"utf8"));return NE.parse(n)}catch(n){if(n instanceof g.ZodError)throw new Tr(`Invalid configuration file ${t}: ${gu(n)}`,{cause:n});if(n instanceof Error)throw new Tr(`Unable to read configuration file ${t}: ${n.message}`,{cause:n});throw n}}function YE(t){let n=t.trim().toLowerCase();if(n==="true"||n==="1")return!0;if(n==="false"||n==="0")return!1;return t}function xE(t){let n={},s={KIRO_PROVIDER_HOST:"host",KIRO_PROVIDER_DEFAULT_REGION:"default_region",KIRO_PROVIDER_ACCOUNT_SELECTION_STRATEGY:"account_selection_strategy",KIRO_PROVIDER_EFFORT:"effort",KIRO_PROVIDER_LOG_LEVEL:"log_level",KIRO_PROVIDER_TEST_UPSTREAM:"test_upstream_endpoint"};for(let[o,c]of Object.entries(s)){let h=t[o];if(h!==void 0)n[c]=h}let r={KIRO_PROVIDER_PORT:"port",KIRO_PROVIDER_RATE_LIMIT_MAX_RETRIES:"rate_limit_max_retries",KIRO_PROVIDER_RATE_LIMIT_RETRY_DELAY_MS:"rate_limit_retry_delay_ms",KIRO_PROVIDER_MAX_REQUEST_ITERATIONS:"max_request_iterations",KIRO_PROVIDER_REQUEST_TIMEOUT_MS:"request_timeout_ms",KIRO_PROVIDER_STREAM_IDLE_TIMEOUT_MS:"stream_idle_timeout_ms",KIRO_PROVIDER_MAX_REQUEST_BODY_BYTES:"max_request_body_bytes",KIRO_PROVIDER_TOKEN_EXPIRY_BUFFER_MS:"token_expiry_buffer_ms"};for(let[o,c]of Object.entries(r)){let h=t[o];if(h!==void 0)n[c]=Number(h)}let e=t.KIRO_PROVIDER_API_KEYS;if(e!==void 0)n.api_keys=e.split(",");let i=t.KIRO_PROVIDER_PROXY_URL;if(i!==void 0)n.proxy_url=i.trim();let f=t.KIRO_PROVIDER_AUTO_EFFORT_MAPPING;if(f!==void 0)n.auto_effort_mapping=YE(f);return n}function gu(t){return t.issues.map((n)=>`${n.path.length>0?n.path.join("."):"config"}: ${n.message}`).join(", ")}function Eu(t={}){let n=t.env??process.env,s=t.configPath??DE(n);try{return Do.parse({...WE(s),...xE(n),...t.overrides})}catch(r){if(r instanceof Tr)throw r;if(r instanceof g.ZodError)throw new Tr(`Invalid configuration: ${gu(r)}`,{cause:r});throw r}}function $e(t){let n=t.split("|"),s=n[0]??"";if(n.length<2)return{refreshToken:s,authMethod:"desktop"};if(n.at(-1)==="idc")return{refreshToken:s,clientId:n[1],clientSecret:n[2],authMethod:"idc"};return{refreshToken:s,authMethod:"desktop"}}function Ru(t,n=120000){if(!t.access||!t.expires)return!0;return Date.now()>=t.expires-n}function Ue(t){if(t.authMethod==="idc"){if(!t.clientId||!t.clientSecret)throw Error("Missing credentials");return`${t.refreshToken}|${t.clientId}|${t.clientSecret}|idc`}return`${t.refreshToken}|desktop`}function QE(t){if(!t)return!1;return t.includes("Invalid refresh token")||t.includes("Invalid grant provided")||t.includes("invalid_grant")||t.includes("ExpiredTokenException")||t.includes("InvalidTokenException")||t.includes("ExpiredClientException")||t.includes("Client is expired")||t.includes("HTTP_401")||t.includes("HTTP_403")}function Le(t){if(!t)return!1;let n=t.toLowerCase();return n.includes("bearer token included in the request is invalid")||n.includes("access token has expired")||n.includes("access_token expired")||n.includes("the access token expired")}function Wo(t){return QE(t)}var bu=4;class Tu extends Error{accountId;constructor(t){super(`Account ${t} changed too frequently to update`);this.accountId=t;this.name="AccountConcurrentUpdateError"}}function JE(t){throw TypeError(`Unsupported account selection strategy: ${String(t)}`)}function Sr(t){return{...t}}function zE(t){return{refresh:Ue({refreshToken:t.refreshToken,authMethod:t.authMethod,...t.clientId?{clientId:t.clientId}:{},...t.clientSecret?{clientSecret:t.clientSecret}:{},...t.profileArn?{profileArn:t.profileArn}:{}}),access:t.accessToken,expires:t.expiresAt,authMethod:t.authMethod,region:t.region,...t.oidcRegion?{oidcRegion:t.oidcRegion}:{},...t.clientId?{clientId:t.clientId}:{},...t.clientSecret?{clientSecret:t.clientSecret}:{},...t.email?{email:t.email}:{},...t.profileArn?{profileArn:t.profileArn}:{}}}class Yo{strategy;database;accounts;stickyId;roundRobinCursor=0;constructor(t,n,s){this.strategy=n;this.database=s;this.accounts=t.map(Sr)}getAccountCount(){return this.accounts.length}getAccounts(){return this.accounts.map(Sr)}getMinWaitTime(){let t=Date.now(),n=this.accounts.map(({rateLimitResetTime:s})=>s-t).filter((s)=>s>0);return n.length===0?0:Math.min(...n)}reconcileFromDb(t=this.database){let n=new Map(this.accounts.map((s)=>[s.id,s]));if(this.accounts=t.getAccounts().map((s)=>{let r=n.get(s.id);return r?.generation===s.generation?r:Sr(s)}),this.stickyId&&!this.accounts.some(({id:s})=>s===this.stickyId))this.stickyId=void 0;return this.getAccounts()}selectHealthyAccount(){let t=Date.now(),n=this.accounts.filter((r)=>this.isSelectable(r,t)).sort((r,e)=>r.id.localeCompare(e.id));if(n.length===0)return null;let s=this.selectCandidate(n);return this.patchAccount(s.id,(r)=>({...r,isHealthy:!0,unhealthyReason:void 0,recoveryTime:void 0,lastUsed:t,usedCount:(r.usedCount??0)+1}))??null}getCurrentOrNext(){return this.selectHealthyAccount()}markRateLimited(t,n){return this.patchAccount(t.id,(s)=>({...s,rateLimitResetTime:n}))}markUnhealthy(t,n,s){let r=Date.now();return this.patchAccount(t.id,(e)=>{if(Wo(n))return{...e,failCount:10,isHealthy:!1,unhealthyReason:n,recoveryTime:void 0,lastUsed:r};let i=e.failCount+1;return{...e,failCount:i,isHealthy:i<10,unhealthyReason:n,recoveryTime:i>=10?s??r+3600000:void 0,lastUsed:r}})}updateFromAuth(t,n){let s=$e(n.refresh);for(let r=0;r<bu;r+=1){let e=r===0?t:this.database.getById(t.id);if(!e||!this.isSameLogin(t,e)){this.reconcileFromDb();return}let i={...e,refreshToken:s.refreshToken,accessToken:n.access,expiresAt:n.expires};if(this.database.updateExistingAccounts([i])===1){let f={...i,generation:e.generation+1};return this.replaceAccount(f),Sr(f)}}this.reconcileFromDb();return}toAuthDetails(t){return zE(t)}isSelectable(t,n){if(Wo(t.unhealthyReason))return!1;if(t.rateLimitResetTime>n)return!1;if(t.isHealthy||Le(t.unhealthyReason))return!0;return t.recoveryTime!==void 0&&t.recoveryTime<=n}isSameLogin(t,n){return n.refreshToken===t.refreshToken&&n.authMethod===t.authMethod&&n.clientId===t.clientId&&n.email===t.email&&n.startUrl===t.startUrl}selectCandidate(t){switch(this.strategy){case"sticky":{let s=t.find(({id:r})=>r===this.stickyId)??t[0];if(!s)throw RangeError("Candidate list cannot be empty");return this.stickyId=s.id,s}case"round-robin":{let n=t[this.roundRobinCursor%t.length];if(!n)throw RangeError("Candidate list cannot be empty");return this.roundRobinCursor+=1,n}case"lowest-usage":{let n=[...t].sort((s,r)=>(s.usedCount??0)-(r.usedCount??0)||(s.lastUsed??0)-(r.lastUsed??0)||s.id.localeCompare(r.id))[0];if(!n)throw RangeError("Candidate list cannot be empty");return n}default:return JE(this.strategy)}}patchAccount(t,n){for(let s=0;s<bu;s+=1){let r=this.database.getById(t);if(!r){this.accounts=this.accounts.filter((i)=>i.id!==t);return}let e=n(r);if(this.database.updateExistingAccounts([e])===1){let i={...e,generation:r.generation+1};return this.replaceAccount(i),Sr(i)}}throw this.reconcileFromDb(),new Tu(t)}replaceAccount(t){let n=this.accounts.findIndex(({id:s})=>s===t.id);if(n===-1)this.accounts.push(t);else this.accounts[n]=t}}var Du=H(Jo(),1);import*as Zt from"net";import*as Ur from"tls";import UR from"assert";import*as mu from"net";import*as Fu from"http";import{Agent as $R}from"https";var vt=Symbol("AgentBaseInternalState");class zo extends Fu.Agent{constructor(t){super(t);this[vt]={}}isSecureEndpoint(t){if(t){if(typeof t.secureEndpoint==="boolean")return t.secureEndpoint;if(typeof t.protocol==="string")return t.protocol==="https:"}let{stack:n}=Error();if(typeof n!=="string")return!1;return n.split(`
50
- `).some((s)=>s.indexOf("(https.js:")!==-1||s.indexOf("node:https:")!==-1)}incrementSockets(t){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;if(!this.sockets[t])this.sockets[t]=[];let n=new mu.Socket({writable:!1});return this.sockets[t].push(n),this.totalSocketCount++,n}decrementSockets(t,n){if(!this.sockets[t]||n===null)return;let s=this.sockets[t],r=s.indexOf(n);if(r!==-1){if(s.splice(r,1),this.totalSocketCount--,s.length===0)delete this.sockets[t]}}getName(t){if(this.isSecureEndpoint(t))return $R.prototype.getName.call(this,t);return super.getName(t)}createSocket(t,n,s){let r={...n,secureEndpoint:this.isSecureEndpoint(n)},e=this.getName(r),i=this.incrementSockets(e);Promise.resolve().then(()=>this.connect(t,r)).then((f)=>{if(this.decrementSockets(e,i),typeof f.addRequest==="function")try{return f.addRequest(t,r)}catch(o){return s(o)}this[vt].currentSocket=f,super.createSocket(t,n,s)},(f)=>{this.decrementSockets(e,i),s(f)})}createConnection(){let t=this[vt].currentSocket;if(this[vt].currentSocket=void 0,!t)throw Error("No socket was returned in the `connect()` function");return t}get defaultPort(){return this[vt].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(t){if(this[vt])this[vt].defaultPort=t}get protocol(){return this[vt].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(t){if(this[vt])this[vt].protocol=t}}import{URL as LR}from"url";var Pu=H(Jo(),1),Be=Pu.default("https-proxy-agent:parse-proxy-response");function ko(t){return new Promise((n,s)=>{let r=0,e=[];function i(){let u=t.read();if(u)h(u);else t.once("readable",i)}function f(){t.removeListener("end",o),t.removeListener("error",c),t.removeListener("readable",i)}function o(){f(),Be("onend"),s(Error("Proxy connection ended before receiving CONNECT response"))}function c(u){f(),Be("onerror %o",u),s(u)}function h(u){e.push(u),r+=u.length;let l=Buffer.concat(e,r),_=l.indexOf(`\r
47
+ >/?`.includes(t.x[t.i]))h+=t.x[t.i++];if(t.trim(),t.x[t.i]!=="=")break;++t.i,t.trim(),r[h]=t.readAttrValue(),s=!0}if(t.i>=t.z)throw Error("@aws-sdk XML parse error: unexpected end of input.");if(t.x[t.i]==="/"){if(++t.i,t.i>=t.z||t.x[t.i]!==">")throw Error("@aws-sdk XML parse error: expected > at the end of self-closing tag.");return++t.i,Object.setPrototypeOf(r,Object.prototype),{tag:n,value:s?r:""}}if(t.x[t.i]!==">")throw Error("@aws-sdk XML parse error: expected > at the end of opening tag.");++t.i;let i=[],e=[],f=!1;while(t.i<t.z){if(t.isNext("</"))break;if(t.x[t.i]==="<")if(t.isNext("<!--"))t.readTo("-->");else if(t.isNext("<![CDATA["))t.i+=9,i.push(t.readTo("]]>"));else if(t.isNext("<?"))t.readTo("?>");else f=!0,e.push(t.parseTag());else{let h="";while(t.i<t.z&&t.x[t.i]!=="<")h+=t.x[t.i++];i.push(t.decodeEntities(h))}}if(!t.isNext("</"))throw Error(`@aws-sdk XML parse error: missing closing tag </${n}>.`);t.i+=2;let o=t.readTo(">").trim();if(o!==n)throw Error(`@aws-sdk XML parse error: mismatched tags <${n}> and </${o}>.`);if(!s&&i.length===0&&!f)return{tag:n,value:""};if(!s&&!f){let h=i.length===1?i[0]:i.join("");if(h.trim()===""&&h.includes(`
48
+ `))return{tag:n,value:""};return{tag:n,value:h}}let c=Object.create(null);for(let h of i){if(h.trim()===""&&h.includes(`
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
+ `).some((s)=>s.indexOf("(https.js:")!==-1||s.indexOf("node:https:")!==-1)}incrementSockets(t){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;if(!this.sockets[t])this.sockets[t]=[];let n=new x0.Socket({writable:!1});return this.sockets[t].push(n),this.totalSocketCount++,n}decrementSockets(t,n){if(!this.sockets[t]||n===null)return;let s=this.sockets[t],r=s.indexOf(n);if(r!==-1){if(s.splice(r,1),this.totalSocketCount--,s.length===0)delete this.sockets[t]}}getName(t){if(this.isSecureEndpoint(t))return KR.prototype.getName.call(this,t);return super.getName(t)}createSocket(t,n,s){let r={...n,secureEndpoint:this.isSecureEndpoint(n)},i=this.getName(r),e=this.incrementSockets(i);Promise.resolve().then(()=>this.connect(t,r)).then((f)=>{if(this.decrementSockets(i,e),typeof f.addRequest==="function")try{return f.addRequest(t,r)}catch(o){return s(o)}this[vt].currentSocket=f,super.createSocket(t,n,s)},(f)=>{this.decrementSockets(i,e),s(f)})}createConnection(){let t=this[vt].currentSocket;if(this[vt].currentSocket=void 0,!t)throw Error("No socket was returned in the `connect()` function");return t}get defaultPort(){return this[vt].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(t){if(this[vt])this[vt].defaultPort=t}get protocol(){return this[vt].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(t){if(this[vt])this[vt].protocol=t}}import{URL as jR}from"url";var C0=Y(Vo(),1),Pi=C0.default("https-proxy-agent:parse-proxy-response");function ao(t){return new Promise((n,s)=>{let r=0,i=[];function e(){let u=t.read();if(u)h(u);else t.once("readable",e)}function f(){t.removeListener("end",o),t.removeListener("error",c),t.removeListener("readable",e)}function o(){f(),Pi("onend"),s(Error("Proxy connection ended before receiving CONNECT response"))}function c(u){f(),Pi("onerror %o",u),s(u)}function h(u){i.push(u),r+=u.length;let _=Buffer.concat(i,r),l=_.indexOf(`\r
51
51
  \r
52
- `);if(_===-1){Be("have not received end of HTTP headers yet..."),i();return}let w=l.slice(0,_).toString("ascii").split(`\r
53
- `),A=w.shift();if(!A)return t.destroy(),s(Error("No header received from proxy CONNECT response"));let M=A.split(" "),d=+M[1],E=M.slice(2).join(" "),b={};for(let L of w){if(!L)continue;let S=L.indexOf(":");if(S===-1)return t.destroy(),s(Error(`Invalid header from proxy CONNECT response: "${L}"`));let O=L.slice(0,S).toLowerCase(),x=L.slice(S+1).trimStart(),X=b[O];if(typeof X==="string")b[O]=[X,x];else if(Array.isArray(X))X.push(x);else b[O]=x}Be("got proxy server response: %o %o",A,b),f(),n({connect:{statusCode:d,statusText:E,headers:b},buffered:l})}t.on("error",c),t.on("end",o),i()})}function Hu(){return async({response:t,scheme:n})=>{if(n.toLowerCase()!=="negotiate")throw Error(`Expected Negotiate scheme but got "${n}"`);let s;try{s=await import("kerberos")}catch{throw Error('The "kerberos" package is required for Negotiate proxy authentication. Install it with: npm install kerberos')}let r=t.headers["proxy-authenticate"]||"",e=Array.isArray(r)?r[0]:r,i=typeof e==="string"&&e.includes(" ")?e.split(" ").slice(1).join(" "):void 0,o=await(await s.initializeClient("HTTP@proxy",{mechOID:s.GSS_MECH_OID_SPNEGO})).step(i||"");if(!o)throw Error("Kerberos client.step() returned no token");return{headers:{"Proxy-Authorization":`Negotiate ${o}`}}}}var ss=Du.default("https-proxy-agent"),me=(t)=>{if(t.servername===void 0&&t.host&&!Zt.isIP(t.host))return{...t,servername:t.host};return t};class Fe extends zo{constructor(t,n){super(n);if(this.options={path:void 0},this.proxy=typeof t==="string"?new LR(t):t,this.proxyHeaders=n?.headers??{},ss("Creating new HttpsProxyAgent instance: %o",this.proxy.href),n?.negotiate)this.onProxyAuth=Hu();else if(n?.onProxyAuth)this.onProxyAuth=n.onProxyAuth;let s=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),r=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...n?Xo(n,"headers","onProxyAuth","negotiate"):null,host:s,port:r}}async connect(t,n){let{proxy:s}=this;if(!n.host)throw TypeError('No "host" provided');let r;if(s.protocol==="https:")ss("Creating `tls.Socket`: %o",this.connectOpts),r=Ur.connect(me(this.connectOpts));else ss("Creating `net.Socket`: %o",this.connectOpts),r=Zt.connect(this.connectOpts);let e=typeof this.proxyHeaders==="function"?this.proxyHeaders():{...this.proxyHeaders},i=Zt.isIPv6(n.host)?`[${n.host}]`:n.host,f=`CONNECT ${i}:${n.port} HTTP/1.1\r
54
- `;if(s.username||s.password){let l=`${decodeURIComponent(s.username)}:${decodeURIComponent(s.password)}`;e["Proxy-Authorization"]=`Basic ${Buffer.from(l).toString("base64")}`}if(e.Host=`${i}:${n.port}`,!e["Proxy-Connection"])e["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close";for(let l of Object.keys(e))f+=`${l}: ${e[l]}\r
55
- `;let o=ko(r);r.write(`${f}\r
56
- `);let{connect:c,buffered:h}=await o;if(t.emit("proxyConnect",c),this.emit("proxyConnect",c,t),t.emit("proxy",{proxy:this.proxy.href,socket:r}),c.statusCode===200){if(t.once("socket",Nu),n.secureEndpoint)return ss("Upgrading socket connection to TLS"),Ur.connect({...Xo(me(n),"host","path","port"),socket:r});return r}if(c.statusCode===407&&this.onProxyAuth){ss("Got 407 response, invoking onProxyAuth callback"),r.destroy();let l=c.headers["proxy-authenticate"]||"",_=Array.isArray(l)?l[0].split(/\s/)[0]:l.split(/\s/)[0],w=await this.onProxyAuth({response:c,scheme:_});return this._connectWithAuth(t,n,w.headers)}r.destroy();let u=new Zt.Socket({writable:!1});return u.readable=!0,t.once("socket",(l)=>{ss("Replaying proxy buffer for failed request"),UR(l.listenerCount("data")>0),l.push(h),l.push(null)}),u}async _connectWithAuth(t,n,s){let{proxy:r}=this,e;if(r.protocol==="https:")e=Ur.connect(me(this.connectOpts));else e=Zt.connect(this.connectOpts);let i=typeof this.proxyHeaders==="function"?this.proxyHeaders():{...this.proxyHeaders},f=Zt.isIPv6(n.host)?`[${n.host}]`:n.host,o=`CONNECT ${f}:${n.port} HTTP/1.1\r
57
- `;if(r.username||r.password){let u=`${decodeURIComponent(r.username)}:${decodeURIComponent(r.password)}`;i["Proxy-Authorization"]=`Basic ${Buffer.from(u).toString("base64")}`}if(Object.assign(i,s),i.Host=`${f}:${n.port}`,!i["Proxy-Connection"])i["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close";for(let u of Object.keys(i))o+=`${u}: ${i[u]}\r
58
- `;let c=ko(e);e.write(`${o}\r
59
- `);let{connect:h}=await c;if(t.emit("proxyConnect",h),this.emit("proxyConnect",h,t),h.statusCode===200){if(t.once("socket",Nu),n.secureEndpoint)return ss("Upgrading socket connection to TLS"),Ur.connect({...Xo(me(n),"host","path","port"),socket:e});return e}throw e.destroy(),Error(`Proxy authentication failed with status ${h.statusCode} after retry`)}}Fe.protocols=["http","https"];function Nu(t){setImmediate(()=>{t.resume()})}function Xo(t,...n){let s={},r;for(r in t)if(!n.includes(r))s[r]=t[r];return s}var Wu=new Map;function xs(t){return t.proxy_url||void 0}function Yu(t){let n=Wu.get(t);if(n!==void 0)return n;let s=new Fe(t,{keepAlive:!0,maxSockets:50});return Wu.set(t,s),s}function xu(t){return t===void 0?{}:{proxy:t}}var IR=Zn.options;function Qu(t){return IR.includes(t)}function qo(t){if(!t||!Qu(t))return"us-east-1";return t}function Lr(t,n){let s=t.replace("{{region}}",n);try{return new URL(s),s}catch{throw Error(`Invalid URL generated: ${s}`)}}function Ju(t){if(!t)return;let n=t.split(":");if(n.length<6)return;if(n[0]!=="arn")return;let s=n[3];if(typeof s!=="string"||!s)return;return Qu(s)?s:void 0}var st={REFRESH_URL:"https://prod.{{region}}.auth.desktop.kiro.dev/refreshToken",REFRESH_IDC_URL:"https://oidc.{{region}}.amazonaws.com/token",BASE_URL:"https://q.{{region}}.amazonaws.com/generateAssistantResponse",USAGE_LIMITS_URL:"https://q.{{region}}.amazonaws.com/getUsageLimits",DEFAULT_REGION:"us-east-1",AXIOS_TIMEOUT:120000,USER_AGENT:"KiroIDE",SDK_VERSION:"3.738.0",SDK_VERSION_USAGE:"3.0.0",CHAT_TRIGGER_TYPE_MANUAL:"MANUAL",ORIGIN_AI_EDITOR:"AI_EDITOR"},Ir={"claude-haiku-4-5":"claude-haiku-4.5","claude-haiku-4-5-thinking":"claude-haiku-4.5","claude-sonnet-4":"claude-sonnet-4","claude-sonnet-4-5":"claude-sonnet-4.5","claude-sonnet-4-5-thinking":"claude-sonnet-4.5","claude-sonnet-4-5-1m":"claude-sonnet-4.5-1m","claude-sonnet-4-5-1m-thinking":"claude-sonnet-4.5-1m","claude-sonnet-4-6":"claude-sonnet-4.6","claude-sonnet-4-6-thinking":"claude-sonnet-4.6","claude-sonnet-4-6-1m":"claude-sonnet-4.6-1m","claude-sonnet-4-6-1m-thinking":"claude-sonnet-4.6-1m","claude-sonnet-5":"claude-sonnet-5","claude-sonnet-5-thinking":"claude-sonnet-5","claude-opus-4-5":"claude-opus-4.5","claude-opus-4-5-thinking":"claude-opus-4.5","claude-opus-4-6":"claude-opus-4.6","claude-opus-4-6-thinking":"claude-opus-4.6","claude-opus-4-6-1m":"claude-opus-4.6-1m","claude-opus-4-6-1m-thinking":"claude-opus-4.6-1m","claude-opus-4-7":"claude-opus-4.7","claude-opus-4-7-thinking":"claude-opus-4.7","claude-opus-4-8":"claude-opus-4.8","claude-opus-4-8-thinking":"claude-opus-4.8",auto:"auto","deepseek-3.2":"deepseek-3.2","glm-5":"glm-5","minimax-m2.5":"minimax-m2.5","minimax-m2.1":"minimax-m2.1","qwen3-coder-next":"qwen3-coder-next","gpt-5.6-sol":"gpt-5.6-sol","gpt-5.6-terra":"gpt-5.6-terra","gpt-5.6-luna":"gpt-5.6-luna","claude-3-7-sonnet":"CLAUDE_3_7_SONNET_20250219_V1_0","nova-swe":"AGI_NOVA_SWE_V1_5","gpt-oss-120b":"OPENAI_GPT_OSS_120B_1_0","minimax-m2":"MINIMAX_MINIMAX_M2","kimi-k2-thinking":"MOONSHOT_KIMI_K2_THINKING"},zu=Object.keys(Ir),V9=new Set(Object.keys(Ir).filter((t)=>t.includes("-1m")));var OR=200000,yR={auto:200000,"claude-haiku-4-5":200000,"claude-sonnet-4":200000,"claude-sonnet-4-5":200000,"claude-sonnet-4-5-1m":1e6,"claude-sonnet-4-6":1e6,"claude-sonnet-4-6-1m":1e6,"claude-sonnet-5":1e6,"claude-opus-4-5":200000,"claude-opus-4-6":1e6,"claude-opus-4-6-1m":1e6,"claude-opus-4-7":1e6,"claude-opus-4-8":1e6,"deepseek-3.2":128000,"glm-5":200000,"minimax-m2.5":200000,"minimax-m2.1":200000,"qwen3-coder-next":256000,"gpt-5.6-sol":272000,"gpt-5.6-terra":272000,"gpt-5.6-luna":272000};function G(t){return yR[t]??OR}var Or={ENDPOINT:"https://prod.{{region}}.auth.desktop.kiro.dev",SSO_OIDC_ENDPOINT:"https://oidc.{{region}}.amazonaws.com",BUILDER_ID_START_URL:"https://view.awsapps.com/start",USER_INFO_URL:"https://view.awsapps.com/api/user/info",SCOPES:["codewhisperer:completions","codewhisperer:analysis","codewhisperer:conversations","codewhisperer:transformations","codewhisperer:taskassist"]};class mn extends Error{code;originalError;constructor(t,n,s){super(t);this.name="KiroTokenRefreshError",this.code=n,this.originalError=s}}function Co(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function Pe(t,n,s){let r=t[n];if(typeof r==="string"&&r)return r;let e=t[s];return typeof e==="string"&&e?e:void 0}function GR(t,n,s){let r=t[n];if(typeof r==="number")return r;let e=t[s];return typeof e==="number"?e:void 0}function BR(t,n){let s;try{s=JSON.parse(t)}catch{return{message:t,code:`HTTP_${n}`}}if(!Co(s))return{message:t,code:`HTTP_${n}`};let r=Pe(s,"message","error_description")??t,e=Pe(s,"__type","error")??`HTTP_${n}`;return{message:r,code:e}}function ku(t){let n=t.userInfo;if(!Co(n))return;let s=n.email;return typeof s==="string"?s:void 0}async function Xu(t,n,s){let r=$e(t.refresh),e=t.authMethod==="idc",i=e?t.oidcRegion??t.region:t.region,f=Lr(e?st.REFRESH_IDC_URL:st.REFRESH_URL,i);if(e&&(!r.clientId||!r.clientSecret))throw new mn("Missing creds","MISSING_CREDENTIALS");let o=e?{refreshToken:r.refreshToken,clientId:r.clientId,clientSecret:r.clientSecret,grantType:"refresh_token"}:{refreshToken:r.refreshToken},c=e?`aws-sdk-js/${st.SDK_VERSION} ua/2.1 os/other lang/js md/browser#unknown_unknown api/sso-oidc#${st.SDK_VERSION} m/E ${st.USER_AGENT}`:`aws-sdk-js/3.0.0 ${st.USER_AGENT}-0.1.0 os/macos lang/js md/nodejs/18.0.0`;try{let h=await fetch(f,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","amz-sdk-request":"attempt=1; max=1","x-amzn-kiro-agent-mode":"vibe","user-agent":c,Connection:"close"},body:JSON.stringify(o),...n?{signal:n}:{},...xu(s)});if(!h.ok){let w=BR(await h.text(),h.status);throw new mn(`Refresh failed: ${w.message}`,w.code)}let u=await h.json();if(!Co(u))throw new mn("No access token","INVALID_RESPONSE");let l=Pe(u,"access_token","accessToken");if(!l)throw new mn("No access token","INVALID_RESPONSE");let _={refreshToken:Pe(u,"refresh_token","refreshToken")??r.refreshToken,authMethod:t.authMethod,...r.clientId?{clientId:r.clientId}:{},...r.clientSecret?{clientSecret:r.clientSecret}:{}};return{refresh:Ue(_),access:l,expires:Date.now()+(GR(u,"expires_in","expiresIn")??3600)*1000,authMethod:t.authMethod,region:t.region,...t.oidcRegion?{oidcRegion:t.oidcRegion}:{},...t.profileArn?{profileArn:t.profileArn}:{},...t.clientId?{clientId:t.clientId}:{},...t.clientSecret?{clientSecret:t.clientSecret}:{},...t.email||ku(u)?{email:t.email??ku(u)}:{}}}catch(h){if(h instanceof mn)throw h;if(h instanceof Error&&h.name==="AbortError")throw h;throw new mn(`Token refresh failed: ${h instanceof Error?h.message:"Unknown error"}`,"NETWORK_ERROR",h instanceof Error?h:void 0)}}class He extends Error{accountId;constructor(t){super(`Account ${t} is no longer available`);this.accountId=t;this.name="AccountUnavailableError"}}class ao{accountManager;tokenExpiryBufferMs;proxyUrl;inFlight=new Map;constructor(t,n,s){this.accountManager=t;this.tokenExpiryBufferMs=n;this.proxyUrl=s}async refreshIfNeeded(t,n,s){if(!Ru(n,this.tokenExpiryBufferMs)){let r=this.accountManager.getAccounts().find(({id:e})=>e===t.id);if(!r)throw new He(t.id);return r}return this.startOrJoinRefresh(t,n,s)}async forceRefresh(t,n){return this.startOrJoinRefresh(t,this.accountManager.toAuthDetails(t),n)}startOrJoinRefresh(t,n,s){if(!("generation"in t)||typeof t.generation!=="number")throw new He(t.id);let r={...t,generation:t.generation},e=`${r.id}:${r.generation}`,i=this.inFlight.get(e);if(i)return i;let f=this.runRefresh(r,n,s).finally(()=>{if(this.inFlight.get(e)===f)this.inFlight.delete(e)});return this.inFlight.set(e,f),f}async runRefresh(t,n,s){let r=await Xu(n,s,this.proxyUrl),e=this.accountManager.updateFromAuth(t,r);if(!e)throw new He(t.id);return e}}import{Database as mR}from"bun:sqlite";import{chmodSync as FR,existsSync as PR,mkdirSync as HR}from"fs";import{homedir as qu}from"os";import{dirname as NR,join as jo}from"path";function Ko(t,n){return{id:t.id,email:t.email,auth_method:t.authMethod,region:t.region,oidc_region:t.oidcRegion??null,client_id:t.clientId??null,client_secret:t.clientSecret??null,profile_arn:t.profileArn??null,start_url:t.startUrl??null,refresh_token:t.refreshToken,access_token:t.accessToken,expires_at:t.expiresAt,rate_limit_reset:t.rateLimitResetTime,is_healthy:t.isHealthy?1:0,unhealthy_reason:t.unhealthyReason??null,recovery_time:t.recoveryTime??null,fail_count:t.failCount,last_used:t.lastUsed??0,used_count:t.usedCount??0,limit_count:t.limitCount??0,last_sync:t.lastSync??0,overage_count:t.overageCount??0,generation:n}}function Ne(t){return{id:t.id,email:t.email,authMethod:t.auth_method,region:t.region,oidcRegion:t.oidc_region??void 0,clientId:t.client_id??void 0,clientSecret:t.client_secret??void 0,profileArn:t.profile_arn??void 0,startUrl:t.start_url??void 0,refreshToken:t.refresh_token,accessToken:t.access_token,expiresAt:t.expires_at,rateLimitResetTime:t.rate_limit_reset,isHealthy:t.is_healthy===1,unhealthyReason:t.unhealthy_reason??void 0,recoveryTime:t.recovery_time??void 0,failCount:t.fail_count,lastUsed:t.last_used,usedCount:t.used_count,limitCount:t.limit_count,lastSync:t.last_sync,overageCount:t.overage_count,generation:t.generation}}function Vo(t){return[t.id,t.email,t.auth_method,t.region??null,t.oidc_region??null,t.client_id??null,t.client_secret??null,t.profile_arn??null,t.start_url??null,t.refresh_token,t.access_token,t.expires_at,t.rate_limit_reset,t.is_healthy,t.unhealthy_reason??null,t.recovery_time??null,t.fail_count,t.last_used,t.used_count,t.limit_count,t.last_sync,t.overage_count,t.generation]}function DR(){let t=process.platform==="win32"?process.env.APPDATA??jo(qu(),"AppData","Roaming"):process.env.XDG_CONFIG_HOME??jo(qu(),".config");return jo(t,"kiro-provider","accounts.db")}var Fn=DR();class rs{db;path;constructor(t=Fn){if(this.path=t,t!==":memory:")HR(NR(t),{recursive:!0});this.db=new mR(t,{create:!0,strict:!0}),this.tightenPermissions(),this.db.run("PRAGMA busy_timeout = 5000"),this.db.run("PRAGMA journal_mode = WAL"),this.withImmediateTransaction(()=>{if(this.db.run(`
52
+ `);if(l===-1){Pi("have not received end of HTTP headers yet..."),e();return}let w=_.slice(0,l).toString("ascii").split(`\r
53
+ `),A=w.shift();if(!A)return t.destroy(),s(Error("No header received from proxy CONNECT response"));let M=A.split(" "),E=+M[1],d=M.slice(2).join(" "),T={};for(let U of w){if(!U)continue;let S=U.indexOf(":");if(S===-1)return t.destroy(),s(Error(`Invalid header from proxy CONNECT response: "${U}"`));let O=U.slice(0,S).toLowerCase(),D=U.slice(S+1).trimStart(),q=T[O];if(typeof q==="string")T[O]=[q,D];else if(Array.isArray(q))q.push(D);else T[O]=D}Pi("got proxy server response: %o %o",A,T),f(),n({connect:{statusCode:E,statusText:d,headers:T},buffered:_})}t.on("error",c),t.on("end",o),e()})}function K0(){return async({response:t,scheme:n})=>{if(n.toLowerCase()!=="negotiate")throw Error(`Expected Negotiate scheme but got "${n}"`);let s;try{s=await import("kerberos")}catch{throw Error('The "kerberos" package is required for Negotiate proxy authentication. Install it with: npm install kerberos')}let r=t.headers["proxy-authenticate"]||"",i=Array.isArray(r)?r[0]:r,e=typeof i==="string"&&i.includes(" ")?i.split(" ").slice(1).join(" "):void 0,o=await(await s.initializeClient("HTTP@proxy",{mechOID:s.GSS_MECH_OID_SPNEGO})).step(e||"");if(!o)throw Error("Kerberos client.step() returned no token");return{headers:{"Proxy-Authorization":`Negotiate ${o}`}}}}var ss=j0.default("https-proxy-agent"),Ni=(t)=>{if(t.servername===void 0&&t.host&&!tn.isIP(t.host))return{...t,servername:t.host};return t};class Wi extends jo{constructor(t,n){super(n);if(this.options={path:void 0},this.proxy=typeof t==="string"?new jR(t):t,this.proxyHeaders=n?.headers??{},ss("Creating new HttpsProxyAgent instance: %o",this.proxy.href),n?.negotiate)this.onProxyAuth=K0();else if(n?.onProxyAuth)this.onProxyAuth=n.onProxyAuth;let s=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),r=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...n?po(n,"headers","onProxyAuth","negotiate"):null,host:s,port:r}}async connect(t,n){let{proxy:s}=this;if(!n.host)throw TypeError('No "host" provided');let r;if(s.protocol==="https:")ss("Creating `tls.Socket`: %o",this.connectOpts),r=Ir.connect(Ni(this.connectOpts));else ss("Creating `net.Socket`: %o",this.connectOpts),r=tn.connect(this.connectOpts);let i=typeof this.proxyHeaders==="function"?this.proxyHeaders():{...this.proxyHeaders},e=tn.isIPv6(n.host)?`[${n.host}]`:n.host,f=`CONNECT ${e}:${n.port} HTTP/1.1\r
54
+ `;if(s.username||s.password){let _=`${decodeURIComponent(s.username)}:${decodeURIComponent(s.password)}`;i["Proxy-Authorization"]=`Basic ${Buffer.from(_).toString("base64")}`}if(i.Host=`${e}:${n.port}`,!i["Proxy-Connection"])i["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close";for(let _ of Object.keys(i))f+=`${_}: ${i[_]}\r
55
+ `;let o=ao(r);r.write(`${f}\r
56
+ `);let{connect:c,buffered:h}=await o;if(t.emit("proxyConnect",c),this.emit("proxyConnect",c,t),t.emit("proxy",{proxy:this.proxy.href,socket:r}),c.statusCode===200){if(t.once("socket",V0),n.secureEndpoint)return ss("Upgrading socket connection to TLS"),Ir.connect({...po(Ni(n),"host","path","port"),socket:r});return r}if(c.statusCode===407&&this.onProxyAuth){ss("Got 407 response, invoking onProxyAuth callback"),r.destroy();let _=c.headers["proxy-authenticate"]||"",l=Array.isArray(_)?_[0].split(/\s/)[0]:_.split(/\s/)[0],w=await this.onProxyAuth({response:c,scheme:l});return this._connectWithAuth(t,n,w.headers)}r.destroy();let u=new tn.Socket({writable:!1});return u.readable=!0,t.once("socket",(_)=>{ss("Replaying proxy buffer for failed request"),VR(_.listenerCount("data")>0),_.push(h),_.push(null)}),u}async _connectWithAuth(t,n,s){let{proxy:r}=this,i;if(r.protocol==="https:")i=Ir.connect(Ni(this.connectOpts));else i=tn.connect(this.connectOpts);let e=typeof this.proxyHeaders==="function"?this.proxyHeaders():{...this.proxyHeaders},f=tn.isIPv6(n.host)?`[${n.host}]`:n.host,o=`CONNECT ${f}:${n.port} HTTP/1.1\r
57
+ `;if(r.username||r.password){let u=`${decodeURIComponent(r.username)}:${decodeURIComponent(r.password)}`;e["Proxy-Authorization"]=`Basic ${Buffer.from(u).toString("base64")}`}if(Object.assign(e,s),e.Host=`${f}:${n.port}`,!e["Proxy-Connection"])e["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close";for(let u of Object.keys(e))o+=`${u}: ${e[u]}\r
58
+ `;let c=ao(i);i.write(`${o}\r
59
+ `);let{connect:h}=await c;if(t.emit("proxyConnect",h),this.emit("proxyConnect",h,t),h.statusCode===200){if(t.once("socket",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(`
60
60
  CREATE TABLE IF NOT EXISTS accounts (
61
61
  id TEXT PRIMARY KEY, email TEXT NOT NULL, auth_method TEXT NOT NULL,
62
62
  region TEXT NOT NULL, oidc_region TEXT, client_id TEXT, client_secret TEXT,
@@ -79,19 +79,19 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
79
79
  WHERE NOT EXISTS (
80
80
  SELECT 1 FROM removed_accounts WHERE removed_accounts.id = accounts.id
81
81
  )
82
- `).all().map(Ne)}getById(t){let n=this.db.query(`
82
+ `).all().map(mi)}getById(t){let n=this.db.query(`
83
83
  SELECT accounts.* FROM accounts
84
84
  WHERE accounts.id = ? AND NOT EXISTS (
85
85
  SELECT 1 FROM removed_accounts WHERE removed_accounts.id = accounts.id
86
86
  )
87
- `).get(t);return n===null?void 0:Ne(n)}insertAccount(t){return this.withImmediateTransaction(()=>{let n=this.db.query("SELECT generation FROM accounts WHERE id = ?").get(t.id),s=this.db.query("SELECT last_generation FROM removed_accounts WHERE id = ?").get(t.id),r=Math.max(n?.generation??0,s?.last_generation??0)+1,e=Ko(t,r);return this.db.query(`
87
+ `).get(t);return n===null?void 0:mi(n)}insertAccount(t){return this.withImmediateTransaction(()=>{let n=this.db.query("SELECT generation FROM accounts WHERE id = ?").get(t.id),s=this.db.query("SELECT last_generation FROM removed_accounts WHERE id = ?").get(t.id),r=Math.max(n?.generation??0,s?.last_generation??0)+1,i=nf(t,r);return this.db.query(`
88
88
  INSERT OR REPLACE INTO accounts (
89
89
  id, email, auth_method, region, oidc_region, client_id, client_secret,
90
90
  profile_arn, start_url, refresh_token, access_token, expires_at,
91
91
  rate_limit_reset, is_healthy, unhealthy_reason, recovery_time, fail_count,
92
92
  last_used, used_count, limit_count, last_sync, overage_count, generation
93
93
  ) VALUES (${Array.from({length:23},()=>"?").join(", ")})
94
- `).run(...Vo(e)),this.clearRemovedAccountInternal(t.id),Ne(e)})}updateExistingAccounts(t){return this.withImmediateTransaction(()=>{let n=0,s=this.db.query(`
94
+ `).run(...sf(i)),this.clearRemovedAccountInternal(t.id),mi(i)})}updateExistingAccounts(t){return this.withImmediateTransaction(()=>{let n=0,s=this.db.query(`
95
95
  UPDATE accounts SET
96
96
  email = ?, auth_method = ?, region = ?, oidc_region = ?, client_id = ?,
97
97
  client_secret = ?, profile_arn = ?, start_url = ?, refresh_token = ?,
@@ -102,43 +102,51 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
102
102
  WHERE id = ? AND generation = ? AND NOT EXISTS (
103
103
  SELECT 1 FROM removed_accounts WHERE removed_accounts.id = accounts.id
104
104
  )
105
- `);for(let r of t){let e=Vo(Ko(r,r.generation)),i=e.shift();e.pop(),n+=s.run(...e,i??r.id,r.generation).changes}return n})}removeAccount(t){this.withImmediateTransaction(()=>{let n=this.db.query("SELECT generation FROM accounts WHERE id = ?").get(t),s=this.db.query("SELECT last_generation FROM removed_accounts WHERE id = ?").get(t),r=n?.generation??s?.last_generation??0;this.db.query("DELETE FROM accounts WHERE id = ?").run(t),this.db.query(`
105
+ `);for(let r of t){let i=sf(nf(r,r.generation)),e=i.shift();i.pop(),n+=s.run(...i,e??r.id,r.generation).changes}return n})}removeAccount(t){this.withImmediateTransaction(()=>{let n=this.db.query("SELECT generation FROM accounts WHERE id = ?").get(t),s=this.db.query("SELECT last_generation FROM removed_accounts WHERE id = ?").get(t),r=n?.generation??s?.last_generation??0;this.db.query("DELETE FROM accounts WHERE id = ?").run(t),this.db.query(`
106
106
  INSERT OR REPLACE INTO removed_accounts (id, removed_at, last_generation)
107
107
  VALUES (?, ?, ?)
108
- `).run(t,Date.now(),r)})}clearRemovedAccount(t){this.withImmediateTransaction(()=>this.clearRemovedAccountInternal(t))}close(){this.db.close()}clearRemovedAccountInternal(t){this.db.query("DELETE FROM removed_accounts WHERE id = ?").run(t)}withImmediateTransaction(t){this.db.exec("BEGIN IMMEDIATE");try{let n=t();return this.db.exec("COMMIT"),n}catch(n){throw this.db.exec("ROLLBACK"),n}finally{this.tightenPermissions()}}tightenPermissions(){if(this.path===":memory:")return;for(let t of[this.path,`${this.path}-wal`,`${this.path}-shm`])if(PR(t))FR(t,384)}}function Z(t,n,s,r){let e={message:n,type:s};if(r!==void 0)e.code=r;return new Response(JSON.stringify({error:e}),{status:t,headers:{"Content-Type":"application/json"}})}var Cu="Bearer ";function au(t,n){let s=t.headers.get("Authorization");if(s===null)return{ok:!1,response:Z(401,"Missing Authorization header.","authentication_error","missing_api_key")};if(!s.startsWith(Cu))return{ok:!1,response:Z(401,"Authorization header must use the Bearer scheme.","authentication_error","invalid_api_key")};let r=s.slice(Cu.length);if(!n.includes(r))return{ok:!1,response:Z(401,"Incorrect API key provided.","authentication_error","invalid_api_key")};return{ok:!0}}var Jn=H(kt(),1);var Zr=H(kt(),1);var te=H(kt(),1);var $n=H(kt(),1);var Bt=H(kt(),1);var a=H(Rt(),1);var lr=H(Qn(),1),cd=H(Pn(),1);var Gc=H(_i(),1);var ne=H(Tt(),1);var Ft=H(fs(),1);var V=H(pr(),1);var Y=H(En(),1);var tr=H(Qn(),1);var Zs=H(En(),1);var nA=async(t,n,s)=>{return{operation:Zs.getSmithyContext(n).operation}};function dG(t){return{schemeId:"smithy.api#httpBearerAuth",propertiesExtractor:({profile:n,filepath:s,configFilepath:r,ignoreCache:e},i)=>({identityProperties:{profile:n,filepath:s,configFilepath:r,ignoreCache:e}})}}var sA=(t)=>{let n=[];switch(t.operation){default:n.push(dG(t))}return n},rA=(t)=>{let n=tr.memoizeIdentityProvider(t.token,tr.isIdentityExpired,tr.doesIdentityRequireRefresh);return Object.assign(t,{authSchemePreference:Zs.normalizeProvider(t.authSchemePreference??[]),token:n})};var eA=(t)=>{return Object.assign(t,{useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,defaultSigningName:"amazoncodewhispererstreamingservice"})},iA={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}};var oA={name:"@aws/codewhisperer-streaming-client",description:"@aws/codewhisperer-streaming-client",version:"1.0.45",scripts:{build:"concurrently 'npm:build:cjs' 'npm:build:es' 'npm:build:types'","build:cjs":"tsc -p tsconfig.cjs.json","build:es":"tsc -p tsconfig.es.json","build:types":"tsc -p tsconfig.types.json","build:types:downlevel":"downlevel-dts dist-types dist-types/ts3.4",clean:"premove dist-cjs dist-es dist-types tsconfig.cjs.tsbuildinfo tsconfig.es.tsbuildinfo tsconfig.types.tsbuildinfo",prepack:"npm run clean && npm run build"},main:"./dist-cjs/index.js",types:"./dist-types/index.d.ts",module:"./dist-es/index.js",sideEffects:!1,dependencies:{tslib:"^2.6.2","@aws-crypto/sha256-browser":"5.2.0","@aws-crypto/sha256-js":"5.2.0","@aws-sdk/core":"^3.974.7","@aws-sdk/middleware-host-header":"^3.972.10","@aws-sdk/middleware-logger":"^3.972.10","@aws-sdk/middleware-recursion-detection":"^3.972.11","@aws-sdk/middleware-user-agent":"^3.972.37","@aws-sdk/region-config-resolver":"^3.972.13","@aws-sdk/token-providers":"^3.1040.0","@aws-sdk/types":"^3.973.8","@aws-sdk/util-endpoints":"^3.996.8","@aws-sdk/util-user-agent-browser":"^3.972.10","@aws-sdk/util-user-agent-node":"^3.973.23","@smithy/config-resolver":"^4.4.17","@smithy/core":"^3.23.17","@smithy/eventstream-serde-browser":"^4.2.14","@smithy/eventstream-serde-config-resolver":"^4.3.14","@smithy/eventstream-serde-node":"^4.2.14","@smithy/fetch-http-handler":"^5.3.17","@smithy/hash-node":"^4.2.14","@smithy/invalid-dependency":"^4.2.14","@smithy/middleware-content-length":"^4.2.14","@smithy/middleware-endpoint":"^4.4.32","@smithy/middleware-retry":"^4.5.7","@smithy/middleware-serde":"^4.2.20","@smithy/middleware-stack":"^4.2.14","@smithy/node-config-provider":"^4.3.14","@smithy/node-http-handler":"^4.6.1","@smithy/protocol-http":"^5.3.14","@smithy/smithy-client":"^4.12.13","@smithy/types":"^4.14.1","@smithy/url-parser":"^4.2.14","@smithy/util-base64":"^4.3.2","@smithy/util-body-length-browser":"^4.2.2","@smithy/util-body-length-node":"^4.2.3","@smithy/util-defaults-mode-browser":"^4.3.49","@smithy/util-defaults-mode-node":"^4.2.54","@smithy/util-endpoints":"^3.4.2","@smithy/util-middleware":"^4.2.14","@smithy/util-retry":"^4.3.6","@smithy/util-utf8":"^4.2.2"},devDependencies:{"@tsconfig/node20":"20.1.8",concurrently:"7.0.0","downlevel-dts":"0.10.1",premove:"4.0.0",typescript:"~5.8.3","@types/node":"^20.14.8"},engines:{node:">=20.0.0"},typesVersions:{"<4.5":{"dist-types/*":["dist-types/ts3.4/*"]}},files:["dist-*/**"],browser:{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.browser"},"react-native":{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.native"},license:"Apache-2.0"};var nd=H(kt(),1),sd=H(zc(),1);var cr=H(Rt(),1);var $t=H(Rt(),1);var qA=300000,sr="To refresh this SSO session run 'aws sso login' with the corresponding profile.";var b1=async(t,n={},s)=>{let{SSOOIDCClient:r}=await Promise.resolve().then(() => H(Ih(),1)),e=(f)=>n.clientConfig?.[f]??n.parentClientConfig?.[f]??s?.[f];return new r(Object.assign({},n.clientConfig??{},{region:t??n.clientConfig?.region,logger:e("logger"),userAgentAppId:e("userAgentAppId")}))};var T1=async(t,n,s={},r)=>{let{CreateTokenCommand:e}=await Promise.resolve().then(() => H(Ih(),1));return(await b1(n,s,r)).send(new e({clientId:t.clientId,clientSecret:t.clientSecret,refreshToken:t.refreshToken,grantType:"refresh_token"}))};var S1=H(Rt(),1);var Oh=(t)=>{if(t.expiration&&t.expiration.getTime()<Date.now())throw new S1.TokenProviderError(`Token is expired. ${sr}`,!1)};var $1=H(Rt(),1);var Xn=(t,n,s=!1)=>{if(typeof n>"u")throw new $1.TokenProviderError(`Value not present for '${t}' in SSO Token${s?". Cannot refresh":""}. ${sr}`,!1)};var U1=H(Rt(),1);import{promises as JH}from"fs";var{writeFile:zH}=JH,L1=(t,n)=>{let s=U1.getSSOTokenFilepath(t),r=JSON.stringify(n,null,2);return zH(s,r)};var I1=new Date(0),O1=(t={})=>async({callerClientConfig:n}={})=>{t.logger?.debug("@aws-sdk/token-providers - fromSso");let s=await $t.parseKnownFiles(t),r=$t.getProfileName({profile:t.profile??n?.profile}),e=s[r];if(!e)throw new $t.TokenProviderError(`Profile '${r}' could not be found in shared credentials file.`,!1);else if(!e.sso_session)throw new $t.TokenProviderError(`Profile '${r}' is missing required property 'sso_session'.`);let i=e.sso_session,o=(await $t.loadSsoSessionData(t))[i];if(!o)throw new $t.TokenProviderError(`Sso session '${i}' could not be found in shared credentials file.`,!1);for(let A of["sso_start_url","sso_region"])if(!o[A])throw new $t.TokenProviderError(`Sso session '${i}' is missing required property '${A}'.`,!1);let{sso_start_url:c,sso_region:h}=o,u;try{u=await $t.getSSOTokenFromFile(i)}catch(A){throw new $t.TokenProviderError(`The SSO session token associated with profile=${r} was not found or is invalid. ${sr}`,!1)}Xn("accessToken",u.accessToken),Xn("expiresAt",u.expiresAt);let{accessToken:l,expiresAt:_}=u,w={token:l,expiration:new Date(_)};if(w.expiration.getTime()-Date.now()>qA)return w;if(Date.now()-I1.getTime()<30000)return Oh(w),w;Xn("clientId",u.clientId,!0),Xn("clientSecret",u.clientSecret,!0),Xn("refreshToken",u.refreshToken,!0);try{I1.setTime(Date.now());let A=await T1(u,h,t,n);Xn("accessToken",A.accessToken),Xn("expiresIn",A.expiresIn);let M=new Date(Date.now()+A.expiresIn*1000);try{await L1(i,{...u,accessToken:A.accessToken,expiresAt:M.toISOString(),refreshToken:A.refreshToken})}catch(d){}return{token:A.accessToken,expiration:M}}catch(A){return Oh(w),w}};var yh=(t={})=>cr.memoize(cr.chain(O1(t),async()=>{throw new cr.TokenProviderError("Could not load token from any providers",!1)}),(n)=>n.expiration!==void 0&&n.expiration.getTime()-Date.now()<300000,(n)=>n.expiration!==void 0);var un=H(kt(),1);var rd=H(Qn(),1);var ro=H(_i(),1);var Gh=H(bt(),1);var Un=H(Rt(),1);var go=H(Ni(),1);var Bh=H(bt(),1);var mh=H(Rt(),1);var ot=H(pr(),1);var v1=H(bh(),1),Z1=H(Qn(),1);var Fh=H(Tt(),1);var hr=H(bt(),1);var ds=H(bt(),1);var Mt=H(fs(),1);var le="ref",gs=-1,eo=!0,y1="isSet",F1="PartitionResult",io="booleanEquals",Ph="getAttr",G1={[le]:"Endpoint"},Hh={[le]:F1},ur={},B1=[{[le]:"Region"}],m1={conditions:[[y1,[G1]],[y1,B1],["aws.partition",B1,F1],[io,[{[le]:"UseFIPS"},eo]],[io,[{[le]:"UseDualStack"},eo]],[io,[{fn:Ph,argv:[Hh,"supportsDualStack"]},eo]],[io,[{fn:Ph,argv:[Hh,"supportsFIPS"]},eo]],["stringEquals",[{fn:Ph,argv:[Hh,"name"]},"aws-us-gov"]]],results:[[gs],[gs,"Invalid Configuration: FIPS and custom endpoint are not supported"],[gs,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[G1,ur],["https://amazoncodewhispererstreamingservice-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",ur],[gs,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://amazoncodewhispererstreamingservice.{Region}.amazonaws.com",ur],["https://amazoncodewhispererstreamingservice-fips.{Region}.{PartitionResult#dnsSuffix}",ur],[gs,"FIPS is enabled but this partition does not support FIPS"],["https://amazoncodewhispererstreamingservice.{Region}.{PartitionResult#dualStackDnsSuffix}",ur],[gs,"DualStack is enabled but this partition does not support DualStack"],["https://amazoncodewhispererstreamingservice.{Region}.{PartitionResult#dnsSuffix}",ur],[gs,"Invalid Configuration: Missing Region"]]},kH=2,Ut=1e8,XH=new Int32Array([-1,1,-1,0,13,3,1,4,Ut+12,2,5,Ut+12,3,8,6,4,7,Ut+11,5,Ut+9,Ut+10,4,11,9,6,10,Ut+8,7,Ut+6,Ut+7,5,12,Ut+5,6,Ut+4,Ut+5,3,Ut+1,14,4,Ut+2,Ut+3]),P1=Mt.BinaryDecisionDiagram.from(XH,kH,m1.conditions,m1.results);var qH=new Mt.EndpointCache({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),H1=(t,n={})=>{return qH.get(t,()=>Mt.decideEndpoint(P1,{endpointParams:t,logger:n.logger}))};Mt.customEndpointFunctions.aws=Bt.awsEndpointFunctions;var Wh=H(Pn(),1);class Lt extends Y.ServiceException{constructor(t){super(t);Object.setPrototypeOf(this,Lt.prototype)}}class oo extends Lt{name="AccessDeniedException";$fault="client";reason;constructor(t){super({name:"AccessDeniedException",$fault:"client",...t});Object.setPrototypeOf(this,oo.prototype),this.reason=t.reason}}class fo extends Lt{name="ConflictException";$fault="client";reason;constructor(t){super({name:"ConflictException",$fault:"client",...t});Object.setPrototypeOf(this,fo.prototype),this.reason=t.reason}}class co extends Lt{name="InternalServerException";$fault="server";$retryable={};reason;constructor(t){super({name:"InternalServerException",$fault:"server",...t});Object.setPrototypeOf(this,co.prototype),this.reason=t.reason}}class ho extends Lt{name="ThrottlingException";$fault="client";$retryable={throttling:!0};reason;constructor(t){super({name:"ThrottlingException",$fault:"client",...t});Object.setPrototypeOf(this,ho.prototype),this.reason=t.reason}}class uo extends Lt{name="ValidationException";$fault="client";reason;constructor(t){super({name:"ValidationException",$fault:"client",...t});Object.setPrototypeOf(this,uo.prototype),this.reason=t.reason}}class lo extends Lt{name="ResourceNotFoundException";$fault="client";constructor(t){super({name:"ResourceNotFoundException",$fault:"client",...t});Object.setPrototypeOf(this,lo.prototype)}}class _o extends Lt{name="ServiceUnavailableException";$fault="server";constructor(t){super({name:"ServiceUnavailableException",$fault:"server",...t});Object.setPrototypeOf(this,_o.prototype)}}class wo extends Lt{name="ServiceQuotaExceededException";$fault="client";reason;constructor(t){super({name:"ServiceQuotaExceededException",$fault:"client",...t});Object.setPrototypeOf(this,wo.prototype),this.reason=t.reason}}class Ao extends Lt{name="DryRunOperationException";$fault="client";responseCode;constructor(t){super({name:"DryRunOperationException",$fault:"client",...t});Object.setPrototypeOf(this,Ao.prototype),this.responseCode=t.responseCode}}var N1=Wh.TypeRegistry.for("smithy.ts.sdk.synthetic.com.amazon.aws.codewhisperer.streaming"),CH=[-3,"smithy.ts.sdk.synthetic.com.amazon.aws.codewhisperer.streaming","CodeWhispererStreamingServiceException",0,[],[]];N1.registerError(CH,Lt);var ln=Wh.TypeRegistry.for("com.amazon.aws.codewhisperer"),aH=[-3,"com.amazon.aws.codewhisperer","AccessDeniedException",{["error"]:"client",["httpError"]:403},["message","reason"],[0,0],1];ln.registerError(aH,oo);var KH=[-3,"com.amazon.aws.codewhisperer","ConflictException",{["error"]:"client",["httpError"]:409},["message","reason"],[0,0],1];ln.registerError(KH,fo);var VH=[-3,"com.amazon.aws.codewhisperer","DryRunOperationException",{["error"]:"client"},["message","responseCode"],[0,[1,32]]];ln.registerError(VH,Ao);var D1=[-3,"com.amazon.aws.codewhisperer","InternalServerException",{["error"]:"server",["httpError"]:500},["message","reason"],[0,0],1];ln.registerError(D1,co);var jH=[-3,"com.amazon.aws.codewhisperer","ResourceNotFoundException",{["error"]:"client",["httpError"]:404},["message"],[0],1];ln.registerError(jH,lo);var pH=[-3,"com.amazon.aws.codewhisperer","ServiceQuotaExceededException",{["error"]:"client",["httpError"]:402},["message","reason"],[0,0],1];ln.registerError(pH,wo);var vH=[-3,"com.amazon.aws.codewhisperer","ServiceUnavailableException",{["error"]:"server",["httpError"]:503},["message"],[0],1];ln.registerError(vH,_o);var ZH=[-3,"com.amazon.aws.codewhisperer","ThrottlingException",{["error"]:"client",["httpError"]:429},["message","reason"],[0,0],1];ln.registerError(ZH,ho);var tN=[-3,"com.amazon.aws.codewhisperer","ValidationException",{["error"]:"client",["httpError"]:400},["message","reason"],[0,0],1];ln.registerError(tN,uo);var W1=[N1,ln];var Yh=[0,"com.amazon.aws.codewhisperer","SensitiveDocument",8,15],B=[0,"com.amazon.aws.codewhisperer","SensitiveString",8,0],nN=[0,"com.amazon.aws.codewhisperer","ToolDescription",8,0],Mo=[0,"com.amazon.aws.codewhisperer","ToolName",8,0],q=[0,"com.amazon.aws.q","SensitiveString",8,0],sN=[3,"com.amazon.aws.codewhisperer","AdditionalContentEntry",0,["name","description","innerContext"],[[()=>B,0],[()=>B,0],[()=>B,0]],2],rN=[3,"com.amazon.aws.codewhisperer","AppStudioState",0,["namespace","propertyName","propertyContext","propertyValue"],[[()=>B,0],[()=>B,0],[()=>B,0],[()=>B,0]],3],eN=[3,"com.amazon.aws.codewhisperer","AssistantResponseEvent",0,["content","modelId"],[[()=>B,0],0],1],iN=[3,"com.amazon.aws.codewhisperer","AssistantResponseMessage",0,["content","messageId","supplementaryWebLinks","references","followupPrompt","toolUses","cachePoint","reasoningContent"],[[()=>B,0],0,[()=>V1,0],()=>K1,[()=>Y1,0],[()=>YD,0],()=>xh,[()=>cW,0]],1];var xh=[3,"com.amazon.aws.codewhisperer","CachePoint",0,["type"],[0],1],oN=[3,"com.amazon.aws.codewhisperer","CitationEvent",0,["target","citationLink","citationText"],[()=>nW,[()=>B,0],[()=>B,0]],2],fN=[3,"com.amazon.aws.codewhisperer","ClientCacheConfig",0,["useClientCachingOnly"],[2]],cN=[3,"com.amazon.aws.codewhisperer","CodeDescription",0,["href"],[[()=>B,0]],1],hN=[3,"com.amazon.aws.codewhisperer","CodeEvent",0,["content"],[[()=>B,0]],1],uN=[3,"com.amazon.aws.codewhisperer","CodeReferenceEvent",0,["references"],[()=>K1]],lN=[3,"com.amazon.aws.codewhisperer","ConsoleState",0,["region","consoleUrl","serviceId","serviceConsolePage","serviceSubconsolePage","taskName","uxErrorMessage"],[0,[()=>B,0],0,0,0,[()=>B,0],[()=>B,0]]],_N=[3,"com.amazon.aws.codewhisperer","ContextUsageEvent",0,["contextUsagePercentage"],[1]],wN=[3,"com.amazon.aws.codewhisperer","ConversationState",0,["currentMessage","chatTriggerType","conversationId","workspaceId","history","customizationArn","agentContinuationId","agentTaskType"],[[()=>j1,0],0,0,0,[()=>OD,0],0,0,0],2],AN=[3,"com.amazon.aws.codewhisperer","DiagnosticLocation",0,["uri","range"],[[()=>B,0],()=>Qh],2],MN=[3,"com.amazon.aws.codewhisperer","DiagnosticRelatedInformation",0,["location","message"],[[()=>AN,0],[()=>B,0]],2],dN=[3,"com.amazon.aws.codewhisperer","DocumentBlock",0,["name","format","source"],[0,0,[()=>iW,0]],3],gN=[3,"com.amazon.aws.codewhisperer","DocumentCitationEvent",0,["source","title","location","sourceContent"],[[()=>B,0],[()=>B,0],[()=>eW,0],[()=>BD,0]]],EN=[3,"com.amazon.aws.codewhisperer","DocumentCitationSearchResultSpan",0,["searchResultIndex","start","end"],[1,1,1]],RN=[3,"com.amazon.aws.codewhisperer","DocumentCitationSourceContent",0,["text"],[[()=>B,0]]],Nh=[3,"com.amazon.aws.codewhisperer","DocumentCitationSpan",0,["documentIndex","start","end"],[1,1,1]],bN=[3,"com.amazon.aws.codewhisperer","DocumentCitationWebLocation",0,["url","domain"],[[()=>B,0],[()=>B,0]]],TN=[3,"com.amazon.aws.codewhisperer","DocumentSymbol",0,["name","type","source"],[0,0,0],2],SN=[3,"com.amazon.aws.codewhisperer","DryRunSucceedEvent",0,[],[]],$N=[3,"com.amazon.aws.codewhisperer","EditorState",0,["document","cursorState","relevantDocuments","useRelevantDocuments","workspaceFolders"],[[()=>J1,0],()=>sW,[()=>PD,0],2,[()=>xD,0]]],UN=[3,"com.amazon.aws.codewhisperer","EnvironmentVariable",0,["key","value"],[[()=>B,0],[()=>B,0]]],LN=[3,"com.amazon.aws.codewhisperer","EnvState",0,["operatingSystem","currentWorkingDirectory","environmentVariables","timezoneOffset"],[0,[()=>B,0],[()=>mD,0],1]],Y1=[3,"com.amazon.aws.codewhisperer","FollowupPrompt",0,["content","userIntent"],[[()=>B,0],0],1],IN=[3,"com.amazon.aws.codewhisperer","FollowupPromptEvent",0,["followupPrompt"],[[()=>Y1,0]]],ON=[3,"com.amazon.aws.codewhisperer","GitState",0,["status"],[[()=>B,0]]],yN=[3,"com.amazon.aws.codewhisperer","ImageBlock",0,["format","source"],[0,[()=>oW,0]],2],GN=[3,"com.amazon.aws.codewhisperer","IntentsEvent",0,["intents"],[[()=>vD,0]]],BN=[3,"com.amazon.aws.codewhisperer","InvalidStateEvent",0,["reason","message"],[0,0],2],mN=[3,"com.amazon.aws.codewhisperer","MessageMetadataEvent",0,["conversationId","utteranceId"],[0,0]],FN=[3,"com.amazon.aws.codewhisperer","MetadataEvent",0,["tokenUsage"],[()=>vN]],PN=[3,"com.amazon.aws.codewhisperer","MeteringEvent",0,["usage","unit","unitPlural"],[1,0,0]],Dh=[3,"com.amazon.aws.codewhisperer","Position",0,["line","character"],[1,1],2],x1=[3,"com.amazon.aws.codewhisperer","ProgrammingLanguage",0,["languageName"],[0],1],Qh=[3,"com.amazon.aws.codewhisperer","Range",0,["start","end"],[()=>Dh,()=>Dh],2],HN=[3,"com.amazon.aws.codewhisperer","ReasoningContentEvent",8,["text","redactedContent","signature"],[[()=>B,0],21,[()=>B,0]]],NN=[3,"com.amazon.aws.codewhisperer","ReasoningText",8,["text","signature"],[[()=>B,0],[()=>B,0]],1],DN=[3,"com.amazon.aws.codewhisperer","Reference",0,["licenseName","repository","url","recommendationContentSpan"],[0,0,0,()=>Q1]],WN=[3,"com.amazon.aws.codewhisperer","RelevantTextDocument",0,["relativeFilePath","programmingLanguage","text","documentSymbols","type"],[[()=>B,0],()=>x1,[()=>B,0],()=>a1,0],1],YN=[3,"com.amazon.aws.codewhisperer","RuntimeDiagnostic",0,["source","severity","message"],[[()=>B,0],0,[()=>B,0]],3],xN=[3,"com.amazon.aws.codewhisperer","ShellHistoryEntry",0,["command","directory","exitCode","stdout","stderr"],[[()=>B,0],[()=>B,0],1,[()=>B,0],[()=>B,0]],1],QN=[3,"com.amazon.aws.codewhisperer","ShellState",0,["shellName","shellHistory"],[0,[()=>HD,0]],1],Q1=[3,"com.amazon.aws.codewhisperer","Span",0,["start","end"],[1,1]],JN=[3,"com.amazon.aws.codewhisperer","SupplementaryWebLink",0,["url","title","snippet"],[[()=>B,0],[()=>B,0],[()=>B,0]],2],zN=[3,"com.amazon.aws.codewhisperer","SupplementaryWebLinksEvent",0,["supplementaryWebLinks"],[[()=>V1,0]]],J1=[3,"com.amazon.aws.codewhisperer","TextDocument",0,["relativeFilePath","programmingLanguage","text","documentSymbols"],[[()=>B,0],()=>x1,[()=>B,0],()=>a1],1],kN=[3,"com.amazon.aws.codewhisperer","TextDocumentDiagnostic",0,["document","range","source","severity","message","code","codeDescription","tags","relatedInformation","data"],[[()=>J1,0],()=>Qh,[()=>B,0],0,[()=>B,0],[()=>B,0],[()=>cN,0],64,[()=>yD,0],[()=>B,0]],5],XN=[3,"com.amazon.aws.codewhisperer","ToolInputSchema",0,["json"],[[()=>Yh,0]]],z1=[3,"com.amazon.aws.codewhisperer","ToolResult",0,["toolUseId","content","status","toolName"],[0,[()=>ND,0],0,[()=>Mo,0]],2],qN=[3,"com.amazon.aws.codewhisperer","ToolResultEvent",0,["toolResult"],[[()=>z1,0]]],CN=[3,"com.amazon.aws.codewhisperer","ToolSpecification",0,["inputSchema","name","description"],[[()=>XN,0],[()=>Mo,0],[()=>nN,0]],2],aN=[3,"com.amazon.aws.codewhisperer","ToolUse",0,["toolUseId","name","input"],[0,[()=>Mo,0],[()=>Yh,0]],3],KN=[3,"com.amazon.aws.codewhisperer","ToolUseEvent",0,["toolUseId","name","input","stop"],[0,[()=>Mo,0],[()=>B,0],2],2];var VN=[3,"com.amazon.aws.codewhisperer","UserInputMessage",0,["content","userInputMessageContext","userIntent","origin","images","documents","modelId","cachePoint","clientCacheConfig"],[[()=>B,0],[()=>jN,0],0,0,[()=>FD,0],[()=>GD,0],0,()=>xh,()=>fN],1],jN=[3,"com.amazon.aws.codewhisperer","UserInputMessageContext",0,["editorState","shellState","gitState","envState","appStudioContext","diagnostic","consoleState","userSettings","additionalContext","toolResults","tools"],[[()=>$N,0],[()=>QN,0],[()=>ON,0],[()=>LN,0],[()=>rN,0],[()=>rW,0],[()=>lN,0],()=>pN,[()=>ID,0],[()=>DD,0],[()=>WD,0]]],pN=[3,"com.amazon.aws.codewhisperer","UserSettings",0,["hasConsentedToCrossRegionCalls"],[2]];var vN=[3,"com.amazon.aws.codewhisperer.internal","TokenUsage",0,["uncachedInputTokens","outputTokens","totalTokens","cacheReadInputTokens","cacheWriteInputTokens","contextUsagePercentage","normalizedTokenUsage"],[1,1,1,1,1,1,1],3];var ZN=[3,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponseRequest",0,["conversationState","profileArn","agentMode","additionalModelRequestFields"],[[()=>wN,0],0,[0,{["httpHeader"]:"x-amzn-kiro-agent-mode"}],15],1],tD=[3,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponseResponse",0,["conversationId","generateAssistantResponseResponse"],[[0,{["httpHeader"]:"x-amzn-codewhisperer-conversation-id"}],[()=>tW,16]],2];var nD=[3,"com.amazon.aws.q","InteractionComponentsEvent",0,["interactionComponentEntries"],[[()=>kD,0]],1],Jh=[3,"com.amazon.aws.q.interactioncomponents","Action",0,["webLink","moduleLink"],[[()=>LD,0],[()=>lD,0]]],zh=[3,"com.amazon.aws.q.interactioncomponents","Alert",0,["type","content"],[0,[()=>QD,0]],2],sD=[3,"com.amazon.aws.q.interactioncomponents","AlertComponent",0,["text"],[[()=>_e,0]]],rD=[3,"com.amazon.aws.q.interactioncomponents","Clarification",0,["questions","dismissible"],[[()=>zD,0],2],1],eD=[3,"com.amazon.aws.q.interactioncomponents","ClarificationAnswerOption",0,["label","value"],[[()=>q,0],[()=>q,0]],2],iD=[3,"com.amazon.aws.q.interactioncomponents","ClarificationQuestion",0,["question","options","allowCustom","skippable"],[[()=>q,0],[()=>JD,0],2,2],2],oD=[3,"com.amazon.aws.q.interactioncomponents","CloudWatchTroubleshootingLink",0,["label","investigationPayload","defaultText"],[[()=>q,0],[()=>q,0],[()=>q,0]],2],k1=[3,"com.amazon.aws.q.interactioncomponents","InfrastructureUpdate",0,["transition"],[[()=>fD,0]]],fD=[3,"com.amazon.aws.q.interactioncomponents","InfrastructureUpdateTransition",0,["currentState","nextState"],[[()=>q,0],[()=>q,0]],2],cD=[3,"com.amazon.aws.q.interactioncomponents","InlineArtifact",0,["dsl","summary","title","artifactLabel"],[[()=>q,0],[()=>q,0],[()=>q,0],[()=>q,0]],4],hD=[3,"com.amazon.aws.q.interactioncomponents","InteractionComponent",0,["text","alert","infrastructureUpdate","progress","step","taskDetails","taskReference","suggestions","section","resource","resourceList","action","clarification","inlineArtifact"],[[()=>_e,0],[()=>zh,0],[()=>k1,0],[()=>X1,0],[()=>C1,0],[()=>SD,0],()=>UD,[()=>gD,0],[()=>wD,0],[()=>kh,0],[()=>q1,0],[()=>Jh,0],[()=>rD,0],[()=>cD,0]]],uD=[3,"com.amazon.aws.q.interactioncomponents","InteractionComponentEntry",0,["interactionComponent","interactionComponentId"],[[()=>hD,0],0],1],lD=[3,"com.amazon.aws.q.interactioncomponents","ModuleLink",0,["cloudWatchTroubleshootingLink"],[[()=>oD,0]]],X1=[3,"com.amazon.aws.q.interactioncomponents","Progress",0,["content"],[[()=>XD,0]],1],_D=[3,"com.amazon.aws.q.interactioncomponents","ProgressComponent",0,["step"],[[()=>C1,0]]],kh=[3,"com.amazon.aws.q.interactioncomponents","Resource",0,["title","link","description","type","ARN","resourceJsonString"],[[()=>q,0],[()=>q,0],[()=>q,0],[()=>q,0],[()=>q,0],[()=>q,0]],6],q1=[3,"com.amazon.aws.q.interactioncomponents","ResourceList",0,["items","action"],[[()=>qD,0],[()=>Jh,0]],1],wD=[3,"com.amazon.aws.q.interactioncomponents","Section",0,["title","content","action"],[[()=>q,0],[()=>CD,0],[()=>Jh,0]],2],AD=[3,"com.amazon.aws.q.interactioncomponents","SectionComponent",0,["text","alert","resource","resourceList"],[[()=>_e,0],[()=>zh,0],[()=>kh,0],[()=>q1,0]]],C1=[3,"com.amazon.aws.q.interactioncomponents","Step",0,["id","state","label","content"],[1,0,[()=>q,0],[()=>aD,0]],3],MD=[3,"com.amazon.aws.q.interactioncomponents","StepComponent",0,["text"],[[()=>_e,0]]],dD=[3,"com.amazon.aws.q.interactioncomponents","Suggestion",0,["value"],[[()=>q,0]],1],gD=[3,"com.amazon.aws.q.interactioncomponents","Suggestions",0,["items"],[[()=>KD,0]],1],ED=[3,"com.amazon.aws.q.interactioncomponents","TaskAction",0,["label","payload","note","primary","disabled","confirmation"],[[()=>q,0],[()=>ZD,0],[()=>bD,0],2,2,[()=>RD,0]],2],RD=[3,"com.amazon.aws.q.interactioncomponents","TaskActionConfirmation",0,["content"],[[()=>q,0]]],bD=[3,"com.amazon.aws.q.interactioncomponents","TaskActionNote",0,["content","type"],[[()=>q,0],0],1],TD=[3,"com.amazon.aws.q.interactioncomponents","TaskComponent",0,["text","infrastructureUpdate","alert","progress"],[[()=>_e,0],[()=>k1,0],[()=>zh,0],[()=>X1,0]]],SD=[3,"com.amazon.aws.q.interactioncomponents","TaskDetails",0,["overview","content","actions"],[[()=>$D,0],[()=>jD,0],[()=>VD,0]],2],$D=[3,"com.amazon.aws.q.interactioncomponents","TaskOverview",0,["label","description"],[[()=>q,0],[()=>q,0]],2],UD=[3,"com.amazon.aws.q.interactioncomponents","TaskReference",0,["taskId"],[0],1],_e=[3,"com.amazon.aws.q.interactioncomponents","Text",0,["content"],[[()=>q,0]],1],LD=[3,"com.amazon.aws.q.interactioncomponents","WebLink",0,["label","url"],[[()=>q,0],[()=>q,0]],2];var ID=[1,"com.amazon.aws.codewhisperer","AdditionalContentList",0,[()=>sN,0]],OD=[1,"com.amazon.aws.codewhisperer","ChatHistory",0,[()=>j1,0]],yD=[1,"com.amazon.aws.codewhisperer","DiagnosticRelatedInformationList",0,[()=>MN,0]];var GD=[1,"com.amazon.aws.codewhisperer","DocumentBlocks",0,[()=>dN,0]],BD=[1,"com.amazon.aws.codewhisperer","DocumentCitationSourceContents",0,[()=>RN,0]],a1=[1,"com.amazon.aws.codewhisperer","DocumentSymbols",0,()=>TN],mD=[1,"com.amazon.aws.codewhisperer","EnvironmentVariables",0,[()=>UN,0]],FD=[1,"com.amazon.aws.codewhisperer","ImageBlocks",0,[()=>yN,0]],K1=[1,"com.amazon.aws.codewhisperer","References",0,()=>DN],PD=[1,"com.amazon.aws.codewhisperer","RelevantDocumentList",0,[()=>WN,0]],HD=[1,"com.amazon.aws.codewhisperer","ShellHistory",0,[()=>xN,0]],V1=[1,"com.amazon.aws.codewhisperer","SupplementaryWebLinks",0,[()=>JN,0]],ND=[1,"com.amazon.aws.codewhisperer","ToolResultContent",0,[()=>uW,0]],DD=[1,"com.amazon.aws.codewhisperer","ToolResults",0,[()=>z1,0]],WD=[1,"com.amazon.aws.codewhisperer","Tools",0,[()=>hW,0]],YD=[1,"com.amazon.aws.codewhisperer","ToolUses",0,[()=>aN,0]],xD=[1,"com.amazon.aws.codewhisperer","WorkspaceFolderList",0,[()=>B,0]],QD=[1,"com.amazon.aws.q.interactioncomponents","AlertComponentList",0,[()=>sD,0]],JD=[1,"com.amazon.aws.q.interactioncomponents","ClarificationAnswerOptionsList",0,[()=>eD,0]],zD=[1,"com.amazon.aws.q.interactioncomponents","ClarificationQuestionList",0,[()=>iD,0]],kD=[1,"com.amazon.aws.q.interactioncomponents","InteractionComponentEntryList",0,[()=>uD,0]],XD=[1,"com.amazon.aws.q.interactioncomponents","ProgressComponentList",0,[()=>_D,0]],qD=[1,"com.amazon.aws.q.interactioncomponents","Resources",0,[()=>kh,0]],CD=[1,"com.amazon.aws.q.interactioncomponents","SectionComponentList",0,[()=>AD,0]],aD=[1,"com.amazon.aws.q.interactioncomponents","StepComponentList",0,[()=>MD,0]],KD=[1,"com.amazon.aws.q.interactioncomponents","SuggestionList",0,[()=>dD,0]],VD=[1,"com.amazon.aws.q.interactioncomponents","TaskActionList",0,[()=>ED,0]],jD=[1,"com.amazon.aws.q.interactioncomponents","TaskComponentList",0,[()=>TD,0]],pD=[2,"com.amazon.aws.codewhisperer","IntentData",8,0,()=>fW],vD=[2,"com.amazon.aws.codewhisperer","IntentMap",0,[0,0],[()=>pD,0]],ZD=[2,"com.amazon.aws.q.interactioncomponents","TaskActionPayload",0,[0,0],[()=>q,0]],j1=[4,"com.amazon.aws.codewhisperer","ChatMessage",0,["userInputMessage","assistantResponseMessage"],[[()=>VN,0],[()=>iN,0]]],tW=[4,"com.amazon.aws.codewhisperer","ChatResponseStream",{["streaming"]:1},["messageMetadataEvent","assistantResponseEvent","reasoningContentEvent","dryRunSucceedEvent","codeReferenceEvent","supplementaryWebLinksEvent","followupPromptEvent","codeEvent","intentsEvent","interactionComponentsEvent","toolUseEvent","toolResultEvent","metadataEvent","meteringEvent","contextUsageEvent","citationEvent","documentCitationEvent","invalidStateEvent","error"],[()=>mN,[()=>eN,0],[()=>HN,0],()=>SN,()=>uN,[()=>zN,0],[()=>IN,0],[()=>hN,0],[()=>GN,0],[()=>nD,0],[()=>KN,0],[()=>qN,0],()=>FN,()=>PN,()=>_N,[()=>oN,0],[()=>gN,0],()=>BN,[()=>D1,0]]],nW=[4,"com.amazon.aws.codewhisperer","CitationTarget",0,["location","range"],[1,()=>Q1]],sW=[4,"com.amazon.aws.codewhisperer","CursorState",0,["position","range"],[()=>Dh,()=>Qh]],rW=[4,"com.amazon.aws.codewhisperer","Diagnostic",0,["textDocumentDiagnostic","runtimeDiagnostic"],[[()=>kN,0],[()=>YN,0]]],eW=[4,"com.amazon.aws.codewhisperer","DocumentCitationLocation",0,["documentPage","documentChar","documentChunk","searchResult","web"],[()=>Nh,()=>Nh,()=>Nh,()=>EN,[()=>bN,0]]],iW=[4,"com.amazon.aws.codewhisperer","DocumentSource",8,["bytes"],[21]];var oW=[4,"com.amazon.aws.codewhisperer","ImageSource",8,["bytes"],[21]],fW=[4,"com.amazon.aws.codewhisperer","IntentDataType",0,["string"],[0]],cW=[4,"com.amazon.aws.codewhisperer","ReasoningContent",8,["reasoningText","redactedContent"],[[()=>NN,0],21]];var hW=[4,"com.amazon.aws.codewhisperer","Tool",0,["toolSpecification","cachePoint"],[[()=>CN,0],()=>xh]],uW=[4,"com.amazon.aws.codewhisperer","ToolResultContentBlock",0,["text","json"],[[()=>B,0],[()=>Yh,0]]];var p1=[9,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponse",{["http"]:["POST","/generateAssistantResponse",200]},()=>ZN,()=>tD];var td=(t)=>{return{apiVersion:"2023-11-27",base64Decoder:t?.base64Decoder??hr.fromBase64,base64Encoder:t?.base64Encoder??hr.toBase64,disableHostPrefix:t?.disableHostPrefix??!1,endpointProvider:t?.endpointProvider??H1,extensions:t?.extensions??[],httpAuthSchemeProvider:t?.httpAuthSchemeProvider??sA,httpAuthSchemes:t?.httpAuthSchemes??[{schemeId:"smithy.api#httpBearerAuth",identityProvider:(n)=>n.getIdentityProvider("smithy.api#httpBearerAuth"),signer:new Z1.HttpBearerAuthSigner}],logger:t?.logger??new Y.NoOpLogger,protocol:t?.protocol??v1.AwsRestJsonProtocol,protocolSettings:t?.protocolSettings??{defaultNamespace:"com.amazon.aws.codewhisperer.streaming",errorTypeRegistries:W1,version:"2023-11-27",serviceTarget:"AmazonCodeWhispererStreamingService"},serviceId:t?.serviceId??"CodeWhispererStreaming",urlParser:t?.urlParser??Fh.parseUrl,utf8Decoder:t?.utf8Decoder??ds.fromUtf8,utf8Encoder:t?.utf8Encoder??ds.toUtf8}};var ed=(t)=>{Y.emitWarningIfUnsupportedVersion(process.version);let n=mh.resolveDefaultsModeConfig(t),s=()=>n().then(Y.loadConfigsForDefaultMode),r=td(t);nd.emitWarningIfUnsupportedVersion(process.version);let e={profile:t?.profile,logger:r.logger};return{...r,...t,runtime:"node",defaultsMode:n,authSchemePreference:t?.authSchemePreference??Un.loadConfig(sd.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS,e),bodyLengthChecker:t?.bodyLengthChecker??Bh.calculateBodyLength,defaultUserAgentProvider:t?.defaultUserAgentProvider??un.createDefaultUserAgentProvider({serviceId:r.serviceId,clientVersion:oA.version}),eventStreamSerdeProvider:t?.eventStreamSerdeProvider??ro.eventStreamSerdeProvider,httpAuthSchemes:t?.httpAuthSchemes??[{schemeId:"smithy.api#httpBearerAuth",identityProvider:(i)=>i.getIdentityProvider("smithy.api#httpBearerAuth")||(async(f)=>{return await yh(f)(f)}),signer:new rd.HttpBearerAuthSigner}],maxAttempts:t?.maxAttempts??Un.loadConfig(V.NODE_MAX_ATTEMPT_CONFIG_OPTIONS,t),region:t?.region??Un.loadConfig(a.NODE_REGION_CONFIG_OPTIONS,{...a.NODE_REGION_CONFIG_FILE_OPTIONS,...e}),requestHandler:go.NodeHttpHandler.create(t?.requestHandler??s),retryMode:t?.retryMode??Un.loadConfig({...V.NODE_RETRY_MODE_CONFIG_OPTIONS,default:async()=>(await s()).retryMode||ot.DEFAULT_RETRY_MODE},t),sha256:t?.sha256??Gh.Hash.bind(null,"sha256"),streamCollector:t?.streamCollector??go.streamCollector,useDualstackEndpoint:t?.useDualstackEndpoint??Un.loadConfig(a.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS,e),useFipsEndpoint:t?.useFipsEndpoint??Un.loadConfig(a.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS,e),userAgentAppId:t?.userAgentAppId??Un.loadConfig(un.NODE_APP_ID_CONFIG_OPTIONS,e)}};var mt=H(kt(),1);var It=H(Tt(),1);var id=(t)=>{let{httpAuthSchemes:n,httpAuthSchemeProvider:s,token:r}=t;return{setHttpAuthScheme(e){let i=n.findIndex((f)=>f.schemeId===e.schemeId);if(i===-1)n.push(e);else n.splice(i,1,e)},httpAuthSchemes(){return n},setHttpAuthSchemeProvider(e){s=e},httpAuthSchemeProvider(){return s},setToken(e){r=e},token(){return r}}},od=(t)=>{return{httpAuthSchemes:t.httpAuthSchemes(),httpAuthSchemeProvider:t.httpAuthSchemeProvider(),token:t.token()}};var fd=(t,n)=>{let s=Object.assign(mt.getAwsRegionExtensionConfiguration(t),Y.getDefaultExtensionConfiguration(t),It.getHttpHandlerExtensionConfiguration(t),id(t));return n.forEach((r)=>r.configure(s)),Object.assign(t,mt.resolveAwsRegionExtensionConfiguration(s),Y.resolveDefaultRuntimeConfig(s),It.resolveHttpHandlerRuntimeConfig(s),od(s))};class Xh extends Y.Client{config;constructor(...[t]){let n=ed(t||{});super(n);this.initConfig=n;let s=eA(n),r=$n.resolveUserAgentConfig(s),e=V.resolveRetryConfig(r),i=a.resolveRegionConfig(e),f=Jn.resolveHostHeaderConfig(i),o=Ft.resolveEndpointConfig(f),c=Bt.resolveDefaultAwsRegionalEndpointsConfig(o),h=Gc.resolveEventStreamSerdeConfig(c),u=rA(h),l=fd(u,t?.extensions||[]);this.config=l,this.middlewareStack.use(cd.getSchemaSerdePlugin(this.config)),this.middlewareStack.use($n.getUserAgentPlugin(this.config)),this.middlewareStack.use(V.getRetryPlugin(this.config)),this.middlewareStack.use(ne.getContentLengthPlugin(this.config)),this.middlewareStack.use(Jn.getHostHeaderPlugin(this.config)),this.middlewareStack.use(Zr.getLoggerPlugin(this.config)),this.middlewareStack.use(te.getRecursionDetectionPlugin(this.config)),this.middlewareStack.use(lr.getHttpAuthSchemeEndpointRuleSetPlugin(this.config,{httpAuthSchemeParametersProvider:nA,identityProviderConfigProvider:async(_)=>new lr.DefaultIdentityProviderConfig({"smithy.api#httpBearerAuth":_.token})})),this.middlewareStack.use(lr.getHttpSigningPlugin(this.config))}destroy(){super.destroy()}}class qh extends Y.Command.classBuilder().ep(iA).m(function(t,n,s,r){return[Ft.getEndpointPlugin(s,t.getEndpointParameterInstructions())]}).s("AmazonCodeWhispererStreamingService","GenerateAssistantResponse",{eventStream:{output:!0}}).n("CodeWhispererStreamingClient","GenerateAssistantResponseCommand").sc(p1).build(){}function hd(t){let n=Ir[t];if(!n)throw Error(`Unsupported model: ${t}. Supported models: ${zu.join(", ")}`);return n}var ud=new Set(["claude-opus-4-8","claude-opus-4-7","claude-sonnet-5","claude-sonnet-4-6","gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"]),ld=["low","medium","high","xhigh","max"];function Eo(t){for(let n of ld){let s=`-${n}`;if(t.endsWith(s)){let r=t.slice(0,-s.length);if(ud.has(r))return{wireId:hd(r),effort:n}}}return{wireId:hd(t),effort:void 0}}function lW(t){for(let n of ld){let s=`-${n}`;if(t.endsWith(s)){let r=t.slice(0,-s.length);if(ud.has(r))return r}}if(t.endsWith("-thinking")){let n=t.slice(0,-9);if(Ir[n])return n}return t}function _d(t){return G(lW(t))}var _W=["low","medium","high","xhigh","max"];function wW(t){return typeof t==="string"&&_W.some((n)=>n===t)}var wd=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"]),Ad=new Set(["claude-opus-4.7","claude-opus-4.8","claude-sonnet-5",...wd]),AW=new Set(["claude-opus-4.5","claude-opus-4.6","claude-opus-4.6-1m","claude-sonnet-4.5","claude-sonnet-4.5-1m","claude-sonnet-4.6","claude-sonnet-4.6-1m",...Ad]);function Ro(t){return AW.has(t)}function MW(t){return Ad.has(t)}function Md(t,n){if(wd.has(t))return{reasoning:{effort:n}};return{output_config:{effort:n}}}function dW(t,n){if(!Ro(t))return;if(n==="xhigh"&&!MW(t))return"max";return n}function gW(t,n){if(!Ro(n))return;let s;if(t<=1e4)s="low";else if(t<=20000)s="medium";else if(t<=28000)s="high";else s="max";return s}function dd(t){let n;if(Ro(t.model))n={wireId:t.model,effort:void 0};else try{n=Eo(t.model)}catch(r){if(r instanceof Error&&r.message.startsWith("Unsupported model:"))return;throw r}if(!Ro(n.wireId))return;let s=[n.effort,t.reasoningEffort,t.configEffort];for(let r of s)if(wW(r))return dW(n.wireId,r);if(!t.think)return;if(t.autoEffortMapping??!0)return gW(t.budget,n.wireId);return"medium"}import{randomUUID as $W}from"crypto";function we(t){return typeof t==="object"&&t!==null}function EW(t){let n=atob(t),s=new Uint8Array(n.length);for(let r=0;r<n.length;r++)s[r]=n.charCodeAt(r);return s}function RW(t){let n=[];for(let s of t){if(!we(s)||s.type!=="image"||!we(s.source))continue;let r=s.source;if(r.type!=="base64"||typeof r.data!=="string")continue;n.push({mediaType:typeof r.media_type==="string"?r.media_type:"image/jpeg",data:r.data})}return n}function bW(t){let n=[];for(let s of t){if(!we(s)||s.type!=="image_url"||!we(s.image_url))continue;let r=s.image_url.url;if(typeof r!=="string"||!r.startsWith("data:"))continue;let[e="",i]=r.split(",",2);if(!i)continue;let f=e.split(";")[0]?.replace("data:","");n.push({mediaType:f||"image/jpeg",data:i})}return n}function bo(t){if(!Array.isArray(t))return[];return[...RW(t),...bW(t)]}function To(t){let n=[],s=0;for(let r of t){if(n.length>=4)break;if(s+r.data.length>3750000)break;n.push(r),s+=r.data.length}return{images:n.map((r)=>({format:r.mediaType.split("/")[1]||"png",source:{bytes:EW(r.data)}})),omitted:t.length-n.length}}function So(t){let n=[];for(let s of t){if(!we(s))continue;if(typeof s.text==="string")n.push(s.text);else if(s.type==="text"&&s.text)n.push(String(s.text))}return n.join("")}function Ch(t){return typeof t==="object"&&t!==null}function gd(t,n){for(let s of t){if(s.role!=="assistant")continue;if(s.tool_calls){for(let r of s.tool_calls)if(r.id===n)return r}if(Array.isArray(s.content)){for(let r of s.content)if(Ch(r)&&r.type==="tool_use"&&r.id===n)return r}}return null}function Ed(t){let n=[];for(let s of t){if(n.length===0){n.push({...s});continue}let r=n[n.length-1];if(!r||s.role!==r.role){n.push({...s});continue}if(Array.isArray(r.content)&&Array.isArray(s.content))r.content.push(...s.content);else if(typeof r.content==="string"&&typeof s.content==="string")r.content+=`
109
- ${s.content}`;else if(Array.isArray(r.content)&&typeof s.content==="string")r.content.push({type:"text",text:s.content});else if(typeof r.content==="string"&&Array.isArray(s.content))r.content=[{type:"text",text:r.content},...s.content];if(s.tool_calls){if(!r.tool_calls)r.tool_calls=[];r.tool_calls.push(...s.tool_calls)}if(s.role==="tool"){if(!r.tool_results)r.tool_results=[{content:r.content,tool_call_id:r.tool_call_id}];r.tool_results.push({content:s.content,tool_call_id:s.tool_call_id})}}return n}function Ot(t){if(t===null||t===void 0)return"";if(typeof t==="string")return t;if(!Ch(t))return"";if(typeof t.content==="string")return t.content;if(Array.isArray(t.content))return t.content.filter((n)=>Ch(n)&&n.type==="text").map((n)=>typeof n.text==="string"?n.text:"").join("");return typeof t.text==="string"?t.text:""}function Rd(t){return t.map((n)=>({toolSpecification:{name:n.name||n.function?.name,description:(n.description||n.function?.description||"").substring(0,9216),inputSchema:{json:n.input_schema||n.function?.parameters||{}}}}))}function Ae(t){let n=[],s=new Set;for(let r of t)if(!s.has(r.toolUseId))s.add(r.toolUseId),n.push(r);return n}function bd(t){return typeof t==="object"&&t!==null}function TW(t){let n=t.function?.arguments;return{input:typeof n==="string"?JSON.parse(n):n,name:t.function?.name??"",toolUseId:t.id??""}}function SW(t){if(t.length<4)return t;let n=[],s=0;while(s<t.length){let r=t[s];if(r?.assistantResponseMessage?.toolUses&&s+1<t.length&&t[s+1]?.userInputMessage?.userInputMessageContext?.toolResults){let e=s,i=s;while(i<t.length){let o=t[i],c=i+1<t.length?t[i+1]:void 0;if(!o?.assistantResponseMessage?.toolUses||!c?.userInputMessage?.userInputMessageContext?.toolResults)break;i+=2}let f=(i-e)/2;for(let o=e;o<i;o+=2){let c=t[o],h=t[o+1];if(!c||!h)continue;if(f>1&&o!==e)n.push({assistantResponseMessage:{content:"[system: tool calling continues]",toolUses:c.assistantResponseMessage?.toolUses}});else n.push(c);n.push(h)}s=i}else{if(r)n.push(r);s++}}return n}function Td(t,n){let s=[];for(let r=0;r<t.length-1;r++){let e=t[r];if(!e)continue;if(e.role==="user"){let h={content:"",modelId:n,origin:st.ORIGIN_AI_EDITOR},u=[];if(Array.isArray(e.content)){h.content=So(e.content);for(let _ of e.content){if(!bd(_)||_.type!=="tool_result"||typeof _.tool_use_id!=="string")continue;u.push({content:[{text:Ot(_.content??_)}],status:"success",toolUseId:_.tool_use_id})}let l=bo(e.content);if(l.length>0){let _=To(l);if(h.images=_.images,_.omitted>0)h.content+=`
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
+ ${s.content}`;else if(Array.isArray(r.content)&&typeof s.content==="string")r.content.push({type:"text",text:s.content});else if(typeof r.content==="string"&&Array.isArray(s.content))r.content=[{type:"text",text:r.content},...s.content];if(s.tool_calls){if(!r.tool_calls)r.tool_calls=[];r.tool_calls.push(...s.tool_calls)}if(s.role==="tool"){if(!r.tool_results)r.tool_results=[{content:r.content,tool_call_id:r.tool_call_id}];r.tool_results.push({content:s.content,tool_call_id:s.tool_call_id})}}return n}function Bt(t){if(t===null||t===void 0)return"";if(typeof t==="string")return t;if(!vh(t))return"";if(typeof t.content==="string")return t.content;if(Array.isArray(t.content))return t.content.filter((n)=>vh(n)&&n.type==="text").map((n)=>typeof n.text==="string"?n.text:"").join("");return typeof t.text==="string"?t.text:""}function Hg(t){return t.map((n)=>({toolSpecification:{name:n.name||n.function?.name,description:(n.description||n.function?.description||"").substring(0,9216),inputSchema:{json:n.input_schema||n.function?.parameters||{}}}}))}function gi(t){let n=[],s=new Set;for(let r of t)if(!s.has(r.toolUseId))s.add(r.toolUseId),n.push(r);return n}function Pg(t){return typeof t==="object"&&t!==null}function q7(t){let n=t.function?.arguments;return{input:typeof n==="string"?JSON.parse(n):n,name:t.function?.name??"",toolUseId:t.id??""}}function C7(t){if(t.length<4)return t;let n=[],s=0;while(s<t.length){let r=t[s];if(r?.assistantResponseMessage?.toolUses&&s+1<t.length&&t[s+1]?.userInputMessage?.userInputMessageContext?.toolResults){let i=s,e=s;while(e<t.length){let o=t[e],c=e+1<t.length?t[e+1]:void 0;if(!o?.assistantResponseMessage?.toolUses||!c?.userInputMessage?.userInputMessageContext?.toolResults)break;e+=2}let f=(e-i)/2;for(let o=i;o<e;o+=2){let c=t[o],h=t[o+1];if(!c||!h)continue;if(f>1&&o!==i){let u=c.assistantResponseMessage?.content.match(/^<thinking>[\s\S]*?<\/thinking>/)?.[0];n.push({assistantResponseMessage:{content:u?`${u}
110
110
 
111
- [${_.omitted} image(s) omitted due to API limits]`}}else h.content=Ot(e);if(u.length>0)h.userInputMessageContext={toolResults:Ae(u)};if(s[s.length-1]?.userInputMessage)s.push({assistantResponseMessage:{content:"[system: conversation continues]"}});s.push({userInputMessage:h});continue}if(e.role==="tool"){let h=[];if(e.tool_results)for(let u of e.tool_results){if(!u.tool_call_id)continue;h.push({content:[{text:Ot(u)}],status:"success",toolUseId:u.tool_call_id})}else if(e.tool_call_id)h.push({content:[{text:Ot(e)}],status:"success",toolUseId:e.tool_call_id});if(s[s.length-1]?.userInputMessage)s.push({assistantResponseMessage:{content:"[system: conversation continues]"}});s.push({userInputMessage:{content:"Tool results provided.",modelId:n,origin:st.ORIGIN_AI_EDITOR,userInputMessageContext:{toolResults:Ae(h)}}});continue}if(e.role!=="assistant")continue;let i={content:""},f=[],o="";if(Array.isArray(e.content))for(let h of e.content){if(!bd(h))continue;if(h.type==="text")i.content+=typeof h.text==="string"?h.text:"";else if(h.type==="thinking")o+=typeof h.thinking==="string"?h.thinking:typeof h.text==="string"?h.text:"";else if(h.type==="tool_use"&&typeof h.id==="string"&&typeof h.name==="string")f.push({input:h.input,name:h.name,toolUseId:h.id})}else i.content=Ot(e);if(e.tool_calls)for(let h of e.tool_calls)f.push(TW(h));if(o)i.content=i.content?`<thinking>${o}</thinking>
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+=`
112
112
 
113
- ${i.content}`:`<thinking>${o}</thinking>`;if(f.length>0)i.toolUses=f;if(!i.content&&!i.toolUses)continue;let c=s[s.length-1]?.assistantResponseMessage;if(c){if(i.content)c.content=c.content?`${c.content}
113
+ [${l.omitted} image(s) omitted due to API limits]`}}else h.content=Bt(i);if(u.length>0)h.userInputMessageContext={toolResults:gi(u)};if(s[s.length-1]?.userInputMessage)s.push({assistantResponseMessage:{content:"[system: conversation continues]"}});s.push({userInputMessage:h});continue}if(i.role==="tool"){let h=[];if(i.tool_results)for(let u of i.tool_results){if(!u.tool_call_id)continue;h.push({content:[{text:Bt(u)}],status:"success",toolUseId:u.tool_call_id})}else if(i.tool_call_id)h.push({content:[{text:Bt(i)}],status:"success",toolUseId:i.tool_call_id});if(s[s.length-1]?.userInputMessage)s.push({assistantResponseMessage:{content:"[system: conversation continues]"}});s.push({userInputMessage:{content:"Tool results provided.",modelId:n,origin:ot.ORIGIN_AI_EDITOR,userInputMessageContext:{toolResults:gi(h)}}});continue}if(i.role!=="assistant")continue;let e={content:""},f=[],o="";if(Array.isArray(i.content))for(let h of i.content){if(!Pg(h))continue;if(h.type==="text")e.content+=typeof h.text==="string"?h.text:"";else if(h.type==="thinking")o+=typeof h.thinking==="string"?h.thinking:typeof h.text==="string"?h.text:"";else if(h.type==="tool_use"&&typeof h.id==="string"&&typeof h.name==="string")f.push({input:h.input,name:h.name,toolUseId:h.id})}else e.content=Bt(i);if(i.tool_calls)for(let h of i.tool_calls)f.push(q7(h));if(o){let h=o.replaceAll("</thinking>","<\\/thinking>");e.content=e.content?`<thinking>${h}</thinking>
114
114
 
115
- ${i.content}`:i.content;if(i.toolUses)c.toolUses=[...c.toolUses??[],...i.toolUses]}else s.push({assistantResponseMessage:i})}return SW(s)}function Sd(t,n,s){if(!n)return t;let r=t.find((e)=>e.userInputMessage);if(r?.userInputMessage)r.userInputMessage.content=`${n}
115
+ ${e.content}`:`<thinking>${h}</thinking>`}if(f.length>0)e.toolUses=f;if(!e.content&&!e.toolUses)continue;let c=s[s.length-1]?.assistantResponseMessage;if(c){if(e.content)c.content=c.content?`${c.content}
116
116
 
117
- ${r.userInputMessage.content||""}`;else t.unshift({userInputMessage:{content:n,modelId:s,origin:st.ORIGIN_AI_EDITOR}});return t}function $d(t){return t.some((n)=>Boolean(n.assistantResponseMessage?.toolUses)||Boolean(n.userInputMessage?.userInputMessageContext?.toolResults))}function Ud(t){let n=new Set;for(let s of t)for(let r of s.assistantResponseMessage?.toolUses??[])if(r.name)n.add(r.name);return n}function _n(t){return typeof t==="object"&&t!==null}function UW(t){return _n(t)}function LW(t){return _n(t)}function IW(t){let n=typeof t==="string"?JSON.parse(t):t;if(!_n(n))return{messages:[],tools:[],system:""};return{messages:Array.isArray(n.messages)?n.messages.filter(UW):[],tools:Array.isArray(n.tools)?n.tools.filter(LW):[],system:typeof n.system==="string"?n.system:""}}function OW(t){if(Array.isArray(t))return"array";if(t===null)return"string";let n=typeof t;return n==="number"||n==="boolean"||n==="string"||n==="object"?n:"string"}function yW(t,n){let s=n?.find((i)=>i.name===t&&_n(i.input)),r={};if(s&&_n(s.input))for(let[i,f]of Object.entries(s.input))r[i]={type:OW(f)};let e=Object.keys(r).length>0?{type:"object",properties:r}:{type:"object"};return{toolSpecification:{name:t,description:`Tool ${t}`,inputSchema:{json:e}}}}function GW(t,n){let s={content:""},r=[],e="";if(Array.isArray(n.content))for(let i of n.content){if(!_n(i))continue;if(i.type==="text"&&typeof i.text==="string")s.content+=i.text;else if(i.type==="thinking")e+=typeof i.thinking==="string"?i.thinking:typeof i.text==="string"?i.text:"";else if(i.type==="tool_use"&&typeof i.id==="string"&&typeof i.name==="string")r.push({input:i.input,name:i.name,toolUseId:i.id})}else s.content=Ot(n);for(let i of n.tool_calls??[]){if(typeof i.id!=="string"||typeof i.function?.name!=="string")continue;let f=i.function.arguments;r.push({input:typeof f==="string"?JSON.parse(f):f,name:i.function.name,toolUseId:i.id})}if(e)s.content=s.content?`<thinking>${e}</thinking>
117
+ ${e.content}`:e.content;if(e.toolUses)c.toolUses=[...c.toolUses??[],...e.toolUses]}else s.push({assistantResponseMessage:e})}return C7(s)}function Wg(t,n,s){if(!n)return t;let r=t.find((i)=>i.userInputMessage);if(r?.userInputMessage)r.userInputMessage.content=`${n}
118
118
 
119
- ${s.content}`:`<thinking>${e}</thinking>`;if(r.length>0)s.toolUses=r;if(s.content||s.toolUses)t.push({assistantResponseMessage:s})}function BW(t){let n="",s=[],r=[];if(t.role==="tool"){let e=t.tool_results??[{content:t.content,tool_call_id:t.tool_call_id}];for(let i of e){if(typeof i.tool_call_id!=="string")continue;s.push({content:[{text:Ot(i)}],status:"success",toolUseId:i.tool_call_id})}}else if(Array.isArray(t.content)){n=So(t.content);for(let i of t.content){if(!_n(i)||i.type!=="tool_result"||typeof i.tool_use_id!=="string")continue;s.push({content:[{text:Ot(i.content??i)}],status:"success",toolUseId:i.tool_use_id})}let e=To(bo(t.content));if(r.push(...e.images),e.omitted>0)n+=`
119
+ ${r.userInputMessage.content||""}`;else t.unshift({userInputMessage:{content:n,modelId:s,origin:ot.ORIGIN_AI_EDITOR}});return t}function Dg(t){return t.some((n)=>Boolean(n.assistantResponseMessage?.toolUses)||Boolean(n.userInputMessage?.userInputMessageContext?.toolResults))}function Yg(t){let n=new Set;for(let s of t)for(let r of s.assistantResponseMessage?.toolUses??[])if(r.name)n.add(r.name);return n}function wn(t){return typeof t==="object"&&t!==null}function V7(t){return wn(t)}function j7(t){return wn(t)}function a7(t){let n=typeof t==="string"?JSON.parse(t):t;if(!wn(n))return{messages:[],tools:[],system:""};return{messages:Array.isArray(n.messages)?n.messages.filter(V7):[],tools:Array.isArray(n.tools)?n.tools.filter(j7):[],system:typeof n.system==="string"?n.system:""}}function p7(t){if(Array.isArray(t))return"array";if(t===null)return"string";let n=typeof t;return n==="number"||n==="boolean"||n==="string"||n==="object"?n:"string"}function Z7(t,n){let s=n?.find((e)=>e.name===t&&wn(e.input)),r={};if(s&&wn(s.input))for(let[e,f]of Object.entries(s.input))r[e]={type:p7(f)};let i=Object.keys(r).length>0?{type:"object",properties:r}:{type:"object"};return{toolSpecification:{name:t,description:`Tool ${t}`,inputSchema:{json:i}}}}function v7(t,n){let s={content:""},r=[],i="";if(Array.isArray(n.content))for(let e of n.content){if(!wn(e))continue;if(e.type==="text"&&typeof e.text==="string")s.content+=e.text;else if(e.type==="thinking")i+=typeof e.thinking==="string"?e.thinking:typeof e.text==="string"?e.text:"";else if(e.type==="tool_use"&&typeof e.id==="string"&&typeof e.name==="string")r.push({input:e.input,name:e.name,toolUseId:e.id})}else s.content=Bt(n);for(let e of n.tool_calls??[]){if(typeof e.id!=="string"||typeof e.function?.name!=="string")continue;let f=e.function.arguments;r.push({input:typeof f==="string"?JSON.parse(f):f,name:e.function.name,toolUseId:e.id})}if(i){let e=i.replaceAll("</thinking>","<\\/thinking>");s.content=s.content?`<thinking>${e}</thinking>
120
120
 
121
- [${e.omitted} image(s) omitted due to API limits]`}else n=Ot(t);if(!n)n=s.length>0?"Tool results provided.":"[system: conversation continues]";return{content:n,toolResults:s,images:r}}function mW(t,n){let s=gd(t,n.toolUseId);if(!_n(s))return;let r=_n(s.function)?s.function:void 0,e=typeof s.name==="string"?s.name:typeof r?.name==="string"?r.name:"tool",i=s.input??r?.arguments;return{name:e,toolUseId:n.toolUseId,input:typeof i==="string"?JSON.parse(i):i??{}}}function Ld(t,n,s,r=!1,e=20000){let i=IW(t);if(i.messages.length===0)throw Error("No messages");let{wireId:f,effort:o}=Eo(n),c=i.messages.filter((U)=>U.role==="system"),h=Ed(i.messages.filter((U)=>U.role!=="system")),u=i.system,l=c.map(Ot).join(`
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+=`
122
122
 
123
- `);if(l)u=u?`${u}
123
+ [${i.omitted} image(s) omitted due to API limits]`}else n=Bt(t);if(!n)n=s.length>0?"Tool results provided.":"[system: conversation continues]";return{content:n,toolResults:s,images:r}}function n9(t,n){let s=Bg(t,n.toolUseId);if(!wn(s))return;let r=wn(s.function)?s.function:void 0,i=typeof s.name==="string"?s.name:typeof r?.name==="string"?r.name:"tool",e=s.input??r?.arguments;return{name:i,toolUseId:n.toolUseId,input:typeof e==="string"?JSON.parse(e):e??{}}}function mg(t,n,s,r=!1,i=20000){let e=a7(t);if(e.messages.length===0)throw Error("No messages");let{wireId:f,effort:o}=To(n),c=e.messages.filter((R)=>R.role==="system"),h=Fg(e.messages.filter((R)=>R.role!=="system")),u=e.system,_=c.map(Bt).join(`
124
124
 
125
- ${l}`:l;if(r&&!u.includes("<thinking_mode>")){let U=`<thinking_mode>enabled</thinking_mode><max_thinking_length>${e}</max_thinking_length>`;u=u?`${U}
126
- ${u}`:U}let _=h.at(-1);if(_?.role==="assistant"&&Ot(_)==="{")h.pop();let w=h.at(-1);if(!w)throw Error("Empty");let A=Td(h,f),M=w.role==="user"&&!(Array.isArray(w.content)&&w.content.some((U)=>_n(U)&&U.type==="tool_result")),d=h.at(-2);if(M&&d?.role==="assistant"&&A.at(-1)?.userInputMessage){let U=Ot(d);if(U)A.push({assistantResponseMessage:{content:U}})}A=Sd(A,u,f);let E="[system: conversation continues]",b=[],L=[];if(w.role==="assistant")GW(A,w);else{if(A.at(-1)&&!A.at(-1)?.assistantResponseMessage)A.push({assistantResponseMessage:{content:"[system: conversation continues]"}});let U=BW(w);E=U.content,b=U.toolResults,L=U.images}let S=A.flatMap((U)=>U.assistantResponseMessage?.toolUses??[]),O=new Set(S.map((U)=>U.toolUseId)),x=[],X=[];for(let U of b)if(O.has(U.toolUseId))x.push(U);else{let z=mW(i.messages,U);if(z)X.push({call:z,result:U});else E+=`
125
+ `);if(_)u=u?`${u}
127
126
 
128
- [Output for tool call ${U.toolUseId}]:
129
- ${U.content[0]?.text??""}`}if(X.length>0){if(!A.at(-1)||A.at(-1)?.assistantResponseMessage)A.push({userInputMessage:{content:"Running tools...",modelId:f,origin:st.ORIGIN_AI_EDITOR}});A.push({assistantResponseMessage:{content:"I will execute the following tools.",toolUses:X.map(({call:U})=>U)}}),x.push(...X.map(({result:U})=>U))}let v={content:E,modelId:f,origin:st.ORIGIN_AI_EDITOR};if(L.length>0)v.images=L;let Q=Rd(i.tools).filter((U)=>typeof U.toolSpecification.name==="string").map((U)=>({toolSpecification:{...U.toolSpecification,name:U.toolSpecification.name??""}}));if(x.length>0||Q.length>0){if(v.userInputMessageContext={},x.length>0)v.userInputMessageContext.toolResults=Ae(x);if(Q.length>0)v.userInputMessageContext.tools=Q}if($d(A)){let U=v.userInputMessageContext?.tools??[],z=new Set(U.map((an)=>an.toolSpecification.name)),Gt=[...Ud(A)].filter((an)=>!z.has(an));if(Gt.length>0)v.userInputMessageContext??={},v.userInputMessageContext.tools=[...U,...Gt.map((an)=>yW(an,S))]}let rt=$W(),Dt={conversationState:{chatTriggerType:st.CHAT_TRIGGER_TYPE_MANUAL,conversationId:rt,currentMessage:{userInputMessage:v},...A.length>0?{history:A}:{}},...s.profileArn?{profileArn:s.profileArn}:{}};return o===void 0?{request:Dt,resolved:f,convId:rt}:{request:Dt,resolved:f,convId:rt,variantEffort:o}}function FW(t){let n=typeof t==="string"?JSON.parse(t):t;if(typeof n!=="object"||n===null||!("reasoning_effort"in n))return;let s=n.reasoning_effort;return typeof s==="string"||s===null?s:void 0}function Id(t,n,s,r=!1,e=20000,i){let{request:f,resolved:o,convId:c}=Ld(t,n,s,r,e),h=dd({model:n,think:r,budget:e,reasoningEffort:FW(t),configEffort:i?.effort,autoEffortMapping:i?.autoEffortMapping});return{conversationState:f.conversationState,...f.profileArn?{profileArn:f.profileArn}:{},streaming:!0,effectiveModel:o,conversationId:c,region:Ju(s.profileArn)??s.region,...h?{effort:h}:{}}}function Od(t){return Math.ceil(t.length/4)}async function $o(t,n){if(n?.aborted)return{kind:"aborted"};let s=t.next();if(!n)return{kind:"event",result:await s};return new Promise((r,e)=>{let i=()=>r({kind:"aborted"});n.addEventListener("abort",i,{once:!0}),s.then((f)=>{n.removeEventListener("abort",i),r({kind:"event",result:f})},(f)=>{n.removeEventListener("abort",i),e(f)})})}function Me(t,n){if(!n?.name||!n.toolUseId)return;let s=t.get(n.toolUseId);if(s){s.input+=n.input??"";return}t.set(n.toolUseId,{toolUseId:n.toolUseId,name:n.name,input:n.input??""})}function yd(t){let n=[],s=0;for(let r of t.values()){let e=r.input;try{e=JSON.stringify(JSON.parse(r.input))}catch{e=r.input}n.push({type:"content_block_start",index:s,content_block:{type:"tool_use",id:r.toolUseId,name:r.name,input:{}}},{type:"content_block_delta",index:s,delta:{type:"input_json_delta",partial_json:e}},{type:"content_block_stop",index:s}),s+=1}return n}function Uo(t,n){let s=n.metadataEvent?.tokenUsage;if(s)t.outputTokens=s.outputTokens??t.outputTokens,t.totalTokens=s.totalTokens??t.totalTokens,t.inputTokens=s.inputTokens??(s.uncachedInputTokens===void 0?t.inputTokens:s.uncachedInputTokens+(s.cacheReadInputTokens??0)+(s.cacheWriteInputTokens??0));t.contextUsagePercentage=n.contextUsageEvent?.contextUsagePercentage??n.metadataEvent?.contextUsagePercentage??s?.contextUsagePercentage??t.contextUsagePercentage}function Lo(t,n,s){let r=t.outputTokens??Od(n),e=t.inputTokens;if(e===void 0&&t.totalTokens!==void 0)e=Math.max(0,t.totalTokens-r);if(e===void 0&&t.contextUsagePercentage!==void 0&&t.contextUsagePercentage>0){let i=Math.round(_d(s)*t.contextUsagePercentage/100);e=Math.max(0,i-r)}return{inputTokens:e??0,outputTokens:r}}class Gd extends Error{name="MissingSdkEventStreamError";constructor(){super("SDK response has no event stream")}}async function Bd(t,n,s,r){let e=t.generateAssistantResponseResponse;if(!e)throw new Gd;let i=e[Symbol.asyncIterator](),f=new Map,o={},c="",h="",u=!1,l=!1;try{while(!0){let A=await $o(i,r);if(A.kind==="aborted"){if(i.return)await i.return();l=!0;break}if(A.result.done){u=!0;break}let M=A.result.value;Uo(o,M),h+=M.reasoningContentEvent?.text??"",c+=M.assistantResponseEvent?.content??"",Me(f,M.toolUseEvent)}}finally{if(!u&&!l&&i.return)await i.return()}let _=Lo(o,c,n),w={role:"assistant",content:c,...h?{reasoning_content:h}:{},...f.size>0?{tool_calls:Array.from(f.values(),(A)=>({id:A.toolUseId,type:"function",function:{name:A.name,arguments:A.input}}))}:{}};return{id:s,object:"chat.completion",created:Math.floor(Date.now()/1000),model:n,choices:[{index:0,message:w,finish_reason:f.size>0?"tool_calls":"stop"}],usage:{prompt_tokens:_.inputTokens,completion_tokens:_.outputTokens,total_tokens:_.inputTokens+_.outputTokens}}}var PW=[/input is too long/i,/CONTENT_LENGTH_EXCEEDS_THRESHOLD/i],HW=/econnreset|etimedout|enotfound|network|fetch failed|socket/i;function Io(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function ah(t,n){let s=t[n];return typeof s==="string"?s:void 0}function NW(t){let n=t.$metadata;if(!Io(n))return;let s=n.httpStatusCode;return typeof s==="number"?s:void 0}function DW(t){let n=t.$response;if(!Io(n))return;let s=n.headers;if(!Io(s))return;let r={};for(let[e,i]of Object.entries(s))if(typeof i==="string")r[e]=i;else if(typeof i==="number")r[e]=String(i);return Object.keys(r).length>0?r:void 0}function Kh(t){if(!Io(t))return{message:t instanceof Error?t.message:String(t)};let n=NW(t),s=ah(t,"message")??String(t),r=ah(t,"name"),e=ah(t,"reason"),i=DW(t);return{message:s,...n!==void 0?{status:n}:{},...r!==void 0?{code:r}:{},...e!==void 0?{reason:e}:{},...i!==void 0?{headers:i}:{}}}function WW(t){let n=Object.entries(t??{}).find(([r])=>r.toLowerCase()==="retry-after"),s=Number.parseInt(n?.[1]??"60",10);return Number.isFinite(s)&&s>=0?s*1000:60000}function YW(t){return PW.some((n)=>n.test(t))}function md(t,n){if(t.reason==="INVALID_MODEL_ID"){let s=t.status??400;return{action:"fail",status:s,terminalStatus:s}}if(t.reason==="TEMPORARILY_SUSPENDED")return n.accountCount>1?{action:"switch",...t.status!==void 0?{status:t.status}:{}}:{action:"fail",...t.status!==void 0?{status:t.status}:{},terminalStatus:t.status??403};switch(t.status){case 400:return{action:"fail",status:400,terminalStatus:YW(t.message)?413:400};case 401:return n.retryCount<n.maxRetries?{action:"retry",status:401}:{action:"fail",status:401,terminalStatus:401};case 402:return{action:"fail",status:402,terminalStatus:402};case 403:if(Le(t.message)){if(!n.forcedRefreshAccountIds.has(n.accountId))return n.forcedRefreshAccountIds.add(n.accountId),{action:"refresh-then-retry",status:403};return n.accountCount>1?{action:"switch",status:403}:{action:"fail",status:403,terminalStatus:403}}if(n.accountCount>1)return{action:"switch",status:403};return n.retryCount<n.maxRetries?{action:"retry",status:403,retryAfterMs:n.retryDelayMs*2**n.retryCount}:{action:"fail",status:403,terminalStatus:403};case 429:{let s=WW(t.headers);return n.accountCount>1?{action:"switch",status:429,retryAfterMs:s}:{action:"retry",status:429,retryAfterMs:s}}case 500:return n.serverErrorCount<5?{action:"retry",status:500,retryAfterMs:1000*2**Math.max(0,n.serverErrorCount-1)}:{action:"switch",status:500};case void 0:if(HW.test(t.message))return n.retryCount<n.maxRetries?{action:"retry",retryAfterMs:n.retryDelayMs*2**n.retryCount}:{action:"fail",terminalStatus:500};return{action:"fail",terminalStatus:500};default:return{action:"fail",status:t.status,terminalStatus:t.status}}}var Fd=Promise.resolve();function Ln(t){return t.reason instanceof Error?t.reason:new DOMException("The request was aborted","AbortError")}function _r(t,n){if(n.aborted)return Promise.reject(Ln(n));return new Promise((s,r)=>{let e=()=>r(Ln(n));n.addEventListener("abort",e,{once:!0}),t.then((i)=>{n.removeEventListener("abort",e),s(i)},(i)=>{n.removeEventListener("abort",e),r(i)})})}function Pd(t,n){if(t<=0)return Promise.resolve();return _r(Bun.sleep(t),n)}async function Hd(t){let n=Fd,s,r=new Promise((f)=>{s=f});if(!s)throw TypeError("Queue release was not initialized");let e=s;Fd=n.catch(()=>{return}).then(()=>r);try{await _r(n,t)}catch(f){throw e(),f}let i=!1;return()=>{if(i)return;i=!0,e()}}function Nd(t,n){if(t)return{signal:t,dispose:()=>{return}};let s=new AbortController,r=setTimeout(()=>s.abort(new DOMException("Request deadline exceeded","TimeoutError")),n);return{signal:s.signal,dispose:()=>clearTimeout(r)}}var de="<\uFF5CDSML\uFF5Cfunction_calls";function Vh(){return`tool_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}function xW(t){let n=[],s=/```[\s\S]*?```/g;for(let i=s.exec(t);i!==null;i=s.exec(t))n.push([i.index,i.index+i[0].length]);let r=(i)=>n.some(([f,o])=>i>=f&&i<o),e=/`[^`\n]+`/g;for(let i=e.exec(t);i!==null;i=e.exec(t))if(!r(i.index))n.push([i.index,i.index+i[0].length]);return n}function Es(t,n,s){return s.some(([r,e])=>t<e&&n>r)}function QW(t){let n={},s=/<parameter\s+name="([^"]+)"\s*>([\s\S]*?)<\/parameter>/g;for(let r=s.exec(t);r!==null;r=s.exec(t)){let e=r[1];if(e===void 0)continue;let i=r[2]??"";try{n[e]=JSON.parse(i)}catch{n[e]=i}}return n}function Dd(t,n){return{toolUseId:Vh(),name:t,input:QW(n)}}function JW(t,n,s){let r=[],e=/<function_calls>[\s\S]*?<\/function_calls>/g;for(let f=e.exec(t);f!==null;f=e.exec(t)){let o=f.index,c=o+f[0].length;if(Es(o,c,n))continue;let h=/<invoke\s+name="([^"]+)"\s*>([\s\S]*?)<\/invoke>/g,u=[];for(let l=h.exec(f[0]);l!==null;l=h.exec(f[0])){let _=l[1];if(_)u.push(Dd(_,l[2]??""))}if(u.length===0)continue;r.push({start:o,end:c,toolCalls:u}),s.push([o,c])}let i=/<invoke\s+name="([^"]+)"\s*>([\s\S]*?)<\/invoke>/g;for(let f=i.exec(t);f!==null;f=i.exec(t)){let o=f.index,c=o+f[0].length,h=f[1];if(!h||Es(o,c,n)||Es(o,c,s))continue;r.push({start:o,end:c,toolCalls:[Dd(h,f[2]??"")]}),s.push([o,c])}return r}function zW(t,n,s){let r=[],e=0;for(;;){let i=t.indexOf(de,e);if(i===-1)break;let f=t.slice(i+de.length),o=/<\uFF5C[^>]*?end[^>]*?>|<\/\uFF5CDSML[^>]*?>/.exec(f),c=o!==null?i+de.length+o.index+o[0].length:t.length;if(e=c,Es(i,c,n)||Es(i,c,s))continue;let h=t.slice(i,c),u=[],l=/name["\uFF5C=:\s]+["']?([A-Za-z0-9_]+)/.exec(h),_=/(\{[\s\S]*\})/.exec(h);if(l?.[1]&&_?.[1])try{u.push({toolUseId:Vh(),name:l[1],input:JSON.parse(_[1])})}catch{}r.push({start:i,end:c,toolCalls:u}),s.push([i,c])}return r}function kW(t,n,s){let r=[],e=/\[Called\s+(\w+)\s+with\s+args:\s*(\{[^}]*(?:\{[^}]*\}[^}]*)*\})\]/gs;for(let i=e.exec(t);i!==null;i=e.exec(t)){let f=i.index,o=f+i[0].length,c=i[1],h=i[2];if(!c||!h||Es(f,o,n)||Es(f,o,s))continue;let u;try{u=JSON.parse(h)}catch{continue}r.push({start:f,end:o,toolCalls:[{toolUseId:Vh(),name:c,input:u}]}),s.push([f,o])}return r}function Wd(t){if(!t)return{toolCalls:[],cleanedText:t};let n=xW(t),s=[],r=[...JW(t,n,s),...zW(t,n,s),...kW(t,n,s)];if(r.length===0)return{toolCalls:[],cleanedText:t};r.sort((o,c)=>o.start-c.start);let e=[],i="",f=0;for(let o of r){if(o.start<f)continue;i+=t.slice(f,o.start),f=o.end,e.push(...o.toolCalls)}return i+=t.slice(f),{toolCalls:e,cleanedText:i}}var jh=["<function_calls","<invoke name=",de],XW=Math.max(...jh.map((t)=>t.length));function Yd(t){let n=-1;for(let s of jh){let r=t.indexOf(s);if(r!==-1&&(n===-1||r<n))n=r}return n}function qW(t){let n=Math.min(t.length,XW-1);for(let s=n;s>0;s--){let r=t.slice(t.length-s);for(let e of jh)if(e.length>s&&e.startsWith(r))return s}return 0}class ph{accumulated="";emitted=0;markerSeen=!1;push(t){if(!t)return"";if(this.accumulated+=t,!this.markerSeen&&Yd(this.accumulated)!==-1)this.markerSeen=!0;let n;if(this.markerSeen){let r=Yd(this.accumulated);n=r===-1?this.accumulated.length:r}else n=this.accumulated.length-qW(this.accumulated);if(n<=this.emitted)return"";let s=this.accumulated.slice(this.emitted,n);return this.emitted=n,s}get suppressing(){return this.markerSeen}finalize(){let{toolCalls:t,cleanedText:n}=Wd(this.accumulated),s=n.length>this.emitted?n.slice(this.emitted):"";return{toolCalls:t,remainderText:s}}}function vh(t,n,s){let r=[];if(t.type==="content_block_delta"){if(t.delta?.type==="text_delta")r.push({index:0,delta:{content:t.delta.text??""},finish_reason:null});else if(t.delta?.type==="thinking_delta"){if(t.delta.thinking)r.push({index:0,delta:{reasoning_content:t.delta.thinking},finish_reason:null})}else if(t.delta?.type==="input_json_delta")r.push({index:0,delta:{tool_calls:[{index:t.index,function:{arguments:t.delta.partial_json??""}}]},finish_reason:null})}else if(t.type==="content_block_start"&&t.content_block?.type==="tool_use")r.push({index:0,delta:{tool_calls:[{index:t.index,id:t.content_block.id,type:"function",function:{name:t.content_block.name,arguments:""}}]},finish_reason:null});else if(t.type==="message_delta")r.push({index:0,delta:{},finish_reason:t.delta?.stop_reason==="tool_use"?"tool_calls":"stop"});else return null;if(r.length===0)return null;let e={id:n,object:"chat.completion.chunk",created:Math.floor(Date.now()/1000),model:s,choices:r};if(t.type!=="message_delta")return e;let i=t.usage?.input_tokens??0,f=t.usage?.output_tokens??0;return{...e,usage:{prompt_tokens:i,completion_tokens:f,total_tokens:i+f}}}function Zh(t,n){let s=/```[\s\S]*?```/g,r=[],e=s.exec(t);while(e!==null)r.push([e.index,e.index+e[0].length]),e=s.exec(t);let i=t.indexOf(n,0);while(i!==-1){if(!r.some(([o,c])=>i>=o&&i<c))return i;i=t.indexOf(n,i+n.length)}return-1}function xd(t,n){if(t==="thinking"){if(n.thinkingBlockIndex!==null)return[];let r=n.nextBlockIndex++;return n.thinkingBlockIndex=r,[{type:"content_block_start",index:r,content_block:{type:"thinking",thinking:""}}]}if(n.textBlockIndex!==null)return[];let s=n.nextBlockIndex++;return n.textBlockIndex=s,[{type:"content_block_start",index:s,content_block:{type:"text",text:""}}]}function Rs(t,n){if(t===null||n.stoppedBlocks.has(t))return[];return n.stoppedBlocks.add(t),[{type:"content_block_stop",index:t}]}function qn(t,n){if(!t)return[];let s=xd("text",n),r=n.textBlockIndex;if(r===null)return s;return s.push({type:"content_block_delta",index:r,delta:{type:"text_delta",text:t}}),s}function Cn(t,n){let s=xd("thinking",n),r=n.thinkingBlockIndex;if(r===null)return s;return s.push({type:"content_block_delta",index:r,delta:{type:"thinking_delta",thinking:t}}),s}var Oo="<thinking>",yo="</thinking>";function Qd(t,n){n.buffer+=t;let s=[];while(n.buffer.length>0){if(!n.inThinking&&!n.thinkingExtracted){let e=Zh(n.buffer,Oo);if(e!==-1){let f=n.buffer.slice(0,e);s.push(...qn(f,n)),n.buffer=n.buffer.slice(e+Oo.length),n.inThinking=!0;continue}let i=Math.max(0,n.buffer.length-Oo.length);if(i>0)s.push(...qn(n.buffer.slice(0,i),n)),n.buffer=n.buffer.slice(i);break}if(n.inThinking){let e=Zh(n.buffer,yo);if(e!==-1){if(s.push(...Cn(n.buffer.slice(0,e),n)),n.buffer=n.buffer.slice(e+yo.length),n.inThinking=!1,n.thinkingExtracted=!0,s.push(...Cn("",n)),s.push(...Rs(n.thinkingBlockIndex,n)),n.buffer.startsWith(`
127
+ ${_}`:_;if(r&&!u.includes("<thinking_mode>")){let R=`<thinking_mode>enabled</thinking_mode><max_thinking_length>${i}</max_thinking_length>`;u=u?`${R}
128
+ ${u}`:R}let l=h.at(-1);if(l?.role==="assistant"&&Bt(l)==="{")h.pop();let w=h.at(-1);if(!w)throw Error("Empty");let A=Ng(h,f),M=w.role==="user"&&!(Array.isArray(w.content)&&w.content.some((R)=>wn(R)&&R.type==="tool_result")),E=h.at(-2);if(M&&E?.role==="assistant"&&A.at(-1)?.userInputMessage){let R=Bt(E);if(R)A.push({assistantResponseMessage:{content:R}})}A=Wg(A,u,f);let d="[system: conversation continues]",T=[],U=[];if(w.role==="assistant")v7(A,w);else{if(A.at(-1)&&!A.at(-1)?.assistantResponseMessage)A.push({assistantResponseMessage:{content:"[system: conversation continues]"}});let R=t9(w);d=R.content,T=R.toolResults,U=R.images}let S=A.flatMap((R)=>R.assistantResponseMessage?.toolUses??[]),O=new Set(S.map((R)=>R.toolUseId)),D=[],q=[];for(let R of T)if(O.has(R.toolUseId))D.push(R);else{let W=n9(e.messages,R);if(W)q.push({call:W,result:R});else d+=`
130
129
 
131
- `))n.buffer=n.buffer.slice(2);continue}let i=Math.max(0,n.buffer.length-yo.length);if(i>0)s.push(...Cn(n.buffer.slice(0,i),n)),n.buffer=n.buffer.slice(i);break}let r=n.buffer;n.buffer="",s.push(...qn(r,n))}return s}function Jd(t){if(!t.buffer)return[];let n=t.buffer;if(t.buffer="",!t.inThinking)return qn(n,t);return[...Cn(n,t),...Cn("",t),...Rs(t.thinkingBlockIndex,t)]}class zd extends Error{name="MissingSdkEventStreamError";constructor(){super("SDK response has no event stream")}}async function*kd(t,n,s,r){let e=t.generateAssistantResponseResponse;if(!e)throw new zd;let i={thinkingRequested:!0,buffer:"",inThinking:!1,thinkingExtracted:!1,thinkingBlockIndex:null,textBlockIndex:null,nextBlockIndex:0,stoppedBlocks:new Set},f=new ph,o=new Map,c={},h=e[Symbol.asyncIterator](),u="",l=!1,_=!1,w=!1,A=!1,M=(S,O=!1)=>{if(O&&S.type==="content_block_delta"&&S.delta?.type==="text_delta"){let x=f.push(S.delta.text??"");if(!x)return null;return vh({...S,delta:{...S.delta,text:x}},s,n)}return vh(S,s,n)};try{while(!0){let S=await $o(h,r);if(S.kind==="aborted"){if(h.return)await h.return();A=!0;return}if(S.result.done){w=!0;break}let O=S.result.value;Uo(c,O);let x=O.reasoningContentEvent?.text;if(x){if(_)i.thinkingBlockIndex=null,_=!1;l=!0;for(let v of Cn(x,i)){let Q=M(v);if(Q)yield Q}continue}let X=O.assistantResponseEvent?.content;if(X){if(u+=X,l&&!_){for(let Q of Rs(i.thinkingBlockIndex,i)){let rt=M(Q);if(rt)yield rt}_=!0}let v=l?qn(X,i):Qd(X,i);for(let Q of v){let rt=M(Q,!0);if(rt)yield rt}continue}if(O.toolUseEvent)Me(o,O.toolUseEvent)}}finally{if(!w&&!A&&h.return)await h.return()}if(l&&!_)for(let S of Rs(i.thinkingBlockIndex,i)){let O=M(S);if(O)yield O}for(let S of Jd(i)){let O=M(S,S.delta?.type==="text_delta");if(O)yield O}let{toolCalls:d,remainderText:E}=f.finalize();for(let S of qn(E,i)){let O=M(S);if(O)yield O}for(let S of Rs(i.textBlockIndex,i)){let O=M(S);if(O)yield O}for(let S of d)Me(o,{toolUseId:S.toolUseId,name:S.name,input:typeof S.input==="string"?S.input:JSON.stringify(S.input),stop:!0});for(let S of yd(o)){let O=M(S);if(O)yield O}let b=Lo(c,u,n),L=M({type:"message_delta",delta:{type:"message_delta",stop_reason:o.size>0?"tool_use":"end_turn"},usage:{input_tokens:b.inputTokens,output_tokens:b.outputTokens,cache_creation_input_tokens:0,cache_read_input_tokens:0}});if(L)yield L;M({type:"message_stop"})}class Xd extends Error{timeoutMs;name="StreamIdleTimeoutError";constructor(t){super(`SDK stream idle timeout after ${t}ms`);this.timeoutMs=t}}function qd(t,n,s,r){let e=new AbortController,i=AbortSignal.any([n,e.signal]),f=kd(t.sdkResponse,t.model,t.conversationId,i)[Symbol.asyncIterator](),o=new TextEncoder,c=!1,h,u=()=>{if(h===void 0)return;clearTimeout(h),h=void 0},l=()=>{if(c)return;c=!0,r()},_=async()=>{await f.return?.(void 0)};return new Response(new ReadableStream({async pull(w){let A;try{let M=await Promise.race([f.next(),new Promise((d,E)=>{let b=()=>{u(),E(Ln(i))};if(A=()=>i.removeEventListener("abort",b),i.addEventListener("abort",b,{once:!0}),h=setTimeout(()=>{h=void 0,E(new Xd(s))},s),i.aborted)b()})]);if(i.aborted)throw Ln(i);if(M.done){w.close(),l();return}w.enqueue(o.encode(`${JSON.stringify(M.value)}
132
- `))}catch(M){if(u(),A?.(),e.signal.aborted)return;let d=M instanceof Error?M:TypeError("SDK stream failed with a non-Error reason",{cause:M});e.abort(d),w.error(d);try{await _()}finally{l()}}finally{u(),A?.()}},async cancel(){u(),e.abort();try{await _()}catch{return}finally{l()}}}),{headers:{"Content-Type":"application/x-ndjson; charset=utf-8"}})}var ad=H(Ni(),1);var Cd=new Map,CW=3;function Go(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function aW(t){let n=t.conversationState;if(!Go(n))return;let s=n.currentMessage;if(!Go(s))return;let r=s.userInputMessage;if(!Go(r))return;let e=r.modelId;return typeof e==="string"?e:void 0}function KW(t,n,s,r){let e=r?(()=>{let i=Yu(r);return new ad.NodeHttpHandler({httpAgent:i,httpsAgent:i})})():void 0;return{region:n,endpoint:s,token:()=>Promise.resolve({token:t.access}),maxAttempts:CW,retryMode:"standard",customUserAgent:[[st.USER_AGENT]],...e?{requestHandler:e}:{}}}function Kd(t,n,s,r,e){let i=r??`https://q.${n}.amazonaws.com`,f=JSON.stringify([n,t.email??null,s??null,i,e??null]),o=Cd.get(f);if(o?.token===t.access)return o.client;let c=new Xh(KW(t,n,i,e));if(c.middlewareStack.add((h)=>async(u)=>{if(u.request instanceof It.HttpRequest)u.request.headers["x-amzn-kiro-agent-mode"]="vibe";return h(u)},{step:"build",name:"addKiroHeaders"}),s)c.middlewareStack.add((h)=>async(u)=>{if(u.request instanceof It.HttpRequest&&typeof u.request.body==="string")try{let l=JSON.parse(u.request.body);if(Go(l)){let _=aW(l);if(_)l.additionalModelRequestFields=Md(_,s),u.request.body=JSON.stringify(l)}}catch(l){if(!(l instanceof SyntaxError))throw l}return h(u)},{step:"build",name:"addEffortConfig",priority:"high"});return Cd.set(f,{client:c,token:t.access}),c}function bs(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function VW(t){if(!bs(t))return!1;let n=t.conversationState;return bs(n)&&typeof n.conversationId==="string"&&bs(n.currentMessage)&&typeof n.chatTriggerType==="string"}function jW(t,n){let s=typeof t==="string"?JSON.parse(t):t;if(!bs(s))return{think:n.endsWith("-thinking"),budget:20000};let r=s.providerOptions,e=bs(r)?r.thinkingConfig:void 0,i=s.thinkingConfig,f=bs(e)?e:bs(i)?i:void 0,o=f?.thinkingBudget??f?.budget_tokens;return{think:n.endsWith("-thinking")||f!==void 0,budget:typeof o==="number"?o:20000}}function pW(t,n,s){return Z(t,n,"upstream_error",s)}async function vW(t,n){let{think:s,budget:r}=jW(t.body,t.model),e=new Set,i=new Map,f=0,o=0;while(!0){if(n.aborted)throw Ln(n);if(o+=1,o>t.config.max_request_iterations)return{kind:"response",response:Z(500,`Exceeded max iterations (${t.config.max_request_iterations})`,"request_error","max_request_iterations")};t.accountManager.reconcileFromDb();let c=t.accountManager.selectHealthyAccount();if(!c)return{kind:"response",response:Z(503,"All accounts are unhealthy or rate-limited","service_unavailable","no_healthy_accounts")};let h=t.accountManager.toAuthDetails(c),u=await _r(t.tokenRefresher.refreshIfNeeded(c,h,n),n),l=t.accountManager.toAuthDetails(u),_=Se.safeParse(t.config.effort),w=Id(t.body,t.model,l,s,r,{autoEffortMapping:t.config.auto_effort_mapping,..._.success?{effort:_.data}:{}}),M=(t.makeClient??Kd)(l,w.region,w.effort,t.config.test_upstream_endpoint,xs(t.config)),d={conversationState:w.conversationState,...w.profileArn?{profileArn:w.profileArn}:{}};if(!VW(d))throw TypeError("Transformed request is not a valid SDK command input");let E=new qh(d);try{let b=await _r(M.send(E,{abortSignal:n}),n);if(t.stream)return{kind:"stream",sdkResponse:b,model:t.model,conversationId:w.conversationId};let L=await Bd(b,t.model,w.conversationId,n);if(n.aborted)throw Ln(n);return{kind:"response",response:Response.json(L,{headers:{"Content-Type":"application/json"}})}}catch(b){if(n.aborted)throw Ln(n);let L=Kh(b),S=L.status===500?(i.get(u.id)??0)+1:0;if(L.status===500)i.set(u.id,S);let O=md(L,{accountId:u.id,accountCount:t.accountManager.getAccountCount(),retryCount:f,maxRetries:t.config.rate_limit_max_retries,serverErrorCount:S,retryDelayMs:t.config.rate_limit_retry_delay_ms,forcedRefreshAccountIds:e});switch(O.action){case"refresh-then-retry":await _r(t.tokenRefresher.forceRefresh(u,n),n);continue;case"retry":f+=1,await Pd(O.retryAfterMs??0,n);continue;case"switch":if(L.reason==="TEMPORARILY_SUSPENDED")t.accountManager.markUnhealthy(u,`InvalidTokenException: Account Suspended: ${L.message}`);else t.accountManager.markRateLimited(u,Date.now()+(O.retryAfterMs??t.config.rate_limit_retry_delay_ms));continue;case"fail":if(L.reason==="TEMPORARILY_SUSPENDED")t.accountManager.markUnhealthy(u,`InvalidTokenException: Account Suspended: ${L.message}`);return{kind:"response",response:pW(O.terminalStatus??O.status??500,L.message,L.code)}}}}}async function Vd(t){let n=Nd(t.deadlineSignal,t.config.request_timeout_ms),s,r=!1;try{s=await Hd(n.signal);let e=await vW(t,n.signal);if(e.kind==="response")return e.response;let i=s;return s=void 0,r=!0,qd(e,n.signal,t.config.stream_idle_timeout_ms,()=>{i(),n.dispose()})}catch(e){if(n.signal.aborted)return Z(504,"Request deadline exceeded","timeout_error","request_timeout");let i=Kh(e);return Z(500,i.message,"internal_error",i.code)}finally{if(!r)s?.(),n.dispose()}}var ge=Object.freeze({input:Object.freeze(["text"]),output:Object.freeze(["text"])}),ft=Object.freeze({input:Object.freeze(["text","image"]),output:Object.freeze(["text"])}),C=Object.freeze({input:Object.freeze(["text","image","pdf"]),output:Object.freeze(["text"])}),jd=Object.freeze(["auto","claude-sonnet-4","claude-sonnet-4-5","claude-sonnet-4-6","claude-sonnet-4-6-low","claude-sonnet-4-6-medium","claude-sonnet-4-6-high","claude-sonnet-4-6-max","claude-sonnet-5","claude-sonnet-5-low","claude-sonnet-5-medium","claude-sonnet-5-high","claude-sonnet-5-xhigh","claude-sonnet-5-max","claude-haiku-4-5","claude-opus-4-5","claude-opus-4-6","claude-opus-4-7","claude-opus-4-7-low","claude-opus-4-7-medium","claude-opus-4-7-high","claude-opus-4-7-xhigh","claude-opus-4-7-max","claude-opus-4-8","claude-opus-4-8-low","claude-opus-4-8-medium","claude-opus-4-8-high","claude-opus-4-8-xhigh","claude-opus-4-8-max","claude-opus-4-8-thinking","deepseek-3.2","glm-5","minimax-m2.5","minimax-m2.1","qwen3-coder-next","gpt-5.6-sol","gpt-5.6-sol-low","gpt-5.6-sol-medium","gpt-5.6-sol-high","gpt-5.6-sol-xhigh","gpt-5.6-sol-max","gpt-5.6-terra","gpt-5.6-terra-low","gpt-5.6-terra-medium","gpt-5.6-terra-high","gpt-5.6-terra-xhigh","gpt-5.6-terra-max","gpt-5.6-luna","gpt-5.6-luna-low","gpt-5.6-luna-medium","gpt-5.6-luna-high","gpt-5.6-luna-xhigh","gpt-5.6-luna-max"]),pd=Object.freeze([{id:"auto",wireId:"auto",name:"Auto (1.0x)",contextLimit:G("auto"),outputLimit:64000,modalities:C},{id:"claude-sonnet-4",wireId:"claude-sonnet-4",name:"Claude Sonnet 4.0 (1.3x)",contextLimit:G("claude-sonnet-4"),outputLimit:64000,modalities:C},{id:"claude-sonnet-4-5",wireId:"claude-sonnet-4.5",name:"Claude Sonnet 4.5 (1.3x)",contextLimit:G("claude-sonnet-4-5"),outputLimit:64000,modalities:C},{id:"claude-sonnet-4-6",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (1.3x)",contextLimit:G("claude-sonnet-4-6"),outputLimit:64000,modalities:C},{id:"claude-sonnet-4-6-low",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (low) (1.3x)",contextLimit:G("claude-sonnet-4-6"),outputLimit:64000,modalities:C},{id:"claude-sonnet-4-6-medium",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (medium) (1.3x)",contextLimit:G("claude-sonnet-4-6"),outputLimit:64000,modalities:C},{id:"claude-sonnet-4-6-high",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (high) (1.3x)",contextLimit:G("claude-sonnet-4-6"),outputLimit:64000,modalities:C},{id:"claude-sonnet-4-6-max",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (max) (1.3x)",contextLimit:G("claude-sonnet-4-6"),outputLimit:64000,modalities:C},{id:"claude-sonnet-5",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (1.3x)",contextLimit:G("claude-sonnet-5"),outputLimit:64000,modalities:C},{id:"claude-sonnet-5-low",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (low) (1.3x)",contextLimit:G("claude-sonnet-5"),outputLimit:64000,modalities:C},{id:"claude-sonnet-5-medium",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (medium) (1.3x)",contextLimit:G("claude-sonnet-5"),outputLimit:64000,modalities:C},{id:"claude-sonnet-5-high",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (high) (1.3x)",contextLimit:G("claude-sonnet-5"),outputLimit:64000,modalities:C},{id:"claude-sonnet-5-xhigh",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (xhigh) (1.3x)",contextLimit:G("claude-sonnet-5"),outputLimit:64000,modalities:C},{id:"claude-sonnet-5-max",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (max) (1.3x)",contextLimit:G("claude-sonnet-5"),outputLimit:64000,modalities:C},{id:"claude-haiku-4-5",wireId:"claude-haiku-4.5",name:"Claude Haiku 4.5 (0.4x)",contextLimit:G("claude-haiku-4-5"),outputLimit:64000,modalities:ft},{id:"claude-opus-4-5",wireId:"claude-opus-4.5",name:"Claude Opus 4.5 (2.2x)",contextLimit:G("claude-opus-4-5"),outputLimit:64000,modalities:C},{id:"claude-opus-4-6",wireId:"claude-opus-4.6",name:"Claude Opus 4.6 (2.2x)",contextLimit:G("claude-opus-4-6"),outputLimit:64000,modalities:C},{id:"claude-opus-4-7",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (2.2x)",contextLimit:G("claude-opus-4-7"),outputLimit:64000,modalities:C},{id:"claude-opus-4-7-low",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (low) (2.2x)",contextLimit:G("claude-opus-4-7"),outputLimit:64000,modalities:C},{id:"claude-opus-4-7-medium",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (medium) (2.2x)",contextLimit:G("claude-opus-4-7"),outputLimit:64000,modalities:C},{id:"claude-opus-4-7-high",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (high) (2.2x)",contextLimit:G("claude-opus-4-7"),outputLimit:64000,modalities:C},{id:"claude-opus-4-7-xhigh",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (xhigh) (2.2x)",contextLimit:G("claude-opus-4-7"),outputLimit:64000,modalities:C},{id:"claude-opus-4-7-max",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (max) (2.2x)",contextLimit:G("claude-opus-4-7"),outputLimit:64000,modalities:C},{id:"claude-opus-4-8",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (2.2x)",contextLimit:G("claude-opus-4-8"),outputLimit:64000,modalities:C},{id:"claude-opus-4-8-low",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (low) (2.2x)",contextLimit:G("claude-opus-4-8"),outputLimit:64000,modalities:C},{id:"claude-opus-4-8-medium",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (medium) (2.2x)",contextLimit:G("claude-opus-4-8"),outputLimit:64000,modalities:C},{id:"claude-opus-4-8-high",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (high) (2.2x)",contextLimit:G("claude-opus-4-8"),outputLimit:64000,modalities:C},{id:"claude-opus-4-8-xhigh",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (xhigh) (2.2x)",contextLimit:G("claude-opus-4-8"),outputLimit:64000,modalities:C},{id:"claude-opus-4-8-max",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (max) (2.2x)",contextLimit:G("claude-opus-4-8"),outputLimit:64000,modalities:C},{id:"claude-opus-4-8-thinking",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 Thinking (2.2x)",contextLimit:G("claude-opus-4-8"),outputLimit:64000,modalities:C},{id:"deepseek-3.2",wireId:"deepseek-3.2",name:"DeepSeek 3.2 (0.25x)",contextLimit:G("deepseek-3.2"),outputLimit:64000,modalities:ge},{id:"glm-5",wireId:"glm-5",name:"GLM-5 (0.5x)",contextLimit:G("glm-5"),outputLimit:64000,modalities:ge},{id:"minimax-m2.5",wireId:"minimax-m2.5",name:"MiniMax M2.5 (0.25x)",contextLimit:G("minimax-m2.5"),outputLimit:64000,modalities:ge},{id:"minimax-m2.1",wireId:"minimax-m2.1",name:"MiniMax M2.1 (0.15x)",contextLimit:G("minimax-m2.1"),outputLimit:64000,modalities:ge},{id:"qwen3-coder-next",wireId:"qwen3-coder-next",name:"Qwen3 Coder Next (0.05x)",contextLimit:G("qwen3-coder-next"),outputLimit:64000,modalities:ge},{id:"gpt-5.6-sol",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (2.4x)",contextLimit:G("gpt-5.6-sol"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-sol-low",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (low) (2.4x)",contextLimit:G("gpt-5.6-sol"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-sol-medium",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (medium) (2.4x)",contextLimit:G("gpt-5.6-sol"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-sol-high",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (high) (2.4x)",contextLimit:G("gpt-5.6-sol"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-sol-xhigh",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (xhigh) (2.4x)",contextLimit:G("gpt-5.6-sol"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-sol-max",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (max) (2.4x)",contextLimit:G("gpt-5.6-sol"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-terra",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (1.2x)",contextLimit:G("gpt-5.6-terra"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-terra-low",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (low) (1.2x)",contextLimit:G("gpt-5.6-terra"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-terra-medium",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (medium) (1.2x)",contextLimit:G("gpt-5.6-terra"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-terra-high",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (high) (1.2x)",contextLimit:G("gpt-5.6-terra"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-terra-xhigh",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (xhigh) (1.2x)",contextLimit:G("gpt-5.6-terra"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-terra-max",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (max) (1.2x)",contextLimit:G("gpt-5.6-terra"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-luna",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna",contextLimit:G("gpt-5.6-luna"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-luna-low",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (low)",contextLimit:G("gpt-5.6-luna"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-luna-medium",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (medium)",contextLimit:G("gpt-5.6-luna"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-luna-high",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (high)",contextLimit:G("gpt-5.6-luna"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-luna-xhigh",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (xhigh)",contextLimit:G("gpt-5.6-luna"),outputLimit:64000,modalities:ft},{id:"gpt-5.6-luna-max",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (max)",contextLimit:G("gpt-5.6-luna"),outputLimit:64000,modalities:ft}]);var vd=g.record(g.unknown()),ZW=new Set(jd),t7=g.object({type:g.literal("text"),text:g.string()}).passthrough(),n7=g.object({type:g.literal("image_url"),image_url:g.object({url:g.string(),detail:g.string().optional()}).passthrough()}).passthrough(),s7=g.object({type:g.literal("image"),source:g.object({type:g.string(),data:g.string(),media_type:g.string().optional()}).passthrough()}).passthrough(),r7=g.object({type:g.literal("tool_result"),tool_use_id:g.string().min(1),content:g.unknown()}).passthrough(),e7=g.object({type:g.literal("tool_use"),id:g.string().min(1),name:g.string().min(1),input:g.unknown()}).passthrough(),i7=g.object({type:g.literal("thinking"),thinking:g.string().optional(),text:g.string().optional()}).passthrough(),o7=g.discriminatedUnion("type",[t7,n7,s7,r7,e7,i7]),Bo=g.union([g.string(),g.array(o7)]);function f7(t){try{return JSON.parse(t),!0}catch(n){if(n instanceof SyntaxError)return!1;throw n}}var c7=g.object({id:g.string().min(1),type:g.literal("function"),function:g.object({name:g.string().min(1),arguments:g.string().refine(f7,"function arguments must contain valid JSON")}).passthrough()}).passthrough(),h7=g.object({role:g.literal("system"),content:Bo}).passthrough(),u7=g.object({role:g.literal("user"),content:Bo}).passthrough(),l7=g.object({role:g.literal("assistant"),content:Bo.nullable().optional(),tool_calls:g.array(c7).min(1).optional()}).passthrough().refine((t)=>t.content!==null&&t.content!==void 0?!0:t.tool_calls!==void 0,{message:"assistant message requires content or tool_calls"}),_7=g.object({role:g.literal("tool"),content:Bo,tool_call_id:g.string().min(1)}).passthrough(),w7=g.union([h7,u7,l7,_7]),A7=g.object({type:g.literal("function"),function:g.object({name:g.string().min(1),description:g.string().optional(),parameters:vd.optional()}).passthrough()}).passthrough(),M7=g.object({name:g.string().min(1),description:g.string().optional(),input_schema:vd.optional()}).passthrough(),d7=g.object({model:g.string().refine((t)=>ZW.has(t),{message:"model is not supported"}),stream:g.boolean().default(!1),messages:g.array(w7).min(1),tools:g.array(g.union([A7,M7])).optional(),reasoning_effort:g.enum(["low","medium","high","xhigh","max"]).optional()}).passthrough();function Zd(t){let n=d7.safeParse(t);if(n.success)return{ok:!0,value:n.data};let s=n.error.issues.map((r)=>{return`${r.path.length>0?r.path.join("."):"request"}: ${r.message}`}).join(", ");return{ok:!1,response:Z(400,`Invalid request: ${s}`,"invalid_request_error","invalid_request")}}class nu extends Error{limit;name="RequestBodyTooLargeError";constructor(t){super(`Request body exceeds the ${t} byte limit`);this.limit=t}}function tu(t){return t.reason instanceof Error?t.reason:new DOMException("Request deadline exceeded","TimeoutError")}async function g7(t,n,s){let r=t.body?.getReader();if(!r)return{ok:!0,text:""};let e=[],i=0,f,o=new Promise((h,u)=>{f=u}),c=()=>{let h=tu(s.combined);f?.(h),r.cancel(h)};s.combined.addEventListener("abort",c,{once:!0});try{while(!0){if(s.combined.aborted)throw tu(s.combined);let l=await Promise.race([r.read(),o]);if(s.combined.aborted)throw tu(s.combined);if(l.done)break;if(i+=l.value.byteLength,i>n)throw new nu(n);e.push(l.value)}let h=new Uint8Array(i),u=0;for(let l of e)h.set(l,u),u+=l.byteLength;return{ok:!0,text:new TextDecoder().decode(h)}}catch(h){if(h instanceof nu)return r.cancel(h).catch(()=>{return}),{ok:!1,response:Z(413,h.message,"invalid_request_error","request_too_large")};if(s.deadline.aborted)return r.cancel(h).catch(()=>{return}),{ok:!1,response:Z(504,"Request deadline exceeded","timeout_error","request_timeout")};if(s.client.aborted)return r.cancel(h).catch(()=>{return}),{ok:!1,response:Z(499,"Client closed request","request_aborted","client_disconnected")};throw h}finally{s.combined.removeEventListener("abort",c)}}function E7(t,n){let s=t.body;if(!s)return t;let r=s.getReader(),e=new TextDecoder,i=new TextEncoder,f="",o=!1,c=!1,h=()=>{if(c)return;c=!0,n()};return new Response(new ReadableStream({async pull(u){try{while(!0){let l=f.indexOf(`
133
- `);if(l>=0){let A=f.slice(0,l).trimEnd();if(f=f.slice(l+1),A.length>0){u.enqueue(i.encode(`data: ${A}
130
+ [Output for tool call ${R.toolUseId}]:
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(`
134
132
 
135
- `));return}continue}let _=await r.read();if(!_.done){f+=e.decode(_.value,{stream:!0});continue}f+=e.decode();let w=f.trim();if(f="",w.length>0){u.enqueue(i.encode(`data: ${w}
133
+ `))n.buffer=n.buffer.slice(2);continue}let e=Math.max(0,n.buffer.length-Fo.length);if(e>0)s.push(...Kn(n.buffer.slice(0,e),n)),n.buffer=n.buffer.slice(e);break}let r=n.buffer;n.buffer="",s.push(...Cn(r,n))}return s}function tE(t){if(!t.buffer)return[];let n=t.buffer;if(t.buffer="",!t.inThinking)return Cn(n,t);return[...Kn(n,t),...Kn("",t),...Rs(t.thinkingBlockIndex,t)]}class nE extends Error{name="MissingSdkEventStreamError";constructor(){super("SDK response has no event stream")}}async function*sE(t,n,s,r){let i=t.generateAssistantResponseResponse;if(!i)throw new nE;let e={thinkingRequested:!0,buffer:"",inThinking:!1,thinkingExtracted:!1,thinkingBlockIndex:null,textBlockIndex:null,nextBlockIndex:0,stoppedBlocks:new Set},f=new i0,o=new Map,c={},h=i[Symbol.asyncIterator](),u="",_=!1,l=!1,w=!1,A=!1,M=(S,O=!1)=>{if(O&&S.type==="content_block_delta"&&S.delta?.type==="text_delta"){let D=f.push(S.delta.text??"");if(!D)return null;return e0({...S,delta:{...S.delta,text:D}},s,n)}return e0(S,s,n)};try{while(!0){let S=await Io(h,r);if(S.kind==="aborted"){if(h.return)await h.return();A=!0;return}if(S.result.done){w=!0;break}let O=S.result.value;Oo(c,O);let D=O.reasoningContentEvent?.text;if(D){if(l)e.thinkingBlockIndex=null,l=!1;_=!0;for(let tt of Kn(D,e)){let J=M(tt);if(J)yield J}continue}let q=O.assistantResponseEvent?.content;if(q){if(u+=q,_&&!l){for(let J of Rs(e.thinkingBlockIndex,e)){let G=M(J);if(G)yield G}l=!0}let tt=_?Cn(q,e):vg(q,e);for(let J of tt){let G=M(J,!0);if(G)yield G}continue}if(O.toolUseEvent)Ei(o,O.toolUseEvent)}}finally{if(!w&&!A&&h.return)await h.return()}if(_&&!l)for(let S of Rs(e.thinkingBlockIndex,e)){let O=M(S);if(O)yield O}for(let S of tE(e)){let O=M(S,S.delta?.type==="text_delta");if(O)yield O}let{toolCalls:E,remainderText:d}=f.finalize();for(let S of Cn(d,e)){let O=M(S);if(O)yield O}for(let S of Rs(e.textBlockIndex,e)){let O=M(S);if(O)yield O}for(let S of E)Ei(o,{toolUseId:S.toolUseId,name:S.name,input:typeof S.input==="string"?S.input:JSON.stringify(S.input),stop:!0});for(let S of kg(o)){let O=M(S);if(O)yield O}let T=yo(c,u,n),U=M({type:"message_delta",delta:{type:"message_delta",stop_reason:o.size>0?"tool_use":"end_turn"},usage:{input_tokens:T.inputTokens,output_tokens:T.outputTokens,cache_creation_input_tokens:0,cache_read_input_tokens:0}});if(U)yield U;M({type:"message_stop"})}class rE extends Error{timeoutMs;name="StreamIdleTimeoutError";constructor(t){super(`SDK stream idle timeout after ${t}ms`);this.timeoutMs=t}}function iE(t,n,s,r){let i=new AbortController,e=AbortSignal.any([n,i.signal]),f=sE(t.sdkResponse,t.model,t.conversationId,e)[Symbol.asyncIterator](),o=new TextEncoder,c=!1,h,u=()=>{if(h===void 0)return;clearTimeout(h),h=void 0},_=()=>{if(c)return;c=!0,r()},l=async()=>{await f.return?.(void 0)};return new Response(new ReadableStream({async pull(w){let A;try{let M=await Promise.race([f.next(),new Promise((E,d)=>{let T=()=>{u(),d(In(e))};if(A=()=>e.removeEventListener("abort",T),e.addEventListener("abort",T,{once:!0}),h=setTimeout(()=>{h=void 0,d(new rE(s))},s),e.aborted)T()})]);if(e.aborted)throw In(e);if(M.done){w.close(),_();return}w.enqueue(o.encode(`${JSON.stringify(M.value)}
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}
136
136
 
137
- `));return}if(!o){o=!0,u.enqueue(i.encode(`data: [DONE]
137
+ `));return}continue}let l=await r.read();if(!l.done){f+=i.decode(l.value,{stream:!0});continue}f+=i.decode();let w=f.trim();if(f="",w.length>0){u.enqueue(e.encode(`data: ${w}
138
138
 
139
- `));return}u.close(),h();return}}catch{let l=JSON.stringify({error:{message:"Upstream stream error",type:"upstream_error"}});u.enqueue(i.encode(`data: ${l}
139
+ `));return}if(!o){o=!0,u.enqueue(e.encode(`data: [DONE]
140
140
 
141
- `)),u.close(),h()}},cancel(u){r.cancel(u).catch(()=>{return}),h()}}),{status:t.status,headers:{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive"}})}async function tg(t,n,s){let r=new AbortController,e=setTimeout(()=>r.abort(new DOMException("Request deadline exceeded","TimeoutError")),n.request_timeout_ms),i=AbortSignal.any([r.signal,t.signal]),f={combined:i,deadline:r.signal,client:t.signal},o=await g7(t,n.max_request_body_bytes,f);if(!o.ok)return clearTimeout(e),o.response;let c;try{c=JSON.parse(o.text)}catch(_){if(clearTimeout(e),!(_ instanceof SyntaxError))throw _;return Z(400,"Request body must contain valid JSON","invalid_request_error","invalid_json")}let h=Zd(c);if(!h.ok)return clearTimeout(e),h.response;let u=await Vd({body:h.value,model:h.value.model,stream:h.value.stream,config:n,accountManager:s.accountManager,tokenRefresher:s.tokenRefresher,deadlineSignal:i,...s.makeClient?{makeClient:s.makeClient}:{}});if(t.signal.aborted&&!r.signal.aborted)return clearTimeout(e),Z(499,"Client closed request","request_aborted","client_disconnected");let l=u.headers.get("Content-Type")??"";if(!h.value.stream||l.includes("application/json"))return clearTimeout(e),u;if(!l.includes("application/x-ndjson"))return clearTimeout(e),Z(500,"Pipeline returned an unsupported streaming response","internal_error","invalid_pipeline_response");return E7(u,()=>clearTimeout(e))}function ng(){return new Response(JSON.stringify({status:"ok"}),{status:200,headers:{"Content-Type":"application/json"}})}var R7=1700000000;function sg(){let t=pd.map((n)=>({id:n.id,object:"model",created:R7,owned_by:"kiro",name:n.name,context_limit:n.contextLimit,output_limit:n.outputLimit,modalities:n.modalities}));return new Response(JSON.stringify({object:"list",data:t}),{status:200,headers:{"Content-Type":"application/json"}})}function b7(t,n){return async(s)=>{let r=au(s,t.api_keys);if(!r.ok)return r.response;let e=new URL(s.url);try{if(s.method==="POST"&&e.pathname==="/v1/chat/completions")return await tg(s,t,n);if(s.method==="GET"&&e.pathname==="/v1/models")return sg();if(s.method==="GET"&&e.pathname==="/health")return ng();return Z(404,"Route not found","invalid_request_error","not_found")}catch(i){let f=i instanceof Error?i.message:"Internal server error";return Z(500,f,"internal_error","internal_error")}}}function T7(t,n={}){let s=n.createDatabase?.()??new rs,r=new Yo(s.getAccounts(),t.account_selection_strategy,s),e=xs(t),i=n.createTokenRefresher?n.createTokenRefresher(r,t.token_expiry_buffer_ms,e):new ao(r,t.token_expiry_buffer_ms,e);return{accountManager:r,tokenRefresher:i}}function rg(t){return Bun.serve({hostname:t.host,port:t.port,fetch:b7(t,T7(t))})}import{parseArgs as su}from"util";var mo=`Usage: kiro-provider <command> [options]
141
+ `));return}u.close(),h();return}}catch{let _=JSON.stringify({error:{message:"Upstream stream error",type:"upstream_error"}});u.enqueue(e.encode(`data: ${_}
142
+
143
+ `)),u.close(),h()}},cancel(u){r.cancel(u).catch(()=>{return}),h()}}),{status:t.status,headers:{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive"}})}async function lE(t,n,s){let r=new AbortController,i=setTimeout(()=>r.abort(new DOMException("Request deadline exceeded","TimeoutError")),n.request_timeout_ms),e=AbortSignal.any([r.signal,t.signal]),f={combined:e,deadline:r.signal,client:t.signal},o=await iY(t,n.max_request_body_bytes,f);if(!o.ok)return clearTimeout(i),o.response;let c;try{c=JSON.parse(o.text)}catch(l){if(clearTimeout(i),!(l instanceof SyntaxError))throw l;return V(400,"Request body must contain valid JSON","invalid_request_error","invalid_json")}let h=Wo(c);if(!h.ok)return clearTimeout(i),h.response;let u=await Po({body:h.value,model:h.value.model,stream:h.value.stream,config:n,accountManager:s.accountManager,tokenRefresher:s.tokenRefresher,deadlineSignal:e,...s.makeClient?{makeClient:s.makeClient}:{}});if(t.signal.aborted&&!r.signal.aborted)return clearTimeout(i),V(499,"Client closed request","request_aborted","client_disconnected");let _=u.headers.get("Content-Type")??"";if(!h.value.stream||_.includes("application/json"))return clearTimeout(i),u;if(!_.includes("application/x-ndjson"))return clearTimeout(i),V(500,"Pipeline returned an unsupported streaming response","internal_error","invalid_pipeline_response");return eY(u,()=>clearTimeout(i))}function wE(){return new Response(JSON.stringify({status:"ok"}),{status:200,headers:{"Content-Type":"application/json"}})}var oY=1700000000;function AE(){let t=hE.map((n)=>({id:n.id,object:"model",created:oY,owned_by:"kiro",name:n.name,context_limit:n.contextLimit,output_limit:n.outputLimit,modalities:n.modalities}));return new Response(JSON.stringify({object:"list",data:t}),{status:200,headers:{"Content-Type":"application/json"}})}import{randomUUID as l0}from"crypto";function fY(t){return t.type==="message"}function cY(t){return t.type==="function_call"}function hY(t){return t.type==="function_call_output"}function uY(t){return t.type==="reasoning"}function _Y(t,n){let s=[];for(let r of t){if((r.type==="input_text"||r.type==="output_text")&&"text"in r&&typeof r.text==="string"){s.push({type:"text",text:r.text});continue}if(r.type==="input_image"&&"image_url"in r&&typeof r.image_url==="string"){s.push({type:"image_url",image_url:{url:r.image_url}});continue}n.count++}return s}function lY(t){return[...(t.summary??[]).map((n)=>n.text),...(t.content??[]).map((n)=>n.reasoning_text)].filter((n)=>n.length>0).join(`
144
+ `)}function wY(t){if(t==="minimal")return"low";if(t==="low"||t==="medium"||t==="high"||t==="xhigh")return t;return}function u0(t){return{type:"thinking",thinking:t}}function ME(t){let n=[],s={count:0},r=0,i=!1,e="";if(t.instructions&&t.instructions.length>0)n.push({role:"system",content:t.instructions});if(typeof t.input==="string")n.push({role:"user",content:t.input}),i=!0;else{let c=()=>{if(!e)return;n.push({role:"assistant",content:[u0(e)]}),e="",i=!0};for(let h of t.input){if(uY(h)){let u=lY(h);if(u)e=e?`${e}
145
+ ${u}`:u;continue}if(cY(h)){n.push({role:"assistant",...e?{content:[u0(e)]}:{},tool_calls:[{id:h.call_id,type:"function",function:{name:h.name,arguments:h.arguments}}]}),e="",i=!0;continue}if(fY(h)){if(h.role!=="assistant")c();let u=_Y(h.content,s);if(h.role==="assistant")n.push({role:"assistant",content:e?[u0(e),...u]:u}),e="",i=!0;else if(n.push({role:h.role,content:u}),h.role==="user")i=!0;continue}if(hY(h)){c(),n.push({role:"tool",tool_call_id:h.call_id,content:h.output}),i=!0;continue}c(),r++}c()}if(s.count,!i)return{ok:!1,code:"empty_input"};let f=wY(t.reasoning?.effort);return{ok:!0,body:{model:t.model,stream:t.stream,messages:n,...t.tools?{tools:t.tools.map((c)=>({type:"function",function:{name:c.name,...c.description!==void 0?{description:c.description}:{},...c.parameters!==void 0?{parameters:c.parameters}:{}}}))}:{},...t.tool_choice!==void 0?{tool_choice:t.tool_choice}:{},...f!==void 0?{reasoning_effort:f}:{}}}}import{randomUUID as Yo}from"crypto";function gE(t){return{type:"response.created",sequence_number:t.sequenceNumber,response:{id:t.responseId,object:"response",status:"in_progress",model:t.model,output:[]}}}function _0(t){return{type:"response.output_item.added",sequence_number:t.sequenceNumber,output_index:t.outputIndex,item:t.item}}function EE(t){return{type:"response.output_text.delta",sequence_number:t.sequenceNumber,item_id:t.itemId,output_index:t.outputIndex,content_index:t.contentIndex,delta:t.delta}}function dE(t){return{type:"response.reasoning_summary_text.delta",sequence_number:t.sequenceNumber,item_id:t.itemId,output_index:t.outputIndex,summary_index:t.summaryIndex,delta:t.delta}}function RE(t){return{type:"response.reasoning_summary_text.done",sequence_number:t.sequenceNumber,item_id:t.itemId,output_index:t.outputIndex,summary_index:t.summaryIndex,text:t.text}}function Do(t){return{type:"response.output_item.done",sequence_number:t.sequenceNumber,output_index:t.outputIndex,item:t.item}}function bE(t){return{type:"response.completed",sequence_number:t.sequenceNumber,response:{id:t.responseId,object:"response",status:"completed",model:t.model,output:t.output,usage:t.usage}}}function TE(t){return{type:"response.failed",sequence_number:t.sequenceNumber,response:{id:t.responseId,object:"response",status:"failed",model:t.model,error:t.error}}}function SE(t){return`event: ${t.type}
146
+ data: ${JSON.stringify(t)}
147
+
148
+ `}function wr(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function AY(t){if(!wr(t)||typeof t.index!=="number"||!wr(t.function))return;let n=t.id,s=t.function.name,r=t.function.arguments;if(n!==void 0&&typeof n!=="string"||s!==void 0&&typeof s!=="string"||typeof r!=="string")return;return{index:t.index,id:n,name:s,arguments:r}}function MY(t){if(!wr(t))return;let n=["content","reasoning_content","tool_calls"].filter((r)=>t[r]!==void 0);if(n.length===0)return{kind:"empty"};if(n.length!==1)return;if(typeof t.content==="string")return{kind:"text",text:t.content};if(typeof t.reasoning_content==="string")return{kind:"reasoning",text:t.reasoning_content};if(!Array.isArray(t.tool_calls))return;let s=[];for(let r of t.tool_calls){let i=AY(r);if(!i)return;s.push(i)}return{kind:"tool_calls",calls:s}}function gY(t){if(!wr(t))return;if(typeof t.prompt_tokens!=="number"||typeof t.completion_tokens!=="number"||typeof t.total_tokens!=="number")return;return{input_tokens:t.prompt_tokens,output_tokens:t.completion_tokens,total_tokens:t.total_tokens}}function $E(t){let n;try{n=JSON.parse(t)}catch(f){if(f instanceof SyntaxError)return;throw f}if(!wr(n)||n.object!=="chat.completion.chunk"||!Array.isArray(n.choices))return;let s=n.choices[0];if(!wr(s))return;let r=MY(s.delta),i=s.finish_reason;if(!r||i!==null&&i!=="stop"&&i!=="tool_calls")return;let e=n.usage===void 0?void 0:gY(n.usage);if(n.usage!==void 0&&!e)return;return{delta:r,finishReason:i,usage:e}}function UE(t,n){let r=(t.body??new ReadableStream({start:(G)=>G.close()})).getReader(),i=new TextDecoder,e=new TextEncoder,f=`resp_${Yo()}`,o=`msg_${Yo()}`,c=new Map,h=new Map,u="",_="",l,w,A=0,M=0,E=!1,d=!1,T=!1,U=()=>{if(T)return;T=!0,n.finalize()},S=(G,K)=>{G.enqueue(e.encode(SE(K(M)))),M+=1},O=async(G)=>{await r.cancel(G).catch(()=>{return})},D=async(G,K)=>{if(d)return;d=!0,S(G,(R)=>TE({responseId:f,model:n.model,error:{code:"upstream_error",message:K},sequenceNumber:R})),await O(),U(),G.close()},q=(G)=>{if(!w)return;let K={id:w.id,type:"reasoning",summary:[{type:"summary_text",text:w.text}]};S(G,(R)=>RE({itemId:w?.id??"",outputIndex:w?.outputIndex??0,summaryIndex:0,text:w?.text??"",sequenceNumber:R})),S(G,(R)=>Do({item:K,outputIndex:w?.outputIndex??0,sequenceNumber:R})),h.set(w.outputIndex,K),w=void 0},tt=(G,K)=>{switch(K.kind){case"empty":return;case"reasoning":{if(!w)w={id:`rs_${Yo()}`,outputIndex:A,text:""},A+=1,S(G,(R)=>_0({item:{id:w?.id??"",type:"reasoning",summary:[]},outputIndex:w?.outputIndex??0,sequenceNumber:R}));w.text+=K.text,S(G,(R)=>dE({itemId:w?.id??"",outputIndex:w?.outputIndex??0,summaryIndex:0,delta:K.text,sequenceNumber:R}));return}case"text":{if(q(G),l===void 0)l=A,A+=1,S(G,(R)=>_0({item:{id:o,type:"message",role:"assistant",content:[]},outputIndex:l??0,sequenceNumber:R}));_+=K.text,S(G,(R)=>EE({itemId:o,outputIndex:l??0,contentIndex:0,delta:K.text,sequenceNumber:R}));return}case"tool_calls":q(G);for(let R of K.calls){let W=c.get(R.index)??{itemId:`fc_${Yo()}`,id:"",name:"",arguments:""};if(W.id.length===0&&R.id!==void 0)W.id=R.id;if(W.name.length===0&&R.name!==void 0)W.name=R.name;W.arguments+=R.arguments,c.set(R.index,W)}return}},J=async(G,K)=>{if([...c.values()].some((k)=>k.id.length===0||k.name.length===0)){await D(G,"Malformed upstream tool call");return}if(q(G),l!==void 0){let k={id:o,type:"message",role:"assistant",content:[{type:"output_text",text:_}]};S(G,(st)=>Do({item:k,outputIndex:l??0,sequenceNumber:st})),h.set(l,k)}for(let[,k]of[...c.entries()].sort(([st],[bi])=>st-bi)){let st=A;A+=1;let bi={id:k.itemId,type:"function_call",call_id:k.id,name:k.name,arguments:k.arguments};S(G,(PE)=>Do({item:bi,outputIndex:st,sequenceNumber:PE})),h.set(st,bi)}let W=[...h.entries()].sort(([k],[st])=>k-st).map(([,k])=>k);E=!0,d=!0,S(G,(k)=>bE({responseId:f,model:n.model,output:W,usage:K,sequenceNumber:k})),await O(),U(),G.close()};return new Response(new ReadableStream({start(G){S(G,(K)=>gE({responseId:f,model:n.model,sequenceNumber:K}))},async pull(G){try{while(!d){let K=u.indexOf(`
149
+ `);if(K>=0){let k=u.slice(0,K).trimEnd();if(u=u.slice(K+1),k.length===0)continue;let st=$E(k);if(!st){await D(G,"Malformed upstream stream");return}if(tt(G,st.delta),st.finishReason!==null){if(!st.usage){await D(G,"Terminal upstream chunk omitted usage");return}await J(G,st.usage);return}if(st.delta.kind!=="tool_calls"&&st.delta.kind!=="empty")return;continue}let R=await r.read();if(!R.done){u+=i.decode(R.value,{stream:!0});continue}u+=i.decode();let W=u.trim();if(u="",W.length>0){let k=$E(W);if(!k){await D(G,"Malformed upstream stream");return}if(tt(G,k.delta),k.finishReason!==null&&k.usage){await J(G,k.usage);return}}if(!E)await D(G,"Upstream stream ended before completion");return}}catch{await D(G,"Upstream stream error")}finally{if(d)U()}},async cancel(G){d=!0,await O(G),U()}}),{headers:{"Cache-Control":"no-cache","Content-Type":"text/event-stream; charset=utf-8"}})}class A0 extends Error{limit;name="RequestBodyTooLargeError";constructor(t){super(`Request body exceeds the ${t} byte limit`);this.limit=t}}function w0(t){return t.reason instanceof Error?t.reason:new DOMException("Request deadline exceeded","TimeoutError")}async function EY(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=w0(s.combined);f?.(h),r.cancel(h)};s.combined.addEventListener("abort",c,{once:!0});try{while(!0){if(s.combined.aborted)throw w0(s.combined);let _=await Promise.race([r.read(),o]);if(s.combined.aborted)throw w0(s.combined);if(_.done)break;if(e+=_.value.byteLength,e>n)throw new A0(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 A0)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 Ar(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function dY(t){if(!Ar(t)||!Array.isArray(t.choices)||!Ar(t.usage))return;let n=t.choices[0];if(!Ar(n)||!Ar(n.message))return;let s=n.message;if(typeof s.content!=="string")return;let r=s.reasoning_content;if(r!==void 0&&typeof r!=="string")return;let i=[];if(s.tool_calls!==void 0){if(!Array.isArray(s.tool_calls))return;for(let e of s.tool_calls){if(!Ar(e)||typeof e.id!=="string"||!Ar(e.function)||typeof e.function.name!=="string"||typeof e.function.arguments!=="string")return;i.push({id:e.id,name:e.function.name,arguments:e.function.arguments})}}if(typeof t.usage.prompt_tokens!=="number"||typeof t.usage.completion_tokens!=="number"||typeof t.usage.total_tokens!=="number")return;return{message:{content:s.content,reasoningContent:r,toolCalls:i},usage:{input_tokens:t.usage.prompt_tokens,output_tokens:t.usage.completion_tokens,total_tokens:t.usage.total_tokens}}}function RY(t,n){let s=[];if(t.message.reasoningContent){let i={id:`rs_${l0()}`,type:"reasoning",summary:[{type:"summary_text",text:t.message.reasoningContent}]};s.push(i)}let r={id:`msg_${l0()}`,type:"message",role:"assistant",content:[{type:"output_text",text:t.message.content}]};s.push(r);for(let i of t.message.toolCalls){let e={type:"function_call",call_id:i.id,name:i.name,arguments:i.arguments};s.push(e)}return Response.json({id:`resp_${l0()}`,object:"response",status:"completed",model:n,output:s,usage:t.usage})}async function LE(t,n,s){let r=new AbortController,i=setTimeout(()=>r.abort(new DOMException("Request deadline exceeded","TimeoutError")),n.request_timeout_ms),e=AbortSignal.any([r.signal,t.signal]),f=await EY(t,n.max_request_body_bytes,{combined:e,deadline:r.signal,client:t.signal});if(!f.ok)return clearTimeout(i),f.response;let o;try{o=JSON.parse(f.text)}catch(A){if(clearTimeout(i),!(A instanceof SyntaxError))throw A;return V(400,"Request body must contain valid JSON","invalid_request_error","invalid_json")}let c=_E(o);if(!c.ok)return clearTimeout(i),c.response;let h=ME(c.value);if(!h.ok)return clearTimeout(i),V(400,"input produced no messages","invalid_request_error","empty_input");let u=Wo(h.body);if(!u.ok)return clearTimeout(i),u.response;let _=c.value.stream,l=await(s.runPipeline??Po)({body:u.value,model:u.value.model,stream:_,config:n,accountManager:s.accountManager,tokenRefresher:s.tokenRefresher,deadlineSignal:e,...s.makeClient?{makeClient:s.makeClient}:{}});if(t.signal.aborted&&!r.signal.aborted)return await l.body?.cancel().catch(()=>{return}),clearTimeout(i),V(499,"Client closed request","request_aborted","client_disconnected");let w=l.headers.get("Content-Type")??"";if(_&&w.includes("application/x-ndjson"))return UE(l,{model:u.value.model,finalize:()=>clearTimeout(i)});if(w.includes("application/json")){if(clearTimeout(i),_||!l.ok)return l;let A=await l.json(),M=dY(A);if(M)return RY(M,u.value.model);return V(500,"Pipeline returned an invalid non-streaming response","internal_error","invalid_pipeline_response")}return await l.body?.cancel().catch(()=>{return}),clearTimeout(i),V(500,"Pipeline returned an unsupported response","internal_error","invalid_pipeline_response")}function bY(t,n){return async(s)=>{let r=ou(s,t.api_keys);if(!r.ok)return r.response;let i=new URL(s.url);try{if(s.method==="POST"&&i.pathname==="/v1/chat/completions")return await lE(s,t,n);if(s.method==="POST"&&i.pathname==="/v1/responses")return await LE(s,t,n);if(s.method==="GET"&&i.pathname==="/v1/models")return AE();if(s.method==="GET"&&i.pathname==="/health")return wE();return V(404,"Route not found","invalid_request_error","not_found")}catch(e){let f=e instanceof Error?e.message:"Internal server error";return V(500,f,"internal_error","internal_error")}}}function TY(t,n={}){let s=n.createDatabase?.()??new rs,r=new qo(s.getAccounts(),t.account_selection_strategy,s),i=Qs(t),e=n.createTokenRefresher?n.createTokenRefresher(r,t.token_expiry_buffer_ms,i):new tf(r,t.token_expiry_buffer_ms,i);return{accountManager:r,tokenRefresher:e}}function IE(t){return Bun.serve({hostname:t.host,port:t.port,fetch:bY(t,TY(t))})}import{parseArgs as M0}from"util";var mo=`Usage: kiro-provider <command> [options]
142
150
 
143
151
  Commands:
144
152
  serve [--config <path>] [--host <host>] [--port <port>] [--proxy <url>]
@@ -153,10 +161,10 @@ Commands:
153
161
  Remove an account and write a tombstone.
154
162
 
155
163
  Options:
156
- -h, --help Show this help.`;class wr extends Error{constructor(t){super(t);this.name="CliUsageError"}}function S7(t){let n=su({args:[...t],options:{config:{type:"string"},host:{type:"string"},port:{type:"string"},proxy:{type:"string"},help:{type:"boolean",short:"h"}},strict:!0,allowPositionals:!1});if(n.values.help)return{kind:"help"};let s=n.values.port===void 0?void 0:Number(n.values.port);if(s!==void 0&&(!Number.isInteger(s)||s<1||s>65535))throw new wr(`Invalid port: ${n.values.port}`);return{kind:"serve",...n.values.config?{configPath:n.values.config}:{},...n.values.host?{host:n.values.host}:{},...s!==void 0?{port:s}:{},...n.values.proxy!==void 0?{proxy:n.values.proxy}:{}}}function $7(t){let n=su({args:[...t],options:{config:{type:"string"},"start-url":{type:"string"},region:{type:"string"}},strict:!0,allowPositionals:!1});return{kind:"login",...n.values.config?{configPath:n.values.config}:{},...n.values["start-url"]?{startUrl:n.values["start-url"]}:{},...n.values.region?{region:n.values.region}:{}}}function U7(t){let n=su({args:[...t],options:{from:{type:"string"},config:{type:"string"},help:{type:"boolean",short:"h"}},strict:!0,allowPositionals:!1});if(n.values.help)return{kind:"help"};return{kind:"accounts-import",...n.values.from?{from:n.values.from}:{},...n.values.config?{configPath:n.values.config}:{}}}function L7(t){let n=t[0];switch(n){case"list":if(t.length!==1)throw new wr("accounts list takes no arguments");return{kind:"accounts-list"};case"import":return U7(t.slice(1));case"remove":{let s=t[1];if(!s||t.length!==2)throw new wr("accounts remove requires exactly one <id|email>");return{kind:"accounts-remove",identifier:s}}default:throw new wr(n===void 0?"accounts requires list, import, or remove":`Unknown accounts command: ${n}`)}}function ru(t){let n=t[0];switch(n){case void 0:case"--help":case"-h":return{kind:"help"};case"serve":return S7(t.slice(1));case"login":return $7(t.slice(1));case"accounts":return L7(t.slice(1));default:throw new wr(`Unknown command: ${n}`)}}import{Database as I7}from"bun:sqlite";import{homedir as O7}from"os";import{join as eg}from"path";var y7=g.object({id:g.string().min(1),email:g.string().min(1),auth_method:g.string(),region:g.string(),oidc_region:g.string().nullable(),client_id:g.string().nullable(),client_secret:g.string().nullable(),profile_arn:g.string().nullable(),start_url:g.string().nullable(),refresh_token:g.string(),access_token:g.string(),expires_at:g.number(),rate_limit_reset:g.number().nullable(),is_healthy:g.number().nullable(),unhealthy_reason:g.string().nullable(),recovery_time:g.number().nullable(),fail_count:g.number().nullable(),last_used:g.number().nullable(),used_count:g.number().nullable(),limit_count:g.number().nullable(),last_sync:g.number().nullable(),overage_count:g.number().nullable()});function G7(t=process.env){let n=t.XDG_CONFIG_HOME??eg(O7(),".config");return eg(n,"opencode","kiro.db")}function Kt(t){return t===null||t===""?void 0:t}function B7(t){if(!t.refresh_token)return{kind:"skipped",reason:"missing refresh token"};if(!t.access_token)return{kind:"skipped",reason:"missing access token"};let n=Zn.safeParse(t.region);if(!n.success)return{kind:"skipped",reason:"missing or unsupported region"};if(t.auth_method!=="idc"&&t.auth_method!=="desktop")return{kind:"skipped",reason:"unsupported auth method"};if(t.auth_method==="idc"&&(!t.client_id||!t.client_secret))return{kind:"skipped",reason:"IDC client credentials missing"};let s=Kt(t.oidc_region),r=s===void 0?void 0:Zn.safeParse(s);if(r!==void 0&&!r.success)return{kind:"skipped",reason:"unsupported OIDC region"};return{kind:"usable",account:{id:t.id,email:t.email,authMethod:t.auth_method,region:n.data,...r?.success?{oidcRegion:r.data}:{},...Kt(t.client_id)?{clientId:Kt(t.client_id)}:{},...Kt(t.client_secret)?{clientSecret:Kt(t.client_secret)}:{},...Kt(t.profile_arn)?{profileArn:Kt(t.profile_arn)}:{},...Kt(t.start_url)?{startUrl:Kt(t.start_url)}:{},refreshToken:t.refresh_token,accessToken:t.access_token,expiresAt:t.expires_at,rateLimitResetTime:t.rate_limit_reset??0,isHealthy:t.is_healthy!==0,...Kt(t.unhealthy_reason)?{unhealthyReason:Kt(t.unhealthy_reason)}:{},...t.recovery_time===null?{}:{recoveryTime:t.recovery_time},failCount:t.fail_count??0,lastUsed:t.last_used??0,usedCount:t.used_count??0,limitCount:t.limit_count??0,lastSync:t.last_sync??0,overageCount:t.overage_count??0}}}function ig(t,n){let s=t.from??G7(),r=new I7(s,{readonly:!0,strict:!0}),e=0,i=0;try{let o=r.query(`SELECT
164
+ -h, --help Show this help.`;class Mr extends Error{constructor(t){super(t);this.name="CliUsageError"}}function SY(t){let n=M0({args:[...t],options:{config:{type:"string"},host:{type:"string"},port:{type:"string"},proxy:{type:"string"},help:{type:"boolean",short:"h"}},strict:!0,allowPositionals:!1});if(n.values.help)return{kind:"help"};let s=n.values.port===void 0?void 0:Number(n.values.port);if(s!==void 0&&(!Number.isInteger(s)||s<1||s>65535))throw new Mr(`Invalid port: ${n.values.port}`);return{kind:"serve",...n.values.config?{configPath:n.values.config}:{},...n.values.host?{host:n.values.host}:{},...s!==void 0?{port:s}:{},...n.values.proxy!==void 0?{proxy:n.values.proxy}:{}}}function $Y(t){let n=M0({args:[...t],options:{config:{type:"string"},"start-url":{type:"string"},region:{type:"string"}},strict:!0,allowPositionals:!1});return{kind:"login",...n.values.config?{configPath:n.values.config}:{},...n.values["start-url"]?{startUrl:n.values["start-url"]}:{},...n.values.region?{region:n.values.region}:{}}}function UY(t){let n=M0({args:[...t],options:{from:{type:"string"},config:{type:"string"},help:{type:"boolean",short:"h"}},strict:!0,allowPositionals:!1});if(n.values.help)return{kind:"help"};return{kind:"accounts-import",...n.values.from?{from:n.values.from}:{},...n.values.config?{configPath:n.values.config}:{}}}function LY(t){let n=t[0];switch(n){case"list":if(t.length!==1)throw new Mr("accounts list takes no arguments");return{kind:"accounts-list"};case"import":return UY(t.slice(1));case"remove":{let s=t[1];if(!s||t.length!==2)throw new Mr("accounts remove requires exactly one <id|email>");return{kind:"accounts-remove",identifier:s}}default:throw new Mr(n===void 0?"accounts requires list, import, or remove":`Unknown accounts command: ${n}`)}}function g0(t){let n=t[0];switch(n){case void 0:case"--help":case"-h":return{kind:"help"};case"serve":return SY(t.slice(1));case"login":return $Y(t.slice(1));case"accounts":return LY(t.slice(1));default:throw new Mr(`Unknown command: ${n}`)}}import{Database as IY}from"bun:sqlite";import{homedir as OY}from"os";import{join as OE}from"path";var yY=g.object({id:g.string().min(1),email:g.string().min(1),auth_method:g.string(),region:g.string(),oidc_region:g.string().nullable(),client_id:g.string().nullable(),client_secret:g.string().nullable(),profile_arn:g.string().nullable(),start_url:g.string().nullable(),refresh_token:g.string(),access_token:g.string(),expires_at:g.number(),rate_limit_reset:g.number().nullable(),is_healthy:g.number().nullable(),unhealthy_reason:g.string().nullable(),recovery_time:g.number().nullable(),fail_count:g.number().nullable(),last_used:g.number().nullable(),used_count:g.number().nullable(),limit_count:g.number().nullable(),last_sync:g.number().nullable(),overage_count:g.number().nullable()});function GY(t=process.env){let n=t.XDG_CONFIG_HOME??OE(OY(),".config");return OE(n,"opencode","kiro.db")}function jt(t){return t===null||t===""?void 0:t}function BY(t){if(!t.refresh_token)return{kind:"skipped",reason:"missing refresh token"};if(!t.access_token)return{kind:"skipped",reason:"missing access token"};let n=vn.safeParse(t.region);if(!n.success)return{kind:"skipped",reason:"missing or unsupported region"};if(t.auth_method!=="idc"&&t.auth_method!=="desktop")return{kind:"skipped",reason:"unsupported auth method"};if(t.auth_method==="idc"&&(!t.client_id||!t.client_secret))return{kind:"skipped",reason:"IDC client credentials missing"};let s=jt(t.oidc_region),r=s===void 0?void 0:vn.safeParse(s);if(r!==void 0&&!r.success)return{kind:"skipped",reason:"unsupported OIDC region"};return{kind:"usable",account:{id:t.id,email:t.email,authMethod:t.auth_method,region:n.data,...r?.success?{oidcRegion:r.data}:{},...jt(t.client_id)?{clientId:jt(t.client_id)}:{},...jt(t.client_secret)?{clientSecret:jt(t.client_secret)}:{},...jt(t.profile_arn)?{profileArn:jt(t.profile_arn)}:{},...jt(t.start_url)?{startUrl:jt(t.start_url)}:{},refreshToken:t.refresh_token,accessToken:t.access_token,expiresAt:t.expires_at,rateLimitResetTime:t.rate_limit_reset??0,isHealthy:t.is_healthy!==0,...jt(t.unhealthy_reason)?{unhealthyReason:jt(t.unhealthy_reason)}:{},...t.recovery_time===null?{}:{recoveryTime:t.recovery_time},failCount:t.fail_count??0,lastUsed:t.last_used??0,usedCount:t.used_count??0,limitCount:t.limit_count??0,lastSync:t.last_sync??0,overageCount:t.overage_count??0}}}function yE(t,n){let s=t.from??GY(),r=new IY(s,{readonly:!0,strict:!0}),i=0,e=0;try{let o=r.query(`SELECT
157
165
  id, email, auth_method, region, oidc_region, client_id, client_secret,
158
166
  profile_arn, start_url, refresh_token, access_token, expires_at,
159
167
  rate_limit_reset, is_healthy, unhealthy_reason, recovery_time, fail_count,
160
168
  last_used, used_count, limit_count, last_sync, overage_count
161
- FROM accounts`).all();for(let c of o){let h=y7.safeParse(c);if(!h.success){i+=1,n.stdout("Skipped malformed source account row");continue}let u=B7(h.data);if(u.kind==="skipped"){i+=1,n.stdout(`Skipped ${h.data.email}: ${u.reason}`);continue}n.database.insertAccount(u.account),e+=1,n.stdout(`Imported ${u.account.email} ${u.account.authMethod} ${u.account.region}`)}}finally{r.close()}let f=n.database.getAccounts().length;return n.stdout(`Imported ${e}, skipped ${i}, total in DB now ${f}`),{imported:e,skipped:i,total:f}}import{createHash as H7}from"crypto";var m7=g.object({clientId:g.string().min(1),clientSecret:g.string().min(1)}),F7=g.object({verificationUri:g.string().min(1),verificationUriComplete:g.string().min(1),userCode:g.string().min(1),deviceCode:g.string().min(1),interval:g.number().positive().default(5),expiresIn:g.number().positive().default(600)}),P7=g.object({error:g.string().optional(),error_description:g.string().optional(),access_token:g.string().optional(),accessToken:g.string().optional(),refresh_token:g.string().optional(),refreshToken:g.string().optional(),expires_in:g.number().optional(),expiresIn:g.number().optional()}).passthrough();class yt extends Error{constructor(t,n){super(t,n);this.name="KiroIDCError"}}async function eu(t){try{return await t.text()}catch(n){if(n instanceof Error)return"";throw n}}async function og(t,n,s){let r=qo(t),e=Lr(Or.SSO_OIDC_ENDPOINT,r),i=n??Or.BUILDER_ID_START_URL,f=await fetch(`${e}/client/register`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":st.USER_AGENT},body:JSON.stringify({clientName:"Kiro IDE",clientType:"public",scopes:Or.SCOPES,grantTypes:["urn:ietf:params:oauth:grant-type:device_code","refresh_token"]}),...s?{proxy:s}:{}});if(!f.ok)throw new yt(`Client registration failed: ${f.status} ${await eu(f)}`);let o=m7.safeParse(await f.json());if(!o.success)throw new yt("Client registration response missing clientId or clientSecret",{cause:o.error});let c=await fetch(`${e}/device_authorization`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":st.USER_AGENT},body:JSON.stringify({clientId:o.data.clientId,clientSecret:o.data.clientSecret,startUrl:i}),...s?{proxy:s}:{}});if(!c.ok)throw new yt(`Device authorization failed: ${c.status} ${await eu(c)}`);let h=F7.safeParse(await c.json());if(!h.success)throw new yt("Device authorization response missing required fields",{cause:h.error});return{verificationUrl:h.data.verificationUri,verificationUriComplete:h.data.verificationUriComplete,userCode:h.data.userCode,deviceCode:h.data.deviceCode,clientId:o.data.clientId,clientSecret:o.data.clientSecret,interval:h.data.interval,expiresIn:h.data.expiresIn,region:r,startUrl:i}}async function fg(t,n,s,r,e,i,f=(c)=>new Promise((h)=>setTimeout(h,c)),o){if(!t||!n||!s)throw new yt("Missing required parameters for token polling");let c=qo(i),h=Lr(Or.SSO_OIDC_ENDPOINT,c),u=Math.floor(e/r),l=r*1000;for(let _=1;_<=u;_+=1){await f(l);let w=await fetch(`${h}/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":st.USER_AGENT},body:JSON.stringify({clientId:t,clientSecret:n,deviceCode:s,grantType:"urn:ietf:params:oauth:grant-type:device_code"}),...o?{proxy:o}:{}}),A=await eu(w),M={};if(A)try{M=JSON.parse(A)}catch(S){throw new yt(`Token polling failed: invalid JSON response (HTTP ${w.status}): ${A.slice(0,300)}`,{cause:S})}let d=P7.safeParse(M);if(!d.success)throw new yt(`Token polling failed: invalid response (HTTP ${w.status})`,{cause:d.error});let E=d.data;switch(E.error){case void 0:break;case"authorization_pending":continue;case"slow_down":l+=5000;continue;case"expired_token":throw new yt("Device code has expired. Please restart the authorization process.");case"access_denied":throw new yt("Authorization was denied by the user.");default:throw new yt(`Token polling failed: ${E.error} - ${E.error_description??""}`)}let b=E.access_token??E.accessToken,L=E.refresh_token??E.refreshToken;if(b&&L)return{refreshToken:L,accessToken:b,expiresAt:Date.now()+(E.expires_in??E.expiresIn??3600)*1000,email:"builder-id@aws.amazon.com",clientId:t,clientSecret:n,region:c,authMethod:"idc"};if(!w.ok)throw new yt(`Token request failed with status: ${w.status} ${A?`(${A.slice(0,200)})`:""}`);throw new yt(`Token polling failed: missing tokens in response: ${A?A.slice(0,300):"[empty]"}`)}throw new yt("Token polling timed out. Authorization may have expired.")}function N7(t){if(t===void 0||t.trim()==="")return;let n=new URL(t.trim());return n.hash="",n.search="",n.pathname=`${n.pathname.replace(/\/start\/?$/,"").replace(/\/+$/,"")}/start`,n.toString()}function D7(t,n){return H7("sha256").update(`${t}:idc:${n}:`).digest("hex")}async function cg(t,n={},s={}){let r=s.authorize??og,e=s.poll??fg,i=s.stdout??console.log,f=N7(n.startUrl),o=Zn.parse(n.region??t.default_region),c=xs(t),h=await r(o,f,c);i(`Open this URL to sign in:
162
- ${h.verificationUriComplete}`);let u=await e(h.clientId,h.clientSecret,h.deviceCode,h.interval,h.expiresIn,o,void 0,c),l={id:D7(u.email,u.clientId),email:u.email,authMethod:"idc",region:o,oidcRegion:o,clientId:u.clientId,clientSecret:u.clientSecret,...f?{startUrl:f}:{},refreshToken:u.refreshToken,accessToken:u.accessToken,expiresAt:u.expiresAt,rateLimitResetTime:0,isHealthy:!0,failCount:0,usedCount:0,limitCount:0},_=s.openDb?.(Fn)??new rs(Fn);try{_.insertAccount(l)}finally{_.close()}i(`Login successful: ${l.email}`)}function W7(t){let n=t.isHealthy?"healthy":"unhealthy";return`${t.email} ${t.region} ${n} generation=${t.generation} used=${t.usedCount??0}/${t.limitCount??0}`}var Y7={loadConfig:Eu,startServer:rg,runLogin:cg,runImportAccounts:ig,openDb:(t)=>new rs(t),stdout:console.log,stderr:console.error};async function x7(t,n){switch(t.kind){case"help":return n.stdout(mo),0;case"serve":{let s={...t.host?{host:t.host}:{},...t.port!==void 0?{port:t.port}:{},...t.proxy!==void 0?{proxy_url:t.proxy}:{}},r=n.loadConfig({...t.configPath?{configPath:t.configPath}:{},overrides:s});if(r.test_upstream_endpoint)n.stderr(`WARNING: test_upstream_endpoint is set (${r.test_upstream_endpoint}); routing upstream to a NON-production endpoint. Unset it for normal use.`);let e=n.startServer(r);return n.stdout(`Listening on http://${e.hostname??r.host}:${e.port??r.port}`),0}case"login":{let s=n.loadConfig({...t.configPath?{configPath:t.configPath}:{}});return await n.runLogin(s,{...t.startUrl?{startUrl:t.startUrl}:{},...t.region?{region:t.region}:{}}),0}case"accounts-list":{let s=n.openDb(Fn);try{for(let r of s.getAccounts())n.stdout(W7(r))}finally{s.close()}return 0}case"accounts-import":{let s=n.openDb(Fn);try{n.runImportAccounts({...t.from?{from:t.from}:{}},{database:s,stdout:n.stdout})}finally{s.close()}return 0}case"accounts-remove":{let s=n.openDb(Fn);try{let r=s.getAccounts().find((e)=>e.id===t.identifier||e.email===t.identifier);if(!r)return n.stderr(`Account not found: ${t.identifier}`),1;s.removeAccount(r.id),n.stdout(`Removed account ${r.email}`)}finally{s.close()}return 0}}}async function hg(t=process.argv.slice(2),n=Y7){let s;try{s=ru(t)}catch(r){return n.stderr(r instanceof Error?r.message:String(r)),n.stderr(mo),1}try{return await x7(s,n)}catch(r){return n.stderr(r instanceof Error?r.message:String(r)),1}}process.exitCode=await hg();
169
+ FROM accounts`).all();for(let c of o){let h=yY.safeParse(c);if(!h.success){e+=1,n.stdout("Skipped malformed source account row");continue}let u=BY(h.data);if(u.kind==="skipped"){e+=1,n.stdout(`Skipped ${h.data.email}: ${u.reason}`);continue}n.database.insertAccount(u.account),i+=1,n.stdout(`Imported ${u.account.email} ${u.account.authMethod} ${u.account.region}`)}}finally{r.close()}let f=n.database.getAccounts().length;return n.stdout(`Imported ${i}, skipped ${e}, total in DB now ${f}`),{imported:i,skipped:e,total:f}}import{createHash as NY}from"crypto";var FY=g.object({clientId:g.string().min(1),clientSecret:g.string().min(1)}),HY=g.object({verificationUri:g.string().min(1),verificationUriComplete:g.string().min(1),userCode:g.string().min(1),deviceCode:g.string().min(1),interval:g.number().positive().default(5),expiresIn:g.number().positive().default(600)}),PY=g.object({error:g.string().optional(),error_description:g.string().optional(),access_token:g.string().optional(),accessToken:g.string().optional(),refresh_token:g.string().optional(),refreshToken:g.string().optional(),expires_in:g.number().optional(),expiresIn:g.number().optional()}).passthrough();class Ft extends Error{constructor(t,n){super(t,n);this.name="KiroIDCError"}}async function E0(t){try{return await t.text()}catch(n){if(n instanceof Error)return"";throw n}}async function GE(t,n,s){let r=Zo(t),i=Or(Gr.SSO_OIDC_ENDPOINT,r),e=n??Gr.BUILDER_ID_START_URL,f=await fetch(`${i}/client/register`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":ot.USER_AGENT},body:JSON.stringify({clientName:"Kiro IDE",clientType:"public",scopes:Gr.SCOPES,grantTypes:["urn:ietf:params:oauth:grant-type:device_code","refresh_token"]}),...s?{proxy:s}:{}});if(!f.ok)throw new Ft(`Client registration failed: ${f.status} ${await E0(f)}`);let o=FY.safeParse(await f.json());if(!o.success)throw new Ft("Client registration response missing clientId or clientSecret",{cause:o.error});let c=await fetch(`${i}/device_authorization`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":ot.USER_AGENT},body:JSON.stringify({clientId:o.data.clientId,clientSecret:o.data.clientSecret,startUrl:e}),...s?{proxy:s}:{}});if(!c.ok)throw new Ft(`Device authorization failed: ${c.status} ${await E0(c)}`);let h=HY.safeParse(await c.json());if(!h.success)throw new Ft("Device authorization response missing required fields",{cause:h.error});return{verificationUrl:h.data.verificationUri,verificationUriComplete:h.data.verificationUriComplete,userCode:h.data.userCode,deviceCode:h.data.deviceCode,clientId:o.data.clientId,clientSecret:o.data.clientSecret,interval:h.data.interval,expiresIn:h.data.expiresIn,region:r,startUrl:e}}async function BE(t,n,s,r,i,e,f=(c)=>new Promise((h)=>setTimeout(h,c)),o){if(!t||!n||!s)throw new Ft("Missing required parameters for token polling");let c=Zo(e),h=Or(Gr.SSO_OIDC_ENDPOINT,c),u=Math.floor(i/r),_=r*1000;for(let l=1;l<=u;l+=1){await f(_);let w=await fetch(`${h}/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":ot.USER_AGENT},body:JSON.stringify({clientId:t,clientSecret:n,deviceCode:s,grantType:"urn:ietf:params:oauth:grant-type:device_code"}),...o?{proxy:o}:{}}),A=await E0(w),M={};if(A)try{M=JSON.parse(A)}catch(S){throw new Ft(`Token polling failed: invalid JSON response (HTTP ${w.status}): ${A.slice(0,300)}`,{cause:S})}let E=PY.safeParse(M);if(!E.success)throw new Ft(`Token polling failed: invalid response (HTTP ${w.status})`,{cause:E.error});let d=E.data;switch(d.error){case void 0:break;case"authorization_pending":continue;case"slow_down":_+=5000;continue;case"expired_token":throw new Ft("Device code has expired. Please restart the authorization process.");case"access_denied":throw new Ft("Authorization was denied by the user.");default:throw new Ft(`Token polling failed: ${d.error} - ${d.error_description??""}`)}let T=d.access_token??d.accessToken,U=d.refresh_token??d.refreshToken;if(T&&U)return{refreshToken:U,accessToken:T,expiresAt:Date.now()+(d.expires_in??d.expiresIn??3600)*1000,email:"builder-id@aws.amazon.com",clientId:t,clientSecret:n,region:c,authMethod:"idc"};if(!w.ok)throw new Ft(`Token request failed with status: ${w.status} ${A?`(${A.slice(0,200)})`:""}`);throw new Ft(`Token polling failed: missing tokens in response: ${A?A.slice(0,300):"[empty]"}`)}throw new Ft("Token polling timed out. Authorization may have expired.")}function WY(t){if(t===void 0||t.trim()==="")return;let n=new URL(t.trim());return n.hash="",n.search="",n.pathname=`${n.pathname.replace(/\/start\/?$/,"").replace(/\/+$/,"")}/start`,n.toString()}function DY(t,n){return NY("sha256").update(`${t}:idc:${n}:`).digest("hex")}async function FE(t,n={},s={}){let r=s.authorize??GE,i=s.poll??BE,e=s.stdout??console.log,f=WY(n.startUrl),o=vn.parse(n.region??t.default_region),c=Qs(t),h=await r(o,f,c);e(`Open this URL to sign in:
170
+ ${h.verificationUriComplete}`);let u=await i(h.clientId,h.clientSecret,h.deviceCode,h.interval,h.expiresIn,o,void 0,c),_={id:DY(u.email,u.clientId),email:u.email,authMethod:"idc",region:o,oidcRegion:o,clientId:u.clientId,clientSecret:u.clientSecret,...f?{startUrl:f}:{},refreshToken:u.refreshToken,accessToken:u.accessToken,expiresAt:u.expiresAt,rateLimitResetTime:0,isHealthy:!0,failCount:0,usedCount:0,limitCount:0},l=s.openDb?.(Pn)??new rs(Pn);try{l.insertAccount(_)}finally{l.close()}e(`Login successful: ${_.email}`)}function YY(t){let n=t.isHealthy?"healthy":"unhealthy";return`${t.email} ${t.region} ${n} generation=${t.generation} used=${t.usedCount??0}/${t.limitCount??0}`}var mY={loadConfig:F0,startServer:IE,runLogin:FE,runImportAccounts:yE,openDb:(t)=>new rs(t),stdout:console.log,stderr:console.error};async function QY(t,n){switch(t.kind){case"help":return n.stdout(mo),0;case"serve":{let s={...t.host?{host:t.host}:{},...t.port!==void 0?{port:t.port}:{},...t.proxy!==void 0?{proxy_url:t.proxy}:{}},r=n.loadConfig({...t.configPath?{configPath:t.configPath}:{},overrides:s});if(r.test_upstream_endpoint)n.stderr(`WARNING: test_upstream_endpoint is set (${r.test_upstream_endpoint}); routing upstream to a NON-production endpoint. Unset it for normal use.`);let i=n.startServer(r);return n.stdout(`Listening on http://${i.hostname??r.host}:${i.port??r.port}`),0}case"login":{let s=n.loadConfig({...t.configPath?{configPath:t.configPath}:{}});return await n.runLogin(s,{...t.startUrl?{startUrl:t.startUrl}:{},...t.region?{region:t.region}:{}}),0}case"accounts-list":{let s=n.openDb(Pn);try{for(let r of s.getAccounts())n.stdout(YY(r))}finally{s.close()}return 0}case"accounts-import":{let s=n.openDb(Pn);try{n.runImportAccounts({...t.from?{from:t.from}:{}},{database:s,stdout:n.stdout})}finally{s.close()}return 0}case"accounts-remove":{let s=n.openDb(Pn);try{let r=s.getAccounts().find((i)=>i.id===t.identifier||i.email===t.identifier);if(!r)return n.stderr(`Account not found: ${t.identifier}`),1;s.removeAccount(r.id),n.stdout(`Removed account ${r.email}`)}finally{s.close()}return 0}}}async function HE(t=process.argv.slice(2),n=mY){let s;try{s=g0(t)}catch(r){return n.stderr(r instanceof Error?r.message:String(r)),n.stderr(mo),1}try{return await QY(s,n)}catch(r){return n.stderr(r instanceof Error?r.message:String(r)),1}}process.exitCode=await HE();