foundation-sdk 0.2.2 → 0.2.4

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.
@@ -0,0 +1,27 @@
1
+ "use strict";var FoundationSDK=(()=>{var cr=Object.defineProperty;var Ua=Object.getOwnPropertyDescriptor;var Oa=Object.getOwnPropertyNames;var Da=Object.prototype.hasOwnProperty;var dr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,o)=>(typeof require<"u"?require:t)[o]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Ma=(e,t)=>{for(var o in t)cr(e,o,{get:t[o],enumerable:!0})},ka=(e,t,o,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Oa(t))!Da.call(e,n)&&n!==o&&cr(e,n,{get:()=>t[n],enumerable:!(r=Ua(t,n))||r.enumerable});return e};var Fa=e=>ka(cr({},"__esModule",{value:!0}),e);var Ou={};Ma(Ou,{createFoundation:()=>va});var yn="Logging",ur="x-amz-user-agent",En="NoHubcallbackProvidedException";var se;(function(e){e.DEBUG="DEBUG",e.ERROR="ERROR",e.INFO="INFO",e.WARN="WARN",e.VERBOSE="VERBOSE",e.NONE="NONE"})(se||(se={}));var Sn={VERBOSE:1,DEBUG:2,INFO:3,WARN:4,ERROR:5,NONE:6},C=class e{constructor(t,o=se.WARN){this.name=t,this.level=o,this._pluggables=[]}_padding(t){return t<10?"0"+t:""+t}_ts(){let t=new Date;return[this._padding(t.getMinutes()),this._padding(t.getSeconds())].join(":")+"."+t.getMilliseconds()}configure(t){return t?(this._config=t,this._config):this._config}_log(t,...o){let r=this.level;e.LOG_LEVEL&&(r=e.LOG_LEVEL),typeof window<"u"&&window.LOG_LEVEL&&(r=window.LOG_LEVEL);let n=Sn[r];if(!(Sn[t]>=n))return;let s=console.log.bind(console);t===se.ERROR&&console.error&&(s=console.error.bind(console)),t===se.WARN&&console.warn&&(s=console.warn.bind(console)),e.BIND_ALL_LOG_LEVELS&&(t===se.INFO&&console.info&&(s=console.info.bind(console)),t===se.DEBUG&&console.debug&&(s=console.debug.bind(console)));let a=`[${t}] ${this._ts()} ${this.name}`,c="";if(o.length===1&&typeof o[0]=="string")c=`${a} - ${o[0]}`,s(c);else if(o.length===1)c=`${a} ${o[0]}`,s(a,o[0]);else if(typeof o[0]=="string"){let d=o.slice(1);d.length===1&&(d=d[0]),c=`${a} - ${o[0]} ${d}`,s(`${a} - ${o[0]}`,d)}else c=`${a} ${o}`,s(a,o);for(let d of this._pluggables){let u={message:c,timestamp:Date.now()};d.pushLogs([u])}}log(...t){this._log(se.INFO,...t)}info(...t){this._log(se.INFO,...t)}warn(...t){this._log(se.WARN,...t)}error(...t){this._log(se.ERROR,...t)}debug(...t){this._log(se.DEBUG,...t)}verbose(...t){this._log(se.VERBOSE,...t)}addPluggable(t){t&&t.getCategoryName()===yn&&(this._pluggables.push(t),t.configure(this._config))}listPluggables(){return this._pluggables}};C.LOG_LEVEL=null;C.BIND_ALL_LOG_LEVELS=!1;var U=class e extends Error{constructor({message:t,name:o,recoverySuggestion:r,underlyingError:n,metadata:i}){if(super(t),this.name=o,this.underlyingError=n,this.recoverySuggestion=r,i){let{extendedRequestId:s,httpStatusCode:a,requestId:c}=i;this.metadata={extendedRequestId:s,httpStatusCode:a,requestId:c}}this.constructor=e,Object.setPrototypeOf(this,e.prototype)}};var ue;(function(e){e.NoEndpointId="NoEndpointId",e.PlatformNotSupported="PlatformNotSupported",e.Unknown="Unknown",e.NetworkError="NetworkError"})(ue||(ue={}));var Se=(e,t=U)=>(o,r,n)=>{let{message:i,recoverySuggestion:s}=e[r];if(!o)throw new t({name:r,message:n?`${i} ${n}`:i,recoverySuggestion:s})};var j=typeof Symbol<"u"?Symbol("amplify_default"):"@@amplify_default",Dt=new C("Hub"),no=class{constructor(t){this.listeners=new Map,this.protectedChannels=["core","auth","api","analytics","interactions","pubsub","storage","ui","xr"],this.name=t}_remove(t,o){let r=this.listeners.get(t);if(!r){Dt.warn(`No listeners for ${t}`);return}this.listeners.set(t,[...r.filter(({callback:n})=>n!==o)])}dispatch(t,o,r,n){typeof t=="string"&&this.protectedChannels.indexOf(t)>-1&&(n===j||Dt.warn(`WARNING: ${t} is protected and dispatching on it can have unintended consequences`));let i={channel:t,payload:{...o},source:r,patternInfo:[]};try{this._toListeners(i)}catch(s){Dt.error(s)}}listen(t,o,r="noname"){let n;if(typeof o!="function")throw new U({name:En,message:"No callback supplied to Hub"});n=o;let i=this.listeners.get(t);return i||(i=[],this.listeners.set(t,i)),i.push({name:r,callback:n}),()=>{this._remove(t,n)}}_toListeners(t){let{channel:o,payload:r}=t,n=this.listeners.get(o);n&&n.forEach(i=>{Dt.debug(`Dispatching to ${o} with `,r);try{i.callback(t)}catch(s){Dt.error(s)}})}},Z=new no("__default__"),io=new no("internal-hub");var st=()=>{if(typeof window=="object"&&typeof window.crypto=="object")return window.crypto;if(typeof crypto=="object")return crypto;throw new U({name:"MissingPolyfill",message:"Cannot resolve the `crypto` function from the environment."})},In=()=>{if(typeof window<"u"&&typeof window.btoa=="function")return window.btoa;if(typeof btoa=="function")return btoa;throw new U({name:"Base64EncoderError",message:"Cannot resolve the `btoa` function from the environment."})},wn=()=>{if(typeof window<"u"&&typeof window.atob=="function")return window.atob;if(typeof atob=="function")return atob;throw new U({name:"Base64EncoderError",message:"Cannot resolve the `atob` function from the environment."})};var at={convert(e,t){let o=e;return t?.urlSafe&&(o=o.replace(/-/g,"+").replace(/_/g,"/")),wn()(o)}};var Ie;(function(e){e.AuthTokenConfigException="AuthTokenConfigException",e.AuthUserPoolAndIdentityPoolException="AuthUserPoolAndIdentityPoolException",e.AuthUserPoolException="AuthUserPoolException",e.InvalidIdentityPoolIdException="InvalidIdentityPoolIdException",e.OAuthNotConfigureException="OAuthNotConfigureException"})(Ie||(Ie={}));var La={[Ie.AuthTokenConfigException]:{message:"Auth Token Provider not configured.",recoverySuggestion:"Make sure to call Amplify.configure in your app."},[Ie.AuthUserPoolAndIdentityPoolException]:{message:"Auth UserPool or IdentityPool not configured.",recoverySuggestion:"Make sure to call Amplify.configure in your app with UserPoolId and IdentityPoolId."},[Ie.AuthUserPoolException]:{message:"Auth UserPool not configured.",recoverySuggestion:"Make sure to call Amplify.configure in your app with userPoolId and userPoolClientId."},[Ie.InvalidIdentityPoolIdException]:{message:"Invalid identity pool id provided.",recoverySuggestion:"Make sure a valid identityPoolId is given in the config."},[Ie.OAuthNotConfigureException]:{message:"oauth param not configured.",recoverySuggestion:"Make sure to call Amplify.configure with oauth parameter in your app."}},so=Se(La);function E(e){let t=!0;e?t=!!e.userPoolId&&!!e.userPoolClientId:t=!1,so(t,Ie.AuthUserPoolException)}function Le(e){let t=!!e?.loginWith?.oauth?.domain&&!!e?.loginWith?.oauth?.redirectSignOut&&!!e?.loginWith?.oauth?.redirectSignIn&&!!e?.loginWith?.oauth?.responseType;so(t,Ie.OAuthNotConfigureException)}function ct(e){let t=!!e?.identityPoolId;so(t,Ie.InvalidIdentityPoolIdException)}function Q(e){let t=e.split(".");if(t.length!==3)throw new Error("Invalid token");try{let r=t[1].replace(/-/g,"+").replace(/_/g,"/"),n=decodeURIComponent(at.convert(r).split("").map(s=>`%${`00${s.charCodeAt(0).toString(16)}`.slice(-2)}`).join("")),i=JSON.parse(n);return{toString:()=>e,payload:i}}catch{throw new Error("Invalid token payload")}}var pr=e=>{let t=Reflect.ownKeys(e);for(let o of t){let r=e[o];(r&&typeof r=="object"||typeof r=="function")&&pr(r)}return Object.freeze(e)};var Ba=new C("parseAWSExports"),Ha={API_KEY:"apiKey",AWS_IAM:"iam",AMAZON_COGNITO_USER_POOLS:"userPool",OPENID_CONNECT:"oidc",NONE:"none",AWS_LAMBDA:"lambda",LAMBDA:"lambda"},xn=(e={})=>{if(!Object.prototype.hasOwnProperty.call(e,"aws_project_region"))throw new U({name:"InvalidParameterException",message:"Invalid config parameter.",recoverySuggestion:"Ensure passing the config object imported from `amplifyconfiguration.json`."});let{aws_appsync_apiKey:t,aws_appsync_authenticationType:o,aws_appsync_graphqlEndpoint:r,aws_appsync_region:n,aws_bots_config:i,aws_cognito_identity_pool_id:s,aws_cognito_sign_up_verification_method:a,aws_cognito_mfa_configuration:c,aws_cognito_mfa_types:d,aws_cognito_password_protection_settings:u,aws_cognito_verification_mechanisms:p,aws_cognito_signup_attributes:l,aws_cognito_social_providers:m,aws_cognito_username_attributes:h,aws_mandatory_sign_in:I,aws_mobile_analytics_app_id:A,aws_mobile_analytics_app_region:S,aws_user_files_s3_bucket:M,aws_user_files_s3_bucket_region:H,aws_user_files_s3_dangerously_connect_to_http_endpoint_for_testing:le,aws_user_pools_id:ie,aws_user_pools_web_client_id:Ee,geo:F,oauth:nt,predictions:de,aws_cloud_logic_custom:yt,Notifications:Et,modelIntrospection:Fe}=e,$={};A&&($.Analytics={Pinpoint:{appId:A,region:S}});let{InAppMessaging:x,Push:X}=Et??{};if(x?.AWSPinpoint||X?.AWSPinpoint){if(x?.AWSPinpoint){let{appId:L,region:it}=x.AWSPinpoint;$.Notifications={InAppMessaging:{Pinpoint:{appId:L,region:it}}}}if(X?.AWSPinpoint){let{appId:L,region:it}=X.AWSPinpoint;$.Notifications={...$.Notifications,PushNotification:{Pinpoint:{appId:L,region:it}}}}}if(Array.isArray(i)&&($.Interactions={LexV1:Object.fromEntries(i.map(L=>[L.name,L]))}),r){let L=Ha[o];L||Ba.debug(`Invalid authentication type ${o}. Falling back to IAM.`),$.API={GraphQL:{endpoint:r,apiKey:t,region:n,defaultAuthMode:L??"iam"}},Fe&&($.API.GraphQL.modelIntrospection=Fe)}let ro=c?{status:c&&c.toLowerCase(),totpEnabled:d?.includes("TOTP")??!1,smsEnabled:d?.includes("SMS")??!1}:void 0,Pa=u?{minLength:u.passwordPolicyMinLength,requireLowercase:u.passwordPolicyCharacters?.includes("REQUIRES_LOWERCASE")??!1,requireUppercase:u.passwordPolicyCharacters?.includes("REQUIRES_UPPERCASE")??!1,requireNumbers:u.passwordPolicyCharacters?.includes("REQUIRES_NUMBERS")??!1,requireSpecialCharacters:u.passwordPolicyCharacters?.includes("REQUIRES_SYMBOLS")??!1}:void 0,Ta=Array.from(new Set([...p??[],...l??[]])).reduce((L,it)=>({...L,[it.toLowerCase()]:{required:!0}}),{}),mn=h?.includes("EMAIL")??!1,fn=h?.includes("PHONE_NUMBER")??!1;(s||ie)&&($.Auth={Cognito:{identityPoolId:s,allowGuestAccess:I!=="enable",signUpVerificationMethod:a,userAttributes:Ta,userPoolClientId:Ee,userPoolId:ie,mfa:ro,passwordFormat:Pa,loginWith:{username:!(mn||fn),email:mn,phone:fn}}});let Ra=nt?Object.keys(nt).length>0:!1,_a=m?m.length>0:!1;if($.Auth&&Ra&&($.Auth.Cognito.loginWith={...$.Auth.Cognito.loginWith,oauth:{...Ka(nt),..._a&&{providers:Wa(m)}}}),M&&($.Storage={S3:{bucket:M,region:H,dangerouslyConnectToHttpEndpointForTesting:le}}),F){let{amazon_location_service:L}=F;$.Geo={LocationService:{maps:L.maps,geofenceCollections:L.geofenceCollections,searchIndices:L.search_indices,region:L.region}}}if(yt&&($.API={...$.API,REST:yt.reduce((L,it)=>{let{name:Na,endpoint:ba,region:gn,service:hn}=it;return{...L,[Na]:{endpoint:ba,...hn?{service:hn}:void 0,...gn?{region:gn}:void 0}}},{})}),de){let{VoiceId:L}=de?.convert?.speechGenerator?.defaults??{};$.Predictions=L?{...de,convert:{...de.convert,speechGenerator:{...de.convert.speechGenerator,defaults:{voiceId:L}}}}:de}return $},An=e=>e?.split(",")??[],Ka=({domain:e,scope:t,redirectSignIn:o,redirectSignOut:r,responseType:n})=>({domain:e,scopes:t,redirectSignIn:An(o),redirectSignOut:An(r),responseType:n}),Wa=e=>e.map(t=>{let o=t.toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)});var Mt=Symbol("oauth-listener");var ee=[];for(let e=0;e<256;++e)ee.push((e+256).toString(16).slice(1));function Cn(e,t=0){return(ee[e[t+0]]+ee[e[t+1]]+ee[e[t+2]]+ee[e[t+3]]+"-"+ee[e[t+4]]+ee[e[t+5]]+"-"+ee[e[t+6]]+ee[e[t+7]]+"-"+ee[e[t+8]]+ee[e[t+9]]+"-"+ee[e[t+10]]+ee[e[t+11]]+ee[e[t+12]]+ee[e[t+13]]+ee[e[t+14]]+ee[e[t+15]]).toLowerCase()}var vn=dr("crypto"),co=new Uint8Array(256),ao=co.length;function lr(){return ao>co.length-16&&((0,vn.randomFillSync)(co),ao=0),co.slice(ao,ao+=16)}var Pn=dr("crypto"),mr={randomUUID:Pn.randomUUID};function Va(e,t,o){if(mr.randomUUID&&!t&&!e)return mr.randomUUID();e=e||{};let r=e.random??e.rng?.()??lr();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(o=o||0,o<0||o+16>t.length)throw new RangeError(`UUID byte range ${o}:${o+15} is out of buffer bounds`);for(let n=0;n<16;++n)t[o+n]=r[n];return t}return Cn(r)}var fr=Va;function Rn(e){let{version:t}=e;return t?t.startsWith("1"):!1}function za(e){if(!e)return;let{bucket_name:t,aws_region:o,buckets:r}=e;return{S3:{bucket:t,region:o,buckets:r&&ec(r)}}}function qa(e){if(!e)return;let{user_pool_id:t,user_pool_client_id:o,identity_pool_id:r,password_policy:n,mfa_configuration:i,mfa_methods:s,unauthenticated_identities_enabled:a,oauth:c,username_attributes:d,standard_required_attributes:u,groups:p,passwordless:l}=e,m={Cognito:{userPoolId:t,userPoolClientId:o,groups:p}};return r&&(m.Cognito={...m.Cognito,identityPoolId:r}),n&&(m.Cognito.passwordFormat={requireLowercase:n.require_lowercase,requireNumbers:n.require_numbers,requireUppercase:n.require_uppercase,requireSpecialCharacters:n.require_symbols,minLength:n.min_length??6}),i&&(m.Cognito.mfa={status:Qa(i),smsEnabled:s?.includes("SMS"),totpEnabled:s?.includes("TOTP")}),a&&(m.Cognito.allowGuestAccess=a),c&&(m.Cognito.loginWith={oauth:{domain:c.domain,redirectSignIn:c.redirect_sign_in_uri,redirectSignOut:c.redirect_sign_out_uri,responseType:c.response_type==="token"?"token":"code",scopes:c.scopes,providers:Za(c.identity_providers)}}),d&&(m.Cognito.loginWith={...m.Cognito.loginWith,email:d.includes("email"),phone:d.includes("phone_number"),username:d.includes("username")}),u&&(m.Cognito.userAttributes=u.reduce((h,I)=>({...h,[I]:{required:!0}}),{})),l&&(m.Cognito.passwordless={emailOtpEnabled:l.email_otp_enabled,smsOtpEnabled:l.sms_otp_enabled,webAuthn:l.web_authn?{relyingPartyId:l.web_authn.relying_party_id,userVerification:l.web_authn.user_verification}:void 0,preferredChallenge:l.preferred_challenge}),m}function $a(e){if(!e?.amazon_pinpoint)return;let{amazon_pinpoint:t}=e;return{Pinpoint:{appId:t.app_id,region:t.aws_region}}}function ja(e){if(!e)return;let{aws_region:t,geofence_collections:o,maps:r,search_indices:n}=e;return{LocationService:{region:t,searchIndices:n,geofenceCollections:o,maps:r}}}function Ga(e){if(!e)return;let{aws_region:t,default_authorization_type:o,url:r,api_key:n,model_introspection:i}=e;return{GraphQL:{endpoint:r,defaultAuthMode:Nn(o),region:t,apiKey:n,modelIntrospection:i}}}function Ya(e){if(!e?.events)return;let{url:t,aws_region:o,api_key:r,default_authorization_type:n}=e.events;return{Events:{endpoint:t,defaultAuthMode:Nn(n),region:o,apiKey:r}}}function Ja(e){if(!e)return;let{aws_region:t,channels:o,amazon_pinpoint_app_id:r}=e,n=o.includes("IN_APP_MESSAGING"),i=o.includes("APNS")||o.includes("FCM");if(!(n||i))return;let s={};return n&&(s.InAppMessaging={Pinpoint:{appId:r,region:t}}),i&&(s.PushNotification={Pinpoint:{appId:r,region:t}}),s}function _n(e){let t={};if(e.storage&&(t.Storage=za(e.storage)),e.auth&&(t.Auth=qa(e.auth)),e.analytics&&(t.Analytics=$a(e.analytics)),e.geo&&(t.Geo=ja(e.geo)),e.data&&(t.API=Ga(e.data)),e.custom){let o=Ya(e.custom);o&&"Events"in o&&(t.API={...t.API,...o})}return e.notifications&&(t.Notifications=Ja(e.notifications)),t}var Xa={AMAZON_COGNITO_USER_POOLS:"userPool",API_KEY:"apiKey",AWS_IAM:"iam",AWS_LAMBDA:"lambda",OPENID_CONNECT:"oidc"};function Nn(e){return Xa[e]}var Tn={GOOGLE:"Google",LOGIN_WITH_AMAZON:"Amazon",FACEBOOK:"Facebook",SIGN_IN_WITH_APPLE:"Apple"};function Za(e=[]){return e.reduce((t,o)=>(Tn[o]!==void 0&&t.push(Tn[o]),t),[])}function Qa(e){return e==="OPTIONAL"?"optional":e==="REQUIRED"?"on":"off"}function ec(e){let t={};return e.forEach(({name:o,bucket_name:r,aws_region:n,paths:i})=>{if(o in t)throw new Error(`Duplicate friendly name found: ${o}. Name must be unique.`);let s=i?Object.entries(i).reduce((a,[c,d])=>(d!==void 0&&(a[c]=d),a),{}):void 0;t[o]={bucketName:r,region:n,paths:s}}),t}var kt=e=>Object.keys(e).some(t=>t.startsWith("aws_"))?xn(e):Rn(e)?_n(e):e;function bn(e,t,o,r){function n(i){return i instanceof o?i:new o(function(s){s(i)})}return new(o||(o=Promise))(function(i,s){function a(u){try{d(r.next(u))}catch(p){s(p)}}function c(u){try{d(r.throw(u))}catch(p){s(p)}}function d(u){u.done?i(u.value):n(u.value).then(a,c)}d((r=r.apply(e,t||[])).next())})}function Un(e,t){var o={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},r,n,i,s=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function a(d){return function(u){return c([d,u])}}function c(d){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,d[0]&&(o=0)),o;)try{if(r=1,n&&(i=d[0]&2?n.return:d[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,d[1])).done)return i;switch(n=0,i&&(d=[d[0]&2,i.value]),d[0]){case 0:case 1:i=d;break;case 4:return o.label++,{value:d[1],done:!1};case 5:o.label++,n=d[1],d=[0];continue;case 7:d=o.ops.pop(),o.trys.pop();continue;default:if(i=o.trys,!(i=i.length>0&&i[i.length-1])&&(d[0]===6||d[0]===2)){o=0;continue}if(d[0]===3&&(!i||d[1]>i[0]&&d[1]<i[3])){o.label=d[1];break}if(d[0]===6&&o.label<i[1]){o.label=i[1],i=d;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(d);break}i[2]&&o.ops.pop(),o.trys.pop();continue}d=t.call(e,o)}catch(u){d=[6,u],n=0}finally{r=i=0}if(d[0]&5)throw d[1];return{value:d[0]?d[1]:void 0,done:!0}}}var ae=64,On=32,Dn=new Uint32Array([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]),Mn=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],kn=Math.pow(2,53)-1;var Ft=(function(){function e(){this.state=Int32Array.from(Mn),this.temp=new Int32Array(64),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0,this.finished=!1}return e.prototype.update=function(t){if(this.finished)throw new Error("Attempted to update an already finished hash.");var o=0,r=t.byteLength;if(this.bytesHashed+=r,this.bytesHashed*8>kn)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;r>0;)this.buffer[this.bufferLength++]=t[o++],r--,this.bufferLength===ae&&(this.hashBuffer(),this.bufferLength=0)},e.prototype.digest=function(){if(!this.finished){var t=this.bytesHashed*8,o=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),r=this.bufferLength;if(o.setUint8(this.bufferLength++,128),r%ae>=ae-8){for(var n=this.bufferLength;n<ae;n++)o.setUint8(n,0);this.hashBuffer(),this.bufferLength=0}for(var n=this.bufferLength;n<ae-8;n++)o.setUint8(n,0);o.setUint32(ae-8,Math.floor(t/4294967296),!0),o.setUint32(ae-4,t),this.hashBuffer(),this.finished=!0}for(var i=new Uint8Array(On),n=0;n<8;n++)i[n*4]=this.state[n]>>>24&255,i[n*4+1]=this.state[n]>>>16&255,i[n*4+2]=this.state[n]>>>8&255,i[n*4+3]=this.state[n]>>>0&255;return i},e.prototype.hashBuffer=function(){for(var t=this,o=t.buffer,r=t.state,n=r[0],i=r[1],s=r[2],a=r[3],c=r[4],d=r[5],u=r[6],p=r[7],l=0;l<ae;l++){if(l<16)this.temp[l]=(o[l*4]&255)<<24|(o[l*4+1]&255)<<16|(o[l*4+2]&255)<<8|o[l*4+3]&255;else{var m=this.temp[l-2],h=(m>>>17|m<<15)^(m>>>19|m<<13)^m>>>10;m=this.temp[l-15];var I=(m>>>7|m<<25)^(m>>>18|m<<14)^m>>>3;this.temp[l]=(h+this.temp[l-7]|0)+(I+this.temp[l-16]|0)}var A=(((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))+(c&d^~c&u)|0)+(p+(Dn[l]+this.temp[l]|0)|0)|0,S=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&i^n&s^i&s)|0;p=u,u=d,d=c,c=a+A|0,a=s,s=i,i=n,n=A+S|0}r[0]+=n,r[1]+=i,r[2]+=s,r[3]+=a,r[4]+=c,r[5]+=d,r[6]+=u,r[7]+=p},e})();var gr=dr("buffer");var Fn=(e,t)=>{if(typeof e!="string")throw new TypeError(`The "input" argument must be of type string. Received type ${typeof e} (${e})`);return t?gr.Buffer.from(e,t):gr.Buffer.from(e)};var hr=e=>{let t=Fn(e,"utf8");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength/Uint8Array.BYTES_PER_ELEMENT)};var tc=typeof Buffer<"u"&&Buffer.from?function(e){return Buffer.from(e,"utf8")}:hr;function uo(e){return e instanceof Uint8Array?e:typeof e=="string"?tc(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e)}function yr(e){return typeof e=="string"?e.length===0:e.byteLength===0}var Be=(function(){function e(t){this.secret=t,this.hash=new Ft,this.reset()}return e.prototype.update=function(t){if(!(yr(t)||this.error))try{this.hash.update(uo(t))}catch(o){this.error=o}},e.prototype.digestSync=function(){if(this.error)throw this.error;return this.outer?(this.outer.finished||this.outer.update(this.hash.digest()),this.outer.digest()):this.hash.digest()},e.prototype.digest=function(){return bn(this,void 0,void 0,function(){return Un(this,function(t){return[2,this.digestSync()]})})},e.prototype.reset=function(){if(this.hash=new Ft,this.secret){this.outer=new Ft;var t=oc(this.secret),o=new Uint8Array(ae);o.set(t);for(var r=0;r<ae;r++)t[r]^=54,o[r]^=92;this.hash.update(t),this.outer.update(o);for(var r=0;r<t.byteLength;r++)t[r]=0}},e})();function oc(e){var t=uo(e);if(t.byteLength>ae){var o=new Ft;o.update(t),t=o.digest()}var r=new Uint8Array(ae);return r.set(t),r}var rc={},nc={};for(let e=0;e<256;e++){let t=e.toString(16).toLowerCase();t.length===1&&(t=`0${t}`),rc[e]=t,nc[t]=e}var T;(function(e){e.WebUnknown="0",e.React="1",e.NextJs="2",e.Angular="3",e.VueJs="4",e.Nuxt="5",e.Svelte="6",e.ServerSideUnknown="100",e.ReactSSR="101",e.NextJsSSR="102",e.AngularSSR="103",e.VueJsSSR="104",e.NuxtSSR="105",e.SvelteSSR="106",e.ReactNative="201",e.Expo="202"})(T||(T={}));var Lt;(function(e){e.AI="ai",e.API="api",e.Auth="auth",e.Analytics="analytics",e.DataStore="datastore",e.Geo="geo",e.InAppMessaging="inappmessaging",e.Interactions="interactions",e.Predictions="predictions",e.PubSub="pubsub",e.PushNotification="pushnotification",e.Storage="storage"})(Lt||(Lt={}));var Er;(function(e){e.CreateConversation="1",e.GetConversation="2",e.ListConversations="3",e.DeleteConversation="4",e.SendMessage="5",e.ListMessages="6",e.OnMessage="7",e.Generation="8",e.UpdateConversation="9"})(Er||(Er={}));var Sr;(function(e){e.Record="1",e.IdentifyUser="2"})(Sr||(Sr={}));var Ir;(function(e){e.GraphQl="1",e.Get="2",e.Post="3",e.Put="4",e.Patch="5",e.Del="6",e.Head="7"})(Ir||(Ir={}));var R;(function(e){e.SignUp="1",e.ConfirmSignUp="2",e.ResendSignUpCode="3",e.SignIn="4",e.FetchMFAPreference="6",e.UpdateMFAPreference="7",e.SetUpTOTP="10",e.VerifyTOTPSetup="11",e.ConfirmSignIn="12",e.DeleteUserAttributes="15",e.DeleteUser="16",e.UpdateUserAttributes="17",e.FetchUserAttributes="18",e.ConfirmUserAttribute="22",e.SignOut="26",e.UpdatePassword="27",e.ResetPassword="28",e.ConfirmResetPassword="29",e.FederatedSignIn="30",e.RememberDevice="32",e.ForgetDevice="33",e.FetchDevices="34",e.SendUserAttributeVerificationCode="35",e.SignInWithRedirect="36",e.StartWebAuthnRegistration="37",e.CompleteWebAuthnRegistration="38",e.ListWebAuthnCredentials="39",e.DeleteWebAuthnCredential="40"})(R||(R={}));var wr;(function(e){e.Subscribe="1",e.GraphQl="2"})(wr||(wr={}));var Ar;(function(e){e.SearchByText="0",e.SearchByCoordinates="1",e.SearchForSuggestions="2",e.SearchByPlaceId="3",e.SaveGeofences="4",e.GetGeofence="5",e.ListGeofences="6",e.DeleteGeofences="7"})(Ar||(Ar={}));var xr;(function(e){e.SyncMessages="1",e.IdentifyUser="2",e.NotifyMessageInteraction="3"})(xr||(xr={}));var Cr;(function(e){e.None="0"})(Cr||(Cr={}));var vr;(function(e){e.Convert="1",e.Identify="2",e.Interpret="3"})(vr||(vr={}));var Pr;(function(e){e.Subscribe="1"})(Pr||(Pr={}));var Tr;(function(e){e.InitializePushNotifications="1",e.IdentifyUser="2"})(Tr||(Tr={}));var Rr;(function(e){e.UploadData="1",e.DownloadData="2",e.List="3",e.Copy="4",e.Remove="5",e.GetProperties="6",e.GetUrl="7",e.GetDataAccess="8",e.ListCallerAccessGrants="9"})(Rr||(Rr={}));var _r="6.16.2";var $e=()=>typeof global<"u";var me=()=>typeof window<"u",po=()=>typeof document<"u",St=()=>typeof process<"u",je=(e,t)=>!!Object.keys(e).find(o=>o.startsWith(t));function Ln(){let e=r=>r.startsWith("_react")||r.startsWith("__react"),t=r=>Object.keys(r).find(e),o=()=>Array.from(document.querySelectorAll("[id]"));return po()&&o().some(t)}function Bn(){return St()&&typeof process.env<"u"&&!!Object.keys(process.env).find(e=>e.includes("react"))}function Hn(){return me()&&je(window,"__VUE")}function Kn(){return $e()&&je(global,"__VUE")}function Wn(){return me()&&je(window,"__SVELTE")}function Vn(){return St()&&typeof process.env<"u"&&!!Object.keys(process.env).find(e=>e.includes("svelte"))}function zn(){return me()&&window.next&&typeof window.next=="object"}function qn(){return $e()&&(je(global,"__next")||je(global,"__NEXT"))}function $n(){return me()&&(window.__NUXT__!==void 0||window.$nuxt!==void 0)}function jn(){return $e()&&typeof global.__NUXT_PATHS__<"u"}function Gn(){let e=!!(po()&&document.querySelector("[ng-version]")),t=!!(me()&&typeof window.ng<"u");return e||t}function Yn(){return St()&&typeof process.env=="object"&&process.env.npm_lifecycle_script?.startsWith("ng ")||!1}function Jn(){return typeof navigator<"u"&&typeof navigator.product<"u"&&navigator.product==="ReactNative"}function Xn(){return $e()&&typeof global.expo<"u"}function Zn(){return me()}var ic=[{platform:T.Expo,detectionMethod:Xn},{platform:T.ReactNative,detectionMethod:Jn},{platform:T.NextJs,detectionMethod:zn},{platform:T.Nuxt,detectionMethod:$n},{platform:T.Angular,detectionMethod:Gn},{platform:T.React,detectionMethod:Ln},{platform:T.VueJs,detectionMethod:Hn},{platform:T.Svelte,detectionMethod:Wn},{platform:T.WebUnknown,detectionMethod:Zn},{platform:T.NextJsSSR,detectionMethod:qn},{platform:T.NuxtSSR,detectionMethod:jn},{platform:T.ReactSSR,detectionMethod:Bn},{platform:T.VueJsSSR,detectionMethod:Kn},{platform:T.AngularSSR,detectionMethod:Yn},{platform:T.SvelteSSR,detectionMethod:Vn}];function Qn(){return ic.find(e=>e.detectionMethod())?.platform||T.ServerSideUnknown}var Bt,lo=[],mo=!1,sc=10,ac=10,cc=1e3,fo=()=>{if(!Bt){if(Bt=Qn(),mo)for(;lo.length;)lo.pop()?.();else lo.forEach(e=>{e()});ei(T.ServerSideUnknown,sc),ei(T.WebUnknown,ac)}return Bt},ti=e=>{mo||lo.push(e)};function dc(){Bt=void 0}function ei(e,t){Bt===e&&!mo&&setTimeout(()=>{dc(),mo=!0,setTimeout(fo,cc)},t)}var uc={};var oi=(e,t)=>uc[e]?.[t]?.additionalDetails;var ri="aws-amplify",ni=e=>e.replace(/\+.*/,""),Nr=class{constructor(){this.userAgent=`${ri}/${ni(_r)}`}get framework(){return fo()}get isReactNative(){return this.framework===T.ReactNative||this.framework===T.Expo}observeFrameworkChanges(t){ti(t)}},pc=new Nr,ii=({category:e,action:t}={})=>{let o=[[ri,ni(_r)]];if(e&&o.push([e,t]),o.push(["framework",fo()]),e&&t){let r=oi(e,t);r&&r.forEach(n=>{o.push(n)})}return o},He=e=>ii(e).map(([r,n])=>r&&n?`${r}/${n}`:r).join(" ");var Ke=()=>typeof window<"u"&&typeof window.document<"u";var si=new C("Auth"),go=class{configure(t,o){this.authConfig=t,this.authOptions=o,t&&t.Cognito?.userPoolEndpoint&&si.warn(ai("Amazon Cognito User Pool")),t&&t.Cognito?.identityPoolEndpoint&&si.warn(ai("Amazon Cognito Identity Pool"))}async fetchAuthSession(t={}){let o,r,n=await this.getTokens(t);return n?(r=n.accessToken?.payload?.sub,o=await this.authOptions?.credentialsProvider?.getCredentialsAndIdentityId({authConfig:this.authConfig,tokens:n,authenticated:!0,forceRefresh:t.forceRefresh})):o=await this.authOptions?.credentialsProvider?.getCredentialsAndIdentityId({authConfig:this.authConfig,authenticated:!1,forceRefresh:t.forceRefresh}),{tokens:n,credentials:o?.credentials,identityId:o?.identityId,userSub:r}}async clearCredentials(){await this.authOptions?.credentialsProvider?.clearCredentialsAndIdentityId()}async getTokens(t){return await this.authOptions?.tokenProvider?.getTokens(t)??void 0}},ai=e=>`You are using a custom Amazon ${e} endpoint, ensure the endpoint is correct.`;var ho=class{constructor(){this.oAuthListener=void 0,this.isConfigured=!1,this.resourcesConfig={},this.libraryOptions={},this.Auth=new go}configure(t,o){let r=kt(t);this.resourcesConfig=r,o&&(this.libraryOptions=o),this.resourcesConfig=pr(this.resourcesConfig),this.Auth.configure(this.resourcesConfig.Auth,this.libraryOptions.Auth),(this.resourcesConfig.Analytics?.Pinpoint||this.resourcesConfig.Notifications?.InAppMessaging?.Pinpoint||this.resourcesConfig.Notifications?.PushNotification?.Pinpoint)&&console.warn("AWS will end support for Amazon Pinpoint on October 30, 2026. The guidance is to use AWS End User Messaging for push notifications and SMS, Amazon Simple Email Service for sending emails, Amazon Connect for campaigns, journeys, endpoints, and engagement analytics. Pinpoint recommends Amazon Kinesis for event collection and mobile analytics."),Z.dispatch("core",{event:"configure",data:this.resourcesConfig},"Configure",j),this.notifyOAuthListener(),this.isConfigured=!0}getConfig(){return this.isConfigured||console.warn("Amplify has not been configured. Please call Amplify.configure() before using this service."),this.resourcesConfig}[Mt](t){this.resourcesConfig.Auth?.Cognito.loginWith?.oauth?t(this.resourcesConfig.Auth?.Cognito):this.oAuthListener=t}notifyOAuthListener(){!this.resourcesConfig.Auth?.Cognito.loginWith?.oauth||!this.oAuthListener||(this.oAuthListener(this.resourcesConfig.Auth?.Cognito),this.oAuthListener=void 0)}},w=new ho;var ci=(e,t)=>e.Auth.fetchAuthSession(t);var yo=e=>ci(w,e);function Ht(){return w.Auth.clearCredentials()}var dt=e=>{let{headers:t,statusCode:o}=e;return{...lc(e)?e.$metadata:{},httpStatusCode:o,requestId:t["x-amzn-requestid"]??t["x-amzn-request-id"]??t["x-amz-request-id"],extendedRequestId:t["x-amz-id-2"],cfId:t["x-amz-cf-id"]}},lc=e=>typeof e?.$metadata=="object";var pe=async e=>{if(!e||e.statusCode<300)return;let t=await Re(e),r=(s=>{let[a]=s.toString().split(/[,:]+/);return a.includes("#")?a.split("#")[1]:a})(e.headers["x-amzn-errortype"]??t.code??t.__type??"UnknownError"),n=t.message??t.Message??"Unknown error",i=new Error(n);return Object.assign(i,{name:r,$metadata:dt(e)})},Re=async e=>{if(!e.body)throw new Error("Missing response payload");let t=await e.body.json();return Object.assign(t,{$metadata:dt(e)})};var b=(e,t,o,r)=>async(n,i)=>{let s={...r,...n},a=await s.endpointResolver(s,i),c=await t(i,a),d=await e(c,{...s});return o(d)};function di(e=3e5){return r=>{let n=2**r*100+100*Math.random();return n>e?!1:n}}var br="amz-sdk-invocation-id",ui="amz-sdk-request";var Kt=e=>{let o=di(3e5)(e);return o===!1?3e5:o};var fc=["AuthFailure","InvalidSignatureException","RequestExpired","RequestInTheFuture","RequestTimeTooSkewed","SignatureDoesNotMatch","BadRequestException"],pi=e=>!!e&&fc.includes(e);var Wt=e=>async(t,o)=>{let r=o??await e(t)??void 0,n=r?.code||r?.name,i=t?.statusCode;return{retryable:Ec(o)||yc(i,n)||pi(n)||Sc(i,n)}},gc=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException"],hc=["TimeoutError","RequestTimeout","RequestTimeoutException"],yc=(e,t)=>e===429||!!t&&gc.includes(t),Ec=e=>[ue.NetworkError,"ERR_NETWORK"].includes(e?.name),Sc=(e,t)=>!!e&&[500,502,503,504].includes(e)||!!t&&hc.includes(t);var Ur="cognito-identity",Eo={service:Ur,retryDecider:Wt(pe),computeDelay:Kt,cache:"no-store"};var fi=({maxAttempts:e=3,retryDecider:t,computeDelay:o,abortSignal:r})=>{if(e<1)throw new Error("maxAttempts must be greater than 0");return(n,i)=>async function(a){let c,d=i.attemptsCount??0,u,p=()=>{if(u)return li(u,d),u;throw li(c,d),c};for(;!r?.aborted&&d<e;){try{u=await n(a),c=void 0}catch(h){c=h,u=void 0}d=(i.attemptsCount??0)>d?i.attemptsCount??0:d+1,i.attemptsCount=d;let{isCredentialsExpiredError:l,retryable:m}=await t(u,c,i);if(m){if(i.isCredentialsExpired=!!l,!r?.aborted&&d<e){let h=o(d);await Ic(h,r)}continue}else return p()}if(r?.aborted)throw new Error("Request aborted.");return p()}},Ic=(e,t)=>{if(t?.aborted)return Promise.resolve();let o,r,n=new Promise(i=>{r=i,o=setTimeout(i,e)});return t?.addEventListener("abort",function i(s){clearTimeout(o),t?.removeEventListener("abort",i),r()}),n},li=(e,t)=>{Object.prototype.toString.call(e)==="[object Object]"&&(e.$metadata={...e.$metadata??{},attempts:t})};var gi=fr;var hi=()=>e=>async function(o){return o.headers[br]||(o.headers[br]=gi()),e(o)};var yi=({maxAttempts:e=3})=>(t,o)=>async function(n){let i=o.attemptsCount??0;return n.headers[ui]=`attempt=${i+1}; max=${e}`,t(n)};var Ei=({userAgentHeader:e="x-amz-user-agent",userAgentValue:t=""})=>o=>async function(n){if(t.trim().length===0)return await o(n);{let i=e.toLowerCase();return n.headers[i]=n.headers[i]?`${n.headers[i]} ${t}`:t,await o(n)}};var ut=(e,t)=>(o,r)=>{let n={},i=s=>e(s,r);for(let s=t.length-1;s>=0;s--){let a=t[s];i=a(r)(i,n)}return i(o)};var So=e=>{let t;return()=>(t||(t=e()),t)};var wc=e=>!["HEAD","GET"].includes(e.toUpperCase()),Si=async({url:e,method:t,headers:o,body:r},{abortSignal:n,cache:i,withCrossDomainCredentials:s})=>{let a;try{a=await fetch(e,{method:t,headers:o,body:wc(t)?r:void 0,signal:n,cache:i,credentials:s?"include":"same-origin"})}catch(p){throw p instanceof TypeError?new U({name:ue.NetworkError,message:"A network error has occurred.",underlyingError:p}):p}let c={};a.headers?.forEach((p,l)=>{c[l.toLowerCase()]=p});let d={statusCode:a.status,headers:c,body:null},u=Object.assign(a.body??{},{text:So(()=>a.text()),blob:So(()=>a.blob()),json:So(()=>a.json())});return{...d,body:u}};var Vt=ut(Si,[Ei,hi,fi,yi]);var Ii=()=>e=>async function(o){return o.headers["cache-control"]="no-store",e(o)};var Io=ut(Vt,[Ii]);var wo=e=>(t,o)=>{let r=Ac(e),n=JSON.stringify(t);return xc(o,r,n)},Ac=e=>({"content-type":"application/x-amz-json-1.1","x-amz-target":`AWSCognitoIdentityService.${e}`}),xc=({url:e},t,o)=>({headers:t,url:e,body:o,method:"POST"});var Ao=e=>b(Io,wo("GetCredentialsForIdentity"),Cc,{...Eo,...e,userAgentValue:He()}),Cc=async e=>{if(e.statusCode>=300)throw await pe(e);let t=await Re(e);return{IdentityId:t.IdentityId,Credentials:vc(t.Credentials),$metadata:dt(e)}},vc=({Expiration:e,...t}={})=>({...t,Expiration:e&&new Date(e*1e3)});var Or=e=>b(Io,wo("GetId"),Pc,{...Eo,...e,userAgentValue:He()}),Pc=async e=>{if(e.statusCode>=300)throw await pe(e);return{IdentityId:(await Re(e)).IdentityId,$metadata:dt(e)}};var Dr={id:"aws",outputs:{dnsSuffix:"amazonaws.com"},regionRegex:"^(us|eu|ap|sa|ca|me|af)\\-\\w+\\-\\d+$",regions:["aws-global"]},wi={partitions:[Dr,{id:"aws-cn",outputs:{dnsSuffix:"amazonaws.com.cn"},regionRegex:"^cn\\-\\w+\\-\\d+$",regions:["aws-cn-global"]}]};var zt=e=>{let{partitions:t}=wi;for(let{regions:o,outputs:r,regionRegex:n}of t){let i=new RegExp(n);if(o.includes(e)||i.test(e))return r.dnsSuffix}return Dr.outputs.dnsSuffix};var te=URL;var Mr=({region:e})=>({url:new te(`https://${Ur}.${e}.${zt(e)}`)});var We=class extends U{constructor(){super({name:ue.PlatformNotSupported,message:"Function not supported on current platform"})}};var _e=class{constructor(t){this.storage=t}async setItem(t,o){if(!this.storage)throw new We;this.storage.setItem(t,o)}async getItem(t){if(!this.storage)throw new We;return this.storage.getItem(t)}async removeItem(t){if(!this.storage)throw new We;this.storage.removeItem(t)}async clear(){if(!this.storage)throw new We;this.storage.clear()}};var pt=class{constructor(){this.storage=new Map}get length(){return this.storage.size}key(t){return t>this.length-1?null:Array.from(this.storage.keys())[t]}setItem(t,o){this.storage.set(t,o)}getItem(t){return this.storage.get(t)??null}removeItem(t){this.storage.delete(t)}clear(){this.storage.clear()}};var Ai=new C("CoreStorageUtils"),xo=()=>{try{if(typeof window<"u"&&window.localStorage)return window.localStorage}catch{Ai.info("localStorage not found. InMemoryStorage is used as a fallback.")}return new pt},Co=()=>{try{if(typeof window<"u"&&window.sessionStorage)return window.sessionStorage.getItem("test"),window.sessionStorage;throw new Error("sessionStorage is not defined")}catch{return Ai.info("sessionStorage not found. InMemoryStorage is used as a fallback."),new pt}};var vo=class extends _e{constructor(){super(xo())}};var Po=class extends _e{constructor(){super(Co())}};var To=class{constructor(t){this._storage=t}get storage(){if(!this._storage)throw new We;return this._storage}setItem(t,o){this.storage.setItem(t,o)}getItem(t){return this.storage.getItem(t)}removeItem(t){this.storage.removeItem(t)}clear(){this.storage.clear()}};var Ro=class extends To{constructor(){super(Co())}};function _o(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var r in o)e[r]=o[r]}return e}var Tc={read:function(e){return e[0]==='"'&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function kr(e,t){function o(n,i,s){if(!(typeof document>"u")){s=_o({},t,s),typeof s.expires=="number"&&(s.expires=new Date(Date.now()+s.expires*864e5)),s.expires&&(s.expires=s.expires.toUTCString()),n=encodeURIComponent(n).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var a="";for(var c in s)s[c]&&(a+="; "+c,s[c]!==!0&&(a+="="+s[c].split(";")[0]));return document.cookie=n+"="+e.write(i,n)+a}}function r(n){if(!(typeof document>"u"||arguments.length&&!n)){for(var i=document.cookie?document.cookie.split("; "):[],s={},a=0;a<i.length;a++){var c=i[a].split("="),d=c.slice(1).join("=");try{var u=decodeURIComponent(c[0]);if(s[u]=e.read(d,u),n===u)break}catch{}}return n?s[n]:s}}return Object.create({set:o,get:r,remove:function(n,i){o(n,"",_o({},i,{expires:-1}))},withAttributes:function(n){return kr(this.converter,_o({},this.attributes,n))},withConverter:function(n){return kr(_o({},this.converter,n),this.attributes)}},{attributes:{value:Object.freeze(t)},converter:{value:Object.freeze(e)}})}var qt=kr(Tc,{path:"/"});var $t=class{constructor(t={}){let{path:o,domain:r,expires:n,sameSite:i,secure:s}=t;if(this.domain=r,this.path=o||"/",this.expires=Object.prototype.hasOwnProperty.call(t,"expires")?n:365,this.secure=Object.prototype.hasOwnProperty.call(t,"secure")?s:!0,Object.prototype.hasOwnProperty.call(t,"sameSite")){if(!i||!["strict","lax","none"].includes(i))throw new Error('The sameSite value of cookieStorage must be "lax", "strict" or "none".');if(i==="none"&&!this.secure)throw new Error("sameSite = None requires the Secure attribute in latest browser versions.");this.sameSite=i}}async setItem(t,o){qt.set(t,o,this.getData())}async getItem(t){return qt.get(t)??null}async removeItem(t){qt.remove(t,this.getData())}async clear(){let t=qt.get(),o=Object.keys(t).map(r=>this.removeItem(r));await Promise.all(o)}getData(){return{path:this.path,expires:this.expires,domain:this.domain,secure:this.secure,...this.sameSite&&{sameSite:this.sameSite}}}};var we=new vo,Rc=new Po,Ae=new Ro,_c=new _e(new pt);var Ge={keyPrefix:"aws-amplify-cache",capacityInBytes:1048576,itemMaxSize:21e4,defaultTTL:2592e5,defaultPriority:5,warningThreshold:.8},Ve="CurSize";function Fr(e){let t=0;t=e.length;for(let o=e.length;o>=0;o-=1){let r=e.charCodeAt(o);r>127&&r<=2047?t+=1:r>2047&&r<=65535&&(t+=2),r>=56320&&r<=57343&&(o-=1)}return t}function Ye(){return new Date().getTime()}var lt=e=>`${e}${Ve}`;var Je;(function(e){e.NoCacheItem="NoCacheItem",e.NullNextNode="NullNextNode",e.NullPreviousNode="NullPreviousNode"})(Je||(Je={}));var Nc={[Je.NoCacheItem]:{message:"Item not found in the cache storage."},[Je.NullNextNode]:{message:"Next node is null."},[Je.NullPreviousNode]:{message:"Previous node is null."}},Lr=Se(Nc);var k=new C("StorageCache"),No=class{constructor({config:t,keyValueStorage:o}){this.config={...Ge,...t},this.keyValueStorage=o,this.sanitizeConfig()}getModuleName(){return"Cache"}configure(t){return t&&(t.keyPrefix&&k.warn("keyPrefix can not be re-configured on an existing Cache instance."),this.config={...this.config,...t}),this.sanitizeConfig(),this.config}async getCurrentCacheSize(){let t=await this.getStorage().getItem(lt(this.config.keyPrefix));return t||(await this.getStorage().setItem(lt(this.config.keyPrefix),"0"),t="0"),Number(t)}async setItem(t,o,r){if(k.debug(`Set item: key is ${t}, value is ${o} with options: ${r}`),!t||t===Ve){k.warn(`Invalid key: should not be empty or reserved key: '${Ve}'`);return}if(typeof o>"u"){k.warn("The value of item should not be undefined!");return}let n={priority:r?.priority!==void 0?r.priority:this.config.defaultPriority,expires:r?.expires!==void 0?r.expires:this.config.defaultTTL+Ye()};if(n.priority<1||n.priority>5){k.warn("Invalid parameter: priority due to out or range. It should be within 1 and 5.");return}let i=`${this.config.keyPrefix}${t}`,s=this.fillCacheItem(i,o,n);if(s.byteSize>this.config.itemMaxSize){k.warn(`Item with key: ${t} you are trying to put into is too big!`);return}try{let a=await this.getStorage().getItem(i);if(a&&await this.removeCacheItem(i,JSON.parse(a).byteSize),await this.isCacheFull(s.byteSize)){let c=await this.clearInvalidAndGetRemainingKeys();if(await this.isCacheFull(s.byteSize)){let d=await this.sizeToPop(s.byteSize);await this.popOutItems(c,d)}}return this.setCacheItem(i,s)}catch(a){k.warn(`setItem failed! ${a}`)}}async getItem(t,o){k.debug(`Get item: key is ${t} with options ${o}`);let r;if(!t||t===Ve)return k.warn(`Invalid key: should not be empty or reserved key: '${Ve}'`),null;let n=`${this.config.keyPrefix}${t}`;try{if(r=await this.getStorage().getItem(n),r!=null)if(await this.isExpired(n))await this.removeCacheItem(n,JSON.parse(r).byteSize);else return(await this.updateVisitedTime(JSON.parse(r),n)).data;if(o?.callback){let i=o.callback();return i!==null&&await this.setItem(t,i,o),i}return null}catch(i){return k.warn(`getItem failed! ${i}`),null}}async removeItem(t){if(k.debug(`Remove item: key is ${t}`),!t||t===Ve){k.warn(`Invalid key: should not be empty or reserved key: '${Ve}'`);return}let o=`${this.config.keyPrefix}${t}`;try{let r=await this.getStorage().getItem(o);r&&await this.removeCacheItem(o,JSON.parse(r).byteSize)}catch(r){k.warn(`removeItem failed! ${r}`)}}async getAllKeys(){try{return await this.getAllCacheKeys()}catch(t){return k.warn(`getAllkeys failed! ${t}`),[]}}getStorage(){return this.keyValueStorage}async isExpired(t){let o=await this.getStorage().getItem(t);Lr(o!==null,Je.NoCacheItem,`Key: ${t}`);let r=JSON.parse(o);return Ye()>=r.expires}async removeCacheItem(t,o){let r=await this.getStorage().getItem(t);Lr(r!==null,Je.NoCacheItem,`Key: ${t}`);let n=o??JSON.parse(r).byteSize;await this.decreaseCurrentSizeInBytes(n);try{await this.getStorage().removeItem(t)}catch(i){await this.increaseCurrentSizeInBytes(n),k.error(`Failed to remove item: ${i}`)}}fillCacheItem(t,o,r){let n={key:t,data:o,timestamp:Ye(),visitedTime:Ye(),priority:r.priority??0,expires:r.expires??0,type:typeof o,byteSize:0};return n.byteSize=Fr(JSON.stringify(n)),n.byteSize=Fr(JSON.stringify(n)),n}sanitizeConfig(){this.config.itemMaxSize>this.config.capacityInBytes&&(k.error("Invalid parameter: itemMaxSize. It should be smaller than capacityInBytes. Setting back to default."),this.config.itemMaxSize=Ge.itemMaxSize),(this.config.defaultPriority>5||this.config.defaultPriority<1)&&(k.error("Invalid parameter: defaultPriority. It should be between 1 and 5. Setting back to default."),this.config.defaultPriority=Ge.defaultPriority),(Number(this.config.warningThreshold)>1||Number(this.config.warningThreshold)<0)&&(k.error("Invalid parameter: warningThreshold. It should be between 0 and 1. Setting back to default."),this.config.warningThreshold=Ge.warningThreshold);let t=5*1024*1024;this.config.capacityInBytes>t&&(k.error("Cache Capacity should be less than 5MB. Setting back to default. Setting back to default."),this.config.capacityInBytes=Ge.capacityInBytes)}async increaseCurrentSizeInBytes(t){let o=await this.getCurrentCacheSize();await this.getStorage().setItem(lt(this.config.keyPrefix),(o+t).toString())}async decreaseCurrentSizeInBytes(t){let o=await this.getCurrentCacheSize();await this.getStorage().setItem(lt(this.config.keyPrefix),(o-t).toString())}async updateVisitedTime(t,o){return t.visitedTime=Ye(),await this.getStorage().setItem(o,JSON.stringify(t)),t}async setCacheItem(t,o){await this.increaseCurrentSizeInBytes(o.byteSize);try{await this.getStorage().setItem(t,JSON.stringify(o))}catch(r){await this.decreaseCurrentSizeInBytes(o.byteSize),k.error(`Failed to set item ${r}`)}}async sizeToPop(t){let r=await this.getCurrentCacheSize()+t-this.config.capacityInBytes,n=(1-this.config.warningThreshold)*this.config.capacityInBytes;return r>n?r:n}async isCacheFull(t){let o=await this.getCurrentCacheSize();return t+o>this.config.capacityInBytes}async popOutItems(t,o){let r=[],n=o;for(let i of t){let s=await this.getStorage().getItem(i);if(s!=null){let a=JSON.parse(s);r.push(a)}}r.sort((i,s)=>i.priority>s.priority?-1:i.priority<s.priority?1:i.visitedTime<s.visitedTime?-1:1);for(let i of r)if(await this.removeCacheItem(i.key,i.byteSize),n-=i.byteSize,n<=0)return}async clearInvalidAndGetRemainingKeys(){let t=[],o=await this.getAllCacheKeys({omitSizeKey:!0});for(let r of o)await this.isExpired(r)?await this.removeCacheItem(r):t.push(r);return t}async clear(){k.debug("Clear Cache");try{let t=await this.getAllKeys();for(let o of t){let r=`${this.config.keyPrefix}${o}`;await this.getStorage().removeItem(r)}}catch(t){k.warn(`clear failed! ${t}`)}}};var bc=new C("StorageCache"),bo=class e extends No{constructor(t){let o=xo();super({config:t,keyValueStorage:new _e(o)}),this.storage=o,this.getItem=this.getItem.bind(this),this.setItem=this.setItem.bind(this),this.removeItem=this.removeItem.bind(this)}async getAllCacheKeys(t){let{omitSizeKey:o}=t??{},r=[];for(let n=0;n<this.storage.length;n++){let i=this.storage.key(n);o&&i===lt(this.config.keyPrefix)||i?.startsWith(this.config.keyPrefix)&&r.push(i.substring(this.config.keyPrefix.length))}return r}createInstance(t){return(!t.keyPrefix||t.keyPrefix===Ge.keyPrefix)&&(bc.error("invalid keyPrefix, setting keyPrefix with timeStamp"),t.keyPrefix=Ye.toString()),new e(t)}};var Uc=new bo;var Oc=new C("I18n"),xi=class{constructor(){this._options=null,this._lang=null,this._dict={}}setDefaultLanguage(){!this._lang&&typeof window<"u"&&window&&window.navigator&&(this._lang=window.navigator.language),Oc.debug(this._lang)}setLanguage(t){this._lang=t}get(t,o=void 0){if(this.setDefaultLanguage(),!this._lang)return typeof o<"u"?o:t;let r=this._lang,n=this.getByLanguage(t,r);return n||(r.indexOf("-")>0&&(n=this.getByLanguage(t,r.split("-")[0])),n)?n:typeof o<"u"?o:t}getByLanguage(t,o,r=null){if(!o)return r;let n=this._dict[o];return n?n[t]:r}putVocabulariesForLanguage(t,o){let r=this._dict[t];r||(r=this._dict[t]={}),this._dict[t]={...r,...o}}putVocabularies(t){Object.keys(t).forEach(o=>{this.putVocabulariesForLanguage(o,t[o])})}};var Xe;(function(e){e.NotConfigured="NotConfigured"})(Xe||(Xe={}));var Dc={[Xe.NotConfigured]:{message:"i18n is not configured."}},jt=Se(Dc);var Ci=new C("I18n"),Uo={language:null},xe=null,Oo=class e{static configure(t){return Ci.debug("configure I18n"),t&&(Uo=Object.assign({},Uo,t.I18n||t),e.createInstance()),Uo}static getModuleName(){return"I18n"}static createInstance(){Ci.debug("create I18n instance"),!xe&&(xe=new xi)}static setLanguage(t){e.checkConfig(),jt(!!xe,Xe.NotConfigured),xe.setLanguage(t)}static get(t,o){return e.checkConfig()?(jt(!!xe,Xe.NotConfigured),xe.get(t,o)):typeof o>"u"?t:o}static putVocabulariesForLanguage(t,o){e.checkConfig(),jt(!!xe,Xe.NotConfigured),xe.putVocabulariesForLanguage(t,o)}static putVocabularies(t){e.checkConfig(),jt(!!xe,Xe.NotConfigured),xe.putVocabularies(t)}static checkConfig(){return xe||e.createInstance(),!0}};Oo.createInstance();var Br=e=>{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",o=[],r=new Uint8Array(e);st().getRandomValues(r);for(let n of r)o.push(t[n%t.length]);return o.join("")};function Hr(e){return(e.match(/.{2}/g)||[]).map(o=>String.fromCharCode(parseInt(o,16))).join("")}function Kr(e){return e.split("").map(t=>t.charCodeAt(0).toString(16).padStart(2,"0")).join("")}var Wr=e=>{let t;return async(...o)=>t||(t=new Promise((r,n)=>{e(...o).then(i=>{r(i)}).catch(i=>{n(i)}).finally(()=>{t=void 0})}),t)};function Do({expiresAt:e,clockDrift:t,tolerance:o=5e3}){return Date.now()+t+o>e}var Vr=async()=>{let{userAgentData:e}=navigator;if(!e)return navigator.userAgent;let{platform:t="",platformVersion:o="",model:r="",architecture:n="",fullVersionList:i=[]}=await e.getHighEntropyValues(["platform","platformVersion","architecture","model","fullVersionList"]),s=i.map(c=>`${c.brand}/${c.version}`).join(";");return[t,o,n,r,t,s].filter(c=>c).join(" ")||navigator.userAgent};function vi(e){return Array.from(e,t=>String.fromCodePoint(t)).join("")}var fe={convert(e,t={urlSafe:!1,skipPadding:!1}){let o=typeof e=="string"?e:vi(e),r=In()(o);return t.urlSafe&&(r=r.replace(/\+/g,"-").replace(/\//g,"_")),t.skipPadding&&(r=r.replace(/=/g,"")),r}};function Pi(){return st().getRandomValues(new Uint32Array(1))[0]}function Mc(e){let{words:t}=e,{sigBytes:o}=e,r=[];for(let n=0;n<o;n++){let i=t[n>>>2]>>>24-n%4*8&255;r.push((i>>>4).toString(16)),r.push((i&15).toString(16))}return r.join("")}var Gt=class e{constructor(t,o){this.words=[];let r=t;r=this.words=r||[],o!==void 0?this.sigBytes=o:this.sigBytes=r.length*4}random(t){let o=[];for(let r=0;r<t;r+=4)o.push(Pi());return new e(o,t)}toString(){return Mc(this)}};var y;(function(e){e.EmptySignInUsername="EmptySignInUsername",e.EmptySignInPassword="EmptySignInPassword",e.CustomAuthSignInPassword="CustomAuthSignInPassword",e.EmptySignUpUsername="EmptySignUpUsername",e.EmptySignUpPassword="EmptySignUpPassword",e.EmptyConfirmSignUpUsername="EmptyConfirmSignUpUsername",e.EmptyConfirmSignUpCode="EmptyConfirmSignUpCode",e.EmptyResendSignUpCodeUsername="EmptyresendSignUpCodeUsername",e.EmptyChallengeResponse="EmptyChallengeResponse",e.EmptyConfirmResetPasswordUsername="EmptyConfirmResetPasswordUsername",e.EmptyConfirmResetPasswordNewPassword="EmptyConfirmResetPasswordNewPassword",e.EmptyConfirmResetPasswordConfirmationCode="EmptyConfirmResetPasswordConfirmationCode",e.EmptyResetPasswordUsername="EmptyResetPasswordUsername",e.EmptyVerifyTOTPSetupCode="EmptyVerifyTOTPSetupCode",e.EmptyConfirmUserAttributeCode="EmptyConfirmUserAttributeCode",e.IncorrectMFAMethod="IncorrectMFAMethod",e.EmptyUpdatePassword="EmptyUpdatePassword",e.InvalidPreferredChallenge="InvalidPreferredChallenge"})(y||(y={}));var Mo={[y.EmptyChallengeResponse]:{message:"challengeResponse is required to confirmSignIn"},[y.EmptyConfirmResetPasswordUsername]:{message:"username is required to confirmResetPassword"},[y.EmptyConfirmSignUpCode]:{message:"code is required to confirmSignUp"},[y.EmptyConfirmSignUpUsername]:{message:"username is required to confirmSignUp"},[y.EmptyConfirmResetPasswordConfirmationCode]:{message:"confirmationCode is required to confirmResetPassword"},[y.EmptyConfirmResetPasswordNewPassword]:{message:"newPassword is required to confirmResetPassword"},[y.EmptyResendSignUpCodeUsername]:{message:"username is required to confirmSignUp"},[y.EmptyResetPasswordUsername]:{message:"username is required to resetPassword"},[y.EmptySignInPassword]:{message:"password is required to signIn"},[y.EmptySignInUsername]:{message:"username is required to signIn"},[y.EmptySignUpPassword]:{message:"password is required to signUp"},[y.EmptySignUpUsername]:{message:"username is required to signUp"},[y.CustomAuthSignInPassword]:{message:"A password is not needed when signing in with CUSTOM_WITHOUT_SRP",recoverySuggestion:"Do not include a password in your signIn call."},[y.IncorrectMFAMethod]:{message:"Incorrect MFA method was chosen. It should be either SMS, TOTP, or EMAIL",recoverySuggestion:"Try to pass SMS, TOTP, or EMAIL as the challengeResponse"},[y.EmptyVerifyTOTPSetupCode]:{message:"code is required to verifyTotpSetup"},[y.EmptyUpdatePassword]:{message:"oldPassword and newPassword are required to changePassword"},[y.EmptyConfirmUserAttributeCode]:{message:"confirmation code is required to confirmUserAttribute"},[y.InvalidPreferredChallenge]:{message:"The preferred challenge is not enabled in your backend configuration",recoverySuggestion:"Ensure the authentication method is enabled in your Amplify backend configuration"}},q;(function(e){e.DEFAULT_MSG="Authentication Error",e.EMPTY_EMAIL="Email cannot be empty",e.EMPTY_PHONE="Phone number cannot be empty",e.EMPTY_USERNAME="Username cannot be empty",e.INVALID_USERNAME="The username should either be a string or one of the sign in types",e.EMPTY_PASSWORD="Password cannot be empty",e.EMPTY_CODE="Confirmation code cannot be empty",e.SIGN_UP_ERROR="Error creating account",e.NO_MFA="No valid MFA method provided",e.INVALID_MFA="Invalid MFA type",e.EMPTY_CHALLENGE="Challenge response cannot be empty",e.NO_USER_SESSION="Failed to get the session because the user is empty",e.NETWORK_ERROR="Network Error",e.DEVICE_CONFIG="Device tracking has not been configured in this User Pool",e.AUTOSIGNIN_ERROR="Please use your credentials to sign in",e.OAUTH_ERROR="Couldn't finish OAuth flow, check your User Pool HostedUI settings"})(q||(q={}));var Ne;(function(e){e.SignInException="SignInException",e.OAuthSignInError="OAuthSignInException"})(Ne||(Ne={}));var g=class e extends U{constructor(t){super(t),this.constructor=e,Object.setPrototypeOf(this,e.prototype)}};function _(e,t){let{message:o,recoverySuggestion:r}=Mo[t];if(!e)throw new g({name:t,message:o,recoverySuggestion:r})}function v(e){let t=e?.split("_")[0];if(!e||e.indexOf("_")<0||!t||typeof t!="string")throw new g({name:"InvalidUserPoolId",message:"Invalid user pool id provided."});return t}function Yt(e){if(!e||!e.includes(":"))throw new g({name:"InvalidIdentityPoolIdException",message:"Invalid identity pool id provided.",recoverySuggestion:"Make sure a valid identityPoolId is given in the config."});return e.split(":")[0]}function zr(e){return Object.entries(e).map(([t,o])=>({Name:t,Value:o}))}var Ti;(function(e){e.ConcurrentModificationException="ConcurrentModificationException",e.ForbiddenException="ForbiddenException",e.InternalErrorException="InternalErrorException",e.InvalidParameterException="InvalidParameterException",e.NotAuthorizedException="NotAuthorizedException",e.ResourceNotFoundException="ResourceNotFoundException",e.SoftwareTokenMFANotFoundException="SoftwareTokenMFANotFoundException"})(Ti||(Ti={}));var Ri;(function(e){e.ForbiddenException="ForbiddenException",e.InternalErrorException="InternalErrorException",e.InvalidParameterException="InvalidParameterException",e.InvalidPasswordException="InvalidPasswordException",e.LimitExceededException="LimitExceededException",e.NotAuthorizedException="NotAuthorizedException",e.PasswordResetRequiredException="PasswordResetRequiredException",e.ResourceNotFoundException="ResourceNotFoundException",e.TooManyRequestsException="TooManyRequestsException",e.UserNotConfirmedException="UserNotConfirmedException",e.UserNotFoundException="UserNotFoundException"})(Ri||(Ri={}));var _i;(function(e){e.ForbiddenException="ForbiddenException",e.InternalErrorException="InternalErrorException",e.InvalidLambdaResponseException="InvalidLambdaResponseException",e.InvalidParameterException="InvalidParameterException",e.InvalidPasswordException="InvalidPasswordException",e.InvalidUserPoolConfigurationException="InvalidUserPoolConfigurationException",e.NotAuthorizedException="NotAuthorizedException",e.PasswordResetRequiredException="PasswordResetRequiredException",e.ResourceNotFoundException="ResourceNotFoundException",e.TooManyRequestsException="TooManyRequestsException",e.UsernameExistsException="UsernameExistsException",e.UserNotConfirmedException="UserNotConfirmedException",e.UserNotFoundException="UserNotFoundException"})(_i||(_i={}));var Ni;(function(e){e.CodeMismatchException="CodeMismatchException",e.ExpiredCodeException="ExpiredCodeException",e.ForbiddenException="ForbiddenException",e.InternalErrorException="InternalErrorException",e.InvalidLambdaResponseException="InvalidLambdaResponseException",e.InvalidParameterException="InvalidParameterException",e.InvalidPasswordException="InvalidPasswordException",e.LimitExceededException="LimitExceededException",e.NotAuthorizedException="NotAuthorizedException",e.ResourceNotFoundException="ResourceNotFoundException",e.TooManyFailedAttemptsException="TooManyFailedAttemptsException",e.TooManyRequestsException="TooManyRequestsException",e.UnexpectedLambdaException="UnexpectedLambdaException",e.UserLambdaValidationException="UserLambdaValidationException",e.UserNotConfirmedException="UserNotConfirmedException",e.UserNotFoundException="UserNotFoundException"})(Ni||(Ni={}));var bi;(function(e){e.AliasExistsException="AliasExistsException",e.CodeMismatchException="CodeMismatchException",e.ExpiredCodeException="ExpiredCodeException",e.ForbiddenException="ForbiddenException",e.InternalErrorException="InternalErrorException",e.InvalidLambdaResponseException="InvalidLambdaResponseException",e.InvalidParameterException="InvalidParameterException",e.LimitExceededException="LimitExceededException",e.NotAuthorizedException="NotAuthorizedException",e.ResourceNotFoundException="ResourceNotFoundException",e.TooManyFailedAttemptsException="TooManyFailedAttemptsException",e.TooManyRequestsException="TooManyRequestsException",e.UnexpectedLambdaException="UnexpectedLambdaException",e.UserLambdaValidationException="UserLambdaValidationException",e.UserNotFoundException="UserNotFoundException"})(bi||(bi={}));var Ui;(function(e){e.ForbiddenException="ForbiddenException",e.InternalErrorException="InternalErrorException",e.InvalidParameterException="InvalidParameterException",e.NotAuthorizedException="NotAuthorizedException",e.PasswordResetRequiredException="PasswordResetRequiredException",e.ResourceNotFoundException="ResourceNotFoundException",e.TooManyRequestsException="TooManyRequestsException",e.UserNotConfirmedException="UserNotConfirmedException",e.UserNotFoundException="UserNotFoundException"})(Ui||(Ui={}));var Oi;(function(e){e.ForbiddenException="ForbiddenException",e.InternalErrorException="InternalErrorException",e.InvalidParameterException="InvalidParameterException",e.NotAuthorizedException="NotAuthorizedException",e.PasswordResetRequiredException="PasswordResetRequiredException",e.ResourceNotFoundException="ResourceNotFoundException",e.TooManyRequestsException="TooManyRequestsException",e.UserNotConfirmedException="UserNotConfirmedException",e.UserNotFoundException="UserNotFoundException"})(Oi||(Oi={}));var Di;(function(e){e.ForbiddenException="ForbiddenException",e.InternalErrorException="InternalErrorException",e.InvalidParameterException="InvalidParameterException",e.InvalidUserPoolConfigurationException="InvalidUserPoolConfigurationException",e.NotAuthorizedException="NotAuthorizedException",e.PasswordResetRequiredException="PasswordResetRequiredException",e.ResourceNotFoundException="ResourceNotFoundException",e.TooManyRequestsException="TooManyRequestsException",e.UserNotConfirmedException="UserNotConfirmedException",e.UserNotFoundException="UserNotFoundException"})(Di||(Di={}));var Mi;(function(e){e.CodeDeliveryFailureException="CodeDeliveryFailureException",e.ForbiddenException="ForbiddenException",e.InternalErrorException="InternalErrorException",e.InvalidEmailRoleAccessPolicyException="InvalidEmailRoleAccessPolicyException",e.InvalidLambdaResponseException="InvalidLambdaResponseException",e.InvalidParameterException="InvalidParameterException",e.InvalidSmsRoleAccessPolicyException="InvalidSmsRoleAccessPolicyException",e.InvalidSmsRoleTrustRelationshipException="InvalidSmsRoleTrustRelationshipException",e.LimitExceededException="LimitExceededException",e.NotAuthorizedException="NotAuthorizedException",e.ResourceNotFoundException="ResourceNotFoundException",e.TooManyRequestsException="TooManyRequestsException",e.UnexpectedLambdaException="UnexpectedLambdaException",e.UserLambdaValidationException="UserLambdaValidationException",e.UserNotFoundException="UserNotFoundException"})(Mi||(Mi={}));var ki;(function(e){e.ForbiddenException="ForbiddenException",e.InternalErrorException="InternalErrorException",e.InvalidParameterException="InvalidParameterException",e.NotAuthorizedException="NotAuthorizedException",e.PasswordResetRequiredException="PasswordResetRequiredException",e.ResourceNotFoundException="ResourceNotFoundException",e.TooManyRequestsException="TooManyRequestsException",e.UserNotConfirmedException="UserNotConfirmedException",e.UserNotFoundException="UserNotFoundException"})(ki||(ki={}));var Fi;(function(e){e.ExternalServiceException="ExternalServiceException",e.InternalErrorException="InternalErrorException",e.InvalidParameterException="InvalidParameterException",e.LimitExceededException="LimitExceededException",e.NotAuthorizedException="NotAuthorizedException",e.ResourceConflictException="ResourceConflictException",e.ResourceNotFoundException="ResourceNotFoundException",e.TooManyRequestsException="TooManyRequestsException"})(Fi||(Fi={}));var Li;(function(e){e.ExternalServiceException="ExternalServiceException",e.InternalErrorException="InternalErrorException",e.InvalidIdentityPoolConfigurationException="InvalidIdentityPoolConfigurationException",e.InvalidParameterException="InvalidParameterException",e.NotAuthorizedException="NotAuthorizedException",e.ResourceConflictException="ResourceConflictException",e.ResourceNotFoundException="ResourceNotFoundException",e.TooManyRequestsException="TooManyRequestsException"})(Li||(Li={}));var Bi;(function(e){e.CodeDeliveryFailureException="CodeDeliveryFailureException",e.ForbiddenException="ForbiddenException",e.InternalErrorException="InternalErrorException",e.InvalidEmailRoleAccessPolicyException="InvalidEmailRoleAccessPolicyException",e.InvalidLambdaResponseException="InvalidLambdaResponseException",e.InvalidParameterException="InvalidParameterException",e.InvalidSmsRoleAccessPolicyException="InvalidSmsRoleAccessPolicyException",e.InvalidSmsRoleTrustRelationshipException="InvalidSmsRoleTrustRelationshipException",e.LimitExceededException="LimitExceededException",e.NotAuthorizedException="NotAuthorizedException",e.PasswordResetRequiredException="PasswordResetRequiredException",e.ResourceNotFoundException="ResourceNotFoundException",e.TooManyRequestsException="TooManyRequestsException",e.UnexpectedLambdaException="UnexpectedLambdaException",e.UserLambdaValidationException="UserLambdaValidationException",e.UserNotConfirmedException="UserNotConfirmedException",e.UserNotFoundException="UserNotFoundException"})(Bi||(Bi={}));var Hi;(function(e){e.ForbiddenException="ForbiddenException",e.InternalErrorException="InternalErrorException",e.InvalidParameterException="InvalidParameterException",e.NotAuthorizedException="NotAuthorizedException",e.PasswordResetRequiredException="PasswordResetRequiredException",e.ResourceNotFoundException="ResourceNotFoundException",e.TooManyRequestsException="TooManyRequestsException",e.UserNotConfirmedException="UserNotConfirmedException"})(Hi||(Hi={}));var Jt;(function(e){e.PasswordResetRequiredException="PasswordResetRequiredException",e.ForbiddenException="ForbiddenException",e.InternalErrorException="InternalErrorException",e.InvalidLambdaResponseException="InvalidLambdaResponseException",e.InvalidParameterException="InvalidParameterException",e.InvalidSmsRoleAccessPolicyException="InvalidSmsRoleAccessPolicyException",e.InvalidSmsRoleTrustRelationshipException="InvalidSmsRoleTrustRelationshipException",e.InvalidUserPoolConfigurationException="InvalidUserPoolConfigurationException",e.NotAuthorizedException="NotAuthorizedException",e.ResourceNotFoundException="ResourceNotFoundException",e.TooManyRequestsException="TooManyRequestsException",e.UnexpectedLambdaException="UnexpectedLambdaException",e.UserLambdaValidationException="UserLambdaValidationException",e.UserNotConfirmedException="UserNotConfirmedException",e.UserNotFoundException="UserNotFoundException"})(Jt||(Jt={}));var Ki;(function(e){e.CodeDeliveryFailureException="CodeDeliveryFailureException",e.ForbiddenException="ForbiddenException",e.InternalErrorException="InternalErrorException",e.InvalidEmailRoleAccessPolicyException="InvalidEmailRoleAccessPolicyException",e.InvalidLambdaResponseException="InvalidLambdaResponseException",e.InvalidParameterException="InvalidParameterException",e.InvalidSmsRoleAccessPolicyException="InvalidSmsRoleAccessPolicyException",e.InvalidSmsRoleTrustRelationshipException="InvalidSmsRoleTrustRelationshipException",e.LimitExceededException="LimitExceededException",e.NotAuthorizedException="NotAuthorizedException",e.ResourceNotFoundException="ResourceNotFoundException",e.TooManyRequestsException="TooManyRequestsException",e.UnexpectedLambdaException="UnexpectedLambdaException",e.UserLambdaValidationException="UserLambdaValidationException",e.UserNotFoundException="UserNotFoundException"})(Ki||(Ki={}));var Wi;(function(e){e.AliasExistsException="AliasExistsException",e.CodeMismatchException="CodeMismatchException",e.ExpiredCodeException="ExpiredCodeException",e.ForbiddenException="ForbiddenException",e.InternalErrorException="InternalErrorException",e.InvalidLambdaResponseException="InvalidLambdaResponseException",e.InvalidParameterException="InvalidParameterException",e.InvalidPasswordException="InvalidPasswordException",e.InvalidSmsRoleAccessPolicyException="InvalidSmsRoleAccessPolicyException",e.InvalidSmsRoleTrustRelationshipException="InvalidSmsRoleTrustRelationshipException",e.InvalidUserPoolConfigurationException="InvalidUserPoolConfigurationException",e.MFAMethodNotFoundException="MFAMethodNotFoundException",e.NotAuthorizedException="NotAuthorizedException",e.PasswordResetRequiredException="PasswordResetRequiredException",e.ResourceNotFoundException="ResourceNotFoundException",e.SoftwareTokenMFANotFoundException="SoftwareTokenMFANotFoundException",e.TooManyRequestsException="TooManyRequestsException",e.UnexpectedLambdaException="UnexpectedLambdaException",e.UserLambdaValidationException="UserLambdaValidationException",e.UserNotConfirmedException="UserNotConfirmedException",e.UserNotFoundException="UserNotFoundException"})(Wi||(Wi={}));var Vi;(function(e){e.ForbiddenException="ForbiddenException",e.InternalErrorException="InternalErrorException",e.InvalidParameterException="InvalidParameterException",e.NotAuthorizedException="NotAuthorizedException",e.PasswordResetRequiredException="PasswordResetRequiredException",e.ResourceNotFoundException="ResourceNotFoundException",e.UserNotConfirmedException="UserNotConfirmedException",e.UserNotFoundException="UserNotFoundException"})(Vi||(Vi={}));var ko;(function(e){e.CodeDeliveryFailureException="CodeDeliveryFailureException",e.InternalErrorException="InternalErrorException",e.InvalidEmailRoleAccessPolicyException="InvalidEmailRoleAccessPolicyException",e.InvalidLambdaResponseException="InvalidLambdaResponseException",e.InvalidParameterException="InvalidParameterException",e.InvalidPasswordException="InvalidPasswordException",e.InvalidSmsRoleAccessPolicyException="InvalidSmsRoleAccessPolicyException",e.InvalidSmsRoleTrustRelationshipException="InvalidSmsRoleTrustRelationshipException",e.NotAuthorizedException="NotAuthorizedException",e.ResourceNotFoundException="ResourceNotFoundException",e.TooManyRequestsException="TooManyRequestsException",e.UnexpectedLambdaException="UnexpectedLambdaException",e.UserLambdaValidationException="UserLambdaValidationException",e.UsernameExistsException="UsernameExistsException"})(ko||(ko={}));var zi;(function(e){e.AliasExistsException="AliasExistsException",e.CodeDeliveryFailureException="CodeDeliveryFailureException",e.CodeMismatchException="CodeMismatchException",e.ExpiredCodeException="ExpiredCodeException",e.ForbiddenException="ForbiddenException",e.InternalErrorException="InternalErrorException",e.InvalidEmailRoleAccessPolicyException="InvalidEmailRoleAccessPolicyException",e.InvalidLambdaResponseException="InvalidLambdaResponseException",e.InvalidParameterException="InvalidParameterException",e.InvalidSmsRoleAccessPolicyException="InvalidSmsRoleAccessPolicyException",e.InvalidSmsRoleTrustRelationshipException="InvalidSmsRoleTrustRelationshipException",e.NotAuthorizedException="NotAuthorizedException",e.PasswordResetRequiredException="PasswordResetRequiredException",e.ResourceNotFoundException="ResourceNotFoundException",e.TooManyRequestsException="TooManyRequestsException",e.UnexpectedLambdaException="UnexpectedLambdaException",e.UserLambdaValidationException="UserLambdaValidationException",e.UserNotConfirmedException="UserNotConfirmedException",e.UserNotFoundException="UserNotFoundException"})(zi||(zi={}));var qi;(function(e){e.CodeMismatchException="CodeMismatchException",e.EnableSoftwareTokenMFAException="EnableSoftwareTokenMFAException",e.ForbiddenException="ForbiddenException",e.InternalErrorException="InternalErrorException",e.InvalidParameterException="InvalidParameterException",e.InvalidUserPoolConfigurationException="InvalidUserPoolConfigurationException",e.NotAuthorizedException="NotAuthorizedException",e.PasswordResetRequiredException="PasswordResetRequiredException",e.ResourceNotFoundException="ResourceNotFoundException",e.SoftwareTokenMFANotFoundException="SoftwareTokenMFANotFoundException",e.TooManyRequestsException="TooManyRequestsException",e.UserNotConfirmedException="UserNotConfirmedException",e.UserNotFoundException="UserNotFoundException"})(qi||(qi={}));var $i;(function(e){e.AliasExistsException="AliasExistsException",e.CodeMismatchException="CodeMismatchException",e.ExpiredCodeException="ExpiredCodeException",e.ForbiddenException="ForbiddenException",e.InternalErrorException="InternalErrorException",e.InvalidParameterException="InvalidParameterException",e.LimitExceededException="LimitExceededException",e.NotAuthorizedException="NotAuthorizedException",e.PasswordResetRequiredException="PasswordResetRequiredException",e.ResourceNotFoundException="ResourceNotFoundException",e.TooManyRequestsException="TooManyRequestsException",e.UserNotConfirmedException="UserNotConfirmedException",e.UserNotFoundException="UserNotFoundException"})($i||($i={}));var ji;(function(e){e.ForbiddenException="ForbiddenException",e.InternalErrorException="InternalErrorException",e.InvalidParameterException="InvalidParameterException",e.InvalidUserPoolConfigurationException="InvalidUserPoolConfigurationException",e.NotAuthorizedException="NotAuthorizedException",e.PasswordResetRequiredException="PasswordResetRequiredException",e.ResourceNotFoundException="ResourceNotFoundException",e.TooManyRequestsException="TooManyRequestsException",e.UserNotConfirmedException="UserNotConfirmedException",e.UserNotFoundException="UserNotFoundException"})(ji||(ji={}));var Gi;(function(e){e.ForbiddenException="ForbiddenException",e.InternalErrorException="InternalErrorException",e.InvalidParameterException="InvalidParameterException",e.InvalidUserPoolConfigurationException="InvalidUserPoolConfigurationException",e.NotAuthorizedException="NotAuthorizedException",e.PasswordResetRequiredException="PasswordResetRequiredException",e.ResourceNotFoundException="ResourceNotFoundException",e.TooManyRequestsException="TooManyRequestsException",e.UserNotConfirmedException="UserNotConfirmedException",e.UserNotFoundException="UserNotFoundException"})(Gi||(Gi={}));var It="UserUnAuthenticatedException",Yi="UserAlreadyAuthenticatedException",Ji="DeviceMetadataNotFoundException",Fo="AutoSignInException",kc="InvalidRedirectException",Fc="InvalidAppSchemeException",Lc="InvalidPreferredRedirectUrlException",Xi=new g({name:kc,message:"signInRedirect or signOutRedirect had an invalid format or was not found.",recoverySuggestion:"Please make sure the signIn/Out redirect in your oauth config is valid."}),Qh=new g({name:Fc,message:"A valid non-http app scheme was not found in the config.",recoverySuggestion:"Please make sure a valid custom app scheme is present in the config."}),Zi=new g({name:Lc,message:"The given preferredRedirectUrl does not match any items in the redirectSignOutUrls array from the config.",recoverySuggestion:"Please make sure a matching preferredRedirectUrl is provided."}),Bc="InvalidOriginException",Qi=new g({name:Bc,message:"redirect is coming from a different origin. The oauth flow needs to be initiated from the same origin",recoverySuggestion:"Please call signInWithRedirect from the same origin."}),es="OAuthSignOutException",ts="TokenRefreshException",os="UnexpectedSignInInterruptionException";function Lo(e){if(!e||!e.accessToken)throw new g({name:It,message:"User needs to be authenticated to call this API.",recoverySuggestion:"Sign in before calling this API again."})}function rs(e){if(!e||!e.idToken)throw new g({name:It,message:"User needs to be authenticated to call this API.",recoverySuggestion:"Sign in before calling this API again."})}var Hc=new g({name:ts,message:`Token refresh is not supported when authenticated with the 'implicit grant' (token) oauth flow.
2
+ Please change your oauth configuration to use 'code grant' flow.`,recoverySuggestion:`Please logout and change your Amplify configuration to use "code grant" flow.
3
+ E.g { responseType: 'code' }`}),Kc=new g({name:It,message:"User needs to be authenticated to call this API.",recoverySuggestion:"Sign in before calling this API again."});function Bo(e){if(Vc(e))throw Hc;if(!Wc(e))throw Kc}function qr(e){if(!e||!e.deviceKey||!e.deviceGroupKey||!e.randomPassword)throw new g({name:Ji,message:"Either deviceKey, deviceGroupKey or secretPassword were not found during the sign-in process.",recoverySuggestion:"Make sure to not clear storage after calling the signIn API."})}var ns={inflightOAuth:"inflightOAuth",oauthSignIn:"oauthSignIn",oauthPKCE:"oauthPKCE",oauthState:"oauthState"};function is(e){return e?.accessToken||e?.idToken}function Wc(e){return is(e)&&e?.refreshToken}function Vc(e){return is(e)&&!e?.refreshToken}var ss=async e=>{let t=e.getConfig().Auth?.Cognito;E(t);let o=await e.Auth.getTokens({forceRefresh:!1});Lo(o);let{"cognito:username":r,sub:n}=o.idToken?.payload??{},i={username:r,userId:n},s=zc(o);return s&&(i.signInDetails=s),i};function zc(e){return e?.signInDetails}var Ze=async()=>ss(w);var O=(e,t)=>He({category:Lt.Auth,action:e,...t});var K=e=>(t,o)=>{let r=qc(e),n=JSON.stringify(t);return $c(o,r,n)},qc=e=>({"content-type":"application/x-amz-json-1.1","x-amz-target":`AWSCognitoIdentityProviderService.${e}`}),$c=({url:e},t,o)=>({headers:t,url:e,body:o,method:"POST"});function B(e){if(!e||e.name==="Error"||e instanceof TypeError)throw new g({name:ue.Unknown,message:"An unknown error has occurred.",underlyingError:e})}var G=()=>async e=>{if(e.statusCode>=300){let t=await pe(e);throw B(t),new g({name:t.name,message:t.message,metadata:t.$metadata})}return Re(e)};var jc=()=>(e,t)=>async function(r){return r.headers["cache-control"]="no-store",e(r)},W=ut(Vt,[jc]);var Ho="cognito-idp";var V={service:Ho,retryDecider:Wt(pe),computeDelay:Kt,get userAgentValue(){return He()},cache:"no-store"};var Qe=e=>b(W,K("InitiateAuth"),G(),{...V,...e});var mt=e=>b(W,K("RespondToAuthChallenge"),G(),{...V,...e});var as=e=>b(W,K("AssociateSoftwareToken"),G(),{...V,...e});var cs=({region:e})=>({url:new te(`https://${Ho}.${e}.${zt(e)}`)});var P=({endpointOverride:e})=>t=>e?{url:new te(e)}:cs(t);var ds=e=>b(W,K("GetTokensFromRefreshToken"),G(),{...V,...e});var Gc=async({tokens:e,authConfig:t,username:o,clientMetadata:r})=>{E(t?.Cognito);let{userPoolId:n,userPoolClientId:i,userPoolEndpoint:s}=t.Cognito,a=v(n);Bo(e);let c=ds({endpointResolver:P({endpointOverride:s})}),{AuthenticationResult:d}=await c({region:a},{ClientId:i,RefreshToken:e.refreshToken,DeviceKey:e.deviceMetadata?.deviceKey,ClientMetadata:r}),u=Q(d?.AccessToken??""),p=d?.IdToken?Q(d.IdToken):void 0,{iat:l}=u.payload;if(!l)throw new g({name:"iatNotFoundException",message:"iat not found in access token"});let m=l*1e3-new Date().getTime();return{accessToken:u,idToken:p,clockDrift:m,refreshToken:d?.RefreshToken??e.refreshToken,username:o}},us=Wr(Gc);var ps={accessToken:"accessToken",idToken:"idToken",oidcProvider:"oidcProvider",clockDrift:"clockDrift",refreshToken:"refreshToken",deviceKey:"deviceKey",randomPasswordKey:"randomPasswordKey",deviceGroupKey:"deviceGroupKey",signInDetails:"signInDetails",oauthMetadata:"oauthMetadata"};var Xt;(function(e){e.InvalidAuthTokens="InvalidAuthTokens"})(Xt||(Xt={}));var Yc={[Xt.InvalidAuthTokens]:{message:"Invalid tokens.",recoverySuggestion:"Make sure the tokens are valid."}},ls=Se(Yc);var $r="CognitoIdentityServiceProvider";var Ko=class{getKeyValueStorage(){if(!this.keyValueStorage)throw new g({name:"KeyValueStorageNotFoundException",message:"KeyValueStorage was not found in TokenStore"});return this.keyValueStorage}setKeyValueStorage(t){this.keyValueStorage=t}setAuthConfig(t){this.authConfig=t}async loadTokens(){try{let t=await this.getAuthKeys(),o=await this.getKeyValueStorage().getItem(t.accessToken);if(!o)throw new g({name:"NoSessionFoundException",message:"Auth session was not found. Make sure to call signIn."});let r=Q(o),n=await this.getKeyValueStorage().getItem(t.idToken),i=n?Q(n):void 0,s=await this.getKeyValueStorage().getItem(t.refreshToken)??void 0,a=await this.getKeyValueStorage().getItem(t.clockDrift)??"0",c=Number.parseInt(a),d=await this.getKeyValueStorage().getItem(t.signInDetails),u={accessToken:r,idToken:i,refreshToken:s,deviceMetadata:await this.getDeviceMetadata()??void 0,clockDrift:c,username:await this.getLastAuthUser()};return d&&(u.signInDetails=JSON.parse(d)),u}catch{return null}}async storeTokens(t){ls(t!==void 0,Xt.InvalidAuthTokens);let o=t.username;await this.getKeyValueStorage().setItem(this.getLastAuthUserKey(),o);let r=await this.getAuthKeys();await this.getKeyValueStorage().setItem(r.accessToken,t.accessToken.toString()),t.idToken?await this.getKeyValueStorage().setItem(r.idToken,t.idToken.toString()):await this.getKeyValueStorage().removeItem(r.idToken),t.refreshToken?await this.getKeyValueStorage().setItem(r.refreshToken,t.refreshToken):await this.getKeyValueStorage().removeItem(r.refreshToken),t.deviceMetadata&&(t.deviceMetadata.deviceKey&&await this.getKeyValueStorage().setItem(r.deviceKey,t.deviceMetadata.deviceKey),t.deviceMetadata.deviceGroupKey&&await this.getKeyValueStorage().setItem(r.deviceGroupKey,t.deviceMetadata.deviceGroupKey),await this.getKeyValueStorage().setItem(r.randomPasswordKey,t.deviceMetadata.randomPassword)),t.signInDetails?await this.getKeyValueStorage().setItem(r.signInDetails,JSON.stringify(t.signInDetails)):await this.getKeyValueStorage().removeItem(r.signInDetails),await this.getKeyValueStorage().setItem(r.clockDrift,`${t.clockDrift}`)}async clearTokens(){let t=await this.getAuthKeys();await Promise.all([this.getKeyValueStorage().removeItem(t.accessToken),this.getKeyValueStorage().removeItem(t.idToken),this.getKeyValueStorage().removeItem(t.clockDrift),this.getKeyValueStorage().removeItem(t.refreshToken),this.getKeyValueStorage().removeItem(t.signInDetails),this.getKeyValueStorage().removeItem(this.getLastAuthUserKey()),this.getKeyValueStorage().removeItem(t.oauthMetadata)])}async getDeviceMetadata(t){let o=await this.getAuthKeys(t),r=await this.getKeyValueStorage().getItem(o.deviceKey),n=await this.getKeyValueStorage().getItem(o.deviceGroupKey),i=await this.getKeyValueStorage().getItem(o.randomPasswordKey);return i&&n&&r?{deviceKey:r,deviceGroupKey:n,randomPassword:i}:null}async clearDeviceMetadata(t){let o=await this.getAuthKeys(t);await Promise.all([this.getKeyValueStorage().removeItem(o.deviceKey),this.getKeyValueStorage().removeItem(o.deviceGroupKey),this.getKeyValueStorage().removeItem(o.randomPasswordKey)])}async getAuthKeys(t){E(this.authConfig?.Cognito);let o=t??await this.getLastAuthUser();return Jc($r,`${this.authConfig.Cognito.userPoolClientId}.${o}`)}getLastAuthUserKey(){E(this.authConfig?.Cognito);let t=this.authConfig.Cognito.userPoolClientId;return`${$r}.${t}.LastAuthUser`}async getLastAuthUser(){return await this.getKeyValueStorage().getItem(this.getLastAuthUserKey())??"username"}async setOAuthMetadata(t){let{oauthMetadata:o}=await this.getAuthKeys();await this.getKeyValueStorage().setItem(o,JSON.stringify(t))}async getOAuthMetadata(){let{oauthMetadata:t}=await this.getAuthKeys(),o=await this.getKeyValueStorage().getItem(t);return o&&JSON.parse(o)}},Jc=(e,t)=>Zt(ps)(`${e}`,t);function Zt(e){let t=Object.values({...e});return(o,r)=>t.reduce((n,i)=>({...n,[i]:`${o}.${r}.${i}`}),{})}var ms="amplify-signin-with-hostedUI",be="CognitoIdentityServiceProvider",wt=class{constructor(t){this.keyValueStorage=t}async clearOAuthInflightData(){E(this.cognitoConfig);let t=Ue(be,this.cognitoConfig.userPoolClientId);await Promise.all([this.keyValueStorage.removeItem(t.inflightOAuth),this.keyValueStorage.removeItem(t.oauthPKCE),this.keyValueStorage.removeItem(t.oauthState)])}async clearOAuthData(){E(this.cognitoConfig);let t=Ue(be,this.cognitoConfig.userPoolClientId);return await this.clearOAuthInflightData(),await this.keyValueStorage.removeItem(ms),this.keyValueStorage.removeItem(t.oauthSignIn)}loadOAuthState(){E(this.cognitoConfig);let t=Ue(be,this.cognitoConfig.userPoolClientId);return this.keyValueStorage.getItem(t.oauthState)}storeOAuthState(t){E(this.cognitoConfig);let o=Ue(be,this.cognitoConfig.userPoolClientId);return this.keyValueStorage.setItem(o.oauthState,t)}loadPKCE(){E(this.cognitoConfig);let t=Ue(be,this.cognitoConfig.userPoolClientId);return this.keyValueStorage.getItem(t.oauthPKCE)}storePKCE(t){E(this.cognitoConfig);let o=Ue(be,this.cognitoConfig.userPoolClientId);return this.keyValueStorage.setItem(o.oauthPKCE,t)}setAuthConfig(t){this.cognitoConfig=t}async loadOAuthInFlight(){E(this.cognitoConfig);let t=Ue(be,this.cognitoConfig.userPoolClientId);return await this.keyValueStorage.getItem(t.inflightOAuth)==="true"}async storeOAuthInFlight(t){E(this.cognitoConfig);let o=Ue(be,this.cognitoConfig.userPoolClientId);await this.keyValueStorage.setItem(o.inflightOAuth,`${t}`)}async loadOAuthSignIn(){E(this.cognitoConfig);let t=Ue(be,this.cognitoConfig.userPoolClientId),o=await this.keyValueStorage.getItem(ms),[r,n]=(await this.keyValueStorage.getItem(t.oauthSignIn))?.split(",")??[];return{isOAuthSignIn:r==="true"||o==="true",preferPrivateSession:n==="true"}}async storeOAuthSignIn(t,o=!1){E(this.cognitoConfig);let r=Ue(be,this.cognitoConfig.userPoolClientId);await this.keyValueStorage.setItem(r.oauthSignIn,`${t},${o}`)}},Ue=(e,t)=>Zt(ns)(e,t);var z=new wt(we);var jr=[],fs=e=>{jr.push(e)},Wo=()=>{for(;jr.length;)jr.pop()?.()};var Vo=class{constructor(){this.waitForInflightOAuth=Ke()?async()=>{if(await z.loadOAuthInFlight())return this.inflightPromise?this.inflightPromise:(this.inflightPromise=new Promise((t,o)=>{fs(t)}),this.inflightPromise)}:async()=>{}}setAuthConfig(t){z.setAuthConfig(t.Cognito),this.authConfig=t}setTokenRefresher(t){this.tokenRefresher=t}setAuthTokenStore(t){this.tokenStore=t}getTokenStore(){if(!this.tokenStore)throw new g({name:"EmptyTokenStoreException",message:"TokenStore not set"});return this.tokenStore}getTokenRefresher(){if(!this.tokenRefresher)throw new g({name:"EmptyTokenRefresherException",message:"TokenRefresher not set"});return this.tokenRefresher}setClientMetadataProvider(t){this.clientMetadataProvider=t}async getTokens(t){let o;try{E(this.authConfig?.Cognito)}catch{return null}await this.waitForInflightOAuth(),this.inflightPromise=void 0,o=await this.getTokenStore().loadTokens();let r=await this.getTokenStore().getLastAuthUser();if(o===null)return null;let n=!!o?.idToken&&Do({expiresAt:(o.idToken?.payload?.exp??0)*1e3,clockDrift:o.clockDrift??0}),i=Do({expiresAt:(o.accessToken?.payload?.exp??0)*1e3,clockDrift:o.clockDrift??0});return(t?.forceRefresh||n||i)&&(o=await this.refreshTokens({tokens:o,username:r,clientMetadata:t?.clientMetadata??await this.clientMetadataProvider?.()}),o===null)?null:{accessToken:o?.accessToken,idToken:o?.idToken,signInDetails:o?.signInDetails}}async refreshTokens({tokens:t,username:o,clientMetadata:r}){try{let{signInDetails:n}=t,i=await this.getTokenRefresher()({tokens:t,authConfig:this.authConfig,username:o,clientMetadata:r});return i.signInDetails=n,await this.setTokens({tokens:i}),Z.dispatch("auth",{event:"tokenRefresh"},"Auth",j),i}catch(n){return this.handleErrors(n)}}handleErrors(t){if(B(t),this.isAuthenticationError(t)&&this.clearTokens(),Z.dispatch("auth",{event:"tokenRefresh_failure",data:{error:t}},"Auth",j),t.name.startsWith("NotAuthorizedException"))return null;throw t}isAuthenticationError(t){return["NotAuthorizedException","TokenRevokedException","UserNotFoundException","PasswordResetRequiredException","UserNotConfirmedException","RefreshTokenReuseException"].some(r=>t?.name?.startsWith?.(r))}async setTokens({tokens:t}){return this.getTokenStore().storeTokens(t)}async clearTokens(){return this.getTokenStore().clearTokens()}getDeviceMetadata(t){return this.getTokenStore().getDeviceMetadata(t)}clearDeviceMetadata(t){return this.getTokenStore().clearDeviceMetadata(t)}setOAuthMetadata(t){return this.getTokenStore().setOAuthMetadata(t)}getOAuthMetadata(){return this.getTokenStore().getOAuthMetadata()}};var zo=class{constructor(){this.authTokenStore=new Ko,this.authTokenStore.setKeyValueStorage(we),this.tokenOrchestrator=new Vo,this.tokenOrchestrator.setAuthTokenStore(this.authTokenStore),this.tokenOrchestrator.setTokenRefresher(us)}getTokens(t={}){return this.tokenOrchestrator.getTokens(t)}setKeyValueStorage(t){this.authTokenStore.setKeyValueStorage(t)}setClientMetadataProvider(t){this.tokenOrchestrator.setClientMetadataProvider(t)}setAuthConfig(t){this.authTokenStore.setAuthConfig(t),this.tokenOrchestrator.setAuthConfig(t)}};var ft=new zo,{tokenOrchestrator:D}=ft;async function oe(e){if(e.AccessToken){let t=Q(e.AccessToken),o=(t.payload.iat||0)*1e3,r=new Date().getTime(),n=o>0?o-r:0,i,s,a;e.RefreshToken&&(s=e.RefreshToken),e.IdToken&&(i=Q(e.IdToken)),e?.NewDeviceMetadata&&(a=e.NewDeviceMetadata);let c={accessToken:t,idToken:i,refreshToken:s,clockDrift:n,deviceMetadata:a,username:e.username};e?.signInDetails&&(c.signInDetails=e.signInDetails),await D.setTokens({tokens:c})}else throw new U({message:"Invalid tokens",name:"InvalidTokens",recoverySuggestion:"Check Cognito UserPool settings"})}var Xc="Unable to get user session following successful sign-in.",ce=async()=>{try{Z.dispatch("auth",{event:"signedIn",data:await Ze()},"Auth",j)}catch(e){throw e.name===It?new g({name:os,message:Xc,recoverySuggestion:"This most likely is due to auth tokens not being persisted. If you are using cookie store, please ensure cookies can be correctly set from your server."}):e}};function gs(){return{active:!1}}var Zc=(e,t)=>{switch(t.type){case"SET_USERNAME":return{...e,username:t.value};case"SET_SESSION":return{...e,session:t.value};case"START":return{...e,active:!0};case"RESET":return gs();default:return e}},Qc=e=>{let t=e(gs(),{type:"RESET"});return{getState:()=>t,dispatch:o=>{t=e(t,o)}}},ze=Qc(Zc);var ed=180*1e3,qo="CognitoSignInState",qe={username:`${qo}.username`,challengeName:`${qo}.challengeName`,signInSession:`${qo}.signInSession`,expiry:`${qo}.expiry`},td=(e,t)=>{switch(t.type){case"SET_SIGN_IN_SESSION":return $o({signInSession:t.value}),{...e,signInSession:t.value};case"SET_SIGN_IN_STATE":return $o(t.value),{...t.value};case"SET_CHALLENGE_NAME":return $o({challengeName:t.value}),{...e,challengeName:t.value};case"SET_USERNAME":return $o({username:t.value}),{...e,username:t.value};case"SET_INITIAL_STATE":return rd();case"RESET_STATE":return hs(),Gr();default:return e}},od=e=>{let t=Number(e),o=Date.now();return t<=o},re=()=>{Ce.dispatch({type:"RESET_STATE"})},hs=()=>{for(let e of Object.values(qe))Ae.removeItem(e)},Gr=()=>({username:void 0,challengeName:void 0,signInSession:void 0}),rd=()=>{let e=Ae.getItem(qe.expiry);if(!e||od(e))return hs(),Gr();let t=Ae.getItem(qe.username)??void 0,o=Ae.getItem(qe.challengeName)??void 0,r=Ae.getItem(qe.signInSession)??void 0;return{username:t,challengeName:o,signInSession:r}},nd=e=>{let t=e(Gr(),{type:"SET_INITIAL_STATE"});return{getState:()=>t,dispatch:o=>{t=e(t,o)}}},Ce=nd(td);function ge(e){Ce.dispatch({type:"SET_SIGN_IN_STATE",value:e})}var $o=({challengeName:e,signInSession:t,username:o})=>{o&&Ae.setItem(qe.username,o),e&&Ae.setItem(qe.challengeName,e),t&&(Ae.setItem(qe.signInSession,t),Ae.setItem(qe.expiry,String(Date.now()+ed)))};var Yr="Passkeys may not be supported on this device. Ensure your application is running in a secure context (HTTPS) and Web Authentication API is supported.";var Oe=class e extends U{constructor(t){super(t),this.constructor=e,Object.setPrototypeOf(this,e.prototype)}},N;(function(e){e.PasskeyNotSupported="PasskeyNotSupported",e.PasskeyAlreadyExists="PasskeyAlreadyExists",e.InvalidPasskeyRegistrationOptions="InvalidPasskeyRegistrationOptions",e.InvalidPasskeyAuthenticationOptions="InvalidPasskeyAuthenticationOptions",e.RelyingPartyMismatch="RelyingPartyMismatch",e.PasskeyRegistrationFailed="PasskeyRegistrationFailed",e.PasskeyRetrievalFailed="PasskeyRetrievalFailed",e.PasskeyRegistrationCanceled="PasskeyRegistrationCanceled",e.PasskeyAuthenticationCanceled="PasskeyAuthenticationCanceled",e.PasskeyOperationAborted="PasskeyOperationAborted"})(N||(N={}));var Jr="User may have canceled the ceremony or another interruption has occurred. Check underlying error for details.",ys="Ensure your user pool is configured to support the WEB_AUTHN as an authentication factor.",At={[N.PasskeyNotSupported]:{message:"Passkeys may not be supported on this device.",recoverySuggestion:Yr},[N.InvalidPasskeyRegistrationOptions]:{message:"Invalid passkey registration options.",recoverySuggestion:ys},[N.InvalidPasskeyAuthenticationOptions]:{message:"Invalid passkey authentication options.",recoverySuggestion:ys},[N.PasskeyRegistrationFailed]:{message:"Device failed to create passkey.",recoverySuggestion:Yr},[N.PasskeyRetrievalFailed]:{message:"Device failed to retrieve passkey.",recoverySuggestion:"Passkeys may not be available on this device. Try an alternative authentication factor like PASSWORD, EMAIL_OTP, or SMS_OTP."},[N.PasskeyAlreadyExists]:{message:"Passkey already exists in authenticator.",recoverySuggestion:"Proceed with existing passkey or try again after deleting the credential."},[N.PasskeyRegistrationCanceled]:{message:"Passkey registration ceremony has been canceled.",recoverySuggestion:Jr},[N.PasskeyAuthenticationCanceled]:{message:"Passkey authentication ceremony has been canceled.",recoverySuggestion:Jr},[N.PasskeyOperationAborted]:{message:"Passkey operation has been aborted.",recoverySuggestion:Jr},[N.RelyingPartyMismatch]:{message:"Relying party does not match current domain.",recoverySuggestion:"Ensure relying party identifier matches current domain."}},xt=Se(At,Oe);var Es=e=>{if(e instanceof Error){if(e.name==="AbortError"){let{message:t,recoverySuggestion:o}=At[N.PasskeyOperationAborted];return new Oe({name:N.PasskeyOperationAborted,message:t,recoverySuggestion:o,underlyingError:e})}if(e.name==="SecurityError"){let{message:t,recoverySuggestion:o}=At[N.RelyingPartyMismatch];return new Oe({name:N.RelyingPartyMismatch,message:t,recoverySuggestion:o,underlyingError:e})}}return new Oe({name:ue.Unknown,message:"An unknown error has occurred.",underlyingError:e})};var Ss=e=>{if(e instanceof Oe)return e;if(e instanceof Error&&e.name==="NotAllowedError"){let{message:t,recoverySuggestion:o}=At[N.PasskeyAuthenticationCanceled];return new Oe({name:N.PasskeyAuthenticationCanceled,message:t,recoverySuggestion:o,underlyingError:e})}return Es(e)};var Is=()=>Ke()&&window.isSecureContext&&"credentials"in navigator&&typeof window.PublicKeyCredential=="function";var Ct=e=>fe.convert(new Uint8Array(e),{urlSafe:!0,skipPadding:!0});var Xr=e=>Uint8Array.from(at.convert(e,{urlSafe:!0}),t=>t.charCodeAt(0)).buffer;var ws=e=>{let t=Xr(e.challenge),o=(e.allowCredentials||[]).map(r=>({...r,id:Xr(r.id)}));return{...e,challenge:t,allowCredentials:o}},As=e=>{let t={clientDataJSON:Ct(e.response.clientDataJSON),authenticatorData:Ct(e.response.authenticatorData),signature:Ct(e.response.signature)};e.response.userHandle&&(t.userHandle=Ct(e.response.userHandle));let o={id:e.id,rawId:Ct(e.rawId),type:e.type,clientExtensionResults:e.getClientExtensionResults(),response:t};return e.authenticatorAttachment&&(o.authenticatorAttachment=e.authenticatorAttachment),o};function xs(e){xt(e&&e instanceof PublicKeyCredential&&e.response instanceof AuthenticatorAssertionResponse,N.PasskeyRetrievalFailed)}var Cs=async e=>{try{let t=Is();xt(t,N.PasskeyNotSupported);let o=ws(e),r=await navigator.credentials.get({publicKey:o});return xs(r),As(r)}catch(t){throw Ss(t)}};var vs=e=>b(W,K("ConfirmDevice"),G(),{...V,...e});var vt={convert(e){return new TextEncoder().encode(e)}};function f(e,t){e!=null&&this.fromString(e,t)}function ne(){return new f(null,null)}var et,id=0xdeadbeefcafe,Ps=(id&16777215)===15715070;function sd(e,t,o,r,n,i){for(;--i>=0;){let s=t*this[e++]+o[r]+n;n=Math.floor(s/67108864),o[r++]=s&67108863}return n}function ad(e,t,o,r,n,i){let s=t&32767,a=t>>15;for(;--i>=0;){let c=this[e]&32767,d=this[e++]>>15,u=a*c+d*s;c=s*c+((u&32767)<<15)+o[r]+(n&1073741823),n=(c>>>30)+(u>>>15)+a*d+(n>>>30),o[r++]=c&1073741823}return n}function cd(e,t,o,r,n,i){let s=t&16383,a=t>>14;for(;--i>=0;){let c=this[e]&16383,d=this[e++]>>14,u=a*c+d*s;c=s*c+((u&16383)<<14)+o[r]+n,n=(c>>28)+(u>>14)+a*d,o[r++]=c&268435455}return n}var Ts=typeof navigator<"u";Ts&&Ps&&navigator.appName==="Microsoft Internet Explorer"?(f.prototype.am=ad,et=30):Ts&&Ps&&navigator.appName!=="Netscape"?(f.prototype.am=sd,et=26):(f.prototype.am=cd,et=28);f.prototype.DB=et;f.prototype.DM=(1<<et)-1;f.prototype.DV=1<<et;var Zr=52;f.prototype.FV=Math.pow(2,Zr);f.prototype.F1=Zr-et;f.prototype.F2=2*et-Zr;var dd="0123456789abcdefghijklmnopqrstuvwxyz",jo=[],Pt,he;Pt=48;for(he=0;he<=9;++he)jo[Pt++]=he;Pt=97;for(he=10;he<36;++he)jo[Pt++]=he;Pt=65;for(he=10;he<36;++he)jo[Pt++]=he;function Rs(e){return dd.charAt(e)}function ud(e,t){let o=jo[e.charCodeAt(t)];return o??-1}function pd(e){for(let t=this.t-1;t>=0;--t)e[t]=this[t];e.t=this.t,e.s=this.s}function ld(e){this.t=1,this.s=e<0?-1:0,e>0?this[0]=e:e<-1?this[0]=e+this.DV:this.t=0}function Qr(e){let t=ne();return t.fromInt(e),t}function md(e,t){let o;if(t===16)o=4;else if(t===8)o=3;else if(t===2)o=1;else if(t===32)o=5;else if(t===4)o=2;else throw new Error("Only radix 2, 4, 8, 16, 32 are supported");this.t=0,this.s=0;let r=e.length,n=!1,i=0;for(;--r>=0;){let s=ud(e,r);if(s<0){e.charAt(r)==="-"&&(n=!0);continue}n=!1,i===0?this[this.t++]=s:i+o>this.DB?(this[this.t-1]|=(s&(1<<this.DB-i)-1)<<i,this[this.t++]=s>>this.DB-i):this[this.t-1]|=s<<i,i+=o,i>=this.DB&&(i-=this.DB)}this.clamp(),n&&f.ZERO.subTo(this,this)}function fd(){let e=this.s&this.DM;for(;this.t>0&&this[this.t-1]==e;)--this.t}function gd(e){if(this.s<0)return"-"+this.negate().toString(e);let t;if(e==16)t=4;else if(e===8)t=3;else if(e===2)t=1;else if(e===32)t=5;else if(e===4)t=2;else throw new Error("Only radix 2, 4, 8, 16, 32 are supported");let o=(1<<t)-1,r,n=!1,i="",s=this.t,a=this.DB-s*this.DB%t;if(s-- >0)for(a<this.DB&&(r=this[s]>>a)>0&&(n=!0,i=Rs(r));s>=0;)a<t?(r=(this[s]&(1<<a)-1)<<t-a,r|=this[--s]>>(a+=this.DB-t)):(r=this[s]>>(a-=t)&o,a<=0&&(a+=this.DB,--s)),r>0&&(n=!0),n&&(i+=Rs(r));return n?i:"0"}function hd(){let e=ne();return f.ZERO.subTo(this,e),e}function yd(){return this.s<0?this.negate():this}function Ed(e){let t=this.s-e.s;if(t!=0)return t;let o=this.t;if(t=o-e.t,t!=0)return this.s<0?-t:t;for(;--o>=0;)if((t=this[o]-e[o])!=0)return t;return 0}function en(e){let t=1,o;return(o=e>>>16)!==0&&(e=o,t+=16),(o=e>>8)!==0&&(e=o,t+=8),(o=e>>4)!==0&&(e=o,t+=4),(o=e>>2)!==0&&(e=o,t+=2),(o=e>>1)!==0&&(e=o,t+=1),t}function Sd(){return this.t<=0?0:this.DB*(this.t-1)+en(this[this.t-1]^this.s&this.DM)}function Id(e,t){let o;for(o=this.t-1;o>=0;--o)t[o+e]=this[o];for(o=e-1;o>=0;--o)t[o]=0;t.t=this.t+e,t.s=this.s}function wd(e,t){for(let o=e;o<this.t;++o)t[o-e]=this[o];t.t=Math.max(this.t-e,0),t.s=this.s}function Ad(e,t){let o=e%this.DB,r=this.DB-o,n=(1<<r)-1,i=Math.floor(e/this.DB),s=this.s<<o&this.DM,a;for(a=this.t-1;a>=0;--a)t[a+i+1]=this[a]>>r|s,s=(this[a]&n)<<o;for(a=i-1;a>=0;--a)t[a]=0;t[i]=s,t.t=this.t+i+1,t.s=this.s,t.clamp()}function xd(e,t){t.s=this.s;let o=Math.floor(e/this.DB);if(o>=this.t){t.t=0;return}let r=e%this.DB,n=this.DB-r,i=(1<<r)-1;t[0]=this[o]>>r;for(let s=o+1;s<this.t;++s)t[s-o-1]|=(this[s]&i)<<n,t[s-o]=this[s]>>r;r>0&&(t[this.t-o-1]|=(this.s&i)<<n),t.t=this.t-o,t.clamp()}function Cd(e,t){let o=0,r=0,n=Math.min(e.t,this.t);for(;o<n;)r+=this[o]-e[o],t[o++]=r&this.DM,r>>=this.DB;if(e.t<this.t){for(r-=e.s;o<this.t;)r+=this[o],t[o++]=r&this.DM,r>>=this.DB;r+=this.s}else{for(r+=this.s;o<e.t;)r-=e[o],t[o++]=r&this.DM,r>>=this.DB;r-=e.s}t.s=r<0?-1:0,r<-1?t[o++]=this.DV+r:r>0&&(t[o++]=r),t.t=o,t.clamp()}function vd(e,t){let o=this.abs(),r=e.abs(),n=o.t;for(t.t=n+r.t;--n>=0;)t[n]=0;for(n=0;n<r.t;++n)t[n+o.t]=o.am(0,r[n],t,n,0,o.t);t.s=0,t.clamp(),this.s!==e.s&&f.ZERO.subTo(t,t)}function Pd(e){let t=this.abs(),o=e.t=2*t.t;for(;--o>=0;)e[o]=0;for(o=0;o<t.t-1;++o){let r=t.am(o,t[o],e,2*o,0,1);(e[o+t.t]+=t.am(o+1,2*t[o],e,2*o+1,r,t.t-o-1))>=t.DV&&(e[o+t.t]-=t.DV,e[o+t.t+1]=1)}e.t>0&&(e[e.t-1]+=t.am(o,t[o],e,2*o,0,1)),e.s=0,e.clamp()}function Td(e,t,o){let r=e.abs();if(r.t<=0)return;let n=this.abs();if(n.t<r.t){t?.fromInt(0),o!=null&&this.copyTo(o);return}o===null&&(o=ne());let i=ne(),s=this.s,a=e.s,c=this.DB-en(r[r.t-1]);c>0?(r.lShiftTo(c,i),n.lShiftTo(c,o)):(r.copyTo(i),n.copyTo(o));let d=i.t,u=i[d-1];if(u===0)return;let p=u*(1<<this.F1)+(d>1?i[d-2]>>this.F2:0),l=this.FV/p,m=(1<<this.F1)/p,h=1<<this.F2,I=o.t,A=I-d,S=t===null?ne():t;for(i.dlShiftTo(A,S),o.compareTo(S)>=0&&(o[o.t++]=1,o.subTo(S,o)),f.ONE.dlShiftTo(d,S),S.subTo(i,i);i.t<d;)i[i.t++]=0;for(;--A>=0;){let M=o[--I]===u?this.DM:Math.floor(o[I]*l+(o[I-1]+h)*m);if((o[I]+=i.am(0,M,o,A,0,d))<M)for(i.dlShiftTo(A,S),o.subTo(S,o);o[I]<--M;)o.subTo(S,o)}t!==null&&(o.drShiftTo(d,t),s!==a&&f.ZERO.subTo(t,t)),o.t=d,o.clamp(),c>0&&o.rShiftTo(c,o),s<0&&f.ZERO.subTo(o,o)}function Rd(e){let t=ne();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(f.ZERO)>0&&e.subTo(t,t),t}function _d(){if(this.t<1)return 0;let e=this[0];if((e&1)===0)return 0;let t=e&3;return t=t*(2-(e&15)*t)&15,t=t*(2-(e&255)*t)&255,t=t*(2-((e&65535)*t&65535))&65535,t=t*(2-e*t%this.DV)%this.DV,t>0?this.DV-t:-t}function Nd(e){return this.compareTo(e)===0}function bd(e,t){let o=0,r=0,n=Math.min(e.t,this.t);for(;o<n;)r+=this[o]+e[o],t[o++]=r&this.DM,r>>=this.DB;if(e.t<this.t){for(r+=e.s;o<this.t;)r+=this[o],t[o++]=r&this.DM,r>>=this.DB;r+=this.s}else{for(r+=this.s;o<e.t;)r+=e[o],t[o++]=r&this.DM,r>>=this.DB;r+=e.s}t.s=r<0?-1:0,r>0?t[o++]=r:r<-1&&(t[o++]=this.DV+r),t.t=o,t.clamp()}function Ud(e){let t=ne();return this.addTo(e,t),t}function Od(e){let t=ne();return this.subTo(e,t),t}function Dd(e){let t=ne();return this.multiplyTo(e,t),t}function Md(e){let t=ne();return this.divRemTo(e,t,null),t}function Tt(e){this.m=e,this.mp=e.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<<e.DB-15)-1,this.mt2=2*e.t}function kd(e){let t=ne();return e.abs().dlShiftTo(this.m.t,t),t.divRemTo(this.m,null,t),e.s<0&&t.compareTo(f.ZERO)>0&&this.m.subTo(t,t),t}function Fd(e){let t=ne();return e.copyTo(t),this.reduce(t),t}function Ld(e){for(;e.t<=this.mt2;)e[e.t++]=0;for(let t=0;t<this.m.t;++t){let o=e[t]&32767,r=o*this.mpl+((o*this.mph+(e[t]>>15)*this.mpl&this.um)<<15)&e.DM;for(o=t+this.m.t,e[o]+=this.m.am(0,r,e,t,0,this.m.t);e[o]>=e.DV;)e[o]-=e.DV,e[++o]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)}function Bd(e,t){e.squareTo(t),this.reduce(t)}function Hd(e,t,o){e.multiplyTo(t,o),this.reduce(o)}Tt.prototype.convert=kd;Tt.prototype.revert=Fd;Tt.prototype.reduce=Ld;Tt.prototype.mulTo=Hd;Tt.prototype.sqrTo=Bd;function Kd(e,t,o){let r=e.bitLength(),n,i=Qr(1),s=new Tt(t);if(r<=0)return i;r<18?n=1:r<48?n=3:r<144?n=4:r<768?n=5:n=6;let a=[],c=3,d=n-1,u=(1<<n)-1;if(a[1]=s.convert(this),n>1){let S=ne();for(s.sqrTo(a[1],S);c<=u;)a[c]=ne(),s.mulTo(S,a[c-2],a[c]),c+=2}let p=e.t-1,l,m=!0,h=ne(),I;for(r=en(e[p])-1;p>=0;){for(r>=d?l=e[p]>>r-d&u:(l=(e[p]&(1<<r+1)-1)<<d-r,p>0&&(l|=e[p-1]>>this.DB+r-d)),c=n;(l&1)===0;)l>>=1,--c;if((r-=c)<0&&(r+=this.DB,--p),m)a[l].copyTo(i),m=!1;else{for(;c>1;)s.sqrTo(i,h),s.sqrTo(h,i),c-=2;c>0?s.sqrTo(i,h):(I=i,i=h,h=I),s.mulTo(h,a[l],i)}for(;p>=0&&(e[p]&1<<r)===0;)s.sqrTo(i,h),I=i,i=h,h=I,--r<0&&(r=this.DB-1,--p)}let A=s.revert(i);return o(null,A),A}f.prototype.copyTo=pd;f.prototype.fromInt=ld;f.prototype.fromString=md;f.prototype.clamp=fd;f.prototype.dlShiftTo=Id;f.prototype.drShiftTo=wd;f.prototype.lShiftTo=Ad;f.prototype.rShiftTo=xd;f.prototype.subTo=Cd;f.prototype.multiplyTo=vd;f.prototype.squareTo=Pd;f.prototype.divRemTo=Td;f.prototype.invDigit=_d;f.prototype.addTo=bd;f.prototype.toString=gd;f.prototype.negate=hd;f.prototype.abs=yd;f.prototype.compareTo=Ed;f.prototype.bitLength=Sd;f.prototype.mod=Rd;f.prototype.equals=Nd;f.prototype.add=Ud;f.prototype.subtract=Od;f.prototype.multiply=Dd;f.prototype.divide=Md;f.prototype.modPow=Kd;f.ZERO=Qr(0);f.ONE=Qr(1);var _s=async({a:e,g:t,k:o,x:r,B:n,N:i,U:s})=>new Promise((a,c)=>{t.modPow(r,i,(d,u)=>{if(d){c(d);return}n.subtract(o.multiply(u)).modPow(e.add(s.multiply(r)),i,(p,l)=>{if(p){c(p);return}a(l.mod(i))})})});var Ns="FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF",tn={},Go={};for(let e=0;e<256;e++){let t=e.toString(16).toLowerCase();t.length===1&&(t=`0${t}`),tn[e]=t,Go[t]=e}var De=e=>{if(e.length%2!==0)throw new Error("Hex encoded strings must have an even number length");let t=new Uint8Array(e.length/2);for(let o=0;o<e.length;o+=2){let r=e.slice(o,o+2).toLowerCase();if(r in Go)t[o/2]=Go[r];else throw new Error(`Cannot decode unrecognized sequence ${r} as hexadecimal`)}return t};var Rt=e=>{let t="";for(let o=0;o<e.byteLength;o++)t+=tn[e[o]];return t};var Qt=e=>{let t=new Be;t.update(e);let o=t.digestSync(),r=Rt(o);return new Array(64-r.length).join("0")+r};var _t=e=>Qt(De(e));var Wd=/^[89a-f]/i,ve=e=>{if(!(e instanceof f))throw new Error("Not a BigInteger");let t=e.compareTo(f.ZERO)<0,o=e.abs().toString(16);if(o=o.length%2!==0?`0${o}`:o,o=Wd.test(o)?`00${o}`:o,t){let r=o.split("").map(i=>{let s=~parseInt(i,16)&15;return"0123456789ABCDEF".charAt(s)}).join("");o=new f(r,16).add(f.ONE).toString(16),o.toUpperCase().startsWith("FF8")&&(o=o.substring(2))}return o};var bs=({A:e,B:t})=>{let o=new f(_t(ve(e)+ve(t)),16);if(o.equals(f.ZERO))throw new Error("U cannot be zero.");return o};var Us=(e,t,o)=>{let r=new Be(t);r.update(e);let n=r.digestSync(),i=new Be(n);return i.update(o),i.digestSync().slice(0,16)};var Nt=e=>{let t=new Gt().random(e).toString();return De(t)};var Os=()=>fe.convert(Nt(40));var Yo=class{constructor({userPoolName:t,a:o,g:r,A:n,N:i}){this.encoder=vt,this.userPoolName=t,this.a=o,this.g=r,this.A=n,this.N=i,this.k=new f(_t(`${ve(i)}${ve(r)}`),16)}getRandomPassword(){if(!this.randomPassword)throw new g({name:"EmptyBigIntegerRandomPassword",message:"random password is empty"});return this.randomPassword}getSaltToHashDevices(){if(!this.saltToHashDevices)throw new g({name:"EmptyBigIntegersaltToHashDevices",message:"saltToHashDevices is empty"});return this.saltToHashDevices}getVerifierDevices(){if(!this.verifierDevices)throw new g({name:"EmptyBigIntegerVerifierDevices",message:"verifyDevices is empty"});return this.verifierDevices}async generateHashDevice(t,o){this.randomPassword=Os();let r=`${t}${o}:${this.randomPassword}`,n=Qt(r),i=Rt(Nt(16));return this.saltToHashDevices=ve(new f(i,16)),new Promise((s,a)=>{this.g.modPow(new f(_t(this.saltToHashDevices+n),16),this.N,(c,d)=>{if(c){a(c);return}this.verifierDevices=ve(d),s()})})}async getPasswordAuthenticationKey({username:t,password:o,serverBValue:r,salt:n}){if(r.mod(this.N).equals(f.ZERO))throw new Error("B cannot be zero.");let i=bs({A:this.A,B:r}),s=`${this.userPoolName}${t}:${o}`,a=Qt(s),c=new f(_t(ve(n)+a),16),d=await _s({a:this.a,g:this.g,k:this.k,x:c,B:r,N:this.N,U:i}),u=this.encoder.convert("Caldera Derived Key"),p=this.encoder.convert(""),l=new Uint8Array(u.byteLength+p.byteLength);return l.set(u,0),l.set(p,u.byteLength),Us(De(ve(d)),De(ve(i)),l)}};var Ds=async({a:e,g:t,N:o})=>new Promise((r,n)=>{t.modPow(e,o,(i,s)=>{if(i){n(i);return}if(s.mod(o).equals(f.ZERO)){n(new Error("Illegal parameter. A mod N cannot be 0."));return}r(s)})});var tt=async e=>{let t=new f(Ns,16),o=new f("2",16),r=Vd(),n=await Ds({a:r,g:o,N:t});return new Yo({userPoolName:e,a:r,g:o,A:n,N:t})},Vd=()=>{let e=Rt(Nt(128));return new f(e,16)};async function ye({userPoolId:e,userPoolEndpoint:t,newDeviceMetadata:o,accessToken:r}){if(!o)return;let n=e.split("_")[1]||"",i=await tt(n),s=o?.DeviceKey,a=o?.DeviceGroupKey;try{await i.generateHashDevice(a??"",s??"")}catch{return}let c={Salt:fe.convert(De(i.getSaltToHashDevices())),PasswordVerifier:fe.convert(De(i.getVerifierDevices()))},d=i.getRandomPassword();try{return await vs({endpointResolver:P({endpointOverride:t})})({region:v(e)},{AccessToken:r,DeviceName:await Vr(),DeviceKey:o?.DeviceKey,DeviceSecretVerifierConfig:c}),{deviceKey:s,deviceGroupKey:a,randomPassword:d}}catch{return}}async function Ms(e){let t=w.getConfig().Auth?.Cognito;E(t);let{username:o,signInSession:r,signInDetails:n,challengeName:i}=Ce.getState();if(i!=="WEB_AUTHN"||!o)throw new g({name:Ne.SignInException,message:"Unable to proceed due to invalid sign in state."});let{CREDENTIAL_REQUEST_OPTIONS:s}=e;xt(!!s,N.InvalidPasskeyAuthenticationOptions);let a=await Cs(JSON.parse(s)),c=mt({endpointResolver:P({endpointOverride:t.userPoolEndpoint})}),{ChallengeName:d,ChallengeParameters:u,AuthenticationResult:p,Session:l}=await c({region:v(t.userPoolId),userAgentValue:O(R.ConfirmSignIn)},{ChallengeName:"WEB_AUTHN",ChallengeResponses:{USERNAME:o,CREDENTIAL:JSON.stringify(a)},ClientId:t.userPoolClientId,Session:r});if(ge({signInSession:l,username:o,challengeName:d,signInDetails:n}),p)return await oe({...p,username:o,NewDeviceMetadata:await ye({userPoolId:t.userPoolId,userPoolEndpoint:t.userPoolEndpoint,newDeviceMetadata:p.NewDeviceMetadata,accessToken:p.AccessToken}),signInDetails:n}),Ce.dispatch({type:"RESET_STATE"}),await ce(),{isSignedIn:!0,nextStep:{signInStep:"DONE"}};if(d==="WEB_AUTHN")throw new g({name:Ne.SignInException,message:"Sequential WEB_AUTHN challenges returned from underlying service cannot be handled."});return{challengeName:d,challengeParameters:u}}function Y({username:e,userPoolId:t,userPoolClientId:o}){if(typeof window>"u")return;let r=window.AmazonCognitoAdvancedSecurityData;if(typeof r>"u")return;let n=r.getData(e,t,o);return n?{EncodedData:n}:{}}var zd=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],qd=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],Jo=()=>{let e=new Date,t=qd[e.getUTCDay()],o=zd[e.getUTCMonth()],r=e.getUTCDate(),n=e.getUTCHours();n<10&&(n=`0${n}`);let i=e.getUTCMinutes();i<10&&(i=`0${i}`);let s=e.getUTCSeconds();s<10&&(s=`0${s}`);let a=e.getUTCFullYear();return`${t} ${o} ${r} ${n}:${i}:${s} UTC ${a}`};var Xo=({userPoolName:e,username:t,challengeParameters:o,dateNow:r,hkdf:n})=>{let i=vt.convert(e),s=vt.convert(t),a=$d(o.SECRET_BLOCK),c=vt.convert(r),d=new Uint8Array(i.byteLength+s.byteLength+a.byteLength+c.byteLength);d.set(i,0),d.set(s,i.byteLength),d.set(a,i.byteLength+s.byteLength),d.set(c,i.byteLength+s.byteLength+a.byteLength);let u=new Be(n);u.update(d);let p=u.digestSync();return fe.convert(p)},$d=e=>{let t="=".repeat((4-e.length%4)%4),o=(e+t).replace(/-/g,"+").replace(/_/g,"/"),r=at.convert(o),n=new Uint8Array(r.length);for(let i=0;i<r.length;++i)n[i]=r.charCodeAt(i);return n};async function eo({username:e,config:t,clientMetadata:o,session:r,tokenOrchestrator:n}){let{userPoolId:i,userPoolEndpoint:s}=t,a=t.userPoolClientId,c=await n?.getDeviceMetadata(e);qr(c);let d=await tt(c.deviceGroupKey),u={USERNAME:e,SRP_A:d.A.toString(16),DEVICE_KEY:c.deviceKey},p={ChallengeName:"DEVICE_SRP_AUTH",ClientId:a,ChallengeResponses:u,ClientMetadata:o,Session:r},l=mt({endpointResolver:P({endpointOverride:s})}),{ChallengeParameters:m,Session:h}=await l({region:v(i)},p);return jd(e,m,o,h,d,t,n)}async function jd(e,t,o,r,n,{userPoolId:i,userPoolClientId:s,userPoolEndpoint:a},c){let d=await c?.getDeviceMetadata(e);qr(d);let u=new f(t?.SRP_B,16),p=new f(t?.SALT,16),{deviceKey:l}=d,{deviceGroupKey:m}=d,h=await n.getPasswordAuthenticationKey({username:d.deviceKey,password:d.randomPassword,serverBValue:u,salt:p}),I=Jo(),A={USERNAME:t?.USERNAME??e,PASSWORD_CLAIM_SECRET_BLOCK:t?.SECRET_BLOCK,TIMESTAMP:I,PASSWORD_CLAIM_SIGNATURE:Xo({username:l,userPoolName:m,challengeParameters:t,dateNow:I,hkdf:h}),DEVICE_KEY:l},S=Y({username:e,userPoolId:i,userPoolClientId:s}),M={ChallengeName:"DEVICE_PASSWORD_VERIFIER",ClientId:s,ChallengeResponses:A,Session:r,ClientMetadata:o,UserContextData:S};return mt({endpointResolver:P({endpointOverride:a})})({region:v(i)},M)}async function Zo(e,t,o,r,n,i,s){let{userPoolId:a,userPoolClientId:c,userPoolEndpoint:d}=i,u=a?.split("_")[1]||"",p=new f(t?.SRP_B,16),l=new f(t?.SALT,16),m=t?.USER_ID_FOR_SRP;if(!m)throw new g({name:"EmptyUserIdForSRPException",message:"USER_ID_FOR_SRP was not found in challengeParameters"});let h=await n.getPasswordAuthenticationKey({username:m,password:e,serverBValue:p,salt:l}),I=Jo(),A={USERNAME:m,PASSWORD_CLAIM_SECRET_BLOCK:t?.SECRET_BLOCK,TIMESTAMP:I,PASSWORD_CLAIM_SIGNATURE:Xo({username:m,userPoolName:u,challengeParameters:t,dateNow:I,hkdf:h})},S=await s.getDeviceMetadata(m);S&&S.deviceKey&&(A.DEVICE_KEY=S.deviceKey);let M=Y({username:m,userPoolId:a,userPoolClientId:c}),H={ChallengeName:"PASSWORD_VERIFIER",ChallengeResponses:A,ClientMetadata:o,Session:r,ClientId:c,UserContextData:M},ie=await mt({endpointResolver:P({endpointOverride:d})})({region:v(a)},H);return ie.ChallengeName==="DEVICE_SRP_AUTH"?eo({username:m,config:i,clientMetadata:o,session:ie.Session,tokenOrchestrator:s}):ie}async function ot(e,t,o,r){try{return await e(...t)}catch(n){if(n instanceof g&&n.name==="ResourceNotFoundException"&&n.message.includes("Device does not exist."))return await r.clearDeviceMetadata(o),e(...t);throw n}}function rt(e){let{dispatch:t}=Ce;t({type:"SET_USERNAME",value:e})}async function Qo({username:e,password:t,clientMetadata:o,config:r,tokenOrchestrator:n,authFlow:i,preferredChallenge:s}){let{userPoolId:a,userPoolClientId:c,userPoolEndpoint:d}=r,u=a?.split("_")[1]||"",p=await tt(u),l={USERNAME:e,SRP_A:p.A.toString(16)};i==="USER_AUTH"&&s&&(l.PREFERRED_CHALLENGE=s);let m=Y({username:e,userPoolId:a,userPoolClientId:c}),h={AuthFlow:i,AuthParameters:l,ClientMetadata:o,ClientId:c,UserContextData:m},A=await Qe({endpointResolver:P({endpointOverride:d})})({region:v(a),userAgentValue:O(R.SignIn)},h),{ChallengeParameters:S,Session:M}=A,H=S?.USERNAME??e;return rt(H),A.ChallengeName==="PASSWORD_VERIFIER"?ot(Zo,[t,S,o,M,p,r,n],H,n):A}var ks="userAttributes.";function Gd(e){return"isSignedIn"in e&&"nextStep"in e}async function Bs(e,t,o,r,n){let{userPoolClientId:i,userPoolId:s,userPoolEndpoint:a}=r,c={USERNAME:e,PASSWORD:t},d=await n.getDeviceMetadata(e);d&&d.deviceKey&&(c.DEVICE_KEY=d.deviceKey);let u=Y({username:e,userPoolId:s,userPoolClientId:i}),p={AuthFlow:"USER_PASSWORD_AUTH",AuthParameters:c,ClientMetadata:o,ClientId:i,UserContextData:u},m=await Qe({endpointResolver:P({endpointOverride:a})})({region:v(s),userAgentValue:O(R.SignIn)},p),h=m.ChallengeParameters?.USERNAME??m.ChallengeParameters?.USER_ID_FOR_SRP??e;return rt(h),m.ChallengeName==="DEVICE_SRP_AUTH"?eo({username:h,config:r,clientMetadata:o,session:m.Session,tokenOrchestrator:n}):m}async function Hs(e,t,o,r,n){return Qo({username:e,password:t,clientMetadata:o,config:r,tokenOrchestrator:n,authFlow:"USER_SRP_AUTH"})}async function Ks(e,t,o,r){let{userPoolClientId:n,userPoolId:i,userPoolEndpoint:s}=o,a={USERNAME:e},c=await r.getDeviceMetadata(e);c&&c.deviceKey&&(a.DEVICE_KEY=c.deviceKey);let d=Y({username:e,userPoolId:i,userPoolClientId:n}),u={AuthFlow:"CUSTOM_AUTH",AuthParameters:a,ClientMetadata:t,ClientId:n,UserContextData:d},l=await Qe({endpointResolver:P({endpointOverride:s})})({region:v(i),userAgentValue:O(R.SignIn)},u),m=l.ChallengeParameters?.USERNAME??e;return rt(m),l.ChallengeName==="DEVICE_SRP_AUTH"?eo({username:m,config:o,clientMetadata:t,session:l.Session,tokenOrchestrator:r}):l}async function Ws(e,t,o,r,n){E(r);let{userPoolId:i,userPoolClientId:s,userPoolEndpoint:a}=r,c=i?.split("_")[1]||"",d=await tt(c),u={USERNAME:e,SRP_A:d.A.toString(16),CHALLENGE_NAME:"SRP_A"},p=Y({username:e,userPoolId:i,userPoolClientId:s}),l={AuthFlow:"CUSTOM_AUTH",AuthParameters:u,ClientMetadata:o,ClientId:s,UserContextData:p},m=Qe({endpointResolver:P({endpointOverride:a})}),{ChallengeParameters:h,Session:I}=await m({region:v(i),userAgentValue:O(R.SignIn)},l),A=h?.USERNAME??e;return rt(A),ot(Zo,[t,h,o,I,d,r,n],A,n)}async function Pe(e){let{challengeName:t,challengeParameters:o,availableChallenges:r}=e,n=w.getConfig().Auth?.Cognito;switch(E(n),t){case"CUSTOM_CHALLENGE":return{isSignedIn:!1,nextStep:{signInStep:"CONFIRM_SIGN_IN_WITH_CUSTOM_CHALLENGE",additionalInfo:o}};case"MFA_SETUP":{let{signInSession:i,username:s}=Ce.getState(),a=Fs(Ls(o.MFAS_CAN_SETUP))||[],c=Zd(a),d=c.includes("TOTP"),u=c.includes("EMAIL");if(d&&u)return{isSignedIn:!1,nextStep:{signInStep:"CONTINUE_SIGN_IN_WITH_MFA_SETUP_SELECTION",allowedMFATypes:c}};if(u)return{isSignedIn:!1,nextStep:{signInStep:"CONTINUE_SIGN_IN_WITH_EMAIL_SETUP"}};if(d){let p=as({endpointResolver:P({endpointOverride:n.userPoolEndpoint})}),{Session:l,SecretCode:m}=await p({region:v(n.userPoolId)},{Session:i});return Ce.dispatch({type:"SET_SIGN_IN_SESSION",value:l}),{isSignedIn:!1,nextStep:{signInStep:"CONTINUE_SIGN_IN_WITH_TOTP_SETUP",totpSetupDetails:Yd(m,s)}}}throw new g({name:Ne.SignInException,message:`Cannot initiate MFA setup from available types: ${a}`})}case"NEW_PASSWORD_REQUIRED":return{isSignedIn:!1,nextStep:{signInStep:"CONFIRM_SIGN_IN_WITH_NEW_PASSWORD_REQUIRED",missingAttributes:Jd(o.requiredAttributes)}};case"SELECT_MFA_TYPE":return{isSignedIn:!1,nextStep:{signInStep:"CONTINUE_SIGN_IN_WITH_MFA_SELECTION",allowedMFATypes:Fs(Ls(o.MFAS_CAN_CHOOSE))}};case"SMS_OTP":case"SMS_MFA":return{isSignedIn:!1,nextStep:{signInStep:"CONFIRM_SIGN_IN_WITH_SMS_CODE",codeDeliveryDetails:{deliveryMedium:o.CODE_DELIVERY_DELIVERY_MEDIUM,destination:o.CODE_DELIVERY_DESTINATION}}};case"SOFTWARE_TOKEN_MFA":return{isSignedIn:!1,nextStep:{signInStep:"CONFIRM_SIGN_IN_WITH_TOTP_CODE"}};case"EMAIL_OTP":return{isSignedIn:!1,nextStep:{signInStep:"CONFIRM_SIGN_IN_WITH_EMAIL_CODE",codeDeliveryDetails:{deliveryMedium:o.CODE_DELIVERY_DELIVERY_MEDIUM,destination:o.CODE_DELIVERY_DESTINATION}}};case"WEB_AUTHN":{let i=await Ms(o);return Gd(i)?i:Pe(i)}case"PASSWORD":case"PASSWORD_SRP":return{isSignedIn:!1,nextStep:{signInStep:"CONFIRM_SIGN_IN_WITH_PASSWORD"}};case"SELECT_CHALLENGE":return{isSignedIn:!1,nextStep:{signInStep:"CONTINUE_SIGN_IN_WITH_FIRST_FACTOR_SELECTION",availableChallenges:r}}}throw new g({name:Ne.SignInException,message:`An error occurred during the sign in process. ${t} challengeName returned by the underlying service was not addressed.`})}function Yd(e,t){return{sharedSecret:e,getSetupUri:(o,r)=>{let n=`otpauth://totp/${o}:${r??t}?secret=${e}&issuer=${o}`;return new te(n)}}}function Me(e){if(e===Jt.PasswordResetRequiredException)return{isSignedIn:!1,nextStep:{signInStep:"RESET_PASSWORD"}};if(e===Jt.UserNotConfirmedException)return{isSignedIn:!1,nextStep:{signInStep:"CONFIRM_SIGN_UP"}}}function Jd(e){return e?JSON.parse(e).map(o=>o.includes(ks)?o.replace(ks,""):o):[]}function Xd(e){if(e==="SMS_MFA")return"SMS";if(e==="SOFTWARE_TOKEN_MFA")return"TOTP";if(e==="EMAIL_OTP")return"EMAIL"}function Fs(e){if(e)return e.map(Xd).filter(Boolean)}function Ls(e){return e?JSON.parse(e):[]}function Zd(e){return e.filter(t=>t==="EMAIL"||t==="TOTP")}async function er(){let e;try{e=await Ze()}catch{}if(e&&e.userId&&e.username)throw new g({name:Yi,message:"There is already a signed in user.",recoverySuggestion:"Call signOut before calling signIn again."})}function ke(e){return Ce.getState().username??e}async function Vs(e){let t=w.getConfig().Auth?.Cognito;E(t);let{username:o,password:r,options:n}=e,i={loginId:o,authFlowType:"CUSTOM_WITHOUT_SRP"},s=n?.clientMetadata;_(!!o,y.EmptySignInUsername),_(!r,y.CustomAuthSignInPassword);try{let{ChallengeName:a,ChallengeParameters:c,AuthenticationResult:d,Session:u}=await ot(Ks,[o,s,t,D],o,D),p=ke(o);return ge({signInSession:u,username:p,challengeName:a,signInDetails:i}),d?(await oe({username:p,...d,NewDeviceMetadata:await ye({userPoolId:t.userPoolId,userPoolEndpoint:t.userPoolEndpoint,newDeviceMetadata:d.NewDeviceMetadata,accessToken:d.AccessToken}),signInDetails:i}),re(),await ce(),{isSignedIn:!0,nextStep:{signInStep:"DONE"}}):Pe({challengeName:a,challengeParameters:c})}catch(a){re(),B(a);let c=Me(a.name);if(c)return c;throw a}}async function zs(e){let{username:t,password:o,options:r}=e,n={loginId:t,authFlowType:"CUSTOM_WITH_SRP"},i=w.getConfig().Auth?.Cognito;E(i);let s=r?.clientMetadata;_(!!t,y.EmptySignInUsername),_(!!o,y.EmptySignInPassword);try{let{ChallengeName:a,ChallengeParameters:c,AuthenticationResult:d,Session:u}=await Ws(t,o,s,i,D),p=ke(t);return ge({signInSession:u,username:p,challengeName:a,signInDetails:n}),d?(await oe({username:p,...d,NewDeviceMetadata:await ye({userPoolId:i.userPoolId,userPoolEndpoint:i.userPoolEndpoint,newDeviceMetadata:d.NewDeviceMetadata,accessToken:d.AccessToken}),signInDetails:n}),re(),await ce(),{isSignedIn:!0,nextStep:{signInStep:"DONE"}}):Pe({challengeName:a,challengeParameters:c})}catch(a){re(),B(a);let c=Me(a.name);if(c)return c;throw a}}var qs=async()=>{throw new g({name:Fo,message:"The autoSignIn flow has not started, or has been cancelled/completed.",recoverySuggestion:"Please try to use the signIn API or log out before starting a new autoSignIn flow."})},$s=qs;function to(e){$s=e}function J(e=!0){e&&($s=qs),ze.dispatch({type:"RESET"})}async function on(e){let{username:t,password:o}=e,r=w.getConfig().Auth?.Cognito,n={loginId:t,authFlowType:"USER_SRP_AUTH"};E(r);let i=e.options?.clientMetadata;_(!!t,y.EmptySignInUsername),_(!!o,y.EmptySignInPassword);try{let{ChallengeName:s,ChallengeParameters:a,AuthenticationResult:c,Session:d}=await Hs(t,o,i,r,D),u=ke(t);return ge({signInSession:d,username:u,challengeName:s,signInDetails:n}),c?(await oe({username:u,...c,NewDeviceMetadata:await ye({userPoolId:r.userPoolId,userPoolEndpoint:r.userPoolEndpoint,newDeviceMetadata:c.NewDeviceMetadata,accessToken:c.AccessToken}),signInDetails:n}),re(),await ce(),J(),{isSignedIn:!0,nextStep:{signInStep:"DONE"}}):Pe({challengeName:s,challengeParameters:a})}catch(s){re(),J(),B(s);let a=Me(s.name);if(a)return a;throw s}}async function js(e){let{username:t,password:o,options:r}=e,n=w.getConfig().Auth?.Cognito,i={loginId:t,authFlowType:"USER_PASSWORD_AUTH"};E(n);let s=r?.clientMetadata;_(!!t,y.EmptySignInUsername),_(!!o,y.EmptySignInPassword);try{let{ChallengeName:a,ChallengeParameters:c,AuthenticationResult:d,Session:u}=await ot(Bs,[t,o,s,n,D],t,D),p=ke(t);return ge({signInSession:u,username:p,challengeName:a,signInDetails:i}),d?(await oe({...d,username:p,NewDeviceMetadata:await ye({userPoolId:n.userPoolId,userPoolEndpoint:n.userPoolEndpoint,newDeviceMetadata:d.NewDeviceMetadata,accessToken:d.AccessToken}),signInDetails:i}),re(),await ce(),J(),{isSignedIn:!0,nextStep:{signInStep:"DONE"}}):Pe({challengeName:a,challengeParameters:c})}catch(a){re(),J(),B(a);let c=Me(a.name);if(c)return c;throw a}}async function Gs({username:e,clientMetadata:t,config:o,tokenOrchestrator:r,preferredChallenge:n,password:i,session:s}){let{userPoolId:a,userPoolClientId:c,userPoolEndpoint:d}=o,u=Y({username:e,userPoolId:a,userPoolClientId:c}),p={USERNAME:e};if(n){if(o.passwordless&&(n==="EMAIL_OTP"&&!o.passwordless.emailOtpEnabled||n==="SMS_OTP"&&!o.passwordless.smsOtpEnabled||n==="WEB_AUTHN"&&!o.passwordless.webAuthn)&&_(!1,y.InvalidPreferredChallenge),n==="PASSWORD_SRP")return _(!!i,y.EmptySignInPassword),Qo({username:e,password:i,clientMetadata:t,config:o,tokenOrchestrator:r,authFlow:"USER_AUTH",preferredChallenge:n});n==="PASSWORD"&&(_(!!i,y.EmptySignInPassword),p.PASSWORD=i),p.PREFERRED_CHALLENGE=n}let l={AuthFlow:"USER_AUTH",AuthParameters:p,ClientMetadata:t,ClientId:c,UserContextData:u};s&&(l.Session=s);let h=await Qe({endpointResolver:P({endpointOverride:d})})({region:v(a),userAgentValue:O(R.SignIn)},l);return rt(e),h}async function tr(e){let{username:t,password:o,options:r}=e,n=w.getConfig().Auth?.Cognito,i={loginId:t,authFlowType:"USER_AUTH"};E(n);let s=r?.clientMetadata,a=r?.preferredChallenge??n?.passwordless?.preferredChallenge;_(!!t,y.EmptySignInUsername);try{let c={username:t,config:n,tokenOrchestrator:D,clientMetadata:s,preferredChallenge:a,password:o},d=ze.getState();d.active&&d.username===t&&(c.session=d.session);let u=await Gs(c),p=ke(t);return ge({signInSession:u.Session,username:p,challengeName:u.ChallengeName,signInDetails:i}),u.AuthenticationResult?(await oe({username:p,...u.AuthenticationResult,NewDeviceMetadata:await ye({userPoolId:n.userPoolId,userPoolEndpoint:n.userPoolEndpoint,newDeviceMetadata:u.AuthenticationResult.NewDeviceMetadata,accessToken:u.AuthenticationResult.AccessToken}),signInDetails:i}),re(),await ce(),J(),{isSignedIn:!0,nextStep:{signInStep:"DONE"}}):Pe({challengeName:u.ChallengeName,challengeParameters:u.ChallengeParameters,availableChallenges:"AvailableChallenges"in u?u.AvailableChallenges:void 0})}catch(c){re(),J(),B(c);let d=Me(c.name);if(d)return d;throw c}}async function bt(e){J(!1);let t=e.options?.authFlowType;switch(await er(),t){case"USER_SRP_AUTH":return on(e);case"USER_PASSWORD_AUTH":return js(e);case"CUSTOM_WITHOUT_SRP":return Vs(e);case"CUSTOM_WITH_SRP":return zs(e);case"USER_AUTH":return tr(e);default:return on(e)}}var Ys=180*1e3;function Js(e){let t=io.listen("auth-internal",async({payload:r})=>{r.event==="confirmSignUp"&&r.data?.isSignUpComplete&&(io.dispatch("auth-internal",{event:"autoSignIn"}),to(Qs(e)),t())}),o=setTimeout(()=>{t(),clearTimeout(o),J()},Ys)}function Xs(e,t){let o;return r=>{o||e(...r),clearTimeout(o),o=setTimeout(()=>{o=void 0},t)}}function Qd(e,t,o){let r=Date.now(),n=setInterval(async()=>{if(Date.now()-r>Ys)clearInterval(n),o(new g({name:Fo,message:"The account was not confirmed on time.",recoverySuggestion:"Try to verify your account by clicking the link sent your email or phone and then login manually."})),J();else try{let a=await bt(e);a.nextStep.signInStep!=="CONFIRM_SIGN_UP"&&(t(a),clearInterval(n),J())}catch(a){clearInterval(n),o(a),J()}},5e3)}var eu=Xs(Qd,300),tu=Xs(ou,300);function Zs(e){return async()=>new Promise((t,o)=>{eu([e,t,o])})}async function ou(e,t,o){try{let r=e?.options?.authFlowType==="USER_AUTH"?await tr(e):await bt(e);t(r),J()}catch(r){o(r),J()}}function Qs(e){return async()=>new Promise((t,o)=>{tu([e,t,o])})}var ea=Qs;var ru=()=>async e=>{if(e.statusCode>=300){let t=await pe(e);if(B(t),t.name===ko.InvalidParameterException&&/'password'/.test(t.message)&&/Member must not be null/.test(t.message)){let o=y.EmptySignUpPassword,{message:r,recoverySuggestion:n}=Mo[o];throw new g({name:o,message:r,recoverySuggestion:n})}throw new g({name:t.name,message:t.message})}return Re(e)},ta=e=>b(W,K("SignUp"),ru(),{...V,...e});async function rn(e){let{username:t,password:o,options:r}=e,n=w.getConfig().Auth?.Cognito,i=n?.signUpVerificationMethod??"code",{clientMetadata:s,validationData:a,autoSignIn:c}=e.options??{};E(n),_(!!t,y.EmptySignUpUsername);let d=typeof c!="boolean"?c:void 0,u={username:t,options:d};d?.authFlowType!=="CUSTOM_WITHOUT_SRP"&&(u.password=o);let{userPoolId:p,userPoolClientId:l,userPoolEndpoint:m}=n,h=ta({endpointResolver:P({endpointOverride:m})}),I={Username:t,Password:void 0,UserAttributes:r?.userAttributes&&zr(r?.userAttributes),ClientMetadata:s,ValidationData:a&&zr(a),ClientId:l,UserContextData:Y({username:t,userPoolId:p,userPoolClientId:l})};o&&(I.Password=o);let{UserSub:A,CodeDeliveryDetails:S,UserConfirmed:M,Session:H}=await h({region:v(p),userAgentValue:O(R.SignUp)},I);(d||c===!0)&&(ze.dispatch({type:"START"}),ze.dispatch({type:"SET_USERNAME",value:t}),ze.dispatch({type:"SET_SESSION",value:H}));let le={destination:S?.Destination,deliveryMedium:S?.DeliveryMedium,attributeName:S?.AttributeName},ie=!!M,Ee=ze.getState().active;if(ie)return Ee?(to(ea(u)),{isSignUpComplete:!0,nextStep:{signUpStep:"COMPLETE_AUTO_SIGN_IN"},userId:A}):{isSignUpComplete:!0,nextStep:{signUpStep:"DONE"},userId:A};if(Ee){if(i==="link")return to(Zs(u)),{isSignUpComplete:!1,nextStep:{signUpStep:"COMPLETE_AUTO_SIGN_IN",codeDeliveryDetails:le},userId:A};Js(u)}return{isSignUpComplete:!1,nextStep:{signUpStep:"CONFIRM_SIGN_UP",codeDeliveryDetails:le},userId:A}}var oa=e=>b(W,K("ForgotPassword"),G(),{...V,...e});async function nn(e){let{username:t}=e;_(!!t,y.EmptyResetPasswordUsername);let o=w.getConfig().Auth?.Cognito;E(o);let{userPoolClientId:r,userPoolId:n,userPoolEndpoint:i}=o,s=e.options?.clientMetadata,a=Y({username:t,userPoolId:n,userPoolClientId:r}),u=(await oa({endpointResolver:P({endpointOverride:i})})({region:v(n),userAgentValue:O(R.ResetPassword)},{Username:t,ClientMetadata:s,ClientId:r,UserContextData:a})).CodeDeliveryDetails;return{isPasswordReset:!1,nextStep:{resetPasswordStep:"CONFIRM_RESET_PASSWORD_WITH_CODE",codeDeliveryDetails:{deliveryMedium:u?.DeliveryMedium,destination:u?.Destination,attributeName:u?.AttributeName}}}}var ra=e=>b(W,K("ConfirmForgotPassword"),G(),{...V,...e});async function sn(e){let t=w.getConfig().Auth?.Cognito;E(t);let{userPoolClientId:o,userPoolId:r,userPoolEndpoint:n}=t,{username:i,newPassword:s}=e;_(!!i,y.EmptyConfirmResetPasswordUsername),_(!!s,y.EmptyConfirmResetPasswordNewPassword);let a=e.confirmationCode;_(!!a,y.EmptyConfirmResetPasswordConfirmationCode);let c=e.options?.clientMetadata,d=Y({username:i,userPoolId:r,userPoolClientId:o});await ra({endpointResolver:P({endpointOverride:n})})({region:v(t.userPoolId),userAgentValue:O(R.ConfirmResetPassword)},{Username:i,ConfirmationCode:a,Password:s,ClientMetadata:c,ClientId:t.userPoolClientId,UserContextData:d})}var yv=new C("AuthError");var na={oauthSignInError:{message:q.OAUTH_ERROR,log:"Make sure Cognito Hosted UI has been configured correctly"},noConfig:{message:q.DEFAULT_MSG,log:`
4
+ Error: Amplify has not been configured correctly.
5
+ This error is typically caused by one of the following scenarios:
6
+
7
+ 1. Make sure you're passing the awsconfig object to Amplify.configure() in your app's entry point
8
+ See https://aws-amplify.github.io/docs/js/authentication#configure-your-app for more information
9
+
10
+ 2. There might be multiple conflicting versions of amplify packages in your node_modules.
11
+ Refer to our docs site for help upgrading Amplify packages (https://docs.amplify.aws/lib/troubleshooting/upgrading/q/platform/js)
12
+ `},missingAuthConfig:{message:q.DEFAULT_MSG,log:`
13
+ Error: Amplify has not been configured correctly.
14
+ The configuration object is missing required auth properties.
15
+ This error is typically caused by one of the following scenarios:
16
+
17
+ 1. Did you run \`amplify push\` after adding auth via \`amplify add auth\`?
18
+ See https://aws-amplify.github.io/docs/js/authentication#amplify-project-setup for more information
19
+
20
+ 2. This could also be caused by multiple conflicting versions of amplify packages, see (https://docs.amplify.aws/lib/troubleshooting/upgrading/q/platform/js) for help upgrading Amplify packages.
21
+ `},emptyUsername:{message:q.EMPTY_USERNAME},invalidUsername:{message:q.INVALID_USERNAME},emptyPassword:{message:q.EMPTY_PASSWORD},emptyCode:{message:q.EMPTY_CODE},signUpError:{message:q.SIGN_UP_ERROR,log:"The first parameter should either be non-null string or object"},noMFA:{message:q.NO_MFA},invalidMFA:{message:q.INVALID_MFA},emptyChallengeResponse:{message:q.EMPTY_CHALLENGE},noUserSession:{message:q.NO_USER_SESSION},deviceConfig:{message:q.DEVICE_CONFIG},networkError:{message:q.NETWORK_ERROR},autoSignInError:{message:q.AUTOSIGNIN_ERROR},default:{message:q.DEFAULT_MSG}};var Te=(e,t)=>new g({message:e??"An error has occurred during the oauth process.",name:Ne.OAuthSignInError,recoverySuggestion:t??na.oauthSignInError.log});var or;(function(e){e.NoConfig="noConfig",e.MissingAuthConfig="missingAuthConfig",e.EmptyUsername="emptyUsername",e.InvalidUsername="invalidUsername",e.EmptyPassword="emptyPassword",e.EmptyCode="emptyCode",e.SignUpError="signUpError",e.NoMFA="noMFA",e.InvalidMFA="invalidMFA",e.EmptyChallengeResponse="emptyChallengeResponse",e.NoUserSession="noUserSession",e.Default="default",e.DeviceConfig="deviceConfig",e.NetworkError="networkError",e.AutoSignInError="autoSignInError",e.OAuthSignInError="oauthSignInError"})(or||(or={}));var nu="`signInWithRedirect` has been canceled.",iu="An error occurred while validating the state.",su="Try to initiate an OAuth flow from Amplify",an=async e=>{let t=await z.loadOAuthState(),o=e===t?t:void 0;if(!o)throw new g({name:or.OAuthSignInError,message:e===null?nu:iu,recoverySuggestion:e===null?void 0:su});return o};var rr=async({currentUrl:e,userAgentValue:t,clientId:o,redirectUri:r,responseType:n,domain:i,preferPrivateSession:s})=>{let a=new te(e),c=a.searchParams.get("error"),d=a.searchParams.get("error_description");if(c)throw Te(d??c);return n==="code"?au({currentUrl:e,userAgentValue:t,clientId:o,redirectUri:r,domain:i,preferPrivateSession:s}):cu({currentUrl:e,redirectUri:r,preferPrivateSession:s})},au=async({currentUrl:e,userAgentValue:t,clientId:o,redirectUri:r,domain:n,preferPrivateSession:i})=>{let s=new te(e),a=s.searchParams.get("code"),c=s.searchParams.get("state");if(!a||!c)throw Te("User cancelled OAuth flow.");let d=await an(c),u="https://"+n+"/oauth2/token",p=await z.loadPKCE(),l={grant_type:"authorization_code",code:a,client_id:o,redirect_uri:r,...p?{code_verifier:p}:{}},m=Object.entries(l).map(([Ee,F])=>`${encodeURIComponent(Ee)}=${encodeURIComponent(F)}`).join("&"),{access_token:h,refresh_token:I,id_token:A,error:S,error_message:M,token_type:H,expires_in:le}=await(await fetch(u,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",[ur]:t},body:m})).json();if(S)throw Te(M??S);let ie=(h&&Q(h).payload.username)??"username";return await oe({username:ie,AccessToken:h,IdToken:A,RefreshToken:I}),ia({redirectUri:r,state:d,preferPrivateSession:i})},cu=async({currentUrl:e,redirectUri:t,preferPrivateSession:o})=>{let r=new te(e),{id_token:n,access_token:i,state:s,token_type:a,expires_in:c,error_description:d,error:u}=(r.hash??"#").substring(1).split("&").map(m=>m.split("=")).reduce((m,[h,I])=>({...m,[h]:I}),{id_token:void 0,access_token:void 0,state:void 0,token_type:void 0,expires_in:void 0,error_description:void 0,error:void 0});if(u)throw Te(d??u);if(!i)throw Te("No access token returned from OAuth flow.");let p=await an(s),l=(i&&Q(i).payload.username)??"username";return await oe({username:l,AccessToken:i,IdToken:n}),ia({redirectUri:t,state:p,preferPrivateSession:o})},ia=async({redirectUri:e,state:t,preferPrivateSession:o})=>{await D.setOAuthMetadata({oauthSignIn:!0}),await z.clearOAuthData(),await z.storeOAuthSignIn(!0,o),Wo(),pu(e),du(t)&&Z.dispatch("auth",{event:"customOAuthState",data:Hr(uu(t))},"Auth",j),Z.dispatch("auth",{event:"signInWithRedirect"},"Auth",j),await ce()},du=e=>/-/.test(e),uu=e=>e.split("-").splice(1).join("-"),pu=e=>{typeof window<"u"&&typeof window.history<"u"&&window.history.replaceState(window.history.state,"",e)};function Ut(e,t){if(t){let o=e?.find(r=>r===t);if(!o)throw Zi;return o}else{let o=e?.find(lu)??e?.find(mu),r=e?.find(gu)??e?.find(fu);if(o)return o;throw r?Qi:Xi}}var lu=e=>e.startsWith(String(window.location.origin+(window.location.pathname||"/"))),mu=e=>e.includes(String(window.location.hostname)),fu=e=>e.startsWith("http://"),gu=e=>e.startsWith("https://");var Ot=async e=>{Wo(),await z.clearOAuthInflightData(),Z.dispatch("auth",{event:"signInWithRedirect_failure",data:{error:e}},"Auth",j)};var sa=async e=>{try{E(e),Le(e),z.setAuthConfig(e)}catch{return}if(await z.loadOAuthInFlight())try{let t=window.location.href,{loginWith:o,userPoolClientId:r}=e,{domain:n,redirectSignIn:i,responseType:s}=o.oauth,a=Ut(i);await rr({currentUrl:t,clientId:r,domain:n,redirectUri:a,responseType:s,userAgentValue:O(R.SignInWithRedirect)})}catch(t){await Ot(t)}};Ke()&&w[Mt](sa);var aa={Google:"Google",Facebook:"Facebook",Amazon:"LoginWithAmazon",Apple:"SignInWithApple"};var nr=async e=>{window?.location&&(window.location.href=e.replace("http://","https://"))};var ca="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",da=e=>{let t=new Uint8Array(e);st().getRandomValues(t);let o="",r;for(let n of t)o+=ca.charAt(n%ca.length);return{value:o,method:"S256",toCodeChallenge(){return r||(r=hu(o),r)}}};function hu(e){let t=new Be;return t.update(e),yu(fe.convert(t.digestSync(),{urlSafe:!0}))}function yu(e){return e.replace(/=/g,"")}var ua=()=>Br(32);var pa=e=>{async function t(o){if(o.persisted&&await e.loadOAuthInFlight()){let n=Te("User cancelled OAuth flow.");await Ot(n)}window.removeEventListener("pageshow",t)}window.addEventListener("pageshow",t)};async function ir(e){let t=w.getConfig().Auth?.Cognito;E(t),Le(t),z.setAuthConfig(t),e?.options?.prompt||await er();let o="COGNITO",r;return typeof e?.provider=="string"?o=aa[e.provider]:e?.provider?.custom?o=e.provider.custom:e?.provider?.idpIdentifier&&({idpIdentifier:r}=e.provider),Eu({oauthConfig:t.loginWith.oauth,clientId:t.userPoolClientId,provider:o,idpIdentifier:r,customState:e?.customState,preferPrivateSession:e?.options?.preferPrivateSession,options:{loginHint:e?.options?.loginHint,lang:e?.options?.lang,nonce:e?.options?.nonce,prompt:e?.options?.prompt},authSessionOpener:e?.options?.authSessionOpener})}var Eu=async({oauthConfig:e,provider:t,idpIdentifier:o,clientId:r,customState:n,preferPrivateSession:i,options:s,authSessionOpener:a})=>{let{domain:c,redirectSignIn:d,responseType:u,scopes:p}=e,{loginHint:l,lang:m,nonce:h,prompt:I}=s??{},A=ua(),S=a||nr,M=n?`${A}-${Kr(n)}`:A,{value:H,method:le,toCodeChallenge:ie}=da(128),Ee=Ut(e.redirectSignIn);Ke()&&z.storeOAuthInFlight(!0),z.storeOAuthState(M),z.storePKCE(H);let F=new URLSearchParams;F.append("redirect_uri",Ee),F.append("response_type",u),F.append("client_id",r),o?F.append("idp_identifier",o):F.append("identity_provider",t),F.append("scope",p.join(" ")),l&&F.append("login_hint",l),m&&F.append("lang",m),h&&F.append("nonce",h),I&&F.append("prompt",I.toLowerCase()),F.append("state",M),u==="code"&&(F.append("code_challenge",ie()),F.append("code_challenge_method",le));let nt=`https://${c}/oauth2/authorize?${F.toString()}`;pa(z);let{type:de,error:yt,url:Et}=await S(nt,d,i)??{};try{if(de==="error")throw Te(String(yt));if(de==="canceled")throw Te(String(de));de==="success"&&Et&&await rr({currentUrl:Et,clientId:r,domain:c,redirectUri:Ee,responseType:u,userAgentValue:O(R.SignInWithRedirect),preferPrivateSession:i})}catch(Fe){throw await Ot(Fe),Fe}};var la=async e=>{await e.clearOAuthData(),D.clearTokens(),await Ht(),Z.dispatch("auth",{event:"signedOut"},"Auth",j)};var ma=async(e,t=!1,o)=>{Le(e);let{loginWith:r,userPoolClientId:n}=e,{domain:i,redirectSignOut:s}=r.oauth,a=Ut(s,o),c=`https://${i}/logout?${Object.entries({client_id:n,logout_uri:encodeURIComponent(a)}).map(([d,u])=>`${d}=${u}`).join("&")}`;return nr(c)};var fa=async(e,t,o,r)=>{let{isOAuthSignIn:n}=await t.loadOAuthSignIn(),i=await o.getOAuthMetadata();if(await la(t),n||i?.oauthSignIn)return ma(e,!1,r)};var ga=e=>b(W,K("RevokeToken"),G(),{...V,...e});var ha=e=>b(W,K("GlobalSignOut"),G(),{...V,...e});var ya=new C("Auth");async function cn(e){let t=w.getConfig().Auth?.Cognito;E(t),e?.global?await Iu(t):await Su(t);let o;try{Le(t),o=!0}catch{o=!1}if(o){let r=new wt(we);r.setAuthConfig(t);let{type:n}=await fa(t,r,D,e?.oauth?.redirectUrl)??{};if(n==="error")throw new g({name:es,message:"An error occurred when attempting to log out from OAuth provider."})}else D.clearTokens(),await Ht(),Z.dispatch("auth",{event:"signedOut"},"Auth",j)}async function Su(e){try{let{userPoolEndpoint:t,userPoolId:o,userPoolClientId:r}=e,n=await D.getTokenStore().loadTokens();Bo(n),wu(n.accessToken)&&await ga({endpointResolver:P({endpointOverride:t})})({region:v(o),userAgentValue:O(R.SignOut)},{ClientId:r,Token:n.refreshToken})}catch{ya.debug("Client signOut error caught but will proceed with token removal")}}async function Iu(e){try{let{userPoolEndpoint:t,userPoolId:o}=e,r=await D.getTokenStore().loadTokens();Lo(r),await ha({endpointResolver:P({endpointOverride:t})})({region:v(o),userAgentValue:O(R.SignOut)},{AccessToken:r.accessToken.toString()})}catch{ya.debug("Global signOut error caught but will proceed with token removal")}}var wu=e=>!!e?.payload?.origin_jti;var Ea={identityId:"identityId"};var Au=new C("DefaultIdentityIdStore"),gt=class{setAuthConfig(t){ct(t.Cognito),this.authConfig=t,this._authKeys=xu("Cognito",t.Cognito.identityPoolId)}constructor(t){this._authKeys={},this._hasGuestIdentityId=!1,this.keyValueStorage=t}async loadIdentityId(){ct(this.authConfig?.Cognito);try{if(this._primaryIdentityId)return{id:this._primaryIdentityId,type:"primary"};{let t=await this.keyValueStorage.getItem(this._authKeys.identityId);return t?(this._hasGuestIdentityId=!0,{id:t,type:"guest"}):null}}catch(t){return Au.log("Error getting stored IdentityId.",t),null}}async storeIdentityId(t){ct(this.authConfig?.Cognito),t.type==="guest"?(this.keyValueStorage.setItem(this._authKeys.identityId,t.id),this._primaryIdentityId=void 0,this._hasGuestIdentityId=!0):(this._primaryIdentityId=t.id,this._hasGuestIdentityId&&(this.keyValueStorage.removeItem(this._authKeys.identityId),this._hasGuestIdentityId=!1))}async clearIdentityId(){this._primaryIdentityId=void 0,await this.keyValueStorage.removeItem(this._authKeys.identityId)}},xu=(e,t)=>Zt(Ea)(`com.amplify.${e}`,t);var oo=({endpointOverride:e})=>t=>e?{url:new te(e)}:Mr(t);function sr(e){let t=Q(e).payload.iss,o={};if(!t)throw new g({name:"InvalidIdTokenException",message:"Invalid Idtoken."});let r=t.replace(/(^\w+:|^)\/\//,"");return o[r]=e,o}async function Sa({tokens:e,authConfig:t,identityIdStore:o}){o.setAuthConfig({Cognito:t});let r=await o.loadIdentityId();if(r)return r.id;let n=e?.idToken?sr(e.idToken.toString()):{},i=await Cu(n,t);return o.storeIdentityId({id:i,type:e?"primary":"guest"}),i}async function Cu(e,t){let o=t?.identityPoolId,r=Yt(o),n=Or({endpointResolver:oo({endpointOverride:t.identityPoolEndpoint})}),i;try{i=(await n({region:r},{IdentityPoolId:o,Logins:e})).IdentityId}catch(s){throw B(s),new g(s)}if(!i)throw new g({name:"GetIdResponseException",message:"Received undefined response from getId operation",recoverySuggestion:"Make sure to pass a valid identityPoolId in the configuration."});return i}var ar=new C("CognitoCredentialsProvider"),Ia=3e3*1e3,ht=class{constructor(t){this._nextCredentialsRefresh=0,this._identityIdStore=t}async clearCredentialsAndIdentityId(){ar.debug("Clearing out credentials and identityId"),this._credentialsAndIdentityId=void 0,await this._identityIdStore.clearIdentityId()}async clearCredentials(){ar.debug("Clearing out in-memory credentials"),this._credentialsAndIdentityId=void 0}async getCredentialsAndIdentityId(t){let o=t.authenticated,{tokens:r}=t,{authConfig:n}=t;try{ct(n?.Cognito)}catch{return}if(!o&&!n.Cognito.allowGuestAccess)return;let{forceRefresh:i}=t,s=this.hasTokenChanged(r),a=await Sa({tokens:r,authConfig:n.Cognito,identityIdStore:this._identityIdStore});return(i||s)&&this.clearCredentials(),o?(rs(r),this.credsForOIDCTokens(n.Cognito,r,a)):this.getGuestCredentials(a,n.Cognito)}async getGuestCredentials(t,o){if(this._credentialsAndIdentityId&&!this.isPastTTL()&&this._credentialsAndIdentityId.isAuthenticatedCreds===!1)return ar.info("returning stored credentials as they neither past TTL nor expired."),this._credentialsAndIdentityId;this.clearCredentials();let r=Yt(o.identityPoolId),n=Ao({endpointResolver:oo({endpointOverride:o.identityPoolEndpoint})}),i;try{i=await n({region:r},{IdentityId:t})}catch(s){throw B(s),new g(s)}if(i?.Credentials?.AccessKeyId&&i?.Credentials?.SecretKey){this._nextCredentialsRefresh=new Date().getTime()+Ia;let s={credentials:{accessKeyId:i.Credentials.AccessKeyId,secretAccessKey:i.Credentials.SecretKey,sessionToken:i.Credentials.SessionToken,expiration:i.Credentials.Expiration},identityId:t};return i.IdentityId&&(s.identityId=i.IdentityId,this._identityIdStore.storeIdentityId({id:i.IdentityId,type:"guest"})),this._credentialsAndIdentityId={...s,isAuthenticatedCreds:!1},s}else throw new g({name:"CredentialsNotFoundException",message:"Cognito did not respond with either Credentials, AccessKeyId or SecretKey."})}async credsForOIDCTokens(t,o,r){if(this._credentialsAndIdentityId&&!this.isPastTTL()&&this._credentialsAndIdentityId.isAuthenticatedCreds===!0)return ar.debug("returning stored credentials as they neither past TTL nor expired."),this._credentialsAndIdentityId;this.clearCredentials();let n=o.idToken?sr(o.idToken.toString()):{},i=Yt(t.identityPoolId),s=Ao({endpointResolver:oo({endpointOverride:t.identityPoolEndpoint})}),a;try{a=await s({region:i},{IdentityId:r,Logins:n})}catch(c){throw B(c),new g(c)}if(a?.Credentials?.AccessKeyId&&a?.Credentials?.SecretKey){this._nextCredentialsRefresh=new Date().getTime()+Ia;let c={credentials:{accessKeyId:a.Credentials.AccessKeyId,secretAccessKey:a.Credentials.SecretKey,sessionToken:a.Credentials.SessionToken,expiration:a.Credentials.Expiration},identityId:r};return a.IdentityId&&(c.identityId=a.IdentityId,this._identityIdStore.storeIdentityId({id:a.IdentityId,type:"primary"})),this._credentialsAndIdentityId={...c,isAuthenticatedCreds:!0,associatedIdToken:o.idToken?.toString()},c}else throw new g({name:"CredentialsException",message:"Cognito did not respond with either Credentials, AccessKeyId or SecretKey."})}isPastTTL(){return this._nextCredentialsRefresh===void 0?!0:this._nextCredentialsRefresh<=Date.now()}hasTokenChanged(t){return!!t&&!!this._credentialsAndIdentityId?.associatedIdToken&&t.idToken?.toString()!==this._credentialsAndIdentityId.associatedIdToken}};var dn=new ht(new gt(we));var un={configure(e,t){let o=kt(e),r=new $t({sameSite:"lax"}),n=t?.ssr?r:we,i=t?.ssr?new ht(new gt(r)):dn;if(!o.Auth){w.configure(o,t);return}if(t?.Auth){w.configure(o,t);return}if(!w.libraryOptions.Auth){ft.setAuthConfig(o.Auth),ft.setKeyValueStorage(n),w.configure(o,{...t,Auth:{tokenProvider:ft,credentialsProvider:i}});return}if(t){let s=w.libraryOptions.Auth;t.ssr!==void 0&&(ft.setKeyValueStorage(n),s.credentialsProvider=i),w.configure(o,{Auth:s,...t});return}w.configure(o)},getConfig(){return w.getConfig()}};var wa=new Map;function pn(e,t){wa.set(e,t)}pn("none",async()=>({login:async()=>{},logout:async()=>{},getUser:async()=>{},getTokenSilently:async()=>"none",isAuthenticated:async()=>!0}));async function Aa(e){let t=wa.get(e.provider);if(!t)throw new Error(`Auth provider "${e.provider}" not registered. Import "foundation-sdk/${e.provider}" to register it.`);return t(e)}function xa(e){let t=null,o=[];function r(){o.forEach(i=>{try{i(t)}catch{}})}async function n(){let i=await e.getUser();t=i?{id:i.id,email:i.email,name:i.name,picture:i.picture}:null}return{get user(){return t},get isAuthenticated(){return!!t},async getToken(){return e.getTokenSilently()},async login(i){await e.login(i),await n(),r()},async logout(i){await e.logout(i),t=null,r()},async signIn(i,s){if(!e.signIn)throw new Error("signIn not supported by this auth provider");await e.signIn(i,s),await n(),r()},async signUp(i,s,a){if(!e.signUp)throw new Error("signUp not supported by this auth provider");await e.signUp(i,s,a)},async forgotPassword(i){if(!e.forgotPassword)throw new Error("forgotPassword not supported by this auth provider");await e.forgotPassword(i)},async resetPassword(i,s){if(!e.resetPassword)throw new Error("resetPassword not supported by this auth provider");await e.resetPassword(i,s)},onChange(i){return o.length>=100?(console.warn("[Foundation SDK] Auth listener limit reached."),()=>{}):(o.push(i),()=>{let s=o.indexOf(i);s>-1&&o.splice(s,1)})},async _initUser(){await e.isAuthenticated()&&await n()}}}function vu(e){return e?.response!==void 0?e.response:e?.data!==void 0?e.data:e}function Pu(e,t){let o=t?.error;if(o){let n=o.message||"Unknown error",i=o.details;if(i?.length){let s=i.map(a=>a.field?`${a.field}: ${a.message}`:a.message).join(", ");n=n?`${n} ${s}`:s}return Object.assign(new Error(n),{code:o.code,type:o.code,details:i,status:e})}let r=t?.data?.message||t?.message;return r?Object.assign(new Error(r),{status:e}):Object.assign(new Error(`HTTP ${e}`),{status:e})}function Ca(e){function t(n){return{"X-Foundation-Mvp-Application-Id":e.appId,"X-Foundation-Mvp-Tenant-Id":e.tenantId,"X-Foundation-Mvp-Application-Version":e.version,"Content-Type":"application/json",Authorization:`Bearer ${n}`}}async function o(n,i,s,a={}){let c=await e.getToken(),d=t(c),u=`${n}${i}`;if(a.params){let h=new URLSearchParams;for(let[A,S]of Object.entries(a.params))S!=null&&h.set(A,String(S));let I=h.toString();I&&(u+=`?${I}`)}let p={method:s,headers:d};a.body!==void 0&&(p.body=JSON.stringify(a.body));let l=await fetch(u,p);if(!l.ok){let h={};try{h=await l.json()}catch{}throw Pu(l.status,h)}if(l.status===204)return null;let m=await l.json();return vu(m)}async function r(n,i={}){return fetch(n,i)}return{request:o,rawFetch:r,headers:t}}function ln(e){if(!e)throw new Error("Token parsing failed: Missing auth token");try{let[t,o]=e.split("?"),r=t.split(".");if(r.length!==3)throw new Error("Invalid JWT format");let n=atob(r[1]),i=JSON.parse(n);o&&new URLSearchParams(o).forEach((u,p)=>{i[p]=u});let s=i["BaseApplication/apiBaseUrl"];if(!s)throw new Error("Token missing apiBaseUrl");let a=i["BaseApplication/websocketBaseUrl"]||"",c=i["BaseApplication/accountBaseUrl"]||s;return{sub:i.sub||"",apiBaseUrl:s,accountBaseUrl:c,websocketBaseUrl:a,userId:i["BaseApplication/userId"]||"",namespace:i["BaseApplication/namespace"]}}catch(t){if(t instanceof Error&&t.message.startsWith("Token"))throw t;let o=t instanceof Error?t.message:"Failed to parse token";throw new Error(`Token parsing failed: ${o}`)}}async function va(e){let t=e.configUrl,o=e.appId,r=e.tenantId;try{let x=await fetch("/foundation-env.json");if(x.ok){let X=await x.json();X.configUrl&&(t=X.configUrl,o=X.applicationId||o,r=X.applicationTenant||r)}}catch{}if(!t)throw new Error("No configUrl provided and /foundation-env.json not found");let n={Accept:"application/json","Cache-Control":"no-cache"};o&&(n["X-Foundation-Mvp-Application-Id"]=o),r&&(n["X-Foundation-Mvp-Tenant-Id"]=r);let i=await fetch(t,{headers:n});if(!i.ok)throw new Error(`Failed to fetch config: ${i.statusText}`);let s=await i.json(),a=s.data??s,c=a.auth||{provider:"none"},d=e.auth||await Aa(c),p=xa(d);await p._initUser();let l,m;if(e.baseUrl)l=e.baseUrl,m=e.baseUrl;else if(c.apiUrls?.apiBaseUrl){let x=c.apiUrls;l=x.apiBaseUrl,m=x.accountBaseUrl||l}else{let x=await d.getTokenSilently(),X=ln(x);l=X.apiBaseUrl,m=X.accountBaseUrl}let h=o||a.app?.id||a.tenant?.identifier||"",I=r||a.tenant?.identifier||"",A=a.app?.version||a.core?.version||"0.0.0",S=Ca({appId:h,tenantId:I,version:A,getToken:()=>d.getTokenSilently()}),M={};try{M=await S.request(l,"/api/v1/config/init","GET")||{}}catch(x){console.warn("[Foundation SDK] Backend config fetch failed:",x)}let H={...a,...M},le="";try{let x=await d.getTokenSilently();x&&x!=="none"&&(le=ln(x).namespace||"")}catch{}let ie={get app(){let x=H.app||{};return{id:x.id||h,name:x.name||"",version:x.version||A,environment:x.environment||"",...x}},get features(){return H.features||{}},get plans(){return H.plans||[]},get theme(){let x=H.theme||{};return{colors:x.colors||{},dark:x.dark||{},defaultColorScheme:x.defaultColorScheme}},get connectors(){return H.connectors||{}},get resources(){return H.resources||{}},get auth(){let{provider:x,...X}=c;return{provider:x,...X}},get raw(){return H}},Ee=Tu(S,l),F=Ru(S,l,le),nt=_u(S,m),de=Nu(S,l,m,le),yt=bu(S,l),Et=Uu(),Fe=[];return{get ready(){return Promise.resolve()},get isReady(){return!0},auth:p,db:Ee,files:F,integration:de,account:nt,config:ie,openapi:yt,log:Et,on(x,X){return x==="entity.changed"?(Fe.push(X),()=>{let ro=Fe.indexOf(X);ro>-1&&Fe.splice(ro,1)}):()=>{}}}}function Tu(e,t){return{async list(o,r={}){let{filters:n,limit:i,cursor:s,orderBy:a,orderDir:c}=r,d={...n};return i&&(d.limit=i),s&&(d.next=s),a&&(d.orderBy=a),c&&(d.orderDir=c),e.request(t,`/api/v1/core/${o}`,"GET",{params:d})},async get(o,r){return e.request(t,`/api/v1/core/${o}`,"GET",{params:{id:r}})},async create(o,r){return e.request(t,`/api/v1/core/${o}`,"POST",{body:r})},async update(o,r,n){return e.request(t,`/api/v1/core/${o}`,"PUT",{body:{id:r,...n}})},async save(o,r){try{return await e.request(t,`/api/v1/core/${o}`,"PUT",{body:r})}catch{return e.request(t,`/api/v1/core/${o}`,"POST",{body:r})}},async delete(o,r){await e.request(t,`/api/v1/core/${o}`,"DELETE",{body:{id:r}})}}}function Ru(e,t,o){return{async initiate(r){return e.request(t,"/api/v1/core/upload","POST",{body:{...r,__namespace:o}})},async upload(r){let n;r.file instanceof ArrayBuffer?n=r.file:n=await r.file.arrayBuffer();let i=await e.request(t,"/api/v1/core/upload","POST",{body:{name:r.name,contentType:r.contentType,contentLength:n.byteLength,sha256:r.sha256,__namespace:o}});if(!i.signedUrl||!i.signedData)throw new Error("Missing signedUrl or signedData in response");let s=new FormData;Object.entries(i.signedData).forEach(([c,d])=>{s.append(c,d)}),s.append("file",new Blob([n],{type:r.contentType}),r.name);let a=await fetch(i.signedUrl,{method:"POST",body:s});if(a.status!==204)throw new Error(`S3 upload failed: ${a.status}`);return{id:i.id,name:i.name,status:"uploaded",s3UploadComplete:!0}},async get(r){return e.request(t,"/api/v1/core/files","GET",{params:{id:r,__namespace:o}})},async delete(r){await e.request(t,`/api/v1/core/files/${r}`,"DELETE")},async list(r={}){let n={__namespace:o};r.limit&&(n.limit=r.limit),r.cursor&&(n.cursor=r.cursor);let i=await e.request(t,"/api/v1/core/files","GET",{params:n});return{items:i?.items||[],nextCursor:i?.next}}}}function _u(e,t){return{async get(){return e.request(t,"/api/v1/accounts/account","GET")},async update(o){await e.request(t,"/api/v1/accounts/account","PUT",{body:{user:o}})},async usage(){return e.request(t,"/api/v1/accounts/account/usage","GET")},async resendVerification(){await e.request(t,"/api/v1/accounts/account/resend-verification","POST")}}}function Nu(e,t,o,r){let n={async list(){return e.request(t,"/api/v1/config/connectors","GET")},async connections(){return e.request(t,"/api/v1/core/integrations","GET",{params:{query:"default",__namespace:r}})},async all(){let[i,s]=await Promise.all([n.list(),n.connections()]),a=Array.isArray(i)?i:i?.items||[],c=Array.isArray(s)?s:s?.items||[],d=new Map;for(let u of c){let p=u.source||u.id;d.has(p)||d.set(p,[]),d.get(p).push(u)}return a.map(u=>{let p=d.get(u.id)||[];return{...u,connections:p,connected:p.some(l=>l.connected),connectionCount:p.filter(l=>l.connected).length}})},async status(i){let s=await n.connections(),c=(Array.isArray(s)?s:s?.items||[]).filter(d=>d.source===i&&d.connected);return{connected:c.length>0,connections:c}},async connect(i){return e.request(o,`/api/v1/accounts/integrations/${i}/initialize`,"POST",{body:{__namespace:r}})},async disconnect(i,s){await e.request(o,`/api/v1/accounts/integrations/${i}/remove`,"POST",{body:{configurationId:s}})}};return n}function bu(e,t){return{async get(){return e.request(t,"/api/v1/config/openapi","GET")}}}function Uu(){return{info:(e,t)=>console.log(`[Foundation] ${e}`,t??""),warn:(e,t)=>console.warn(`[Foundation] ${e}`,t??""),error:(e,t)=>console.error(`[Foundation] ${e}`,t??""),event:(e,t)=>console.log(`[Foundation Event] ${e}`,t??"")}}pn("cognito",async e=>{let t=e.cognito;if(!t)throw new Error("Cognito config required");return un.configure({Auth:{Cognito:{userPoolId:t.userPoolId,userPoolClientId:t.clientId,loginWith:{oauth:{domain:t.domain.replace("https://",""),scopes:(t.scope||"openid profile email").split(" "),redirectSignIn:[window.location.origin],redirectSignOut:[window.location.origin],responseType:"code"}}}}}),{login:async()=>{await ir()},logout:async()=>{await cn()},getUser:async()=>{try{let o=await Ze();return{id:o.userId,email:o.signInDetails?.loginId||"",name:o.username}}catch{return}},getTokenSilently:async()=>{let r=(await yo()).tokens?.accessToken?.toString();if(!r)throw new Error("No token");return r},isAuthenticated:async()=>{try{return await Ze(),!0}catch{return!1}},signIn:async(o,r)=>{await bt({username:o,password:r})},signUp:async(o,r,n)=>{await rn({username:o,password:r,options:{userAttributes:{email:o,...n}}})},forgotPassword:async o=>{await nn({username:o})},resetPassword:async(o,r)=>{await sn({username:"",confirmationCode:o,newPassword:r})}}});return Fa(Ou);})();
22
+ /*! Bundled license information:
23
+
24
+ js-cookie/dist/js.cookie.mjs:
25
+ (*! js-cookie v3.0.5 | MIT *)
26
+ */
27
+ //# sourceMappingURL=foundation-sdk.browser.global.js.map