UNPKG

@allthings/cloud-toolkit

Version:

Standardizes the setup of aws, datadog and other things

1 lines 1.04 MB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("querystring"),require("zlib"),require("crypto"),require("events"),require("url"),require("util"),require("fs"),require("http"),require("https"),require("stream"),require("net"),require("dns"),require("os"),require("path"),require("tls"),require("child_process"),require("buffer"),require("string_decoder")):"function"==typeof define&&define.amd?define(["exports","querystring","zlib","crypto","events","url","util","fs","http","https","stream","net","dns","os","path","tls","child_process","buffer","string_decoder"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).allthings={},e.querystring,e.zlib,e.require$$2$1,e.require$$0$a,e.require$$0$3,e.require$$0$8,e.require$$0$7,e.require$$0$5,e.require$$1,e.require$$0$4,e.require$$7,e.require$$4,e.require$$0$6,e.require$$0$9,e.require$$1$1,e.require$$0$b,e.require$$0$c,e.require$$1$2)}(this,(function(exports,querystring,zlib,require$$2$1,require$$0$a,require$$0$3,require$$0$8,require$$0$7,require$$0$5,require$$1,require$$0$4,require$$7,require$$4,require$$0$6,require$$0$9,require$$1$1,require$$0$b,require$$0$c,require$$1$2){"use strict";function _interopNamespaceDefault(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(n){if("default"!==n){var i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:function(){return e[n]}})}})),t.default=e,Object.freeze(t)}var querystring__namespace=_interopNamespaceDefault(querystring),zlib__namespace=_interopNamespaceDefault(zlib),require$$2__namespace=_interopNamespaceDefault(require$$2$1);const defaultErrorHandler$1=(e,t,n)=>{const{requestId:i}=e.requestContext,r=n.name&&"string"==typeof n.name?n.name.replace(/([A-Z])([A-Z])([a-z])|([a-z])([A-Z])/g,"$1$4 $2$3$5"):"Error",o=n.message||"",a=n.statusCode?` ${n.statusCode}`:"";return"ClientError"===n.name||n.statusCode>=400&&n.statusCode<500?t.respondTo({html:`<html><body><strong>${r}${a}</strong>: ${o}<br/>Request ID: ${i}</body></html>`,json:{error:n.name,message:o,requestId:i}},n.statusCode||400):t.respondTo({html:`<html><body>An internal server error occurred.<br/>Request ID: ${i}</body></html>`,json:{error:"Internal server error",message:"An internal server error occurred",requestId:i}},500)};class ClientError extends Error{name="ClientError";statusCode=400;constructor(e,t,n=400){super(String(e)),this.name=t||this.name,this.statusCode=n}}class ServerError extends Error{name="ServerError";statusCode=500;constructor(e,t,n=500){super(String(e)),this.name=t||this.name,this.statusCode=n}}const applyMiddleware=async(e,t,...n)=>e.reduce((async(e,t)=>t(await e,...n)),Promise.resolve(t)),decodeBase64=e=>Buffer.from(e,"base64").toString("utf8"),decodeBase64Body=e=>e.isBase64Encoded&&"string"==typeof e.body?{...e,body:decodeBase64(e.body)}:e,parseCookiePair=e=>{const t=e.indexOf("="),n=-1!==t,i=n&&e.slice(0,Math.max(0,t)).trim(),r=n&&e.substr(t+1,e.length).trim(),o=r&&'"'===r[0]?r.slice(1,-1):r;return i?{[i]:o?decodeURIComponent(o):""}:{}},parseCookieHeader=e=>e.split(/; */).reduce(((e,t)=>({...e,...parseCookiePair(t)})),{}),cookies$1=e=>({...e,cookies:parseCookieHeader(e.headers?.cookie||"")}),setHostname=e=>({...e,hostname:e.headers?.host||void 0}),parseJson=e=>{try{return JSON.parse(e)}catch{return{}}},parseJsonBody$1=e=>{const{headers:t,body:n}=e;return t["content-type"]&&"application/json"===t["content-type"].split(";").shift()&&"string"==typeof n?{...e,body:parseJson(n)}:e},state$1=new Map([["invocationCount",0]]),meta=e=>{const t=Number(state$1.get("invocationCount"));return{...e,meta:{...e.meta,coldStart:!t,invocationCount:state$1.set("invocationCount",t+1).get("invocationCount")}}},normalizeHeaders=({headers:e={},...t})=>({...t,headers:Object.keys(e).reduce(((n,i)=>{const r=i.toLowerCase();return"aws"===t.provider&&Reflect.has(n,r)&&"content-type"===r&&"application/json"===e[i]?n:{...n,[r]:e[i]}}),{})}),normalizeProgrammingModel=e=>({...e,method:e.httpMethod??e.requestContext?.http?.method??"",path:e.path??e.requestContext?.http?.path??"",provider:"aws",query:e.queryStringParameters||{},source:e.requestContext?"api-gateway":e.source}),addTimestamp=e=>({...e,timestamp:Date.now()}),parseUrlEncodedBody=e=>{const{headers:t,body:n}=e;return t["content-type"]&&"application/x-www-form-urlencoded"===t["content-type"].split(";").shift()&&"string"==typeof n?{...e,body:querystring__namespace.parse(n)}:e};var makeRequest=async(e,t,n={})=>applyMiddleware([addTimestamp,normalizeProgrammingModel,normalizeHeaders,decodeBase64Body,cookies$1,parseUrlEncodedBody,parseJsonBody$1,setHostname,meta,...n.requestMiddleware||[]],Object.freeze({...e,context:t}),n);const setHeader=(e,t,n,i)=>(Object.assign(t.headers,{[n]:i}),e),makeResponseObject=(e,t="",n=200,{headers:i={},...r}={},o)=>Object.freeze({...e,body:t||"",headers:{...e?.headers,"content-type":o,...i},statusCode:n,...r}),html=(e,t,n,i,r)=>makeResponseObject(e,n,i,r,"text/html"),stringifyIfNotStringifiedJson=e=>{const t="string"==typeof e?e.trim():e;return"string"==typeof e&&["{",'"'].includes(t[0])&&["}",'"'].includes(t.at(-1))?t:JSON.stringify(e)},json$2=(e,t,n,i,r)=>makeResponseObject(e,stringifyIfNotStringifiedJson(n),i,r,"application/json"),COMPRESSIBLE=["application/activity+json","application/alto-costmap+json","application/alto-costmapfilter+json","application/alto-directory+json","application/alto-endpointcost+json","application/alto-endpointcostparams+json","application/alto-endpointprop+json","application/alto-endpointpropparams+json","application/alto-error+json","application/alto-networkmap+json","application/alto-networkmapfilter+json","application/atom+xml","application/calendar+json","application/coap-group+json","application/csvm+json","application/dart","application/dicom+json","application/ecmascript","application/fhir+json","application/fido.trusted-apps+json","application/geo+json","application/javascript","application/jf2feed+json","application/jose+json","application/jrd+json","application/json","application/json-patch+json","application/jsonml+json","application/jwk+json","application/jwk-set+json","application/ld+json","application/manifest+json","application/merge-patch+json","application/mud+json","application/postscript","application/ppsp-tracker+json","application/problem+json","application/raml+yaml","application/rdap+json","application/rdf+xml","application/reputon+json","application/rss+xml","application/rtf","application/scim+json","application/soap+xml","application/tar","application/vcard+json","application/vnd.amadeus+json","application/vnd.api+json","application/vnd.apothekende.reservation+json","application/vnd.avalon+json","application/vnd.bbf.usp.msg+json","application/vnd.bekitzur-stech+json","application/vnd.capasystems-pg+json","application/vnd.collection+json","application/vnd.collection.doc+json","application/vnd.collection.next+json","application/vnd.coreos.ignition+json","application/vnd.dart","application/vnd.datapackage+json","application/vnd.dataresource+json","application/vnd.document+json","application/vnd.drive+json","application/vnd.geo+json","application/vnd.google-earth.kml+xml","application/vnd.hal+json","application/vnd.hc+json","application/vnd.heroku+json","application/vnd.hyper+json","application/vnd.hyper-item+json","application/vnd.hyperdrive+json","application/vnd.ims.lis.v2.result+json","application/vnd.ims.lti.v2.toolconsumerprofile+json","application/vnd.ims.lti.v2.toolproxy+json","application/vnd.ims.lti.v2.toolproxy.id+json","application/vnd.ims.lti.v2.toolsettings+json","application/vnd.ims.lti.v2.toolsettings.simple+json","application/vnd.las.las+json","application/vnd.mason+json","application/vnd.micro+json","application/vnd.miele+json","application/vnd.mozilla.xul+xml","application/vnd.ms-fontobject","application/vnd.ms-opentype","application/vnd.nearst.inv+json","application/vnd.oftn.l10n+json","application/vnd.oma.lwm2m+json","application/vnd.oracle.resource+json","application/vnd.pagerduty+json","application/vnd.restful+json","application/vnd.siren+json","application/vnd.sun.wadl+xml","application/vnd.tableschema+json","application/vnd.vel+json","application/vnd.xacml+json","application/voucher-cms+json","application/wasm","application/webpush-options+json","application/x-httpd-php","application/x-javascript","application/x-ns-proxy-autoconfig","application/x-sh","application/x-tar","application/x-virtualbox-hdd","application/x-virtualbox-ova","application/x-virtualbox-ovf","application/x-virtualbox-vbox","application/x-virtualbox-vdi","application/x-virtualbox-vhd","application/x-virtualbox-vmdk","application/x-web-app-manifest+json","application/x-www-form-urlencoded","application/xhtml+xml","application/xml","application/xml-dtd","application/xop+xml","application/yang-data+json","application/yang-patch+json","font/otf","image/bmp","image/svg+xml","image/vnd.adobe.photoshop","image/x-icon","image/x-ms-bmp","message/imdn+xml","message/rfc822","model/gltf+json","model/gltf-binary","model/x3d+xml","text/cache-manifest","text/calender","text/cmd","text/css","text/csv","text/html","text/javascript","text/jsx","text/markdown","text/n3","text/plain","text/richtext","text/rtf","text/tab-separated-values","text/uri-list","text/vcard","text/vtt","text/x-gwt-rpc","text/x-jquery-tmpl","text/x-markdown","text/x-org","text/x-processing","text/x-suse-ymp","text/xml","x-shader/x-fragment","x-shader/x-vertex"],ZLIB_DEFAULT_OPTIONS={level:5},acceptEncoding=(e,t)=>e.find((e=>t.some((t=>e===t)))),getBestAcceptEncoding=e=>{const{headers:t}=e,n=(t["accept-encoding"]||"").split(/, */),i=acceptEncoding(n,["gzip","deflate","identity"]);return"deflate"===i&&acceptEncoding(n,["gzip"])?acceptEncoding(n,["gzip","identity"]):i},compressResponse=(e,t)=>{const{body:n,headers:i,...r}=e,o="gzip"===t?zlib__namespace.gzipSync(n,ZLIB_DEFAULT_OPTIONS):zlib__namespace.deflateSync(n,ZLIB_DEFAULT_OPTIONS);return{...r,body:o.toString("base64"),headers:{...i,"content-encoding":t,"content-length":o.byteLength},isBase64Encoded:!0}},compress=(e,t)=>{const{body:n,headers:i}=e,r=getBestAcceptEncoding(t);return COMPRESSIBLE.includes(i["content-type"])&&void 0!==r&&"identity"!==r&&n&&n.length>256&&r?compressResponse(e,r):e},contentLengthHeader=e=>{const{body:t,headers:n,...i}=e;return{...i,body:t,headers:{...n,"content-length":n["content-length"]||Buffer.byteLength(t)}}},DEFAULT_POLICIES={"default-src":"'self' https: 'unsafe-inline'","img-src":"* data: blob:"},cspHeaders=(e,t,n)=>{const{headers:i={},...r}=e,o={...DEFAULT_POLICIES,...n.cspPolicies};return{...r,headers:{...i,"content-security-policy":Object.keys(o).map((e=>`${e} ${o[e]}`)).join(";"),"referrer-policy":"strict-origin-when-cross-origin","x-content-type-options":"nosniff","x-frame-options":{"'none'":"DENY","'self'":"SAMEORIGIN"}[o["frame-ancestors"]]||void 0,"x-xss-protection":"1; mode=block"}}},enforcedHeaders=(e,t,n)=>({...e,headers:{...e.headers,...n.headers??{}}}),EMPTY_ENTITY_TAG='"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"',entitytag=e=>{const t=require$$2__namespace.createHash("sha1").update(e,"utf8").digest("base64").slice(0,27);return`"${("string"==typeof e?Buffer.byteLength(e,"utf8"):e.length).toString(16)}-${t}"`},etag=e=>0===e.length?EMPTY_ENTITY_TAG:entitytag(e),etagHeader=e=>({...e,headers:{...e.headers,etag:etag(e.body)}}),aws$1=e=>{const{headers:t,requestContext:n,context:i}=e;return{apig:{requestId:n.requestId,resourcePath:n.resourcePath??""},awsAccountId:n.accountId,cloudfront:{country:t["cloudfront-viewer-country"],desktop:"true"===t["cloudfront-is-desktop-viewer"],mobile:"true"===t["cloudfront-is-mobile-viewer"],smarttv:"true"===t["cloudfront-is-smarttv-viewer"],tablet:"true"===t["cloudfront-is-tablet-viewer"]},deploymentStage:n.stage,lambda:{functionName:i.functionName,memoryLimit:Number(i.memoryLimitInMB),remainingExecutionTime:i.getRemainingTimeInMillis?.(),requestId:i.awsRequestId},sourceIp:n.identity?.sourceIp??n?.http?.sourceIp}},logger$3=(e,t)=>{const{source:n,headers:i,meta:r,requestContext:o,provider:a,hostname:s,body:c,timestamp:l,path:d,query:u}=e,p=t.statusCode>=500&&t.statusCode<600,m={dateTime:(new Date).toISOString(),eventSource:n,hostname:s,httpMethod:o.httpMethod,httpProtocol:i.via?.split(" ")[0],httpReferrer:i.referer,httpUserAgent:i["user-agent"],requestContentLength:c&&c.length>0||0,requestTime:Date.now()-l,requestUri:d+(u&&Object.keys(u).length>0?`?${querystring__namespace.stringify(u)}`:""),responseContentLength:t.headers["content-length"],statusCode:t.statusCode,xForwardedHost:i["x-forwarded-host"],...r,..."aws"===a&&aws$1(e)};return(p?process.stderr:process.stdout).write(JSON.stringify(m))&&m},logResponse=(e,t,n)=>n.enableLogger&&("function"==typeof n.logger?n.logger(t,e):logger$3(t,e))&&e||e,redirect=(e,t,n,i=302,r={})=>makeResponseObject(e,"",i,{...r,headers:{...r.headers,location:n}}),getBestMatchedFormat=(e,t)=>{const n=e.default||"html",i=t&&"string"==typeof t&&t.split(";")[0].split(",").map((e=>e.split("/").at(-1)));return i&&i.find((t=>Reflect.has(e,t)))||n},getBestMatchedResponseHelper=e=>{switch(e){case"html":return html;case"json":return json$2}throw new TypeError(`"${e}" is not a valid Alagarr respondTo() format.`)},getBestMatchedFormatBody=(e,t)=>{switch(t){case"html":return e.html;case"json":return e.json}throw new TypeError(`"${t}" is not a valid Alagarr respondTo() format.`)},respondTo=(e,t,n,i,r)=>{const{headers:{accept:o}}=t,a=getBestMatchedFormat(n,o);return getBestMatchedResponseHelper(a)(e,t,getBestMatchedFormatBody(n,a),i,r)},text=(e,t,n,i,r)=>makeResponseObject(e,n,i,r,"text/plain"),middlewareMap={enableCompression:compress,enableContentLength:contentLengthHeader,enableCspHeaders:cspHeaders,enableETagHeader:etagHeader,enableEnforcedHeaders:enforcedHeaders};var makeResponse=async(e,t,n)=>{const i=makeResponseObject(),r=[text,html,json$2,redirect,respondTo].reduce(((r,o)=>({...r,[o.name]:async(...r)=>t(null,await applyMiddleware(Object.keys(middlewareMap).reduce(((e,t)=>n[t]?[...e,middlewareMap[t]]:e),[...n.responseMiddleware||[],...n.enableLogger?[logResponse]:[]]),o(i,e,...r),e,n))})),{raw:t}),o=[setHeader].reduce(((e,t)=>({...e,[t.name]:(...e)=>t(o,i,...e)})),r);return o};const DEFAULT_OPTIONS={cspPolicies:[],enableCompression:!0,enableContentLength:!0,enableCspHeaders:!0,enableETagHeader:!0,enableEnforcedHeaders:!0,enableLogger:!0,enableStrictTransportSecurity:!0,errorHandler:defaultErrorHandler$1,requestMiddleware:[],responseMiddleware:[]},noopHandler=(e,t)=>{throw new ServerError("Misconfiguration in Alagarr setup. No handler function was provided.")},alagarr=(e=noopHandler,t=DEFAULT_OPTIONS)=>async(n,i,r)=>{const o={...DEFAULT_OPTIONS,...t},a=await makeRequest(n,i,o),s=await makeResponse(a,r,o);try{return await e(a,s,i)}catch(e){const t="function"==typeof o.errorHandler?o.errorHandler:defaultErrorHandler$1;try{return await t(a,s,e)}catch(e){return console.error("There was an error in the error handler provided to Alagaar",e,t.toString()),defaultErrorHandler$1(a,s,e)}}};var HttpAuthLocation,HttpApiKeyAuthLocation,EndpointURLScheme,AlgorithmId,FieldPosition;!function(e){e.HEADER="header",e.QUERY="query"}(HttpAuthLocation||(HttpAuthLocation={})),function(e){e.HEADER="header",e.QUERY="query"}(HttpApiKeyAuthLocation||(HttpApiKeyAuthLocation={})),function(e){e.HTTP="http",e.HTTPS="https"}(EndpointURLScheme||(EndpointURLScheme={})),function(e){e.MD5="md5",e.CRC32="crc32",e.CRC32C="crc32c",e.SHA1="sha1",e.SHA256="sha256"}(AlgorithmId||(AlgorithmId={})),function(e){e[e.HEADER=0]="HEADER",e[e.TRAILER=1]="TRAILER"}(FieldPosition||(FieldPosition={}));const SMITHY_CONTEXT_KEY="__smithy_context";var IniSectionType,RequestHandlerProtocol;!function(e){e.PROFILE="profile",e.SSO_SESSION="sso-session",e.SERVICES="services"}(IniSectionType||(IniSectionType={})),function(e){e.HTTP_0_9="http/0.9",e.HTTP_1_0="http/1.0",e.TDS_8_0="tds/8.0"}(RequestHandlerProtocol||(RequestHandlerProtocol={}));const getSmithyContext=e=>e[SMITHY_CONTEXT_KEY]||(e[SMITHY_CONTEXT_KEY]={}),normalizeProvider$1=e=>{if("function"==typeof e)return e;const t=Promise.resolve(e);return()=>t},DEFAULT_ACCOUNT_ID_ENDPOINT_MODE="preferred",ACCOUNT_ID_ENDPOINT_MODE_VALUES=["disabled","preferred","required"];function validateAccountIdEndpointMode(e){return ACCOUNT_ID_ENDPOINT_MODE_VALUES.includes(e)}const resolveAccountIdEndpointModeConfig=e=>{const{accountIdEndpointMode:t}=e,n=normalizeProvider$1(t??DEFAULT_ACCOUNT_ID_ENDPOINT_MODE);return Object.assign(e,{accountIdEndpointMode:async()=>{const e=await n();if(!validateAccountIdEndpointMode(e))throw new Error(`Invalid value for accountIdEndpointMode: ${e}. Valid values are: "required", "preferred", "disabled".`);return e}})},getHttpHandlerExtensionConfiguration=e=>({setHttpHandler(t){e.httpHandler=t},httpHandler:()=>e.httpHandler,updateHttpClientConfig(t,n){e.httpHandler?.updateHttpClientConfig(t,n)},httpHandlerConfigs:()=>e.httpHandler.httpHandlerConfigs()}),resolveHttpHandlerRuntimeConfig=e=>({httpHandler:e.httpHandler()});class HttpRequest{constructor(e){this.method=e.method||"GET",this.hostname=e.hostname||"localhost",this.port=e.port,this.query=e.query||{},this.headers=e.headers||{},this.body=e.body,this.protocol=e.protocol?":"!==e.protocol.slice(-1)?`${e.protocol}:`:e.protocol:"https:",this.path=e.path?"/"!==e.path.charAt(0)?`/${e.path}`:e.path:"/",this.username=e.username,this.password=e.password,this.fragment=e.fragment}static clone(e){const t=new HttpRequest({...e,headers:{...e.headers}});return t.query&&(t.query=cloneQuery(t.query)),t}static isInstance(e){if(!e)return!1;const t=e;return"method"in t&&"protocol"in t&&"hostname"in t&&"path"in t&&"object"==typeof t.query&&"object"==typeof t.headers}clone(){return HttpRequest.clone(this)}}function cloneQuery(e){return Object.keys(e).reduce(((t,n)=>{const i=e[n];return{...t,[n]:Array.isArray(i)?[...i]:i}}),{})}class HttpResponse{constructor(e){this.statusCode=e.statusCode,this.reason=e.reason,this.headers=e.headers||{},this.body=e.body}static isInstance(e){if(!e)return!1;const t=e;return"number"==typeof t.statusCode&&"object"==typeof t.headers}}var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},iterator$1,hasRequiredIterator$1,foreach,hasRequiredForeach;function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function getAugmentedNamespace(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var n=function e(){var n=!1;try{n=this instanceof e}catch{}return n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach((function(t){var i=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,i.get?i:{enumerable:!0,get:function(){return e[t]}})})),n}function requireIterator$1(){if(hasRequiredIterator$1)return iterator$1;function e(e){Object.defineProperty(this,"_next",{writable:!1,enumerable:!1,value:e}),this.done=!1}return hasRequiredIterator$1=1,e.prototype.next=function(){if(this.done)return{done:!0};var e=this._next();return e.done&&(this.done=!0),e},"undefined"!=typeof Symbol&&(e.prototype[Symbol.iterator]=function(){return this}),e.of=function(){var t=arguments,n=t.length,i=0;return new e((function(){return i>=n?{done:!0}:{done:!1,value:t[i++]}}))},e.empty=function(){var t=new e(null);return t.done=!0,t},e.is=function(t){return t instanceof e||"object"==typeof t&&null!==t&&"function"==typeof t.next},iterator$1=e}function requireForeach(){if(hasRequiredForeach)return foreach;hasRequiredForeach=1;var e="undefined"!=typeof ArrayBuffer,t="undefined"!=typeof Symbol;function n(n,i){var r,o,a,s,c;if(!n)throw new Error("obliterator/forEach: invalid iterable.");if("function"!=typeof i)throw new Error("obliterator/forEach: expecting a callback.");if(Array.isArray(n)||e&&ArrayBuffer.isView(n)||"string"==typeof n||"[object Arguments]"===n.toString())for(a=0,s=n.length;a<s;a++)i(n[a],a);else if("function"!=typeof n.forEach)if(t&&Symbol.iterator in n&&"function"!=typeof n.next&&(n=n[Symbol.iterator]()),"function"!=typeof n.next)for(o in n)n.hasOwnProperty(o)&&i(n[o],o);else for(r=n,a=0;!0!==(c=r.next()).done;)i(c.value,a),a++;else n.forEach(i)}return n.forEachWithNullKeys=function(n,i){var r,o,a,s,c;if(!n)throw new Error("obliterator/forEachWithNullKeys: invalid iterable.");if("function"!=typeof i)throw new Error("obliterator/forEachWithNullKeys: expecting a callback.");if(Array.isArray(n)||e&&ArrayBuffer.isView(n)||"string"==typeof n||"[object Arguments]"===n.toString())for(a=0,s=n.length;a<s;a++)i(n[a],null);else if(n instanceof Set)n.forEach((function(e){i(e,null)}));else if("function"!=typeof n.forEach)if(t&&Symbol.iterator in n&&"function"!=typeof n.next&&(n=n[Symbol.iterator]()),"function"!=typeof n.next)for(o in n)n.hasOwnProperty(o)&&i(n[o],o);else for(r=n,a=0;!0!==(c=r.next()).done;)i(c.value,null),a++;else n.forEach(i)},foreach=n}var typedArrays={},hasRequiredTypedArrays;function requireTypedArrays(){return hasRequiredTypedArrays||(hasRequiredTypedArrays=1,function(e){var t=Math.pow(2,8)-1,n=Math.pow(2,16)-1,i=Math.pow(2,32)-1,r=Math.pow(2,7)-1,o=Math.pow(2,15)-1,a=Math.pow(2,31)-1;e.getPointerArray=function(e){var r=e-1;return r<=t?Uint8Array:r<=n?Uint16Array:r<=i?Uint32Array:Float64Array},e.getSignedPointerArray=function(e){var t=e-1;return t<=r?Int8Array:t<=o?Int16Array:t<=a?Int32Array:Float64Array},e.getNumberType=function(e){return e===(0|e)?-1===Math.sign(e)?e<=127&&e>=-128?Int8Array:e<=32767&&e>=-32768?Int16Array:Int32Array:e<=255?Uint8Array:e<=65535?Uint16Array:Uint32Array:Float64Array};var s={Uint8Array:1,Int8Array:2,Uint16Array:3,Int16Array:4,Uint32Array:5,Int32Array:6,Float32Array:7,Float64Array:8};e.getMinimalRepresentation=function(t,n){var i,r,o,a,c,l=null,d=0;for(a=0,c=t.length;a<c;a++)o=n?n(t[a]):t[a],r=e.getNumberType(o),(i=s[r.name])>d&&(d=i,l=r);return l},e.isTypedArray=function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)},e.concat=function(){var e,t,n,i=0;for(e=0,n=arguments.length;e<n;e++)i+=arguments[e].length;var r=new arguments[0].constructor(i);for(e=0,t=0;e<n;e++)r.set(arguments[e],t),t+=arguments[e].length;return r},e.indices=function(t){for(var n=new(e.getPointerArray(t))(t),i=0;i<t;i++)n[i]=i;return n}}(typedArrays)),typedArrays}var iterables={},hasRequiredIterables,lruCache,hasRequiredLruCache;function requireIterables(){if(hasRequiredIterables)return iterables;hasRequiredIterables=1;var e=requireForeach(),t=requireTypedArrays();function n(e){return"number"==typeof e.length?e.length:"number"==typeof e.size?e.size:void 0}return iterables.isArrayLike=function(e){return Array.isArray(e)||t.isTypedArray(e)},iterables.guessLength=n,iterables.toArray=function(t){var i=n(t),r="number"==typeof i?new Array(i):[],o=0;return e(t,(function(e){r[o++]=e})),r},iterables.toArrayWithIndices=function(i){var r=n(i),o="number"==typeof r?t.getPointerArray(r):Array,a="number"==typeof r?new Array(r):[],s="number"==typeof r?new o(r):[],c=0;return e(i,(function(e){a[c]=e,s[c]=c++})),[a,s]},iterables}function requireLruCache(){if(hasRequiredLruCache)return lruCache;hasRequiredLruCache=1;var e=requireIterator$1(),t=requireForeach(),n=requireTypedArrays(),i=requireIterables();function r(e,t,i){if(arguments.length<2&&(i=e,e=null,t=null),this.capacity=i,"number"!=typeof this.capacity||this.capacity<=0)throw new Error("mnemonist/lru-cache: capacity should be positive number.");var r=n.getPointerArray(i);this.forward=new r(i),this.backward=new r(i),this.K="function"==typeof e?new e(i):new Array(i),this.V="function"==typeof t?new t(i):new Array(i),this.size=0,this.head=0,this.tail=0,this.items={}}return r.prototype.clear=function(){this.size=0,this.head=0,this.tail=0,this.items={}},r.prototype.splayOnTop=function(e){var t=this.head;if(this.head===e)return this;var n=this.backward[e],i=this.forward[e];return this.tail===e?this.tail=n:this.backward[i]=n,this.forward[n]=i,this.backward[t]=e,this.head=e,this.forward[e]=t,this},r.prototype.set=function(e,t){var n=this.items[e];if(void 0!==n)return this.splayOnTop(n),void(this.V[n]=t);this.size<this.capacity?n=this.size++:(n=this.tail,this.tail=this.backward[n],delete this.items[this.K[n]]),this.items[e]=n,this.K[n]=e,this.V[n]=t,this.forward[n]=this.head,this.backward[this.head]=n,this.head=n},r.prototype.setpop=function(e,t){var n=null,i=null,r=this.items[e];return void 0!==r?(this.splayOnTop(r),n=this.V[r],this.V[r]=t,{evicted:!1,key:e,value:n}):(this.size<this.capacity?r=this.size++:(r=this.tail,this.tail=this.backward[r],n=this.V[r],i=this.K[r],delete this.items[this.K[r]]),this.items[e]=r,this.K[r]=e,this.V[r]=t,this.forward[r]=this.head,this.backward[this.head]=r,this.head=r,i?{evicted:!0,key:i,value:n}:null)},r.prototype.has=function(e){return e in this.items},r.prototype.get=function(e){var t=this.items[e];if(void 0!==t)return this.splayOnTop(t),this.V[t]},r.prototype.peek=function(e){var t=this.items[e];if(void 0!==t)return this.V[t]},r.prototype.forEach=function(e,t){t=arguments.length>1?t:this;for(var n=0,i=this.size,r=this.head,o=this.K,a=this.V,s=this.forward;n<i;)e.call(t,a[r],o[r],this),r=s[r],n++},r.prototype.keys=function(){var t=0,n=this.size,i=this.head,r=this.K,o=this.forward;return new e((function(){if(t>=n)return{done:!0};var e=r[i];return++t<n&&(i=o[i]),{done:!1,value:e}}))},r.prototype.values=function(){var t=0,n=this.size,i=this.head,r=this.V,o=this.forward;return new e((function(){if(t>=n)return{done:!0};var e=r[i];return++t<n&&(i=o[i]),{done:!1,value:e}}))},r.prototype.entries=function(){var t=0,n=this.size,i=this.head,r=this.K,o=this.V,a=this.forward;return new e((function(){if(t>=n)return{done:!0};var e=r[i],s=o[i];return++t<n&&(i=a[i]),{done:!1,value:[e,s]}}))},"undefined"!=typeof Symbol&&(r.prototype[Symbol.iterator]=r.prototype.entries),r.prototype.inspect=function(){for(var e,t=new Map,n=this.entries();!(e=n.next()).done;)t.set(e.value[0],e.value[1]);return Object.defineProperty(t,"constructor",{value:r,enumerable:!1}),t},"undefined"!=typeof Symbol&&(r.prototype[Symbol.for("nodejs.util.inspect.custom")]=r.prototype.inspect),r.from=function(e,n,o,a){if(arguments.length<2){if("number"!=typeof(a=i.guessLength(e)))throw new Error("mnemonist/lru-cache.from: could not guess iterable length. Please provide desired capacity as last argument.")}else 2===arguments.length&&(a=n,n=null,o=null);var s=new r(n,o,a);return t(e,(function(e,t){s.set(t,e)})),s},lruCache=r}var lruCacheExports=requireLruCache(),LRUCache=getDefaultExportFromCjs(lruCacheExports);let EndpointCache$1=class{cache;constructor(e){this.cache=new LRUCache(e)}getEndpoint(e){const t=this.get(e);if(!t||0===t.length)return;const n=t.map((e=>e.Address));return n[Math.floor(Math.random()*n.length)]}get(e){if(!this.has(e))return;const t=this.cache.get(e);if(!t)return;const n=Date.now(),i=t.filter((e=>n<e.Expires));if(0!==i.length)return i;this.delete(e)}set(e,t){const n=Date.now();this.cache.set(e,t.map((({Address:e,CachePeriodInMinutes:t})=>({Address:e,Expires:n+60*t*1e3}))))}delete(e){this.cache.set(e,[])}has(e){if(!this.cache.has(e))return!1;const t=this.cache.peek(e);return!!t&&t.length>0}clear(){this.cache.clear()}};const resolveEndpointDiscoveryConfig=(e,{endpointDiscoveryCommandCtor:t})=>{const{endpointCacheSize:n,endpointDiscoveryEnabled:i,endpointDiscoveryEnabledProvider:r}=e;return Object.assign(e,{endpointDiscoveryCommandCtor:t,endpointCache:new EndpointCache$1(n??1e3),endpointDiscoveryEnabled:void 0!==i?()=>Promise.resolve(i):r,isClientEndpointDiscoveryEnabled:void 0!==i})};function resolveHostHeaderConfig(e){return e}const hostHeaderMiddleware=e=>t=>async n=>{if(!HttpRequest.isInstance(n.request))return t(n);const{request:i}=n,{handlerProtocol:r=""}=e.requestHandler.metadata||{};if(r.indexOf("h2")>=0&&!i.headers[":authority"])delete i.headers.host,i.headers[":authority"]=i.hostname+(i.port?":"+i.port:"");else if(!i.headers.host){let e=i.hostname;null!=i.port&&(e+=`:${i.port}`),i.headers.host=e}return t(n)},hostHeaderMiddlewareOptions={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},getHostHeaderPlugin=e=>({applyToStack:t=>{t.add(hostHeaderMiddleware(e),hostHeaderMiddlewareOptions)}}),loggerMiddleware=()=>(e,t)=>async n=>{try{const i=await e(n),{clientName:r,commandName:o,logger:a,dynamoDbDocumentClientOptions:s={}}=t,{overrideInputFilterSensitiveLog:c,overrideOutputFilterSensitiveLog:l}=s,d=c??t.inputFilterSensitiveLog,u=l??t.outputFilterSensitiveLog,{$metadata:p,...m}=i.output;return a?.info?.({clientName:r,commandName:o,input:d(n.input),output:u(m),metadata:p}),i}catch(e){const{clientName:i,commandName:r,logger:o,dynamoDbDocumentClientOptions:a={}}=t,{overrideInputFilterSensitiveLog:s}=a,c=s??t.inputFilterSensitiveLog;throw o?.error?.({clientName:i,commandName:r,input:c(n.input),error:e,metadata:e.$metadata}),e}},loggerMiddlewareOptions={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},getLoggerPlugin=e=>({applyToStack:e=>{e.add(loggerMiddleware(),loggerMiddlewareOptions)}}),TRACE_ID_HEADER_NAME="X-Amzn-Trace-Id",ENV_LAMBDA_FUNCTION_NAME="AWS_LAMBDA_FUNCTION_NAME",ENV_TRACE_ID="_X_AMZN_TRACE_ID",recursionDetectionMiddleware=e=>t=>async n=>{const{request:i}=n;if(!HttpRequest.isInstance(i)||"node"!==e.runtime)return t(n);const r=Object.keys(i.headers??{}).find((e=>e.toLowerCase()===TRACE_ID_HEADER_NAME.toLowerCase()))??TRACE_ID_HEADER_NAME;if(i.headers.hasOwnProperty(r))return t(n);const o=[][ENV_TRACE_ID],a=e=>"string"==typeof e&&e.length>0;return a([][ENV_LAMBDA_FUNCTION_NAME])&&a(o)&&(i.headers[TRACE_ID_HEADER_NAME]=o),t({...n,request:i})},addRecursionDetectionMiddlewareOptions={step:"build",tags:["RECURSION_DETECTION"],name:"recursionDetectionMiddleware",override:!0,priority:"low"},getRecursionDetectionPlugin=e=>({applyToStack:t=>{t.add(recursionDetectionMiddleware(e),addRecursionDetectionMiddlewareOptions)}}),resolveAuthOptions=(e,t)=>{if(!t||0===t.length)return e;const n=[];for(const i of t)for(const t of e){t.schemeId.split("#")[1]===i&&n.push(t)}for(const t of e)n.find((({schemeId:e})=>e===t.schemeId))||n.push(t);return n};function convertHttpAuthSchemesToMap(e){const t=new Map;for(const n of e)t.set(n.schemeId,n);return t}const httpAuthSchemeMiddleware=(e,t)=>(n,i)=>async r=>{const o=e.httpAuthSchemeProvider(await t.httpAuthSchemeParametersProvider(e,i,r.input)),a=e.authSchemePreference?await e.authSchemePreference():[],s=resolveAuthOptions(o,a),c=convertHttpAuthSchemesToMap(e.httpAuthSchemes),l=getSmithyContext(i),d=[];for(const n of s){const r=c.get(n.schemeId);if(!r){d.push(`HttpAuthScheme \`${n.schemeId}\` was not enabled for this service.`);continue}const o=r.identityProvider(await t.identityProviderConfigProvider(e));if(!o){d.push(`HttpAuthScheme \`${n.schemeId}\` did not have an IdentityProvider configured.`);continue}const{identityProperties:a={},signingProperties:s={}}=n.propertiesExtractor?.(e,i)||{};n.identityProperties=Object.assign(n.identityProperties||{},a),n.signingProperties=Object.assign(n.signingProperties||{},s),l.selectedHttpAuthScheme={httpAuthOption:n,identity:await o(n.identityProperties),signer:r.signer};break}if(!l.selectedHttpAuthScheme)throw new Error(d.join("\n"));return n(r)},httpAuthSchemeEndpointRuleSetMiddlewareOptions={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},getHttpAuthSchemeEndpointRuleSetPlugin=(e,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:n})=>({applyToStack:i=>{i.addRelativeTo(httpAuthSchemeMiddleware(e,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:n}),httpAuthSchemeEndpointRuleSetMiddlewareOptions)}}),deserializerMiddleware=(e,t)=>(n,i)=>async r=>{const{response:o}=await n(r);try{return{response:o,output:await t(o,e)}}catch(e){if(Object.defineProperty(e,"$response",{value:o}),!("$metadata"in e)){const t="Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.";try{e.message+="\n "+t}catch(e){i.logger&&"NoOpLogger"!==i.logger?.constructor?.name?i.logger?.warn?.(t):console.warn(t)}void 0!==e.$responseBodyText&&e.$response&&(e.$response.body=e.$responseBodyText);try{if(HttpResponse.isInstance(o)){const{headers:t={}}=o,n=Object.entries(t);e.$metadata={httpStatusCode:o.statusCode,requestId:findHeader(/^x-[\w-]+-request-?id$/,n),extendedRequestId:findHeader(/^x-[\w-]+-id-2$/,n),cfId:findHeader(/^x-[\w-]+-cf-id$/,n)}}}catch(e){}}throw e}},findHeader=(e,t)=>(t.find((([t])=>t.match(e)))||[void 0,void 0])[1],serializerMiddleware=(e,t)=>(n,i)=>async r=>{const o=e,a=i.endpointV2?.url&&o.urlParser?async()=>o.urlParser(i.endpointV2.url):o.endpoint;if(!a)throw new Error("No valid endpoint provider available.");const s=await t(r.input,{...e,endpoint:a});return n({...r,request:s})},deserializerMiddlewareOption={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},serializerMiddlewareOption={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function getSerdePlugin(e,t,n){return{applyToStack:i=>{i.add(deserializerMiddleware(e,n),deserializerMiddlewareOption),i.add(serializerMiddleware(e,t),serializerMiddlewareOption)}}}serializerMiddlewareOption.name;const defaultErrorHandler=e=>e=>{throw e},defaultSuccessHandler=(e,t)=>{},httpSigningMiddleware=e=>(e,t)=>async n=>{if(!HttpRequest.isInstance(n.request))return e(n);const i=getSmithyContext(t).selectedHttpAuthScheme;if(!i)throw new Error("No HttpAuthScheme was selected: unable to sign request");const{httpAuthOption:{signingProperties:r={}},identity:o,signer:a}=i,s=await e({...n,request:await a.sign(n.request,o,r)}).catch((a.errorHandler||defaultErrorHandler)(r));return(a.successHandler||defaultSuccessHandler)(s.response,r),s},httpSigningMiddlewareOptions={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},getHttpSigningPlugin=e=>({applyToStack:e=>{e.addRelativeTo(httpSigningMiddleware(),httpSigningMiddlewareOptions)}}),normalizeProvider=e=>{if("function"==typeof e)return e;const t=Promise.resolve(e);return()=>t},makePagedClientRequest=async(e,t,n,i=e=>e,...r)=>{let o=new e(n);return o=i(o)??o,await t.send(o,...r)};function createPaginator(e,t,n,i,r){return async function*(o,a,...s){const c=a;let l,d=o.startingToken??c[n],u=!0;for(;u;){if(c[n]=d,r&&(c[r]=c[r]??o.pageSize),!(o.client instanceof e))throw new Error(`Invalid client, expected instance of ${e.name}`);l=await makePagedClientRequest(t,o.client,a,o.withCommand,...s),yield l;const p=d;d=get(l,i),u=!(!d||o.stopOnSameToken&&d===p)}}}const get=(e,t)=>{let n=e;const i=t.split(".");for(const e of i){if(!n||"object"!=typeof n)return;n=n[e]}return n},alphabetByEncoding={},alphabetByValue=new Array(64);for(let e=0,t="A".charCodeAt(0),n="Z".charCodeAt(0);e+t<=n;e++){const n=String.fromCharCode(e+t);alphabetByEncoding[n]=e,alphabetByValue[e]=n}for(let e=0,t="a".charCodeAt(0),n="z".charCodeAt(0);e+t<=n;e++){const n=String.fromCharCode(e+t),i=e+26;alphabetByEncoding[n]=i,alphabetByValue[i]=n}for(let e=0;e<10;e++){alphabetByEncoding[e.toString(10)]=e+52;const t=e.toString(10),n=e+52;alphabetByEncoding[t]=n,alphabetByValue[n]=t}alphabetByEncoding["+"]=62,alphabetByValue[62]="+",alphabetByEncoding["/"]=63,alphabetByValue[63]="/";const bitsPerLetter=6,bitsPerByte=8,maxLetterValue=63,fromBase64=e=>{let t=e.length/4*3;"=="===e.slice(-2)?t-=2:"="===e.slice(-1)&&t--;const n=new ArrayBuffer(t),i=new DataView(n);for(let t=0;t<e.length;t+=4){let n=0,r=0;for(let i=t,o=t+3;i<=o;i++)if("="!==e[i]){if(!(e[i]in alphabetByEncoding))throw new TypeError(`Invalid character ${e[i]} in base64 string.`);n|=alphabetByEncoding[e[i]]<<(o-i)*bitsPerLetter,r+=bitsPerLetter}else n>>=bitsPerLetter;const o=t/4*3;n>>=r%bitsPerByte;const a=Math.floor(r/bitsPerByte);for(let e=0;e<a;e++){const t=(a-e-1)*bitsPerByte;i.setUint8(o+e,(n&255<<t)>>t)}}return new Uint8Array(n)},fromUtf8$2=e=>(new TextEncoder).encode(e),toUint8Array=e=>"string"==typeof e?fromUtf8$2(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e),toUtf8=e=>{if("string"==typeof e)return e;if("object"!=typeof e||"number"!=typeof e.byteOffset||"number"!=typeof e.byteLength)throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return new TextDecoder("utf-8").decode(e)};function toBase64(e){let t;t="string"==typeof e?fromUtf8$2(e):e;const n="object"==typeof t&&"number"==typeof t.length,i="object"==typeof t&&"number"==typeof t.byteOffset&&"number"==typeof t.byteLength;if(!n&&!i)throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");let r="";for(let e=0;e<t.length;e+=3){let n=0,i=0;for(let r=e,o=Math.min(e+3,t.length);r<o;r++)n|=t[r]<<(o-r-1)*bitsPerByte,i+=bitsPerByte;const o=Math.ceil(i/bitsPerLetter);n<<=o*bitsPerLetter-i;for(let e=1;e<=o;e++){const t=(o-e)*bitsPerLetter;r+=alphabetByValue[(n&maxLetterValue<<t)>>t]}r+="==".slice(0,4-o)}return r}function transformToString(e,t="utf-8"){return"base64"===t?toBase64(e):toUtf8(e)}function transformFromString(e,t){return"base64"===t?Uint8ArrayBlobAdapter.mutate(fromBase64(e)):Uint8ArrayBlobAdapter.mutate(fromUtf8$2(e))}class Uint8ArrayBlobAdapter extends Uint8Array{static fromString(e,t="utf-8"){if("string"==typeof e)return transformFromString(e,t);throw new Error(`Unsupported conversion from ${typeof e} to Uint8ArrayBlobAdapter.`)}static mutate(e){return Object.setPrototypeOf(e,Uint8ArrayBlobAdapter.prototype),e}transformToString(e="utf-8"){return transformToString(this,e)}}const escapeUri=e=>encodeURIComponent(e).replace(/[!'()*]/g,hexEncode),hexEncode=e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`;function buildQueryString(e){const t=[];for(let n of Object.keys(e).sort()){const i=e[n];if(n=escapeUri(n),Array.isArray(i))for(let e=0,r=i.length;e<r;e++)t.push(`${n}=${escapeUri(i[e])}`);else{let e=n;(i||"string"==typeof i)&&(e+=`=${escapeUri(i)}`),t.push(e)}}return t.join("&")}function createRequest(e,t){return new Request(e,t)}function requestTimeout(e=0){return new Promise(((t,n)=>{e&&setTimeout((()=>{const t=new Error(`Request did not complete within ${e} ms`);t.name="TimeoutError",n(t)}),e)}))}const keepAliveSupport={supported:void 0};class FetchHttpHandler{static create(e){return"function"==typeof e?.handle?e:new FetchHttpHandler(e)}constructor(e){"function"==typeof e?this.configProvider=e().then((e=>e||{})):(this.config=e??{},this.configProvider=Promise.resolve(this.config)),void 0===keepAliveSupport.supported&&(keepAliveSupport.supported=Boolean("undefined"!=typeof Request&&"keepalive"in createRequest("https://[::1]")))}destroy(){}async handle(e,{abortSignal:t}={}){this.config||(this.config=await this.configProvider);const n=this.config.requestTimeout,i=!0===this.config.keepAlive,r=this.config.credentials;if(t?.aborted){const e=new Error("Request aborted");return e.name="AbortError",Promise.reject(e)}let o=e.path;const a=buildQueryString(e.query||{});a&&(o+=`?${a}`),e.fragment&&(o+=`#${e.fragment}`);let s="";if(null!=e.username||null!=e.password){s=`${e.username??""}:${e.password??""}@`}const{port:c,method:l}=e,d=`${e.protocol}//${s}${e.hostname}${c?`:${c}`:""}${o}`,u="GET"===l||"HEAD"===l?void 0:e.body,p={body:u,headers:new Headers(e.headers),method:l,credentials:r};this.config?.cache&&(p.cache=this.config.cache),u&&(p.duplex="half"),"undefined"!=typeof AbortController&&(p.signal=t),keepAliveSupport.supported&&(p.keepalive=i),"function"==typeof this.config.requestInit&&Object.assign(p,this.config.requestInit(e));let m=()=>{};const h=createRequest(d,p),f=[fetch(h).then((e=>{const t=e.headers,n={};for(const e of t.entries())n[e[0]]=e[1];return null!=e.body?{response:new HttpResponse({headers:n,reason:e.statusText,statusCode:e.status,body:e.body})}:e.blob().then((t=>({response:new HttpResponse({headers:n,reason:e.statusText,statusCode:e.status,body:t})})))})),requestTimeout(n)];return t&&f.push(new Promise(((e,n)=>{const i=()=>{const e=new Error("Request aborted");e.name="AbortError",n(e)};if("function"==typeof t.addEventListener){const e=t;e.addEventListener("abort",i,{once:!0}),m=()=>e.removeEventListener("abort",i)}else t.onabort=i}))),Promise.race(f).finally(m)}updateHttpClientConfig(e,t){this.config=void 0,this.configProvider=this.configProvider.then((n=>(n[e]=t,n)))}httpHandlerConfigs(){return this.config??{}}}const streamCollector=async e=>"function"==typeof Blob&&e instanceof Blob||"Blob"===e.constructor?.name?void 0!==Blob.prototype.arrayBuffer?new Uint8Array(await e.arrayBuffer()):collectBlob(e):collectStream(e);async function collectBlob(e){const t=await readToBase64(e),n=fromBase64(t);return new Uint8Array(n)}async function collectStream(e){const t=[],n=e.getReader();let i=!1,r=0;for(;!i;){const{done:e,value:o}=await n.read();o&&(t.push(o),r+=o.length),i=e}const o=new Uint8Array(r);let a=0;for(const e of t)o.set(e,a),a+=e.length;return o}function readToBase64(e){return new Promise(((t,n)=>{const i=new FileReader;i.onloadend=()=>{if(2!==i.readyState)return n(new Error("Reader aborted too early"));const e=i.result??"",r=e.indexOf(","),o=r>-1?r+1:e.length;t(e.substring(o))},i.onabort=()=>n(new Error("Read aborted")),i.onerror=()=>n(i.error),i.readAsDataURL(e)}))}const SHORT_TO_HEX={},HEX_TO_SHORT={};for(let e=0;e<256;e++){let t=e.toString(16).toLowerCase();1===t.length&&(t=`0${t}`),SHORT_TO_HEX[e]=t,HEX_TO_SHORT[t]=e}function fromHex(e){if(e.length%2!=0)throw new Error("Hex encoded strings must have an even number length");const t=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2){const i=e.slice(n,n+2).toLowerCase();if(!(i in HEX_TO_SHORT))throw new Error(`Cannot decode unrecognized sequence ${i} as hexadecimal`);t[n/2]=HEX_TO_SHORT[i]}return t}function toHex(e){let t="";for(let n=0;n<e.byteLength;n++)t+=SHORT_TO_HEX[e[n]];return t}const collectBody=async(e=new Uint8Array,t)=>{if(e instanceof Uint8Array)return Uint8ArrayBlobAdapter.mutate(e);if(!e)return Uint8ArrayBlobAdapter.mutate(new Uint8Array);const n=t.streamCollector(e);return Uint8ArrayBlobAdapter.mutate(await n)};function extendedEncodeURIComponent(e){return encodeURIComponent(e).replace(/[!'()*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))}const parseBoolean=e=>{switch(e){case"true":return!0;case"false":return!1;default:throw new Error(`Unable to parse boolean value "${e}"`)}},expectBoolean=e=>{if(null!=e){if("number"==typeof e){if(0!==e&&1!==e||logger$2.warn(stackTraceWarning(`Expected boolean, got ${typeof e}: ${e}`)),0===e)return!1;if(1===e)return!0}if("string"==typeof e){const t=e.toLowerCase();if("false"!==t&&"true"!==t||logger$2.warn(stackTraceWarning(`Expected boolean, got ${typeof e}: ${e}`)),"false"===t)return!1;if("true"===t)return!0}if("boolean"==typeof e)return e;throw new TypeError(`Expected boolean, got ${typeof e}: ${e}`)}},expectNumber=e=>{if(null!=e){if("string"==typeof e){const t=parseFloat(e);if(!Number.isNaN(t))return String(t)!==String(e)&&logger$2.warn(stackTraceWarning(`Expected number but observed string: ${e}`)),t}if("number"==typeof e)return e;throw new TypeError(`Expected number, got ${typeof e}: ${e}`)}},MAX_FLOAT=Math.ceil(2**127*(2-2**-23)),expectFloat32=e=>{const t=expectNumber(e);if(void 0!==t&&!Number.isNaN(t)&&t!==1/0&&t!==-1/0&&Math.abs(t)>MAX_FLOAT)throw new TypeError(`Expected 32-bit float, got ${e}`);return t},expectLong=e=>{if(null!=e){if(Number.isInteger(e)&&!Number.isNaN(e))return e;throw new TypeError(`Expected integer, got ${typeof e}: ${e}`)}},expectInt32=e=>expectSizedInt(e,32),expectShort=e=>expectSizedInt(e,16),expectByte=e=>expectSizedInt(e,8),expectSizedInt=(e,t)=>{const n=expectLong(e);if(void 0!==n&&castInt(n,t)!==n)throw new TypeError(`Expected ${t}-bit integer, got ${e}`);return n},castInt=(e,t)=>{switch(t){case 32:return Int32Array.of(e)[0];case 16:return Int16Array.of(e)[0];case 8:return Int8Array.of(e)[0]}},expectNonNull=(e,t)=>{if(null==e)throw new TypeError("Expected a non-null value");return e},expectObject=e=>{if(null==e)return;if("object"==typeof e&&!Array.isArray(e))return e;const t=Array.isArray(e)?"array":typeof e;throw new TypeError(`Expected object, got ${t}: ${e}`)},expectString=e=>{if(null!=e){if("string"==typeof e)return e;if(["boolean","number","bigint"].includes(typeof e))return logger$2.warn(stackTraceWarning(`Expected string, got ${typeof e}: ${e}`)),String(e);throw new TypeError(`Expected string, got ${typeof e}: ${e}`)}},expectUnion=e=>{if(null==e)return;const t=expectObject(e),n=Object.entries(t).filter((([,e])=>null!=e)).map((([e])=>e));if(0===n.length)throw new TypeError("Unions must have exactly one non-null member. None were found.");if(n.length>1)throw new TypeError(`Unions must have exactly one non-null member. Keys ${n} were not null.`);return t},strictParseDouble=e=>expectNumber("string"==typeof e?parseNumber(e):e),strictParseFloat=strictParseDouble,strictParseFloat32=e=>expectFloat32("string"==typeof e?parseNumber(e):e),NUMBER_REGEX=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,parseNumber=e=>{const t=e.match(NUMBER_REGEX);if(null===t||t[0].length!==e.length)throw new TypeError("Expected real number, got implicit NaN");return parseFloat(e)},limitedParseDouble=e=>"string"==typeof e?parseFloatString(e):expectNumber(e),parseFloatString=e=>{switch(e){case"NaN":return NaN;case"Infinity":return 1/0;case"-Infinity":return-1/0;default:throw new Error(`Unable to parse float value: ${e}`)}},strictParseLong=e=>expectLong("string"==typeof e?parseNumber(e):e),strictParseShort=e=>expectShort("string"==typeof e?parseNumber(e):e),strictParseByte=e=>expectByte("string"==typeof e?parseNumber(e):e),stackTraceWarning=e=>String(new TypeError(e).stack||e).split("\n").slice(0,5).filter((e=>!e.includes("stackTraceWarning"))).join("\n"),logger$2={warn:console.warn},MONTHS=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],RFC3339_WITH_OFFSET=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),parseRfc3339DateTimeWithOffset=e=>{if(null==e)return;if("string"!=typeof e)throw new TypeError("RFC-3339 date-times must be expressed as strings");const t=RFC3339_WITH_OFFSET.exec(e);if(!t)throw new TypeError("Invalid RFC-3339 date-time value");const[n,i,r,o,a,s,c,l,d]=t,u=strictParseShort(stripLeadingZeroes(i)),p=parseDateValue(r,"month",1,12),m=parseDateValue(o,"day",1,31),h=buildDate(u,p,m,{hours:a,minutes:s,seconds:c,fractionalMilliseconds:l});return"Z"!=d.toUpperCase()&&h.setTime(h.getTime()-parseOffsetToMilliseconds(d)),h},parseEpochTimestamp=e=>{if(null==e)return;let t;if("number"==typeof e)t=e;else if("string"==typeof e)t=strictParseDouble(e);else{if("object"!=typeof e||1!==e.tag)throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");t=e.value}if(Number.isNaN(t)||t===1/0||t===-1/0)throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(1e3*t))},buildDate=(e,t,n,i)=>{const r=t-1;return validateDayOfMonth(e,r,n),new Date(Date.UTC(e,r,n,parseDateValue(i.hours,"hour",0,23),parseDateValue(i.minutes,"minute",0,59),parseDateValue(i.seconds,"seconds",0,60),parseMilliseconds(i.fractionalMilliseconds)))},DAYS_IN_MONTH=[31,28,31,30,31,30,31,31,30,31,30,31],validateDayOfMonth=(e,t,n)=>{let i=DAYS_IN_MONTH[t];if(1===t&&isLeapYear(e)&&(i=29),n>i)throw new TypeError(`Invalid day for ${MONTHS[t]} in ${e}: ${n}`)},isLeapYear=e=>e%4==0&&(e%100!=0||e%400==0),parseDateValue=(e,t,n,i)=>{const r=strictParseByte(stripLeadingZeroes(e));if(r<n||r>i)throw new TypeError(`${t} must be between ${n} and ${i}, inclusive`);return r},parseMilliseconds=e=>null==e?0:1e3*strictParseFloat32("0."+e),parseOffsetToMilliseconds=e=>{const t=e[0];let n=1;if("+"==t)n=1;else{if("-"!=t)throw new TypeError(`Offset direction, ${t}, must be "+" or "-"`);n=-1}return n*(60*Number(e.substring(1,3))+Number(e.substring(4,6)))*60*1e3},stripLeadingZeroes=e=>{let t=0;for(;t<e.length-1&&"0"===e.charAt(t);)t++;return 0===t?e:e.slice(t)},resolvedPath=(e,t,n,i,r,o)=>{if(null==t||void 0===t[n])throw new Error("No value provided for input HTTP label: "+n+".");{const t=i();if(t.length<=0)throw new Error("Empty value provided for input HTTP label: "+n+".");e=e.replace(r,o?t.split("/").map((e=>extendedEncodeURIComponent(e))).join("/"):extendedEncodeURIComponent(t))}return e};function requestBuilder(e,t){return new RequestBuilder(e,t)}class RequestBuilder{constructor(e,t){this.input=e,this.context=t,this.query={},this.method="",this.headers={},this.path="",this.body=null,this.hostname="",this.resolvePathStack=[]}async build(){const{hostname:e,protocol:t="https",port:n,path:i}=await this.context.endpoint();this.path=i;for(const e of this.resolvePathStack)e(this.path);return new HttpRequest({protocol:t,hostname:this.hostname||e,port:n,method:this.method,path:this.path,query:this.query,body:this.body,headers:this.headers})}hn(e){return this.hostname=e,this}bp(e){return this.resolvePathStack.push((t=>{this.path=`${t?.endsWith("/")?t.slice(0,-1):t||""}`+e})),this}p(e,t,n,i){return this.resolvePathStack.push((r=>{this.path=resolvedPath(r,this.input,e,t,n,i)})),this}h(e){return this.headers=e,this}q(e){return this.query=e,this}b(e){return this.body=e,this}m(e){return this.method=e,this}}function setFeature$1(e,t,n){e.__smithy_context?e.__smithy_context.features||(e.__smithy_context.features={}):e.__smithy_context={features:{}},e.__smithy_context.features[t]=n}class DefaultIdentityProviderConfig{constructor(e){this.authSchemes=new Map;for(const[t,n]of Object.entries(e))void 0!==n&&this.authSchemes.set(t,n)}getIdent